cmodlistview_moc.cpp 34 KB

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