cmodlistview_moc.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862
  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 = std::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. enableModByName(modName);
  421. checkManagerErrors();
  422. }
  423. void CModListView::enableModByName(QString modName)
  424. {
  425. assert(findBlockingMods(modName).empty());
  426. assert(findInvalidDependencies(modName).empty());
  427. for(auto & name : modModel->getRequirements(modName))
  428. {
  429. if(modModel->getMod(name).isDisabled())
  430. manager->enableMod(name);
  431. }
  432. emit modsChanged();
  433. }
  434. void CModListView::on_disableButton_clicked()
  435. {
  436. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  437. disableModByName(modName);
  438. checkManagerErrors();
  439. }
  440. void CModListView::disableModByName(QString modName)
  441. {
  442. if(modModel->hasMod(modName) && modModel->getMod(modName).isEnabled())
  443. manager->disableMod(modName);
  444. emit modsChanged();
  445. }
  446. void CModListView::on_updateButton_clicked()
  447. {
  448. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  449. assert(findInvalidDependencies(modName).empty());
  450. for(auto & name : modModel->getRequirements(modName))
  451. {
  452. auto mod = modModel->getMod(name);
  453. // update required mod, install missing (can be new dependency)
  454. if(mod.isUpdateable() || !mod.isInstalled())
  455. downloadFile(name + ".zip", mod.getValue("download").toString(), "mods");
  456. }
  457. }
  458. void CModListView::on_uninstallButton_clicked()
  459. {
  460. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  461. // NOTE: perhaps add "manually installed" flag and uninstall those dependencies that don't have it?
  462. if(modModel->hasMod(modName) && modModel->getMod(modName).isInstalled())
  463. {
  464. if(modModel->getMod(modName).isEnabled())
  465. manager->disableMod(modName);
  466. manager->uninstallMod(modName);
  467. }
  468. emit modsChanged();
  469. checkManagerErrors();
  470. }
  471. void CModListView::on_installButton_clicked()
  472. {
  473. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  474. assert(findInvalidDependencies(modName).empty());
  475. for(auto & name : modModel->getRequirements(modName))
  476. {
  477. auto mod = modModel->getMod(name);
  478. if(!mod.isInstalled())
  479. downloadFile(name + ".zip", mod.getValue("download").toString(), "mods");
  480. }
  481. }
  482. void CModListView::downloadFile(QString file, QString url, QString description)
  483. {
  484. if(!dlManager)
  485. {
  486. dlManager = new CDownloadManager();
  487. ui->progressWidget->setVisible(true);
  488. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  489. this, SLOT(downloadProgress(qint64,qint64)));
  490. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  491. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  492. connect(modModel, &CModListModel::dataChanged, filterModel, &QAbstractItemModel::dataChanged);
  493. QString progressBarFormat = "Downloading %s%. %p% (%v KB out of %m KB) finished";
  494. progressBarFormat.replace("%s%", description);
  495. ui->progressBar->setFormat(progressBarFormat);
  496. }
  497. dlManager->downloadFile(QUrl(url), file);
  498. }
  499. void CModListView::downloadProgress(qint64 current, qint64 max)
  500. {
  501. // display progress, in kilobytes
  502. ui->progressBar->setValue(current / 1024);
  503. ui->progressBar->setMaximum(max / 1024);
  504. }
  505. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  506. {
  507. QString title = "Download failed";
  508. QString firstLine = "Unable to download all files.\n\nEncountered errors:\n\n";
  509. QString lastLine = "\n\nInstall successfully downloaded?";
  510. bool doInstallFiles = false;
  511. // if all files were d/loaded there should be no errors. And on failure there must be an error
  512. assert(failedFiles.empty() == errors.empty());
  513. if(savedFiles.empty())
  514. {
  515. // no successfully downloaded mods
  516. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  517. }
  518. else if(!failedFiles.empty())
  519. {
  520. // some mods were not downloaded
  521. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  522. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  523. if(result == QMessageBox::Yes)
  524. doInstallFiles = true;
  525. }
  526. else
  527. {
  528. // everything OK
  529. doInstallFiles = true;
  530. }
  531. // remove progress bar after some delay so user can see that download was complete and not interrupted.
  532. QTimer::singleShot(1000, this, SLOT(hideProgressBar()));
  533. dlManager->deleteLater();
  534. dlManager = nullptr;
  535. if(doInstallFiles)
  536. installFiles(savedFiles);
  537. emit modsChanged();
  538. }
  539. void CModListView::hideProgressBar()
  540. {
  541. if(dlManager == nullptr) // it was not recreated meanwhile
  542. {
  543. ui->progressWidget->setVisible(false);
  544. ui->progressBar->setMaximum(0);
  545. ui->progressBar->setValue(0);
  546. }
  547. }
  548. void CModListView::installFiles(QStringList files)
  549. {
  550. QStringList mods;
  551. QStringList images;
  552. // TODO: some better way to separate zip's with mods and downloaded repository files
  553. for(QString filename : files)
  554. {
  555. if(filename.endsWith(".zip"))
  556. mods.push_back(filename);
  557. if(filename.endsWith(".json"))
  558. {
  559. //download and merge additional files
  560. auto repodata = JsonUtils::JsonFromFile(filename).toMap();
  561. if(repodata.value("name").isNull())
  562. {
  563. for(const auto & key : repodata.keys())
  564. {
  565. auto modjson = repodata[key].toMap().value("mod");
  566. if(!modjson.isNull())
  567. {
  568. downloadFile(key + ".json", modjson.toString(), "mod json");
  569. }
  570. }
  571. }
  572. else
  573. {
  574. auto modn = QFileInfo(filename).baseName();
  575. QVariantMap temp;
  576. temp[modn] = repodata;
  577. repodata = temp;
  578. }
  579. manager->loadRepository(repodata);
  580. }
  581. if(filename.endsWith(".png"))
  582. images.push_back(filename);
  583. }
  584. if(!mods.empty())
  585. installMods(mods);
  586. if(!images.empty())
  587. loadScreenshots();
  588. }
  589. void CModListView::installMods(QStringList archives)
  590. {
  591. QStringList modNames;
  592. for(QString archive : archives)
  593. {
  594. // get basename out of full file name
  595. // remove path remove extension
  596. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  597. modNames.push_back(modName);
  598. }
  599. QStringList modsToEnable;
  600. // disable mod(s), to properly recalculate dependencies, if changed
  601. for(QString mod : boost::adaptors::reverse(modNames))
  602. {
  603. CModEntry entry = modModel->getMod(mod);
  604. if(entry.isInstalled())
  605. {
  606. // enable mod if installed and enabled
  607. if(entry.isEnabled())
  608. modsToEnable.push_back(mod);
  609. }
  610. else
  611. {
  612. // enable mod if m
  613. if(settings["launcher"]["enableInstalledMods"].Bool())
  614. modsToEnable.push_back(mod);
  615. }
  616. }
  617. // uninstall old version of mod, if installed
  618. for(QString mod : boost::adaptors::reverse(modNames))
  619. {
  620. if(modModel->getMod(mod).isInstalled())
  621. manager->uninstallMod(mod);
  622. }
  623. for(int i = 0; i < modNames.size(); i++)
  624. manager->installMod(modNames[i], archives[i]);
  625. std::function<void(QString)> enableMod;
  626. enableMod = [&](QString modName)
  627. {
  628. auto mod = modModel->getMod(modName);
  629. if(mod.isInstalled() && !mod.getValue("keepDisabled").toBool())
  630. {
  631. if(mod.isDisabled() && manager->enableMod(modName))
  632. {
  633. for(QString child : modModel->getChildren(modName))
  634. enableMod(child);
  635. }
  636. }
  637. };
  638. for(QString mod : modsToEnable)
  639. {
  640. enableMod(mod);
  641. }
  642. for(QString archive : archives)
  643. QFile::remove(archive);
  644. checkManagerErrors();
  645. }
  646. void CModListView::on_refreshButton_clicked()
  647. {
  648. loadRepositories();
  649. }
  650. void CModListView::on_pushButton_clicked()
  651. {
  652. delete dlManager;
  653. dlManager = nullptr;
  654. hideProgressBar();
  655. }
  656. void CModListView::modelReset()
  657. {
  658. if(ui->modInfoWidget->isVisible())
  659. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  660. }
  661. void CModListView::checkManagerErrors()
  662. {
  663. QString errors = manager->getErrors().join('\n');
  664. if(errors.size() != 0)
  665. {
  666. QString title = "Operation failed";
  667. QString description = "Encountered errors:\n" + errors;
  668. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  669. }
  670. }
  671. void CModListView::on_tabWidget_currentChanged(int index)
  672. {
  673. loadScreenshots();
  674. }
  675. void CModListView::loadScreenshots()
  676. {
  677. if(ui->tabWidget->currentIndex() == 2 && ui->modInfoWidget->isVisible())
  678. {
  679. ui->screenshotsList->clear();
  680. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  681. assert(modModel->hasMod(modName)); //should be filtered out by check above
  682. for(QString & url : modModel->getMod(modName).getValue("screenshots").toStringList())
  683. {
  684. // URL must be encoded to something else to get rid of symbols illegal in file names
  685. auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  686. auto hashedStr = QString::fromUtf8(hashed.toHex());
  687. QString fullPath = CLauncherDirs::get().downloadsPath() + '/' + hashedStr + ".png";
  688. QPixmap pixmap(fullPath);
  689. if(pixmap.isNull())
  690. {
  691. // image file not exists or corrupted - try to redownload
  692. downloadFile(hashedStr + ".png", url, "screenshots");
  693. }
  694. else
  695. {
  696. // managed to load cached image
  697. QIcon icon(pixmap);
  698. QListWidgetItem * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  699. ui->screenshotsList->addItem(item);
  700. }
  701. }
  702. }
  703. }
  704. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  705. {
  706. if(index.isValid())
  707. {
  708. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  709. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  710. ImageViewer::showPixmap(pixmap, this);
  711. }
  712. }
  713. void CModListView::on_showInfoButton_clicked()
  714. {
  715. showModInfo();
  716. }
  717. const CModList & CModListView::getModList() const
  718. {
  719. assert(modModel);
  720. return *modModel;
  721. }