cmodlistview_moc.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110
  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 unknownDeps = tr("This mod can not be installed or enabled because the following dependencies are not present");
  322. QString thisIsSubmod = tr("This is a submod and it cannot be installed or uninstalled separately from its parent mod");
  323. QString notes;
  324. notes += replaceIfNotEmpty(getModNames(mod.getID(), findInvalidDependencies(mod.getID())), listTemplate.arg(unknownDeps));
  325. if(mod.isSubmod())
  326. notes += noteTemplate.arg(thisIsSubmod);
  327. if(notes.size())
  328. result += textTemplate.arg(tr("Notes")).arg(notes);
  329. return result;
  330. }
  331. void CModListView::disableModInfo()
  332. {
  333. ui->disableButton->setVisible(false);
  334. ui->enableButton->setVisible(false);
  335. ui->installButton->setVisible(false);
  336. ui->uninstallButton->setVisible(false);
  337. ui->updateButton->setVisible(false);
  338. }
  339. void CModListView::dataChanged(const QModelIndex & topleft, const QModelIndex & bottomRight)
  340. {
  341. selectMod(ui->allModsView->currentIndex());
  342. }
  343. void CModListView::selectMod(const QModelIndex & index)
  344. {
  345. ui->tabWidget->setCurrentIndex(0);
  346. if(!index.isValid())
  347. {
  348. disableModInfo();
  349. }
  350. else
  351. {
  352. const auto modName = index.data(ModRoles::ModNameRole).toString();
  353. auto mod = modStateModel->getMod(modName);
  354. ui->tabWidget->setTabEnabled(1, !mod.getChangelog().isEmpty());
  355. ui->tabWidget->setTabEnabled(2, !mod.getScreenshots().isEmpty());
  356. ui->modInfoBrowser->setHtml(genModInfoText(mod));
  357. ui->changelogBrowser->setHtml(genChangelogText(mod));
  358. Helper::enableScrollBySwiping(ui->modInfoBrowser);
  359. Helper::enableScrollBySwiping(ui->changelogBrowser);
  360. //FIXME: this function should be recursive
  361. //FIXME: ensure that this is also reflected correctly in "Notes" section of mod description
  362. bool hasInvalidDeps = !findInvalidDependencies(modName).empty();
  363. ui->disableButton->setVisible(modStateModel->isModInstalled(mod.getID()) && modStateModel->isModEnabled(mod.getID()));
  364. ui->enableButton->setVisible(modStateModel->isModInstalled(mod.getID()) && !modStateModel->isModEnabled(mod.getID()));
  365. ui->installButton->setVisible(mod.isAvailable() && !mod.isSubmod());
  366. ui->uninstallButton->setVisible(mod.isInstalled() && !mod.isSubmod());
  367. ui->updateButton->setVisible(mod.isUpdateAvailable());
  368. // Block buttons if action is not allowed at this time
  369. ui->disableButton->setEnabled(true);
  370. ui->enableButton->setEnabled(!hasInvalidDeps);
  371. ui->installButton->setEnabled(!hasInvalidDeps);
  372. ui->uninstallButton->setEnabled(true);
  373. ui->updateButton->setEnabled(!hasInvalidDeps);
  374. loadScreenshots();
  375. }
  376. }
  377. void CModListView::modSelected(const QModelIndex & current, const QModelIndex &)
  378. {
  379. selectMod(current);
  380. }
  381. void CModListView::on_allModsView_activated(const QModelIndex & index)
  382. {
  383. selectMod(index);
  384. loadScreenshots();
  385. }
  386. void CModListView::on_lineEdit_textChanged(const QString & arg1)
  387. {
  388. #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
  389. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1, QRegularExpression::UnanchoredWildcardConversion);
  390. #else
  391. auto baseStr = QRegularExpression::wildcardToRegularExpression(arg1);
  392. //Hack due to lack QRegularExpression::UnanchoredWildcardConversion in Qt5
  393. baseStr.chop(3);
  394. baseStr.remove(0,5);
  395. #endif
  396. QRegularExpression regExp{baseStr, QRegularExpression::CaseInsensitiveOption};
  397. filterModel->setFilterRegularExpression(regExp);
  398. }
  399. void CModListView::on_comboBox_currentIndexChanged(int index)
  400. {
  401. auto enumIndex = static_cast<ModFilterMask>(index);
  402. filterModel->setTypeFilter(enumIndex);
  403. }
  404. QStringList CModListView::findInvalidDependencies(QString mod)
  405. {
  406. QStringList ret;
  407. for(QString requirement : modStateModel->getMod(mod).getDependencies())
  408. {
  409. if(modStateModel->isModExists(requirement))
  410. continue;
  411. if(modStateModel->isSubmod(requirement))
  412. {
  413. QString parentModID = modStateModel->getTopParent(requirement);
  414. if (modStateModel->isModExists(parentModID) && !modStateModel->isModInstalled(parentModID))
  415. continue;
  416. }
  417. ret += requirement;
  418. }
  419. return ret;
  420. }
  421. void CModListView::on_enableButton_clicked()
  422. {
  423. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  424. enableModByName(modName);
  425. checkManagerErrors();
  426. }
  427. void CModListView::enableModByName(QString modName)
  428. {
  429. manager->enableMods({modName});
  430. modModel->reloadRepositories();
  431. }
  432. void CModListView::on_disableButton_clicked()
  433. {
  434. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  435. disableModByName(modName);
  436. checkManagerErrors();
  437. }
  438. void CModListView::disableModByName(QString modName)
  439. {
  440. manager->disableMod(modName);
  441. modModel->reloadRepositories();
  442. }
  443. QStringList CModListView::getModsToInstall(QString mod)
  444. {
  445. QStringList result;
  446. QStringList candidates;
  447. QStringList processed;
  448. candidates.push_back(mod);
  449. while (!candidates.empty())
  450. {
  451. QString potentialToInstall = candidates.back();
  452. candidates.pop_back();
  453. processed.push_back(potentialToInstall);
  454. if (modStateModel->isSubmod(potentialToInstall))
  455. potentialToInstall = modStateModel->getTopParent(potentialToInstall);
  456. if (!modStateModel->isModExists(potentialToInstall))
  457. throw std::runtime_error("Attempt to install non-existing mod! Mod name:" + potentialToInstall.toStdString());
  458. if (modStateModel->isModInstalled(potentialToInstall))
  459. continue;
  460. result.push_back(potentialToInstall);
  461. QStringList dependencies = modStateModel->getMod(potentialToInstall).getDependencies();
  462. for (const auto & dependency : dependencies)
  463. {
  464. if (!processed.contains(dependency) && !candidates.contains(dependency))
  465. candidates.push_back(dependency);
  466. }
  467. }
  468. assert(result.removeDuplicates() == 0);
  469. return result;
  470. }
  471. void CModListView::on_updateButton_clicked()
  472. {
  473. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  474. assert(findInvalidDependencies(modName).empty());
  475. for(const auto & name : getModsToInstall(modName))
  476. {
  477. auto mod = modStateModel->getMod(name);
  478. // update required mod, install missing (can be new dependency)
  479. if(mod.isUpdateAvailable() || !mod.isInstalled())
  480. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeMegabytes());
  481. }
  482. }
  483. void CModListView::on_uninstallButton_clicked()
  484. {
  485. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  486. if(modStateModel->isModExists(modName) && modStateModel->getMod(modName).isInstalled())
  487. {
  488. if(modStateModel->isModEnabled(modName))
  489. manager->disableMod(modName);
  490. manager->uninstallMod(modName);
  491. modModel->reloadRepositories();
  492. }
  493. checkManagerErrors();
  494. }
  495. void CModListView::on_installButton_clicked()
  496. {
  497. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  498. assert(findInvalidDependencies(modName).empty());
  499. for(const auto & name : getModsToInstall(modName))
  500. {
  501. auto mod = modStateModel->getMod(name);
  502. if(mod.isAvailable())
  503. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeMegabytes());
  504. else if(!modStateModel->isModEnabled(name))
  505. enableModByName(name);
  506. }
  507. }
  508. void CModListView::on_installFromFileButton_clicked()
  509. {
  510. // iOS can't display modal dialogs when called directly on button press
  511. // https://bugreports.qt.io/browse/QTBUG-98651
  512. QTimer::singleShot(0, this, [this]
  513. {
  514. QString filter = tr("All supported files") + " (*.h3m *.vmap *.h3c *.vcmp *.zip *.json *.exe);;" +
  515. tr("Maps") + " (*.h3m *.vmap);;" +
  516. tr("Campaigns") + " (*.h3c *.vcmp);;" +
  517. tr("Configs") + " (*.json);;" +
  518. tr("Mods") + " (*.zip);;" +
  519. tr("Gog files") + " (*.exe)";
  520. #if defined(VCMI_MOBILE)
  521. filter = tr("All files (*.*)"); //Workaround for sometimes incorrect mime for some extensions (e.g. for exe)
  522. #endif
  523. QStringList files = QFileDialog::getOpenFileNames(this, tr("Select files (configs, mods, maps, campaigns, gog files) to install..."), QDir::homePath(), filter);
  524. for(const auto & file : files)
  525. {
  526. manualInstallFile(file);
  527. }
  528. });
  529. }
  530. void CModListView::manualInstallFile(QString filePath)
  531. {
  532. QString fileName = QFileInfo{filePath}.fileName();
  533. if(filePath.endsWith(".zip", Qt::CaseInsensitive))
  534. downloadFile(fileName.toLower()
  535. // mod name currently comes from zip file -> remove suffixes from github zip download
  536. .replace(QRegularExpression("-[0-9a-f]{40}"), "")
  537. .replace(QRegularExpression("-vcmi-.+\\.zip"), ".zip")
  538. .replace("-main.zip", ".zip")
  539. , QUrl::fromLocalFile(filePath), "mods");
  540. else if(filePath.endsWith(".json", Qt::CaseInsensitive))
  541. {
  542. QDir configDir(QString::fromStdString(VCMIDirs::get().userConfigPath().string()));
  543. QStringList configFile = configDir.entryList({fileName}, QDir::Filter::Files); // case insensitive check
  544. if(!configFile.empty())
  545. {
  546. 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);
  547. if(dialogResult == QMessageBox::Yes)
  548. {
  549. const auto configFilePath = configDir.filePath(configFile[0]);
  550. QFile::remove(configFilePath);
  551. QFile::copy(filePath, configFilePath);
  552. // reload settings
  553. Helper::loadSettings();
  554. for(const auto widget : qApp->allWidgets())
  555. if(auto settingsView = qobject_cast<CSettingsView *>(widget))
  556. settingsView->loadSettings();
  557. modStateModel->reloadLocalState();
  558. modModel->reloadRepositories();
  559. }
  560. }
  561. }
  562. else
  563. downloadFile(fileName, QUrl::fromLocalFile(filePath), fileName);
  564. }
  565. void CModListView::downloadFile(QString file, QString url, QString description, qint64 size)
  566. {
  567. downloadFile(file, QUrl{url}, description, size);
  568. }
  569. void CModListView::downloadFile(QString file, QUrl url, QString description, qint64 size)
  570. {
  571. if(!dlManager)
  572. {
  573. dlManager = new CDownloadManager();
  574. ui->progressWidget->setVisible(true);
  575. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  576. this, SLOT(downloadProgress(qint64,qint64)));
  577. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  578. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  579. connect(manager.get(), SIGNAL(extractionProgress(qint64,qint64)),
  580. this, SLOT(extractionProgress(qint64,qint64)));
  581. connect(modModel, &ModStateItemModel::dataChanged, filterModel, &QAbstractItemModel::dataChanged);
  582. const auto progressBarFormat = tr("Downloading %1. %p% (%v MB out of %m MB) finished").arg(description);
  583. ui->progressBar->setFormat(progressBarFormat);
  584. }
  585. dlManager->downloadFile(url, file, size);
  586. }
  587. void CModListView::downloadProgress(qint64 current, qint64 max)
  588. {
  589. // display progress, in megabytes
  590. ui->progressBar->setVisible(true);
  591. ui->progressBar->setMaximum(max / (1024 * 1024));
  592. ui->progressBar->setValue(current / (1024 * 1024));
  593. }
  594. void CModListView::extractionProgress(qint64 current, qint64 max)
  595. {
  596. // display progress, in extracted files
  597. ui->progressBar->setVisible(true);
  598. ui->progressBar->setMaximum(max);
  599. ui->progressBar->setValue(current);
  600. }
  601. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  602. {
  603. QString title = tr("Download failed");
  604. QString firstLine = tr("Unable to download all files.\n\nEncountered errors:\n\n");
  605. QString lastLine = tr("\n\nInstall successfully downloaded?");
  606. bool doInstallFiles = false;
  607. // if all files were d/loaded there should be no errors. And on failure there must be an error
  608. assert(failedFiles.empty() == errors.empty());
  609. if(savedFiles.empty())
  610. {
  611. // no successfully downloaded mods
  612. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok);
  613. }
  614. else if(!failedFiles.empty())
  615. {
  616. // some mods were not downloaded
  617. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  618. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  619. if(result == QMessageBox::Yes)
  620. doInstallFiles = true;
  621. }
  622. else
  623. {
  624. // everything OK
  625. doInstallFiles = true;
  626. }
  627. dlManager->deleteLater();
  628. dlManager = nullptr;
  629. ui->progressBar->setMaximum(0);
  630. ui->progressBar->setValue(0);
  631. if(doInstallFiles)
  632. installFiles(savedFiles);
  633. hideProgressBar();
  634. }
  635. void CModListView::hideProgressBar()
  636. {
  637. if(dlManager == nullptr) // it was not recreated meanwhile
  638. {
  639. ui->progressWidget->setVisible(false);
  640. ui->progressBar->setMaximum(0);
  641. ui->progressBar->setValue(0);
  642. }
  643. }
  644. void CModListView::installFiles(QStringList files)
  645. {
  646. QStringList mods;
  647. QStringList maps;
  648. QStringList images;
  649. QStringList exe;
  650. JsonNode repository;
  651. // TODO: some better way to separate zip's with mods and downloaded repository files
  652. for(QString filename : files)
  653. {
  654. if(filename.endsWith(".zip", Qt::CaseInsensitive))
  655. mods.push_back(filename);
  656. else if(filename.endsWith(".h3m", Qt::CaseInsensitive) || filename.endsWith(".h3c", Qt::CaseInsensitive) || filename.endsWith(".vmap", Qt::CaseInsensitive) || filename.endsWith(".vcmp", Qt::CaseInsensitive))
  657. maps.push_back(filename);
  658. if(filename.endsWith(".exe", Qt::CaseInsensitive))
  659. exe.push_back(filename);
  660. else if(filename.endsWith(".json", Qt::CaseInsensitive))
  661. {
  662. //download and merge additional files
  663. const auto &repoData = JsonUtils::jsonFromFile(filename);
  664. if(repoData["name"].isNull())
  665. {
  666. // This is main repository index. Download all referenced mods
  667. for(const auto & [modName, modJson] : repoData.Struct())
  668. {
  669. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  670. auto modJsonUrl = modJson["mod"];
  671. if(!modJsonUrl.isNull())
  672. downloadFile(QString::fromStdString(modName + ".json"), QString::fromStdString(modJsonUrl.String()), tr("mods repository index"));
  673. repository[modNameLower] = modJson;
  674. }
  675. }
  676. else
  677. {
  678. // This is json of a single mod. Extract name of mod and add it to repo
  679. auto modName = QFileInfo(filename).baseName().toStdString();
  680. auto modNameLower = boost::algorithm::to_lower_copy(modName);
  681. repository[modNameLower] = repoData;
  682. }
  683. }
  684. else if(filename.endsWith(".png", Qt::CaseInsensitive))
  685. images.push_back(filename);
  686. }
  687. if (!repository.isNull())
  688. {
  689. manager->appendRepositories(repository);
  690. modModel->reloadRepositories();
  691. static const QString repositoryCachePath = CLauncherDirs::downloadsPath() + "/repositoryCache.json";
  692. JsonUtils::jsonToFile(repositoryCachePath, modStateModel->getRepositoryData());
  693. }
  694. if(!mods.empty())
  695. installMods(mods);
  696. if(!maps.empty())
  697. installMaps(maps);
  698. if(!exe.empty())
  699. {
  700. ui->progressBar->setFormat(tr("Installing chronicles"));
  701. float prog = 0.0;
  702. auto futureExtract = std::async(std::launch::async, [this, exe, &prog]()
  703. {
  704. ChroniclesExtractor ce(this, [&prog](float progress) { prog = progress; });
  705. ce.installChronicles(exe);
  706. return true;
  707. });
  708. while(futureExtract.wait_for(std::chrono::milliseconds(10)) != std::future_status::ready)
  709. {
  710. emit extractionProgress(static_cast<int>(prog * 1000.f), 1000);
  711. qApp->processEvents();
  712. }
  713. if(futureExtract.get())
  714. {
  715. //update
  716. modStateModel->reloadLocalState();
  717. modModel->reloadRepositories();
  718. }
  719. }
  720. if(!images.empty())
  721. loadScreenshots();
  722. }
  723. void CModListView::installMods(QStringList archives)
  724. {
  725. QStringList modNames;
  726. QStringList modsToEnable;
  727. for(QString archive : archives)
  728. {
  729. // get basename out of full file name
  730. // remove path remove extension
  731. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  732. modNames.push_back(modName);
  733. }
  734. // uninstall old version of mod, if installed
  735. for(QString mod : modNames)
  736. {
  737. if(modStateModel->getMod(mod).isInstalled())
  738. {
  739. if (modStateModel->isModEnabled(mod))
  740. modsToEnable.push_back(mod);
  741. manager->uninstallMod(mod);
  742. }
  743. else
  744. {
  745. // installation of previously not present mod -> enable it
  746. modsToEnable.push_back(mod);
  747. }
  748. }
  749. for(int i = 0; i < modNames.size(); i++)
  750. {
  751. ui->progressBar->setFormat(tr("Installing mod %1").arg(modNames[i]));
  752. manager->installMod(modNames[i], archives[i]);
  753. }
  754. manager->enableMods(modsToEnable);
  755. checkManagerErrors();
  756. for(QString archive : archives)
  757. QFile::remove(archive);
  758. }
  759. void CModListView::installMaps(QStringList maps)
  760. {
  761. const auto destDir = CLauncherDirs::mapsPath() + QChar{'/'};
  762. for(QString map : maps)
  763. {
  764. QFile(map).rename(destDir + map.section('/', -1, -1));
  765. }
  766. }
  767. void CModListView::on_refreshButton_clicked()
  768. {
  769. loadRepositories();
  770. }
  771. void CModListView::on_pushButton_clicked()
  772. {
  773. delete dlManager;
  774. dlManager = nullptr;
  775. hideProgressBar();
  776. }
  777. void CModListView::modelReset()
  778. {
  779. selectMod(filterModel->rowCount() > 0 ? filterModel->index(0, 0) : QModelIndex());
  780. }
  781. void CModListView::checkManagerErrors()
  782. {
  783. QString errors = manager->getErrors().join('\n');
  784. if(errors.size() != 0)
  785. {
  786. QString title = tr("Operation failed");
  787. QString description = tr("Encountered errors:\n") + errors;
  788. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok);
  789. }
  790. }
  791. void CModListView::on_tabWidget_currentChanged(int index)
  792. {
  793. loadScreenshots();
  794. }
  795. void CModListView::loadScreenshots()
  796. {
  797. if(ui->tabWidget->currentIndex() == 2)
  798. {
  799. if(!ui->allModsView->currentIndex().isValid())
  800. {
  801. // select the first mod, so we can access its data
  802. ui->allModsView->setCurrentIndex(filterModel->index(0, 0));
  803. }
  804. ui->screenshotsList->clear();
  805. QString modName = ui->allModsView->currentIndex().data(ModRoles::ModNameRole).toString();
  806. assert(modStateModel->isModExists(modName)); //should be filtered out by check above
  807. for(QString url : modStateModel->getMod(modName).getScreenshots())
  808. {
  809. // URL must be encoded to something else to get rid of symbols illegal in file names
  810. const auto hashed = QCryptographicHash::hash(url.toUtf8(), QCryptographicHash::Md5);
  811. const auto fileName = QString{QLatin1String{"%1.png"}}.arg(QLatin1String{hashed.toHex()});
  812. const auto fullPath = QString{QLatin1String{"%1/%2"}}.arg(CLauncherDirs::downloadsPath(), fileName);
  813. QPixmap pixmap(fullPath);
  814. if(pixmap.isNull())
  815. {
  816. // image file not exists or corrupted - try to redownload
  817. downloadFile(fileName, url, tr("screenshots"));
  818. }
  819. else
  820. {
  821. // managed to load cached image
  822. QIcon icon(pixmap);
  823. auto * item = new QListWidgetItem(icon, QString(tr("Screenshot %1")).arg(ui->screenshotsList->count() + 1));
  824. ui->screenshotsList->addItem(item);
  825. }
  826. }
  827. }
  828. }
  829. void CModListView::on_screenshotsList_clicked(const QModelIndex & index)
  830. {
  831. if(index.isValid())
  832. {
  833. QIcon icon = ui->screenshotsList->item(index.row())->icon();
  834. auto pixmap = icon.pixmap(icon.availableSizes()[0]);
  835. ImageViewer::showPixmap(pixmap, this);
  836. }
  837. }
  838. void CModListView::doInstallMod(const QString & modName)
  839. {
  840. assert(findInvalidDependencies(modName).empty());
  841. for(const auto & name : modStateModel->getMod(modName).getDependencies())
  842. {
  843. auto mod = modStateModel->getMod(name);
  844. if(!mod.isInstalled())
  845. downloadFile(name + ".zip", mod.getDownloadUrl(), name, mod.getDownloadSizeMegabytes());
  846. }
  847. }
  848. bool CModListView::isModAvailable(const QString & modName)
  849. {
  850. return !modStateModel->isModInstalled(modName);
  851. }
  852. bool CModListView::isModEnabled(const QString & modName)
  853. {
  854. return modStateModel->isModEnabled(modName);
  855. }
  856. bool CModListView::isModInstalled(const QString & modName)
  857. {
  858. auto mod = modStateModel->getMod(modName);
  859. return mod.isInstalled();
  860. }
  861. QString CModListView::getTranslationModName(const QString & language)
  862. {
  863. for(const auto & modName : modStateModel->getAllMods())
  864. {
  865. auto mod = modStateModel->getMod(modName);
  866. if (!mod.isTranslation())
  867. continue;
  868. if (mod.getBaseLanguage() != language)
  869. continue;
  870. return modName;
  871. }
  872. return QString();
  873. }
  874. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  875. {
  876. if(!index.isValid())
  877. return;
  878. auto modName = index.data(ModRoles::ModNameRole).toString();
  879. auto mod = modStateModel->getMod(modName);
  880. bool hasInvalidDeps = !findInvalidDependencies(modName).empty();
  881. if(!hasInvalidDeps && mod.isAvailable() && !mod.isSubmod())
  882. {
  883. on_installButton_clicked();
  884. return;
  885. }
  886. if(!hasInvalidDeps && mod.isUpdateAvailable() && index.column() == ModFields::STATUS_UPDATE)
  887. {
  888. on_updateButton_clicked();
  889. return;
  890. }
  891. if(index.column() == ModFields::NAME)
  892. {
  893. if(ui->allModsView->isExpanded(index))
  894. ui->allModsView->collapse(index);
  895. else
  896. ui->allModsView->expand(index);
  897. return;
  898. }
  899. if(!hasInvalidDeps && !modStateModel->isModEnabled(modName))
  900. {
  901. on_enableButton_clicked();
  902. return;
  903. }
  904. if(modStateModel->isModEnabled(modName))
  905. {
  906. on_disableButton_clicked();
  907. return;
  908. }
  909. }