cmodlistview_moc.cpp 38 KB

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