cmodlistview_moc.cpp 43 KB

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