cmodlistview_moc.cpp 32 KB

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