cmodlistview_moc.cpp 25 KB

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