cmodlistview_moc.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060
  1. /*
  2. * cmodlistview_moc.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "cmodlistview_moc.h"
  12. #include "ui_cmodlistview_moc.h"
  13. #include "imageviewer_moc.h"
  14. #include "../mainwindow_moc.h"
  15. #include <QJsonArray>
  16. #include <QCryptographicHash>
  17. #include <QRegularExpression>
  18. #include "cmodlistmodel_moc.h"
  19. #include "cmodmanager.h"
  20. #include "cdownloadmanager_moc.h"
  21. #include "../settingsView/csettingsview_moc.h"
  22. #include "../launcherdirs.h"
  23. #include "../jsonutils.h"
  24. #include "../../lib/VCMIDirs.h"
  25. #include "../../lib/CConfigHandler.h"
  26. #include "../../lib/Languages.h"
  27. #include "../../lib/modding/CModVersion.h"
  28. static double mbToBytes(double mb)
  29. {
  30. return mb * 1024 * 1024;
  31. }
  32. void CModListView::setupModModel()
  33. {
  34. modModel = new CModListModel(this);
  35. manager = std::make_unique<CModManager>(modModel);
  36. }
  37. void CModListView::changeEvent(QEvent *event)
  38. {
  39. if(event->type() == QEvent::LanguageChange)
  40. {
  41. ui->retranslateUi(this);
  42. modModel->reloadRepositories();
  43. }
  44. QWidget::changeEvent(event);
  45. }
  46. void CModListView::dragEnterEvent(QDragEnterEvent* event)
  47. {
  48. if(event->mimeData()->hasUrls())
  49. for(const auto & url : event->mimeData()->urls())
  50. for(const auto & ending : QStringList({".zip", ".h3m", ".h3c", ".vmap", ".vcmp", ".json"}))
  51. if(url.fileName().endsWith(ending, Qt::CaseInsensitive))
  52. {
  53. event->acceptProposedAction();
  54. return;
  55. }
  56. }
  57. void CModListView::dropEvent(QDropEvent* event)
  58. {
  59. const QMimeData* mimeData = event->mimeData();
  60. if(mimeData->hasUrls())
  61. {
  62. const QList<QUrl> urlList = mimeData->urls();
  63. for (const auto & url : urlList)
  64. manualInstallFile(url);
  65. }
  66. }
  67. void CModListView::setupFilterModel()
  68. {
  69. filterModel = new CModFilterModel(modModel, this);
  70. filterModel->setFilterKeyColumn(-1); // filter across all columns
  71. filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); // to make it more user-friendly
  72. filterModel->setDynamicSortFilter(true);
  73. }
  74. void CModListView::setupModsView()
  75. {
  76. ui->allModsView->setModel(filterModel);
  77. // input data is not sorted - sort it before display
  78. ui->allModsView->sortByColumn(ModFields::TYPE, Qt::AscendingOrder);
  79. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_ENABLED, QHeaderView::Fixed);
  80. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_UPDATE, QHeaderView::Fixed);
  81. QSettings s(Ui::teamName, Ui::appName);
  82. auto state = s.value("AllModsView/State").toByteArray();
  83. if(!state.isNull()) //read last saved settings
  84. {
  85. ui->allModsView->header()->restoreState(state);
  86. }
  87. else //default //TODO: default high-DPI scaling
  88. {
  89. ui->allModsView->setColumnWidth(ModFields::NAME, 185);
  90. ui->allModsView->setColumnWidth(ModFields::TYPE, 75);
  91. ui->allModsView->setColumnWidth(ModFields::VERSION, 60);
  92. }
  93. ui->allModsView->resizeColumnToContents(ModFields::STATUS_ENABLED);
  94. ui->allModsView->resizeColumnToContents(ModFields::STATUS_UPDATE);
  95. ui->allModsView->setUniformRowHeights(true);
  96. connect(ui->allModsView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&,const QModelIndex&)),
  97. this, SLOT(modSelected(const QModelIndex&,const QModelIndex&)));
  98. connect(filterModel, SIGNAL(modelReset()),
  99. this, SLOT(modelReset()));
  100. connect(modModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
  101. this, SLOT(dataChanged(QModelIndex,QModelIndex)));
  102. }
  103. CModListView::CModListView(QWidget * parent)
  104. : QWidget(parent)
  105. , ui(new Ui::CModListView)
  106. {
  107. ui->setupUi(this);
  108. setAcceptDrops(true);
  109. setupModModel();
  110. setupFilterModel();
  111. setupModsView();
  112. ui->progressWidget->setVisible(false);
  113. dlManager = nullptr;
  114. if(settings["launcher"]["autoCheckRepositories"].Bool())
  115. {
  116. loadRepositories();
  117. }
  118. else
  119. {
  120. manager->resetRepositories();
  121. }
  122. #ifdef Q_OS_IOS
  123. for(auto * scrollWidget : {
  124. (QAbstractItemView*)ui->allModsView,
  125. (QAbstractItemView*)ui->screenshotsList})
  126. {
  127. QScroller::grabGesture(scrollWidget, QScroller::LeftMouseButtonGesture);
  128. scrollWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
  129. scrollWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  130. }
  131. #endif
  132. }
  133. void CModListView::loadRepositories()
  134. {
  135. manager->resetRepositories();
  136. QStringList repositories;
  137. if (settings["launcher"]["defaultRepositoryEnabled"].Bool())
  138. repositories.push_back(QString::fromStdString(settings["launcher"]["defaultRepositoryURL"].String()));
  139. if (settings["launcher"]["extraRepositoryEnabled"].Bool())
  140. repositories.push_back(QString::fromStdString(settings["launcher"]["extraRepositoryURL"].String()));
  141. for(auto entry : repositories)
  142. {
  143. if (entry.isEmpty())
  144. continue;
  145. // URL must be encoded to something else to get rid of symbols illegal in file names
  146. auto hashed = QCryptographicHash::hash(entry.toUtf8(), QCryptographicHash::Md5);
  147. auto hashedStr = QString::fromUtf8(hashed.toHex());
  148. downloadFile(hashedStr + ".json", entry, "repository index");
  149. }
  150. }
  151. CModListView::~CModListView()
  152. {
  153. QSettings s(Ui::teamName, Ui::appName);
  154. s.setValue("AllModsView/State", ui->allModsView->header()->saveState());
  155. delete ui;
  156. }
  157. static QString replaceIfNotEmpty(QVariant value, QString pattern)
  158. {
  159. if(value.canConvert<QStringList>())
  160. return pattern.arg(value.toStringList().join(", "));
  161. if(value.canConvert<QString>())
  162. return pattern.arg(value.toString());
  163. // all valid types of data should have been filtered by code above
  164. assert(!value.isValid());
  165. return "";
  166. }
  167. static QString replaceIfNotEmpty(QStringList value, QString pattern)
  168. {
  169. if(!value.empty())
  170. return pattern.arg(value.join(", "));
  171. return "";
  172. }
  173. QString CModListView::genChangelogText(CModEntry & mod)
  174. {
  175. QString headerTemplate = "<p><span style=\" font-weight:600;\">%1: </span></p>";
  176. QString entryBegin = "<p align=\"justify\"><ul>";
  177. QString entryEnd = "</ul></p>";
  178. QString entryLine = "<li>%1</li>";
  179. //QString versionSeparator = "<hr/>";
  180. QString result;
  181. QVariantMap changelog = mod.getValue("changelog").toMap();
  182. QList<QString> versions = changelog.keys();
  183. std::sort(versions.begin(), versions.end(), [](QString lesser, QString greater)
  184. {
  185. return CModVersion::fromString(lesser.toStdString()) < CModVersion::fromString(greater.toStdString());
  186. });
  187. std::reverse(versions.begin(), versions.end());
  188. for(auto & version : versions)
  189. {
  190. result += headerTemplate.arg(version);
  191. result += entryBegin;
  192. for(auto & line : changelog.value(version).toStringList())
  193. result += entryLine.arg(line);
  194. result += entryEnd;
  195. }
  196. return result;
  197. }
  198. QStringList CModListView::getModNames(QStringList input)
  199. {
  200. QStringList result;
  201. for(const auto & modID : input)
  202. {
  203. auto mod = modModel->getMod(modID.toLower());
  204. QString modName = mod.getValue("name").toString();
  205. if (modName.isEmpty())
  206. result += modID.toLower();
  207. else
  208. result += modName;
  209. }
  210. return result;
  211. }
  212. QString CModListView::genModInfoText(CModEntry & mod)
  213. {
  214. QString prefix = "<p><span style=\" font-weight:600;\">%1: </span>"; // shared prefix
  215. QString redPrefix = "<p><span style=\" font-weight:600; color:red\">%1: </span>"; // shared prefix
  216. QString lineTemplate = prefix + "%2</p>";
  217. QString urlTemplate = prefix + "<a href=\"%2\">%3</a></p>";
  218. QString textTemplate = prefix + "</p><p align=\"justify\">%2</p>";
  219. QString listTemplate = "<p align=\"justify\">%1: %2</p>";
  220. QString noteTemplate = "<p align=\"justify\">%1</p>";
  221. QString incompatibleString = redPrefix + tr("Mod is incompatible") + "</p>";
  222. QString supportedVersions = redPrefix + "%2 %3 %4</p>";
  223. QString result;
  224. result += replaceIfNotEmpty(mod.getValue("name"), lineTemplate.arg(tr("Mod name")));
  225. result += replaceIfNotEmpty(mod.getValue("installedVersion"), lineTemplate.arg(tr("Installed version")));
  226. result += replaceIfNotEmpty(mod.getValue("latestVersion"), lineTemplate.arg(tr("Latest version")));
  227. if(mod.getValue("localSizeBytes").isValid())
  228. result += replaceIfNotEmpty(CModEntry::sizeToString(mod.getValue("localSizeBytes").toDouble()), lineTemplate.arg(tr("Size")));
  229. if((mod.isAvailable() || mod.isUpdateable()) && mod.getValue("downloadSize").isValid())
  230. result += replaceIfNotEmpty(CModEntry::sizeToString(mbToBytes(mod.getValue("downloadSize").toDouble())), lineTemplate.arg(tr("Download size")));
  231. result += replaceIfNotEmpty(mod.getValue("author"), lineTemplate.arg(tr("Authors")));
  232. if(mod.getValue("licenseURL").isValid())
  233. result += urlTemplate.arg(tr("License")).arg(mod.getValue("licenseURL").toString()).arg(mod.getValue("licenseName").toString());
  234. if(mod.getValue("contact").isValid())
  235. result += urlTemplate.arg(tr("Contact")).arg(mod.getValue("contact").toString()).arg(mod.getValue("contact").toString());
  236. //compatibility info
  237. if(!mod.isCompatible())
  238. {
  239. auto compatibilityInfo = mod.getValue("compatibility").toMap();
  240. auto minStr = compatibilityInfo.value("min").toString();
  241. auto maxStr = compatibilityInfo.value("max").toString();
  242. result += incompatibleString.arg(tr("Compatibility"));
  243. if(minStr == maxStr)
  244. result += supportedVersions.arg(tr("Required VCMI version"), minStr, "", "");
  245. else
  246. {
  247. if(minStr.isEmpty() || maxStr.isEmpty())
  248. {
  249. if(minStr.isEmpty())
  250. result += supportedVersions.arg(tr("Supported VCMI version"), maxStr, ", ", "please upgrade mod");
  251. else
  252. result += supportedVersions.arg(tr("Required VCMI version"), minStr, " ", "or above");
  253. }
  254. else
  255. result += supportedVersions.arg(tr("Supported VCMI versions"), minStr, " - ", maxStr);
  256. }
  257. }
  258. QStringList supportedLanguages;
  259. QVariant baseLanguageVariant = mod.getBaseValue("language");
  260. QString baseLanguageID = baseLanguageVariant.isValid() ? baseLanguageVariant.toString() : "english";
  261. bool needToShowSupportedLanguages = false;
  262. for(const auto & language : Languages::getLanguageList())
  263. {
  264. if (!language.hasTranslation)
  265. continue;
  266. QString languageID = QString::fromStdString(language.identifier);
  267. if (languageID != baseLanguageID && !mod.getValue(languageID).isValid())
  268. continue;
  269. if (languageID != baseLanguageID)
  270. needToShowSupportedLanguages = true;
  271. supportedLanguages += QApplication::translate("Language", language.nameEnglish.c_str());
  272. }
  273. if(needToShowSupportedLanguages)
  274. result += replaceIfNotEmpty(supportedLanguages, lineTemplate.arg(tr("Languages")));
  275. result += replaceIfNotEmpty(getModNames(mod.getDependencies()), lineTemplate.arg(tr("Required mods")));
  276. result += replaceIfNotEmpty(getModNames(mod.getConflicts()), lineTemplate.arg(tr("Conflicting mods")));
  277. result += replaceIfNotEmpty(mod.getValue("description"), textTemplate.arg(tr("Description")));
  278. result += "<p></p>"; // to get some empty space
  279. QString unknownDeps = tr("This mod can not be installed or enabled because the following dependencies are not present");
  280. QString blockingMods = tr("This mod can not be enabled because the following mods are incompatible with it");
  281. QString hasActiveDependentMods = tr("This mod cannot be disabled because it is required by the following mods");
  282. QString hasDependentMods = tr("This mod cannot be uninstalled or updated because it is required by the following mods");
  283. QString thisIsSubmod = tr("This is a submod and it cannot be installed or uninstalled separately from its parent mod");
  284. QString notes;
  285. notes += replaceIfNotEmpty(getModNames(findInvalidDependencies(mod.getName())), listTemplate.arg(unknownDeps));
  286. notes += replaceIfNotEmpty(getModNames(findBlockingMods(mod.getName())), listTemplate.arg(blockingMods));
  287. if(mod.isEnabled())
  288. notes += replaceIfNotEmpty(getModNames(findDependentMods(mod.getName(), true)), listTemplate.arg(hasActiveDependentMods));
  289. if(mod.isInstalled())
  290. notes += replaceIfNotEmpty(getModNames(findDependentMods(mod.getName(), false)), listTemplate.arg(hasDependentMods));
  291. if(mod.isSubmod())
  292. notes += noteTemplate.arg(thisIsSubmod);
  293. if(notes.size())
  294. result += textTemplate.arg(tr("Notes")).arg(notes);
  295. return result;
  296. }
  297. void CModListView::disableModInfo()
  298. {
  299. ui->disableButton->setVisible(false);
  300. ui->enableButton->setVisible(false);
  301. ui->installButton->setVisible(false);
  302. ui->uninstallButton->setVisible(false);
  303. ui->updateButton->setVisible(false);
  304. }
  305. void CModListView::dataChanged(const QModelIndex & topleft, const QModelIndex & bottomRight)
  306. {
  307. selectMod(ui->allModsView->currentIndex());
  308. }
  309. void CModListView::selectMod(const QModelIndex & index)
  310. {
  311. if(!index.isValid())
  312. {
  313. disableModInfo();
  314. }
  315. else
  316. {
  317. auto mod = modModel->getMod(index.data(ModRoles::ModNameRole).toString());
  318. ui->modInfoBrowser->setHtml(genModInfoText(mod));
  319. ui->changelogBrowser->setHtml(genChangelogText(mod));
  320. bool hasInvalidDeps = !findInvalidDependencies(index.data(ModRoles::ModNameRole).toString()).empty();
  321. bool hasBlockingMods = !findBlockingMods(index.data(ModRoles::ModNameRole).toString()).empty();
  322. bool hasDependentMods = !findDependentMods(index.data(ModRoles::ModNameRole).toString(), true).empty();
  323. ui->disableButton->setVisible(mod.isEnabled());
  324. ui->enableButton->setVisible(mod.isDisabled());
  325. ui->installButton->setVisible(mod.isAvailable() && !mod.isSubmod());
  326. ui->uninstallButton->setVisible(mod.isInstalled() && !mod.isSubmod());
  327. ui->updateButton->setVisible(mod.isUpdateable());
  328. // Block buttons if action is not allowed at this time
  329. // TODO: automate handling of some of these cases instead of forcing player
  330. // to resolve all conflicts manually.
  331. ui->disableButton->setEnabled(!hasDependentMods && !mod.isEssential());
  332. ui->enableButton->setEnabled(!hasBlockingMods && !hasInvalidDeps);
  333. ui->installButton->setEnabled(!hasInvalidDeps);
  334. ui->uninstallButton->setEnabled(!hasDependentMods && !mod.isEssential());
  335. ui->updateButton->setEnabled(!hasInvalidDeps && !hasDependentMods);
  336. loadScreenshots();
  337. }
  338. }
  339. void CModListView::modSelected(const QModelIndex & current, const QModelIndex &)
  340. {
  341. selectMod(current);
  342. }
  343. void CModListView::on_allModsView_activated(const QModelIndex & index)
  344. {
  345. selectMod(index);
  346. loadScreenshots();
  347. }
  348. void CModListView::on_lineEdit_textChanged(const QString & arg1)
  349. {
  350. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  351. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1, QRegularExpression::UnanchoredWildcardConversion);
  352. #else
  353. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1);
  354. //Hack due to lack QRegularExpression::UnanchoredWildcardConversion in Qt5
  355. baseStr.chop(3);
  356. baseStr.remove(0,5);
  357. #endif
  358. QRegularExpression regExp{baseStr, QRegularExpression::CaseInsensitiveOption};
  359. filterModel->setFilterRegularExpression(regExp);
  360. }
  361. void CModListView::on_comboBox_currentIndexChanged(int index)
  362. {
  363. switch(index)
  364. {
  365. case 0:
  366. filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::MASK_NONE);
  367. break;
  368. case 1:
  369. filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::INSTALLED);
  370. break;
  371. case 2:
  372. filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::INSTALLED);
  373. break;
  374. case 3:
  375. filterModel->setTypeFilter(ModStatus::UPDATEABLE, ModStatus::UPDATEABLE);
  376. break;
  377. case 4:
  378. filterModel->setTypeFilter(ModStatus::ENABLED | ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
  379. break;
  380. case 5:
  381. filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
  382. break;
  383. }
  384. }
  385. QStringList CModListView::findInvalidDependencies(QString mod)
  386. {
  387. QStringList ret;
  388. for(QString requrement : modModel->getRequirements(mod))
  389. {
  390. if(!modModel->hasMod(requrement))
  391. ret += requrement;
  392. }
  393. return ret;
  394. }
  395. QStringList CModListView::findBlockingMods(QString modUnderTest)
  396. {
  397. QStringList ret;
  398. auto required = modModel->getRequirements(modUnderTest);
  399. for(QString name : modModel->getModList())
  400. {
  401. auto mod = modModel->getMod(name);
  402. if(mod.isEnabled())
  403. {
  404. // one of enabled mods have requirement (or this mod) marked as conflict
  405. for(auto conflict : mod.getConflicts())
  406. {
  407. if(required.contains(conflict))
  408. ret.push_back(name);
  409. }
  410. }
  411. }
  412. return ret;
  413. }
  414. QStringList CModListView::findDependentMods(QString mod, bool excludeDisabled)
  415. {
  416. QStringList ret;
  417. for(QString modName : modModel->getModList())
  418. {
  419. auto current = modModel->getMod(modName);
  420. if(!current.isInstalled() || !current.isVisible())
  421. continue;
  422. if(current.getDependencies().contains(mod, Qt::CaseInsensitive))
  423. {
  424. if(!(current.isDisabled() && excludeDisabled))
  425. ret += modName;
  426. }
  427. }
  428. return ret;
  429. }
  430. void CModListView::on_enableButton_clicked()
  431. {
  432. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  433. enableModByName(modName);
  434. checkManagerErrors();
  435. }
  436. void CModListView::enableModByName(QString modName)
  437. {
  438. assert(findBlockingMods(modName).empty());
  439. assert(findInvalidDependencies(modName).empty());
  440. for(auto & name : modModel->getRequirements(modName))
  441. {
  442. if(modModel->getMod(name).isDisabled())
  443. manager->enableMod(name);
  444. }
  445. emit modsChanged();
  446. }
  447. void CModListView::on_disableButton_clicked()
  448. {
  449. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  450. disableModByName(modName);
  451. checkManagerErrors();
  452. }
  453. void CModListView::disableModByName(QString modName)
  454. {
  455. if(modModel->hasMod(modName) && modModel->getMod(modName).isEnabled())
  456. manager->disableMod(modName);
  457. emit modsChanged();
  458. }
  459. void CModListView::on_updateButton_clicked()
  460. {
  461. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  462. assert(findInvalidDependencies(modName).empty());
  463. for(auto & name : modModel->getRequirements(modName))
  464. {
  465. auto mod = modModel->getMod(name);
  466. // update required mod, install missing (can be new dependency)
  467. if(mod.isUpdateable() || !mod.isInstalled())
  468. downloadFile(name + ".zip", mod.getValue("download").toString(), "mods", mbToBytes(mod.getValue("downloadSize").toDouble()));
  469. }
  470. }
  471. void CModListView::on_uninstallButton_clicked()
  472. {
  473. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  474. // NOTE: perhaps add "manually installed" flag and uninstall those dependencies that don't have it?
  475. if(modModel->hasMod(modName) && modModel->getMod(modName).isInstalled())
  476. {
  477. if(modModel->getMod(modName).isEnabled())
  478. manager->disableMod(modName);
  479. manager->uninstallMod(modName);
  480. }
  481. emit modsChanged();
  482. checkManagerErrors();
  483. }
  484. void CModListView::on_installButton_clicked()
  485. {
  486. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  487. assert(findInvalidDependencies(modName).empty());
  488. for(auto & name : modModel->getRequirements(modName))
  489. {
  490. auto mod = modModel->getMod(name);
  491. if(!mod.isInstalled())
  492. downloadFile(name + ".zip", mod.getValue("download").toString(), "mods", mbToBytes(mod.getValue("downloadSize").toDouble()));
  493. }
  494. }
  495. void CModListView::on_installFromFileButton_clicked()
  496. {
  497. QString filter = tr("All supported files") + " (*.h3m *.vmap *.h3c *.vcmp *.zip *.json);;" + tr("Maps") + " (*.h3m *.vmap);;" + tr("Campaigns") + " (*.h3c *.vcmp);;" + tr("Configs") + " (*.json);;" + tr("Mods") + " (*.zip)";
  498. QStringList files = QFileDialog::getOpenFileNames(this, tr("Select files (configs, mods, maps, campaigns) to install..."), QDir::homePath(), filter);
  499. for (const auto & file : files)
  500. {
  501. QUrl url = QUrl::fromLocalFile(file);
  502. manualInstallFile(url);
  503. }
  504. }
  505. void CModListView::manualInstallFile(QUrl url)
  506. {
  507. QString urlStr = url.toString();
  508. QString fileName = url.fileName();
  509. if(urlStr.endsWith(".zip", Qt::CaseInsensitive))
  510. downloadFile(fileName.toLower()
  511. // mod name currently comes from zip file -> remove suffixes from github zip download
  512. .replace(QRegularExpression("-[0-9a-f]{40}"), "")
  513. .replace(QRegularExpression("-vcmi-.+\\.zip"), ".zip")
  514. .replace("-main.zip", ".zip")
  515. , urlStr, "mods", 0);
  516. else if(urlStr.endsWith(".json", Qt::CaseInsensitive))
  517. {
  518. QDir configDir(QString::fromStdString(VCMIDirs::get().userConfigPath().string()));
  519. QStringList configFile = configDir.entryList({fileName}, QDir::Filter::Files); // case insensitive check
  520. if(!configFile.empty())
  521. {
  522. if(QMessageBox::warning(this, tr("Replace config file?"), tr("Do you want to replace %1?").arg(configFile[0]), QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
  523. {
  524. QFile::remove(configDir.filePath(configFile[0]));
  525. QFile::copy(url.toLocalFile(), configDir.filePath(configFile[0]));
  526. // reload settings
  527. for(auto widget : qApp->topLevelWidgets())
  528. if(auto mainWindow = qobject_cast<MainWindow *>(widget))
  529. mainWindow->loadSettings();
  530. for(auto widget : qApp->allWidgets())
  531. if(auto settingsView = qobject_cast<CSettingsView *>(widget))
  532. settingsView->loadSettings();
  533. manager->loadMods();
  534. manager->loadModSettings();
  535. }
  536. }
  537. }
  538. else
  539. downloadFile(fileName, urlStr, "mods", 0);
  540. }
  541. void CModListView::downloadFile(QString file, QString url, QString description, qint64 size)
  542. {
  543. if(!dlManager)
  544. {
  545. dlManager = new CDownloadManager();
  546. ui->progressWidget->setVisible(true);
  547. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  548. this, SLOT(downloadProgress(qint64,qint64)));
  549. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  550. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  551. connect(manager.get(), SIGNAL(extractionProgress(qint64,qint64)),
  552. this, SLOT(extractionProgress(qint64,qint64)));
  553. connect(modModel, &CModListModel::dataChanged, filterModel, &QAbstractItemModel::dataChanged);
  554. QString progressBarFormat = tr("Downloading %s%. %p% (%v MB out of %m MB) finished");
  555. progressBarFormat.replace("%s%", description);
  556. ui->progressBar->setFormat(progressBarFormat);
  557. }
  558. dlManager->downloadFile(QUrl(url), file, size);
  559. }
  560. void CModListView::downloadProgress(qint64 current, qint64 max)
  561. {
  562. // display progress, in megabytes
  563. ui->progressBar->setVisible(true);
  564. ui->progressBar->setMaximum(max / (1024 * 1024));
  565. ui->progressBar->setValue(current / (1024 * 1024));
  566. }
  567. void CModListView::extractionProgress(qint64 current, qint64 max)
  568. {
  569. // display progress, in extracted files
  570. ui->progressBar->setVisible(true);
  571. ui->progressBar->setMaximum(max);
  572. ui->progressBar->setValue(current);
  573. }
  574. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  575. {
  576. QString title = tr("Download failed");
  577. QString firstLine = tr("Unable to download all files.\n\nEncountered errors:\n\n");
  578. QString lastLine = tr("\n\nInstall successfully downloaded?");
  579. bool doInstallFiles = false;
  580. // if all files were d/loaded there should be no errors. And on failure there must be an error
  581. assert(failedFiles.empty() == errors.empty());
  582. if(savedFiles.empty())
  583. {
  584. // no successfully downloaded mods
  585. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  586. }
  587. else if(!failedFiles.empty())
  588. {
  589. // some mods were not downloaded
  590. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  591. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  592. if(result == QMessageBox::Yes)
  593. doInstallFiles = true;
  594. }
  595. else
  596. {
  597. // everything OK
  598. doInstallFiles = true;
  599. }
  600. dlManager->deleteLater();
  601. dlManager = nullptr;
  602. ui->progressBar->setMaximum(0);
  603. ui->progressBar->setValue(0);
  604. if(doInstallFiles)
  605. installFiles(savedFiles);
  606. hideProgressBar();
  607. emit modsChanged();
  608. }
  609. void CModListView::hideProgressBar()
  610. {
  611. if(dlManager == nullptr) // it was not recreated meanwhile
  612. {
  613. ui->progressWidget->setVisible(false);
  614. ui->progressBar->setMaximum(0);
  615. ui->progressBar->setValue(0);
  616. }
  617. }
  618. void CModListView::installFiles(QStringList files)
  619. {
  620. QStringList mods;
  621. QStringList maps;
  622. QStringList images;
  623. QVector<QVariantMap> repositories;
  624. // TODO: some better way to separate zip's with mods and downloaded repository files
  625. for(QString filename : files)
  626. {
  627. if(filename.endsWith(".zip", Qt::CaseInsensitive))
  628. mods.push_back(filename);
  629. else if(filename.endsWith(".h3m", Qt::CaseInsensitive) || filename.endsWith(".h3c", Qt::CaseInsensitive) || filename.endsWith(".vmap", Qt::CaseInsensitive) || filename.endsWith(".vcmp", Qt::CaseInsensitive))
  630. maps.push_back(filename);
  631. else if(filename.endsWith(".json", Qt::CaseInsensitive))
  632. {
  633. //download and merge additional files
  634. auto repoData = JsonUtils::JsonFromFile(filename).toMap();
  635. if(repoData.value("name").isNull())
  636. {
  637. for(const auto & key : repoData.keys())
  638. {
  639. auto modjson = repoData[key].toMap().value("mod");
  640. if(!modjson.isNull())
  641. {
  642. downloadFile(key + ".json", modjson.toString(), "repository index");
  643. }
  644. }
  645. }
  646. else
  647. {
  648. auto modn = QFileInfo(filename).baseName();
  649. QVariantMap temp;
  650. temp[modn] = repoData;
  651. repoData = temp;
  652. }
  653. repositories.push_back(repoData);
  654. }
  655. else if(filename.endsWith(".png", Qt::CaseInsensitive))
  656. images.push_back(filename);
  657. }
  658. manager->loadRepositories(repositories);
  659. if(!mods.empty())
  660. installMods(mods);
  661. if(!maps.empty())
  662. installMaps(maps);
  663. if(!images.empty())
  664. loadScreenshots();
  665. }
  666. void CModListView::installMods(QStringList archives)
  667. {
  668. QStringList modNames;
  669. for(QString archive : archives)
  670. {
  671. // get basename out of full file name
  672. // remove path remove extension
  673. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  674. modNames.push_back(modName);
  675. }
  676. QStringList modsToEnable;
  677. // disable mod(s), to properly recalculate dependencies, if changed
  678. for(QString mod : boost::adaptors::reverse(modNames))
  679. {
  680. CModEntry entry = modModel->getMod(mod);
  681. if(entry.isInstalled())
  682. {
  683. // enable mod if installed and enabled
  684. if(entry.isEnabled())
  685. modsToEnable.push_back(mod);
  686. }
  687. else
  688. {
  689. // enable mod if m
  690. if(settings["launcher"]["enableInstalledMods"].Bool())
  691. modsToEnable.push_back(mod);
  692. }
  693. }
  694. // uninstall old version of mod, if installed
  695. for(QString mod : boost::adaptors::reverse(modNames))
  696. {
  697. if(modModel->getMod(mod).isInstalled())
  698. manager->uninstallMod(mod);
  699. }
  700. for(int i = 0; i < modNames.size(); i++)
  701. {
  702. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  703. manager->installMod(modNames[i], archives[i]);
  704. }
  705. std::function<void(QString)> enableMod;
  706. enableMod = [&](QString modName)
  707. {
  708. auto mod = modModel->getMod(modName);
  709. if(mod.isInstalled() && !mod.getValue("keepDisabled").toBool())
  710. {
  711. if(mod.isDisabled() && manager->enableMod(modName))
  712. {
  713. for(QString child : modModel->getChildren(modName))
  714. enableMod(child);
  715. }
  716. }
  717. };
  718. for(QString mod : modsToEnable)
  719. {
  720. enableMod(mod);
  721. }
  722. checkManagerErrors();
  723. for(QString archive : archives)
  724. QFile::remove(archive);
  725. }
  726. void CModListView::installMaps(QStringList maps)
  727. {
  728. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  729. for(QString map : maps)
  730. {
  731. QFile(map).rename(destDir + map.section('/', -1, -1));
  732. }
  733. }
  734. void CModListView::on_refreshButton_clicked()
  735. {
  736. loadRepositories();
  737. }
  738. void CModListView::on_pushButton_clicked()
  739. {
  740. delete dlManager;
  741. dlManager = nullptr;
  742. hideProgressBar();
  743. }
  744. void CModListView::modelReset()
  745. {
  746. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  747. }
  748. void CModListView::checkManagerErrors()
  749. {
  750. QString errors = manager->getErrors().join('\n');
  751. if(errors.size() != 0)
  752. {
  753. QString title = tr("Operation failed");
  754. QString description = tr("Encountered errors:\n") + errors;
  755. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  756. }
  757. }
  758. void CModListView::on_tabWidget_currentChanged(int index)
  759. {
  760. loadScreenshots();
  761. }
  762. void CModListView::loadScreenshots()
  763. {
  764. if(ui->tabWidget->currentIndex() == 2)
  765. {
  766. ui->screenshotsList->clear();
  767. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  768. assert(modModel->hasMod(modName)); //should be filtered out by check above
  769. for(QString url : modModel->getMod(modName).getValue("screenshots").toStringList())
  770. {
  771. // URL must be encoded to something else to get rid of symbols illegal in file names
  772. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  773. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  774. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  775. QPixmap pixmap(fullPath);
  776. if(pixmap.isNull())
  777. {
  778. // image file not exists or corrupted - try to redownload
  779. downloadFile(fileName, url, "screenshots");
  780. }
  781. else
  782. {
  783. // managed to load cached image
  784. QIcon icon(pixmap);
  785. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  786. ui->screenshotsList->addItem(item);
  787. }
  788. }
  789. }
  790. }
  791. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  792. {
  793. if(index.isValid())
  794. {
  795. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  796. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  797. ImageViewer::showPixmap(pixmap, this);
  798. }
  799. }
  800. const CModList & CModListView::getModList() const
  801. {
  802. assert(modModel);
  803. return *modModel;
  804. }
  805. void CModListView::doInstallMod(const QString & modName)
  806. {
  807. assert(findInvalidDependencies(modName).empty());
  808. for(auto & name : modModel->getRequirements(modName))
  809. {
  810. auto mod = modModel->getMod(name);
  811. if(!mod.isInstalled())
  812. downloadFile(name + ".zip", mod.getValue("download").toString(), "mods", mbToBytes(mod.getValue("downloadSize").toDouble()));
  813. }
  814. }
  815. bool CModListView::isModAvailable(const QString & modName)
  816. {
  817. auto mod = modModel->getMod(modName);
  818. return mod.isAvailable();
  819. }
  820. bool CModListView::isModEnabled(const QString & modName)
  821. {
  822. auto mod = modModel->getMod(modName);
  823. return mod.isEnabled();
  824. }
  825. QString CModListView::getTranslationModName(const QString & language)
  826. {
  827. for(const auto & modName : modModel->getModList())
  828. {
  829. auto mod = modModel->getMod(modName);
  830. if (!mod.isTranslation())
  831. continue;
  832. if (mod.getBaseValue("language").toString() != language)
  833. continue;
  834. return modName;
  835. }
  836. return QString();
  837. }
  838. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  839. {
  840. if(!index.isValid())
  841. return;
  842. auto modName = index.data(ModRoles::ModNameRole).toString();
  843. auto mod = modModel->getMod(modName);
  844. bool hasInvalidDeps = !findInvalidDependencies(modName).empty();
  845. bool hasBlockingMods = !findBlockingMods(modName).empty();
  846. bool hasDependentMods = !findDependentMods(modName, true).empty();
  847. if(!hasInvalidDeps && mod.isAvailable() && !mod.isSubmod())
  848. {
  849. on_installButton_clicked();
  850. return;
  851. }
  852. if(!hasInvalidDeps && !hasDependentMods && mod.isUpdateable() && index.column() == ModFields::STATUS_UPDATE)
  853. {
  854. on_updateButton_clicked();
  855. return;
  856. }
  857. if(index.column() == ModFields::NAME)
  858. {
  859. if(ui->allModsView->isExpanded(index))
  860. ui->allModsView->collapse(index);
  861. else
  862. ui->allModsView->expand(index);
  863. return;
  864. }
  865. if(!hasBlockingMods && !hasInvalidDeps && mod.isDisabled())
  866. {
  867. on_enableButton_clicked();
  868. return;
  869. }
  870. if(!hasDependentMods && !mod.isEssential() && mod.isEnabled())
  871. {
  872. on_disableButton_clicked();
  873. return;
  874. }
  875. }