cmodlistview_moc.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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. setAcceptDrops(true);
  94. ui->uninstallButton->setIcon(QIcon{":/icons/mod-delete.png"});
  95. ui->enableButton->setIcon(QIcon{":/icons/mod-enabled.png"});
  96. ui->disableButton->setIcon(QIcon{":/icons/mod-disabled.png"});
  97. ui->updateButton->setIcon(QIcon{":/icons/mod-update.png"});
  98. ui->installButton->setIcon(QIcon{":/icons/mod-download.png"});
  99. ui->splitter->setStyleSheet("QSplitter::handle {background: palette('window');}");
  100. disableModInfo();
  101. setupModModel();
  102. setupFilterModel();
  103. setupModsView();
  104. ui->progressWidget->setVisible(false);
  105. dlManager = nullptr;
  106. modModel->reloadRepositories();
  107. if(settings["launcher"]["autoCheckRepositories"].Bool())
  108. loadRepositories();
  109. #ifdef VCMI_MOBILE
  110. for(auto * scrollWidget : {
  111. (QAbstractItemView*)ui->allModsView,
  112. (QAbstractItemView*)ui->screenshotsList})
  113. {
  114. Helper::enableScrollBySwiping(scrollWidget);
  115. scrollWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
  116. scrollWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  117. }
  118. #endif
  119. }
  120. void CModListView::reload()
  121. {
  122. modStateModel->reloadLocalState();
  123. modModel->reloadRepositories();
  124. }
  125. void CModListView::loadRepositories()
  126. {
  127. QStringList repositories;
  128. if (settings["launcher"]["defaultRepositoryEnabled"].Bool())
  129. repositories.push_back(QString::fromStdString(settings["launcher"]["defaultRepositoryURL"].String()));
  130. if (settings["launcher"]["extraRepositoryEnabled"].Bool())
  131. repositories.push_back(QString::fromStdString(settings["launcher"]["extraRepositoryURL"].String()));
  132. for(const auto & entry : repositories)
  133. {
  134. if (entry.isEmpty())
  135. continue;
  136. // URL must be encoded to something else to get rid of symbols illegal in file names
  137. auto hashed = QCryptographicHash::hash(entry.toUtf8(), QCryptographicHash::Md5);
  138. auto hashedStr = QString::fromUtf8(hashed.toHex());
  139. downloadFile(hashedStr + ".json", entry, tr("mods repository index"));
  140. }
  141. }
  142. CModListView::~CModListView()
  143. {
  144. QSettings s(Ui::teamName, Ui::appName);
  145. s.setValue("AllModsView/State", ui->allModsView->header()->saveState());
  146. delete ui;
  147. }
  148. static QString replaceIfNotEmpty(QVariant value, QString pattern)
  149. {
  150. if(value.canConvert<QString>())
  151. {
  152. if (value.toString().isEmpty())
  153. return "";
  154. else
  155. return pattern.arg(value.toString());
  156. }
  157. if(value.canConvert<QStringList>())
  158. {
  159. if (value.toStringList().isEmpty())
  160. return "";
  161. else
  162. return pattern.arg(value.toStringList().join(", "));
  163. }
  164. // all valid types of data should have been filtered by code above
  165. assert(!value.isValid());
  166. return "";
  167. }
  168. static QString replaceIfNotEmpty(QStringList value, QString pattern)
  169. {
  170. if(!value.empty())
  171. return pattern.arg(value.join(", "));
  172. return "";
  173. }
  174. QString CModListView::genChangelogText(const ModState & mod)
  175. {
  176. QString headerTemplate = "<p><span style=\" font-weight:600;\">%1: </span></p>";
  177. QString entryBegin = "<p align=\"justify\"><ul>";
  178. QString entryEnd = "</ul></p>";
  179. QString entryLine = "<li>%1</li>";
  180. //QString versionSeparator = "<hr/>";
  181. QString result;
  182. QMap<QString, QStringList> changelog = mod.getChangelog();
  183. QList<QString> versions = changelog.keys();
  184. std::sort(versions.begin(), versions.end(), [](QString lesser, QString greater)
  185. {
  186. return CModVersion::fromString(lesser.toStdString()) < CModVersion::fromString(greater.toStdString());
  187. });
  188. std::reverse(versions.begin(), versions.end());
  189. for(const auto & version : versions)
  190. {
  191. result += headerTemplate.arg(version);
  192. result += entryBegin;
  193. for(const auto & line : changelog.value(version))
  194. result += entryLine.arg(line);
  195. result += entryEnd;
  196. }
  197. return result;
  198. }
  199. QStringList CModListView::getModNames(QString queryingModID, QStringList input)
  200. {
  201. QStringList result;
  202. auto queryingMod = modStateModel->getMod(queryingModID);
  203. for(const auto & modID : input)
  204. {
  205. if (modStateModel->isModExists(modID) && modStateModel->getMod(modID).isHidden())
  206. continue;
  207. QString parentModID = modStateModel->getTopParent(modID);
  208. QString displayName;
  209. if (modStateModel->isSubmod(modID) && queryingMod.getParentID() != parentModID )
  210. {
  211. // show in form "parent mod (submod)"
  212. QString parentDisplayName = parentModID;
  213. QString submodDisplayName = modID;
  214. if (modStateModel->isModExists(parentModID))
  215. parentDisplayName = modStateModel->getMod(parentModID).getName();
  216. if (modStateModel->isModExists(modID))
  217. submodDisplayName = modStateModel->getMod(modID).getName();
  218. displayName = QString("%1 (%2)").arg(submodDisplayName, parentDisplayName);
  219. }
  220. else
  221. {
  222. // show simply as mod name
  223. displayName = modID;
  224. if (modStateModel->isModExists(modID))
  225. displayName = modStateModel->getMod(modID).getName();
  226. }
  227. result += displayName;
  228. }
  229. return result;
  230. }
  231. QString CModListView::genModInfoText(const ModState & mod)
  232. {
  233. QString prefix = "<p><span style=\" font-weight:600;\">%1: </span>"; // shared prefix
  234. QString redPrefix = "<p><span style=\" font-weight:600; color:red\">%1: </span>"; // shared prefix
  235. QString lineTemplate = prefix + "%2</p>";
  236. QString urlTemplate = prefix + "<a href=\"%2\">%3</a></p>";
  237. QString textTemplate = prefix + "</p><p align=\"justify\">%2</p>";
  238. QString listTemplate = "<p align=\"justify\">%1: %2</p>";
  239. QString noteTemplate = "<p align=\"justify\">%1</p>";
  240. QString incompatibleString = redPrefix + tr("Mod is incompatible") + "</p>";
  241. QString supportedVersions = redPrefix + "%2 %3 %4</p>";
  242. QString result;
  243. result += replaceIfNotEmpty(mod.getName(), lineTemplate.arg(tr("Mod name")));
  244. if (mod.isUpdateAvailable())
  245. {
  246. result += replaceIfNotEmpty(mod.getInstalledVersion(), lineTemplate.arg(tr("Installed version")));
  247. result += replaceIfNotEmpty(mod.getRepositoryVersion(), lineTemplate.arg(tr("Latest version")));
  248. }
  249. else
  250. {
  251. if (mod.isInstalled())
  252. result += replaceIfNotEmpty(mod.getInstalledVersion(), lineTemplate.arg(tr("Installed version")));
  253. else
  254. result += replaceIfNotEmpty(mod.getRepositoryVersion(), lineTemplate.arg(tr("Latest version")));
  255. }
  256. if (mod.isInstalled())
  257. result += replaceIfNotEmpty(modStateModel->getInstalledModSizeFormatted(mod.getID()), lineTemplate.arg(tr("Size")));
  258. if((!mod.isInstalled() || mod.isUpdateAvailable()) && !mod.getDownloadSizeFormatted().isEmpty())
  259. result += replaceIfNotEmpty(mod.getDownloadSizeFormatted(), lineTemplate.arg(tr("Download size")));
  260. result += replaceIfNotEmpty(mod.getAuthors(), lineTemplate.arg(tr("Authors")));
  261. if(!mod.getLicenseName().isEmpty())
  262. result += urlTemplate.arg(tr("License")).arg(mod.getLicenseUrl()).arg(mod.getLicenseName());
  263. if(!mod.getContact().isEmpty())
  264. result += urlTemplate.arg(tr("Contact")).arg(mod.getContact()).arg(mod.getContact());
  265. //compatibility info
  266. if(!mod.isCompatible())
  267. {
  268. auto compatibilityInfo = mod.getCompatibleVersionRange();
  269. auto minStr = compatibilityInfo.first;
  270. auto maxStr = compatibilityInfo.second;
  271. result += incompatibleString.arg(tr("Compatibility"));
  272. if(minStr == maxStr)
  273. result += supportedVersions.arg(tr("Required VCMI version"), minStr, "", "");
  274. else
  275. {
  276. if(minStr.isEmpty() || maxStr.isEmpty())
  277. {
  278. if(minStr.isEmpty())
  279. result += supportedVersions.arg(tr("Supported VCMI version"), maxStr, ", ", tr("please upgrade mod"));
  280. else
  281. result += supportedVersions.arg(tr("Required VCMI version"), minStr, " ", tr("or newer"));
  282. }
  283. else
  284. result += supportedVersions.arg(tr("Supported VCMI versions"), minStr, " - ", maxStr);
  285. }
  286. }
  287. QVariant baseLanguageVariant = mod.getBaseLanguage();
  288. QString baseLanguageID = baseLanguageVariant.isValid() ? baseLanguageVariant.toString() : "english";
  289. QStringList supportedLanguages = mod.getSupportedLanguages();
  290. if(supportedLanguages.size() > 1)
  291. {
  292. QStringList supportedLanguagesTranslated;
  293. for (const auto & languageID : supportedLanguages)
  294. supportedLanguagesTranslated += QApplication::translate("Language", Languages::getLanguageOptions(languageID.toStdString()).nameEnglish.c_str());
  295. result += replaceIfNotEmpty(supportedLanguagesTranslated, lineTemplate.arg(tr("Languages")));
  296. }
  297. QStringList conflicts = mod.getConflicts();
  298. for (const auto & otherMod : modStateModel->getAllMods())
  299. {
  300. QStringList otherConflicts = modStateModel->getMod(otherMod).getConflicts();
  301. if (otherConflicts.contains(mod.getID()) && !conflicts.contains(otherMod))
  302. conflicts.push_back(otherMod);
  303. }
  304. result += replaceIfNotEmpty(getModNames(mod.getID(), mod.getDependencies()), lineTemplate.arg(tr("Required mods")));
  305. result += replaceIfNotEmpty(getModNames(mod.getID(), conflicts), lineTemplate.arg(tr("Conflicting mods")));
  306. result += replaceIfNotEmpty(mod.getDescription(), textTemplate.arg(tr("Description")));
  307. result += "<p></p>"; // to get some empty space
  308. QString translationMismatch = tr("This mod cannot be enabled because it translates into a different language.");
  309. QString notInstalledDeps = tr("This mod can not be enabled because the following dependencies are not present");
  310. QString unavailableDeps = tr("This mod can not be installed because the following dependencies are not present");
  311. QString thisIsSubmod = tr("This is a submod and it cannot be installed or uninstalled separately from its parent mod");
  312. QString notes;
  313. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  314. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  315. if (mod.isInstalled())
  316. notes += replaceIfNotEmpty(getModNames(mod.getID(), notInstalledDependencies), listTemplate.arg(notInstalledDeps));
  317. else
  318. notes += replaceIfNotEmpty(getModNames(mod.getID(), unavailableDependencies), listTemplate.arg(unavailableDeps));
  319. if(mod.isSubmod())
  320. notes += noteTemplate.arg(thisIsSubmod);
  321. if (mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage().toStdString())
  322. notes += noteTemplate.arg(translationMismatch);
  323. if(notes.size())
  324. result += textTemplate.arg(tr("Notes")).arg(notes);
  325. return result;
  326. }
  327. void CModListView::disableModInfo()
  328. {
  329. ui->disableButton->setVisible(false);
  330. ui->enableButton->setVisible(false);
  331. ui->installButton->setVisible(false);
  332. ui->uninstallButton->setVisible(false);
  333. ui->updateButton->setVisible(false);
  334. }
  335. void CModListView::dataChanged(const QModelIndex & topleft, const QModelIndex & bottomRight)
  336. {
  337. selectMod(ui->allModsView->currentIndex());
  338. }
  339. void CModListView::selectMod(const QModelIndex & index)
  340. {
  341. ui->tabWidget->setCurrentIndex(0);
  342. if(!index.isValid())
  343. {
  344. disableModInfo();
  345. }
  346. else
  347. {
  348. const auto modName = index.data(ModRoles::ModNameRole).toString();
  349. auto mod = modStateModel->getMod(modName);
  350. ui->tabWidget->setTabEnabled(1, !mod.getChangelog().isEmpty());
  351. ui->tabWidget->setTabEnabled(2, !mod.getScreenshots().isEmpty());
  352. ui->modInfoBrowser->setHtml(genModInfoText(mod));
  353. ui->changelogBrowser->setHtml(genChangelogText(mod));
  354. Helper::enableScrollBySwiping(ui->modInfoBrowser);
  355. Helper::enableScrollBySwiping(ui->changelogBrowser);
  356. QStringList notInstalledDependencies = this->getModsToInstall(modName);
  357. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  358. bool translationMismatch = mod.isTranslation() && CGeneralTextHandler::getPreferredLanguage() != mod.getBaseLanguage().toStdString();
  359. ui->disableButton->setVisible(modStateModel->isModInstalled(mod.getID()) && modStateModel->isModEnabled(mod.getID()));
  360. ui->enableButton->setVisible(modStateModel->isModInstalled(mod.getID()) && !modStateModel->isModEnabled(mod.getID()));
  361. ui->installButton->setVisible(mod.isAvailable() && !mod.isSubmod());
  362. ui->uninstallButton->setVisible(mod.isInstalled() && !mod.isSubmod());
  363. ui->updateButton->setVisible(mod.isUpdateAvailable());
  364. // Block buttons if action is not allowed at this time
  365. ui->disableButton->setEnabled(true);
  366. ui->enableButton->setEnabled(notInstalledDependencies.empty() && !translationMismatch);
  367. ui->installButton->setEnabled(unavailableDependencies.empty());
  368. ui->uninstallButton->setEnabled(true);
  369. ui->updateButton->setEnabled(unavailableDependencies.empty());
  370. loadScreenshots();
  371. }
  372. }
  373. void CModListView::modSelected(const QModelIndex & current, const QModelIndex &)
  374. {
  375. selectMod(current);
  376. }
  377. void CModListView::on_allModsView_activated(const QModelIndex & index)
  378. {
  379. selectMod(index);
  380. loadScreenshots();
  381. }
  382. void CModListView::on_lineEdit_textChanged(const QString & arg1)
  383. {
  384. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  385. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1, QRegularExpression::UnanchoredWildcardConversion);
  386. #else
  387. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1);
  388. //Hack due to lack QRegularExpression::UnanchoredWildcardConversion in Qt5
  389. baseStr.chop(3);
  390. baseStr.remove(0,5);
  391. #endif
  392. QRegularExpression regExp{baseStr, QRegularExpression::CaseInsensitiveOption};
  393. filterModel->setFilterRegularExpression(regExp);
  394. }
  395. void CModListView::on_comboBox_currentIndexChanged(int index)
  396. {
  397. auto enumIndex = static_cast<ModFilterMask>(index);
  398. filterModel->setTypeFilter(enumIndex);
  399. }
  400. QStringList CModListView::findUnavailableMods(QStringList candidates)
  401. {
  402. QStringList invalidMods;
  403. for(QString modName : candidates)
  404. {
  405. if(!modStateModel->isModExists(modName))
  406. invalidMods.push_back(modName);
  407. }
  408. return invalidMods;
  409. }
  410. void CModListView::on_enableButton_clicked()
  411. {
  412. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  413. enableModByName(modName);
  414. checkManagerErrors();
  415. }
  416. void CModListView::enableModByName(QString modName)
  417. {
  418. manager->enableMods({modName});
  419. modModel->modChanged(modName);
  420. }
  421. void CModListView::on_disableButton_clicked()
  422. {
  423. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  424. disableModByName(modName);
  425. checkManagerErrors();
  426. }
  427. void CModListView::disableModByName(QString modName)
  428. {
  429. manager->disableMod(modName);
  430. modModel->modChanged(modName);
  431. }
  432. QStringList CModListView::getModsToInstall(QString mod)
  433. {
  434. QStringList result;
  435. QStringList candidates;
  436. QStringList processed;
  437. candidates.push_back(mod);
  438. while (!candidates.empty())
  439. {
  440. QString potentialToInstall = candidates.back();
  441. candidates.pop_back();
  442. processed.push_back(potentialToInstall);
  443. if (modStateModel->isSubmod(potentialToInstall))
  444. {
  445. QString topParent = modStateModel->getTopParent(potentialToInstall);
  446. if (modStateModel->isModInstalled(topParent))
  447. {
  448. if (modStateModel->isModUpdateAvailable(topParent))
  449. potentialToInstall = modStateModel->getTopParent(potentialToInstall);
  450. // else - potentially broken mod that depends on non-existing submod
  451. }
  452. else
  453. potentialToInstall = modStateModel->getTopParent(potentialToInstall);
  454. }
  455. if (modStateModel->isModExists(potentialToInstall) && !modStateModel->isModInstalled(potentialToInstall))
  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->progressBar->setFormat(tr("Installing chronicles"));
  648. float prog = 0.0;
  649. auto futureExtract = std::async(std::launch::async, [this, exe, &prog]()
  650. {
  651. ChroniclesExtractor ce(this, [&prog](float progress) { prog = progress; });
  652. ce.installChronicles(exe);
  653. return true;
  654. });
  655. while(futureExtract.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
  656. {
  657. emit extractionProgress(static_cast<int>(prog * 1000.f), 1000);
  658. qApp->processEvents();
  659. }
  660. if(futureExtract.get())
  661. {
  662. //update
  663. modStateModel->reloadLocalState();
  664. modModel->reloadRepositories();
  665. }
  666. }
  667. if(!images.empty())
  668. loadScreenshots();
  669. }
  670. void CModListView::installMods(QStringList archives)
  671. {
  672. QStringList modNames;
  673. QStringList modsToEnable;
  674. for(QString archive : archives)
  675. {
  676. // get basename out of full file name
  677. // remove path remove extension
  678. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  679. modNames.push_back(modName);
  680. }
  681. // uninstall old version of mod, if installed
  682. for(QString mod : modNames)
  683. {
  684. if(modStateModel->getMod(mod).isInstalled())
  685. {
  686. if (modStateModel->isModEnabled(mod))
  687. modsToEnable.push_back(mod);
  688. manager->uninstallMod(mod);
  689. }
  690. else
  691. {
  692. // installation of previously not present mod -> enable it
  693. modsToEnable.push_back(mod);
  694. }
  695. }
  696. for(int i = 0; i < modNames.size(); i++)
  697. {
  698. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  699. manager->installMod(modNames[i], archives[i]);
  700. }
  701. if (!modsToEnable.empty())
  702. manager->enableMods(modsToEnable);
  703. checkManagerErrors();
  704. for(QString archive : archives)
  705. QFile::remove(archive);
  706. }
  707. void CModListView::installMaps(QStringList maps)
  708. {
  709. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  710. for(QString map : maps)
  711. {
  712. QFile(map).rename(destDir + map.section('/', -1, -1));
  713. }
  714. }
  715. void CModListView::on_refreshButton_clicked()
  716. {
  717. loadRepositories();
  718. }
  719. void CModListView::on_pushButton_clicked()
  720. {
  721. delete dlManager;
  722. dlManager = nullptr;
  723. hideProgressBar();
  724. }
  725. void CModListView::modelReset()
  726. {
  727. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  728. }
  729. void CModListView::checkManagerErrors()
  730. {
  731. QString errors = manager->getErrors().join('\n');
  732. if(errors.size() != 0)
  733. {
  734. QString title = tr("Operation failed");
  735. QString description = tr("Encountered errors:\n") + errors;
  736. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  737. }
  738. }
  739. void CModListView::on_tabWidget_currentChanged(int index)
  740. {
  741. loadScreenshots();
  742. }
  743. void CModListView::loadScreenshots()
  744. {
  745. if(ui->tabWidget->currentIndex() == 2)
  746. {
  747. if(!ui->allModsView->currentIndex().isValid())
  748. {
  749. // select the first mod, so we can access its data
  750. ui->allModsView->setCurrentIndex(filterModel->index(0, 0));
  751. }
  752. ui->screenshotsList->clear();
  753. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  754. assert(modStateModel->isModExists(modName)); //should be filtered out by check above
  755. for(QString url : modStateModel->getMod(modName).getScreenshots())
  756. {
  757. // URL must be encoded to something else to get rid of symbols illegal in file names
  758. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  759. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  760. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  761. QPixmap pixmap(fullPath);
  762. if(pixmap.isNull())
  763. {
  764. // image file not exists or corrupted - try to redownload
  765. downloadFile(fileName, url, tr("screenshots"));
  766. }
  767. else
  768. {
  769. // managed to load cached image
  770. QIcon icon(pixmap);
  771. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  772. ui->screenshotsList->addItem(item);
  773. }
  774. }
  775. }
  776. }
  777. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  778. {
  779. if(index.isValid())
  780. {
  781. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  782. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  783. ImageViewer::showPixmap(pixmap, this);
  784. }
  785. }
  786. void CModListView::doInstallMod(const QString & modName)
  787. {
  788. for(const auto & name : modStateModel->getMod(modName).getDependencies())
  789. {
  790. auto mod = modStateModel->getMod(name);
  791. if(!mod.isInstalled())
  792. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeBytes());
  793. }
  794. }
  795. bool CModListView::isModAvailable(const QString & modName)
  796. {
  797. return !modStateModel->isModInstalled(modName);
  798. }
  799. bool CModListView::isModEnabled(const QString & modName)
  800. {
  801. return modStateModel->isModEnabled(modName);
  802. }
  803. bool CModListView::isModInstalled(const QString & modName)
  804. {
  805. auto mod = modStateModel->getMod(modName);
  806. return mod.isInstalled();
  807. }
  808. QStringList CModListView::getInstalledChronicles()
  809. {
  810. QStringList result;
  811. for(const auto & modName : modStateModel->getAllMods())
  812. {
  813. auto mod = modStateModel->getMod(modName);
  814. if (!mod.isInstalled())
  815. continue;
  816. if (mod.getTopParentID() != "chronicles")
  817. continue;
  818. result += modName;
  819. }
  820. return result;
  821. }
  822. QStringList CModListView::getUpdateableMods()
  823. {
  824. QStringList result;
  825. for(const auto & modName : modStateModel->getAllMods())
  826. {
  827. auto mod = modStateModel->getMod(modName);
  828. if (mod.isUpdateAvailable())
  829. result.push_back(modName);
  830. }
  831. return result;
  832. }
  833. QString CModListView::getTranslationModName(const QString & language)
  834. {
  835. for(const auto & modName : modStateModel->getAllMods())
  836. {
  837. auto mod = modStateModel->getMod(modName);
  838. if (!mod.isTranslation())
  839. continue;
  840. if (mod.getBaseLanguage() != language)
  841. continue;
  842. return modName;
  843. }
  844. return QString();
  845. }
  846. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  847. {
  848. if(!index.isValid())
  849. return;
  850. auto modName = index.data(ModRoles::ModNameRole).toString();
  851. auto mod = modStateModel->getMod(modName);
  852. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  853. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  854. if(unavailableDependencies.empty() && mod.isAvailable() && !mod.isSubmod())
  855. {
  856. on_installButton_clicked();
  857. return;
  858. }
  859. if(unavailableDependencies.empty() && mod.isUpdateAvailable() && index.column() == ModFields::STATUS_UPDATE)
  860. {
  861. on_updateButton_clicked();
  862. return;
  863. }
  864. if(index.column() == ModFields::NAME)
  865. {
  866. if(ui->allModsView->isExpanded(index))
  867. ui->allModsView->collapse(index);
  868. else
  869. ui->allModsView->expand(index);
  870. return;
  871. }
  872. if(notInstalledDependencies.empty() && !modStateModel->isModEnabled(modName))
  873. {
  874. on_enableButton_clicked();
  875. return;
  876. }
  877. if(modStateModel->isModEnabled(modName))
  878. {
  879. on_disableButton_clicked();
  880. return;
  881. }
  882. }
  883. void CModListView::createNewPreset(const QString & presetName)
  884. {
  885. modStateModel->createNewPreset(presetName);
  886. }
  887. void CModListView::deletePreset(const QString & presetName)
  888. {
  889. modStateModel->deletePreset(presetName);
  890. }
  891. void CModListView::activatePreset(const QString & presetName)
  892. {
  893. modStateModel->activatePreset(presetName);
  894. modStateModel->reloadLocalState();
  895. }
  896. void CModListView::renamePreset(const QString & oldPresetName, const QString & newPresetName)
  897. {
  898. modStateModel->renamePreset(oldPresetName, newPresetName);
  899. }
  900. QStringList CModListView::getAllPresets() const
  901. {
  902. return modStateModel->getAllPresets();
  903. }
  904. QString CModListView::getActivePreset() const
  905. {
  906. return modStateModel->getActivePreset();
  907. }