cmodlistview_moc.cpp 25 KB

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