cmodlistview_moc.cpp 31 KB

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