cmodlistview_moc.cpp 33 KB

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