cmodlistview_moc.cpp 21 KB

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