cmodlistview_moc.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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. emit 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. // uninstall old version of mod, if installed
  706. for(QString mod : modNames)
  707. {
  708. if(modStateModel->isModExists(mod) && modStateModel->getMod(mod).isInstalled())
  709. {
  710. logGlobal->info("Uninstalling old version of mod '%s'", mod.toStdString());
  711. if (modStateModel->isModEnabled(mod))
  712. modsToEnable.push_back(mod);
  713. manager->uninstallMod(mod);
  714. }
  715. else
  716. {
  717. // installation of previously not present mod -> enable it
  718. modsToEnable.push_back(mod);
  719. }
  720. }
  721. reload(); // FIXME: better way that won't reset selection
  722. for(int i = 0; i < modNames.size(); i++)
  723. {
  724. logGlobal->info("Installing mod '%s'", modNames[i].toStdString());
  725. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  726. manager->installMod(modNames[i], archives[i]);
  727. }
  728. reload();
  729. if (!modsToEnable.empty())
  730. {
  731. manager->enableMods(modsToEnable);
  732. }
  733. checkManagerErrors();
  734. for(QString archive : archives)
  735. {
  736. logGlobal->info("Erasing archive '%s'", archive.toStdString());
  737. QFile::remove(archive);
  738. }
  739. }
  740. void CModListView::installMaps(QStringList maps)
  741. {
  742. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  743. for(QString map : maps)
  744. {
  745. logGlobal->info("Importing map '%s'", map.toStdString());
  746. QFile(map).rename(destDir + map.section('/', -1, -1));
  747. }
  748. }
  749. void CModListView::on_refreshButton_clicked()
  750. {
  751. loadRepositories();
  752. }
  753. void CModListView::on_pushButton_clicked()
  754. {
  755. delete dlManager;
  756. dlManager = nullptr;
  757. hideProgressBar();
  758. }
  759. void CModListView::modelReset()
  760. {
  761. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  762. }
  763. void CModListView::checkManagerErrors()
  764. {
  765. QString errors = manager->getErrors().join('\n');
  766. if(errors.size() != 0)
  767. {
  768. QString title = tr("Operation failed");
  769. QString description = tr("Encountered errors:\n") + errors;
  770. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  771. }
  772. }
  773. void CModListView::on_tabWidget_currentChanged(int index)
  774. {
  775. loadScreenshots();
  776. }
  777. void CModListView::loadScreenshots()
  778. {
  779. if(ui->tabWidget->currentIndex() == 2)
  780. {
  781. if(!ui->allModsView->currentIndex().isValid())
  782. {
  783. // select the first mod, so we can access its data
  784. ui->allModsView->setCurrentIndex(filterModel->index(0, 0));
  785. }
  786. ui->screenshotsList->clear();
  787. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  788. assert(modStateModel->isModExists(modName)); //should be filtered out by check above
  789. for(QString url : modStateModel->getMod(modName).getScreenshots())
  790. {
  791. // URL must be encoded to something else to get rid of symbols illegal in file names
  792. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  793. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  794. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  795. QPixmap pixmap(fullPath);
  796. if(pixmap.isNull())
  797. {
  798. // image file not exists or corrupted - try to redownload
  799. downloadFile(fileName, url, tr("screenshots"));
  800. }
  801. else
  802. {
  803. // managed to load cached image
  804. QIcon icon(pixmap);
  805. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  806. ui->screenshotsList->addItem(item);
  807. }
  808. }
  809. }
  810. }
  811. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  812. {
  813. if(index.isValid())
  814. {
  815. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  816. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  817. ImageViewer::showPixmap(pixmap, this);
  818. }
  819. }
  820. void CModListView::doInstallMod(const QString & modName)
  821. {
  822. for(const auto & name : getModsToInstall(modName))
  823. {
  824. auto mod = modStateModel->getMod(name);
  825. if(mod.isAvailable())
  826. downloadMod(mod);
  827. else if(!modStateModel->isModEnabled(name))
  828. enableModByName(name);
  829. }
  830. }
  831. bool CModListView::isModAvailable(const QString & modName)
  832. {
  833. return !modStateModel->isModInstalled(modName);
  834. }
  835. bool CModListView::isModEnabled(const QString & modName)
  836. {
  837. return modStateModel->isModEnabled(modName);
  838. }
  839. bool CModListView::isModInstalled(const QString & modName)
  840. {
  841. auto mod = modStateModel->getMod(modName);
  842. return mod.isInstalled();
  843. }
  844. QStringList CModListView::getInstalledChronicles()
  845. {
  846. QStringList result;
  847. for(const auto & modName : modStateModel->getAllMods())
  848. {
  849. auto mod = modStateModel->getMod(modName);
  850. if (!mod.isInstalled())
  851. continue;
  852. if (mod.getTopParentID() != "chronicles")
  853. continue;
  854. result += modName;
  855. }
  856. return result;
  857. }
  858. QStringList CModListView::getUpdateableMods()
  859. {
  860. QStringList result;
  861. for(const auto & modName : modStateModel->getAllMods())
  862. {
  863. auto mod = modStateModel->getMod(modName);
  864. if (mod.isUpdateAvailable())
  865. result.push_back(modName);
  866. }
  867. return result;
  868. }
  869. QString CModListView::getTranslationModName(const QString & language)
  870. {
  871. for(const auto & modName : modStateModel->getAllMods())
  872. {
  873. auto mod = modStateModel->getMod(modName);
  874. if (!mod.isTranslation())
  875. continue;
  876. if (mod.getBaseLanguage() != language)
  877. continue;
  878. return modName;
  879. }
  880. return QString();
  881. }
  882. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  883. {
  884. if(!index.isValid())
  885. return;
  886. auto modName = index.data(ModRoles::ModNameRole).toString();
  887. auto mod = modStateModel->getMod(modName);
  888. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  889. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  890. if(unavailableDependencies.empty() && mod.isAvailable() && !mod.isSubmod())
  891. {
  892. on_installButton_clicked();
  893. return;
  894. }
  895. if(unavailableDependencies.empty() && mod.isUpdateAvailable() && index.column() == ModFields::STATUS_UPDATE)
  896. {
  897. on_updateButton_clicked();
  898. return;
  899. }
  900. if(index.column() == ModFields::NAME)
  901. {
  902. if(ui->allModsView->isExpanded(index))
  903. ui->allModsView->collapse(index);
  904. else
  905. ui->allModsView->expand(index);
  906. return;
  907. }
  908. if(notInstalledDependencies.empty() && !modStateModel->isModEnabled(modName))
  909. {
  910. on_enableButton_clicked();
  911. return;
  912. }
  913. if(modStateModel->isModEnabled(modName))
  914. {
  915. on_disableButton_clicked();
  916. return;
  917. }
  918. }
  919. void CModListView::createNewPreset(const QString & presetName)
  920. {
  921. modStateModel->createNewPreset(presetName);
  922. }
  923. void CModListView::deletePreset(const QString & presetName)
  924. {
  925. modStateModel->deletePreset(presetName);
  926. }
  927. void CModListView::activatePreset(const QString & presetName)
  928. {
  929. modStateModel->activatePreset(presetName);
  930. reload();
  931. }
  932. void CModListView::renamePreset(const QString & oldPresetName, const QString & newPresetName)
  933. {
  934. modStateModel->renamePreset(oldPresetName, newPresetName);
  935. }
  936. QStringList CModListView::getAllPresets() const
  937. {
  938. return modStateModel->getAllPresets();
  939. }
  940. QString CModListView::getActivePreset() const
  941. {
  942. return modStateModel->getActivePreset();
  943. }