cmodlistview_moc.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. /*
  2. * cmodlistview_moc.cpp, part of VCMI engine
  3. *
  4. * Authors: listed in file AUTHORS in main folder
  5. *
  6. * License: GNU General Public License v2.0 or later
  7. * Full text of license available in license.txt file, in main folder
  8. *
  9. */
  10. #include "StdInc.h"
  11. #include "cmodlistview_moc.h"
  12. #include "ui_cmodlistview_moc.h"
  13. #include "imageviewer_moc.h"
  14. #include "../mainwindow_moc.h"
  15. #include <QJsonArray>
  16. #include <QCryptographicHash>
  17. #include <QRegularExpression>
  18. #include "cmodlistmodel_moc.h"
  19. #include "cmodmanager.h"
  20. #include "cdownloadmanager_moc.h"
  21. #include "../settingsView/csettingsview_moc.h"
  22. #include "../launcherdirs.h"
  23. #include "../jsonutils.h"
  24. #include "../helper.h"
  25. #include "../../lib/VCMIDirs.h"
  26. #include "../../lib/CConfigHandler.h"
  27. #include "../../lib/Languages.h"
  28. #include "../../lib/modding/CModVersion.h"
  29. static double mbToBytes(double mb)
  30. {
  31. return mb * 1024 * 1024;
  32. }
  33. void CModListView::setupModModel()
  34. {
  35. modModel = new CModListModel(this);
  36. manager = std::make_unique<CModManager>(modModel);
  37. }
  38. void CModListView::changeEvent(QEvent *event)
  39. {
  40. if(event->type() == QEvent::LanguageChange)
  41. {
  42. ui->retranslateUi(this);
  43. modModel->reloadRepositories();
  44. }
  45. QWidget::changeEvent(event);
  46. }
  47. void CModListView::dragEnterEvent(QDragEnterEvent* event)
  48. {
  49. if(event->mimeData()->hasUrls())
  50. for(const auto & url : event->mimeData()->urls())
  51. for(const auto & ending : QStringList({".zip", ".h3m", ".h3c", ".vmap", ".vcmp", ".json"}))
  52. if(url.fileName().endsWith(ending, Qt::CaseInsensitive))
  53. {
  54. event->acceptProposedAction();
  55. return;
  56. }
  57. }
  58. void CModListView::dropEvent(QDropEvent* event)
  59. {
  60. const QMimeData* mimeData = event->mimeData();
  61. if(mimeData->hasUrls())
  62. {
  63. const QList<QUrl> urlList = mimeData->urls();
  64. for (const auto & url : urlList)
  65. manualInstallFile(url.toLocalFile());
  66. }
  67. }
  68. void CModListView::setupFilterModel()
  69. {
  70. filterModel = new CModFilterModel(modModel, this);
  71. filterModel->setFilterKeyColumn(-1); // filter across all columns
  72. filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); // to make it more user-friendly
  73. filterModel->setDynamicSortFilter(true);
  74. }
  75. void CModListView::setupModsView()
  76. {
  77. ui->allModsView->setModel(filterModel);
  78. // input data is not sorted - sort it before display
  79. ui->allModsView->sortByColumn(ModFields::TYPE, Qt::AscendingOrder);
  80. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_ENABLED, QHeaderView::Fixed);
  81. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_UPDATE, QHeaderView::Fixed);
  82. QSettings s(Ui::teamName, Ui::appName);
  83. auto state = s.value("AllModsView/State").toByteArray();
  84. if(!state.isNull()) //read last saved settings
  85. {
  86. ui->allModsView->header()->restoreState(state);
  87. }
  88. else //default //TODO: default high-DPI scaling
  89. {
  90. ui->allModsView->setColumnWidth(ModFields::NAME, 220);
  91. ui->allModsView->setColumnWidth(ModFields::TYPE, 75);
  92. }
  93. ui->allModsView->resizeColumnToContents(ModFields::STATUS_ENABLED);
  94. ui->allModsView->resizeColumnToContents(ModFields::STATUS_UPDATE);
  95. ui->allModsView->setUniformRowHeights(true);
  96. connect(ui->allModsView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&,const QModelIndex&)),
  97. this, SLOT(modSelected(const QModelIndex&,const QModelIndex&)));
  98. connect(filterModel, SIGNAL(modelReset()),
  99. this, SLOT(modelReset()));
  100. connect(modModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
  101. this, SLOT(dataChanged(QModelIndex,QModelIndex)));
  102. }
  103. CModListView::CModListView(QWidget * parent)
  104. : QWidget(parent)
  105. , ui(new Ui::CModListView)
  106. {
  107. ui->setupUi(this);
  108. setAcceptDrops(true);
  109. ui->uninstallButton->setIcon(QIcon{":/icons/mod-delete.png"});
  110. ui->enableButton->setIcon(QIcon{":/icons/mod-enabled.png"});
  111. ui->disableButton->setIcon(QIcon{":/icons/mod-disabled.png"});
  112. ui->updateButton->setIcon(QIcon{":/icons/mod-update.png"});
  113. ui->installButton->setIcon(QIcon{":/icons/mod-download.png"});
  114. 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. // iOS can't display modal dialogs when called directly on button press
  517. // https://bugreports.qt.io/browse/QTBUG-98651
  518. QTimer::singleShot(0, this, [this]
  519. {
  520. 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)";
  521. QStringList files = QFileDialog::getOpenFileNames(this, tr("Select files (configs, mods, maps, campaigns) to install..."), QDir::homePath(), filter);
  522. for(const auto & file : files)
  523. {
  524. manualInstallFile(file);
  525. }
  526. });
  527. }
  528. void CModListView::manualInstallFile(QString filePath)
  529. {
  530. QString fileName = QFileInfo{filePath}.fileName();
  531. if(filePath.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. , QUrl::fromLocalFile(filePath), "mods");
  538. else if(filePath.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(filePath, 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, QUrl::fromLocalFile(filePath), fileName);
  562. }
  563. void CModListView::downloadFile(QString file, QString url, QString description, qint64 size)
  564. {
  565. downloadFile(file, QUrl{url}, description, size);
  566. }
  567. void CModListView::downloadFile(QString file, QUrl url, QString description, qint64 size)
  568. {
  569. if(!dlManager)
  570. {
  571. dlManager = new CDownloadManager();
  572. ui->progressWidget->setVisible(true);
  573. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  574. this, SLOT(downloadProgress(qint64,qint64)));
  575. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  576. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  577. connect(manager.get(), SIGNAL(extractionProgress(qint64,qint64)),
  578. this, SLOT(extractionProgress(qint64,qint64)));
  579. connect(modModel, &CModListModel::dataChanged, filterModel, &QAbstractItemModel::dataChanged);
  580. const auto progressBarFormat = tr("Downloading %1. %p% (%v MB out of %m MB) finished").arg(description);
  581. ui->progressBar->setFormat(progressBarFormat);
  582. }
  583. dlManager->downloadFile(url, file, size);
  584. }
  585. void CModListView::downloadProgress(qint64 current, qint64 max)
  586. {
  587. // display progress, in megabytes
  588. ui->progressBar->setVisible(true);
  589. ui->progressBar->setMaximum(max / (1024 * 1024));
  590. ui->progressBar->setValue(current / (1024 * 1024));
  591. }
  592. void CModListView::extractionProgress(qint64 current, qint64 max)
  593. {
  594. // display progress, in extracted files
  595. ui->progressBar->setVisible(true);
  596. ui->progressBar->setMaximum(max);
  597. ui->progressBar->setValue(current);
  598. }
  599. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  600. {
  601. QString title = tr("Download failed");
  602. QString firstLine = tr("Unable to download all files.\n\nEncountered errors:\n\n");
  603. QString lastLine = tr("\n\nInstall successfully downloaded?");
  604. bool doInstallFiles = false;
  605. // if all files were d/loaded there should be no errors. And on failure there must be an error
  606. assert(failedFiles.empty() == errors.empty());
  607. if(savedFiles.empty())
  608. {
  609. // no successfully downloaded mods
  610. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  611. }
  612. else if(!failedFiles.empty())
  613. {
  614. // some mods were not downloaded
  615. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  616. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  617. if(result == QMessageBox::Yes)
  618. doInstallFiles = true;
  619. }
  620. else
  621. {
  622. // everything OK
  623. doInstallFiles = true;
  624. }
  625. dlManager->deleteLater();
  626. dlManager = nullptr;
  627. ui->progressBar->setMaximum(0);
  628. ui->progressBar->setValue(0);
  629. if(doInstallFiles)
  630. installFiles(savedFiles);
  631. hideProgressBar();
  632. emit modsChanged();
  633. }
  634. void CModListView::hideProgressBar()
  635. {
  636. if(dlManager == nullptr) // it was not recreated meanwhile
  637. {
  638. ui->progressWidget->setVisible(false);
  639. ui->progressBar->setMaximum(0);
  640. ui->progressBar->setValue(0);
  641. }
  642. }
  643. void CModListView::installFiles(QStringList files)
  644. {
  645. QStringList mods;
  646. QStringList maps;
  647. QStringList images;
  648. QVector<QVariantMap> repositories;
  649. // TODO: some better way to separate zip's with mods and downloaded repository files
  650. for(QString filename : files)
  651. {
  652. if(filename.endsWith(".zip", Qt::CaseInsensitive))
  653. mods.push_back(filename);
  654. else if(filename.endsWith(".h3m", Qt::CaseInsensitive) || filename.endsWith(".h3c", Qt::CaseInsensitive) || filename.endsWith(".vmap", Qt::CaseInsensitive) || filename.endsWith(".vcmp", Qt::CaseInsensitive))
  655. maps.push_back(filename);
  656. else if(filename.endsWith(".json", Qt::CaseInsensitive))
  657. {
  658. //download and merge additional files
  659. auto repoData = JsonUtils::JsonFromFile(filename).toMap();
  660. if(repoData.value("name").isNull())
  661. {
  662. for(const auto & key : repoData.keys())
  663. {
  664. auto modjson = repoData[key].toMap().value("mod");
  665. if(!modjson.isNull())
  666. {
  667. downloadFile(key + ".json", modjson.toString(), tr("mods repository index"));
  668. }
  669. }
  670. }
  671. else
  672. {
  673. auto modn = QFileInfo(filename).baseName();
  674. QVariantMap temp;
  675. temp[modn] = repoData;
  676. repoData = temp;
  677. }
  678. repositories.push_back(repoData);
  679. }
  680. else if(filename.endsWith(".png", Qt::CaseInsensitive))
  681. images.push_back(filename);
  682. }
  683. if (!repositories.empty())
  684. manager->loadRepositories(repositories);
  685. if(!mods.empty())
  686. installMods(mods);
  687. if(!maps.empty())
  688. installMaps(maps);
  689. if(!images.empty())
  690. loadScreenshots();
  691. }
  692. void CModListView::installMods(QStringList archives)
  693. {
  694. QStringList modNames;
  695. for(QString archive : archives)
  696. {
  697. // get basename out of full file name
  698. // remove path remove extension
  699. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  700. modNames.push_back(modName);
  701. }
  702. QStringList modsToEnable;
  703. // disable mod(s), to properly recalculate dependencies, if changed
  704. for(QString mod : boost::adaptors::reverse(modNames))
  705. {
  706. CModEntry entry = modModel->getMod(mod);
  707. if(entry.isInstalled())
  708. {
  709. // enable mod if installed and enabled
  710. if(entry.isEnabled())
  711. modsToEnable.push_back(mod);
  712. }
  713. else
  714. {
  715. // enable mod if m
  716. if(settings["launcher"]["enableInstalledMods"].Bool())
  717. modsToEnable.push_back(mod);
  718. }
  719. }
  720. // uninstall old version of mod, if installed
  721. for(QString mod : boost::adaptors::reverse(modNames))
  722. {
  723. if(modModel->getMod(mod).isInstalled())
  724. manager->uninstallMod(mod);
  725. }
  726. for(int i = 0; i < modNames.size(); i++)
  727. {
  728. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  729. manager->installMod(modNames[i], archives[i]);
  730. }
  731. std::function<void(QString)> enableMod;
  732. enableMod = [&](QString modName)
  733. {
  734. auto mod = modModel->getMod(modName);
  735. if(mod.isInstalled() && !mod.getValue("keepDisabled").toBool())
  736. {
  737. for (auto const & dependencyName : mod.getDependencies())
  738. {
  739. auto dependency = modModel->getMod(dependencyName);
  740. if(dependency.isDisabled())
  741. manager->enableMod(dependencyName);
  742. }
  743. if(mod.isDisabled() && manager->enableMod(modName))
  744. {
  745. for(QString child : modModel->getChildren(modName))
  746. enableMod(child);
  747. }
  748. }
  749. };
  750. for(QString mod : modsToEnable)
  751. {
  752. enableMod(mod);
  753. }
  754. checkManagerErrors();
  755. for(QString archive : archives)
  756. QFile::remove(archive);
  757. }
  758. void CModListView::installMaps(QStringList maps)
  759. {
  760. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  761. for(QString map : maps)
  762. {
  763. QFile(map).rename(destDir + map.section('/', -1, -1));
  764. }
  765. }
  766. void CModListView::on_refreshButton_clicked()
  767. {
  768. loadRepositories();
  769. }
  770. void CModListView::on_pushButton_clicked()
  771. {
  772. delete dlManager;
  773. dlManager = nullptr;
  774. hideProgressBar();
  775. }
  776. void CModListView::modelReset()
  777. {
  778. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  779. }
  780. void CModListView::checkManagerErrors()
  781. {
  782. QString errors = manager->getErrors().join('\n');
  783. if(errors.size() != 0)
  784. {
  785. QString title = tr("Operation failed");
  786. QString description = tr("Encountered errors:\n") + errors;
  787. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  788. }
  789. }
  790. void CModListView::on_tabWidget_currentChanged(int index)
  791. {
  792. loadScreenshots();
  793. }
  794. void CModListView::loadScreenshots()
  795. {
  796. if(ui->tabWidget->currentIndex() == 2)
  797. {
  798. ui->screenshotsList->clear();
  799. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  800. assert(modModel->hasMod(modName)); //should be filtered out by check above
  801. for(QString url : modModel->getMod(modName).getValue("screenshots").toStringList())
  802. {
  803. // URL must be encoded to something else to get rid of symbols illegal in file names
  804. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  805. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  806. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  807. QPixmap pixmap(fullPath);
  808. if(pixmap.isNull())
  809. {
  810. // image file not exists or corrupted - try to redownload
  811. downloadFile(fileName, url, tr("screenshots"));
  812. }
  813. else
  814. {
  815. // managed to load cached image
  816. QIcon icon(pixmap);
  817. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  818. ui->screenshotsList->addItem(item);
  819. }
  820. }
  821. }
  822. }
  823. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  824. {
  825. if(index.isValid())
  826. {
  827. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  828. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  829. ImageViewer::showPixmap(pixmap, this);
  830. }
  831. }
  832. const CModList & CModListView::getModList() const
  833. {
  834. assert(modModel);
  835. return *modModel;
  836. }
  837. void CModListView::doInstallMod(const QString & modName)
  838. {
  839. assert(findInvalidDependencies(modName).empty());
  840. for(auto & name : modModel->getRequirements(modName))
  841. {
  842. auto mod = modModel->getMod(name);
  843. if(!mod.isInstalled())
  844. downloadFile(name + ".zip", mod.getValue("download").toString(), name, mbToBytes(mod.getValue("downloadSize").toDouble()));
  845. }
  846. }
  847. bool CModListView::isModAvailable(const QString & modName)
  848. {
  849. auto mod = modModel->getMod(modName);
  850. return mod.isAvailable();
  851. }
  852. bool CModListView::isModEnabled(const QString & modName)
  853. {
  854. auto mod = modModel->getMod(modName);
  855. return mod.isEnabled();
  856. }
  857. QString CModListView::getTranslationModName(const QString & language)
  858. {
  859. for(const auto & modName : modModel->getModList())
  860. {
  861. auto mod = modModel->getMod(modName);
  862. if (!mod.isTranslation())
  863. continue;
  864. if (mod.getBaseValue("language").toString() != language)
  865. continue;
  866. return modName;
  867. }
  868. return QString();
  869. }
  870. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  871. {
  872. if(!index.isValid())
  873. return;
  874. auto modName = index.data(ModRoles::ModNameRole).toString();
  875. auto mod = modModel->getMod(modName);
  876. bool hasInvalidDeps = !findInvalidDependencies(modName).empty();
  877. bool hasBlockingMods = !findBlockingMods(modName).empty();
  878. bool hasDependentMods = !findDependentMods(modName, true).empty();
  879. if(!hasInvalidDeps && mod.isAvailable() && !mod.isSubmod())
  880. {
  881. on_installButton_clicked();
  882. return;
  883. }
  884. if(!hasInvalidDeps && !hasDependentMods && mod.isUpdateable() && index.column() == ModFields::STATUS_UPDATE)
  885. {
  886. on_updateButton_clicked();
  887. return;
  888. }
  889. if(index.column() == ModFields::NAME)
  890. {
  891. if(ui->allModsView->isExpanded(index))
  892. ui->allModsView->collapse(index);
  893. else
  894. ui->allModsView->expand(index);
  895. return;
  896. }
  897. if(!hasBlockingMods && !hasInvalidDeps && mod.isDisabled())
  898. {
  899. on_enableButton_clicked();
  900. return;
  901. }
  902. if(!hasDependentMods && !mod.isEssential() && mod.isEnabled())
  903. {
  904. on_disableButton_clicked();
  905. return;
  906. }
  907. }