cmodlistview_moc.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089
  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. QString filter = tr("All supported files") + " (*.h3m *.vmap *.h3c *.vcmp *.zip *.json);;" + tr("Maps") + " (*.h3m *.vmap);;" + tr("Campaigns") + " (*.h3c *.vcmp);;" + tr("Configs") + " (*.json);;" + tr("Mods") + " (*.zip)";
  517. QStringList files = QFileDialog::getOpenFileNames(this, tr("Select files (configs, mods, maps, campaigns) to install..."), QDir::homePath(), filter);
  518. for (const auto & file : files)
  519. {
  520. manualInstallFile(file);
  521. }
  522. }
  523. void CModListView::manualInstallFile(QString filePath)
  524. {
  525. QString fileName = QFileInfo{filePath}.fileName();
  526. if(filePath.endsWith(".zip", Qt::CaseInsensitive))
  527. downloadFile(fileName.toLower()
  528. // mod name currently comes from zip file -> remove suffixes from github zip download
  529. .replace(QRegularExpression("-[0-9a-f]{40}"), "")
  530. .replace(QRegularExpression("-vcmi-.+\\.zip"), ".zip")
  531. .replace("-main.zip", ".zip")
  532. , QUrl::fromLocalFile(filePath), "mods");
  533. else if(filePath.endsWith(".json", Qt::CaseInsensitive))
  534. {
  535. QDir configDir(QString::fromStdString(VCMIDirs::get().userConfigPath().string()));
  536. QStringList configFile = configDir.entryList({fileName}, QDir::Filter::Files); // case insensitive check
  537. if(!configFile.empty())
  538. {
  539. 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);
  540. if(dialogResult == QMessageBox::Yes)
  541. {
  542. const auto configFilePath = configDir.filePath(configFile[0]);
  543. QFile::remove(configFilePath);
  544. QFile::copy(filePath, configFilePath);
  545. // reload settings
  546. Helper::loadSettings();
  547. for(auto widget : qApp->allWidgets())
  548. if(auto settingsView = qobject_cast<CSettingsView *>(widget))
  549. settingsView->loadSettings();
  550. manager->loadMods();
  551. manager->loadModSettings();
  552. }
  553. }
  554. }
  555. else
  556. downloadFile(fileName, QUrl::fromLocalFile(filePath), fileName);
  557. }
  558. void CModListView::downloadFile(QString file, QString url, QString description, qint64 size)
  559. {
  560. downloadFile(file, QUrl{url}, description, size);
  561. }
  562. void CModListView::downloadFile(QString file, QUrl url, QString description, qint64 size)
  563. {
  564. if(!dlManager)
  565. {
  566. dlManager = new CDownloadManager();
  567. ui->progressWidget->setVisible(true);
  568. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  569. this, SLOT(downloadProgress(qint64,qint64)));
  570. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  571. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  572. connect(manager.get(), SIGNAL(extractionProgress(qint64,qint64)),
  573. this, SLOT(extractionProgress(qint64,qint64)));
  574. connect(modModel, &CModListModel::dataChanged, filterModel, &QAbstractItemModel::dataChanged);
  575. const auto progressBarFormat = tr("Downloading %1. %p% (%v MB out of %m MB) finished").arg(description);
  576. ui->progressBar->setFormat(progressBarFormat);
  577. }
  578. dlManager->downloadFile(url, file, size);
  579. }
  580. void CModListView::downloadProgress(qint64 current, qint64 max)
  581. {
  582. // display progress, in megabytes
  583. ui->progressBar->setVisible(true);
  584. ui->progressBar->setMaximum(max / (1024 * 1024));
  585. ui->progressBar->setValue(current / (1024 * 1024));
  586. }
  587. void CModListView::extractionProgress(qint64 current, qint64 max)
  588. {
  589. // display progress, in extracted files
  590. ui->progressBar->setVisible(true);
  591. ui->progressBar->setMaximum(max);
  592. ui->progressBar->setValue(current);
  593. }
  594. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  595. {
  596. QString title = tr("Download failed");
  597. QString firstLine = tr("Unable to download all files.\n\nEncountered errors:\n\n");
  598. QString lastLine = tr("\n\nInstall successfully downloaded?");
  599. bool doInstallFiles = false;
  600. // if all files were d/loaded there should be no errors. And on failure there must be an error
  601. assert(failedFiles.empty() == errors.empty());
  602. if(savedFiles.empty())
  603. {
  604. // no successfully downloaded mods
  605. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  606. }
  607. else if(!failedFiles.empty())
  608. {
  609. // some mods were not downloaded
  610. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  611. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  612. if(result == QMessageBox::Yes)
  613. doInstallFiles = true;
  614. }
  615. else
  616. {
  617. // everything OK
  618. doInstallFiles = true;
  619. }
  620. dlManager->deleteLater();
  621. dlManager = nullptr;
  622. ui->progressBar->setMaximum(0);
  623. ui->progressBar->setValue(0);
  624. if(doInstallFiles)
  625. installFiles(savedFiles);
  626. hideProgressBar();
  627. emit modsChanged();
  628. }
  629. void CModListView::hideProgressBar()
  630. {
  631. if(dlManager == nullptr) // it was not recreated meanwhile
  632. {
  633. ui->progressWidget->setVisible(false);
  634. ui->progressBar->setMaximum(0);
  635. ui->progressBar->setValue(0);
  636. }
  637. }
  638. void CModListView::installFiles(QStringList files)
  639. {
  640. QStringList mods;
  641. QStringList maps;
  642. QStringList images;
  643. QVector<QVariantMap> repositories;
  644. // TODO: some better way to separate zip's with mods and downloaded repository files
  645. for(QString filename : files)
  646. {
  647. if(filename.endsWith(".zip", Qt::CaseInsensitive))
  648. mods.push_back(filename);
  649. else if(filename.endsWith(".h3m", Qt::CaseInsensitive) || filename.endsWith(".h3c", Qt::CaseInsensitive) || filename.endsWith(".vmap", Qt::CaseInsensitive) || filename.endsWith(".vcmp", Qt::CaseInsensitive))
  650. maps.push_back(filename);
  651. else if(filename.endsWith(".json", Qt::CaseInsensitive))
  652. {
  653. //download and merge additional files
  654. auto repoData = JsonUtils::JsonFromFile(filename).toMap();
  655. if(repoData.value("name").isNull())
  656. {
  657. for(const auto & key : repoData.keys())
  658. {
  659. auto modjson = repoData[key].toMap().value("mod");
  660. if(!modjson.isNull())
  661. {
  662. downloadFile(key + ".json", modjson.toString(), tr("mods repository index"));
  663. }
  664. }
  665. }
  666. else
  667. {
  668. auto modn = QFileInfo(filename).baseName();
  669. QVariantMap temp;
  670. temp[modn] = repoData;
  671. repoData = temp;
  672. }
  673. repositories.push_back(repoData);
  674. }
  675. else if(filename.endsWith(".png", Qt::CaseInsensitive))
  676. images.push_back(filename);
  677. }
  678. if (!repositories.empty())
  679. manager->loadRepositories(repositories);
  680. if(!mods.empty())
  681. installMods(mods);
  682. if(!maps.empty())
  683. installMaps(maps);
  684. if(!images.empty())
  685. loadScreenshots();
  686. }
  687. void CModListView::installMods(QStringList archives)
  688. {
  689. QStringList modNames;
  690. for(QString archive : archives)
  691. {
  692. // get basename out of full file name
  693. // remove path remove extension
  694. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  695. modNames.push_back(modName);
  696. }
  697. QStringList modsToEnable;
  698. // disable mod(s), to properly recalculate dependencies, if changed
  699. for(QString mod : boost::adaptors::reverse(modNames))
  700. {
  701. CModEntry entry = modModel->getMod(mod);
  702. if(entry.isInstalled())
  703. {
  704. // enable mod if installed and enabled
  705. if(entry.isEnabled())
  706. modsToEnable.push_back(mod);
  707. }
  708. else
  709. {
  710. // enable mod if m
  711. if(settings["launcher"]["enableInstalledMods"].Bool())
  712. modsToEnable.push_back(mod);
  713. }
  714. }
  715. // uninstall old version of mod, if installed
  716. for(QString mod : boost::adaptors::reverse(modNames))
  717. {
  718. if(modModel->getMod(mod).isInstalled())
  719. manager->uninstallMod(mod);
  720. }
  721. for(int i = 0; i < modNames.size(); i++)
  722. {
  723. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  724. manager->installMod(modNames[i], archives[i]);
  725. }
  726. std::function<void(QString)> enableMod;
  727. enableMod = [&](QString modName)
  728. {
  729. auto mod = modModel->getMod(modName);
  730. if(mod.isInstalled() && !mod.getValue("keepDisabled").toBool())
  731. {
  732. for (auto const & dependencyName : mod.getDependencies())
  733. {
  734. auto dependency = modModel->getMod(dependencyName);
  735. if(dependency.isDisabled())
  736. manager->enableMod(dependencyName);
  737. }
  738. if(mod.isDisabled() && manager->enableMod(modName))
  739. {
  740. for(QString child : modModel->getChildren(modName))
  741. enableMod(child);
  742. }
  743. }
  744. };
  745. for(QString mod : modsToEnable)
  746. {
  747. enableMod(mod);
  748. }
  749. checkManagerErrors();
  750. for(QString archive : archives)
  751. QFile::remove(archive);
  752. }
  753. void CModListView::installMaps(QStringList maps)
  754. {
  755. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  756. for(QString map : maps)
  757. {
  758. QFile(map).rename(destDir + map.section('/', -1, -1));
  759. }
  760. }
  761. void CModListView::on_refreshButton_clicked()
  762. {
  763. loadRepositories();
  764. }
  765. void CModListView::on_pushButton_clicked()
  766. {
  767. delete dlManager;
  768. dlManager = nullptr;
  769. hideProgressBar();
  770. }
  771. void CModListView::modelReset()
  772. {
  773. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  774. }
  775. void CModListView::checkManagerErrors()
  776. {
  777. QString errors = manager->getErrors().join('\n');
  778. if(errors.size() != 0)
  779. {
  780. QString title = tr("Operation failed");
  781. QString description = tr("Encountered errors:\n") + errors;
  782. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  783. }
  784. }
  785. void CModListView::on_tabWidget_currentChanged(int index)
  786. {
  787. loadScreenshots();
  788. }
  789. void CModListView::loadScreenshots()
  790. {
  791. if(ui->tabWidget->currentIndex() == 2)
  792. {
  793. ui->screenshotsList->clear();
  794. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  795. assert(modModel->hasMod(modName)); //should be filtered out by check above
  796. for(QString url : modModel->getMod(modName).getValue("screenshots").toStringList())
  797. {
  798. // URL must be encoded to something else to get rid of symbols illegal in file names
  799. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  800. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  801. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  802. QPixmap pixmap(fullPath);
  803. if(pixmap.isNull())
  804. {
  805. // image file not exists or corrupted - try to redownload
  806. downloadFile(fileName, url, tr("screenshots"));
  807. }
  808. else
  809. {
  810. // managed to load cached image
  811. QIcon icon(pixmap);
  812. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  813. ui->screenshotsList->addItem(item);
  814. }
  815. }
  816. }
  817. }
  818. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  819. {
  820. if(index.isValid())
  821. {
  822. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  823. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  824. ImageViewer::showPixmap(pixmap, this);
  825. }
  826. }
  827. const CModList & CModListView::getModList() const
  828. {
  829. assert(modModel);
  830. return *modModel;
  831. }
  832. void CModListView::doInstallMod(const QString & modName)
  833. {
  834. assert(findInvalidDependencies(modName).empty());
  835. for(auto & name : modModel->getRequirements(modName))
  836. {
  837. auto mod = modModel->getMod(name);
  838. if(!mod.isInstalled())
  839. downloadFile(name + ".zip", mod.getValue("download").toString(), name, mbToBytes(mod.getValue("downloadSize").toDouble()));
  840. }
  841. }
  842. bool CModListView::isModAvailable(const QString & modName)
  843. {
  844. auto mod = modModel->getMod(modName);
  845. return mod.isAvailable();
  846. }
  847. bool CModListView::isModEnabled(const QString & modName)
  848. {
  849. auto mod = modModel->getMod(modName);
  850. return mod.isEnabled();
  851. }
  852. QString CModListView::getTranslationModName(const QString & language)
  853. {
  854. for(const auto & modName : modModel->getModList())
  855. {
  856. auto mod = modModel->getMod(modName);
  857. if (!mod.isTranslation())
  858. continue;
  859. if (mod.getBaseValue("language").toString() != language)
  860. continue;
  861. return modName;
  862. }
  863. return QString();
  864. }
  865. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  866. {
  867. if(!index.isValid())
  868. return;
  869. auto modName = index.data(ModRoles::ModNameRole).toString();
  870. auto mod = modModel->getMod(modName);
  871. bool hasInvalidDeps = !findInvalidDependencies(modName).empty();
  872. bool hasBlockingMods = !findBlockingMods(modName).empty();
  873. bool hasDependentMods = !findDependentMods(modName, true).empty();
  874. if(!hasInvalidDeps && mod.isAvailable() && !mod.isSubmod())
  875. {
  876. on_installButton_clicked();
  877. return;
  878. }
  879. if(!hasInvalidDeps && !hasDependentMods && mod.isUpdateable() && index.column() == ModFields::STATUS_UPDATE)
  880. {
  881. on_updateButton_clicked();
  882. return;
  883. }
  884. if(index.column() == ModFields::NAME)
  885. {
  886. if(ui->allModsView->isExpanded(index))
  887. ui->allModsView->collapse(index);
  888. else
  889. ui->allModsView->expand(index);
  890. return;
  891. }
  892. if(!hasBlockingMods && !hasInvalidDeps && mod.isDisabled())
  893. {
  894. on_enableButton_clicked();
  895. return;
  896. }
  897. if(!hasDependentMods && !mod.isEssential() && mod.isEnabled())
  898. {
  899. on_disableButton_clicked();
  900. return;
  901. }
  902. }