cmodlistview_moc.cpp 34 KB

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