cmodlistview_moc.cpp 34 KB

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