cmodlistview_moc.cpp 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501
  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. dlManager->downloadFile(url, file, sizeBytes);
  650. }
  651. void CModListView::downloadProgress(qint64 current, qint64 max)
  652. {
  653. // display progress, in megabytes
  654. ui->progressBar->setVisible(true);
  655. ui->progressBar->setMaximum(max / (1024 * 1024));
  656. ui->progressBar->setValue(current / (1024 * 1024));
  657. }
  658. void CModListView::extractionProgress(qint64 current, qint64 max)
  659. {
  660. // display progress, in extracted files
  661. ui->progressBar->setVisible(true);
  662. ui->progressBar->setMaximum(max);
  663. ui->progressBar->setValue(current);
  664. }
  665. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  666. {
  667. QString title = tr("Download failed");
  668. QString firstLine = tr("Unable to download all files.\n\nEncountered errors:\n\n");
  669. QString lastLine = tr("\n\nInstall successfully downloaded?");
  670. bool doInstallFiles = false;
  671. // if all files were d/loaded there should be no errors. And on failure there must be an error
  672. assert(failedFiles.empty() == errors.empty());
  673. if(savedFiles.empty())
  674. {
  675. // no successfully downloaded mods
  676. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  677. }
  678. else if(!failedFiles.empty())
  679. {
  680. // some mods were not downloaded
  681. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  682. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  683. if(result == QMessageBox::Yes)
  684. doInstallFiles = true;
  685. }
  686. else
  687. {
  688. // everything OK
  689. doInstallFiles = true;
  690. }
  691. enqueuedModDownloads.clear();
  692. dlManager->deleteLater();
  693. dlManager = nullptr;
  694. ui->progressBar->setMaximum(0);
  695. ui->progressBar->setValue(0);
  696. if(doInstallFiles)
  697. installFiles(savedFiles);
  698. hideProgressBar();
  699. }
  700. void CModListView::hideProgressBar()
  701. {
  702. if(dlManager == nullptr) // it was not recreated meanwhile
  703. {
  704. ui->progressWidget->setVisible(false);
  705. ui->progressBar->setMaximum(0);
  706. ui->progressBar->setValue(0);
  707. }
  708. }
  709. void CModListView::installFiles(QStringList files)
  710. {
  711. QStringList mods;
  712. QStringList maps;
  713. QStringList images;
  714. QStringList exe;
  715. bool repositoryFilesEnqueued = false;
  716. // TODO: some better way to separate zip's with mods and downloaded repository files
  717. for(QString filename : files)
  718. {
  719. QString realFilename = Helper::getRealPath(filename);
  720. if(realFilename.endsWith(".zip", Qt::CaseInsensitive))
  721. {
  722. ZipArchive archive(qstringToPath(realFilename));
  723. auto fileList = archive.listFiles();
  724. bool hasModJson = false;
  725. bool hasMaps = false;
  726. for (const auto& file : fileList)
  727. {
  728. QString lower = QString::fromStdString(file).toLower();
  729. // Check for mod.json anywhere in archive
  730. if (lower.endsWith("mod.json"))
  731. hasModJson = true;
  732. // Check for map files anywhere
  733. if (lower.endsWith(".h3m") || lower.endsWith(".h3c") || lower.endsWith(".vmap") || lower.endsWith(".vcmp"))
  734. hasMaps = true;
  735. }
  736. if (hasModJson)
  737. mods.push_back(filename);
  738. else if (hasMaps)
  739. maps.push_back(filename);
  740. else
  741. mods.push_back(filename);
  742. }
  743. else if(realFilename.endsWith(".h3m", Qt::CaseInsensitive) || realFilename.endsWith(".h3c", Qt::CaseInsensitive) || realFilename.endsWith(".vmap", Qt::CaseInsensitive) || realFilename.endsWith(".vcmp", Qt::CaseInsensitive))
  744. maps.push_back(filename);
  745. if(realFilename.endsWith(".exe", Qt::CaseInsensitive))
  746. exe.push_back(filename);
  747. else if(realFilename.endsWith(".json", Qt::CaseInsensitive))
  748. {
  749. //download and merge additional files
  750. JsonNode repoData = JsonUtils::jsonFromFile(filename);
  751. if(repoData["name"].isNull())
  752. {
  753. // MODS COMPATIBILITY: in 1.6, repository list contains mod list directly, in 1.7 it is located in 'availableMods' node
  754. const auto & availableRepositoryMods = repoData["availableMods"].isNull() ? repoData : repoData["availableMods"];
  755. // This is main repository index. Download all referenced mods
  756. for(const auto & [modName, modJson] : availableRepositoryMods.Struct())
  757. {
  758. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  759. auto modJsonUrl = modJson["mod"];
  760. if(!modJsonUrl.isNull())
  761. {
  762. downloadFile(QString::fromStdString(modName + ".json"), QString::fromStdString(modJsonUrl.String()), tr("mods repository index"));
  763. repositoryFilesEnqueued = true;
  764. }
  765. accumulatedRepositoryData[modNameLower] = modJson;
  766. }
  767. }
  768. else
  769. {
  770. // This is json of a single mod. Extract name of mod and add it to repo
  771. auto modName = QFileInfo(filename).baseName().toStdString();
  772. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  773. JsonUtils::merge(accumulatedRepositoryData[modNameLower], repoData);
  774. }
  775. }
  776. else if(realFilename.endsWith(".png", Qt::CaseInsensitive))
  777. images.push_back(filename);
  778. }
  779. if (!accumulatedRepositoryData.isNull() && !repositoryFilesEnqueued)
  780. {
  781. logGlobal->info("Installing repository: started");
  782. manager->setRepositoryData(accumulatedRepositoryData);
  783. modModel->reloadViewModel();
  784. accumulatedRepositoryData.clear();
  785. static const QString repositoryCachePath = CLauncherDirs::downloadsPath() + "/repositoryCache.json";
  786. JsonUtils::jsonToFile(repositoryCachePath, modStateModel->getRepositoryData());
  787. logGlobal->info("Installing repository: ended");
  788. }
  789. if(!mods.empty())
  790. {
  791. logGlobal->info("Installing mods: started");
  792. installMods(mods);
  793. logGlobal->info("Installing mods: ended");
  794. }
  795. if(!maps.empty())
  796. {
  797. logGlobal->info("Installing maps: started");
  798. installMaps(maps);
  799. logGlobal->info("Installing maps: ended");
  800. }
  801. if(!exe.empty())
  802. {
  803. logGlobal->info("Installing chronicles: started");
  804. ui->progressBar->setFormat(tr("Installing Heroes Chronicles"));
  805. ui->progressWidget->setVisible(true);
  806. ui->abortButton->setEnabled(false);
  807. float prog = 0.0;
  808. auto futureExtract = std::async(std::launch::async, [this, exe, &prog]()
  809. {
  810. ChroniclesExtractor ce(this, [&prog](float progress) { prog = progress; });
  811. ce.installChronicles(exe);
  812. return true;
  813. });
  814. while(futureExtract.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
  815. {
  816. extractionProgress(static_cast<int>(prog * 1000.f), 1000);
  817. qApp->processEvents();
  818. }
  819. if(futureExtract.get())
  820. {
  821. hideProgressBar();
  822. ui->abortButton->setEnabled(true);
  823. ui->progressWidget->setVisible(false);
  824. //update
  825. reload("chronicles");
  826. if (modStateModel->isModExists("chronicles"))
  827. enableModByName("chronicles");
  828. }
  829. logGlobal->info("Installing chronicles: ended");
  830. }
  831. if(!images.empty())
  832. loadScreenshots();
  833. }
  834. void CModListView::installMods(QStringList archives)
  835. {
  836. QStringList modNames;
  837. QStringList modsToEnable;
  838. for(QString archive : archives)
  839. {
  840. // get basename out of full file name
  841. // remove path remove extension
  842. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  843. modNames.push_back(modName);
  844. }
  845. if (!activatingPreset.isEmpty())
  846. {
  847. modStateModel->activatePreset(activatingPreset);
  848. activatingPreset.clear();
  849. }
  850. // uninstall old version of mod, if installed
  851. for(QString mod : modNames)
  852. {
  853. if(modStateModel->isModExists(mod) && modStateModel->getMod(mod).isInstalled())
  854. {
  855. logGlobal->info("Uninstalling old version of mod '%s'", mod.toStdString());
  856. if (modStateModel->isModEnabled(mod))
  857. modsToEnable.push_back(mod);
  858. manager->uninstallMod(mod);
  859. reload(mod);
  860. }
  861. else
  862. {
  863. // installation of previously not present mod -> enable it
  864. modsToEnable.push_back(mod);
  865. }
  866. }
  867. QString lastInstalled;
  868. for(int i = 0; i < modNames.size(); i++)
  869. {
  870. logGlobal->info("Installing mod '%s'", modNames[i].toStdString());
  871. ui->progressBar->setFormat(tr("Installing mod %1").arg(modStateModel->getMod(modNames[i]).getName()));
  872. manager->installMod(modNames[i], archives[i]);
  873. if (i == modNames.size() - 1 && modStateModel->isModExists(modNames[i]))
  874. lastInstalled = modStateModel->getMod(modNames[i]).getID();
  875. }
  876. reload(lastInstalled);
  877. if (!modsToEnable.empty())
  878. {
  879. manager->enableMods(modsToEnable);
  880. }
  881. checkManagerErrors();
  882. for(QString archive : archives)
  883. {
  884. logGlobal->info("Erasing archive '%s'", archive.toStdString());
  885. QFile::remove(archive);
  886. }
  887. }
  888. void CModListView::installMaps(QStringList maps)
  889. {
  890. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  891. int successCount = 0;
  892. QStringList failedMaps;
  893. // Pre-scan maps to count total conflicts (used for Yes to All/No to All)
  894. int conflictCount = 0;
  895. for (const QString& map : maps)
  896. {
  897. if (map.endsWith(".zip", Qt::CaseInsensitive))
  898. {
  899. ZipArchive archive(qstringToPath(map));
  900. for (const auto& file : archive.listFiles())
  901. {
  902. QString name = QString::fromStdString(file);
  903. if (name.endsWith(".h3m", Qt::CaseInsensitive) || name.endsWith(".h3c", Qt::CaseInsensitive) ||
  904. name.endsWith(".vmap", Qt::CaseInsensitive) || name.endsWith(".vcmp", Qt::CaseInsensitive))
  905. {
  906. if (QFile::exists(destDir + name))
  907. conflictCount++;
  908. }
  909. }
  910. }
  911. else
  912. {
  913. QString fileName = map.section('/', -1, -1);
  914. if (QFile::exists(destDir + fileName))
  915. conflictCount++;
  916. }
  917. }
  918. bool applyToAll = false;
  919. bool overwriteAll = false;
  920. auto askOverwrite = [&](const QString& name) -> bool {
  921. if (applyToAll)
  922. return overwriteAll;
  923. QMessageBox msgBox(this);
  924. msgBox.setIcon(QMessageBox::Question);
  925. msgBox.setWindowTitle(tr("Map exists"));
  926. msgBox.setText(tr("Map '%1' already exists. Do you want to overwrite it?").arg(name));
  927. QPushButton* yes = msgBox.addButton(QMessageBox::Yes);
  928. msgBox.addButton(QMessageBox::No);
  929. QPushButton* yesAll = nullptr;
  930. QPushButton* noAll = nullptr;
  931. if (conflictCount > 1)
  932. {
  933. yesAll = msgBox.addButton(tr("Yes to All"), QMessageBox::YesRole);
  934. noAll = msgBox.addButton(tr("No to All"), QMessageBox::NoRole);
  935. }
  936. msgBox.exec();
  937. QAbstractButton* clicked = msgBox.clickedButton();
  938. if (clicked == yes)
  939. return true;
  940. if (clicked == yesAll)
  941. {
  942. applyToAll = true;
  943. overwriteAll = true;
  944. return true;
  945. }
  946. if (clicked == noAll)
  947. {
  948. applyToAll = true;
  949. overwriteAll = false;
  950. return false;
  951. }
  952. return false;
  953. };
  954. // Process each map file and archive
  955. for (const QString& map : maps)
  956. {
  957. if (map.endsWith(".zip", Qt::CaseInsensitive))
  958. {
  959. // ZIP archive
  960. ZipArchive archive(qstringToPath(map));
  961. for (const auto& file : archive.listFiles())
  962. {
  963. QString name = QString::fromStdString(file);
  964. if (!(name.endsWith(".h3m", Qt::CaseInsensitive) || name.endsWith(".h3c", Qt::CaseInsensitive) ||
  965. name.endsWith(".vmap", Qt::CaseInsensitive) || name.endsWith(".vcmp", Qt::CaseInsensitive)))
  966. continue;
  967. QString destFile = destDir + name;
  968. logGlobal->info("Importing map '%s' from ZIP '%s'", name.toStdString(), map.toStdString());
  969. if (QFile::exists(destFile))
  970. {
  971. if (!askOverwrite(name))
  972. {
  973. logGlobal->info("Skipped map '%s'", name.toStdString());
  974. continue;
  975. }
  976. QFile::remove(destFile);
  977. }
  978. if (archive.extract(qstringToPath(destDir), file))
  979. successCount++;
  980. else
  981. {
  982. logGlobal->warn("Failed to extract map '%s'", name.toStdString());
  983. failedMaps.push_back(name);
  984. }
  985. }
  986. }
  987. else
  988. {
  989. // Single map file
  990. QString fileName = map.section('/', -1, -1);
  991. QString destFile = destDir + fileName;
  992. logGlobal->info("Importing map '%s'", map.toStdString());
  993. if (QFile::exists(destFile))
  994. {
  995. if (!askOverwrite(fileName))
  996. {
  997. logGlobal->info("Skipped map '%s'", fileName.toStdString());
  998. continue;
  999. }
  1000. QFile::remove(destFile);
  1001. }
  1002. if (QFile::copy(map, destFile))
  1003. successCount++;
  1004. else
  1005. {
  1006. logGlobal->warn("Failed to copy map '%s'", fileName.toStdString());
  1007. failedMaps.push_back(fileName);
  1008. }
  1009. }
  1010. }
  1011. if (successCount > 0)
  1012. QMessageBox::information(this, tr("Import complete"), tr("%1 map(s) successfully imported.").arg(successCount));
  1013. if (!failedMaps.isEmpty())
  1014. QMessageBox::warning(this, tr("Import failed"), tr("Failed to import the following maps:\n%1").arg(failedMaps.join("\n")));
  1015. }
  1016. void CModListView::on_refreshButton_clicked()
  1017. {
  1018. loadRepositories();
  1019. }
  1020. void CModListView::on_abortButton_clicked()
  1021. {
  1022. delete dlManager;
  1023. dlManager = nullptr;
  1024. hideProgressBar();
  1025. }
  1026. void CModListView::modelReset()
  1027. {
  1028. ui->allModsView->setCurrentIndex(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  1029. }
  1030. void CModListView::checkManagerErrors()
  1031. {
  1032. QString errors = manager->getErrors().join('\n');
  1033. if(errors.size() != 0)
  1034. {
  1035. QString title = tr("Operation failed");
  1036. QString description = tr("Encountered errors:\n") + errors;
  1037. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  1038. }
  1039. }
  1040. void CModListView::on_tabWidget_currentChanged(int index)
  1041. {
  1042. loadScreenshots();
  1043. }
  1044. void CModListView::loadScreenshots()
  1045. {
  1046. if(ui->tabWidget->currentIndex() != 2)
  1047. return;
  1048. assert(ui->allModsView->currentIndex().isValid());
  1049. if (!ui->allModsView->currentIndex().isValid())
  1050. return;
  1051. ui->screenshotsList->clear();
  1052. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  1053. assert(modStateModel->isModExists(modName)); //should be filtered out by check above
  1054. for(QString url : modStateModel->getMod(modName).getScreenshots())
  1055. {
  1056. // URL must be encoded to something else to get rid of symbols illegal in file names
  1057. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  1058. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  1059. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  1060. QPixmap pixmap(fullPath);
  1061. if(pixmap.isNull())
  1062. {
  1063. // image file not exists or corrupted - try to redownload
  1064. downloadFile(fileName, url, tr("screenshots"));
  1065. }
  1066. else
  1067. {
  1068. // managed to load cached image
  1069. QIcon icon(pixmap);
  1070. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  1071. ui->screenshotsList->addItem(item);
  1072. }
  1073. }
  1074. }
  1075. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  1076. {
  1077. if(index.isValid())
  1078. {
  1079. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  1080. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  1081. ImageViewer::showPixmap(pixmap, this);
  1082. }
  1083. }
  1084. void CModListView::doInstallMod(const QString & modName)
  1085. {
  1086. for(const auto & name : getModsToInstall(modName))
  1087. {
  1088. auto mod = modStateModel->getMod(name);
  1089. if(mod.isAvailable())
  1090. downloadMod(mod);
  1091. else if(!modStateModel->isModEnabled(name))
  1092. enableModByName(name);
  1093. }
  1094. }
  1095. void CModListView::doUninstallMod(const QString & modName)
  1096. {
  1097. if(modStateModel->isModExists(modName) && modStateModel->getMod(modName).isInstalled())
  1098. {
  1099. if(modStateModel->isModEnabled(modName))
  1100. manager->disableMod(modName);
  1101. manager->uninstallMod(modName);
  1102. reload(modName);
  1103. }
  1104. }
  1105. bool CModListView::isModAvailable(const QString & modName)
  1106. {
  1107. return modStateModel->isModExists(modName) && !modStateModel->isModInstalled(modName);
  1108. }
  1109. bool CModListView::isModEnabled(const QString & modName)
  1110. {
  1111. return modStateModel->isModEnabled(modName);
  1112. }
  1113. bool CModListView::isModInstalled(const QString & modName)
  1114. {
  1115. auto mod = modStateModel->getMod(modName);
  1116. return mod.isInstalled();
  1117. }
  1118. QStringList CModListView::getInstalledChronicles()
  1119. {
  1120. QStringList result;
  1121. for(const auto & modName : modStateModel->getAllMods())
  1122. {
  1123. auto mod = modStateModel->getMod(modName);
  1124. if (!mod.isInstalled())
  1125. continue;
  1126. if (mod.getTopParentID() != "chronicles")
  1127. continue;
  1128. result += modName;
  1129. }
  1130. return result;
  1131. }
  1132. QStringList CModListView::getUpdateableMods()
  1133. {
  1134. QStringList result;
  1135. for(const auto & modName : modStateModel->getAllMods())
  1136. {
  1137. auto mod = modStateModel->getMod(modName);
  1138. if (!mod.isUpdateAvailable())
  1139. continue;
  1140. QStringList notInstalledDependencies = getModsToInstall(mod.getID());
  1141. QStringList unavailableDependencies = findUnavailableMods(notInstalledDependencies);
  1142. if (unavailableDependencies.empty())
  1143. result.push_back(modName);
  1144. }
  1145. return result;
  1146. }
  1147. QString CModListView::getTranslationModName(const QString & language)
  1148. {
  1149. for(const auto & modName : modStateModel->getAllMods())
  1150. {
  1151. auto mod = modStateModel->getMod(modName);
  1152. if (!mod.isTranslation())
  1153. continue;
  1154. if (mod.getBaseLanguage() != language)
  1155. continue;
  1156. return modName;
  1157. }
  1158. return QString();
  1159. }
  1160. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  1161. {
  1162. if(!index.isValid())
  1163. return;
  1164. auto modName = index.data(ModRoles::ModNameRole).toString();
  1165. auto mod = modStateModel->getMod(modName);
  1166. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  1167. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  1168. if(unavailableDependencies.empty() && mod.isAvailable() && !mod.isSubmod())
  1169. {
  1170. on_installButton_clicked();
  1171. return;
  1172. }
  1173. if(unavailableDependencies.empty() && mod.isUpdateAvailable() && index.column() == ModFields::STATUS_UPDATE)
  1174. {
  1175. on_updateButton_clicked();
  1176. return;
  1177. }
  1178. if(index.column() == ModFields::NAME)
  1179. {
  1180. if(ui->allModsView->isExpanded(index))
  1181. ui->allModsView->collapse(index);
  1182. else
  1183. ui->allModsView->expand(index);
  1184. return;
  1185. }
  1186. if(notInstalledDependencies.empty() && !modStateModel->isModEnabled(modName))
  1187. {
  1188. on_enableButton_clicked();
  1189. return;
  1190. }
  1191. if(modStateModel->isModEnabled(modName))
  1192. {
  1193. on_disableButton_clicked();
  1194. return;
  1195. }
  1196. }
  1197. void CModListView::createNewPreset(const QString & presetName)
  1198. {
  1199. modStateModel->createNewPreset(presetName);
  1200. }
  1201. void CModListView::deletePreset(const QString & presetName)
  1202. {
  1203. modStateModel->deletePreset(presetName);
  1204. }
  1205. void CModListView::activatePreset(const QString & presetName)
  1206. {
  1207. modStateModel->activatePreset(presetName);
  1208. reload();
  1209. }
  1210. void CModListView::renamePreset(const QString & oldPresetName, const QString & newPresetName)
  1211. {
  1212. modStateModel->renamePreset(oldPresetName, newPresetName);
  1213. }
  1214. QStringList CModListView::getAllPresets() const
  1215. {
  1216. return modStateModel->getAllPresets();
  1217. }
  1218. QString CModListView::getActivePreset() const
  1219. {
  1220. return modStateModel->getActivePreset();
  1221. }
  1222. JsonNode CModListView::exportCurrentPreset() const
  1223. {
  1224. return modStateModel->exportCurrentPreset();
  1225. }
  1226. void CModListView::importPreset(const JsonNode & data)
  1227. {
  1228. const auto & [presetName, modList] = modStateModel->importPreset(data);
  1229. if (modList.empty())
  1230. {
  1231. modStateModel->activatePreset(presetName);
  1232. modStateModel->reloadLocalState();
  1233. }
  1234. else
  1235. {
  1236. activatingPreset = presetName;
  1237. for (const auto & modID : modList)
  1238. doInstallMod(modID);
  1239. }
  1240. }