cmodlistview_moc.cpp 31 KB

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