cmodlistview_moc.cpp 25 KB

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