cmodlistview_moc.cpp 24 KB

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