cmodlistview_moc.cpp 25 KB

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