cmodlistview_moc.cpp 33 KB

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