cmodlistview_moc.cpp 34 KB

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