cmodlistview_moc.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  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 <QJsonArray>
  15. #include <QCryptographicHash>
  16. #include "cmodlistmodel_moc.h"
  17. #include "cmodmanager.h"
  18. #include "cdownloadmanager_moc.h"
  19. #include "../launcherdirs.h"
  20. #include "../../lib/CConfigHandler.h"
  21. void CModListView::setupModModel()
  22. {
  23. modModel = new CModListModel();
  24. manager = new CModManager(modModel);
  25. }
  26. void CModListView::setupFilterModel()
  27. {
  28. filterModel = new CModFilterModel(modModel);
  29. filterModel->setFilterKeyColumn(-1); // filter across all columns
  30. filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); // to make it more user-friendly
  31. filterModel->setDynamicSortFilter(true);
  32. }
  33. void CModListView::setupModsView()
  34. {
  35. ui->allModsView->setModel(filterModel);
  36. // input data is not sorted - sort it before display
  37. ui->allModsView->sortByColumn(ModFields::TYPE, Qt::AscendingOrder);
  38. ui->allModsView->setColumnWidth(ModFields::NAME, 185);
  39. ui->allModsView->setColumnWidth(ModFields::STATUS_ENABLED, 30);
  40. ui->allModsView->setColumnWidth(ModFields::STATUS_UPDATE, 30);
  41. ui->allModsView->setColumnWidth(ModFields::TYPE, 75);
  42. ui->allModsView->setColumnWidth(ModFields::SIZE, 80);
  43. ui->allModsView->setColumnWidth(ModFields::VERSION, 60);
  44. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_ENABLED, QHeaderView::Fixed);
  45. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_UPDATE, QHeaderView::Fixed);
  46. ui->allModsView->setUniformRowHeights(true);
  47. connect( ui->allModsView->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex &, const QModelIndex & )),
  48. this, SLOT( modSelected( const QModelIndex &, const QModelIndex & )));
  49. connect( filterModel, SIGNAL( modelReset()),
  50. this, SLOT( modelReset()));
  51. connect( modModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
  52. this, SLOT(dataChanged(QModelIndex,QModelIndex)));
  53. }
  54. CModListView::CModListView(QWidget *parent) :
  55. QWidget(parent),
  56. settingsListener(settings.listen["launcher"]["repositoryURL"]),
  57. ui(new Ui::CModListView)
  58. {
  59. settingsListener([&](const JsonNode &){ repositoriesChanged = true; });
  60. ui->setupUi(this);
  61. setupModModel();
  62. setupFilterModel();
  63. setupModsView();
  64. ui->progressWidget->setVisible(false);
  65. dlManager = nullptr;
  66. disableModInfo();
  67. if (settings["launcher"]["autoCheckRepositories"].Bool())
  68. {
  69. loadRepositories();
  70. }
  71. else
  72. {
  73. manager->resetRepositories();
  74. }
  75. }
  76. void CModListView::loadRepositories()
  77. {
  78. manager->resetRepositories();
  79. for (auto entry : settings["launcher"]["repositoryURL"].Vector())
  80. {
  81. QString str = QString::fromUtf8(entry.String().c_str());
  82. // URL must be encoded to something else to get rid of symbols illegal in file names
  83. auto hashed = QCryptographicHash::hash(str.toUtf8(), QCryptographicHash::Md5);
  84. auto hashedStr = QString::fromUtf8(hashed.toHex());
  85. downloadFile(hashedStr + ".json", str, "repository index");
  86. }
  87. }
  88. CModListView::~CModListView()
  89. {
  90. delete ui;
  91. }
  92. void CModListView::showEvent(QShowEvent * event)
  93. {
  94. QWidget::showEvent(event);
  95. if (repositoriesChanged)
  96. {
  97. repositoriesChanged = false;
  98. if (settings["launcher"]["autoCheckRepositories"].Bool())
  99. {
  100. loadRepositories();
  101. }
  102. }
  103. }
  104. void CModListView::showModInfo()
  105. {
  106. enableModInfo();
  107. ui->modInfoWidget->show();
  108. ui->hideModInfoButton->setArrowType(Qt::RightArrow);
  109. ui->showInfoButton->setVisible(false);
  110. loadScreenshots();
  111. }
  112. void CModListView::hideModInfo()
  113. {
  114. ui->modInfoWidget->hide();
  115. ui->hideModInfoButton->setArrowType(Qt::LeftArrow);
  116. ui->hideModInfoButton->setEnabled(true);
  117. ui->showInfoButton->setVisible(true);
  118. }
  119. static QString replaceIfNotEmpty(QVariant value, QString pattern)
  120. {
  121. if (value.canConvert<QStringList>())
  122. return pattern.arg(value.toStringList().join(", "));
  123. if (value.canConvert<QString>())
  124. return pattern.arg(value.toString());
  125. // all valid types of data should have been filtered by code above
  126. assert(!value.isValid());
  127. return "";
  128. }
  129. static QString replaceIfNotEmpty(QStringList value, QString pattern)
  130. {
  131. if (!value.empty())
  132. return pattern.arg(value.join(", "));
  133. return "";
  134. }
  135. QString CModListView::genChangelogText(CModEntry &mod)
  136. {
  137. QString headerTemplate = "<p><span style=\" font-weight:600;\">%1: </span></p>";
  138. QString entryBegin = "<p align=\"justify\"><ul>";
  139. QString entryEnd = "</ul></p>";
  140. QString entryLine = "<li>%1</li>";
  141. //QString versionSeparator = "<hr/>";
  142. QString result;
  143. QVariantMap changelog = mod.getValue("changelog").toMap();
  144. QList<QString> versions = changelog.keys();
  145. std::sort(versions.begin(), versions.end(), [](QString lesser, QString greater)
  146. {
  147. return !CModEntry::compareVersions(lesser, greater);
  148. });
  149. for (auto & version : versions)
  150. {
  151. result += headerTemplate.arg(version);
  152. result += entryBegin;
  153. for (auto & line : changelog.value(version).toStringList())
  154. result += entryLine.arg(line);
  155. result += entryEnd;
  156. }
  157. return result;
  158. }
  159. QString CModListView::genModInfoText(CModEntry &mod)
  160. {
  161. QString prefix = "<p><span style=\" font-weight:600;\">%1: </span>"; // shared prefix
  162. QString lineTemplate = prefix + "%2</p>";
  163. QString urlTemplate = prefix + "<a href=\"%2\">%3</a></p>";
  164. QString textTemplate = prefix + "</p><p align=\"justify\">%2</p>";
  165. QString listTemplate = "<p align=\"justify\">%1: %2</p>";
  166. QString noteTemplate = "<p align=\"justify\">%1</p>";
  167. QString result;
  168. result += replaceIfNotEmpty(mod.getValue("name"), lineTemplate.arg(tr("Mod name")));
  169. result += replaceIfNotEmpty(mod.getValue("installedVersion"), lineTemplate.arg(tr("Installed version")));
  170. result += replaceIfNotEmpty(mod.getValue("latestVersion"), lineTemplate.arg(tr("Latest version")));
  171. if (mod.getValue("size").isValid())
  172. result += replaceIfNotEmpty(CModEntry::sizeToString(mod.getValue("size").toDouble()), lineTemplate.arg(tr("Download size")));
  173. result += replaceIfNotEmpty(mod.getValue("author"), lineTemplate.arg(tr("Authors")));
  174. if (mod.getValue("licenseURL").isValid())
  175. result += urlTemplate.arg(tr("License")).arg(mod.getValue("licenseURL").toString()).arg(mod.getValue("licenseName").toString());
  176. if (mod.getValue("contact").isValid())
  177. result += urlTemplate.arg(tr("Home")).arg(mod.getValue("contact").toString()).arg(mod.getValue("contact").toString());
  178. result += replaceIfNotEmpty(mod.getValue("depends"), lineTemplate.arg(tr("Required mods")));
  179. result += replaceIfNotEmpty(mod.getValue("conflicts"), lineTemplate.arg(tr("Conflicting mods")));
  180. result += replaceIfNotEmpty(mod.getValue("description"), textTemplate.arg(tr("Description")));
  181. result += "<p></p>"; // to get some empty space
  182. QString unknownDeps = tr("This mod can not be installed or enabled because following dependencies are not present");
  183. QString blockingMods = tr("This mod can not be enabled because following mods are incompatible with this mod");
  184. QString hasActiveDependentMods = tr("This mod can not be disabled because it is required to run following mods");
  185. QString hasDependentMods = tr("This mod can not be uninstalled or updated because it is required to run following mods");
  186. QString thisIsSubmod = tr("This is submod and it can not be installed or uninstalled separately from parent mod");
  187. QString notes;
  188. notes += replaceIfNotEmpty(findInvalidDependencies(mod.getName()), listTemplate.arg(unknownDeps));
  189. notes += replaceIfNotEmpty(findBlockingMods(mod.getName()), listTemplate.arg(blockingMods));
  190. if (mod.isEnabled())
  191. notes += replaceIfNotEmpty(findDependentMods(mod.getName(), true), listTemplate.arg(hasActiveDependentMods));
  192. if (mod.isInstalled())
  193. notes += replaceIfNotEmpty(findDependentMods(mod.getName(), false), listTemplate.arg(hasDependentMods));
  194. if (mod.getName().contains('.'))
  195. notes += noteTemplate.arg(thisIsSubmod);
  196. if (notes.size())
  197. result += textTemplate.arg(tr("Notes")).arg(notes);
  198. return result;
  199. }
  200. void CModListView::enableModInfo()
  201. {
  202. ui->hideModInfoButton->setEnabled(true);
  203. ui->showInfoButton->setVisible(true);
  204. }
  205. void CModListView::disableModInfo()
  206. {
  207. hideModInfo();
  208. ui->hideModInfoButton->setEnabled(false);
  209. ui->showInfoButton->setVisible(false);
  210. ui->disableButton->setVisible(false);
  211. ui->enableButton->setVisible(false);
  212. ui->installButton->setVisible(false);
  213. ui->uninstallButton->setVisible(false);
  214. ui->updateButton->setVisible(false);
  215. }
  216. void CModListView::dataChanged(const QModelIndex & topleft, const QModelIndex & bottomRight)
  217. {
  218. selectMod(ui->allModsView->currentIndex());
  219. }
  220. void CModListView::selectMod(const QModelIndex & index)
  221. {
  222. if (!index.isValid())
  223. {
  224. disableModInfo();
  225. }
  226. else
  227. {
  228. auto mod = modModel->getMod(index.data(ModRoles::ModNameRole).toString());
  229. ui->modInfoBrowser->setHtml(genModInfoText(mod));
  230. ui->changelogBrowser->setHtml(genChangelogText(mod));
  231. bool hasInvalidDeps = !findInvalidDependencies(index.data(ModRoles::ModNameRole).toString()).empty();
  232. bool hasBlockingMods = !findBlockingMods(index.data(ModRoles::ModNameRole).toString()).empty();
  233. bool hasDependentMods = !findDependentMods(index.data(ModRoles::ModNameRole).toString(), true).empty();
  234. ui->hideModInfoButton->setEnabled(true);
  235. ui->showInfoButton->setVisible(!ui->modInfoWidget->isVisible());
  236. ui->disableButton->setVisible(mod.isEnabled());
  237. ui->enableButton->setVisible(mod.isDisabled());
  238. ui->installButton->setVisible(mod.isAvailable() && !mod.getName().contains('.'));
  239. ui->uninstallButton->setVisible(mod.isInstalled() && !mod.getName().contains('.'));
  240. ui->updateButton->setVisible(mod.isUpdateable());
  241. // Block buttons if action is not allowed at this time
  242. // TODO: automate handling of some of these cases instead of forcing player
  243. // to resolve all conflicts manually.
  244. ui->disableButton->setEnabled(!hasDependentMods);
  245. ui->enableButton->setEnabled(!hasBlockingMods && !hasInvalidDeps);
  246. ui->installButton->setEnabled(!hasInvalidDeps);
  247. ui->uninstallButton->setEnabled(!hasDependentMods);
  248. ui->updateButton->setEnabled(!hasInvalidDeps && !hasDependentMods);
  249. loadScreenshots();
  250. }
  251. }
  252. void CModListView::keyPressEvent(QKeyEvent * event)
  253. {
  254. if (event->key() == Qt::Key_Escape && ui->modInfoWidget->isVisible() )
  255. {
  256. hideModInfo();
  257. }
  258. else
  259. {
  260. return QWidget::keyPressEvent(event);
  261. }
  262. }
  263. void CModListView::modSelected(const QModelIndex & current, const QModelIndex & )
  264. {
  265. selectMod(current);
  266. }
  267. void CModListView::on_hideModInfoButton_clicked()
  268. {
  269. if (ui->modInfoWidget->isVisible())
  270. hideModInfo();
  271. else
  272. showModInfo();
  273. }
  274. void CModListView::on_allModsView_activated(const QModelIndex &index)
  275. {
  276. showModInfo();
  277. selectMod(index);
  278. }
  279. void CModListView::on_lineEdit_textChanged(const QString &arg1)
  280. {
  281. QRegExp regExp(arg1, Qt::CaseInsensitive, QRegExp::Wildcard);
  282. filterModel->setFilterRegExp(regExp);
  283. }
  284. void CModListView::on_comboBox_currentIndexChanged(int index)
  285. {
  286. switch (index)
  287. {
  288. break; case 0: filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::MASK_NONE);
  289. break; case 1: filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::INSTALLED);
  290. break; case 2: filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::INSTALLED);
  291. break; case 3: filterModel->setTypeFilter(ModStatus::UPDATEABLE, ModStatus::UPDATEABLE);
  292. break; case 4: filterModel->setTypeFilter(ModStatus::ENABLED | ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
  293. break; case 5: filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
  294. }
  295. }
  296. QStringList CModListView::findInvalidDependencies(QString mod)
  297. {
  298. QStringList ret;
  299. for (QString requrement : modModel->getRequirements(mod))
  300. {
  301. if (!modModel->hasMod(requrement))
  302. ret += requrement;
  303. }
  304. return ret;
  305. }
  306. QStringList CModListView::findBlockingMods(QString mod)
  307. {
  308. QStringList ret;
  309. auto required = modModel->getRequirements(mod);
  310. for (QString name : modModel->getModList())
  311. {
  312. auto mod = modModel->getMod(name);
  313. if (mod.isEnabled())
  314. {
  315. // one of enabled mods have requirement (or this mod) marked as conflict
  316. for (auto conflict : mod.getValue("conflicts").toStringList())
  317. if (required.contains(conflict))
  318. ret.push_back(name);
  319. }
  320. }
  321. return ret;
  322. }
  323. QStringList CModListView::findDependentMods(QString mod, bool excludeDisabled)
  324. {
  325. QStringList ret;
  326. for (QString modName : modModel->getModList())
  327. {
  328. auto current = modModel->getMod(modName);
  329. if (!current.isInstalled())
  330. continue;
  331. if (current.getValue("depends").toStringList().contains(mod) &&
  332. !(current.isDisabled() && excludeDisabled))
  333. ret += modName;
  334. }
  335. return ret;
  336. }
  337. void CModListView::on_enableButton_clicked()
  338. {
  339. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  340. assert(findBlockingMods(modName).empty());
  341. assert(findInvalidDependencies(modName).empty());
  342. for (auto & name : modModel->getRequirements(modName))
  343. if (modModel->getMod(name).isDisabled())
  344. manager->enableMod(name);
  345. checkManagerErrors();
  346. }
  347. void CModListView::on_disableButton_clicked()
  348. {
  349. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  350. if (modModel->hasMod(modName) &&
  351. modModel->getMod(modName).isEnabled())
  352. manager->disableMod(modName);
  353. checkManagerErrors();
  354. }
  355. void CModListView::on_updateButton_clicked()
  356. {
  357. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  358. assert(findInvalidDependencies(modName).empty());
  359. for (auto & name : modModel->getRequirements(modName))
  360. {
  361. auto mod = modModel->getMod(name);
  362. // update required mod, install missing (can be new dependency)
  363. if (mod.isUpdateable() || !mod.isInstalled())
  364. downloadFile(name + ".zip", mod.getValue("download").toString(), "mods");
  365. }
  366. }
  367. void CModListView::on_uninstallButton_clicked()
  368. {
  369. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  370. // NOTE: perhaps add "manually installed" flag and uninstall those dependencies that don't have it?
  371. if (modModel->hasMod(modName) &&
  372. modModel->getMod(modName).isInstalled())
  373. {
  374. if (modModel->getMod(modName).isEnabled())
  375. manager->disableMod(modName);
  376. manager->uninstallMod(modName);
  377. }
  378. checkManagerErrors();
  379. }
  380. void CModListView::on_installButton_clicked()
  381. {
  382. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  383. assert(findInvalidDependencies(modName).empty());
  384. for (auto & name : modModel->getRequirements(modName))
  385. {
  386. auto mod = modModel->getMod(name);
  387. if (!mod.isInstalled())
  388. downloadFile(name + ".zip", mod.getValue("download").toString(), "mods");
  389. }
  390. }
  391. void CModListView::downloadFile(QString file, QString url, QString description)
  392. {
  393. if (!dlManager)
  394. {
  395. dlManager = new CDownloadManager();
  396. ui->progressWidget->setVisible(true);
  397. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  398. this, SLOT(downloadProgress(qint64,qint64)));
  399. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  400. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  401. QString progressBarFormat = "Downloading %s%. %p% (%v KB out of %m KB) finished";
  402. progressBarFormat.replace("%s%", description);
  403. ui->progressBar->setFormat(progressBarFormat);
  404. }
  405. dlManager->downloadFile(QUrl(url), file);
  406. }
  407. void CModListView::downloadProgress(qint64 current, qint64 max)
  408. {
  409. // display progress, in kilobytes
  410. ui->progressBar->setValue(current/1024);
  411. ui->progressBar->setMaximum(max/1024);
  412. }
  413. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  414. {
  415. QString title = "Download failed";
  416. QString firstLine = "Unable to download all files.\n\nEncountered errors:\n\n";
  417. QString lastLine = "\n\nInstall successfully downloaded?";
  418. // if all files were d/loaded there should be no errors. And on failure there must be an error
  419. assert(failedFiles.empty() == errors.empty());
  420. if (savedFiles.empty())
  421. {
  422. // no successfully downloaded mods
  423. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok );
  424. }
  425. else if (!failedFiles.empty())
  426. {
  427. // some mods were not downloaded
  428. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  429. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  430. if (result == QMessageBox::Yes)
  431. installFiles(savedFiles);
  432. }
  433. else
  434. {
  435. // everything OK
  436. installFiles(savedFiles);
  437. }
  438. // remove progress bar after some delay so user can see that download was complete and not interrupted.
  439. QTimer::singleShot(1000, this, SLOT(hideProgressBar()));
  440. dlManager->deleteLater();
  441. dlManager = nullptr;
  442. }
  443. void CModListView::hideProgressBar()
  444. {
  445. if (dlManager == nullptr) // it was not recreated meanwhile
  446. {
  447. ui->progressWidget->setVisible(false);
  448. ui->progressBar->setMaximum(0);
  449. ui->progressBar->setValue(0);
  450. }
  451. }
  452. void CModListView::installFiles(QStringList files)
  453. {
  454. QStringList mods;
  455. QStringList images;
  456. // TODO: some better way to separate zip's with mods and downloaded repository files
  457. for (QString filename : files)
  458. {
  459. if (filename.endsWith(".zip"))
  460. mods.push_back(filename);
  461. if (filename.endsWith(".json"))
  462. manager->loadRepository(filename);
  463. if (filename.endsWith(".png"))
  464. images.push_back(filename);
  465. }
  466. if (!mods.empty())
  467. installMods(mods);
  468. if (!images.empty())
  469. loadScreenshots();
  470. }
  471. void CModListView::installMods(QStringList archives)
  472. {
  473. QStringList modNames;
  474. for (QString archive : archives)
  475. {
  476. // get basename out of full file name
  477. // remove path remove extension
  478. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  479. modNames.push_back(modName);
  480. }
  481. QStringList modsToEnable;
  482. // disable mod(s), to properly recalculate dependencies, if changed
  483. for (QString mod : boost::adaptors::reverse(modNames))
  484. {
  485. CModEntry entry = modModel->getMod(mod);
  486. if (entry.isInstalled())
  487. {
  488. // enable mod if installed and enabled
  489. if (entry.isEnabled())
  490. modsToEnable.push_back(mod);
  491. }
  492. else
  493. {
  494. // enable mod if m
  495. if (settings["launcher"]["enableInstalledMods"].Bool())
  496. modsToEnable.push_back(mod);
  497. }
  498. }
  499. // uninstall old version of mod, if installed
  500. for (QString mod : boost::adaptors::reverse(modNames))
  501. {
  502. if (modModel->getMod(mod).isInstalled())
  503. manager->uninstallMod(mod);
  504. }
  505. for (int i=0; i<modNames.size(); i++)
  506. manager->installMod(modNames[i], archives[i]);
  507. std::function<void(QString)> enableMod;
  508. enableMod = [&](QString modName)
  509. {
  510. auto mod = modModel->getMod(modName);
  511. if (mod.isInstalled() && !mod.getValue("keepDisabled").toBool())
  512. {
  513. if (manager->enableMod(modName))
  514. {
  515. for (QString child : modModel->getChildren(modName))
  516. enableMod(child);
  517. }
  518. }
  519. };
  520. for (QString mod : modsToEnable)
  521. {
  522. enableMod(mod);
  523. }
  524. for (QString archive : archives)
  525. QFile::remove(archive);
  526. checkManagerErrors();
  527. }
  528. void CModListView::on_refreshButton_clicked()
  529. {
  530. loadRepositories();
  531. }
  532. void CModListView::on_pushButton_clicked()
  533. {
  534. delete dlManager;
  535. dlManager = nullptr;
  536. hideProgressBar();
  537. }
  538. void CModListView::modelReset()
  539. {
  540. if (ui->modInfoWidget->isVisible())
  541. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0,0) : QModelIndex());
  542. }
  543. void CModListView::checkManagerErrors()
  544. {
  545. QString errors = manager->getErrors().join('\n');
  546. if (errors.size() != 0)
  547. {
  548. QString title = "Operation failed";
  549. QString description = "Encountered errors:\n" + errors;
  550. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok );
  551. }
  552. }
  553. void CModListView::on_tabWidget_currentChanged(int index)
  554. {
  555. loadScreenshots();
  556. }
  557. void CModListView::loadScreenshots()
  558. {
  559. if (ui->tabWidget->currentIndex() == 2 && ui->modInfoWidget->isVisible())
  560. {
  561. ui->screenshotsList->clear();
  562. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  563. assert(modModel->hasMod(modName)); //should be filtered out by check above
  564. for (QString & url : modModel->getMod(modName).getValue("screenshots").toStringList())
  565. {
  566. // URL must be encoded to something else to get rid of symbols illegal in file names
  567. auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  568. auto hashedStr = QString::fromUtf8(hashed.toHex());
  569. QString fullPath = CLauncherDirs::get().downloadsPath() + '/' + hashedStr + ".png";
  570. QPixmap pixmap(fullPath);
  571. if (pixmap.isNull())
  572. {
  573. // image file not exists or corrupted - try to redownload
  574. downloadFile(hashedStr + ".png", url, "screenshots");
  575. }
  576. else
  577. {
  578. // managed to load cached image
  579. QIcon icon(pixmap);
  580. QListWidgetItem * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  581. ui->screenshotsList->addItem(item);
  582. }
  583. }
  584. }
  585. }
  586. void CModListView::on_screenshotsList_clicked(const QModelIndex &index)
  587. {
  588. if (index.isValid())
  589. {
  590. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  591. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  592. ImageViewer::showPixmap(pixmap, this);
  593. }
  594. }
  595. void CModListView::on_showInfoButton_clicked()
  596. {
  597. showModInfo();
  598. }