cmodlistview_moc.cpp 24 KB

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