cmodlistview_moc.cpp 34 KB

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