cmodlistview_moc.cpp 23 KB

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