cmodlistview_moc.cpp 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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. void CModListView::onCustomContextMenu(const QPoint &point)
  340. {
  341. QModelIndex index = ui->allModsView->indexAt(point);
  342. if(index.isValid())
  343. {
  344. const auto modName = index.data(ModRoles::ModNameRole).toString();
  345. auto mod = modStateModel->getMod(modName);
  346. QStringList notInstalledDependencies = getModsToInstall(modName);
  347. QStringList unavailableDependencies = findUnavailableMods(notInstalledDependencies);
  348. bool translationMismatch = mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage().toStdString();
  349. bool modIsBeingDownloaded = enqueuedModDownloads.contains(mod.getID());
  350. auto contextMenu = new QMenu(tr("Context menu"), this);
  351. QList<QAction*> actions;
  352. auto addContextEntry = [this, &contextMenu, &actions, mod](bool condition, QString name, std::function<void(ModState)> function){
  353. if(condition)
  354. {
  355. actions.append(new QAction(name, this));
  356. connect(actions.back(), &QAction::triggered, this, [mod, function](){ function(mod); });
  357. contextMenu->addAction(actions.back());
  358. }
  359. };
  360. addContextEntry(
  361. modStateModel->isModInstalled(mod.getID()) && modStateModel->isModEnabled(mod.getID()),
  362. tr("Disable"),
  363. [this](ModState mod){ disableModByName(mod.getID()); }
  364. );
  365. addContextEntry(
  366. modStateModel->isModInstalled(mod.getID()) && !modStateModel->isModEnabled(mod.getID()) && notInstalledDependencies.empty() && !translationMismatch,
  367. tr("Enable"),
  368. [this](ModState mod){ enableModByName(mod.getID());
  369. });
  370. addContextEntry(
  371. mod.isAvailable() && !mod.isSubmod() && unavailableDependencies.empty() && !modIsBeingDownloaded,
  372. tr("Install"),
  373. [this](ModState mod){ doInstallMod(mod.getID()); }
  374. );
  375. addContextEntry(
  376. mod.isInstalled() && !mod.isSubmod(),
  377. tr("Uninstall"),
  378. [this](ModState mod){
  379. if(modStateModel->isModEnabled(mod.getID()))
  380. manager->disableMod(mod.getID());
  381. manager->uninstallMod(mod.getID());
  382. reload();
  383. }
  384. );
  385. addContextEntry(
  386. mod.isUpdateAvailable() && unavailableDependencies.empty() && !modIsBeingDownloaded,
  387. tr("Update"),
  388. [this](ModState mod){ doUpdateMod(mod.getID()); }
  389. );
  390. #ifndef VCMI_MOBILE
  391. addContextEntry(
  392. mod.isInstalled(),
  393. tr("Open directory"),
  394. [this](ModState mod){ openModDictionary(mod.getID()); }
  395. );
  396. #endif
  397. addContextEntry(
  398. !mod.getDownloadUrl().isEmpty(),
  399. tr("Open repository"),
  400. [](ModState mod){
  401. QUrl url(mod.getDownloadUrl());
  402. QString repoUrl = QString("%1://%2/%3/%4")
  403. .arg(url.scheme())
  404. .arg(url.host())
  405. .arg(url.path().split('/')[1])
  406. .arg(url.path().split('/')[2]);
  407. QDesktopServices::openUrl(repoUrl);
  408. }
  409. );
  410. contextMenu->exec(ui->allModsView->viewport()->mapToGlobal(point));
  411. }
  412. }
  413. void CModListView::dataChanged(const QModelIndex & topleft, const QModelIndex & bottomRight)
  414. {
  415. selectMod(ui->allModsView->currentIndex());
  416. }
  417. void CModListView::selectMod(const QModelIndex & index)
  418. {
  419. ui->tabWidget->setCurrentIndex(0);
  420. if(!index.isValid())
  421. {
  422. disableModInfo();
  423. }
  424. else
  425. {
  426. const auto modName = index.data(ModRoles::ModNameRole).toString();
  427. auto mod = modStateModel->getMod(modName);
  428. ui->tabWidget->setTabEnabled(1, !mod.getChangelog().isEmpty());
  429. ui->tabWidget->setTabEnabled(2, !mod.getScreenshots().isEmpty());
  430. ui->modInfoBrowser->setHtml(genModInfoText(mod));
  431. ui->changelogBrowser->setHtml(genChangelogText(mod));
  432. Helper::enableScrollBySwiping(ui->modInfoBrowser);
  433. Helper::enableScrollBySwiping(ui->changelogBrowser);
  434. QStringList notInstalledDependencies = getModsToInstall(modName);
  435. QStringList unavailableDependencies = findUnavailableMods(notInstalledDependencies);
  436. bool translationMismatch = mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage().toStdString();
  437. bool modIsBeingDownloaded = enqueuedModDownloads.contains(mod.getID());
  438. ui->disableButton->setVisible(modStateModel->isModInstalled(mod.getID()) && modStateModel->isModEnabled(mod.getID()));
  439. ui->enableButton->setVisible(modStateModel->isModInstalled(mod.getID()) && !modStateModel->isModEnabled(mod.getID()));
  440. ui->installButton->setVisible(mod.isAvailable() && !mod.isSubmod());
  441. ui->uninstallButton->setVisible(mod.isInstalled() && !mod.isSubmod());
  442. ui->updateButton->setVisible(mod.isUpdateAvailable());
  443. // Block buttons if action is not allowed at this time
  444. ui->disableButton->setEnabled(true);
  445. ui->enableButton->setEnabled(notInstalledDependencies.empty() && !translationMismatch);
  446. ui->installButton->setEnabled(unavailableDependencies.empty() && !modIsBeingDownloaded);
  447. ui->uninstallButton->setEnabled(true);
  448. ui->updateButton->setEnabled(unavailableDependencies.empty() && !modIsBeingDownloaded);
  449. loadScreenshots();
  450. }
  451. }
  452. void CModListView::modSelected(const QModelIndex & current, const QModelIndex &)
  453. {
  454. selectMod(current);
  455. }
  456. void CModListView::on_allModsView_activated(const QModelIndex & index)
  457. {
  458. selectMod(index);
  459. loadScreenshots();
  460. }
  461. void CModListView::on_lineEdit_textChanged(const QString & arg1)
  462. {
  463. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  464. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1, QRegularExpression::UnanchoredWildcardConversion);
  465. #else
  466. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1);
  467. //Hack due to lack QRegularExpression::UnanchoredWildcardConversion in Qt5
  468. baseStr.chop(3);
  469. baseStr.remove(0,5);
  470. #endif
  471. QRegularExpression regExp{baseStr, QRegularExpression::CaseInsensitiveOption};
  472. filterModel->setFilterRegularExpression(regExp);
  473. }
  474. void CModListView::on_comboBox_currentIndexChanged(int index)
  475. {
  476. auto enumIndex = static_cast<ModFilterMask>(index);
  477. filterModel->setTypeFilter(enumIndex);
  478. }
  479. QStringList CModListView::findUnavailableMods(QStringList candidates)
  480. {
  481. QStringList invalidMods;
  482. for(QString modName : candidates)
  483. {
  484. if(!modStateModel->isModExists(modName))
  485. invalidMods.push_back(modName);
  486. }
  487. return invalidMods;
  488. }
  489. void CModListView::on_enableButton_clicked()
  490. {
  491. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  492. enableModByName(modName);
  493. checkManagerErrors();
  494. }
  495. void CModListView::enableModByName(QString modName)
  496. {
  497. manager->enableMods({modName});
  498. modModel->modChanged(modName);
  499. }
  500. void CModListView::on_disableButton_clicked()
  501. {
  502. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  503. disableModByName(modName);
  504. checkManagerErrors();
  505. }
  506. void CModListView::disableModByName(QString modName)
  507. {
  508. manager->disableMod(modName);
  509. modModel->modChanged(modName);
  510. }
  511. QStringList CModListView::getModsToInstall(QString mod)
  512. {
  513. QStringList result;
  514. QStringList candidates;
  515. QStringList processed;
  516. candidates.push_back(mod);
  517. while (!candidates.empty())
  518. {
  519. QString potentialToInstall = candidates.back();
  520. candidates.pop_back();
  521. processed.push_back(potentialToInstall);
  522. if (modStateModel->isSubmod(potentialToInstall))
  523. {
  524. QString topParent = modStateModel->getTopParent(potentialToInstall);
  525. if (modStateModel->isModInstalled(topParent))
  526. {
  527. if (modStateModel->isModUpdateAvailable(topParent))
  528. potentialToInstall = modStateModel->getTopParent(potentialToInstall);
  529. // else - potentially broken mod that depends on non-existing submod
  530. }
  531. else
  532. potentialToInstall = modStateModel->getTopParent(potentialToInstall);
  533. }
  534. if (!modStateModel->isModInstalled(potentialToInstall))
  535. result.push_back(potentialToInstall);
  536. if (modStateModel->isModExists(potentialToInstall))
  537. {
  538. QStringList dependencies = modStateModel->getMod(potentialToInstall).getDependencies();
  539. for (const auto & dependency : dependencies)
  540. {
  541. if (!processed.contains(dependency) && !candidates.contains(dependency))
  542. candidates.push_back(dependency);
  543. }
  544. }
  545. }
  546. result.removeDuplicates();
  547. return result;
  548. }
  549. void CModListView::on_updateButton_clicked()
  550. {
  551. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  552. doUpdateMod(modName);
  553. ui->updateButton->setEnabled(false);
  554. }
  555. void CModListView::doUpdateMod(const QString & modName)
  556. {
  557. auto targetMod = modStateModel->getMod(modName);
  558. if(targetMod.isUpdateAvailable())
  559. downloadMod(targetMod);
  560. for(const auto & name : getModsToInstall(modName))
  561. {
  562. auto mod = modStateModel->getMod(name);
  563. // update required mod, install missing (can be new dependency)
  564. if(mod.isUpdateAvailable() || !mod.isInstalled())
  565. downloadMod(mod);
  566. }
  567. }
  568. void CModListView::openModDictionary(const QString & modName)
  569. {
  570. QString tmp = modName;
  571. tmp.replace(".", "/Mods/");
  572. ResourcePath resID(std::string("Mods/") + tmp.toStdString(), EResType::DIRECTORY);
  573. // Get location of the mod, in case-insensitive way
  574. QString modDir = pathToQString(*CResourceHandler::get()->getResourceName(resID));
  575. Helper::revealDirectoryInFileBrowser(modDir);
  576. }
  577. void CModListView::on_uninstallButton_clicked()
  578. {
  579. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  580. if(modStateModel->isModExists(modName) && modStateModel->getMod(modName).isInstalled())
  581. {
  582. if(modStateModel->isModEnabled(modName))
  583. manager->disableMod(modName);
  584. manager->uninstallMod(modName);
  585. reload();
  586. }
  587. checkManagerErrors();
  588. }
  589. void CModListView::on_installButton_clicked()
  590. {
  591. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  592. doInstallMod(modName);
  593. ui->installButton->setEnabled(false);
  594. }
  595. void CModListView::downloadMod(const ModState & mod)
  596. {
  597. if (enqueuedModDownloads.contains(mod.getID()))
  598. return;
  599. enqueuedModDownloads.push_back(mod.getID());
  600. downloadFile(mod.getID() + ".zip", mod.getDownloadUrl(), mod.getName(), mod.getDownloadSizeBytes());
  601. }
  602. void CModListView::downloadFile(QString file, QUrl url, QString description, qint64 sizeBytes)
  603. {
  604. if(!dlManager)
  605. {
  606. dlManager = new CDownloadManager();
  607. ui->progressWidget->setVisible(true);
  608. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  609. this, SLOT(downloadProgress(qint64,qint64)));
  610. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  611. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  612. connect(manager.get(), SIGNAL(extractionProgress(qint64,qint64)),
  613. this, SLOT(extractionProgress(qint64,qint64)));
  614. connect(modModel, &ModStateItemModel::dataChanged, filterModel, &QAbstractItemModel::dataChanged);
  615. const auto progressBarFormat = tr("Downloading %1. %p% (%v MB out of %m MB) finished").arg(description);
  616. ui->progressBar->setFormat(progressBarFormat);
  617. }
  618. dlManager->downloadFile(url, file, sizeBytes);
  619. }
  620. void CModListView::downloadProgress(qint64 current, qint64 max)
  621. {
  622. // display progress, in megabytes
  623. ui->progressBar->setVisible(true);
  624. ui->progressBar->setMaximum(max / (1024 * 1024));
  625. ui->progressBar->setValue(current / (1024 * 1024));
  626. }
  627. void CModListView::extractionProgress(qint64 current, qint64 max)
  628. {
  629. // display progress, in extracted files
  630. ui->progressBar->setVisible(true);
  631. ui->progressBar->setMaximum(max);
  632. ui->progressBar->setValue(current);
  633. }
  634. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  635. {
  636. QString title = tr("Download failed");
  637. QString firstLine = tr("Unable to download all files.\n\nEncountered errors:\n\n");
  638. QString lastLine = tr("\n\nInstall successfully downloaded?");
  639. bool doInstallFiles = false;
  640. // if all files were d/loaded there should be no errors. And on failure there must be an error
  641. assert(failedFiles.empty() == errors.empty());
  642. if(savedFiles.empty())
  643. {
  644. // no successfully downloaded mods
  645. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  646. }
  647. else if(!failedFiles.empty())
  648. {
  649. // some mods were not downloaded
  650. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  651. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  652. if(result == QMessageBox::Yes)
  653. doInstallFiles = true;
  654. }
  655. else
  656. {
  657. // everything OK
  658. doInstallFiles = true;
  659. }
  660. enqueuedModDownloads.clear();
  661. dlManager->deleteLater();
  662. dlManager = nullptr;
  663. ui->progressBar->setMaximum(0);
  664. ui->progressBar->setValue(0);
  665. if(doInstallFiles)
  666. installFiles(savedFiles);
  667. hideProgressBar();
  668. }
  669. void CModListView::hideProgressBar()
  670. {
  671. if(dlManager == nullptr) // it was not recreated meanwhile
  672. {
  673. ui->progressWidget->setVisible(false);
  674. ui->progressBar->setMaximum(0);
  675. ui->progressBar->setValue(0);
  676. }
  677. }
  678. void CModListView::installFiles(QStringList files)
  679. {
  680. QStringList mods;
  681. QStringList maps;
  682. QStringList images;
  683. QStringList exe;
  684. bool repositoryFilesEnqueued = false;
  685. // TODO: some better way to separate zip's with mods and downloaded repository files
  686. for(QString filename : files)
  687. {
  688. QString realFilename = Helper::getRealPath(filename);
  689. if(realFilename.endsWith(".zip", Qt::CaseInsensitive))
  690. mods.push_back(filename);
  691. else if(realFilename.endsWith(".h3m", Qt::CaseInsensitive) || realFilename.endsWith(".h3c", Qt::CaseInsensitive) || realFilename.endsWith(".vmap", Qt::CaseInsensitive) || realFilename.endsWith(".vcmp", Qt::CaseInsensitive))
  692. maps.push_back(filename);
  693. if(realFilename.endsWith(".exe", Qt::CaseInsensitive))
  694. exe.push_back(filename);
  695. else if(realFilename.endsWith(".json", Qt::CaseInsensitive))
  696. {
  697. //download and merge additional files
  698. JsonNode repoData = JsonUtils::jsonFromFile(filename);
  699. if(repoData["name"].isNull())
  700. {
  701. // This is main repository index. Download all referenced mods
  702. for(const auto & [modName, modJson] : repoData.Struct())
  703. {
  704. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  705. auto modJsonUrl = modJson["mod"];
  706. if(!modJsonUrl.isNull())
  707. {
  708. downloadFile(QString::fromStdString(modName + ".json"), QString::fromStdString(modJsonUrl.String()), tr("mods repository index"));
  709. repositoryFilesEnqueued = true;
  710. }
  711. accumulatedRepositoryData[modNameLower] = modJson;
  712. }
  713. }
  714. else
  715. {
  716. // This is json of a single mod. Extract name of mod and add it to repo
  717. auto modName = QFileInfo(filename).baseName().toStdString();
  718. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  719. JsonUtils::merge(accumulatedRepositoryData[modNameLower], repoData);
  720. }
  721. }
  722. else if(realFilename.endsWith(".png", Qt::CaseInsensitive))
  723. images.push_back(filename);
  724. }
  725. if (!accumulatedRepositoryData.isNull() && !repositoryFilesEnqueued)
  726. {
  727. logGlobal->info("Installing repository: started");
  728. manager->setRepositoryData(accumulatedRepositoryData);
  729. modModel->reloadViewModel();
  730. accumulatedRepositoryData.clear();
  731. static const QString repositoryCachePath = CLauncherDirs::downloadsPath() + "/repositoryCache.json";
  732. JsonUtils::jsonToFile(repositoryCachePath, modStateModel->getRepositoryData());
  733. logGlobal->info("Installing repository: ended");
  734. }
  735. if(!mods.empty())
  736. {
  737. logGlobal->info("Installing mods: started");
  738. installMods(mods);
  739. reload();
  740. logGlobal->info("Installing mods: ended");
  741. }
  742. if(!maps.empty())
  743. {
  744. logGlobal->info("Installing maps: started");
  745. installMaps(maps);
  746. logGlobal->info("Installing maps: ended");
  747. }
  748. if(!exe.empty())
  749. {
  750. logGlobal->info("Installing chronicles: started");
  751. ui->progressBar->setFormat(tr("Installing Heroes Chronicles"));
  752. ui->progressWidget->setVisible(true);
  753. ui->pushButton->setEnabled(false);
  754. float prog = 0.0;
  755. auto futureExtract = std::async(std::launch::async, [this, exe, &prog]()
  756. {
  757. ChroniclesExtractor ce(this, [&prog](float progress) { prog = progress; });
  758. ce.installChronicles(exe);
  759. reload();
  760. if (modStateModel->isModExists("chronicles"))
  761. enableModByName("chronicles");
  762. return true;
  763. });
  764. while(futureExtract.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
  765. {
  766. extractionProgress(static_cast<int>(prog * 1000.f), 1000);
  767. qApp->processEvents();
  768. }
  769. if(futureExtract.get())
  770. {
  771. hideProgressBar();
  772. ui->pushButton->setEnabled(true);
  773. ui->progressWidget->setVisible(false);
  774. //update
  775. reload();
  776. }
  777. logGlobal->info("Installing chronicles: ended");
  778. }
  779. if(!images.empty())
  780. loadScreenshots();
  781. }
  782. void CModListView::installMods(QStringList archives)
  783. {
  784. QStringList modNames;
  785. QStringList modsToEnable;
  786. for(QString archive : archives)
  787. {
  788. // get basename out of full file name
  789. // remove path remove extension
  790. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  791. modNames.push_back(modName);
  792. }
  793. if (!activatingPreset.isEmpty())
  794. {
  795. modStateModel->activatePreset(activatingPreset);
  796. activatingPreset.clear();
  797. }
  798. // uninstall old version of mod, if installed
  799. for(QString mod : modNames)
  800. {
  801. if(modStateModel->isModExists(mod) && modStateModel->getMod(mod).isInstalled())
  802. {
  803. logGlobal->info("Uninstalling old version of mod '%s'", mod.toStdString());
  804. if (modStateModel->isModEnabled(mod))
  805. modsToEnable.push_back(mod);
  806. manager->uninstallMod(mod);
  807. }
  808. else
  809. {
  810. // installation of previously not present mod -> enable it
  811. modsToEnable.push_back(mod);
  812. }
  813. }
  814. reload(); // FIXME: better way that won't reset selection
  815. for(int i = 0; i < modNames.size(); i++)
  816. {
  817. logGlobal->info("Installing mod '%s'", modNames[i].toStdString());
  818. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  819. manager->installMod(modNames[i], archives[i]);
  820. }
  821. reload();
  822. if (!modsToEnable.empty())
  823. {
  824. manager->enableMods(modsToEnable);
  825. }
  826. checkManagerErrors();
  827. for(QString archive : archives)
  828. {
  829. logGlobal->info("Erasing archive '%s'", archive.toStdString());
  830. QFile::remove(archive);
  831. }
  832. }
  833. void CModListView::installMaps(QStringList maps)
  834. {
  835. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  836. for(QString map : maps)
  837. {
  838. logGlobal->info("Importing map '%s'", map.toStdString());
  839. QFile(map).rename(destDir + map.section('/', -1, -1));
  840. }
  841. }
  842. void CModListView::on_refreshButton_clicked()
  843. {
  844. loadRepositories();
  845. }
  846. void CModListView::on_pushButton_clicked()
  847. {
  848. delete dlManager;
  849. dlManager = nullptr;
  850. hideProgressBar();
  851. }
  852. void CModListView::modelReset()
  853. {
  854. ui->allModsView->setCurrentIndex(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  855. }
  856. void CModListView::checkManagerErrors()
  857. {
  858. QString errors = manager->getErrors().join('\n');
  859. if(errors.size() != 0)
  860. {
  861. QString title = tr("Operation failed");
  862. QString description = tr("Encountered errors:\n") + errors;
  863. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  864. }
  865. }
  866. void CModListView::on_tabWidget_currentChanged(int index)
  867. {
  868. loadScreenshots();
  869. }
  870. void CModListView::loadScreenshots()
  871. {
  872. if(ui->tabWidget->currentIndex() != 2)
  873. return;
  874. assert(ui->allModsView->currentIndex().isValid());
  875. if (!ui->allModsView->currentIndex().isValid())
  876. return;
  877. ui->screenshotsList->clear();
  878. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  879. assert(modStateModel->isModExists(modName)); //should be filtered out by check above
  880. for(QString url : modStateModel->getMod(modName).getScreenshots())
  881. {
  882. // URL must be encoded to something else to get rid of symbols illegal in file names
  883. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  884. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  885. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  886. QPixmap pixmap(fullPath);
  887. if(pixmap.isNull())
  888. {
  889. // image file not exists or corrupted - try to redownload
  890. downloadFile(fileName, url, tr("screenshots"));
  891. }
  892. else
  893. {
  894. // managed to load cached image
  895. QIcon icon(pixmap);
  896. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  897. ui->screenshotsList->addItem(item);
  898. }
  899. }
  900. }
  901. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  902. {
  903. if(index.isValid())
  904. {
  905. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  906. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  907. ImageViewer::showPixmap(pixmap, this);
  908. }
  909. }
  910. void CModListView::doInstallMod(const QString & modName)
  911. {
  912. for(const auto & name : getModsToInstall(modName))
  913. {
  914. auto mod = modStateModel->getMod(name);
  915. if(mod.isAvailable())
  916. downloadMod(mod);
  917. else if(!modStateModel->isModEnabled(name))
  918. enableModByName(name);
  919. }
  920. }
  921. bool CModListView::isModAvailable(const QString & modName)
  922. {
  923. return modStateModel->isModExists(modName) && !modStateModel->isModInstalled(modName);
  924. }
  925. bool CModListView::isModEnabled(const QString & modName)
  926. {
  927. return modStateModel->isModEnabled(modName);
  928. }
  929. bool CModListView::isModInstalled(const QString & modName)
  930. {
  931. auto mod = modStateModel->getMod(modName);
  932. return mod.isInstalled();
  933. }
  934. QStringList CModListView::getInstalledChronicles()
  935. {
  936. QStringList result;
  937. for(const auto & modName : modStateModel->getAllMods())
  938. {
  939. auto mod = modStateModel->getMod(modName);
  940. if (!mod.isInstalled())
  941. continue;
  942. if (mod.getTopParentID() != "chronicles")
  943. continue;
  944. result += modName;
  945. }
  946. return result;
  947. }
  948. QStringList CModListView::getUpdateableMods()
  949. {
  950. QStringList result;
  951. for(const auto & modName : modStateModel->getAllMods())
  952. {
  953. auto mod = modStateModel->getMod(modName);
  954. if (!mod.isUpdateAvailable())
  955. continue;
  956. QStringList notInstalledDependencies = getModsToInstall(mod.getID());
  957. QStringList unavailableDependencies = findUnavailableMods(notInstalledDependencies);
  958. if (unavailableDependencies.empty())
  959. result.push_back(modName);
  960. }
  961. return result;
  962. }
  963. QString CModListView::getTranslationModName(const QString & language)
  964. {
  965. for(const auto & modName : modStateModel->getAllMods())
  966. {
  967. auto mod = modStateModel->getMod(modName);
  968. if (!mod.isTranslation())
  969. continue;
  970. if (mod.getBaseLanguage() != language)
  971. continue;
  972. return modName;
  973. }
  974. return QString();
  975. }
  976. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  977. {
  978. if(!index.isValid())
  979. return;
  980. auto modName = index.data(ModRoles::ModNameRole).toString();
  981. auto mod = modStateModel->getMod(modName);
  982. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  983. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  984. if(unavailableDependencies.empty() && mod.isAvailable() && !mod.isSubmod())
  985. {
  986. on_installButton_clicked();
  987. return;
  988. }
  989. if(unavailableDependencies.empty() && mod.isUpdateAvailable() && index.column() == ModFields::STATUS_UPDATE)
  990. {
  991. on_updateButton_clicked();
  992. return;
  993. }
  994. if(index.column() == ModFields::NAME)
  995. {
  996. if(ui->allModsView->isExpanded(index))
  997. ui->allModsView->collapse(index);
  998. else
  999. ui->allModsView->expand(index);
  1000. return;
  1001. }
  1002. if(notInstalledDependencies.empty() && !modStateModel->isModEnabled(modName))
  1003. {
  1004. on_enableButton_clicked();
  1005. return;
  1006. }
  1007. if(modStateModel->isModEnabled(modName))
  1008. {
  1009. on_disableButton_clicked();
  1010. return;
  1011. }
  1012. }
  1013. void CModListView::createNewPreset(const QString & presetName)
  1014. {
  1015. modStateModel->createNewPreset(presetName);
  1016. }
  1017. void CModListView::deletePreset(const QString & presetName)
  1018. {
  1019. modStateModel->deletePreset(presetName);
  1020. }
  1021. void CModListView::activatePreset(const QString & presetName)
  1022. {
  1023. modStateModel->activatePreset(presetName);
  1024. reload();
  1025. }
  1026. void CModListView::renamePreset(const QString & oldPresetName, const QString & newPresetName)
  1027. {
  1028. modStateModel->renamePreset(oldPresetName, newPresetName);
  1029. }
  1030. QStringList CModListView::getAllPresets() const
  1031. {
  1032. return modStateModel->getAllPresets();
  1033. }
  1034. QString CModListView::getActivePreset() const
  1035. {
  1036. return modStateModel->getActivePreset();
  1037. }
  1038. JsonNode CModListView::exportCurrentPreset() const
  1039. {
  1040. return modStateModel->exportCurrentPreset();
  1041. }
  1042. void CModListView::importPreset(const JsonNode & data)
  1043. {
  1044. const auto & [presetName, modList] = modStateModel->importPreset(data);
  1045. if (modList.empty())
  1046. {
  1047. modStateModel->activatePreset(presetName);
  1048. modStateModel->reloadLocalState();
  1049. }
  1050. else
  1051. {
  1052. activatingPreset = presetName;
  1053. for (const auto & modID : modList)
  1054. doInstallMod(modID);
  1055. }
  1056. }