cmodlistview_moc.cpp 21 KB

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