cmodlistview_moc.cpp 24 KB

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