cmodlistview_moc.cpp 25 KB

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