cmodlistview_moc.cpp 34 KB

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