cmodlistview_moc.cpp 26 KB

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