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