cmodlistview_moc.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. #include "StdInc.h"
  2. #include "cmodlistview_moc.h"
  3. #include "ui_cmodlistview_moc.h"
  4. #include <QJsonArray>
  5. #include <QCryptographicHash>
  6. #include "cmodlistmodel_moc.h"
  7. #include "cmodmanager.h"
  8. #include "cdownloadmanager_moc.h"
  9. #include "../launcherdirs.h"
  10. #include "../../lib/CConfigHandler.h"
  11. void CModListView::setupModModel()
  12. {
  13. modModel = new CModListModel();
  14. manager = new CModManager(modModel);
  15. }
  16. void CModListView::setupFilterModel()
  17. {
  18. filterModel = new CModFilterModel(modModel);
  19. filterModel->setFilterKeyColumn(-1); // filter across all columns
  20. filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); // to make it more user-friendly
  21. }
  22. void CModListView::setupModsView()
  23. {
  24. ui->allModsView->setModel(filterModel);
  25. // input data is not sorted - sort it before display
  26. ui->allModsView->sortByColumn(ModFields::TYPE, Qt::AscendingOrder);
  27. ui->allModsView->setColumnWidth(ModFields::STATUS_ENABLED, 30);
  28. ui->allModsView->setColumnWidth(ModFields::STATUS_UPDATE, 30);
  29. ui->allModsView->setColumnWidth(ModFields::NAME, 120);
  30. ui->allModsView->setColumnWidth(ModFields::SIZE, 60);
  31. ui->allModsView->setColumnWidth(ModFields::VERSION, 60);
  32. connect( ui->allModsView->selectionModel(), SIGNAL( currentRowChanged( const QModelIndex &, const QModelIndex & )),
  33. this, SLOT( modSelected( const QModelIndex &, const QModelIndex & )));
  34. connect( filterModel, SIGNAL( modelReset()),
  35. this, SLOT( modelReset()));
  36. selectMod(filterModel->rowCount() > 0 ? 0 : -1);
  37. }
  38. CModListView::CModListView(QWidget *parent) :
  39. QWidget(parent),
  40. settingsListener(settings.listen["launcher"]["repositoryURL"]),
  41. ui(new Ui::CModListView)
  42. {
  43. settingsListener([&](const JsonNode &){ repositoriesChanged = true; });
  44. ui->setupUi(this);
  45. setupModModel();
  46. setupFilterModel();
  47. setupModsView();
  48. ui->progressWidget->setVisible(false);
  49. dlManager = nullptr;
  50. loadRepositories();
  51. }
  52. void CModListView::loadRepositories()
  53. {
  54. manager->resetRepositories();
  55. for (auto entry : settings["launcher"]["repositoryURL"].Vector())
  56. {
  57. QString str = QString::fromUtf8(entry.String().c_str());
  58. // URL must be encoded to something else to get rid of symbols illegal in file names
  59. auto hashed = QCryptographicHash::hash(str.toUtf8(), QCryptographicHash::Md5);
  60. auto hashedStr = QString::fromUtf8(hashed.toHex());
  61. downloadFile(hashedStr + ".json", str, "repository index");
  62. }
  63. }
  64. CModListView::~CModListView()
  65. {
  66. delete ui;
  67. }
  68. void CModListView::showEvent(QShowEvent * event)
  69. {
  70. QWidget::showEvent(event);
  71. if (repositoriesChanged)
  72. {
  73. repositoriesChanged = false;
  74. loadRepositories();
  75. }
  76. }
  77. void CModListView::showModInfo()
  78. {
  79. ui->modInfoWidget->show();
  80. ui->hideModInfoButton->setArrowType(Qt::RightArrow);
  81. }
  82. void CModListView::hideModInfo()
  83. {
  84. ui->modInfoWidget->hide();
  85. ui->hideModInfoButton->setArrowType(Qt::LeftArrow);
  86. }
  87. static QString replaceIfNotEmpty(QVariant value, QString pattern)
  88. {
  89. if (value.canConvert<QStringList>())
  90. return pattern.arg(value.toStringList().join(", "));
  91. if (value.canConvert<QString>())
  92. return pattern.arg(value.toString());
  93. // all valid types of data should have been filtered by code above
  94. assert(!value.isValid());
  95. return "";
  96. }
  97. static QVariant sizeToString(QVariant value)
  98. {
  99. if (value.canConvert<QString>())
  100. {
  101. static QString symbols = "kMGTPE";
  102. auto number = value.toUInt();
  103. size_t i=0;
  104. while (number >= 1000)
  105. {
  106. number /= 1000;
  107. i++;
  108. }
  109. return QVariant(QString("%1 %2B").arg(number).arg(symbols.at(i)));
  110. }
  111. return value;
  112. }
  113. static QString replaceIfNotEmpty(QStringList value, QString pattern)
  114. {
  115. if (!value.empty())
  116. return pattern.arg(value.join(", "));
  117. return "";
  118. }
  119. QString CModListView::genModInfoText(CModEntry &mod)
  120. {
  121. QString prefix = "<p><span style=\" font-weight:600;\">%1: </span>"; // shared prefix
  122. QString lineTemplate = prefix + "%2</p>";
  123. QString urlTemplate = prefix + "<a href=\"%2\"><span style=\" text-decoration: underline; color:#0000ff;\">%2</span></a></p>";
  124. QString textTemplate = prefix + "</p><p align=\"justify\">%2</p>";
  125. QString noteTemplate = "<p align=\"justify\">%1: %2</p>";
  126. QString result;
  127. result += "<html><body>";
  128. result += replaceIfNotEmpty(mod.getValue("name"), lineTemplate.arg("Mod name"));
  129. result += replaceIfNotEmpty(mod.getValue("installedVersion"), lineTemplate.arg("Installed version"));
  130. result += replaceIfNotEmpty(mod.getValue("latestVersion"), lineTemplate.arg("Latest version"));
  131. result += replaceIfNotEmpty(sizeToString(mod.getValue("size")), lineTemplate.arg("Download size"));
  132. result += replaceIfNotEmpty(mod.getValue("author"), lineTemplate.arg("Authors"));
  133. result += replaceIfNotEmpty(mod.getValue("contact"), urlTemplate.arg("Home"));
  134. result += replaceIfNotEmpty(mod.getValue("depends"), lineTemplate.arg("Required mods"));
  135. result += replaceIfNotEmpty(mod.getValue("conflicts"), lineTemplate.arg("Conflicting mods"));
  136. result += replaceIfNotEmpty(mod.getValue("description"), textTemplate.arg("Description"));
  137. result += "<p></p>"; // to get some empty space
  138. QString unknownDeps = "This mod can not be installed or enabled because following dependencies are not present";
  139. QString blockingMods = "This mod can not be enabled because following mods are incompatible with this mod";
  140. QString hasActiveDependentMods = "This mod can not be disabled because it is required to run following mods";
  141. QString hasDependentMods = "This mod can not be uninstalled or updated because it is required to run following mods";
  142. QString notes;
  143. notes += replaceIfNotEmpty(findInvalidDependencies(mod.getName()), noteTemplate.arg(unknownDeps));
  144. notes += replaceIfNotEmpty(findBlockingMods(mod.getName()), noteTemplate.arg(blockingMods));
  145. if (mod.isEnabled())
  146. notes += replaceIfNotEmpty(findDependentMods(mod.getName(), true), noteTemplate.arg(hasActiveDependentMods));
  147. if (mod.isInstalled())
  148. notes += replaceIfNotEmpty(findDependentMods(mod.getName(), false), noteTemplate.arg(hasDependentMods));
  149. if (notes.size())
  150. result += textTemplate.arg("Notes").arg(notes);
  151. result += "</body></html>";
  152. return result;
  153. }
  154. void CModListView::enableModInfo()
  155. {
  156. showModInfo();
  157. ui->hideModInfoButton->setEnabled(true);
  158. }
  159. void CModListView::disableModInfo()
  160. {
  161. hideModInfo();
  162. ui->hideModInfoButton->setEnabled(false);
  163. }
  164. void CModListView::selectMod(int index)
  165. {
  166. if (index < 0)
  167. {
  168. disableModInfo();
  169. }
  170. else
  171. {
  172. enableModInfo();
  173. auto mod = modModel->getMod(modModel->modIndexToName(index));
  174. ui->textBrowser->setHtml(genModInfoText(mod));
  175. bool hasInvalidDeps = !findInvalidDependencies(modModel->modIndexToName(index)).empty();
  176. bool hasBlockingMods = !findBlockingMods(modModel->modIndexToName(index)).empty();
  177. bool hasDependentMods = !findDependentMods(modModel->modIndexToName(index), true).empty();
  178. ui->disableButton->setVisible(mod.isEnabled());
  179. ui->enableButton->setVisible(mod.isDisabled());
  180. ui->installButton->setVisible(mod.isAvailable());
  181. ui->uninstallButton->setVisible(mod.isInstalled());
  182. ui->updateButton->setVisible(mod.isUpdateable());
  183. // Block buttons if action is not allowed at this time
  184. // TODO: automate handling of some of these cases instead of forcing player
  185. // to resolve all conflicts manually.
  186. ui->disableButton->setEnabled(!hasDependentMods);
  187. ui->enableButton->setEnabled(!hasBlockingMods && !hasInvalidDeps);
  188. ui->installButton->setEnabled(!hasInvalidDeps);
  189. ui->uninstallButton->setEnabled(!hasDependentMods);
  190. ui->updateButton->setEnabled(!hasInvalidDeps && !hasDependentMods);
  191. }
  192. }
  193. void CModListView::keyPressEvent(QKeyEvent * event)
  194. {
  195. if (event->key() == Qt::Key_Escape && ui->modInfoWidget->isVisible() )
  196. {
  197. ui->modInfoWidget->hide();
  198. }
  199. else
  200. {
  201. return QWidget::keyPressEvent(event);
  202. }
  203. }
  204. void CModListView::modSelected(const QModelIndex & current, const QModelIndex & )
  205. {
  206. selectMod(filterModel->mapToSource(current).row());
  207. }
  208. void CModListView::on_hideModInfoButton_clicked()
  209. {
  210. if (ui->modInfoWidget->isVisible())
  211. hideModInfo();
  212. else
  213. showModInfo();
  214. }
  215. void CModListView::on_allModsView_doubleClicked(const QModelIndex &index)
  216. {
  217. showModInfo();
  218. selectMod(filterModel->mapToSource(index).row());
  219. }
  220. void CModListView::on_lineEdit_textChanged(const QString &arg1)
  221. {
  222. QRegExp regExp(arg1, Qt::CaseInsensitive, QRegExp::Wildcard);
  223. filterModel->setFilterRegExp(regExp);
  224. }
  225. void CModListView::on_comboBox_currentIndexChanged(int index)
  226. {
  227. switch (index)
  228. {
  229. break; case 0: filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::MASK_NONE);
  230. break; case 1: filterModel->setTypeFilter(ModStatus::MASK_NONE, ModStatus::INSTALLED);
  231. break; case 2: filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::INSTALLED);
  232. break; case 3: filterModel->setTypeFilter(ModStatus::UPDATEABLE, ModStatus::UPDATEABLE);
  233. break; case 4: filterModel->setTypeFilter(ModStatus::ENABLED | ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
  234. break; case 5: filterModel->setTypeFilter(ModStatus::INSTALLED, ModStatus::ENABLED | ModStatus::INSTALLED);
  235. }
  236. }
  237. QStringList CModListView::findInvalidDependencies(QString mod)
  238. {
  239. QStringList ret;
  240. for (QString requrement : modModel->getRequirements(mod))
  241. {
  242. if (!modModel->hasMod(requrement))
  243. ret += requrement;
  244. }
  245. return ret;
  246. }
  247. QStringList CModListView::findBlockingMods(QString mod)
  248. {
  249. QStringList ret;
  250. auto required = modModel->getRequirements(mod);
  251. for (QString name : modModel->getModList())
  252. {
  253. auto mod = modModel->getMod(name);
  254. if (mod.isEnabled())
  255. {
  256. // one of enabled mods have requirement (or this mod) marked as conflict
  257. for (auto conflict : mod.getValue("conflicts").toStringList())
  258. if (required.contains(conflict))
  259. ret.push_back(name);
  260. }
  261. }
  262. return ret;
  263. }
  264. QStringList CModListView::findDependentMods(QString mod, bool excludeDisabled)
  265. {
  266. QStringList ret;
  267. for (QString modName : modModel->getModList())
  268. {
  269. auto current = modModel->getMod(modName);
  270. if (!current.isInstalled())
  271. continue;
  272. if (current.getValue("depends").toStringList().contains(mod) &&
  273. !(current.isDisabled() && excludeDisabled))
  274. ret += modName;
  275. }
  276. return ret;
  277. }
  278. void CModListView::on_enableButton_clicked()
  279. {
  280. QString modName = modModel->modIndexToName(filterModel->mapToSource(ui->allModsView->currentIndex()).row());
  281. assert(findBlockingMods(modName).empty());
  282. assert(findInvalidDependencies(modName).empty());
  283. for (auto & name : modModel->getRequirements(modName))
  284. if (modModel->getMod(name).isDisabled())
  285. manager->enableMod(name);
  286. checkManagerErrors();
  287. }
  288. void CModListView::on_disableButton_clicked()
  289. {
  290. QString modName = modModel->modIndexToName(filterModel->mapToSource(ui->allModsView->currentIndex()).row());
  291. if (modModel->hasMod(modName) &&
  292. modModel->getMod(modName).isEnabled())
  293. manager->disableMod(modName);
  294. checkManagerErrors();
  295. }
  296. void CModListView::on_updateButton_clicked()
  297. {
  298. QString modName = modModel->modIndexToName(filterModel->mapToSource(ui->allModsView->currentIndex()).row());
  299. assert(findInvalidDependencies(modName).empty());
  300. for (auto & name : modModel->getRequirements(modName))
  301. {
  302. auto mod = modModel->getMod(name);
  303. // update required mod, install missing (can be new dependency)
  304. if (mod.isUpdateable() || !mod.isInstalled())
  305. downloadFile(name + ".zip", mod.getValue("download").toString(), "mods");
  306. }
  307. }
  308. void CModListView::on_uninstallButton_clicked()
  309. {
  310. QString modName = modModel->modIndexToName(filterModel->mapToSource(ui->allModsView->currentIndex()).row());
  311. // NOTE: perhaps add "manually installed" flag and uninstall those dependencies that don't have it?
  312. if (modModel->hasMod(modName) &&
  313. modModel->getMod(modName).isInstalled())
  314. {
  315. if (modModel->getMod(modName).isEnabled())
  316. manager->disableMod(modName);
  317. manager->uninstallMod(modName);
  318. }
  319. checkManagerErrors();
  320. }
  321. void CModListView::on_installButton_clicked()
  322. {
  323. QString modName = modModel->modIndexToName(filterModel->mapToSource(ui->allModsView->currentIndex()).row());
  324. assert(findInvalidDependencies(modName).empty());
  325. for (auto & name : modModel->getRequirements(modName))
  326. {
  327. auto mod = modModel->getMod(name);
  328. if (!mod.isInstalled())
  329. downloadFile(name + ".zip", mod.getValue("download").toString(), "mods");
  330. }
  331. }
  332. void CModListView::downloadFile(QString file, QString url, QString description)
  333. {
  334. if (!dlManager)
  335. {
  336. dlManager = new CDownloadManager();
  337. ui->progressWidget->setVisible(true);
  338. connect(dlManager, SIGNAL(downloadProgress(qint64,qint64)),
  339. this, SLOT(downloadProgress(qint64,qint64)));
  340. connect(dlManager, SIGNAL(finished(QStringList,QStringList,QStringList)),
  341. this, SLOT(downloadFinished(QStringList,QStringList,QStringList)));
  342. QString progressBarFormat = "Downloading %s%. %p% (%v KB out of %m KB) finished";
  343. progressBarFormat.replace("%s%", description);
  344. ui->progressBar->setFormat(progressBarFormat);
  345. }
  346. dlManager->downloadFile(QUrl(url), file);
  347. }
  348. void CModListView::downloadProgress(qint64 current, qint64 max)
  349. {
  350. // display progress, in kilobytes
  351. ui->progressBar->setValue(current/1024);
  352. ui->progressBar->setMaximum(max/1024);
  353. }
  354. void CModListView::downloadFinished(QStringList savedFiles, QStringList failedFiles, QStringList errors)
  355. {
  356. QString title = "Download failed";
  357. QString firstLine = "Unable to download all files.\n\nEncountered errors:\n\n";
  358. QString lastLine = "\n\nInstall successfully downloaded?";
  359. // if all files were d/loaded there should be no errors. And on failure there must be an error
  360. assert(failedFiles.empty() == errors.empty());
  361. if (savedFiles.empty())
  362. {
  363. // no successfully downloaded mods
  364. QMessageBox::warning(this, title, firstLine + errors.join("\n"), QMessageBox::Ok, QMessageBox::Ok );
  365. }
  366. else if (!failedFiles.empty())
  367. {
  368. // some mods were not downloaded
  369. int result = QMessageBox::warning (this, title, firstLine + errors.join("\n") + lastLine,
  370. QMessageBox::Yes | QMessageBox::No, QMessageBox::No );
  371. if (result == QMessageBox::Yes)
  372. installFiles(savedFiles);
  373. }
  374. else
  375. {
  376. // everything OK
  377. installFiles(savedFiles);
  378. }
  379. // remove progress bar after some delay so user can see that download was complete and not interrupted.
  380. QTimer::singleShot(1000, this, SLOT(hideProgressBar()));
  381. dlManager->deleteLater();
  382. dlManager = nullptr;
  383. }
  384. void CModListView::hideProgressBar()
  385. {
  386. if (dlManager == nullptr) // it was not recreated meanwhile
  387. {
  388. ui->progressWidget->setVisible(false);
  389. ui->progressBar->setMaximum(0);
  390. ui->progressBar->setValue(0);
  391. }
  392. }
  393. void CModListView::installFiles(QStringList files)
  394. {
  395. QStringList mods;
  396. // TODO: some better way to separate zip's with mods and downloaded repository files
  397. for (QString filename : files)
  398. {
  399. if (filename.contains(".zip"))
  400. mods.push_back(filename);
  401. if (filename.contains(".json"))
  402. manager->loadRepository(filename);
  403. }
  404. if (!mods.empty())
  405. installMods(mods);
  406. }
  407. void CModListView::installMods(QStringList archives)
  408. {
  409. QStringList modNames;
  410. for (QString archive : archives)
  411. {
  412. // get basename out of full file name
  413. // remove path remove extension
  414. QString modName = archive.section('/', -1, -1).section('.', 0, 0);
  415. modNames.push_back(modName);
  416. }
  417. // disable mod(s), to properly recalculate dependencies, if changed
  418. for (QString mod : boost::adaptors::reverse(modNames))
  419. {
  420. if (modModel->getMod(mod).isInstalled())
  421. manager->disableMod(mod);
  422. }
  423. // uninstall old version of mod, if installed
  424. for (QString mod : boost::adaptors::reverse(modNames))
  425. {
  426. if (modModel->getMod(mod).isInstalled())
  427. manager->uninstallMod(mod);
  428. }
  429. for (int i=0; i<modNames.size(); i++)
  430. manager->installMod(modNames[i], archives[i]);
  431. if (settings["launcher"]["enableInstalledMods"].Bool())
  432. {
  433. for (QString mod : modNames)
  434. manager->enableMod(mod);
  435. }
  436. for (QString archive : archives)
  437. QFile::remove(archive);
  438. checkManagerErrors();
  439. }
  440. void CModListView::on_pushButton_clicked()
  441. {
  442. delete dlManager;
  443. dlManager = nullptr;
  444. hideProgressBar();
  445. }
  446. void CModListView::modelReset()
  447. {
  448. //selectMod(filterModel->mapToSource(ui->allModsView->currentIndex()).row());
  449. selectMod(filterModel->rowCount() > 0 ? 0 : -1);
  450. }
  451. void CModListView::checkManagerErrors()
  452. {
  453. QString errors = manager->getErrors().join('\n');
  454. if (errors.size() != 0)
  455. {
  456. QString title = "Operation failed";
  457. QString description = "Encountered errors:\n" + errors;
  458. QMessageBox::warning(this, title, description, QMessageBox::Ok, QMessageBox::Ok );
  459. }
  460. }