cmodlistview_moc.cpp 20 KB

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