cmodlistview_moc.cpp 24 KB

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