cmodlistview_moc.cpp 43 KB

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