cmodlistview_moc.cpp 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500
  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. }
  860. else
  861. {
  862. // installation of previously not present mod -> enable it
  863. modsToEnable.push_back(mod);
  864. }
  865. }
  866. QString lastInstalled;
  867. for(int i = 0; i < modNames.size(); i++)
  868. {
  869. logGlobal->info("Installing mod '%s'", modNames[i].toStdString());
  870. ui->progressBar->setFormat(tr("Installing mod %1").arg(modStateModel->getMod(modNames[i]).getName()));
  871. manager->installMod(modNames[i], archives[i]);
  872. if (i == modNames.size() - 1 && modStateModel->isModExists(modNames[i]))
  873. lastInstalled = modStateModel->getMod(modNames[i]).getID();
  874. }
  875. reload(lastInstalled);
  876. if (!modsToEnable.empty())
  877. {
  878. manager->enableMods(modsToEnable);
  879. }
  880. checkManagerErrors();
  881. for(QString archive : archives)
  882. {
  883. logGlobal->info("Erasing archive '%s'", archive.toStdString());
  884. QFile::remove(archive);
  885. }
  886. }
  887. void CModListView::installMaps(QStringList maps)
  888. {
  889. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  890. int successCount = 0;
  891. QStringList failedMaps;
  892. // Pre-scan maps to count total conflicts (used for Yes to All/No to All)
  893. int conflictCount = 0;
  894. for (const QString& map : maps)
  895. {
  896. if (map.endsWith(".zip", Qt::CaseInsensitive))
  897. {
  898. ZipArchive archive(qstringToPath(map));
  899. for (const auto& file : archive.listFiles())
  900. {
  901. QString name = QString::fromStdString(file);
  902. if (name.endsWith(".h3m", Qt::CaseInsensitive) || name.endsWith(".h3c", Qt::CaseInsensitive) ||
  903. name.endsWith(".vmap", Qt::CaseInsensitive) || name.endsWith(".vcmp", Qt::CaseInsensitive))
  904. {
  905. if (QFile::exists(destDir + name))
  906. conflictCount++;
  907. }
  908. }
  909. }
  910. else
  911. {
  912. QString fileName = map.section('/', -1, -1);
  913. if (QFile::exists(destDir + fileName))
  914. conflictCount++;
  915. }
  916. }
  917. bool applyToAll = false;
  918. bool overwriteAll = false;
  919. auto askOverwrite = [&](const QString& name) -> bool {
  920. if (applyToAll)
  921. return overwriteAll;
  922. QMessageBox msgBox(this);
  923. msgBox.setIcon(QMessageBox::Question);
  924. msgBox.setWindowTitle(tr("Map exists"));
  925. msgBox.setText(tr("Map '%1' already exists. Do you want to overwrite it?").arg(name));
  926. QPushButton* yes = msgBox.addButton(QMessageBox::Yes);
  927. msgBox.addButton(QMessageBox::No);
  928. QPushButton* yesAll = nullptr;
  929. QPushButton* noAll = nullptr;
  930. if (conflictCount > 1)
  931. {
  932. yesAll = msgBox.addButton(tr("Yes to All"), QMessageBox::YesRole);
  933. noAll = msgBox.addButton(tr("No to All"), QMessageBox::NoRole);
  934. }
  935. msgBox.exec();
  936. QAbstractButton* clicked = msgBox.clickedButton();
  937. if (clicked == yes)
  938. return true;
  939. if (clicked == yesAll)
  940. {
  941. applyToAll = true;
  942. overwriteAll = true;
  943. return true;
  944. }
  945. if (clicked == noAll)
  946. {
  947. applyToAll = true;
  948. overwriteAll = false;
  949. return false;
  950. }
  951. return false;
  952. };
  953. // Process each map file and archive
  954. for (const QString& map : maps)
  955. {
  956. if (map.endsWith(".zip", Qt::CaseInsensitive))
  957. {
  958. // ZIP archive
  959. ZipArchive archive(qstringToPath(map));
  960. for (const auto& file : archive.listFiles())
  961. {
  962. QString name = QString::fromStdString(file);
  963. if (!(name.endsWith(".h3m", Qt::CaseInsensitive) || name.endsWith(".h3c", Qt::CaseInsensitive) ||
  964. name.endsWith(".vmap", Qt::CaseInsensitive) || name.endsWith(".vcmp", Qt::CaseInsensitive)))
  965. continue;
  966. QString destFile = destDir + name;
  967. logGlobal->info("Importing map '%s' from ZIP '%s'", name.toStdString(), map.toStdString());
  968. if (QFile::exists(destFile))
  969. {
  970. if (!askOverwrite(name))
  971. {
  972. logGlobal->info("Skipped map '%s'", name.toStdString());
  973. continue;
  974. }
  975. QFile::remove(destFile);
  976. }
  977. if (archive.extract(qstringToPath(destDir), file))
  978. successCount++;
  979. else
  980. {
  981. logGlobal->warn("Failed to extract map '%s'", name.toStdString());
  982. failedMaps.push_back(name);
  983. }
  984. }
  985. }
  986. else
  987. {
  988. // Single map file
  989. QString fileName = map.section('/', -1, -1);
  990. QString destFile = destDir + fileName;
  991. logGlobal->info("Importing map '%s'", map.toStdString());
  992. if (QFile::exists(destFile))
  993. {
  994. if (!askOverwrite(fileName))
  995. {
  996. logGlobal->info("Skipped map '%s'", fileName.toStdString());
  997. continue;
  998. }
  999. QFile::remove(destFile);
  1000. }
  1001. if (QFile::copy(map, destFile))
  1002. successCount++;
  1003. else
  1004. {
  1005. logGlobal->warn("Failed to copy map '%s'", fileName.toStdString());
  1006. failedMaps.push_back(fileName);
  1007. }
  1008. }
  1009. }
  1010. if (successCount > 0)
  1011. QMessageBox::information(this, tr("Import complete"), tr("%1 map(s) successfully imported.").arg(successCount));
  1012. if (!failedMaps.isEmpty())
  1013. QMessageBox::warning(this, tr("Import failed"), tr("Failed to import the following maps:\n%1").arg(failedMaps.join("\n")));
  1014. }
  1015. void CModListView::on_refreshButton_clicked()
  1016. {
  1017. loadRepositories();
  1018. }
  1019. void CModListView::on_abortButton_clicked()
  1020. {
  1021. delete dlManager;
  1022. dlManager = nullptr;
  1023. hideProgressBar();
  1024. }
  1025. void CModListView::modelReset()
  1026. {
  1027. ui->allModsView->setCurrentIndex(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  1028. }
  1029. void CModListView::checkManagerErrors()
  1030. {
  1031. QString errors = manager->getErrors().join('\n');
  1032. if(errors.size() != 0)
  1033. {
  1034. QString title = tr("Operation failed");
  1035. QString description = tr("Encountered errors:\n") + errors;
  1036. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  1037. }
  1038. }
  1039. void CModListView::on_tabWidget_currentChanged(int index)
  1040. {
  1041. loadScreenshots();
  1042. }
  1043. void CModListView::loadScreenshots()
  1044. {
  1045. if(ui->tabWidget->currentIndex() != 2)
  1046. return;
  1047. assert(ui->allModsView->currentIndex().isValid());
  1048. if (!ui->allModsView->currentIndex().isValid())
  1049. return;
  1050. ui->screenshotsList->clear();
  1051. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  1052. assert(modStateModel->isModExists(modName)); //should be filtered out by check above
  1053. for(QString url : modStateModel->getMod(modName).getScreenshots())
  1054. {
  1055. // URL must be encoded to something else to get rid of symbols illegal in file names
  1056. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  1057. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  1058. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  1059. QPixmap pixmap(fullPath);
  1060. if(pixmap.isNull())
  1061. {
  1062. // image file not exists or corrupted - try to redownload
  1063. downloadFile(fileName, url, tr("screenshots"));
  1064. }
  1065. else
  1066. {
  1067. // managed to load cached image
  1068. QIcon icon(pixmap);
  1069. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  1070. ui->screenshotsList->addItem(item);
  1071. }
  1072. }
  1073. }
  1074. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  1075. {
  1076. if(index.isValid())
  1077. {
  1078. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  1079. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  1080. ImageViewer::showPixmap(pixmap, this);
  1081. }
  1082. }
  1083. void CModListView::doInstallMod(const QString & modName)
  1084. {
  1085. for(const auto & name : getModsToInstall(modName))
  1086. {
  1087. auto mod = modStateModel->getMod(name);
  1088. if(mod.isAvailable())
  1089. downloadMod(mod);
  1090. else if(!modStateModel->isModEnabled(name))
  1091. enableModByName(name);
  1092. }
  1093. }
  1094. void CModListView::doUninstallMod(const QString & modName)
  1095. {
  1096. if(modStateModel->isModExists(modName) && modStateModel->getMod(modName).isInstalled())
  1097. {
  1098. if(modStateModel->isModEnabled(modName))
  1099. manager->disableMod(modName);
  1100. manager->uninstallMod(modName);
  1101. reload();
  1102. }
  1103. }
  1104. bool CModListView::isModAvailable(const QString & modName)
  1105. {
  1106. return modStateModel->isModExists(modName) && !modStateModel->isModInstalled(modName);
  1107. }
  1108. bool CModListView::isModEnabled(const QString & modName)
  1109. {
  1110. return modStateModel->isModEnabled(modName);
  1111. }
  1112. bool CModListView::isModInstalled(const QString & modName)
  1113. {
  1114. auto mod = modStateModel->getMod(modName);
  1115. return mod.isInstalled();
  1116. }
  1117. QStringList CModListView::getInstalledChronicles()
  1118. {
  1119. QStringList result;
  1120. for(const auto & modName : modStateModel->getAllMods())
  1121. {
  1122. auto mod = modStateModel->getMod(modName);
  1123. if (!mod.isInstalled())
  1124. continue;
  1125. if (mod.getTopParentID() != "chronicles")
  1126. continue;
  1127. result += modName;
  1128. }
  1129. return result;
  1130. }
  1131. QStringList CModListView::getUpdateableMods()
  1132. {
  1133. QStringList result;
  1134. for(const auto & modName : modStateModel->getAllMods())
  1135. {
  1136. auto mod = modStateModel->getMod(modName);
  1137. if (!mod.isUpdateAvailable())
  1138. continue;
  1139. QStringList notInstalledDependencies = getModsToInstall(mod.getID());
  1140. QStringList unavailableDependencies = findUnavailableMods(notInstalledDependencies);
  1141. if (unavailableDependencies.empty())
  1142. result.push_back(modName);
  1143. }
  1144. return result;
  1145. }
  1146. QString CModListView::getTranslationModName(const QString & language)
  1147. {
  1148. for(const auto & modName : modStateModel->getAllMods())
  1149. {
  1150. auto mod = modStateModel->getMod(modName);
  1151. if (!mod.isTranslation())
  1152. continue;
  1153. if (mod.getBaseLanguage() != language)
  1154. continue;
  1155. return modName;
  1156. }
  1157. return QString();
  1158. }
  1159. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  1160. {
  1161. if(!index.isValid())
  1162. return;
  1163. auto modName = index.data(ModRoles::ModNameRole).toString();
  1164. auto mod = modStateModel->getMod(modName);
  1165. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  1166. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  1167. if(unavailableDependencies.empty() && mod.isAvailable() && !mod.isSubmod())
  1168. {
  1169. on_installButton_clicked();
  1170. return;
  1171. }
  1172. if(unavailableDependencies.empty() && mod.isUpdateAvailable() && index.column() == ModFields::STATUS_UPDATE)
  1173. {
  1174. on_updateButton_clicked();
  1175. return;
  1176. }
  1177. if(index.column() == ModFields::NAME)
  1178. {
  1179. if(ui->allModsView->isExpanded(index))
  1180. ui->allModsView->collapse(index);
  1181. else
  1182. ui->allModsView->expand(index);
  1183. return;
  1184. }
  1185. if(notInstalledDependencies.empty() && !modStateModel->isModEnabled(modName))
  1186. {
  1187. on_enableButton_clicked();
  1188. return;
  1189. }
  1190. if(modStateModel->isModEnabled(modName))
  1191. {
  1192. on_disableButton_clicked();
  1193. return;
  1194. }
  1195. }
  1196. void CModListView::createNewPreset(const QString & presetName)
  1197. {
  1198. modStateModel->createNewPreset(presetName);
  1199. }
  1200. void CModListView::deletePreset(const QString & presetName)
  1201. {
  1202. modStateModel->deletePreset(presetName);
  1203. }
  1204. void CModListView::activatePreset(const QString & presetName)
  1205. {
  1206. modStateModel->activatePreset(presetName);
  1207. reload();
  1208. }
  1209. void CModListView::renamePreset(const QString & oldPresetName, const QString & newPresetName)
  1210. {
  1211. modStateModel->renamePreset(oldPresetName, newPresetName);
  1212. }
  1213. QStringList CModListView::getAllPresets() const
  1214. {
  1215. return modStateModel->getAllPresets();
  1216. }
  1217. QString CModListView::getActivePreset() const
  1218. {
  1219. return modStateModel->getActivePreset();
  1220. }
  1221. JsonNode CModListView::exportCurrentPreset() const
  1222. {
  1223. return modStateModel->exportCurrentPreset();
  1224. }
  1225. void CModListView::importPreset(const JsonNode & data)
  1226. {
  1227. const auto & [presetName, modList] = modStateModel->importPreset(data);
  1228. if (modList.empty())
  1229. {
  1230. modStateModel->activatePreset(presetName);
  1231. modStateModel->reloadLocalState();
  1232. }
  1233. else
  1234. {
  1235. activatingPreset = presetName;
  1236. for (const auto & modID : modList)
  1237. doInstallMod(modID);
  1238. }
  1239. }