cmodlistview_moc.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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/VCMIDirs.h"
  28. #include "../../lib/CConfigHandler.h"
  29. #include "../../lib/texts/Languages.h"
  30. #include "../../lib/modding/CModVersion.h"
  31. #include "../../lib/filesystem/Filesystem.h"
  32. #include "../../lib/texts/CGeneralTextHandler.h"
  33. #include <future>
  34. void CModListView::setupModModel()
  35. {
  36. static const QString repositoryCachePath = CLauncherDirs::downloadsPath() + "/repositoryCache.json";
  37. const auto &cachedRepositoryData = JsonUtils::jsonFromFile(repositoryCachePath);
  38. modStateModel = std::make_shared<ModStateModel>();
  39. if (!cachedRepositoryData.isNull())
  40. modStateModel->appendRepositories(cachedRepositoryData);
  41. modModel = new ModStateItemModel(modStateModel, this);
  42. manager = std::make_unique<ModStateController>(modStateModel);
  43. }
  44. void CModListView::changeEvent(QEvent *event)
  45. {
  46. if(event->type() == QEvent::LanguageChange)
  47. {
  48. ui->retranslateUi(this);
  49. modModel->reloadRepositories();
  50. }
  51. QWidget::changeEvent(event);
  52. }
  53. void CModListView::setupFilterModel()
  54. {
  55. filterModel = new CModFilterModel(modModel, this);
  56. filterModel->setFilterKeyColumn(-1); // filter across all columns
  57. filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); // to make it more user-friendly
  58. filterModel->setDynamicSortFilter(true);
  59. }
  60. void CModListView::setupModsView()
  61. {
  62. ui->allModsView->setModel(filterModel);
  63. // input data is not sorted - sort it before display
  64. ui->allModsView->sortByColumn(ModFields::TYPE, Qt::AscendingOrder);
  65. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_ENABLED, QHeaderView::Fixed);
  66. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_UPDATE, QHeaderView::Fixed);
  67. QSettings s(Ui::teamName, Ui::appName);
  68. auto state = s.value("AllModsView/State").toByteArray();
  69. if(!state.isNull()) //read last saved settings
  70. {
  71. ui->allModsView->header()->restoreState(state);
  72. }
  73. else //default //TODO: default high-DPI scaling
  74. {
  75. ui->allModsView->setColumnWidth(ModFields::NAME, 220);
  76. ui->allModsView->setColumnWidth(ModFields::TYPE, 75);
  77. }
  78. ui->allModsView->resizeColumnToContents(ModFields::STATUS_ENABLED);
  79. ui->allModsView->resizeColumnToContents(ModFields::STATUS_UPDATE);
  80. ui->allModsView->setUniformRowHeights(true);
  81. connect(ui->allModsView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&,const QModelIndex&)),
  82. this, SLOT(modSelected(const QModelIndex&,const QModelIndex&)));
  83. connect(filterModel, SIGNAL(modelReset()),
  84. this, SLOT(modelReset()));
  85. connect(modModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
  86. this, SLOT(dataChanged(QModelIndex,QModelIndex)));
  87. }
  88. CModListView::CModListView(QWidget * parent)
  89. : QWidget(parent)
  90. , ui(new Ui::CModListView)
  91. {
  92. ui->setupUi(this);
  93. ui->uninstallButton->setIcon(QIcon{":/icons/mod-delete.png"});
  94. ui->enableButton->setIcon(QIcon{":/icons/mod-enabled.png"});
  95. ui->disableButton->setIcon(QIcon{":/icons/mod-disabled.png"});
  96. ui->updateButton->setIcon(QIcon{":/icons/mod-update.png"});
  97. ui->installButton->setIcon(QIcon{":/icons/mod-download.png"});
  98. ui->splitter->setStyleSheet("QSplitter::handle {background: palette('window');}");
  99. disableModInfo();
  100. setupModModel();
  101. setupFilterModel();
  102. setupModsView();
  103. ui->progressWidget->setVisible(false);
  104. dlManager = nullptr;
  105. modModel->reloadRepositories();
  106. if(settings["launcher"]["autoCheckRepositories"].Bool())
  107. loadRepositories();
  108. #ifdef VCMI_MOBILE
  109. for(auto * scrollWidget : {
  110. (QAbstractItemView*)ui->allModsView,
  111. (QAbstractItemView*)ui->screenshotsList})
  112. {
  113. Helper::enableScrollBySwiping(scrollWidget);
  114. scrollWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
  115. scrollWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  116. }
  117. #endif
  118. }
  119. void CModListView::reload()
  120. {
  121. modStateModel->reloadLocalState();
  122. modModel->reloadRepositories();
  123. }
  124. void CModListView::loadRepositories()
  125. {
  126. QStringList repositories;
  127. if (settings["launcher"]["defaultRepositoryEnabled"].Bool())
  128. repositories.push_back(QString::fromStdString(settings["launcher"]["defaultRepositoryURL"].String()));
  129. if (settings["launcher"]["extraRepositoryEnabled"].Bool())
  130. repositories.push_back(QString::fromStdString(settings["launcher"]["extraRepositoryURL"].String()));
  131. for(const auto & entry : repositories)
  132. {
  133. if (entry.isEmpty())
  134. continue;
  135. // URL must be encoded to something else to get rid of symbols illegal in file names
  136. auto hashed = QCryptographicHash::hash(entry.toUtf8(), QCryptographicHash::Md5);
  137. auto hashedStr = QString::fromUtf8(hashed.toHex());
  138. downloadFile(hashedStr + ".json", entry, tr("mods repository index"));
  139. }
  140. }
  141. CModListView::~CModListView()
  142. {
  143. QSettings s(Ui::teamName, Ui::appName);
  144. s.setValue("AllModsView/State", ui->allModsView->header()->saveState());
  145. delete ui;
  146. }
  147. static QString replaceIfNotEmpty(QVariant value, QString pattern)
  148. {
  149. if(value.canConvert<QString>())
  150. {
  151. if (value.toString().isEmpty())
  152. return "";
  153. else
  154. return pattern.arg(value.toString());
  155. }
  156. if(value.canConvert<QStringList>())
  157. {
  158. if (value.toStringList().isEmpty())
  159. return "";
  160. else
  161. return pattern.arg(value.toStringList().join(", "));
  162. }
  163. // all valid types of data should have been filtered by code above
  164. assert(!value.isValid());
  165. return "";
  166. }
  167. static QString replaceIfNotEmpty(QStringList value, QString pattern)
  168. {
  169. if(!value.empty())
  170. return pattern.arg(value.join(", "));
  171. return "";
  172. }
  173. QString CModListView::genChangelogText(const ModState & mod)
  174. {
  175. QString headerTemplate = "<p><span style=\" font-weight:600;\">%1: </span></p>";
  176. QString entryBegin = "<p align=\"justify\"><ul>";
  177. QString entryEnd = "</ul></p>";
  178. QString entryLine = "<li>%1</li>";
  179. //QString versionSeparator = "<hr/>";
  180. QString result;
  181. QMap<QString, QStringList> changelog = mod.getChangelog();
  182. QList<QString> versions = changelog.keys();
  183. std::sort(versions.begin(), versions.end(), [](QString lesser, QString greater)
  184. {
  185. return CModVersion::fromString(lesser.toStdString()) < CModVersion::fromString(greater.toStdString());
  186. });
  187. std::reverse(versions.begin(), versions.end());
  188. for(const auto & version : versions)
  189. {
  190. result += headerTemplate.arg(version);
  191. result += entryBegin;
  192. for(const auto & line : changelog.value(version))
  193. result += entryLine.arg(line);
  194. result += entryEnd;
  195. }
  196. return result;
  197. }
  198. QStringList CModListView::getModNames(QString queryingModID, QStringList input)
  199. {
  200. QStringList result;
  201. auto queryingMod = modStateModel->getMod(queryingModID);
  202. for(const auto & modID : input)
  203. {
  204. if (modStateModel->isModExists(modID) && modStateModel->getMod(modID).isHidden())
  205. continue;
  206. QString parentModID = modStateModel->getTopParent(modID);
  207. QString displayName;
  208. if (modStateModel->isSubmod(modID) && queryingMod.getParentID() != parentModID )
  209. {
  210. // show in form "parent mod (submod)"
  211. QString parentDisplayName = parentModID;
  212. QString submodDisplayName = modID;
  213. if (modStateModel->isModExists(parentModID))
  214. parentDisplayName = modStateModel->getMod(parentModID).getName();
  215. if (modStateModel->isModExists(modID))
  216. submodDisplayName = modStateModel->getMod(modID).getName();
  217. displayName = QString("%1 (%2)").arg(submodDisplayName, parentDisplayName);
  218. }
  219. else
  220. {
  221. // show simply as mod name
  222. displayName = modID;
  223. if (modStateModel->isModExists(modID))
  224. displayName = modStateModel->getMod(modID).getName();
  225. }
  226. result += displayName;
  227. }
  228. return result;
  229. }
  230. QString CModListView::genModInfoText(const ModState & mod)
  231. {
  232. QString prefix = "<p><span style=\" font-weight:600;\">%1: </span>"; // shared prefix
  233. QString redPrefix = "<p><span style=\" font-weight:600; color:red\">%1: </span>"; // shared prefix
  234. QString lineTemplate = prefix + "%2</p>";
  235. QString urlTemplate = prefix + "<a href=\"%2\">%3</a></p>";
  236. QString textTemplate = prefix + "</p><p align=\"justify\">%2</p>";
  237. QString listTemplate = "<p align=\"justify\">%1: %2</p>";
  238. QString noteTemplate = "<p align=\"justify\">%1</p>";
  239. QString incompatibleString = redPrefix + tr("Mod is incompatible") + "</p>";
  240. QString supportedVersions = redPrefix + "%2 %3 %4</p>";
  241. QString result;
  242. result += replaceIfNotEmpty(mod.getName(), lineTemplate.arg(tr("Mod name")));
  243. if (mod.isUpdateAvailable())
  244. {
  245. result += replaceIfNotEmpty(mod.getInstalledVersion(), lineTemplate.arg(tr("Installed version")));
  246. result += replaceIfNotEmpty(mod.getRepositoryVersion(), lineTemplate.arg(tr("Latest version")));
  247. }
  248. else
  249. {
  250. if (mod.isInstalled())
  251. result += replaceIfNotEmpty(mod.getInstalledVersion(), lineTemplate.arg(tr("Installed version")));
  252. else
  253. result += replaceIfNotEmpty(mod.getRepositoryVersion(), lineTemplate.arg(tr("Latest version")));
  254. }
  255. if (mod.isInstalled())
  256. result += replaceIfNotEmpty(modStateModel->getInstalledModSizeFormatted(mod.getID()), lineTemplate.arg(tr("Size")));
  257. if((!mod.isInstalled() || mod.isUpdateAvailable()) && !mod.getDownloadSizeFormatted().isEmpty())
  258. result += replaceIfNotEmpty(mod.getDownloadSizeFormatted(), lineTemplate.arg(tr("Download size")));
  259. result += replaceIfNotEmpty(mod.getAuthors(), lineTemplate.arg(tr("Authors")));
  260. if(!mod.getLicenseName().isEmpty())
  261. result += urlTemplate.arg(tr("License")).arg(mod.getLicenseUrl()).arg(mod.getLicenseName());
  262. if(!mod.getContact().isEmpty())
  263. result += urlTemplate.arg(tr("Contact")).arg(mod.getContact()).arg(mod.getContact());
  264. //compatibility info
  265. if(!mod.isCompatible())
  266. {
  267. auto compatibilityInfo = mod.getCompatibleVersionRange();
  268. auto minStr = compatibilityInfo.first;
  269. auto maxStr = compatibilityInfo.second;
  270. result += incompatibleString.arg(tr("Compatibility"));
  271. if(minStr == maxStr)
  272. result += supportedVersions.arg(tr("Required VCMI version"), minStr, "", "");
  273. else
  274. {
  275. if(minStr.isEmpty() || maxStr.isEmpty())
  276. {
  277. if(minStr.isEmpty())
  278. result += supportedVersions.arg(tr("Supported VCMI version"), maxStr, ", ", tr("please upgrade mod"));
  279. else
  280. result += supportedVersions.arg(tr("Required VCMI version"), minStr, " ", tr("or newer"));
  281. }
  282. else
  283. result += supportedVersions.arg(tr("Supported VCMI versions"), minStr, " - ", maxStr);
  284. }
  285. }
  286. QVariant baseLanguageVariant = mod.getBaseLanguage();
  287. QString baseLanguageID = baseLanguageVariant.isValid() ? baseLanguageVariant.toString() : "english";
  288. QStringList supportedLanguages = mod.getSupportedLanguages();
  289. if(supportedLanguages.size() > 1)
  290. {
  291. QStringList supportedLanguagesTranslated;
  292. for (const auto & languageID : supportedLanguages)
  293. supportedLanguagesTranslated += QApplication::translate("Language", Languages::getLanguageOptions(languageID.toStdString()).nameEnglish.c_str());
  294. result += replaceIfNotEmpty(supportedLanguagesTranslated, lineTemplate.arg(tr("Languages")));
  295. }
  296. QStringList conflicts = mod.getConflicts();
  297. for (const auto & otherMod : modStateModel->getAllMods())
  298. {
  299. QStringList otherConflicts = modStateModel->getMod(otherMod).getConflicts();
  300. if (otherConflicts.contains(mod.getID()) && !conflicts.contains(otherMod))
  301. conflicts.push_back(otherMod);
  302. }
  303. result += replaceIfNotEmpty(getModNames(mod.getID(), mod.getDependencies()), lineTemplate.arg(tr("Required mods")));
  304. result += replaceIfNotEmpty(getModNames(mod.getID(), conflicts), lineTemplate.arg(tr("Conflicting mods")));
  305. result += replaceIfNotEmpty(mod.getDescription(), textTemplate.arg(tr("Description")));
  306. result += "<p></p>"; // to get some empty space
  307. QString translationMismatch = tr("This mod cannot be enabled because it translates into a different language.");
  308. QString notInstalledDeps = tr("This mod can not be enabled because the following dependencies are not present");
  309. QString unavailableDeps = tr("This mod can not be installed because the following dependencies are not present");
  310. QString thisIsSubmod = tr("This is a submod and it cannot be installed or uninstalled separately from its parent mod");
  311. QString notes;
  312. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  313. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  314. if (mod.isInstalled())
  315. notes += replaceIfNotEmpty(getModNames(mod.getID(), notInstalledDependencies), listTemplate.arg(notInstalledDeps));
  316. else
  317. notes += replaceIfNotEmpty(getModNames(mod.getID(), unavailableDependencies), listTemplate.arg(unavailableDeps));
  318. if(mod.isSubmod())
  319. notes += noteTemplate.arg(thisIsSubmod);
  320. if (mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage().toStdString())
  321. notes += noteTemplate.arg(translationMismatch);
  322. if(notes.size())
  323. result += textTemplate.arg(tr("Notes")).arg(notes);
  324. return result;
  325. }
  326. void CModListView::disableModInfo()
  327. {
  328. ui->disableButton->setVisible(false);
  329. ui->enableButton->setVisible(false);
  330. ui->installButton->setVisible(false);
  331. ui->uninstallButton->setVisible(false);
  332. ui->updateButton->setVisible(false);
  333. }
  334. void CModListView::dataChanged(const QModelIndex & topleft, const QModelIndex & bottomRight)
  335. {
  336. selectMod(ui->allModsView->currentIndex());
  337. }
  338. void CModListView::selectMod(const QModelIndex & index)
  339. {
  340. ui->tabWidget->setCurrentIndex(0);
  341. if(!index.isValid())
  342. {
  343. disableModInfo();
  344. }
  345. else
  346. {
  347. const auto modName = index.data(ModRoles::ModNameRole).toString();
  348. auto mod = modStateModel->getMod(modName);
  349. ui->tabWidget->setTabEnabled(1, !mod.getChangelog().isEmpty());
  350. ui->tabWidget->setTabEnabled(2, !mod.getScreenshots().isEmpty());
  351. ui->modInfoBrowser->setHtml(genModInfoText(mod));
  352. ui->changelogBrowser->setHtml(genChangelogText(mod));
  353. Helper::enableScrollBySwiping(ui->modInfoBrowser);
  354. Helper::enableScrollBySwiping(ui->changelogBrowser);
  355. QStringList notInstalledDependencies = this->getModsToInstall(modName);
  356. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  357. bool translationMismatch = mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage().toStdString();
  358. ui->disableButton->setVisible(modStateModel->isModInstalled(mod.getID()) && modStateModel->isModEnabled(mod.getID()));
  359. ui->enableButton->setVisible(modStateModel->isModInstalled(mod.getID()) && !modStateModel->isModEnabled(mod.getID()));
  360. ui->installButton->setVisible(mod.isAvailable() && !mod.isSubmod());
  361. ui->uninstallButton->setVisible(mod.isInstalled() && !mod.isSubmod());
  362. ui->updateButton->setVisible(mod.isUpdateAvailable());
  363. // Block buttons if action is not allowed at this time
  364. ui->disableButton->setEnabled(true);
  365. ui->enableButton->setEnabled(notInstalledDependencies.empty() && !translationMismatch);
  366. ui->installButton->setEnabled(unavailableDependencies.empty());
  367. ui->uninstallButton->setEnabled(true);
  368. ui->updateButton->setEnabled(unavailableDependencies.empty());
  369. loadScreenshots();
  370. }
  371. }
  372. void CModListView::modSelected(const QModelIndex & current, const QModelIndex &)
  373. {
  374. selectMod(current);
  375. }
  376. void CModListView::on_allModsView_activated(const QModelIndex & index)
  377. {
  378. selectMod(index);
  379. loadScreenshots();
  380. }
  381. void CModListView::on_lineEdit_textChanged(const QString & arg1)
  382. {
  383. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  384. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1, QRegularExpression::UnanchoredWildcardConversion);
  385. #else
  386. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1);
  387. //Hack due to lack QRegularExpression::UnanchoredWildcardConversion in Qt5
  388. baseStr.chop(3);
  389. baseStr.remove(0,5);
  390. #endif
  391. QRegularExpression regExp{baseStr, QRegularExpression::CaseInsensitiveOption};
  392. filterModel->setFilterRegularExpression(regExp);
  393. }
  394. void CModListView::on_comboBox_currentIndexChanged(int index)
  395. {
  396. auto enumIndex = static_cast<ModFilterMask>(index);
  397. filterModel->setTypeFilter(enumIndex);
  398. }
  399. QStringList CModListView::findUnavailableMods(QStringList candidates)
  400. {
  401. QStringList invalidMods;
  402. for(QString modName : candidates)
  403. {
  404. if(!modStateModel->isModExists(modName))
  405. invalidMods.push_back(modName);
  406. }
  407. return invalidMods;
  408. }
  409. void CModListView::on_enableButton_clicked()
  410. {
  411. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  412. enableModByName(modName);
  413. checkManagerErrors();
  414. }
  415. void CModListView::enableModByName(QString modName)
  416. {
  417. manager->enableMods({modName});
  418. modModel->modChanged(modName);
  419. }
  420. void CModListView::on_disableButton_clicked()
  421. {
  422. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  423. disableModByName(modName);
  424. checkManagerErrors();
  425. }
  426. void CModListView::disableModByName(QString modName)
  427. {
  428. manager->disableMod(modName);
  429. modModel->modChanged(modName);
  430. }
  431. QStringList CModListView::getModsToInstall(QString mod)
  432. {
  433. QStringList result;
  434. QStringList candidates;
  435. QStringList processed;
  436. candidates.push_back(mod);
  437. while (!candidates.empty())
  438. {
  439. QString potentialToInstall = candidates.back();
  440. candidates.pop_back();
  441. processed.push_back(potentialToInstall);
  442. if (modStateModel->isModExists(potentialToInstall) && modStateModel->isModInstalled(potentialToInstall))
  443. continue;
  444. if (modStateModel->isSubmod(potentialToInstall))
  445. {
  446. QString topParent = modStateModel->getTopParent(potentialToInstall);
  447. if (modStateModel->isModInstalled(topParent))
  448. {
  449. if (modStateModel->isModUpdateAvailable(topParent))
  450. potentialToInstall = modStateModel->getTopParent(potentialToInstall);
  451. // else - potentially broken mod that depends on non-existing submod
  452. }
  453. else
  454. potentialToInstall = modStateModel->getTopParent(potentialToInstall);
  455. }
  456. result.push_back(potentialToInstall);
  457. if (modStateModel->isModExists(potentialToInstall))
  458. {
  459. QStringList dependencies = modStateModel->getMod(potentialToInstall).getDependencies();
  460. for (const auto & dependency : dependencies)
  461. {
  462. if (!processed.contains(dependency) && !candidates.contains(dependency))
  463. candidates.push_back(dependency);
  464. }
  465. }
  466. }
  467. result.removeDuplicates();
  468. return result;
  469. }
  470. void CModListView::on_updateButton_clicked()
  471. {
  472. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  473. doUpdateMod(modName);
  474. }
  475. void CModListView::doUpdateMod(const QString & modName)
  476. {
  477. auto targetMod = modStateModel->getMod(modName);
  478. if(targetMod.isUpdateAvailable())
  479. downloadFile(modName + ".zip", targetMod.getDownloadUrl(), modName, targetMod.getDownloadSizeBytes());
  480. for(const auto & name : getModsToInstall(modName))
  481. {
  482. auto mod = modStateModel->getMod(name);
  483. // update required mod, install missing (can be new dependency)
  484. if(mod.isUpdateAvailable() || !mod.isInstalled())
  485. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeBytes());
  486. }
  487. }
  488. void CModListView::on_uninstallButton_clicked()
  489. {
  490. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  491. if(modStateModel->isModExists(modName) && modStateModel->getMod(modName).isInstalled())
  492. {
  493. if(modStateModel->isModEnabled(modName))
  494. manager->disableMod(modName);
  495. manager->uninstallMod(modName);
  496. modModel->reloadRepositories();
  497. }
  498. checkManagerErrors();
  499. }
  500. void CModListView::on_installButton_clicked()
  501. {
  502. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  503. for(const auto & name : getModsToInstall(modName))
  504. {
  505. auto mod = modStateModel->getMod(name);
  506. if(mod.isAvailable())
  507. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeBytes());
  508. else if(!modStateModel->isModEnabled(name))
  509. enableModByName(name);
  510. }
  511. }
  512. void CModListView::downloadFile(QString file, QUrl url, QString description, qint64 sizeBytes)
  513. {
  514. if(!dlManager)
  515. {
  516. dlManager = new CDownloadManager();
  517. ui->progressWidget->setVisible(true);
  518. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  519. this, SLOT(downloadProgress(qint64,qint64)));
  520. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  521. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  522. connect(manager.get(), SIGNAL(extractionProgress(qint64,qint64)),
  523. this, SLOT(extractionProgress(qint64,qint64)));
  524. connect(modModel, &ModStateItemModel::dataChanged, filterModel, &QAbstractItemModel::dataChanged);
  525. const auto progressBarFormat = tr("Downloading %1. %p% (%v MB out of %m MB) finished").arg(description);
  526. ui->progressBar->setFormat(progressBarFormat);
  527. }
  528. dlManager->downloadFile(url, file, sizeBytes);
  529. }
  530. void CModListView::downloadProgress(qint64 current, qint64 max)
  531. {
  532. // display progress, in megabytes
  533. ui->progressBar->setVisible(true);
  534. ui->progressBar->setMaximum(max / (1024 * 1024));
  535. ui->progressBar->setValue(current / (1024 * 1024));
  536. }
  537. void CModListView::extractionProgress(qint64 current, qint64 max)
  538. {
  539. // display progress, in extracted files
  540. ui->progressBar->setVisible(true);
  541. ui->progressBar->setMaximum(max);
  542. ui->progressBar->setValue(current);
  543. }
  544. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  545. {
  546. QString title = tr("Download failed");
  547. QString firstLine = tr("Unable to download all files.\n\nEncountered errors:\n\n");
  548. QString lastLine = tr("\n\nInstall successfully downloaded?");
  549. bool doInstallFiles = false;
  550. // if all files were d/loaded there should be no errors. And on failure there must be an error
  551. assert(failedFiles.empty() == errors.empty());
  552. if(savedFiles.empty())
  553. {
  554. // no successfully downloaded mods
  555. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  556. }
  557. else if(!failedFiles.empty())
  558. {
  559. // some mods were not downloaded
  560. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  561. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  562. if(result == QMessageBox::Yes)
  563. doInstallFiles = true;
  564. }
  565. else
  566. {
  567. // everything OK
  568. doInstallFiles = true;
  569. }
  570. dlManager->deleteLater();
  571. dlManager = nullptr;
  572. ui->progressBar->setMaximum(0);
  573. ui->progressBar->setValue(0);
  574. if(doInstallFiles)
  575. installFiles(savedFiles);
  576. hideProgressBar();
  577. }
  578. void CModListView::hideProgressBar()
  579. {
  580. if(dlManager == nullptr) // it was not recreated meanwhile
  581. {
  582. ui->progressWidget->setVisible(false);
  583. ui->progressBar->setMaximum(0);
  584. ui->progressBar->setValue(0);
  585. }
  586. }
  587. void CModListView::installFiles(QStringList files)
  588. {
  589. QStringList mods;
  590. QStringList maps;
  591. QStringList images;
  592. QStringList exe;
  593. JsonNode repository;
  594. // TODO: some better way to separate zip's with mods and downloaded repository files
  595. for(QString filename : files)
  596. {
  597. if(filename.endsWith(".zip", Qt::CaseInsensitive))
  598. mods.push_back(filename);
  599. else if(filename.endsWith(".h3m", Qt::CaseInsensitive) || filename.endsWith(".h3c", Qt::CaseInsensitive) || filename.endsWith(".vmap", Qt::CaseInsensitive) || filename.endsWith(".vcmp", Qt::CaseInsensitive))
  600. maps.push_back(filename);
  601. if(filename.endsWith(".exe", Qt::CaseInsensitive))
  602. exe.push_back(filename);
  603. else if(filename.endsWith(".json", Qt::CaseInsensitive))
  604. {
  605. //download and merge additional files
  606. const auto &repoData = JsonUtils::jsonFromFile(filename);
  607. if(repoData["name"].isNull())
  608. {
  609. // This is main repository index. Download all referenced mods
  610. for(const auto & [modName, modJson] : repoData.Struct())
  611. {
  612. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  613. auto modJsonUrl = modJson["mod"];
  614. if(!modJsonUrl.isNull())
  615. downloadFile(QString::fromStdString(modName + ".json"), QString::fromStdString(modJsonUrl.String()), tr("mods repository index"));
  616. repository[modNameLower] = modJson;
  617. }
  618. }
  619. else
  620. {
  621. // This is json of a single mod. Extract name of mod and add it to repo
  622. auto modName = QFileInfo(filename).baseName().toStdString();
  623. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  624. repository[modNameLower] = repoData;
  625. }
  626. }
  627. else if(filename.endsWith(".png", Qt::CaseInsensitive))
  628. images.push_back(filename);
  629. }
  630. if (!repository.isNull())
  631. {
  632. manager->appendRepositories(repository);
  633. modModel->reloadRepositories();
  634. static const QString repositoryCachePath = CLauncherDirs::downloadsPath() + "/repositoryCache.json";
  635. JsonUtils::jsonToFile(repositoryCachePath, modStateModel->getRepositoryData());
  636. }
  637. if(!mods.empty())
  638. {
  639. installMods(mods);
  640. modStateModel->reloadLocalState();
  641. modModel->reloadRepositories();
  642. }
  643. if(!maps.empty())
  644. installMaps(maps);
  645. if(!exe.empty())
  646. {
  647. ui->progressWidget->setVisible(true);
  648. ui->pushButton->setEnabled(false);
  649. ui->progressBar->setFormat(tr("Installing chronicles"));
  650. float prog = 0.0;
  651. auto futureExtract = std::async(std::launch::async, [this, exe, &prog]()
  652. {
  653. ChroniclesExtractor ce(this, [&prog](float progress) { prog = progress; });
  654. ce.installChronicles(exe);
  655. return true;
  656. });
  657. while(futureExtract.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
  658. {
  659. emit extractionProgress(static_cast<int>(prog * 1000.f), 1000);
  660. qApp->processEvents();
  661. }
  662. if(futureExtract.get())
  663. {
  664. hideProgressBar();
  665. ui->pushButton->setEnabled(true);
  666. ui->progressWidget->setVisible(false);
  667. //update
  668. modStateModel->reloadLocalState();
  669. modModel->reloadRepositories();
  670. }
  671. }
  672. if(!images.empty())
  673. loadScreenshots();
  674. }
  675. void CModListView::installMods(QStringList archives)
  676. {
  677. QStringList modNames;
  678. QStringList modsToEnable;
  679. for(QString archive : archives)
  680. {
  681. // get basename out of full file name
  682. // remove path remove extension
  683. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  684. modNames.push_back(modName);
  685. }
  686. // uninstall old version of mod, if installed
  687. for(QString mod : modNames)
  688. {
  689. if(modStateModel->getMod(mod).isInstalled())
  690. {
  691. if (modStateModel->isModEnabled(mod))
  692. modsToEnable.push_back(mod);
  693. manager->uninstallMod(mod);
  694. }
  695. else
  696. {
  697. // installation of previously not present mod -> enable it
  698. modsToEnable.push_back(mod);
  699. }
  700. }
  701. for(int i = 0; i < modNames.size(); i++)
  702. {
  703. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  704. manager->installMod(modNames[i], archives[i]);
  705. }
  706. if (!modsToEnable.empty())
  707. manager->enableMods(modsToEnable);
  708. checkManagerErrors();
  709. for(QString archive : archives)
  710. QFile::remove(archive);
  711. }
  712. void CModListView::installMaps(QStringList maps)
  713. {
  714. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  715. for(QString map : maps)
  716. {
  717. QFile(map).rename(destDir + map.section('/', -1, -1));
  718. }
  719. }
  720. void CModListView::on_refreshButton_clicked()
  721. {
  722. loadRepositories();
  723. }
  724. void CModListView::on_pushButton_clicked()
  725. {
  726. delete dlManager;
  727. dlManager = nullptr;
  728. hideProgressBar();
  729. }
  730. void CModListView::modelReset()
  731. {
  732. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  733. }
  734. void CModListView::checkManagerErrors()
  735. {
  736. QString errors = manager->getErrors().join('\n');
  737. if(errors.size() != 0)
  738. {
  739. QString title = tr("Operation failed");
  740. QString description = tr("Encountered errors:\n") + errors;
  741. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  742. }
  743. }
  744. void CModListView::on_tabWidget_currentChanged(int index)
  745. {
  746. loadScreenshots();
  747. }
  748. void CModListView::loadScreenshots()
  749. {
  750. if(ui->tabWidget->currentIndex() == 2)
  751. {
  752. if(!ui->allModsView->currentIndex().isValid())
  753. {
  754. // select the first mod, so we can access its data
  755. ui->allModsView->setCurrentIndex(filterModel->index(0, 0));
  756. }
  757. ui->screenshotsList->clear();
  758. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  759. assert(modStateModel->isModExists(modName)); //should be filtered out by check above
  760. for(QString url : modStateModel->getMod(modName).getScreenshots())
  761. {
  762. // URL must be encoded to something else to get rid of symbols illegal in file names
  763. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  764. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  765. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  766. QPixmap pixmap(fullPath);
  767. if(pixmap.isNull())
  768. {
  769. // image file not exists or corrupted - try to redownload
  770. downloadFile(fileName, url, tr("screenshots"));
  771. }
  772. else
  773. {
  774. // managed to load cached image
  775. QIcon icon(pixmap);
  776. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  777. ui->screenshotsList->addItem(item);
  778. }
  779. }
  780. }
  781. }
  782. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  783. {
  784. if(index.isValid())
  785. {
  786. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  787. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  788. ImageViewer::showPixmap(pixmap, this);
  789. }
  790. }
  791. void CModListView::doInstallMod(const QString & modName)
  792. {
  793. for(const auto & name : modStateModel->getMod(modName).getDependencies())
  794. {
  795. auto mod = modStateModel->getMod(name);
  796. if(!mod.isInstalled())
  797. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeBytes());
  798. }
  799. }
  800. bool CModListView::isModAvailable(const QString & modName)
  801. {
  802. return !modStateModel->isModInstalled(modName);
  803. }
  804. bool CModListView::isModEnabled(const QString & modName)
  805. {
  806. return modStateModel->isModEnabled(modName);
  807. }
  808. bool CModListView::isModInstalled(const QString & modName)
  809. {
  810. auto mod = modStateModel->getMod(modName);
  811. return mod.isInstalled();
  812. }
  813. QStringList CModListView::getInstalledChronicles()
  814. {
  815. QStringList result;
  816. for(const auto & modName : modStateModel->getAllMods())
  817. {
  818. auto mod = modStateModel->getMod(modName);
  819. if (!mod.isInstalled())
  820. continue;
  821. if (mod.getTopParentID() != "chronicles")
  822. continue;
  823. result += modName;
  824. }
  825. return result;
  826. }
  827. QStringList CModListView::getUpdateableMods()
  828. {
  829. QStringList result;
  830. for(const auto & modName : modStateModel->getAllMods())
  831. {
  832. auto mod = modStateModel->getMod(modName);
  833. if (mod.isUpdateAvailable())
  834. result.push_back(modName);
  835. }
  836. return result;
  837. }
  838. QString CModListView::getTranslationModName(const QString & language)
  839. {
  840. for(const auto & modName : modStateModel->getAllMods())
  841. {
  842. auto mod = modStateModel->getMod(modName);
  843. if (!mod.isTranslation())
  844. continue;
  845. if (mod.getBaseLanguage() != language)
  846. continue;
  847. return modName;
  848. }
  849. return QString();
  850. }
  851. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  852. {
  853. if(!index.isValid())
  854. return;
  855. auto modName = index.data(ModRoles::ModNameRole).toString();
  856. auto mod = modStateModel->getMod(modName);
  857. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  858. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  859. if(unavailableDependencies.empty() && mod.isAvailable() && !mod.isSubmod())
  860. {
  861. on_installButton_clicked();
  862. return;
  863. }
  864. if(unavailableDependencies.empty() && mod.isUpdateAvailable() && index.column() == ModFields::STATUS_UPDATE)
  865. {
  866. on_updateButton_clicked();
  867. return;
  868. }
  869. if(index.column() == ModFields::NAME)
  870. {
  871. if(ui->allModsView->isExpanded(index))
  872. ui->allModsView->collapse(index);
  873. else
  874. ui->allModsView->expand(index);
  875. return;
  876. }
  877. if(notInstalledDependencies.empty() && !modStateModel->isModEnabled(modName))
  878. {
  879. on_enableButton_clicked();
  880. return;
  881. }
  882. if(modStateModel->isModEnabled(modName))
  883. {
  884. on_disableButton_clicked();
  885. return;
  886. }
  887. }
  888. void CModListView::createNewPreset(const QString & presetName)
  889. {
  890. modStateModel->createNewPreset(presetName);
  891. }
  892. void CModListView::deletePreset(const QString & presetName)
  893. {
  894. modStateModel->deletePreset(presetName);
  895. }
  896. void CModListView::activatePreset(const QString & presetName)
  897. {
  898. modStateModel->activatePreset(presetName);
  899. modStateModel->reloadLocalState();
  900. }
  901. void CModListView::renamePreset(const QString & oldPresetName, const QString & newPresetName)
  902. {
  903. modStateModel->renamePreset(oldPresetName, newPresetName);
  904. }
  905. QStringList CModListView::getAllPresets() const
  906. {
  907. return modStateModel->getAllPresets();
  908. }
  909. QString CModListView::getActivePreset() const
  910. {
  911. return modStateModel->getActivePreset();
  912. }