cmodlistview_moc.cpp 33 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::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. assert(result.removeDuplicates() == 0);
  483. return result;
  484. }
  485. void CModListView::on_updateButton_clicked()
  486. {
  487. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  488. for(const auto & name : getModsToInstall(modName))
  489. {
  490. auto mod = modStateModel->getMod(name);
  491. // update required mod, install missing (can be new dependency)
  492. if(mod.isUpdateAvailable() || !mod.isInstalled())
  493. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeBytes());
  494. }
  495. }
  496. void CModListView::on_uninstallButton_clicked()
  497. {
  498. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  499. if(modStateModel->isModExists(modName) && modStateModel->getMod(modName).isInstalled())
  500. {
  501. if(modStateModel->isModEnabled(modName))
  502. manager->disableMod(modName);
  503. manager->uninstallMod(modName);
  504. modModel->reloadRepositories();
  505. }
  506. checkManagerErrors();
  507. }
  508. void CModListView::on_installButton_clicked()
  509. {
  510. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  511. for(const auto & name : getModsToInstall(modName))
  512. {
  513. auto mod = modStateModel->getMod(name);
  514. if(mod.isAvailable())
  515. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeBytes());
  516. else if(!modStateModel->isModEnabled(name))
  517. enableModByName(name);
  518. }
  519. }
  520. void CModListView::on_installFromFileButton_clicked()
  521. {
  522. // iOS can't display modal dialogs when called directly on button press
  523. // https://bugreports.qt.io/browse/QTBUG-98651
  524. QTimer::singleShot(0, this, [this]
  525. {
  526. QString filter = tr("All supported files") + " (*.h3m *.vmap *.h3c *.vcmp *.zip *.json *.exe);;" +
  527. tr("Maps") + " (*.h3m *.vmap);;" +
  528. tr("Campaigns") + " (*.h3c *.vcmp);;" +
  529. tr("Configs") + " (*.json);;" +
  530. tr("Mods") + " (*.zip);;" +
  531. tr("Gog files") + " (*.exe)";
  532. #if defined(VCMI_MOBILE)
  533. filter = tr("All files (*.*)"); //Workaround for sometimes incorrect mime for some extensions (e.g. for exe)
  534. #endif
  535. QStringList files = QFileDialog::getOpenFileNames(this, tr("Select files (configs, mods, maps, campaigns, gog files) to install..."), QDir::homePath(), filter);
  536. for(const auto & file : files)
  537. {
  538. manualInstallFile(file);
  539. }
  540. });
  541. }
  542. void CModListView::manualInstallFile(QString filePath)
  543. {
  544. QString fileName = QFileInfo{filePath}.fileName();
  545. if(filePath.endsWith(".zip", Qt::CaseInsensitive))
  546. downloadFile(fileName.toLower()
  547. // mod name currently comes from zip file -> remove suffixes from github zip download
  548. .replace(QRegularExpression("-[0-9a-f]{40}"), "")
  549. .replace(QRegularExpression("-vcmi-.+\\.zip"), ".zip")
  550. .replace("-main.zip", ".zip")
  551. , QUrl::fromLocalFile(filePath), "mods");
  552. else if(filePath.endsWith(".json", Qt::CaseInsensitive))
  553. {
  554. QDir configDir(QString::fromStdString(VCMIDirs::get().userConfigPath().string()));
  555. QStringList configFile = configDir.entryList({fileName}, QDir::Filter::Files); // case insensitive check
  556. if(!configFile.empty())
  557. {
  558. 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);
  559. if(dialogResult == QMessageBox::Yes)
  560. {
  561. const auto configFilePath = configDir.filePath(configFile[0]);
  562. QFile::remove(configFilePath);
  563. QFile::copy(filePath, configFilePath);
  564. // reload settings
  565. Helper::loadSettings();
  566. for(const auto widget : qApp->allWidgets())
  567. if(auto settingsView = qobject_cast<CSettingsView *>(widget))
  568. settingsView->loadSettings();
  569. modStateModel->reloadLocalState();
  570. modModel->reloadRepositories();
  571. }
  572. }
  573. }
  574. else
  575. downloadFile(fileName, QUrl::fromLocalFile(filePath), fileName);
  576. }
  577. void CModListView::downloadFile(QString file, QString url, QString description, qint64 sizeBytes)
  578. {
  579. downloadFile(file, QUrl{url}, description, sizeBytes);
  580. }
  581. void CModListView::downloadFile(QString file, QUrl url, QString description, qint64 sizeBytes)
  582. {
  583. if(!dlManager)
  584. {
  585. dlManager = new CDownloadManager();
  586. ui->progressWidget->setVisible(true);
  587. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  588. this, SLOT(downloadProgress(qint64,qint64)));
  589. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  590. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  591. connect(manager.get(), SIGNAL(extractionProgress(qint64,qint64)),
  592. this, SLOT(extractionProgress(qint64,qint64)));
  593. connect(modModel, &ModStateItemModel::dataChanged, filterModel, &QAbstractItemModel::dataChanged);
  594. const auto progressBarFormat = tr("Downloading %1. %p% (%v MB out of %m MB) finished").arg(description);
  595. ui->progressBar->setFormat(progressBarFormat);
  596. }
  597. dlManager->downloadFile(url, file, sizeBytes);
  598. }
  599. void CModListView::downloadProgress(qint64 current, qint64 max)
  600. {
  601. // display progress, in megabytes
  602. ui->progressBar->setVisible(true);
  603. ui->progressBar->setMaximum(max / (1024 * 1024));
  604. ui->progressBar->setValue(current / (1024 * 1024));
  605. }
  606. void CModListView::extractionProgress(qint64 current, qint64 max)
  607. {
  608. // display progress, in extracted files
  609. ui->progressBar->setVisible(true);
  610. ui->progressBar->setMaximum(max);
  611. ui->progressBar->setValue(current);
  612. }
  613. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  614. {
  615. QString title = tr("Download failed");
  616. QString firstLine = tr("Unable to download all files.\n\nEncountered errors:\n\n");
  617. QString lastLine = tr("\n\nInstall successfully downloaded?");
  618. bool doInstallFiles = false;
  619. // if all files were d/loaded there should be no errors. And on failure there must be an error
  620. assert(failedFiles.empty() == errors.empty());
  621. if(savedFiles.empty())
  622. {
  623. // no successfully downloaded mods
  624. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  625. }
  626. else if(!failedFiles.empty())
  627. {
  628. // some mods were not downloaded
  629. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  630. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  631. if(result == QMessageBox::Yes)
  632. doInstallFiles = true;
  633. }
  634. else
  635. {
  636. // everything OK
  637. doInstallFiles = true;
  638. }
  639. dlManager->deleteLater();
  640. dlManager = nullptr;
  641. ui->progressBar->setMaximum(0);
  642. ui->progressBar->setValue(0);
  643. if(doInstallFiles)
  644. installFiles(savedFiles);
  645. hideProgressBar();
  646. }
  647. void CModListView::hideProgressBar()
  648. {
  649. if(dlManager == nullptr) // it was not recreated meanwhile
  650. {
  651. ui->progressWidget->setVisible(false);
  652. ui->progressBar->setMaximum(0);
  653. ui->progressBar->setValue(0);
  654. }
  655. }
  656. void CModListView::installFiles(QStringList files)
  657. {
  658. QStringList mods;
  659. QStringList maps;
  660. QStringList images;
  661. QStringList exe;
  662. JsonNode repository;
  663. // TODO: some better way to separate zip's with mods and downloaded repository files
  664. for(QString filename : files)
  665. {
  666. if(filename.endsWith(".zip", Qt::CaseInsensitive))
  667. mods.push_back(filename);
  668. else if(filename.endsWith(".h3m", Qt::CaseInsensitive) || filename.endsWith(".h3c", Qt::CaseInsensitive) || filename.endsWith(".vmap", Qt::CaseInsensitive) || filename.endsWith(".vcmp", Qt::CaseInsensitive))
  669. maps.push_back(filename);
  670. if(filename.endsWith(".exe", Qt::CaseInsensitive))
  671. exe.push_back(filename);
  672. else if(filename.endsWith(".json", Qt::CaseInsensitive))
  673. {
  674. //download and merge additional files
  675. const auto &repoData = JsonUtils::jsonFromFile(filename);
  676. if(repoData["name"].isNull())
  677. {
  678. // This is main repository index. Download all referenced mods
  679. for(const auto & [modName, modJson] : repoData.Struct())
  680. {
  681. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  682. auto modJsonUrl = modJson["mod"];
  683. if(!modJsonUrl.isNull())
  684. downloadFile(QString::fromStdString(modName + ".json"), QString::fromStdString(modJsonUrl.String()), tr("mods repository index"));
  685. repository[modNameLower] = modJson;
  686. }
  687. }
  688. else
  689. {
  690. // This is json of a single mod. Extract name of mod and add it to repo
  691. auto modName = QFileInfo(filename).baseName().toStdString();
  692. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  693. repository[modNameLower] = repoData;
  694. }
  695. }
  696. else if(filename.endsWith(".png", Qt::CaseInsensitive))
  697. images.push_back(filename);
  698. }
  699. if (!repository.isNull())
  700. {
  701. manager->appendRepositories(repository);
  702. modModel->reloadRepositories();
  703. static const QString repositoryCachePath = CLauncherDirs::downloadsPath() + "/repositoryCache.json";
  704. JsonUtils::jsonToFile(repositoryCachePath, modStateModel->getRepositoryData());
  705. }
  706. if(!mods.empty())
  707. installMods(mods);
  708. if(!maps.empty())
  709. installMaps(maps);
  710. if(!exe.empty())
  711. {
  712. ui->progressBar->setFormat(tr("Installing chronicles"));
  713. float prog = 0.0;
  714. auto futureExtract = std::async(std::launch::async, [this, exe, &prog]()
  715. {
  716. ChroniclesExtractor ce(this, [&prog](float progress) { prog = progress; });
  717. ce.installChronicles(exe);
  718. return true;
  719. });
  720. while(futureExtract.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
  721. {
  722. emit extractionProgress(static_cast<int>(prog * 1000.f), 1000);
  723. qApp->processEvents();
  724. }
  725. if(futureExtract.get())
  726. {
  727. //update
  728. modStateModel->reloadLocalState();
  729. modModel->reloadRepositories();
  730. }
  731. }
  732. if(!images.empty())
  733. loadScreenshots();
  734. }
  735. void CModListView::installMods(QStringList archives)
  736. {
  737. QStringList modNames;
  738. QStringList modsToEnable;
  739. for(QString archive : archives)
  740. {
  741. // get basename out of full file name
  742. // remove path remove extension
  743. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  744. modNames.push_back(modName);
  745. }
  746. // uninstall old version of mod, if installed
  747. for(QString mod : modNames)
  748. {
  749. if(modStateModel->getMod(mod).isInstalled())
  750. {
  751. if (modStateModel->isModEnabled(mod))
  752. modsToEnable.push_back(mod);
  753. manager->uninstallMod(mod);
  754. }
  755. else
  756. {
  757. // installation of previously not present mod -> enable it
  758. modsToEnable.push_back(mod);
  759. }
  760. }
  761. for(int i = 0; i < modNames.size(); i++)
  762. {
  763. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  764. manager->installMod(modNames[i], archives[i]);
  765. }
  766. manager->enableMods(modsToEnable);
  767. checkManagerErrors();
  768. for(QString archive : archives)
  769. QFile::remove(archive);
  770. }
  771. void CModListView::installMaps(QStringList maps)
  772. {
  773. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  774. for(QString map : maps)
  775. {
  776. QFile(map).rename(destDir + map.section('/', -1, -1));
  777. }
  778. }
  779. void CModListView::on_refreshButton_clicked()
  780. {
  781. loadRepositories();
  782. }
  783. void CModListView::on_pushButton_clicked()
  784. {
  785. delete dlManager;
  786. dlManager = nullptr;
  787. hideProgressBar();
  788. }
  789. void CModListView::modelReset()
  790. {
  791. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  792. }
  793. void CModListView::checkManagerErrors()
  794. {
  795. QString errors = manager->getErrors().join('\n');
  796. if(errors.size() != 0)
  797. {
  798. QString title = tr("Operation failed");
  799. QString description = tr("Encountered errors:\n") + errors;
  800. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  801. }
  802. }
  803. void CModListView::on_tabWidget_currentChanged(int index)
  804. {
  805. loadScreenshots();
  806. }
  807. void CModListView::loadScreenshots()
  808. {
  809. if(ui->tabWidget->currentIndex() == 2)
  810. {
  811. if(!ui->allModsView->currentIndex().isValid())
  812. {
  813. // select the first mod, so we can access its data
  814. ui->allModsView->setCurrentIndex(filterModel->index(0, 0));
  815. }
  816. ui->screenshotsList->clear();
  817. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  818. assert(modStateModel->isModExists(modName)); //should be filtered out by check above
  819. for(QString url : modStateModel->getMod(modName).getScreenshots())
  820. {
  821. // URL must be encoded to something else to get rid of symbols illegal in file names
  822. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  823. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  824. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  825. QPixmap pixmap(fullPath);
  826. if(pixmap.isNull())
  827. {
  828. // image file not exists or corrupted - try to redownload
  829. downloadFile(fileName, url, tr("screenshots"));
  830. }
  831. else
  832. {
  833. // managed to load cached image
  834. QIcon icon(pixmap);
  835. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  836. ui->screenshotsList->addItem(item);
  837. }
  838. }
  839. }
  840. }
  841. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  842. {
  843. if(index.isValid())
  844. {
  845. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  846. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  847. ImageViewer::showPixmap(pixmap, this);
  848. }
  849. }
  850. void CModListView::doInstallMod(const QString & modName)
  851. {
  852. for(const auto & name : modStateModel->getMod(modName).getDependencies())
  853. {
  854. auto mod = modStateModel->getMod(name);
  855. if(!mod.isInstalled())
  856. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeBytes());
  857. }
  858. }
  859. bool CModListView::isModAvailable(const QString & modName)
  860. {
  861. return !modStateModel->isModInstalled(modName);
  862. }
  863. bool CModListView::isModEnabled(const QString & modName)
  864. {
  865. return modStateModel->isModEnabled(modName);
  866. }
  867. bool CModListView::isModInstalled(const QString & modName)
  868. {
  869. auto mod = modStateModel->getMod(modName);
  870. return mod.isInstalled();
  871. }
  872. QString CModListView::getTranslationModName(const QString & language)
  873. {
  874. for(const auto & modName : modStateModel->getAllMods())
  875. {
  876. auto mod = modStateModel->getMod(modName);
  877. if (!mod.isTranslation())
  878. continue;
  879. if (mod.getBaseLanguage() != language)
  880. continue;
  881. return modName;
  882. }
  883. return QString();
  884. }
  885. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  886. {
  887. if(!index.isValid())
  888. return;
  889. auto modName = index.data(ModRoles::ModNameRole).toString();
  890. auto mod = modStateModel->getMod(modName);
  891. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  892. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  893. if(unavailableDependencies.empty() && mod.isAvailable() && !mod.isSubmod())
  894. {
  895. on_installButton_clicked();
  896. return;
  897. }
  898. if(unavailableDependencies.empty() && mod.isUpdateAvailable() && index.column() == ModFields::STATUS_UPDATE)
  899. {
  900. on_updateButton_clicked();
  901. return;
  902. }
  903. if(index.column() == ModFields::NAME)
  904. {
  905. if(ui->allModsView->isExpanded(index))
  906. ui->allModsView->collapse(index);
  907. else
  908. ui->allModsView->expand(index);
  909. return;
  910. }
  911. if(notInstalledDependencies.empty() && !modStateModel->isModEnabled(modName))
  912. {
  913. on_enableButton_clicked();
  914. return;
  915. }
  916. if(modStateModel->isModEnabled(modName))
  917. {
  918. on_disableButton_clicked();
  919. return;
  920. }
  921. }