cmodlistview_moc.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136
  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 "chroniclesextractor.h"
  22. #include "../settingsView/csettingsview_moc.h"
  23. #include "../launcherdirs.h"
  24. #include "../jsonutils.h"
  25. #include "../helper.h"
  26. #include "../../lib/VCMIDirs.h"
  27. #include "../../lib/CConfigHandler.h"
  28. #include "../../lib/texts/Languages.h"
  29. #include "../../lib/modding/CModVersion.h"
  30. #include "../../lib/filesystem/Filesystem.h"
  31. static double mbToBytes(double mb)
  32. {
  33. return mb * 1024 * 1024;
  34. }
  35. void CModListView::setupModModel()
  36. {
  37. modModel = new CModListModel(this);
  38. manager = std::make_unique<CModManager>(modModel);
  39. }
  40. void CModListView::changeEvent(QEvent *event)
  41. {
  42. if(event->type() == QEvent::LanguageChange)
  43. {
  44. ui->retranslateUi(this);
  45. modModel->reloadRepositories();
  46. }
  47. QWidget::changeEvent(event);
  48. }
  49. void CModListView::dragEnterEvent(QDragEnterEvent* event)
  50. {
  51. if(event->mimeData()->hasUrls())
  52. for(const auto & url : event->mimeData()->urls())
  53. for(const auto & ending : QStringList({".zip", ".h3m", ".h3c", ".vmap", ".vcmp", ".json", ".exe"}))
  54. if(url.fileName().endsWith(ending, Qt::CaseInsensitive))
  55. {
  56. event->acceptProposedAction();
  57. return;
  58. }
  59. }
  60. void CModListView::dropEvent(QDropEvent* event)
  61. {
  62. const QMimeData* mimeData = event->mimeData();
  63. if(mimeData->hasUrls())
  64. {
  65. const QList<QUrl> urlList = mimeData->urls();
  66. for (const auto & url : urlList)
  67. manualInstallFile(url.toLocalFile());
  68. }
  69. }
  70. void CModListView::setupFilterModel()
  71. {
  72. filterModel = new CModFilterModel(modModel, this);
  73. filterModel->setFilterKeyColumn(-1); // filter across all columns
  74. filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); // to make it more user-friendly
  75. filterModel->setDynamicSortFilter(true);
  76. }
  77. void CModListView::setupModsView()
  78. {
  79. ui->allModsView->setModel(filterModel);
  80. // input data is not sorted - sort it before display
  81. ui->allModsView->sortByColumn(ModFields::TYPE, Qt::AscendingOrder);
  82. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_ENABLED, QHeaderView::Fixed);
  83. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_UPDATE, QHeaderView::Fixed);
  84. QSettings s(Ui::teamName, Ui::appName);
  85. auto state = s.value("AllModsView/State").toByteArray();
  86. if(!state.isNull()) //read last saved settings
  87. {
  88. ui->allModsView->header()->restoreState(state);
  89. }
  90. else //default //TODO: default high-DPI scaling
  91. {
  92. ui->allModsView->setColumnWidth(ModFields::NAME, 220);
  93. ui->allModsView->setColumnWidth(ModFields::TYPE, 75);
  94. }
  95. ui->allModsView->resizeColumnToContents(ModFields::STATUS_ENABLED);
  96. ui->allModsView->resizeColumnToContents(ModFields::STATUS_UPDATE);
  97. ui->allModsView->setUniformRowHeights(true);
  98. connect(ui->allModsView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&,const QModelIndex&)),
  99. this, SLOT(modSelected(const QModelIndex&,const QModelIndex&)));
  100. connect(filterModel, SIGNAL(modelReset()),
  101. this, SLOT(modelReset()));
  102. connect(modModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
  103. this, SLOT(dataChanged(QModelIndex,QModelIndex)));
  104. }
  105. CModListView::CModListView(QWidget * parent)
  106. : QWidget(parent)
  107. , ui(new Ui::CModListView)
  108. {
  109. ui->setupUi(this);
  110. setAcceptDrops(true);
  111. ui->uninstallButton->setIcon(QIcon{":/icons/mod-delete.png"});
  112. ui->enableButton->setIcon(QIcon{":/icons/mod-enabled.png"});
  113. ui->disableButton->setIcon(QIcon{":/icons/mod-disabled.png"});
  114. ui->updateButton->setIcon(QIcon{":/icons/mod-update.png"});
  115. ui->installButton->setIcon(QIcon{":/icons/mod-download.png"});
  116. ui->splitter->setStyleSheet("QSplitter::handle {background: palette('window');}");
  117. setupModModel();
  118. setupFilterModel();
  119. setupModsView();
  120. ui->progressWidget->setVisible(false);
  121. dlManager = nullptr;
  122. if(settings["launcher"]["autoCheckRepositories"].Bool())
  123. {
  124. loadRepositories();
  125. }
  126. else
  127. {
  128. manager->resetRepositories();
  129. }
  130. #ifdef VCMI_MOBILE
  131. for(auto * scrollWidget : {
  132. (QAbstractItemView*)ui->allModsView,
  133. (QAbstractItemView*)ui->screenshotsList})
  134. {
  135. Helper::enableScrollBySwiping(scrollWidget);
  136. scrollWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
  137. scrollWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  138. }
  139. #endif
  140. }
  141. void CModListView::loadRepositories()
  142. {
  143. manager->resetRepositories();
  144. QStringList repositories;
  145. if (settings["launcher"]["defaultRepositoryEnabled"].Bool())
  146. repositories.push_back(QString::fromStdString(settings["launcher"]["defaultRepositoryURL"].String()));
  147. if (settings["launcher"]["extraRepositoryEnabled"].Bool())
  148. repositories.push_back(QString::fromStdString(settings["launcher"]["extraRepositoryURL"].String()));
  149. for(auto entry : repositories)
  150. {
  151. if (entry.isEmpty())
  152. continue;
  153. // URL must be encoded to something else to get rid of symbols illegal in file names
  154. auto hashed = QCryptographicHash::hash(entry.toUtf8(), QCryptographicHash::Md5);
  155. auto hashedStr = QString::fromUtf8(hashed.toHex());
  156. downloadFile(hashedStr + ".json", entry, tr("mods repository index"));
  157. }
  158. }
  159. CModListView::~CModListView()
  160. {
  161. QSettings s(Ui::teamName, Ui::appName);
  162. s.setValue("AllModsView/State", ui->allModsView->header()->saveState());
  163. delete ui;
  164. }
  165. static QString replaceIfNotEmpty(QVariant value, QString pattern)
  166. {
  167. if(value.canConvert<QStringList>())
  168. return pattern.arg(value.toStringList().join(", "));
  169. if(value.canConvert<QString>())
  170. return pattern.arg(value.toString());
  171. // all valid types of data should have been filtered by code above
  172. assert(!value.isValid());
  173. return "";
  174. }
  175. static QString replaceIfNotEmpty(QStringList value, QString pattern)
  176. {
  177. if(!value.empty())
  178. return pattern.arg(value.join(", "));
  179. return "";
  180. }
  181. QString CModListView::genChangelogText(CModEntry & mod)
  182. {
  183. QString headerTemplate = "<p><span style=\" font-weight:600;\">%1: </span></p>";
  184. QString entryBegin = "<p align=\"justify\"><ul>";
  185. QString entryEnd = "</ul></p>";
  186. QString entryLine = "<li>%1</li>";
  187. //QString versionSeparator = "<hr/>";
  188. QString result;
  189. QVariantMap changelog = mod.getValue("changelog").toMap();
  190. QList<QString> versions = changelog.keys();
  191. std::sort(versions.begin(), versions.end(), [](QString lesser, QString greater)
  192. {
  193. return CModVersion::fromString(lesser.toStdString()) < CModVersion::fromString(greater.toStdString());
  194. });
  195. std::reverse(versions.begin(), versions.end());
  196. for(auto & version : versions)
  197. {
  198. result += headerTemplate.arg(version);
  199. result += entryBegin;
  200. for(auto & line : changelog.value(version).toStringList())
  201. result += entryLine.arg(line);
  202. result += entryEnd;
  203. }
  204. return result;
  205. }
  206. QStringList CModListView::getModNames(QStringList input)
  207. {
  208. QStringList result;
  209. for(const auto & modID : input)
  210. {
  211. auto mod = modModel->getMod(modID.toLower());
  212. QString modName = mod.getValue("name").toString();
  213. if (modName.isEmpty())
  214. result += modID.toLower();
  215. else
  216. result += modName;
  217. }
  218. return result;
  219. }
  220. QString CModListView::genModInfoText(CModEntry & mod)
  221. {
  222. QString prefix = "<p><span style=\" font-weight:600;\">%1: </span>"; // shared prefix
  223. QString redPrefix = "<p><span style=\" font-weight:600; color:red\">%1: </span>"; // shared prefix
  224. QString lineTemplate = prefix + "%2</p>";
  225. QString urlTemplate = prefix + "<a href=\"%2\">%3</a></p>";
  226. QString textTemplate = prefix + "</p><p align=\"justify\">%2</p>";
  227. QString listTemplate = "<p align=\"justify\">%1: %2</p>";
  228. QString noteTemplate = "<p align=\"justify\">%1</p>";
  229. QString incompatibleString = redPrefix + tr("Mod is incompatible") + "</p>";
  230. QString supportedVersions = redPrefix + "%2 %3 %4</p>";
  231. QString result;
  232. result += replaceIfNotEmpty(mod.getValue("name"), lineTemplate.arg(tr("Mod name")));
  233. result += replaceIfNotEmpty(mod.getValue("installedVersion"), lineTemplate.arg(tr("Installed version")));
  234. result += replaceIfNotEmpty(mod.getValue("latestVersion"), lineTemplate.arg(tr("Latest version")));
  235. if(mod.getValue("localSizeBytes").isValid())
  236. result += replaceIfNotEmpty(CModEntry::sizeToString(mod.getValue("localSizeBytes").toDouble()), lineTemplate.arg(tr("Size")));
  237. if((mod.isAvailable() || mod.isUpdateable()) && mod.getValue("downloadSize").isValid())
  238. result += replaceIfNotEmpty(CModEntry::sizeToString(mbToBytes(mod.getValue("downloadSize").toDouble())), lineTemplate.arg(tr("Download size")));
  239. result += replaceIfNotEmpty(mod.getValue("author"), lineTemplate.arg(tr("Authors")));
  240. if(mod.getValue("licenseURL").isValid())
  241. result += urlTemplate.arg(tr("License")).arg(mod.getValue("licenseURL").toString()).arg(mod.getValue("licenseName").toString());
  242. if(mod.getValue("contact").isValid())
  243. result += urlTemplate.arg(tr("Contact")).arg(mod.getValue("contact").toString()).arg(mod.getValue("contact").toString());
  244. //compatibility info
  245. if(!mod.isCompatible())
  246. {
  247. auto compatibilityInfo = mod.getValue("compatibility").toMap();
  248. auto minStr = compatibilityInfo.value("min").toString();
  249. auto maxStr = compatibilityInfo.value("max").toString();
  250. result += incompatibleString.arg(tr("Compatibility"));
  251. if(minStr == maxStr)
  252. result += supportedVersions.arg(tr("Required VCMI version"), minStr, "", "");
  253. else
  254. {
  255. if(minStr.isEmpty() || maxStr.isEmpty())
  256. {
  257. if(minStr.isEmpty())
  258. result += supportedVersions.arg(tr("Supported VCMI version"), maxStr, ", ", tr("please upgrade mod"));
  259. else
  260. result += supportedVersions.arg(tr("Required VCMI version"), minStr, " ", tr("or newer"));
  261. }
  262. else
  263. result += supportedVersions.arg(tr("Supported VCMI versions"), minStr, " - ", maxStr);
  264. }
  265. }
  266. QStringList supportedLanguages;
  267. QVariant baseLanguageVariant = mod.getBaseValue("language");
  268. QString baseLanguageID = baseLanguageVariant.isValid() ? baseLanguageVariant.toString() : "english";
  269. bool needToShowSupportedLanguages = false;
  270. for(const auto & language : Languages::getLanguageList())
  271. {
  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.isAvailable())
  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. // iOS can't display modal dialogs when called directly on button press
  520. // https://bugreports.qt.io/browse/QTBUG-98651
  521. QTimer::singleShot(0, this, [this]
  522. {
  523. QString filter = tr("All supported files") + " (*.h3m *.vmap *.h3c *.vcmp *.zip *.json *.exe);;" + tr("Maps") + " (*.h3m *.vmap);;" + tr("Campaigns") + " (*.h3c *.vcmp);;" + tr("Configs") + " (*.json);;" + tr("Mods") + " (*.zip);;" + tr("Gog files") + " (*.exe)";
  524. QStringList files = QFileDialog::getOpenFileNames(this, tr("Select files (configs, mods, maps, campaigns, gog files) to install..."), QDir::homePath(), filter);
  525. for(const auto & file : files)
  526. {
  527. manualInstallFile(file);
  528. }
  529. });
  530. }
  531. void CModListView::manualInstallFile(QString filePath)
  532. {
  533. QString fileName = QFileInfo{filePath}.fileName();
  534. if(filePath.endsWith(".zip", Qt::CaseInsensitive))
  535. downloadFile(fileName.toLower()
  536. // mod name currently comes from zip file -> remove suffixes from github zip download
  537. .replace(QRegularExpression("-[0-9a-f]{40}"), "")
  538. .replace(QRegularExpression("-vcmi-.+\\.zip"), ".zip")
  539. .replace("-main.zip", ".zip")
  540. , QUrl::fromLocalFile(filePath), "mods");
  541. else if(filePath.endsWith(".json", Qt::CaseInsensitive))
  542. {
  543. QDir configDir(QString::fromStdString(VCMIDirs::get().userConfigPath().string()));
  544. QStringList configFile = configDir.entryList({fileName}, QDir::Filter::Files); // case insensitive check
  545. if(!configFile.empty())
  546. {
  547. 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);
  548. if(dialogResult == QMessageBox::Yes)
  549. {
  550. const auto configFilePath = configDir.filePath(configFile[0]);
  551. QFile::remove(configFilePath);
  552. QFile::copy(filePath, configFilePath);
  553. // reload settings
  554. Helper::loadSettings();
  555. for(auto widget : qApp->allWidgets())
  556. if(auto settingsView = qobject_cast<CSettingsView *>(widget))
  557. settingsView->loadSettings();
  558. manager->loadMods();
  559. manager->loadModSettings();
  560. }
  561. }
  562. }
  563. else
  564. downloadFile(fileName, QUrl::fromLocalFile(filePath), fileName);
  565. }
  566. void CModListView::downloadFile(QString file, QString url, QString description, qint64 size)
  567. {
  568. downloadFile(file, QUrl{url}, description, size);
  569. }
  570. void CModListView::downloadFile(QString file, QUrl url, QString description, qint64 size)
  571. {
  572. if(!dlManager)
  573. {
  574. dlManager = new CDownloadManager();
  575. ui->progressWidget->setVisible(true);
  576. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  577. this, SLOT(downloadProgress(qint64,qint64)));
  578. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  579. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  580. connect(manager.get(), SIGNAL(extractionProgress(qint64,qint64)),
  581. this, SLOT(extractionProgress(qint64,qint64)));
  582. connect(modModel, &CModListModel::dataChanged, filterModel, &QAbstractItemModel::dataChanged);
  583. const auto progressBarFormat = tr("Downloading %1. %p% (%v MB out of %m MB) finished").arg(description);
  584. ui->progressBar->setFormat(progressBarFormat);
  585. }
  586. dlManager->downloadFile(url, file, size);
  587. }
  588. void CModListView::downloadProgress(qint64 current, qint64 max)
  589. {
  590. // display progress, in megabytes
  591. ui->progressBar->setVisible(true);
  592. ui->progressBar->setMaximum(max / (1024 * 1024));
  593. ui->progressBar->setValue(current / (1024 * 1024));
  594. }
  595. void CModListView::extractionProgress(qint64 current, qint64 max)
  596. {
  597. // display progress, in extracted files
  598. ui->progressBar->setVisible(true);
  599. ui->progressBar->setMaximum(max);
  600. ui->progressBar->setValue(current);
  601. }
  602. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  603. {
  604. QString title = tr("Download failed");
  605. QString firstLine = tr("Unable to download all files.\n\nEncountered errors:\n\n");
  606. QString lastLine = tr("\n\nInstall successfully downloaded?");
  607. bool doInstallFiles = false;
  608. // if all files were d/loaded there should be no errors. And on failure there must be an error
  609. assert(failedFiles.empty() == errors.empty());
  610. if(savedFiles.empty())
  611. {
  612. // no successfully downloaded mods
  613. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  614. }
  615. else if(!failedFiles.empty())
  616. {
  617. // some mods were not downloaded
  618. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  619. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  620. if(result == QMessageBox::Yes)
  621. doInstallFiles = true;
  622. }
  623. else
  624. {
  625. // everything OK
  626. doInstallFiles = true;
  627. }
  628. dlManager->deleteLater();
  629. dlManager = nullptr;
  630. ui->progressBar->setMaximum(0);
  631. ui->progressBar->setValue(0);
  632. if(doInstallFiles)
  633. installFiles(savedFiles);
  634. hideProgressBar();
  635. emit modsChanged();
  636. }
  637. void CModListView::hideProgressBar()
  638. {
  639. if(dlManager == nullptr) // it was not recreated meanwhile
  640. {
  641. ui->progressWidget->setVisible(false);
  642. ui->progressBar->setMaximum(0);
  643. ui->progressBar->setValue(0);
  644. }
  645. }
  646. void CModListView::installFiles(QStringList files)
  647. {
  648. QStringList mods;
  649. QStringList maps;
  650. QStringList images;
  651. QStringList exe;
  652. QVector<QVariantMap> repositories;
  653. // TODO: some better way to separate zip's with mods and downloaded repository files
  654. for(QString filename : files)
  655. {
  656. if(filename.endsWith(".zip", Qt::CaseInsensitive))
  657. mods.push_back(filename);
  658. else if(filename.endsWith(".h3m", Qt::CaseInsensitive) || filename.endsWith(".h3c", Qt::CaseInsensitive) || filename.endsWith(".vmap", Qt::CaseInsensitive) || filename.endsWith(".vcmp", Qt::CaseInsensitive))
  659. maps.push_back(filename);
  660. if(filename.endsWith(".exe", Qt::CaseInsensitive))
  661. exe.push_back(filename);
  662. else if(filename.endsWith(".json", Qt::CaseInsensitive))
  663. {
  664. //download and merge additional files
  665. auto repoData = JsonUtils::JsonFromFile(filename).toMap();
  666. if(repoData.value("name").isNull())
  667. {
  668. for(const auto & key : repoData.keys())
  669. {
  670. auto modjson = repoData[key].toMap().value("mod");
  671. if(!modjson.isNull())
  672. {
  673. downloadFile(key + ".json", modjson.toString(), tr("mods repository index"));
  674. }
  675. }
  676. }
  677. else
  678. {
  679. auto modn = QFileInfo(filename).baseName();
  680. QVariantMap temp;
  681. temp[modn] = repoData;
  682. repoData = temp;
  683. }
  684. repositories.push_back(repoData);
  685. }
  686. else if(filename.endsWith(".png", Qt::CaseInsensitive))
  687. images.push_back(filename);
  688. }
  689. if (!repositories.empty())
  690. manager->loadRepositories(repositories);
  691. if(!mods.empty())
  692. installMods(mods);
  693. if(!maps.empty())
  694. installMaps(maps);
  695. if(!exe.empty())
  696. {
  697. ui->progressBar->setFormat(tr("Installing chronicles"));
  698. float prog = 0.0;
  699. auto futureExtract = std::async(std::launch::async, [this, exe, &prog]()
  700. {
  701. ChroniclesExtractor ce(this, [&prog](float progress) { prog = progress; });
  702. ce.installChronicles(exe);
  703. return true;
  704. });
  705. while(futureExtract.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
  706. {
  707. emit extractionProgress(int(prog * 1000.f), 1000);
  708. qApp->processEvents();
  709. }
  710. if(futureExtract.get())
  711. {
  712. //update
  713. CResourceHandler::get("initial")->updateFilteredFiles([](const std::string &){ return true; });
  714. manager->loadMods();
  715. modModel->reloadRepositories();
  716. emit modsChanged();
  717. }
  718. }
  719. if(!images.empty())
  720. loadScreenshots();
  721. }
  722. void CModListView::installMods(QStringList archives)
  723. {
  724. QStringList modNames;
  725. for(QString archive : archives)
  726. {
  727. // get basename out of full file name
  728. // remove path remove extension
  729. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  730. modNames.push_back(modName);
  731. }
  732. QStringList modsToEnable;
  733. // disable mod(s), to properly recalculate dependencies, if changed
  734. for(QString mod : boost::adaptors::reverse(modNames))
  735. {
  736. CModEntry entry = modModel->getMod(mod);
  737. if(entry.isInstalled())
  738. {
  739. // enable mod if installed and enabled
  740. if(entry.isEnabled())
  741. modsToEnable.push_back(mod);
  742. }
  743. else
  744. {
  745. // enable mod if m
  746. if(settings["launcher"]["enableInstalledMods"].Bool())
  747. modsToEnable.push_back(mod);
  748. }
  749. }
  750. // uninstall old version of mod, if installed
  751. for(QString mod : boost::adaptors::reverse(modNames))
  752. {
  753. if(modModel->getMod(mod).isInstalled())
  754. manager->uninstallMod(mod);
  755. }
  756. for(int i = 0; i < modNames.size(); i++)
  757. {
  758. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  759. manager->installMod(modNames[i], archives[i]);
  760. }
  761. std::function<void(QString)> enableMod;
  762. enableMod = [&](QString modName)
  763. {
  764. auto mod = modModel->getMod(modName);
  765. if(mod.isInstalled() && !mod.getValue("keepDisabled").toBool())
  766. {
  767. for (auto const & dependencyName : mod.getDependencies())
  768. {
  769. auto dependency = modModel->getMod(dependencyName);
  770. if(dependency.isDisabled())
  771. manager->enableMod(dependencyName);
  772. }
  773. if(mod.isDisabled() && manager->enableMod(modName))
  774. {
  775. for(QString child : modModel->getChildren(modName))
  776. enableMod(child);
  777. }
  778. }
  779. };
  780. for(QString mod : modsToEnable)
  781. {
  782. enableMod(mod);
  783. }
  784. checkManagerErrors();
  785. for(QString archive : archives)
  786. QFile::remove(archive);
  787. }
  788. void CModListView::installMaps(QStringList maps)
  789. {
  790. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  791. for(QString map : maps)
  792. {
  793. QFile(map).rename(destDir + map.section('/', -1, -1));
  794. }
  795. }
  796. void CModListView::on_refreshButton_clicked()
  797. {
  798. loadRepositories();
  799. }
  800. void CModListView::on_pushButton_clicked()
  801. {
  802. delete dlManager;
  803. dlManager = nullptr;
  804. hideProgressBar();
  805. }
  806. void CModListView::modelReset()
  807. {
  808. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  809. }
  810. void CModListView::checkManagerErrors()
  811. {
  812. QString errors = manager->getErrors().join('\n');
  813. if(errors.size() != 0)
  814. {
  815. QString title = tr("Operation failed");
  816. QString description = tr("Encountered errors:\n") + errors;
  817. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  818. }
  819. }
  820. void CModListView::on_tabWidget_currentChanged(int index)
  821. {
  822. loadScreenshots();
  823. }
  824. void CModListView::loadScreenshots()
  825. {
  826. if(ui->tabWidget->currentIndex() == 2)
  827. {
  828. if(!ui->allModsView->currentIndex().isValid())
  829. {
  830. // select the first mod, so we can access its data
  831. ui->allModsView->setCurrentIndex(filterModel->index(0, 0));
  832. }
  833. ui->screenshotsList->clear();
  834. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  835. assert(modModel->hasMod(modName)); //should be filtered out by check above
  836. for(QString url : modModel->getMod(modName).getValue("screenshots").toStringList())
  837. {
  838. // URL must be encoded to something else to get rid of symbols illegal in file names
  839. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  840. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  841. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  842. QPixmap pixmap(fullPath);
  843. if(pixmap.isNull())
  844. {
  845. // image file not exists or corrupted - try to redownload
  846. downloadFile(fileName, url, tr("screenshots"));
  847. }
  848. else
  849. {
  850. // managed to load cached image
  851. QIcon icon(pixmap);
  852. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  853. ui->screenshotsList->addItem(item);
  854. }
  855. }
  856. }
  857. }
  858. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  859. {
  860. if(index.isValid())
  861. {
  862. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  863. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  864. ImageViewer::showPixmap(pixmap, this);
  865. }
  866. }
  867. const CModList & CModListView::getModList() const
  868. {
  869. assert(modModel);
  870. return *modModel;
  871. }
  872. void CModListView::doInstallMod(const QString & modName)
  873. {
  874. assert(findInvalidDependencies(modName).empty());
  875. for(auto & name : modModel->getRequirements(modName))
  876. {
  877. auto mod = modModel->getMod(name);
  878. if(!mod.isInstalled())
  879. downloadFile(name + ".zip", mod.getValue("download").toString(), name, mbToBytes(mod.getValue("downloadSize").toDouble()));
  880. }
  881. }
  882. bool CModListView::isModAvailable(const QString & modName)
  883. {
  884. auto mod = modModel->getMod(modName);
  885. return mod.isAvailable();
  886. }
  887. bool CModListView::isModEnabled(const QString & modName)
  888. {
  889. auto mod = modModel->getMod(modName);
  890. return mod.isEnabled();
  891. }
  892. QString CModListView::getTranslationModName(const QString & language)
  893. {
  894. for(const auto & modName : modModel->getModList())
  895. {
  896. auto mod = modModel->getMod(modName);
  897. if (!mod.isTranslation())
  898. continue;
  899. if (mod.getBaseValue("language").toString() != language)
  900. continue;
  901. return modName;
  902. }
  903. return QString();
  904. }
  905. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  906. {
  907. if(!index.isValid())
  908. return;
  909. auto modName = index.data(ModRoles::ModNameRole).toString();
  910. auto mod = modModel->getMod(modName);
  911. bool hasInvalidDeps = !findInvalidDependencies(modName).empty();
  912. bool hasBlockingMods = !findBlockingMods(modName).empty();
  913. bool hasDependentMods = !findDependentMods(modName, true).empty();
  914. if(!hasInvalidDeps && mod.isAvailable() && !mod.isSubmod())
  915. {
  916. on_installButton_clicked();
  917. return;
  918. }
  919. if(!hasInvalidDeps && !hasDependentMods && mod.isUpdateable() && index.column() == ModFields::STATUS_UPDATE)
  920. {
  921. on_updateButton_clicked();
  922. return;
  923. }
  924. if(index.column() == ModFields::NAME)
  925. {
  926. if(ui->allModsView->isExpanded(index))
  927. ui->allModsView->collapse(index);
  928. else
  929. ui->allModsView->expand(index);
  930. return;
  931. }
  932. if(!hasBlockingMods && !hasInvalidDeps && mod.isDisabled())
  933. {
  934. on_enableButton_clicked();
  935. return;
  936. }
  937. if(!hasDependentMods && !mod.isEssential() && mod.isEnabled())
  938. {
  939. on_disableButton_clicked();
  940. return;
  941. }
  942. }