cmodlistview_moc.cpp 34 KB

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