cmodlistview_moc.cpp 27 KB

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