cmodlistview_moc.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  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/CConfigHandler.h"
  28. #include "../../lib/VCMIDirs.h"
  29. #include "../../lib/filesystem/Filesystem.h"
  30. #include "../../lib/json/JsonUtils.h"
  31. #include "../../lib/modding/CModVersion.h"
  32. #include "../../lib/texts/CGeneralTextHandler.h"
  33. #include "../../lib/texts/Languages.h"
  34. #include <future>
  35. void CModListView::setupModModel()
  36. {
  37. static const QString repositoryCachePath = CLauncherDirs::downloadsPath() + "/repositoryCache.json";
  38. const auto &cachedRepositoryData = JsonUtils::jsonFromFile(repositoryCachePath);
  39. modStateModel = std::make_shared<ModStateModel>();
  40. if (!cachedRepositoryData.isNull())
  41. modStateModel->setRepositoryData(cachedRepositoryData);
  42. modModel = new ModStateItemModel(modStateModel, this);
  43. manager = std::make_unique<ModStateController>(modStateModel);
  44. }
  45. void CModListView::changeEvent(QEvent *event)
  46. {
  47. if(event->type() == QEvent::LanguageChange)
  48. {
  49. ui->retranslateUi(this);
  50. modModel->reloadViewModel();
  51. }
  52. QWidget::changeEvent(event);
  53. }
  54. void CModListView::setupFilterModel()
  55. {
  56. filterModel = new CModFilterModel(modModel, this);
  57. filterModel->setFilterKeyColumn(-1); // filter across all columns
  58. filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); // to make it more user-friendly
  59. filterModel->setDynamicSortFilter(true);
  60. }
  61. void CModListView::setupModsView()
  62. {
  63. ui->allModsView->setModel(filterModel);
  64. // input data is not sorted - sort it before display
  65. ui->allModsView->sortByColumn(ModFields::TYPE, Qt::AscendingOrder);
  66. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_ENABLED, QHeaderView::Fixed);
  67. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_UPDATE, QHeaderView::Fixed);
  68. QSettings s(Ui::teamName, Ui::appName);
  69. auto state = s.value("AllModsView/State").toByteArray();
  70. if(!state.isNull()) //read last saved settings
  71. {
  72. ui->allModsView->header()->restoreState(state);
  73. }
  74. else //default //TODO: default high-DPI scaling
  75. {
  76. ui->allModsView->setColumnWidth(ModFields::NAME, 220);
  77. ui->allModsView->setColumnWidth(ModFields::TYPE, 75);
  78. }
  79. ui->allModsView->resizeColumnToContents(ModFields::STATUS_ENABLED);
  80. ui->allModsView->resizeColumnToContents(ModFields::STATUS_UPDATE);
  81. ui->allModsView->setUniformRowHeights(true);
  82. ui->allModsView->setContextMenuPolicy(Qt::CustomContextMenu);
  83. connect(ui->allModsView, SIGNAL(customContextMenuRequested(const QPoint &)),
  84. this, SLOT(onCustomContextMenu(const QPoint &)));
  85. connect(ui->allModsView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&,const QModelIndex&)),
  86. this, SLOT(modSelected(const QModelIndex&,const QModelIndex&)));
  87. connect(filterModel, SIGNAL(modelReset()),
  88. this, SLOT(modelReset()));
  89. connect(modModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
  90. this, SLOT(dataChanged(QModelIndex,QModelIndex)));
  91. }
  92. CModListView::CModListView(QWidget * parent)
  93. : QWidget(parent)
  94. , ui(new Ui::CModListView)
  95. {
  96. ui->setupUi(this);
  97. ui->uninstallButton->setIcon(QIcon{":/icons/mod-delete.png"});
  98. ui->enableButton->setIcon(QIcon{":/icons/mod-enabled.png"});
  99. ui->disableButton->setIcon(QIcon{":/icons/mod-disabled.png"});
  100. ui->updateButton->setIcon(QIcon{":/icons/mod-update.png"});
  101. ui->installButton->setIcon(QIcon{":/icons/mod-download.png"});
  102. ui->splitter->setStyleSheet("QSplitter::handle {background: palette('window');}");
  103. disableModInfo();
  104. setupModModel();
  105. setupFilterModel();
  106. setupModsView();
  107. ui->progressWidget->setVisible(false);
  108. dlManager = nullptr;
  109. modModel->reloadViewModel();
  110. if(settings["launcher"]["autoCheckRepositories"].Bool())
  111. loadRepositories();
  112. #ifdef VCMI_MOBILE
  113. for(auto * scrollWidget : {
  114. (QAbstractItemView*)ui->allModsView,
  115. (QAbstractItemView*)ui->screenshotsList})
  116. {
  117. Helper::enableScrollBySwiping(scrollWidget);
  118. scrollWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
  119. scrollWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  120. }
  121. #endif
  122. }
  123. void CModListView::reload()
  124. {
  125. modStateModel->reloadLocalState();
  126. modModel->reloadViewModel();
  127. }
  128. void CModListView::loadRepositories()
  129. {
  130. accumulatedRepositoryData.clear();
  131. QStringList repositories;
  132. if (settings["launcher"]["defaultRepositoryEnabled"].Bool())
  133. repositories.push_back(QString::fromStdString(settings["launcher"]["defaultRepositoryURL"].String()));
  134. if (settings["launcher"]["extraRepositoryEnabled"].Bool())
  135. repositories.push_back(QString::fromStdString(settings["launcher"]["extraRepositoryURL"].String()));
  136. for(const auto & entry : repositories)
  137. {
  138. if (entry.isEmpty())
  139. continue;
  140. // URL must be encoded to something else to get rid of symbols illegal in file names
  141. auto hashed = QCryptographicHash::hash(entry.toUtf8(), QCryptographicHash::Md5);
  142. auto hashedStr = QString::fromUtf8(hashed.toHex());
  143. downloadFile(hashedStr + ".json", entry, tr("mods repository index"));
  144. }
  145. }
  146. CModListView::~CModListView()
  147. {
  148. QSettings s(Ui::teamName, Ui::appName);
  149. s.setValue("AllModsView/State", ui->allModsView->header()->saveState());
  150. delete ui;
  151. }
  152. static QString replaceIfNotEmpty(QVariant value, QString pattern)
  153. {
  154. if(value.canConvert<QString>())
  155. {
  156. if (value.toString().isEmpty())
  157. return "";
  158. else
  159. return pattern.arg(value.toString());
  160. }
  161. if(value.canConvert<QStringList>())
  162. {
  163. if (value.toStringList().isEmpty())
  164. return "";
  165. else
  166. return pattern.arg(value.toStringList().join(", "));
  167. }
  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(const ModState & 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. QMap<QString, QStringList> changelog = mod.getChangelog();
  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(const auto & version : versions)
  194. {
  195. result += headerTemplate.arg(version);
  196. result += entryBegin;
  197. for(const auto & line : changelog.value(version))
  198. result += entryLine.arg(line);
  199. result += entryEnd;
  200. }
  201. return result;
  202. }
  203. QStringList CModListView::getModNames(QString queryingModID, QStringList input)
  204. {
  205. QStringList result;
  206. auto queryingMod = modStateModel->getMod(queryingModID);
  207. for(const auto & modID : input)
  208. {
  209. if (modStateModel->isModExists(modID) && modStateModel->getMod(modID).isHidden())
  210. continue;
  211. QString parentModID = modStateModel->getTopParent(modID);
  212. QString displayName;
  213. if (modStateModel->isSubmod(modID) && queryingMod.getParentID() != parentModID )
  214. {
  215. // show in form "parent mod (submod)"
  216. QString parentDisplayName = parentModID;
  217. QString submodDisplayName = modID;
  218. if (modStateModel->isModExists(parentModID))
  219. parentDisplayName = modStateModel->getMod(parentModID).getName();
  220. if (modStateModel->isModExists(modID))
  221. submodDisplayName = modStateModel->getMod(modID).getName();
  222. displayName = QString("%1 (%2)").arg(submodDisplayName, parentDisplayName);
  223. }
  224. else
  225. {
  226. // show simply as mod name
  227. displayName = modID;
  228. if (modStateModel->isModExists(modID))
  229. displayName = modStateModel->getMod(modID).getName();
  230. }
  231. result += displayName;
  232. }
  233. return result;
  234. }
  235. QString CModListView::genModInfoText(const ModState & mod)
  236. {
  237. QString prefix = "<p><span style=\" font-weight:600;\">%1: </span>"; // shared prefix
  238. QString redPrefix = "<p><span style=\" font-weight:600; color:red\">%1: </span>"; // shared prefix
  239. QString lineTemplate = prefix + "%2</p>";
  240. QString urlTemplate = prefix + "<a href=\"%2\">%3</a></p>";
  241. QString textTemplate = prefix + "</p><p align=\"justify\">%2</p>";
  242. QString listTemplate = "<p align=\"justify\">%1: %2</p>";
  243. QString noteTemplate = "<p align=\"justify\">%1</p>";
  244. QString incompatibleString = redPrefix + tr("Mod is incompatible") + "</p>";
  245. QString supportedVersions = redPrefix + "%2 %3 %4</p>";
  246. QString result;
  247. result += replaceIfNotEmpty(mod.getName(), lineTemplate.arg(tr("Mod name")));
  248. if (mod.isUpdateAvailable())
  249. {
  250. result += replaceIfNotEmpty(mod.getInstalledVersion(), lineTemplate.arg(tr("Installed version")));
  251. result += replaceIfNotEmpty(mod.getRepositoryVersion(), lineTemplate.arg(tr("Latest version")));
  252. }
  253. else
  254. {
  255. if (mod.isInstalled())
  256. result += replaceIfNotEmpty(mod.getInstalledVersion(), lineTemplate.arg(tr("Installed version")));
  257. else
  258. result += replaceIfNotEmpty(mod.getRepositoryVersion(), lineTemplate.arg(tr("Latest version")));
  259. }
  260. if (mod.isInstalled())
  261. result += replaceIfNotEmpty(modStateModel->getInstalledModSizeFormatted(mod.getID()), lineTemplate.arg(tr("Size")));
  262. if((!mod.isInstalled() || mod.isUpdateAvailable()) && !mod.getDownloadSizeFormatted().isEmpty())
  263. result += replaceIfNotEmpty(mod.getDownloadSizeFormatted(), lineTemplate.arg(tr("Download size")));
  264. result += replaceIfNotEmpty(mod.getAuthors(), lineTemplate.arg(tr("Authors")));
  265. if(!mod.getLicenseName().isEmpty())
  266. result += urlTemplate.arg(tr("License")).arg(mod.getLicenseUrl()).arg(mod.getLicenseName());
  267. if(!mod.getContact().isEmpty())
  268. result += urlTemplate.arg(tr("Contact")).arg(mod.getContact()).arg(mod.getContact());
  269. //compatibility info
  270. if(!mod.isCompatible())
  271. {
  272. auto compatibilityInfo = mod.getCompatibleVersionRange();
  273. auto minStr = compatibilityInfo.first;
  274. auto maxStr = compatibilityInfo.second;
  275. result += incompatibleString.arg(tr("Compatibility"));
  276. if(minStr == maxStr)
  277. result += supportedVersions.arg(tr("Required VCMI version"), minStr, "", "");
  278. else
  279. {
  280. if(minStr.isEmpty() || maxStr.isEmpty())
  281. {
  282. if(minStr.isEmpty())
  283. result += supportedVersions.arg(tr("Supported VCMI version"), maxStr, ", ", tr("please upgrade mod"));
  284. else
  285. result += supportedVersions.arg(tr("Required VCMI version"), minStr, " ", tr("or newer"));
  286. }
  287. else
  288. result += supportedVersions.arg(tr("Supported VCMI versions"), minStr, " - ", maxStr);
  289. }
  290. }
  291. QVariant baseLanguageVariant = mod.getBaseLanguage();
  292. QString baseLanguageID = baseLanguageVariant.isValid() ? baseLanguageVariant.toString() : "english";
  293. QStringList supportedLanguages = mod.getSupportedLanguages();
  294. if(supportedLanguages.size() > 1)
  295. {
  296. QStringList supportedLanguagesTranslated;
  297. for (const auto & languageID : supportedLanguages)
  298. supportedLanguagesTranslated += QApplication::translate("Language", Languages::getLanguageOptions(languageID.toStdString()).nameEnglish.c_str());
  299. result += replaceIfNotEmpty(supportedLanguagesTranslated, lineTemplate.arg(tr("Languages")));
  300. }
  301. QStringList conflicts = mod.getConflicts();
  302. for (const auto & otherMod : modStateModel->getAllMods())
  303. {
  304. QStringList otherConflicts = modStateModel->getMod(otherMod).getConflicts();
  305. if (otherConflicts.contains(mod.getID()) && !conflicts.contains(otherMod))
  306. conflicts.push_back(otherMod);
  307. }
  308. result += replaceIfNotEmpty(getModNames(mod.getID(), mod.getDependencies()), lineTemplate.arg(tr("Required mods")));
  309. result += replaceIfNotEmpty(getModNames(mod.getID(), conflicts), lineTemplate.arg(tr("Conflicting mods")));
  310. result += replaceIfNotEmpty(mod.getDescription(), textTemplate.arg(tr("Description")));
  311. result += "<p></p>"; // to get some empty space
  312. QString translationMismatch = tr("This mod cannot be enabled because it translates into a different language.");
  313. QString notInstalledDeps = tr("This mod can not be enabled because the following dependencies are not present");
  314. QString unavailableDeps = tr("This mod can not be installed because the following dependencies are not present");
  315. QString thisIsSubmod = tr("This is a submod and it cannot be installed or uninstalled separately from its parent mod");
  316. QString notes;
  317. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  318. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  319. if (mod.isInstalled())
  320. notes += replaceIfNotEmpty(getModNames(mod.getID(), notInstalledDependencies), listTemplate.arg(notInstalledDeps));
  321. else
  322. notes += replaceIfNotEmpty(getModNames(mod.getID(), unavailableDependencies), listTemplate.arg(unavailableDeps));
  323. if(mod.isSubmod())
  324. notes += noteTemplate.arg(thisIsSubmod);
  325. if (mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage().toStdString())
  326. notes += noteTemplate.arg(translationMismatch);
  327. if(notes.size())
  328. result += textTemplate.arg(tr("Notes")).arg(notes);
  329. return result;
  330. }
  331. void CModListView::disableModInfo()
  332. {
  333. ui->disableButton->setVisible(false);
  334. ui->enableButton->setVisible(false);
  335. ui->installButton->setVisible(false);
  336. ui->uninstallButton->setVisible(false);
  337. ui->updateButton->setVisible(false);
  338. }
  339. auto CModListView::buttonEnabledState(QString modName, ModState & mod)
  340. {
  341. struct result {
  342. bool disableVisible; bool enableVisible; bool installVisible; bool uninstallVisible; bool updateVisible; bool directoryVisible; bool repositoryVisible;
  343. bool disableEnabled; bool enableEnabled; bool installEnabled; bool uninstallEnabled; bool updateEnabled; bool directoryEnabled; bool repositoryEnabled;
  344. } res;
  345. QStringList notInstalledDependencies = getModsToInstall(modName);
  346. QStringList unavailableDependencies = findUnavailableMods(notInstalledDependencies);
  347. bool translationMismatch = mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage().toStdString();
  348. bool modIsBeingDownloaded = enqueuedModDownloads.contains(mod.getID());
  349. res.disableVisible = modStateModel->isModInstalled(mod.getID()) && modStateModel->isModEnabled(mod.getID());
  350. res.enableVisible = modStateModel->isModInstalled(mod.getID()) && !modStateModel->isModEnabled(mod.getID());
  351. res.installVisible = mod.isAvailable() && !mod.isSubmod();
  352. res.uninstallVisible = mod.isInstalled() && !mod.isSubmod();
  353. res.updateVisible = mod.isUpdateAvailable();
  354. #ifndef VCMI_MOBILE
  355. res.directoryVisible = mod.isInstalled();
  356. #else
  357. res.directoryVisible = false;
  358. #endif
  359. res.repositoryVisible = !mod.getDownloadUrl().isEmpty();
  360. // Block buttons if action is not allowed at this time
  361. res.disableEnabled = true;
  362. res.enableEnabled = notInstalledDependencies.empty() && !translationMismatch;
  363. res.installEnabled = unavailableDependencies.empty() && !modIsBeingDownloaded;
  364. res.uninstallEnabled = true;
  365. res.updateEnabled = unavailableDependencies.empty() && !modIsBeingDownloaded;
  366. res.directoryEnabled = true;
  367. res.repositoryEnabled = true;
  368. return res;
  369. }
  370. void CModListView::onCustomContextMenu(const QPoint &point)
  371. {
  372. QModelIndex index = ui->allModsView->indexAt(point);
  373. if(index.isValid())
  374. {
  375. const auto modName = index.data(ModRoles::ModNameRole).toString();
  376. auto mod = modStateModel->getMod(modName);
  377. auto contextMenu = new QMenu(tr("Context menu"), this);
  378. QList<QAction*> actions;
  379. auto addContextEntry = [this, &contextMenu, &actions, mod](bool visible, bool enabled, QString name, std::function<void(ModState)> function){
  380. if(visible)
  381. {
  382. actions.append(new QAction(name, this));
  383. connect(actions.back(), &QAction::triggered, this, [mod, function](){ function(mod); });
  384. contextMenu->addAction(actions.back());
  385. actions.back()->setEnabled(enabled);
  386. }
  387. };
  388. auto state = buttonEnabledState(modName, mod);
  389. addContextEntry(
  390. state.disableVisible, state.disableEnabled,
  391. tr("Disable"),
  392. [this](ModState mod){ disableModByName(mod.getID()); }
  393. );
  394. addContextEntry(
  395. state.enableVisible, state.enableEnabled,
  396. tr("Enable"),
  397. [this](ModState mod){ enableModByName(mod.getID());
  398. });
  399. addContextEntry(
  400. state.installVisible, state.installEnabled,
  401. tr("Install"),
  402. [this](ModState mod){ doInstallMod(mod.getID()); }
  403. );
  404. addContextEntry(
  405. state.uninstallVisible, state.uninstallEnabled,
  406. tr("Uninstall"),
  407. [this](ModState mod){ doUninstallMod(mod.getID()); }
  408. );
  409. addContextEntry(
  410. state.updateVisible, state.updateEnabled,
  411. tr("Update"),
  412. [this](ModState mod){ doUpdateMod(mod.getID()); }
  413. );
  414. addContextEntry(
  415. state.directoryVisible, state.directoryEnabled,
  416. tr("Open directory"),
  417. [this](ModState mod){ openModDictionary(mod.getID()); }
  418. );
  419. addContextEntry(
  420. state.repositoryVisible, state.repositoryEnabled,
  421. tr("Open repository"),
  422. [](ModState mod){
  423. QUrl url(mod.getDownloadUrl());
  424. QString repoUrl = QString("%1://%2/%3/%4")
  425. .arg(url.scheme())
  426. .arg(url.host())
  427. .arg(url.path().split('/')[1])
  428. .arg(url.path().split('/')[2]);
  429. QDesktopServices::openUrl(repoUrl);
  430. }
  431. );
  432. contextMenu->exec(ui->allModsView->viewport()->mapToGlobal(point));
  433. }
  434. }
  435. void CModListView::dataChanged(const QModelIndex & topleft, const QModelIndex & bottomRight)
  436. {
  437. selectMod(ui->allModsView->currentIndex());
  438. }
  439. void CModListView::selectMod(const QModelIndex & index)
  440. {
  441. ui->tabWidget->setCurrentIndex(0);
  442. if(!index.isValid())
  443. {
  444. disableModInfo();
  445. }
  446. else
  447. {
  448. const auto modName = index.data(ModRoles::ModNameRole).toString();
  449. auto mod = modStateModel->getMod(modName);
  450. ui->tabWidget->setTabEnabled(1, !mod.getChangelog().isEmpty());
  451. ui->tabWidget->setTabEnabled(2, !mod.getScreenshots().isEmpty());
  452. ui->modInfoBrowser->setHtml(genModInfoText(mod));
  453. ui->changelogBrowser->setHtml(genChangelogText(mod));
  454. Helper::enableScrollBySwiping(ui->modInfoBrowser);
  455. Helper::enableScrollBySwiping(ui->changelogBrowser);
  456. auto state = buttonEnabledState(modName, mod);
  457. ui->disableButton->setVisible(state.disableVisible);
  458. ui->enableButton->setVisible(state.enableVisible);
  459. ui->installButton->setVisible(state.installVisible);
  460. ui->uninstallButton->setVisible(state.uninstallVisible);
  461. ui->updateButton->setVisible(state.updateVisible);
  462. // Block buttons if action is not allowed at this time
  463. ui->disableButton->setEnabled(state.disableEnabled);
  464. ui->enableButton->setEnabled(state.enableEnabled);
  465. ui->installButton->setEnabled(state.installEnabled);
  466. ui->uninstallButton->setEnabled(state.uninstallEnabled);
  467. ui->updateButton->setEnabled(state.updateEnabled);
  468. loadScreenshots();
  469. }
  470. }
  471. void CModListView::modSelected(const QModelIndex & current, const QModelIndex &)
  472. {
  473. selectMod(current);
  474. }
  475. void CModListView::on_allModsView_activated(const QModelIndex & index)
  476. {
  477. selectMod(index);
  478. loadScreenshots();
  479. }
  480. void CModListView::on_lineEdit_textChanged(const QString & arg1)
  481. {
  482. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  483. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1, QRegularExpression::UnanchoredWildcardConversion);
  484. #else
  485. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1);
  486. //Hack due to lack QRegularExpression::UnanchoredWildcardConversion in Qt5
  487. baseStr.chop(3);
  488. baseStr.remove(0,5);
  489. #endif
  490. QRegularExpression regExp{baseStr, QRegularExpression::CaseInsensitiveOption};
  491. filterModel->setFilterRegularExpression(regExp);
  492. }
  493. void CModListView::on_comboBox_currentIndexChanged(int index)
  494. {
  495. auto enumIndex = static_cast<ModFilterMask>(index);
  496. filterModel->setTypeFilter(enumIndex);
  497. }
  498. QStringList CModListView::findUnavailableMods(QStringList candidates)
  499. {
  500. QStringList invalidMods;
  501. for(QString modName : candidates)
  502. {
  503. if(!modStateModel->isModExists(modName))
  504. invalidMods.push_back(modName);
  505. }
  506. return invalidMods;
  507. }
  508. void CModListView::on_enableButton_clicked()
  509. {
  510. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  511. enableModByName(modName);
  512. checkManagerErrors();
  513. }
  514. void CModListView::enableModByName(QString modName)
  515. {
  516. manager->enableMods({modName});
  517. modModel->modChanged(modName);
  518. }
  519. void CModListView::on_disableButton_clicked()
  520. {
  521. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  522. disableModByName(modName);
  523. checkManagerErrors();
  524. }
  525. void CModListView::disableModByName(QString modName)
  526. {
  527. manager->disableMod(modName);
  528. modModel->modChanged(modName);
  529. }
  530. QStringList CModListView::getModsToInstall(QString mod)
  531. {
  532. QStringList result;
  533. QStringList candidates;
  534. QStringList processed;
  535. candidates.push_back(mod);
  536. while (!candidates.empty())
  537. {
  538. QString potentialToInstall = candidates.back();
  539. candidates.pop_back();
  540. processed.push_back(potentialToInstall);
  541. if (modStateModel->isSubmod(potentialToInstall))
  542. {
  543. QString topParent = modStateModel->getTopParent(potentialToInstall);
  544. if (modStateModel->isModInstalled(topParent))
  545. {
  546. if (modStateModel->isModUpdateAvailable(topParent))
  547. potentialToInstall = modStateModel->getTopParent(potentialToInstall);
  548. // else - potentially broken mod that depends on non-existing submod
  549. }
  550. else
  551. potentialToInstall = modStateModel->getTopParent(potentialToInstall);
  552. }
  553. if (!modStateModel->isModInstalled(potentialToInstall))
  554. result.push_back(potentialToInstall);
  555. if (modStateModel->isModExists(potentialToInstall))
  556. {
  557. QStringList dependencies = modStateModel->getMod(potentialToInstall).getDependencies();
  558. for (const auto & dependency : dependencies)
  559. {
  560. if (!processed.contains(dependency) && !candidates.contains(dependency))
  561. candidates.push_back(dependency);
  562. }
  563. }
  564. }
  565. result.removeDuplicates();
  566. return result;
  567. }
  568. void CModListView::on_updateButton_clicked()
  569. {
  570. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  571. doUpdateMod(modName);
  572. ui->updateButton->setEnabled(false);
  573. }
  574. void CModListView::doUpdateMod(const QString & modName)
  575. {
  576. auto targetMod = modStateModel->getMod(modName);
  577. if(targetMod.isUpdateAvailable())
  578. downloadMod(targetMod);
  579. for(const auto & name : getModsToInstall(modName))
  580. {
  581. auto mod = modStateModel->getMod(name);
  582. // update required mod, install missing (can be new dependency)
  583. if(mod.isUpdateAvailable() || !mod.isInstalled())
  584. downloadMod(mod);
  585. }
  586. }
  587. void CModListView::openModDictionary(const QString & modName)
  588. {
  589. QString tmp = modName;
  590. tmp.replace(".", "/Mods/");
  591. ResourcePath resID(std::string("Mods/") + tmp.toStdString(), EResType::DIRECTORY);
  592. // Get location of the mod, in case-insensitive way
  593. QString modDir = pathToQString(*CResourceHandler::get()->getResourceName(resID));
  594. Helper::revealDirectoryInFileBrowser(modDir);
  595. }
  596. void CModListView::on_uninstallButton_clicked()
  597. {
  598. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  599. doUninstallMod(modName);
  600. checkManagerErrors();
  601. }
  602. void CModListView::on_installButton_clicked()
  603. {
  604. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  605. doInstallMod(modName);
  606. ui->installButton->setEnabled(false);
  607. }
  608. void CModListView::downloadMod(const ModState & mod)
  609. {
  610. if (enqueuedModDownloads.contains(mod.getID()))
  611. return;
  612. enqueuedModDownloads.push_back(mod.getID());
  613. downloadFile(mod.getID() + ".zip", mod.getDownloadUrl(), mod.getName(), mod.getDownloadSizeBytes());
  614. }
  615. void CModListView::downloadFile(QString file, QUrl url, QString description, qint64 sizeBytes)
  616. {
  617. if(!dlManager)
  618. {
  619. dlManager = new CDownloadManager();
  620. ui->progressWidget->setVisible(true);
  621. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  622. this, SLOT(downloadProgress(qint64,qint64)));
  623. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  624. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  625. connect(manager.get(), SIGNAL(extractionProgress(qint64,qint64)),
  626. this, SLOT(extractionProgress(qint64,qint64)));
  627. connect(modModel, &ModStateItemModel::dataChanged, filterModel, &QAbstractItemModel::dataChanged);
  628. const auto progressBarFormat = tr("Downloading %1. %p% (%v MB out of %m MB) finished").arg(description);
  629. ui->progressBar->setFormat(progressBarFormat);
  630. }
  631. dlManager->downloadFile(url, file, sizeBytes);
  632. }
  633. void CModListView::downloadProgress(qint64 current, qint64 max)
  634. {
  635. // display progress, in megabytes
  636. ui->progressBar->setVisible(true);
  637. ui->progressBar->setMaximum(max / (1024 * 1024));
  638. ui->progressBar->setValue(current / (1024 * 1024));
  639. }
  640. void CModListView::extractionProgress(qint64 current, qint64 max)
  641. {
  642. // display progress, in extracted files
  643. ui->progressBar->setVisible(true);
  644. ui->progressBar->setMaximum(max);
  645. ui->progressBar->setValue(current);
  646. }
  647. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  648. {
  649. QString title = tr("Download failed");
  650. QString firstLine = tr("Unable to download all files.\n\nEncountered errors:\n\n");
  651. QString lastLine = tr("\n\nInstall successfully downloaded?");
  652. bool doInstallFiles = false;
  653. // if all files were d/loaded there should be no errors. And on failure there must be an error
  654. assert(failedFiles.empty() == errors.empty());
  655. if(savedFiles.empty())
  656. {
  657. // no successfully downloaded mods
  658. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  659. }
  660. else if(!failedFiles.empty())
  661. {
  662. // some mods were not downloaded
  663. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  664. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  665. if(result == QMessageBox::Yes)
  666. doInstallFiles = true;
  667. }
  668. else
  669. {
  670. // everything OK
  671. doInstallFiles = true;
  672. }
  673. enqueuedModDownloads.clear();
  674. dlManager->deleteLater();
  675. dlManager = nullptr;
  676. ui->progressBar->setMaximum(0);
  677. ui->progressBar->setValue(0);
  678. if(doInstallFiles)
  679. installFiles(savedFiles);
  680. hideProgressBar();
  681. }
  682. void CModListView::hideProgressBar()
  683. {
  684. if(dlManager == nullptr) // it was not recreated meanwhile
  685. {
  686. ui->progressWidget->setVisible(false);
  687. ui->progressBar->setMaximum(0);
  688. ui->progressBar->setValue(0);
  689. }
  690. }
  691. void CModListView::installFiles(QStringList files)
  692. {
  693. QStringList mods;
  694. QStringList maps;
  695. QStringList images;
  696. QStringList exe;
  697. bool repositoryFilesEnqueued = false;
  698. // TODO: some better way to separate zip's with mods and downloaded repository files
  699. for(QString filename : files)
  700. {
  701. QString realFilename = Helper::getRealPath(filename);
  702. if(realFilename.endsWith(".zip", Qt::CaseInsensitive))
  703. mods.push_back(filename);
  704. else if(realFilename.endsWith(".h3m", Qt::CaseInsensitive) || realFilename.endsWith(".h3c", Qt::CaseInsensitive) || realFilename.endsWith(".vmap", Qt::CaseInsensitive) || realFilename.endsWith(".vcmp", Qt::CaseInsensitive))
  705. maps.push_back(filename);
  706. if(realFilename.endsWith(".exe", Qt::CaseInsensitive))
  707. exe.push_back(filename);
  708. else if(realFilename.endsWith(".json", Qt::CaseInsensitive))
  709. {
  710. //download and merge additional files
  711. JsonNode repoData = JsonUtils::jsonFromFile(filename);
  712. if(repoData["name"].isNull())
  713. {
  714. // This is main repository index. Download all referenced mods
  715. for(const auto & [modName, modJson] : repoData.Struct())
  716. {
  717. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  718. auto modJsonUrl = modJson["mod"];
  719. if(!modJsonUrl.isNull())
  720. {
  721. downloadFile(QString::fromStdString(modName + ".json"), QString::fromStdString(modJsonUrl.String()), tr("mods repository index"));
  722. repositoryFilesEnqueued = true;
  723. }
  724. accumulatedRepositoryData[modNameLower] = modJson;
  725. }
  726. }
  727. else
  728. {
  729. // This is json of a single mod. Extract name of mod and add it to repo
  730. auto modName = QFileInfo(filename).baseName().toStdString();
  731. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  732. JsonUtils::merge(accumulatedRepositoryData[modNameLower], repoData);
  733. }
  734. }
  735. else if(realFilename.endsWith(".png", Qt::CaseInsensitive))
  736. images.push_back(filename);
  737. }
  738. if (!accumulatedRepositoryData.isNull() && !repositoryFilesEnqueued)
  739. {
  740. logGlobal->info("Installing repository: started");
  741. manager->setRepositoryData(accumulatedRepositoryData);
  742. modModel->reloadViewModel();
  743. accumulatedRepositoryData.clear();
  744. static const QString repositoryCachePath = CLauncherDirs::downloadsPath() + "/repositoryCache.json";
  745. JsonUtils::jsonToFile(repositoryCachePath, modStateModel->getRepositoryData());
  746. logGlobal->info("Installing repository: ended");
  747. }
  748. if(!mods.empty())
  749. {
  750. logGlobal->info("Installing mods: started");
  751. installMods(mods);
  752. reload();
  753. logGlobal->info("Installing mods: ended");
  754. }
  755. if(!maps.empty())
  756. {
  757. logGlobal->info("Installing maps: started");
  758. installMaps(maps);
  759. logGlobal->info("Installing maps: ended");
  760. }
  761. if(!exe.empty())
  762. {
  763. logGlobal->info("Installing chronicles: started");
  764. ui->progressBar->setFormat(tr("Installing Heroes Chronicles"));
  765. ui->progressWidget->setVisible(true);
  766. ui->pushButton->setEnabled(false);
  767. float prog = 0.0;
  768. auto futureExtract = std::async(std::launch::async, [this, exe, &prog]()
  769. {
  770. ChroniclesExtractor ce(this, [&prog](float progress) { prog = progress; });
  771. ce.installChronicles(exe);
  772. reload();
  773. if (modStateModel->isModExists("chronicles"))
  774. enableModByName("chronicles");
  775. return true;
  776. });
  777. while(futureExtract.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
  778. {
  779. extractionProgress(static_cast<int>(prog * 1000.f), 1000);
  780. qApp->processEvents();
  781. }
  782. if(futureExtract.get())
  783. {
  784. hideProgressBar();
  785. ui->pushButton->setEnabled(true);
  786. ui->progressWidget->setVisible(false);
  787. //update
  788. reload();
  789. }
  790. logGlobal->info("Installing chronicles: ended");
  791. }
  792. if(!images.empty())
  793. loadScreenshots();
  794. }
  795. void CModListView::installMods(QStringList archives)
  796. {
  797. QStringList modNames;
  798. QStringList modsToEnable;
  799. for(QString archive : archives)
  800. {
  801. // get basename out of full file name
  802. // remove path remove extension
  803. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  804. modNames.push_back(modName);
  805. }
  806. if (!activatingPreset.isEmpty())
  807. {
  808. modStateModel->activatePreset(activatingPreset);
  809. activatingPreset.clear();
  810. }
  811. // uninstall old version of mod, if installed
  812. for(QString mod : modNames)
  813. {
  814. if(modStateModel->isModExists(mod) && modStateModel->getMod(mod).isInstalled())
  815. {
  816. logGlobal->info("Uninstalling old version of mod '%s'", mod.toStdString());
  817. if (modStateModel->isModEnabled(mod))
  818. modsToEnable.push_back(mod);
  819. manager->uninstallMod(mod);
  820. }
  821. else
  822. {
  823. // installation of previously not present mod -> enable it
  824. modsToEnable.push_back(mod);
  825. }
  826. }
  827. reload(); // FIXME: better way that won't reset selection
  828. for(int i = 0; i < modNames.size(); i++)
  829. {
  830. logGlobal->info("Installing mod '%s'", modNames[i].toStdString());
  831. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  832. manager->installMod(modNames[i], archives[i]);
  833. }
  834. reload();
  835. if (!modsToEnable.empty())
  836. {
  837. manager->enableMods(modsToEnable);
  838. }
  839. checkManagerErrors();
  840. for(QString archive : archives)
  841. {
  842. logGlobal->info("Erasing archive '%s'", archive.toStdString());
  843. QFile::remove(archive);
  844. }
  845. }
  846. void CModListView::installMaps(QStringList maps)
  847. {
  848. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  849. for(QString map : maps)
  850. {
  851. logGlobal->info("Importing map '%s'", map.toStdString());
  852. QFile(map).rename(destDir + map.section('/', -1, -1));
  853. }
  854. }
  855. void CModListView::on_refreshButton_clicked()
  856. {
  857. loadRepositories();
  858. }
  859. void CModListView::on_pushButton_clicked()
  860. {
  861. delete dlManager;
  862. dlManager = nullptr;
  863. hideProgressBar();
  864. }
  865. void CModListView::modelReset()
  866. {
  867. ui->allModsView->setCurrentIndex(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  868. }
  869. void CModListView::checkManagerErrors()
  870. {
  871. QString errors = manager->getErrors().join('\n');
  872. if(errors.size() != 0)
  873. {
  874. QString title = tr("Operation failed");
  875. QString description = tr("Encountered errors:\n") + errors;
  876. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  877. }
  878. }
  879. void CModListView::on_tabWidget_currentChanged(int index)
  880. {
  881. loadScreenshots();
  882. }
  883. void CModListView::loadScreenshots()
  884. {
  885. if(ui->tabWidget->currentIndex() != 2)
  886. return;
  887. assert(ui->allModsView->currentIndex().isValid());
  888. if (!ui->allModsView->currentIndex().isValid())
  889. return;
  890. ui->screenshotsList->clear();
  891. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  892. assert(modStateModel->isModExists(modName)); //should be filtered out by check above
  893. for(QString url : modStateModel->getMod(modName).getScreenshots())
  894. {
  895. // URL must be encoded to something else to get rid of symbols illegal in file names
  896. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  897. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  898. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  899. QPixmap pixmap(fullPath);
  900. if(pixmap.isNull())
  901. {
  902. // image file not exists or corrupted - try to redownload
  903. downloadFile(fileName, url, tr("screenshots"));
  904. }
  905. else
  906. {
  907. // managed to load cached image
  908. QIcon icon(pixmap);
  909. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  910. ui->screenshotsList->addItem(item);
  911. }
  912. }
  913. }
  914. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  915. {
  916. if(index.isValid())
  917. {
  918. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  919. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  920. ImageViewer::showPixmap(pixmap, this);
  921. }
  922. }
  923. void CModListView::doInstallMod(const QString & modName)
  924. {
  925. for(const auto & name : getModsToInstall(modName))
  926. {
  927. auto mod = modStateModel->getMod(name);
  928. if(mod.isAvailable())
  929. downloadMod(mod);
  930. else if(!modStateModel->isModEnabled(name))
  931. enableModByName(name);
  932. }
  933. }
  934. void CModListView::doUninstallMod(const QString & modName)
  935. {
  936. if(modStateModel->isModExists(modName) && modStateModel->getMod(modName).isInstalled())
  937. {
  938. if(modStateModel->isModEnabled(modName))
  939. manager->disableMod(modName);
  940. manager->uninstallMod(modName);
  941. reload();
  942. }
  943. }
  944. bool CModListView::isModAvailable(const QString & modName)
  945. {
  946. return modStateModel->isModExists(modName) && !modStateModel->isModInstalled(modName);
  947. }
  948. bool CModListView::isModEnabled(const QString & modName)
  949. {
  950. return modStateModel->isModEnabled(modName);
  951. }
  952. bool CModListView::isModInstalled(const QString & modName)
  953. {
  954. auto mod = modStateModel->getMod(modName);
  955. return mod.isInstalled();
  956. }
  957. QStringList CModListView::getInstalledChronicles()
  958. {
  959. QStringList result;
  960. for(const auto & modName : modStateModel->getAllMods())
  961. {
  962. auto mod = modStateModel->getMod(modName);
  963. if (!mod.isInstalled())
  964. continue;
  965. if (mod.getTopParentID() != "chronicles")
  966. continue;
  967. result += modName;
  968. }
  969. return result;
  970. }
  971. QStringList CModListView::getUpdateableMods()
  972. {
  973. QStringList result;
  974. for(const auto & modName : modStateModel->getAllMods())
  975. {
  976. auto mod = modStateModel->getMod(modName);
  977. if (!mod.isUpdateAvailable())
  978. continue;
  979. QStringList notInstalledDependencies = getModsToInstall(mod.getID());
  980. QStringList unavailableDependencies = findUnavailableMods(notInstalledDependencies);
  981. if (unavailableDependencies.empty())
  982. result.push_back(modName);
  983. }
  984. return result;
  985. }
  986. QString CModListView::getTranslationModName(const QString & language)
  987. {
  988. for(const auto & modName : modStateModel->getAllMods())
  989. {
  990. auto mod = modStateModel->getMod(modName);
  991. if (!mod.isTranslation())
  992. continue;
  993. if (mod.getBaseLanguage() != language)
  994. continue;
  995. return modName;
  996. }
  997. return QString();
  998. }
  999. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  1000. {
  1001. if(!index.isValid())
  1002. return;
  1003. auto modName = index.data(ModRoles::ModNameRole).toString();
  1004. auto mod = modStateModel->getMod(modName);
  1005. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  1006. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  1007. if(unavailableDependencies.empty() && mod.isAvailable() && !mod.isSubmod())
  1008. {
  1009. on_installButton_clicked();
  1010. return;
  1011. }
  1012. if(unavailableDependencies.empty() && mod.isUpdateAvailable() && index.column() == ModFields::STATUS_UPDATE)
  1013. {
  1014. on_updateButton_clicked();
  1015. return;
  1016. }
  1017. if(index.column() == ModFields::NAME)
  1018. {
  1019. if(ui->allModsView->isExpanded(index))
  1020. ui->allModsView->collapse(index);
  1021. else
  1022. ui->allModsView->expand(index);
  1023. return;
  1024. }
  1025. if(notInstalledDependencies.empty() && !modStateModel->isModEnabled(modName))
  1026. {
  1027. on_enableButton_clicked();
  1028. return;
  1029. }
  1030. if(modStateModel->isModEnabled(modName))
  1031. {
  1032. on_disableButton_clicked();
  1033. return;
  1034. }
  1035. }
  1036. void CModListView::createNewPreset(const QString & presetName)
  1037. {
  1038. modStateModel->createNewPreset(presetName);
  1039. }
  1040. void CModListView::deletePreset(const QString & presetName)
  1041. {
  1042. modStateModel->deletePreset(presetName);
  1043. }
  1044. void CModListView::activatePreset(const QString & presetName)
  1045. {
  1046. modStateModel->activatePreset(presetName);
  1047. reload();
  1048. }
  1049. void CModListView::renamePreset(const QString & oldPresetName, const QString & newPresetName)
  1050. {
  1051. modStateModel->renamePreset(oldPresetName, newPresetName);
  1052. }
  1053. QStringList CModListView::getAllPresets() const
  1054. {
  1055. return modStateModel->getAllPresets();
  1056. }
  1057. QString CModListView::getActivePreset() const
  1058. {
  1059. return modStateModel->getActivePreset();
  1060. }
  1061. JsonNode CModListView::exportCurrentPreset() const
  1062. {
  1063. return modStateModel->exportCurrentPreset();
  1064. }
  1065. void CModListView::importPreset(const JsonNode & data)
  1066. {
  1067. const auto & [presetName, modList] = modStateModel->importPreset(data);
  1068. if (modList.empty())
  1069. {
  1070. modStateModel->activatePreset(presetName);
  1071. modStateModel->reloadLocalState();
  1072. }
  1073. else
  1074. {
  1075. activatingPreset = presetName;
  1076. for (const auto & modID : modList)
  1077. doInstallMod(modID);
  1078. }
  1079. }