cmodlistview_moc.cpp 28 KB

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