cmodlistview_moc.cpp 32 KB

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