cmodlistview_moc.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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 "modstatemodel.h"
  19. #include "modstateitemmodel_moc.h"
  20. #include "modstatecontroller.h"
  21. #include "cdownloadmanager_moc.h"
  22. #include "chroniclesextractor.h"
  23. #include "../settingsView/csettingsview_moc.h"
  24. #include "../vcmiqt/launcherdirs.h"
  25. #include "../vcmiqt/jsonutils.h"
  26. #include "../helper.h"
  27. #include "../../lib/VCMIDirs.h"
  28. #include "../../lib/CConfigHandler.h"
  29. #include "../../lib/texts/Languages.h"
  30. #include "../../lib/modding/CModVersion.h"
  31. #include "../../lib/filesystem/Filesystem.h"
  32. #include <future>
  33. void CModListView::setupModModel()
  34. {
  35. static const QString repositoryCachePath = CLauncherDirs::downloadsPath() + "/repositoryCache.json";
  36. const auto &cachedRepositoryData = JsonUtils::jsonFromFile(repositoryCachePath);
  37. modStateModel = std::make_shared<ModStateModel>();
  38. if (!cachedRepositoryData.isNull())
  39. modStateModel->appendRepositories(cachedRepositoryData);
  40. modModel = new ModStateItemModel(modStateModel, this);
  41. manager = std::make_unique<ModStateController>(modStateModel);
  42. }
  43. void CModListView::changeEvent(QEvent *event)
  44. {
  45. if(event->type() == QEvent::LanguageChange)
  46. {
  47. ui->retranslateUi(this);
  48. modModel->reloadRepositories();
  49. }
  50. QWidget::changeEvent(event);
  51. }
  52. void CModListView::dragEnterEvent(QDragEnterEvent* event)
  53. {
  54. if(event->mimeData()->hasUrls())
  55. for(const auto & url : event->mimeData()->urls())
  56. for(const auto & ending : QStringList({".zip", ".h3m", ".h3c", ".vmap", ".vcmp", ".json", ".exe"}))
  57. if(url.fileName().endsWith(ending, Qt::CaseInsensitive))
  58. {
  59. event->acceptProposedAction();
  60. return;
  61. }
  62. }
  63. void CModListView::dropEvent(QDropEvent* event)
  64. {
  65. const QMimeData* mimeData = event->mimeData();
  66. if(mimeData->hasUrls())
  67. {
  68. const QList<QUrl> urlList = mimeData->urls();
  69. for (const auto & url : urlList)
  70. manualInstallFile(url.toLocalFile());
  71. }
  72. }
  73. void CModListView::setupFilterModel()
  74. {
  75. filterModel = new CModFilterModel(modModel, this);
  76. filterModel->setFilterKeyColumn(-1); // filter across all columns
  77. filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); // to make it more user-friendly
  78. filterModel->setDynamicSortFilter(true);
  79. }
  80. void CModListView::setupModsView()
  81. {
  82. ui->allModsView->setModel(filterModel);
  83. // input data is not sorted - sort it before display
  84. ui->allModsView->sortByColumn(ModFields::TYPE, Qt::AscendingOrder);
  85. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_ENABLED, QHeaderView::Fixed);
  86. ui->allModsView->header()->setSectionResizeMode(ModFields::STATUS_UPDATE, QHeaderView::Fixed);
  87. QSettings s(Ui::teamName, Ui::appName);
  88. auto state = s.value("AllModsView/State").toByteArray();
  89. if(!state.isNull()) //read last saved settings
  90. {
  91. ui->allModsView->header()->restoreState(state);
  92. }
  93. else //default //TODO: default high-DPI scaling
  94. {
  95. ui->allModsView->setColumnWidth(ModFields::NAME, 220);
  96. ui->allModsView->setColumnWidth(ModFields::TYPE, 75);
  97. }
  98. ui->allModsView->resizeColumnToContents(ModFields::STATUS_ENABLED);
  99. ui->allModsView->resizeColumnToContents(ModFields::STATUS_UPDATE);
  100. ui->allModsView->setUniformRowHeights(true);
  101. connect(ui->allModsView->selectionModel(), SIGNAL(currentRowChanged(const QModelIndex&,const QModelIndex&)),
  102. this, SLOT(modSelected(const QModelIndex&,const QModelIndex&)));
  103. connect(filterModel, SIGNAL(modelReset()),
  104. this, SLOT(modelReset()));
  105. connect(modModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
  106. this, SLOT(dataChanged(QModelIndex,QModelIndex)));
  107. }
  108. CModListView::CModListView(QWidget * parent)
  109. : QWidget(parent)
  110. , ui(new Ui::CModListView)
  111. {
  112. ui->setupUi(this);
  113. setAcceptDrops(true);
  114. ui->uninstallButton->setIcon(QIcon{":/icons/mod-delete.png"});
  115. ui->enableButton->setIcon(QIcon{":/icons/mod-enabled.png"});
  116. ui->disableButton->setIcon(QIcon{":/icons/mod-disabled.png"});
  117. ui->updateButton->setIcon(QIcon{":/icons/mod-update.png"});
  118. ui->installButton->setIcon(QIcon{":/icons/mod-download.png"});
  119. ui->splitter->setStyleSheet("QSplitter::handle {background: palette('window');}");
  120. setupModModel();
  121. setupFilterModel();
  122. setupModsView();
  123. ui->progressWidget->setVisible(false);
  124. dlManager = nullptr;
  125. if(settings["launcher"]["autoCheckRepositories"].Bool())
  126. loadRepositories();
  127. #ifdef VCMI_MOBILE
  128. for(auto * scrollWidget : {
  129. (QAbstractItemView*)ui->allModsView,
  130. (QAbstractItemView*)ui->screenshotsList})
  131. {
  132. Helper::enableScrollBySwiping(scrollWidget);
  133. scrollWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
  134. scrollWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
  135. }
  136. #endif
  137. }
  138. void CModListView::loadRepositories()
  139. {
  140. QStringList repositories;
  141. if (settings["launcher"]["defaultRepositoryEnabled"].Bool())
  142. repositories.push_back(QString::fromStdString(settings["launcher"]["defaultRepositoryURL"].String()));
  143. if (settings["launcher"]["extraRepositoryEnabled"].Bool())
  144. repositories.push_back(QString::fromStdString(settings["launcher"]["extraRepositoryURL"].String()));
  145. for(const auto & entry : repositories)
  146. {
  147. if (entry.isEmpty())
  148. continue;
  149. // URL must be encoded to something else to get rid of symbols illegal in file names
  150. auto hashed = QCryptographicHash::hash(entry.toUtf8(), QCryptographicHash::Md5);
  151. auto hashedStr = QString::fromUtf8(hashed.toHex());
  152. downloadFile(hashedStr + ".json", entry, tr("mods repository index"));
  153. }
  154. }
  155. CModListView::~CModListView()
  156. {
  157. QSettings s(Ui::teamName, Ui::appName);
  158. s.setValue("AllModsView/State", ui->allModsView->header()->saveState());
  159. delete ui;
  160. }
  161. static QString replaceIfNotEmpty(QVariant value, QString pattern)
  162. {
  163. if(value.canConvert<QString>())
  164. {
  165. if (value.toString().isEmpty())
  166. return "";
  167. else
  168. return pattern.arg(value.toString());
  169. }
  170. if(value.canConvert<QStringList>())
  171. {
  172. if (value.toStringList().isEmpty())
  173. return "";
  174. else
  175. return pattern.arg(value.toStringList().join(", "));
  176. }
  177. // all valid types of data should have been filtered by code above
  178. assert(!value.isValid());
  179. return "";
  180. }
  181. static QString replaceIfNotEmpty(QStringList value, QString pattern)
  182. {
  183. if(!value.empty())
  184. return pattern.arg(value.join(", "));
  185. return "";
  186. }
  187. QString CModListView::genChangelogText(const ModState & mod)
  188. {
  189. QString headerTemplate = "<p><span style=\" font-weight:600;\">%1: </span></p>";
  190. QString entryBegin = "<p align=\"justify\"><ul>";
  191. QString entryEnd = "</ul></p>";
  192. QString entryLine = "<li>%1</li>";
  193. //QString versionSeparator = "<hr/>";
  194. QString result;
  195. QMap<QString, QStringList> changelog = mod.getChangelog();
  196. QList<QString> versions = changelog.keys();
  197. std::sort(versions.begin(), versions.end(), [](QString lesser, QString greater)
  198. {
  199. return CModVersion::fromString(lesser.toStdString()) < CModVersion::fromString(greater.toStdString());
  200. });
  201. std::reverse(versions.begin(), versions.end());
  202. for(const auto & version : versions)
  203. {
  204. result += headerTemplate.arg(version);
  205. result += entryBegin;
  206. for(const auto & line : changelog.value(version))
  207. result += entryLine.arg(line);
  208. result += entryEnd;
  209. }
  210. return result;
  211. }
  212. QStringList CModListView::getModNames(QString queryingModID, QStringList input)
  213. {
  214. QStringList result;
  215. auto queryingMod = modStateModel->getMod(queryingModID);
  216. for(const auto & modID : input)
  217. {
  218. if (modStateModel->isModExists(modID) && modStateModel->getMod(modID).isHidden())
  219. continue;
  220. QString parentModID = modStateModel->getTopParent(modID);
  221. QString displayName;
  222. if (modStateModel->isSubmod(modID) && queryingMod.getParentID() != parentModID )
  223. {
  224. // show in form "parent mod (submod)"
  225. QString parentDisplayName = parentModID;
  226. QString submodDisplayName = modID;
  227. if (modStateModel->isModExists(parentModID))
  228. parentDisplayName = modStateModel->getMod(parentModID).getName();
  229. if (modStateModel->isModExists(modID))
  230. submodDisplayName = modStateModel->getMod(modID).getName();
  231. displayName = QString("%1 (%2)").arg(submodDisplayName, parentDisplayName);
  232. }
  233. else
  234. {
  235. // show simply as mod name
  236. displayName = modID;
  237. if (modStateModel->isModExists(modID))
  238. displayName = modStateModel->getMod(modID).getName();
  239. }
  240. result += displayName;
  241. }
  242. return result;
  243. }
  244. QString CModListView::genModInfoText(const ModState & mod)
  245. {
  246. QString prefix = "<p><span style=\" font-weight:600;\">%1: </span>"; // shared prefix
  247. QString redPrefix = "<p><span style=\" font-weight:600; color:red\">%1: </span>"; // shared prefix
  248. QString lineTemplate = prefix + "%2</p>";
  249. QString urlTemplate = prefix + "<a href=\"%2\">%3</a></p>";
  250. QString textTemplate = prefix + "</p><p align=\"justify\">%2</p>";
  251. QString listTemplate = "<p align=\"justify\">%1: %2</p>";
  252. QString noteTemplate = "<p align=\"justify\">%1</p>";
  253. QString incompatibleString = redPrefix + tr("Mod is incompatible") + "</p>";
  254. QString supportedVersions = redPrefix + "%2 %3 %4</p>";
  255. QString result;
  256. result += replaceIfNotEmpty(mod.getName(), lineTemplate.arg(tr("Mod name")));
  257. if (mod.isUpdateAvailable())
  258. {
  259. result += replaceIfNotEmpty(mod.getInstalledVersion(), lineTemplate.arg(tr("Installed version")));
  260. result += replaceIfNotEmpty(mod.getRepositoryVersion(), lineTemplate.arg(tr("Latest version")));
  261. }
  262. else
  263. {
  264. if (mod.isInstalled())
  265. result += replaceIfNotEmpty(mod.getInstalledVersion(), lineTemplate.arg(tr("Installed version")));
  266. else
  267. result += replaceIfNotEmpty(mod.getRepositoryVersion(), lineTemplate.arg(tr("Latest version")));
  268. }
  269. if (mod.isInstalled())
  270. result += replaceIfNotEmpty(modStateModel->getInstalledModSizeFormatted(mod.getID()), lineTemplate.arg(tr("Size")));
  271. if((!mod.isInstalled() || mod.isUpdateAvailable()) && !mod.getDownloadSizeFormatted().isEmpty())
  272. result += replaceIfNotEmpty(mod.getDownloadSizeFormatted(), lineTemplate.arg(tr("Download size")));
  273. result += replaceIfNotEmpty(mod.getAuthors(), lineTemplate.arg(tr("Authors")));
  274. if(!mod.getLicenseName().isEmpty())
  275. result += urlTemplate.arg(tr("License")).arg(mod.getLicenseUrl()).arg(mod.getLicenseName());
  276. if(!mod.getContact().isEmpty())
  277. result += urlTemplate.arg(tr("Contact")).arg(mod.getContact()).arg(mod.getContact());
  278. //compatibility info
  279. if(!mod.isCompatible())
  280. {
  281. auto compatibilityInfo = mod.getCompatibleVersionRange();
  282. auto minStr = compatibilityInfo.first;
  283. auto maxStr = compatibilityInfo.second;
  284. result += incompatibleString.arg(tr("Compatibility"));
  285. if(minStr == maxStr)
  286. result += supportedVersions.arg(tr("Required VCMI version"), minStr, "", "");
  287. else
  288. {
  289. if(minStr.isEmpty() || maxStr.isEmpty())
  290. {
  291. if(minStr.isEmpty())
  292. result += supportedVersions.arg(tr("Supported VCMI version"), maxStr, ", ", tr("please upgrade mod"));
  293. else
  294. result += supportedVersions.arg(tr("Required VCMI version"), minStr, " ", tr("or newer"));
  295. }
  296. else
  297. result += supportedVersions.arg(tr("Supported VCMI versions"), minStr, " - ", maxStr);
  298. }
  299. }
  300. QVariant baseLanguageVariant = mod.getBaseLanguage();
  301. QString baseLanguageID = baseLanguageVariant.isValid() ? baseLanguageVariant.toString() : "english";
  302. QStringList supportedLanguages = mod.getSupportedLanguages();
  303. if(supportedLanguages.size() > 1)
  304. {
  305. QStringList supportedLanguagesTranslated;
  306. for (const auto & languageID : supportedLanguages)
  307. supportedLanguagesTranslated += QApplication::translate("Language", Languages::getLanguageOptions(languageID.toStdString()).nameEnglish.c_str());
  308. result += replaceIfNotEmpty(supportedLanguagesTranslated, lineTemplate.arg(tr("Languages")));
  309. }
  310. QStringList conflicts = mod.getConflicts();
  311. for (const auto & otherMod : modStateModel->getAllMods())
  312. {
  313. QStringList otherConflicts = modStateModel->getMod(otherMod).getConflicts();
  314. if (otherConflicts.contains(mod.getID()) && !conflicts.contains(otherMod))
  315. conflicts.push_back(otherMod);
  316. }
  317. result += replaceIfNotEmpty(getModNames(mod.getID(), mod.getDependencies()), lineTemplate.arg(tr("Required mods")));
  318. result += replaceIfNotEmpty(getModNames(mod.getID(), conflicts), lineTemplate.arg(tr("Conflicting mods")));
  319. result += replaceIfNotEmpty(mod.getDescription(), textTemplate.arg(tr("Description")));
  320. result += "<p></p>"; // to get some empty space
  321. QString notInstalledDeps = tr("This mod can not be enabled because the following dependencies are not present");
  322. QString unavailableDeps = tr("This mod can not be installed because the following dependencies are not present");
  323. QString thisIsSubmod = tr("This is a submod and it cannot be installed or uninstalled separately from its parent mod");
  324. QString notes;
  325. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  326. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  327. if (mod.isInstalled())
  328. notes += replaceIfNotEmpty(getModNames(mod.getID(), notInstalledDependencies), listTemplate.arg(notInstalledDeps));
  329. else
  330. notes += replaceIfNotEmpty(getModNames(mod.getID(), unavailableDependencies), listTemplate.arg(unavailableDeps));
  331. if(mod.isSubmod())
  332. notes += noteTemplate.arg(thisIsSubmod);
  333. if(notes.size())
  334. result += textTemplate.arg(tr("Notes")).arg(notes);
  335. return result;
  336. }
  337. void CModListView::disableModInfo()
  338. {
  339. ui->disableButton->setVisible(false);
  340. ui->enableButton->setVisible(false);
  341. ui->installButton->setVisible(false);
  342. ui->uninstallButton->setVisible(false);
  343. ui->updateButton->setVisible(false);
  344. }
  345. void CModListView::dataChanged(const QModelIndex & topleft, const QModelIndex & bottomRight)
  346. {
  347. selectMod(ui->allModsView->currentIndex());
  348. }
  349. void CModListView::selectMod(const QModelIndex & index)
  350. {
  351. ui->tabWidget->setCurrentIndex(0);
  352. if(!index.isValid())
  353. {
  354. disableModInfo();
  355. }
  356. else
  357. {
  358. const auto modName = index.data(ModRoles::ModNameRole).toString();
  359. auto mod = modStateModel->getMod(modName);
  360. ui->tabWidget->setTabEnabled(1, !mod.getChangelog().isEmpty());
  361. ui->tabWidget->setTabEnabled(2, !mod.getScreenshots().isEmpty());
  362. ui->modInfoBrowser->setHtml(genModInfoText(mod));
  363. ui->changelogBrowser->setHtml(genChangelogText(mod));
  364. Helper::enableScrollBySwiping(ui->modInfoBrowser);
  365. Helper::enableScrollBySwiping(ui->changelogBrowser);
  366. QStringList notInstalledDependencies = this->getModsToInstall(modName);
  367. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  368. ui->disableButton->setVisible(modStateModel->isModInstalled(mod.getID()) && modStateModel->isModEnabled(mod.getID()));
  369. ui->enableButton->setVisible(modStateModel->isModInstalled(mod.getID()) && !modStateModel->isModEnabled(mod.getID()));
  370. ui->installButton->setVisible(mod.isAvailable() && !mod.isSubmod());
  371. ui->uninstallButton->setVisible(mod.isInstalled() && !mod.isSubmod());
  372. ui->updateButton->setVisible(mod.isUpdateAvailable());
  373. // Block buttons if action is not allowed at this time
  374. ui->disableButton->setEnabled(true);
  375. ui->enableButton->setEnabled(notInstalledDependencies.empty());
  376. ui->installButton->setEnabled(unavailableDependencies.empty());
  377. ui->uninstallButton->setEnabled(true);
  378. ui->updateButton->setEnabled(unavailableDependencies.empty());
  379. loadScreenshots();
  380. }
  381. }
  382. void CModListView::modSelected(const QModelIndex & current, const QModelIndex &)
  383. {
  384. selectMod(current);
  385. }
  386. void CModListView::on_allModsView_activated(const QModelIndex & index)
  387. {
  388. selectMod(index);
  389. loadScreenshots();
  390. }
  391. void CModListView::on_lineEdit_textChanged(const QString & arg1)
  392. {
  393. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  394. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1, QRegularExpression::UnanchoredWildcardConversion);
  395. #else
  396. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1);
  397. //Hack due to lack QRegularExpression::UnanchoredWildcardConversion in Qt5
  398. baseStr.chop(3);
  399. baseStr.remove(0,5);
  400. #endif
  401. QRegularExpression regExp{baseStr, QRegularExpression::CaseInsensitiveOption};
  402. filterModel->setFilterRegularExpression(regExp);
  403. }
  404. void CModListView::on_comboBox_currentIndexChanged(int index)
  405. {
  406. auto enumIndex = static_cast<ModFilterMask>(index);
  407. filterModel->setTypeFilter(enumIndex);
  408. }
  409. QStringList CModListView::findUnavailableMods(QStringList candidates)
  410. {
  411. QStringList invalidMods;
  412. for(QString modName : candidates)
  413. {
  414. if(!modStateModel->isModExists(modName))
  415. invalidMods.push_back(modName);
  416. }
  417. return invalidMods;
  418. }
  419. void CModListView::on_enableButton_clicked()
  420. {
  421. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  422. enableModByName(modName);
  423. checkManagerErrors();
  424. }
  425. void CModListView::enableModByName(QString modName)
  426. {
  427. manager->enableMods({modName});
  428. modModel->reloadRepositories();
  429. }
  430. void CModListView::on_disableButton_clicked()
  431. {
  432. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  433. disableModByName(modName);
  434. checkManagerErrors();
  435. }
  436. void CModListView::disableModByName(QString modName)
  437. {
  438. manager->disableMod(modName);
  439. modModel->reloadRepositories();
  440. }
  441. QStringList CModListView::getModsToInstall(QString mod)
  442. {
  443. QStringList result;
  444. QStringList candidates;
  445. QStringList processed;
  446. candidates.push_back(mod);
  447. while (!candidates.empty())
  448. {
  449. QString potentialToInstall = candidates.back();
  450. candidates.pop_back();
  451. processed.push_back(potentialToInstall);
  452. if (modStateModel->isModInstalled(potentialToInstall))
  453. continue;
  454. if (modStateModel->isSubmod(potentialToInstall))
  455. {
  456. QString topParent = modStateModel->getTopParent(potentialToInstall);
  457. if (modStateModel->isModInstalled(topParent))
  458. {
  459. if (modStateModel->isModUpdateAvailable(topParent))
  460. potentialToInstall = modStateModel->getTopParent(potentialToInstall);
  461. // else - potentially broken mod that depends on non-existing submod
  462. }
  463. else
  464. potentialToInstall = modStateModel->getTopParent(potentialToInstall);
  465. }
  466. result.push_back(potentialToInstall);
  467. if (modStateModel->isModExists(potentialToInstall))
  468. {
  469. QStringList dependencies = modStateModel->getMod(potentialToInstall).getDependencies();
  470. for (const auto & dependency : dependencies)
  471. {
  472. if (!processed.contains(dependency) && !candidates.contains(dependency))
  473. candidates.push_back(dependency);
  474. }
  475. }
  476. }
  477. assert(result.removeDuplicates() == 0);
  478. return result;
  479. }
  480. void CModListView::on_updateButton_clicked()
  481. {
  482. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  483. for(const auto & name : getModsToInstall(modName))
  484. {
  485. auto mod = modStateModel->getMod(name);
  486. // update required mod, install missing (can be new dependency)
  487. if(mod.isUpdateAvailable() || !mod.isInstalled())
  488. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeMegabytes());
  489. }
  490. }
  491. void CModListView::on_uninstallButton_clicked()
  492. {
  493. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  494. if(modStateModel->isModExists(modName) && modStateModel->getMod(modName).isInstalled())
  495. {
  496. if(modStateModel->isModEnabled(modName))
  497. manager->disableMod(modName);
  498. manager->uninstallMod(modName);
  499. modModel->reloadRepositories();
  500. }
  501. checkManagerErrors();
  502. }
  503. void CModListView::on_installButton_clicked()
  504. {
  505. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  506. for(const auto & name : getModsToInstall(modName))
  507. {
  508. auto mod = modStateModel->getMod(name);
  509. if(mod.isAvailable())
  510. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeMegabytes());
  511. else if(!modStateModel->isModEnabled(name))
  512. enableModByName(name);
  513. }
  514. }
  515. void CModListView::on_installFromFileButton_clicked()
  516. {
  517. // iOS can't display modal dialogs when called directly on button press
  518. // https://bugreports.qt.io/browse/QTBUG-98651
  519. QTimer::singleShot(0, this, [this]
  520. {
  521. QString filter = tr("All supported files") + " (*.h3m *.vmap *.h3c *.vcmp *.zip *.json *.exe);;" +
  522. tr("Maps") + " (*.h3m *.vmap);;" +
  523. tr("Campaigns") + " (*.h3c *.vcmp);;" +
  524. tr("Configs") + " (*.json);;" +
  525. tr("Mods") + " (*.zip);;" +
  526. tr("Gog files") + " (*.exe)";
  527. #if defined(VCMI_MOBILE)
  528. filter = tr("All files (*.*)"); //Workaround for sometimes incorrect mime for some extensions (e.g. for exe)
  529. #endif
  530. QStringList files = QFileDialog::getOpenFileNames(this, tr("Select files (configs, mods, maps, campaigns, gog files) to install..."), QDir::homePath(), filter);
  531. for(const auto & file : files)
  532. {
  533. manualInstallFile(file);
  534. }
  535. });
  536. }
  537. void CModListView::manualInstallFile(QString filePath)
  538. {
  539. QString fileName = QFileInfo{filePath}.fileName();
  540. if(filePath.endsWith(".zip", Qt::CaseInsensitive))
  541. downloadFile(fileName.toLower()
  542. // mod name currently comes from zip file -> remove suffixes from github zip download
  543. .replace(QRegularExpression("-[0-9a-f]{40}"), "")
  544. .replace(QRegularExpression("-vcmi-.+\\.zip"), ".zip")
  545. .replace("-main.zip", ".zip")
  546. , QUrl::fromLocalFile(filePath), "mods");
  547. else if(filePath.endsWith(".json", Qt::CaseInsensitive))
  548. {
  549. QDir configDir(QString::fromStdString(VCMIDirs::get().userConfigPath().string()));
  550. QStringList configFile = configDir.entryList({fileName}, QDir::Filter::Files); // case insensitive check
  551. if(!configFile.empty())
  552. {
  553. auto dialogResult = QMessageBox::warning(this, tr("Replace config file?"), tr("Do you want to replace %1?").arg(configFile[0]), QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
  554. if(dialogResult == QMessageBox::Yes)
  555. {
  556. const auto configFilePath = configDir.filePath(configFile[0]);
  557. QFile::remove(configFilePath);
  558. QFile::copy(filePath, configFilePath);
  559. // reload settings
  560. Helper::loadSettings();
  561. for(const auto widget : qApp->allWidgets())
  562. if(auto settingsView = qobject_cast<CSettingsView *>(widget))
  563. settingsView->loadSettings();
  564. modStateModel->reloadLocalState();
  565. modModel->reloadRepositories();
  566. }
  567. }
  568. }
  569. else
  570. downloadFile(fileName, QUrl::fromLocalFile(filePath), fileName);
  571. }
  572. void CModListView::downloadFile(QString file, QString url, QString description, qint64 size)
  573. {
  574. downloadFile(file, QUrl{url}, description, size);
  575. }
  576. void CModListView::downloadFile(QString file, QUrl url, QString description, qint64 size)
  577. {
  578. if(!dlManager)
  579. {
  580. dlManager = new CDownloadManager();
  581. ui->progressWidget->setVisible(true);
  582. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  583. this, SLOT(downloadProgress(qint64,qint64)));
  584. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  585. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  586. connect(manager.get(), SIGNAL(extractionProgress(qint64,qint64)),
  587. this, SLOT(extractionProgress(qint64,qint64)));
  588. connect(modModel, &ModStateItemModel::dataChanged, filterModel, &QAbstractItemModel::dataChanged);
  589. const auto progressBarFormat = tr("Downloading %1. %p% (%v MB out of %m MB) finished").arg(description);
  590. ui->progressBar->setFormat(progressBarFormat);
  591. }
  592. dlManager->downloadFile(url, file, size);
  593. }
  594. void CModListView::downloadProgress(qint64 current, qint64 max)
  595. {
  596. // display progress, in megabytes
  597. ui->progressBar->setVisible(true);
  598. ui->progressBar->setMaximum(max / (1024 * 1024));
  599. ui->progressBar->setValue(current / (1024 * 1024));
  600. }
  601. void CModListView::extractionProgress(qint64 current, qint64 max)
  602. {
  603. // display progress, in extracted files
  604. ui->progressBar->setVisible(true);
  605. ui->progressBar->setMaximum(max);
  606. ui->progressBar->setValue(current);
  607. }
  608. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  609. {
  610. QString title = tr("Download failed");
  611. QString firstLine = tr("Unable to download all files.\n\nEncountered errors:\n\n");
  612. QString lastLine = tr("\n\nInstall successfully downloaded?");
  613. bool doInstallFiles = false;
  614. // if all files were d/loaded there should be no errors. And on failure there must be an error
  615. assert(failedFiles.empty() == errors.empty());
  616. if(savedFiles.empty())
  617. {
  618. // no successfully downloaded mods
  619. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  620. }
  621. else if(!failedFiles.empty())
  622. {
  623. // some mods were not downloaded
  624. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  625. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  626. if(result == QMessageBox::Yes)
  627. doInstallFiles = true;
  628. }
  629. else
  630. {
  631. // everything OK
  632. doInstallFiles = true;
  633. }
  634. dlManager->deleteLater();
  635. dlManager = nullptr;
  636. ui->progressBar->setMaximum(0);
  637. ui->progressBar->setValue(0);
  638. if(doInstallFiles)
  639. installFiles(savedFiles);
  640. hideProgressBar();
  641. }
  642. void CModListView::hideProgressBar()
  643. {
  644. if(dlManager == nullptr) // it was not recreated meanwhile
  645. {
  646. ui->progressWidget->setVisible(false);
  647. ui->progressBar->setMaximum(0);
  648. ui->progressBar->setValue(0);
  649. }
  650. }
  651. void CModListView::installFiles(QStringList files)
  652. {
  653. QStringList mods;
  654. QStringList maps;
  655. QStringList images;
  656. QStringList exe;
  657. JsonNode repository;
  658. // TODO: some better way to separate zip's with mods and downloaded repository files
  659. for(QString filename : files)
  660. {
  661. if(filename.endsWith(".zip", Qt::CaseInsensitive))
  662. mods.push_back(filename);
  663. else if(filename.endsWith(".h3m", Qt::CaseInsensitive) || filename.endsWith(".h3c", Qt::CaseInsensitive) || filename.endsWith(".vmap", Qt::CaseInsensitive) || filename.endsWith(".vcmp", Qt::CaseInsensitive))
  664. maps.push_back(filename);
  665. if(filename.endsWith(".exe", Qt::CaseInsensitive))
  666. exe.push_back(filename);
  667. else if(filename.endsWith(".json", Qt::CaseInsensitive))
  668. {
  669. //download and merge additional files
  670. const auto &repoData = JsonUtils::jsonFromFile(filename);
  671. if(repoData["name"].isNull())
  672. {
  673. // This is main repository index. Download all referenced mods
  674. for(const auto & [modName, modJson] : repoData.Struct())
  675. {
  676. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  677. auto modJsonUrl = modJson["mod"];
  678. if(!modJsonUrl.isNull())
  679. downloadFile(QString::fromStdString(modName + ".json"), QString::fromStdString(modJsonUrl.String()), tr("mods repository index"));
  680. repository[modNameLower] = modJson;
  681. }
  682. }
  683. else
  684. {
  685. // This is json of a single mod. Extract name of mod and add it to repo
  686. auto modName = QFileInfo(filename).baseName().toStdString();
  687. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  688. repository[modNameLower] = repoData;
  689. }
  690. }
  691. else if(filename.endsWith(".png", Qt::CaseInsensitive))
  692. images.push_back(filename);
  693. }
  694. if (!repository.isNull())
  695. {
  696. manager->appendRepositories(repository);
  697. modModel->reloadRepositories();
  698. static const QString repositoryCachePath = CLauncherDirs::downloadsPath() + "/repositoryCache.json";
  699. JsonUtils::jsonToFile(repositoryCachePath, modStateModel->getRepositoryData());
  700. }
  701. if(!mods.empty())
  702. installMods(mods);
  703. if(!maps.empty())
  704. installMaps(maps);
  705. if(!exe.empty())
  706. {
  707. ui->progressBar->setFormat(tr("Installing chronicles"));
  708. float prog = 0.0;
  709. auto futureExtract = std::async(std::launch::async, [this, exe, &prog]()
  710. {
  711. ChroniclesExtractor ce(this, [&prog](float progress) { prog = progress; });
  712. ce.installChronicles(exe);
  713. return true;
  714. });
  715. while(futureExtract.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
  716. {
  717. emit extractionProgress(static_cast<int>(prog * 1000.f), 1000);
  718. qApp->processEvents();
  719. }
  720. if(futureExtract.get())
  721. {
  722. //update
  723. modStateModel->reloadLocalState();
  724. modModel->reloadRepositories();
  725. }
  726. }
  727. if(!images.empty())
  728. loadScreenshots();
  729. }
  730. void CModListView::installMods(QStringList archives)
  731. {
  732. QStringList modNames;
  733. QStringList modsToEnable;
  734. for(QString archive : archives)
  735. {
  736. // get basename out of full file name
  737. // remove path remove extension
  738. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  739. modNames.push_back(modName);
  740. }
  741. // uninstall old version of mod, if installed
  742. for(QString mod : modNames)
  743. {
  744. if(modStateModel->getMod(mod).isInstalled())
  745. {
  746. if (modStateModel->isModEnabled(mod))
  747. modsToEnable.push_back(mod);
  748. manager->uninstallMod(mod);
  749. }
  750. else
  751. {
  752. // installation of previously not present mod -> enable it
  753. modsToEnable.push_back(mod);
  754. }
  755. }
  756. for(int i = 0; i < modNames.size(); i++)
  757. {
  758. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  759. manager->installMod(modNames[i], archives[i]);
  760. }
  761. manager->enableMods(modsToEnable);
  762. checkManagerErrors();
  763. for(QString archive : archives)
  764. QFile::remove(archive);
  765. }
  766. void CModListView::installMaps(QStringList maps)
  767. {
  768. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  769. for(QString map : maps)
  770. {
  771. QFile(map).rename(destDir + map.section('/', -1, -1));
  772. }
  773. }
  774. void CModListView::on_refreshButton_clicked()
  775. {
  776. loadRepositories();
  777. }
  778. void CModListView::on_pushButton_clicked()
  779. {
  780. delete dlManager;
  781. dlManager = nullptr;
  782. hideProgressBar();
  783. }
  784. void CModListView::modelReset()
  785. {
  786. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  787. }
  788. void CModListView::checkManagerErrors()
  789. {
  790. QString errors = manager->getErrors().join('\n');
  791. if(errors.size() != 0)
  792. {
  793. QString title = tr("Operation failed");
  794. QString description = tr("Encountered errors:\n") + errors;
  795. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  796. }
  797. }
  798. void CModListView::on_tabWidget_currentChanged(int index)
  799. {
  800. loadScreenshots();
  801. }
  802. void CModListView::loadScreenshots()
  803. {
  804. if(ui->tabWidget->currentIndex() == 2)
  805. {
  806. if(!ui->allModsView->currentIndex().isValid())
  807. {
  808. // select the first mod, so we can access its data
  809. ui->allModsView->setCurrentIndex(filterModel->index(0, 0));
  810. }
  811. ui->screenshotsList->clear();
  812. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  813. assert(modStateModel->isModExists(modName)); //should be filtered out by check above
  814. for(QString url : modStateModel->getMod(modName).getScreenshots())
  815. {
  816. // URL must be encoded to something else to get rid of symbols illegal in file names
  817. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  818. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  819. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  820. QPixmap pixmap(fullPath);
  821. if(pixmap.isNull())
  822. {
  823. // image file not exists or corrupted - try to redownload
  824. downloadFile(fileName, url, tr("screenshots"));
  825. }
  826. else
  827. {
  828. // managed to load cached image
  829. QIcon icon(pixmap);
  830. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  831. ui->screenshotsList->addItem(item);
  832. }
  833. }
  834. }
  835. }
  836. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  837. {
  838. if(index.isValid())
  839. {
  840. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  841. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  842. ImageViewer::showPixmap(pixmap, this);
  843. }
  844. }
  845. void CModListView::doInstallMod(const QString & modName)
  846. {
  847. for(const auto & name : modStateModel->getMod(modName).getDependencies())
  848. {
  849. auto mod = modStateModel->getMod(name);
  850. if(!mod.isInstalled())
  851. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeMegabytes());
  852. }
  853. }
  854. bool CModListView::isModAvailable(const QString & modName)
  855. {
  856. return !modStateModel->isModInstalled(modName);
  857. }
  858. bool CModListView::isModEnabled(const QString & modName)
  859. {
  860. return modStateModel->isModEnabled(modName);
  861. }
  862. bool CModListView::isModInstalled(const QString & modName)
  863. {
  864. auto mod = modStateModel->getMod(modName);
  865. return mod.isInstalled();
  866. }
  867. QString CModListView::getTranslationModName(const QString & language)
  868. {
  869. for(const auto & modName : modStateModel->getAllMods())
  870. {
  871. auto mod = modStateModel->getMod(modName);
  872. if (!mod.isTranslation())
  873. continue;
  874. if (mod.getBaseLanguage() != language)
  875. continue;
  876. return modName;
  877. }
  878. return QString();
  879. }
  880. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  881. {
  882. if(!index.isValid())
  883. return;
  884. auto modName = index.data(ModRoles::ModNameRole).toString();
  885. auto mod = modStateModel->getMod(modName);
  886. QStringList notInstalledDependencies = this->getModsToInstall(mod.getID());
  887. QStringList unavailableDependencies = this->findUnavailableMods(notInstalledDependencies);
  888. if(unavailableDependencies.empty() && mod.isAvailable() && !mod.isSubmod())
  889. {
  890. on_installButton_clicked();
  891. return;
  892. }
  893. if(unavailableDependencies.empty() && mod.isUpdateAvailable() && index.column() == ModFields::STATUS_UPDATE)
  894. {
  895. on_updateButton_clicked();
  896. return;
  897. }
  898. if(index.column() == ModFields::NAME)
  899. {
  900. if(ui->allModsView->isExpanded(index))
  901. ui->allModsView->collapse(index);
  902. else
  903. ui->allModsView->expand(index);
  904. return;
  905. }
  906. if(notInstalledDependencies.empty() && !modStateModel->isModEnabled(modName))
  907. {
  908. on_enableButton_clicked();
  909. return;
  910. }
  911. if(modStateModel->isModEnabled(modName))
  912. {
  913. on_disableButton_clicked();
  914. return;
  915. }
  916. }