id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
28,993
TechnicPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/modplatform/technic/TechnicPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2021-2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "TechnicPage.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/widgets/ProjectItem.h" #include "ui_TechnicPage.h" #include <QKeyEvent> #include "ui/dialogs/NewInstanceDialog.h" #include "BuildConfig.h" #include "Json.h" #include "StringUtils.h" #include "TechnicModel.h" #include "modplatform/technic/SingleZipPackInstallTask.h" #include "modplatform/technic/SolderPackInstallTask.h" #include "Application.h" #include "modplatform/technic/SolderPackManifest.h" #include "net/ApiDownload.h" TechnicPage::TechnicPage(NewInstanceDialog* dialog, QWidget* parent) : QWidget(parent), ui(new Ui::TechnicPage), dialog(dialog), m_fetch_progress(this, false) { ui->setupUi(this); ui->searchEdit->installEventFilter(this); model = new Technic::ListModel(this); ui->packView->setModel(model); m_search_timer.setTimerType(Qt::TimerType::CoarseTimer); m_search_timer.setSingleShot(true); connect(&m_search_timer, &QTimer::timeout, this, &TechnicPage::triggerSearch); m_fetch_progress.hideIfInactive(true); m_fetch_progress.setFixedHeight(24); m_fetch_progress.progressFormat(""); ui->verticalLayout->insertWidget(1, &m_fetch_progress); connect(ui->packView->selectionModel(), &QItemSelectionModel::currentChanged, this, &TechnicPage::onSelectionChanged); connect(ui->versionSelectionBox, &QComboBox::currentTextChanged, this, &TechnicPage::onVersionSelectionChanged); ui->packView->setItemDelegate(new ProjectItemDelegate(this)); } bool TechnicPage::eventFilter(QObject* watched, QEvent* event) { if (watched == ui->searchEdit && event->type() == QEvent::KeyPress) { QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event); if (keyEvent->key() == Qt::Key_Return) { triggerSearch(); keyEvent->accept(); return true; } else { if (m_search_timer.isActive()) m_search_timer.stop(); m_search_timer.start(350); } } return QWidget::eventFilter(watched, event); } TechnicPage::~TechnicPage() { delete ui; } bool TechnicPage::shouldDisplay() const { return true; } void TechnicPage::retranslate() { ui->retranslateUi(this); } void TechnicPage::openedImpl() { suggestCurrent(); triggerSearch(); } void TechnicPage::triggerSearch() { model->searchWithTerm(ui->searchEdit->text()); m_fetch_progress.watch(model->activeSearchJob().get()); } void TechnicPage::onSelectionChanged(QModelIndex first, [[maybe_unused]] QModelIndex second) { ui->versionSelectionBox->clear(); if (!first.isValid()) { if (isOpened) { dialog->setSuggestedPack(); } return; } current = model->data(first, Qt::UserRole).value<Technic::Modpack>(); suggestCurrent(); } void TechnicPage::suggestCurrent() { if (!isOpened) { return; } if (current.broken) { dialog->setSuggestedPack(); return; } QString editedLogoName = "technic_" + current.logoName; model->getLogo(current.logoName, current.logoUrl, [this, editedLogoName](QString logo) { dialog->setSuggestedIconFromFile(logo, editedLogoName); }); if (current.metadataLoaded) { metadataLoaded(); return; } auto netJob = makeShared<NetJob>(QString("Technic::PackMeta(%1)").arg(current.name), APPLICATION->network()); QString slug = current.slug; netJob->addNetAction(Net::ApiDownload::makeByteArray( QString("%1modpack/%2?build=%3").arg(BuildConfig.TECHNIC_API_BASE_URL, slug, BuildConfig.TECHNIC_API_BUILD), response)); QObject::connect(netJob.get(), &NetJob::succeeded, this, [this, slug] { jobPtr.reset(); if (current.slug != slug) { return; } QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); QJsonObject obj = doc.object(); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Technic at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } if (!obj.contains("url")) { qWarning() << "Json doesn't contain an url key"; return; } QJsonValueRef url = obj["url"]; if (url.isString()) { current.url = url.toString(); } else { if (!obj.contains("solder")) { qWarning() << "Json doesn't contain a valid url or solder key"; return; } QJsonValueRef solderUrl = obj["solder"]; if (solderUrl.isString()) { current.url = solderUrl.toString(); current.isSolder = true; } else { qWarning() << "Json doesn't contain a valid url or solder key"; return; } } current.minecraftVersion = Json::ensureString(obj, "minecraft", QString(), "__placeholder__"); current.websiteUrl = Json::ensureString(obj, "platformUrl", QString(), "__placeholder__"); current.author = Json::ensureString(obj, "user", QString(), "__placeholder__"); current.description = Json::ensureString(obj, "description", QString(), "__placeholder__"); current.currentVersion = Json::ensureString(obj, "version", QString(), "__placeholder__"); current.metadataLoaded = true; metadataLoaded(); }); connect(jobPtr.get(), &NetJob::failed, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); }); jobPtr = netJob; jobPtr->start(); } // expects current.metadataLoaded to be true void TechnicPage::metadataLoaded() { QString text = ""; QString name = current.name; if (current.websiteUrl.isEmpty()) text = name.toHtmlEscaped(); else text = "<a href=\"" + current.websiteUrl.toHtmlEscaped() + "\">" + name.toHtmlEscaped() + "</a>"; if (!current.author.isEmpty()) { text += "<br>" + tr(" by ") + current.author.toHtmlEscaped(); } text += "<br><br>"; ui->packDescription->setHtml(StringUtils::htmlListPatch(text + current.description)); // Strip trailing forward-slashes from Solder URL's if (current.isSolder) { while (current.url.endsWith('/')) current.url.chop(1); } // Display versions from Solder if (!current.isSolder) { // If the pack isn't a Solder pack, it only has the single version ui->versionSelectionBox->addItem(current.currentVersion); } else if (current.versionsLoaded) { // reverse foreach, so that the newest versions are first for (auto i = current.versions.size(); i--;) { ui->versionSelectionBox->addItem(current.versions.at(i)); } ui->versionSelectionBox->setCurrentText(current.recommended); } else { // For now, until the versions are pulled from the Solder instance, display the current // version so we can display something quicker ui->versionSelectionBox->addItem(current.currentVersion); auto netJob = makeShared<NetJob>(QString("Technic::SolderMeta(%1)").arg(current.name), APPLICATION->network()); auto url = QString("%1/modpack/%2").arg(current.url, current.slug); netJob->addNetAction(Net::ApiDownload::makeByteArray(QUrl(url), response)); QObject::connect(netJob.get(), &NetJob::succeeded, this, &TechnicPage::onSolderLoaded); connect(jobPtr.get(), &NetJob::failed, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); }); jobPtr = netJob; jobPtr->start(); } selectVersion(); } void TechnicPage::selectVersion() { if (!isOpened) { return; } if (current.broken) { dialog->setSuggestedPack(); return; } if (!current.isSolder) { dialog->setSuggestedPack(current.name, selectedVersion, new Technic::SingleZipPackInstallTask(current.url, current.minecraftVersion)); } else { dialog->setSuggestedPack(current.name, selectedVersion, new Technic::SolderPackInstallTask(APPLICATION->network(), current.url, current.slug, selectedVersion, current.minecraftVersion)); } } void TechnicPage::onSolderLoaded() { jobPtr.reset(); auto fallback = [this]() { current.versionsLoaded = true; current.versions.clear(); current.versions.append(current.currentVersion); }; current.versions.clear(); QJsonParseError parse_error{}; auto doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Solder at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; fallback(); return; } auto obj = doc.object(); TechnicSolder::Pack pack; try { TechnicSolder::loadPack(pack, obj); } catch (const JSONValidationError& err) { qCritical() << "Couldn't parse Solder pack metadata:" << err.cause(); fallback(); return; } current.versionsLoaded = true; current.recommended = pack.recommended; current.versions.append(pack.builds); // Finally, let's reload :) ui->versionSelectionBox->clear(); metadataLoaded(); } void TechnicPage::onVersionSelectionChanged(QString version) { if (version.isNull() || version.isEmpty()) { selectedVersion = ""; return; } selectedVersion = version; selectVersion(); } void TechnicPage::setSearchTerm(QString term) { ui->searchEdit->setText(term); } QString TechnicPage::getSerachTerm() const { return ui->searchEdit->text(); }
11,608
C++
.cpp
297
32.653199
140
0.656033
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,994
GameOptionsPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/GameOptionsPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "GameOptionsPage.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/gameoptions/GameOptions.h" #include "ui_GameOptionsPage.h" GameOptionsPage::GameOptionsPage(MinecraftInstance* inst, QWidget* parent) : QWidget(parent), ui(new Ui::GameOptionsPage) { ui->setupUi(this); ui->tabWidget->tabBar()->hide(); m_model = inst->gameOptionsModel(); ui->optionsView->setModel(m_model.get()); auto head = ui->optionsView->header(); if (head->count()) { head->setSectionResizeMode(0, QHeaderView::ResizeToContents); for (int i = 1; i < head->count(); i++) { head->setSectionResizeMode(i, QHeaderView::Stretch); } } } GameOptionsPage::~GameOptionsPage() { // m_model->save(); } void GameOptionsPage::openedImpl() { // m_model->observe(); } void GameOptionsPage::closedImpl() { // m_model->unobserve(); } void GameOptionsPage::retranslate() { ui->retranslateUi(this); }
2,461
C++
.cpp
68
33.455882
121
0.716799
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
28,995
ShaderPackPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/ShaderPackPage.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only AND Apache-2.0 /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ShaderPackPage.h" #include "ui_ExternalResourcesPage.h" #include "ResourceDownloadTask.h" #include "minecraft/mod/ShaderPackFolderModel.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ProgressDialog.h" #include "ui/dialogs/ResourceDownloadDialog.h" #include "ui/dialogs/ResourceUpdateDialog.h" ShaderPackPage::ShaderPackPage(MinecraftInstance* instance, std::shared_ptr<ShaderPackFolderModel> model, QWidget* parent) : ExternalResourcesPage(instance, model, parent), m_model(model) { ui->actionDownloadItem->setText(tr("Download Packs")); ui->actionDownloadItem->setToolTip(tr("Download shader packs from online mod platforms")); ui->actionDownloadItem->setEnabled(true); ui->actionsToolbar->insertActionBefore(ui->actionAddItem, ui->actionDownloadItem); connect(ui->actionDownloadItem, &QAction::triggered, this, &ShaderPackPage::downloadShaderPack); ui->actionUpdateItem->setToolTip(tr("Try to check or update all selected shader packs (all shader packs if none are selected)")); connect(ui->actionUpdateItem, &QAction::triggered, this, &ShaderPackPage::updateShaderPacks); ui->actionsToolbar->insertActionBefore(ui->actionAddItem, ui->actionUpdateItem); auto updateMenu = new QMenu(this); auto update = updateMenu->addAction(ui->actionUpdateItem->text()); connect(update, &QAction::triggered, this, &ShaderPackPage::updateShaderPacks); updateMenu->addAction(ui->actionResetItemMetadata); connect(ui->actionResetItemMetadata, &QAction::triggered, this, &ShaderPackPage::deleteShaderPackMetadata); ui->actionUpdateItem->setMenu(updateMenu); ui->actionChangeVersion->setToolTip(tr("Change a shader pack's version.")); connect(ui->actionChangeVersion, &QAction::triggered, this, &ShaderPackPage::changeShaderPackVersion); ui->actionsToolbar->insertActionAfter(ui->actionUpdateItem, ui->actionChangeVersion); } void ShaderPackPage::downloadShaderPack() { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance ResourceDownload::ShaderPackDownloadDialog mdownload(this, m_model, m_instance); if (mdownload.exec()) { auto tasks = new ConcurrentTask("Download Shader Packs", APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); tasks->deleteLater(); }); for (auto& task : mdownload.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } } void ShaderPackPage::updateShaderPacks() { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance auto profile = static_cast<MinecraftInstance*>(m_instance)->getPackProfile(); if (APPLICATION->settings()->get("ModMetadataDisabled").toBool()) { QMessageBox::critical(this, tr("Error"), tr("Shader pack updates are unavailable when metadata is disabled!")); return; } if (m_instance != nullptr && m_instance->isRunning()) { auto response = CustomMessageBox::selectable(this, tr("Confirm Update"), tr("Updating shader packs while the game is running may pack duplication and game crashes.\n" "The old files may not be deleted as they are in use.\n" "Are you sure you want to do this?"), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); auto mods_list = m_model->selectedResources(selection); bool use_all = mods_list.empty(); if (use_all) mods_list = m_model->allResources(); ResourceUpdateDialog update_dialog(this, m_instance, m_model, mods_list, false, false); update_dialog.checkCandidates(); if (update_dialog.aborted()) { CustomMessageBox::selectable(this, tr("Aborted"), tr("The shader pack updater was aborted!"), QMessageBox::Warning)->show(); return; } if (update_dialog.noUpdates()) { QString message{ tr("'%1' is up-to-date! :)").arg(mods_list.front()->name()) }; if (mods_list.size() > 1) { if (use_all) { message = tr("All shader packs are up-to-date! :)"); } else { message = tr("All selected shader packs are up-to-date! :)"); } } CustomMessageBox::selectable(this, tr("Update checker"), message)->exec(); return; } if (update_dialog.exec()) { auto tasks = new ConcurrentTask("Download Shader Packs", APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) { CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); } tasks->deleteLater(); }); for (auto task : update_dialog.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } } void ShaderPackPage::deleteShaderPackMetadata() { auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); auto selectionCount = m_model->selectedShaderPacks(selection).length(); if (selectionCount == 0) return; if (selectionCount > 1) { auto response = CustomMessageBox::selectable(this, tr("Confirm Removal"), tr("You are about to remove the metadata for %1 shader packs.\n" "Are you sure?") .arg(selectionCount), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } m_model->deleteMetadata(selection); } void ShaderPackPage::changeShaderPackVersion() { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance if (APPLICATION->settings()->get("ModMetadataDisabled").toBool()) { QMessageBox::critical(this, tr("Error"), tr("Shader pack updates are unavailable when metadata is disabled!")); return; } const QModelIndexList rows = ui->treeView->selectionModel()->selectedRows(); if (rows.count() != 1) return; Resource& resource = m_model->at(m_filterModel->mapToSource(rows[0]).row()); if (resource.metadata() == nullptr) return; ResourceDownload::ShaderPackDownloadDialog mdownload(this, m_model, m_instance); mdownload.setResourceMetadata(resource.metadata()); if (mdownload.exec()) { auto tasks = new ConcurrentTask("Download Shader Packs", APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); tasks->deleteLater(); }); for (auto& task : mdownload.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } }
11,281
C++
.cpp
223
42.076233
134
0.649147
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,996
ModFolderPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/ModFolderPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ModFolderPage.h" #include "ui/dialogs/ExportToModListDialog.h" #include "ui_ExternalResourcesPage.h" #include <QAbstractItemModel> #include <QAction> #include <QEvent> #include <QKeyEvent> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> #include <algorithm> #include "Application.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ResourceDownloadDialog.h" #include "ui/dialogs/ResourceUpdateDialog.h" #include "minecraft/PackProfile.h" #include "minecraft/VersionFilterData.h" #include "minecraft/mod/Mod.h" #include "minecraft/mod/ModFolderModel.h" #include "tasks/ConcurrentTask.h" #include "tasks/Task.h" #include "ui/dialogs/ProgressDialog.h" ModFolderPage::ModFolderPage(BaseInstance* inst, std::shared_ptr<ModFolderModel> model, QWidget* parent) : ExternalResourcesPage(inst, model, parent), m_model(model) { ui->actionDownloadItem->setText(tr("Download Mods")); ui->actionDownloadItem->setToolTip(tr("Download mods from online mod platforms")); ui->actionDownloadItem->setEnabled(true); ui->actionsToolbar->insertActionBefore(ui->actionAddItem, ui->actionDownloadItem); connect(ui->actionDownloadItem, &QAction::triggered, this, &ModFolderPage::downloadMods); ui->actionUpdateItem->setToolTip(tr("Try to check or update all selected mods (all mods if none are selected)")); connect(ui->actionUpdateItem, &QAction::triggered, this, &ModFolderPage::updateMods); ui->actionsToolbar->insertActionBefore(ui->actionAddItem, ui->actionUpdateItem); auto updateMenu = new QMenu(this); auto update = updateMenu->addAction(tr("Check for Updates")); connect(update, &QAction::triggered, this, &ModFolderPage::updateMods); updateMenu->addAction(ui->actionVerifyItemDependencies); connect(ui->actionVerifyItemDependencies, &QAction::triggered, this, [this] { updateMods(true); }); auto depsDisabled = APPLICATION->settings()->getSetting("ModDependenciesDisabled"); ui->actionVerifyItemDependencies->setVisible(!depsDisabled->get().toBool()); connect(depsDisabled.get(), &Setting::SettingChanged, this, [this](const Setting& setting, const QVariant& value) { ui->actionVerifyItemDependencies->setVisible(!value.toBool()); }); updateMenu->addAction(ui->actionResetItemMetadata); connect(ui->actionResetItemMetadata, &QAction::triggered, this, &ModFolderPage::deleteModMetadata); ui->actionUpdateItem->setMenu(updateMenu); ui->actionChangeVersion->setToolTip(tr("Change a mod's version.")); connect(ui->actionChangeVersion, &QAction::triggered, this, &ModFolderPage::changeModVersion); ui->actionsToolbar->insertActionAfter(ui->actionUpdateItem, ui->actionChangeVersion); ui->actionViewHomepage->setToolTip(tr("View the homepages of all selected mods.")); ui->actionExportMetadata->setToolTip(tr("Export mod's metadata to text.")); connect(ui->actionExportMetadata, &QAction::triggered, this, &ModFolderPage::exportModMetadata); ui->actionsToolbar->insertActionAfter(ui->actionViewHomepage, ui->actionExportMetadata); } bool ModFolderPage::shouldDisplay() const { return true; } void ModFolderPage::updateFrame(const QModelIndex& current, [[maybe_unused]] const QModelIndex& previous) { auto sourceCurrent = m_filterModel->mapToSource(current); int row = sourceCurrent.row(); const Mod& mod = m_model->at(row); ui->frame->updateWithMod(mod); } void ModFolderPage::removeItems(const QItemSelection& selection) { if (m_instance != nullptr && m_instance->isRunning()) { auto response = CustomMessageBox::selectable(this, tr("Confirm Delete"), tr("If you remove mods while the game is running it may crash your game.\n" "Are you sure you want to do this?"), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } m_model->deleteResources(selection.indexes()); } void ModFolderPage::downloadMods() { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance auto profile = static_cast<MinecraftInstance*>(m_instance)->getPackProfile(); if (!profile->getModLoaders().has_value()) { QMessageBox::critical(this, tr("Error"), tr("Please install a mod loader first!")); return; } ResourceDownload::ModDownloadDialog mdownload(this, m_model, m_instance); if (mdownload.exec()) { auto tasks = new ConcurrentTask(tr("Download Mods"), APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); tasks->deleteLater(); }); for (auto& task : mdownload.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } } void ModFolderPage::updateMods(bool includeDeps) { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance auto profile = static_cast<MinecraftInstance*>(m_instance)->getPackProfile(); if (!profile->getModLoaders().has_value()) { QMessageBox::critical(this, tr("Error"), tr("Please install a mod loader first!")); return; } if (APPLICATION->settings()->get("ModMetadataDisabled").toBool()) { QMessageBox::critical(this, tr("Error"), tr("Mod updates are unavailable when metadata is disabled!")); return; } if (m_instance != nullptr && m_instance->isRunning()) { auto response = CustomMessageBox::selectable(this, tr("Confirm Update"), tr("Updating mods while the game is running may cause mod duplication and game crashes.\n" "The old files may not be deleted as they are in use.\n" "Are you sure you want to do this?"), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); auto mods_list = m_model->selectedResources(selection); bool use_all = mods_list.empty(); if (use_all) mods_list = m_model->allResources(); ResourceUpdateDialog update_dialog(this, m_instance, m_model, mods_list, includeDeps, true); update_dialog.checkCandidates(); if (update_dialog.aborted()) { CustomMessageBox::selectable(this, tr("Aborted"), tr("The mod updater was aborted!"), QMessageBox::Warning)->show(); return; } if (update_dialog.noUpdates()) { QString message{ tr("'%1' is up-to-date! :)").arg(mods_list.front()->name()) }; if (mods_list.size() > 1) { if (use_all) { message = tr("All mods are up-to-date! :)"); } else { message = tr("All selected mods are up-to-date! :)"); } } CustomMessageBox::selectable(this, tr("Update checker"), message)->exec(); return; } if (update_dialog.exec()) { auto tasks = new ConcurrentTask("Download Mods", APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) { CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); } tasks->deleteLater(); }); for (auto task : update_dialog.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } } void ModFolderPage::deleteModMetadata() { auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); auto selectionCount = m_model->selectedMods(selection).length(); if (selectionCount == 0) return; if (selectionCount > 1) { auto response = CustomMessageBox::selectable(this, tr("Confirm Removal"), tr("You are about to remove the metadata for %1 mods.\n" "Are you sure?") .arg(selectionCount), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } m_model->deleteMetadata(selection); } void ModFolderPage::changeModVersion() { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance auto profile = static_cast<MinecraftInstance*>(m_instance)->getPackProfile(); if (!profile->getModLoaders().has_value()) { QMessageBox::critical(this, tr("Error"), tr("Please install a mod loader first!")); return; } if (APPLICATION->settings()->get("ModMetadataDisabled").toBool()) { QMessageBox::critical(this, tr("Error"), tr("Mod updates are unavailable when metadata is disabled!")); return; } auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); auto mods_list = m_model->selectedMods(selection); if (mods_list.length() != 1 || mods_list[0]->metadata() == nullptr) return; ResourceDownload::ModDownloadDialog mdownload(this, m_model, m_instance); mdownload.setResourceMetadata((*mods_list.begin())->metadata()); if (mdownload.exec()) { auto tasks = new ConcurrentTask("Download Mods", APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); tasks->deleteLater(); }); for (auto& task : mdownload.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } } void ModFolderPage::exportModMetadata() { auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); auto selectedMods = m_model->selectedMods(selection); if (selectedMods.length() == 0) selectedMods = m_model->allMods(); std::sort(selectedMods.begin(), selectedMods.end(), [](const Mod* a, const Mod* b) { return a->name() < b->name(); }); ExportToModListDialog dlg(m_instance->name(), selectedMods, this); dlg.exec(); } CoreModFolderPage::CoreModFolderPage(BaseInstance* inst, std::shared_ptr<ModFolderModel> mods, QWidget* parent) : ModFolderPage(inst, mods, parent) { auto mcInst = dynamic_cast<MinecraftInstance*>(m_instance); if (mcInst) { auto version = mcInst->getPackProfile(); if (version && version->getComponent("net.minecraftforge") && version->getComponent("net.minecraft")) { auto minecraftCmp = version->getComponent("net.minecraft"); if (!minecraftCmp->m_loaded) { version->reload(Net::Mode::Offline); auto update = version->getCurrentTask(); if (update) { connect(update.get(), &Task::finished, this, [this] { if (m_container) { m_container->refreshContainer(); } }); update->start(); } } } } } bool CoreModFolderPage::shouldDisplay() const { if (ModFolderPage::shouldDisplay()) { auto inst = dynamic_cast<MinecraftInstance*>(m_instance); if (!inst) return true; auto version = inst->getPackProfile(); if (!version || !version->getComponent("net.minecraftforge") || !version->getComponent("net.minecraft")) return false; auto minecraftCmp = version->getComponent("net.minecraft"); return minecraftCmp->m_loaded && minecraftCmp->getReleaseDateTime() < g_VersionFilterData.legacyCutoffDate; } return false; } NilModFolderPage::NilModFolderPage(BaseInstance* inst, std::shared_ptr<ModFolderModel> mods, QWidget* parent) : ModFolderPage(inst, mods, parent) {} bool NilModFolderPage::shouldDisplay() const { return m_model->dir().exists(); }
16,494
C++
.cpp
338
40.526627
134
0.64795
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,998
ManagedPackPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/ManagedPackPage.cpp
// SPDX-FileCopyrightText: 2022 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "ManagedPackPage.h" #include <QDesktopServices> #include <QUrl> #include <QUrlQuery> #include "ui_ManagedPackPage.h" #include <QFileDialog> #include <QListView> #include <QProxyStyle> #include <QStyleFactory> #include "Application.h" #include "BuildConfig.h" #include "InstanceImportTask.h" #include "InstanceList.h" #include "InstanceTask.h" #include "Json.h" #include "Markdown.h" #include "StringUtils.h" #include "modplatform/modrinth/ModrinthPackManifest.h" #include "ui/InstanceWindow.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ProgressDialog.h" #include "net/ApiDownload.h" /** This is just to override the combo box popup behavior so that the combo box doesn't take the whole screen. * ... thanks Qt. */ class NoBigComboBoxStyle : public QProxyStyle { Q_OBJECT public: // clang-format off int styleHint(QStyle::StyleHint hint, const QStyleOption* option = nullptr, const QWidget* widget = nullptr, QStyleHintReturn* returnData = nullptr) const override { if (hint == QStyle::SH_ComboBox_Popup) return false; return QProxyStyle::styleHint(hint, option, widget, returnData); } // clang-format on /** * Something about QProxyStyle and QStyle objects means they can't be free'd just * because all the widgets using them are gone. * They seems to be tied to the QApplicaiton lifecycle. * So make singletons tied to the lifetime of the application to clean them up and ensure they aren't * being remade over and over again, thus leaking memory. */ public: static NoBigComboBoxStyle* getInstance(QStyle* style) { static QHash<QStyle*, NoBigComboBoxStyle*> s_singleton_instances_ = {}; static std::mutex s_singleton_instances_mutex_; std::lock_guard<std::mutex> lock(s_singleton_instances_mutex_); auto inst_iter = s_singleton_instances_.constFind(style); NoBigComboBoxStyle* inst = nullptr; if (inst_iter == s_singleton_instances_.constEnd() || *inst_iter == nullptr) { inst = new NoBigComboBoxStyle(style); inst->setParent(APPLICATION); s_singleton_instances_.insert(style, inst); qDebug() << "QProxyStyle NoBigComboBox created for" << style->objectName() << style; } else { inst = *inst_iter; } return inst; } private: NoBigComboBoxStyle(QStyle* style) : QProxyStyle(style) {} }; ManagedPackPage* ManagedPackPage::createPage(BaseInstance* inst, QString type, QWidget* parent) { if (type == "modrinth") return new ModrinthManagedPackPage(inst, nullptr, parent); if (type == "flame" && (APPLICATION->capabilities() & Application::SupportsFlame)) return new FlameManagedPackPage(inst, nullptr, parent); return new GenericManagedPackPage(inst, nullptr, parent); } ManagedPackPage::ManagedPackPage(BaseInstance* inst, InstanceWindow* instance_window, QWidget* parent) : QWidget(parent), m_instance_window(instance_window), ui(new Ui::ManagedPackPage), m_inst(inst) { Q_ASSERT(inst); ui->setupUi(this); // NOTE: GTK2 themes crash with the proxy style. // This seems like an upstream bug, so there's not much else that can be done. if (!QStyleFactory::keys().contains("gtk2")) { auto comboStyle = NoBigComboBoxStyle::getInstance(ui->versionsComboBox->style()); ui->versionsComboBox->setStyle(comboStyle); } ui->reloadButton->setVisible(false); connect(ui->reloadButton, &QPushButton::clicked, this, [this](bool) { ui->reloadButton->setVisible(false); m_loaded = false; // Pretend we're opening the page again openedImpl(); }); connect(ui->changelogTextBrowser, &QTextBrowser::anchorClicked, this, [](const QUrl url) { if (url.scheme().isEmpty()) { auto querry = QUrlQuery(url.query()).queryItemValue("remoteUrl", QUrl::FullyDecoded); // curseforge workaround for linkout?remoteUrl= auto decoded = QUrl::fromPercentEncoding(querry.toUtf8()); auto newUrl = QUrl(decoded); if (newUrl.isValid() && (newUrl.scheme() == "http" || newUrl.scheme() == "https")) QDesktopServices ::openUrl(newUrl); return; } QDesktopServices::openUrl(url); }); } ManagedPackPage::~ManagedPackPage() { delete ui; } void ManagedPackPage::openedImpl() { if (m_inst->getManagedPackID().isEmpty()) { ui->packVersion->hide(); ui->packVersionLabel->hide(); ui->packOrigin->hide(); ui->packOriginLabel->hide(); ui->versionsComboBox->hide(); ui->updateButton->hide(); ui->updateToVersionLabel->hide(); ui->updateFromFileButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); ui->packName->setText(m_inst->name()); ui->changelogTextBrowser->setText(tr("This is a local modpack.\n" "This can be updated only using a file in %1 format\n") .arg(displayName())); return; } ui->packName->setText(m_inst->getManagedPackName()); ui->packVersion->setText(m_inst->getManagedPackVersionName()); ui->packOrigin->setText(tr("Website: <a href=%1>%2</a> | Pack ID: %3 | Version ID: %4") .arg(url(), displayName(), m_inst->getManagedPackID(), m_inst->getManagedPackVersionID())); parseManagedPack(); } QString ManagedPackPage::displayName() const { auto type = m_inst->getManagedPackType(); if (type.isEmpty()) return {}; if (type == "flame") type = "CurseForge"; return type.replace(0, 1, type[0].toUpper()); } QIcon ManagedPackPage::icon() const { return APPLICATION->getThemedIcon(m_inst->getManagedPackType()); } QString ManagedPackPage::helpPage() const { return {}; } void ManagedPackPage::retranslate() { ui->retranslateUi(this); } bool ManagedPackPage::shouldDisplay() const { return m_inst->isManagedPack(); } bool ManagedPackPage::runUpdateTask(InstanceTask* task) { Q_ASSERT(task); unique_qobject_ptr<Task> wrapped_task(APPLICATION->instances()->wrapInstanceTask(task)); connect(task, &Task::failed, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); }); connect(task, &Task::succeeded, [this, task]() { QStringList warnings = task->warnings(); if (warnings.count()) CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); }); connect(task, &Task::aborted, [this] { CustomMessageBox::selectable(this, tr("Task aborted"), tr("The task has been aborted by the user."), QMessageBox::Information) ->show(); }); ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(task); return task->wasSuccessful(); } void ManagedPackPage::suggestVersion() { ui->updateButton->setText(tr("Update pack")); ui->updateButton->setDisabled(false); } void ManagedPackPage::setFailState() { qDebug() << "Setting fail state!"; // We block signals here so that suggestVersion() doesn't get called, causing an assertion fail. ui->versionsComboBox->blockSignals(true); ui->versionsComboBox->clear(); ui->versionsComboBox->addItem(tr("Failed to search for available versions."), {}); ui->versionsComboBox->blockSignals(false); ui->changelogTextBrowser->setText(tr("Failed to request changelog data for this modpack.")); ui->updateButton->setText(tr("Cannot update!")); ui->updateButton->setDisabled(true); ui->reloadButton->setVisible(true); } ModrinthManagedPackPage::ModrinthManagedPackPage(BaseInstance* inst, InstanceWindow* instance_window, QWidget* parent) : ManagedPackPage(inst, instance_window, parent) { Q_ASSERT(inst->isManagedPack()); connect(ui->versionsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(suggestVersion())); connect(ui->updateButton, &QPushButton::clicked, this, &ModrinthManagedPackPage::update); connect(ui->updateFromFileButton, &QPushButton::clicked, this, &ModrinthManagedPackPage::updateFromFile); } // MODRINTH void ModrinthManagedPackPage::parseManagedPack() { qDebug() << "Parsing Modrinth pack"; // No need for the extra work because we already have everything we need. if (m_loaded) return; if (m_fetch_job && m_fetch_job->isRunning()) m_fetch_job->abort(); m_fetch_job.reset(new NetJob(QString("Modrinth::PackVersions(%1)").arg(m_inst->getManagedPackName()), APPLICATION->network())); auto response = std::make_shared<QByteArray>(); QString id = m_inst->getManagedPackID(); m_fetch_job->addNetAction( Net::ApiDownload::makeByteArray(QString("%1/project/%2/version").arg(BuildConfig.MODRINTH_PROD_URL, id), response)); QObject::connect(m_fetch_job.get(), &NetJob::succeeded, this, [this, response, id] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Modrinth at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; setFailState(); return; } try { Modrinth::loadIndexedVersions(m_pack, doc); } catch (const JSONValidationError& e) { qDebug() << *response; qWarning() << "Error while reading modrinth modpack version: " << e.cause(); setFailState(); return; } // We block signals here so that suggestVersion() doesn't get called, causing an assertion fail. ui->versionsComboBox->blockSignals(true); ui->versionsComboBox->clear(); ui->versionsComboBox->blockSignals(false); for (auto version : m_pack.versions) { QString name = version.version; if (!version.name.contains(version.version)) name = QString("%1 — %2").arg(version.name, version.version); // NOTE: the id from version isn't the same id in the modpack format spec... // e.g. HexMC's 4.4.0 has versionId 4.0.0 in the modpack index.............. if (version.version == m_inst->getManagedPackVersionName()) name = tr("%1 (Current)").arg(name); ui->versionsComboBox->addItem(name, QVariant(version.id)); } suggestVersion(); m_loaded = true; }); QObject::connect(m_fetch_job.get(), &NetJob::failed, this, &ModrinthManagedPackPage::setFailState); QObject::connect(m_fetch_job.get(), &NetJob::aborted, this, &ModrinthManagedPackPage::setFailState); ui->changelogTextBrowser->setText(tr("Fetching changelogs...")); m_fetch_job->start(); } QString ModrinthManagedPackPage::url() const { return "https://modrinth.com/mod/" + m_inst->getManagedPackID(); } void ModrinthManagedPackPage::suggestVersion() { auto index = ui->versionsComboBox->currentIndex(); if (m_pack.versions.length() == 0) { setFailState(); return; } auto version = m_pack.versions.at(index); ui->changelogTextBrowser->setHtml(StringUtils::htmlListPatch(markdownToHTML(version.changelog.toUtf8()))); ManagedPackPage::suggestVersion(); } void ModrinthManagedPackPage::update() { auto index = ui->versionsComboBox->currentIndex(); if (m_pack.versions.length() == 0) { setFailState(); return; } auto version = m_pack.versions.at(index); QMap<QString, QString> extra_info; // NOTE: Don't use 'm_pack.id' here, since we didn't completely parse all the metadata for the pack, including this field. extra_info.insert("pack_id", m_inst->getManagedPackID()); extra_info.insert("pack_version_id", version.id); extra_info.insert("original_instance_id", m_inst->id()); auto extracted = new InstanceImportTask(version.download_url, this, std::move(extra_info)); InstanceName inst_name(m_inst->getManagedPackName(), version.version); inst_name.setName(m_inst->name().replace(m_inst->getManagedPackVersionName(), version.version)); extracted->setName(inst_name); extracted->setGroup(APPLICATION->instances()->getInstanceGroup(m_inst->id())); extracted->setIcon(m_inst->iconKey()); extracted->setConfirmUpdate(false); auto did_succeed = runUpdateTask(extracted); if (m_instance_window && did_succeed) m_instance_window->close(); } void ModrinthManagedPackPage::updateFromFile() { auto output = QFileDialog::getOpenFileUrl(this, tr("Choose update file"), QDir::homePath(), tr("Modrinth pack") + " (*.mrpack *.zip)"); if (output.isEmpty()) return; QMap<QString, QString> extra_info; extra_info.insert("pack_id", m_inst->getManagedPackID()); extra_info.insert("pack_version_id", QString()); extra_info.insert("original_instance_id", m_inst->id()); auto extracted = new InstanceImportTask(output, this, std::move(extra_info)); extracted->setName(m_inst->name()); extracted->setGroup(APPLICATION->instances()->getInstanceGroup(m_inst->id())); extracted->setIcon(m_inst->iconKey()); extracted->setConfirmUpdate(false); auto did_succeed = runUpdateTask(extracted); if (m_instance_window && did_succeed) m_instance_window->close(); } // FLAME FlameManagedPackPage::FlameManagedPackPage(BaseInstance* inst, InstanceWindow* instance_window, QWidget* parent) : ManagedPackPage(inst, instance_window, parent) { Q_ASSERT(inst->isManagedPack()); connect(ui->versionsComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(suggestVersion())); connect(ui->updateButton, &QPushButton::clicked, this, &FlameManagedPackPage::update); connect(ui->updateFromFileButton, &QPushButton::clicked, this, &FlameManagedPackPage::updateFromFile); } void FlameManagedPackPage::parseManagedPack() { qDebug() << "Parsing Flame pack"; // We need to tell the user to redownload the pack, since we didn't save the required info previously if (m_inst->getManagedPackID().isEmpty()) { setFailState(); QString message = tr("<h1>Hey there!</h1>" "<h4>" "It seems like your Pack ID is null. This is because of a bug in older versions of the launcher.<br/>" "Unfortunately, we can't do the proper API requests without this information.<br/>" "<br/>" "So, in order for this feature to work, you will need to re-download the modpack from the built-in downloader.<br/>" "<br/>" "Don't worry though, it will ask you to update this instance instead, so you'll not lose this instance!" "</h4>"); ui->changelogTextBrowser->setHtml(StringUtils::htmlListPatch(message)); return; } // No need for the extra work because we already have everything we need. if (m_loaded) return; if (m_fetch_job && m_fetch_job->isRunning()) m_fetch_job->abort(); m_fetch_job.reset(new NetJob(QString("Flame::PackVersions(%1)").arg(m_inst->getManagedPackName()), APPLICATION->network())); auto response = std::make_shared<QByteArray>(); QString id = m_inst->getManagedPackID(); m_fetch_job->addNetAction(Net::ApiDownload::makeByteArray(QString("%1/mods/%2/files").arg(BuildConfig.FLAME_BASE_URL, id), response)); QObject::connect(m_fetch_job.get(), &NetJob::succeeded, this, [this, response, id] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Flame at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; setFailState(); return; } try { auto obj = doc.object(); auto data = Json::ensureArray(obj, "data"); Flame::loadIndexedPackVersions(m_pack, data); } catch (const JSONValidationError& e) { qDebug() << *response; qWarning() << "Error while reading flame modpack version: " << e.cause(); setFailState(); return; } // We block signals here so that suggestVersion() doesn't get called, causing an assertion fail. ui->versionsComboBox->blockSignals(true); ui->versionsComboBox->clear(); ui->versionsComboBox->blockSignals(false); for (auto version : m_pack.versions) { QString name = version.version; if (version.fileId == m_inst->getManagedPackVersionID().toInt()) name = tr("%1 (Current)").arg(name); ui->versionsComboBox->addItem(name, QVariant(version.fileId)); } suggestVersion(); m_loaded = true; }); QObject::connect(m_fetch_job.get(), &NetJob::failed, this, &FlameManagedPackPage::setFailState); QObject::connect(m_fetch_job.get(), &NetJob::aborted, this, &FlameManagedPackPage::setFailState); m_fetch_job->start(); } QString FlameManagedPackPage::url() const { // FIXME: We should display the websiteUrl field, but this requires doing the API request first :( return "https://www.curseforge.com/projects/" + m_inst->getManagedPackID(); } void FlameManagedPackPage::suggestVersion() { auto index = ui->versionsComboBox->currentIndex(); if (m_pack.versions.length() == 0) { setFailState(); return; } auto version = m_pack.versions.at(index); ui->changelogTextBrowser->setHtml( StringUtils::htmlListPatch(m_api.getModFileChangelog(m_inst->getManagedPackID().toInt(), version.fileId))); ManagedPackPage::suggestVersion(); } void FlameManagedPackPage::update() { auto index = ui->versionsComboBox->currentIndex(); if (m_pack.versions.length() == 0) { setFailState(); return; } auto version = m_pack.versions.at(index); QMap<QString, QString> extra_info; extra_info.insert("pack_id", m_inst->getManagedPackID()); extra_info.insert("pack_version_id", QString::number(version.fileId)); extra_info.insert("original_instance_id", m_inst->id()); auto extracted = new InstanceImportTask(version.downloadUrl, this, std::move(extra_info)); extracted->setName(m_inst->name()); extracted->setGroup(APPLICATION->instances()->getInstanceGroup(m_inst->id())); extracted->setIcon(m_inst->iconKey()); extracted->setConfirmUpdate(false); auto did_succeed = runUpdateTask(extracted); if (m_instance_window && did_succeed) m_instance_window->close(); } void FlameManagedPackPage::updateFromFile() { auto output = QFileDialog::getOpenFileUrl(this, tr("Choose update file"), QDir::homePath(), tr("CurseForge pack") + " (*.zip)"); if (output.isEmpty()) return; QMap<QString, QString> extra_info; extra_info.insert("pack_id", m_inst->getManagedPackID()); extra_info.insert("pack_version_id", QString()); extra_info.insert("original_instance_id", m_inst->id()); auto extracted = new InstanceImportTask(output, this, std::move(extra_info)); extracted->setName(m_inst->name()); extracted->setGroup(APPLICATION->instances()->getInstanceGroup(m_inst->id())); extracted->setIcon(m_inst->iconKey()); extracted->setConfirmUpdate(false); auto did_succeed = runUpdateTask(extracted); if (m_instance_window && did_succeed) m_instance_window->close(); } #include "ManagedPackPage.moc"
20,088
C++
.cpp
446
38.430493
167
0.670286
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
28,999
InstanceSettingsPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/InstanceSettingsPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "InstanceSettingsPage.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/WorldList.h" #include "settings/Setting.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/java/InstallJavaDialog.h" #include "ui_InstanceSettingsPage.h" #include <QDialog> #include <QFileDialog> #include <QMessageBox> #include <sys.h> #include "ui/dialogs/VersionSelectDialog.h" #include "ui/widgets/CustomCommands.h" #include "Application.h" #include "BuildConfig.h" #include "JavaCommon.h" #include "minecraft/auth/AccountList.h" #include "FileSystem.h" #include "java/JavaInstallList.h" #include "java/JavaUtils.h" InstanceSettingsPage::InstanceSettingsPage(BaseInstance* inst, QWidget* parent) : QWidget(parent), ui(new Ui::InstanceSettingsPage), m_instance(inst) { m_settings = inst->settings(); ui->setupUi(this); ui->javaDownloadBtn->setHidden(!BuildConfig.JAVA_DOWNLOADER_ENABLED); connect(ui->openGlobalJavaSettingsButton, &QCommandLinkButton::clicked, this, &InstanceSettingsPage::globalSettingsButtonClicked); connect(APPLICATION, &Application::globalSettingsAboutToOpen, this, &InstanceSettingsPage::applySettings); connect(APPLICATION, &Application::globalSettingsClosed, this, &InstanceSettingsPage::loadSettings); connect(ui->instanceAccountSelector, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &InstanceSettingsPage::changeInstanceAccount); connect(ui->useNativeGLFWCheck, &QAbstractButton::toggled, this, &InstanceSettingsPage::onUseNativeGLFWChanged); connect(ui->useNativeOpenALCheck, &QAbstractButton::toggled, this, &InstanceSettingsPage::onUseNativeOpenALChanged); auto mInst = dynamic_cast<MinecraftInstance*>(inst); m_world_quickplay_supported = mInst && mInst->traits().contains("feature:is_quick_play_singleplayer"); if (m_world_quickplay_supported) { auto worlds = mInst->worldList(); worlds->update(); for (const auto& world : worlds->allWorlds()) { ui->worldsCb->addItem(world.folderName()); } } else { ui->worldsCb->hide(); ui->worldJoinButton->hide(); ui->serverJoinAddressButton->setChecked(true); ui->serverJoinAddress->setEnabled(true); ui->serverJoinAddressButton->setStyleSheet("QRadioButton::indicator { width: 0px; height: 0px; }"); } loadSettings(); updateThresholds(); } InstanceSettingsPage::~InstanceSettingsPage() { delete ui; } void InstanceSettingsPage::globalSettingsButtonClicked(bool) { switch (ui->settingsTabs->currentIndex()) { case 0: APPLICATION->ShowGlobalSettings(this, "java-settings"); return; case 2: APPLICATION->ShowGlobalSettings(this, "custom-commands"); return; case 3: APPLICATION->ShowGlobalSettings(this, "environment-variables"); return; default: APPLICATION->ShowGlobalSettings(this, "minecraft-settings"); return; } } bool InstanceSettingsPage::apply() { applySettings(); return true; } void InstanceSettingsPage::applySettings() { SettingsObject::Lock lock(m_settings); // Miscellaneous bool miscellaneous = ui->miscellaneousSettingsBox->isChecked(); m_settings->set("OverrideMiscellaneous", miscellaneous); if (miscellaneous) { m_settings->set("CloseAfterLaunch", ui->closeAfterLaunchCheck->isChecked()); m_settings->set("QuitAfterGameStop", ui->quitAfterGameStopCheck->isChecked()); } else { m_settings->reset("CloseAfterLaunch"); m_settings->reset("QuitAfterGameStop"); } // Console bool console = ui->consoleSettingsBox->isChecked(); m_settings->set("OverrideConsole", console); if (console) { m_settings->set("ShowConsole", ui->showConsoleCheck->isChecked()); m_settings->set("AutoCloseConsole", ui->autoCloseConsoleCheck->isChecked()); m_settings->set("ShowConsoleOnError", ui->showConsoleErrorCheck->isChecked()); } else { m_settings->reset("ShowConsole"); m_settings->reset("AutoCloseConsole"); m_settings->reset("ShowConsoleOnError"); } // Window Size bool window = ui->windowSizeGroupBox->isChecked(); m_settings->set("OverrideWindow", window); if (window) { m_settings->set("LaunchMaximized", ui->maximizedCheckBox->isChecked()); m_settings->set("MinecraftWinWidth", ui->windowWidthSpinBox->value()); m_settings->set("MinecraftWinHeight", ui->windowHeightSpinBox->value()); } else { m_settings->reset("LaunchMaximized"); m_settings->reset("MinecraftWinWidth"); m_settings->reset("MinecraftWinHeight"); } // Memory bool memory = ui->memoryGroupBox->isChecked(); m_settings->set("OverrideMemory", memory); if (memory) { int min = ui->minMemSpinBox->value(); int max = ui->maxMemSpinBox->value(); if (min < max) { m_settings->set("MinMemAlloc", min); m_settings->set("MaxMemAlloc", max); } else { m_settings->set("MinMemAlloc", max); m_settings->set("MaxMemAlloc", min); } m_settings->set("PermGen", ui->permGenSpinBox->value()); } else { m_settings->reset("MinMemAlloc"); m_settings->reset("MaxMemAlloc"); m_settings->reset("PermGen"); } // Java Install Settings bool javaInstall = ui->javaSettingsGroupBox->isChecked(); m_settings->set("OverrideJavaLocation", javaInstall); if (javaInstall) { m_settings->set("JavaPath", ui->javaPathTextBox->text()); m_settings->set("IgnoreJavaCompatibility", ui->skipCompatibilityCheckbox->isChecked()); } else { m_settings->reset("JavaPath"); m_settings->reset("IgnoreJavaCompatibility"); } // Java arguments bool javaArgs = ui->javaArgumentsGroupBox->isChecked(); m_settings->set("OverrideJavaArgs", javaArgs); if (javaArgs) { m_settings->set("JvmArgs", ui->jvmArgsTextBox->toPlainText().replace("\n", " ")); } else { m_settings->reset("JvmArgs"); } // Custom Commands bool custcmd = ui->customCommands->checked(); m_settings->set("OverrideCommands", custcmd); if (custcmd) { m_settings->set("PreLaunchCommand", ui->customCommands->prelaunchCommand()); m_settings->set("WrapperCommand", ui->customCommands->wrapperCommand()); m_settings->set("PostExitCommand", ui->customCommands->postexitCommand()); } else { m_settings->reset("PreLaunchCommand"); m_settings->reset("WrapperCommand"); m_settings->reset("PostExitCommand"); } // Environment Variables auto env = ui->environmentVariables->override(); m_settings->set("OverrideEnv", env); if (env) m_settings->set("Env", ui->environmentVariables->value()); else m_settings->reset("Env"); // Workarounds bool workarounds = ui->nativeWorkaroundsGroupBox->isChecked(); m_settings->set("OverrideNativeWorkarounds", workarounds); if (workarounds) { m_settings->set("UseNativeGLFW", ui->useNativeGLFWCheck->isChecked()); m_settings->set("CustomGLFWPath", ui->lineEditGLFWPath->text()); m_settings->set("UseNativeOpenAL", ui->useNativeOpenALCheck->isChecked()); m_settings->set("CustomOpenALPath", ui->lineEditOpenALPath->text()); } else { m_settings->reset("UseNativeGLFW"); m_settings->reset("CustomGLFWPath"); m_settings->reset("UseNativeOpenAL"); m_settings->reset("CustomOpenALPath"); } // Performance bool performance = ui->perfomanceGroupBox->isChecked(); m_settings->set("OverridePerformance", performance); if (performance) { m_settings->set("EnableFeralGamemode", ui->enableFeralGamemodeCheck->isChecked()); m_settings->set("EnableMangoHud", ui->enableMangoHud->isChecked()); m_settings->set("UseDiscreteGpu", ui->useDiscreteGpuCheck->isChecked()); m_settings->set("UseZink", ui->useZink->isChecked()); } else { m_settings->reset("EnableFeralGamemode"); m_settings->reset("EnableMangoHud"); m_settings->reset("UseDiscreteGpu"); m_settings->reset("UseZink"); } // Game time bool gameTime = ui->gameTimeGroupBox->isChecked(); m_settings->set("OverrideGameTime", gameTime); if (gameTime) { m_settings->set("ShowGameTime", ui->showGameTime->isChecked()); m_settings->set("RecordGameTime", ui->recordGameTime->isChecked()); } else { m_settings->reset("ShowGameTime"); m_settings->reset("RecordGameTime"); } // Join server on launch bool joinServerOnLaunch = ui->serverJoinGroupBox->isChecked(); m_settings->set("JoinServerOnLaunch", joinServerOnLaunch); if (joinServerOnLaunch) { if (ui->serverJoinAddressButton->isChecked() || !m_world_quickplay_supported) { m_settings->set("JoinServerOnLaunchAddress", ui->serverJoinAddress->text()); m_settings->reset("JoinWorldOnLaunch"); } else { m_settings->set("JoinWorldOnLaunch", ui->worldsCb->currentText()); m_settings->reset("JoinServerOnLaunchAddress"); } } else { m_settings->reset("JoinServerOnLaunchAddress"); m_settings->reset("JoinWorldOnLaunch"); } // Use an account for this instance bool useAccountForInstance = ui->instanceAccountGroupBox->isChecked(); m_settings->set("UseAccountForInstance", useAccountForInstance); if (!useAccountForInstance) { m_settings->reset("InstanceAccountId"); } bool overrideLegacySettings = ui->legacySettingsGroupBox->isChecked(); m_settings->set("OverrideLegacySettings", overrideLegacySettings); if (overrideLegacySettings) { m_settings->set("OnlineFixes", ui->onlineFixes->isChecked()); } else { m_settings->reset("OnlineFixes"); } // FIXME: This should probably be called by a signal instead m_instance->updateRuntimeContext(); } void InstanceSettingsPage::loadSettings() { // Miscellaneous ui->miscellaneousSettingsBox->setChecked(m_settings->get("OverrideMiscellaneous").toBool()); ui->closeAfterLaunchCheck->setChecked(m_settings->get("CloseAfterLaunch").toBool()); ui->quitAfterGameStopCheck->setChecked(m_settings->get("QuitAfterGameStop").toBool()); // Console ui->consoleSettingsBox->setChecked(m_settings->get("OverrideConsole").toBool()); ui->showConsoleCheck->setChecked(m_settings->get("ShowConsole").toBool()); ui->autoCloseConsoleCheck->setChecked(m_settings->get("AutoCloseConsole").toBool()); ui->showConsoleErrorCheck->setChecked(m_settings->get("ShowConsoleOnError").toBool()); // Window Size ui->windowSizeGroupBox->setChecked(m_settings->get("OverrideWindow").toBool()); ui->maximizedCheckBox->setChecked(m_settings->get("LaunchMaximized").toBool()); ui->maximizedWarning->setVisible(m_settings->get("LaunchMaximized").toBool() && !m_instance->isLegacy()); ui->windowWidthSpinBox->setValue(m_settings->get("MinecraftWinWidth").toInt()); ui->windowHeightSpinBox->setValue(m_settings->get("MinecraftWinHeight").toInt()); // Memory ui->memoryGroupBox->setChecked(m_settings->get("OverrideMemory").toBool()); int min = m_settings->get("MinMemAlloc").toInt(); int max = m_settings->get("MaxMemAlloc").toInt(); if (min < max) { ui->minMemSpinBox->setValue(min); ui->maxMemSpinBox->setValue(max); } else { ui->minMemSpinBox->setValue(max); ui->maxMemSpinBox->setValue(min); } ui->permGenSpinBox->setValue(m_settings->get("PermGen").toInt()); bool permGenVisible = m_settings->get("PermGenVisible").toBool(); ui->permGenSpinBox->setVisible(permGenVisible); ui->labelPermGen->setVisible(permGenVisible); ui->labelPermgenNote->setVisible(permGenVisible); // Java Settings bool overrideLocation = m_settings->get("OverrideJavaLocation").toBool(); bool overrideArgs = m_settings->get("OverrideJavaArgs").toBool(); connect(m_settings->getSetting("OverrideJavaLocation").get(), &Setting::SettingChanged, ui->javaSettingsGroupBox, [this] { ui->javaSettingsGroupBox->setChecked(m_settings->get("OverrideJavaLocation").toBool()); }); ui->javaSettingsGroupBox->setChecked(overrideLocation); ui->javaPathTextBox->setText(m_settings->get("JavaPath").toString()); connect(m_settings->getSetting("JavaPath").get(), &Setting::SettingChanged, ui->javaSettingsGroupBox, [this] { ui->javaPathTextBox->setText(m_settings->get("JavaPath").toString()); }); ui->skipCompatibilityCheckbox->setChecked(m_settings->get("IgnoreJavaCompatibility").toBool()); ui->javaArgumentsGroupBox->setChecked(overrideArgs); ui->jvmArgsTextBox->setPlainText(m_settings->get("JvmArgs").toString()); // Custom commands ui->customCommands->initialize(true, m_settings->get("OverrideCommands").toBool(), m_settings->get("PreLaunchCommand").toString(), m_settings->get("WrapperCommand").toString(), m_settings->get("PostExitCommand").toString()); // Environment variables ui->environmentVariables->initialize(true, m_settings->get("OverrideEnv").toBool(), m_settings->get("Env").toMap()); // Workarounds ui->nativeWorkaroundsGroupBox->setChecked(m_settings->get("OverrideNativeWorkarounds").toBool()); ui->useNativeGLFWCheck->setChecked(m_settings->get("UseNativeGLFW").toBool()); ui->lineEditGLFWPath->setText(m_settings->get("CustomGLFWPath").toString()); #ifdef Q_OS_LINUX ui->lineEditGLFWPath->setPlaceholderText(APPLICATION->m_detectedGLFWPath); #else ui->lineEditGLFWPath->setPlaceholderText(tr("Path to %1 library file").arg(BuildConfig.GLFW_LIBRARY_NAME)); #endif ui->useNativeOpenALCheck->setChecked(m_settings->get("UseNativeOpenAL").toBool()); ui->lineEditOpenALPath->setText(m_settings->get("CustomOpenALPath").toString()); #ifdef Q_OS_LINUX ui->lineEditOpenALPath->setPlaceholderText(APPLICATION->m_detectedOpenALPath); #else ui->lineEditOpenALPath->setPlaceholderText(tr("Path to %1 library file").arg(BuildConfig.OPENAL_LIBRARY_NAME)); #endif // Performance ui->perfomanceGroupBox->setChecked(m_settings->get("OverridePerformance").toBool()); ui->enableFeralGamemodeCheck->setChecked(m_settings->get("EnableFeralGamemode").toBool()); ui->enableMangoHud->setChecked(m_settings->get("EnableMangoHud").toBool()); ui->useDiscreteGpuCheck->setChecked(m_settings->get("UseDiscreteGpu").toBool()); ui->useZink->setChecked(m_settings->get("UseZink").toBool()); #if !defined(Q_OS_LINUX) ui->settingsTabs->setTabVisible(ui->settingsTabs->indexOf(ui->performancePage), false); #endif if (!(APPLICATION->capabilities() & Application::SupportsGameMode)) { ui->enableFeralGamemodeCheck->setDisabled(true); ui->enableFeralGamemodeCheck->setToolTip(tr("Feral Interactive's GameMode could not be found on your system.")); } if (!(APPLICATION->capabilities() & Application::SupportsMangoHud)) { ui->enableMangoHud->setDisabled(true); ui->enableMangoHud->setToolTip(tr("MangoHud could not be found on your system.")); } // Miscellanous ui->gameTimeGroupBox->setChecked(m_settings->get("OverrideGameTime").toBool()); ui->showGameTime->setChecked(m_settings->get("ShowGameTime").toBool()); ui->recordGameTime->setChecked(m_settings->get("RecordGameTime").toBool()); ui->serverJoinGroupBox->setChecked(m_settings->get("JoinServerOnLaunch").toBool()); if (auto server = m_settings->get("JoinServerOnLaunchAddress").toString(); !server.isEmpty()) { ui->serverJoinAddress->setText(server); ui->serverJoinAddressButton->setChecked(true); ui->worldJoinButton->setChecked(false); ui->serverJoinAddress->setEnabled(true); ui->worldsCb->setEnabled(false); } else if (auto world = m_settings->get("JoinWorldOnLaunch").toString(); !world.isEmpty() && m_world_quickplay_supported) { ui->worldsCb->setCurrentText(world); ui->serverJoinAddressButton->setChecked(false); ui->worldJoinButton->setChecked(true); ui->serverJoinAddress->setEnabled(false); ui->worldsCb->setEnabled(true); } else { ui->serverJoinAddressButton->setChecked(true); ui->worldJoinButton->setChecked(false); ui->serverJoinAddress->setEnabled(true); ui->worldsCb->setEnabled(false); } ui->instanceAccountGroupBox->setChecked(m_settings->get("UseAccountForInstance").toBool()); updateAccountsMenu(); ui->legacySettingsGroupBox->setChecked(m_settings->get("OverrideLegacySettings").toBool()); ui->onlineFixes->setChecked(m_settings->get("OnlineFixes").toBool()); } void InstanceSettingsPage::on_javaDownloadBtn_clicked() { auto jdialog = new Java::InstallDialog({}, m_instance, this); jdialog->exec(); } void InstanceSettingsPage::on_javaDetectBtn_clicked() { if (JavaUtils::getJavaCheckPath().isEmpty()) { JavaCommon::javaCheckNotFound(this); return; } JavaInstallPtr java; VersionSelectDialog vselect(APPLICATION->javalist().get(), tr("Select a Java version"), this, true); vselect.setResizeOn(2); vselect.exec(); if (vselect.result() == QDialog::Accepted && vselect.selectedVersion()) { java = std::dynamic_pointer_cast<JavaInstall>(vselect.selectedVersion()); ui->javaPathTextBox->setText(java->path); bool visible = java->id.requiresPermGen() && m_settings->get("OverrideMemory").toBool(); ui->permGenSpinBox->setVisible(visible); ui->labelPermGen->setVisible(visible); ui->labelPermgenNote->setVisible(visible); m_settings->set("PermGenVisible", visible); if (!java->is_64bit && m_settings->get("MaxMemAlloc").toInt() > 2048) { CustomMessageBox::selectable(this, tr("Confirm Selection"), tr("You selected a 32-bit version of Java.\n" "This installation does not support more than 2048MiB of RAM.\n" "Please make sure that the maximum memory value is lower."), QMessageBox::Warning, QMessageBox::Ok, QMessageBox::Ok) ->exec(); } } } void InstanceSettingsPage::on_javaBrowseBtn_clicked() { QString raw_path = QFileDialog::getOpenFileName(this, tr("Find Java executable")); // do not allow current dir - it's dirty. Do not allow dirs that don't exist if (raw_path.isEmpty()) { return; } QString cooked_path = FS::NormalizePath(raw_path); QFileInfo javaInfo(cooked_path); if (!javaInfo.exists() || !javaInfo.isExecutable()) { return; } ui->javaPathTextBox->setText(cooked_path); // custom Java could be anything... enable perm gen option ui->permGenSpinBox->setVisible(true); ui->labelPermGen->setVisible(true); ui->labelPermgenNote->setVisible(true); m_settings->set("PermGenVisible", true); } void InstanceSettingsPage::on_javaTestBtn_clicked() { if (checker) { return; } checker.reset(new JavaCommon::TestCheck(this, ui->javaPathTextBox->text(), ui->jvmArgsTextBox->toPlainText().replace("\n", " "), ui->minMemSpinBox->value(), ui->maxMemSpinBox->value(), ui->permGenSpinBox->value())); connect(checker.get(), SIGNAL(finished()), SLOT(checkerFinished())); checker->run(); } void InstanceSettingsPage::onUseNativeGLFWChanged(bool checked) { ui->lineEditGLFWPath->setEnabled(checked); } void InstanceSettingsPage::onUseNativeOpenALChanged(bool checked) { ui->lineEditOpenALPath->setEnabled(checked); } void InstanceSettingsPage::updateAccountsMenu() { ui->instanceAccountSelector->clear(); auto accounts = APPLICATION->accounts(); int accountIndex = accounts->findAccountByProfileId(m_settings->get("InstanceAccountId").toString()); for (int i = 0; i < accounts->count(); i++) { MinecraftAccountPtr account = accounts->at(i); ui->instanceAccountSelector->addItem(getFaceForAccount(account), account->profileName(), i); if (i == accountIndex) ui->instanceAccountSelector->setCurrentIndex(i); } } QIcon InstanceSettingsPage::getFaceForAccount(MinecraftAccountPtr account) { if (auto face = account->getFace(); !face.isNull()) { return face; } return APPLICATION->getThemedIcon("noaccount"); } void InstanceSettingsPage::changeInstanceAccount(int index) { auto accounts = APPLICATION->accounts(); if (index != -1 && accounts->at(index) && ui->instanceAccountGroupBox->isChecked()) { auto account = accounts->at(index); m_settings->set("InstanceAccountId", account->profileId()); } } void InstanceSettingsPage::on_maxMemSpinBox_valueChanged([[maybe_unused]] int i) { updateThresholds(); } void InstanceSettingsPage::checkerFinished() { checker.reset(); } void InstanceSettingsPage::retranslate() { ui->retranslateUi(this); ui->customCommands->retranslate(); // TODO: why is this seperate from the others? ui->environmentVariables->retranslate(); } void InstanceSettingsPage::updateThresholds() { auto sysMiB = Sys::getSystemRam() / Sys::mebibyte; unsigned int maxMem = ui->maxMemSpinBox->value(); unsigned int minMem = ui->minMemSpinBox->value(); QString iconName; if (maxMem >= sysMiB) { iconName = "status-bad"; ui->labelMaxMemIcon->setToolTip(tr("Your maximum memory allocation exceeds your system memory capacity.")); } else if (maxMem > (sysMiB * 0.9)) { iconName = "status-yellow"; ui->labelMaxMemIcon->setToolTip(tr("Your maximum memory allocation approaches your system memory capacity.")); } else if (maxMem < minMem) { iconName = "status-yellow"; ui->labelMaxMemIcon->setToolTip(tr("Your maximum memory allocation is smaller than the minimum value")); } else { iconName = "status-good"; ui->labelMaxMemIcon->setToolTip(""); } { auto height = ui->labelMaxMemIcon->fontInfo().pixelSize(); QIcon icon = APPLICATION->getThemedIcon(iconName); QPixmap pix = icon.pixmap(height, height); ui->labelMaxMemIcon->setPixmap(pix); } } void InstanceSettingsPage::on_serverJoinAddressButton_toggled(bool checked) { ui->serverJoinAddress->setEnabled(checked); } void InstanceSettingsPage::on_worldJoinButton_toggled(bool checked) { ui->worldsCb->setEnabled(checked); }
24,409
C++
.cpp
531
39.922787
134
0.694554
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,000
ExternalResourcesPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/ExternalResourcesPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ExternalResourcesPage.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui_ExternalResourcesPage.h" #include "DesktopServices.h" #include "Version.h" #include "minecraft/mod/ResourceFolderModel.h" #include "ui/GuiUtil.h" #include <QHeaderView> #include <QKeyEvent> #include <QMenu> #include <algorithm> ExternalResourcesPage::ExternalResourcesPage(BaseInstance* instance, std::shared_ptr<ResourceFolderModel> model, QWidget* parent) : QMainWindow(parent), m_instance(instance), ui(new Ui::ExternalResourcesPage), m_model(model) { ui->setupUi(this); ui->actionsToolbar->insertSpacer(ui->actionViewConfigs); m_filterModel = model->createFilterProxyModel(this); m_filterModel->setDynamicSortFilter(true); m_filterModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_filterModel->setSourceModel(m_model.get()); m_filterModel->setFilterKeyColumn(-1); ui->treeView->setModel(m_filterModel); // must come after setModel ui->treeView->setResizeModes(m_model->columnResizeModes()); ui->treeView->installEventFilter(this); ui->treeView->sortByColumn(1, Qt::AscendingOrder); ui->treeView->setContextMenuPolicy(Qt::CustomContextMenu); // The default function names by Qt are pretty ugly, so let's just connect the actions manually, // to make it easier to read :) connect(ui->actionAddItem, &QAction::triggered, this, &ExternalResourcesPage::addItem); connect(ui->actionRemoveItem, &QAction::triggered, this, &ExternalResourcesPage::removeItem); connect(ui->actionEnableItem, &QAction::triggered, this, &ExternalResourcesPage::enableItem); connect(ui->actionDisableItem, &QAction::triggered, this, &ExternalResourcesPage::disableItem); connect(ui->actionViewHomepage, &QAction::triggered, this, &ExternalResourcesPage::viewHomepage); connect(ui->actionViewConfigs, &QAction::triggered, this, &ExternalResourcesPage::viewConfigs); connect(ui->actionViewFolder, &QAction::triggered, this, &ExternalResourcesPage::viewFolder); connect(ui->treeView, &ModListView::customContextMenuRequested, this, &ExternalResourcesPage::ShowContextMenu); connect(ui->treeView, &ModListView::activated, this, &ExternalResourcesPage::itemActivated); auto selection_model = ui->treeView->selectionModel(); connect(selection_model, &QItemSelectionModel::currentChanged, this, [this](const QModelIndex& current, const QModelIndex& previous) { if (!current.isValid()) { ui->frame->clear(); return; } updateFrame(current, previous); }); auto updateExtra = [this]() { if (updateExtraInfo) updateExtraInfo(id(), extraHeaderInfoString()); }; connect(selection_model, &QItemSelectionModel::selectionChanged, this, updateExtra); connect(model.get(), &ResourceFolderModel::updateFinished, this, updateExtra); connect(model.get(), &ResourceFolderModel::parseFinished, this, updateExtra); connect(selection_model, &QItemSelectionModel::selectionChanged, this, [this] { updateActions(); }); connect(m_model.get(), &ResourceFolderModel::rowsInserted, this, [this] { updateActions(); }); connect(m_model.get(), &ResourceFolderModel::rowsRemoved, this, [this] { updateActions(); }); auto viewHeader = ui->treeView->header(); viewHeader->setContextMenuPolicy(Qt::CustomContextMenu); connect(viewHeader, &QHeaderView::customContextMenuRequested, this, &ExternalResourcesPage::ShowHeaderContextMenu); m_model->loadColumns(ui->treeView); connect(ui->treeView->header(), &QHeaderView::sectionResized, this, [this] { m_model->saveColumns(ui->treeView); }); connect(ui->filterEdit, &QLineEdit::textChanged, this, &ExternalResourcesPage::filterTextChanged); } ExternalResourcesPage::~ExternalResourcesPage() { delete ui; } QMenu* ExternalResourcesPage::createPopupMenu() { QMenu* filteredMenu = QMainWindow::createPopupMenu(); filteredMenu->removeAction(ui->actionsToolbar->toggleViewAction()); return filteredMenu; } void ExternalResourcesPage::ShowContextMenu(const QPoint& pos) { auto menu = ui->actionsToolbar->createContextMenu(this, tr("Context menu")); menu->exec(ui->treeView->mapToGlobal(pos)); delete menu; } void ExternalResourcesPage::ShowHeaderContextMenu(const QPoint& pos) { auto menu = m_model->createHeaderContextMenu(ui->treeView); menu->exec(ui->treeView->mapToGlobal(pos)); menu->deleteLater(); } void ExternalResourcesPage::openedImpl() { m_model->startWatching(); auto const setting_name = QString("WideBarVisibility_%1").arg(id()); if (!APPLICATION->settings()->contains(setting_name)) m_wide_bar_setting = APPLICATION->settings()->registerSetting(setting_name); else m_wide_bar_setting = APPLICATION->settings()->getSetting(setting_name); ui->actionsToolbar->setVisibilityState(m_wide_bar_setting->get().toByteArray()); } void ExternalResourcesPage::closedImpl() { m_model->stopWatching(); m_wide_bar_setting->set(ui->actionsToolbar->getVisibilityState()); } void ExternalResourcesPage::retranslate() { ui->retranslateUi(this); } void ExternalResourcesPage::itemActivated(const QModelIndex&) { auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()); m_model->setResourceEnabled(selection.indexes(), EnableAction::TOGGLE); } void ExternalResourcesPage::filterTextChanged(const QString& newContents) { m_viewFilter = newContents; m_filterModel->setFilterRegularExpression(m_viewFilter); } bool ExternalResourcesPage::shouldDisplay() const { return true; } bool ExternalResourcesPage::listFilter(QKeyEvent* keyEvent) { switch (keyEvent->key()) { case Qt::Key_Delete: removeItem(); return true; case Qt::Key_Plus: addItem(); return true; default: break; } return QWidget::eventFilter(ui->treeView, keyEvent); } bool ExternalResourcesPage::eventFilter(QObject* obj, QEvent* ev) { if (ev->type() != QEvent::KeyPress) return QWidget::eventFilter(obj, ev); QKeyEvent* keyEvent = static_cast<QKeyEvent*>(ev); if (obj == ui->treeView) return listFilter(keyEvent); return QWidget::eventFilter(obj, ev); } void ExternalResourcesPage::addItem() { auto list = GuiUtil::BrowseForFiles( helpPage(), tr("Select %1", "Select whatever type of files the page contains. Example: 'Loader Mods'").arg(displayName()), m_fileSelectionFilter.arg(displayName()), APPLICATION->settings()->get("CentralModsDir").toString(), this->parentWidget()); if (!list.isEmpty()) { for (auto filename : list) { m_model->installResource(filename); } } } void ExternalResourcesPage::removeItem() { auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()); int count = 0; bool folder = false; for (auto& i : selection.indexes()) { if (i.column() == 0) { count++; // if a folder is selected, show the confirmation dialog if (m_model->at(i.row()).fileinfo().isDir()) folder = true; } } QString text; bool multiple = count > 1; if (multiple) { text = tr("You are about to remove %1 items.\n" "This may be permanent and they will be gone from the folder.\n\n" "Are you sure?") .arg(count); } else if (folder) { text = tr("You are about to remove the folder \"%1\".\n" "This may be permanent and it will be gone from the parent folder.\n\n" "Are you sure?") .arg(m_model->at(selection.indexes().at(0).row()).fileinfo().fileName()); } if (!text.isEmpty()) { auto response = CustomMessageBox::selectable(this, tr("Confirm Removal"), text, QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } removeItems(selection); } void ExternalResourcesPage::removeItems(const QItemSelection& selection) { if (m_instance != nullptr && m_instance->isRunning()) { auto response = CustomMessageBox::selectable(this, tr("Confirm Delete"), tr("If you remove this resource while the game is running it may crash your game.\n" "Are you sure you want to do this?"), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } m_model->deleteResources(selection.indexes()); } void ExternalResourcesPage::enableItem() { auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()); m_model->setResourceEnabled(selection.indexes(), EnableAction::ENABLE); } void ExternalResourcesPage::disableItem() { if (m_instance != nullptr && m_instance->isRunning()) { auto response = CustomMessageBox::selectable(this, tr("Confirm disable"), tr("If you disable this resource while the game is running it may crash your game.\n" "Are you sure you want to do this?"), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()); m_model->setResourceEnabled(selection.indexes(), EnableAction::DISABLE); } void ExternalResourcesPage::viewHomepage() { auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); for (auto resource : m_model->selectedResources(selection)) { auto url = resource->homepage(); if (!url.isEmpty()) DesktopServices::openUrl(url); } } void ExternalResourcesPage::viewConfigs() { DesktopServices::openPath(m_instance->instanceConfigFolder(), true); } void ExternalResourcesPage::viewFolder() { DesktopServices::openPath(m_model->dir().absolutePath(), true); } void ExternalResourcesPage::updateActions() { const bool hasSelection = ui->treeView->selectionModel()->hasSelection(); const QModelIndexList selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); const QList<Resource*> selectedResources = m_model->selectedResources(selection); ui->actionUpdateItem->setEnabled(!m_model->empty()); ui->actionResetItemMetadata->setEnabled(hasSelection); ui->actionChangeVersion->setEnabled(selectedResources.size() == 1 && selectedResources[0]->metadata() != nullptr); ui->actionRemoveItem->setEnabled(hasSelection); ui->actionEnableItem->setEnabled(hasSelection); ui->actionDisableItem->setEnabled(hasSelection); ui->actionViewHomepage->setEnabled(hasSelection && std::any_of(selectedResources.begin(), selectedResources.end(), [](Resource* resource) { return !resource->homepage().isEmpty(); })); ui->actionExportMetadata->setEnabled(!m_model->empty()); } void ExternalResourcesPage::updateFrame(const QModelIndex& current, [[maybe_unused]] const QModelIndex& previous) { auto sourceCurrent = m_filterModel->mapToSource(current); int row = sourceCurrent.row(); Resource const& resource = m_model->at(row); ui->frame->updateWithResource(resource); } QString ExternalResourcesPage::extraHeaderInfoString() { if (ui && ui->treeView && ui->treeView->selectionModel()) { auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); if (auto count = std::count_if(selection.cbegin(), selection.cend(), [](auto v) { return v.column() == 0; }); count != 0) return tr(" (%1 installed, %2 selected)").arg(m_model->size()).arg(count); } return tr(" (%1 installed)").arg(m_model->size()); }
14,060
C++
.cpp
302
40.039735
138
0.686962
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,001
ServersPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/ServersPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ServersPage.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui_ServersPage.h" #include <FileSystem.h> #include <io/stream_reader.h> #include <minecraft/MinecraftInstance.h> #include <tag_compound.h> #include <tag_list.h> #include <tag_primitive.h> #include <tag_string.h> #include <sstream> #include <QFileSystemWatcher> #include <QMenu> #include <QTimer> static const int COLUMN_COUNT = 2; // 3 , TBD: latency and other nice things. struct Server { // Types enum class AcceptsTextures : int { ASK = 0, ALWAYS = 1, NEVER = 2 }; // Methods Server() { m_name = QObject::tr("Minecraft Server"); } Server(const QString& name, const QString& address) { m_name = name; m_address = address; } Server(nbt::tag_compound& server) { std::string addressStr(server["ip"]); m_address = QString::fromUtf8(addressStr.c_str()); std::string nameStr(server["name"]); m_name = QString::fromUtf8(nameStr.c_str()); if (server["icon"]) { std::string base64str(server["icon"]); m_icon = QByteArray::fromBase64(base64str.c_str()); } if (server.has_key("acceptTextures", nbt::tag_type::Byte)) { bool value = server["acceptTextures"].as<nbt::tag_byte>().get(); if (value) { m_acceptsTextures = AcceptsTextures::ALWAYS; } else { m_acceptsTextures = AcceptsTextures::NEVER; } } } void serialize(nbt::tag_compound& server) { server.insert("name", m_name.trimmed().toUtf8().toStdString()); server.insert("ip", m_address.trimmed().toUtf8().toStdString()); if (m_icon.size()) { server.insert("icon", m_icon.toBase64().toStdString()); } if (m_acceptsTextures != AcceptsTextures::ASK) { server.insert("acceptTextures", nbt::tag_byte(m_acceptsTextures == AcceptsTextures::ALWAYS)); } } // Data - persistent and user changeable QString m_name; QString m_address; AcceptsTextures m_acceptsTextures = AcceptsTextures::ASK; // Data - persistent and automatically updated QByteArray m_icon; // Data - temporary bool m_checked = false; bool m_up = false; QString m_motd; // https://mctools.org/motd-creator int m_ping = 0; int m_currentPlayers = 0; int m_maxPlayers = 0; }; static std::unique_ptr<nbt::tag_compound> parseServersDat(const QString& filename) { try { QByteArray input = FS::read(filename); std::istringstream foo(std::string(input.constData(), input.size())); auto pair = nbt::io::read_compound(foo); if (pair.first != "") return nullptr; if (pair.second == nullptr) return nullptr; return std::move(pair.second); } catch (...) { return nullptr; } } static bool serializeServerDat(const QString& filename, nbt::tag_compound* levelInfo) { try { if (!FS::ensureFilePathExists(filename)) { return false; } std::ostringstream s; nbt::io::write_tag("", *levelInfo, s); QByteArray val(s.str().data(), (int)s.str().size()); FS::write(filename, val); return true; } catch (...) { return false; } } class ServersModel : public QAbstractListModel { Q_OBJECT public: enum Roles { ServerPtrRole = Qt::UserRole, }; explicit ServersModel(const QString& path, QObject* parent = 0) : QAbstractListModel(parent) { m_path = path; m_watcher = new QFileSystemWatcher(this); connect(m_watcher, &QFileSystemWatcher::fileChanged, this, &ServersModel::fileChanged); connect(m_watcher, &QFileSystemWatcher::directoryChanged, this, &ServersModel::dirChanged); m_saveTimer.setSingleShot(true); m_saveTimer.setInterval(5000); connect(&m_saveTimer, &QTimer::timeout, this, &ServersModel::save_internal); } virtual ~ServersModel() = default; void observe() { if (m_observed) { return; } m_observed = true; if (!m_loaded) { load(); } updateFSObserver(); } void unobserve() { if (!m_observed) { return; } m_observed = false; updateFSObserver(); } void lock() { if (m_locked) { return; } saveNow(); m_locked = true; updateFSObserver(); } void unlock() { if (!m_locked) { return; } m_locked = false; updateFSObserver(); } int addEmptyRow(int position) { if (m_locked) { return -1; } if (position < 0 || position >= rowCount()) { position = rowCount(); } beginInsertRows(QModelIndex(), position, position); m_servers.insert(position, Server()); endInsertRows(); scheduleSave(); return position; } bool removeRow(int row) { if (m_locked) { return false; } if (row < 0 || row >= rowCount()) { return false; } beginRemoveRows(QModelIndex(), row, row); m_servers.removeAt(row); endRemoveRows(); // does absolutely nothing, the selected server stays as the next line... scheduleSave(); return true; } bool moveUp(int row) { if (m_locked) { return false; } if (row <= 0) { return false; } beginMoveRows(QModelIndex(), row, row, QModelIndex(), row - 1); #if QT_VERSION >= QT_VERSION_CHECK(5, 13, 0) m_servers.swapItemsAt(row - 1, row); #else m_servers.swap(row - 1, row); #endif endMoveRows(); scheduleSave(); return true; } bool moveDown(int row) { if (m_locked) { return false; } int count = rowCount(); if (row + 1 >= count) { return false; } beginMoveRows(QModelIndex(), row, row, QModelIndex(), row + 2); #if QT_VERSION >= QT_VERSION_CHECK(5, 13, 0) m_servers.swapItemsAt(row + 1, row); #else m_servers.swap(row + 1, row); #endif endMoveRows(); scheduleSave(); return true; } QVariant headerData(int section, Qt::Orientation orientation, int role) const override { if (section < 0 || section >= COLUMN_COUNT) return QVariant(); if (role == Qt::DisplayRole) { switch (section) { case 0: return tr("Name"); case 1: return tr("Address"); case 2: return tr("Latency"); } } return QAbstractListModel::headerData(section, orientation, role); } virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override { if (!index.isValid()) return QVariant(); int row = index.row(); int column = index.column(); if (column < 0 || column >= COLUMN_COUNT) return QVariant(); if (row < 0 || row >= m_servers.size()) return QVariant(); switch (column) { case 0: switch (role) { case Qt::DecorationRole: { auto& bytes = m_servers[row].m_icon; if (bytes.size()) { QPixmap px; if (px.loadFromData(bytes)) return QIcon(px); } return APPLICATION->getThemedIcon("unknown_server"); } case Qt::DisplayRole: return m_servers[row].m_name; case ServerPtrRole: return QVariant::fromValue<void*>((void*)&m_servers[row]); default: return QVariant(); } case 1: switch (role) { case Qt::DisplayRole: return m_servers[row].m_address; default: return QVariant(); } case 2: switch (role) { case Qt::DisplayRole: return m_servers[row].m_ping; default: return QVariant(); } default: return QVariant(); } } virtual int rowCount(const QModelIndex& parent = QModelIndex()) const override { return parent.isValid() ? 0 : m_servers.size(); } int columnCount(const QModelIndex& parent) const override { return parent.isValid() ? 0 : COLUMN_COUNT; } Server* at(int index) { if (index < 0 || index >= rowCount()) { return nullptr; } return &m_servers[index]; } void setName(int row, const QString& name) { if (m_locked) { return; } auto server = at(row); if (!server || server->m_name == name) { return; } server->m_name = name; emit dataChanged(index(row, 0), index(row, COLUMN_COUNT - 1)); scheduleSave(); } void setAddress(int row, const QString& address) { if (m_locked) { return; } auto server = at(row); if (!server || server->m_address == address) { return; } server->m_address = address; emit dataChanged(index(row, 0), index(row, COLUMN_COUNT - 1)); scheduleSave(); } void setAcceptsTextures(int row, Server::AcceptsTextures textures) { if (m_locked) { return; } auto server = at(row); if (!server || server->m_acceptsTextures == textures) { return; } server->m_acceptsTextures = textures; emit dataChanged(index(row, 0), index(row, COLUMN_COUNT - 1)); scheduleSave(); } void load() { cancelSave(); beginResetModel(); QList<Server> servers; auto serversDat = parseServersDat(serversPath()); if (serversDat) { auto& serversList = serversDat->at("servers").as<nbt::tag_list>(); for (auto iter = serversList.begin(); iter != serversList.end(); iter++) { auto& serverTag = (*iter).as<nbt::tag_compound>(); Server s(serverTag); servers.append(s); } } m_servers.swap(servers); m_loaded = true; endResetModel(); } void saveNow() { if (saveIsScheduled()) { save_internal(); } } public slots: void dirChanged(const QString& path) { qDebug() << "Changed:" << path; load(); } void fileChanged(const QString& path) { qDebug() << "Changed:" << path; } private slots: void save_internal() { cancelSave(); QString path = serversPath(); qDebug() << "Server list about to be saved to" << path; nbt::tag_compound out; nbt::tag_list list; for (auto& server : m_servers) { nbt::tag_compound serverNbt; server.serialize(serverNbt); list.push_back(std::move(serverNbt)); } out.insert("servers", nbt::value(std::move(list))); if (!serializeServerDat(path, &out)) { qDebug() << "Failed to save server list:" << path << "Will try again."; scheduleSave(); } } private: void scheduleSave() { if (!m_loaded) { qDebug() << "Server list should never save if it didn't successfully load, path:" << m_path; return; } if (!m_dirty) { m_dirty = true; qDebug() << "Server list save is scheduled for" << m_path; } m_saveTimer.start(); } void cancelSave() { m_dirty = false; m_saveTimer.stop(); } bool saveIsScheduled() const { return m_dirty; } void updateFSObserver() { bool observingFS = m_watcher->directories().contains(m_path); if (m_observed && m_locked) { if (!observingFS) { qWarning() << "Will watch" << m_path; if (!m_watcher->addPath(m_path)) { qWarning() << "Failed to start watching" << m_path; } } } else { if (observingFS) { qWarning() << "Will stop watching" << m_path; if (!m_watcher->removePath(m_path)) { qWarning() << "Failed to stop watching" << m_path; } } } } QString serversPath() { QFileInfo foo(FS::PathCombine(m_path, "servers.dat")); return foo.filePath(); } private: bool m_loaded = false; bool m_locked = false; bool m_observed = false; bool m_dirty = false; QString m_path; QList<Server> m_servers; QFileSystemWatcher* m_watcher = nullptr; QTimer m_saveTimer; }; ServersPage::ServersPage(InstancePtr inst, QWidget* parent) : QMainWindow(parent), ui(new Ui::ServersPage) { ui->setupUi(this); m_inst = inst; m_model = new ServersModel(inst->gameRoot(), this); ui->serversView->setIconSize(QSize(64, 64)); ui->serversView->setModel(m_model); ui->serversView->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->serversView, &QTreeView::customContextMenuRequested, this, &ServersPage::ShowContextMenu); auto head = ui->serversView->header(); if (head->count()) { head->setSectionResizeMode(0, QHeaderView::Stretch); for (int i = 1; i < head->count(); i++) { head->setSectionResizeMode(i, QHeaderView::ResizeToContents); } } auto selectionModel = ui->serversView->selectionModel(); connect(selectionModel, &QItemSelectionModel::currentChanged, this, &ServersPage::currentChanged); connect(m_inst.get(), &MinecraftInstance::runningStatusChanged, this, &ServersPage::runningStateChanged); connect(ui->nameLine, &QLineEdit::textEdited, this, &ServersPage::nameEdited); connect(ui->addressLine, &QLineEdit::textEdited, this, &ServersPage::addressEdited); connect(ui->resourceComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(resourceIndexChanged(int))); connect(m_model, &QAbstractItemModel::rowsRemoved, this, &ServersPage::rowsRemoved); m_locked = m_inst->isRunning(); if (m_locked) { m_model->lock(); } updateState(); } ServersPage::~ServersPage() { m_model->saveNow(); delete ui; } void ServersPage::retranslate() { ui->retranslateUi(this); } void ServersPage::ShowContextMenu(const QPoint& pos) { auto menu = ui->toolBar->createContextMenu(this, tr("Context menu")); menu->exec(ui->serversView->mapToGlobal(pos)); delete menu; } QMenu* ServersPage::createPopupMenu() { QMenu* filteredMenu = QMainWindow::createPopupMenu(); filteredMenu->removeAction(ui->toolBar->toggleViewAction()); return filteredMenu; } void ServersPage::runningStateChanged(bool running) { if (m_locked == running) { return; } m_locked = running; if (m_locked) { m_model->lock(); } else { m_model->unlock(); } updateState(); } void ServersPage::currentChanged(const QModelIndex& current, [[maybe_unused]] const QModelIndex& previous) { int nextServer = -1; if (!current.isValid()) { nextServer = -1; } else { nextServer = current.row(); } currentServer = nextServer; updateState(); } // WARNING: this is here because currentChanged is not accurate when removing rows. the current item needs to be fixed up after removal. void ServersPage::rowsRemoved([[maybe_unused]] const QModelIndex& parent, int first, int last) { if (currentServer < first) { // current was before the removal return; } else if (currentServer >= first && currentServer <= last) { // current got removed... return; } else { // current was past the removal int count = last - first + 1; currentServer -= count; } } void ServersPage::nameEdited(const QString& name) { m_model->setName(currentServer, name); } void ServersPage::addressEdited(const QString& address) { m_model->setAddress(currentServer, address); } void ServersPage::resourceIndexChanged(int index) { auto acceptsTextures = Server::AcceptsTextures(index); m_model->setAcceptsTextures(currentServer, acceptsTextures); } void ServersPage::updateState() { auto server = m_model->at(currentServer); bool serverEditEnabled = server && !m_locked; ui->addressLine->setEnabled(serverEditEnabled); ui->nameLine->setEnabled(serverEditEnabled); ui->resourceComboBox->setEnabled(serverEditEnabled); ui->actionMove_Down->setEnabled(serverEditEnabled); ui->actionMove_Up->setEnabled(serverEditEnabled); ui->actionRemove->setEnabled(serverEditEnabled); ui->actionJoin->setEnabled(serverEditEnabled); if (server) { ui->addressLine->setText(server->m_address); ui->nameLine->setText(server->m_name); ui->resourceComboBox->setCurrentIndex(int(server->m_acceptsTextures)); } else { ui->addressLine->setText(QString()); ui->nameLine->setText(QString()); ui->resourceComboBox->setCurrentIndex(0); } ui->actionAdd->setDisabled(m_locked); } void ServersPage::openedImpl() { m_model->observe(); auto const setting_name = QString("WideBarVisibility_%1").arg(id()); if (!APPLICATION->settings()->contains(setting_name)) m_wide_bar_setting = APPLICATION->settings()->registerSetting(setting_name); else m_wide_bar_setting = APPLICATION->settings()->getSetting(setting_name); ui->toolBar->setVisibilityState(m_wide_bar_setting->get().toByteArray()); } void ServersPage::closedImpl() { m_model->unobserve(); m_wide_bar_setting->set(ui->toolBar->getVisibilityState()); } void ServersPage::on_actionAdd_triggered() { int position = m_model->addEmptyRow(currentServer + 1); if (position < 0) { return; } // select the new row ui->serversView->selectionModel()->setCurrentIndex( m_model->index(position), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Clear | QItemSelectionModel::Rows); currentServer = position; } void ServersPage::on_actionRemove_triggered() { auto response = CustomMessageBox::selectable(this, tr("Confirm Removal"), tr("You are about to remove \"%1\".\n" "This is permanent and the server will be gone from your list forever (A LONG TIME).\n\n" "Are you sure?") .arg(m_model->at(currentServer)->m_name), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; m_model->removeRow(currentServer); } void ServersPage::on_actionMove_Up_triggered() { if (m_model->moveUp(currentServer)) { currentServer--; } } void ServersPage::on_actionMove_Down_triggered() { if (m_model->moveDown(currentServer)) { currentServer++; } } void ServersPage::on_actionJoin_triggered() { const auto& address = m_model->at(currentServer)->m_address; APPLICATION->launch(m_inst, true, false, std::make_shared<MinecraftTarget>(MinecraftTarget::parse(address, false))); } #include "ServersPage.moc"
21,611
C++
.cpp
649
25.457627
136
0.592028
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,002
TexturePackPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/TexturePackPage.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only AND Apache-2.0 /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "TexturePackPage.h" #include "ResourceDownloadTask.h" #include "minecraft/mod/TexturePack.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ProgressDialog.h" #include "ui/dialogs/ResourceDownloadDialog.h" #include "ui/dialogs/ResourceUpdateDialog.h" TexturePackPage::TexturePackPage(MinecraftInstance* instance, std::shared_ptr<TexturePackFolderModel> model, QWidget* parent) : ExternalResourcesPage(instance, model, parent), m_model(model) { ui->actionDownloadItem->setText(tr("Download Packs")); ui->actionDownloadItem->setToolTip(tr("Download texture packs from online mod platforms")); ui->actionDownloadItem->setEnabled(true); ui->actionsToolbar->insertActionBefore(ui->actionAddItem, ui->actionDownloadItem); connect(ui->actionDownloadItem, &QAction::triggered, this, &TexturePackPage::downloadTexturePacks); ui->actionUpdateItem->setToolTip(tr("Try to check or update all selected texture packs (all texture packs if none are selected)")); connect(ui->actionUpdateItem, &QAction::triggered, this, &TexturePackPage::updateTexturePacks); ui->actionsToolbar->insertActionBefore(ui->actionAddItem, ui->actionUpdateItem); auto updateMenu = new QMenu(this); auto update = updateMenu->addAction(ui->actionUpdateItem->text()); connect(update, &QAction::triggered, this, &TexturePackPage::updateTexturePacks); updateMenu->addAction(ui->actionResetItemMetadata); connect(ui->actionResetItemMetadata, &QAction::triggered, this, &TexturePackPage::deleteTexturePackMetadata); ui->actionUpdateItem->setMenu(updateMenu); ui->actionChangeVersion->setToolTip(tr("Change a texture pack's version.")); connect(ui->actionChangeVersion, &QAction::triggered, this, &TexturePackPage::changeTexturePackVersion); ui->actionsToolbar->insertActionAfter(ui->actionUpdateItem, ui->actionChangeVersion); ui->actionViewHomepage->setToolTip(tr("View the homepages of all selected texture packs.")); } void TexturePackPage::updateFrame(const QModelIndex& current, [[maybe_unused]] const QModelIndex& previous) { auto sourceCurrent = m_filterModel->mapToSource(current); int row = sourceCurrent.row(); auto& rp = static_cast<TexturePack&>(m_model->at(row)); ui->frame->updateWithTexturePack(rp); } void TexturePackPage::downloadTexturePacks() { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance ResourceDownload::TexturePackDownloadDialog mdownload(this, m_model, m_instance); if (mdownload.exec()) { auto tasks = new ConcurrentTask("Download Texture Packs", APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); tasks->deleteLater(); }); for (auto& task : mdownload.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } } void TexturePackPage::updateTexturePacks() { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance auto profile = static_cast<MinecraftInstance*>(m_instance)->getPackProfile(); if (APPLICATION->settings()->get("ModMetadataDisabled").toBool()) { QMessageBox::critical(this, tr("Error"), tr("Texture pack updates are unavailable when metadata is disabled!")); return; } if (m_instance != nullptr && m_instance->isRunning()) { auto response = CustomMessageBox::selectable( this, tr("Confirm Update"), tr("Updating texture packs while the game is running may cause pack duplication and game crashes.\n" "The old files may not be deleted as they are in use.\n" "Are you sure you want to do this?"), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); auto mods_list = m_model->selectedResources(selection); bool use_all = mods_list.empty(); if (use_all) mods_list = m_model->allResources(); ResourceUpdateDialog update_dialog(this, m_instance, m_model, mods_list, false, false); update_dialog.checkCandidates(); if (update_dialog.aborted()) { CustomMessageBox::selectable(this, tr("Aborted"), tr("The texture pack updater was aborted!"), QMessageBox::Warning)->show(); return; } if (update_dialog.noUpdates()) { QString message{ tr("'%1' is up-to-date! :)").arg(mods_list.front()->name()) }; if (mods_list.size() > 1) { if (use_all) { message = tr("All texture packs are up-to-date! :)"); } else { message = tr("All selected texture packs are up-to-date! :)"); } } CustomMessageBox::selectable(this, tr("Update checker"), message)->exec(); return; } if (update_dialog.exec()) { auto tasks = new ConcurrentTask("Download Texture Packs", APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) { CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); } tasks->deleteLater(); }); for (auto task : update_dialog.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } } void TexturePackPage::deleteTexturePackMetadata() { auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); auto selectionCount = m_model->selectedTexturePacks(selection).length(); if (selectionCount == 0) return; if (selectionCount > 1) { auto response = CustomMessageBox::selectable(this, tr("Confirm Removal"), tr("You are about to remove the metadata for %1 texture packs.\n" "Are you sure?") .arg(selectionCount), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } m_model->deleteMetadata(selection); } void TexturePackPage::changeTexturePackVersion() { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance if (APPLICATION->settings()->get("ModMetadataDisabled").toBool()) { QMessageBox::critical(this, tr("Error"), tr("Texture pack updates are unavailable when metadata is disabled!")); return; } const QModelIndexList rows = ui->treeView->selectionModel()->selectedRows(); if (rows.count() != 1) return; Resource& resource = m_model->at(m_filterModel->mapToSource(rows[0]).row()); if (resource.metadata() == nullptr) return; ResourceDownload::TexturePackDownloadDialog mdownload(this, m_model, m_instance); mdownload.setResourceMetadata(resource.metadata()); if (mdownload.exec()) { auto tasks = new ConcurrentTask("Download Texture Packs", APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); tasks->deleteLater(); }); for (auto& task : mdownload.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } }
11,667
C++
.cpp
230
42.452174
135
0.654261
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,003
VersionPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/VersionPage.cpp
// SPDX-FileCopyrightText: 2022-2023 Sefa Eyeoglu <contact@scrumplex.net> // // SPDX-License-Identifier: GPL-3.0-only AND Apache-2.0 /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022-2023 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Application.h" #include <QAbstractItemModel> #include <QEvent> #include <QKeyEvent> #include <QLabel> #include <QListView> #include <QMenu> #include <QMessageBox> #include <QString> #include <QUrl> #include <algorithm> #include "QObjectPtr.h" #include "VersionPage.h" #include "meta/JsonFormat.h" #include "tasks/SequentialTask.h" #include "ui/dialogs/InstallLoaderDialog.h" #include "ui_VersionPage.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/NewComponentDialog.h" #include "ui/dialogs/ProgressDialog.h" #include "ui/dialogs/VersionSelectDialog.h" #include "ui/GuiUtil.h" #include "DesktopServices.h" #include "Exception.h" #include "icons/IconList.h" #include "minecraft/PackProfile.h" #include "minecraft/auth/AccountList.h" #include "meta/Index.h" #include "meta/VersionList.h" class IconProxy : public QIdentityProxyModel { Q_OBJECT public: IconProxy(QWidget* parentWidget) : QIdentityProxyModel(parentWidget) { connect(parentWidget, &QObject::destroyed, this, &IconProxy::widgetGone); m_parentWidget = parentWidget; } virtual QVariant data(const QModelIndex& proxyIndex, int role = Qt::DisplayRole) const override { QVariant var = QIdentityProxyModel::data(proxyIndex, role); int column = proxyIndex.column(); if (column == 0 && role == Qt::DecorationRole && m_parentWidget) { if (!var.isNull()) { auto string = var.toString(); if (string == "warning") { return APPLICATION->getThemedIcon("status-yellow"); } else if (string == "error") { return APPLICATION->getThemedIcon("status-bad"); } } return APPLICATION->getThemedIcon("status-good"); } return var; } private slots: void widgetGone() { m_parentWidget = nullptr; } private: QWidget* m_parentWidget = nullptr; }; QIcon VersionPage::icon() const { return APPLICATION->icons()->getIcon(m_inst->iconKey()); } bool VersionPage::shouldDisplay() const { return true; } void VersionPage::retranslate() { ui->retranslateUi(this); } void VersionPage::openedImpl() { auto const setting_name = QString("WideBarVisibility_%1").arg(id()); if (!APPLICATION->settings()->contains(setting_name)) m_wide_bar_setting = APPLICATION->settings()->registerSetting(setting_name); else m_wide_bar_setting = APPLICATION->settings()->getSetting(setting_name); ui->toolBar->setVisibilityState(m_wide_bar_setting->get().toByteArray()); } void VersionPage::closedImpl() { m_wide_bar_setting->set(ui->toolBar->getVisibilityState()); } QMenu* VersionPage::createPopupMenu() { QMenu* filteredMenu = QMainWindow::createPopupMenu(); filteredMenu->removeAction(ui->toolBar->toggleViewAction()); return filteredMenu; } VersionPage::VersionPage(MinecraftInstance* inst, QWidget* parent) : QMainWindow(parent), ui(new Ui::VersionPage), m_inst(inst) { ui->setupUi(this); ui->toolBar->insertSpacer(ui->actionReload); m_profile = m_inst->getPackProfile(); reloadPackProfile(); auto proxy = new IconProxy(ui->packageView); proxy->setSourceModel(m_profile.get()); m_filterModel = new QSortFilterProxyModel(this); m_filterModel->setDynamicSortFilter(true); m_filterModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_filterModel->setSortCaseSensitivity(Qt::CaseInsensitive); m_filterModel->setSourceModel(proxy); m_filterModel->setFilterKeyColumn(-1); ui->packageView->setModel(m_filterModel); ui->packageView->installEventFilter(this); ui->packageView->setSelectionMode(QAbstractItemView::SingleSelection); ui->packageView->setContextMenuPolicy(Qt::CustomContextMenu); auto smodel = ui->packageView->selectionModel(); connect(smodel, &QItemSelectionModel::currentChanged, this, &VersionPage::versionCurrent); connect(smodel, &QItemSelectionModel::currentChanged, this, &VersionPage::packageCurrent); connect(m_profile.get(), &PackProfile::minecraftChanged, this, &VersionPage::updateVersionControls); updateVersionControls(); preselect(0); connect(ui->packageView, &ModListView::customContextMenuRequested, this, &VersionPage::showContextMenu); connect(ui->packageView, &QAbstractItemView::activated, this, [this](const QModelIndex& index) { auto component = m_profile->getComponent(index.row()); component->setEnabled(!component->isEnabled()); }); connect(ui->filterEdit, &QLineEdit::textChanged, this, &VersionPage::onFilterTextChanged); } VersionPage::~VersionPage() { delete ui; } void VersionPage::showContextMenu(const QPoint& pos) { auto menu = ui->toolBar->createContextMenu(this, tr("Context menu")); menu->exec(ui->packageView->mapToGlobal(pos)); delete menu; } void VersionPage::packageCurrent(const QModelIndex& current, [[maybe_unused]] const QModelIndex& previous) { if (!current.isValid()) { ui->frame->clear(); return; } int row = current.row(); auto patch = m_profile->getComponent(row); auto severity = patch->getProblemSeverity(); switch (severity) { case ProblemSeverity::Warning: ui->frame->setName(tr("%1 possibly has issues.").arg(patch->getName())); break; case ProblemSeverity::Error: ui->frame->setName(tr("%1 has issues!").arg(patch->getName())); break; default: case ProblemSeverity::None: ui->frame->clear(); return; } auto& problems = patch->getProblems(); QString problemOut; for (auto& problem : problems) { if (problem.m_severity == ProblemSeverity::Error) { problemOut += tr("Error: "); } else if (problem.m_severity == ProblemSeverity::Warning) { problemOut += tr("Warning: "); } problemOut += problem.m_description; problemOut += "\n"; } ui->frame->setDescription(problemOut); } void VersionPage::updateVersionControls() { updateButtons(); } void VersionPage::updateButtons(int row) { if (row == -1) row = currentRow(); auto patch = m_profile->getComponent(row); ui->actionRemove->setEnabled(patch && patch->isRemovable()); ui->actionMove_down->setEnabled(patch && patch->isMoveable()); ui->actionMove_up->setEnabled(patch && patch->isMoveable()); ui->actionChange_version->setEnabled(patch && patch->isVersionChangeable(false)); ui->actionEdit->setEnabled(patch && patch->isCustom()); ui->actionCustomize->setEnabled(patch && patch->isCustomizable()); ui->actionRevert->setEnabled(patch && patch->isRevertible()); } bool VersionPage::reloadPackProfile() { try { m_profile->reload(Net::Mode::Online); return true; } catch (const Exception& e) { QMessageBox::critical(this, tr("Error"), e.cause()); return false; } catch (...) { QMessageBox::critical(this, tr("Error"), tr("Couldn't load the instance profile.")); return false; } } void VersionPage::on_actionReload_triggered() { reloadPackProfile(); m_container->refreshContainer(); } void VersionPage::on_actionRemove_triggered() { if (!ui->packageView->currentIndex().isValid()) { return; } int index = ui->packageView->currentIndex().row(); auto component = m_profile->getComponent(index); if (component->isCustom()) { auto response = CustomMessageBox::selectable(this, tr("Confirm Removal"), tr("You are about to remove \"%1\".\n" "This is permanent and will completely remove the custom component.\n\n" "Are you sure?") .arg(component->getName()), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } // FIXME: use actual model, not reloading. if (!m_profile->remove(index)) { QMessageBox::critical(this, tr("Error"), tr("Couldn't remove file")); } updateButtons(); reloadPackProfile(); m_container->refreshContainer(); } void VersionPage::on_actionAdd_to_Minecraft_jar_triggered() { auto list = GuiUtil::BrowseForFiles("jarmod", tr("Select jar mods"), tr("Minecraft.jar mods") + " (*.zip *.jar)", APPLICATION->settings()->get("CentralModsDir").toString(), this->parentWidget()); if (!list.empty()) { m_profile->installJarMods(list); } updateButtons(); } void VersionPage::on_actionReplace_Minecraft_jar_triggered() { auto jarPath = GuiUtil::BrowseForFile("jar", tr("Select jar"), tr("Minecraft.jar replacement") + " (*.jar)", APPLICATION->settings()->get("CentralModsDir").toString(), this->parentWidget()); if (!jarPath.isEmpty()) { m_profile->installCustomJar(jarPath); } updateButtons(); } void VersionPage::on_actionImport_Components_triggered() { QStringList list = GuiUtil::BrowseForFiles("component", tr("Select components"), tr("Components") + " (*.json)", APPLICATION->settings()->get("CentralModsDir").toString(), this->parentWidget()); if (!list.isEmpty()) { if (!m_profile->installComponents(list)) { QMessageBox::warning(this, tr("Failed to import components"), tr("Some components could not be imported. Check logs for details")); } } updateButtons(); } void VersionPage::on_actionAdd_Agents_triggered() { QStringList list = GuiUtil::BrowseForFiles("agent", tr("Select agents"), tr("Java agents") + " (*.jar)", APPLICATION->settings()->get("CentralModsDir").toString(), this->parentWidget()); if (!list.isEmpty()) m_profile->installAgents(list); updateButtons(); } void VersionPage::on_actionMove_up_triggered() { try { m_profile->move(currentRow(), PackProfile::MoveUp); } catch (const Exception& e) { QMessageBox::critical(this, tr("Error"), e.cause()); } updateButtons(); } void VersionPage::on_actionMove_down_triggered() { try { m_profile->move(currentRow(), PackProfile::MoveDown); } catch (const Exception& e) { QMessageBox::critical(this, tr("Error"), e.cause()); } updateButtons(); } void VersionPage::on_actionChange_version_triggered() { auto versionRow = currentRow(); if (versionRow == -1) { return; } auto patch = m_profile->getComponent(versionRow); auto name = patch->getName(); auto list = patch->getVersionList(); list->clearExternalRecommends(); if (!list) { return; } auto uid = list->uid(); // recommend the correct lwjgl version for the current minecraft version if (uid == "org.lwjgl" || uid == "org.lwjgl3") { auto minecraft = m_profile->getComponent("net.minecraft"); auto lwjglReq = std::find_if(minecraft->m_cachedRequires.cbegin(), minecraft->m_cachedRequires.cend(), [uid](const Meta::Require& req) -> bool { return req.uid == uid; }); if (lwjglReq != minecraft->m_cachedRequires.cend()) { auto lwjglVersion = !lwjglReq->equalsVersion.isEmpty() ? lwjglReq->equalsVersion : lwjglReq->suggests; if (!lwjglVersion.isEmpty()) { list->addExternalRecommends({ lwjglVersion }); } } } VersionSelectDialog vselect(list.get(), tr("Change %1 version").arg(name), this); if (uid == "net.fabricmc.intermediary" || uid == "org.quiltmc.hashed") { vselect.setEmptyString(tr("No intermediary mappings versions are currently available.")); vselect.setEmptyErrorString(tr("Couldn't load or download the intermediary mappings version lists!")); } vselect.setExactIfPresentFilter(BaseVersionList::ParentVersionRole, m_profile->getComponentVersion("net.minecraft")); auto currentVersion = patch->getVersion(); if (!currentVersion.isEmpty()) { vselect.setCurrentVersion(currentVersion); } if (!vselect.exec() || !vselect.selectedVersion()) return; qDebug() << "Change" << uid << "to" << vselect.selectedVersion()->descriptor(); bool important = false; if (uid == "net.minecraft") { important = true; if (APPLICATION->settings()->get("AutomaticJavaSwitch").toBool() && m_inst->settings()->get("AutomaticJava").toBool() && m_inst->settings()->get("OverrideJavaLocation").toBool()) { m_inst->settings()->set("OverrideJavaLocation", false); m_inst->settings()->set("JavaPath", ""); } } m_profile->setComponentVersion(uid, vselect.selectedVersion()->descriptor(), important); m_profile->resolve(Net::Mode::Online); m_container->refreshContainer(); } void VersionPage::on_actionDownload_All_triggered() { if (!APPLICATION->accounts()->anyAccountIsValid()) { CustomMessageBox::selectable(this, tr("Error"), tr("Cannot download Minecraft or update instances unless you have at least " "one account added.\nPlease add a Microsoft account."), QMessageBox::Warning) ->show(); return; } auto updateTasks = m_inst->createUpdateTask(); if (updateTasks.isEmpty()) { return; } auto task = makeShared<SequentialTask>(); for (auto t : updateTasks) { task->addTask(t); } ProgressDialog tDialog(this); connect(task.get(), &Task::failed, this, &VersionPage::onGameUpdateError); // FIXME: unused return value tDialog.execWithTask(task.get()); updateButtons(); m_container->refreshContainer(); } void VersionPage::on_actionInstall_Loader_triggered() { InstallLoaderDialog dialog(m_inst->getPackProfile(), QString(), this); dialog.exec(); m_container->refreshContainer(); } void VersionPage::on_actionAdd_Empty_triggered() { NewComponentDialog compdialog(QString(), QString(), this); QStringList blacklist; for (int i = 0; i < m_profile->rowCount(); i++) { auto comp = m_profile->getComponent(i); blacklist.push_back(comp->getID()); } compdialog.setBlacklist(blacklist); if (compdialog.exec()) { qDebug() << "name:" << compdialog.name(); qDebug() << "uid:" << compdialog.uid(); m_profile->installEmpty(compdialog.uid(), compdialog.name()); } } void VersionPage::on_actionLibrariesFolder_triggered() { DesktopServices::openPath(m_inst->getLocalLibraryPath(), true); } void VersionPage::on_actionMinecraftFolder_triggered() { DesktopServices::openPath(m_inst->gameRoot(), true); } void VersionPage::versionCurrent(const QModelIndex& current, [[maybe_unused]] const QModelIndex& previous) { currentIdx = current.row(); updateButtons(currentIdx); } void VersionPage::preselect(int row) { if (row < 0) { row = 0; } if (row >= m_profile->rowCount(QModelIndex())) { row = m_profile->rowCount(QModelIndex()) - 1; } if (row < 0) { return; } auto model_index = m_profile->index(row); ui->packageView->selectionModel()->select(model_index, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); updateButtons(row); } void VersionPage::onGameUpdateError(QString error) { CustomMessageBox::selectable(this, tr("Error updating instance"), error, QMessageBox::Warning)->show(); } ComponentPtr VersionPage::current() { auto row = currentRow(); if (row < 0) { return nullptr; } return m_profile->getComponent(row); } int VersionPage::currentRow() { if (ui->packageView->selectionModel()->selectedRows().isEmpty()) { return -1; } return ui->packageView->selectionModel()->selectedRows().first().row(); } void VersionPage::on_actionCustomize_triggered() { auto version = currentRow(); if (version == -1) { return; } auto patch = m_profile->getComponent(version); if (!patch->getVersionFile()) { // TODO: wait for the update task to finish here... return; } if (!m_profile->customize(version)) { // TODO: some error box here } updateButtons(); preselect(currentIdx); } void VersionPage::on_actionEdit_triggered() { auto version = current(); if (!version) { return; } auto filename = version->getFilename(); if (!QFileInfo::exists(filename)) { qWarning() << "file" << filename << "can't be opened for editing, doesn't exist!"; return; } APPLICATION->openJsonEditor(filename); } void VersionPage::on_actionRevert_triggered() { auto version = currentRow(); if (version == -1) { return; } auto component = m_profile->getComponent(version); auto response = CustomMessageBox::selectable(this, tr("Confirm Reversion"), tr("You are about to revert \"%1\".\n" "This is permanent and will completely revert your customizations.\n\n" "Are you sure?") .arg(component->getName()), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; if (!m_profile->revertToBase(version)) { // TODO: some error box here } updateButtons(); preselect(currentIdx); m_container->refreshContainer(); } void VersionPage::onFilterTextChanged(const QString& newContents) { m_filterModel->setFilterFixedString(newContents); } #include "VersionPage.moc"
19,981
C++
.cpp
523
31.650096
128
0.649355
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,004
WorldListPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/WorldListPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "WorldListPage.h" #include "minecraft/WorldList.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui_WorldListPage.h" #include <QClipboard> #include <QEvent> #include <QInputDialog> #include <QKeyEvent> #include <QMenu> #include <QMessageBox> #include <QSortFilterProxyModel> #include <QTreeView> #include <Qt> #include "FileSystem.h" #include "tools/MCEditTool.h" #include "DesktopServices.h" #include "ui/GuiUtil.h" #include "Application.h" class WorldListProxyModel : public QSortFilterProxyModel { Q_OBJECT public: WorldListProxyModel(QObject* parent) : QSortFilterProxyModel(parent) {} virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const { QModelIndex sourceIndex = mapToSource(index); if (index.column() == 0 && role == Qt::DecorationRole) { WorldList* worlds = qobject_cast<WorldList*>(sourceModel()); auto iconFile = worlds->data(sourceIndex, WorldList::IconFileRole).toString(); if (iconFile.isNull()) { // NOTE: Minecraft uses the same placeholder for servers AND worlds return APPLICATION->getThemedIcon("unknown_server"); } return QIcon(iconFile); } return sourceIndex.data(role); } }; WorldListPage::WorldListPage(InstancePtr inst, std::shared_ptr<WorldList> worlds, QWidget* parent) : QMainWindow(parent), m_inst(inst), ui(new Ui::WorldListPage), m_worlds(worlds) { ui->setupUi(this); ui->toolBar->insertSpacer(ui->actionRefresh); WorldListProxyModel* proxy = new WorldListProxyModel(this); proxy->setSortCaseSensitivity(Qt::CaseInsensitive); proxy->setSourceModel(m_worlds.get()); proxy->setSortRole(Qt::UserRole); ui->worldTreeView->setSortingEnabled(true); ui->worldTreeView->setModel(proxy); ui->worldTreeView->installEventFilter(this); ui->worldTreeView->setContextMenuPolicy(Qt::CustomContextMenu); ui->worldTreeView->setIconSize(QSize(64, 64)); connect(ui->worldTreeView, &QTreeView::customContextMenuRequested, this, &WorldListPage::ShowContextMenu); auto head = ui->worldTreeView->header(); head->setSectionResizeMode(0, QHeaderView::Stretch); head->setSectionResizeMode(1, QHeaderView::ResizeToContents); head->setSectionResizeMode(4, QHeaderView::ResizeToContents); connect(ui->worldTreeView->selectionModel(), &QItemSelectionModel::currentChanged, this, &WorldListPage::worldChanged); worldChanged(QModelIndex(), QModelIndex()); } void WorldListPage::openedImpl() { m_worlds->startWatching(); auto mInst = std::dynamic_pointer_cast<MinecraftInstance>(m_inst); if (!mInst || !mInst->traits().contains("feature:is_quick_play_singleplayer")) { ui->toolBar->removeAction(ui->actionJoin); } auto const setting_name = QString("WideBarVisibility_%1").arg(id()); if (!APPLICATION->settings()->contains(setting_name)) m_wide_bar_setting = APPLICATION->settings()->registerSetting(setting_name); else m_wide_bar_setting = APPLICATION->settings()->getSetting(setting_name); ui->toolBar->setVisibilityState(m_wide_bar_setting->get().toByteArray()); } void WorldListPage::closedImpl() { m_worlds->stopWatching(); m_wide_bar_setting->set(ui->toolBar->getVisibilityState()); } WorldListPage::~WorldListPage() { m_worlds->stopWatching(); delete ui; } void WorldListPage::ShowContextMenu(const QPoint& pos) { auto menu = ui->toolBar->createContextMenu(this, tr("Context menu")); menu->exec(ui->worldTreeView->mapToGlobal(pos)); delete menu; } QMenu* WorldListPage::createPopupMenu() { QMenu* filteredMenu = QMainWindow::createPopupMenu(); filteredMenu->removeAction(ui->toolBar->toggleViewAction()); return filteredMenu; } bool WorldListPage::shouldDisplay() const { return true; } void WorldListPage::retranslate() { ui->retranslateUi(this); } bool WorldListPage::worldListFilter(QKeyEvent* keyEvent) { switch (keyEvent->key()) { case Qt::Key_Delete: on_actionRemove_triggered(); return true; default: break; } return QWidget::eventFilter(ui->worldTreeView, keyEvent); } bool WorldListPage::eventFilter(QObject* obj, QEvent* ev) { if (ev->type() != QEvent::KeyPress) { return QWidget::eventFilter(obj, ev); } QKeyEvent* keyEvent = static_cast<QKeyEvent*>(ev); if (obj == ui->worldTreeView) return worldListFilter(keyEvent); return QWidget::eventFilter(obj, ev); } void WorldListPage::on_actionRemove_triggered() { auto proxiedIndex = getSelectedWorld(); if (!proxiedIndex.isValid()) return; auto result = CustomMessageBox::selectable(this, tr("Confirm Deletion"), tr("You are about to delete \"%1\".\n" "The world may be gone forever (A LONG TIME).\n\n" "Are you sure?") .arg(m_worlds->allWorlds().at(proxiedIndex.row()).name()), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (result != QMessageBox::Yes) { return; } m_worlds->stopWatching(); m_worlds->deleteWorld(proxiedIndex.row()); m_worlds->startWatching(); } void WorldListPage::on_actionView_Folder_triggered() { DesktopServices::openPath(m_worlds->dir().absolutePath(), true); } void WorldListPage::on_actionDatapacks_triggered() { QModelIndex index = getSelectedWorld(); if (!index.isValid()) { return; } if (!worldSafetyNagQuestion(tr("Open World Datapacks Folder"))) return; auto fullPath = m_worlds->data(index, WorldList::FolderRole).toString(); DesktopServices::openPath(FS::PathCombine(fullPath, "datapacks"), true); } void WorldListPage::on_actionReset_Icon_triggered() { auto proxiedIndex = getSelectedWorld(); if (!proxiedIndex.isValid()) return; if (m_worlds->resetIcon(proxiedIndex.row())) { ui->actionReset_Icon->setEnabled(false); } } QModelIndex WorldListPage::getSelectedWorld() { auto index = ui->worldTreeView->selectionModel()->currentIndex(); auto proxy = (QSortFilterProxyModel*)ui->worldTreeView->model(); return proxy->mapToSource(index); } void WorldListPage::on_actionCopy_Seed_triggered() { QModelIndex index = getSelectedWorld(); if (!index.isValid()) { return; } int64_t seed = m_worlds->data(index, WorldList::SeedRole).toLongLong(); APPLICATION->clipboard()->setText(QString::number(seed)); } void WorldListPage::on_actionMCEdit_triggered() { if (m_mceditStarting) return; auto mcedit = APPLICATION->mcedit(); const QString mceditPath = mcedit->path(); QModelIndex index = getSelectedWorld(); if (!index.isValid()) { return; } if (!worldSafetyNagQuestion(tr("Open World in MCEdit"))) return; auto fullPath = m_worlds->data(index, WorldList::FolderRole).toString(); auto program = mcedit->getProgramPath(); if (program.size()) { #ifdef Q_OS_WIN32 if (!QProcess::startDetached(program, { fullPath }, mceditPath)) { mceditError(); } #else m_mceditProcess.reset(new LoggedProcess()); m_mceditProcess->setDetachable(true); connect(m_mceditProcess.get(), &LoggedProcess::stateChanged, this, &WorldListPage::mceditState); m_mceditProcess->start(program, { fullPath }); m_mceditProcess->setWorkingDirectory(mceditPath); m_mceditStarting = true; #endif } else { QMessageBox::warning(this->parentWidget(), tr("No MCEdit found or set up!"), tr("You do not have MCEdit set up or it was moved.\nYou can set it up in the global settings.")); } } void WorldListPage::mceditError() { QMessageBox::warning(this->parentWidget(), tr("MCEdit failed to start!"), tr("MCEdit failed to start.\nIt may be necessary to reinstall it.")); } void WorldListPage::mceditState(LoggedProcess::State state) { bool failed = false; switch (state) { case LoggedProcess::NotRunning: case LoggedProcess::Starting: return; case LoggedProcess::FailedToStart: case LoggedProcess::Crashed: case LoggedProcess::Aborted: { failed = true; } /* fallthrough */ case LoggedProcess::Running: case LoggedProcess::Finished: { m_mceditStarting = false; break; } } if (failed) { mceditError(); } } void WorldListPage::worldChanged([[maybe_unused]] const QModelIndex& current, [[maybe_unused]] const QModelIndex& previous) { QModelIndex index = getSelectedWorld(); bool enable = index.isValid(); ui->actionCopy_Seed->setEnabled(enable); ui->actionMCEdit->setEnabled(enable); ui->actionRemove->setEnabled(enable); ui->actionCopy->setEnabled(enable); ui->actionRename->setEnabled(enable); ui->actionDatapacks->setEnabled(enable); bool hasIcon = !index.data(WorldList::IconFileRole).isNull(); ui->actionReset_Icon->setEnabled(enable && hasIcon); auto mInst = std::dynamic_pointer_cast<MinecraftInstance>(m_inst); auto supportsJoin = mInst && mInst->traits().contains("feature:is_quick_play_singleplayer"); ui->actionJoin->setEnabled(enable && supportsJoin); if (!supportsJoin) { ui->toolBar->removeAction(ui->actionJoin); } } void WorldListPage::on_actionAdd_triggered() { auto list = GuiUtil::BrowseForFiles(displayName(), tr("Select a Minecraft world zip"), tr("Minecraft World Zip File") + " (*.zip)", QString(), this->parentWidget()); if (!list.empty()) { m_worlds->stopWatching(); for (auto filename : list) { m_worlds->installWorld(QFileInfo(filename)); } m_worlds->startWatching(); } } bool WorldListPage::isWorldSafe(QModelIndex) { return !m_inst->isRunning(); } bool WorldListPage::worldSafetyNagQuestion(const QString& actionType) { if (!isWorldSafe(getSelectedWorld())) { auto result = QMessageBox::question( this, actionType, tr("Changing a world while Minecraft is running is potentially unsafe.\nDo you wish to proceed?")); if (result == QMessageBox::No) { return false; } } return true; } void WorldListPage::on_actionCopy_triggered() { QModelIndex index = getSelectedWorld(); if (!index.isValid()) { return; } if (!worldSafetyNagQuestion(tr("Copy World"))) return; auto worldVariant = m_worlds->data(index, WorldList::ObjectRole); auto world = (World*)worldVariant.value<void*>(); bool ok = false; QString name = QInputDialog::getText(this, tr("World name"), tr("Enter a new name for the copy."), QLineEdit::Normal, world->name(), &ok); if (ok && name.length() > 0) { world->install(m_worlds->dir().absolutePath(), name); } } void WorldListPage::on_actionRename_triggered() { QModelIndex index = getSelectedWorld(); if (!index.isValid()) { return; } if (!worldSafetyNagQuestion(tr("Rename World"))) return; auto worldVariant = m_worlds->data(index, WorldList::ObjectRole); auto world = (World*)worldVariant.value<void*>(); bool ok = false; QString name = QInputDialog::getText(this, tr("World name"), tr("Enter a new world name."), QLineEdit::Normal, world->name(), &ok); if (ok && name.length() > 0) { world->rename(name); } } void WorldListPage::on_actionRefresh_triggered() { m_worlds->update(); } void WorldListPage::on_actionJoin_triggered() { QModelIndex index = getSelectedWorld(); if (!index.isValid()) { return; } auto worldVariant = m_worlds->data(index, WorldList::ObjectRole); auto world = (World*)worldVariant.value<void*>(); APPLICATION->launch(m_inst, true, false, std::make_shared<MinecraftTarget>(MinecraftTarget::parse(world->folderName(), true))); } #include "WorldListPage.moc"
13,958
C++
.cpp
372
31.857527
135
0.676756
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,005
ResourcePackPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/ResourcePackPage.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only AND Apache-2.0 /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ResourcePackPage.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ProgressDialog.h" #include "ui/dialogs/ResourceDownloadDialog.h" #include "ui/dialogs/ResourceUpdateDialog.h" ResourcePackPage::ResourcePackPage(MinecraftInstance* instance, std::shared_ptr<ResourcePackFolderModel> model, QWidget* parent) : ExternalResourcesPage(instance, model, parent), m_model(model) { ui->actionDownloadItem->setText(tr("Download Packs")); ui->actionDownloadItem->setToolTip(tr("Download resource packs from online mod platforms")); ui->actionDownloadItem->setEnabled(true); ui->actionsToolbar->insertActionBefore(ui->actionAddItem, ui->actionDownloadItem); connect(ui->actionDownloadItem, &QAction::triggered, this, &ResourcePackPage::downloadResourcePacks); ui->actionUpdateItem->setToolTip(tr("Try to check or update all selected resource packs (all resource packs if none are selected)")); connect(ui->actionUpdateItem, &QAction::triggered, this, &ResourcePackPage::updateResourcePacks); ui->actionsToolbar->insertActionBefore(ui->actionAddItem, ui->actionUpdateItem); auto updateMenu = new QMenu(this); auto update = updateMenu->addAction(ui->actionUpdateItem->text()); connect(update, &QAction::triggered, this, &ResourcePackPage::updateResourcePacks); updateMenu->addAction(ui->actionResetItemMetadata); connect(ui->actionResetItemMetadata, &QAction::triggered, this, &ResourcePackPage::deleteResourcePackMetadata); ui->actionUpdateItem->setMenu(updateMenu); ui->actionChangeVersion->setToolTip(tr("Change a mod's version.")); connect(ui->actionChangeVersion, &QAction::triggered, this, &ResourcePackPage::changeResourcePackVersion); ui->actionsToolbar->insertActionAfter(ui->actionUpdateItem, ui->actionChangeVersion); } void ResourcePackPage::updateFrame(const QModelIndex& current, [[maybe_unused]] const QModelIndex& previous) { auto sourceCurrent = m_filterModel->mapToSource(current); int row = sourceCurrent.row(); auto& rp = static_cast<ResourcePack&>(m_model->at(row)); ui->frame->updateWithResourcePack(rp); } void ResourcePackPage::downloadResourcePacks() { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance ResourceDownload::ResourcePackDownloadDialog mdownload(this, m_model, m_instance); if (mdownload.exec()) { auto tasks = new ConcurrentTask("Download Resource Pack", APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); tasks->deleteLater(); }); for (auto& task : mdownload.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } } void ResourcePackPage::updateResourcePacks() { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance auto profile = static_cast<MinecraftInstance*>(m_instance)->getPackProfile(); if (APPLICATION->settings()->get("ModMetadataDisabled").toBool()) { QMessageBox::critical(this, tr("Error"), tr("Resource pack updates are unavailable when metadata is disabled!")); return; } if (m_instance != nullptr && m_instance->isRunning()) { auto response = CustomMessageBox::selectable( this, tr("Confirm Update"), tr("Updating resource packs while the game is running may cause pack duplication and game crashes.\n" "The old files may not be deleted as they are in use.\n" "Are you sure you want to do this?"), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); auto mods_list = m_model->selectedResources(selection); bool use_all = mods_list.empty(); if (use_all) mods_list = m_model->allResources(); ResourceUpdateDialog update_dialog(this, m_instance, m_model, mods_list, false, false); update_dialog.checkCandidates(); if (update_dialog.aborted()) { CustomMessageBox::selectable(this, tr("Aborted"), tr("The resource pack updater was aborted!"), QMessageBox::Warning)->show(); return; } if (update_dialog.noUpdates()) { QString message{ tr("'%1' is up-to-date! :)").arg(mods_list.front()->name()) }; if (mods_list.size() > 1) { if (use_all) { message = tr("All resource packs are up-to-date! :)"); } else { message = tr("All selected resource packs are up-to-date! :)"); } } CustomMessageBox::selectable(this, tr("Update checker"), message)->exec(); return; } if (update_dialog.exec()) { auto tasks = new ConcurrentTask("Download Resource Packs", APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) { CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); } tasks->deleteLater(); }); for (auto task : update_dialog.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } } void ResourcePackPage::deleteResourcePackMetadata() { auto selection = m_filterModel->mapSelectionToSource(ui->treeView->selectionModel()->selection()).indexes(); auto selectionCount = m_model->selectedResourcePacks(selection).length(); if (selectionCount == 0) return; if (selectionCount > 1) { auto response = CustomMessageBox::selectable(this, tr("Confirm Removal"), tr("You are about to remove the metadata for %1 resource packs.\n" "Are you sure?") .arg(selectionCount), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; } m_model->deleteMetadata(selection); } void ResourcePackPage::changeResourcePackVersion() { if (m_instance->typeName() != "Minecraft") return; // this is a null instance or a legacy instance if (APPLICATION->settings()->get("ModMetadataDisabled").toBool()) { QMessageBox::critical(this, tr("Error"), tr("Resource pack updates are unavailable when metadata is disabled!")); return; } const QModelIndexList rows = ui->treeView->selectionModel()->selectedRows(); if (rows.count() != 1) return; Resource& resource = m_model->at(m_filterModel->mapToSource(rows[0]).row()); if (resource.metadata() == nullptr) return; ResourceDownload::ResourcePackDownloadDialog mdownload(this, m_model, m_instance); mdownload.setResourceMetadata(resource.metadata()); if (mdownload.exec()) { auto tasks = new ConcurrentTask("Download Resource Packs", APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt()); connect(tasks, &Task::failed, [this, tasks](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); tasks->deleteLater(); }); connect(tasks, &Task::aborted, [this, tasks]() { CustomMessageBox::selectable(this, tr("Aborted"), tr("Download stopped by user."), QMessageBox::Information)->show(); tasks->deleteLater(); }); connect(tasks, &Task::succeeded, [this, tasks]() { QStringList warnings = tasks->warnings(); if (warnings.count()) CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->show(); tasks->deleteLater(); }); for (auto& task : mdownload.getTasks()) { tasks->addTask(task); } ProgressDialog loadDialog(this); loadDialog.setSkipButton(true, tr("Abort")); loadDialog.execWithTask(tasks); m_model->update(); } }
11,524
C++
.cpp
227
42.431718
137
0.653282
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,007
ScreenshotsPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/ScreenshotsPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ScreenshotsPage.h" #include "BuildConfig.h" #include "ui_ScreenshotsPage.h" #include <QClipboard> #include <QEvent> #include <QFileIconProvider> #include <QFileSystemModel> #include <QKeyEvent> #include <QLineEdit> #include <QMap> #include <QMenu> #include <QModelIndex> #include <QMutableListIterator> #include <QPainter> #include <QRegularExpression> #include <QSet> #include <QStyledItemDelegate> #include <Application.h> #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ProgressDialog.h" #include "net/NetJob.h" #include "screenshots/ImgurAlbumCreation.h" #include "screenshots/ImgurUpload.h" #include "tasks/SequentialTask.h" #include <DesktopServices.h> #include <FileSystem.h> #include "RWStorage.h" using SharedIconCache = RWStorage<QString, QIcon>; using SharedIconCachePtr = std::shared_ptr<SharedIconCache>; class ThumbnailingResult : public QObject { Q_OBJECT public slots: inline void emitResultsReady(const QString& path) { emit resultsReady(path); } inline void emitResultsFailed(const QString& path) { emit resultsFailed(path); } signals: void resultsReady(const QString& path); void resultsFailed(const QString& path); }; class ThumbnailRunnable : public QRunnable { public: ThumbnailRunnable(QString path, SharedIconCachePtr cache) { m_path = path; m_cache = cache; } void run() { QFileInfo info(m_path); if (info.isDir()) return; if ((info.suffix().compare("png", Qt::CaseInsensitive) != 0)) return; if (!m_cache->stale(m_path)) return; QImage image(m_path); if (image.isNull()) { m_resultEmitter.emitResultsFailed(m_path); qDebug() << "Error loading screenshot: " + m_path + ". Perhaps too large?"; return; } QImage small; if (image.width() > image.height()) small = image.scaledToWidth(512).scaledToWidth(256, Qt::SmoothTransformation); else small = image.scaledToHeight(512).scaledToHeight(256, Qt::SmoothTransformation); QPoint offset((256 - small.width()) / 2, (256 - small.height()) / 2); QImage square(QSize(256, 256), QImage::Format_ARGB32); square.fill(Qt::transparent); QPainter painter(&square); painter.drawImage(offset, small); painter.end(); QIcon icon(QPixmap::fromImage(square)); m_cache->add(m_path, icon); m_resultEmitter.emitResultsReady(m_path); } QString m_path; SharedIconCachePtr m_cache; ThumbnailingResult m_resultEmitter; }; // this is about as elegant and well written as a bag of bricks with scribbles done by insane // asylum patients. class FilterModel : public QIdentityProxyModel { Q_OBJECT public: explicit FilterModel(QObject* parent = 0) : QIdentityProxyModel(parent) { m_thumbnailingPool.setMaxThreadCount(4); m_thumbnailCache = std::make_shared<SharedIconCache>(); m_thumbnailCache->add("placeholder", APPLICATION->getThemedIcon("screenshot-placeholder")); connect(&watcher, SIGNAL(fileChanged(QString)), SLOT(fileChanged(QString))); } virtual ~FilterModel() { m_thumbnailingPool.clear(); if (!m_thumbnailingPool.waitForDone(500)) qDebug() << "Thumbnail pool took longer than 500ms to finish"; } virtual QVariant data(const QModelIndex& proxyIndex, int role = Qt::DisplayRole) const { auto model = sourceModel(); if (!model) return QVariant(); if (role == Qt::DisplayRole || role == Qt::EditRole) { QVariant result = sourceModel()->data(mapToSource(proxyIndex), role); return result.toString().remove(QRegularExpression("\\.png$")); } if (role == Qt::DecorationRole) { QVariant result = sourceModel()->data(mapToSource(proxyIndex), QFileSystemModel::FilePathRole); QString filePath = result.toString(); QIcon temp; if (!watched.contains(filePath)) { ((QFileSystemWatcher&)watcher).addPath(filePath); ((QSet<QString>&)watched).insert(filePath); } if (m_thumbnailCache->get(filePath, temp)) { return temp; } if (!m_failed.contains(filePath)) { ((FilterModel*)this)->thumbnailImage(filePath); } return (m_thumbnailCache->get("placeholder")); } return sourceModel()->data(mapToSource(proxyIndex), role); } virtual bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) { auto model = sourceModel(); if (!model) return false; if (role != Qt::EditRole) return false; // FIXME: this is a workaround for a bug in QFileSystemModel, where it doesn't // sort after renames { ((QFileSystemModel*)model)->setNameFilterDisables(true); ((QFileSystemModel*)model)->setNameFilterDisables(false); } return model->setData(mapToSource(index), value.toString() + ".png", role); } private: void thumbnailImage(QString path) { auto runnable = new ThumbnailRunnable(path, m_thumbnailCache); connect(&(runnable->m_resultEmitter), SIGNAL(resultsReady(QString)), SLOT(thumbnailReady(QString))); connect(&(runnable->m_resultEmitter), SIGNAL(resultsFailed(QString)), SLOT(thumbnailFailed(QString))); ((QThreadPool&)m_thumbnailingPool).start(runnable); } private slots: void thumbnailReady(QString path) { emit layoutChanged(); } void thumbnailFailed(QString path) { m_failed.insert(path); } void fileChanged(QString filepath) { m_thumbnailCache->setStale(filepath); // reinsert the path... watcher.removePath(filepath); if (QFile::exists(filepath)) { watcher.addPath(filepath); thumbnailImage(filepath); } } private: SharedIconCachePtr m_thumbnailCache; QThreadPool m_thumbnailingPool; QSet<QString> m_failed; QSet<QString> watched; QFileSystemWatcher watcher; }; class CenteredEditingDelegate : public QStyledItemDelegate { public: explicit CenteredEditingDelegate(QObject* parent = 0) : QStyledItemDelegate(parent) {} virtual ~CenteredEditingDelegate() {} virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const { auto widget = QStyledItemDelegate::createEditor(parent, option, index); auto foo = dynamic_cast<QLineEdit*>(widget); if (foo) { foo->setAlignment(Qt::AlignHCenter); foo->setFrame(true); foo->setMaximumWidth(192); } return widget; } }; ScreenshotsPage::ScreenshotsPage(QString path, QWidget* parent) : QMainWindow(parent), ui(new Ui::ScreenshotsPage) { m_model.reset(new QFileSystemModel()); m_filterModel.reset(new FilterModel()); m_filterModel->setSourceModel(m_model.get()); m_model->setFilter(QDir::Files); m_model->setReadOnly(false); m_model->setNameFilters({ "*.png" }); m_model->setNameFilterDisables(false); // Sorts by modified date instead of creation date because that column is not available and would require subclassing, this should work // considering screenshots aren't modified after creation. constexpr int file_modified_column_index = 3; m_model->sort(file_modified_column_index, Qt::DescendingOrder); m_folder = path; m_valid = FS::ensureFolderPathExists(m_folder); ui->setupUi(this); ui->toolBar->insertSpacer(ui->actionView_Folder); ui->listView->setIconSize(QSize(128, 128)); ui->listView->setGridSize(QSize(192, 160)); ui->listView->setSpacing(9); // ui->listView->setUniformItemSizes(true); ui->listView->setLayoutMode(QListView::Batched); ui->listView->setViewMode(QListView::IconMode); ui->listView->setResizeMode(QListView::Adjust); ui->listView->installEventFilter(this); ui->listView->setEditTriggers(QAbstractItemView::NoEditTriggers); ui->listView->setItemDelegate(new CenteredEditingDelegate(this)); ui->listView->setContextMenuPolicy(Qt::CustomContextMenu); connect(ui->listView, &QListView::customContextMenuRequested, this, &ScreenshotsPage::ShowContextMenu); connect(ui->listView, SIGNAL(activated(QModelIndex)), SLOT(onItemActivated(QModelIndex))); } bool ScreenshotsPage::eventFilter(QObject* obj, QEvent* evt) { if (obj != ui->listView) return QWidget::eventFilter(obj, evt); if (evt->type() != QEvent::KeyPress) { return QWidget::eventFilter(obj, evt); } QKeyEvent* keyEvent = static_cast<QKeyEvent*>(evt); if (keyEvent->matches(QKeySequence::Copy)) { on_actionCopy_File_s_triggered(); return true; } switch (keyEvent->key()) { case Qt::Key_Delete: on_actionDelete_triggered(); return true; case Qt::Key_F2: on_actionRename_triggered(); return true; default: break; } return QWidget::eventFilter(obj, evt); } void ScreenshotsPage::retranslate() { ui->retranslateUi(this); } ScreenshotsPage::~ScreenshotsPage() { delete ui; } void ScreenshotsPage::ShowContextMenu(const QPoint& pos) { auto menu = ui->toolBar->createContextMenu(this, tr("Context menu")); if (ui->listView->selectionModel()->selectedRows().size() > 1) { menu->removeAction(ui->actionCopy_Image); } menu->exec(ui->listView->mapToGlobal(pos)); delete menu; } QMenu* ScreenshotsPage::createPopupMenu() { QMenu* filteredMenu = QMainWindow::createPopupMenu(); filteredMenu->removeAction(ui->toolBar->toggleViewAction()); return filteredMenu; } void ScreenshotsPage::onItemActivated(QModelIndex index) { if (!index.isValid()) return; auto info = m_model->fileInfo(index); DesktopServices::openPath(info); } void ScreenshotsPage::onCurrentSelectionChanged(const QItemSelection& selected) { bool allReadable = !selected.isEmpty(); bool allWritable = !selected.isEmpty(); for (auto index : selected.indexes()) { if (!index.isValid()) break; auto info = m_model->fileInfo(index); if (!info.isReadable()) allReadable = false; if (!info.isWritable()) allWritable = false; } ui->actionUpload->setEnabled(allReadable); ui->actionCopy_Image->setEnabled(allReadable); ui->actionCopy_File_s->setEnabled(allReadable); ui->actionDelete->setEnabled(allWritable); ui->actionRename->setEnabled(allWritable); } void ScreenshotsPage::on_actionView_Folder_triggered() { DesktopServices::openPath(m_folder, true); } void ScreenshotsPage::on_actionUpload_triggered() { auto selection = ui->listView->selectionModel()->selectedRows(); if (selection.isEmpty()) return; QString text; QUrl baseUrl(BuildConfig.IMGUR_BASE_URL); if (selection.size() > 1) text = tr("You are about to upload %1 screenshots to %2.\n" "You should double-check for personal information.\n\n" "Are you sure?") .arg(QString::number(selection.size()), baseUrl.host()); else text = tr("You are about to upload the selected screenshot to %1.\n" "You should double-check for personal information.\n\n" "Are you sure?") .arg(baseUrl.host()); auto response = CustomMessageBox::selectable(this, "Confirm Upload", text, QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) return; QList<ScreenShot::Ptr> uploaded; auto job = NetJob::Ptr(new NetJob("Screenshot Upload", APPLICATION->network())); ProgressDialog dialog(this); dialog.setSkipButton(true, tr("Abort")); if (selection.size() < 2) { auto item = selection.at(0); auto info = m_model->fileInfo(item); auto screenshot = std::make_shared<ScreenShot>(info); job->addNetAction(ImgurUpload::make(screenshot)); connect(job.get(), &Task::failed, [this](QString reason) { CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), reason, QMessageBox::Critical)->show(); }); connect(job.get(), &Task::aborted, [this] { CustomMessageBox::selectable(this, tr("Screenshots upload aborted"), tr("The task has been aborted by the user."), QMessageBox::Information) ->show(); }); m_uploadActive = true; if (dialog.execWithTask(job.get()) == QDialog::Accepted) { auto link = screenshot->m_url; QClipboard* clipboard = QApplication::clipboard(); qDebug() << "ImgurUpload link" << link; clipboard->setText(link); CustomMessageBox::selectable( this, tr("Upload finished"), tr("The <a href=\"%1\">link to the uploaded screenshot</a> has been placed in your clipboard.").arg(link), QMessageBox::Information) ->exec(); } m_uploadActive = false; return; } for (auto item : selection) { auto info = m_model->fileInfo(item); auto screenshot = std::make_shared<ScreenShot>(info); uploaded.push_back(screenshot); job->addNetAction(ImgurUpload::make(screenshot)); } SequentialTask task; auto albumTask = NetJob::Ptr(new NetJob("Imgur Album Creation", APPLICATION->network())); auto imgurResult = std::make_shared<ImgurAlbumCreation::Result>(); auto imgurAlbum = ImgurAlbumCreation::make(imgurResult, uploaded); albumTask->addNetAction(imgurAlbum); task.addTask(job); task.addTask(albumTask); connect(&task, &Task::failed, [this](QString reason) { CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), reason, QMessageBox::Critical)->show(); }); connect(&task, &Task::aborted, [this] { CustomMessageBox::selectable(this, tr("Screenshots upload aborted"), tr("The task has been aborted by the user."), QMessageBox::Information) ->show(); }); m_uploadActive = true; if (dialog.execWithTask(&task) == QDialog::Accepted) { if (imgurResult->id.isEmpty()) { CustomMessageBox::selectable(this, tr("Failed to upload screenshots!"), tr("Unknown error"), QMessageBox::Warning)->exec(); } else { auto link = QString("https://imgur.com/a/%1").arg(imgurResult->id); qDebug() << "ImgurUpload link" << link; QClipboard* clipboard = QApplication::clipboard(); clipboard->setText(link); CustomMessageBox::selectable( this, tr("Upload finished"), tr("The <a href=\"%1\">link to the uploaded album</a> has been placed in your clipboard.").arg(link), QMessageBox::Information) ->exec(); } } m_uploadActive = false; } void ScreenshotsPage::on_actionCopy_Image_triggered() { auto selection = ui->listView->selectionModel()->selectedRows(); if (selection.size() < 1) { return; } // You can only copy one image to the clipboard. In the case of multiple selected files, only the first one gets copied. auto item = selection[0]; auto info = m_model->fileInfo(item); QImage image(info.absoluteFilePath()); Q_ASSERT(!image.isNull()); QApplication::clipboard()->setImage(image, QClipboard::Clipboard); } void ScreenshotsPage::on_actionCopy_File_s_triggered() { auto selection = ui->listView->selectionModel()->selectedRows(); if (selection.size() < 1) { // Don't do anything so we don't empty the users clipboard return; } QString buf = ""; for (auto item : selection) { auto info = m_model->fileInfo(item); buf += "file:///" + info.absoluteFilePath() + "\r\n"; } QMimeData* mimeData = new QMimeData(); mimeData->setData("text/uri-list", buf.toLocal8Bit()); QApplication::clipboard()->setMimeData(mimeData); } void ScreenshotsPage::on_actionDelete_triggered() { auto selected = ui->listView->selectionModel()->selectedIndexes(); int count = ui->listView->selectionModel()->selectedRows().size(); QString text; if (count > 1) text = tr("You are about to delete %1 screenshots.\n" "This may be permanent and they will be gone from the folder.\n\n" "Are you sure?") .arg(count); else text = tr("You are about to delete the selected screenshot.\n" "This may be permanent and it will be gone from the folder.\n\n" "Are you sure?") .arg(count); auto response = CustomMessageBox::selectable(this, tr("Confirm Deletion"), text, QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No)->exec(); if (response != QMessageBox::Yes) return; for (auto item : selected) { if (FS::trash(m_model->filePath(item))) continue; m_model->remove(item); } } void ScreenshotsPage::on_actionRename_triggered() { auto selection = ui->listView->selectionModel()->selectedIndexes(); if (selection.isEmpty()) return; ui->listView->edit(selection[0]); // TODO: mass renaming } void ScreenshotsPage::openedImpl() { if (!m_valid) { m_valid = FS::ensureFolderPathExists(m_folder); } if (m_valid) { QString path = QDir(m_folder).absolutePath(); auto idx = m_model->setRootPath(path); if (idx.isValid()) { ui->listView->setModel(m_filterModel.get()); connect(ui->listView->selectionModel(), &QItemSelectionModel::selectionChanged, this, &ScreenshotsPage::onCurrentSelectionChanged); onCurrentSelectionChanged(ui->listView->selectionModel()->selection()); // set initial button enable states ui->listView->setRootIndex(m_filterModel->mapFromSource(idx)); } else { ui->listView->setModel(nullptr); } } auto const setting_name = QString("WideBarVisibility_%1").arg(id()); if (!APPLICATION->settings()->contains(setting_name)) m_wide_bar_setting = APPLICATION->settings()->registerSetting(setting_name); else m_wide_bar_setting = APPLICATION->settings()->getSetting(setting_name); ui->toolBar->setVisibilityState(m_wide_bar_setting->get().toByteArray()); } void ScreenshotsPage::closedImpl() { m_wide_bar_setting->set(ui->toolBar->getVisibilityState()); } #include "ScreenshotsPage.moc"
20,683
C++
.cpp
512
33.435547
139
0.656654
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,008
LogPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/instance/LogPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2024 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "LogPage.h" #include "ui_LogPage.h" #include "Application.h" #include <QIdentityProxyModel> #include <QScrollBar> #include <QShortcut> #include "launch/LaunchTask.h" #include "settings/Setting.h" #include "ui/GuiUtil.h" #include "ui/themes/ThemeManager.h" #include <BuildConfig.h> class LogFormatProxyModel : public QIdentityProxyModel { public: LogFormatProxyModel(QObject* parent = nullptr) : QIdentityProxyModel(parent) {} QVariant data(const QModelIndex& index, int role) const override { const LogColors& colors = APPLICATION->themeManager()->getLogColors(); switch (role) { case Qt::FontRole: return m_font; case Qt::ForegroundRole: { auto level = static_cast<MessageLevel::Enum>(QIdentityProxyModel::data(index, LogModel::LevelRole).toInt()); QColor result = colors.foreground.value(level); if (result.isValid()) return result; break; } case Qt::BackgroundRole: { auto level = static_cast<MessageLevel::Enum>(QIdentityProxyModel::data(index, LogModel::LevelRole).toInt()); QColor result = colors.background.value(level); if (result.isValid()) return result; break; } } return QIdentityProxyModel::data(index, role); } void setFont(QFont font) { m_font = font; } QModelIndex find(const QModelIndex& start, const QString& value, bool reverse) const { QModelIndex parentIndex = parent(start); auto compare = [this, start, parentIndex, value](int r) -> QModelIndex { QModelIndex idx = index(r, start.column(), parentIndex); if (!idx.isValid() || idx == start) { return QModelIndex(); } QVariant v = data(idx, Qt::DisplayRole); QString t = v.toString(); if (t.contains(value, Qt::CaseInsensitive)) return idx; return QModelIndex(); }; if (reverse) { int from = start.row(); int to = 0; for (int i = 0; i < 2; ++i) { for (int r = from; (r >= to); --r) { auto idx = compare(r); if (idx.isValid()) return idx; } // prepare for the next iteration from = rowCount() - 1; to = start.row(); } } else { int from = start.row(); int to = rowCount(parentIndex); for (int i = 0; i < 2; ++i) { for (int r = from; (r < to); ++r) { auto idx = compare(r); if (idx.isValid()) return idx; } // prepare for the next iteration from = 0; to = start.row(); } } return QModelIndex(); } private: QFont m_font; }; LogPage::LogPage(InstancePtr instance, QWidget* parent) : QWidget(parent), ui(new Ui::LogPage), m_instance(instance) { ui->setupUi(this); ui->tabWidget->tabBar()->hide(); m_proxy = new LogFormatProxyModel(this); // set up fonts in the log proxy { QString fontFamily = APPLICATION->settings()->get("ConsoleFont").toString(); bool conversionOk = false; int fontSize = APPLICATION->settings()->get("ConsoleFontSize").toInt(&conversionOk); if (!conversionOk) { fontSize = 11; } m_proxy->setFont(QFont(fontFamily, fontSize)); } ui->text->setModel(m_proxy); // set up instance and launch process recognition { auto launchTask = m_instance->getLaunchTask(); if (launchTask) { setInstanceLaunchTaskChanged(launchTask, true); } connect(m_instance.get(), &BaseInstance::launchTaskChanged, this, &LogPage::onInstanceLaunchTaskChanged); } auto findShortcut = new QShortcut(QKeySequence(QKeySequence::Find), this); connect(findShortcut, SIGNAL(activated()), SLOT(findActivated())); auto findNextShortcut = new QShortcut(QKeySequence(QKeySequence::FindNext), this); connect(findNextShortcut, SIGNAL(activated()), SLOT(findNextActivated())); connect(ui->searchBar, SIGNAL(returnPressed()), SLOT(on_findButton_clicked())); auto findPreviousShortcut = new QShortcut(QKeySequence(QKeySequence::FindPrevious), this); connect(findPreviousShortcut, SIGNAL(activated()), SLOT(findPreviousActivated())); } LogPage::~LogPage() { delete ui; } void LogPage::modelStateToUI() { if (m_model->wrapLines()) { ui->text->setWordWrap(true); ui->wrapCheckbox->setCheckState(Qt::Checked); } else { ui->text->setWordWrap(false); ui->wrapCheckbox->setCheckState(Qt::Unchecked); } if (m_model->suspended()) { ui->trackLogCheckbox->setCheckState(Qt::Unchecked); } else { ui->trackLogCheckbox->setCheckState(Qt::Checked); } } void LogPage::UIToModelState() { if (!m_model) { return; } m_model->setLineWrap(ui->wrapCheckbox->checkState() == Qt::Checked); m_model->suspend(ui->trackLogCheckbox->checkState() != Qt::Checked); } void LogPage::setInstanceLaunchTaskChanged(shared_qobject_ptr<LaunchTask> proc, bool initial) { m_process = proc; if (m_process) { m_model = proc->getLogModel(); m_proxy->setSourceModel(m_model.get()); if (initial) { modelStateToUI(); } else { UIToModelState(); } } else { m_proxy->setSourceModel(nullptr); m_model.reset(); } } void LogPage::onInstanceLaunchTaskChanged(shared_qobject_ptr<LaunchTask> proc) { setInstanceLaunchTaskChanged(proc, false); } bool LogPage::apply() { return true; } bool LogPage::shouldDisplay() const { return true; } void LogPage::on_btnPaste_clicked() { if (!m_model) return; // FIXME: turn this into a proper task and move the upload logic out of GuiUtil! m_model->append(MessageLevel::Launcher, QString("Log upload triggered at: %1").arg(QDateTime::currentDateTime().toString(Qt::RFC2822Date))); auto url = GuiUtil::uploadPaste(tr("Minecraft Log"), m_model->toPlainText(), this); if (!url.has_value()) { m_model->append(MessageLevel::Error, QString("Log upload canceled")); } else if (url->isNull()) { m_model->append(MessageLevel::Error, QString("Log upload failed!")); } else { m_model->append(MessageLevel::Launcher, QString("Log uploaded to: %1").arg(url.value())); } } void LogPage::on_btnCopy_clicked() { if (!m_model) return; m_model->append(MessageLevel::Launcher, QString("Clipboard copy at: %1").arg(QDateTime::currentDateTime().toString(Qt::RFC2822Date))); GuiUtil::setClipboardText(m_model->toPlainText()); } void LogPage::on_btnClear_clicked() { if (!m_model) return; m_model->clear(); m_container->refreshContainer(); } void LogPage::on_btnBottom_clicked() { ui->text->scrollToBottom(); } void LogPage::on_trackLogCheckbox_clicked(bool checked) { if (!m_model) return; m_model->suspend(!checked); } void LogPage::on_wrapCheckbox_clicked(bool checked) { ui->text->setWordWrap(checked); if (!m_model) return; m_model->setLineWrap(checked); } void LogPage::on_findButton_clicked() { auto modifiers = QApplication::keyboardModifiers(); bool reverse = modifiers & Qt::ShiftModifier; ui->text->findNext(ui->searchBar->text(), reverse); } void LogPage::findNextActivated() { ui->text->findNext(ui->searchBar->text(), false); } void LogPage::findPreviousActivated() { ui->text->findNext(ui->searchBar->text(), true); } void LogPage::findActivated() { // focus the search bar if it doesn't have focus if (!ui->searchBar->hasFocus()) { ui->searchBar->setFocus(); ui->searchBar->selectAll(); } } void LogPage::retranslate() { ui->retranslateUi(this); }
9,803
C++
.cpp
280
28.485714
138
0.634177
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,009
LauncherPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/global/LauncherPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (c) 2022 dada513 <dada513@protonmail.com> * Copyright (C) 2022 Tayou <git@tayou.org> * Copyright (C) 2024 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "LauncherPage.h" #include "ui_LauncherPage.h" #include <QDir> #include <QFileDialog> #include <QMenuBar> #include <QMessageBox> #include <QTextCharFormat> #include <FileSystem.h> #include "Application.h" #include "BuildConfig.h" #include "DesktopServices.h" #include "settings/SettingsObject.h" #include "ui/themes/ITheme.h" #include "ui/themes/ThemeManager.h" #include "updater/ExternalUpdater.h" #include <QApplication> #include <QProcess> // FIXME: possibly move elsewhere enum InstSortMode { // Sort alphabetically by name. Sort_Name, // Sort by which instance was launched most recently. Sort_LastLaunch }; LauncherPage::LauncherPage(QWidget* parent) : QWidget(parent), ui(new Ui::LauncherPage) { ui->setupUi(this); ui->sortingModeGroup->setId(ui->sortByNameBtn, Sort_Name); ui->sortingModeGroup->setId(ui->sortLastLaunchedBtn, Sort_LastLaunch); defaultFormat = new QTextCharFormat(ui->fontPreview->currentCharFormat()); m_languageModel = APPLICATION->translations(); loadSettings(); ui->updateSettingsBox->setHidden(!APPLICATION->updater()); connect(ui->fontSizeBox, QOverload<int>::of(&QSpinBox::valueChanged), this, &LauncherPage::refreshFontPreview); connect(ui->consoleFont, &QFontComboBox::currentFontChanged, this, &LauncherPage::refreshFontPreview); connect(ui->themeCustomizationWidget, &ThemeCustomizationWidget::currentWidgetThemeChanged, this, &LauncherPage::refreshFontPreview); connect(ui->themeCustomizationWidget, &ThemeCustomizationWidget::currentCatChanged, APPLICATION, &Application::currentCatChanged); } LauncherPage::~LauncherPage() { delete ui; delete defaultFormat; } bool LauncherPage::apply() { applySettings(); return true; } void LauncherPage::on_instDirBrowseBtn_clicked() { QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Instance Folder"), ui->instDirTextBox->text()); // do not allow current dir - it's dirty. Do not allow dirs that don't exist if (!raw_dir.isEmpty() && QDir(raw_dir).exists()) { QString cooked_dir = FS::NormalizePath(raw_dir); if (FS::checkProblemticPathJava(QDir(cooked_dir))) { QMessageBox warning; warning.setText( tr("You're trying to specify an instance folder which\'s path " "contains at least one \'!\'. " "Java is known to cause problems if that is the case, your " "instances (probably) won't start!")); warning.setInformativeText( tr("Do you really want to use this path? " "Selecting \"No\" will close this and not alter your instance path.")); warning.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); int result = warning.exec(); if (result == QMessageBox::Ok) { ui->instDirTextBox->setText(cooked_dir); } } else if (DesktopServices::isFlatpak() && raw_dir.startsWith("/run/user")) { QMessageBox warning; warning.setText(tr("You're trying to specify an instance folder " "which was granted temporarily via Flatpak.\n" "This is known to cause problems. " "After a restart the launcher might break, " "because it will no longer have access to that directory.\n\n" "Granting %1 access to it via Flatseal is recommended.") .arg(BuildConfig.LAUNCHER_DISPLAYNAME)); warning.setInformativeText(tr("Do you want to proceed anyway?")); warning.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); int result = warning.exec(); if (result == QMessageBox::Ok) { ui->instDirTextBox->setText(cooked_dir); } } else { ui->instDirTextBox->setText(cooked_dir); } } } void LauncherPage::on_iconsDirBrowseBtn_clicked() { QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Icons Folder"), ui->iconsDirTextBox->text()); // do not allow current dir - it's dirty. Do not allow dirs that don't exist if (!raw_dir.isEmpty() && QDir(raw_dir).exists()) { QString cooked_dir = FS::NormalizePath(raw_dir); ui->iconsDirTextBox->setText(cooked_dir); } } void LauncherPage::on_modsDirBrowseBtn_clicked() { QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Mods Folder"), ui->modsDirTextBox->text()); // do not allow current dir - it's dirty. Do not allow dirs that don't exist if (!raw_dir.isEmpty() && QDir(raw_dir).exists()) { QString cooked_dir = FS::NormalizePath(raw_dir); ui->modsDirTextBox->setText(cooked_dir); } } void LauncherPage::on_downloadsDirBrowseBtn_clicked() { QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Downloads Folder"), ui->downloadsDirTextBox->text()); if (!raw_dir.isEmpty() && QDir(raw_dir).exists()) { QString cooked_dir = FS::NormalizePath(raw_dir); ui->downloadsDirTextBox->setText(cooked_dir); } } void LauncherPage::on_javaDirBrowseBtn_clicked() { QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Java Folder"), ui->javaDirTextBox->text()); if (!raw_dir.isEmpty() && QDir(raw_dir).exists()) { QString cooked_dir = FS::NormalizePath(raw_dir); ui->javaDirTextBox->setText(cooked_dir); } } void LauncherPage::on_skinsDirBrowseBtn_clicked() { QString raw_dir = QFileDialog::getExistingDirectory(this, tr("Skins Folder"), ui->skinsDirTextBox->text()); // do not allow current dir - it's dirty. Do not allow dirs that don't exist if (!raw_dir.isEmpty() && QDir(raw_dir).exists()) { QString cooked_dir = FS::NormalizePath(raw_dir); ui->skinsDirTextBox->setText(cooked_dir); } } void LauncherPage::on_metadataDisableBtn_clicked() { ui->metadataWarningLabel->setHidden(!ui->metadataDisableBtn->isChecked()); } void LauncherPage::applySettings() { auto s = APPLICATION->settings(); // Updates if (APPLICATION->updater()) { APPLICATION->updater()->setAutomaticallyChecksForUpdates(ui->autoUpdateCheckBox->isChecked()); APPLICATION->updater()->setUpdateCheckInterval(ui->updateIntervalSpinBox->value() * 3600); } s->set("MenuBarInsteadOfToolBar", ui->preferMenuBarCheckBox->isChecked()); s->set("NumberOfConcurrentTasks", ui->numberOfConcurrentTasksSpinBox->value()); s->set("NumberOfConcurrentDownloads", ui->numberOfConcurrentDownloadsSpinBox->value()); s->set("NumberOfManualRetries", ui->numberOfManualRetriesSpinBox->value()); s->set("RequestTimeout", ui->timeoutSecondsSpinBox->value()); // Console settings s->set("ShowConsole", ui->showConsoleCheck->isChecked()); s->set("AutoCloseConsole", ui->autoCloseConsoleCheck->isChecked()); s->set("ShowConsoleOnError", ui->showConsoleErrorCheck->isChecked()); QString consoleFontFamily = ui->consoleFont->currentFont().family(); s->set("ConsoleFont", consoleFontFamily); s->set("ConsoleFontSize", ui->fontSizeBox->value()); s->set("ConsoleMaxLines", ui->lineLimitSpinBox->value()); s->set("ConsoleOverflowStop", ui->checkStopLogging->checkState() != Qt::Unchecked); // Folders // TODO: Offer to move instances to new instance folder. s->set("InstanceDir", ui->instDirTextBox->text()); s->set("CentralModsDir", ui->modsDirTextBox->text()); s->set("IconsDir", ui->iconsDirTextBox->text()); s->set("DownloadsDir", ui->downloadsDirTextBox->text()); s->set("SkinsDir", ui->skinsDirTextBox->text()); s->set("JavaDir", ui->javaDirTextBox->text()); s->set("DownloadsDirWatchRecursive", ui->downloadsDirWatchRecursiveCheckBox->isChecked()); auto sortMode = (InstSortMode)ui->sortingModeGroup->checkedId(); switch (sortMode) { case Sort_LastLaunch: s->set("InstSortMode", "LastLaunch"); break; case Sort_Name: default: s->set("InstSortMode", "Name"); break; } // Cat s->set("CatOpacity", ui->catOpacitySpinBox->value()); // Mods s->set("ModMetadataDisabled", ui->metadataDisableBtn->isChecked()); s->set("ModDependenciesDisabled", ui->dependenciesDisableBtn->isChecked()); s->set("SkipModpackUpdatePrompt", ui->skipModpackUpdatePromptBtn->isChecked()); } void LauncherPage::loadSettings() { auto s = APPLICATION->settings(); // Updates if (APPLICATION->updater()) { ui->autoUpdateCheckBox->setChecked(APPLICATION->updater()->getAutomaticallyChecksForUpdates()); ui->updateIntervalSpinBox->setValue(APPLICATION->updater()->getUpdateCheckInterval() / 3600); } // Toolbar/menu bar settings (not applicable if native menu bar is present) ui->toolsBox->setEnabled(!QMenuBar().isNativeMenuBar()); #ifdef Q_OS_MACOS ui->toolsBox->setVisible(!QMenuBar().isNativeMenuBar()); #endif ui->preferMenuBarCheckBox->setChecked(s->get("MenuBarInsteadOfToolBar").toBool()); ui->numberOfConcurrentTasksSpinBox->setValue(s->get("NumberOfConcurrentTasks").toInt()); ui->numberOfConcurrentDownloadsSpinBox->setValue(s->get("NumberOfConcurrentDownloads").toInt()); ui->numberOfManualRetriesSpinBox->setValue(s->get("NumberOfManualRetries").toInt()); ui->timeoutSecondsSpinBox->setValue(s->get("RequestTimeout").toInt()); // Console settings ui->showConsoleCheck->setChecked(s->get("ShowConsole").toBool()); ui->autoCloseConsoleCheck->setChecked(s->get("AutoCloseConsole").toBool()); ui->showConsoleErrorCheck->setChecked(s->get("ShowConsoleOnError").toBool()); QString fontFamily = APPLICATION->settings()->get("ConsoleFont").toString(); QFont consoleFont(fontFamily); ui->consoleFont->setCurrentFont(consoleFont); bool conversionOk = true; int fontSize = APPLICATION->settings()->get("ConsoleFontSize").toInt(&conversionOk); if (!conversionOk) { fontSize = 11; } ui->fontSizeBox->setValue(fontSize); refreshFontPreview(); ui->lineLimitSpinBox->setValue(s->get("ConsoleMaxLines").toInt()); ui->checkStopLogging->setChecked(s->get("ConsoleOverflowStop").toBool()); // Folders ui->instDirTextBox->setText(s->get("InstanceDir").toString()); ui->modsDirTextBox->setText(s->get("CentralModsDir").toString()); ui->iconsDirTextBox->setText(s->get("IconsDir").toString()); ui->downloadsDirTextBox->setText(s->get("DownloadsDir").toString()); ui->skinsDirTextBox->setText(s->get("SkinsDir").toString()); ui->javaDirTextBox->setText(s->get("JavaDir").toString()); ui->downloadsDirWatchRecursiveCheckBox->setChecked(s->get("DownloadsDirWatchRecursive").toBool()); QString sortMode = s->get("InstSortMode").toString(); if (sortMode == "LastLaunch") { ui->sortLastLaunchedBtn->setChecked(true); } else { ui->sortByNameBtn->setChecked(true); } // Cat ui->catOpacitySpinBox->setValue(s->get("CatOpacity").toInt()); // Mods ui->metadataDisableBtn->setChecked(s->get("ModMetadataDisabled").toBool()); ui->metadataWarningLabel->setHidden(!ui->metadataDisableBtn->isChecked()); ui->dependenciesDisableBtn->setChecked(s->get("ModDependenciesDisabled").toBool()); ui->skipModpackUpdatePromptBtn->setChecked(s->get("SkipModpackUpdatePrompt").toBool()); } void LauncherPage::refreshFontPreview() { const LogColors& colors = APPLICATION->themeManager()->getLogColors(); int fontSize = ui->fontSizeBox->value(); QString fontFamily = ui->consoleFont->currentFont().family(); ui->fontPreview->clear(); defaultFormat->setFont(QFont(fontFamily, fontSize)); auto print = [this, colors](const QString& message, MessageLevel::Enum level) { QTextCharFormat format(*defaultFormat); QColor bg = colors.background.value(level); QColor fg = colors.foreground.value(level); if (bg.isValid()) format.setBackground(bg); if (fg.isValid()) format.setForeground(fg); // append a paragraph/line auto workCursor = ui->fontPreview->textCursor(); workCursor.movePosition(QTextCursor::End); workCursor.insertText(message, format); workCursor.insertBlock(); }; print(QString("%1 version: %2 (%3)\n") .arg(BuildConfig.LAUNCHER_DISPLAYNAME, BuildConfig.printableVersionString(), BuildConfig.BUILD_PLATFORM), MessageLevel::Launcher); QDate today = QDate::currentDate(); if (today.month() == 10 && today.day() == 31) print(tr("[Test/ERROR] OOoooOOOoooo! A spooky error!"), MessageLevel::Error); else print(tr("[Test/ERROR] A spooky error!"), MessageLevel::Error); print(tr("[Test/INFO] A harmless message..."), MessageLevel::Info); print(tr("[Test/WARN] A not so spooky warning."), MessageLevel::Warning); print(tr("[Test/DEBUG] A secret debugging message..."), MessageLevel::Debug); print(tr("[Test/FATAL] A terrifying fatal error!"), MessageLevel::Fatal); } void LauncherPage::retranslate() { ui->retranslateUi(this); }
14,907
C++
.cpp
315
41.4
137
0.691228
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,010
EnvironmentVariablesPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/global/EnvironmentVariablesPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <QTabBar> #include <QTabWidget> #include <QVBoxLayout> #include "EnvironmentVariablesPage.h" EnvironmentVariablesPage::EnvironmentVariablesPage(QWidget* parent) : QWidget(parent) { auto verticalLayout = new QVBoxLayout(this); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); auto tabWidget = new QTabWidget(this); tabWidget->setObjectName(QStringLiteral("tabWidget")); variables = new EnvironmentVariables(this); variables->setContentsMargins(6, 6, 6, 6); tabWidget->addTab(variables, "Foo"); tabWidget->tabBar()->hide(); verticalLayout->addWidget(tabWidget); variables->initialize(false, false, APPLICATION->settings()->get("Env").toMap()); } QString EnvironmentVariablesPage::displayName() const { return tr("Environment Variables"); } QIcon EnvironmentVariablesPage::icon() const { return APPLICATION->getThemedIcon("environment-variables"); } QString EnvironmentVariablesPage::id() const { return "environment-variables"; } QString EnvironmentVariablesPage::helpPage() const { return "Environment-variables"; } bool EnvironmentVariablesPage::apply() { APPLICATION->settings()->set("Env", variables->value()); return true; } void EnvironmentVariablesPage::retranslate() { variables->retranslate(); }
2,101
C++
.cpp
60
32.383333
85
0.760099
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,011
JavaPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/global/JavaPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "JavaPage.h" #include "BuildConfig.h" #include "JavaCommon.h" #include "java/JavaInstall.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/java/InstallJavaDialog.h" #include "ui_JavaPage.h" #include <QCheckBox> #include <QDir> #include <QFileDialog> #include <QMessageBox> #include <QStringListModel> #include <QTabBar> #include "ui/dialogs/VersionSelectDialog.h" #include "java/JavaInstallList.h" #include "java/JavaUtils.h" #include <FileSystem.h> #include <sys.h> #include "Application.h" #include "settings/SettingsObject.h" JavaPage::JavaPage(QWidget* parent) : QWidget(parent), ui(new Ui::JavaPage) { ui->setupUi(this); if (BuildConfig.JAVA_DOWNLOADER_ENABLED) { ui->managedJavaList->initialize(new JavaInstallList(this, true)); ui->managedJavaList->setResizeOn(2); ui->managedJavaList->selectCurrent(); ui->managedJavaList->setEmptyString(tr("No managed Java versions are installed")); ui->managedJavaList->setEmptyErrorString(tr("Couldn't load the managed Java list!")); connect(ui->autodetectJavaCheckBox, &QCheckBox::stateChanged, this, [this] { ui->autodownloadCheckBox->setEnabled(ui->autodetectJavaCheckBox->isChecked()); if (!ui->autodetectJavaCheckBox->isChecked()) ui->autodownloadCheckBox->setChecked(false); }); } else { ui->autodownloadCheckBox->setHidden(true); ui->tabWidget->tabBar()->hide(); } loadSettings(); updateThresholds(); } JavaPage::~JavaPage() { delete ui; } bool JavaPage::apply() { applySettings(); return true; } void JavaPage::applySettings() { auto s = APPLICATION->settings(); // Memory int min = ui->minMemSpinBox->value(); int max = ui->maxMemSpinBox->value(); if (min < max) { s->set("MinMemAlloc", min); s->set("MaxMemAlloc", max); } else { s->set("MinMemAlloc", max); s->set("MaxMemAlloc", min); } s->set("PermGen", ui->permGenSpinBox->value()); // Java Settings s->set("JavaPath", ui->javaPathTextBox->text()); s->set("JvmArgs", ui->jvmArgsTextBox->toPlainText().replace("\n", " ")); s->set("IgnoreJavaCompatibility", ui->skipCompatibilityCheckbox->isChecked()); s->set("IgnoreJavaWizard", ui->skipJavaWizardCheckbox->isChecked()); s->set("AutomaticJavaSwitch", ui->autodetectJavaCheckBox->isChecked()); s->set("AutomaticJavaDownload", ui->autodownloadCheckBox->isChecked()); JavaCommon::checkJVMArgs(s->get("JvmArgs").toString(), this->parentWidget()); } void JavaPage::loadSettings() { auto s = APPLICATION->settings(); // Memory int min = s->get("MinMemAlloc").toInt(); int max = s->get("MaxMemAlloc").toInt(); if (min < max) { ui->minMemSpinBox->setValue(min); ui->maxMemSpinBox->setValue(max); } else { ui->minMemSpinBox->setValue(max); ui->maxMemSpinBox->setValue(min); } ui->permGenSpinBox->setValue(s->get("PermGen").toInt()); // Java Settings ui->javaPathTextBox->setText(s->get("JavaPath").toString()); ui->jvmArgsTextBox->setPlainText(s->get("JvmArgs").toString()); ui->skipCompatibilityCheckbox->setChecked(s->get("IgnoreJavaCompatibility").toBool()); ui->skipJavaWizardCheckbox->setChecked(s->get("IgnoreJavaWizard").toBool()); ui->autodetectJavaCheckBox->setChecked(s->get("AutomaticJavaSwitch").toBool()); ui->autodownloadCheckBox->setChecked(s->get("AutomaticJavaSwitch").toBool() && s->get("AutomaticJavaDownload").toBool()); } void JavaPage::on_javaDetectBtn_clicked() { if (JavaUtils::getJavaCheckPath().isEmpty()) { JavaCommon::javaCheckNotFound(this); return; } JavaInstallPtr java; VersionSelectDialog vselect(APPLICATION->javalist().get(), tr("Select a Java version"), this, true); vselect.setResizeOn(2); vselect.exec(); if (vselect.result() == QDialog::Accepted && vselect.selectedVersion()) { java = std::dynamic_pointer_cast<JavaInstall>(vselect.selectedVersion()); ui->javaPathTextBox->setText(java->path); if (!java->is_64bit && APPLICATION->settings()->get("MaxMemAlloc").toInt() > 2048) { CustomMessageBox::selectable(this, tr("Confirm Selection"), tr("You selected a 32-bit version of Java.\n" "This installation does not support more than 2048MiB of RAM.\n" "Please make sure that the maximum memory value is lower."), QMessageBox::Warning, QMessageBox::Ok, QMessageBox::Ok) ->exec(); } } } void JavaPage::on_javaBrowseBtn_clicked() { QString raw_path = QFileDialog::getOpenFileName(this, tr("Find Java executable")); // do not allow current dir - it's dirty. Do not allow dirs that don't exist if (raw_path.isEmpty()) { return; } QString cooked_path = FS::NormalizePath(raw_path); QFileInfo javaInfo(cooked_path); ; if (!javaInfo.exists() || !javaInfo.isExecutable()) { return; } ui->javaPathTextBox->setText(cooked_path); } void JavaPage::on_javaTestBtn_clicked() { if (checker) { return; } checker.reset(new JavaCommon::TestCheck(this, ui->javaPathTextBox->text(), ui->jvmArgsTextBox->toPlainText().replace("\n", " "), ui->minMemSpinBox->value(), ui->maxMemSpinBox->value(), ui->permGenSpinBox->value())); connect(checker.get(), SIGNAL(finished()), SLOT(checkerFinished())); checker->run(); } void JavaPage::on_downloadJavaButton_clicked() { auto jdialog = new Java::InstallDialog({}, nullptr, this); jdialog->exec(); ui->managedJavaList->loadList(); } void JavaPage::on_maxMemSpinBox_valueChanged([[maybe_unused]] int i) { updateThresholds(); } void JavaPage::checkerFinished() { checker.reset(); } void JavaPage::retranslate() { ui->retranslateUi(this); } void JavaPage::updateThresholds() { auto sysMiB = Sys::getSystemRam() / Sys::mebibyte; unsigned int maxMem = ui->maxMemSpinBox->value(); unsigned int minMem = ui->minMemSpinBox->value(); QString iconName; if (maxMem >= sysMiB) { iconName = "status-bad"; ui->labelMaxMemIcon->setToolTip(tr("Your maximum memory allocation exceeds your system memory capacity.")); } else if (maxMem > (sysMiB * 0.9)) { iconName = "status-yellow"; ui->labelMaxMemIcon->setToolTip(tr("Your maximum memory allocation approaches your system memory capacity.")); } else if (maxMem < minMem) { iconName = "status-yellow"; ui->labelMaxMemIcon->setToolTip(tr("Your maximum memory allocation is smaller than the minimum value")); } else { iconName = "status-good"; ui->labelMaxMemIcon->setToolTip(""); } { auto height = ui->labelMaxMemIcon->fontInfo().pixelSize(); QIcon icon = APPLICATION->getThemedIcon(iconName); QPixmap pix = icon.pixmap(height, height); ui->labelMaxMemIcon->setPixmap(pix); } } void JavaPage::on_removeJavaButton_clicked() { auto version = ui->managedJavaList->selectedVersion(); auto dcast = std::dynamic_pointer_cast<JavaInstall>(version); if (!dcast) { return; } QDir dir(APPLICATION->javaPath()); auto entries = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot); for (auto& entry : entries) { if (dcast->path.startsWith(entry.canonicalFilePath())) { auto response = CustomMessageBox::selectable(this, tr("Confirm Deletion"), tr("You are about to remove the Java installation named \"%1\".\n" "Are you sure?") .arg(entry.fileName()), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response == QMessageBox::Yes) { FS::deletePath(entry.canonicalFilePath()); ui->managedJavaList->loadList(); } break; } } } void JavaPage::on_refreshJavaButton_clicked() { ui->managedJavaList->loadList(); }
9,989
C++
.cpp
251
33.302789
132
0.652138
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,012
AccountListPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/global/AccountListPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "AccountListPage.h" #include "ui/dialogs/skins/SkinManageDialog.h" #include "ui_AccountListPage.h" #include <QItemSelectionModel> #include <QMenu> #include <QPushButton> #include <QDebug> #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/MSALoginDialog.h" #include "ui/dialogs/OfflineLoginDialog.h" #include "Application.h" AccountListPage::AccountListPage(QWidget* parent) : QMainWindow(parent), ui(new Ui::AccountListPage) { ui->setupUi(this); ui->listView->setEmptyString( tr("Welcome!\n" "If you're new here, you can select the \"Add Microsoft\" button to link your Microsoft account.")); ui->listView->setEmptyMode(VersionListView::String); ui->listView->setContextMenuPolicy(Qt::CustomContextMenu); m_accounts = APPLICATION->accounts(); ui->listView->setModel(m_accounts.get()); ui->listView->header()->setSectionResizeMode(AccountList::VListColumns::ProfileNameColumn, QHeaderView::Stretch); ui->listView->header()->setSectionResizeMode(AccountList::VListColumns::NameColumn, QHeaderView::Stretch); ui->listView->header()->setSectionResizeMode(AccountList::VListColumns::TypeColumn, QHeaderView::ResizeToContents); ui->listView->header()->setSectionResizeMode(AccountList::VListColumns::StatusColumn, QHeaderView::ResizeToContents); ui->listView->setSelectionMode(QAbstractItemView::SingleSelection); // Expand the account column QItemSelectionModel* selectionModel = ui->listView->selectionModel(); connect(selectionModel, &QItemSelectionModel::selectionChanged, [this]([[maybe_unused]] const QItemSelection& sel, [[maybe_unused]] const QItemSelection& dsel) { updateButtonStates(); }); connect(ui->listView, &VersionListView::customContextMenuRequested, this, &AccountListPage::ShowContextMenu); connect(ui->listView, &VersionListView::activated, this, [this](const QModelIndex& index) { m_accounts->setDefaultAccount(m_accounts->at(index.row())); }); connect(m_accounts.get(), &AccountList::listChanged, this, &AccountListPage::listChanged); connect(m_accounts.get(), &AccountList::listActivityChanged, this, &AccountListPage::listChanged); connect(m_accounts.get(), &AccountList::defaultAccountChanged, this, &AccountListPage::listChanged); updateButtonStates(); // Xbox authentication won't work without a client identifier, so disable the button if it is missing if (~APPLICATION->capabilities() & Application::SupportsMSA) { ui->actionAddMicrosoft->setVisible(false); ui->actionAddMicrosoft->setToolTip(tr("No Microsoft Authentication client ID was set.")); } } AccountListPage::~AccountListPage() { delete ui; } void AccountListPage::retranslate() { ui->retranslateUi(this); } void AccountListPage::ShowContextMenu(const QPoint& pos) { auto menu = ui->toolBar->createContextMenu(this, tr("Context menu")); menu->exec(ui->listView->mapToGlobal(pos)); delete menu; } void AccountListPage::changeEvent(QEvent* event) { if (event->type() == QEvent::LanguageChange) { ui->retranslateUi(this); } QMainWindow::changeEvent(event); } QMenu* AccountListPage::createPopupMenu() { QMenu* filteredMenu = QMainWindow::createPopupMenu(); filteredMenu->removeAction(ui->toolBar->toggleViewAction()); return filteredMenu; } void AccountListPage::listChanged() { updateButtonStates(); } void AccountListPage::on_actionAddMicrosoft_triggered() { auto account = MSALoginDialog::newAccount(this); if (account) { m_accounts->addAccount(account); if (m_accounts->count() == 1) { m_accounts->setDefaultAccount(account); } } } void AccountListPage::on_actionAddOffline_triggered() { if (!m_accounts->anyAccountIsValid()) { QMessageBox::warning(this, tr("Error"), tr("You must add a Microsoft account that owns Minecraft before you can add an offline account." "<br><br>" "If you have lost your account you can contact Microsoft for support.")); return; } MinecraftAccountPtr account = OfflineLoginDialog::newAccount(this, tr("Please enter your desired username to add your offline account.")); if (account) { m_accounts->addAccount(account); if (m_accounts->count() == 1) { m_accounts->setDefaultAccount(account); } } } void AccountListPage::on_actionRemove_triggered() { auto response = CustomMessageBox::selectable(this, tr("Remove account?"), tr("Do you really want to delete this account?"), QMessageBox::Question, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response != QMessageBox::Yes) { return; } QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes(); if (selection.size() > 0) { QModelIndex selected = selection.first(); m_accounts->removeAccount(selected); } } void AccountListPage::on_actionRefresh_triggered() { QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes(); if (selection.size() > 0) { QModelIndex selected = selection.first(); MinecraftAccountPtr account = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>(); m_accounts->requestRefresh(account->internalId()); } } void AccountListPage::on_actionSetDefault_triggered() { QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes(); if (selection.size() > 0) { QModelIndex selected = selection.first(); MinecraftAccountPtr account = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>(); m_accounts->setDefaultAccount(account); } } void AccountListPage::on_actionNoDefault_triggered() { m_accounts->setDefaultAccount(nullptr); } void AccountListPage::updateButtonStates() { // If there is no selection, disable buttons that require something selected. QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes(); bool hasSelection = !selection.empty(); bool accountIsReady = false; bool accountIsOnline = false; if (hasSelection) { QModelIndex selected = selection.first(); MinecraftAccountPtr account = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>(); accountIsReady = !account->isActive(); accountIsOnline = account->accountType() != AccountType::Offline; } ui->actionRemove->setEnabled(accountIsReady); ui->actionSetDefault->setEnabled(accountIsReady); ui->actionManageSkins->setEnabled(accountIsReady && accountIsOnline); ui->actionRefresh->setEnabled(accountIsReady && accountIsOnline); if (m_accounts->defaultAccount().get() == nullptr) { ui->actionNoDefault->setEnabled(false); ui->actionNoDefault->setChecked(true); } else { ui->actionNoDefault->setEnabled(true); ui->actionNoDefault->setChecked(false); } ui->listView->resizeColumnToContents(3); } void AccountListPage::on_actionManageSkins_triggered() { QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes(); if (selection.size() > 0) { QModelIndex selected = selection.first(); MinecraftAccountPtr account = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>(); SkinManageDialog dialog(this, account); dialog.exec(); } }
9,146
C++
.cpp
209
38.660287
135
0.715585
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,014
LanguagePage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/global/LanguagePage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "LanguagePage.h" #include <QVBoxLayout> #include "ui/widgets/LanguageSelectionWidget.h" LanguagePage::LanguagePage(QWidget* parent) : QWidget(parent) { setObjectName(QStringLiteral("languagePage")); auto layout = new QVBoxLayout(this); mainWidget = new LanguageSelectionWidget(this); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(mainWidget); retranslate(); } LanguagePage::~LanguagePage() {} bool LanguagePage::apply() { applySettings(); return true; } void LanguagePage::applySettings() { auto settings = APPLICATION->settings(); QString key = mainWidget->getSelectedLanguageKey(); settings->set("Language", key); } void LanguagePage::loadSettings() { // NIL } void LanguagePage::retranslate() { mainWidget->retranslate(); }
2,366
C++
.cpp
67
32.925373
80
0.736796
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,015
CustomCommandsPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/global/CustomCommandsPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CustomCommandsPage.h" #include <QTabBar> #include <QTabWidget> #include <QVBoxLayout> CustomCommandsPage::CustomCommandsPage(QWidget* parent) : QWidget(parent) { auto verticalLayout = new QVBoxLayout(this); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); auto tabWidget = new QTabWidget(this); tabWidget->setObjectName(QStringLiteral("tabWidget")); commands = new CustomCommands(this); commands->setContentsMargins(6, 6, 6, 6); tabWidget->addTab(commands, "Foo"); tabWidget->tabBar()->hide(); verticalLayout->addWidget(tabWidget); loadSettings(); } CustomCommandsPage::~CustomCommandsPage() {} bool CustomCommandsPage::apply() { applySettings(); return true; } void CustomCommandsPage::applySettings() { auto s = APPLICATION->settings(); s->set("PreLaunchCommand", commands->prelaunchCommand()); s->set("WrapperCommand", commands->wrapperCommand()); s->set("PostExitCommand", commands->postexitCommand()); } void CustomCommandsPage::loadSettings() { auto s = APPLICATION->settings(); commands->initialize(false, true, s->get("PreLaunchCommand").toString(), s->get("WrapperCommand").toString(), s->get("PostExitCommand").toString()); } void CustomCommandsPage::retranslate() { commands->retranslate(); }
2,949
C++
.cpp
76
35.881579
113
0.73089
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,016
MinecraftPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/global/MinecraftPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MinecraftPage.h" #include "BuildConfig.h" #include "ui_MinecraftPage.h" #include <QDir> #include <QMessageBox> #include <QTabBar> #include "Application.h" #include "settings/SettingsObject.h" #ifdef Q_OS_LINUX #include "MangoHud.h" #endif MinecraftPage::MinecraftPage(QWidget* parent) : QWidget(parent), ui(new Ui::MinecraftPage) { ui->setupUi(this); connect(ui->useNativeGLFWCheck, &QAbstractButton::toggled, this, &MinecraftPage::onUseNativeGLFWChanged); connect(ui->useNativeOpenALCheck, &QAbstractButton::toggled, this, &MinecraftPage::onUseNativeOpenALChanged); loadSettings(); updateCheckboxStuff(); } MinecraftPage::~MinecraftPage() { delete ui; } bool MinecraftPage::apply() { applySettings(); return true; } void MinecraftPage::updateCheckboxStuff() { ui->windowWidthSpinBox->setEnabled(!ui->maximizedCheckBox->isChecked()); ui->windowHeightSpinBox->setEnabled(!ui->maximizedCheckBox->isChecked()); } void MinecraftPage::on_maximizedCheckBox_clicked(bool checked) { Q_UNUSED(checked); updateCheckboxStuff(); } void MinecraftPage::onUseNativeGLFWChanged(bool checked) { ui->lineEditGLFWPath->setEnabled(checked); } void MinecraftPage::onUseNativeOpenALChanged(bool checked) { ui->lineEditOpenALPath->setEnabled(checked); } void MinecraftPage::applySettings() { auto s = APPLICATION->settings(); // Window Size s->set("LaunchMaximized", ui->maximizedCheckBox->isChecked()); s->set("MinecraftWinWidth", ui->windowWidthSpinBox->value()); s->set("MinecraftWinHeight", ui->windowHeightSpinBox->value()); // Native library workarounds s->set("UseNativeGLFW", ui->useNativeGLFWCheck->isChecked()); s->set("CustomGLFWPath", ui->lineEditGLFWPath->text()); s->set("UseNativeOpenAL", ui->useNativeOpenALCheck->isChecked()); s->set("CustomOpenALPath", ui->lineEditOpenALPath->text()); // Peformance related options s->set("EnableFeralGamemode", ui->enableFeralGamemodeCheck->isChecked()); s->set("EnableMangoHud", ui->enableMangoHud->isChecked()); s->set("UseDiscreteGpu", ui->useDiscreteGpuCheck->isChecked()); s->set("UseZink", ui->useZink->isChecked()); // Game time s->set("ShowGameTime", ui->showGameTime->isChecked()); s->set("ShowGlobalGameTime", ui->showGlobalGameTime->isChecked()); s->set("RecordGameTime", ui->recordGameTime->isChecked()); s->set("ShowGameTimeWithoutDays", ui->showGameTimeWithoutDays->isChecked()); // Miscellaneous s->set("CloseAfterLaunch", ui->closeAfterLaunchCheck->isChecked()); s->set("QuitAfterGameStop", ui->quitAfterGameStopCheck->isChecked()); // Legacy settings s->set("OnlineFixes", ui->onlineFixes->isChecked()); } void MinecraftPage::loadSettings() { auto s = APPLICATION->settings(); // Window Size ui->maximizedCheckBox->setChecked(s->get("LaunchMaximized").toBool()); ui->windowWidthSpinBox->setValue(s->get("MinecraftWinWidth").toInt()); ui->windowHeightSpinBox->setValue(s->get("MinecraftWinHeight").toInt()); ui->useNativeGLFWCheck->setChecked(s->get("UseNativeGLFW").toBool()); ui->lineEditGLFWPath->setText(s->get("CustomGLFWPath").toString()); ui->lineEditGLFWPath->setPlaceholderText(tr("Path to %1 library file").arg(BuildConfig.GLFW_LIBRARY_NAME)); #ifdef Q_OS_LINUX if (!APPLICATION->m_detectedGLFWPath.isEmpty()) ui->lineEditGLFWPath->setPlaceholderText(tr("Auto detected path: %1").arg(APPLICATION->m_detectedGLFWPath)); #endif ui->useNativeOpenALCheck->setChecked(s->get("UseNativeOpenAL").toBool()); ui->lineEditOpenALPath->setText(s->get("CustomOpenALPath").toString()); ui->lineEditOpenALPath->setPlaceholderText(tr("Path to %1 library file").arg(BuildConfig.OPENAL_LIBRARY_NAME)); #ifdef Q_OS_LINUX if (!APPLICATION->m_detectedOpenALPath.isEmpty()) ui->lineEditOpenALPath->setPlaceholderText(tr("Auto detected path: %1").arg(APPLICATION->m_detectedOpenALPath)); #endif ui->enableFeralGamemodeCheck->setChecked(s->get("EnableFeralGamemode").toBool()); ui->enableMangoHud->setChecked(s->get("EnableMangoHud").toBool()); ui->useDiscreteGpuCheck->setChecked(s->get("UseDiscreteGpu").toBool()); ui->useZink->setChecked(s->get("UseZink").toBool()); #if !defined(Q_OS_LINUX) ui->perfomanceGroupBox->setVisible(false); #endif if (!(APPLICATION->capabilities() & Application::SupportsGameMode)) { ui->enableFeralGamemodeCheck->setDisabled(true); ui->enableFeralGamemodeCheck->setToolTip(tr("Feral Interactive's GameMode could not be found on your system.")); } if (!(APPLICATION->capabilities() & Application::SupportsMangoHud)) { ui->enableMangoHud->setDisabled(true); ui->enableMangoHud->setToolTip(tr("MangoHud could not be found on your system.")); } ui->showGameTime->setChecked(s->get("ShowGameTime").toBool()); ui->showGlobalGameTime->setChecked(s->get("ShowGlobalGameTime").toBool()); ui->recordGameTime->setChecked(s->get("RecordGameTime").toBool()); ui->showGameTimeWithoutDays->setChecked(s->get("ShowGameTimeWithoutDays").toBool()); ui->closeAfterLaunchCheck->setChecked(s->get("CloseAfterLaunch").toBool()); ui->quitAfterGameStopCheck->setChecked(s->get("QuitAfterGameStop").toBool()); ui->onlineFixes->setChecked(s->get("OnlineFixes").toBool()); } void MinecraftPage::retranslate() { ui->retranslateUi(this); }
6,936
C++
.cpp
156
40.99359
120
0.735447
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,017
APIPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/pages/global/APIPage.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright (c) 2022 Lenny McLennington <lenny@sneed.church> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "APIPage.h" #include "ui_APIPage.h" #include <QFileDialog> #include <QMessageBox> #include <QRegularExpression> #include <QStandardPaths> #include <QTabBar> #include <QValidator> #include <QVariant> #include "Application.h" #include "BuildConfig.h" #include "net/PasteUpload.h" #include "settings/SettingsObject.h" #include "tools/BaseProfiler.h" APIPage::APIPage(QWidget* parent) : QWidget(parent), ui(new Ui::APIPage) { // This is here so you can reorder the entries in the combobox without messing stuff up int comboBoxEntries[] = { PasteUpload::PasteType::Mclogs, PasteUpload::PasteType::NullPointer, PasteUpload::PasteType::PasteGG, PasteUpload::PasteType::Hastebin }; static QRegularExpression validUrlRegExp("https?://.+"); static QRegularExpression validMSAClientID( QRegularExpression::anchoredPattern("[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}")); static QRegularExpression validFlameKey(QRegularExpression::anchoredPattern("\\$2[ayb]\\$.{56}")); ui->setupUi(this); for (auto pasteType : comboBoxEntries) { ui->pasteTypeComboBox->addItem(PasteUpload::PasteTypes.at(pasteType).name, pasteType); } void (QComboBox::*currentIndexChangedSignal)(int)(&QComboBox::currentIndexChanged); connect(ui->pasteTypeComboBox, currentIndexChangedSignal, this, &APIPage::updateBaseURLPlaceholder); // This function needs to be called even when the ComboBox's index is still in its default state. updateBaseURLPlaceholder(ui->pasteTypeComboBox->currentIndex()); // NOTE: this allows http://, but we replace that with https later anyway ui->metaURL->setValidator(new QRegularExpressionValidator(validUrlRegExp, ui->metaURL)); ui->baseURLEntry->setValidator(new QRegularExpressionValidator(validUrlRegExp, ui->baseURLEntry)); ui->msaClientID->setValidator(new QRegularExpressionValidator(validMSAClientID, ui->msaClientID)); ui->flameKey->setValidator(new QRegularExpressionValidator(validFlameKey, ui->flameKey)); ui->metaURL->setPlaceholderText(BuildConfig.META_URL); ui->userAgentLineEdit->setPlaceholderText(BuildConfig.USER_AGENT); loadSettings(); resetBaseURLNote(); connect(ui->pasteTypeComboBox, currentIndexChangedSignal, this, &APIPage::updateBaseURLNote); connect(ui->baseURLEntry, &QLineEdit::textEdited, this, &APIPage::resetBaseURLNote); } APIPage::~APIPage() { delete ui; } void APIPage::resetBaseURLNote() { ui->baseURLNote->hide(); baseURLPasteType = ui->pasteTypeComboBox->currentIndex(); } void APIPage::updateBaseURLNote(int index) { if (baseURLPasteType == index) { ui->baseURLNote->hide(); } else if (!ui->baseURLEntry->text().isEmpty()) { ui->baseURLNote->show(); } } void APIPage::updateBaseURLPlaceholder(int index) { int pasteType = ui->pasteTypeComboBox->itemData(index).toInt(); QString pasteDefaultURL = PasteUpload::PasteTypes.at(pasteType).defaultBase; ui->baseURLEntry->setPlaceholderText(pasteDefaultURL); } void APIPage::loadSettings() { auto s = APPLICATION->settings(); int pasteType = s->get("PastebinType").toInt(); QString pastebinURL = s->get("PastebinCustomAPIBase").toString(); ui->baseURLEntry->setText(pastebinURL); int pasteTypeIndex = ui->pasteTypeComboBox->findData(pasteType); if (pasteTypeIndex == -1) { pasteTypeIndex = ui->pasteTypeComboBox->findData(PasteUpload::PasteType::Mclogs); ui->baseURLEntry->clear(); } ui->pasteTypeComboBox->setCurrentIndex(pasteTypeIndex); QString msaClientID = s->get("MSAClientIDOverride").toString(); ui->msaClientID->setText(msaClientID); QString metaURL = s->get("MetaURLOverride").toString(); ui->metaURL->setText(metaURL); QString flameKey = s->get("FlameKeyOverride").toString(); ui->flameKey->setText(flameKey); QString modrinthToken = s->get("ModrinthToken").toString(); ui->modrinthToken->setText(modrinthToken); QString customUserAgent = s->get("UserAgentOverride").toString(); ui->userAgentLineEdit->setText(customUserAgent); ui->technicClientID->setText(s->get("TechnicClientID").toString()); } void APIPage::applySettings() { auto s = APPLICATION->settings(); s->set("PastebinType", ui->pasteTypeComboBox->currentData().toInt()); s->set("PastebinCustomAPIBase", ui->baseURLEntry->text()); QString msaClientID = ui->msaClientID->text(); s->set("MSAClientIDOverride", msaClientID); QUrl metaURL(ui->metaURL->text()); // Add required trailing slash if (!metaURL.isEmpty() && !metaURL.path().endsWith('/')) { QString path = metaURL.path(); path.append('/'); metaURL.setPath(path); } // Don't allow HTTP, since meta is basically RCE with all the jar files. if (!metaURL.isEmpty() && metaURL.scheme() == "http") { metaURL.setScheme("https"); } s->set("MetaURLOverride", metaURL.toString()); QString flameKey = ui->flameKey->text(); s->set("FlameKeyOverride", flameKey); QString modrinthToken = ui->modrinthToken->text(); s->set("ModrinthToken", modrinthToken); s->set("UserAgentOverride", ui->userAgentLineEdit->text()); s->set("TechnicClientID", ui->technicClientID->text()); } bool APIPage::apply() { applySettings(); return true; } void APIPage::retranslate() { ui->retranslateUi(this); }
7,114
C++
.cpp
162
40.055556
131
0.725816
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,019
AboutDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/AboutDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "AboutDialog.h" #include <QIcon> #include "Application.h" #include "BuildConfig.h" #include "Markdown.h" #include "StringUtils.h" #include "ui_AboutDialog.h" #include <net/NetJob.h> #include <qobject.h> namespace { QString getLink(QString link, QString name) { return QString("&lt;<a href='%1'>%2</a>&gt;").arg(link).arg(name); } QString getWebsite(QString link) { return getLink(link, QObject::tr("Website")); } QString getGitHub(QString username) { return getLink("https://github.com/" + username, "GitHub"); } // Credits // This is a hack, but I can't think of a better way to do this easily without screwing with QTextDocument... QString getCreditsHtml() { QString output; QTextStream stream(&output); #if QT_VERSION <= QT_VERSION_CHECK(6, 0, 0) stream.setCodec(QTextCodec::codecForName("UTF-8")); #endif stream << "<center>\n"; //: %1 is the name of the launcher, determined at build time, e.g. "Prism Launcher Developers" stream << "<h3>" << QObject::tr("%1 Developers", "About Credits").arg(BuildConfig.LAUNCHER_DISPLAYNAME) << "</h3>\n"; stream << QString("<p>Sefa Eyeoglu (Scrumplex) %1</p>\n").arg(getWebsite("https://scrumplex.net")); stream << QString("<p>d-513 %1</p>\n").arg(getGitHub("d-513")); stream << QString("<p>txtsd %1</p>\n").arg(getWebsite("https://ihavea.quest")); stream << QString("<p>timoreo %1</p>\n").arg(getGitHub("timoreo22")); stream << QString("<p>ZekeZ %1</p>\n").arg(getGitHub("ZekeZDev")); stream << QString("<p>cozyGalvinism %1</p>\n").arg(getGitHub("cozyGalvinism")); stream << QString("<p>DioEgizio %1</p>\n").arg(getGitHub("DioEgizio")); stream << QString("<p>flowln %1</p>\n").arg(getGitHub("flowln")); stream << QString("<p>ViRb3 %1</p>\n").arg(getGitHub("ViRb3")); stream << QString("<p>Rachel Powers (Ryex) %1</p>\n").arg(getGitHub("Ryex")); stream << QString("<p>TayouVR %1</p>\n").arg(getGitHub("TayouVR")); stream << QString("<p>TheKodeToad %1</p>\n").arg(getGitHub("TheKodeToad")); stream << QString("<p>getchoo %1</p>\n").arg(getGitHub("getchoo")); stream << QString("<p>Alexandru Tripon (Trial97) %1</p>\n").arg(getGitHub("Trial97")); stream << "<br />\n"; // TODO: possibly retrieve from git history at build time? //: %1 is the name of the launcher, determined at build time, e.g. "Prism Launcher Developers" stream << "<h3>" << QObject::tr("%1 Developers", "About Credits").arg("MultiMC") << "</h3>\n"; stream << "<p>Andrew Okin &lt;<a href='mailto:forkk@forkk.net'>forkk@forkk.net</a>&gt;</p>\n"; stream << QString("<p>Petr Mr√°zek &lt;<a href='mailto:peterix@gmail.com'>peterix@gmail.com</a>&gt;</p>\n"); stream << "<p>Sky Welch &lt;<a href='mailto:multimc@bunnies.io'>multimc@bunnies.io</a>&gt;</p>\n"; stream << "<p>Jan (02JanDal) &lt;<a href='mailto:02jandal@gmail.com'>02jandal@gmail.com</a>&gt;</p>\n"; stream << "<p>RoboSky &lt;<a href='https://twitter.com/RoboSky_'>@RoboSky_</a>&gt;</p>\n"; stream << "<br />\n"; stream << "<h3>" << QObject::tr("With thanks to", "About Credits") << "</h3>\n"; stream << QString("<p>Boba %1</p>\n").arg(getWebsite("https://bobaonline.neocities.org/")); stream << QString("<p>AutiOne %1</p>\n").arg(getWebsite("https://auti.one/")); stream << QString("<p>Fulmine %1</p>\n").arg(getWebsite("https://fulmine.xyz/")); stream << QString("<p>ely %1</p>\n").arg(getGitHub("elyrodso")); stream << QString("<p>gon sawa %1</p>\n").arg(getGitHub("gonsawa")); stream << QString("<p>Pankakes</p>\n"); stream << QString("<p>tobimori %1</p>\n").arg(getGitHub("tobimori")); stream << "<p>Orochimarufan &lt;<a href='mailto:orochimarufan.x3@gmail.com'>orochimarufan.x3@gmail.com</a>&gt;</p>\n"; stream << "<p>TakSuyu &lt;<a href='mailto:taksuyu@gmail.com'>taksuyu@gmail.com</a>&gt;</p>\n"; stream << "<p>Kilobyte &lt;<a href='mailto:stiepen22@gmx.de'>stiepen22@gmx.de</a>&gt;</p>\n"; stream << "<p>Rootbear75 &lt;<a href='https://twitter.com/rootbear75'>@rootbear75</a>&gt;</p>\n"; stream << "<p>Zeker Zhayard &lt;<a href='https://twitter.com/zeker_zhayard'>@Zeker_Zhayard</a>&gt;</p>\n"; stream << "<p>Everyone who helped establish our branding!</p>\n"; stream << "<p>And everyone else who <a href='https://github.com/PrismLauncher/PrismLauncher/graphs/contributors'>contributed</a>!</p>\n"; stream << "<br />\n"; stream << "</center>\n"; return output; } QString getLicenseHtml() { QFile dataFile(":/documents/COPYING.md"); dataFile.open(QIODevice::ReadOnly); QString output = markdownToHTML(dataFile.readAll()); return output; } } // namespace AboutDialog::AboutDialog(QWidget* parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); QString launcherName = BuildConfig.LAUNCHER_DISPLAYNAME; setWindowTitle(tr("About %1").arg(launcherName)); QString chtml = getCreditsHtml(); ui->creditsText->setHtml(StringUtils::htmlListPatch(chtml)); QString lhtml = getLicenseHtml(); ui->licenseText->setHtml(StringUtils::htmlListPatch(lhtml)); ui->urlLabel->setOpenExternalLinks(true); ui->icon->setPixmap(APPLICATION->getThemedIcon("logo").pixmap(64)); ui->title->setText(launcherName); ui->versionLabel->setText(BuildConfig.printableVersionString()); if (!BuildConfig.BUILD_PLATFORM.isEmpty()) ui->platformLabel->setText(tr("Platform") + ": " + BuildConfig.BUILD_PLATFORM); else ui->platformLabel->setVisible(false); if (!BuildConfig.GIT_COMMIT.isEmpty()) ui->commitLabel->setText(tr("Commit: %1").arg(BuildConfig.GIT_COMMIT)); else ui->commitLabel->setVisible(false); if (!BuildConfig.BUILD_DATE.isEmpty()) ui->buildDateLabel->setText(tr("Build date: %1").arg(BuildConfig.BUILD_DATE)); else ui->buildDateLabel->setVisible(false); if (!BuildConfig.VERSION_CHANNEL.isEmpty()) ui->channelLabel->setText(tr("Channel") + ": " + BuildConfig.VERSION_CHANNEL); else ui->channelLabel->setVisible(false); QString urlText("<html><head/><body><p><a href=\"%1\">%1</a></p></body></html>"); ui->urlLabel->setText(urlText.arg(BuildConfig.LAUNCHER_GIT)); ui->copyLabel->setText(BuildConfig.LAUNCHER_COPYRIGHT); connect(ui->closeButton, SIGNAL(clicked()), SLOT(close())); connect(ui->aboutQt, &QPushButton::clicked, &QApplication::aboutQt); } AboutDialog::~AboutDialog() { delete ui; }
7,981
C++
.cpp
159
46.345912
138
0.672655
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,020
NewComponentDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/NewComponentDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "NewComponentDialog.h" #include "Application.h" #include "ui_NewComponentDialog.h" #include <BaseVersion.h> #include <InstanceList.h> #include <icons/IconList.h> #include <tasks/Task.h> #include "IconPickerDialog.h" #include "ProgressDialog.h" #include "VersionSelectDialog.h" #include <QFileDialog> #include <QLayout> #include <QPushButton> #include <QValidator> #include <meta/Index.h> #include <meta/VersionList.h> NewComponentDialog::NewComponentDialog(const QString& initialName, const QString& initialUid, QWidget* parent) : QDialog(parent), ui(new Ui::NewComponentDialog) { ui->setupUi(this); resize(minimumSizeHint()); ui->nameTextBox->setText(initialName); ui->uidTextBox->setText(initialUid); connect(ui->nameTextBox, &QLineEdit::textChanged, this, &NewComponentDialog::updateDialogState); connect(ui->uidTextBox, &QLineEdit::textChanged, this, &NewComponentDialog::updateDialogState); ui->nameTextBox->setFocus(); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); originalPlaceholderText = ui->uidTextBox->placeholderText(); updateDialogState(); } NewComponentDialog::~NewComponentDialog() { delete ui; } void NewComponentDialog::updateDialogState() { auto protoUid = ui->nameTextBox->text().toLower(); protoUid.remove(QRegularExpression("[^a-z]")); if (protoUid.isEmpty()) { ui->uidTextBox->setPlaceholderText(originalPlaceholderText); } else { QString suggestedUid = "org.multimc.custom." + protoUid; ui->uidTextBox->setPlaceholderText(suggestedUid); } bool allowOK = !name().isEmpty() && !uid().isEmpty() && !uidBlacklist.contains(uid()); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(allowOK); } QString NewComponentDialog::name() const { auto result = ui->nameTextBox->text(); if (result.size()) { return result.trimmed(); } return QString(); } QString NewComponentDialog::uid() const { auto result = ui->uidTextBox->text(); if (result.size()) { return result.trimmed(); } result = ui->uidTextBox->placeholderText(); if (result.size() && result != originalPlaceholderText) { return result.trimmed(); } return QString(); } void NewComponentDialog::setBlacklist(QStringList badUids) { uidBlacklist = badUids; }
3,915
C++
.cpp
106
33.820755
110
0.72792
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,021
ScrollMessageBox.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ScrollMessageBox.cpp
#include "ScrollMessageBox.h" #include <QPushButton> #include "ui_ScrollMessageBox.h" ScrollMessageBox::ScrollMessageBox(QWidget* parent, const QString& title, const QString& text, const QString& body) : QDialog(parent), ui(new Ui::ScrollMessageBox) { ui->setupUi(this); this->setWindowTitle(title); ui->label->setText(text); ui->textBrowser->setText(body); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } ScrollMessageBox::~ScrollMessageBox() { delete ui; }
584
C++
.cpp
17
31.294118
115
0.737589
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,022
ProfileSetupDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ProfileSetupDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ProfileSetupDialog.h" #include "net/RawHeaderProxy.h" #include "ui_ProfileSetupDialog.h" #include <QAction> #include <QDebug> #include <QJsonDocument> #include <QPushButton> #include <QRegularExpressionValidator> #include "ui/dialogs/ProgressDialog.h" #include <Application.h> #include "minecraft/auth/Parsers.h" #include "net/Upload.h" ProfileSetupDialog::ProfileSetupDialog(MinecraftAccountPtr accountToSetup, QWidget* parent) : QDialog(parent), m_accountToSetup(accountToSetup), ui(new Ui::ProfileSetupDialog) { ui->setupUi(this); ui->errorLabel->setVisible(false); goodIcon = APPLICATION->getThemedIcon("status-good"); yellowIcon = APPLICATION->getThemedIcon("status-yellow"); badIcon = APPLICATION->getThemedIcon("status-bad"); QRegularExpression permittedNames("[a-zA-Z0-9_]{3,16}"); auto nameEdit = ui->nameEdit; nameEdit->setValidator(new QRegularExpressionValidator(permittedNames)); nameEdit->setClearButtonEnabled(true); validityAction = nameEdit->addAction(yellowIcon, QLineEdit::LeadingPosition); connect(nameEdit, &QLineEdit::textEdited, this, &ProfileSetupDialog::nameEdited); checkStartTimer.setSingleShot(true); connect(&checkStartTimer, &QTimer::timeout, this, &ProfileSetupDialog::startCheck); setNameStatus(NameStatus::NotSet, QString()); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } ProfileSetupDialog::~ProfileSetupDialog() { delete ui; } void ProfileSetupDialog::on_buttonBox_accepted() { setupProfile(currentCheck); } void ProfileSetupDialog::on_buttonBox_rejected() { reject(); } void ProfileSetupDialog::setNameStatus(ProfileSetupDialog::NameStatus status, QString errorString = QString()) { nameStatus = status; auto okButton = ui->buttonBox->button(QDialogButtonBox::Ok); switch (nameStatus) { case NameStatus::Available: { validityAction->setIcon(goodIcon); okButton->setEnabled(true); } break; case NameStatus::NotSet: case NameStatus::Pending: validityAction->setIcon(yellowIcon); okButton->setEnabled(false); break; case NameStatus::Exists: case NameStatus::Error: validityAction->setIcon(badIcon); okButton->setEnabled(false); break; } if (!errorString.isEmpty()) { ui->errorLabel->setText(errorString); ui->errorLabel->setVisible(true); } else { ui->errorLabel->setVisible(false); } } void ProfileSetupDialog::nameEdited(const QString& name) { if (!ui->nameEdit->hasAcceptableInput()) { setNameStatus(NameStatus::NotSet, tr("Name is too short - must be between 3 and 16 characters long.")); return; } scheduleCheck(name); } void ProfileSetupDialog::scheduleCheck(const QString& name) { queuedCheck = name; setNameStatus(NameStatus::Pending); checkStartTimer.start(1000); } void ProfileSetupDialog::startCheck() { if (isChecking) { return; } if (queuedCheck.isNull()) { return; } checkName(queuedCheck); } void ProfileSetupDialog::checkName(const QString& name) { if (isChecking) { return; } currentCheck = name; isChecking = true; QUrl url(QString("https://api.minecraftservices.com/minecraft/profile/name/%1/available").arg(name)); auto headers = QList<Net::HeaderPair>{ { "Content-Type", "application/json" }, { "Accept", "application/json" }, { "Authorization", QString("Bearer %1").arg(m_accountToSetup->accessToken()).toUtf8() } }; m_check_response.reset(new QByteArray()); if (m_check_task) disconnect(m_check_task.get(), nullptr, this, nullptr); m_check_task = Net::Download::makeByteArray(url, m_check_response); m_check_task->addHeaderProxy(new Net::RawHeaderProxy(headers)); connect(m_check_task.get(), &Task::finished, this, &ProfileSetupDialog::checkFinished); m_check_task->setNetwork(APPLICATION->network()); m_check_task->start(); } void ProfileSetupDialog::checkFinished() { if (m_check_task->error() == QNetworkReply::NoError) { auto doc = QJsonDocument::fromJson(*m_check_response); auto root = doc.object(); auto statusValue = root.value("status").toString("INVALID"); if (statusValue == "AVAILABLE") { setNameStatus(NameStatus::Available); } else if (statusValue == "DUPLICATE") { setNameStatus(NameStatus::Exists, tr("Minecraft profile with name %1 already exists.").arg(currentCheck)); } else if (statusValue == "NOT_ALLOWED") { setNameStatus(NameStatus::Exists, tr("The name %1 is not allowed.").arg(currentCheck)); } else { setNameStatus(NameStatus::Error, tr("Unhandled profile name status: %1").arg(statusValue)); } } else { setNameStatus(NameStatus::Error, tr("Failed to check name availability.")); } isChecking = false; } void ProfileSetupDialog::setupProfile(const QString& profileName) { if (isWorking) { return; } QString payloadTemplate("{\"profileName\":\"%1\"}"); QUrl url("https://api.minecraftservices.com/minecraft/profile"); auto headers = QList<Net::HeaderPair>{ { "Content-Type", "application/json" }, { "Accept", "application/json" }, { "Authorization", QString("Bearer %1").arg(m_accountToSetup->accessToken()).toUtf8() } }; m_profile_response.reset(new QByteArray()); m_profile_task = Net::Upload::makeByteArray(url, m_profile_response, payloadTemplate.arg(profileName).toUtf8()); m_profile_task->addHeaderProxy(new Net::RawHeaderProxy(headers)); connect(m_profile_task.get(), &Task::finished, this, &ProfileSetupDialog::setupProfileFinished); m_profile_task->setNetwork(APPLICATION->network()); m_profile_task->start(); isWorking = true; auto button = ui->buttonBox->button(QDialogButtonBox::Cancel); button->setEnabled(false); } namespace { struct MojangError { static MojangError fromJSON(QByteArray data) { MojangError out; out.error = QString::fromUtf8(data); auto doc = QJsonDocument::fromJson(data, &out.parseError); auto object = doc.object(); out.fullyParsed = true; out.fullyParsed &= Parsers::getString(object.value("path"), out.path); out.fullyParsed &= Parsers::getString(object.value("error"), out.error); out.fullyParsed &= Parsers::getString(object.value("errorMessage"), out.errorMessage); return out; } QString rawError; QJsonParseError parseError; bool fullyParsed; QString path; QString error; QString errorMessage; }; } // namespace void ProfileSetupDialog::setupProfileFinished() { isWorking = false; if (m_profile_task->error() == QNetworkReply::NoError) { /* * data contains the profile in the response * ... we could parse it and update the account, but let's just return back to the normal login flow instead... */ accept(); } else { auto parsedError = MojangError::fromJSON(*m_profile_response); ui->errorLabel->setVisible(true); ui->errorLabel->setText(tr("The server returned the following error:") + "\n\n" + parsedError.errorMessage); qDebug() << parsedError.rawError; auto button = ui->buttonBox->button(QDialogButtonBox::Cancel); button->setEnabled(true); } }
9,215
C++
.cpp
229
34.528384
133
0.685222
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,023
NewsDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/NewsDialog.cpp
#include "NewsDialog.h" #include "ui_NewsDialog.h" NewsDialog::NewsDialog(QList<NewsEntryPtr> entries, QWidget* parent) : QDialog(parent), ui(new Ui::NewsDialog()) { ui->setupUi(this); for (auto entry : entries) { ui->articleListWidget->addItem(entry->title); m_entries.insert(entry->title, entry); } connect(ui->articleListWidget, &QListWidget::currentTextChanged, this, &NewsDialog::selectedArticleChanged); connect(ui->toggleListButton, &QPushButton::clicked, this, &NewsDialog::toggleArticleList); m_article_list_hidden = ui->articleListWidget->isHidden(); auto first_item = ui->articleListWidget->item(0); first_item->setSelected(true); auto article_entry = m_entries.constFind(first_item->text()).value(); ui->articleTitleLabel->setText(QString("<a href='%1'>%2</a>").arg(article_entry->link, first_item->text())); ui->currentArticleContentBrowser->setText(article_entry->content); ui->currentArticleContentBrowser->flush(); } NewsDialog::~NewsDialog() { delete ui; } void NewsDialog::selectedArticleChanged(const QString& new_title) { auto article_entry = m_entries.constFind(new_title).value(); ui->articleTitleLabel->setText(QString("<a href='%1'>%2</a>").arg(article_entry->link, new_title)); ui->currentArticleContentBrowser->setText(article_entry->content); ui->currentArticleContentBrowser->flush(); } void NewsDialog::toggleArticleList() { m_article_list_hidden = !m_article_list_hidden; ui->articleListWidget->setHidden(m_article_list_hidden); if (m_article_list_hidden) ui->toggleListButton->setText(tr("Show article list")); else ui->toggleListButton->setText(tr("Hide article list")); }
1,735
C++
.cpp
39
40.153846
112
0.724138
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,024
ExportToModListDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ExportToModListDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ExportToModListDialog.h" #include <QCheckBox> #include <QComboBox> #include <QTextEdit> #include "FileSystem.h" #include "Markdown.h" #include "StringUtils.h" #include "modplatform/helpers/ExportToModList.h" #include "ui_ExportToModListDialog.h" #include <QFileDialog> #include <QFileSystemModel> #include <QJsonDocument> #include <QMessageBox> #include <QPushButton> const QHash<ExportToModList::Formats, QString> ExportToModListDialog::exampleLines = { { ExportToModList::HTML, "<li><a href=\"{url}\">{name}</a> [{version}] by {authors}</li>" }, { ExportToModList::MARKDOWN, "[{name}]({url}) [{version}] by {authors}" }, { ExportToModList::PLAINTXT, "{name} ({url}) [{version}] by {authors}" }, { ExportToModList::JSON, "{\"name\":\"{name}\",\"url\":\"{url}\",\"version\":\"{version}\",\"authors\":\"{authors}\"}," }, { ExportToModList::CSV, "{name},{url},{version},\"{authors}\"" }, }; ExportToModListDialog::ExportToModListDialog(QString name, QList<Mod*> mods, QWidget* parent) : QDialog(parent), m_mods(mods), m_template_changed(false), m_name(name), ui(new Ui::ExportToModListDialog) { ui->setupUi(this); enableCustom(false); connect(ui->formatComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ExportToModListDialog::formatChanged); connect(ui->authorsCheckBox, &QCheckBox::stateChanged, this, &ExportToModListDialog::trigger); connect(ui->versionCheckBox, &QCheckBox::stateChanged, this, &ExportToModListDialog::trigger); connect(ui->urlCheckBox, &QCheckBox::stateChanged, this, &ExportToModListDialog::trigger); connect(ui->filenameCheckBox, &QCheckBox::stateChanged, this, &ExportToModListDialog::trigger); connect(ui->authorsButton, &QPushButton::clicked, this, [this](bool) { addExtra(ExportToModList::Authors); }); connect(ui->versionButton, &QPushButton::clicked, this, [this](bool) { addExtra(ExportToModList::Version); }); connect(ui->urlButton, &QPushButton::clicked, this, [this](bool) { addExtra(ExportToModList::Url); }); connect(ui->filenameButton, &QPushButton::clicked, this, [this](bool) { addExtra(ExportToModList::FileName); }); connect(ui->templateText, &QTextEdit::textChanged, this, [this] { if (ui->templateText->toPlainText() != exampleLines[m_format]) ui->formatComboBox->setCurrentIndex(5); triggerImp(); }); connect(ui->copyButton, &QPushButton::clicked, this, [this](bool) { this->ui->finalText->selectAll(); this->ui->finalText->copy(); }); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Save)->setText(tr("Save")); triggerImp(); } ExportToModListDialog::~ExportToModListDialog() { delete ui; } void ExportToModListDialog::formatChanged(int index) { switch (index) { case 0: { enableCustom(false); ui->resultText->show(); m_format = ExportToModList::HTML; break; } case 1: { enableCustom(false); ui->resultText->show(); m_format = ExportToModList::MARKDOWN; break; } case 2: { enableCustom(false); ui->resultText->hide(); m_format = ExportToModList::PLAINTXT; break; } case 3: { enableCustom(false); ui->resultText->hide(); m_format = ExportToModList::JSON; break; } case 4: { enableCustom(false); ui->resultText->hide(); m_format = ExportToModList::CSV; break; } case 5: { m_template_changed = true; enableCustom(true); ui->resultText->hide(); m_format = ExportToModList::CUSTOM; break; } } triggerImp(); } void ExportToModListDialog::triggerImp() { if (m_format == ExportToModList::CUSTOM) { ui->finalText->setPlainText(ExportToModList::exportToModList(m_mods, ui->templateText->toPlainText())); return; } auto opt = 0; if (ui->authorsCheckBox->isChecked()) opt |= ExportToModList::Authors; if (ui->versionCheckBox->isChecked()) opt |= ExportToModList::Version; if (ui->urlCheckBox->isChecked()) opt |= ExportToModList::Url; if (ui->filenameCheckBox->isChecked()) opt |= ExportToModList::FileName; auto txt = ExportToModList::exportToModList(m_mods, m_format, static_cast<ExportToModList::OptionalData>(opt)); ui->finalText->setPlainText(txt); switch (m_format) { case ExportToModList::CUSTOM: return; case ExportToModList::HTML: ui->resultText->setHtml(StringUtils::htmlListPatch(txt)); break; case ExportToModList::MARKDOWN: ui->resultText->setHtml(StringUtils::htmlListPatch(markdownToHTML(txt))); break; case ExportToModList::PLAINTXT: break; case ExportToModList::JSON: break; case ExportToModList::CSV: break; } auto exampleLine = exampleLines[m_format]; if (!m_template_changed && ui->templateText->toPlainText() != exampleLine) ui->templateText->setPlainText(exampleLine); } void ExportToModListDialog::done(int result) { if (result == Accepted) { const QString filename = FS::RemoveInvalidFilenameChars(m_name); const QString output = QFileDialog::getSaveFileName(this, tr("Export %1").arg(m_name), FS::PathCombine(QDir::homePath(), filename + extension()), tr("File") + " (*.txt *.html *.md *.json *.csv)", nullptr); if (output.isEmpty()) return; try { FS::write(output, ui->finalText->toPlainText().toUtf8()); } catch (const FS::FileSystemException& e) { qCritical() << "Failed to save mod list file :" << e.cause(); } } QDialog::done(result); } QString ExportToModListDialog::extension() { switch (m_format) { case ExportToModList::HTML: return ".html"; case ExportToModList::MARKDOWN: return ".md"; case ExportToModList::PLAINTXT: return ".txt"; case ExportToModList::CUSTOM: return ".txt"; case ExportToModList::JSON: return ".json"; case ExportToModList::CSV: return ".csv"; } return ".txt"; } void ExportToModListDialog::addExtra(ExportToModList::OptionalData option) { if (m_format != ExportToModList::CUSTOM) return; switch (option) { case ExportToModList::Authors: ui->templateText->insertPlainText("{authors}"); break; case ExportToModList::Url: ui->templateText->insertPlainText("{url}"); break; case ExportToModList::Version: ui->templateText->insertPlainText("{version}"); break; case ExportToModList::FileName: ui->templateText->insertPlainText("{filename}"); break; } } void ExportToModListDialog::enableCustom(bool enabled) { ui->authorsCheckBox->setHidden(enabled); ui->authorsButton->setHidden(!enabled); ui->versionCheckBox->setHidden(enabled); ui->versionButton->setHidden(!enabled); ui->urlCheckBox->setHidden(enabled); ui->urlButton->setHidden(!enabled); ui->filenameCheckBox->setHidden(enabled); ui->filenameButton->setHidden(!enabled); }
8,333
C++
.cpp
214
31.873832
134
0.643871
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,025
MSALoginDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/MSALoginDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "MSALoginDialog.h" #include "Application.h" #include "ui_MSALoginDialog.h" #include "DesktopServices.h" #include "minecraft/auth/AuthFlow.h" #include <QApplication> #include <QClipboard> #include <QPixmap> #include <QUrl> #include <QtWidgets/QPushButton> MSALoginDialog::MSALoginDialog(QWidget* parent) : QDialog(parent), ui(new Ui::MSALoginDialog) { ui->setupUi(this); // make font monospace QFont font; font.setPixelSize(ui->code->fontInfo().pixelSize()); font.setFamily(APPLICATION->settings()->get("ConsoleFont").toString()); font.setStyleHint(QFont::Monospace); font.setFixedPitch(true); ui->code->setFont(font); connect(ui->copyCode, &QPushButton::clicked, this, [this] { QApplication::clipboard()->setText(ui->code->text()); }); ui->qr->setPixmap(QIcon((":/documents/login-qr.svg")).pixmap(QSize(150, 150))); connect(ui->loginButton, &QPushButton::clicked, this, [this] { if (m_url.isValid()) { if (!DesktopServices::openUrl(m_url)) { QApplication::clipboard()->setText(m_url.toString()); } } }); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); } int MSALoginDialog::exec() { // Setup the login task and start it m_account = MinecraftAccount::createBlankMSA(); m_authflow_task = m_account->login(false); connect(m_authflow_task.get(), &Task::failed, this, &MSALoginDialog::onTaskFailed); connect(m_authflow_task.get(), &Task::succeeded, this, &QDialog::accept); connect(m_authflow_task.get(), &Task::aborted, this, &MSALoginDialog::reject); connect(m_authflow_task.get(), &Task::status, this, &MSALoginDialog::onAuthFlowStatus); connect(m_authflow_task.get(), &AuthFlow::authorizeWithBrowser, this, &MSALoginDialog::authorizeWithBrowser); connect(m_authflow_task.get(), &AuthFlow::authorizeWithBrowserWithExtra, this, &MSALoginDialog::authorizeWithBrowserWithExtra); connect(ui->buttonBox->button(QDialogButtonBox::Cancel), &QPushButton::clicked, m_authflow_task.get(), &Task::abort); m_devicecode_task.reset(new AuthFlow(m_account->accountData(), AuthFlow::Action::DeviceCode)); connect(m_devicecode_task.get(), &Task::failed, this, &MSALoginDialog::onTaskFailed); connect(m_devicecode_task.get(), &Task::succeeded, this, &QDialog::accept); connect(m_devicecode_task.get(), &Task::aborted, this, &MSALoginDialog::reject); connect(m_devicecode_task.get(), &Task::status, this, &MSALoginDialog::onDeviceFlowStatus); connect(m_devicecode_task.get(), &AuthFlow::authorizeWithBrowser, this, &MSALoginDialog::authorizeWithBrowser); connect(m_devicecode_task.get(), &AuthFlow::authorizeWithBrowserWithExtra, this, &MSALoginDialog::authorizeWithBrowserWithExtra); connect(ui->buttonBox->button(QDialogButtonBox::Cancel), &QPushButton::clicked, m_devicecode_task.get(), &Task::abort); QMetaObject::invokeMethod(m_authflow_task.get(), &Task::start, Qt::QueuedConnection); QMetaObject::invokeMethod(m_devicecode_task.get(), &Task::start, Qt::QueuedConnection); return QDialog::exec(); } MSALoginDialog::~MSALoginDialog() { delete ui; } void MSALoginDialog::onTaskFailed(QString reason) { // Set message m_authflow_task->disconnect(); m_devicecode_task->disconnect(); ui->stackedWidget->setCurrentIndex(0); auto lines = reason.split('\n'); QString processed; for (auto line : lines) { if (line.size()) { processed += "<font color='red'>" + line + "</font><br />"; } else { processed += "<br />"; } } ui->status->setText(processed); auto task = m_authflow_task; if (task->failReason().isEmpty()) { task = m_devicecode_task; } if (task) { ui->loadingLabel->setText(task->getStatus()); } disconnect(ui->buttonBox->button(QDialogButtonBox::Cancel), &QPushButton::clicked, m_authflow_task.get(), &Task::abort); disconnect(ui->buttonBox->button(QDialogButtonBox::Cancel), &QPushButton::clicked, m_devicecode_task.get(), &Task::abort); connect(ui->buttonBox->button(QDialogButtonBox::Cancel), &QPushButton::clicked, this, &MSALoginDialog::reject); } void MSALoginDialog::authorizeWithBrowser(const QUrl& url) { ui->stackedWidget2->setCurrentIndex(1); ui->loginButton->setToolTip(QString("<div style='width: 200px;'>%1</div>").arg(url.toString())); m_url = url; } void MSALoginDialog::authorizeWithBrowserWithExtra(QString url, QString code, int expiresIn) { ui->stackedWidget->setCurrentIndex(1); const auto linkString = QString("<a href=\"%1\">%2</a>").arg(url, url); ui->code->setText(code); auto isDefaultUrl = url == "https://www.microsoft.com/link"; ui->qr->setVisible(isDefaultUrl); if (isDefaultUrl) { ui->qrMessage->setText(tr("Open %1 or scan the QR and enter the above code.").arg(linkString)); } else { ui->qrMessage->setText(tr("Open %1 and enter the above code.").arg(linkString)); } } void MSALoginDialog::onDeviceFlowStatus(QString status) { ui->stackedWidget->setCurrentIndex(0); ui->status->setText(status); } void MSALoginDialog::onAuthFlowStatus(QString status) { ui->stackedWidget2->setCurrentIndex(0); ui->status2->setText(status); } // Public interface MinecraftAccountPtr MSALoginDialog::newAccount(QWidget* parent) { MSALoginDialog dlg(parent); if (dlg.exec() == QDialog::Accepted) { return dlg.m_account; } return nullptr; }
7,011
C++
.cpp
158
40.348101
133
0.708559
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,026
UpdateAvailableDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/UpdateAvailableDialog.cpp
// SPDX-FileCopyrightText: 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "UpdateAvailableDialog.h" #include <QPushButton> #include "Application.h" #include "BuildConfig.h" #include "Markdown.h" #include "StringUtils.h" #include "ui_UpdateAvailableDialog.h" UpdateAvailableDialog::UpdateAvailableDialog(const QString& currentVersion, const QString& availableVersion, const QString& releaseNotes, QWidget* parent) : QDialog(parent), ui(new Ui::UpdateAvailableDialog) { ui->setupUi(this); QString launcherName = BuildConfig.LAUNCHER_DISPLAYNAME; ui->headerLabel->setText(tr("A new version of %1 is available!").arg(launcherName)); ui->versionAvailableLabel->setText( tr("Version %1 is now available - you have %2 . Would you like to download it now?").arg(availableVersion).arg(currentVersion)); ui->icon->setPixmap(APPLICATION->getThemedIcon("checkupdate").pixmap(64)); auto releaseNotesHtml = markdownToHTML(releaseNotes); ui->releaseNotes->setHtml(StringUtils::htmlListPatch(releaseNotesHtml)); ui->releaseNotes->setOpenExternalLinks(true); connect(ui->skipButton, &QPushButton::clicked, this, [this]() { setResult(ResultCode::Skip); done(ResultCode::Skip); }); connect(ui->delayButton, &QPushButton::clicked, this, [this]() { setResult(ResultCode::DontInstall); done(ResultCode::DontInstall); }); connect(ui->installButton, &QPushButton::clicked, this, [this]() { setResult(ResultCode::Install); done(ResultCode::Install); }); }
2,476
C++
.cpp
55
39
136
0.698176
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,027
ChooseProviderDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ChooseProviderDialog.cpp
#include "ChooseProviderDialog.h" #include "ui_ChooseProviderDialog.h" #include <QPushButton> #include <QRadioButton> #include "modplatform/ModIndex.h" ChooseProviderDialog::ChooseProviderDialog(QWidget* parent, bool single_choice, bool allow_skipping) : QDialog(parent), ui(new Ui::ChooseProviderDialog) { ui->setupUi(this); addProviders(); m_providers.button(0)->click(); connect(ui->skipOneButton, &QPushButton::clicked, this, &ChooseProviderDialog::skipOne); connect(ui->skipAllButton, &QPushButton::clicked, this, &ChooseProviderDialog::skipAll); connect(ui->confirmOneButton, &QPushButton::clicked, this, &ChooseProviderDialog::confirmOne); connect(ui->confirmAllButton, &QPushButton::clicked, this, &ChooseProviderDialog::confirmAll); if (single_choice) { ui->providersLayout->removeWidget(ui->skipAllButton); ui->providersLayout->removeWidget(ui->confirmAllButton); } if (!allow_skipping) { ui->providersLayout->removeWidget(ui->skipOneButton); ui->providersLayout->removeWidget(ui->skipAllButton); } } ChooseProviderDialog::~ChooseProviderDialog() { delete ui; } void ChooseProviderDialog::setDescription(QString desc) { ui->explanationLabel->setText(desc); } void ChooseProviderDialog::skipOne() { reject(); } void ChooseProviderDialog::skipAll() { m_response.skip_all = true; reject(); } void ChooseProviderDialog::confirmOne() { m_response.chosen = getSelectedProvider(); m_response.try_others = ui->tryOthersCheckbox->isChecked(); accept(); } void ChooseProviderDialog::confirmAll() { m_response.chosen = getSelectedProvider(); m_response.confirm_all = true; m_response.try_others = ui->tryOthersCheckbox->isChecked(); accept(); } auto ChooseProviderDialog::getSelectedProvider() const -> ModPlatform::ResourceProvider { return ModPlatform::ResourceProvider(m_providers.checkedId()); } void ChooseProviderDialog::addProviders() { int btn_index = 0; QRadioButton* btn; for (auto& provider : { ModPlatform::ResourceProvider::MODRINTH, ModPlatform::ResourceProvider::FLAME }) { btn = new QRadioButton(ModPlatform::ProviderCapabilities::readableName(provider), this); m_providers.addButton(btn, btn_index++); ui->providersLayout->addWidget(btn); } } void ChooseProviderDialog::disableInput() { for (auto& btn : m_providers.buttons()) btn->setEnabled(false); ui->skipOneButton->setEnabled(false); ui->skipAllButton->setEnabled(false); ui->confirmOneButton->setEnabled(false); ui->confirmAllButton->setEnabled(false); }
2,644
C++
.cpp
77
30.519481
110
0.742353
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,028
BlockedModsDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/BlockedModsDialog.cpp
// SPDX-FileCopyrightText: 2022 Sefa Eyeoglu <contact@scrumplex.net> // SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> // SPDX-FileCopyrightText: 2022 kumquat-ir <66188216+kumquat-ir@users.noreply.github.com> // // SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * Copyright (C) 2022 kumquat-ir <66188216+kumquat-ir@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "BlockedModsDialog.h" #include "ui_BlockedModsDialog.h" #include "Application.h" #include "modplatform/helpers/HashUtils.h" #include <QDebug> #include <QDesktopServices> #include <QDialogButtonBox> #include <QDir> #include <QDirIterator> #include <QDragEnterEvent> #include <QFileDialog> #include <QFileInfo> #include <QMimeData> #include <QPushButton> #include <QStandardPaths> #include <QTimer> BlockedModsDialog::BlockedModsDialog(QWidget* parent, const QString& title, const QString& text, QList<BlockedMod>& mods, QString hash_type) : QDialog(parent), ui(new Ui::BlockedModsDialog), m_mods(mods), m_hash_type(hash_type) { m_hashing_task = shared_qobject_ptr<ConcurrentTask>( new ConcurrentTask("MakeHashesTask", APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt())); connect(m_hashing_task.get(), &Task::finished, this, &BlockedModsDialog::hashTaskFinished); ui->setupUi(this); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); m_openMissingButton = ui->buttonBox->addButton(tr("Open Missing"), QDialogButtonBox::ActionRole); connect(m_openMissingButton, &QPushButton::clicked, this, [this]() { openAll(true); }); auto downloadFolderButton = ui->buttonBox->addButton(tr("Add Download Folder"), QDialogButtonBox::ActionRole); connect(downloadFolderButton, &QPushButton::clicked, this, &BlockedModsDialog::addDownloadFolder); connect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, &BlockedModsDialog::directoryChanged); qDebug() << "[Blocked Mods Dialog] Mods List: " << mods; // defer setup of file system watchers until after the dialog is shown // this allows OS (namely macOS) permission prompts to show after the relevant dialog appears QTimer::singleShot(0, this, [this] { setupWatch(); scanPaths(); update(); }); this->setWindowTitle(title); ui->labelDescription->setText(text); // force all URL handling as external connect(ui->textBrowserWatched, &QTextBrowser::anchorClicked, this, [](const QUrl url) { QDesktopServices::openUrl(url); }); setAcceptDrops(true); update(); } BlockedModsDialog::~BlockedModsDialog() { delete ui; } void BlockedModsDialog::dragEnterEvent(QDragEnterEvent* e) { if (e->mimeData()->hasUrls()) { e->acceptProposedAction(); } } void BlockedModsDialog::dropEvent(QDropEvent* e) { for (QUrl& url : e->mimeData()->urls()) { if (url.scheme().isEmpty()) { // ensure isLocalFile() works correctly url.setScheme("file"); } if (!url.isLocalFile()) { // can't drop external files here. continue; } QString filePath = url.toLocalFile(); qDebug() << "[Blocked Mods Dialog] Dropped file:" << filePath; addHashTask(filePath); // watch for changes QFileInfo file = QFileInfo(filePath); QString path = file.dir().absolutePath(); qDebug() << "[Blocked Mods Dialog] Adding watch path:" << path; m_watcher.addPath(path); } scanPaths(); update(); } void BlockedModsDialog::done(int r) { QDialog::done(r); disconnect(&m_watcher, &QFileSystemWatcher::directoryChanged, this, &BlockedModsDialog::directoryChanged); } void BlockedModsDialog::openAll(bool missingOnly) { for (auto& mod : m_mods) { if (!missingOnly || !mod.matched) { QDesktopServices::openUrl(mod.websiteUrl); } } } void BlockedModsDialog::addDownloadFolder() { QString dir = QFileDialog::getExistingDirectory(this, tr("Select directory where you downloaded the mods"), QStandardPaths::writableLocation(QStandardPaths::DownloadLocation), QFileDialog::ShowDirsOnly); qDebug() << "[Blocked Mods Dialog] Adding watch path:" << dir; m_watcher.addPath(dir); scanPath(dir, true); update(); } /// @brief update UI with current status of the blocked mod detection void BlockedModsDialog::update() { QString text; QString span; for (auto& mod : m_mods) { if (mod.matched) { // &#x2714; -> html for HEAVY CHECK MARK : ✔ span = QString(tr("<span style=\"color:green\"> &#x2714; Found at %1 </span>")).arg(mod.localPath); } else { // &#x2718; -> html for HEAVY BALLOT X : ✘ span = QString(tr("<span style=\"color:red\"> &#x2718; Not Found </span>")); } text += QString(tr("%1: <a href='%2'>%2</a> <p>Hash: %3 %4</p> <br/>")).arg(mod.name, mod.websiteUrl, mod.hash, span); } ui->textBrowserModsListing->setText(text); QString watching; for (auto& dir : m_watcher.directories()) { QUrl fileURL = QUrl::fromLocalFile(dir); watching += QString("<a href=\"%1\">%2</a><br/>").arg(fileURL.toString(), dir); } ui->textBrowserWatched->setText(watching); if (allModsMatched()) { ui->labelModsFound->setText("<span style=\"color:green\">✔</span>" + tr("All mods found")); m_openMissingButton->setDisabled(true); } else { ui->labelModsFound->setText(tr("Please download the missing mods.")); m_openMissingButton->setDisabled(false); } } /// @brief Signal fired when a watched directory has changed /// @param path the path to the changed directory void BlockedModsDialog::directoryChanged(QString path) { qDebug() << "[Blocked Mods Dialog] Directory changed: " << path; validateMatchedMods(); scanPath(path, true); } /// @brief add the user downloads folder and the global mods folder to the filesystem watcher void BlockedModsDialog::setupWatch() { const QString downloadsFolder = APPLICATION->settings()->get("DownloadsDir").toString(); const QString modsFolder = APPLICATION->settings()->get("CentralModsDir").toString(); const bool downloadsFolderWatchRecursive = APPLICATION->settings()->get("DownloadsDirWatchRecursive").toBool(); watchPath(downloadsFolder, downloadsFolderWatchRecursive); watchPath(modsFolder, true); } void BlockedModsDialog::watchPath(QString path, bool watch_recursive) { auto to_watch = QFileInfo(path); if (!to_watch.isReadable()) { qWarning() << "[Blocked Mods Dialog] Failed to add Watch Path (unable to read):" << path; return; } auto to_watch_path = to_watch.canonicalFilePath(); if (m_watcher.directories().contains(to_watch_path)) return; // don't watch the same path twice (no loops!) qDebug() << "[Blocked Mods Dialog] Adding Watch Path:" << path; m_watcher.addPath(to_watch_path); if (!to_watch.isDir() || !watch_recursive) return; QDirIterator it(to_watch_path, QDir::Filter::Dirs | QDir::Filter::NoDotAndDotDot, QDirIterator::NoIteratorFlags); while (it.hasNext()) { QString watch_dir = QDir(it.next()).canonicalPath(); // resolve symlinks and relative paths watchPath(watch_dir, watch_recursive); } } /// @brief scan all watched folder void BlockedModsDialog::scanPaths() { for (auto& dir : m_watcher.directories()) { scanPath(dir, false); } runHashTask(); } /// @brief Scan the directory at path, skip paths that do not contain a file name /// of a blocked mod we are looking for /// @param path the directory to scan void BlockedModsDialog::scanPath(QString path, bool start_task) { QDir scan_dir(path); QDirIterator scan_it(path, QDir::Filter::Files | QDir::Filter::Hidden, QDirIterator::NoIteratorFlags); while (scan_it.hasNext()) { QString file = scan_it.next(); if (!checkValidPath(file)) { continue; } addHashTask(file); } if (start_task) { runHashTask(); } } /// @brief add a hashing task for the file located at path, add the path to the pending set if the hashing task is already running /// @param path the path to the local file being hashed void BlockedModsDialog::addHashTask(QString path) { qDebug() << "[Blocked Mods Dialog] adding a Hash task for" << path << "to the pending set."; m_pending_hash_paths.insert(path); } /// @brief add a hashing task for the file located at path and connect it to check that hash against /// our blocked mods list /// @param path the path to the local file being hashed void BlockedModsDialog::buildHashTask(QString path) { auto hash_task = Hashing::createHasher(path, m_hash_type); qDebug() << "[Blocked Mods Dialog] Creating Hash task for path: " << path; connect(hash_task.get(), &Task::succeeded, this, [this, hash_task, path] { checkMatchHash(hash_task->getResult(), path); }); connect(hash_task.get(), &Task::failed, this, [path] { qDebug() << "Failed to hash path: " << path; }); m_hashing_task->addTask(hash_task); } /// @brief check if the computed hash for the provided path matches a blocked /// mod we are looking for /// @param hash the computed hash for the provided path /// @param path the path to the local file being compared void BlockedModsDialog::checkMatchHash(QString hash, QString path) { bool match = false; qDebug() << "[Blocked Mods Dialog] Checking for match on hash: " << hash << "| From path:" << path; for (auto& mod : m_mods) { if (mod.matched) { continue; } if (mod.hash.compare(hash, Qt::CaseInsensitive) == 0) { mod.matched = true; mod.localPath = path; match = true; qDebug() << "[Blocked Mods Dialog] Hash match found:" << mod.name << hash << "| From path:" << path; break; } } if (match) { update(); } } /// @brief Check if the name of the file at path matches the name of a blocked mod we are searching for /// @param path the path to check /// @return boolean: did the path match the name of a blocked mod? bool BlockedModsDialog::checkValidPath(QString path) { const QFileInfo file = QFileInfo(path); const QString filename = file.fileName(); auto compare = [](QString fsFilename, QString metadataFilename) { return metadataFilename.compare(fsFilename, Qt::CaseInsensitive) == 0; }; // super lax compare (but not fuzzy) // convert to lowercase // convert all speratores to whitespace // simplify sequence of internal whitespace to a single space // efectivly compare two strings ignoring all separators and case auto laxCompare = [](QString fsfilename, QString metadataFilename) { // allowed character seperators QList<QChar> allowedSeperators = { '-', '+', '.', '_' }; // copy in lowercase auto fsName = fsfilename.toLower(); auto metaName = metadataFilename.toLower(); // replace all potential allowed seperatores with whitespace for (auto sep : allowedSeperators) { fsName = fsName.replace(sep, ' '); metaName = metaName.replace(sep, ' '); } // remove extraneous whitespace fsName = fsName.simplified(); metaName = metaName.simplified(); return fsName.compare(metaName) == 0; }; for (auto& mod : m_mods) { if (compare(filename, mod.name)) { // if the mod is not yet matched and doesn't have a hash then // just match it with the file that has the exact same name if (!mod.matched && mod.hash.isEmpty()) { mod.matched = true; mod.localPath = path; return false; } qDebug() << "[Blocked Mods Dialog] Name match found:" << mod.name << "| From path:" << path; return true; } if (laxCompare(filename, mod.name)) { qDebug() << "[Blocked Mods Dialog] Lax name match found:" << mod.name << "| From path:" << path; return true; } } return false; } bool BlockedModsDialog::allModsMatched() { return std::all_of(m_mods.begin(), m_mods.end(), [](auto const& mod) { return mod.matched; }); } /// @brief ensure matched file paths still exist void BlockedModsDialog::validateMatchedMods() { bool changed = false; for (auto& mod : m_mods) { if (mod.matched) { QFileInfo file = QFileInfo(mod.localPath); if (!file.exists() || !file.isFile()) { qDebug() << "[Blocked Mods Dialog] File" << mod.localPath << "for mod" << mod.name << "has vanshed! marking as not matched."; mod.localPath = ""; mod.matched = false; changed = true; } } } if (changed) { update(); } } /// @brief run hash task or mark a pending run if it is already running void BlockedModsDialog::runHashTask() { if (!m_hashing_task->isRunning()) { m_rehash_pending = false; if (!m_pending_hash_paths.isEmpty()) { qDebug() << "[Blocked Mods Dialog] there are pending hash tasks, building and running tasks"; auto path = m_pending_hash_paths.begin(); while (path != m_pending_hash_paths.end()) { buildHashTask(*path); path = m_pending_hash_paths.erase(path); } m_hashing_task->start(); } } else { qDebug() << "[Blocked Mods Dialog] queueing another run of the hashing task"; qDebug() << "[Blocked Mods Dialog] pending hash tasks:" << m_pending_hash_paths; m_rehash_pending = true; } } void BlockedModsDialog::hashTaskFinished() { qDebug() << "[Blocked Mods Dialog] All hash tasks finished"; if (m_rehash_pending) { qDebug() << "[Blocked Mods Dialog] task finished with a rehash pending, rerunning"; runHashTask(); } } /// qDebug print support for the BlockedMod struct QDebug operator<<(QDebug debug, const BlockedMod& m) { QDebugStateSaver saver(debug); debug.nospace() << "{ name: " << m.name << ", websiteUrl: " << m.websiteUrl << ", hash: " << m.hash << ", matched: " << m.matched << ", localPath: " << m.localPath << "}"; return debug; }
15,337
C++
.cpp
367
35.915531
140
0.657356
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,029
ResourceUpdateDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ResourceUpdateDialog.cpp
#include "ResourceUpdateDialog.h" #include "ChooseProviderDialog.h" #include "CustomMessageBox.h" #include "ProgressDialog.h" #include "ScrollMessageBox.h" #include "StringUtils.h" #include "minecraft/mod/tasks/GetModDependenciesTask.h" #include "modplatform/ModIndex.h" #include "modplatform/flame/FlameAPI.h" #include "ui_ReviewMessageBox.h" #include "Markdown.h" #include "tasks/ConcurrentTask.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "modplatform/EnsureMetadataTask.h" #include "modplatform/flame/FlameCheckUpdate.h" #include "modplatform/modrinth/ModrinthCheckUpdate.h" #include <QTextBrowser> #include <QTreeWidgetItem> #include <optional> static std::list<Version> mcVersions(BaseInstance* inst) { return { static_cast<MinecraftInstance*>(inst)->getPackProfile()->getComponent("net.minecraft")->getVersion() }; } static QList<ModPlatform::ModLoaderType> mcLoadersList(BaseInstance* inst) { return static_cast<MinecraftInstance*>(inst)->getPackProfile()->getModLoadersList(); } ResourceUpdateDialog::ResourceUpdateDialog(QWidget* parent, BaseInstance* instance, const std::shared_ptr<ResourceFolderModel> resource_model, QList<Resource*>& search_for, bool include_deps, bool filter_loaders) : ReviewMessageBox(parent, tr("Confirm resources to update"), "") , m_parent(parent) , m_resource_model(resource_model) , m_candidates(search_for) , m_second_try_metadata(new ConcurrentTask("Second Metadata Search", APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt())) , m_instance(instance) , m_include_deps(include_deps) , m_filter_loaders(filter_loaders) { ReviewMessageBox::setGeometry(0, 0, 800, 600); ui->explainLabel->setText(tr("You're about to update the following resources:")); ui->onlyCheckedLabel->setText(tr("Only resources with a check will be updated!")); } void ResourceUpdateDialog::checkCandidates() { // Ensure mods have valid metadata auto went_well = ensureMetadata(); if (!went_well) { m_aborted = true; return; } // Report failed metadata generation if (!m_failed_metadata.empty()) { QString text; for (const auto& failed : m_failed_metadata) { const auto& mod = std::get<0>(failed); const auto& reason = std::get<1>(failed); text += tr("Mod name: %1<br>File name: %2<br>Reason: %3<br><br>").arg(mod->name(), mod->fileinfo().fileName(), reason); } ScrollMessageBox message_dialog(m_parent, tr("Metadata generation failed"), tr("Could not generate metadata for the following resources:<br>" "Do you wish to proceed without those resources?"), text); message_dialog.setModal(true); if (message_dialog.exec() == QDialog::Rejected) { m_aborted = true; QMetaObject::invokeMethod(this, "reject", Qt::QueuedConnection); return; } } auto versions = mcVersions(m_instance); auto loadersList = m_filter_loaders ? mcLoadersList(m_instance) : QList<ModPlatform::ModLoaderType>(); SequentialTask check_task(tr("Checking for updates")); if (!m_modrinth_to_update.empty()) { m_modrinth_check_task.reset(new ModrinthCheckUpdate(m_modrinth_to_update, versions, loadersList, m_resource_model)); connect(m_modrinth_check_task.get(), &CheckUpdateTask::checkFailed, this, [this](Resource* resource, QString reason, QUrl recover_url) { m_failed_check_update.append({ resource, reason, recover_url }); }); check_task.addTask(m_modrinth_check_task); } if (!m_flame_to_update.empty()) { m_flame_check_task.reset(new FlameCheckUpdate(m_flame_to_update, versions, loadersList, m_resource_model)); connect(m_flame_check_task.get(), &CheckUpdateTask::checkFailed, this, [this](Resource* resource, QString reason, QUrl recover_url) { m_failed_check_update.append({ resource, reason, recover_url }); }); check_task.addTask(m_flame_check_task); } connect(&check_task, &Task::failed, this, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); }); connect(&check_task, &Task::succeeded, this, [this, &check_task]() { QStringList warnings = check_task.warnings(); if (warnings.count()) { CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->exec(); } }); // Check for updates ProgressDialog progress_dialog(m_parent); progress_dialog.setSkipButton(true, tr("Abort")); progress_dialog.setWindowTitle(tr("Checking for updates...")); auto ret = progress_dialog.execWithTask(&check_task); // If the dialog was skipped / some download error happened if (ret == QDialog::DialogCode::Rejected) { m_aborted = true; QMetaObject::invokeMethod(this, "reject", Qt::QueuedConnection); return; } QList<std::shared_ptr<GetModDependenciesTask::PackDependency>> selectedVers; // Add found updates for Modrinth if (m_modrinth_check_task) { auto modrinth_updates = m_modrinth_check_task->getUpdates(); for (auto& updatable : modrinth_updates) { qDebug() << QString("Mod %1 has an update available!").arg(updatable.name); appendResource(updatable); m_tasks.insert(updatable.name, updatable.download); } selectedVers.append(m_modrinth_check_task->getDependencies()); } // Add found updated for Flame if (m_flame_check_task) { auto flame_updates = m_flame_check_task->getUpdates(); for (auto& updatable : flame_updates) { qDebug() << QString("Mod %1 has an update available!").arg(updatable.name); appendResource(updatable); m_tasks.insert(updatable.name, updatable.download); } selectedVers.append(m_flame_check_task->getDependencies()); } // Report failed update checking if (!m_failed_check_update.empty()) { QString text; for (const auto& failed : m_failed_check_update) { const auto& mod = std::get<0>(failed); const auto& reason = std::get<1>(failed); const auto& recover_url = std::get<2>(failed); qDebug() << mod->name() << " failed to check for updates!"; text += tr("Mod name: %1").arg(mod->name()) + "<br>"; if (!reason.isEmpty()) text += tr("Reason: %1").arg(reason) + "<br>"; if (!recover_url.isEmpty()) //: %1 is the link to download it manually text += tr("Possible solution: Getting the latest version manually:<br>%1<br>") .arg(QString("<a href='%1'>%1</a>").arg(recover_url.toString())); text += "<br>"; } ScrollMessageBox message_dialog(m_parent, tr("Failed to check for updates"), tr("Could not check or get the following resources for updates:<br>" "Do you wish to proceed without those resources?"), text); message_dialog.setModal(true); if (message_dialog.exec() == QDialog::Rejected) { m_aborted = true; QMetaObject::invokeMethod(this, "reject", Qt::QueuedConnection); return; } } if (m_include_deps && !APPLICATION->settings()->get("ModDependenciesDisabled").toBool()) { // dependencies auto* mod_model = dynamic_cast<ModFolderModel*>(m_resource_model.get()); if (mod_model != nullptr) { auto depTask = makeShared<GetModDependenciesTask>(m_instance, mod_model, selectedVers); connect(depTask.get(), &Task::failed, this, [this](const QString& reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); }); auto weak = depTask.toWeakRef(); connect(depTask.get(), &Task::succeeded, this, [this, weak]() { QStringList warnings; if (auto depTask = weak.lock()) { warnings = depTask->warnings(); } if (warnings.count()) { CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->exec(); } }); ProgressDialog progress_dialog_deps(m_parent); progress_dialog_deps.setSkipButton(true, tr("Abort")); progress_dialog_deps.setWindowTitle(tr("Checking for dependencies...")); auto dret = progress_dialog_deps.execWithTask(depTask.get()); // If the dialog was skipped / some download error happened if (dret == QDialog::DialogCode::Rejected) { m_aborted = true; QMetaObject::invokeMethod(this, "reject", Qt::QueuedConnection); return; } static FlameAPI api; auto dependencyExtraInfo = depTask->getExtraInfo(); for (const auto& dep : depTask->getDependecies()) { auto changelog = dep->version.changelog; if (dep->pack->provider == ModPlatform::ResourceProvider::FLAME) changelog = api.getModFileChangelog(dep->version.addonId.toInt(), dep->version.fileId.toInt()); auto download_task = makeShared<ResourceDownloadTask>(dep->pack, dep->version, m_resource_model); auto extraInfo = dependencyExtraInfo.value(dep->version.addonId.toString()); CheckUpdateTask::Update updatable = { dep->pack->name, dep->version.hash, tr("Not installed"), dep->version.version, dep->version.version_type, changelog, dep->pack->provider, download_task, !extraInfo.maybe_installed }; appendResource(updatable, extraInfo.required_by); m_tasks.insert(updatable.name, updatable.download); } } } // If there's no resource to be updated if (ui->modTreeWidget->topLevelItemCount() == 0) { m_no_updates = true; } else { // FIXME: Find a more efficient way of doing this! // Sort major items in alphabetical order (also sorts the children unfortunately) ui->modTreeWidget->sortItems(0, Qt::SortOrder::AscendingOrder); // Re-sort the children auto* item = ui->modTreeWidget->topLevelItem(0); for (int i = 1; item != nullptr; ++i) { item->sortChildren(0, Qt::SortOrder::DescendingOrder); item = ui->modTreeWidget->topLevelItem(i); } } if (m_aborted || m_no_updates) QMetaObject::invokeMethod(this, "reject", Qt::QueuedConnection); } // Part 1: Ensure we have a valid metadata auto ResourceUpdateDialog::ensureMetadata() -> bool { auto index_dir = indexDir(); SequentialTask seq(tr("Looking for metadata")); // A better use of data structures here could remove the need for this QHash QHash<QString, bool> should_try_others; QList<Resource*> modrinth_tmp; QList<Resource*> flame_tmp; bool confirm_rest = false; bool try_others_rest = false; bool skip_rest = false; ModPlatform::ResourceProvider provider_rest = ModPlatform::ResourceProvider::MODRINTH; auto addToTmp = [&modrinth_tmp, &flame_tmp](Resource* resource, ModPlatform::ResourceProvider p) { switch (p) { case ModPlatform::ResourceProvider::MODRINTH: modrinth_tmp.push_back(resource); break; case ModPlatform::ResourceProvider::FLAME: flame_tmp.push_back(resource); break; } }; for (auto candidate : m_candidates) { if (candidate->status() != ResourceStatus::NO_METADATA) { onMetadataEnsured(candidate); continue; } if (skip_rest) continue; if (candidate->type() == ResourceType::FOLDER) { continue; } if (confirm_rest) { addToTmp(candidate, provider_rest); should_try_others.insert(candidate->internal_id(), try_others_rest); continue; } ChooseProviderDialog chooser(this); chooser.setDescription(tr("The resource '%1' does not have a metadata yet. We need to generate it in order to track relevant " "information on how to update this mod. " "To do this, please select a mod provider which we can use to check for updates for this mod.") .arg(candidate->name())); auto confirmed = chooser.exec() == QDialog::DialogCode::Accepted; auto response = chooser.getResponse(); if (response.skip_all) skip_rest = true; if (response.confirm_all) { confirm_rest = true; provider_rest = response.chosen; try_others_rest = response.try_others; } should_try_others.insert(candidate->internal_id(), response.try_others); if (confirmed) addToTmp(candidate, response.chosen); } if (!modrinth_tmp.empty()) { auto modrinth_task = makeShared<EnsureMetadataTask>(modrinth_tmp, index_dir, ModPlatform::ResourceProvider::MODRINTH); connect(modrinth_task.get(), &EnsureMetadataTask::metadataReady, [this](Resource* candidate) { onMetadataEnsured(candidate); }); connect(modrinth_task.get(), &EnsureMetadataTask::metadataFailed, [this, &should_try_others](Resource* candidate) { onMetadataFailed(candidate, should_try_others.find(candidate->internal_id()).value(), ModPlatform::ResourceProvider::MODRINTH); }); connect(modrinth_task.get(), &EnsureMetadataTask::failed, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); }); if (modrinth_task->getHashingTask()) seq.addTask(modrinth_task->getHashingTask()); seq.addTask(modrinth_task); } if (!flame_tmp.empty()) { auto flame_task = makeShared<EnsureMetadataTask>(flame_tmp, index_dir, ModPlatform::ResourceProvider::FLAME); connect(flame_task.get(), &EnsureMetadataTask::metadataReady, [this](Resource* candidate) { onMetadataEnsured(candidate); }); connect(flame_task.get(), &EnsureMetadataTask::metadataFailed, [this, &should_try_others](Resource* candidate) { onMetadataFailed(candidate, should_try_others.find(candidate->internal_id()).value(), ModPlatform::ResourceProvider::FLAME); }); connect(flame_task.get(), &EnsureMetadataTask::failed, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); }); if (flame_task->getHashingTask()) seq.addTask(flame_task->getHashingTask()); seq.addTask(flame_task); } seq.addTask(m_second_try_metadata); ProgressDialog checking_dialog(m_parent); checking_dialog.setSkipButton(true, tr("Abort")); checking_dialog.setWindowTitle(tr("Generating metadata...")); auto ret_metadata = checking_dialog.execWithTask(&seq); return (ret_metadata != QDialog::DialogCode::Rejected); } void ResourceUpdateDialog::onMetadataEnsured(Resource* resource) { // When the mod is a folder, for instance if (!resource->metadata()) return; switch (resource->metadata()->provider) { case ModPlatform::ResourceProvider::MODRINTH: m_modrinth_to_update.push_back(resource); break; case ModPlatform::ResourceProvider::FLAME: m_flame_to_update.push_back(resource); break; } } ModPlatform::ResourceProvider next(ModPlatform::ResourceProvider p) { switch (p) { case ModPlatform::ResourceProvider::MODRINTH: return ModPlatform::ResourceProvider::FLAME; case ModPlatform::ResourceProvider::FLAME: return ModPlatform::ResourceProvider::MODRINTH; } return ModPlatform::ResourceProvider::FLAME; } void ResourceUpdateDialog::onMetadataFailed(Resource* resource, bool try_others, ModPlatform::ResourceProvider first_choice) { if (try_others) { auto index_dir = indexDir(); auto task = makeShared<EnsureMetadataTask>(resource, index_dir, next(first_choice)); connect(task.get(), &EnsureMetadataTask::metadataReady, [this](Resource* candidate) { onMetadataEnsured(candidate); }); connect(task.get(), &EnsureMetadataTask::metadataFailed, [this](Resource* candidate) { onMetadataFailed(candidate, false); }); connect(task.get(), &EnsureMetadataTask::failed, [this](const QString& reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); }); m_second_try_metadata->addTask(task); } else { QString reason{ tr("Couldn't find a valid version on the selected mod provider(s)") }; m_failed_metadata.append({ resource, reason }); } } void ResourceUpdateDialog::appendResource(CheckUpdateTask::Update const& info, QStringList requiredBy) { auto item_top = new QTreeWidgetItem(ui->modTreeWidget); item_top->setCheckState(0, info.enabled ? Qt::CheckState::Checked : Qt::CheckState::Unchecked); if (!info.enabled) { item_top->setToolTip(0, tr("Mod was disabled as it may be already installed.")); } item_top->setText(0, info.name); item_top->setExpanded(true); auto provider_item = new QTreeWidgetItem(item_top); provider_item->setText(0, tr("Provider: %1").arg(ModPlatform::ProviderCapabilities::readableName(info.provider))); auto old_version_item = new QTreeWidgetItem(item_top); old_version_item->setText(0, tr("Old version: %1").arg(info.old_version)); auto new_version_item = new QTreeWidgetItem(item_top); new_version_item->setText(0, tr("New version: %1").arg(info.new_version)); if (info.new_version_type.has_value()) { auto new_version_type_itme = new QTreeWidgetItem(item_top); new_version_type_itme->setText(0, tr("New Version Type: %1").arg(info.new_version_type.value().toString())); } if (!requiredBy.isEmpty()) { auto requiredByItem = new QTreeWidgetItem(item_top); if (requiredBy.length() == 1) { requiredByItem->setText(0, tr("Required by: %1").arg(requiredBy.back())); } else { requiredByItem->setText(0, tr("Required by:")); auto i = 0; for (auto req : requiredBy) { auto reqItem = new QTreeWidgetItem(requiredByItem); reqItem->setText(0, req); reqItem->insertChildren(i++, { reqItem }); } } ui->toggleDepsButton->show(); m_deps << item_top; } auto changelog_item = new QTreeWidgetItem(item_top); changelog_item->setText(0, tr("Changelog of the latest version")); auto changelog = new QTreeWidgetItem(changelog_item); auto changelog_area = new QTextBrowser(); QString text = info.changelog; switch (info.provider) { case ModPlatform::ResourceProvider::MODRINTH: { text = markdownToHTML(info.changelog.toUtf8()); break; } default: break; } changelog_area->setHtml(StringUtils::htmlListPatch(text)); changelog_area->setOpenExternalLinks(true); changelog_area->setLineWrapMode(QTextBrowser::LineWrapMode::WidgetWidth); changelog_area->setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAsNeeded); ui->modTreeWidget->setItemWidget(changelog, 0, changelog_area); ui->modTreeWidget->addTopLevelItem(item_top); } auto ResourceUpdateDialog::getTasks() -> const QList<ResourceDownloadTask::Ptr> { QList<ResourceDownloadTask::Ptr> list; auto* item = ui->modTreeWidget->topLevelItem(0); for (int i = 1; item != nullptr; ++i) { if (item->checkState(0) == Qt::CheckState::Checked) { list.push_back(m_tasks.find(item->text(0)).value()); } item = ui->modTreeWidget->topLevelItem(i); } return list; }
20,790
C++
.cpp
415
40.308434
139
0.632518
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,030
InstallLoaderDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/InstallLoaderDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "InstallLoaderDialog.h" #include <QDialogButtonBox> #include <QPushButton> #include <QVBoxLayout> #include "Application.h" #include "BuildConfig.h" #include "DesktopServices.h" #include "meta/Index.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "ui/widgets/PageContainer.h" #include "ui/widgets/VersionSelectWidget.h" class InstallLoaderPage : public VersionSelectWidget, public BasePage { Q_OBJECT public: InstallLoaderPage(const QString& id, const QString& iconName, const QString& name, const Version& oldestVersion, const std::shared_ptr<PackProfile> profile) : VersionSelectWidget(nullptr), uid(id), iconName(iconName), name(name) { const QString minecraftVersion = profile->getComponentVersion("net.minecraft"); setEmptyString(tr("No versions are currently available for Minecraft %1").arg(minecraftVersion)); setExactIfPresentFilter(BaseVersionList::ParentVersionRole, minecraftVersion); if (oldestVersion != Version() && Version(minecraftVersion) < oldestVersion) setExactFilter(BaseVersionList::ParentVersionRole, "AAA"); if (const QString currentVersion = profile->getComponentVersion(id); !currentVersion.isNull()) setCurrentVersion(currentVersion); } QString id() const override { return uid; } QString displayName() const override { return name; } QIcon icon() const override { return APPLICATION->getThemedIcon(iconName); } void openedImpl() override { if (loaded) return; const auto versions = APPLICATION->metadataIndex()->get(uid); if (!versions) return; initialize(versions.get()); loaded = true; } void setParentContainer(BasePageContainer* container) override { auto dialog = dynamic_cast<QDialog*>(dynamic_cast<PageContainer*>(container)->parent()); connect(view(), &QAbstractItemView::doubleClicked, dialog, &QDialog::accept); } private: const QString uid; const QString iconName; const QString name; bool loaded = false; }; static InstallLoaderPage* pageCast(BasePage* page) { auto result = dynamic_cast<InstallLoaderPage*>(page); Q_ASSERT(result != nullptr); return result; } InstallLoaderDialog::InstallLoaderDialog(std::shared_ptr<PackProfile> profile, const QString& uid, QWidget* parent) : QDialog(parent), profile(std::move(profile)), container(new PageContainer(this, QString(), this)), buttons(new QDialogButtonBox(this)) { auto layout = new QVBoxLayout(this); container->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); layout->addWidget(container); auto buttonLayout = new QHBoxLayout(this); auto refreshButton = new QPushButton(tr("&Refresh"), this); connect(refreshButton, &QPushButton::clicked, this, [this] { pageCast(container->selectedPage())->loadList(); }); buttonLayout->addWidget(refreshButton); buttons->setOrientation(Qt::Horizontal); buttons->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); buttons->button(QDialogButtonBox::Ok)->setText(tr("Ok")); buttons->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); buttonLayout->addWidget(buttons); layout->addLayout(buttonLayout); setWindowTitle(dialogTitle()); setWindowModality(Qt::WindowModal); resize(520, 347); for (BasePage* page : container->getPages()) { if (page->id() == uid) container->selectPage(page->id()); connect(pageCast(page), &VersionSelectWidget::selectedVersionChanged, this, [this, page] { if (page->id() == container->selectedPage()->id()) validate(container->selectedPage()); }); } connect(container, &PageContainer::selectedPageChanged, this, [this](BasePage* previous, BasePage* current) { validate(current); }); pageCast(container->selectedPage())->selectSearch(); validate(container->selectedPage()); } QList<BasePage*> InstallLoaderDialog::getPages() { return { // NeoForge new InstallLoaderPage("net.neoforged", "neoforged", tr("NeoForge"), {}, profile), // Forge new InstallLoaderPage("net.minecraftforge", "forge", tr("Forge"), {}, profile), // Fabric new InstallLoaderPage("net.fabricmc.fabric-loader", "fabricmc", tr("Fabric"), Version("1.14"), profile), // Quilt new InstallLoaderPage("org.quiltmc.quilt-loader", "quiltmc", tr("Quilt"), Version("1.14"), profile), // LiteLoader new InstallLoaderPage("com.mumfrey.liteloader", "liteloader", tr("LiteLoader"), {}, profile) }; } QString InstallLoaderDialog::dialogTitle() { return tr("Install Loader"); } void InstallLoaderDialog::validate(BasePage* page) { buttons->button(QDialogButtonBox::Ok)->setEnabled(pageCast(page)->selectedVersion() != nullptr); } void InstallLoaderDialog::done(int result) { if (result == Accepted) { auto* page = pageCast(container->selectedPage()); if (page->selectedVersion()) { profile->setComponentVersion(page->id(), page->selectedVersion()->descriptor()); profile->resolve(Net::Mode::Online); } } QDialog::done(result); } #include "InstallLoaderDialog.moc"
6,343
C++
.cpp
144
38.055556
140
0.695011
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,031
NewInstanceDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/NewInstanceDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "NewInstanceDialog.h" #include "Application.h" #include "ui/pages/modplatform/ModpackProviderBasePage.h" #include "ui/pages/modplatform/import_ftb/ImportFTBPage.h" #include "ui_NewInstanceDialog.h" #include <BaseVersion.h> #include <InstanceList.h> #include <icons/IconList.h> #include <tasks/Task.h> #include "IconPickerDialog.h" #include "ProgressDialog.h" #include "VersionSelectDialog.h" #include <QDialogButtonBox> #include <QFileDialog> #include <QLayout> #include <QPushButton> #include <QScreen> #include <QValidator> #include <utility> #include "ui/pages/modplatform/CustomPage.h" #include "ui/pages/modplatform/ImportPage.h" #include "ui/pages/modplatform/atlauncher/AtlPage.h" #include "ui/pages/modplatform/flame/FlamePage.h" #include "ui/pages/modplatform/legacy_ftb/Page.h" #include "ui/pages/modplatform/modrinth/ModrinthPage.h" #include "ui/pages/modplatform/technic/TechnicPage.h" #include "ui/widgets/PageContainer.h" NewInstanceDialog::NewInstanceDialog(const QString& initialGroup, const QString& url, const QMap<QString, QString>& extra_info, QWidget* parent) : QDialog(parent), ui(new Ui::NewInstanceDialog) { ui->setupUi(this); setWindowIcon(APPLICATION->getThemedIcon("new")); InstIconKey = "default"; ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey)); QStringList groups = APPLICATION->instances()->getGroups(); groups.prepend(""); int index = groups.indexOf(initialGroup); if (index == -1) { index = 1; groups.insert(index, initialGroup); } ui->groupBox->addItems(groups); ui->groupBox->setCurrentIndex(index); ui->groupBox->lineEdit()->setPlaceholderText(tr("No group")); // NOTE: m_buttons must be initialized before PageContainer, because it indirectly accesses m_buttons through setSuggestedPack! Do not // move this below. m_buttons = new QDialogButtonBox(QDialogButtonBox::Help | QDialogButtonBox::Ok | QDialogButtonBox::Cancel); m_container = new PageContainer(this, {}, this); m_container->setSizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Expanding); m_container->layout()->setContentsMargins(0, 0, 0, 0); ui->verticalLayout->insertWidget(2, m_container); m_container->addButtons(m_buttons); connect(m_container, &PageContainer::selectedPageChanged, this, [this](BasePage* previous, BasePage* selected) { m_buttons->button(QDialogButtonBox::Ok)->setEnabled(creationTask && !instName().isEmpty()); }); // Bonk Qt over its stupid head and make sure it understands which button is the default one... // See: https://stackoverflow.com/questions/24556831/qbuttonbox-set-default-button auto OkButton = m_buttons->button(QDialogButtonBox::Ok); OkButton->setDefault(true); OkButton->setAutoDefault(true); OkButton->setText(tr("OK")); connect(OkButton, &QPushButton::clicked, this, &NewInstanceDialog::accept); auto CancelButton = m_buttons->button(QDialogButtonBox::Cancel); CancelButton->setDefault(false); CancelButton->setAutoDefault(false); CancelButton->setText(tr("Cancel")); connect(CancelButton, &QPushButton::clicked, this, &NewInstanceDialog::reject); auto HelpButton = m_buttons->button(QDialogButtonBox::Help); HelpButton->setDefault(false); HelpButton->setAutoDefault(false); HelpButton->setText(tr("Help")); connect(HelpButton, &QPushButton::clicked, m_container, &PageContainer::help); if (!url.isEmpty()) { QUrl actualUrl(url); m_container->selectPage("import"); importPage->setUrl(url); importPage->setExtraInfo(extra_info); } updateDialogState(); if (APPLICATION->settings()->get("NewInstanceGeometry").isValid()) { restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get("NewInstanceGeometry").toByteArray())); } else { #if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) auto screen = parent->screen(); #else auto screen = QGuiApplication::primaryScreen(); #endif auto geometry = screen->availableSize(); resize(width(), qMin(geometry.height() - 50, 710)); } connect(m_container, &PageContainer::selectedPageChanged, this, &NewInstanceDialog::selectedPageChanged); } void NewInstanceDialog::reject() { APPLICATION->settings()->set("NewInstanceGeometry", saveGeometry().toBase64()); // This is just so that the pages get the close() call and can react to it, if needed. m_container->prepareToClose(); QDialog::reject(); } void NewInstanceDialog::accept() { APPLICATION->settings()->set("NewInstanceGeometry", saveGeometry().toBase64()); importIconNow(); // This is just so that the pages get the close() call and can react to it, if needed. m_container->prepareToClose(); QDialog::accept(); } QList<BasePage*> NewInstanceDialog::getPages() { QList<BasePage*> pages; importPage = new ImportPage(this); pages.append(new CustomPage(this)); pages.append(importPage); pages.append(new AtlPage(this)); if (APPLICATION->capabilities() & Application::SupportsFlame) pages.append(new FlamePage(this)); pages.append(new LegacyFTB::Page(this)); pages.append(new FTBImportAPP::ImportFTBPage(this)); pages.append(new ModrinthPage(this)); pages.append(new TechnicPage(this)); return pages; } QString NewInstanceDialog::dialogTitle() { return tr("New Instance"); } NewInstanceDialog::~NewInstanceDialog() { delete ui; } void NewInstanceDialog::setSuggestedPack(const QString& name, InstanceTask* task) { creationTask.reset(task); ui->instNameTextBox->setPlaceholderText(name); importVersion.clear(); if (!task) { ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey)); importIcon = false; } auto allowOK = task && !instName().isEmpty(); m_buttons->button(QDialogButtonBox::Ok)->setEnabled(allowOK); } void NewInstanceDialog::setSuggestedPack(const QString& name, QString version, InstanceTask* task) { creationTask.reset(task); ui->instNameTextBox->setPlaceholderText(name); importVersion = std::move(version); if (!task) { ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey)); importIcon = false; } auto allowOK = task && !instName().isEmpty(); m_buttons->button(QDialogButtonBox::Ok)->setEnabled(allowOK); } void NewInstanceDialog::setSuggestedIconFromFile(const QString& path, const QString& name) { importIcon = true; importIconPath = path; importIconName = name; // Hmm, for some reason they can be to small ui->iconButton->setIcon(QIcon(path)); } void NewInstanceDialog::setSuggestedIcon(const QString& key) { if (key == "default") return; auto icon = APPLICATION->icons()->getIcon(key); importIcon = false; ui->iconButton->setIcon(icon); } InstanceTask* NewInstanceDialog::extractTask() { InstanceTask* extracted = creationTask.release(); InstanceName inst_name(ui->instNameTextBox->placeholderText().trimmed(), importVersion); inst_name.setName(ui->instNameTextBox->text().trimmed()); extracted->setName(inst_name); extracted->setGroup(instGroup()); extracted->setIcon(iconKey()); return extracted; } void NewInstanceDialog::updateDialogState() { auto allowOK = creationTask && !instName().isEmpty(); auto OkButton = m_buttons->button(QDialogButtonBox::Ok); if (OkButton->isEnabled() != allowOK) { OkButton->setEnabled(allowOK); } } QString NewInstanceDialog::instName() const { auto result = ui->instNameTextBox->text().trimmed(); if (result.size()) { return result; } result = ui->instNameTextBox->placeholderText().trimmed(); if (result.size()) { return result; } return QString(); } QString NewInstanceDialog::instGroup() const { return ui->groupBox->currentText(); } QString NewInstanceDialog::iconKey() const { return InstIconKey; } void NewInstanceDialog::on_iconButton_clicked() { importIconNow(); // so the user can switch back IconPickerDialog dlg(this); dlg.execWithSelection(InstIconKey); if (dlg.result() == QDialog::Accepted) { InstIconKey = dlg.selectedIconKey; ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey)); importIcon = false; } } void NewInstanceDialog::on_instNameTextBox_textChanged([[maybe_unused]] const QString& arg1) { updateDialogState(); } void NewInstanceDialog::importIconNow() { if (importIcon) { APPLICATION->icons()->installIcon(importIconPath, importIconName); InstIconKey = importIconName.mid(0, importIconName.lastIndexOf('.')); importIcon = false; } APPLICATION->settings()->set("NewInstanceGeometry", saveGeometry().toBase64()); } void NewInstanceDialog::selectedPageChanged(BasePage* previous, BasePage* selected) { auto prevPage = dynamic_cast<ModpackProviderBasePage*>(previous); if (prevPage) { m_searchTerm = prevPage->getSerachTerm(); } auto nextPage = dynamic_cast<ModpackProviderBasePage*>(selected); if (nextPage) { nextPage->setSearchTerm(m_searchTerm); } }
10,902
C++
.cpp
281
34.451957
138
0.717179
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,032
ExportInstanceDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ExportInstanceDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ExportInstanceDialog.h" #include <BaseInstance.h> #include <MMCZip.h> #include <QFileDialog> #include <QFileSystemModel> #include <QMessageBox> #include "FileIgnoreProxy.h" #include "QObjectPtr.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ProgressDialog.h" #include "ui_ExportInstanceDialog.h" #include <FileSystem.h> #include <icons/IconList.h> #include <QDebug> #include <QFileInfo> #include <QPushButton> #include <QSaveFile> #include <QSortFilterProxyModel> #include <QStack> #include <functional> #include "Application.h" #include "SeparatorPrefixTree.h" ExportInstanceDialog::ExportInstanceDialog(InstancePtr instance, QWidget* parent) : QDialog(parent), ui(new Ui::ExportInstanceDialog), m_instance(instance) { ui->setupUi(this); auto model = new QFileSystemModel(this); model->setIconProvider(&icons); auto root = instance->instanceRoot(); proxyModel = new FileIgnoreProxy(root, this); proxyModel->setSourceModel(model); auto prefix = QDir(instance->instanceRoot()).relativeFilePath(instance->gameRoot()); proxyModel->ignoreFilesWithPath().insert({ FS::PathCombine(prefix, "logs"), FS::PathCombine(prefix, "crash-reports") }); proxyModel->ignoreFilesWithName().append({ ".DS_Store", "thumbs.db", "Thumbs.db" }); proxyModel->ignoreFilesWithPath().insert( { FS::PathCombine(prefix, ".cache"), FS::PathCombine(prefix, ".fabric"), FS::PathCombine(prefix, ".quilt") }); loadPackIgnore(); ui->treeView->setModel(proxyModel); ui->treeView->setRootIndex(proxyModel->mapFromSource(model->index(root))); ui->treeView->sortByColumn(0, Qt::AscendingOrder); connect(proxyModel, SIGNAL(rowsInserted(QModelIndex, int, int)), SLOT(rowsInserted(QModelIndex, int, int))); model->setFilter(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Hidden); model->setRootPath(root); auto headerView = ui->treeView->header(); headerView->setSectionResizeMode(QHeaderView::ResizeToContents); headerView->setSectionResizeMode(0, QHeaderView::Stretch); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } ExportInstanceDialog::~ExportInstanceDialog() { delete ui; } /// Save icon to instance's folder is needed void SaveIcon(InstancePtr m_instance) { auto iconKey = m_instance->iconKey(); auto iconList = APPLICATION->icons(); auto mmcIcon = iconList->icon(iconKey); if (!mmcIcon || mmcIcon->isBuiltIn()) { return; } auto path = mmcIcon->getFilePath(); if (!path.isNull()) { QFileInfo inInfo(path); FS::copy(path, FS::PathCombine(m_instance->instanceRoot(), inInfo.fileName()))(); return; } auto& image = mmcIcon->m_images[mmcIcon->type()]; auto& icon = image.icon; auto sizes = icon.availableSizes(); if (sizes.size() == 0) { return; } auto areaOf = [](QSize size) { return size.width() * size.height(); }; QSize largest = sizes[0]; // find variant with largest area for (auto size : sizes) { if (areaOf(largest) < areaOf(size)) { largest = size; } } auto pixmap = icon.pixmap(largest); pixmap.save(FS::PathCombine(m_instance->instanceRoot(), iconKey + ".png")); } void ExportInstanceDialog::doExport() { auto name = FS::RemoveInvalidFilenameChars(m_instance->name()); const QString output = QFileDialog::getSaveFileName(this, tr("Export %1").arg(m_instance->name()), FS::PathCombine(QDir::homePath(), name + ".zip"), "Zip (*.zip)", nullptr); if (output.isEmpty()) { QDialog::done(QDialog::Rejected); return; } SaveIcon(m_instance); auto files = QFileInfoList(); if (!MMCZip::collectFileListRecursively(m_instance->instanceRoot(), nullptr, &files, std::bind(&FileIgnoreProxy::filterFile, proxyModel, std::placeholders::_1))) { QMessageBox::warning(this, tr("Error"), tr("Unable to export instance")); QDialog::done(QDialog::Rejected); return; } auto task = makeShared<MMCZip::ExportToZipTask>(output, m_instance->instanceRoot(), files, "", true, true); connect(task.get(), &Task::failed, this, [this, output](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); }); connect(task.get(), &Task::finished, this, [task] { task->deleteLater(); }); ProgressDialog progress(this); progress.setSkipButton(true, tr("Abort")); auto result = progress.execWithTask(task.get()); QDialog::done(result); } void ExportInstanceDialog::done(int result) { savePackIgnore(); if (result == QDialog::Accepted) { doExport(); return; } QDialog::done(result); } void ExportInstanceDialog::rowsInserted(QModelIndex parent, int top, int bottom) { // WARNING: possible off-by-one? for (int i = top; i < bottom; i++) { auto node = proxyModel->index(i, 0, parent); if (proxyModel->shouldExpand(node)) { auto expNode = node.parent(); if (!expNode.isValid()) { continue; } ui->treeView->expand(node); } } } QString ExportInstanceDialog::ignoreFileName() { return FS::PathCombine(m_instance->instanceRoot(), ".packignore"); } void ExportInstanceDialog::loadPackIgnore() { auto filename = ignoreFileName(); QFile ignoreFile(filename); if (!ignoreFile.open(QIODevice::ReadOnly)) { return; } auto ignoreData = ignoreFile.readAll(); auto string = QString::fromUtf8(ignoreData); #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) proxyModel->setBlockedPaths(string.split('\n', Qt::SkipEmptyParts)); #else proxyModel->setBlockedPaths(string.split('\n', QString::SkipEmptyParts)); #endif } void ExportInstanceDialog::savePackIgnore() { auto ignoreData = proxyModel->blockedPaths().toStringList().join('\n').toUtf8(); auto filename = ignoreFileName(); try { FS::write(filename, ignoreData); } catch (const Exception& e) { qWarning() << e.cause(); } }
7,876
C++
.cpp
199
34.904523
136
0.68652
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,033
ProfileSelectDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ProfileSelectDialog.cpp
/* Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ProfileSelectDialog.h" #include "ui_ProfileSelectDialog.h" #include <QDebug> #include <QItemSelectionModel> #include <QPushButton> #include "Application.h" #include "ui/dialogs/ProgressDialog.h" ProfileSelectDialog::ProfileSelectDialog(const QString& message, int flags, QWidget* parent) : QDialog(parent), ui(new Ui::ProfileSelectDialog) { ui->setupUi(this); m_accounts = APPLICATION->accounts(); auto view = ui->listView; // view->setModel(m_accounts.get()); // view->hideColumn(AccountList::ActiveColumn); view->setColumnCount(1); view->setRootIsDecorated(false); // FIXME: use a real model, not this if (QTreeWidgetItem* header = view->headerItem()) { header->setText(0, tr("Name")); } else { view->setHeaderLabel(tr("Name")); } QList<QTreeWidgetItem*> items; for (int i = 0; i < m_accounts->count(); i++) { MinecraftAccountPtr account = m_accounts->at(i); QString profileLabel; if (account->isInUse()) { profileLabel = tr("%1 (in use)").arg(account->profileName()); } else { profileLabel = account->profileName(); } auto item = new QTreeWidgetItem(view); item->setText(0, profileLabel); item->setIcon(0, account->getFace()); item->setData(0, AccountList::PointerRole, QVariant::fromValue(account)); items.append(item); } view->addTopLevelItems(items); // Set the message label. ui->msgLabel->setVisible(!message.isEmpty()); ui->msgLabel->setText(message); // Flags... ui->globalDefaultCheck->setVisible(flags & GlobalDefaultCheckbox); ui->instDefaultCheck->setVisible(flags & InstanceDefaultCheckbox); qDebug() << flags; // Select the first entry in the list. ui->listView->setCurrentIndex(ui->listView->model()->index(0, 0)); connect(ui->listView, SIGNAL(doubleClicked(QModelIndex)), SLOT(on_buttonBox_accepted())); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } ProfileSelectDialog::~ProfileSelectDialog() { delete ui; } MinecraftAccountPtr ProfileSelectDialog::selectedAccount() const { return m_selected; } bool ProfileSelectDialog::useAsGlobalDefault() const { return ui->globalDefaultCheck->isChecked(); } bool ProfileSelectDialog::useAsInstDefaullt() const { return ui->instDefaultCheck->isChecked(); } void ProfileSelectDialog::on_buttonBox_accepted() { QModelIndexList selection = ui->listView->selectionModel()->selectedIndexes(); if (selection.size() > 0) { QModelIndex selected = selection.first(); m_selected = selected.data(AccountList::PointerRole).value<MinecraftAccountPtr>(); } close(); } void ProfileSelectDialog::on_buttonBox_rejected() { close(); }
3,483
C++
.cpp
95
32.357895
93
0.706912
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,034
ProgressDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ProgressDialog.cpp
/// SPDX-License-Identifier: GPL-3.0-only /* * PrismLaucher - Minecraft Launcher * Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ProgressDialog.h" #include <QPoint> #include "ui_ProgressDialog.h" #include <QDebug> #include <QKeyEvent> #include <limits> #include "tasks/Task.h" #include "ui/widgets/SubTaskProgressBar.h" // map a value in a numeric range of an arbitrary type to between 0 and INT_MAX // for getting the best precision out of the qt progress bar template <typename T, std::enable_if_t<std::is_arithmetic_v<T>, bool> = true> std::tuple<int, int> map_int_zero_max(T current, T range_max, T range_min) { int int_max = std::numeric_limits<int>::max(); auto type_range = range_max - range_min; double percentage = static_cast<double>(current - range_min) / static_cast<double>(type_range); int mapped_current = percentage * int_max; return { mapped_current, int_max }; } ProgressDialog::ProgressDialog(QWidget* parent) : QDialog(parent), ui(new Ui::ProgressDialog) { ui->setupUi(this); ui->taskProgressScrollArea->setHidden(true); this->setWindowFlags(this->windowFlags() & ~Qt::WindowContextHelpButtonHint); setAttribute(Qt::WidgetAttribute::WA_QuitOnClose, true); changeProgress(0, 100); updateSize(true); setSkipButton(false); } void ProgressDialog::setSkipButton(bool present, QString label) { ui->skipButton->setAutoDefault(false); ui->skipButton->setDefault(false); ui->skipButton->setFocusPolicy(Qt::ClickFocus); ui->skipButton->setEnabled(present); ui->skipButton->setVisible(present); ui->skipButton->setText(label); updateSize(); } void ProgressDialog::on_skipButton_clicked(bool checked) { Q_UNUSED(checked); if (ui->skipButton->isEnabled()) // prevent other triggers from aborting m_task->abort(); } ProgressDialog::~ProgressDialog() { for (auto conn : this->m_taskConnections) { disconnect(conn); } delete ui; } void ProgressDialog::updateSize(bool recenterParent) { QSize lastSize = this->size(); QPoint lastPos = this->pos(); int minHeight = ui->globalStatusDetailsLabel->minimumSize().height() + (ui->verticalLayout->spacing() * 2); minHeight += ui->globalProgressBar->minimumSize().height() + ui->verticalLayout->spacing(); if (!ui->taskProgressScrollArea->isHidden()) minHeight += ui->taskProgressScrollArea->minimumSizeHint().height() + ui->verticalLayout->spacing(); if (ui->skipButton->isVisible()) minHeight += ui->skipButton->height() + ui->verticalLayout->spacing(); minHeight = std::max(minHeight, 60); QSize minSize = QSize(480, minHeight); setMinimumSize(minSize); adjustSize(); QSize newSize = this->size(); // if the current window is a different size auto parent = this->parentWidget(); if (recenterParent && parent) { auto newX = std::max(0, parent->x() + ((parent->width() - newSize.width()) / 2)); auto newY = std::max(0, parent->y() + ((parent->height() - newSize.height()) / 2)); this->move(newX, newY); } else if (lastSize != newSize) { // center on old position after resize QSize sizeDiff = lastSize - newSize; // last size was smaller, the results should be negative auto newX = std::max(0, lastPos.x() + (sizeDiff.width() / 2)); auto newY = std::max(0, lastPos.y() + (sizeDiff.height() / 2)); this->move(newX, newY); } } int ProgressDialog::execWithTask(Task* task) { this->m_task = task; if (!task) { qDebug() << "Programmer error: Progress dialog created with null task."; return QDialog::DialogCode::Accepted; } QDialog::DialogCode result{}; if (handleImmediateResult(result)) { return result; } // Connect signals. this->m_taskConnections.push_back(connect(task, &Task::started, this, &ProgressDialog::onTaskStarted)); this->m_taskConnections.push_back(connect(task, &Task::failed, this, &ProgressDialog::onTaskFailed)); this->m_taskConnections.push_back(connect(task, &Task::succeeded, this, &ProgressDialog::onTaskSucceeded)); this->m_taskConnections.push_back(connect(task, &Task::status, this, &ProgressDialog::changeStatus)); this->m_taskConnections.push_back(connect(task, &Task::details, this, &ProgressDialog::changeStatus)); this->m_taskConnections.push_back(connect(task, &Task::stepProgress, this, &ProgressDialog::changeStepProgress)); this->m_taskConnections.push_back(connect(task, &Task::progress, this, &ProgressDialog::changeProgress)); this->m_taskConnections.push_back(connect(task, &Task::aborted, this, &ProgressDialog::hide)); this->m_taskConnections.push_back(connect(task, &Task::abortStatusChanged, ui->skipButton, &QPushButton::setEnabled)); m_is_multi_step = task->isMultiStep(); ui->taskProgressScrollArea->setHidden(!m_is_multi_step); updateSize(); // It's a good idea to start the task after we entered the dialog's event loop :^) if (!task->isRunning()) { QMetaObject::invokeMethod(task, &Task::start, Qt::QueuedConnection); } else { changeStatus(task->getStatus()); changeProgress(task->getProgress(), task->getTotalProgress()); } return QDialog::exec(); } // TODO: only provide the unique_ptr overloads int ProgressDialog::execWithTask(std::unique_ptr<Task>&& task) { connect(this, &ProgressDialog::destroyed, task.get(), &Task::deleteLater); return execWithTask(task.release()); } int ProgressDialog::execWithTask(std::unique_ptr<Task>& task) { connect(this, &ProgressDialog::destroyed, task.get(), &Task::deleteLater); return execWithTask(task.release()); } bool ProgressDialog::handleImmediateResult(QDialog::DialogCode& result) { if (m_task->isFinished()) { if (m_task->wasSuccessful()) { result = QDialog::Accepted; } else { result = QDialog::Rejected; } return true; } return false; } Task* ProgressDialog::getTask() { return m_task; } void ProgressDialog::onTaskStarted() {} void ProgressDialog::onTaskFailed([[maybe_unused]] QString failure) { reject(); hide(); } void ProgressDialog::onTaskSucceeded() { accept(); hide(); } void ProgressDialog::changeStatus([[maybe_unused]] const QString& status) { ui->globalStatusLabel->setText(m_task->getStatus()); ui->globalStatusLabel->adjustSize(); ui->globalStatusDetailsLabel->setText(m_task->getDetails()); ui->globalStatusDetailsLabel->adjustSize(); updateSize(); } void ProgressDialog::addTaskProgress(TaskStepProgress const& progress) { SubTaskProgressBar* task_bar = new SubTaskProgressBar(this); taskProgress.insert(progress.uid, task_bar); ui->taskProgressLayout->addWidget(task_bar); } void ProgressDialog::changeStepProgress(TaskStepProgress const& task_progress) { m_is_multi_step = true; if (ui->taskProgressScrollArea->isHidden()) { ui->taskProgressScrollArea->setHidden(false); updateSize(); } if (!taskProgress.contains(task_progress.uid)) addTaskProgress(task_progress); auto task_bar = taskProgress.value(task_progress.uid); auto const [mapped_current, mapped_total] = map_int_zero_max<qint64>(task_progress.current, task_progress.total, 0); if (task_progress.total <= 0) { task_bar->setRange(0, 0); } else { task_bar->setRange(0, mapped_total); } task_bar->setValue(mapped_current); task_bar->setStatus(task_progress.status); task_bar->setDetails(task_progress.details); if (task_progress.isDone()) { task_bar->setVisible(false); } } void ProgressDialog::changeProgress(qint64 current, qint64 total) { ui->globalProgressBar->setMaximum(total); ui->globalProgressBar->setValue(current); } void ProgressDialog::keyPressEvent(QKeyEvent* e) { if (ui->skipButton->isVisible()) { if (e->key() == Qt::Key_Escape) { on_skipButton_clicked(true); return; } else if (e->key() == Qt::Key_Tab) { ui->skipButton->setFocusPolicy(Qt::StrongFocus); ui->skipButton->setFocus(); ui->skipButton->setAutoDefault(true); ui->skipButton->setDefault(true); return; } } QDialog::keyPressEvent(e); } void ProgressDialog::closeEvent(QCloseEvent* e) { if (m_task && m_task->isRunning()) { e->ignore(); } else { QDialog::closeEvent(e); } }
9,894
C++
.cpp
252
34.813492
122
0.694919
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,035
OfflineLoginDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/OfflineLoginDialog.cpp
#include "OfflineLoginDialog.h" #include "ui_OfflineLoginDialog.h" #include <QtWidgets/QPushButton> OfflineLoginDialog::OfflineLoginDialog(QWidget* parent) : QDialog(parent), ui(new Ui::OfflineLoginDialog) { ui->setupUi(this); ui->progressBar->setVisible(false); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); } OfflineLoginDialog::~OfflineLoginDialog() { delete ui; } // Stage 1: User interaction void OfflineLoginDialog::accept() { setUserInputsEnabled(false); ui->progressBar->setVisible(true); // Setup the login task and start it m_account = MinecraftAccount::createOffline(ui->userTextBox->text()); m_loginTask = m_account->login(); connect(m_loginTask.get(), &Task::failed, this, &OfflineLoginDialog::onTaskFailed); connect(m_loginTask.get(), &Task::succeeded, this, &OfflineLoginDialog::onTaskSucceeded); connect(m_loginTask.get(), &Task::status, this, &OfflineLoginDialog::onTaskStatus); connect(m_loginTask.get(), &Task::progress, this, &OfflineLoginDialog::onTaskProgress); m_loginTask->start(); } void OfflineLoginDialog::setUserInputsEnabled(bool enable) { ui->userTextBox->setEnabled(enable); ui->buttonBox->setEnabled(enable); } void OfflineLoginDialog::on_allowLongUsernames_stateChanged(int value) { if (value == Qt::Checked) { ui->userTextBox->setMaxLength(INT_MAX); } else { ui->userTextBox->setMaxLength(16); } } // Enable the OK button only when the textbox contains something. void OfflineLoginDialog::on_userTextBox_textEdited(const QString& newText) { ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!newText.isEmpty()); } void OfflineLoginDialog::onTaskFailed(const QString& reason) { // Set message auto lines = reason.split('\n'); QString processed; for (auto line : lines) { if (line.size()) { processed += "<font color='red'>" + line + "</font><br />"; } else { processed += "<br />"; } } ui->label->setText(processed); // Re-enable user-interaction setUserInputsEnabled(true); ui->progressBar->setVisible(false); } void OfflineLoginDialog::onTaskSucceeded() { QDialog::accept(); } void OfflineLoginDialog::onTaskStatus(const QString& status) { ui->label->setText(status); } void OfflineLoginDialog::onTaskProgress(qint64 current, qint64 total) { ui->progressBar->setMaximum(total); ui->progressBar->setValue(current); } // Public interface MinecraftAccountPtr OfflineLoginDialog::newAccount(QWidget* parent, QString msg) { OfflineLoginDialog dlg(parent); dlg.ui->label->setText(msg); if (dlg.exec() == QDialog::Accepted) { return dlg.m_account; } return nullptr; }
3,066
C++
.cpp
89
30.573034
105
0.716988
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,037
ResourceDownloadDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ResourceDownloadDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ResourceDownloadDialog.h" #include <QEventLoop> #include <QList> #include <QPushButton> #include <algorithm> #include "Application.h" #include "ResourceDownloadTask.h" #include "minecraft/PackProfile.h" #include "minecraft/mod/ModFolderModel.h" #include "minecraft/mod/ResourcePackFolderModel.h" #include "minecraft/mod/ShaderPackFolderModel.h" #include "minecraft/mod/TexturePackFolderModel.h" #include "minecraft/mod/tasks/GetModDependenciesTask.h" #include "modplatform/ModIndex.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ProgressDialog.h" #include "ui/dialogs/ReviewMessageBox.h" #include "ui/pages/modplatform/ResourcePage.h" #include "ui/pages/modplatform/flame/FlameResourcePages.h" #include "ui/pages/modplatform/modrinth/ModrinthResourcePages.h" #include "modplatform/flame/FlameAPI.h" #include "modplatform/modrinth/ModrinthAPI.h" #include "ui/widgets/PageContainer.h" namespace ResourceDownload { ResourceDownloadDialog::ResourceDownloadDialog(QWidget* parent, const std::shared_ptr<ResourceFolderModel> base_model) : QDialog(parent) , m_base_model(base_model) , m_buttons(QDialogButtonBox::Help | QDialogButtonBox::Ok | QDialogButtonBox::Cancel) , m_vertical_layout(this) { setObjectName(QStringLiteral("ResourceDownloadDialog")); resize(std::max(0.5 * parent->width(), 400.0), std::max(0.75 * parent->height(), 400.0)); setWindowIcon(APPLICATION->getThemedIcon("new")); // Bonk Qt over its stupid head and make sure it understands which button is the default one... // See: https://stackoverflow.com/questions/24556831/qbuttonbox-set-default-button auto OkButton = m_buttons.button(QDialogButtonBox::Ok); OkButton->setEnabled(false); OkButton->setDefault(true); OkButton->setAutoDefault(true); OkButton->setText(tr("Review and confirm")); OkButton->setShortcut(tr("Ctrl+Return")); auto CancelButton = m_buttons.button(QDialogButtonBox::Cancel); CancelButton->setDefault(false); CancelButton->setAutoDefault(false); auto HelpButton = m_buttons.button(QDialogButtonBox::Help); HelpButton->setDefault(false); HelpButton->setAutoDefault(false); setWindowModality(Qt::WindowModal); } void ResourceDownloadDialog::accept() { if (!geometrySaveKey().isEmpty()) APPLICATION->settings()->set(geometrySaveKey(), saveGeometry().toBase64()); QDialog::accept(); } void ResourceDownloadDialog::reject() { auto selected = getTasks(); if (selected.count() > 0) { auto reply = CustomMessageBox::selectable(this, tr("Confirmation Needed"), tr("You have %1 selected resources.\n" "Are you sure you want to close this dialog?") .arg(selected.count()), QMessageBox::Question, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (reply != QMessageBox::Yes) { return; } } if (!geometrySaveKey().isEmpty()) APPLICATION->settings()->set(geometrySaveKey(), saveGeometry().toBase64()); QDialog::reject(); } // NOTE: We can't have this in the ctor because PageContainer calls a virtual function, and so // won't work with subclasses if we put it in this ctor. void ResourceDownloadDialog::initializeContainer() { m_container = new PageContainer(this, {}, this); m_container->setSizePolicy(QSizePolicy::Policy::Preferred, QSizePolicy::Policy::Expanding); m_container->layout()->setContentsMargins(0, 0, 0, 0); m_vertical_layout.addWidget(m_container); m_container->addButtons(&m_buttons); connect(m_container, &PageContainer::selectedPageChanged, this, &ResourceDownloadDialog::selectedPageChanged); } void ResourceDownloadDialog::connectButtons() { auto OkButton = m_buttons.button(QDialogButtonBox::Ok); OkButton->setToolTip( tr("Opens a new popup to review your selected %1 and confirm your selection. Shortcut: Ctrl+Return").arg(resourcesString())); connect(OkButton, &QPushButton::clicked, this, &ResourceDownloadDialog::confirm); auto CancelButton = m_buttons.button(QDialogButtonBox::Cancel); connect(CancelButton, &QPushButton::clicked, this, &ResourceDownloadDialog::reject); auto HelpButton = m_buttons.button(QDialogButtonBox::Help); connect(HelpButton, &QPushButton::clicked, m_container, &PageContainer::help); } void ResourceDownloadDialog::confirm() { auto confirm_dialog = ReviewMessageBox::create(this, tr("Confirm %1 to download").arg(resourcesString())); confirm_dialog->retranslateUi(resourcesString()); QHash<QString, GetModDependenciesTask::PackDependencyExtraInfo> dependencyExtraInfo; QStringList depNames; if (auto task = getModDependenciesTask(); task) { connect(task.get(), &Task::failed, this, [this](QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->exec(); }); auto weak = task.toWeakRef(); connect(task.get(), &Task::succeeded, this, [this, weak]() { QStringList warnings; if (auto task = weak.lock()) { warnings = task->warnings(); } if (warnings.count()) { CustomMessageBox::selectable(this, tr("Warnings"), warnings.join('\n'), QMessageBox::Warning)->exec(); } }); // Check for updates ProgressDialog progress_dialog(this); progress_dialog.setSkipButton(true, tr("Abort")); progress_dialog.setWindowTitle(tr("Checking for dependencies...")); auto ret = progress_dialog.execWithTask(task.get()); // If the dialog was skipped / some download error happened if (ret == QDialog::DialogCode::Rejected) { QMetaObject::invokeMethod(this, "reject", Qt::QueuedConnection); return; } else { for (auto dep : task->getDependecies()) { addResource(dep->pack, dep->version); depNames << dep->pack->name; } dependencyExtraInfo = task->getExtraInfo(); } } auto selected = getTasks(); std::sort(selected.begin(), selected.end(), [](const DownloadTaskPtr& a, const DownloadTaskPtr& b) { return QString::compare(a->getName(), b->getName(), Qt::CaseInsensitive) < 0; }); for (auto& task : selected) { auto extraInfo = dependencyExtraInfo.value(task->getPack()->addonId.toString()); confirm_dialog->appendResource({ task->getName(), task->getFilename(), task->getCustomPath(), ModPlatform::ProviderCapabilities::name(task->getProvider()), extraInfo.required_by, task->getVersion().version_type.toString(), !extraInfo.maybe_installed }); } if (confirm_dialog->exec()) { auto deselected = confirm_dialog->deselectedResources(); for (auto page : m_container->getPages()) { auto res = static_cast<ResourcePage*>(page); for (auto name : deselected) res->removeResourceFromPage(name); } this->accept(); } else { for (auto name : depNames) removeResource(name); } } bool ResourceDownloadDialog::selectPage(QString pageId) { return m_container->selectPage(pageId); } ResourcePage* ResourceDownloadDialog::selectedPage() { ResourcePage* result = dynamic_cast<ResourcePage*>(m_container->selectedPage()); Q_ASSERT(result != nullptr); return result; } void ResourceDownloadDialog::addResource(ModPlatform::IndexedPack::Ptr pack, ModPlatform::IndexedVersion& ver) { removeResource(pack->name); selectedPage()->addResourceToPage(pack, ver, getBaseModel()); setButtonStatus(); } void ResourceDownloadDialog::removeResource(const QString& pack_name) { for (auto page : m_container->getPages()) { static_cast<ResourcePage*>(page)->removeResourceFromPage(pack_name); } setButtonStatus(); } void ResourceDownloadDialog::setButtonStatus() { auto selected = false; for (auto page : m_container->getPages()) { auto res = static_cast<ResourcePage*>(page); selected = selected || res->hasSelectedPacks(); } m_buttons.button(QDialogButtonBox::Ok)->setEnabled(selected); } const QList<ResourceDownloadDialog::DownloadTaskPtr> ResourceDownloadDialog::getTasks() { QList<DownloadTaskPtr> selected; for (auto page : m_container->getPages()) { auto res = static_cast<ResourcePage*>(page); selected.append(res->selectedPacks()); } return selected; } void ResourceDownloadDialog::selectedPageChanged(BasePage* previous, BasePage* selected) { auto* prev_page = dynamic_cast<ResourcePage*>(previous); if (!prev_page) { qCritical() << "Page '" << previous->displayName() << "' in ResourceDownloadDialog is not a ResourcePage!"; return; } // Same effect as having a global search bar ResourcePage* result = dynamic_cast<ResourcePage*>(selected); Q_ASSERT(result != nullptr); result->setSearchTerm(prev_page->getSearchTerm()); } ModDownloadDialog::ModDownloadDialog(QWidget* parent, const std::shared_ptr<ModFolderModel>& mods, BaseInstance* instance) : ResourceDownloadDialog(parent, mods), m_instance(instance) { setWindowTitle(dialogTitle()); initializeContainer(); connectButtons(); if (!geometrySaveKey().isEmpty()) restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get(geometrySaveKey()).toByteArray())); } QList<BasePage*> ModDownloadDialog::getPages() { QList<BasePage*> pages; auto loaders = static_cast<MinecraftInstance*>(m_instance)->getPackProfile()->getSupportedModLoaders().value(); if (ModrinthAPI::validateModLoaders(loaders)) pages.append(ModrinthModPage::create(this, *m_instance)); if (APPLICATION->capabilities() & Application::SupportsFlame && FlameAPI::validateModLoaders(loaders)) pages.append(FlameModPage::create(this, *m_instance)); return pages; } GetModDependenciesTask::Ptr ModDownloadDialog::getModDependenciesTask() { if (!APPLICATION->settings()->get("ModDependenciesDisabled").toBool()) { // dependencies if (auto model = dynamic_cast<ModFolderModel*>(getBaseModel().get()); model) { QList<std::shared_ptr<GetModDependenciesTask::PackDependency>> selectedVers; for (auto& selected : getTasks()) { selectedVers.append(std::make_shared<GetModDependenciesTask::PackDependency>(selected->getPack(), selected->getVersion())); } return makeShared<GetModDependenciesTask>(m_instance, model, selectedVers); } } return nullptr; } ResourcePackDownloadDialog::ResourcePackDownloadDialog(QWidget* parent, const std::shared_ptr<ResourcePackFolderModel>& resource_packs, BaseInstance* instance) : ResourceDownloadDialog(parent, resource_packs), m_instance(instance) { setWindowTitle(dialogTitle()); initializeContainer(); connectButtons(); if (!geometrySaveKey().isEmpty()) restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get(geometrySaveKey()).toByteArray())); } QList<BasePage*> ResourcePackDownloadDialog::getPages() { QList<BasePage*> pages; pages.append(ModrinthResourcePackPage::create(this, *m_instance)); if (APPLICATION->capabilities() & Application::SupportsFlame) pages.append(FlameResourcePackPage::create(this, *m_instance)); return pages; } TexturePackDownloadDialog::TexturePackDownloadDialog(QWidget* parent, const std::shared_ptr<TexturePackFolderModel>& resource_packs, BaseInstance* instance) : ResourceDownloadDialog(parent, resource_packs), m_instance(instance) { setWindowTitle(dialogTitle()); initializeContainer(); connectButtons(); if (!geometrySaveKey().isEmpty()) restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get(geometrySaveKey()).toByteArray())); } QList<BasePage*> TexturePackDownloadDialog::getPages() { QList<BasePage*> pages; pages.append(ModrinthTexturePackPage::create(this, *m_instance)); if (APPLICATION->capabilities() & Application::SupportsFlame) pages.append(FlameTexturePackPage::create(this, *m_instance)); return pages; } ShaderPackDownloadDialog::ShaderPackDownloadDialog(QWidget* parent, const std::shared_ptr<ShaderPackFolderModel>& shaders, BaseInstance* instance) : ResourceDownloadDialog(parent, shaders), m_instance(instance) { setWindowTitle(dialogTitle()); initializeContainer(); connectButtons(); if (!geometrySaveKey().isEmpty()) restoreGeometry(QByteArray::fromBase64(APPLICATION->settings()->get(geometrySaveKey()).toByteArray())); } QList<BasePage*> ShaderPackDownloadDialog::getPages() { QList<BasePage*> pages; pages.append(ModrinthShaderPackPage::create(this, *m_instance)); if (APPLICATION->capabilities() & Application::SupportsFlame) pages.append(FlameShaderPackPage::create(this, *m_instance)); return pages; } void ResourceDownloadDialog::setResourceMetadata(const std::shared_ptr<Metadata::ModStruct>& meta) { switch (meta->provider) { case ModPlatform::ResourceProvider::MODRINTH: selectPage(Modrinth::id()); break; case ModPlatform::ResourceProvider::FLAME: selectPage(Flame::id()); break; } setWindowTitle(tr("Change %1 version").arg(meta->name)); m_container->hidePageList(); m_buttons.hide(); auto page = selectedPage(); page->openProject(meta->project_id); } } // namespace ResourceDownload
14,956
C++
.cpp
331
38.199396
139
0.687277
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,038
ImportResourceDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ImportResourceDialog.cpp
#include "ImportResourceDialog.h" #include "ui_ImportResourceDialog.h" #include <QFileDialog> #include <QPushButton> #include "Application.h" #include "InstanceList.h" #include <InstanceList.h> #include "ui/instanceview/InstanceDelegate.h" #include "ui/instanceview/InstanceProxyModel.h" ImportResourceDialog::ImportResourceDialog(QString file_path, PackedResourceType type, QWidget* parent) : QDialog(parent), ui(new Ui::ImportResourceDialog), m_resource_type(type), m_file_path(file_path) { ui->setupUi(this); setWindowModality(Qt::WindowModal); auto contentsWidget = ui->instanceView; contentsWidget->setViewMode(QListView::ListMode); contentsWidget->setFlow(QListView::LeftToRight); contentsWidget->setIconSize(QSize(48, 48)); contentsWidget->setMovement(QListView::Static); contentsWidget->setResizeMode(QListView::Adjust); contentsWidget->setSelectionMode(QAbstractItemView::SingleSelection); contentsWidget->setSpacing(5); contentsWidget->setWordWrap(true); contentsWidget->setWrapping(true); // NOTE: We can't have uniform sizes because the text may wrap if it's too long. If we set this, it will cut off the wrapped text. contentsWidget->setUniformItemSizes(false); contentsWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); contentsWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); contentsWidget->setItemDelegate(new ListViewDelegate()); proxyModel = new InstanceProxyModel(this); proxyModel->setSourceModel(APPLICATION->instances().get()); proxyModel->sort(0); contentsWidget->setModel(proxyModel); connect(contentsWidget, SIGNAL(doubleClicked(QModelIndex)), SLOT(activated(QModelIndex))); connect(contentsWidget->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), SLOT(selectionChanged(QItemSelection, QItemSelection))); ui->label->setText( tr("Choose the instance you would like to import this %1 to.").arg(ResourceUtils::getPackedTypeName(m_resource_type))); ui->label_file_path->setText(tr("File: %1").arg(m_file_path)); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } void ImportResourceDialog::activated(QModelIndex index) { selectedInstanceKey = index.data(InstanceList::InstanceIDRole).toString(); accept(); } void ImportResourceDialog::selectionChanged(QItemSelection selected, QItemSelection deselected) { if (selected.empty()) return; QString key = selected.first().indexes().first().data(InstanceList::InstanceIDRole).toString(); if (!key.isEmpty()) { selectedInstanceKey = key; } } ImportResourceDialog::~ImportResourceDialog() { delete ui; }
2,799
C++
.cpp
60
42.5
134
0.765591
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,039
VersionSelectDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/VersionSelectDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "VersionSelectDialog.h" #include <QDebug> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QHBoxLayout> #include <QtWidgets/QPushButton> #include <QtWidgets/QVBoxLayout> #include "ui/widgets/VersionSelectWidget.h" #include "BaseVersion.h" #include "BaseVersionList.h" VersionSelectDialog::VersionSelectDialog(BaseVersionList* vlist, QString title, QWidget* parent, bool cancelable) : QDialog(parent) { setObjectName(QStringLiteral("VersionSelectDialog")); resize(400, 347); m_verticalLayout = new QVBoxLayout(this); m_verticalLayout->setObjectName(QStringLiteral("verticalLayout")); m_versionWidget = new VersionSelectWidget(parent); m_verticalLayout->addWidget(m_versionWidget); m_horizontalLayout = new QHBoxLayout(); m_horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); m_refreshButton = new QPushButton(this); m_refreshButton->setObjectName(QStringLiteral("refreshButton")); m_horizontalLayout->addWidget(m_refreshButton); m_buttonBox = new QDialogButtonBox(this); m_buttonBox->setObjectName(QStringLiteral("buttonBox")); m_buttonBox->setOrientation(Qt::Horizontal); m_buttonBox->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); m_buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Ok")); m_buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); m_horizontalLayout->addWidget(m_buttonBox); m_verticalLayout->addLayout(m_horizontalLayout); retranslate(); connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(m_versionWidget->view(), &QAbstractItemView::doubleClicked, this, &QDialog::accept); connect(m_buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); QMetaObject::connectSlotsByName(this); setWindowModality(Qt::WindowModal); setWindowTitle(title); m_vlist = vlist; if (!cancelable) { m_buttonBox->button(QDialogButtonBox::Cancel)->setEnabled(false); } } void VersionSelectDialog::retranslate() { // FIXME: overrides custom title given in constructor! setWindowTitle(tr("Choose Version")); m_refreshButton->setToolTip(tr("Reloads the version list.")); m_refreshButton->setText(tr("&Refresh")); } void VersionSelectDialog::setCurrentVersion(const QString& version) { m_currentVersion = version; m_versionWidget->setCurrentVersion(version); } void VersionSelectDialog::setEmptyString(QString emptyString) { m_versionWidget->setEmptyString(emptyString); } void VersionSelectDialog::setEmptyErrorString(QString emptyErrorString) { m_versionWidget->setEmptyErrorString(emptyErrorString); } void VersionSelectDialog::setResizeOn(int column) { resizeOnColumn = column; } int VersionSelectDialog::exec() { QDialog::open(); m_versionWidget->initialize(m_vlist, true); m_versionWidget->selectSearch(); if (resizeOnColumn != -1) { m_versionWidget->setResizeOn(resizeOnColumn); } return QDialog::exec(); } void VersionSelectDialog::selectRecommended() { m_versionWidget->selectRecommended(); } BaseVersion::Ptr VersionSelectDialog::selectedVersion() const { return m_versionWidget->selectedVersion(); } void VersionSelectDialog::on_refreshButton_clicked() { m_versionWidget->loadList(); } void VersionSelectDialog::setExactFilter(BaseVersionList::ModelRoles role, QString filter) { m_versionWidget->setExactFilter(role, filter); } void VersionSelectDialog::setExactIfPresentFilter(BaseVersionList::ModelRoles role, QString filter) { m_versionWidget->setExactIfPresentFilter(role, filter); } void VersionSelectDialog::setFuzzyFilter(BaseVersionList::ModelRoles role, QString filter) { m_versionWidget->setFuzzyFilter(role, filter); }
5,312
C++
.cpp
135
36.303704
131
0.764226
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,040
CopyInstanceDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/CopyInstanceDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QLayout> #include <QPushButton> #include "Application.h" #include "BuildConfig.h" #include "CopyInstanceDialog.h" #include "ui_CopyInstanceDialog.h" #include "ui/dialogs/IconPickerDialog.h" #include "BaseInstance.h" #include "BaseVersion.h" #include "DesktopServices.h" #include "FileSystem.h" #include "InstanceList.h" #include "icons/IconList.h" CopyInstanceDialog::CopyInstanceDialog(InstancePtr original, QWidget* parent) : QDialog(parent), ui(new Ui::CopyInstanceDialog), m_original(original) { ui->setupUi(this); resize(minimumSizeHint()); layout()->setSizeConstraint(QLayout::SetFixedSize); InstIconKey = original->iconKey(); ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey)); ui->instNameTextBox->setText(original->name()); ui->instNameTextBox->setFocus(); QStringList groups = APPLICATION->instances()->getGroups(); groups.prepend(""); ui->groupBox->addItems(groups); int index = groups.indexOf(APPLICATION->instances()->getInstanceGroup(m_original->id())); if (index == -1) index = 0; ui->groupBox->setCurrentIndex(index); ui->groupBox->lineEdit()->setPlaceholderText(tr("No group")); ui->copySavesCheckbox->setChecked(m_selectedOptions.isCopySavesEnabled()); ui->keepPlaytimeCheckbox->setChecked(m_selectedOptions.isKeepPlaytimeEnabled()); ui->copyGameOptionsCheckbox->setChecked(m_selectedOptions.isCopyGameOptionsEnabled()); ui->copyResPacksCheckbox->setChecked(m_selectedOptions.isCopyResourcePacksEnabled()); ui->copyShaderPacksCheckbox->setChecked(m_selectedOptions.isCopyShaderPacksEnabled()); ui->copyServersCheckbox->setChecked(m_selectedOptions.isCopyServersEnabled()); ui->copyModsCheckbox->setChecked(m_selectedOptions.isCopyModsEnabled()); ui->copyScreenshotsCheckbox->setChecked(m_selectedOptions.isCopyScreenshotsEnabled()); ui->symbolicLinksCheckbox->setChecked(m_selectedOptions.isUseSymLinksEnabled()); ui->hardLinksCheckbox->setChecked(m_selectedOptions.isUseHardLinksEnabled()); ui->recursiveLinkCheckbox->setChecked(m_selectedOptions.isLinkRecursivelyEnabled()); ui->dontLinkSavesCheckbox->setChecked(m_selectedOptions.isDontLinkSavesEnabled()); auto detectedFS = FS::statFS(m_original->instanceRoot()).fsType; m_cloneSupported = FS::canCloneOnFS(detectedFS); m_linkSupported = FS::canLinkOnFS(detectedFS); if (m_cloneSupported) { ui->cloneSupportedLabel->setText(tr("Reflinks are supported on %1").arg(FS::getFilesystemTypeName(detectedFS))); } else { ui->cloneSupportedLabel->setText(tr("Reflinks aren't supported on %1").arg(FS::getFilesystemTypeName(detectedFS))); } #if defined(Q_OS_WIN) ui->symbolicLinksCheckbox->setIcon(style()->standardIcon(QStyle::SP_VistaShield)); ui->symbolicLinksCheckbox->setToolTip(tr("Use symbolic links instead of copying files.") + "\n" + tr("On Windows, symbolic links may require admin permission to create.")); #endif updateLinkOptions(); updateUseCloneCheckbox(); auto HelpButton = ui->buttonBox->button(QDialogButtonBox::Help); connect(HelpButton, &QPushButton::clicked, this, &CopyInstanceDialog::help); HelpButton->setText(tr("Help")); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } CopyInstanceDialog::~CopyInstanceDialog() { delete ui; } void CopyInstanceDialog::updateDialogState() { auto allowOK = !instName().isEmpty(); auto OkButton = ui->buttonBox->button(QDialogButtonBox::Ok); if (OkButton->isEnabled() != allowOK) { OkButton->setEnabled(allowOK); } } QString CopyInstanceDialog::instName() const { auto result = ui->instNameTextBox->text().trimmed(); if (result.size()) { return result; } return QString(); } QString CopyInstanceDialog::iconKey() const { return InstIconKey; } QString CopyInstanceDialog::instGroup() const { return ui->groupBox->currentText(); } const InstanceCopyPrefs& CopyInstanceDialog::getChosenOptions() const { return m_selectedOptions; } void CopyInstanceDialog::help() { DesktopServices::openUrl(QUrl(BuildConfig.HELP_URL.arg("instance-copy"))); } void CopyInstanceDialog::checkAllCheckboxes(const bool& b) { ui->keepPlaytimeCheckbox->setChecked(b); ui->copySavesCheckbox->setChecked(b); ui->copyGameOptionsCheckbox->setChecked(b); ui->copyResPacksCheckbox->setChecked(b); ui->copyShaderPacksCheckbox->setChecked(b); ui->copyServersCheckbox->setChecked(b); ui->copyModsCheckbox->setChecked(b); ui->copyScreenshotsCheckbox->setChecked(b); } // Check the "Select all" checkbox if all options are already selected: void CopyInstanceDialog::updateSelectAllCheckbox() { ui->selectAllCheckbox->blockSignals(true); ui->selectAllCheckbox->setChecked(m_selectedOptions.allTrue()); ui->selectAllCheckbox->blockSignals(false); } void CopyInstanceDialog::updateUseCloneCheckbox() { ui->useCloneCheckbox->setEnabled(m_cloneSupported && !ui->symbolicLinksCheckbox->isChecked() && !ui->hardLinksCheckbox->isChecked()); ui->useCloneCheckbox->setChecked(m_cloneSupported && m_selectedOptions.isUseCloneEnabled() && !ui->symbolicLinksCheckbox->isChecked() && !ui->hardLinksCheckbox->isChecked()); } void CopyInstanceDialog::updateLinkOptions() { ui->symbolicLinksCheckbox->setEnabled(m_linkSupported && !ui->hardLinksCheckbox->isChecked() && !ui->useCloneCheckbox->isChecked()); ui->hardLinksCheckbox->setEnabled(m_linkSupported && !ui->symbolicLinksCheckbox->isChecked() && !ui->useCloneCheckbox->isChecked()); ui->symbolicLinksCheckbox->setChecked(m_linkSupported && m_selectedOptions.isUseSymLinksEnabled() && !ui->useCloneCheckbox->isChecked()); ui->hardLinksCheckbox->setChecked(m_linkSupported && m_selectedOptions.isUseHardLinksEnabled() && !ui->useCloneCheckbox->isChecked()); bool linksInUse = (ui->symbolicLinksCheckbox->isChecked() || ui->hardLinksCheckbox->isChecked()); ui->recursiveLinkCheckbox->setEnabled(m_linkSupported && linksInUse && !ui->hardLinksCheckbox->isChecked()); ui->dontLinkSavesCheckbox->setEnabled(m_linkSupported && linksInUse); ui->recursiveLinkCheckbox->setChecked(m_linkSupported && linksInUse && m_selectedOptions.isLinkRecursivelyEnabled()); ui->dontLinkSavesCheckbox->setChecked(m_linkSupported && linksInUse && m_selectedOptions.isDontLinkSavesEnabled()); #if defined(Q_OS_WIN) auto OkButton = ui->buttonBox->button(QDialogButtonBox::Ok); OkButton->setIcon(m_selectedOptions.isUseSymLinksEnabled() ? style()->standardIcon(QStyle::SP_VistaShield) : QIcon()); #endif } void CopyInstanceDialog::on_iconButton_clicked() { IconPickerDialog dlg(this); dlg.execWithSelection(InstIconKey); if (dlg.result() == QDialog::Accepted) { InstIconKey = dlg.selectedIconKey; ui->iconButton->setIcon(APPLICATION->icons()->getIcon(InstIconKey)); } } void CopyInstanceDialog::on_instNameTextBox_textChanged([[maybe_unused]] const QString& arg1) { updateDialogState(); } void CopyInstanceDialog::on_selectAllCheckbox_stateChanged(int state) { bool checked; checked = (state == Qt::Checked); checkAllCheckboxes(checked); } void CopyInstanceDialog::on_copySavesCheckbox_stateChanged(int state) { m_selectedOptions.enableCopySaves(state == Qt::Checked); ui->dontLinkSavesCheckbox->setChecked((state == Qt::Checked) && ui->dontLinkSavesCheckbox->isChecked()); updateSelectAllCheckbox(); } void CopyInstanceDialog::on_keepPlaytimeCheckbox_stateChanged(int state) { m_selectedOptions.enableKeepPlaytime(state == Qt::Checked); updateSelectAllCheckbox(); } void CopyInstanceDialog::on_copyGameOptionsCheckbox_stateChanged(int state) { m_selectedOptions.enableCopyGameOptions(state == Qt::Checked); updateSelectAllCheckbox(); } void CopyInstanceDialog::on_copyResPacksCheckbox_stateChanged(int state) { m_selectedOptions.enableCopyResourcePacks(state == Qt::Checked); updateSelectAllCheckbox(); } void CopyInstanceDialog::on_copyShaderPacksCheckbox_stateChanged(int state) { m_selectedOptions.enableCopyShaderPacks(state == Qt::Checked); updateSelectAllCheckbox(); } void CopyInstanceDialog::on_copyServersCheckbox_stateChanged(int state) { m_selectedOptions.enableCopyServers(state == Qt::Checked); updateSelectAllCheckbox(); } void CopyInstanceDialog::on_copyModsCheckbox_stateChanged(int state) { m_selectedOptions.enableCopyMods(state == Qt::Checked); updateSelectAllCheckbox(); } void CopyInstanceDialog::on_copyScreenshotsCheckbox_stateChanged(int state) { m_selectedOptions.enableCopyScreenshots(state == Qt::Checked); updateSelectAllCheckbox(); } void CopyInstanceDialog::on_symbolicLinksCheckbox_stateChanged(int state) { m_selectedOptions.enableUseSymLinks(state == Qt::Checked); updateUseCloneCheckbox(); updateLinkOptions(); } void CopyInstanceDialog::on_hardLinksCheckbox_stateChanged(int state) { m_selectedOptions.enableUseHardLinks(state == Qt::Checked); if (state == Qt::Checked && !ui->recursiveLinkCheckbox->isChecked()) { ui->recursiveLinkCheckbox->setChecked(true); } updateUseCloneCheckbox(); updateLinkOptions(); } void CopyInstanceDialog::on_recursiveLinkCheckbox_stateChanged(int state) { m_selectedOptions.enableLinkRecursively(state == Qt::Checked); updateLinkOptions(); } void CopyInstanceDialog::on_dontLinkSavesCheckbox_stateChanged(int state) { m_selectedOptions.enableDontLinkSaves(state == Qt::Checked); } void CopyInstanceDialog::on_useCloneCheckbox_stateChanged(int state) { m_selectedOptions.enableUseClone(m_cloneSupported && (state == Qt::Checked)); updateUseCloneCheckbox(); updateLinkOptions(); }
11,513
C++
.cpp
266
39.511278
140
0.754464
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,041
ReviewMessageBox.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ReviewMessageBox.cpp
#include "ReviewMessageBox.h" #include "ui_ReviewMessageBox.h" #include "Application.h" #include <QPushButton> ReviewMessageBox::ReviewMessageBox(QWidget* parent, [[maybe_unused]] QString const& title, [[maybe_unused]] QString const& icon) : QDialog(parent), ui(new Ui::ReviewMessageBox) { ui->setupUi(this); auto back_button = ui->buttonBox->button(QDialogButtonBox::Cancel); back_button->setText(tr("Back")); ui->toggleDepsButton->hide(); ui->modTreeWidget->header()->setSectionResizeMode(0, QHeaderView::Stretch); ui->modTreeWidget->header()->setStretchLastSection(false); ui->modTreeWidget->header()->setSectionResizeMode(1, QHeaderView::ResizeToContents); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &ReviewMessageBox::accept); connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &ReviewMessageBox::reject); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } ReviewMessageBox::~ReviewMessageBox() { delete ui; } auto ReviewMessageBox::create(QWidget* parent, QString&& title, QString&& icon) -> ReviewMessageBox* { return new ReviewMessageBox(parent, title, icon); } void ReviewMessageBox::appendResource(ResourceInformation&& info) { auto itemTop = new QTreeWidgetItem(ui->modTreeWidget); itemTop->setCheckState(0, info.enabled ? Qt::CheckState::Checked : Qt::CheckState::Unchecked); itemTop->setText(0, info.name); if (!info.enabled) { itemTop->setToolTip(0, tr("Mod was disabled as it may be already installed.")); } auto filenameItem = new QTreeWidgetItem(itemTop); filenameItem->setText(0, tr("Filename: %1").arg(info.filename)); auto childIndx = 0; itemTop->insertChildren(childIndx++, { filenameItem }); if (!info.custom_file_path.isEmpty()) { auto customPathItem = new QTreeWidgetItem(itemTop); customPathItem->setText(0, tr("This download will be placed in: %1").arg(info.custom_file_path)); itemTop->insertChildren(1, { customPathItem }); itemTop->setIcon(1, QIcon(APPLICATION->getThemedIcon("status-yellow"))); itemTop->setToolTip( childIndx++, tr("This file will be downloaded to a folder location different from the default, possibly due to its loader requiring it.")); } auto providerItem = new QTreeWidgetItem(itemTop); providerItem->setText(0, tr("Provider: %1").arg(info.provider)); itemTop->insertChildren(childIndx++, { providerItem }); if (!info.required_by.isEmpty()) { auto requiredByItem = new QTreeWidgetItem(itemTop); if (info.required_by.length() == 1) { requiredByItem->setText(0, tr("Required by: %1").arg(info.required_by.back())); } else { requiredByItem->setText(0, tr("Required by:")); auto i = 0; for (auto req : info.required_by) { auto reqItem = new QTreeWidgetItem(requiredByItem); reqItem->setText(0, req); reqItem->insertChildren(i++, { reqItem }); } } itemTop->insertChildren(childIndx++, { requiredByItem }); ui->toggleDepsButton->show(); m_deps << itemTop; } auto versionTypeItem = new QTreeWidgetItem(itemTop); versionTypeItem->setText(0, tr("Version Type: %1").arg(info.version_type)); itemTop->insertChildren(childIndx++, { versionTypeItem }); ui->modTreeWidget->addTopLevelItem(itemTop); } auto ReviewMessageBox::deselectedResources() -> QStringList { QStringList list; auto* item = ui->modTreeWidget->topLevelItem(0); for (int i = 1; item != nullptr; ++i) { if (item->checkState(0) == Qt::CheckState::Unchecked) { list.append(item->text(0)); } item = ui->modTreeWidget->topLevelItem(i); } return list; } void ReviewMessageBox::retranslateUi(QString resources_name) { setWindowTitle(tr("Confirm %1 selection").arg(resources_name)); ui->explainLabel->setText(tr("You're about to download the following %1:").arg(resources_name)); ui->onlyCheckedLabel->setText(tr("Only %1 with a check will be downloaded!").arg(resources_name)); } void ReviewMessageBox::on_toggleDepsButton_clicked() { m_deps_checked = !m_deps_checked; auto state = m_deps_checked ? Qt::Checked : Qt::Unchecked; for (auto dep : m_deps) dep->setCheckState(0, state); };
4,479
C++
.cpp
98
39.734694
138
0.684428
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,042
EditAccountDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/EditAccountDialog.cpp
/* Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "EditAccountDialog.h" #include <DesktopServices.h> #include <QPushButton> #include <QUrl> #include "ui_EditAccountDialog.h" EditAccountDialog::EditAccountDialog(const QString& text, QWidget* parent, int flags) : QDialog(parent), ui(new Ui::EditAccountDialog) { ui->setupUi(this); ui->label->setText(text); ui->label->setVisible(!text.isEmpty()); ui->userTextBox->setEnabled(flags & UsernameField); ui->passTextBox->setEnabled(flags & PasswordField); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } EditAccountDialog::~EditAccountDialog() { delete ui; } void EditAccountDialog::on_label_linkActivated(const QString& link) { DesktopServices::openUrl(QUrl(link)); } void EditAccountDialog::setUsername(const QString& user) const { ui->userTextBox->setText(user); } QString EditAccountDialog::username() const { return ui->userTextBox->text(); } void EditAccountDialog::setPassword(const QString& pass) const { ui->passTextBox->setText(pass); } QString EditAccountDialog::password() const { return ui->passTextBox->text(); }
1,789
C++
.cpp
53
31.320755
134
0.758261
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,044
ExportPackDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/ExportPackDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ExportPackDialog.h" #include "minecraft/mod/ModFolderModel.h" #include "modplatform/ModIndex.h" #include "modplatform/flame/FlamePackExportTask.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ProgressDialog.h" #include "ui_ExportPackDialog.h" #include <QFileDialog> #include <QFileSystemModel> #include <QJsonDocument> #include <QMessageBox> #include <QPushButton> #include "FastFileIconProvider.h" #include "FileSystem.h" #include "MMCZip.h" #include "modplatform/modrinth/ModrinthPackExportTask.h" ExportPackDialog::ExportPackDialog(InstancePtr instance, QWidget* parent, ModPlatform::ResourceProvider provider) : QDialog(parent), instance(instance), ui(new Ui::ExportPackDialog), m_provider(provider) { Q_ASSERT(m_provider == ModPlatform::ResourceProvider::MODRINTH || m_provider == ModPlatform::ResourceProvider::FLAME); ui->setupUi(this); ui->name->setPlaceholderText(instance->name()); ui->name->setText(instance->settings()->get("ExportName").toString()); ui->version->setText(instance->settings()->get("ExportVersion").toString()); ui->optionalFiles->setChecked(instance->settings()->get("ExportOptionalFiles").toBool()); if (m_provider == ModPlatform::ResourceProvider::MODRINTH) { setWindowTitle(tr("Export Modrinth Pack")); ui->authorLabel->hide(); ui->author->hide(); ui->summary->setPlainText(instance->settings()->get("ExportSummary").toString()); } else { setWindowTitle(tr("Export CurseForge Pack")); ui->summaryLabel->hide(); ui->summary->hide(); ui->author->setText(instance->settings()->get("ExportAuthor").toString()); } // ensure a valid pack is generated // the name and version fields mustn't be empty connect(ui->name, &QLineEdit::textEdited, this, &ExportPackDialog::validate); connect(ui->version, &QLineEdit::textEdited, this, &ExportPackDialog::validate); // the instance name can technically be empty validate(); QFileSystemModel* model = new QFileSystemModel(this); model->setIconProvider(&icons); // use the game root - everything outside cannot be exported const QDir root(instance->gameRoot()); proxy = new FileIgnoreProxy(instance->gameRoot(), this); proxy->ignoreFilesWithPath().insert({ "logs", "crash-reports", ".cache", ".fabric", ".quilt" }); proxy->ignoreFilesWithName().append({ ".DS_Store", "thumbs.db", "Thumbs.db" }); proxy->setSourceModel(model); const QDir::Filters filter(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs | QDir::Hidden); for (const QString& file : root.entryList(filter)) { if (!(file == "mods" || file == "coremods" || file == "datapacks" || file == "config" || file == "options.txt" || file == "servers.dat")) proxy->blockedPaths().insert(file); } MinecraftInstance* mcInstance = dynamic_cast<MinecraftInstance*>(instance.get()); if (mcInstance) { for (auto& resourceModel : mcInstance->resourceLists()) if (resourceModel->indexDir().exists()) proxy->ignoreFilesWithPath().insert(root.relativeFilePath(resourceModel->indexDir().absolutePath())); } ui->files->setModel(proxy); ui->files->setRootIndex(proxy->mapFromSource(model->index(instance->gameRoot()))); ui->files->sortByColumn(0, Qt::AscendingOrder); model->setFilter(filter); model->setRootPath(instance->gameRoot()); QHeaderView* headerView = ui->files->header(); headerView->setSectionResizeMode(QHeaderView::ResizeToContents); headerView->setSectionResizeMode(0, QHeaderView::Stretch); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } ExportPackDialog::~ExportPackDialog() { delete ui; } void ExportPackDialog::done(int result) { auto settings = instance->settings(); settings->set("ExportName", ui->name->text()); settings->set("ExportVersion", ui->version->text()); settings->set("ExportOptionalFiles", ui->optionalFiles->isChecked()); if (m_provider == ModPlatform::ResourceProvider::MODRINTH) settings->set("ExportSummary", ui->summary->toPlainText()); else settings->set("ExportAuthor", ui->author->text()); if (result == Accepted) { const QString name = ui->name->text().isEmpty() ? instance->name() : ui->name->text(); const QString filename = FS::RemoveInvalidFilenameChars(name); QString output; if (m_provider == ModPlatform::ResourceProvider::MODRINTH) { output = QFileDialog::getSaveFileName(this, tr("Export %1").arg(name), FS::PathCombine(QDir::homePath(), filename + ".mrpack"), tr("Modrinth pack") + " (*.mrpack *.zip)", nullptr); if (output.isEmpty()) return; if (!(output.endsWith(".zip") || output.endsWith(".mrpack"))) output.append(".mrpack"); } else { output = QFileDialog::getSaveFileName(this, tr("Export %1").arg(name), FS::PathCombine(QDir::homePath(), filename + ".zip"), tr("CurseForge pack") + " (*.zip)", nullptr); if (output.isEmpty()) return; if (!output.endsWith(".zip")) output.append(".zip"); } Task* task; if (m_provider == ModPlatform::ResourceProvider::MODRINTH) { task = new ModrinthPackExportTask(name, ui->version->text(), ui->summary->toPlainText(), ui->optionalFiles->isChecked(), instance, output, std::bind(&FileIgnoreProxy::filterFile, proxy, std::placeholders::_1)); } else { task = new FlamePackExportTask(name, ui->version->text(), ui->author->text(), ui->optionalFiles->isChecked(), instance, output, std::bind(&FileIgnoreProxy::filterFile, proxy, std::placeholders::_1)); } connect(task, &Task::failed, [this](const QString reason) { CustomMessageBox::selectable(this, tr("Error"), reason, QMessageBox::Critical)->show(); }); connect(task, &Task::aborted, [this] { CustomMessageBox::selectable(this, tr("Task aborted"), tr("The task has been aborted by the user."), QMessageBox::Information) ->show(); }); connect(task, &Task::finished, [task] { task->deleteLater(); }); ProgressDialog progress(this); progress.setSkipButton(true, tr("Abort")); if (progress.execWithTask(task) != QDialog::Accepted) return; } QDialog::done(result); } void ExportPackDialog::validate() { ui->buttonBox->button(QDialogButtonBox::Ok) ->setDisabled(m_provider == ModPlatform::ResourceProvider::MODRINTH && ui->version->text().isEmpty()); }
7,693
C++
.cpp
150
43.973333
139
0.6609
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,045
SkinManageDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/dialogs/skins/SkinManageDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "SkinManageDialog.h" #include "ui_SkinManageDialog.h" #include <FileSystem.h> #include <QAction> #include <QDialog> #include <QEventLoop> #include <QFileDialog> #include <QFileInfo> #include <QKeyEvent> #include <QListView> #include <QMimeDatabase> #include <QPainter> #include <QUrl> #include "Application.h" #include "DesktopServices.h" #include "Json.h" #include "QObjectPtr.h" #include "minecraft/auth/Parsers.h" #include "minecraft/skins/CapeChange.h" #include "minecraft/skins/SkinDelete.h" #include "minecraft/skins/SkinList.h" #include "minecraft/skins/SkinModel.h" #include "minecraft/skins/SkinUpload.h" #include "net/Download.h" #include "net/NetJob.h" #include "tasks/Task.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ProgressDialog.h" #include "ui/instanceview/InstanceDelegate.h" SkinManageDialog::SkinManageDialog(QWidget* parent, MinecraftAccountPtr acct) : QDialog(parent), m_acct(acct), ui(new Ui::SkinManageDialog), m_list(this, APPLICATION->settings()->get("SkinsDir").toString(), acct) { ui->setupUi(this); setWindowModality(Qt::WindowModal); auto contentsWidget = ui->listView; contentsWidget->setViewMode(QListView::IconMode); contentsWidget->setFlow(QListView::LeftToRight); contentsWidget->setIconSize(QSize(48, 48)); contentsWidget->setMovement(QListView::Static); contentsWidget->setResizeMode(QListView::Adjust); contentsWidget->setSelectionMode(QAbstractItemView::SingleSelection); contentsWidget->setSpacing(5); contentsWidget->setWordWrap(false); contentsWidget->setWrapping(true); contentsWidget->setUniformItemSizes(true); contentsWidget->setTextElideMode(Qt::ElideRight); contentsWidget->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); contentsWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); contentsWidget->installEventFilter(this); contentsWidget->setItemDelegate(new ListViewDelegate(this)); contentsWidget->setAcceptDrops(true); contentsWidget->setDropIndicatorShown(true); contentsWidget->viewport()->setAcceptDrops(true); contentsWidget->setDragDropMode(QAbstractItemView::DropOnly); contentsWidget->setDefaultDropAction(Qt::CopyAction); contentsWidget->installEventFilter(this); contentsWidget->setModel(&m_list); connect(contentsWidget, SIGNAL(doubleClicked(QModelIndex)), SLOT(activated(QModelIndex))); connect(contentsWidget->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), SLOT(selectionChanged(QItemSelection, QItemSelection))); connect(ui->listView, &QListView::customContextMenuRequested, this, &SkinManageDialog::show_context_menu); setupCapes(); ui->listView->setCurrentIndex(m_list.index(m_list.getSelectedAccountSkin())); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("OK")); } SkinManageDialog::~SkinManageDialog() { delete ui; } void SkinManageDialog::activated(QModelIndex index) { m_selected_skin = index.data(Qt::UserRole).toString(); accept(); } void SkinManageDialog::selectionChanged(QItemSelection selected, QItemSelection deselected) { if (selected.empty()) return; QString key = selected.first().indexes().first().data(Qt::UserRole).toString(); if (key.isEmpty()) return; m_selected_skin = key; auto skin = m_list.skin(key); if (!skin || !skin->isValid()) return; ui->selectedModel->setPixmap(skin->getTexture().scaled(size() * (1. / 3), Qt::KeepAspectRatio, Qt::FastTransformation)); ui->capeCombo->setCurrentIndex(m_capes_idx.value(skin->getCapeId())); ui->steveBtn->setChecked(skin->getModel() == SkinModel::CLASSIC); ui->alexBtn->setChecked(skin->getModel() == SkinModel::SLIM); } void SkinManageDialog::delayed_scroll(QModelIndex model_index) { auto contentsWidget = ui->listView; contentsWidget->scrollTo(model_index); } void SkinManageDialog::on_openDirBtn_clicked() { DesktopServices::openPath(m_list.getDir(), true); } void SkinManageDialog::on_fileBtn_clicked() { auto filter = QMimeDatabase().mimeTypeForName("image/png").filterString(); QString raw_path = QFileDialog::getOpenFileName(this, tr("Select Skin Texture"), QString(), filter); if (raw_path.isNull()) { return; } auto message = m_list.installSkin(raw_path, {}); if (!message.isEmpty()) { CustomMessageBox::selectable(this, tr("Selected file is not a valid skin"), message, QMessageBox::Critical)->show(); return; } } QPixmap previewCape(QPixmap capeImage) { QPixmap preview = QPixmap(10, 16); QPainter painter(&preview); painter.drawPixmap(0, 0, capeImage.copy(1, 1, 10, 16)); return preview.scaled(80, 128, Qt::IgnoreAspectRatio, Qt::FastTransformation); } void SkinManageDialog::setupCapes() { // FIXME: add a model for this, download/refresh the capes on demand auto& accountData = *m_acct->accountData(); int index = 0; ui->capeCombo->addItem(tr("No Cape"), QVariant()); auto currentCape = accountData.minecraftProfile.currentCape; if (currentCape.isEmpty()) { ui->capeCombo->setCurrentIndex(index); } auto capesDir = FS::PathCombine(m_list.getDir(), "capes"); NetJob::Ptr job{ new NetJob(tr("Download capes"), APPLICATION->network()) }; bool needsToDownload = false; for (auto& cape : accountData.minecraftProfile.capes) { auto path = FS::PathCombine(capesDir, cape.id + ".png"); if (cape.data.size()) { QPixmap capeImage; if (capeImage.loadFromData(cape.data, "PNG") && capeImage.save(path)) { m_capes[cape.id] = previewCape(capeImage); continue; } } if (QFileInfo(path).exists()) { continue; } if (!cape.url.isEmpty()) { needsToDownload = true; job->addNetAction(Net::Download::makeFile(cape.url, path)); } } if (needsToDownload) { ProgressDialog dlg(this); dlg.execWithTask(job.get()); } for (auto& cape : accountData.minecraftProfile.capes) { index++; QPixmap capeImage; if (!m_capes.contains(cape.id)) { auto path = FS::PathCombine(capesDir, cape.id + ".png"); if (QFileInfo(path).exists() && capeImage.load(path)) { capeImage = previewCape(capeImage); m_capes[cape.id] = capeImage; } } if (!capeImage.isNull()) { ui->capeCombo->addItem(capeImage, cape.alias, cape.id); } else { ui->capeCombo->addItem(cape.alias, cape.id); } m_capes_idx[cape.id] = index; } } void SkinManageDialog::on_capeCombo_currentIndexChanged(int index) { auto id = ui->capeCombo->currentData(); auto cape = m_capes.value(id.toString(), {}); if (!cape.isNull()) { ui->capeImage->setPixmap(cape.scaled(size() * (1. / 3), Qt::KeepAspectRatio, Qt::FastTransformation)); } if (auto skin = m_list.skin(m_selected_skin); skin) { skin->setCapeId(id.toString()); } } void SkinManageDialog::on_steveBtn_toggled(bool checked) { if (auto skin = m_list.skin(m_selected_skin); skin) { skin->setModel(checked ? SkinModel::CLASSIC : SkinModel::SLIM); } } void SkinManageDialog::accept() { auto skin = m_list.skin(m_selected_skin); if (!skin) { reject(); return; } auto path = skin->getPath(); ProgressDialog prog(this); NetJob::Ptr skinUpload{ new NetJob(tr("Change skin"), APPLICATION->network(), 1) }; if (!QFile::exists(path)) { CustomMessageBox::selectable(this, tr("Skin Upload"), tr("Skin file does not exist!"), QMessageBox::Warning)->exec(); reject(); return; } skinUpload->addNetAction(SkinUpload::make(m_acct->accessToken(), skin->getPath(), skin->getModelString())); auto selectedCape = skin->getCapeId(); if (selectedCape != m_acct->accountData()->minecraftProfile.currentCape) { skinUpload->addNetAction(CapeChange::make(m_acct->accessToken(), selectedCape)); } skinUpload->addTask(m_acct->refresh().staticCast<Task>()); if (prog.execWithTask(skinUpload.get()) != QDialog::Accepted) { CustomMessageBox::selectable(this, tr("Skin Upload"), tr("Failed to upload skin!"), QMessageBox::Warning)->exec(); reject(); return; } skin->setURL(m_acct->accountData()->minecraftProfile.skin.url); QDialog::accept(); } void SkinManageDialog::on_resetBtn_clicked() { ProgressDialog prog(this); NetJob::Ptr skinReset{ new NetJob(tr("Reset skin"), APPLICATION->network(), 1) }; skinReset->addNetAction(SkinDelete::make(m_acct->accessToken())); skinReset->addTask(m_acct->refresh().staticCast<Task>()); if (prog.execWithTask(skinReset.get()) != QDialog::Accepted) { CustomMessageBox::selectable(this, tr("Skin Delete"), tr("Failed to delete current skin!"), QMessageBox::Warning)->exec(); reject(); return; } QDialog::accept(); } void SkinManageDialog::show_context_menu(const QPoint& pos) { QMenu myMenu(tr("Context menu"), this); myMenu.addAction(ui->action_Rename_Skin); myMenu.addAction(ui->action_Delete_Skin); myMenu.exec(ui->listView->mapToGlobal(pos)); } bool SkinManageDialog::eventFilter(QObject* obj, QEvent* ev) { if (obj == ui->listView) { if (ev->type() == QEvent::KeyPress) { QKeyEvent* keyEvent = static_cast<QKeyEvent*>(ev); switch (keyEvent->key()) { case Qt::Key_Delete: on_action_Delete_Skin_triggered(false); return true; case Qt::Key_F2: on_action_Rename_Skin_triggered(false); return true; default: break; } } } return QDialog::eventFilter(obj, ev); } void SkinManageDialog::on_action_Rename_Skin_triggered(bool checked) { if (!m_selected_skin.isEmpty()) { ui->listView->edit(ui->listView->currentIndex()); } } void SkinManageDialog::on_action_Delete_Skin_triggered(bool checked) { if (m_selected_skin.isEmpty()) return; if (m_list.getSkinIndex(m_selected_skin) == m_list.getSelectedAccountSkin()) { CustomMessageBox::selectable(this, tr("Delete error"), tr("Can not delete skin that is in use."), QMessageBox::Warning)->exec(); return; } auto skin = m_list.skin(m_selected_skin); if (!skin) return; auto response = CustomMessageBox::selectable(this, tr("Confirm Deletion"), tr("You are about to delete \"%1\".\n" "Are you sure?") .arg(skin->name()), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No) ->exec(); if (response == QMessageBox::Yes) { if (!m_list.deleteSkin(m_selected_skin, true)) { m_list.deleteSkin(m_selected_skin, false); } } } void SkinManageDialog::on_urlBtn_clicked() { auto url = QUrl(ui->urlLine->text()); if (!url.isValid()) { CustomMessageBox::selectable(this, tr("Invalid url"), tr("Invalid url"), QMessageBox::Critical)->show(); return; } NetJob::Ptr job{ new NetJob(tr("Download skin"), APPLICATION->network()) }; job->setAskRetry(false); auto path = FS::PathCombine(m_list.getDir(), url.fileName()); job->addNetAction(Net::Download::makeFile(url, path)); ProgressDialog dlg(this); dlg.execWithTask(job.get()); SkinModel s(path); if (!s.isValid()) { CustomMessageBox::selectable(this, tr("URL is not a valid skin"), QFileInfo::exists(path) ? tr("Skin images must be 64x64 or 64x32 pixel PNG files.") : tr("Unable to download the skin: '%1'.").arg(ui->urlLine->text()), QMessageBox::Critical) ->show(); QFile::remove(path); return; } ui->urlLine->setText(""); if (QFileInfo(path).suffix().isEmpty()) { QFile::rename(path, path + ".png"); } } class WaitTask : public Task { public: WaitTask() : m_loop(), m_done(false) {}; virtual ~WaitTask() = default; public slots: void quit() { m_done = true; m_loop.quit(); } protected: virtual void executeTask() { if (!m_done) m_loop.exec(); emitSucceeded(); }; private: QEventLoop m_loop; bool m_done; }; void SkinManageDialog::on_userBtn_clicked() { auto user = ui->urlLine->text(); if (user.isEmpty()) { return; } MinecraftProfile mcProfile; auto path = FS::PathCombine(m_list.getDir(), user + ".png"); NetJob::Ptr job{ new NetJob(tr("Download user skin"), APPLICATION->network(), 1) }; job->setAskRetry(false); auto uuidOut = std::make_shared<QByteArray>(); auto profileOut = std::make_shared<QByteArray>(); auto uuidLoop = makeShared<WaitTask>(); auto profileLoop = makeShared<WaitTask>(); auto getUUID = Net::Download::makeByteArray("https://api.mojang.com/users/profiles/minecraft/" + user, uuidOut); auto getProfile = Net::Download::makeByteArray(QUrl(), profileOut); auto downloadSkin = Net::Download::makeFile(QUrl(), path); QString failReason; connect(getUUID.get(), &Task::aborted, uuidLoop.get(), &WaitTask::quit); connect(getUUID.get(), &Task::failed, this, [&failReason](QString reason) { qCritical() << "Couldn't get user UUID:" << reason; failReason = tr("failed to get user UUID"); }); connect(getUUID.get(), &Task::failed, uuidLoop.get(), &WaitTask::quit); connect(getProfile.get(), &Task::aborted, profileLoop.get(), &WaitTask::quit); connect(getProfile.get(), &Task::failed, profileLoop.get(), &WaitTask::quit); connect(getProfile.get(), &Task::failed, this, [&failReason](QString reason) { qCritical() << "Couldn't get user profile:" << reason; failReason = tr("failed to get user profile"); }); connect(downloadSkin.get(), &Task::failed, this, [&failReason](QString reason) { qCritical() << "Couldn't download skin:" << reason; failReason = tr("failed to download skin"); }); connect(getUUID.get(), &Task::succeeded, this, [uuidLoop, uuidOut, job, getProfile, &failReason] { try { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*uuidOut, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Minecraft skin service at " << parse_error.offset << " reason: " << parse_error.errorString(); failReason = tr("failed to parse get user UUID response"); uuidLoop->quit(); return; } const auto root = doc.object(); auto id = Json::ensureString(root, "id"); if (!id.isEmpty()) { getProfile->setUrl("https://sessionserver.mojang.com/session/minecraft/profile/" + id); } else { failReason = tr("user id is empty"); job->abort(); } } catch (const Exception& e) { qCritical() << "Couldn't load skin json:" << e.cause(); failReason = tr("failed to parse get user UUID response"); } uuidLoop->quit(); }); connect(getProfile.get(), &Task::succeeded, this, [profileLoop, profileOut, job, getProfile, &mcProfile, downloadSkin, &failReason] { if (Parsers::parseMinecraftProfileMojang(*profileOut, mcProfile)) { downloadSkin->setUrl(mcProfile.skin.url); } else { failReason = tr("failed to parse get user profile response"); job->abort(); } profileLoop->quit(); }); job->addNetAction(getUUID); job->addTask(uuidLoop); job->addNetAction(getProfile); job->addTask(profileLoop); job->addNetAction(downloadSkin); ProgressDialog dlg(this); dlg.execWithTask(job.get()); SkinModel s(path); if (!s.isValid()) { if (failReason.isEmpty()) { failReason = tr("the skin is invalid"); } CustomMessageBox::selectable(this, tr("Username not found"), tr("Unable to find the skin for '%1'\n because: %2.").arg(user, failReason), QMessageBox::Critical) ->show(); QFile::remove(path); return; } ui->urlLine->setText(""); s.setModel(mcProfile.skin.variant.toUpper() == "SLIM" ? SkinModel::SLIM : SkinModel::CLASSIC); s.setURL(mcProfile.skin.url); if (m_capes.contains(mcProfile.currentCape)) { s.setCapeId(mcProfile.currentCape); } m_list.updateSkin(&s); } void SkinManageDialog::resizeEvent(QResizeEvent* event) { QWidget::resizeEvent(event); QSize s = size() * (1. / 3); if (auto skin = m_list.skin(m_selected_skin); skin) { if (skin->isValid()) { ui->selectedModel->setPixmap(skin->getTexture().scaled(s, Qt::KeepAspectRatio, Qt::FastTransformation)); } } auto id = ui->capeCombo->currentData(); auto cape = m_capes.value(id.toString(), {}); if (!cape.isNull()) { ui->capeImage->setPixmap(cape.scaled(s, Qt::KeepAspectRatio, Qt::FastTransformation)); } }
18,569
C++
.cpp
461
33.357918
138
0.644405
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,046
DropLabel.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/DropLabel.cpp
#include "DropLabel.h" #include <QDropEvent> #include <QMimeData> DropLabel::DropLabel(QWidget* parent) : QLabel(parent) { setAcceptDrops(true); } void DropLabel::dragEnterEvent(QDragEnterEvent* event) { event->acceptProposedAction(); } void DropLabel::dragMoveEvent(QDragMoveEvent* event) { event->acceptProposedAction(); } void DropLabel::dragLeaveEvent(QDragLeaveEvent* event) { event->accept(); } void DropLabel::dropEvent(QDropEvent* event) { const QMimeData* mimeData = event->mimeData(); if (!mimeData) { return; } if (mimeData->hasUrls()) { auto urls = mimeData->urls(); emit droppedURLs(urls); } event->acceptProposedAction(); }
711
C++
.cpp
31
19.580645
54
0.71535
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,047
Common.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/Common.cpp
#include "Common.h" // Origin: Qt // More specifically, this is a trimmed down version on the algorithm in: // https://code.woboq.org/qt5/qtbase/src/widgets/styles/qcommonstyle.cpp.html#846 QList<std::pair<qreal, QString>> viewItemTextLayout(QTextLayout& textLayout, int lineWidth, qreal& height) { QList<std::pair<qreal, QString>> lines; height = 0; textLayout.beginLayout(); QString str = textLayout.text(); while (true) { QTextLine line = textLayout.createLine(); if (!line.isValid()) break; if (line.textLength() == 0) break; line.setLineWidth(lineWidth); line.setPosition(QPointF(0, height)); height += line.height(); lines.append(std::make_pair(line.naturalTextWidth(), str.mid(line.textStart(), line.textLength()))); } textLayout.endLayout(); return lines; }
887
C++
.cpp
24
30.916667
108
0.663934
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,048
ModFilterWidget.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/ModFilterWidget.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ModFilterWidget.h" #include <QCheckBox> #include <QComboBox> #include <QListWidget> #include <algorithm> #include <list> #include "BaseVersionList.h" #include "Version.h" #include "meta/Index.h" #include "modplatform/ModIndex.h" #include "ui/widgets/CheckComboBox.h" #include "ui_ModFilterWidget.h" #include "Application.h" #include "minecraft/PackProfile.h" unique_qobject_ptr<ModFilterWidget> ModFilterWidget::create(MinecraftInstance* instance, bool extended, QWidget* parent) { return unique_qobject_ptr<ModFilterWidget>(new ModFilterWidget(instance, extended, parent)); } class VersionBasicModel : public QIdentityProxyModel { Q_OBJECT public: explicit VersionBasicModel(QObject* parent = nullptr) : QIdentityProxyModel(parent) {} virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override { if (role == Qt::DisplayRole) return QIdentityProxyModel::data(index, BaseVersionList::VersionIdRole); if (role == Qt::UserRole) return QIdentityProxyModel::data(index, BaseVersionList::VersionIdRole); return {}; } }; class AllVersionProxyModel : public QSortFilterProxyModel { Q_OBJECT public: AllVersionProxyModel(QObject* parent = nullptr) : QSortFilterProxyModel(parent) {} int rowCount(const QModelIndex& parent = QModelIndex()) const override { return QSortFilterProxyModel::rowCount(parent) + 1; } QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override { if (!index.isValid()) { return {}; } if (index.row() == 0) { if (role == Qt::DisplayRole) { return tr("All Versions"); } if (role == Qt::UserRole) { return "all"; } return {}; } QModelIndex newIndex = QSortFilterProxyModel::index(index.row() - 1, index.column()); return QSortFilterProxyModel::data(newIndex, role); } Qt::ItemFlags flags(const QModelIndex& index) const override { if (index.row() == 0) { return Qt::ItemIsSelectable | Qt::ItemIsEnabled; } return QSortFilterProxyModel::flags(index); } }; ModFilterWidget::ModFilterWidget(MinecraftInstance* instance, bool extended, QWidget* parent) : QTabWidget(parent), ui(new Ui::ModFilterWidget), m_instance(instance), m_filter(new Filter()) { ui->setupUi(this); m_versions_proxy = new VersionProxyModel(this); m_versions_proxy->setFilter(BaseVersionList::TypeRole, new ExactFilter("release")); QAbstractProxyModel* proxy = new VersionBasicModel(this); proxy->setSourceModel(m_versions_proxy); if (extended) { if (!m_instance) { ui->environmentGroup->hide(); } ui->versions->setSourceModel(proxy); ui->versions->setSeparator(", "); ui->versions->setDefaultText(tr("All Versions")); ui->version->hide(); } else { auto allVersions = new AllVersionProxyModel(this); allVersions->setSourceModel(proxy); proxy = allVersions; ui->version->setModel(proxy); ui->versions->hide(); ui->showAllVersions->hide(); ui->environmentGroup->hide(); ui->openSource->hide(); } ui->versions->setStyleSheet("combobox-popup: 0;"); ui->version->setStyleSheet("combobox-popup: 0;"); connect(ui->showAllVersions, &QCheckBox::stateChanged, this, &ModFilterWidget::onShowAllVersionsChanged); connect(ui->versions, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ModFilterWidget::onVersionFilterChanged); connect(ui->versions, &CheckComboBox::checkedItemsChanged, this, [this] { onVersionFilterChanged(0); }); connect(ui->version, &QComboBox::currentTextChanged, this, &ModFilterWidget::onVersionFilterTextChanged); connect(ui->neoForge, &QCheckBox::stateChanged, this, &ModFilterWidget::onLoadersFilterChanged); connect(ui->forge, &QCheckBox::stateChanged, this, &ModFilterWidget::onLoadersFilterChanged); connect(ui->fabric, &QCheckBox::stateChanged, this, &ModFilterWidget::onLoadersFilterChanged); connect(ui->quilt, &QCheckBox::stateChanged, this, &ModFilterWidget::onLoadersFilterChanged); connect(ui->neoForge, &QCheckBox::stateChanged, this, &ModFilterWidget::onLoadersFilterChanged); connect(ui->forge, &QCheckBox::stateChanged, this, &ModFilterWidget::onLoadersFilterChanged); connect(ui->fabric, &QCheckBox::stateChanged, this, &ModFilterWidget::onLoadersFilterChanged); connect(ui->quilt, &QCheckBox::stateChanged, this, &ModFilterWidget::onLoadersFilterChanged); if (extended) { connect(ui->clientSide, &QCheckBox::stateChanged, this, &ModFilterWidget::onSideFilterChanged); connect(ui->serverSide, &QCheckBox::stateChanged, this, &ModFilterWidget::onSideFilterChanged); } connect(ui->hideInstalled, &QCheckBox::stateChanged, this, &ModFilterWidget::onHideInstalledFilterChanged); connect(ui->openSource, &QCheckBox::stateChanged, this, &ModFilterWidget::onOpenSourceFilterChanged); connect(ui->releaseCb, &QCheckBox::stateChanged, this, &ModFilterWidget::onReleaseFilterChanged); connect(ui->betaCb, &QCheckBox::stateChanged, this, &ModFilterWidget::onReleaseFilterChanged); connect(ui->alphaCb, &QCheckBox::stateChanged, this, &ModFilterWidget::onReleaseFilterChanged); connect(ui->unknownCb, &QCheckBox::stateChanged, this, &ModFilterWidget::onReleaseFilterChanged); setHidden(true); loadVersionList(); prepareBasicFilter(); } auto ModFilterWidget::getFilter() -> std::shared_ptr<Filter> { m_filter_changed = false; return m_filter; } ModFilterWidget::~ModFilterWidget() { delete ui; } void ModFilterWidget::loadVersionList() { m_version_list = APPLICATION->metadataIndex()->get("net.minecraft"); if (!m_version_list->isLoaded()) { QEventLoop load_version_list_loop; QTimer time_limit_for_list_load; time_limit_for_list_load.setTimerType(Qt::TimerType::CoarseTimer); time_limit_for_list_load.setSingleShot(true); time_limit_for_list_load.callOnTimeout(&load_version_list_loop, &QEventLoop::quit); time_limit_for_list_load.start(4000); auto task = m_version_list->getLoadTask(); connect(task.get(), &Task::failed, [this] { ui->versions->setEnabled(false); ui->showAllVersions->setEnabled(false); }); connect(task.get(), &Task::finished, &load_version_list_loop, &QEventLoop::quit); if (!task->isRunning()) task->start(); load_version_list_loop.exec(); if (time_limit_for_list_load.isActive()) time_limit_for_list_load.stop(); } m_versions_proxy->setSourceModel(m_version_list.get()); } void ModFilterWidget::prepareBasicFilter() { m_filter->openSource = false; if (m_instance) { m_filter->hideInstalled = false; m_filter->side = ""; // or "both" auto loaders = m_instance->getPackProfile()->getSupportedModLoaders().value(); ui->neoForge->setChecked(loaders & ModPlatform::NeoForge); ui->forge->setChecked(loaders & ModPlatform::Forge); ui->fabric->setChecked(loaders & ModPlatform::Fabric); ui->quilt->setChecked(loaders & ModPlatform::Quilt); m_filter->loaders = loaders; auto def = m_instance->getPackProfile()->getComponentVersion("net.minecraft"); m_filter->versions.emplace_front(def); ui->versions->setCheckedItems({ def }); ui->version->setCurrentIndex(ui->version->findText(def)); } else { ui->hideInstalled->hide(); } } void ModFilterWidget::onShowAllVersionsChanged() { if (ui->showAllVersions->isChecked()) m_versions_proxy->clearFilters(); else m_versions_proxy->setFilter(BaseVersionList::TypeRole, new ExactFilter("release")); } void ModFilterWidget::onVersionFilterChanged(int) { auto versions = ui->versions->checkedItems(); versions.sort(); std::list<Version> current_list; for (const QString& version : versions) current_list.emplace_back(version); m_filter_changed = m_filter->versions.size() != current_list.size() || !std::equal(m_filter->versions.begin(), m_filter->versions.end(), current_list.begin(), current_list.end()); m_filter->versions = current_list; if (m_filter_changed) emit filterChanged(); } void ModFilterWidget::onLoadersFilterChanged() { ModPlatform::ModLoaderTypes loaders; if (ui->neoForge->isChecked()) loaders |= ModPlatform::NeoForge; if (ui->forge->isChecked()) loaders |= ModPlatform::Forge; if (ui->fabric->isChecked()) loaders |= ModPlatform::Fabric; if (ui->quilt->isChecked()) loaders |= ModPlatform::Quilt; m_filter_changed = loaders != m_filter->loaders; m_filter->loaders = loaders; if (m_filter_changed) emit filterChanged(); } void ModFilterWidget::onSideFilterChanged() { QString side; if (ui->clientSide->isChecked() != ui->serverSide->isChecked()) { if (ui->clientSide->isChecked()) side = "client"; else side = "server"; } else { // both are checked or none are checked; in either case no filtering will happen side = ""; } m_filter_changed = side != m_filter->side; m_filter->side = side; if (m_filter_changed) emit filterChanged(); } void ModFilterWidget::onHideInstalledFilterChanged() { auto hide = ui->hideInstalled->isChecked(); m_filter_changed = hide != m_filter->hideInstalled; m_filter->hideInstalled = hide; if (m_filter_changed) emit filterChanged(); } void ModFilterWidget::onVersionFilterTextChanged(const QString& version) { m_filter->versions.clear(); if (ui->version->currentData(Qt::UserRole) != "all") { m_filter->versions.emplace_back(version); } m_filter_changed = true; emit filterChanged(); } void ModFilterWidget::setCategories(const QList<ModPlatform::Category>& categories) { m_categories = categories; delete ui->categoryGroup->layout(); auto layout = new QVBoxLayout(ui->categoryGroup); for (const auto& category : categories) { auto name = category.name; name.replace("-", " "); name.replace("&", "&&"); auto checkbox = new QCheckBox(name); auto font = checkbox->font(); font.setCapitalization(QFont::Capitalize); checkbox->setFont(font); layout->addWidget(checkbox); const QString id = category.id; connect(checkbox, &QCheckBox::toggled, this, [this, id](bool checked) { if (checked) m_filter->categoryIds.append(id); else m_filter->categoryIds.removeOne(id); m_filter_changed = true; emit filterChanged(); }); } } void ModFilterWidget::onOpenSourceFilterChanged() { auto open = ui->openSource->isChecked(); m_filter_changed = open != m_filter->openSource; m_filter->openSource = open; if (m_filter_changed) emit filterChanged(); } void ModFilterWidget::onReleaseFilterChanged() { std::list<ModPlatform::IndexedVersionType> releases; if (ui->releaseCb->isChecked()) releases.push_back(ModPlatform::IndexedVersionType(ModPlatform::IndexedVersionType::VersionType::Release)); if (ui->betaCb->isChecked()) releases.push_back(ModPlatform::IndexedVersionType(ModPlatform::IndexedVersionType::VersionType::Beta)); if (ui->alphaCb->isChecked()) releases.push_back(ModPlatform::IndexedVersionType(ModPlatform::IndexedVersionType::VersionType::Alpha)); if (ui->unknownCb->isChecked()) releases.push_back(ModPlatform::IndexedVersionType(ModPlatform::IndexedVersionType::VersionType::Unknown)); m_filter_changed = releases != m_filter->releases; m_filter->releases = releases; if (m_filter_changed) emit filterChanged(); } #include "ModFilterWidget.moc"
13,629
C++
.cpp
322
36.503106
131
0.690758
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,049
EnvironmentVariables.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/EnvironmentVariables.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include <QKeyEvent> #include "Application.h" #include "EnvironmentVariables.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui_EnvironmentVariables.h" EnvironmentVariables::EnvironmentVariables(QWidget* parent) : QWidget(parent), ui(new Ui::EnvironmentVariables) { ui->setupUi(this); ui->list->installEventFilter(this); ui->list->sortItems(0, Qt::AscendingOrder); ui->list->setSortingEnabled(true); ui->list->header()->resizeSections(QHeaderView::Interactive); ui->list->header()->resizeSection(0, 200); connect(ui->add, &QPushButton::clicked, this, [this] { auto item = new QTreeWidgetItem(ui->list); item->setText(0, "ENV_VAR"); item->setText(1, "value"); item->setFlags(item->flags() | Qt::ItemIsEditable); ui->list->addTopLevelItem(item); ui->list->selectionModel()->select(ui->list->model()->index(ui->list->indexOfTopLevelItem(item), 0), QItemSelectionModel::ClearAndSelect | QItemSelectionModel::SelectionFlag::Rows); ui->list->editItem(item); }); connect(ui->remove, &QPushButton::clicked, this, [this] { for (QTreeWidgetItem* item : ui->list->selectedItems()) ui->list->takeTopLevelItem(ui->list->indexOfTopLevelItem(item)); }); connect(ui->clear, &QPushButton::clicked, this, [this] { ui->list->clear(); }); } EnvironmentVariables::~EnvironmentVariables() { delete ui; } void EnvironmentVariables::initialize(bool instance, bool override, const QMap<QString, QVariant>& value) { // update widgets to settings ui->groupBox->setCheckable(instance); ui->groupBox->setChecked(override); // populate ui->list->clear(); for (auto iter = value.begin(); iter != value.end(); iter++) { auto item = new QTreeWidgetItem(ui->list); item->setText(0, iter.key()); item->setText(1, iter.value().toString()); item->setFlags(item->flags() | Qt::ItemIsEditable); ui->list->addTopLevelItem(item); } } bool EnvironmentVariables::eventFilter(QObject* watched, QEvent* event) { if (watched == ui->list && event->type() == QEvent::KeyPress) { const QKeyEvent* keyEvent = (QKeyEvent*)event; if (keyEvent->key() == Qt::Key_Delete) { emit ui->remove->clicked(); return true; } } return QObject::eventFilter(watched, event); } void EnvironmentVariables::retranslate() { ui->retranslateUi(this); } bool EnvironmentVariables::override() const { if (!ui->groupBox->isCheckable()) return false; return ui->groupBox->isChecked(); } QMap<QString, QVariant> EnvironmentVariables::value() const { QMap<QString, QVariant> result; QTreeWidgetItem* item = ui->list->topLevelItem(0); for (int i = 1; item != nullptr; item = ui->list->topLevelItem(i++)) result[item->text(0)] = item->text(1); return result; }
3,684
C++
.cpp
94
34.255319
123
0.679071
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,050
ErrorFrame.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/ErrorFrame.cpp
/* Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QMessageBox> #include <QtGui> #include "ErrorFrame.h" #include "ui_ErrorFrame.h" #include "ui/dialogs/CustomMessageBox.h" void ErrorFrame::clear() { setTitle(QString()); setDescription(QString()); } ErrorFrame::ErrorFrame(QWidget* parent) : QFrame(parent), ui(new Ui::ErrorFrame) { ui->setupUi(this); ui->label_Description->setHidden(true); ui->label_Title->setHidden(true); updateHiddenState(); } ErrorFrame::~ErrorFrame() { delete ui; } void ErrorFrame::updateHiddenState() { if (ui->label_Description->isHidden() && ui->label_Title->isHidden()) { setHidden(true); } else { setHidden(false); } } void ErrorFrame::setTitle(QString text) { if (text.isEmpty()) { ui->label_Title->setHidden(true); } else { ui->label_Title->setText(text); ui->label_Title->setHidden(false); } updateHiddenState(); } void ErrorFrame::setDescription(QString text) { if (text.isEmpty()) { ui->label_Description->setHidden(true); updateHiddenState(); return; } else { ui->label_Description->setHidden(false); updateHiddenState(); } ui->label_Description->setToolTip(""); QString intermediatetext = text.trimmed(); bool prev(false); QChar rem('\n'); QString finaltext; finaltext.reserve(intermediatetext.size()); foreach (const QChar& c, intermediatetext) { if (c == rem && prev) { continue; } prev = c == rem; finaltext += c; } QString labeltext; labeltext.reserve(300); if (finaltext.length() > 290) { ui->label_Description->setOpenExternalLinks(false); ui->label_Description->setTextFormat(Qt::TextFormat::RichText); desc = text; // This allows injecting HTML here. labeltext.append("<html><body>" + finaltext.left(287) + "<a href=\"#mod_desc\">...</a></body></html>"); QObject::connect(ui->label_Description, &QLabel::linkActivated, this, &ErrorFrame::ellipsisHandler); } else { ui->label_Description->setTextFormat(Qt::TextFormat::PlainText); labeltext.append(finaltext); } ui->label_Description->setText(labeltext); } void ErrorFrame::ellipsisHandler(const QString& link) { if (!currentBox) { currentBox = CustomMessageBox::selectable(this, QString(), desc); connect(currentBox, &QMessageBox::finished, this, &ErrorFrame::boxClosed); currentBox->show(); } else { currentBox->setText(desc); } } void ErrorFrame::boxClosed(int result) { currentBox = nullptr; }
3,228
C++
.cpp
105
26.085714
111
0.672558
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
29,053
InfoFrame.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/InfoFrame.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <QLabel> #include <QMessageBox> #include <QTextCursor> #include <QTextDocument> #include <QToolTip> #include "InfoFrame.h" #include "ui_InfoFrame.h" #include "ui/dialogs/CustomMessageBox.h" void setupLinkToolTip(QLabel* label) { QObject::connect(label, &QLabel::linkHovered, [label](const QString& link) { if (auto url = QUrl(link); !url.isValid() || (url.scheme() != "http" && url.scheme() != "https")) return; label->setToolTip(link); }); } InfoFrame::InfoFrame(QWidget* parent) : QFrame(parent), ui(new Ui::InfoFrame) { ui->setupUi(this); ui->descriptionLabel->setHidden(true); ui->nameLabel->setHidden(true); ui->licenseLabel->setHidden(true); ui->issueTrackerLabel->setHidden(true); setupLinkToolTip(ui->iconLabel); setupLinkToolTip(ui->descriptionLabel); setupLinkToolTip(ui->nameLabel); setupLinkToolTip(ui->licenseLabel); setupLinkToolTip(ui->issueTrackerLabel); updateHiddenState(); } InfoFrame::~InfoFrame() { delete ui; } void InfoFrame::updateWithMod(Mod const& m) { if (m.type() == ResourceType::FOLDER) { clear(); return; } QString text = ""; QString name = ""; QString link = m.homepage(); if (m.name().isEmpty()) name = m.internal_id(); else name = m.name(); if (link.isEmpty()) text = name; else { text = "<a href=\"" + QUrl(link).toEncoded() + "\">" + name + "</a>"; } if (!m.authors().isEmpty()) text += " by " + m.authors().join(", "); setName(text); if (m.description().isEmpty()) { setDescription(QString()); } else { setDescription(m.description()); } setImage(m.icon({ 64, 64 })); auto licenses = m.licenses(); QString licenseText = ""; if (!licenses.empty()) { for (auto l : licenses) { if (!licenseText.isEmpty()) { licenseText += "\n"; // add newline between licenses } if (!l.name.isEmpty()) { if (l.url.isEmpty()) { licenseText += l.name; } else { licenseText += "<a href=\"" + l.url + "\">" + l.name + "</a>"; } } else if (!l.url.isEmpty()) { licenseText += "<a href=\"" + l.url + "\">" + l.url + "</a>"; } if (!l.description.isEmpty() && l.description != l.name) { licenseText += " " + l.description; } } } if (!licenseText.isEmpty()) { setLicense(tr("License: %1").arg(licenseText)); } else { setLicense(); } QString issueTracker = ""; if (!m.issueTracker().isEmpty()) { issueTracker += tr("Report issues to: "); issueTracker += "<a href=\"" + m.issueTracker() + "\">" + m.issueTracker() + "</a>"; } setIssueTracker(issueTracker); } void InfoFrame::updateWithResource(const Resource& resource) { const QString homepage = resource.homepage(); if (!homepage.isEmpty()) setName("<a href=\"" + homepage + "\">" + resource.name() + "</a>"); else setName(resource.name()); setImage(); } QString InfoFrame::renderColorCodes(QString input) { // We have to manually set the colors for use. // // A color is set using ยงx, with x = a hex number from 0 to f. // // We traverse the description and, when one of those is found, we create // a span element with that color set. // // TODO: Wrap links inside <a> tags // https://minecraft.wiki/w/Formatting_codes#Color_codes const QMap<QChar, QString> color_codes_map = { { '0', "#000000" }, { '1', "#0000AA" }, { '2', "#00AA00" }, { '3', "#00AAAA" }, { '4', "#AA0000" }, { '5', "#AA00AA" }, { '6', "#FFAA00" }, { '7', "#AAAAAA" }, { '8', "#555555" }, { '9', "#5555FF" }, { 'a', "#55FF55" }, { 'b', "#55FFFF" }, { 'c', "#FF5555" }, { 'd', "#FF55FF" }, { 'e', "#FFFF55" }, { 'f', "#FFFFFF" } }; // https://minecraft.wiki/w/Formatting_codes#Formatting_codes const QMap<QChar, QString> formatting_codes_map = { { 'l', "b" }, { 'm', "s" }, { 'n', "u" }, { 'o', "i" } }; QString html("<html>"); QList<QString> tags{}; auto it = input.constBegin(); while (it != input.constEnd()) { // is current char ยง and is there a following char if (*it == u'ยง' && (it + 1) != input.constEnd()) { auto const& code = *(++it); // incrementing here! auto const color_entry = color_codes_map.constFind(code); auto const tag_entry = formatting_codes_map.constFind(code); if (color_entry != color_codes_map.constEnd()) { // color code html += QString("<span style=\"color: %1;\">").arg(color_entry.value()); tags << "span"; } else if (tag_entry != formatting_codes_map.constEnd()) { // formatting code html += QString("<%1>").arg(tag_entry.value()); tags << tag_entry.value(); } else if (code == 'r') { // reset all formatting while (!tags.isEmpty()) { html += QString("</%1>").arg(tags.takeLast()); } } else { // pass unknown codes through html += QString("ยง%1").arg(code); } } else { html += *it; } it++; } while (!tags.isEmpty()) { html += QString("</%1>").arg(tags.takeLast()); } html += "</html>"; html.replace("\n", "<br>"); return html; } void InfoFrame::updateWithResourcePack(ResourcePack& resource_pack) { QString name = renderColorCodes(resource_pack.name()); const QString homepage = resource_pack.homepage(); if (!homepage.isEmpty()) { name = "<a href=\"" + homepage + "\">" + name + "</a>"; } setName(name); setDescription(renderColorCodes(resource_pack.description())); setImage(resource_pack.image({ 64, 64 })); } void InfoFrame::updateWithTexturePack(TexturePack& texture_pack) { QString name = renderColorCodes(texture_pack.name()); const QString homepage = texture_pack.homepage(); if (!homepage.isEmpty()) { name = "<a href=\"" + homepage + "\">" + name + "</a>"; } setName(name); setDescription(renderColorCodes(texture_pack.description())); setImage(texture_pack.image({ 64, 64 })); } void InfoFrame::clear() { setName(); setDescription(); setImage(); setLicense(); setIssueTracker(); } void InfoFrame::updateHiddenState() { if (ui->descriptionLabel->isHidden() && ui->nameLabel->isHidden() && ui->licenseLabel->isHidden() && ui->issueTrackerLabel->isHidden()) { setHidden(true); } else { setHidden(false); } } void InfoFrame::setName(QString text) { if (text.isEmpty()) { ui->nameLabel->setHidden(true); } else { ui->nameLabel->setText(text); ui->nameLabel->setHidden(false); } updateHiddenState(); } void InfoFrame::setDescription(QString text) { if (text.isEmpty()) { ui->descriptionLabel->setHidden(true); updateHiddenState(); return; } else { ui->descriptionLabel->setHidden(false); updateHiddenState(); } ui->descriptionLabel->setToolTip(""); QString intermediatetext = text.trimmed(); bool prev(false); QChar rem('\n'); QString finaltext; finaltext.reserve(intermediatetext.size()); foreach (const QChar& c, intermediatetext) { if (c == rem && prev) { continue; } prev = c == rem; finaltext += c; } QString labeltext; labeltext.reserve(300); // elide rich text by getting characters without formatting const int maxCharacterElide = 290; QTextDocument doc; doc.setHtml(text); if (doc.characterCount() > maxCharacterElide) { ui->descriptionLabel->setOpenExternalLinks(false); ui->descriptionLabel->setTextFormat(Qt::TextFormat::RichText); // This allows injecting HTML here. m_description = text; // move the cursor to the character elide, doesn't see html QTextCursor cursor(&doc); cursor.movePosition(QTextCursor::End); cursor.setPosition(maxCharacterElide, QTextCursor::KeepAnchor); cursor.removeSelectedText(); // insert the post fix at the cursor cursor.insertHtml("<a href=\"#mod_desc\">...</a>"); labeltext.append(doc.toHtml()); QObject::connect(ui->descriptionLabel, &QLabel::linkActivated, this, &InfoFrame::descriptionEllipsisHandler); } else { ui->descriptionLabel->setTextFormat(Qt::TextFormat::AutoText); labeltext.append(finaltext); } ui->descriptionLabel->setText(labeltext); } void InfoFrame::setLicense(QString text) { if (text.isEmpty()) { ui->licenseLabel->setHidden(true); updateHiddenState(); return; } else { ui->licenseLabel->setHidden(false); updateHiddenState(); } ui->licenseLabel->setToolTip(""); QString intermediatetext = text.trimmed(); bool prev(false); QChar rem('\n'); QString finaltext; finaltext.reserve(intermediatetext.size()); foreach (const QChar& c, intermediatetext) { if (c == rem && prev) { continue; } prev = c == rem; finaltext += c; } QString labeltext; labeltext.reserve(300); if (finaltext.length() > 290) { ui->licenseLabel->setOpenExternalLinks(false); ui->licenseLabel->setTextFormat(Qt::TextFormat::RichText); m_license = text; // This allows injecting HTML here. labeltext.append("<html><body>" + finaltext.left(287) + "<a href=\"#mod_desc\">...</a></body></html>"); QObject::connect(ui->licenseLabel, &QLabel::linkActivated, this, &InfoFrame::licenseEllipsisHandler); } else { ui->licenseLabel->setTextFormat(Qt::TextFormat::AutoText); labeltext.append(finaltext); } ui->licenseLabel->setText(labeltext); } void InfoFrame::setIssueTracker(QString text) { if (text.isEmpty()) { ui->issueTrackerLabel->setHidden(true); } else { ui->issueTrackerLabel->setText(text); ui->issueTrackerLabel->setHidden(false); } updateHiddenState(); } void InfoFrame::setImage(QPixmap img) { if (img.isNull()) { ui->iconLabel->setHidden(true); } else { ui->iconLabel->setHidden(false); ui->iconLabel->setPixmap(img); } } void InfoFrame::descriptionEllipsisHandler([[maybe_unused]] QString link) { if (!m_current_box) { m_current_box = CustomMessageBox::selectable(this, "", m_description); connect(m_current_box, &QMessageBox::finished, this, &InfoFrame::boxClosed); m_current_box->show(); } else { m_current_box->setText(m_description); } } void InfoFrame::licenseEllipsisHandler([[maybe_unused]] QString link) { if (!m_current_box) { m_current_box = CustomMessageBox::selectable(this, "", m_license); connect(m_current_box, &QMessageBox::finished, this, &InfoFrame::boxClosed); m_current_box->show(); } else { m_current_box->setText(m_license); } } void InfoFrame::boxClosed([[maybe_unused]] int result) { m_current_box = nullptr; }
13,074
C++
.cpp
367
29.163488
132
0.602796
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,054
LanguageSelectionWidget.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/LanguageSelectionWidget.cpp
#include "LanguageSelectionWidget.h" #include <QCheckBox> #include <QHeaderView> #include <QLabel> #include <QTreeView> #include <QVBoxLayout> #include "Application.h" #include "BuildConfig.h" #include "settings/Setting.h" #include "translations/TranslationsModel.h" LanguageSelectionWidget::LanguageSelectionWidget(QWidget* parent) : QWidget(parent) { verticalLayout = new QVBoxLayout(this); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); languageView = new QTreeView(this); languageView->setObjectName(QStringLiteral("languageView")); languageView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); languageView->setAlternatingRowColors(true); languageView->setRootIsDecorated(false); languageView->setItemsExpandable(false); languageView->setWordWrap(true); languageView->header()->setCascadingSectionResizes(true); languageView->header()->setStretchLastSection(false); verticalLayout->addWidget(languageView); helpUsLabel = new QLabel(this); helpUsLabel->setObjectName(QStringLiteral("helpUsLabel")); helpUsLabel->setTextInteractionFlags(Qt::LinksAccessibleByMouse); helpUsLabel->setOpenExternalLinks(true); helpUsLabel->setWordWrap(true); verticalLayout->addWidget(helpUsLabel); formatCheckbox = new QCheckBox(this); formatCheckbox->setObjectName(QStringLiteral("formatCheckbox")); formatCheckbox->setCheckState(APPLICATION->settings()->get("UseSystemLocale").toBool() ? Qt::Checked : Qt::Unchecked); connect(formatCheckbox, &QCheckBox::stateChanged, [this]() { APPLICATION->translations()->setUseSystemLocale(formatCheckbox->isChecked()); }); verticalLayout->addWidget(formatCheckbox); auto translations = APPLICATION->translations(); auto index = translations->selectedIndex(); languageView->setModel(translations.get()); languageView->setCurrentIndex(index); languageView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); languageView->header()->setSectionResizeMode(0, QHeaderView::Stretch); connect(languageView->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &LanguageSelectionWidget::languageRowChanged); verticalLayout->setContentsMargins(0, 0, 0, 0); auto language_setting = APPLICATION->settings()->getSetting("Language"); connect(language_setting.get(), &Setting::SettingChanged, this, &LanguageSelectionWidget::languageSettingChanged); } QString LanguageSelectionWidget::getSelectedLanguageKey() const { auto translations = APPLICATION->translations(); return translations->data(languageView->currentIndex(), Qt::UserRole).toString(); } void LanguageSelectionWidget::retranslate() { QString text = tr("Don't see your language or the quality is poor?<br/><a href=\"%1\">Help us with translations!</a>") .arg(BuildConfig.TRANSLATIONS_URL); helpUsLabel->setText(text); formatCheckbox->setText(tr("Use system locales")); } void LanguageSelectionWidget::languageRowChanged(const QModelIndex& current, const QModelIndex& previous) { if (current == previous) { return; } auto translations = APPLICATION->translations(); QString key = translations->data(current, Qt::UserRole).toString(); translations->selectLanguage(key); translations->updateLanguage(key); } void LanguageSelectionWidget::languageSettingChanged(const Setting&, const QVariant&) { auto translations = APPLICATION->translations(); auto index = translations->selectedIndex(); languageView->setCurrentIndex(index); }
3,585
C++
.cpp
75
43.6
137
0.769209
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,055
VersionSelectWidget.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/VersionSelectWidget.cpp
#include "VersionSelectWidget.h" #include <QApplication> #include <QEvent> #include <QHeaderView> #include <QKeyEvent> #include <QProgressBar> #include <QVBoxLayout> #include "VersionProxyModel.h" #include "ui/dialogs/CustomMessageBox.h" VersionSelectWidget::VersionSelectWidget(QWidget* parent) : QWidget(parent) { setObjectName(QStringLiteral("VersionSelectWidget")); verticalLayout = new QVBoxLayout(this); verticalLayout->setObjectName(QStringLiteral("verticalLayout")); verticalLayout->setContentsMargins(0, 0, 0, 0); m_proxyModel = new VersionProxyModel(this); listView = new VersionListView(this); listView->setObjectName(QStringLiteral("listView")); listView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); listView->setAlternatingRowColors(true); listView->setRootIsDecorated(false); listView->setItemsExpandable(false); listView->setWordWrap(true); listView->header()->setCascadingSectionResizes(true); listView->header()->setStretchLastSection(false); listView->setModel(m_proxyModel); verticalLayout->addWidget(listView); search = new QLineEdit(this); search->setPlaceholderText(tr("Search")); search->setClearButtonEnabled(true); verticalLayout->addWidget(search); connect(search, &QLineEdit::textEdited, [this](const QString& value) { m_proxyModel->setSearch(value); if (!value.isEmpty() || !listView->selectionModel()->hasSelection()) { const QModelIndex first = listView->model()->index(0, 0); listView->selectionModel()->setCurrentIndex(first, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); listView->scrollToTop(); } else listView->scrollTo(listView->selectionModel()->currentIndex(), QAbstractItemView::PositionAtCenter); }); search->installEventFilter(this); sneakyProgressBar = new QProgressBar(this); sneakyProgressBar->setObjectName(QStringLiteral("sneakyProgressBar")); sneakyProgressBar->setFormat(QStringLiteral("%p%")); verticalLayout->addWidget(sneakyProgressBar); sneakyProgressBar->setHidden(true); connect(listView->selectionModel(), &QItemSelectionModel::currentRowChanged, this, &VersionSelectWidget::currentRowChanged); QMetaObject::connectSlotsByName(this); } void VersionSelectWidget::setCurrentVersion(const QString& version) { m_currentVersion = version; m_proxyModel->setCurrentVersion(version); } void VersionSelectWidget::setEmptyString(QString emptyString) { listView->setEmptyString(emptyString); } void VersionSelectWidget::setEmptyErrorString(QString emptyErrorString) { listView->setEmptyErrorString(emptyErrorString); } void VersionSelectWidget::setEmptyMode(VersionListView::EmptyMode mode) { listView->setEmptyMode(mode); } VersionSelectWidget::~VersionSelectWidget() {} void VersionSelectWidget::setResizeOn(int column) { listView->header()->setSectionResizeMode(resizeOnColumn, QHeaderView::ResizeToContents); resizeOnColumn = column; listView->header()->setSectionResizeMode(resizeOnColumn, QHeaderView::Stretch); } bool VersionSelectWidget::eventFilter(QObject* watched, QEvent* event) { if (watched == search && event->type() == QEvent::KeyPress) { const QKeyEvent* keyEvent = (QKeyEvent*)event; const bool up = keyEvent->key() == Qt::Key_Up; const bool down = keyEvent->key() == Qt::Key_Down; if (up || down) { const QModelIndex index = listView->model()->index(listView->currentIndex().row() + (up ? -1 : 1), 0); if (index.row() >= 0 && index.row() < listView->model()->rowCount()) { listView->selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect | QItemSelectionModel::Rows); return true; } } } return QObject::eventFilter(watched, event); } void VersionSelectWidget::initialize(BaseVersionList* vlist, bool forceLoad) { m_vlist = vlist; m_proxyModel->setSourceModel(vlist); listView->header()->setSectionResizeMode(QHeaderView::ResizeToContents); listView->header()->setSectionResizeMode(resizeOnColumn, QHeaderView::Stretch); if (!m_vlist->isLoaded() || forceLoad) { loadList(); } else { if (m_proxyModel->rowCount() == 0) { listView->setEmptyMode(VersionListView::String); } preselect(); } } void VersionSelectWidget::closeEvent(QCloseEvent* event) { QWidget::closeEvent(event); } void VersionSelectWidget::loadList() { m_load_task = m_vlist->getLoadTask(); connect(m_load_task.get(), &Task::succeeded, this, &VersionSelectWidget::onTaskSucceeded); connect(m_load_task.get(), &Task::failed, this, &VersionSelectWidget::onTaskFailed); connect(m_load_task.get(), &Task::progress, this, &VersionSelectWidget::changeProgress); if (!m_load_task->isRunning()) { m_load_task->start(); } sneakyProgressBar->setHidden(false); } void VersionSelectWidget::onTaskSucceeded() { if (m_proxyModel->rowCount() == 0) { listView->setEmptyMode(VersionListView::String); } sneakyProgressBar->setHidden(true); preselect(); m_load_task.reset(); } void VersionSelectWidget::onTaskFailed(const QString& reason) { CustomMessageBox::selectable(this, tr("Error"), tr("List update failed:\n%1").arg(reason), QMessageBox::Warning)->show(); onTaskSucceeded(); } void VersionSelectWidget::changeProgress(qint64 current, qint64 total) { sneakyProgressBar->setMaximum(total); sneakyProgressBar->setValue(current); } void VersionSelectWidget::currentRowChanged(const QModelIndex& current, const QModelIndex&) { auto variant = m_proxyModel->data(current, BaseVersionList::VersionPointerRole); emit selectedVersionChanged(variant.value<BaseVersion::Ptr>()); } void VersionSelectWidget::preselect() { if (preselectedAlready) return; selectCurrent(); if (preselectedAlready) return; selectRecommended(); } void VersionSelectWidget::selectCurrent() { if (m_currentVersion.isEmpty()) { return; } auto idx = m_proxyModel->getVersion(m_currentVersion); if (idx.isValid()) { preselectedAlready = true; listView->selectionModel()->setCurrentIndex(idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); listView->scrollTo(idx, QAbstractItemView::PositionAtCenter); } } void VersionSelectWidget::selectSearch() { search->setFocus(); } VersionListView* VersionSelectWidget::view() { return listView; } void VersionSelectWidget::selectRecommended() { auto idx = m_proxyModel->getRecommended(); if (idx.isValid()) { preselectedAlready = true; listView->selectionModel()->setCurrentIndex(idx, QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); listView->scrollTo(idx, QAbstractItemView::PositionAtCenter); } } bool VersionSelectWidget::hasVersions() const { return m_proxyModel->rowCount(QModelIndex()) != 0; } BaseVersion::Ptr VersionSelectWidget::selectedVersion() const { auto currentIndex = listView->selectionModel()->currentIndex(); auto variant = m_proxyModel->data(currentIndex, BaseVersionList::VersionPointerRole); return variant.value<BaseVersion::Ptr>(); } void VersionSelectWidget::setFuzzyFilter(BaseVersionList::ModelRoles role, QString filter) { m_proxyModel->setFilter(role, new ContainsFilter(filter)); } void VersionSelectWidget::setExactFilter(BaseVersionList::ModelRoles role, QString filter) { m_proxyModel->setFilter(role, new ExactFilter(filter)); } void VersionSelectWidget::setExactIfPresentFilter(BaseVersionList::ModelRoles role, QString filter) { m_proxyModel->setFilter(role, new ExactIfPresentFilter(filter)); } void VersionSelectWidget::setFilter(BaseVersionList::ModelRoles role, Filter* filter) { m_proxyModel->setFilter(role, filter); }
7,965
C++
.cpp
207
34.077295
132
0.738669
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,056
LineSeparator.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/LineSeparator.cpp
#include "LineSeparator.h" #include <QLayout> #include <QPainter> #include <QStyle> #include <QStyleOption> void LineSeparator::initStyleOption(QStyleOption* option) const { option->initFrom(this); // in a horizontal layout, the line is vertical (and vice versa) if (m_orientation == Qt::Vertical) option->state |= QStyle::State_Horizontal; } LineSeparator::LineSeparator(QWidget* parent, Qt::Orientation orientation) : QWidget(parent), m_orientation(orientation) { setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); } QSize LineSeparator::sizeHint() const { QStyleOption opt; initStyleOption(&opt); const int extent = style()->pixelMetric(QStyle::PM_ToolBarSeparatorExtent, &opt, parentWidget()); return QSize(extent, extent); } void LineSeparator::paintEvent(QPaintEvent*) { QPainter p(this); QStyleOption opt; initStyleOption(&opt); style()->drawPrimitive(QStyle::PE_IndicatorToolBarSeparator, &opt, &p, parentWidget()); }
995
C++
.cpp
30
30.133333
120
0.75
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,058
LabeledToolButton.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/LabeledToolButton.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "LabeledToolButton.h" #include <QApplication> #include <QDebug> #include <QLabel> #include <QResizeEvent> #include <QStyleOption> #include <QVBoxLayout> /* * * Tool Button with a label on it, instead of the normal text rendering * */ LabeledToolButton::LabeledToolButton(QWidget* parent) : QToolButton(parent), m_label(new QLabel(this)) { // QToolButton::setText(" "); m_label->setWordWrap(true); m_label->setMouseTracking(false); m_label->setAlignment(Qt::AlignCenter); m_label->setTextInteractionFlags(Qt::NoTextInteraction); // somehow, this makes word wrap work in the QLabel. yay. // m_label->setMinimumWidth(100); } QString LabeledToolButton::text() const { return m_label->text(); } void LabeledToolButton::setText(const QString& text) { m_label->setText(text); } void LabeledToolButton::setIcon(QIcon icon) { m_icon = icon; resetIcon(); } /*! \reimp */ QSize LabeledToolButton::sizeHint() const { /* Q_D(const QToolButton); if (d->sizeHint.isValid()) return d->sizeHint; */ ensurePolished(); int w = 0, h = 0; QStyleOptionToolButton opt; initStyleOption(&opt); QSize sz = m_label->sizeHint(); w = sz.width(); h = sz.height(); opt.rect.setSize(QSize(w, h)); // PM_MenuButtonIndicator depends on the height if (popupMode() == MenuButtonPopup) w += style()->pixelMetric(QStyle::PM_MenuButtonIndicator, &opt, this); return style()->sizeFromContents(QStyle::CT_ToolButton, &opt, QSize(w, h), this); } void LabeledToolButton::resizeEvent(QResizeEvent* event) { m_label->setGeometry(QRect(4, 4, width() - 8, height() - 8)); if (!m_icon.isNull()) { resetIcon(); } QWidget::resizeEvent(event); } void LabeledToolButton::resetIcon() { auto iconSz = m_icon.actualSize(QSize(160, 80)); float w = iconSz.width(); float h = iconSz.height(); float ar = w / h; // FIXME: hardcoded max size of 160x80 int newW = 80 * ar; if (newW > 160) newW = 160; QSize newSz(newW, 80); auto pixmap = m_icon.pixmap(newSz); m_label->setPixmap(pixmap); m_label->setMinimumHeight(80); m_label->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); }
3,759
C++
.cpp
115
29.530435
102
0.701267
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,059
LogView.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/LogView.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "LogView.h" #include <QScrollBar> #include <QTextBlock> #include <QTextDocumentFragment> LogView::LogView(QWidget* parent) : QPlainTextEdit(parent) { setWordWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); m_defaultFormat = new QTextCharFormat(currentCharFormat()); } LogView::~LogView() { delete m_defaultFormat; } void LogView::setWordWrap(bool wrapping) { if (wrapping) { setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setLineWrapMode(QPlainTextEdit::WidgetWidth); } else { setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); setLineWrapMode(QPlainTextEdit::NoWrap); } } void LogView::setModel(QAbstractItemModel* model) { if (m_model) { disconnect(m_model, &QAbstractItemModel::modelReset, this, &LogView::repopulate); disconnect(m_model, &QAbstractItemModel::rowsInserted, this, &LogView::rowsInserted); disconnect(m_model, &QAbstractItemModel::rowsAboutToBeInserted, this, &LogView::rowsAboutToBeInserted); disconnect(m_model, &QAbstractItemModel::rowsRemoved, this, &LogView::rowsRemoved); } m_model = model; if (m_model) { connect(m_model, &QAbstractItemModel::modelReset, this, &LogView::repopulate); connect(m_model, &QAbstractItemModel::rowsInserted, this, &LogView::rowsInserted); connect(m_model, &QAbstractItemModel::rowsAboutToBeInserted, this, &LogView::rowsAboutToBeInserted); connect(m_model, &QAbstractItemModel::rowsRemoved, this, &LogView::rowsRemoved); connect(m_model, &QAbstractItemModel::destroyed, this, &LogView::modelDestroyed); } repopulate(); } QAbstractItemModel* LogView::model() const { return m_model; } void LogView::modelDestroyed(QObject* model) { if (m_model == model) { setModel(nullptr); } } void LogView::repopulate() { auto doc = document(); doc->clear(); if (!m_model) { return; } rowsInserted(QModelIndex(), 0, m_model->rowCount() - 1); } void LogView::rowsAboutToBeInserted(const QModelIndex& parent, int first, int last) { Q_UNUSED(parent) Q_UNUSED(first) Q_UNUSED(last) QScrollBar* bar = verticalScrollBar(); int max_bar = bar->maximum(); int val_bar = bar->value(); if (m_scroll) { m_scroll = (max_bar - val_bar) <= 1; } else { m_scroll = val_bar == max_bar; } } void LogView::rowsInserted(const QModelIndex& parent, int first, int last) { QTextDocument document; QTextCursor cursor(&document); for (int i = first; i <= last; i++) { auto idx = m_model->index(i, 0, parent); auto text = m_model->data(idx, Qt::DisplayRole).toString(); QTextCharFormat format(*m_defaultFormat); auto font = m_model->data(idx, Qt::FontRole); if (font.isValid()) { format.setFont(font.value<QFont>()); } auto fg = m_model->data(idx, Qt::ForegroundRole); if (fg.isValid()) { format.setForeground(fg.value<QColor>()); } auto bg = m_model->data(idx, Qt::BackgroundRole); if (bg.isValid()) { format.setBackground(bg.value<QColor>()); } cursor.movePosition(QTextCursor::End); cursor.insertText(text, format); cursor.insertBlock(); } QTextDocumentFragment fragment(&document); QTextCursor workCursor = textCursor(); workCursor.movePosition(QTextCursor::End); workCursor.insertFragment(fragment); if (m_scroll && !m_scrolling) { m_scrolling = true; QMetaObject::invokeMethod(this, "scrollToBottom", Qt::QueuedConnection); } } void LogView::rowsRemoved(const QModelIndex& parent, int first, int last) { // TODO: some day... maybe Q_UNUSED(parent) Q_UNUSED(first) Q_UNUSED(last) } void LogView::scrollToBottom() { m_scrolling = false; verticalScrollBar()->setSliderPosition(verticalScrollBar()->maximum()); } void LogView::findNext(const QString& what, bool reverse) { find(what, reverse ? QTextDocument::FindFlag::FindBackward : QTextDocument::FindFlag(0)); }
5,601
C++
.cpp
157
31.235669
111
0.694547
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,060
VariableSizedImageObject.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/VariableSizedImageObject.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "VariableSizedImageObject.h" #include <QAbstractTextDocumentLayout> #include <QDebug> #include <QPainter> #include <QTextObject> #include <memory> #include "Application.h" #include "net/ApiDownload.h" #include "net/NetJob.h" enum FormatProperties { ImageData = QTextFormat::UserProperty + 1 }; QSizeF VariableSizedImageObject::intrinsicSize(QTextDocument* doc, int posInDocument, const QTextFormat& format) { Q_UNUSED(posInDocument); auto image = qvariant_cast<QImage>(format.property(ImageData)); auto size = image.size(); if (size.isEmpty()) // can't resize an empty image return { size }; // calculate the new image size based on the properties int width = 0; int height = 0; auto widthVar = format.property(QTextFormat::ImageWidth); if (widthVar.isValid()) { width = widthVar.toInt(); } auto heigthVar = format.property(QTextFormat::ImageHeight); if (heigthVar.isValid()) { height = heigthVar.toInt(); } if (width != 0 && height != 0) { size.setWidth(width); size.setHeight(height); } else if (width != 0) { size.setHeight((width * size.height()) / size.width()); size.setWidth(width); } else if (height != 0) { size.setWidth((height * size.width()) / size.height()); size.setHeight(height); } // Get the width of the text content to make the image similar sized. // doc->textWidth() includes the margin, so we need to remove it. auto doc_width = doc->textWidth() - 2 * doc->documentMargin(); if (size.width() > doc_width) size *= doc_width / (double)size.width(); return { size }; } void VariableSizedImageObject::drawObject(QPainter* painter, const QRectF& rect, QTextDocument* doc, int posInDocument, const QTextFormat& format) { if (!format.hasProperty(ImageData)) { QUrl image_url{ qvariant_cast<QString>(format.property(QTextFormat::ImageName)) }; if (m_fetching_images.contains(image_url) || image_url.isEmpty()) return; auto meta = std::make_shared<ImageMetadata>(); meta->posInDocument = posInDocument; meta->url = image_url; auto widthVar = format.property(QTextFormat::ImageWidth); if (widthVar.isValid()) { meta->width = widthVar.toInt(); } auto heigthVar = format.property(QTextFormat::ImageHeight); if (heigthVar.isValid()) { meta->height = heigthVar.toInt(); } loadImage(doc, meta); return; } auto image = qvariant_cast<QImage>(format.property(ImageData)); painter->setRenderHint(QPainter::RenderHint::SmoothPixmapTransform); painter->drawImage(rect, image); } void VariableSizedImageObject::flush() { m_fetching_images.clear(); } void VariableSizedImageObject::parseImage(QTextDocument* doc, std::shared_ptr<ImageMetadata> meta) { QTextCursor cursor(doc); cursor.setPosition(meta->posInDocument); cursor.setKeepPositionOnInsert(true); auto image_char_format = cursor.charFormat(); image_char_format.setObjectType(QTextFormat::ImageObject); image_char_format.setProperty(ImageData, meta->image); image_char_format.setProperty(QTextFormat::ImageName, meta->url.toDisplayString()); image_char_format.setProperty(QTextFormat::ImageWidth, meta->width); image_char_format.setProperty(QTextFormat::ImageHeight, meta->height); // Qt doesn't allow us to modify the properties of an existing object in the document. // So we remove the old one and add the new one with the ImageData property set. cursor.deleteChar(); cursor.insertText(QString(QChar::ObjectReplacementCharacter), image_char_format); } void VariableSizedImageObject::loadImage(QTextDocument* doc, std::shared_ptr<ImageMetadata> meta) { m_fetching_images.insert(meta->url); MetaEntryPtr entry = APPLICATION->metacache()->resolveEntry( m_meta_entry, QString("images/%1").arg(QString(QCryptographicHash::hash(meta->url.toEncoded(), QCryptographicHash::Algorithm::Sha1).toHex()))); auto job = new NetJob(QString("Load Image: %1").arg(meta->url.fileName()), APPLICATION->network()); job->setAskRetry(false); job->addNetAction(Net::ApiDownload::makeCached(meta->url, entry)); auto full_entry_path = entry->getFullPath(); auto source_url = meta->url; auto loadImage = [this, doc, full_entry_path, source_url, meta](const QImage& image) { doc->addResource(QTextDocument::ImageResource, source_url, image); meta->image = image; parseImage(doc, meta); // This size hack is needed to prevent the content from being laid out in an area smaller // than the total width available (weird). auto size = doc->pageSize(); doc->adjustSize(); doc->setPageSize(size); m_fetching_images.remove(source_url); }; connect(job, &NetJob::succeeded, this, [this, full_entry_path, source_url, loadImage] { qDebug() << "Loaded resource at:" << full_entry_path; // If we flushed, don't proceed. if (!m_fetching_images.contains(source_url)) return; QImage image(full_entry_path); loadImage(image); }); connect(job, &NetJob::failed, this, [this, full_entry_path, source_url, loadImage](QString reason) { qWarning() << "Failed resource at:" << full_entry_path << " because:" << reason; // If we flushed, don't proceed. if (!m_fetching_images.contains(source_url)) return; loadImage(QImage()); }); connect(job, &NetJob::finished, job, &NetJob::deleteLater); job->start(); }
6,588
C++
.cpp
150
37.3
137
0.66906
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,061
CheckComboBox.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/CheckComboBox.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "CheckComboBox.h" #include <QAbstractItemView> #include <QBoxLayout> #include <QEvent> #include <QIdentityProxyModel> #include <QKeyEvent> #include <QLineEdit> #include <QListView> #include <QMouseEvent> #include <QStringList> #include <QStylePainter> class CheckComboModel : public QIdentityProxyModel { Q_OBJECT public: explicit CheckComboModel(QObject* parent = nullptr) : QIdentityProxyModel(parent) {} virtual Qt::ItemFlags flags(const QModelIndex& index) const { return QIdentityProxyModel::flags(index) | Qt::ItemIsUserCheckable; } virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const { if (role == Qt::CheckStateRole) { auto txt = QIdentityProxyModel::data(index, Qt::DisplayRole).toString(); return checked.contains(txt) ? Qt::Checked : Qt::Unchecked; } if (role == Qt::DisplayRole) return QIdentityProxyModel::data(index, Qt::DisplayRole); return {}; } virtual bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) { if (role == Qt::CheckStateRole) { auto txt = QIdentityProxyModel::data(index, Qt::DisplayRole).toString(); if (checked.contains(txt)) { checked.removeOne(txt); } else { checked.push_back(txt); } emit dataChanged(index, index); emit checkStateChanged(); return true; } return QIdentityProxyModel::setData(index, value, role); } QStringList getChecked() { return checked; } signals: void checkStateChanged(); private: QStringList checked; }; CheckComboBox::CheckComboBox(QWidget* parent) : QComboBox(parent), m_separator(", ") { view()->installEventFilter(this); view()->window()->installEventFilter(this); view()->viewport()->installEventFilter(this); this->installEventFilter(this); } void CheckComboBox::setSourceModel(QAbstractItemModel* new_model) { auto proxy = new CheckComboModel(this); proxy->setSourceModel(new_model); model()->disconnect(this); QComboBox::setModel(proxy); connect(this, QOverload<int>::of(&QComboBox::activated), this, &CheckComboBox::toggleCheckState); connect(proxy, &CheckComboModel::checkStateChanged, this, &CheckComboBox::emitCheckedItemsChanged); connect(model(), &CheckComboModel::rowsInserted, this, &CheckComboBox::emitCheckedItemsChanged); connect(model(), &CheckComboModel::rowsRemoved, this, &CheckComboBox::emitCheckedItemsChanged); } void CheckComboBox::hidePopup() { if (!containerMousePress) QComboBox::hidePopup(); } void CheckComboBox::emitCheckedItemsChanged() { emit checkedItemsChanged(checkedItems()); } QString CheckComboBox::defaultText() const { return m_default_text; } void CheckComboBox::setDefaultText(const QString& text) { m_default_text = text; } QString CheckComboBox::separator() const { return m_separator; } void CheckComboBox::setSeparator(const QString& separator) { m_separator = separator; } bool CheckComboBox::eventFilter(QObject* receiver, QEvent* event) { switch (event->type()) { case QEvent::KeyPress: case QEvent::KeyRelease: { QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event); if (receiver == this && (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down)) { showPopup(); return true; } else if (keyEvent->key() == Qt::Key_Enter || keyEvent->key() == Qt::Key_Return || keyEvent->key() == Qt::Key_Escape) { QComboBox::hidePopup(); return (keyEvent->key() != Qt::Key_Escape); } break; } case QEvent::MouseButtonPress: { auto ev = static_cast<QMouseEvent*>(event); containerMousePress = ev && view()->indexAt(ev->pos()).isValid(); break; } case QEvent::Wheel: return receiver == this; default: break; } return false; } void CheckComboBox::toggleCheckState(int index) { QVariant value = itemData(index, Qt::CheckStateRole); if (value.isValid()) { Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt()); setItemData(index, (state == Qt::Unchecked ? Qt::Checked : Qt::Unchecked), Qt::CheckStateRole); } emitCheckedItemsChanged(); } Qt::CheckState CheckComboBox::itemCheckState(int index) const { return static_cast<Qt::CheckState>(itemData(index, Qt::CheckStateRole).toInt()); } void CheckComboBox::setItemCheckState(int index, Qt::CheckState state) { setItemData(index, state, Qt::CheckStateRole); } QStringList CheckComboBox::checkedItems() const { if (model()) return dynamic_cast<CheckComboModel*>(model())->getChecked(); return {}; } void CheckComboBox::setCheckedItems(const QStringList& items) { foreach (auto text, items) { auto index = findText(text); setItemCheckState(index, index != -1 ? Qt::Checked : Qt::Unchecked); } } void CheckComboBox::paintEvent(QPaintEvent*) { QStylePainter painter(this); painter.setPen(palette().color(QPalette::Text)); // draw the combobox frame, focusrect and selected etc. QStyleOptionComboBox opt; initStyleOption(&opt); QStringList items = checkedItems(); if (items.isEmpty()) opt.currentText = defaultText(); else opt.currentText = items.join(separator()); painter.drawComplexControl(QStyle::CC_ComboBox, opt); // draw the icon and text painter.drawControl(QStyle::CE_ComboBoxLabel, opt); } #include "CheckComboBox.moc"
6,465
C++
.cpp
181
30.430939
135
0.683866
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,062
ProjectItem.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/ProjectItem.cpp
#include "ProjectItem.h" #include "Common.h" #include <QIcon> #include <QPainter> ProjectItemDelegate::ProjectItemDelegate(QWidget* parent) : QStyledItemDelegate(parent) {} void ProjectItemDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { painter->save(); QStyleOptionViewItem opt(option); initStyleOption(&opt, index); auto rect = opt.rect; if (opt.state & QStyle::State_Selected) { painter->fillRect(rect, opt.palette.highlight()); painter->setPen(opt.palette.highlightedText().color()); } else if (opt.state & QStyle::State_MouseOver) { painter->fillRect(rect, opt.palette.window()); } // The default icon size will be a square (and height is usually the lower value). auto icon_width = rect.height(), icon_height = rect.height(); int icon_x_margin = (rect.height() - icon_width) / 2; int icon_y_margin = (rect.height() - icon_height) / 2; if (!opt.icon.isNull()) { // Icon painting { auto icon_size = opt.decorationSize; icon_width = icon_size.width(); icon_height = icon_size.height(); icon_y_margin = (rect.height() - icon_height) / 2; icon_x_margin = icon_y_margin; // use same margins for consistency } // Centralize icon with a margin to separate from the other elements int x = rect.x() + icon_x_margin; int y = rect.y() + icon_y_margin; // Prevent 'scaling null pixmap' warnings if (icon_width > 0 && icon_height > 0) opt.icon.paint(painter, x, y, icon_width, icon_height); } // Change the rect so that funther painting is easier auto remaining_width = rect.width() - icon_width - 2 * icon_x_margin; rect.setRect(rect.x() + icon_width + 2 * icon_x_margin, rect.y(), remaining_width, rect.height()); int title_height = 0; { // Title painting auto title = index.data(UserDataTypes::TITLE).toString(); painter->save(); auto font = opt.font; if (index.data(UserDataTypes::SELECTED).toBool()) { // Set nice font font.setBold(true); font.setUnderline(true); } if (index.data(UserDataTypes::INSTALLED).toBool()) { auto hRect = opt.rect; hRect.setX(hRect.x() + 1); hRect.setY(hRect.y() + 1); hRect.setHeight(hRect.height() - 2); hRect.setWidth(hRect.width() - 2); // Set nice font font.setItalic(true); font.setOverline(true); painter->drawRect(hRect); } font.setPointSize(font.pointSize() + 2); painter->setFont(font); title_height = QFontMetrics(font).height(); // On the top, aligned to the left after the icon painter->drawText(rect.x(), rect.y() + title_height, title); painter->restore(); } { // Description painting auto description = index.data(UserDataTypes::DESCRIPTION).toString().simplified(); QTextLayout text_layout(description, opt.font); qreal height = 0; auto cut_text = viewItemTextLayout(text_layout, remaining_width, height); // Get first line unconditionally description = cut_text.first().second; auto num_lines = 1; // Get second line, elided if needed if (cut_text.size() > 1) { // 2.5x so because there should be some margin left from the 2x so things don't get too squishy. if (rect.height() - title_height <= 2.5 * opt.fontMetrics.height()) { // If there's not enough space, show only a single line, elided. description = opt.fontMetrics.elidedText(description, opt.textElideMode, cut_text.at(0).first); } else { if (cut_text.size() > 2) { description += opt.fontMetrics.elidedText(cut_text.at(1).second, opt.textElideMode, cut_text.at(1).first); } else { description += cut_text.at(1).second; } num_lines += 1; } } int description_x = rect.x(); // Have the y-value be set based on the number of lines in the description, to centralize the // description text with the space between the base and the title. int description_y = rect.y() + title_height + (rect.height() - title_height) / 2; if (num_lines == 1) description_y -= opt.fontMetrics.height() / 2; else description_y -= opt.fontMetrics.height(); // On the bottom, aligned to the left after the icon, and featuring at most two lines of text (with some margin space to spare) painter->drawText(description_x, description_y, remaining_width, cut_text.size() * opt.fontMetrics.height(), Qt::TextWordWrap, description); } painter->restore(); }
4,982
C++
.cpp
104
38.288462
135
0.606229
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,063
CustomCommands.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/CustomCommands.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CustomCommands.h" #include "ui_CustomCommands.h" CustomCommands::~CustomCommands() { delete ui; } CustomCommands::CustomCommands(QWidget* parent) : QWidget(parent), ui(new Ui::CustomCommands) { ui->setupUi(this); } void CustomCommands::initialize(bool checkable, bool checked, const QString& prelaunch, const QString& wrapper, const QString& postexit) { ui->customCommandsGroupBox->setCheckable(checkable); if (checkable) { ui->customCommandsGroupBox->setChecked(checked); } ui->preLaunchCmdTextBox->setText(prelaunch); ui->wrapperCmdTextBox->setText(wrapper); ui->postExitCmdTextBox->setText(postexit); } void CustomCommands::retranslate() { ui->retranslateUi(this); } bool CustomCommands::checked() const { if (!ui->customCommandsGroupBox->isCheckable()) return true; return ui->customCommandsGroupBox->isChecked(); } QString CustomCommands::prelaunchCommand() const { return ui->preLaunchCmdTextBox->text(); } QString CustomCommands::wrapperCommand() const { return ui->wrapperCmdTextBox->text(); } QString CustomCommands::postexitCommand() const { return ui->postExitCmdTextBox->text(); }
2,677
C++
.cpp
76
32.736842
136
0.744599
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,064
IconLabel.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/IconLabel.cpp
#include "IconLabel.h" #include <QLayout> #include <QPainter> #include <QRect> #include <QStyle> #include <QStyleOption> IconLabel::IconLabel(QWidget* parent, QIcon icon, QSize size) : QWidget(parent), m_size(size), m_icon(icon) { setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); } QSize IconLabel::sizeHint() const { return m_size; } void IconLabel::setIcon(QIcon icon) { m_icon = icon; update(); } void IconLabel::paintEvent(QPaintEvent*) { QPainter p(this); QRect rect = contentsRect(); int width = rect.width(); int height = rect.height(); if (width < height) { rect.setHeight(width); rect.translate(0, (height - width) / 2); } else if (width > height) { rect.setWidth(height); rect.translate((width - height) / 2, 0); } m_icon.paint(&p, rect); }
846
C++
.cpp
34
21.382353
107
0.666667
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,065
ProjectDescriptionPage.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/ProjectDescriptionPage.cpp
#include "ProjectDescriptionPage.h" #include "VariableSizedImageObject.h" #include <QDebug> ProjectDescriptionPage::ProjectDescriptionPage(QWidget* parent) : QTextBrowser(parent), m_image_text_object(new VariableSizedImageObject) { m_image_text_object->setParent(this); document()->documentLayout()->registerHandler(QTextFormat::ImageObject, m_image_text_object.get()); } void ProjectDescriptionPage::setMetaEntry(QString entry) { if (m_image_text_object) m_image_text_object->setMetaEntry(entry); } void ProjectDescriptionPage::flush() { if (m_image_text_object) m_image_text_object->flush(); }
633
C++
.cpp
18
32.111111
137
0.772131
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,066
SubTaskProgressBar.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/SubTaskProgressBar.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * PrismLaucher - Minecraft Launcher * Copyright (C) 2022 Rachel Powers <508861+Ryex@users.noreply.github.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ #include "SubTaskProgressBar.h" #include "ui_SubTaskProgressBar.h" unique_qobject_ptr<SubTaskProgressBar> SubTaskProgressBar::create(QWidget* parent) { auto progress_bar = new SubTaskProgressBar(parent); return unique_qobject_ptr<SubTaskProgressBar>(progress_bar); } SubTaskProgressBar::SubTaskProgressBar(QWidget* parent) : QWidget(parent), ui(new Ui::SubTaskProgressBar) { ui->setupUi(this); } SubTaskProgressBar::~SubTaskProgressBar() { delete ui; } void SubTaskProgressBar::setRange(int min, int max) { ui->progressBar->setRange(min, max); } void SubTaskProgressBar::setValue(int value) { ui->progressBar->setValue(value); } void SubTaskProgressBar::setStatus(QString status) { ui->statusLabel->setText(status); } void SubTaskProgressBar::setDetails(QString details) { ui->statusDetailsLabel->setText(details); }
1,616
C++
.cpp
49
30.857143
105
0.769872
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,067
WideBar.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/WideBar.cpp
#include "WideBar.h" #include <QContextMenuEvent> #include <QCryptographicHash> #include <QToolButton> class ActionButton : public QToolButton { Q_OBJECT public: ActionButton(QAction* action, QWidget* parent = nullptr, bool use_default_action = false) : QToolButton(parent), m_action(action), m_use_default_action(use_default_action) { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); setToolButtonStyle(Qt::ToolButtonTextBesideIcon); // workaround for breeze and breeze forks setProperty("_kde_toolButton_alignment", Qt::AlignLeft); if (m_use_default_action) { setDefaultAction(action); } else { connect(this, &ActionButton::clicked, action, &QAction::trigger); } connect(action, &QAction::changed, this, &ActionButton::actionChanged); actionChanged(); }; public slots: void actionChanged() { setEnabled(m_action->isEnabled()); // better pop up mode if (m_action->menu()) { setPopupMode(QToolButton::MenuButtonPopup); } if (!m_use_default_action) { setChecked(m_action->isChecked()); setCheckable(m_action->isCheckable()); setText(m_action->text()); setIcon(m_action->icon()); setToolTip(m_action->toolTip()); setHidden(!m_action->isVisible()); } setFocusPolicy(Qt::NoFocus); } private: QAction* m_action; bool m_use_default_action; }; WideBar::WideBar(const QString& title, QWidget* parent) : QToolBar(title, parent) { setFloatable(false); setMovable(false); setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu); connect(this, &QToolBar::customContextMenuRequested, this, &WideBar::showVisibilityMenu); } WideBar::WideBar(QWidget* parent) : QToolBar(parent) { setFloatable(false); setMovable(false); setContextMenuPolicy(Qt::ContextMenuPolicy::CustomContextMenu); connect(this, &QToolBar::customContextMenuRequested, this, &WideBar::showVisibilityMenu); } void WideBar::addAction(QAction* action) { BarEntry entry; entry.bar_action = addWidget(new ActionButton(action, this, m_use_default_action)); entry.menu_action = action; entry.type = BarEntry::Type::Action; m_entries.push_back(entry); m_menu_state = MenuState::Dirty; } void WideBar::addSeparator() { BarEntry entry; entry.bar_action = QToolBar::addSeparator(); entry.type = BarEntry::Type::Separator; m_entries.push_back(entry); } auto WideBar::getMatching(QAction* act) -> QList<BarEntry>::iterator { auto iter = std::find_if(m_entries.begin(), m_entries.end(), [act](BarEntry const& entry) { return entry.menu_action == act; }); return iter; } void WideBar::insertActionBefore(QAction* before, QAction* action) { auto iter = getMatching(before); if (iter == m_entries.end()) return; BarEntry entry; entry.bar_action = insertWidget(iter->bar_action, new ActionButton(action, this, m_use_default_action)); entry.menu_action = action; entry.type = BarEntry::Type::Action; m_entries.insert(iter, entry); m_menu_state = MenuState::Dirty; } void WideBar::insertActionAfter(QAction* after, QAction* action) { auto iter = getMatching(after); if (iter == m_entries.end()) return; iter++; // the action to insert after is present // however, the element after it isn't valid if (iter == m_entries.end()) { // append the action instead of inserting it addAction(action); return; } BarEntry entry; entry.bar_action = insertWidget(iter->bar_action, new ActionButton(action, this, m_use_default_action)); entry.menu_action = action; entry.type = BarEntry::Type::Action; m_entries.insert(iter, entry); m_menu_state = MenuState::Dirty; } void WideBar::insertWidgetBefore(QAction* before, QWidget* widget) { auto iter = getMatching(before); if (iter == m_entries.end()) return; insertWidget(iter->bar_action, widget); } void WideBar::insertSpacer(QAction* action) { auto iter = getMatching(action); if (iter == m_entries.end()) return; auto* spacer = new QWidget(); spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); BarEntry entry; entry.bar_action = insertWidget(iter->bar_action, spacer); entry.type = BarEntry::Type::Spacer; m_entries.insert(iter, entry); } void WideBar::insertSeparator(QAction* before) { auto iter = getMatching(before); if (iter == m_entries.end()) return; BarEntry entry; entry.bar_action = QToolBar::insertSeparator(iter->bar_action); entry.type = BarEntry::Type::Separator; m_entries.insert(iter, entry); } QMenu* WideBar::createContextMenu(QWidget* parent, const QString& title) { auto* contextMenu = new QMenu(title, parent); for (auto& item : m_entries) { switch (item.type) { default: case BarEntry::Type::None: break; case BarEntry::Type::Separator: case BarEntry::Type::Spacer: contextMenu->addSeparator(); break; case BarEntry::Type::Action: contextMenu->addAction(item.menu_action); break; } } return contextMenu; } static void copyAction(QAction* from, QAction* to) { Q_ASSERT(from); Q_ASSERT(to); to->setText(from->text()); to->setIcon(from->icon()); to->setToolTip(from->toolTip()); } void WideBar::showVisibilityMenu(QPoint const& position) { if (!m_bar_menu) { m_bar_menu = std::make_unique<QMenu>(this); m_bar_menu->setTearOffEnabled(true); } if (m_menu_state == MenuState::Dirty) { for (auto* old_action : m_bar_menu->actions()) old_action->deleteLater(); m_bar_menu->clear(); m_bar_menu->addActions(m_context_menu_actions); m_bar_menu->addSeparator()->setText(tr("Customize toolbar actions")); for (auto& entry : m_entries) { if (entry.type != BarEntry::Type::Action) continue; auto act = new QAction(); copyAction(entry.menu_action, act); act->setCheckable(true); act->setChecked(entry.bar_action->isVisible()); connect(act, &QAction::toggled, entry.bar_action, [this, &entry](bool toggled) { entry.bar_action->setVisible(toggled); // NOTE: This is needed so that disabled actions get reflected on the button when it is made visible. static_cast<ActionButton*>(widgetForAction(entry.bar_action))->actionChanged(); }); m_bar_menu->addAction(act); } m_menu_state = MenuState::Fresh; } m_bar_menu->popup(mapToGlobal(position)); } void WideBar::addContextMenuAction(QAction* action) { m_context_menu_actions.append(action); } [[nodiscard]] QByteArray WideBar::getVisibilityState() const { QByteArray state; for (auto const& entry : m_entries) { if (entry.type != BarEntry::Type::Action) continue; state.append(entry.bar_action->isVisible() ? '1' : '0'); } state.append(','); state.append(getHash()); return state; } void WideBar::setVisibilityState(QByteArray&& state) { auto split = state.split(','); auto bits = split.first(); auto hash = split.last(); // If the actions changed, we better not try to load the old one to avoid unwanted hiding if (!checkHash(hash)) return; qsizetype i = 0; for (auto& entry : m_entries) { if (entry.type != BarEntry::Type::Action) continue; if (i == bits.size()) break; entry.bar_action->setVisible(bits.at(i++) == '1'); // NOTE: This is needed so that disabled actions get reflected on the button when it is made visible. static_cast<ActionButton*>(widgetForAction(entry.bar_action))->actionChanged(); } } QByteArray WideBar::getHash() const { QCryptographicHash hash(QCryptographicHash::Sha1); for (auto const& entry : m_entries) { if (entry.type != BarEntry::Type::Action) continue; hash.addData(entry.menu_action->text().toLatin1()); } return hash.result().toBase64(); } bool WideBar::checkHash(QByteArray const& old_hash) const { return old_hash == getHash(); } void WideBar::removeAction(QAction* action) { auto iter = getMatching(action); if (iter == m_entries.end()) return; iter->bar_action->setVisible(false); removeAction(iter->bar_action); m_entries.erase(iter); } #include "WideBar.moc"
8,808
C++
.cpp
256
28.15625
132
0.651149
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,068
ProgressWidget.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/ProgressWidget.cpp
// Licensed under the Apache-2.0 license. See README.md for details. #include "ProgressWidget.h" #include <QEventLoop> #include <QLabel> #include <QProgressBar> #include <QVBoxLayout> #include "tasks/Task.h" ProgressWidget::ProgressWidget(QWidget* parent, bool show_label) : QWidget(parent) { auto* layout = new QVBoxLayout(this); if (show_label) { m_label = new QLabel(this); m_label->setWordWrap(true); layout->addWidget(m_label); } m_bar = new QProgressBar(this); m_bar->setMinimum(0); m_bar->setMaximum(100); layout->addWidget(m_bar); setLayout(layout); } void ProgressWidget::reset() { m_bar->reset(); } void ProgressWidget::progressFormat(QString format) { if (format.isEmpty()) m_bar->setTextVisible(false); else m_bar->setFormat(format); } void ProgressWidget::watch(const Task* task) { if (!task) return; if (m_task) disconnect(m_task, nullptr, this, nullptr); m_task = task; connect(m_task, &Task::finished, this, &ProgressWidget::handleTaskFinish); connect(m_task, &Task::status, this, &ProgressWidget::handleTaskStatus); // TODO: should we connect &Task::details connect(m_task, &Task::progress, this, &ProgressWidget::handleTaskProgress); connect(m_task, &Task::destroyed, this, &ProgressWidget::taskDestroyed); if (m_task->isRunning()) show(); else connect(m_task, &Task::started, this, &ProgressWidget::show); } void ProgressWidget::start(const Task* task) { watch(task); if (!m_task->isRunning()) QMetaObject::invokeMethod(const_cast<Task*>(m_task), "start", Qt::QueuedConnection); } bool ProgressWidget::exec(std::shared_ptr<Task> task) { QEventLoop loop; connect(task.get(), &Task::finished, &loop, &QEventLoop::quit); start(task.get()); if (task->isRunning()) loop.exec(); return task->wasSuccessful(); } void ProgressWidget::show() { setHidden(false); } void ProgressWidget::hide() { setHidden(true); } void ProgressWidget::handleTaskFinish() { if (!m_task->wasSuccessful() && m_label) m_label->setText(m_task->failReason()); if (m_hide_if_inactive) hide(); } void ProgressWidget::handleTaskStatus(const QString& status) { if (m_label) m_label->setText(status); } void ProgressWidget::handleTaskProgress(qint64 current, qint64 total) { m_bar->setMaximum(total); m_bar->setValue(current); } void ProgressWidget::taskDestroyed() { m_task = nullptr; }
2,547
C++
.cpp
93
23.397849
92
0.682977
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,069
VersionListView.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/VersionListView.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "VersionListView.h" #include <QApplication> #include <QDrag> #include <QHeaderView> #include <QMouseEvent> #include <QPainter> VersionListView::VersionListView(QWidget* parent) : QTreeView(parent) { m_emptyString = tr("No versions are currently available."); } void VersionListView::rowsInserted(const QModelIndex& parent, int start, int end) { m_itemCount += end - start + 1; updateEmptyViewPort(); QTreeView::rowsInserted(parent, start, end); } void VersionListView::rowsAboutToBeRemoved(const QModelIndex& parent, int start, int end) { m_itemCount -= end - start + 1; updateEmptyViewPort(); QTreeView::rowsInserted(parent, start, end); } void VersionListView::setModel(QAbstractItemModel* model) { m_itemCount = model->rowCount(); updateEmptyViewPort(); QTreeView::setModel(model); } void VersionListView::reset() { if (model()) { m_itemCount = model()->rowCount(); } else { m_itemCount = 0; } updateEmptyViewPort(); QTreeView::reset(); } void VersionListView::setEmptyString(QString emptyString) { m_emptyString = emptyString; updateEmptyViewPort(); } void VersionListView::setEmptyErrorString(QString emptyErrorString) { m_emptyErrorString = emptyErrorString; updateEmptyViewPort(); } void VersionListView::setEmptyMode(VersionListView::EmptyMode mode) { m_emptyMode = mode; updateEmptyViewPort(); } void VersionListView::updateEmptyViewPort() { #ifndef QT_NO_ACCESSIBILITY setAccessibleDescription(currentEmptyString()); #endif /* !QT_NO_ACCESSIBILITY */ if (!m_itemCount) { viewport()->update(); } } void VersionListView::paintEvent(QPaintEvent* event) { if (m_itemCount) { QTreeView::paintEvent(event); } else { paintInfoLabel(event); } } QString VersionListView::currentEmptyString() const { switch (m_emptyMode) { default: case VersionListView::String: return m_emptyString; case VersionListView::ErrorString: return m_emptyErrorString; } } void VersionListView::paintInfoLabel(QPaintEvent* event) const { QString emptyString = currentEmptyString(); // calculate the rect for the overlay QPainter painter(viewport()); painter.setRenderHint(QPainter::Antialiasing, true); QFont font("sans", 20); font.setBold(true); QRect bounds = viewport()->geometry(); bounds.moveTop(0); auto innerBounds = bounds; innerBounds.adjust(10, 10, -10, -10); QColor background = QApplication::palette().color(QPalette::WindowText); QColor foreground = QApplication::palette().color(QPalette::Base); foreground.setAlpha(190); painter.setFont(font); auto fontMetrics = painter.fontMetrics(); auto textRect = fontMetrics.boundingRect(innerBounds, Qt::AlignHCenter | Qt::TextWordWrap, emptyString); textRect.moveCenter(bounds.center()); auto wrapRect = textRect; wrapRect.adjust(-10, -10, 10, 10); // check if we are allowed to draw in our area if (!event->rect().intersects(wrapRect)) { return; } painter.setBrush(QBrush(background)); painter.setPen(foreground); painter.drawRoundedRect(wrapRect, 5.0, 5.0); painter.setPen(foreground); painter.setFont(font); painter.drawText(textRect, Qt::AlignHCenter | Qt::TextWordWrap, emptyString); }
4,931
C++
.cpp
147
29.972789
108
0.723074
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,070
JavaSettingsWidget.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/JavaSettingsWidget.cpp
#include "JavaSettingsWidget.h" #include <QFileDialog> #include <QGroupBox> #include <QLabel> #include <QLayoutItem> #include <QLineEdit> #include <QMessageBox> #include <QPushButton> #include <QSizePolicy> #include <QSpinBox> #include <QToolButton> #include <QVBoxLayout> #include <sys.h> #include "DesktopServices.h" #include "FileSystem.h" #include "JavaCommon.h" #include "java/JavaChecker.h" #include "java/JavaInstall.h" #include "java/JavaInstallList.h" #include "java/JavaUtils.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/java/InstallJavaDialog.h" #include "ui/widgets/VersionSelectWidget.h" #include "Application.h" #include "BuildConfig.h" JavaSettingsWidget::JavaSettingsWidget(QWidget* parent) : QWidget(parent) { m_availableMemory = Sys::getSystemRam() / Sys::mebibyte; goodIcon = APPLICATION->getThemedIcon("status-good"); yellowIcon = APPLICATION->getThemedIcon("status-yellow"); badIcon = APPLICATION->getThemedIcon("status-bad"); m_memoryTimer = new QTimer(this); setupUi(); connect(m_minMemSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onSpinBoxValueChanged(int))); connect(m_maxMemSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onSpinBoxValueChanged(int))); connect(m_permGenSpinBox, SIGNAL(valueChanged(int)), this, SLOT(onSpinBoxValueChanged(int))); connect(m_memoryTimer, &QTimer::timeout, this, &JavaSettingsWidget::memoryValueChanged); connect(m_versionWidget, &VersionSelectWidget::selectedVersionChanged, this, &JavaSettingsWidget::javaVersionSelected); connect(m_javaBrowseBtn, &QPushButton::clicked, this, &JavaSettingsWidget::on_javaBrowseBtn_clicked); connect(m_javaPathTextBox, &QLineEdit::textEdited, this, &JavaSettingsWidget::javaPathEdited); connect(m_javaStatusBtn, &QToolButton::clicked, this, &JavaSettingsWidget::on_javaStatusBtn_clicked); if (BuildConfig.JAVA_DOWNLOADER_ENABLED) { connect(m_javaDownloadBtn, &QPushButton::clicked, this, &JavaSettingsWidget::javaDownloadBtn_clicked); } } void JavaSettingsWidget::setupUi() { setObjectName(QStringLiteral("javaSettingsWidget")); m_verticalLayout = new QVBoxLayout(this); m_verticalLayout->setObjectName(QStringLiteral("verticalLayout")); m_versionWidget = new VersionSelectWidget(this); m_horizontalLayout = new QHBoxLayout(); m_horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); m_javaPathTextBox = new QLineEdit(this); m_javaPathTextBox->setObjectName(QStringLiteral("javaPathTextBox")); m_horizontalLayout->addWidget(m_javaPathTextBox); m_javaBrowseBtn = new QPushButton(this); m_javaBrowseBtn->setObjectName(QStringLiteral("javaBrowseBtn")); m_horizontalLayout->addWidget(m_javaBrowseBtn); m_javaStatusBtn = new QToolButton(this); m_javaStatusBtn->setIcon(yellowIcon); m_horizontalLayout->addWidget(m_javaStatusBtn); m_memoryGroupBox = new QGroupBox(this); m_memoryGroupBox->setObjectName(QStringLiteral("memoryGroupBox")); m_gridLayout_2 = new QGridLayout(m_memoryGroupBox); m_gridLayout_2->setObjectName(QStringLiteral("gridLayout_2")); m_gridLayout_2->setColumnStretch(0, 1); m_labelMinMem = new QLabel(m_memoryGroupBox); m_labelMinMem->setObjectName(QStringLiteral("labelMinMem")); m_gridLayout_2->addWidget(m_labelMinMem, 0, 0, 1, 1); m_minMemSpinBox = new QSpinBox(m_memoryGroupBox); m_minMemSpinBox->setObjectName(QStringLiteral("minMemSpinBox")); m_minMemSpinBox->setSuffix(QStringLiteral(" MiB")); m_minMemSpinBox->setMinimum(8); m_minMemSpinBox->setMaximum(1048576); m_minMemSpinBox->setSingleStep(128); m_labelMinMem->setBuddy(m_minMemSpinBox); m_gridLayout_2->addWidget(m_minMemSpinBox, 0, 1, 1, 1); m_labelMaxMem = new QLabel(m_memoryGroupBox); m_labelMaxMem->setObjectName(QStringLiteral("labelMaxMem")); m_gridLayout_2->addWidget(m_labelMaxMem, 1, 0, 1, 1); m_maxMemSpinBox = new QSpinBox(m_memoryGroupBox); m_maxMemSpinBox->setObjectName(QStringLiteral("maxMemSpinBox")); m_maxMemSpinBox->setSuffix(QStringLiteral(" MiB")); m_maxMemSpinBox->setMinimum(8); m_maxMemSpinBox->setMaximum(1048576); m_maxMemSpinBox->setSingleStep(128); m_labelMaxMem->setBuddy(m_maxMemSpinBox); m_gridLayout_2->addWidget(m_maxMemSpinBox, 1, 1, 1, 1); m_labelMaxMemIcon = new QLabel(m_memoryGroupBox); m_labelMaxMemIcon->setObjectName(QStringLiteral("labelMaxMemIcon")); m_gridLayout_2->addWidget(m_labelMaxMemIcon, 1, 2, 1, 1); m_labelPermGen = new QLabel(m_memoryGroupBox); m_labelPermGen->setObjectName(QStringLiteral("labelPermGen")); m_labelPermGen->setText(QStringLiteral("PermGen:")); m_gridLayout_2->addWidget(m_labelPermGen, 2, 0, 1, 1); m_labelPermGen->setVisible(false); m_permGenSpinBox = new QSpinBox(m_memoryGroupBox); m_permGenSpinBox->setObjectName(QStringLiteral("permGenSpinBox")); m_permGenSpinBox->setSuffix(QStringLiteral(" MiB")); m_permGenSpinBox->setMinimum(4); m_permGenSpinBox->setMaximum(1048576); m_permGenSpinBox->setSingleStep(8); m_gridLayout_2->addWidget(m_permGenSpinBox, 2, 1, 1, 1); m_permGenSpinBox->setVisible(false); m_verticalLayout->addWidget(m_memoryGroupBox); m_horizontalBtnLayout = new QHBoxLayout(); m_horizontalBtnLayout->setObjectName(QStringLiteral("horizontalBtnLayout")); if (BuildConfig.JAVA_DOWNLOADER_ENABLED) { m_javaDownloadBtn = new QPushButton(tr("Download Java"), this); m_horizontalBtnLayout->addWidget(m_javaDownloadBtn); } m_autoJavaGroupBox = new QGroupBox(this); m_autoJavaGroupBox->setObjectName(QStringLiteral("autoJavaGroupBox")); m_veriticalJavaLayout = new QVBoxLayout(m_autoJavaGroupBox); m_veriticalJavaLayout->setObjectName(QStringLiteral("veriticalJavaLayout")); m_autodetectJavaCheckBox = new QCheckBox(m_autoJavaGroupBox); m_autodetectJavaCheckBox->setObjectName("autodetectJavaCheckBox"); m_autodetectJavaCheckBox->setChecked(true); m_veriticalJavaLayout->addWidget(m_autodetectJavaCheckBox); if (BuildConfig.JAVA_DOWNLOADER_ENABLED) { m_autodownloadCheckBox = new QCheckBox(m_autoJavaGroupBox); m_autodownloadCheckBox->setObjectName("autodownloadCheckBox"); m_autodownloadCheckBox->setEnabled(m_autodetectJavaCheckBox->isChecked()); m_veriticalJavaLayout->addWidget(m_autodownloadCheckBox); connect(m_autodetectJavaCheckBox, &QCheckBox::stateChanged, this, [this] { m_autodownloadCheckBox->setEnabled(m_autodetectJavaCheckBox->isChecked()); if (!m_autodetectJavaCheckBox->isChecked()) m_autodownloadCheckBox->setChecked(false); }); connect(m_autodownloadCheckBox, &QCheckBox::stateChanged, this, [this] { auto isChecked = m_autodownloadCheckBox->isChecked(); m_versionWidget->setVisible(!isChecked); m_javaStatusBtn->setVisible(!isChecked); m_javaBrowseBtn->setVisible(!isChecked); m_javaPathTextBox->setVisible(!isChecked); m_javaDownloadBtn->setVisible(!isChecked); if (!isChecked) { m_verticalLayout->removeItem(m_verticalSpacer); } else { m_verticalLayout->addSpacerItem(m_verticalSpacer); } }); } m_verticalLayout->addWidget(m_autoJavaGroupBox); m_verticalLayout->addLayout(m_horizontalBtnLayout); m_verticalLayout->addWidget(m_versionWidget); m_verticalLayout->addLayout(m_horizontalLayout); m_verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding); retranslate(); } void JavaSettingsWidget::initialize() { m_versionWidget->initialize(APPLICATION->javalist().get()); m_versionWidget->selectSearch(); m_versionWidget->setResizeOn(2); auto s = APPLICATION->settings(); // Memory observedMinMemory = s->get("MinMemAlloc").toInt(); observedMaxMemory = s->get("MaxMemAlloc").toInt(); observedPermGenMemory = s->get("PermGen").toInt(); m_minMemSpinBox->setValue(observedMinMemory); m_maxMemSpinBox->setValue(observedMaxMemory); m_permGenSpinBox->setValue(observedPermGenMemory); updateThresholds(); if (BuildConfig.JAVA_DOWNLOADER_ENABLED) { m_autodownloadCheckBox->setChecked(true); } } void JavaSettingsWidget::refresh() { if (BuildConfig.JAVA_DOWNLOADER_ENABLED && m_autodownloadCheckBox->isChecked()) { return; } if (JavaUtils::getJavaCheckPath().isEmpty()) { JavaCommon::javaCheckNotFound(this); return; } m_versionWidget->loadList(); } JavaSettingsWidget::ValidationStatus JavaSettingsWidget::validate() { switch (javaStatus) { default: case JavaStatus::NotSet: /* fallthrough */ case JavaStatus::DoesNotExist: /* fallthrough */ case JavaStatus::DoesNotStart: /* fallthrough */ case JavaStatus::ReturnedInvalidData: { if (!(BuildConfig.JAVA_DOWNLOADER_ENABLED && m_autodownloadCheckBox->isChecked())) { // the java will not be autodownloaded int button = QMessageBox::No; if (m_result.mojangPlatform == "32" && maxHeapSize() > 2048) { button = CustomMessageBox::selectable( this, tr("32-bit Java detected"), tr("You selected a 32-bit installation of Java, but allocated more than 2048MiB as maximum memory.\n" "%1 will not be able to start Minecraft.\n" "Do you wish to proceed?" "\n\n" "You can change the Java version in the settings later.\n") .arg(BuildConfig.LAUNCHER_DISPLAYNAME), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No | QMessageBox::Help, QMessageBox::NoButton) ->exec(); } else { button = CustomMessageBox::selectable(this, tr("No Java version selected"), tr("You either didn't select a Java version or selected one that does not work.\n" "%1 will not be able to start Minecraft.\n" "Do you wish to proceed without a functional version of Java?" "\n\n" "You can change the Java version in the settings later.\n") .arg(BuildConfig.LAUNCHER_DISPLAYNAME), QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No | QMessageBox::Help, QMessageBox::NoButton) ->exec(); } switch (button) { case QMessageBox::Yes: return ValidationStatus::JavaBad; case QMessageBox::Help: DesktopServices::openUrl(QUrl(BuildConfig.HELP_URL.arg("java-wizard"))); /* fallthrough */ case QMessageBox::No: /* fallthrough */ default: return ValidationStatus::Bad; } if (button == QMessageBox::No) { return ValidationStatus::Bad; } } return ValidationStatus::JavaBad; } break; case JavaStatus::Pending: { return ValidationStatus::Bad; } case JavaStatus::Good: { return ValidationStatus::AllOK; } } } QString JavaSettingsWidget::javaPath() const { return m_javaPathTextBox->text(); } int JavaSettingsWidget::maxHeapSize() const { auto min = m_minMemSpinBox->value(); auto max = m_maxMemSpinBox->value(); if (max < min) max = min; return max; } int JavaSettingsWidget::minHeapSize() const { auto min = m_minMemSpinBox->value(); auto max = m_maxMemSpinBox->value(); if (min > max) min = max; return min; } bool JavaSettingsWidget::permGenEnabled() const { return m_permGenSpinBox->isVisible(); } int JavaSettingsWidget::permGenSize() const { return m_permGenSpinBox->value(); } void JavaSettingsWidget::memoryValueChanged() { bool actuallyChanged = false; unsigned int min = m_minMemSpinBox->value(); unsigned int max = m_maxMemSpinBox->value(); unsigned int permgen = m_permGenSpinBox->value(); if (min != observedMinMemory) { observedMinMemory = min; actuallyChanged = true; } if (max != observedMaxMemory) { observedMaxMemory = max; actuallyChanged = true; } if (permgen != observedPermGenMemory) { observedPermGenMemory = permgen; actuallyChanged = true; } if (actuallyChanged) { checkJavaPathOnEdit(m_javaPathTextBox->text()); updateThresholds(); } } void JavaSettingsWidget::javaVersionSelected(BaseVersion::Ptr version) { auto java = std::dynamic_pointer_cast<JavaInstall>(version); if (!java) { return; } auto visible = java->id.requiresPermGen(); m_labelPermGen->setVisible(visible); m_permGenSpinBox->setVisible(visible); m_javaPathTextBox->setText(java->path); checkJavaPath(java->path); } void JavaSettingsWidget::on_javaBrowseBtn_clicked() { auto filter = QString("Java (%1)").arg(JavaUtils::javaExecutable); auto raw_path = QFileDialog::getOpenFileName(this, tr("Find Java executable"), QString(), filter); if (raw_path.isEmpty()) { return; } auto cooked_path = FS::NormalizePath(raw_path); m_javaPathTextBox->setText(cooked_path); checkJavaPath(cooked_path); } void JavaSettingsWidget::javaDownloadBtn_clicked() { auto jdialog = new Java::InstallDialog({}, nullptr, this); jdialog->exec(); } void JavaSettingsWidget::on_javaStatusBtn_clicked() { QString text; bool failed = false; switch (javaStatus) { case JavaStatus::NotSet: checkJavaPath(m_javaPathTextBox->text()); return; case JavaStatus::DoesNotExist: text += QObject::tr("The specified file either doesn't exist or is not a proper executable."); failed = true; break; case JavaStatus::DoesNotStart: { text += QObject::tr("The specified Java binary didn't start properly.<br />"); auto htmlError = m_result.errorLog; if (!htmlError.isEmpty()) { htmlError.replace('\n', "<br />"); text += QString("<font color=\"red\">%1</font>").arg(htmlError); } failed = true; break; } case JavaStatus::ReturnedInvalidData: { text += QObject::tr("The specified Java binary returned unexpected results:<br />"); auto htmlOut = m_result.outLog; if (!htmlOut.isEmpty()) { htmlOut.replace('\n', "<br />"); text += QString("<font color=\"red\">%1</font>").arg(htmlOut); } failed = true; break; } case JavaStatus::Good: text += QObject::tr( "Java test succeeded!<br />Platform reported: %1<br />Java version " "reported: %2<br />") .arg(m_result.realPlatform, m_result.javaVersion.toString()); break; case JavaStatus::Pending: // TODO: abort here? return; } CustomMessageBox::selectable(this, failed ? QObject::tr("Java test failure") : QObject::tr("Java test success"), text, failed ? QMessageBox::Critical : QMessageBox::Information) ->show(); } void JavaSettingsWidget::setJavaStatus(JavaSettingsWidget::JavaStatus status) { javaStatus = status; switch (javaStatus) { case JavaStatus::Good: m_javaStatusBtn->setIcon(goodIcon); break; case JavaStatus::NotSet: case JavaStatus::Pending: m_javaStatusBtn->setIcon(yellowIcon); break; default: m_javaStatusBtn->setIcon(badIcon); break; } } void JavaSettingsWidget::javaPathEdited(const QString& path) { checkJavaPathOnEdit(path); } void JavaSettingsWidget::checkJavaPathOnEdit(const QString& path) { auto realPath = FS::ResolveExecutable(path); QFileInfo pathInfo(realPath); if (pathInfo.baseName().toLower().contains("java")) { checkJavaPath(path); } else { if (!m_checker) { setJavaStatus(JavaStatus::NotSet); } } } void JavaSettingsWidget::checkJavaPath(const QString& path) { if (m_checker) { queuedCheck = path; return; } auto realPath = FS::ResolveExecutable(path); if (realPath.isNull()) { setJavaStatus(JavaStatus::DoesNotExist); return; } setJavaStatus(JavaStatus::Pending); m_checker.reset( new JavaChecker(path, "", minHeapSize(), maxHeapSize(), m_permGenSpinBox->isVisible() ? m_permGenSpinBox->value() : 0, 0)); connect(m_checker.get(), &JavaChecker::checkFinished, this, &JavaSettingsWidget::checkFinished); m_checker->start(); } void JavaSettingsWidget::checkFinished(const JavaChecker::Result& result) { m_result = result; switch (result.validity) { case JavaChecker::Result::Validity::Valid: { setJavaStatus(JavaStatus::Good); break; } case JavaChecker::Result::Validity::ReturnedInvalidData: { setJavaStatus(JavaStatus::ReturnedInvalidData); break; } case JavaChecker::Result::Validity::Errored: { setJavaStatus(JavaStatus::DoesNotStart); break; } } updateThresholds(); m_checker.reset(); if (!queuedCheck.isNull()) { checkJavaPath(queuedCheck); queuedCheck.clear(); } } void JavaSettingsWidget::retranslate() { m_memoryGroupBox->setTitle(tr("Memory")); m_maxMemSpinBox->setToolTip(tr("The maximum amount of memory Minecraft is allowed to use.")); m_labelMinMem->setText(tr("Minimum memory allocation:")); m_labelMaxMem->setText(tr("Maximum memory allocation:")); m_minMemSpinBox->setToolTip(tr("The amount of memory Minecraft is started with.")); m_permGenSpinBox->setToolTip(tr("The amount of memory available to store loaded Java classes.")); m_javaBrowseBtn->setText(tr("Browse")); if (BuildConfig.JAVA_DOWNLOADER_ENABLED) { m_autodownloadCheckBox->setText(tr("Auto-download Mojang Java")); } m_autodetectJavaCheckBox->setText(tr("Autodetect Java version")); m_autoJavaGroupBox->setTitle(tr("Autodetect Java")); } void JavaSettingsWidget::updateThresholds() { QString iconName; if (observedMaxMemory >= m_availableMemory) { iconName = "status-bad"; m_labelMaxMemIcon->setToolTip(tr("Your maximum memory allocation exceeds your system memory capacity.")); } else if (observedMaxMemory > (m_availableMemory * 0.9)) { iconName = "status-yellow"; m_labelMaxMemIcon->setToolTip(tr("Your maximum memory allocation approaches your system memory capacity.")); } else if (observedMaxMemory < observedMinMemory) { iconName = "status-yellow"; m_labelMaxMemIcon->setToolTip(tr("Your maximum memory allocation is smaller than the minimum value")); } else if (BuildConfig.JAVA_DOWNLOADER_ENABLED && m_autodownloadCheckBox->isChecked()) { iconName = "status-good"; m_labelMaxMemIcon->setToolTip(""); } else if (observedMaxMemory > 2048 && !m_result.is_64bit) { iconName = "status-bad"; m_labelMaxMemIcon->setToolTip(tr("You are exceeding the maximum allocation supported by 32-bit installations of Java.")); } else { iconName = "status-good"; m_labelMaxMemIcon->setToolTip(""); } { auto height = m_labelMaxMemIcon->fontInfo().pixelSize(); QIcon icon = APPLICATION->getThemedIcon(iconName); QPixmap pix = icon.pixmap(height, height); m_labelMaxMemIcon->setPixmap(pix); } } bool JavaSettingsWidget::autoDownloadJava() const { return m_autodownloadCheckBox && m_autodownloadCheckBox->isChecked(); } bool JavaSettingsWidget::autoDetectJava() const { return m_autodetectJavaCheckBox->isChecked(); } void JavaSettingsWidget::onSpinBoxValueChanged(int) { m_memoryTimer->start(500); } JavaSettingsWidget::~JavaSettingsWidget() { delete m_verticalSpacer; };
21,009
C++
.cpp
499
33.835671
140
0.656203
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,071
ThemeCustomizationWidget.cpp
PrismLauncher_PrismLauncher/launcher/ui/widgets/ThemeCustomizationWidget.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2024 Tayou <git@tayou.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ThemeCustomizationWidget.h" #include "ui_ThemeCustomizationWidget.h" #include "Application.h" #include "DesktopServices.h" #include "ui/themes/ITheme.h" #include "ui/themes/ThemeManager.h" ThemeCustomizationWidget::ThemeCustomizationWidget(QWidget* parent) : QWidget(parent), ui(new Ui::ThemeCustomizationWidget) { ui->setupUi(this); loadSettings(); ThemeCustomizationWidget::refresh(); connect(ui->iconsComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThemeCustomizationWidget::applyIconTheme); connect(ui->widgetStyleComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThemeCustomizationWidget::applyWidgetTheme); connect(ui->backgroundCatComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThemeCustomizationWidget::applyCatTheme); connect(ui->iconsFolder, &QPushButton::clicked, this, [] { DesktopServices::openPath(APPLICATION->themeManager()->getIconThemesFolder().path()); }); connect(ui->widgetStyleFolder, &QPushButton::clicked, this, [] { DesktopServices::openPath(APPLICATION->themeManager()->getApplicationThemesFolder().path()); }); connect(ui->catPackFolder, &QPushButton::clicked, this, [] { DesktopServices::openPath(APPLICATION->themeManager()->getCatPacksFolder().path()); }); connect(ui->refreshButton, &QPushButton::clicked, this, &ThemeCustomizationWidget::refresh); } ThemeCustomizationWidget::~ThemeCustomizationWidget() { delete ui; } /// <summary> /// The layout was not quite right, so currently this just disables the UI elements, which should be hidden instead /// TODO FIXME /// /// Original Method One: /// ui->iconsComboBox->setVisible(features& ThemeFields::ICONS); /// ui->iconsLabel->setVisible(features& ThemeFields::ICONS); /// ui->widgetStyleComboBox->setVisible(features& ThemeFields::WIDGETS); /// ui->widgetThemeLabel->setVisible(features& ThemeFields::WIDGETS); /// ui->backgroundCatComboBox->setVisible(features& ThemeFields::CAT); /// ui->backgroundCatLabel->setVisible(features& ThemeFields::CAT); /// /// original Method Two: /// if (!(features & ThemeFields::ICONS)) { /// ui->formLayout->setRowVisible(0, false); /// } /// if (!(features & ThemeFields::WIDGETS)) { /// ui->formLayout->setRowVisible(1, false); /// } /// if (!(features & ThemeFields::CAT)) { /// ui->formLayout->setRowVisible(2, false); /// } /// </summary> /// <param name="features"></param> void ThemeCustomizationWidget::showFeatures(ThemeFields features) { ui->iconsComboBox->setEnabled(features & ThemeFields::ICONS); ui->iconsLabel->setEnabled(features & ThemeFields::ICONS); ui->widgetStyleComboBox->setEnabled(features & ThemeFields::WIDGETS); ui->widgetStyleLabel->setEnabled(features & ThemeFields::WIDGETS); ui->backgroundCatComboBox->setEnabled(features & ThemeFields::CAT); ui->backgroundCatLabel->setEnabled(features & ThemeFields::CAT); } void ThemeCustomizationWidget::applyIconTheme(int index) { auto settings = APPLICATION->settings(); auto originalIconTheme = settings->get("IconTheme").toString(); auto newIconTheme = ui->iconsComboBox->itemData(index).toString(); if (originalIconTheme != newIconTheme) { settings->set("IconTheme", newIconTheme); APPLICATION->themeManager()->applyCurrentlySelectedTheme(); } emit currentIconThemeChanged(index); } void ThemeCustomizationWidget::applyWidgetTheme(int index) { auto settings = APPLICATION->settings(); auto originalAppTheme = settings->get("ApplicationTheme").toString(); auto newAppTheme = ui->widgetStyleComboBox->itemData(index).toString(); if (originalAppTheme != newAppTheme) { settings->set("ApplicationTheme", newAppTheme); APPLICATION->themeManager()->applyCurrentlySelectedTheme(); } emit currentWidgetThemeChanged(index); } void ThemeCustomizationWidget::applyCatTheme(int index) { auto settings = APPLICATION->settings(); auto originalCat = settings->get("BackgroundCat").toString(); auto newCat = ui->backgroundCatComboBox->itemData(index).toString(); if (originalCat != newCat) { settings->set("BackgroundCat", newCat); } emit currentCatChanged(index); } void ThemeCustomizationWidget::applySettings() { applyIconTheme(ui->iconsComboBox->currentIndex()); applyWidgetTheme(ui->widgetStyleComboBox->currentIndex()); applyCatTheme(ui->backgroundCatComboBox->currentIndex()); } void ThemeCustomizationWidget::loadSettings() { auto settings = APPLICATION->settings(); { auto currentIconTheme = settings->get("IconTheme").toString(); auto iconThemes = APPLICATION->themeManager()->getValidIconThemes(); int idx = 0; for (auto iconTheme : iconThemes) { QIcon iconForComboBox = QIcon(iconTheme->path() + "/scalable/settings"); ui->iconsComboBox->addItem(iconForComboBox, iconTheme->name(), iconTheme->id()); if (currentIconTheme == iconTheme->id()) { ui->iconsComboBox->setCurrentIndex(idx); } idx++; } } { auto currentTheme = settings->get("ApplicationTheme").toString(); auto themes = APPLICATION->themeManager()->getValidApplicationThemes(); int idx = 0; for (auto& theme : themes) { ui->widgetStyleComboBox->addItem(theme->name(), theme->id()); if (theme->tooltip() != "") { int index = ui->widgetStyleComboBox->count() - 1; ui->widgetStyleComboBox->setItemData(index, theme->tooltip(), Qt::ToolTipRole); } if (currentTheme == theme->id()) { ui->widgetStyleComboBox->setCurrentIndex(idx); } idx++; } } auto cat = settings->get("BackgroundCat").toString(); for (auto& catFromList : APPLICATION->themeManager()->getValidCatPacks()) { QIcon catIcon = QIcon(QString("%1").arg(catFromList->path())); ui->backgroundCatComboBox->addItem(catIcon, catFromList->name(), catFromList->id()); if (cat == catFromList->id()) { ui->backgroundCatComboBox->setCurrentIndex(ui->backgroundCatComboBox->count() - 1); } } } void ThemeCustomizationWidget::retranslate() { ui->retranslateUi(this); } void ThemeCustomizationWidget::refresh() { applySettings(); disconnect(ui->iconsComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThemeCustomizationWidget::applyIconTheme); disconnect(ui->widgetStyleComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThemeCustomizationWidget::applyWidgetTheme); disconnect(ui->backgroundCatComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThemeCustomizationWidget::applyCatTheme); APPLICATION->themeManager()->refresh(); ui->iconsComboBox->clear(); ui->widgetStyleComboBox->clear(); ui->backgroundCatComboBox->clear(); loadSettings(); connect(ui->iconsComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThemeCustomizationWidget::applyIconTheme); connect(ui->widgetStyleComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThemeCustomizationWidget::applyWidgetTheme); connect(ui->backgroundCatComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &ThemeCustomizationWidget::applyCatTheme); };
8,251
C++
.cpp
178
41.314607
140
0.70987
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,072
DarkTheme.cpp
PrismLauncher_PrismLauncher/launcher/ui/themes/DarkTheme.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2024 Tayou <git@tayou.org> * Copyright (C) 2024 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "DarkTheme.h" #include <QObject> QString DarkTheme::id() { return "dark"; } QString DarkTheme::name() { return QObject::tr("Dark"); } QPalette DarkTheme::colorScheme() { QPalette darkPalette; darkPalette.setColor(QPalette::Window, QColor(49, 49, 49)); darkPalette.setColor(QPalette::WindowText, Qt::white); darkPalette.setColor(QPalette::Base, QColor(34, 34, 34)); darkPalette.setColor(QPalette::AlternateBase, QColor(42, 42, 42)); darkPalette.setColor(QPalette::ToolTipBase, Qt::white); darkPalette.setColor(QPalette::ToolTipText, Qt::white); darkPalette.setColor(QPalette::Text, Qt::white); darkPalette.setColor(QPalette::Button, QColor(48, 48, 48)); darkPalette.setColor(QPalette::ButtonText, Qt::white); darkPalette.setColor(QPalette::BrightText, Qt::red); darkPalette.setColor(QPalette::Link, QColor(47, 163, 198)); darkPalette.setColor(QPalette::Highlight, QColor(150, 219, 89)); darkPalette.setColor(QPalette::HighlightedText, Qt::black); darkPalette.setColor(QPalette::PlaceholderText, Qt::darkGray); return fadeInactive(darkPalette, fadeAmount(), fadeColor()); } double DarkTheme::fadeAmount() { return 0.5; } QColor DarkTheme::fadeColor() { return QColor(49, 49, 49); } bool DarkTheme::hasStyleSheet() { return true; } QString DarkTheme::appStyleSheet() { return "QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"; } QString DarkTheme::tooltip() { return ""; }
3,050
C++
.cpp
84
33.714286
94
0.732161
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,073
ThemeManager.cpp
PrismLauncher_PrismLauncher/launcher/ui/themes/ThemeManager.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2024 Tayou <git@tayou.org> * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ThemeManager.h" #include <QApplication> #include <QDir> #include <QDirIterator> #include <QIcon> #include <QImageReader> #include <QStyle> #include <QStyleFactory> #include "Exception.h" #include "ui/themes/BrightTheme.h" #include "ui/themes/CatPack.h" #include "ui/themes/CustomTheme.h" #include "ui/themes/DarkTheme.h" #include "ui/themes/SystemTheme.h" #include "Application.h" ThemeManager::ThemeManager() { themeDebugLog() << "Determining System Widget Theme..."; const auto& style = QApplication::style(); m_defaultStyle = style->objectName(); themeDebugLog() << "System theme seems to be:" << m_defaultStyle; m_defaultPalette = QApplication::palette(); initializeThemes(); initializeCatPacks(); } /// @brief Adds the Theme to the list of themes /// @param theme The Theme to add /// @return Theme ID QString ThemeManager::addTheme(std::unique_ptr<ITheme> theme) { QString id = theme->id(); if (m_themes.find(id) == m_themes.end()) m_themes.emplace(id, std::move(theme)); else themeWarningLog() << "Theme(" << id << ") not added to prevent id duplication"; return id; } /// @brief Gets the Theme from the List via ID /// @param themeId Theme ID of theme to fetch /// @return Theme at themeId ITheme* ThemeManager::getTheme(QString themeId) { return m_themes[themeId].get(); } QString ThemeManager::addIconTheme(IconTheme theme) { QString id = theme.id(); if (m_icons.find(id) == m_icons.end()) m_icons.emplace(id, std::move(theme)); else themeWarningLog() << "IconTheme(" << id << ") not added to prevent id duplication"; return id; } void ThemeManager::initializeThemes() { // Icon themes initializeIcons(); // Initialize widget themes initializeWidgets(); } void ThemeManager::initializeIcons() { // TODO: icon themes and instance icons do not mesh well together. Rearrange and fix discrepancies! // set icon theme search path! themeDebugLog() << "<> Initializing Icon Themes"; auto searchPaths = QIcon::themeSearchPaths(); searchPaths.append(m_iconThemeFolder.path()); QIcon::setThemeSearchPaths(searchPaths); for (const QString& id : builtinIcons) { IconTheme theme(id, QString(":/icons/%1").arg(id)); if (!theme.load()) { themeWarningLog() << "Couldn't load built-in icon theme" << id; continue; } addIconTheme(std::move(theme)); themeDebugLog() << "Loaded Built-In Icon Theme" << id; } if (!m_iconThemeFolder.mkpath(".")) themeWarningLog() << "Couldn't create icon theme folder"; themeDebugLog() << "Icon Theme Folder Path: " << m_iconThemeFolder.absolutePath(); QDirIterator directoryIterator(m_iconThemeFolder.path(), QDir::Dirs | QDir::NoDotAndDotDot); while (directoryIterator.hasNext()) { QDir dir(directoryIterator.next()); IconTheme theme(dir.dirName(), dir.path()); if (!theme.load()) continue; addIconTheme(std::move(theme)); themeDebugLog() << "Loaded Custom Icon Theme from" << dir.path(); } themeDebugLog() << "<> Icon themes initialized."; } void ThemeManager::initializeWidgets() { themeDebugLog() << "<> Initializing Widget Themes"; themeDebugLog() << "Loading Built-in Theme:" << addTheme(std::make_unique<SystemTheme>(m_defaultStyle, m_defaultPalette, true)); auto darkThemeId = addTheme(std::make_unique<DarkTheme>()); themeDebugLog() << "Loading Built-in Theme:" << darkThemeId; themeDebugLog() << "Loading Built-in Theme:" << addTheme(std::make_unique<BrightTheme>()); themeDebugLog() << "<> Initializing System Widget Themes"; QStringList styles = QStyleFactory::keys(); for (auto& st : styles) { #ifdef Q_OS_WINDOWS if (QSysInfo::productVersion() != "11" && st == "windows11") { continue; } #endif themeDebugLog() << "Loading System Theme:" << addTheme(std::make_unique<SystemTheme>(st, m_defaultPalette, false)); } // TODO: need some way to differentiate same name themes in different subdirectories // (maybe smaller grey text next to theme name in dropdown?) if (!m_applicationThemeFolder.mkpath(".")) themeWarningLog() << "Couldn't create theme folder"; themeDebugLog() << "Theme Folder Path: " << m_applicationThemeFolder.absolutePath(); QDirIterator directoryIterator(m_applicationThemeFolder.path(), QDir::Dirs | QDir::NoDotAndDotDot); while (directoryIterator.hasNext()) { QDir dir(directoryIterator.next()); QFileInfo themeJson(dir.absoluteFilePath("theme.json")); if (themeJson.exists()) { // Load "theme.json" based themes themeDebugLog() << "Loading JSON Theme from:" << themeJson.absoluteFilePath(); addTheme(std::make_unique<CustomTheme>(getTheme(darkThemeId), themeJson, true)); } else { // Load pure QSS Themes QDirIterator stylesheetFileIterator(dir.absoluteFilePath(""), { "*.qss", "*.css" }, QDir::Files); while (stylesheetFileIterator.hasNext()) { QFile customThemeFile(stylesheetFileIterator.next()); QFileInfo customThemeFileInfo(customThemeFile); themeDebugLog() << "Loading QSS Theme from:" << customThemeFileInfo.absoluteFilePath(); addTheme(std::make_unique<CustomTheme>(getTheme(darkThemeId), customThemeFileInfo, false)); } } } themeDebugLog() << "<> Widget themes initialized."; } QList<IconTheme*> ThemeManager::getValidIconThemes() { QList<IconTheme*> ret; ret.reserve(m_icons.size()); for (auto&& [id, theme] : m_icons) { ret.append(&theme); } return ret; } QList<ITheme*> ThemeManager::getValidApplicationThemes() { QList<ITheme*> ret; ret.reserve(m_themes.size()); for (auto&& [id, theme] : m_themes) { ret.append(theme.get()); } return ret; } QList<CatPack*> ThemeManager::getValidCatPacks() { QList<CatPack*> ret; ret.reserve(m_catPacks.size()); for (auto&& [id, theme] : m_catPacks) { ret.append(theme.get()); } return ret; } bool ThemeManager::isValidIconTheme(const QString& id) { return !id.isEmpty() && m_icons.find(id) != m_icons.end(); } bool ThemeManager::isValidApplicationTheme(const QString& id) { return !id.isEmpty() && m_themes.find(id) != m_themes.end(); } QDir ThemeManager::getIconThemesFolder() { return m_iconThemeFolder; } QDir ThemeManager::getApplicationThemesFolder() { return m_applicationThemeFolder; } QDir ThemeManager::getCatPacksFolder() { return m_catPacksFolder; } void ThemeManager::setIconTheme(const QString& name) { if (m_icons.find(name) == m_icons.end()) { themeWarningLog() << "Tried to set invalid icon theme:" << name; return; } QIcon::setThemeName(name); } void ThemeManager::setApplicationTheme(const QString& name, bool initial) { auto systemPalette = qApp->palette(); auto themeIter = m_themes.find(name); if (themeIter != m_themes.end()) { auto& theme = themeIter->second; themeDebugLog() << "applying theme" << theme->name(); theme->apply(initial); m_logColors = theme->logColorScheme(); } else { themeWarningLog() << "Tried to set invalid theme:" << name; } } void ThemeManager::applyCurrentlySelectedTheme(bool initial) { auto settings = APPLICATION->settings(); setIconTheme(settings->get("IconTheme").toString()); themeDebugLog() << "<> Icon theme set."; auto applicationTheme = settings->get("ApplicationTheme").toString(); if (applicationTheme == "") { applicationTheme = m_defaultStyle; } setApplicationTheme(applicationTheme, initial); themeDebugLog() << "<> Application theme set."; } QString ThemeManager::getCatPack(QString catName) { auto catIter = m_catPacks.find(!catName.isEmpty() ? catName : APPLICATION->settings()->get("BackgroundCat").toString()); if (catIter != m_catPacks.end()) { auto& catPack = catIter->second; themeDebugLog() << "applying catpack" << catPack->id(); return catPack->path(); } else { themeWarningLog() << "Tried to get invalid catPack:" << catName; } return m_catPacks.begin()->second->path(); } QString ThemeManager::addCatPack(std::unique_ptr<CatPack> catPack) { QString id = catPack->id(); if (m_catPacks.find(id) == m_catPacks.end()) m_catPacks.emplace(id, std::move(catPack)); else themeWarningLog() << "CatPack(" << id << ") not added to prevent id duplication"; return id; } void ThemeManager::initializeCatPacks() { QList<std::pair<QString, QString>> defaultCats{ { "kitteh", QObject::tr("Background Cat (from MultiMC)") }, { "rory", QObject::tr("Rory ID 11 (drawn by Ashtaka)") }, { "rory-flat", QObject::tr("Rory ID 11 (flat edition, drawn by Ashtaka)") }, { "teawie", QObject::tr("Teawie (drawn by SympathyTea)") } }; for (auto [id, name] : defaultCats) { addCatPack(std::unique_ptr<CatPack>(new BasicCatPack(id, name))); } if (!m_catPacksFolder.mkpath(".")) themeWarningLog() << "Couldn't create catpacks folder"; themeDebugLog() << "CatPacks Folder Path:" << m_catPacksFolder.absolutePath(); QStringList supportedImageFormats; for (auto format : QImageReader::supportedImageFormats()) { supportedImageFormats.append("*." + format); } auto loadFiles = [this, supportedImageFormats](QDir dir) { // Load image files directly QDirIterator ImageFileIterator(dir.absoluteFilePath(""), supportedImageFormats, QDir::Files); while (ImageFileIterator.hasNext()) { QFile customCatFile(ImageFileIterator.next()); QFileInfo customCatFileInfo(customCatFile); themeDebugLog() << "Loading CatPack from:" << customCatFileInfo.absoluteFilePath(); addCatPack(std::unique_ptr<CatPack>(new FileCatPack(customCatFileInfo))); } }; loadFiles(m_catPacksFolder); QDirIterator directoryIterator(m_catPacksFolder.path(), QDir::Dirs | QDir::NoDotAndDotDot); while (directoryIterator.hasNext()) { QDir dir(directoryIterator.next()); QFileInfo manifest(dir.absoluteFilePath("catpack.json")); if (manifest.isFile()) { try { // Load background manifest themeDebugLog() << "Loading background manifest from:" << manifest.absoluteFilePath(); addCatPack(std::unique_ptr<CatPack>(new JsonCatPack(manifest))); } catch (const Exception& e) { themeWarningLog() << "Couldn't load catpack json:" << e.cause(); } } else { loadFiles(dir); } } } void ThemeManager::refresh() { m_themes.clear(); m_icons.clear(); m_catPacks.clear(); initializeThemes(); initializeCatPacks(); }
11,939
C++
.cpp
305
33.367213
132
0.660885
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,074
SystemTheme.cpp
PrismLauncher_PrismLauncher/launcher/ui/themes/SystemTheme.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2024 Tayou <git@tayou.org> * Copyright (C) 2024 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SystemTheme.h" #include <QApplication> #include <QStyle> #include <QStyleFactory> #include "HintOverrideProxyStyle.h" #include "ThemeManager.h" SystemTheme::SystemTheme(const QString& styleName, const QPalette& palette, bool isDefaultTheme) { themeName = isDefaultTheme ? "system" : styleName; widgetTheme = styleName; colorPalette = palette; } void SystemTheme::apply(bool initial) { // See https://github.com/MultiMC/Launcher/issues/1790 // or https://github.com/PrismLauncher/PrismLauncher/issues/490 if (initial) { QApplication::setStyle(new HintOverrideProxyStyle(QStyleFactory::create(qtTheme()))); return; } ITheme::apply(initial); } QString SystemTheme::id() { return themeName; } QString SystemTheme::name() { if (themeName.toLower() == "windowsvista") { return QObject::tr("Windows Vista"); } else if (themeName.toLower() == "windows") { return QObject::tr("Windows 9x"); } else if (themeName.toLower() == "windows11") { return QObject::tr("Windows 11"); } else if (themeName.toLower() == "system") { return QObject::tr("System"); } else { return themeName; } } QString SystemTheme::tooltip() { if (themeName.toLower() == "windowsvista") { return QObject::tr("Widget style trying to look like your win32 theme"); } else if (themeName.toLower() == "windows") { return QObject::tr("Windows 9x inspired widget style"); } else if (themeName.toLower() == "windows11") { return QObject::tr("WinUI 3 inspired Qt widget style"); } else if (themeName.toLower() == "fusion") { return QObject::tr("The default Qt widget style"); } else if (themeName.toLower() == "system") { return QObject::tr("Your current system theme"); } else { return ""; } } QString SystemTheme::qtTheme() { return widgetTheme; } QPalette SystemTheme::colorScheme() { return colorPalette; } QString SystemTheme::appStyleSheet() { return QString(); } double SystemTheme::fadeAmount() { return 0.5; } QColor SystemTheme::fadeColor() { return QColor(128, 128, 128); } bool SystemTheme::hasStyleSheet() { return false; }
3,764
C++
.cpp
115
29.46087
96
0.700577
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,075
HintOverrideProxyStyle.cpp
PrismLauncher_PrismLauncher/launcher/ui/themes/HintOverrideProxyStyle.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2024 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "HintOverrideProxyStyle.h" int HintOverrideProxyStyle::styleHint(QStyle::StyleHint hint, const QStyleOption* option, const QWidget* widget, QStyleHintReturn* returnData) const { if (hint == QStyle::SH_ItemView_ActivateItemOnSingleClick) return 0; return QProxyStyle::styleHint(hint, option, widget, returnData); }
1,198
C++
.cpp
27
37.888889
74
0.689212
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,076
CatPack.cpp
PrismLauncher_PrismLauncher/launcher/ui/themes/CatPack.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ui/themes/CatPack.h" #include <QDate> #include <QDir> #include <QDirIterator> #include <QFileInfo> #include <QImageReader> #include <QRandomGenerator> #include "FileSystem.h" #include "Json.h" QString BasicCatPack::path() { const auto now = QDate::currentDate(); const auto birthday = QDate(now.year(), 11, 1); const auto xmas = QDate(now.year(), 12, 25); const auto halloween = QDate(now.year(), 10, 31); QString cat = QString(":/backgrounds/%1").arg(m_id); if (std::abs(now.daysTo(xmas)) <= 4) { cat += "-xmas"; } else if (std::abs(now.daysTo(halloween)) <= 4) { cat += "-spooky"; } else if (std::abs(now.daysTo(birthday)) <= 12) { cat += "-bday"; } return cat; } JsonCatPack::PartialDate partialDate(QJsonObject date) { auto month = Json::ensureInteger(date, "month", 1); if (month > 12) month = 12; else if (month <= 0) month = 1; auto day = Json::ensureInteger(date, "day", 1); if (day > 31) day = 31; else if (day <= 0) day = 1; return { month, day }; }; JsonCatPack::JsonCatPack(QFileInfo& manifestInfo) : BasicCatPack(manifestInfo.dir().dirName()) { QString path = manifestInfo.path(); auto doc = Json::requireDocument(manifestInfo.absoluteFilePath(), "CatPack JSON file"); const auto root = doc.object(); m_name = Json::requireString(root, "name", "Catpack name"); m_default_path = FS::PathCombine(path, Json::requireString(root, "default", "Default Cat")); auto variants = Json::ensureArray(root, "variants", QJsonArray(), "Catpack Variants"); for (auto v : variants) { auto variant = Json::ensureObject(v, QJsonObject(), "Cat variant"); m_variants << Variant{ FS::PathCombine(path, Json::requireString(variant, "path", "Variant path")), partialDate(Json::requireObject(variant, "startTime", "Variant startTime")), partialDate(Json::requireObject(variant, "endTime", "Variant endTime")) }; } } QDate ensureDay(int year, int month, int day) { QDate date(year, month, 1); if (day > date.daysInMonth()) day = date.daysInMonth(); return QDate(year, month, day); } QString JsonCatPack::path() { return path(QDate::currentDate()); } QString JsonCatPack::path(QDate now) { for (auto var : m_variants) { QDate startDate = ensureDay(now.year(), var.startTime.month, var.startTime.day); QDate endDate = ensureDay(now.year(), var.endTime.month, var.endTime.day); if (startDate > endDate) { // it's spans over multiple years if (endDate < now) // end date is in the past so jump one year into the future for endDate endDate = endDate.addYears(1); else // end date is in the future so jump one year into the past for startDate startDate = startDate.addYears(-1); } if (startDate <= now && now <= endDate) return var.path; } auto dInfo = QFileInfo(m_default_path); if (!dInfo.isDir()) return m_default_path; QStringList supportedImageFormats; for (auto format : QImageReader::supportedImageFormats()) { supportedImageFormats.append("*." + format); } auto files = QDir(m_default_path).entryInfoList(supportedImageFormats, QDir::Files, QDir::Name); if (files.length() == 0) return ""; auto idx = (now.dayOfYear() - 1) % files.length(); auto isRandom = dInfo.fileName().compare("random", Qt::CaseInsensitive) == 0; if (isRandom) idx = QRandomGenerator::global()->bounded(0, files.length()); return files[idx].absoluteFilePath(); }
5,197
C++
.cpp
129
35.465116
107
0.663437
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,077
CustomTheme.cpp
PrismLauncher_PrismLauncher/launcher/ui/themes/CustomTheme.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2024 Tayou <git@tayou.org> * Copyright (C) 2024 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "CustomTheme.h" #include <FileSystem.h> #include <Json.h> #include "ThemeManager.h" const char* themeFile = "theme.json"; /// @param baseTheme Base Theme /// @param fileInfo FileInfo object for file to load /// @param isManifest whether to load a theme manifest or a qss file CustomTheme::CustomTheme(ITheme* baseTheme, QFileInfo& fileInfo, bool isManifest) { if (isManifest) { m_id = fileInfo.dir().dirName(); QString path = FS::PathCombine("themes", m_id); QString pathResources = FS::PathCombine("themes", m_id, "resources"); if (!FS::ensureFolderPathExists(path)) { themeWarningLog() << "Theme directory for" << m_id << "could not be created. This theme might be invalid"; return; } if (!FS::ensureFolderPathExists(pathResources)) { themeWarningLog() << "Resources directory for" << m_id << "could not be created"; } auto themeFilePath = FS::PathCombine(path, themeFile); m_palette = baseTheme->colorScheme(); bool hasCustomLogColors = false; if (read(themeFilePath, hasCustomLogColors)) { // If theme data was found, fade "Disabled" color of each role according to FadeAmount m_palette = fadeInactive(m_palette, m_fadeAmount, m_fadeColor); if (!hasCustomLogColors) m_logColors = defaultLogColors(m_palette); } else { themeDebugLog() << "Did not read theme json file correctly, not changing theme, keeping previous."; m_logColors = defaultLogColors(m_palette); return; } auto qssFilePath = FS::PathCombine(path, m_qssFilePath); QFileInfo info(qssFilePath); if (info.isFile()) { try { // TODO: validate qss? m_styleSheet = QString::fromUtf8(FS::read(qssFilePath)); } catch (const Exception& e) { themeWarningLog() << "Couldn't load qss:" << e.cause() << "from" << qssFilePath; return; } } else { themeDebugLog() << "No theme qss present."; } } else { m_id = fileInfo.fileName(); m_name = fileInfo.baseName(); QString path = fileInfo.filePath(); // themeDebugLog << "Theme ID: " << m_id; // themeDebugLog << "Theme Name: " << m_name; // themeDebugLog << "Theme Path: " << path; if (!FS::ensureFilePathExists(path)) { themeWarningLog() << m_name << " Theme file path doesn't exist!"; m_palette = baseTheme->colorScheme(); m_styleSheet = baseTheme->appStyleSheet(); return; } m_palette = baseTheme->colorScheme(); try { // TODO: validate qss? m_styleSheet = QString::fromUtf8(FS::read(path)); } catch (const Exception& e) { themeWarningLog() << "Couldn't load qss:" << e.cause() << "from" << path; m_styleSheet = baseTheme->appStyleSheet(); } } } QStringList CustomTheme::searchPaths() { QString pathResources = FS::PathCombine("themes", m_id, "resources"); if (QFileInfo::exists(pathResources)) return { pathResources }; return {}; } QString CustomTheme::id() { return m_id; } QString CustomTheme::name() { return m_name; } QPalette CustomTheme::colorScheme() { return m_palette; } bool CustomTheme::hasStyleSheet() { return true; } QString CustomTheme::appStyleSheet() { return m_styleSheet; } double CustomTheme::fadeAmount() { return m_fadeAmount; } QColor CustomTheme::fadeColor() { return m_fadeColor; } QString CustomTheme::qtTheme() { return m_widgets; } QString CustomTheme::tooltip() { return m_tooltip; } bool CustomTheme::read(const QString& path, bool& hasCustomLogColors) { QFileInfo pathInfo(path); if (pathInfo.exists() && pathInfo.isFile()) { try { auto doc = Json::requireDocument(path, "Theme JSON file"); const QJsonObject root = doc.object(); m_name = Json::requireString(root, "name", "Theme name"); m_widgets = Json::requireString(root, "widgets", "Qt widget theme"); m_qssFilePath = Json::ensureString(root, "qssFilePath", "themeStyle.css"); auto readColor = [](const QJsonObject& colors, const QString& colorName) -> QColor { auto colorValue = Json::ensureString(colors, colorName, QString()); if (!colorValue.isEmpty()) { QColor color(colorValue); if (!color.isValid()) { themeWarningLog() << "Color value" << colorValue << "for" << colorName << "was not recognized."; return {}; } return color; } return {}; }; if (root.contains("colors")) { auto colorsRoot = Json::requireObject(root, "colors"); auto readAndSetPaletteColor = [this, readColor, colorsRoot](QPalette::ColorRole role, const QString& colorName) { auto color = readColor(colorsRoot, colorName); if (color.isValid()) { m_palette.setColor(role, color); } else { themeDebugLog() << "Color value for" << colorName << "was not present."; } }; // palette readAndSetPaletteColor(QPalette::Window, "Window"); readAndSetPaletteColor(QPalette::WindowText, "WindowText"); readAndSetPaletteColor(QPalette::Base, "Base"); readAndSetPaletteColor(QPalette::AlternateBase, "AlternateBase"); readAndSetPaletteColor(QPalette::ToolTipBase, "ToolTipBase"); readAndSetPaletteColor(QPalette::ToolTipText, "ToolTipText"); readAndSetPaletteColor(QPalette::Text, "Text"); readAndSetPaletteColor(QPalette::Button, "Button"); readAndSetPaletteColor(QPalette::ButtonText, "ButtonText"); readAndSetPaletteColor(QPalette::BrightText, "BrightText"); readAndSetPaletteColor(QPalette::Link, "Link"); readAndSetPaletteColor(QPalette::Highlight, "Highlight"); readAndSetPaletteColor(QPalette::HighlightedText, "HighlightedText"); // fade m_fadeColor = readColor(colorsRoot, "fadeColor"); m_fadeAmount = Json::ensureDouble(colorsRoot, "fadeAmount", 0.5, "fade amount"); } if (root.contains("logColors")) { hasCustomLogColors = true; auto logColorsRoot = Json::requireObject(root, "logColors"); auto readAndSetLogColor = [this, readColor, logColorsRoot](MessageLevel::Enum level, bool fg, const QString& colorName) { auto color = readColor(logColorsRoot, colorName); if (color.isValid()) { if (fg) m_logColors.foreground[level] = color; else m_logColors.background[level] = color; } else { themeDebugLog() << "Color value for" << colorName << "was not present."; } }; readAndSetLogColor(MessageLevel::Message, false, "MessageHighlight"); readAndSetLogColor(MessageLevel::Launcher, false, "LauncherHighlight"); readAndSetLogColor(MessageLevel::Debug, false, "DebugHighlight"); readAndSetLogColor(MessageLevel::Warning, false, "WarningHighlight"); readAndSetLogColor(MessageLevel::Error, false, "ErrorHighlight"); readAndSetLogColor(MessageLevel::Fatal, false, "FatalHighlight"); readAndSetLogColor(MessageLevel::Message, true, "Message"); readAndSetLogColor(MessageLevel::Launcher, true, "Launcher"); readAndSetLogColor(MessageLevel::Debug, true, "Debug"); readAndSetLogColor(MessageLevel::Warning, true, "Warning"); readAndSetLogColor(MessageLevel::Error, true, "Error"); readAndSetLogColor(MessageLevel::Fatal, true, "Fatal"); } } catch (const Exception& e) { themeWarningLog() << "Couldn't load theme json: " << e.cause(); return false; } } else { themeDebugLog() << "No theme json present."; return false; } return true; }
10,217
C++
.cpp
235
33.859574
137
0.605729
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,078
ITheme.cpp
PrismLauncher_PrismLauncher/launcher/ui/themes/ITheme.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Tayou <git@tayou.org> * Copyright (C) 2024 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ITheme.h" #include <QDir> #include <QStyleFactory> #include "Application.h" #include "HintOverrideProxyStyle.h" #include "rainbow.h" void ITheme::apply(bool) { APPLICATION->setStyleSheet(QString()); QApplication::setStyle(new HintOverrideProxyStyle(QStyleFactory::create(qtTheme()))); QApplication::setPalette(colorScheme()); APPLICATION->setStyleSheet(appStyleSheet()); QDir::setSearchPaths("theme", searchPaths()); } QPalette ITheme::fadeInactive(QPalette in, qreal bias, QColor color) { auto blend = [&in, bias, color](QPalette::ColorRole role) { QColor from = in.color(QPalette::Active, role); QColor blended = Rainbow::mix(from, color, bias); in.setColor(QPalette::Disabled, role, blended); }; blend(QPalette::Window); blend(QPalette::WindowText); blend(QPalette::Base); blend(QPalette::AlternateBase); blend(QPalette::ToolTipBase); blend(QPalette::ToolTipText); blend(QPalette::Text); blend(QPalette::Button); blend(QPalette::ButtonText); blend(QPalette::BrightText); blend(QPalette::Link); blend(QPalette::Highlight); blend(QPalette::HighlightedText); return in; } LogColors ITheme::defaultLogColors(const QPalette& palette) { LogColors result; const QColor& bg = palette.color(QPalette::Base); const QColor& fg = palette.color(QPalette::Text); auto blend = [bg, fg](QColor color) { if (Rainbow::luma(fg) > Rainbow::luma(bg)) { // for dark color schemes, produce a fitting color first color = Rainbow::tint(fg, color, 0.5); } // adapt contrast return Rainbow::mix(fg, color, 1); }; result.background[MessageLevel::Fatal] = Qt::black; result.foreground[MessageLevel::Launcher] = blend(QColor("purple")); result.foreground[MessageLevel::Debug] = blend(QColor("green")); result.foreground[MessageLevel::Warning] = blend(QColor("orange")); result.foreground[MessageLevel::Error] = blend(QColor("red")); result.foreground[MessageLevel::Fatal] = blend(QColor("red")); return result; }
3,653
C++
.cpp
92
35.956522
89
0.710948
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,079
IconTheme.cpp
PrismLauncher_PrismLauncher/launcher/ui/themes/IconTheme.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "IconTheme.h" #include <QFile> #include <QSettings> IconTheme::IconTheme(const QString& id, const QString& path) : m_id(id), m_path(path) {} bool IconTheme::load() { const QString path = m_path + "/index.theme"; if (!QFile::exists(path)) return false; QSettings settings(path, QSettings::IniFormat); settings.beginGroup("Icon Theme"); m_name = settings.value("Name").toString(); settings.endGroup(); return !m_name.isNull(); } QString IconTheme::id() { return m_id; } QString IconTheme::path() { return m_path; } QString IconTheme::name() { return m_name; }
1,366
C++
.cpp
44
28.409091
88
0.719726
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,080
BrightTheme.cpp
PrismLauncher_PrismLauncher/launcher/ui/themes/BrightTheme.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2024 Tayou <git@tayou.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "BrightTheme.h" #include <QObject> QString BrightTheme::id() { return "bright"; } QString BrightTheme::name() { return QObject::tr("Bright"); } QPalette BrightTheme::colorScheme() { QPalette brightPalette; brightPalette.setColor(QPalette::Window, QColor(255, 255, 255)); brightPalette.setColor(QPalette::WindowText, QColor(17, 17, 17)); brightPalette.setColor(QPalette::Base, QColor(250, 250, 250)); brightPalette.setColor(QPalette::AlternateBase, QColor(240, 240, 240)); brightPalette.setColor(QPalette::ToolTipBase, QColor(17, 17, 17)); brightPalette.setColor(QPalette::ToolTipText, QColor(255, 255, 255)); brightPalette.setColor(QPalette::Text, Qt::black); brightPalette.setColor(QPalette::Button, QColor(249, 249, 249)); brightPalette.setColor(QPalette::ButtonText, Qt::black); brightPalette.setColor(QPalette::BrightText, Qt::red); brightPalette.setColor(QPalette::Link, QColor(37, 137, 164)); brightPalette.setColor(QPalette::Highlight, QColor(137, 207, 84)); brightPalette.setColor(QPalette::HighlightedText, Qt::black); return fadeInactive(brightPalette, fadeAmount(), fadeColor()); } double BrightTheme::fadeAmount() { return 0.5; } QColor BrightTheme::fadeColor() { return QColor(255, 255, 255); } bool BrightTheme::hasStyleSheet() { return false; } QString BrightTheme::appStyleSheet() { return QString(); } QString BrightTheme::tooltip() { return QString(); }
2,955
C++
.cpp
82
33.47561
80
0.736475
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,082
InstanceProxyModel.cpp
PrismLauncher_PrismLauncher/launcher/ui/instanceview/InstanceProxyModel.cpp
/* Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "InstanceProxyModel.h" #include <BaseInstance.h> #include <icons/IconList.h> #include "Application.h" #include "InstanceView.h" #include <QDebug> InstanceProxyModel::InstanceProxyModel(QObject* parent) : QSortFilterProxyModel(parent) { m_naturalSort.setNumericMode(true); m_naturalSort.setCaseSensitivity(Qt::CaseSensitivity::CaseInsensitive); // FIXME: use loaded translation as source of locale instead, hook this up to translation changes m_naturalSort.setLocale(QLocale::system()); } QVariant InstanceProxyModel::data(const QModelIndex& index, int role) const { QVariant data = QSortFilterProxyModel::data(index, role); if (role == Qt::DecorationRole) { return QVariant(APPLICATION->icons()->getIcon(data.toString())); } return data; } bool InstanceProxyModel::lessThan(const QModelIndex& left, const QModelIndex& right) const { const QString leftCategory = left.data(InstanceViewRoles::GroupRole).toString(); const QString rightCategory = right.data(InstanceViewRoles::GroupRole).toString(); if (leftCategory == rightCategory) { return subSortLessThan(left, right); } else { // FIXME: real group sorting happens in InstanceView::updateGeometries(), see LocaleString auto result = leftCategory.localeAwareCompare(rightCategory); if (result == 0) { return subSortLessThan(left, right); } return result < 0; } } bool InstanceProxyModel::subSortLessThan(const QModelIndex& left, const QModelIndex& right) const { BaseInstance* pdataLeft = static_cast<BaseInstance*>(left.internalPointer()); BaseInstance* pdataRight = static_cast<BaseInstance*>(right.internalPointer()); QString sortMode = APPLICATION->settings()->get("InstSortMode").toString(); if (sortMode == "LastLaunch") { return pdataLeft->lastLaunch() > pdataRight->lastLaunch(); } else { return m_naturalSort.compare(pdataLeft->name(), pdataRight->name()) < 0; } }
2,607
C++
.cpp
61
38.786885
101
0.739661
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,083
AccessibleInstanceView.cpp
PrismLauncher_PrismLauncher/launcher/ui/instanceview/AccessibleInstanceView.cpp
#include "AccessibleInstanceView.h" #include "AccessibleInstanceView_p.h" #include "InstanceView.h" #include <qaccessible.h> #include <qheaderview.h> #include <qvariant.h> #ifndef QT_NO_ACCESSIBILITY QAccessibleInterface* groupViewAccessibleFactory(const QString& classname, QObject* object) { QAccessibleInterface* iface = 0; if (!object || !object->isWidgetType()) return iface; QWidget* widget = static_cast<QWidget*>(object); if (classname == QLatin1String("InstanceView")) { iface = new AccessibleInstanceView((InstanceView*)widget); } return iface; } QAbstractItemView* AccessibleInstanceView::view() const { return qobject_cast<QAbstractItemView*>(object()); } int AccessibleInstanceView::logicalIndex(const QModelIndex& index) const { if (!view()->model() || !index.isValid()) return -1; return index.row() * (index.model()->columnCount()) + index.column(); } AccessibleInstanceView::AccessibleInstanceView(QWidget* w) : QAccessibleObject(w) { Q_ASSERT(view()); } bool AccessibleInstanceView::isValid() const { return view(); } AccessibleInstanceView::~AccessibleInstanceView() { for (QAccessible::Id id : childToId) { QAccessible::deleteAccessibleInterface(id); } } QAccessibleInterface* AccessibleInstanceView::cellAt(int row, int column) const { if (!view()->model()) { return 0; } QModelIndex index = view()->model()->index(row, column, view()->rootIndex()); if (Q_UNLIKELY(!index.isValid())) { qWarning() << "AccessibleInstanceView::cellAt: invalid index: " << index << " for " << view(); return 0; } return child(logicalIndex(index)); } QAccessibleInterface* AccessibleInstanceView::caption() const { return 0; } QString AccessibleInstanceView::columnDescription(int column) const { if (!view()->model()) return QString(); return view()->model()->headerData(column, Qt::Horizontal).toString(); } int AccessibleInstanceView::columnCount() const { if (!view()->model()) return 0; return 1; } int AccessibleInstanceView::rowCount() const { if (!view()->model()) return 0; return view()->model()->rowCount(); } int AccessibleInstanceView::selectedCellCount() const { if (!view()->selectionModel()) return 0; return view()->selectionModel()->selectedIndexes().count(); } int AccessibleInstanceView::selectedColumnCount() const { if (!view()->selectionModel()) return 0; return view()->selectionModel()->selectedColumns().count(); } int AccessibleInstanceView::selectedRowCount() const { if (!view()->selectionModel()) return 0; return view()->selectionModel()->selectedRows().count(); } QString AccessibleInstanceView::rowDescription(int row) const { if (!view()->model()) return QString(); return view()->model()->headerData(row, Qt::Vertical).toString(); } QList<QAccessibleInterface*> AccessibleInstanceView::selectedCells() const { QList<QAccessibleInterface*> cells; if (!view()->selectionModel()) return cells; const QModelIndexList selectedIndexes = view()->selectionModel()->selectedIndexes(); cells.reserve(selectedIndexes.size()); for (const QModelIndex& index : selectedIndexes) cells.append(child(logicalIndex(index))); return cells; } QList<int> AccessibleInstanceView::selectedColumns() const { if (!view()->selectionModel()) { return QList<int>(); } const QModelIndexList selectedColumns = view()->selectionModel()->selectedColumns(); QList<int> columns; columns.reserve(selectedColumns.size()); for (const QModelIndex& index : selectedColumns) { columns.append(index.column()); } return columns; } QList<int> AccessibleInstanceView::selectedRows() const { if (!view()->selectionModel()) { return QList<int>(); } QList<int> rows; const QModelIndexList selectedRows = view()->selectionModel()->selectedRows(); rows.reserve(selectedRows.size()); for (const QModelIndex& index : selectedRows) { rows.append(index.row()); } return rows; } QAccessibleInterface* AccessibleInstanceView::summary() const { return 0; } bool AccessibleInstanceView::isColumnSelected(int column) const { if (!view()->selectionModel()) { return false; } return view()->selectionModel()->isColumnSelected(column, QModelIndex()); } bool AccessibleInstanceView::isRowSelected(int row) const { if (!view()->selectionModel()) { return false; } return view()->selectionModel()->isRowSelected(row, QModelIndex()); } bool AccessibleInstanceView::selectRow(int row) { if (!view()->model() || !view()->selectionModel()) { return false; } QModelIndex index = view()->model()->index(row, 0, view()->rootIndex()); if (!index.isValid() || view()->selectionBehavior() == QAbstractItemView::SelectColumns) { return false; } switch (view()->selectionMode()) { case QAbstractItemView::NoSelection: { return false; } case QAbstractItemView::SingleSelection: { if (view()->selectionBehavior() != QAbstractItemView::SelectRows && columnCount() > 1) return false; view()->clearSelection(); break; } case QAbstractItemView::ContiguousSelection: { if ((!row || !view()->selectionModel()->isRowSelected(row - 1, view()->rootIndex())) && !view()->selectionModel()->isRowSelected(row + 1, view()->rootIndex())) { view()->clearSelection(); } break; } default: { break; } } view()->selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Rows); return true; } bool AccessibleInstanceView::selectColumn(int column) { if (!view()->model() || !view()->selectionModel()) { return false; } QModelIndex index = view()->model()->index(0, column, view()->rootIndex()); if (!index.isValid() || view()->selectionBehavior() == QAbstractItemView::SelectRows) { return false; } switch (view()->selectionMode()) { case QAbstractItemView::NoSelection: { return false; } case QAbstractItemView::SingleSelection: { if (view()->selectionBehavior() != QAbstractItemView::SelectColumns && rowCount() > 1) { return false; } } /* fallthrough */ case QAbstractItemView::ContiguousSelection: { if ((!column || !view()->selectionModel()->isColumnSelected(column - 1, view()->rootIndex())) && !view()->selectionModel()->isColumnSelected(column + 1, view()->rootIndex())) { view()->clearSelection(); } break; } default: { break; } } view()->selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Columns); return true; } bool AccessibleInstanceView::unselectRow(int row) { if (!view()->model() || !view()->selectionModel()) { return false; } QModelIndex index = view()->model()->index(row, 0, view()->rootIndex()); if (!index.isValid()) { return false; } QItemSelection selection(index, index); auto selectionModel = view()->selectionModel(); switch (view()->selectionMode()) { case QAbstractItemView::SingleSelection: // no unselect if (selectedRowCount() == 1) { return false; } break; case QAbstractItemView::ContiguousSelection: { // no unselect if (selectedRowCount() == 1) { return false; } if ((!row || selectionModel->isRowSelected(row - 1, view()->rootIndex())) && selectionModel->isRowSelected(row + 1, view()->rootIndex())) { // If there are rows selected both up the current row and down the current rown, // the ones which are down the current row will be deselected selection = QItemSelection(index, view()->model()->index(rowCount() - 1, 0, view()->rootIndex())); } } default: { break; } } selectionModel->select(selection, QItemSelectionModel::Deselect | QItemSelectionModel::Rows); return true; } bool AccessibleInstanceView::unselectColumn(int column) { auto model = view()->model(); if (!model || !view()->selectionModel()) { return false; } QModelIndex index = model->index(0, column, view()->rootIndex()); if (!index.isValid()) { return false; } QItemSelection selection(index, index); switch (view()->selectionMode()) { case QAbstractItemView::SingleSelection: { // In SingleSelection and ContiguousSelection once an item // is selected, there's no way for the user to unselect all items if (selectedColumnCount() == 1) { return false; } break; } case QAbstractItemView::ContiguousSelection: if (selectedColumnCount() == 1) { return false; } if ((!column || view()->selectionModel()->isColumnSelected(column - 1, view()->rootIndex())) && view()->selectionModel()->isColumnSelected(column + 1, view()->rootIndex())) { // If there are columns selected both at the left of the current row and at the right // of the current row, the ones which are at the right will be deselected selection = QItemSelection(index, model->index(0, columnCount() - 1, view()->rootIndex())); } default: break; } view()->selectionModel()->select(selection, QItemSelectionModel::Deselect | QItemSelectionModel::Columns); return true; } QAccessible::Role AccessibleInstanceView::role() const { return QAccessible::List; } QAccessible::State AccessibleInstanceView::state() const { return QAccessible::State(); } QAccessibleInterface* AccessibleInstanceView::childAt(int x, int y) const { QPoint viewportOffset = view()->viewport()->mapTo(view(), QPoint(0, 0)); QPoint indexPosition = view()->mapFromGlobal(QPoint(x, y) - viewportOffset); // FIXME: if indexPosition < 0 in one coordinate, return header QModelIndex index = view()->indexAt(indexPosition); if (index.isValid()) { return child(logicalIndex(index)); } return 0; } int AccessibleInstanceView::childCount() const { if (!view()->model()) { return 0; } return (view()->model()->rowCount()) * (view()->model()->columnCount()); } int AccessibleInstanceView::indexOfChild(const QAccessibleInterface* iface) const { if (!view()->model()) return -1; QAccessibleInterface* parent = iface->parent(); if (parent->object() != view()) return -1; Q_ASSERT(iface->role() != QAccessible::TreeItem); // should be handled by tree class if (iface->role() == QAccessible::Cell || iface->role() == QAccessible::ListItem) { const AccessibleInstanceViewItem* cell = static_cast<const AccessibleInstanceViewItem*>(iface); return logicalIndex(cell->m_index); } else if (iface->role() == QAccessible::Pane) { return 0; // corner button } else { qWarning() << "AccessibleInstanceView::indexOfChild has a child with unknown role..." << iface->role() << iface->text(QAccessible::Name); } // FIXME: we are in denial of our children. this should stop. return -1; } QString AccessibleInstanceView::text(QAccessible::Text t) const { if (t == QAccessible::Description) return view()->accessibleDescription(); return view()->accessibleName(); } QRect AccessibleInstanceView::rect() const { if (!view()->isVisible()) return QRect(); QPoint pos = view()->mapToGlobal(QPoint(0, 0)); return QRect(pos.x(), pos.y(), view()->width(), view()->height()); } QAccessibleInterface* AccessibleInstanceView::parent() const { if (view() && view()->parent()) { if (qstrcmp("QComboBoxPrivateContainer", view()->parent()->metaObject()->className()) == 0) { return QAccessible::queryAccessibleInterface(view()->parent()->parent()); } return QAccessible::queryAccessibleInterface(view()->parent()); } return 0; } QAccessibleInterface* AccessibleInstanceView::child(int logicalIndex) const { if (!view()->model()) return 0; auto id = childToId.constFind(logicalIndex); if (id != childToId.constEnd()) return QAccessible::accessibleInterface(id.value()); int columns = view()->model()->columnCount(); int row = logicalIndex / columns; int column = logicalIndex % columns; QAccessibleInterface* iface = 0; QModelIndex index = view()->model()->index(row, column, view()->rootIndex()); if (Q_UNLIKELY(!index.isValid())) { qWarning("AccessibleInstanceView::child: Invalid index at: %d %d", row, column); return 0; } iface = new AccessibleInstanceViewItem(view(), index); QAccessible::registerAccessibleInterface(iface); childToId.insert(logicalIndex, QAccessible::uniqueId(iface)); return iface; } void* AccessibleInstanceView::interface_cast(QAccessible::InterfaceType t) { if (t == QAccessible::TableInterface) return static_cast<QAccessibleTableInterface*>(this); return 0; } void AccessibleInstanceView::modelChange(QAccessibleTableModelChangeEvent* event) { // if there is no cache yet, we don't update anything if (childToId.isEmpty()) return; switch (event->modelChangeType()) { case QAccessibleTableModelChangeEvent::ModelReset: for (QAccessible::Id id : childToId) QAccessible::deleteAccessibleInterface(id); childToId.clear(); break; // rows are inserted: move every row after that case QAccessibleTableModelChangeEvent::RowsInserted: case QAccessibleTableModelChangeEvent::ColumnsInserted: { ChildCache newCache; ChildCache::ConstIterator iter = childToId.constBegin(); while (iter != childToId.constEnd()) { QAccessible::Id id = iter.value(); QAccessibleInterface* iface = QAccessible::accessibleInterface(id); Q_ASSERT(iface); if (indexOfChild(iface) >= 0) { newCache.insert(indexOfChild(iface), id); } else { // ### This should really not happen, // but it might if the view has a root index set. // This needs to be fixed. QAccessible::deleteAccessibleInterface(id); } ++iter; } childToId = newCache; break; } case QAccessibleTableModelChangeEvent::ColumnsRemoved: case QAccessibleTableModelChangeEvent::RowsRemoved: { ChildCache newCache; ChildCache::ConstIterator iter = childToId.constBegin(); while (iter != childToId.constEnd()) { QAccessible::Id id = iter.value(); QAccessibleInterface* iface = QAccessible::accessibleInterface(id); Q_ASSERT(iface); if (iface->role() == QAccessible::Cell || iface->role() == QAccessible::ListItem) { Q_ASSERT(iface->tableCellInterface()); AccessibleInstanceViewItem* cell = static_cast<AccessibleInstanceViewItem*>(iface->tableCellInterface()); // Since it is a QPersistentModelIndex, we only need to check if it is valid if (cell->m_index.isValid()) newCache.insert(indexOfChild(cell), id); else QAccessible::deleteAccessibleInterface(id); } ++iter; } childToId = newCache; break; } case QAccessibleTableModelChangeEvent::DataChanged: // nothing to do in this case break; } } // TABLE CELL AccessibleInstanceViewItem::AccessibleInstanceViewItem(QAbstractItemView* view_, const QModelIndex& index_) : view(view_), m_index(index_) { if (Q_UNLIKELY(!index_.isValid())) qWarning() << "AccessibleInstanceViewItem::AccessibleInstanceViewItem with invalid index: " << index_; } void* AccessibleInstanceViewItem::interface_cast(QAccessible::InterfaceType t) { if (t == QAccessible::TableCellInterface) return static_cast<QAccessibleTableCellInterface*>(this); if (t == QAccessible::ActionInterface) return static_cast<QAccessibleActionInterface*>(this); return 0; } int AccessibleInstanceViewItem::columnExtent() const { return 1; } int AccessibleInstanceViewItem::rowExtent() const { return 1; } QList<QAccessibleInterface*> AccessibleInstanceViewItem::rowHeaderCells() const { return {}; } QList<QAccessibleInterface*> AccessibleInstanceViewItem::columnHeaderCells() const { return {}; } int AccessibleInstanceViewItem::columnIndex() const { if (!isValid()) { return -1; } return m_index.column(); } int AccessibleInstanceViewItem::rowIndex() const { if (!isValid()) { return -1; } return m_index.row(); } bool AccessibleInstanceViewItem::isSelected() const { if (!isValid()) { return false; } return view->selectionModel()->isSelected(m_index); } QStringList AccessibleInstanceViewItem::actionNames() const { QStringList names; names << toggleAction(); return names; } void AccessibleInstanceViewItem::doAction(const QString& actionName) { if (actionName == toggleAction()) { if (isSelected()) { unselectCell(); } else { selectCell(); } } } QStringList AccessibleInstanceViewItem::keyBindingsForAction(const QString&) const { return QStringList(); } void AccessibleInstanceViewItem::selectCell() { if (!isValid()) { return; } QAbstractItemView::SelectionMode selectionMode = view->selectionMode(); if (selectionMode == QAbstractItemView::NoSelection) { return; } Q_ASSERT(table()); QAccessibleTableInterface* cellTable = table()->tableInterface(); switch (view->selectionBehavior()) { case QAbstractItemView::SelectItems: break; case QAbstractItemView::SelectColumns: if (cellTable) cellTable->selectColumn(m_index.column()); return; case QAbstractItemView::SelectRows: if (cellTable) cellTable->selectRow(m_index.row()); return; } if (selectionMode == QAbstractItemView::SingleSelection) { view->clearSelection(); } view->selectionModel()->select(m_index, QItemSelectionModel::Select); } void AccessibleInstanceViewItem::unselectCell() { if (!isValid()) return; QAbstractItemView::SelectionMode selectionMode = view->selectionMode(); if (selectionMode == QAbstractItemView::NoSelection) return; QAccessibleTableInterface* cellTable = table()->tableInterface(); switch (view->selectionBehavior()) { case QAbstractItemView::SelectItems: break; case QAbstractItemView::SelectColumns: if (cellTable) cellTable->unselectColumn(m_index.column()); return; case QAbstractItemView::SelectRows: if (cellTable) cellTable->unselectRow(m_index.row()); return; } // If the mode is not MultiSelection or ExtendedSelection and only // one cell is selected it cannot be unselected by the user if ((selectionMode != QAbstractItemView::MultiSelection) && (selectionMode != QAbstractItemView::ExtendedSelection) && (view->selectionModel()->selectedIndexes().count() <= 1)) return; view->selectionModel()->select(m_index, QItemSelectionModel::Deselect); } QAccessibleInterface* AccessibleInstanceViewItem::table() const { return QAccessible::queryAccessibleInterface(view); } QAccessible::Role AccessibleInstanceViewItem::role() const { return QAccessible::ListItem; } QAccessible::State AccessibleInstanceViewItem::state() const { QAccessible::State st; if (!isValid()) return st; QRect globalRect = view->rect(); globalRect.translate(view->mapToGlobal(QPoint(0, 0))); if (!globalRect.intersects(rect())) st.invisible = true; if (view->selectionModel()->isSelected(m_index)) st.selected = true; if (view->selectionModel()->currentIndex() == m_index) st.focused = true; if (m_index.model()->data(m_index, Qt::CheckStateRole).toInt() == Qt::Checked) st.checked = true; Qt::ItemFlags flags = m_index.flags(); if (flags & Qt::ItemIsSelectable) { st.selectable = true; st.focusable = true; if (view->selectionMode() == QAbstractItemView::MultiSelection) st.multiSelectable = true; if (view->selectionMode() == QAbstractItemView::ExtendedSelection) st.extSelectable = true; } return st; } QRect AccessibleInstanceViewItem::rect() const { QRect r; if (!isValid()) return r; r = view->visualRect(m_index); if (!r.isNull()) { r.translate(view->viewport()->mapTo(view, QPoint(0, 0))); r.translate(view->mapToGlobal(QPoint(0, 0))); } return r; } QString AccessibleInstanceViewItem::text(QAccessible::Text t) const { QString value; if (!isValid()) return value; QAbstractItemModel* model = view->model(); switch (t) { case QAccessible::Name: value = model->data(m_index, Qt::AccessibleTextRole).toString(); if (value.isEmpty()) value = model->data(m_index, Qt::DisplayRole).toString(); break; case QAccessible::Description: value = model->data(m_index, Qt::AccessibleDescriptionRole).toString(); break; default: break; } return value; } void AccessibleInstanceViewItem::setText(QAccessible::Text /*t*/, const QString& text) { if (!isValid() || !(m_index.flags() & Qt::ItemIsEditable)) return; view->model()->setData(m_index, text); } bool AccessibleInstanceViewItem::isValid() const { return view && view->model() && m_index.isValid(); } QAccessibleInterface* AccessibleInstanceViewItem::parent() const { return QAccessible::queryAccessibleInterface(view); } QAccessibleInterface* AccessibleInstanceViewItem::child(int) const { return 0; } #endif /* !QT_NO_ACCESSIBILITY */
23,043
C++
.cpp
661
28.18003
138
0.643383
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,084
InstanceDelegate.cpp
PrismLauncher_PrismLauncher/launcher/ui/instanceview/InstanceDelegate.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "InstanceDelegate.h" #include <QApplication> #include <QDebug> #include <QPainter> #include <QTextLayout> #include <QTextOption> #include <QtMath> #include <QIcon> #include <QTextEdit> #include "BaseInstance.h" #include "InstanceList.h" #include "InstanceView.h" // Origin: Qt static void viewItemTextLayout(QTextLayout& textLayout, int lineWidth, qreal& height, qreal& widthUsed) { height = 0; widthUsed = 0; textLayout.beginLayout(); QString str = textLayout.text(); while (true) { QTextLine line = textLayout.createLine(); if (!line.isValid()) break; if (line.textLength() == 0) break; line.setLineWidth(lineWidth); line.setPosition(QPointF(0, height)); height += line.height(); widthUsed = qMax(widthUsed, line.naturalTextWidth()); } textLayout.endLayout(); } ListViewDelegate::ListViewDelegate(QObject* parent) : QStyledItemDelegate(parent) {} void drawSelectionRect(QPainter* painter, const QStyleOptionViewItem& option, const QRect& rect) { if ((option.state & QStyle::State_Selected)) painter->fillRect(rect, option.palette.brush(QPalette::Highlight)); else { QColor backgroundColor = option.palette.color(QPalette::Window); backgroundColor.setAlpha(160); painter->fillRect(rect, QBrush(backgroundColor)); } } void drawFocusRect(QPainter* painter, const QStyleOptionViewItem& option, const QRect& rect) { if (!(option.state & QStyle::State_HasFocus)) return; QStyleOptionFocusRect opt; opt.direction = option.direction; opt.fontMetrics = option.fontMetrics; opt.palette = option.palette; opt.rect = rect; // opt.state = option.state | QStyle::State_KeyboardFocusChange | // QStyle::State_Item; auto col = option.state & QStyle::State_Selected ? QPalette::Highlight : QPalette::Base; opt.backgroundColor = option.palette.color(col); // Apparently some widget styles expect this hint to not be set painter->setRenderHint(QPainter::Antialiasing, false); QStyle* style = option.widget ? option.widget->style() : QApplication::style(); style->drawPrimitive(QStyle::PE_FrameFocusRect, &opt, painter, option.widget); painter->setRenderHint(QPainter::Antialiasing); } // TODO this can be made a lot prettier void drawProgressOverlay(QPainter* painter, const QStyleOptionViewItem& option, const int value, const int maximum) { if (maximum == 0 || value == maximum) { return; } painter->save(); qreal percent = (qreal)value / (qreal)maximum; QColor color = option.palette.color(QPalette::Dark); color.setAlphaF(0.70f); painter->setBrush(color); painter->setPen(QPen(QBrush(), 0)); painter->drawPie(option.rect, 90 * 16, -percent * 360 * 16); painter->restore(); } void drawBadges(QPainter* painter, const QStyleOptionViewItem& option, BaseInstance* instance, QIcon::Mode mode, QIcon::State state) { QList<QString> pixmaps; if (instance->isRunning()) { pixmaps.append("status-running"); } else if (instance->hasCrashed() || instance->hasVersionBroken()) { pixmaps.append("status-bad"); } if (instance->hasUpdateAvailable()) { pixmaps.append("checkupdate"); } static const int itemSide = 24; static const int spacing = 1; const int itemsPerRow = qMax(1, qFloor(double(option.rect.width() + spacing) / double(itemSide + spacing))); const int rows = qCeil((double)pixmaps.size() / (double)itemsPerRow); QListIterator<QString> it(pixmaps); painter->translate(option.rect.topLeft()); for (int y = 0; y < rows; ++y) { for (int x = 0; x < itemsPerRow; ++x) { if (!it.hasNext()) { return; } // FIXME: inject this. auto icon = QIcon::fromTheme(it.next()); // opt.icon.paint(painter, iconbox, Qt::AlignCenter, mode, state); const QPixmap pixmap; // itemSide QRect badgeRect(option.rect.width() - x * itemSide + qMax(x - 1, 0) * spacing - itemSide, y * itemSide + qMax(y - 1, 0) * spacing, itemSide, itemSide); icon.paint(painter, badgeRect, Qt::AlignCenter, mode, state); } } painter->translate(-option.rect.topLeft()); } static QSize viewItemTextSize(const QStyleOptionViewItem* option) { QStyle* style = option->widget ? option->widget->style() : QApplication::style(); QTextOption textOption; textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); QTextLayout textLayout; textLayout.setTextOption(textOption); textLayout.setFont(option->font); textLayout.setText(option->text); const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, option, option->widget) + 1; QRect bounds(0, 0, 100 - 2 * textMargin, 600); qreal height = 0, widthUsed = 0; viewItemTextLayout(textLayout, bounds.width(), height, widthUsed); const QSize size(qCeil(widthUsed), qCeil(height)); return QSize(size.width() + 2 * textMargin, size.height()); } void ListViewDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); painter->save(); painter->setClipRect(opt.rect); opt.features |= QStyleOptionViewItem::WrapText; opt.text = index.data().toString(); opt.textElideMode = Qt::ElideRight; opt.displayAlignment = Qt::AlignTop | Qt::AlignHCenter; QStyle* style = opt.widget ? opt.widget->style() : QApplication::style(); // const int iconSize = style->pixelMetric(QStyle::PM_IconViewIconSize); const int iconSize = 48; QRect iconbox = opt.rect; const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, 0, opt.widget) + 1; QRect textRect = opt.rect; QRect textHighlightRect = textRect; // clip the decoration on top, remove width padding textRect.adjust(textMargin, iconSize + textMargin + 5, -textMargin, 0); textHighlightRect.adjust(0, iconSize + 5, 0, 0); // draw background { // FIXME: unused // QSize textSize = viewItemTextSize ( &opt ); drawSelectionRect(painter, opt, textHighlightRect); /* QPalette::ColorGroup cg; QStyleOptionViewItem opt2(opt); if ((opt.widget && opt.widget->isEnabled()) || (opt.state & QStyle::State_Enabled)) { if (!(opt.state & QStyle::State_Active)) cg = QPalette::Inactive; else cg = QPalette::Normal; } else { cg = QPalette::Disabled; } */ /* opt2.palette.setCurrentColorGroup(cg); // fill in background, if any if (opt.backgroundBrush.style() != Qt::NoBrush) { QPointF oldBO = painter->brushOrigin(); painter->setBrushOrigin(opt.rect.topLeft()); painter->fillRect(opt.rect, opt.backgroundBrush); painter->setBrushOrigin(oldBO); } drawSelectionRect(painter, opt2, textHighlightRect); */ /* if (opt.showDecorationSelected) { drawSelectionRect(painter, opt2, opt.rect); drawFocusRect(painter, opt2, opt.rect); // painter->fillRect ( opt.rect, opt.palette.brush ( cg, QPalette::Highlight ) ); } else { // if ( opt.state & QStyle::State_Selected ) { // QRect textRect = subElementRect ( QStyle::SE_ItemViewItemText, opt, // opt.widget ); // painter->fillRect ( textHighlightRect, opt.palette.brush ( cg, // QPalette::Highlight ) ); drawSelectionRect(painter, opt2, textHighlightRect); drawFocusRect(painter, opt2, textHighlightRect); } } */ } // icon mode and state, also used for badges QIcon::Mode mode = QIcon::Normal; if (!(opt.state & QStyle::State_Enabled)) mode = QIcon::Disabled; else if (opt.state & QStyle::State_Selected) mode = QIcon::Selected; QIcon::State state = opt.state & QStyle::State_Open ? QIcon::On : QIcon::Off; // draw the icon { iconbox.setHeight(iconSize); opt.icon.paint(painter, iconbox, Qt::AlignCenter, mode, state); } // set the text colors QPalette::ColorGroup cg = opt.state & QStyle::State_Enabled ? QPalette::Normal : QPalette::Disabled; if (cg == QPalette::Normal && !(opt.state & QStyle::State_Active)) cg = QPalette::Inactive; if (opt.state & QStyle::State_Selected) { painter->setPen(opt.palette.color(cg, QPalette::HighlightedText)); } else { painter->setPen(opt.palette.color(cg, QPalette::Text)); } // draw the text QTextOption textOption; textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); textOption.setTextDirection(opt.direction); textOption.setAlignment(QStyle::visualAlignment(opt.direction, opt.displayAlignment)); QTextLayout textLayout; textLayout.setTextOption(textOption); textLayout.setFont(opt.font); textLayout.setText(opt.text); qreal width, height; viewItemTextLayout(textLayout, textRect.width(), height, width); const int lineCount = textLayout.lineCount(); const QRect layoutRect = QStyle::alignedRect(opt.direction, opt.displayAlignment, QSize(textRect.width(), int(height)), textRect); const QPointF position = layoutRect.topLeft(); for (int i = 0; i < lineCount; ++i) { const QTextLine line = textLayout.lineAt(i); line.draw(painter, position); } // FIXME: this really has no business of being here. Make generic. auto instance = (BaseInstance*)index.data(InstanceList::InstancePointerRole).value<void*>(); if (instance) { drawBadges(painter, opt, instance, mode, state); } drawProgressOverlay(painter, opt, index.data(InstanceViewRoles::ProgressValueRole).toInt(), index.data(InstanceViewRoles::ProgressMaximumRole).toInt()); painter->restore(); } QSize ListViewDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { QStyleOptionViewItem opt = option; initStyleOption(&opt, index); opt.features |= QStyleOptionViewItem::WrapText; opt.text = index.data().toString(); opt.textElideMode = Qt::ElideRight; opt.displayAlignment = Qt::AlignTop | Qt::AlignHCenter; QStyle* style = opt.widget ? opt.widget->style() : QApplication::style(); const int textMargin = style->pixelMetric(QStyle::PM_FocusFrameHMargin, &option, opt.widget) + 1; int height = 48 + textMargin * 2 + 5; // TODO: turn constants into variables QSize szz = viewItemTextSize(&opt); height += szz.height(); // FIXME: maybe the icon items could scale and keep proportions? QSize sz(100, height); return sz; } class NoReturnTextEdit : public QTextEdit { Q_OBJECT public: explicit NoReturnTextEdit(QWidget* parent) : QTextEdit(parent) { setTextInteractionFlags(Qt::TextEditorInteraction); setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff); } bool event(QEvent* event) override { auto eventType = event->type(); if (eventType == QEvent::KeyPress || eventType == QEvent::KeyRelease) { QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event); auto key = keyEvent->key(); if ((key == Qt::Key_Return || key == Qt::Key_Enter) && eventType == QEvent::KeyPress) { emit editingDone(); return true; } if (key == Qt::Key_Tab) { return true; } } return QTextEdit::event(event); } signals: void editingDone(); }; void ListViewDelegate::updateEditorGeometry(QWidget* editor, const QStyleOptionViewItem& option, [[maybe_unused]] const QModelIndex& index) const { const int iconSize = 48; QRect textRect = option.rect; // QStyle *style = option.widget ? option.widget->style() : QApplication::style(); textRect.adjust(0, iconSize + 5, 0, 0); editor->setGeometry(textRect); } void ListViewDelegate::setEditorData(QWidget* editor, const QModelIndex& index) const { auto text = index.data(Qt::EditRole).toString(); QTextEdit* realEditor = qobject_cast<NoReturnTextEdit*>(editor); realEditor->setAlignment(Qt::AlignHCenter | Qt::AlignTop); realEditor->append(text); realEditor->selectAll(); realEditor->document()->clearUndoRedoStacks(); } void ListViewDelegate::setModelData(QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const { QTextEdit* realEditor = qobject_cast<NoReturnTextEdit*>(editor); QString text = realEditor->toPlainText(); text.replace(QChar('\n'), QChar(' ')); text = text.trimmed(); // Prevent instance names longer than 128 chars text.truncate(128); if (text.size() != 0) { model->setData(index, text); } } QWidget* ListViewDelegate::createEditor(QWidget* parent, [[maybe_unused]] const QStyleOptionViewItem& option, [[maybe_unused]] const QModelIndex& index) const { auto editor = new NoReturnTextEdit(parent); connect(editor, &NoReturnTextEdit::editingDone, this, &ListViewDelegate::editingDone); return editor; } void ListViewDelegate::editingDone() { NoReturnTextEdit* editor = qobject_cast<NoReturnTextEdit*>(sender()); emit commitData(editor); emit closeEditor(editor); } #include "InstanceDelegate.moc"
15,464
C++
.cpp
373
34.975871
134
0.666512
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,085
VisualGroup.cpp
PrismLauncher_PrismLauncher/launcher/ui/instanceview/VisualGroup.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net> * Copyright (C) 2023 Tayou <git@tayou.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "VisualGroup.h" #include <QApplication> #include <QDebug> #include <QModelIndex> #include <QPainter> #include <QtMath> #include <utility> #include "InstanceView.h" VisualGroup::VisualGroup(QString text, InstanceView* view) : view(view), text(std::move(text)), collapsed(false) {} VisualGroup::VisualGroup(const VisualGroup* other) : view(other->view), text(other->text), collapsed(other->collapsed) {} void VisualGroup::update() { auto temp_items = items(); auto itemsPerRow = view->itemsPerRow(); int numRows = qMax(1, qCeil((qreal)temp_items.size() / (qreal)itemsPerRow)); rows = QVector<VisualRow>(numRows); int maxRowHeight = 0; int positionInRow = 0; int currentRow = 0; int offsetFromTop = 0; for (auto item : temp_items) { if (positionInRow == itemsPerRow) { rows[currentRow].height = maxRowHeight; rows[currentRow].top = offsetFromTop; currentRow++; if (currentRow >= rows.size()) { currentRow = rows.size() - 1; } offsetFromTop += maxRowHeight + 5; positionInRow = 0; maxRowHeight = 0; } #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) QStyleOptionViewItem viewItemOption; view->initViewItemOption(&viewItemOption); #else QStyleOptionViewItem viewItemOption = view->viewOptions(); #endif auto itemHeight = view->itemDelegate()->sizeHint(viewItemOption, item).height(); if (itemHeight > maxRowHeight) { maxRowHeight = itemHeight; } rows[currentRow].items.append(item); positionInRow++; } rows[currentRow].height = maxRowHeight; rows[currentRow].top = offsetFromTop; } QPair<int, int> VisualGroup::positionOf(const QModelIndex& index) const { int y = 0; for (auto& row : rows) { for (auto x = 0; x < row.items.size(); x++) { if (row.items[x] == index) { return qMakePair(x, y); } } y++; } qWarning() << "Item" << index.row() << index.data(Qt::DisplayRole).toString() << "not found in visual group" << text; return qMakePair(0, 0); } int VisualGroup::rowTopOf(const QModelIndex& index) const { auto position = positionOf(index); return rows[position.second].top; } int VisualGroup::rowHeightOf(const QModelIndex& index) const { auto position = positionOf(index); return rows[position.second].height; } VisualGroup::HitResults VisualGroup::hitScan(const QPoint& pos) const { VisualGroup::HitResults results = VisualGroup::NoHit; int y_start = verticalPosition(); int body_start = y_start + headerHeight(); int body_end = body_start + contentHeight(); int y = pos.y(); // int x = pos.x(); if (y < y_start) { results = VisualGroup::NoHit; } else if (y < body_start) { results = VisualGroup::HeaderHit; int collapseSize = headerHeight() - 4; // the icon QRect iconRect = QRect(view->m_leftMargin + 2, 2 + y_start, view->width() - 4, collapseSize); if (iconRect.contains(pos)) { results |= VisualGroup::CheckboxHit; } } else if (y < body_end) { results |= VisualGroup::BodyHit; } return results; } void VisualGroup::drawHeader(QPainter* painter, const QStyleOptionViewItem& option) const { QRect optRect = option.rect; optRect.setTop(optRect.top() + 7); QFont font(QApplication::font()); font.setBold(true); const QFontMetrics fontMetrics = QFontMetrics(font); painter->setFont(font); QPen pen; pen.setWidth(2); QColor penColor = option.palette.text().color(); penColor.setAlphaF(0.6); pen.setColor(penColor); painter->setPen(pen); painter->setRenderHint(QPainter::Antialiasing); // sizes and offsets, to keep things consistent below const int arrowOffsetLeft = fontMetrics.height() / 2 + 7; const int textOffsetLeft = arrowOffsetLeft * 2; const int centerHeight = optRect.top() + fontMetrics.height() / 2; const QString& textToDraw = text.isEmpty() ? QObject::tr("Ungrouped") : text; // BEGIN: arrow { constexpr int arrowSize = 6; QPolygon arrowPolygon; if (collapsed) { arrowPolygon << QPoint(arrowOffsetLeft - arrowSize / 2, centerHeight - arrowSize) << QPoint(arrowOffsetLeft + arrowSize / 2, centerHeight) << QPoint(arrowOffsetLeft - arrowSize / 2, centerHeight + arrowSize); painter->drawPolyline(arrowPolygon); } else { arrowPolygon << QPoint(arrowOffsetLeft - arrowSize, centerHeight - arrowSize / 2) << QPoint(arrowOffsetLeft, centerHeight + arrowSize / 2) << QPoint(arrowOffsetLeft + arrowSize, centerHeight - arrowSize / 2); painter->drawPolyline(arrowPolygon); } } // END: arrow // BEGIN: text { QRect textRect(optRect); textRect.setTop(textRect.top()); textRect.setLeft(textOffsetLeft); textRect.setHeight(fontMetrics.height()); textRect.setRight(textRect.right() - 7); painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, textToDraw); } // END: text // BEGIN: horizontal line { penColor.setAlphaF(0.05); pen.setColor(penColor); painter->setPen(pen); // startPoint is left + arrow + text + space const int startPoint = optRect.left() + fontMetrics.height() + fontMetrics.size(Qt::AlignLeft | Qt::AlignVCenter, textToDraw).width() + 20; painter->setRenderHint(QPainter::Antialiasing, false); QPolygon polygon; // for some reason the height (yPos) doesn't look centered, so we are adding 1 to the center height const int lineHeight = centerHeight + 1; polygon << QPoint(startPoint, lineHeight) << QPoint(optRect.right() - 3, lineHeight); painter->drawPolyline(polygon); } // END: horizontal line } int VisualGroup::totalHeight() const { return headerHeight() + contentHeight(); } int VisualGroup::headerHeight() { QFont font(QApplication::font()); font.setBold(true); QFontMetrics fontMetrics(font); const int height = fontMetrics.height() + 1 /* 1 pixel-width gradient */ + 11 /* top and bottom separation */; return height; /* int raw = view->viewport()->fontMetrics().height() + 4; // add english. maybe. depends on font height. if (raw % 2 == 0) raw++; return std::min(raw, 25); */ } int VisualGroup::contentHeight() const { if (collapsed) { return 0; } auto last = rows[numRows() - 1]; return last.top + last.height; } int VisualGroup::numRows() const { return (int)rows.size(); } int VisualGroup::verticalPosition() const { return m_verticalPosition; } QList<QModelIndex> VisualGroup::items() const { QList<QModelIndex> indices; for (int i = 0; i < view->model()->rowCount(); ++i) { const QModelIndex index = view->model()->index(i, 0); if (index.data(InstanceViewRoles::GroupRole).toString() == text) { indices.append(index); } } return indices; }
8,838
C++
.cpp
241
30.892116
128
0.652935
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,086
InstallJavaDialog.cpp
PrismLauncher_PrismLauncher/launcher/ui/java/InstallJavaDialog.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2024 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "InstallJavaDialog.h" #include <QCheckBox> #include <QDialogButtonBox> #include <QMessageBox> #include <QPushButton> #include <QVBoxLayout> #include <QWidget> #include "Application.h" #include "BaseVersionList.h" #include "FileSystem.h" #include "Filter.h" #include "java/download/ArchiveDownloadTask.h" #include "java/download/ManifestDownloadTask.h" #include "java/download/SymlinkTask.h" #include "meta/Index.h" #include "meta/VersionList.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "tasks/SequentialTask.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/dialogs/ProgressDialog.h" #include "ui/java/VersionList.h" #include "ui/widgets/PageContainer.h" #include "ui/widgets/VersionSelectWidget.h" class InstallJavaPage : public QWidget, public BasePage { public: Q_OBJECT public: explicit InstallJavaPage(const QString& id, const QString& iconName, const QString& name, QWidget* parent = nullptr) : QWidget(parent), uid(id), iconName(iconName), name(name) { setObjectName(QStringLiteral("VersionSelectWidget")); horizontalLayout = new QHBoxLayout(this); horizontalLayout->setObjectName(QStringLiteral("horizontalLayout")); horizontalLayout->setContentsMargins(0, 0, 0, 0); majorVersionSelect = new VersionSelectWidget(this); majorVersionSelect->selectCurrent(); majorVersionSelect->setEmptyString(tr("No Java versions are currently available in the meta.")); majorVersionSelect->setEmptyErrorString(tr("Couldn't load or download the Java version lists!")); horizontalLayout->addWidget(majorVersionSelect, 1); javaVersionSelect = new VersionSelectWidget(this); javaVersionSelect->setEmptyString(tr("No Java versions are currently available for your OS.")); javaVersionSelect->setEmptyErrorString(tr("Couldn't load or download the Java version lists!")); horizontalLayout->addWidget(javaVersionSelect, 4); connect(majorVersionSelect, &VersionSelectWidget::selectedVersionChanged, this, &InstallJavaPage::setSelectedVersion); connect(majorVersionSelect, &VersionSelectWidget::selectedVersionChanged, this, &InstallJavaPage::selectionChanged); connect(javaVersionSelect, &VersionSelectWidget::selectedVersionChanged, this, &InstallJavaPage::selectionChanged); QMetaObject::connectSlotsByName(this); } ~InstallJavaPage() { delete horizontalLayout; delete majorVersionSelect; delete javaVersionSelect; } //! loads the list if needed. void initialize(Meta::VersionList::Ptr vlist) { vlist->setProvidedRoles({ BaseVersionList::JavaMajorRole, BaseVersionList::RecommendedRole, BaseVersionList::VersionPointerRole }); majorVersionSelect->initialize(vlist.get()); } void setSelectedVersion(BaseVersion::Ptr version) { auto dcast = std::dynamic_pointer_cast<Meta::Version>(version); if (!dcast) { return; } javaVersionSelect->initialize(new Java::VersionList(dcast, this)); javaVersionSelect->selectCurrent(); } QString id() const override { return uid; } QString displayName() const override { return name; } QIcon icon() const override { return APPLICATION->getThemedIcon(iconName); } void openedImpl() override { if (loaded) return; const auto versions = APPLICATION->metadataIndex()->get(uid); if (!versions) return; initialize(versions); loaded = true; } void setParentContainer(BasePageContainer* container) override { auto dialog = dynamic_cast<QDialog*>(dynamic_cast<PageContainer*>(container)->parent()); connect(javaVersionSelect->view(), &QAbstractItemView::doubleClicked, dialog, &QDialog::accept); } BaseVersion::Ptr selectedVersion() const { return javaVersionSelect->selectedVersion(); } void selectSearch() { javaVersionSelect->selectSearch(); } void loadList() { majorVersionSelect->loadList(); javaVersionSelect->loadList(); } public slots: void setRecommendedMajors(const QStringList& majors) { m_recommended_majors = majors; recommendedFilterChanged(); } void setRecommend(bool recommend) { m_recommend = recommend; recommendedFilterChanged(); } void recommendedFilterChanged() { if (m_recommend) { majorVersionSelect->setFilter(BaseVersionList::ModelRoles::JavaMajorRole, new ExactListFilter(m_recommended_majors)); } else { majorVersionSelect->setFilter(BaseVersionList::ModelRoles::JavaMajorRole, new ExactListFilter()); } } signals: void selectionChanged(); private: const QString uid; const QString iconName; const QString name; bool loaded = false; QHBoxLayout* horizontalLayout = nullptr; VersionSelectWidget* majorVersionSelect = nullptr; VersionSelectWidget* javaVersionSelect = nullptr; QStringList m_recommended_majors; bool m_recommend; }; static InstallJavaPage* pageCast(BasePage* page) { auto result = dynamic_cast<InstallJavaPage*>(page); Q_ASSERT(result != nullptr); return result; } namespace Java { QStringList getRecommendedJavaVersionsFromVersionList(Meta::VersionList::Ptr list) { QStringList recommendedJavas; for (auto ver : list->versions()) { auto major = ver->version(); if (major.startsWith("java")) { major = "Java " + major.mid(4); } recommendedJavas.append(major); } return recommendedJavas; } InstallDialog::InstallDialog(const QString& uid, BaseInstance* instance, QWidget* parent) : QDialog(parent), container(new PageContainer(this, QString(), this)), buttons(new QDialogButtonBox(this)) { auto layout = new QVBoxLayout(this); container->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding); layout->addWidget(container); auto buttonLayout = new QHBoxLayout(this); auto refreshLayout = new QHBoxLayout(this); auto refreshButton = new QPushButton(tr("&Refresh"), this); connect(refreshButton, &QPushButton::clicked, this, [this] { pageCast(container->selectedPage())->loadList(); }); refreshLayout->addWidget(refreshButton); auto recommendedCheckBox = new QCheckBox("Recommended", this); recommendedCheckBox->setCheckState(Qt::CheckState::Checked); connect(recommendedCheckBox, &QCheckBox::stateChanged, this, [this](int state) { for (BasePage* page : container->getPages()) { pageCast(page)->setRecommend(state == Qt::Checked); } }); refreshLayout->addWidget(recommendedCheckBox); buttonLayout->addLayout(refreshLayout); buttons->setOrientation(Qt::Horizontal); buttons->setStandardButtons(QDialogButtonBox::Cancel | QDialogButtonBox::Ok); buttons->button(QDialogButtonBox::Ok)->setText(tr("Download")); buttons->button(QDialogButtonBox::Cancel)->setText(tr("Cancel")); connect(buttons, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(buttons, &QDialogButtonBox::rejected, this, &QDialog::reject); buttonLayout->addWidget(buttons); layout->addLayout(buttonLayout); setWindowTitle(dialogTitle()); setWindowModality(Qt::WindowModal); resize(840, 480); QStringList recommendedJavas; if (auto mcInst = dynamic_cast<MinecraftInstance*>(instance); mcInst) { auto mc = mcInst->getPackProfile()->getComponent("net.minecraft"); if (mc) { auto file = mc->getVersionFile(); // no need for load as it should already be loaded if (file) { for (auto major : file->compatibleJavaMajors) { recommendedJavas.append(QString("Java %1").arg(major)); } } } } else { const auto versions = APPLICATION->metadataIndex()->get("net.minecraft.java"); if (versions) { if (versions->isLoaded()) { recommendedJavas = getRecommendedJavaVersionsFromVersionList(versions); } else { auto newTask = versions->getLoadTask(); if (newTask) { connect(newTask.get(), &Task::succeeded, this, [this, versions] { auto recommendedJavas = getRecommendedJavaVersionsFromVersionList(versions); for (BasePage* page : container->getPages()) { pageCast(page)->setRecommendedMajors(recommendedJavas); } }); if (!newTask->isRunning()) newTask->start(); } else { recommendedJavas = getRecommendedJavaVersionsFromVersionList(versions); } } } } for (BasePage* page : container->getPages()) { if (page->id() == uid) container->selectPage(page->id()); auto cast = pageCast(page); cast->setRecommend(true); connect(cast, &InstallJavaPage::selectionChanged, this, [this, cast] { validate(cast); }); if (!recommendedJavas.isEmpty()) { cast->setRecommendedMajors(recommendedJavas); } } connect(container, &PageContainer::selectedPageChanged, this, [this](BasePage* previous, BasePage* selected) { validate(selected); }); pageCast(container->selectedPage())->selectSearch(); validate(container->selectedPage()); } QList<BasePage*> InstallDialog::getPages() { return { // Mojang new InstallJavaPage("net.minecraft.java", "mojang", tr("Mojang")), // Adoptium new InstallJavaPage("net.adoptium.java", "adoptium", tr("Adoptium")), // Azul new InstallJavaPage("com.azul.java", "azul", tr("Azul Zulu")), }; } QString InstallDialog::dialogTitle() { return tr("Install Java"); } void InstallDialog::validate(BasePage* selected) { buttons->button(QDialogButtonBox::Ok)->setEnabled(!!std::dynamic_pointer_cast<Java::Metadata>(pageCast(selected)->selectedVersion())); } void InstallDialog::done(int result) { if (result == Accepted) { auto* page = pageCast(container->selectedPage()); if (page->selectedVersion()) { auto meta = std::dynamic_pointer_cast<Java::Metadata>(page->selectedVersion()); if (meta) { Task::Ptr task; auto final_path = FS::PathCombine(APPLICATION->javaPath(), meta->m_name); auto deletePath = [final_path] { FS::deletePath(final_path); }; switch (meta->downloadType) { case Java::DownloadType::Manifest: task = makeShared<ManifestDownloadTask>(meta->url, final_path, meta->checksumType, meta->checksumHash); break; case Java::DownloadType::Archive: task = makeShared<ArchiveDownloadTask>(meta->url, final_path, meta->checksumType, meta->checksumHash); break; case Java::DownloadType::Unknown: QString error = QString(tr("Could not determine Java download type!")); CustomMessageBox::selectable(this, tr("Error"), error, QMessageBox::Warning)->show(); deletePath(); } #if defined(Q_OS_MACOS) auto seq = makeShared<SequentialTask>(tr("Install Java")); seq->addTask(task); seq->addTask(makeShared<Java::SymlinkTask>(final_path)); task = seq; #endif connect(task.get(), &Task::failed, this, [this, &deletePath](QString reason) { QString error = QString("Java download failed: %1").arg(reason); CustomMessageBox::selectable(this, tr("Error"), error, QMessageBox::Warning)->show(); deletePath(); }); connect(task.get(), &Task::aborted, this, deletePath); ProgressDialog pg(this); pg.setSkipButton(true, tr("Abort")); pg.execWithTask(task.get()); } else { return; } } else { return; } } QDialog::done(result); } } // namespace Java #include "InstallJavaDialog.moc"
13,217
C++
.cpp
308
34.935065
139
0.661694
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,087
VersionList.cpp
PrismLauncher_PrismLauncher/launcher/ui/java/VersionList.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2024 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "VersionList.h" #include <memory> #include "BaseVersionList.h" #include "SysInfo.h" #include "java/JavaMetadata.h" #include "meta/VersionList.h" namespace Java { VersionList::VersionList(Meta::Version::Ptr version, QObject* parent) : BaseVersionList(parent), m_version(version) { if (version->isLoaded()) sortVersions(); } Task::Ptr VersionList::getLoadTask() { auto task = m_version->loadTask(Net::Mode::Online); connect(task.get(), &Task::finished, this, &VersionList::sortVersions); return task; } const BaseVersion::Ptr VersionList::at(int i) const { return m_vlist.at(i); } bool VersionList::isLoaded() { return m_version->isLoaded(); } int VersionList::count() const { return m_vlist.count(); } QVariant VersionList::data(const QModelIndex& index, int role) const { if (!index.isValid()) return QVariant(); if (index.row() > count()) return QVariant(); auto version = (m_vlist[index.row()]); switch (role) { case SortRole: return -index.row(); case VersionPointerRole: return QVariant::fromValue(std::dynamic_pointer_cast<BaseVersion>(m_vlist[index.row()])); case VersionIdRole: return version->descriptor(); case VersionRole: return version->version.toString(); case RecommendedRole: return false; // do not recommend any version case JavaNameRole: return version->name(); case JavaMajorRole: { auto major = version->version.toString(); if (major.startsWith("java")) { major = "Java " + major.mid(4); } return major; } case TypeRole: return version->packageType; case Meta::VersionList::TimeRole: return version->releaseTime; default: return QVariant(); } } BaseVersionList::RoleList VersionList::providesRoles() const { return { VersionPointerRole, VersionIdRole, VersionRole, RecommendedRole, JavaNameRole, TypeRole, Meta::VersionList::TimeRole }; } bool sortJavas(BaseVersion::Ptr left, BaseVersion::Ptr right) { auto rleft = std::dynamic_pointer_cast<Java::Metadata>(right); auto rright = std::dynamic_pointer_cast<Java::Metadata>(left); return (*rleft) < (*rright); } void VersionList::sortVersions() { if (!m_version || !m_version->data()) return; QString versionStr = SysInfo::getSupportedJavaArchitecture(); beginResetModel(); auto runtimes = m_version->data()->runtimes; m_vlist = {}; if (!versionStr.isEmpty() && !runtimes.isEmpty()) { std::copy_if(runtimes.begin(), runtimes.end(), std::back_inserter(m_vlist), [versionStr](Java::MetadataPtr val) { return val->runtimeOS == versionStr; }); std::sort(m_vlist.begin(), m_vlist.end(), sortJavas); } else { qWarning() << "No Java versions found for your operating system." << SysInfo::currentSystem() << " " << SysInfo::useQTForArch(); } endResetModel(); } } // namespace Java
3,850
C++
.cpp
110
29.745455
136
0.667562
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,089
EnsureMetadataTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/EnsureMetadataTask.cpp
#include "EnsureMetadataTask.h" #include <MurmurHash2.h> #include <QDebug> #include "Application.h" #include "Json.h" #include "minecraft/mod/Mod.h" #include "minecraft/mod/tasks/LocalResourceUpdateTask.h" #include "modplatform/flame/FlameAPI.h" #include "modplatform/flame/FlameModIndex.h" #include "modplatform/helpers/HashUtils.h" #include "modplatform/modrinth/ModrinthAPI.h" #include "modplatform/modrinth/ModrinthPackIndex.h" static ModrinthAPI modrinth_api; static FlameAPI flame_api; EnsureMetadataTask::EnsureMetadataTask(Resource* resource, QDir dir, ModPlatform::ResourceProvider prov) : Task(), m_index_dir(dir), m_provider(prov), m_hashing_task(nullptr), m_current_task(nullptr) { auto hash_task = createNewHash(resource); if (!hash_task) return; connect(hash_task.get(), &Hashing::Hasher::resultsReady, [this, resource](QString hash) { m_resources.insert(hash, resource); }); connect(hash_task.get(), &Task::failed, [this, resource] { emitFail(resource, "", RemoveFromList::No); }); hash_task->start(); } EnsureMetadataTask::EnsureMetadataTask(QList<Resource*>& resources, QDir dir, ModPlatform::ResourceProvider prov) : Task(), m_index_dir(dir), m_provider(prov), m_current_task(nullptr) { m_hashing_task.reset(new ConcurrentTask("MakeHashesTask", APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt())); for (auto* resource : resources) { auto hash_task = createNewHash(resource); if (!hash_task) continue; connect(hash_task.get(), &Hashing::Hasher::resultsReady, [this, resource](QString hash) { m_resources.insert(hash, resource); }); connect(hash_task.get(), &Task::failed, [this, resource] { emitFail(resource, "", RemoveFromList::No); }); m_hashing_task->addTask(hash_task); } } EnsureMetadataTask::EnsureMetadataTask(QHash<QString, Resource*>& resources, QDir dir, ModPlatform::ResourceProvider prov) : Task(), m_resources(resources), m_index_dir(dir), m_provider(prov), m_current_task(nullptr) {} Hashing::Hasher::Ptr EnsureMetadataTask::createNewHash(Resource* resource) { if (!resource || !resource->valid() || resource->type() == ResourceType::FOLDER) return nullptr; return Hashing::createHasher(resource->fileinfo().absoluteFilePath(), m_provider); } QString EnsureMetadataTask::getExistingHash(Resource* resource) { // Check for already computed hashes // (linear on the number of mods vs. linear on the size of the mod's JAR) auto it = m_resources.keyValueBegin(); while (it != m_resources.keyValueEnd()) { if ((*it).second == resource) break; it++; } // We already have the hash computed if (it != m_resources.keyValueEnd()) { return (*it).first; } // No existing hash return {}; } bool EnsureMetadataTask::abort() { // Prevent sending signals to a dead object disconnect(this, 0, 0, 0); if (m_current_task) return m_current_task->abort(); return true; } void EnsureMetadataTask::executeTask() { setStatus(tr("Checking if resources have metadata...")); for (auto* resource : m_resources) { if (!resource->valid()) { qDebug() << "Resource" << resource->name() << "is invalid!"; emitFail(resource); continue; } // They already have the right metadata :o if (resource->status() != ResourceStatus::NO_METADATA && resource->metadata() && resource->metadata()->provider == m_provider) { qDebug() << "Resource" << resource->name() << "already has metadata!"; emitReady(resource); continue; } // Folders don't have metadata if (resource->type() == ResourceType::FOLDER) { emitReady(resource); } } Task::Ptr version_task; switch (m_provider) { case (ModPlatform::ResourceProvider::MODRINTH): version_task = modrinthVersionsTask(); break; case (ModPlatform::ResourceProvider::FLAME): version_task = flameVersionsTask(); break; } auto invalidade_leftover = [this] { for (auto resource = m_resources.constBegin(); resource != m_resources.constEnd(); resource++) emitFail(resource.value(), resource.key(), RemoveFromList::No); m_resources.clear(); emitSucceeded(); }; connect(version_task.get(), &Task::finished, this, [this, invalidade_leftover] { Task::Ptr project_task; switch (m_provider) { case (ModPlatform::ResourceProvider::MODRINTH): project_task = modrinthProjectsTask(); break; case (ModPlatform::ResourceProvider::FLAME): project_task = flameProjectsTask(); break; } if (!project_task) { invalidade_leftover(); return; } connect(project_task.get(), &Task::finished, this, [this, invalidade_leftover, project_task] { invalidade_leftover(); project_task->deleteLater(); if (m_current_task) m_current_task.reset(); }); connect(project_task.get(), &Task::failed, this, &EnsureMetadataTask::emitFailed); m_current_task = project_task; project_task->start(); }); connect(version_task.get(), &Task::finished, [this, version_task] { version_task->deleteLater(); if (m_current_task) m_current_task.reset(); }); if (m_resources.size() > 1) setStatus(tr("Requesting metadata information from %1...").arg(ModPlatform::ProviderCapabilities::readableName(m_provider))); else if (!m_resources.empty()) setStatus(tr("Requesting metadata information from %1 for '%2'...") .arg(ModPlatform::ProviderCapabilities::readableName(m_provider), m_resources.begin().value()->name())); m_current_task = version_task; version_task->start(); } void EnsureMetadataTask::emitReady(Resource* resource, QString key, RemoveFromList remove) { if (!resource) { qCritical() << "Tried to mark a null resource as ready."; if (!key.isEmpty()) m_resources.remove(key); return; } qDebug() << QString("Generated metadata for %1").arg(resource->name()); emit metadataReady(resource); if (remove == RemoveFromList::Yes) { if (key.isEmpty()) key = getExistingHash(resource); m_resources.remove(key); } } void EnsureMetadataTask::emitFail(Resource* resource, QString key, RemoveFromList remove) { if (!resource) { qCritical() << "Tried to mark a null resource as failed."; if (!key.isEmpty()) m_resources.remove(key); return; } qDebug() << QString("Failed to generate metadata for %1").arg(resource->name()); emit metadataFailed(resource); if (remove == RemoveFromList::Yes) { if (key.isEmpty()) key = getExistingHash(resource); m_resources.remove(key); } } // Modrinth Task::Ptr EnsureMetadataTask::modrinthVersionsTask() { auto hash_type = ModPlatform::ProviderCapabilities::hashType(ModPlatform::ResourceProvider::MODRINTH).first(); auto response = std::make_shared<QByteArray>(); auto ver_task = modrinth_api.currentVersions(m_resources.keys(), hash_type, response); // Prevents unfortunate timings when aborting the task if (!ver_task) return Task::Ptr{ nullptr }; connect(ver_task.get(), &Task::succeeded, this, [this, response] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Modrinth::CurrentVersions at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; failed(parse_error.errorString()); return; } try { auto entries = Json::requireObject(doc); for (auto& hash : m_resources.keys()) { auto resource = m_resources.find(hash).value(); try { auto entry = Json::requireObject(entries, hash); setStatus(tr("Parsing API response from Modrinth for '%1'...").arg(resource->name())); qDebug() << "Getting version for" << resource->name() << "from Modrinth"; m_temp_versions.insert(hash, Modrinth::loadIndexedPackVersion(entry)); } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << entries; emitFail(resource); } } } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << doc; } }); return ver_task; } Task::Ptr EnsureMetadataTask::modrinthProjectsTask() { QHash<QString, QString> addonIds; for (auto const& data : m_temp_versions) addonIds.insert(data.addonId.toString(), data.hash); auto response = std::make_shared<QByteArray>(); Task::Ptr proj_task; if (addonIds.isEmpty()) { qWarning() << "No addonId found!"; } else if (addonIds.size() == 1) { proj_task = modrinth_api.getProject(*addonIds.keyBegin(), response); } else { proj_task = modrinth_api.getProjects(addonIds.keys(), response); } // Prevents unfortunate timings when aborting the task if (!proj_task) return Task::Ptr{ nullptr }; connect(proj_task.get(), &Task::succeeded, this, [this, response, addonIds] { QJsonParseError parse_error{}; auto doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Modrinth projects task at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } QJsonArray entries; try { if (addonIds.size() == 1) entries = { doc.object() }; else entries = Json::requireArray(doc); } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << doc; } for (auto entry : entries) { ModPlatform::IndexedPack pack; try { auto entry_obj = Json::requireObject(entry); Modrinth::loadIndexedPack(pack, entry_obj); } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << doc; // Skip this entry, since it has problems continue; } auto hash = addonIds.find(pack.addonId.toString()).value(); auto resource_iter = m_resources.find(hash); if (resource_iter == m_resources.end()) { qWarning() << "Invalid project id from the API response."; continue; } auto* resource = resource_iter.value(); try { setStatus(tr("Parsing API response from Modrinth for '%1'...").arg(resource->name())); modrinthCallback(pack, m_temp_versions.find(hash).value(), resource); } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << entries; emitFail(resource); } } }); return proj_task; } // Flame Task::Ptr EnsureMetadataTask::flameVersionsTask() { auto response = std::make_shared<QByteArray>(); QList<uint> fingerprints; for (auto& murmur : m_resources.keys()) { fingerprints.push_back(murmur.toUInt()); } auto ver_task = flame_api.matchFingerprints(fingerprints, response); connect(ver_task.get(), &Task::succeeded, this, [this, response] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Modrinth::CurrentVersions at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; failed(parse_error.errorString()); return; } try { auto doc_obj = Json::requireObject(doc); auto data_obj = Json::requireObject(doc_obj, "data"); auto data_arr = Json::requireArray(data_obj, "exactMatches"); if (data_arr.isEmpty()) { qWarning() << "No matches found for fingerprint search!"; return; } for (auto match : data_arr) { auto match_obj = Json::ensureObject(match, {}); auto file_obj = Json::ensureObject(match_obj, "file", {}); if (match_obj.isEmpty() || file_obj.isEmpty()) { qWarning() << "Fingerprint match is empty!"; return; } auto fingerprint = QString::number(Json::ensureVariant(file_obj, "fileFingerprint").toUInt()); auto resource = m_resources.find(fingerprint); if (resource == m_resources.end()) { qWarning() << "Invalid fingerprint from the API response."; continue; } setStatus(tr("Parsing API response from CurseForge for '%1'...").arg((*resource)->name())); m_temp_versions.insert(fingerprint, FlameMod::loadIndexedPackVersion(file_obj)); } } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << doc; } }); return ver_task; } Task::Ptr EnsureMetadataTask::flameProjectsTask() { QHash<QString, QString> addonIds; for (auto const& hash : m_resources.keys()) { if (m_temp_versions.contains(hash)) { auto data = m_temp_versions.find(hash).value(); auto id_str = data.addonId.toString(); if (!id_str.isEmpty()) addonIds.insert(data.addonId.toString(), hash); } } auto response = std::make_shared<QByteArray>(); Task::Ptr proj_task; if (addonIds.isEmpty()) { qWarning() << "No addonId found!"; } else if (addonIds.size() == 1) { proj_task = flame_api.getProject(*addonIds.keyBegin(), response); } else { proj_task = flame_api.getProjects(addonIds.keys(), response); } // Prevents unfortunate timings when aborting the task if (!proj_task) return Task::Ptr{ nullptr }; connect(proj_task.get(), &Task::succeeded, this, [this, response, addonIds] { QJsonParseError parse_error{}; auto doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from Modrinth projects task at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } try { QJsonArray entries; if (addonIds.size() == 1) entries = { Json::requireObject(Json::requireObject(doc), "data") }; else entries = Json::requireArray(Json::requireObject(doc), "data"); for (auto entry : entries) { auto entry_obj = Json::requireObject(entry); auto id = QString::number(Json::requireInteger(entry_obj, "id")); auto hash = addonIds.find(id).value(); auto resource = m_resources.find(hash).value(); try { setStatus(tr("Parsing API response from CurseForge for '%1'...").arg(resource->name())); ModPlatform::IndexedPack pack; FlameMod::loadIndexedPack(pack, entry_obj); flameCallback(pack, m_temp_versions.find(hash).value(), resource); } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << entries; emitFail(resource); } } } catch (Json::JsonException& e) { qDebug() << e.cause(); qDebug() << doc; } }); return proj_task; } void EnsureMetadataTask::modrinthCallback(ModPlatform::IndexedPack& pack, ModPlatform::IndexedVersion& ver, Resource* resource) { // Prevent file name mismatch ver.fileName = resource->fileinfo().fileName(); if (ver.fileName.endsWith(".disabled")) ver.fileName.chop(9); QDir tmp_index_dir(m_index_dir); { LocalResourceUpdateTask update_metadata(m_index_dir, pack, ver); QEventLoop loop; QObject::connect(&update_metadata, &Task::finished, &loop, &QEventLoop::quit); update_metadata.start(); if (!update_metadata.isFinished()) loop.exec(); } auto metadata = Metadata::get(tmp_index_dir, pack.slug); if (!metadata.isValid()) { qCritical() << "Failed to generate metadata at last step!"; emitFail(resource); return; } resource->setMetadata(metadata); emitReady(resource); } void EnsureMetadataTask::flameCallback(ModPlatform::IndexedPack& pack, ModPlatform::IndexedVersion& ver, Resource* resource) { try { // Prevent file name mismatch ver.fileName = resource->fileinfo().fileName(); if (ver.fileName.endsWith(".disabled")) ver.fileName.chop(9); QDir tmp_index_dir(m_index_dir); { LocalResourceUpdateTask update_metadata(m_index_dir, pack, ver); QEventLoop loop; QObject::connect(&update_metadata, &Task::finished, &loop, &QEventLoop::quit); update_metadata.start(); if (!update_metadata.isFinished()) loop.exec(); } auto metadata = Metadata::get(tmp_index_dir, pack.slug); if (!metadata.isValid()) { qCritical() << "Failed to generate metadata at last step!"; emitFail(resource); return; } resource->setMetadata(metadata); emitReady(resource); } catch (Json::JsonException& e) { qDebug() << e.cause(); emitFail(resource); } }
18,726
C++
.cpp
446
32.504484
137
0.595056
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,090
ModIndex.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/ModIndex.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "modplatform/ModIndex.h" #include <QCryptographicHash> #include <QDebug> #include <QIODevice> namespace ModPlatform { static const QMap<QString, IndexedVersionType::VersionType> s_indexed_version_type_names = { { "release", IndexedVersionType::VersionType::Release }, { "beta", IndexedVersionType::VersionType::Beta }, { "alpha", IndexedVersionType::VersionType::Alpha } }; IndexedVersionType::IndexedVersionType(const QString& type) : IndexedVersionType(enumFromString(type)) {} IndexedVersionType::IndexedVersionType(const IndexedVersionType::VersionType& type) { m_type = type; } IndexedVersionType::IndexedVersionType(const IndexedVersionType& other) { m_type = other.m_type; } IndexedVersionType& IndexedVersionType::operator=(const IndexedVersionType& other) { m_type = other.m_type; return *this; } const QString IndexedVersionType::toString(const IndexedVersionType::VersionType& type) { return s_indexed_version_type_names.key(type, "unknown"); } IndexedVersionType::VersionType IndexedVersionType::enumFromString(const QString& type) { return s_indexed_version_type_names.value(type, IndexedVersionType::VersionType::Unknown); } const char* ProviderCapabilities::name(ResourceProvider p) { switch (p) { case ResourceProvider::MODRINTH: return "modrinth"; case ResourceProvider::FLAME: return "curseforge"; } return {}; } QString ProviderCapabilities::readableName(ResourceProvider p) { switch (p) { case ResourceProvider::MODRINTH: return "Modrinth"; case ResourceProvider::FLAME: return "CurseForge"; } return {}; } QStringList ProviderCapabilities::hashType(ResourceProvider p) { switch (p) { case ResourceProvider::MODRINTH: return { "sha512", "sha1" }; case ResourceProvider::FLAME: // Try newer formats first, fall back to old format return { "sha1", "md5", "murmur2" }; } return {}; } QString getMetaURL(ResourceProvider provider, QVariant projectID) { return ((provider == ModPlatform::ResourceProvider::FLAME) ? "https://www.curseforge.com/projects/" : "https://modrinth.com/mod/") + projectID.toString(); } auto getModLoaderAsString(ModLoaderType type) -> const QString { switch (type) { case NeoForge: return "neoforge"; case Forge: return "forge"; case Cauldron: return "cauldron"; case LiteLoader: return "liteloader"; case Fabric: return "fabric"; case Quilt: return "quilt"; default: break; } return ""; } auto getModLoaderFromString(QString type) -> ModLoaderType { if (type == "neoforge") return NeoForge; if (type == "forge") return Forge; if (type == "cauldron") return Cauldron; if (type == "liteloader") return LiteLoader; if (type == "fabric") return Fabric; if (type == "quilt") return Quilt; return {}; } } // namespace ModPlatform
3,937
C++
.cpp
123
27.105691
136
0.689755
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,091
ModrinthPackIndex.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/modrinth/ModrinthPackIndex.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ModrinthPackIndex.h" #include "FileSystem.h" #include "ModrinthAPI.h" #include "Json.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "modplatform/ModIndex.h" static ModrinthAPI api; bool shouldDownloadOnSide(QString side) { return side == "required" || side == "optional"; } // https://docs.modrinth.com/api-spec/#tag/projects/operation/getProject void Modrinth::loadIndexedPack(ModPlatform::IndexedPack& pack, QJsonObject& obj) { pack.addonId = Json::ensureString(obj, "project_id"); if (pack.addonId.toString().isEmpty()) pack.addonId = Json::requireString(obj, "id"); pack.provider = ModPlatform::ResourceProvider::MODRINTH; pack.name = Json::requireString(obj, "title"); pack.slug = Json::ensureString(obj, "slug", ""); if (!pack.slug.isEmpty()) pack.websiteUrl = "https://modrinth.com/mod/" + pack.slug; else pack.websiteUrl = ""; pack.description = Json::ensureString(obj, "description", ""); pack.logoUrl = Json::ensureString(obj, "icon_url", ""); pack.logoName = pack.addonId.toString(); ModPlatform::ModpackAuthor modAuthor; modAuthor.name = Json::ensureString(obj, "author", QObject::tr("No author(s)")); modAuthor.url = api.getAuthorURL(modAuthor.name); pack.authors.append(modAuthor); auto client = shouldDownloadOnSide(Json::ensureString(obj, "client_side")); auto server = shouldDownloadOnSide(Json::ensureString(obj, "server_side")); if (server && client) { pack.side = "both"; } else if (server) { pack.side = "server"; } else if (client) { pack.side = "client"; } // Modrinth can have more data than what's provided by the basic search :) pack.extraDataLoaded = false; } void Modrinth::loadExtraPackData(ModPlatform::IndexedPack& pack, QJsonObject& obj) { pack.extraData.issuesUrl = Json::ensureString(obj, "issues_url"); if (pack.extraData.issuesUrl.endsWith('/')) pack.extraData.issuesUrl.chop(1); pack.extraData.sourceUrl = Json::ensureString(obj, "source_url"); if (pack.extraData.sourceUrl.endsWith('/')) pack.extraData.sourceUrl.chop(1); pack.extraData.wikiUrl = Json::ensureString(obj, "wiki_url"); if (pack.extraData.wikiUrl.endsWith('/')) pack.extraData.wikiUrl.chop(1); pack.extraData.discordUrl = Json::ensureString(obj, "discord_url"); if (pack.extraData.discordUrl.endsWith('/')) pack.extraData.discordUrl.chop(1); auto donate_arr = Json::ensureArray(obj, "donation_urls"); for (auto d : donate_arr) { auto d_obj = Json::requireObject(d); ModPlatform::DonationData donate; donate.id = Json::ensureString(d_obj, "id"); donate.platform = Json::ensureString(d_obj, "platform"); donate.url = Json::ensureString(d_obj, "url"); pack.extraData.donate.append(donate); } pack.extraData.status = Json::ensureString(obj, "status"); pack.extraData.body = Json::ensureString(obj, "body").remove("<br>"); pack.extraDataLoaded = true; } void Modrinth::loadIndexedPackVersions(ModPlatform::IndexedPack& pack, QJsonArray& arr, const BaseInstance* inst) { QVector<ModPlatform::IndexedVersion> unsortedVersions; for (auto versionIter : arr) { auto obj = versionIter.toObject(); auto file = loadIndexedPackVersion(obj); if (file.fileId.isValid()) // Heuristic to check if the returned value is valid unsortedVersions.append(file); } auto orderSortPredicate = [](const ModPlatform::IndexedVersion& a, const ModPlatform::IndexedVersion& b) -> bool { // dates are in RFC 3339 format return a.date > b.date; }; std::sort(unsortedVersions.begin(), unsortedVersions.end(), orderSortPredicate); pack.versions = unsortedVersions; pack.versionsLoaded = true; } auto Modrinth::loadIndexedPackVersion(QJsonObject& obj, QString preferred_hash_type, QString preferred_file_name) -> ModPlatform::IndexedVersion { ModPlatform::IndexedVersion file; file.addonId = Json::requireString(obj, "project_id"); file.fileId = Json::requireString(obj, "id"); file.date = Json::requireString(obj, "date_published"); auto versionArray = Json::requireArray(obj, "game_versions"); if (versionArray.empty()) { return {}; } for (auto mcVer : versionArray) { file.mcVersion.append(mcVer.toString()); } auto loaders = Json::requireArray(obj, "loaders"); for (auto loader : loaders) { if (loader == "neoforge") file.loaders |= ModPlatform::NeoForge; else if (loader == "forge") file.loaders |= ModPlatform::Forge; else if (loader == "cauldron") file.loaders |= ModPlatform::Cauldron; else if (loader == "liteloader") file.loaders |= ModPlatform::LiteLoader; else if (loader == "fabric") file.loaders |= ModPlatform::Fabric; else if (loader == "quilt") file.loaders |= ModPlatform::Quilt; } file.version = Json::requireString(obj, "name"); file.version_number = Json::requireString(obj, "version_number"); file.version_type = ModPlatform::IndexedVersionType(Json::requireString(obj, "version_type")); file.changelog = Json::requireString(obj, "changelog"); auto dependencies = Json::ensureArray(obj, "dependencies"); for (auto d : dependencies) { auto dep = Json::ensureObject(d); ModPlatform::Dependency dependency; dependency.addonId = Json::ensureString(dep, "project_id"); dependency.version = Json::ensureString(dep, "version_id"); auto depType = Json::requireString(dep, "dependency_type"); if (depType == "required") dependency.type = ModPlatform::DependencyType::REQUIRED; else if (depType == "optional") dependency.type = ModPlatform::DependencyType::OPTIONAL; else if (depType == "incompatible") dependency.type = ModPlatform::DependencyType::INCOMPATIBLE; else if (depType == "embedded") dependency.type = ModPlatform::DependencyType::EMBEDDED; else dependency.type = ModPlatform::DependencyType::UNKNOWN; file.dependencies.append(dependency); } auto files = Json::requireArray(obj, "files"); int i = 0; if (files.empty()) { // This should not happen normally, but check just in case qWarning() << "Modrinth returned an unexpected empty list of files:" << obj; return {}; } // Find correct file (needed in cases where one version may have multiple files) // Will default to the last one if there's no primary (though I think Modrinth requires that // at least one file is primary, idk) // NOTE: files.count() is 1-indexed, so we need to subtract 1 to become 0-indexed while (i < files.count() - 1) { auto parent = files[i].toObject(); auto fileName = Json::requireString(parent, "filename"); if (!preferred_file_name.isEmpty() && fileName.contains(preferred_file_name)) { file.is_preferred = true; break; } // Grab the primary file, if available if (Json::requireBoolean(parent, "primary")) break; i++; } auto parent = files[i].toObject(); if (parent.contains("url")) { file.downloadUrl = Json::requireString(parent, "url"); file.fileName = Json::requireString(parent, "filename"); file.fileName = FS::RemoveInvalidPathChars(file.fileName); file.is_preferred = Json::requireBoolean(parent, "primary") || (files.count() == 1); auto hash_list = Json::requireObject(parent, "hashes"); if (hash_list.contains(preferred_hash_type)) { file.hash = Json::requireString(hash_list, preferred_hash_type); file.hash_type = preferred_hash_type; } else { auto hash_types = ModPlatform::ProviderCapabilities::hashType(ModPlatform::ResourceProvider::MODRINTH); for (auto& hash_type : hash_types) { if (hash_list.contains(hash_type)) { file.hash = Json::requireString(hash_list, hash_type); file.hash_type = hash_type; break; } } } return file; } return {}; } auto Modrinth::loadDependencyVersions([[maybe_unused]] const ModPlatform::Dependency& m, QJsonArray& arr, const BaseInstance* inst) -> ModPlatform::IndexedVersion { auto profile = (dynamic_cast<const MinecraftInstance*>(inst))->getPackProfile(); QString mcVersion = profile->getComponentVersion("net.minecraft"); auto loaders = profile->getSupportedModLoaders(); QVector<ModPlatform::IndexedVersion> versions; for (auto versionIter : arr) { auto obj = versionIter.toObject(); auto file = loadIndexedPackVersion(obj); if (file.fileId.isValid() && (!loaders.has_value() || !file.loaders || loaders.value() & file.loaders)) // Heuristic to check if the returned value is valid versions.append(file); } auto orderSortPredicate = [](const ModPlatform::IndexedVersion& a, const ModPlatform::IndexedVersion& b) -> bool { // dates are in RFC 3339 format return a.date > b.date; }; std::sort(versions.begin(), versions.end(), orderSortPredicate); return versions.length() != 0 ? versions.front() : ModPlatform::IndexedVersion(); }
10,518
C++
.cpp
228
38.846491
140
0.658077
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,092
ModrinthCheckUpdate.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/modrinth/ModrinthCheckUpdate.cpp
#include "ModrinthCheckUpdate.h" #include "Application.h" #include "ModrinthAPI.h" #include "ModrinthPackIndex.h" #include "Json.h" #include "QObjectPtr.h" #include "ResourceDownloadTask.h" #include "modplatform/helpers/HashUtils.h" #include "tasks/ConcurrentTask.h" static ModrinthAPI api; bool ModrinthCheckUpdate::abort() { if (m_job) return m_job->abort(); return true; } /* Check for update: * - Get latest version available * - Compare hash of the latest version with the current hash * - If equal, no updates, else, there's updates, so add to the list * */ void ModrinthCheckUpdate::executeTask() { setStatus(tr("Preparing resources for Modrinth...")); setProgress(0, (m_loaders_list.isEmpty() ? 1 : m_loaders_list.length()) * 2 + 1); auto hashing_task = makeShared<ConcurrentTask>("MakeModrinthHashesTask", APPLICATION->settings()->get("NumberOfConcurrentTasks").toInt()); for (auto* resource : m_resources) { auto hash = resource->metadata()->hash; // Sadly the API can only handle one hash type per call, se we // need to generate a new hash if the current one is innadequate // (though it will rarely happen, if at all) if (resource->metadata()->hash_format != m_hash_type) { auto hash_task = Hashing::createHasher(resource->fileinfo().absoluteFilePath(), ModPlatform::ResourceProvider::MODRINTH); connect(hash_task.get(), &Hashing::Hasher::resultsReady, [this, resource](QString hash) { m_mappings.insert(hash, resource); }); connect(hash_task.get(), &Task::failed, [this] { failed("Failed to generate hash"); }); hashing_task->addTask(hash_task); } else { m_mappings.insert(hash, resource); } } connect(hashing_task.get(), &Task::finished, this, &ModrinthCheckUpdate::checkNextLoader); m_job = hashing_task; hashing_task->start(); } void ModrinthCheckUpdate::getUpdateModsForLoader(std::optional<ModPlatform::ModLoaderTypes> loader) { setStatus(tr("Waiting for the API response from Modrinth...")); setProgress(m_progress + 1, m_progressTotal); auto response = std::make_shared<QByteArray>(); QStringList hashes = m_mappings.keys(); auto job = api.latestVersions(hashes, m_hash_type, m_game_versions, loader, response); connect(job.get(), &Task::succeeded, this, [this, response, loader] { checkVersionsResponse(response, loader); }); connect(job.get(), &Task::failed, this, &ModrinthCheckUpdate::checkNextLoader); m_job = job; job->start(); } void ModrinthCheckUpdate::checkVersionsResponse(std::shared_ptr<QByteArray> response, std::optional<ModPlatform::ModLoaderTypes> loader) { setStatus(tr("Parsing the API response from Modrinth...")); setProgress(m_progress + 1, m_progressTotal); QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from ModrinthCheckUpdate at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; emitFailed(parse_error.errorString()); return; } try { auto iter = m_mappings.begin(); while (iter != m_mappings.end()) { const QString hash = iter.key(); Resource* resource = iter.value(); auto project_obj = doc[hash].toObject(); // If the returned project is empty, but we have Modrinth metadata, // it means this specific version is not available if (project_obj.isEmpty()) { qDebug() << "Mod " << m_mappings.find(hash).value()->name() << " got an empty response." << "Hash: " << hash; ++iter; continue; } // Sometimes a version may have multiple files, one with "forge" and one with "fabric", // so we may want to filter it QString loader_filter; static auto flags = { ModPlatform::ModLoaderType::NeoForge, ModPlatform::ModLoaderType::Forge, ModPlatform::ModLoaderType::Quilt, ModPlatform::ModLoaderType::Fabric }; for (auto flag : flags) { if (loader.has_value() && loader->testFlag(flag)) { loader_filter = ModPlatform::getModLoaderAsString(flag); break; } } // Currently, we rely on a couple heuristics to determine whether an update is actually available or not: // - The file needs to be preferred: It is either the primary file, or the one found via (explicit) usage of the // loader_filter // - The version reported by the JAR is different from the version reported by the indexed version (it's usually the case) // Such is the pain of having arbitrary files for a given version .-. auto project_ver = Modrinth::loadIndexedPackVersion(project_obj, m_hash_type, loader_filter); if (project_ver.downloadUrl.isEmpty()) { qCritical() << "Modrinth mod without download url!" << project_ver.fileName; ++iter; continue; } // Fake pack with the necessary info to pass to the download task :) auto pack = std::make_shared<ModPlatform::IndexedPack>(); pack->name = resource->name(); pack->slug = resource->metadata()->slug; pack->addonId = resource->metadata()->project_id; pack->provider = ModPlatform::ResourceProvider::MODRINTH; if ((project_ver.hash != hash && project_ver.is_preferred) || (resource->status() == ResourceStatus::NOT_INSTALLED)) { auto download_task = makeShared<ResourceDownloadTask>(pack, project_ver, m_resource_model); QString old_version = resource->metadata()->version_number; if (old_version.isEmpty()) { if (resource->status() == ResourceStatus::NOT_INSTALLED) old_version = tr("Not installed"); else old_version = tr("Unknown"); } m_updates.emplace_back(pack->name, hash, old_version, project_ver.version_number, project_ver.version_type, project_ver.changelog, ModPlatform::ResourceProvider::MODRINTH, download_task, resource->enabled()); } m_deps.append(std::make_shared<GetModDependenciesTask::PackDependency>(pack, project_ver)); iter = m_mappings.erase(iter); } } catch (Json::JsonException& e) { emitFailed(e.cause() + ": " + e.what()); return; } checkNextLoader(); } void ModrinthCheckUpdate::checkNextLoader() { if (m_mappings.isEmpty()) { emitSucceeded(); return; } if (m_loaders_list.isEmpty() && m_loader_idx == 0) { getUpdateModsForLoader({}); m_loader_idx++; return; } if (m_loader_idx < m_loaders_list.size()) { getUpdateModsForLoader(m_loaders_list.at(m_loader_idx)); m_loader_idx++; return; } for (auto resource : m_mappings) { QString reason; if (dynamic_cast<Mod*>(resource) != nullptr) reason = tr("No valid version found for this resource. It's probably unavailable for the current game " "version / mod loader."); else reason = tr("No valid version found for this resource. It's probably unavailable for the current game version."); emit checkFailed(resource, reason); } emitSucceeded(); }
7,819
C++
.cpp
160
39.425
140
0.624033
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,093
ModrinthInstanceCreationTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/modrinth/ModrinthInstanceCreationTask.cpp
#include "ModrinthInstanceCreationTask.h" #include "Application.h" #include "FileSystem.h" #include "InstanceList.h" #include "Json.h" #include "QObjectPtr.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include "minecraft/mod/Mod.h" #include "modplatform/EnsureMetadataTask.h" #include "modplatform/helpers/OverrideUtils.h" #include "modplatform/modrinth/ModrinthPackManifest.h" #include "net/ChecksumValidator.h" #include "net/ApiDownload.h" #include "net/NetJob.h" #include "settings/INISettingsObject.h" #include "ui/dialogs/CustomMessageBox.h" #include "ui/pages/modplatform/OptionalModDialog.h" #include <QAbstractButton> #include <QFileInfo> #include <QHash> #include <vector> bool ModrinthCreationTask::abort() { if (!canAbort()) return false; m_abort = true; if (m_task) m_task->abort(); return Task::abort(); } bool ModrinthCreationTask::updateInstance() { auto instance_list = APPLICATION->instances(); // FIXME: How to handle situations when there's more than one install already for a given modpack? InstancePtr inst; if (auto original_id = originalInstanceID(); !original_id.isEmpty()) { inst = instance_list->getInstanceById(original_id); Q_ASSERT(inst); } else { inst = instance_list->getInstanceByManagedName(originalName()); if (!inst) { inst = instance_list->getInstanceById(originalName()); if (!inst) return false; } } QString index_path = FS::PathCombine(m_stagingPath, "modrinth.index.json"); if (!parseManifest(index_path, m_files, true, false)) return false; auto version_name = inst->getManagedPackVersionName(); m_root_path = QFileInfo(inst->gameRoot()).fileName(); auto version_str = !version_name.isEmpty() ? tr(" (version %1)").arg(version_name) : ""; if (shouldConfirmUpdate()) { auto should_update = askIfShouldUpdate(m_parent, version_str); if (should_update == ShouldUpdate::SkipUpdating) return false; if (should_update == ShouldUpdate::Cancel) { m_abort = true; return false; } } // Remove repeated files, we don't need to download them! QDir old_inst_dir(inst->instanceRoot()); QString old_index_folder(FS::PathCombine(old_inst_dir.absolutePath(), "mrpack")); QString old_index_path(FS::PathCombine(old_index_folder, "modrinth.index.json")); QFileInfo old_index_file(old_index_path); if (old_index_file.exists()) { std::vector<Modrinth::File> old_files; parseManifest(old_index_path, old_files, false, false); // Let's remove all duplicated, identical resources! auto files_iterator = m_files.begin(); begin: while (files_iterator != m_files.end()) { auto const& file = *files_iterator; auto old_files_iterator = old_files.begin(); while (old_files_iterator != old_files.end()) { auto const& old_file = *old_files_iterator; if (old_file.hash == file.hash) { qDebug() << "Removed file at" << file.path << "from list of downloads"; files_iterator = m_files.erase(files_iterator); old_files_iterator = old_files.erase(old_files_iterator); goto begin; // Sorry :c } old_files_iterator++; } files_iterator++; } QDir old_minecraft_dir(inst->gameRoot()); // Some files were removed from the old version, and some will be downloaded in an updated version, // so we're fine removing them! if (!old_files.empty()) { for (auto const& file : old_files) { if (file.path.isEmpty()) continue; qDebug() << "Scheduling" << file.path << "for removal"; m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(file.path)); } } // We will remove all the previous overrides, to prevent duplicate files! // TODO: Currently 'overrides' will always override the stuff on update. How do we preserve unchanged overrides? // FIXME: We may want to do something about disabled mods. auto old_overrides = Override::readOverrides("overrides", old_index_folder); for (const auto& entry : old_overrides) { if (entry.isEmpty()) continue; qDebug() << "Scheduling" << entry << "for removal"; m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(entry)); } auto old_client_overrides = Override::readOverrides("client-overrides", old_index_folder); for (const auto& entry : old_client_overrides) { if (entry.isEmpty()) continue; qDebug() << "Scheduling" << entry << "for removal"; m_files_to_remove.append(old_minecraft_dir.absoluteFilePath(entry)); } } else { // We don't have an old index file, so we may duplicate stuff! auto dialog = CustomMessageBox::selectable(m_parent, tr("No index file."), tr("We couldn't find a suitable index file for the older version. This may cause some " "of the files to be duplicated. Do you want to continue?"), QMessageBox::Warning, QMessageBox::Ok | QMessageBox::Cancel); if (dialog->exec() == QDialog::DialogCode::Rejected) { m_abort = true; return false; } } setOverride(true, inst->id()); qDebug() << "Will override instance!"; m_instance = inst; // We let it go through the createInstance() stage, just with a couple modifications for updating return false; } // https://docs.modrinth.com/docs/modpacks/format_definition/ bool ModrinthCreationTask::createInstance() { QEventLoop loop; QString parent_folder(FS::PathCombine(m_stagingPath, "mrpack")); QString index_path = FS::PathCombine(m_stagingPath, "modrinth.index.json"); if (m_files.empty() && !parseManifest(index_path, m_files, true, true)) return false; // Keep index file in case we need it some other time (like when changing versions) QString new_index_place(FS::PathCombine(parent_folder, "modrinth.index.json")); FS::ensureFilePathExists(new_index_place); FS::move(index_path, new_index_place); auto mcPath = FS::PathCombine(m_stagingPath, m_root_path); auto override_path = FS::PathCombine(m_stagingPath, "overrides"); if (QFile::exists(override_path)) { // Create a list of overrides in "overrides.txt" inside mrpack/ Override::createOverrides("overrides", parent_folder, override_path); // Apply the overrides if (!FS::move(override_path, mcPath)) { setError(tr("Could not rename the overrides folder:\n") + "overrides"); return false; } } // Do client overrides auto client_override_path = FS::PathCombine(m_stagingPath, "client-overrides"); if (QFile::exists(client_override_path)) { // Create a list of overrides in "client-overrides.txt" inside mrpack/ Override::createOverrides("client-overrides", parent_folder, client_override_path); // Apply the overrides if (!FS::overrideFolder(mcPath, client_override_path)) { setError(tr("Could not rename the client overrides folder:\n") + "client overrides"); return false; } } QString configPath = FS::PathCombine(m_stagingPath, "instance.cfg"); auto instanceSettings = std::make_shared<INISettingsObject>(configPath); MinecraftInstance instance(m_globalSettings, instanceSettings, m_stagingPath); auto components = instance.getPackProfile(); components->buildingFromScratch(); components->setComponentVersion("net.minecraft", m_minecraft_version, true); if (!m_fabric_version.isEmpty()) components->setComponentVersion("net.fabricmc.fabric-loader", m_fabric_version); if (!m_quilt_version.isEmpty()) components->setComponentVersion("org.quiltmc.quilt-loader", m_quilt_version); if (!m_forge_version.isEmpty()) components->setComponentVersion("net.minecraftforge", m_forge_version); if (!m_neoForge_version.isEmpty()) components->setComponentVersion("net.neoforged", m_neoForge_version); if (m_instIcon != "default") { instance.setIconKey(m_instIcon); } else if (!m_managed_id.isEmpty()) { instance.setIconKey("modrinth"); } // Don't add managed info to packs without an ID (most likely imported from ZIP) if (!m_managed_id.isEmpty()) instance.setManagedPack("modrinth", m_managed_id, m_managed_name, m_managed_version_id, version()); else instance.setManagedPack("modrinth", "", name(), "", ""); instance.setName(name()); instance.saveNow(); auto downloadMods = makeShared<NetJob>(tr("Mod Download Modrinth"), APPLICATION->network()); auto root_modpack_path = FS::PathCombine(m_stagingPath, m_root_path); auto root_modpack_url = QUrl::fromLocalFile(root_modpack_path); // TODO make this work with other sorts of resource QHash<QString, Resource*> resources; for (auto file : m_files) { auto fileName = file.path; fileName = FS::RemoveInvalidPathChars(fileName); auto file_path = FS::PathCombine(root_modpack_path, fileName); if (!root_modpack_url.isParentOf(QUrl::fromLocalFile(file_path))) { // This means we somehow got out of the root folder, so abort here to prevent exploits setError(tr("One of the files has a path that leads to an arbitrary location (%1). This is a security risk and isn't allowed.") .arg(fileName)); return false; } if (fileName.startsWith("mods/")) { auto mod = new Mod(file_path); ModDetails d; d.mod_id = file_path; mod->setDetails(d); resources[file.hash.toHex()] = mod; } qDebug() << "Will try to download" << file.downloads.front() << "to" << file_path; auto dl = Net::ApiDownload::makeFile(file.downloads.dequeue(), file_path); dl->addValidator(new Net::ChecksumValidator(file.hashAlgorithm, file.hash)); downloadMods->addNetAction(dl); if (!file.downloads.empty()) { // FIXME: This really needs to be put into a ConcurrentTask of // MultipleOptionsTask's , once those exist :) auto param = dl.toWeakRef(); connect(dl.get(), &Task::failed, [&file, file_path, param, downloadMods] { auto ndl = Net::ApiDownload::makeFile(file.downloads.dequeue(), file_path); ndl->addValidator(new Net::ChecksumValidator(file.hashAlgorithm, file.hash)); downloadMods->addNetAction(ndl); if (auto shared = param.lock()) shared->succeeded(); }); } } bool ended_well = false; connect(downloadMods.get(), &NetJob::succeeded, this, [&ended_well]() { ended_well = true; }); connect(downloadMods.get(), &NetJob::failed, [this, &ended_well](const QString& reason) { ended_well = false; setError(reason); }); connect(downloadMods.get(), &NetJob::finished, &loop, &QEventLoop::quit); connect(downloadMods.get(), &NetJob::progress, [this](qint64 current, qint64 total) { setDetails(tr("%1 out of %2 complete").arg(current).arg(total)); setProgress(current, total); }); connect(downloadMods.get(), &NetJob::stepProgress, this, &ModrinthCreationTask::propagateStepProgress); setStatus(tr("Downloading mods...")); downloadMods->start(); m_task = downloadMods; loop.exec(); if (!ended_well) { for (auto resource : resources) { delete resource; } return ended_well; } QEventLoop ensureMetaLoop; QDir folder = FS::PathCombine(instance.modsRoot(), ".index"); auto ensureMetadataTask = makeShared<EnsureMetadataTask>(resources, folder, ModPlatform::ResourceProvider::MODRINTH); connect(ensureMetadataTask.get(), &Task::succeeded, this, [&ended_well]() { ended_well = true; }); connect(ensureMetadataTask.get(), &Task::finished, &ensureMetaLoop, &QEventLoop::quit); connect(ensureMetadataTask.get(), &Task::progress, [this](qint64 current, qint64 total) { setDetails(tr("%1 out of %2 complete").arg(current).arg(total)); setProgress(current, total); }); connect(ensureMetadataTask.get(), &Task::stepProgress, this, &ModrinthCreationTask::propagateStepProgress); ensureMetadataTask->start(); m_task = ensureMetadataTask; ensureMetaLoop.exec(); for (auto resource : resources) { delete resource; } resources.clear(); // Update information of the already installed instance, if any. if (m_instance && ended_well) { setAbortable(false); auto inst = m_instance.value(); // Only change the name if it didn't use a custom name, so that the previous custom name // is preserved, but if we're using the original one, we update the version string. // NOTE: This needs to come before the copyManagedPack call! if (inst->name().contains(inst->getManagedPackVersionName()) && inst->name() != instance.name()) { if (askForChangingInstanceName(m_parent, inst->name(), instance.name()) == InstanceNameChange::ShouldChange) inst->setName(instance.name()); } inst->copyManagedPack(instance); } return ended_well; } bool ModrinthCreationTask::parseManifest(const QString& index_path, std::vector<Modrinth::File>& files, bool set_internal_data, bool show_optional_dialog) { try { auto doc = Json::requireDocument(index_path); auto obj = Json::requireObject(doc, "modrinth.index.json"); int formatVersion = Json::requireInteger(obj, "formatVersion", "modrinth.index.json"); if (formatVersion == 1) { auto game = Json::requireString(obj, "game", "modrinth.index.json"); if (game != "minecraft") { throw JSONValidationError("Unknown game: " + game); } if (set_internal_data) { if (m_managed_version_id.isEmpty()) m_managed_version_id = Json::ensureString(obj, "versionId", {}, "Managed ID"); m_managed_name = Json::ensureString(obj, "name", {}, "Managed Name"); } auto jsonFiles = Json::requireIsArrayOf<QJsonObject>(obj, "files", "modrinth.index.json"); std::vector<Modrinth::File> optionalFiles; for (const auto& modInfo : jsonFiles) { Modrinth::File file; file.path = Json::requireString(modInfo, "path").replace("\\", "/"); auto env = Json::ensureObject(modInfo, "env"); // 'env' field is optional if (!env.isEmpty()) { QString support = Json::ensureString(env, "client", "unsupported"); if (support == "unsupported") { continue; } else if (support == "optional") { file.required = false; } } QJsonObject hashes = Json::requireObject(modInfo, "hashes"); file.hash = QByteArray::fromHex(Json::requireString(hashes, "sha512").toLatin1()); file.hashAlgorithm = QCryptographicHash::Sha512; // Do not use requireUrl, which uses StrictMode, instead use QUrl's default TolerantMode // (as Modrinth seems to incorrectly handle spaces) auto download_arr = Json::ensureArray(modInfo, "downloads"); for (auto download : download_arr) { qWarning() << download.toString(); bool is_last = download.toString() == download_arr.last().toString(); auto download_url = QUrl(download.toString()); if (!download_url.isValid()) { qDebug() << QString("Download URL (%1) for %2 is not a correctly formatted URL").arg(download_url.toString(), file.path); if (is_last && file.downloads.isEmpty()) throw JSONValidationError(tr("Download URL for %1 is not a correctly formatted URL").arg(file.path)); } else { file.downloads.push_back(download_url); } } (file.required ? files : optionalFiles).push_back(file); } if (!optionalFiles.empty()) { QStringList oFiles; for (auto file : optionalFiles) oFiles.push_back(file.path); OptionalModDialog optionalModDialog(m_parent, oFiles); if (optionalModDialog.exec() == QDialog::Rejected) { emitAborted(); return false; } auto selectedMods = optionalModDialog.getResult(); for (auto file : optionalFiles) { if (selectedMods.contains(file.path)) { file.required = true; } else { file.path += ".disabled"; } files.push_back(file); } } if (set_internal_data) { auto dependencies = Json::requireObject(obj, "dependencies", "modrinth.index.json"); for (auto it = dependencies.begin(), end = dependencies.end(); it != end; ++it) { QString name = it.key(); if (name == "minecraft") { m_minecraft_version = Json::requireString(*it, "Minecraft version"); } else if (name == "fabric-loader") { m_fabric_version = Json::requireString(*it, "Fabric Loader version"); } else if (name == "quilt-loader") { m_quilt_version = Json::requireString(*it, "Quilt Loader version"); } else if (name == "forge") { m_forge_version = Json::requireString(*it, "Forge version"); } else if (name == "neoforge") { m_neoForge_version = Json::requireString(*it, "NeoForge version"); } else { throw JSONValidationError("Unknown dependency type: " + name); } } } } else { throw JSONValidationError(QStringLiteral("Unknown format version: %s").arg(formatVersion)); } } catch (const JSONValidationError& e) { setError(tr("Could not understand pack index:\n") + e.cause()); return false; } return true; }
19,366
C++
.cpp
388
38.82732
140
0.601661
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,094
ModrinthPackExportTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/modrinth/ModrinthPackExportTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ModrinthPackExportTask.h" #include <QCoreApplication> #include <QCryptographicHash> #include <QFileInfo> #include <QMessageBox> #include <QtConcurrentRun> #include "Json.h" #include "MMCZip.h" #include "minecraft/PackProfile.h" #include "minecraft/mod/MetadataHandler.h" #include "minecraft/mod/ModFolderModel.h" #include "modplatform/helpers/HashUtils.h" #include "tasks/Task.h" const QStringList ModrinthPackExportTask::PREFIXES({ "mods/", "coremods/", "resourcepacks/", "texturepacks/", "shaderpacks/" }); const QStringList ModrinthPackExportTask::FILE_EXTENSIONS({ "jar", "litemod", "zip" }); ModrinthPackExportTask::ModrinthPackExportTask(const QString& name, const QString& version, const QString& summary, bool optionalFiles, InstancePtr instance, const QString& output, MMCZip::FilterFunction filter) : name(name) , version(version) , summary(summary) , optionalFiles(optionalFiles) , instance(instance) , mcInstance(dynamic_cast<MinecraftInstance*>(instance.get())) , gameRoot(instance->gameRoot()) , output(output) , filter(filter) {} void ModrinthPackExportTask::executeTask() { setStatus(tr("Searching for files...")); setProgress(0, 0); collectFiles(); } bool ModrinthPackExportTask::abort() { if (task) { task->abort(); emitAborted(); return true; } return false; } void ModrinthPackExportTask::collectFiles() { setAbortable(false); QCoreApplication::processEvents(); files.clear(); if (!MMCZip::collectFileListRecursively(instance->gameRoot(), nullptr, &files, filter)) { emitFailed(tr("Could not search for files")); return; } pendingHashes.clear(); resolvedFiles.clear(); if (mcInstance) { mcInstance->loaderModList()->update(); connect(mcInstance->loaderModList().get(), &ModFolderModel::updateFinished, this, &ModrinthPackExportTask::collectHashes); } else collectHashes(); } void ModrinthPackExportTask::collectHashes() { setStatus(tr("Finding file hashes...")); for (const QFileInfo& file : files) { QCoreApplication::processEvents(); const QString relative = gameRoot.relativeFilePath(file.absoluteFilePath()); // require sensible file types if (!std::any_of(PREFIXES.begin(), PREFIXES.end(), [&relative](const QString& prefix) { return relative.startsWith(prefix); })) continue; if (!std::any_of(FILE_EXTENSIONS.begin(), FILE_EXTENSIONS.end(), [&relative](const QString& extension) { return relative.endsWith('.' + extension) || relative.endsWith('.' + extension + ".disabled"); })) continue; QFile openFile(file.absoluteFilePath()); if (!openFile.open(QFile::ReadOnly)) { qWarning() << "Could not open" << file << "for hashing"; continue; } const QByteArray data = openFile.readAll(); if (openFile.error() != QFileDevice::NoError) { qWarning() << "Could not read" << file; continue; } auto sha512 = Hashing::hash(data, Hashing::Algorithm::Sha512); auto allMods = mcInstance->loaderModList()->allMods(); if (auto modIter = std::find_if(allMods.begin(), allMods.end(), [&file](Mod* mod) { return mod->fileinfo() == file; }); modIter != allMods.end()) { const Mod* mod = *modIter; if (mod->metadata() != nullptr) { const QUrl& url = mod->metadata()->url; // ensure the url is permitted on modrinth.com if (!url.isEmpty() && BuildConfig.MODRINTH_MRPACK_HOSTS.contains(url.host())) { qDebug() << "Resolving" << relative << "from index"; auto sha1 = Hashing::hash(data, Hashing::Algorithm::Sha1); ResolvedFile resolvedFile{ sha1, sha512, url.toEncoded(), openFile.size(), mod->metadata()->side }; resolvedFiles[relative] = resolvedFile; // nice! we've managed to resolve based on local metadata! // no need to enqueue it continue; } } } qDebug() << "Enqueueing" << relative << "for Modrinth query"; pendingHashes[relative] = sha512; } setAbortable(true); makeApiRequest(); } void ModrinthPackExportTask::makeApiRequest() { if (pendingHashes.isEmpty()) buildZip(); else { setStatus(tr("Finding versions for hashes...")); auto response = std::make_shared<QByteArray>(); task = api.currentVersions(pendingHashes.values(), "sha512", response); connect(task.get(), &Task::succeeded, [this, response]() { parseApiResponse(response); }); connect(task.get(), &Task::failed, this, &ModrinthPackExportTask::emitFailed); task->start(); } } void ModrinthPackExportTask::parseApiResponse(const std::shared_ptr<QByteArray> response) { task = nullptr; try { const QJsonDocument doc = Json::requireDocument(*response); QMapIterator<QString, QString> iterator(pendingHashes); while (iterator.hasNext()) { iterator.next(); const QJsonObject obj = doc[iterator.value()].toObject(); if (obj.isEmpty()) continue; const QJsonArray files_array = obj["files"].toArray(); if (auto fileIter = std::find_if(files_array.begin(), files_array.end(), [&iterator](const QJsonValue& file) { return file["hashes"]["sha512"] == iterator.value(); }); fileIter != files_array.end()) { // map the file to the url resolvedFiles[iterator.key()] = ResolvedFile{ fileIter->toObject()["hashes"].toObject()["sha1"].toString(), iterator.value(), fileIter->toObject()["url"].toString(), fileIter->toObject()["size"].toInt() }; } } } catch (const Json::JsonException& e) { emitFailed(tr("Failed to parse versions response: %1").arg(e.what())); return; } pendingHashes.clear(); buildZip(); } void ModrinthPackExportTask::buildZip() { setStatus(tr("Adding files...")); auto zipTask = makeShared<MMCZip::ExportToZipTask>(output, gameRoot, files, "overrides/", true, true); zipTask->addExtraFile("modrinth.index.json", generateIndex()); zipTask->setExcludeFiles(resolvedFiles.keys()); auto progressStep = std::make_shared<TaskStepProgress>(); connect(zipTask.get(), &Task::finished, this, [this, progressStep] { progressStep->state = TaskStepState::Succeeded; stepProgress(*progressStep); }); connect(zipTask.get(), &Task::succeeded, this, &ModrinthPackExportTask::emitSucceeded); connect(zipTask.get(), &Task::aborted, this, &ModrinthPackExportTask::emitAborted); connect(zipTask.get(), &Task::failed, this, [this, progressStep](QString reason) { progressStep->state = TaskStepState::Failed; stepProgress(*progressStep); emitFailed(reason); }); connect(zipTask.get(), &Task::stepProgress, this, &ModrinthPackExportTask::propagateStepProgress); connect(zipTask.get(), &Task::progress, this, [this, progressStep](qint64 current, qint64 total) { progressStep->update(current, total); stepProgress(*progressStep); }); connect(zipTask.get(), &Task::status, this, [this, progressStep](QString status) { progressStep->status = status; stepProgress(*progressStep); }); task.reset(zipTask); zipTask->start(); } QByteArray ModrinthPackExportTask::generateIndex() { QJsonObject out; out["formatVersion"] = 1; out["game"] = "minecraft"; out["name"] = name; out["versionId"] = version; if (!summary.isEmpty()) out["summary"] = summary; if (mcInstance) { auto profile = mcInstance->getPackProfile(); // collect all supported components const ComponentPtr minecraft = profile->getComponent("net.minecraft"); const ComponentPtr quilt = profile->getComponent("org.quiltmc.quilt-loader"); const ComponentPtr fabric = profile->getComponent("net.fabricmc.fabric-loader"); const ComponentPtr forge = profile->getComponent("net.minecraftforge"); const ComponentPtr neoForge = profile->getComponent("net.neoforged"); // convert all available components to mrpack dependencies QJsonObject dependencies; if (minecraft != nullptr) dependencies["minecraft"] = minecraft->m_version; if (quilt != nullptr) dependencies["quilt-loader"] = quilt->m_version; if (fabric != nullptr) dependencies["fabric-loader"] = fabric->m_version; if (forge != nullptr) dependencies["forge"] = forge->m_version; if (neoForge != nullptr) dependencies["neoforge"] = neoForge->m_version; out["dependencies"] = dependencies; } QJsonArray filesOut; for (auto iterator = resolvedFiles.constBegin(); iterator != resolvedFiles.constEnd(); iterator++) { QJsonObject fileOut; QString path = iterator.key(); const ResolvedFile& value = iterator.value(); QJsonObject env; // detect disabled mod const QFileInfo pathInfo(path); if (optionalFiles && pathInfo.suffix() == "disabled") { // rename it path = pathInfo.dir().filePath(pathInfo.completeBaseName()); env["client"] = "optional"; env["server"] = "optional"; } else { env["client"] = "required"; env["server"] = "required"; } // a server side mod does not imply that the mod does not work on the client // however, if a mrpack mod is marked as server-only it will not install on the client if (iterator->side == Metadata::ModSide::ClientSide) env["server"] = "unsupported"; fileOut["env"] = env; fileOut["path"] = path; fileOut["downloads"] = QJsonArray{ iterator->url }; QJsonObject hashes; hashes["sha1"] = value.sha1; hashes["sha512"] = value.sha512; fileOut["hashes"] = hashes; fileOut["fileSize"] = value.size; filesOut << fileOut; } out["files"] = filesOut; return QJsonDocument(out).toJson(QJsonDocument::Compact); }
11,545
C++
.cpp
265
34.935849
139
0.624889
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,095
ModrinthPackManifest.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/modrinth/ModrinthPackManifest.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2013-2021 MultiMC Contributors * Copyright 2022 kb1000 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ModrinthPackManifest.h" #include <QFileInfo> #include "Json.h" #include "modplatform/modrinth/ModrinthAPI.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/PackProfile.h" #include <QSet> static ModrinthAPI api; namespace Modrinth { void loadIndexedPack(Modpack& pack, QJsonObject& obj) { pack.id = Json::ensureString(obj, "project_id"); pack.name = Json::ensureString(obj, "title"); pack.description = Json::ensureString(obj, "description"); auto temp_author_name = Json::ensureString(obj, "author"); pack.author = std::make_tuple(temp_author_name, api.getAuthorURL(temp_author_name)); pack.iconUrl = Json::ensureString(obj, "icon_url"); pack.iconName = QString("modrinth_%1.%2").arg(Json::ensureString(obj, "slug"), QFileInfo(pack.iconUrl.fileName()).suffix()); } void loadIndexedInfo(Modpack& pack, QJsonObject& obj) { pack.extra.body = Json::ensureString(obj, "body"); pack.extra.projectUrl = QString("https://modrinth.com/modpack/%1").arg(Json::ensureString(obj, "slug")); pack.extra.issuesUrl = Json::ensureString(obj, "issues_url"); if (pack.extra.issuesUrl.endsWith('/')) pack.extra.issuesUrl.chop(1); pack.extra.sourceUrl = Json::ensureString(obj, "source_url"); if (pack.extra.sourceUrl.endsWith('/')) pack.extra.sourceUrl.chop(1); pack.extra.wikiUrl = Json::ensureString(obj, "wiki_url"); if (pack.extra.wikiUrl.endsWith('/')) pack.extra.wikiUrl.chop(1); pack.extra.discordUrl = Json::ensureString(obj, "discord_url"); if (pack.extra.discordUrl.endsWith('/')) pack.extra.discordUrl.chop(1); auto donate_arr = Json::ensureArray(obj, "donation_urls"); for (auto d : donate_arr) { auto d_obj = Json::requireObject(d); DonationData donate; donate.id = Json::ensureString(d_obj, "id"); donate.platform = Json::ensureString(d_obj, "platform"); donate.url = Json::ensureString(d_obj, "url"); pack.extra.donate.append(donate); } pack.extra.status = Json::ensureString(obj, "status"); pack.extraInfoLoaded = true; } void loadIndexedVersions(Modpack& pack, QJsonDocument& doc) { QVector<ModpackVersion> unsortedVersions; auto arr = Json::requireArray(doc); for (auto versionIter : arr) { auto obj = Json::requireObject(versionIter); auto file = loadIndexedVersion(obj); if (!file.id.isEmpty()) // Heuristic to check if the returned value is valid unsortedVersions.append(file); } auto orderSortPredicate = [](const ModpackVersion& a, const ModpackVersion& b) -> bool { // dates are in RFC 3339 format return a.date > b.date; }; std::sort(unsortedVersions.begin(), unsortedVersions.end(), orderSortPredicate); pack.versions.swap(unsortedVersions); pack.versionsLoaded = true; } auto loadIndexedVersion(QJsonObject& obj) -> ModpackVersion { ModpackVersion file; file.name = Json::requireString(obj, "name"); file.version = Json::requireString(obj, "version_number"); auto gameVersions = Json::ensureArray(obj, "game_versions"); if (!gameVersions.isEmpty()) { file.gameVersion = Json::ensureString(gameVersions[0]); } auto loaders = Json::requireArray(obj, "loaders"); for (auto loader : loaders) { if (loader == "neoforge") file.loaders |= ModPlatform::NeoForge; else if (loader == "forge") file.loaders |= ModPlatform::Forge; else if (loader == "cauldron") file.loaders |= ModPlatform::Cauldron; else if (loader == "liteloader") file.loaders |= ModPlatform::LiteLoader; else if (loader == "fabric") file.loaders |= ModPlatform::Fabric; else if (loader == "quilt") file.loaders |= ModPlatform::Quilt; } file.version_type = ModPlatform::IndexedVersionType(Json::requireString(obj, "version_type")); file.changelog = Json::ensureString(obj, "changelog"); file.id = Json::requireString(obj, "id"); file.project_id = Json::requireString(obj, "project_id"); file.date = Json::requireString(obj, "date_published"); auto files = Json::requireArray(obj, "files"); for (auto file_iter : files) { File indexed_file; auto parent = Json::requireObject(file_iter); auto is_primary = Json::ensureBoolean(parent, (const QString)QStringLiteral("primary"), false); if (!is_primary) { auto filename = Json::ensureString(parent, "filename"); // Checking suffix here is fine because it's the response from Modrinth, // so one would assume it will always be in English. if (!filename.endsWith("mrpack") && !filename.endsWith("zip")) continue; } auto url = Json::requireString(parent, "url"); file.download_url = url; if (is_primary) break; } if (file.download_url.isEmpty()) return {}; return file; } } // namespace Modrinth
6,589
C++
.cpp
151
38.145695
128
0.678175
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,096
ModrinthAPI.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/modrinth/ModrinthAPI.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "ModrinthAPI.h" #include "Application.h" #include "Json.h" #include "net/ApiDownload.h" #include "net/ApiUpload.h" #include "net/NetJob.h" #include "net/Upload.h" Task::Ptr ModrinthAPI::currentVersion(QString hash, QString hash_format, std::shared_ptr<QByteArray> response) { auto netJob = makeShared<NetJob>(QString("Modrinth::GetCurrentVersion"), APPLICATION->network()); netJob->addNetAction(Net::ApiDownload::makeByteArray( QString(BuildConfig.MODRINTH_PROD_URL + "/version_file/%1?algorithm=%2").arg(hash, hash_format), response)); return netJob; } Task::Ptr ModrinthAPI::currentVersions(const QStringList& hashes, QString hash_format, std::shared_ptr<QByteArray> response) { auto netJob = makeShared<NetJob>(QString("Modrinth::GetCurrentVersions"), APPLICATION->network()); QJsonObject body_obj; Json::writeStringList(body_obj, "hashes", hashes); Json::writeString(body_obj, "algorithm", hash_format); QJsonDocument body(body_obj); auto body_raw = body.toJson(); netJob->addNetAction(Net::ApiUpload::makeByteArray(QString(BuildConfig.MODRINTH_PROD_URL + "/version_files"), response, body_raw)); netJob->setAskRetry(false); return netJob; } Task::Ptr ModrinthAPI::latestVersion(QString hash, QString hash_format, std::optional<std::list<Version>> mcVersions, std::optional<ModPlatform::ModLoaderTypes> loaders, std::shared_ptr<QByteArray> response) { auto netJob = makeShared<NetJob>(QString("Modrinth::GetLatestVersion"), APPLICATION->network()); QJsonObject body_obj; if (loaders.has_value()) Json::writeStringList(body_obj, "loaders", getModLoaderStrings(loaders.value())); if (mcVersions.has_value()) { QStringList game_versions; for (auto& ver : mcVersions.value()) { game_versions.append(ver.toString()); } Json::writeStringList(body_obj, "game_versions", game_versions); } QJsonDocument body(body_obj); auto body_raw = body.toJson(); netJob->addNetAction(Net::ApiUpload::makeByteArray( QString(BuildConfig.MODRINTH_PROD_URL + "/version_file/%1/update?algorithm=%2").arg(hash, hash_format), response, body_raw)); return netJob; } Task::Ptr ModrinthAPI::latestVersions(const QStringList& hashes, QString hash_format, std::optional<std::list<Version>> mcVersions, std::optional<ModPlatform::ModLoaderTypes> loaders, std::shared_ptr<QByteArray> response) { auto netJob = makeShared<NetJob>(QString("Modrinth::GetLatestVersions"), APPLICATION->network()); QJsonObject body_obj; Json::writeStringList(body_obj, "hashes", hashes); Json::writeString(body_obj, "algorithm", hash_format); if (loaders.has_value()) Json::writeStringList(body_obj, "loaders", getModLoaderStrings(loaders.value())); if (mcVersions.has_value()) { QStringList game_versions; for (auto& ver : mcVersions.value()) { game_versions.append(ver.toString()); } Json::writeStringList(body_obj, "game_versions", game_versions); } QJsonDocument body(body_obj); auto body_raw = body.toJson(); netJob->addNetAction( Net::ApiUpload::makeByteArray(QString(BuildConfig.MODRINTH_PROD_URL + "/version_files/update"), response, body_raw)); return netJob; } Task::Ptr ModrinthAPI::getProjects(QStringList addonIds, std::shared_ptr<QByteArray> response) const { auto netJob = makeShared<NetJob>(QString("Modrinth::GetProjects"), APPLICATION->network()); auto searchUrl = getMultipleModInfoURL(addonIds); netJob->addNetAction(Net::ApiDownload::makeByteArray(QUrl(searchUrl), response)); return netJob; } QList<ResourceAPI::SortingMethod> ModrinthAPI::getSortingMethods() const { // https://docs.modrinth.com/api-spec/#tag/projects/operation/searchProjects return { { 1, "relevance", QObject::tr("Sort by Relevance") }, { 2, "downloads", QObject::tr("Sort by Downloads") }, { 3, "follows", QObject::tr("Sort by Follows") }, { 4, "newest", QObject::tr("Sort by Newest") }, { 5, "updated", QObject::tr("Sort by Last Updated") } }; } Task::Ptr ModrinthAPI::getModCategories(std::shared_ptr<QByteArray> response) { auto netJob = makeShared<NetJob>(QString("Modrinth::GetCategories"), APPLICATION->network()); netJob->addNetAction(Net::ApiDownload::makeByteArray(QUrl(BuildConfig.MODRINTH_PROD_URL + "/tag/category"), response)); QObject::connect(netJob.get(), &Task::failed, [](QString msg) { qDebug() << "Modrinth failed to get categories:" << msg; }); return netJob; } QList<ModPlatform::Category> ModrinthAPI::loadCategories(std::shared_ptr<QByteArray> response, QString projectType) { QList<ModPlatform::Category> categories; QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from categories at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return categories; } try { auto arr = Json::requireArray(doc); for (auto val : arr) { auto cat = Json::requireObject(val); auto name = Json::requireString(cat, "name"); if (Json::ensureString(cat, "project_type", "") == projectType) categories.push_back({ name, name }); } } catch (Json::JsonException& e) { qCritical() << "Failed to parse response from a version request."; qCritical() << e.what(); qDebug() << doc; } return categories; } QList<ModPlatform::Category> ModrinthAPI::loadModCategories(std::shared_ptr<QByteArray> response) { return loadCategories(response, "mod"); };
6,264
C++
.cpp
130
40.523077
135
0.664043
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,097
Packwiz.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/packwiz/Packwiz.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 flowln <flowlnlnln@gmail.com> * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "Packwiz.h" #include <QDebug> #include <QDir> #include <QObject> #include <sstream> #include <string> #include "FileSystem.h" #include "StringUtils.h" #include "minecraft/mod/Mod.h" #include "modplatform/ModIndex.h" #include <toml++/toml.h> namespace Packwiz { auto getRealIndexName(const QDir& index_dir, QString normalized_fname, bool should_find_match) -> QString { QFile index_file(index_dir.absoluteFilePath(normalized_fname)); QString real_fname = normalized_fname; if (!index_file.exists()) { // Tries to get similar entries for (auto& file_name : index_dir.entryList(QDir::Filter::Files)) { if (!QString::compare(normalized_fname, file_name, Qt::CaseInsensitive)) { real_fname = file_name; break; } } if (should_find_match && !QString::compare(normalized_fname, real_fname, Qt::CaseSensitive)) { qCritical() << "Could not find a match for a valid metadata file!"; qCritical() << "File: " << normalized_fname; return {}; } } return real_fname; } // Helpers static inline auto indexFileName(QString const& mod_slug) -> QString { if (mod_slug.endsWith(".pw.toml")) return mod_slug; return QString("%1.pw.toml").arg(mod_slug); } // Helper functions for extracting data from the TOML file auto stringEntry(toml::table table, QString entry_name) -> QString { auto node = table[StringUtils::toStdString(entry_name)]; if (!node) { qWarning() << "Failed to read str property '" + entry_name + "' in mod metadata."; return {}; } return node.value_or(""); } auto intEntry(toml::table table, QString entry_name) -> int { auto node = table[StringUtils::toStdString(entry_name)]; if (!node) { qWarning() << "Failed to read int property '" + entry_name + "' in mod metadata."; return {}; } return node.value_or(0); } auto V1::createModFormat([[maybe_unused]] const QDir& index_dir, ModPlatform::IndexedPack& mod_pack, ModPlatform::IndexedVersion& mod_version) -> Mod { Mod mod; mod.slug = mod_pack.slug; mod.name = mod_pack.name; mod.filename = mod_version.fileName; if (mod_pack.provider == ModPlatform::ResourceProvider::FLAME) { mod.mode = "metadata:curseforge"; } else { mod.mode = "url"; mod.url = mod_version.downloadUrl; } mod.hash_format = mod_version.hash_type; mod.hash = mod_version.hash; mod.provider = mod_pack.provider; mod.file_id = mod_version.fileId; mod.project_id = mod_pack.addonId; mod.side = stringToSide(mod_version.side.isEmpty() ? mod_pack.side : mod_version.side); mod.loaders = mod_version.loaders; mod.mcVersions = mod_version.mcVersion; mod.mcVersions.sort(); mod.releaseType = mod_version.version_type; mod.version_number = mod_version.version_number; if (mod.version_number.isNull()) // on CurseForge, there is only a version name - not a version number mod.version_number = mod_version.version; return mod; } auto V1::createModFormat(const QDir& index_dir, [[maybe_unused]] ::Mod& internal_mod, QString slug) -> Mod { // Try getting metadata if it exists Mod mod{ getIndexForMod(index_dir, slug) }; if (mod.isValid()) return mod; qWarning() << QString("Tried to create mod metadata with a Mod without metadata!"); return {}; } void V1::updateModIndex(const QDir& index_dir, Mod& mod) { if (!mod.isValid()) { qCritical() << QString("Tried to update metadata of an invalid mod!"); return; } // Ensure the corresponding mod's info exists, and create it if not auto normalized_fname = indexFileName(mod.slug); auto real_fname = getRealIndexName(index_dir, normalized_fname); QFile index_file(index_dir.absoluteFilePath(real_fname)); if (real_fname != normalized_fname) index_file.rename(normalized_fname); // There's already data on there! // TODO: We should do more stuff here, as the user is likely trying to // override a file. In this case, check versions and ask the user what // they want to do! if (index_file.exists()) { index_file.remove(); } else { FS::ensureFilePathExists(index_file.fileName()); } toml::table update; switch (mod.provider) { case (ModPlatform::ResourceProvider::FLAME): if (mod.file_id.toInt() == 0 || mod.project_id.toInt() == 0) { qCritical() << QString("Did not write file %1 because missing information!").arg(normalized_fname); return; } update = toml::table{ { "file-id", mod.file_id.toInt() }, { "project-id", mod.project_id.toInt() }, }; break; case (ModPlatform::ResourceProvider::MODRINTH): if (mod.mod_id().toString().isEmpty() || mod.version().toString().isEmpty()) { qCritical() << QString("Did not write file %1 because missing information!").arg(normalized_fname); return; } update = toml::table{ { "mod-id", mod.mod_id().toString().toStdString() }, { "version", mod.version().toString().toStdString() }, }; break; } toml::array loaders; for (auto loader : { ModPlatform::NeoForge, ModPlatform::Forge, ModPlatform::Cauldron, ModPlatform::LiteLoader, ModPlatform::Fabric, ModPlatform::Quilt }) { if (mod.loaders & loader) { loaders.push_back(getModLoaderAsString(loader).toStdString()); } } toml::array mcVersions; for (auto version : mod.mcVersions) { mcVersions.push_back(version.toStdString()); } if (!index_file.open(QIODevice::ReadWrite)) { qCritical() << QString("Could not open file %1!").arg(normalized_fname); return; } // Put TOML data into the file QTextStream in_stream(&index_file); { auto tbl = toml::table{ { "name", mod.name.toStdString() }, { "filename", mod.filename.toStdString() }, { "side", sideToString(mod.side).toStdString() }, { "x-prismlauncher-loaders", loaders }, { "x-prismlauncher-mc-versions", mcVersions }, { "x-prismlauncher-release-type", mod.releaseType.toString().toStdString() }, { "x-prismlauncher-version-number", mod.version_number.toStdString() }, { "download", toml::table{ { "mode", mod.mode.toStdString() }, { "url", mod.url.toString().toStdString() }, { "hash-format", mod.hash_format.toStdString() }, { "hash", mod.hash.toStdString() }, } }, { "update", toml::table{ { ModPlatform::ProviderCapabilities::name(mod.provider), update } } } }; std::stringstream ss; ss << tbl; in_stream << QString::fromStdString(ss.str()); } index_file.flush(); index_file.close(); } void V1::deleteModIndex(const QDir& index_dir, QString& mod_slug) { auto normalized_fname = indexFileName(mod_slug); auto real_fname = getRealIndexName(index_dir, normalized_fname); if (real_fname.isEmpty()) return; QFile index_file(index_dir.absoluteFilePath(real_fname)); if (!index_file.exists()) { qWarning() << QString("Tried to delete non-existent mod metadata for %1!").arg(mod_slug); return; } if (!index_file.remove()) { qWarning() << QString("Failed to remove metadata for mod %1!").arg(mod_slug); } } void V1::deleteModIndex(const QDir& index_dir, QVariant& mod_id) { for (auto& file_name : index_dir.entryList(QDir::Filter::Files)) { auto mod = getIndexForMod(index_dir, file_name); if (mod.mod_id() == mod_id) { deleteModIndex(index_dir, mod.name); break; } } } auto V1::getIndexForMod(const QDir& index_dir, QString slug) -> Mod { Mod mod; auto normalized_fname = indexFileName(slug); auto real_fname = getRealIndexName(index_dir, normalized_fname, true); if (real_fname.isEmpty()) return {}; toml::table table; #if TOML_EXCEPTIONS try { table = toml::parse_file(StringUtils::toStdString(index_dir.absoluteFilePath(real_fname))); } catch (const toml::parse_error& err) { qWarning() << QString("Could not open file %1!").arg(normalized_fname); qWarning() << "Reason: " << QString(err.what()); return {}; } #else toml::parse_result result = toml::parse_file(StringUtils::toStdString(index_dir.absoluteFilePath(real_fname))); if (!result) { qWarning() << QString("Could not open file %1!").arg(normalized_fname); qWarning() << "Reason: " << result.error().description(); return {}; } table = result.table(); #endif // index_file.close(); mod.slug = slug; { // Basic info mod.name = stringEntry(table, "name"); mod.filename = stringEntry(table, "filename"); mod.side = stringToSide(stringEntry(table, "side")); mod.releaseType = ModPlatform::IndexedVersionType(table["x-prismlauncher-release-type"].value_or("")); if (auto loaders = table["x-prismlauncher-loaders"]; loaders && loaders.is_array()) { for (auto&& loader : *loaders.as_array()) { if (loader.is_string()) { mod.loaders |= ModPlatform::getModLoaderFromString(QString::fromStdString(loader.as_string()->value_or(""))); } } } if (auto versions = table["x-prismlauncher-mc-versions"]; versions && versions.is_array()) { for (auto&& version : *versions.as_array()) { if (version.is_string()) { auto ver = QString::fromStdString(version.as_string()->value_or("")); if (!ver.isEmpty()) { mod.mcVersions << ver; } } } mod.mcVersions.sort(); } } mod.version_number = table["x-prismlauncher-version-number"].value_or(""); { // [download] info auto download_table = table["download"].as_table(); if (!download_table) { qCritical() << QString("No [download] section found on mod metadata!"); return {}; } mod.mode = stringEntry(*download_table, "mode"); mod.url = stringEntry(*download_table, "url"); mod.hash_format = stringEntry(*download_table, "hash-format"); mod.hash = stringEntry(*download_table, "hash"); } { // [update] info using Provider = ModPlatform::ResourceProvider; auto update_table = table["update"]; if (!update_table || !update_table.is_table()) { qCritical() << QString("No [update] section found on mod metadata!"); return {}; } toml::table* mod_provider_table = nullptr; if ((mod_provider_table = update_table[ModPlatform::ProviderCapabilities::name(Provider::FLAME)].as_table())) { mod.provider = Provider::FLAME; mod.file_id = intEntry(*mod_provider_table, "file-id"); mod.project_id = intEntry(*mod_provider_table, "project-id"); } else if ((mod_provider_table = update_table[ModPlatform::ProviderCapabilities::name(Provider::MODRINTH)].as_table())) { mod.provider = Provider::MODRINTH; mod.mod_id() = stringEntry(*mod_provider_table, "mod-id"); mod.version() = stringEntry(*mod_provider_table, "version"); } else { qCritical() << QString("No mod provider on mod metadata!"); return {}; } } return mod; } auto V1::getIndexForMod(const QDir& index_dir, QVariant& mod_id) -> Mod { for (auto& file_name : index_dir.entryList(QDir::Filter::Files)) { auto mod = getIndexForMod(index_dir, file_name); if (mod.mod_id() == mod_id) return mod; } return {}; } auto V1::sideToString(Side side) -> QString { switch (side) { case Side::ClientSide: return "client"; case Side::ServerSide: return "server"; case Side::UniversalSide: return "both"; } return {}; } auto V1::stringToSide(QString side) -> Side { if (side == "client") return Side::ClientSide; if (side == "server") return Side::ServerSide; if (side == "both") return Side::UniversalSide; return Side::UniversalSide; } } // namespace Packwiz
13,845
C++
.cpp
341
32.272727
136
0.600788
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,098
ATLPackIndex.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/atlauncher/ATLPackIndex.cpp
/* * Copyright 2020-2021 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright 2021 Petr Mrazek <peterix@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ATLPackIndex.h" #include <QRegularExpression> #include "Json.h" static void loadIndexedVersion(ATLauncher::IndexedVersion& v, QJsonObject& obj) { v.version = Json::requireString(obj, "version"); v.minecraft = Json::requireString(obj, "minecraft"); } void ATLauncher::loadIndexedPack(ATLauncher::IndexedPack& m, QJsonObject& obj) { m.id = Json::requireInteger(obj, "id"); m.position = Json::requireInteger(obj, "position"); m.name = Json::requireString(obj, "name"); m.type = Json::requireString(obj, "type") == "private" ? ATLauncher::PackType::Private : ATLauncher::PackType::Public; auto versionsArr = Json::requireArray(obj, "versions"); for (const auto versionRaw : versionsArr) { auto versionObj = Json::requireObject(versionRaw); ATLauncher::IndexedVersion version; loadIndexedVersion(version, versionObj); m.versions.append(version); } m.system = Json::ensureBoolean(obj, QString("system"), false); m.description = Json::ensureString(obj, "description", ""); m.safeName = Json::requireString(obj, "name").replace(QRegularExpression("[^A-Za-z0-9]"), "").toLower() + ".png"; }
1,858
C++
.cpp
41
41.853659
122
0.724462
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,099
ATLPackInstallTask.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/atlauncher/ATLPackInstallTask.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2020-2021 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright 2021 Petr Mrazek <peterix@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ATLPackInstallTask.h" #include <QtConcurrent> #include <algorithm> #include <quazip/quazip.h> #include "FileSystem.h" #include "Json.h" #include "MMCZip.h" #include "Version.h" #include "meta/Index.h" #include "meta/Version.h" #include "meta/VersionList.h" #include "minecraft/MinecraftInstance.h" #include "minecraft/OneSixVersionFormat.h" #include "minecraft/PackProfile.h" #include "modplatform/atlauncher/ATLPackManifest.h" #include "net/ChecksumValidator.h" #include "settings/INISettingsObject.h" #include "net/ApiDownload.h" #include "Application.h" #include "BuildConfig.h" #include "ui/dialogs/BlockedModsDialog.h" namespace ATLauncher { static Meta::Version::Ptr getComponentVersion(const QString& uid, const QString& version); PackInstallTask::PackInstallTask(UserInteractionSupport* support, QString packName, QString version, InstallMode installMode) { m_support = support; m_pack_name = packName; m_pack_safe_name = packName.replace(QRegularExpression("[^A-Za-z0-9]"), ""); m_version_name = version; m_install_mode = installMode; } bool PackInstallTask::abort() { if (abortable) { return jobPtr->abort(); } return false; } void PackInstallTask::executeTask() { qDebug() << "PackInstallTask::executeTask: " << QThread::currentThreadId(); NetJob::Ptr netJob{ new NetJob("ATLauncher::VersionFetch", APPLICATION->network()) }; auto searchUrl = QString(BuildConfig.ATL_DOWNLOAD_SERVER_URL + "packs/%1/versions/%2/Configs.json").arg(m_pack_safe_name).arg(m_version_name); netJob->addNetAction(Net::ApiDownload::makeByteArray(QUrl(searchUrl), response)); QObject::connect(netJob.get(), &NetJob::succeeded, this, &PackInstallTask::onDownloadSucceeded); QObject::connect(netJob.get(), &NetJob::failed, this, &PackInstallTask::onDownloadFailed); QObject::connect(netJob.get(), &NetJob::aborted, this, &PackInstallTask::onDownloadAborted); jobPtr = netJob; jobPtr->start(); } void PackInstallTask::onDownloadSucceeded() { qDebug() << "PackInstallTask::onDownloadSucceeded: " << QThread::currentThreadId(); jobPtr.reset(); QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from ATLauncher at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response.get(); return; } auto obj = doc.object(); ATLauncher::PackVersion version; try { ATLauncher::loadVersion(version, obj); } catch (const JSONValidationError& e) { emitFailed(tr("Could not understand pack manifest:\n") + e.cause()); return; } m_version = version; // Derived from the installation mode QString message; bool resetDirectory; switch (m_install_mode) { case InstallMode::Reinstall: case InstallMode::Update: message = m_version.messages.update; resetDirectory = true; break; case InstallMode::Install: message = m_version.messages.install; resetDirectory = false; break; default: emitFailed(tr("Unsupported installation mode")); return; } // Display message if one exists if (!message.isEmpty()) m_support->displayMessage(message); auto ver = getComponentVersion("net.minecraft", m_version.minecraft); if (!ver) { emitFailed(tr("Failed to get local metadata index for '%1' v%2").arg("net.minecraft", m_version.minecraft)); return; } minecraftVersion = ver; if (resetDirectory) { deleteExistingFiles(); } if (m_version.noConfigs) { downloadMods(); } else { installConfigs(); } } void PackInstallTask::onDownloadFailed(QString reason) { qDebug() << "PackInstallTask::onDownloadFailed: " << QThread::currentThreadId(); jobPtr.reset(); emitFailed(reason); } void PackInstallTask::onDownloadAborted() { jobPtr.reset(); emitAborted(); } void PackInstallTask::deleteExistingFiles() { setStatus(tr("Deleting existing files...")); // Setup defaults, as per https://wiki.atlauncher.com/pack-admin/xml/delete VersionDeletes deletes; deletes.folders.append(VersionDelete{ "root", "mods%s%" }); deletes.folders.append(VersionDelete{ "root", "configs%s%" }); deletes.folders.append(VersionDelete{ "root", "bin%s%" }); // Setup defaults, as per https://wiki.atlauncher.com/pack-admin/xml/keep VersionKeeps keeps; keeps.files.append(VersionKeep{ "root", "mods%s%PortalGunSounds.pak" }); keeps.folders.append(VersionKeep{ "root", "mods%s%rei_minimap%s%" }); keeps.folders.append(VersionKeep{ "root", "mods%s%VoxelMods%s%" }); keeps.files.append(VersionKeep{ "root", "config%s%NEI.cfg" }); keeps.files.append(VersionKeep{ "root", "options.txt" }); keeps.files.append(VersionKeep{ "root", "servers.dat" }); // Merge with version deletes and keeps for (const auto& item : m_version.deletes.files) deletes.files.append(item); for (const auto& item : m_version.deletes.folders) deletes.folders.append(item); for (const auto& item : m_version.keeps.files) keeps.files.append(item); for (const auto& item : m_version.keeps.folders) keeps.folders.append(item); auto getPathForBase = [this](const QString& base) { auto minecraftPath = FS::PathCombine(m_stagingPath, "minecraft"); if (base == "root") { return minecraftPath; } else if (base == "config") { return FS::PathCombine(minecraftPath, "config"); } else { qWarning() << "Unrecognised base path" << base; return minecraftPath; } }; auto convertToSystemPath = [](const QString& path) { auto t = path; t.replace("%s%", QDir::separator()); return t; }; auto shouldKeep = [keeps, getPathForBase, convertToSystemPath](const QString& fullPath) { for (const auto& item : keeps.files) { auto basePath = getPathForBase(item.base); auto targetPath = convertToSystemPath(item.target); auto path = FS::PathCombine(basePath, targetPath); if (fullPath == path) { return true; } } for (const auto& item : keeps.folders) { auto basePath = getPathForBase(item.base); auto targetPath = convertToSystemPath(item.target); auto path = FS::PathCombine(basePath, targetPath); if (fullPath.startsWith(path)) { return true; } } return false; }; // Keep track of files to delete QSet<QString> filesToDelete; for (const auto& item : deletes.files) { auto basePath = getPathForBase(item.base); auto targetPath = convertToSystemPath(item.target); auto fullPath = FS::PathCombine(basePath, targetPath); if (shouldKeep(fullPath)) continue; filesToDelete.insert(fullPath); } for (const auto& item : deletes.folders) { auto basePath = getPathForBase(item.base); auto targetPath = convertToSystemPath(item.target); auto fullPath = FS::PathCombine(basePath, targetPath); QDirIterator it(fullPath, QDirIterator::Subdirectories); while (it.hasNext()) { auto path = it.next(); if (shouldKeep(path)) continue; filesToDelete.insert(path); } } // Delete the files for (const auto& item : filesToDelete) { FS::deletePath(item); } } QString PackInstallTask::getDirForModType(ModType type, QString raw) { switch (type) { // Mod types that can either be ignored at this stage, or ignored // completely. case ModType::Root: case ModType::Extract: case ModType::Decomp: case ModType::TexturePackExtract: case ModType::ResourcePackExtract: case ModType::MCPC: return Q_NULLPTR; case ModType::Forge: // Forge detection happens later on, if it cannot be detected it will // install a jarmod component. case ModType::Jar: return "jarmods"; case ModType::Mods: return "mods"; case ModType::Flan: return "Flan"; case ModType::Dependency: return FS::PathCombine("mods", m_version.minecraft); case ModType::Ic2Lib: return FS::PathCombine("mods", "ic2"); case ModType::DenLib: return FS::PathCombine("mods", "denlib"); case ModType::Coremods: return "coremods"; case ModType::Plugins: return "plugins"; case ModType::TexturePack: return "texturepacks"; case ModType::ResourcePack: return "resourcepacks"; case ModType::ShaderPack: return "shaderpacks"; case ModType::Millenaire: qWarning() << "Unsupported mod type: " + raw; return Q_NULLPTR; case ModType::Unknown: emitFailed(tr("Unknown mod type: %1").arg(raw)); return Q_NULLPTR; } return Q_NULLPTR; } QString PackInstallTask::getVersionForLoader(QString uid) { if (m_version.loader.recommended || m_version.loader.latest || m_version.loader.choose) { auto vlist = APPLICATION->metadataIndex()->get(uid); if (!vlist) { emitFailed(tr("Failed to get local metadata index for %1").arg(uid)); return Q_NULLPTR; } vlist->waitToLoad(); if (m_version.loader.recommended || m_version.loader.latest) { for (int i = 0; i < vlist->versions().size(); i++) { auto version = vlist->versions().at(i); auto reqs = version->requiredSet(); // filter by minecraft version, if the loader depends on a certain version. // not all mod loaders depend on a given Minecraft version, so we won't do this // filtering for those loaders. if (m_version.loader.type != "fabric") { auto iter = std::find_if(reqs.begin(), reqs.end(), [](const Meta::Require& req) { return req.uid == "net.minecraft"; }); if (iter == reqs.end()) continue; if (iter->equalsVersion != m_version.minecraft) continue; } if (m_version.loader.recommended) { // first recommended build we find, we use. if (!version->isRecommended()) continue; } return version->descriptor(); } emitFailed(tr("Failed to find version for %1 loader").arg(m_version.loader.type)); return Q_NULLPTR; } else if (m_version.loader.choose) { // Fabric Loader doesn't depend on a given Minecraft version. if (m_version.loader.type == "fabric") { return m_support->chooseVersion(vlist, Q_NULLPTR); } return m_support->chooseVersion(vlist, m_version.minecraft); } } if (m_version.loader.version == Q_NULLPTR || m_version.loader.version.isEmpty()) { emitFailed(tr("No loader version set for modpack!")); return Q_NULLPTR; } return m_version.loader.version; } QString PackInstallTask::detectLibrary(VersionLibrary library) { // Try to detect what the library is if (!library.server.isEmpty() && library.server.split("/").length() >= 3) { auto lastSlash = library.server.lastIndexOf("/"); auto locationAndVersion = library.server.mid(0, lastSlash); auto fileName = library.server.mid(lastSlash + 1); lastSlash = locationAndVersion.lastIndexOf("/"); auto location = locationAndVersion.mid(0, lastSlash); auto version = locationAndVersion.mid(lastSlash + 1); lastSlash = location.lastIndexOf("/"); auto group = location.mid(0, lastSlash).replace("/", "."); auto artefact = location.mid(lastSlash + 1); return group + ":" + artefact + ":" + version; } if (library.file.contains("-")) { auto lastSlash = library.file.lastIndexOf("-"); auto name = library.file.mid(0, lastSlash); auto version = library.file.mid(lastSlash + 1).remove(".jar"); if (name == QString("guava")) { return "com.google.guava:guava:" + version; } else if (name == QString("commons-lang3")) { return "org.apache.commons:commons-lang3:" + version; } } return "org.multimc.atlauncher:" + library.md5 + ":1"; } bool PackInstallTask::createLibrariesComponent(QString instanceRoot, std::shared_ptr<PackProfile> profile) { if (m_version.libraries.isEmpty()) { return true; } QList<GradleSpecifier> exempt; for (const auto& componentUid : componentsToInstall.keys()) { auto componentVersion = componentsToInstall.value(componentUid); for (const auto& library : componentVersion->data()->libraries) { GradleSpecifier lib(library->rawName()); exempt.append(lib); } } { for (const auto& library : minecraftVersion->data()->libraries) { GradleSpecifier lib(library->rawName()); exempt.append(lib); } } auto uuid = QUuid::createUuid(); auto id = uuid.toString().remove('{').remove('}'); auto target_id = "org.multimc.atlauncher." + id; auto patchDir = FS::PathCombine(instanceRoot, "patches"); if (!FS::ensureFolderPathExists(patchDir)) { return false; } auto patchFileName = FS::PathCombine(patchDir, target_id + ".json"); auto f = std::make_shared<VersionFile>(); f->name = m_pack_name + " " + m_version_name + " (libraries)"; const static QMap<QString, QString> liteLoaderMap = { { "61179803bcd5fb7790789b790908663d", "1.12-SNAPSHOT" }, { "1420785ecbfed5aff4a586c5c9dd97eb", "1.12.2-SNAPSHOT" }, { "073f68e2fcb518b91fd0d99462441714", "1.6.2_03" }, { "10a15b52fc59b1bfb9c05b56de1097d6", "1.6.2_02" }, { "b52f90f08303edd3d4c374e268a5acf1", "1.6.2_04" }, { "ea747e24e03e24b7cad5bc8a246e0319", "1.6.2_01" }, { "55785ccc82c07ff0ba038fe24be63ea2", "1.7.10_01" }, { "63ada46e033d0cb6782bada09ad5ca4e", "1.7.10_04" }, { "7983e4b28217c9ae8569074388409c86", "1.7.10_03" }, { "c09882458d74fe0697c7681b8993097e", "1.7.10_02" }, { "db7235aefd407ac1fde09a7baba50839", "1.7.10_00" }, { "6e9028816027f53957bd8fcdfabae064", "1.8" }, { "5e732dc446f9fe2abe5f9decaec40cde", "1.10-SNAPSHOT" }, { "3a98b5ed95810bf164e71c1a53be568d", "1.11.2-SNAPSHOT" }, { "ba8e6285966d7d988a96496f48cbddaa", "1.8.9-SNAPSHOT" }, { "8524af3ac3325a82444cc75ae6e9112f", "1.11-SNAPSHOT" }, { "53639d52340479ccf206a04f5e16606f", "1.5.2_01" }, { "1fcdcf66ce0a0806b7ad8686afdce3f7", "1.6.4_00" }, { "531c116f71ae2b11033f9a11a0f8e668", "1.6.4_01" }, { "4009eeb99c9068f608d3483a6439af88", "1.7.2_03" }, { "66f343354b8417abce1a10d557d2c6e9", "1.7.2_04" }, { "ab554c21f28fbc4ae9b098bcb5f4cceb", "1.7.2_05" }, { "e1d76a05a3723920e2f80a5e66c45f16", "1.7.2_02" }, { "00318cb0c787934d523f63cdfe8ddde4", "1.9-SNAPSHOT" }, { "986fd1ee9525cb0dcab7609401cef754", "1.9.4-SNAPSHOT" }, { "571ad5e6edd5ff40259570c9be588bb5", "1.9.4" }, { "1cdd72f7232e45551f16cc8ffd27ccf3", "1.10.2-SNAPSHOT" }, { "8a7c21f32d77ee08b393dd3921ced8eb", "1.10.2" }, { "b9bef8abc8dc309069aeba6fbbe58980", "1.12.1-SNAPSHOT" } }; for (const auto& lib : m_version.libraries) { // If the library is LiteLoader, we need to ignore it and handle it separately. if (liteLoaderMap.contains(lib.md5)) { auto ver = getComponentVersion("com.mumfrey.liteloader", liteLoaderMap.value(lib.md5)); if (ver) { componentsToInstall.insert("com.mumfrey.liteloader", ver); continue; } } auto libName = detectLibrary(lib); GradleSpecifier libSpecifier(libName); bool libExempt = false; for (const auto& existingLib : exempt) { if (libSpecifier.matchName(existingLib)) { // If the pack specifies a newer version of the lib, use that! libExempt = Version(libSpecifier.version()) >= Version(existingLib.version()); } } if (libExempt) continue; auto library = std::make_shared<Library>(); library->setRawName(libName); switch (lib.download) { case DownloadType::Server: library->setAbsoluteUrl(BuildConfig.ATL_DOWNLOAD_SERVER_URL + lib.url); break; case DownloadType::Direct: library->setAbsoluteUrl(lib.url); break; case DownloadType::Browser: case DownloadType::Unknown: emitFailed(tr("Unknown or unsupported download type: %1").arg(lib.download_raw)); return false; } f->libraries.append(library); } if (f->libraries.isEmpty()) { return true; } QFile file(patchFileName); if (!file.open(QFile::WriteOnly)) { qCritical() << "Error opening" << file.fileName() << "for reading:" << file.errorString(); return false; } file.write(OneSixVersionFormat::versionFileToJson(f).toJson()); file.close(); profile->appendComponent(ComponentPtr{ new Component(profile.get(), target_id, f) }); return true; } bool PackInstallTask::createPackComponent(QString instanceRoot, std::shared_ptr<PackProfile> profile) { if (m_version.mainClass.mainClass.isEmpty() && m_version.extraArguments.arguments.isEmpty()) { return true; } auto mainClass = m_version.mainClass.mainClass; auto extraArguments = m_version.extraArguments.arguments; auto hasMainClassDepends = !m_version.mainClass.depends.isEmpty(); auto hasExtraArgumentsDepends = !m_version.extraArguments.depends.isEmpty(); if (hasMainClassDepends || hasExtraArgumentsDepends) { QSet<QString> mods; for (const auto& item : m_version.mods) { mods.insert(item.name); } if (hasMainClassDepends && !mods.contains(m_version.mainClass.depends)) { mainClass = ""; } if (hasExtraArgumentsDepends && !mods.contains(m_version.extraArguments.depends)) { extraArguments = ""; } } if (mainClass.isEmpty() && extraArguments.isEmpty()) { return true; } auto uuid = QUuid::createUuid(); auto id = uuid.toString().remove('{').remove('}'); auto target_id = "org.multimc.atlauncher." + id; auto patchDir = FS::PathCombine(instanceRoot, "patches"); if (!FS::ensureFolderPathExists(patchDir)) { return false; } auto patchFileName = FS::PathCombine(patchDir, target_id + ".json"); QStringList mainClasses; QStringList tweakers; for (const auto& componentUid : componentsToInstall.keys()) { auto componentVersion = componentsToInstall.value(componentUid); if (componentVersion->data()->mainClass != QString("")) { mainClasses.append(componentVersion->data()->mainClass); } tweakers.append(componentVersion->data()->addTweakers); } auto f = std::make_shared<VersionFile>(); f->name = m_pack_name + " " + m_version_name; if (!mainClass.isEmpty() && !mainClasses.contains(mainClass)) { f->mainClass = mainClass; } // Parse out tweakers auto args = extraArguments.split(" "); QString previous; for (auto arg : args) { if (arg.startsWith("--tweakClass=") || previous == "--tweakClass") { auto tweakClass = arg.remove("--tweakClass="); if (tweakers.contains(tweakClass)) continue; f->addTweakers.append(tweakClass); } previous = arg; } if (f->mainClass == QString() && f->addTweakers.isEmpty()) { return true; } QFile file(patchFileName); if (!file.open(QFile::WriteOnly)) { qCritical() << "Error opening" << file.fileName() << "for reading:" << file.errorString(); return false; } file.write(OneSixVersionFormat::versionFileToJson(f).toJson()); file.close(); profile->appendComponent(ComponentPtr{ new Component(profile.get(), target_id, f) }); return true; } void PackInstallTask::installConfigs() { qDebug() << "PackInstallTask::installConfigs: " << QThread::currentThreadId(); setStatus(tr("Downloading configs...")); jobPtr.reset(new NetJob(tr("Config download"), APPLICATION->network())); auto path = QString("Configs/%1/%2.zip").arg(m_pack_safe_name).arg(m_version_name); auto url = QString(BuildConfig.ATL_DOWNLOAD_SERVER_URL + "packs/%1/versions/%2/Configs.zip").arg(m_pack_safe_name).arg(m_version_name); auto entry = APPLICATION->metacache()->resolveEntry("ATLauncherPacks", path); entry->setStale(true); auto dl = Net::ApiDownload::makeCached(url, entry); if (!m_version.configs.sha1.isEmpty()) { dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, m_version.configs.sha1)); } jobPtr->addNetAction(dl); archivePath = entry->getFullPath(); connect(jobPtr.get(), &NetJob::succeeded, this, [this]() { abortable = false; jobPtr.reset(); extractConfigs(); }); connect(jobPtr.get(), &NetJob::failed, [this](QString reason) { abortable = false; jobPtr.reset(); emitFailed(reason); }); connect(jobPtr.get(), &NetJob::progress, [this](qint64 current, qint64 total) { abortable = true; setProgress(current, total); }); connect(jobPtr.get(), &NetJob::stepProgress, this, &PackInstallTask::propagateStepProgress); connect(jobPtr.get(), &NetJob::aborted, [this] { abortable = false; jobPtr.reset(); emitAborted(); }); jobPtr->start(); } void PackInstallTask::extractConfigs() { qDebug() << "PackInstallTask::extractConfigs: " << QThread::currentThreadId(); setStatus(tr("Extracting configs...")); QDir extractDir(m_stagingPath); QuaZip packZip(archivePath); if (!packZip.open(QuaZip::mdUnzip)) { emitFailed(tr("Failed to open pack configs %1!").arg(archivePath)); return; } #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) m_extractFuture = QtConcurrent::run(QThreadPool::globalInstance(), QOverload<QString, QString>::of(MMCZip::extractDir), archivePath, extractDir.absolutePath() + "/minecraft"); #else m_extractFuture = QtConcurrent::run(QThreadPool::globalInstance(), MMCZip::extractDir, archivePath, extractDir.absolutePath() + "/minecraft"); #endif connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::finished, this, [this]() { downloadMods(); }); connect(&m_extractFutureWatcher, &QFutureWatcher<QStringList>::canceled, this, [this]() { emitAborted(); }); m_extractFutureWatcher.setFuture(m_extractFuture); } void PackInstallTask::downloadMods() { qDebug() << "PackInstallTask::installMods: " << QThread::currentThreadId(); QVector<ATLauncher::VersionMod> optionalMods; for (const auto& mod : m_version.mods) { if (mod.optional) { optionalMods.push_back(mod); } } // Select optional mods, if pack contains any QVector<QString> selectedMods; if (!optionalMods.isEmpty()) { setStatus(tr("Selecting optional mods...")); auto mods = m_support->chooseOptionalMods(m_version, optionalMods); if (!mods.has_value()) { emitAborted(); return; } selectedMods = mods.value(); } setStatus(tr("Downloading mods...")); jarmods.clear(); jobPtr.reset(new NetJob(tr("Mod download"), APPLICATION->network())); QList<VersionMod> blocked_mods; for (const auto& mod : m_version.mods) { // skip non-client mods if (!mod.client) continue; // skip optional mods that were not selected if (mod.optional && !selectedMods.contains(mod.name)) continue; QString url; switch (mod.download) { case DownloadType::Server: url = BuildConfig.ATL_DOWNLOAD_SERVER_URL + mod.url; break; case DownloadType::Browser: { blocked_mods.append(mod); continue; } case DownloadType::Direct: url = mod.url; break; case DownloadType::Unknown: emitFailed(tr("Unknown download type: %1").arg(mod.download_raw)); return; } QFileInfo fileName(mod.file); auto cacheName = fileName.completeBaseName() + "-" + mod.md5 + "." + fileName.suffix(); if (mod.type == ModType::Extract || mod.type == ModType::TexturePackExtract || mod.type == ModType::ResourcePackExtract) { auto entry = APPLICATION->metacache()->resolveEntry("ATLauncherPacks", cacheName); entry->setStale(true); modsToExtract.insert(entry->getFullPath(), mod); auto dl = Net::ApiDownload::makeCached(url, entry); if (!mod.md5.isEmpty()) { dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Md5, mod.md5)); } jobPtr->addNetAction(dl); } else if (mod.type == ModType::Decomp) { auto entry = APPLICATION->metacache()->resolveEntry("ATLauncherPacks", cacheName); entry->setStale(true); modsToDecomp.insert(entry->getFullPath(), mod); auto dl = Net::ApiDownload::makeCached(url, entry); if (!mod.md5.isEmpty()) { dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Md5, mod.md5)); } jobPtr->addNetAction(dl); } else { auto relpath = getDirForModType(mod.type, mod.type_raw); if (relpath == Q_NULLPTR) continue; auto entry = APPLICATION->metacache()->resolveEntry("ATLauncherPacks", cacheName); entry->setStale(true); auto dl = Net::ApiDownload::makeCached(url, entry); if (!mod.md5.isEmpty()) { dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Md5, mod.md5)); } jobPtr->addNetAction(dl); auto path = FS::PathCombine(m_stagingPath, "minecraft", relpath, mod.file); if (mod.type == ModType::Forge) { auto ver = getComponentVersion("net.minecraftforge", mod.version); if (ver) { componentsToInstall.insert("net.minecraftforge", ver); continue; } qDebug() << "Jarmod: " + path; jarmods.push_back(path); } if (mod.type == ModType::Jar) { qDebug() << "Jarmod: " + path; jarmods.push_back(path); } // Download after Forge handling, to avoid downloading Forge twice. qDebug() << "Will download" << url << "to" << path; modsToCopy[entry->getFullPath()] = path; } } if (!blocked_mods.isEmpty()) { QList<BlockedMod> mods; for (auto mod : blocked_mods) { BlockedMod blocked_mod; blocked_mod.name = mod.file; blocked_mod.websiteUrl = mod.url; blocked_mod.hash = mod.md5; blocked_mod.matched = false; blocked_mod.localPath = ""; mods.append(blocked_mod); } qWarning() << "Blocked mods found, displaying mod list"; BlockedModsDialog message_dialog(nullptr, tr("Blocked mods found"), tr("The following files are not available for download in third party launchers.<br/>" "You will need to manually download them and add them to the instance."), mods, "md5"); message_dialog.setModal(true); if (message_dialog.exec()) { qDebug() << "Post dialog blocked mods list: " << mods; for (auto blocked : mods) { if (!blocked.matched) { qDebug() << blocked.name << "was not matched to a local file, skipping copy"; continue; } auto modIter = std::find_if(blocked_mods.begin(), blocked_mods.end(), [blocked](const VersionMod& mod) { return mod.url == blocked.websiteUrl; }); if (modIter == blocked_mods.end()) continue; auto mod = *modIter; if (mod.type == ModType::Extract || mod.type == ModType::TexturePackExtract || mod.type == ModType::ResourcePackExtract) { modsToExtract.insert(blocked.localPath, mod); } else if (mod.type == ModType::Decomp) { modsToDecomp.insert(blocked.localPath, mod); } else { auto relpath = getDirForModType(mod.type, mod.type_raw); if (relpath == Q_NULLPTR) continue; auto path = FS::PathCombine(m_stagingPath, "minecraft", relpath, mod.file); if (mod.type == ModType::Forge) { auto ver = getComponentVersion("net.minecraftforge", mod.version); if (ver) { componentsToInstall.insert("net.minecraftforge", ver); continue; } qDebug() << "Jarmod: " + path; jarmods.push_back(path); } if (mod.type == ModType::Jar) { qDebug() << "Jarmod: " + path; jarmods.push_back(path); } modsToCopy[blocked.localPath] = path; } } } else { emitFailed(tr("Unknown download type: %1").arg("browser")); return; } } connect(jobPtr.get(), &NetJob::succeeded, this, &PackInstallTask::onModsDownloaded); connect(jobPtr.get(), &NetJob::progress, [this](qint64 current, qint64 total) { setDetails(tr("%1 out of %2 complete").arg(current).arg(total)); abortable = true; setProgress(current, total); }); connect(jobPtr.get(), &NetJob::stepProgress, this, &PackInstallTask::propagateStepProgress); connect(jobPtr.get(), &NetJob::aborted, &PackInstallTask::emitAborted); connect(jobPtr.get(), &NetJob::failed, &PackInstallTask::emitFailed); jobPtr->start(); } void PackInstallTask::onModsDownloaded() { abortable = false; qDebug() << "PackInstallTask::onModsDownloaded: " << QThread::currentThreadId(); jobPtr.reset(); if (!modsToExtract.empty() || !modsToDecomp.empty() || !modsToCopy.empty()) { #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) m_modExtractFuture = QtConcurrent::run(QThreadPool::globalInstance(), &PackInstallTask::extractMods, this, modsToExtract, modsToDecomp, modsToCopy); #else m_modExtractFuture = QtConcurrent::run(QThreadPool::globalInstance(), this, &PackInstallTask::extractMods, modsToExtract, modsToDecomp, modsToCopy); #endif connect(&m_modExtractFutureWatcher, &QFutureWatcher<QStringList>::finished, this, &PackInstallTask::onModsExtracted); connect(&m_modExtractFutureWatcher, &QFutureWatcher<QStringList>::canceled, this, &PackInstallTask::emitAborted); m_modExtractFutureWatcher.setFuture(m_modExtractFuture); } else { install(); } } void PackInstallTask::onModsExtracted() { qDebug() << "PackInstallTask::onModsExtracted: " << QThread::currentThreadId(); if (m_modExtractFuture.result()) { install(); } else { emitFailed(tr("Failed to extract mods...")); } } bool PackInstallTask::extractMods(const QMap<QString, VersionMod>& toExtract, const QMap<QString, VersionMod>& toDecomp, const QMap<QString, QString>& toCopy) { qDebug() << "PackInstallTask::extractMods: " << QThread::currentThreadId(); setStatus(tr("Extracting mods...")); for (auto iter = toExtract.begin(); iter != toExtract.end(); iter++) { auto& modPath = iter.key(); auto& mod = iter.value(); QString extractToDir; if (mod.type == ModType::Extract) { extractToDir = getDirForModType(mod.extractTo, mod.extractTo_raw); } else if (mod.type == ModType::TexturePackExtract) { extractToDir = FS::PathCombine("texturepacks", "extracted"); } else if (mod.type == ModType::ResourcePackExtract) { extractToDir = FS::PathCombine("resourcepacks", "extracted"); } QDir extractDir(m_stagingPath); auto extractToPath = FS::PathCombine(extractDir.absolutePath(), "minecraft", extractToDir); QString folderToExtract = ""; if (mod.type == ModType::Extract) { folderToExtract = mod.extractFolder; folderToExtract.remove(QRegularExpression("^/")); } qDebug() << "Extracting " + mod.file + " to " + extractToDir; if (!MMCZip::extractDir(modPath, folderToExtract, extractToPath)) { // assume error return false; } } for (auto iter = toDecomp.begin(); iter != toDecomp.end(); iter++) { auto& modPath = iter.key(); auto& mod = iter.value(); auto extractToDir = getDirForModType(mod.decompType, mod.decompType_raw); QDir extractDir(m_stagingPath); auto extractToPath = FS::PathCombine(extractDir.absolutePath(), "minecraft", extractToDir, mod.decompFile); qDebug() << "Extracting " + mod.decompFile + " to " + extractToDir; if (!MMCZip::extractFile(modPath, mod.decompFile, extractToPath)) { qWarning() << "Failed to extract" << mod.decompFile; return false; } } for (auto iter = toCopy.begin(); iter != toCopy.end(); iter++) { auto& from = iter.key(); auto& to = iter.value(); // If the file already exists, assume the mod is the correct copy - and remove // the copy from the Configs.zip QFileInfo fileInfo(to); if (fileInfo.exists()) { if (!FS::deletePath(to)) { qWarning() << "Failed to delete" << to; return false; } } FS::copy fileCopyOperation(from, to); if (!fileCopyOperation()) { qWarning() << "Failed to copy" << from << "to" << to; return false; } } return true; } void PackInstallTask::install() { qDebug() << "PackInstallTask::install: " << QThread::currentThreadId(); setStatus(tr("Installing modpack")); auto instanceConfigPath = FS::PathCombine(m_stagingPath, "instance.cfg"); auto instanceSettings = std::make_shared<INISettingsObject>(instanceConfigPath); instanceSettings->suspendSave(); MinecraftInstance instance(m_globalSettings, instanceSettings, m_stagingPath); auto components = instance.getPackProfile(); components->buildingFromScratch(); // Use a component to add libraries BEFORE Minecraft if (!createLibrariesComponent(instance.instanceRoot(), components)) { emitFailed(tr("Failed to create libraries component")); return; } // Minecraft components->setComponentVersion("net.minecraft", m_version.minecraft, true); // Loader if (m_version.loader.type == QString("forge")) { auto version = getVersionForLoader("net.minecraftforge"); if (version == Q_NULLPTR) return; components->setComponentVersion("net.minecraftforge", version); } else if (m_version.loader.type == QString("neoforge")) { auto version = getVersionForLoader("net.neoforged"); if (version == Q_NULLPTR) return; components->setComponentVersion("net.neoforged", version); } else if (m_version.loader.type == QString("fabric")) { auto version = getVersionForLoader("net.fabricmc.fabric-loader"); if (version == Q_NULLPTR) return; components->setComponentVersion("net.fabricmc.fabric-loader", version); } else if (m_version.loader.type != QString()) { emitFailed(tr("Unknown loader type: ") + m_version.loader.type); return; } for (const auto& componentUid : componentsToInstall.keys()) { auto version = componentsToInstall.value(componentUid); components->setComponentVersion(componentUid, version->version()); } components->installJarMods(jarmods); // Use a component to fill in the rest of the data // todo: use more detection if (!createPackComponent(instance.instanceRoot(), components)) { emitFailed(tr("Failed to create pack component")); return; } components->saveNow(); instance.setName(name()); instance.setIconKey(m_instIcon); instance.setManagedPack("atlauncher", m_pack_safe_name, m_pack_name, m_version_name, m_version_name); instanceSettings->resumeSave(); jarmods.clear(); emitSucceeded(); } static Meta::Version::Ptr getComponentVersion(const QString& uid, const QString& version) { return APPLICATION->metadataIndex()->getLoadedVersion(uid, version); } } // namespace ATLauncher
39,806
C++
.cpp
902
35.327051
140
0.621724
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,100
ATLShareCode.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/atlauncher/ATLShareCode.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ATLShareCode.h" #include "Json.h" namespace ATLauncher { static void loadShareCodeMod(ShareCodeMod& m, QJsonObject& obj) { m.selected = Json::requireBoolean(obj, "selected"); m.name = Json::requireString(obj, "name"); } static void loadShareCode(ShareCode& c, QJsonObject& obj) { c.pack = Json::requireString(obj, "pack"); c.version = Json::requireString(obj, "version"); auto mods = Json::requireObject(obj, "mods"); auto optional = Json::requireArray(mods, "optional"); for (const auto modRaw : optional) { auto modObj = Json::requireObject(modRaw); ShareCodeMod mod; loadShareCodeMod(mod, modObj); c.mods.append(mod); } } void loadShareCodeResponse(ShareCodeResponse& r, QJsonObject& obj) { r.error = Json::requireBoolean(obj, "error"); r.code = Json::requireInteger(obj, "code"); if (obj.contains("message") && !obj.value("message").isNull()) r.message = Json::requireString(obj, "message"); if (!r.error) { auto dataRaw = Json::requireObject(obj, "data"); loadShareCode(r.data, dataRaw); } } } // namespace ATLauncher
1,900
C++
.cpp
50
34.34
74
0.705435
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,101
ATLPackManifest.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/atlauncher/ATLPackManifest.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2022 Jamie Mansfield <jmansfield@cadixdev.org> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright 2020-2021 Jamie Mansfield <jmansfield@cadixdev.org> * Copyright 2021 Petr Mrazek <peterix@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ATLPackManifest.h" #include "Json.h" static ATLauncher::DownloadType parseDownloadType(QString rawType) { if (rawType == QString("server")) { return ATLauncher::DownloadType::Server; } else if (rawType == QString("browser")) { return ATLauncher::DownloadType::Browser; } else if (rawType == QString("direct")) { return ATLauncher::DownloadType::Direct; } return ATLauncher::DownloadType::Unknown; } static ATLauncher::ModType parseModType(QString rawType) { // See https://wiki.atlauncher.com/mod_types if (rawType == QString("root")) { return ATLauncher::ModType::Root; } else if (rawType == QString("forge")) { return ATLauncher::ModType::Forge; } else if (rawType == QString("jar")) { return ATLauncher::ModType::Jar; } else if (rawType == QString("mods")) { return ATLauncher::ModType::Mods; } else if (rawType == QString("flan")) { return ATLauncher::ModType::Flan; } else if (rawType == QString("dependency") || rawType == QString("depandency")) { return ATLauncher::ModType::Dependency; } else if (rawType == QString("ic2lib")) { return ATLauncher::ModType::Ic2Lib; } else if (rawType == QString("denlib")) { return ATLauncher::ModType::DenLib; } else if (rawType == QString("coremods")) { return ATLauncher::ModType::Coremods; } else if (rawType == QString("mcpc")) { return ATLauncher::ModType::MCPC; } else if (rawType == QString("plugins")) { return ATLauncher::ModType::Plugins; } else if (rawType == QString("extract")) { return ATLauncher::ModType::Extract; } else if (rawType == QString("decomp")) { return ATLauncher::ModType::Decomp; } else if (rawType == QString("texturepack")) { return ATLauncher::ModType::TexturePack; } else if (rawType == QString("resourcepack")) { return ATLauncher::ModType::ResourcePack; } else if (rawType == QString("shaderpack")) { return ATLauncher::ModType::ShaderPack; } else if (rawType == QString("texturepackextract")) { return ATLauncher::ModType::TexturePackExtract; } else if (rawType == QString("resourcepackextract")) { return ATLauncher::ModType::ResourcePackExtract; } else if (rawType == QString("millenaire")) { return ATLauncher::ModType::Millenaire; } return ATLauncher::ModType::Unknown; } static void loadVersionLoader(ATLauncher::VersionLoader& p, QJsonObject& obj) { p.type = Json::requireString(obj, "type"); p.choose = Json::ensureBoolean(obj, QString("choose"), false); auto metadata = Json::requireObject(obj, "metadata"); p.latest = Json::ensureBoolean(metadata, QString("latest"), false); p.recommended = Json::ensureBoolean(metadata, QString("recommended"), false); // Minecraft Forge if (p.type == "forge") { p.version = Json::ensureString(metadata, "version", ""); } // Fabric Loader if (p.type == "fabric") { p.version = Json::ensureString(metadata, "loader", ""); } } static void loadVersionLibrary(ATLauncher::VersionLibrary& p, QJsonObject& obj) { p.url = Json::requireString(obj, "url"); p.file = Json::requireString(obj, "file"); p.md5 = Json::requireString(obj, "md5"); p.download_raw = Json::requireString(obj, "download"); p.download = parseDownloadType(p.download_raw); p.server = Json::ensureString(obj, "server", ""); } static void loadVersionConfigs(ATLauncher::VersionConfigs& p, QJsonObject& obj) { p.filesize = Json::requireInteger(obj, "filesize"); p.sha1 = Json::requireString(obj, "sha1"); } static void loadVersionMod(ATLauncher::VersionMod& p, QJsonObject& obj) { p.name = Json::requireString(obj, "name"); p.version = Json::requireString(obj, "version"); p.url = Json::requireString(obj, "url"); p.file = Json::requireString(obj, "file"); p.md5 = Json::ensureString(obj, "md5", ""); p.download_raw = Json::requireString(obj, "download"); p.download = parseDownloadType(p.download_raw); p.type_raw = Json::requireString(obj, "type"); p.type = parseModType(p.type_raw); // This contributes to the Minecraft Forge detection, where we rely on mod.type being "Forge" // when the mod represents Forge. As there is little difference between "Jar" and "Forge, some // packs regretfully use "Jar". This will correct the type to "Forge" in these cases (as best // it can). if (p.name == QString("Minecraft Forge") && p.type == ATLauncher::ModType::Jar) { p.type_raw = "forge"; p.type = ATLauncher::ModType::Forge; } if (obj.contains("extractTo")) { p.extractTo_raw = Json::requireString(obj, "extractTo"); p.extractTo = parseModType(p.extractTo_raw); p.extractFolder = Json::ensureString(obj, "extractFolder", "").replace("%s%", "/"); } if (obj.contains("decompType")) { p.decompType_raw = Json::requireString(obj, "decompType"); p.decompType = parseModType(p.decompType_raw); p.decompFile = Json::requireString(obj, "decompFile"); } p.description = Json::ensureString(obj, QString("description"), ""); p.optional = Json::ensureBoolean(obj, QString("optional"), false); p.recommended = Json::ensureBoolean(obj, QString("recommended"), false); p.selected = Json::ensureBoolean(obj, QString("selected"), false); p.hidden = Json::ensureBoolean(obj, QString("hidden"), false); p.library = Json::ensureBoolean(obj, QString("library"), false); p.group = Json::ensureString(obj, QString("group"), ""); if (obj.contains("depends")) { auto dependsArr = Json::requireArray(obj, "depends"); for (const auto depends : dependsArr) { p.depends.append(Json::requireString(depends)); } } p.colour = Json::ensureString(obj, QString("colour"), ""); p.warning = Json::ensureString(obj, QString("warning"), ""); p.client = Json::ensureBoolean(obj, QString("client"), false); // computed p.effectively_hidden = p.hidden || p.library; } static void loadVersionMessages(ATLauncher::VersionMessages& m, QJsonObject& obj) { m.install = Json::ensureString(obj, "install", ""); m.update = Json::ensureString(obj, "update", ""); } static void loadVersionMainClass(ATLauncher::PackVersionMainClass& m, QJsonObject& obj) { m.mainClass = Json::ensureString(obj, "mainClass", ""); m.depends = Json::ensureString(obj, "depends", ""); } static void loadVersionExtraArguments(ATLauncher::PackVersionExtraArguments& a, QJsonObject& obj) { a.arguments = Json::ensureString(obj, "arguments", ""); a.depends = Json::ensureString(obj, "depends", ""); } static void loadVersionKeep(ATLauncher::VersionKeep& k, QJsonObject& obj) { k.base = Json::requireString(obj, "base"); k.target = Json::requireString(obj, "target"); } static void loadVersionKeeps(ATLauncher::VersionKeeps& k, QJsonObject& obj) { if (obj.contains("files")) { auto files = Json::requireArray(obj, "files"); for (const auto keepRaw : files) { auto keepObj = Json::requireObject(keepRaw); ATLauncher::VersionKeep keep; loadVersionKeep(keep, keepObj); k.files.append(keep); } } if (obj.contains("folders")) { auto folders = Json::requireArray(obj, "folders"); for (const auto keepRaw : folders) { auto keepObj = Json::requireObject(keepRaw); ATLauncher::VersionKeep keep; loadVersionKeep(keep, keepObj); k.folders.append(keep); } } } static void loadVersionDelete(ATLauncher::VersionDelete& d, QJsonObject& obj) { d.base = Json::requireString(obj, "base"); d.target = Json::requireString(obj, "target"); } static void loadVersionDeletes(ATLauncher::VersionDeletes& d, QJsonObject& obj) { if (obj.contains("files")) { auto files = Json::requireArray(obj, "files"); for (const auto deleteRaw : files) { auto deleteObj = Json::requireObject(deleteRaw); ATLauncher::VersionDelete versionDelete; loadVersionDelete(versionDelete, deleteObj); d.files.append(versionDelete); } } if (obj.contains("folders")) { auto folders = Json::requireArray(obj, "folders"); for (const auto deleteRaw : folders) { auto deleteObj = Json::requireObject(deleteRaw); ATLauncher::VersionDelete versionDelete; loadVersionDelete(versionDelete, deleteObj); d.folders.append(versionDelete); } } } void ATLauncher::loadVersion(PackVersion& v, QJsonObject& obj) { v.version = Json::requireString(obj, "version"); v.minecraft = Json::requireString(obj, "minecraft"); v.noConfigs = Json::ensureBoolean(obj, QString("noConfigs"), false); if (obj.contains("mainClass")) { auto main = Json::requireObject(obj, "mainClass"); loadVersionMainClass(v.mainClass, main); } if (obj.contains("extraArguments")) { auto arguments = Json::requireObject(obj, "extraArguments"); loadVersionExtraArguments(v.extraArguments, arguments); } if (obj.contains("loader")) { auto loader = Json::requireObject(obj, "loader"); loadVersionLoader(v.loader, loader); } if (obj.contains("libraries")) { auto libraries = Json::requireArray(obj, "libraries"); for (const auto libraryRaw : libraries) { auto libraryObj = Json::requireObject(libraryRaw); ATLauncher::VersionLibrary target; loadVersionLibrary(target, libraryObj); v.libraries.append(target); } } if (obj.contains("mods")) { auto mods = Json::requireArray(obj, "mods"); for (const auto modRaw : mods) { auto modObj = Json::requireObject(modRaw); ATLauncher::VersionMod mod; loadVersionMod(mod, modObj); v.mods.append(mod); } } if (obj.contains("configs")) { auto configsObj = Json::requireObject(obj, "configs"); loadVersionConfigs(v.configs, configsObj); } auto colourObj = Json::ensureObject(obj, "colours"); for (const auto& key : colourObj.keys()) { v.colours[key] = Json::requireString(colourObj.value(key), "colour"); } auto warningsObj = Json::ensureObject(obj, "warnings"); for (const auto& key : warningsObj.keys()) { v.warnings[key] = Json::requireString(warningsObj.value(key), "warning"); } auto messages = Json::ensureObject(obj, "messages"); loadVersionMessages(v.messages, messages); auto keeps = Json::ensureObject(obj, "keeps"); loadVersionKeeps(v.keeps, keeps); auto deletes = Json::ensureObject(obj, "deletes"); loadVersionDeletes(v.deletes, deletes); }
12,510
C++
.cpp
291
37.257732
98
0.666119
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
29,102
ExportToModList.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/helpers/ExportToModList.cpp
// SPDX-License-Identifier: GPL-3.0-only /* * Prism Launcher - Minecraft Launcher * Copyright (c) 2023 Trial97 <alexandru.tripon97@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ #include "ExportToModList.h" #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> namespace ExportToModList { QString toHTML(QList<Mod*> mods, OptionalData extraData) { QStringList lines; for (auto mod : mods) { auto meta = mod->metadata(); auto modName = mod->name().toHtmlEscaped(); if (extraData & Url) { auto url = mod->homepage().toHtmlEscaped(); if (!url.isEmpty()) modName = QString("<a href=\"%1\">%2</a>").arg(url, modName); } auto line = modName; if (extraData & Version) { auto ver = mod->version(); if (ver.isEmpty() && meta != nullptr) ver = meta->version().toString(); if (!ver.isEmpty()) line += QString(" [%1]").arg(ver.toHtmlEscaped()); } if (extraData & Authors && !mod->authors().isEmpty()) line += " by " + mod->authors().join(", ").toHtmlEscaped(); if (extraData & FileName) line += QString(" (%1)").arg(mod->fileinfo().fileName().toHtmlEscaped()); lines.append(QString("<li>%1</li>").arg(line)); } return QString("<html><body><ul>\n\t%1\n</ul></body></html>").arg(lines.join("\n\t")); } QString toMarkdownEscaped(QString src) { for (auto ch : "\\`*_{}[]<>()#+-.!|") src.replace(ch, QString("\\%1").arg(ch)); return src; } QString toMarkdown(QList<Mod*> mods, OptionalData extraData) { QStringList lines; for (auto mod : mods) { auto meta = mod->metadata(); auto modName = toMarkdownEscaped(mod->name()); if (extraData & Url) { auto url = mod->homepage(); if (!url.isEmpty()) modName = QString("[%1](%2)").arg(modName, url); } auto line = modName; if (extraData & Version) { auto ver = toMarkdownEscaped(mod->version()); if (ver.isEmpty() && meta != nullptr) ver = toMarkdownEscaped(meta->version().toString()); if (!ver.isEmpty()) line += QString(" [%1]").arg(ver); } if (extraData & Authors && !mod->authors().isEmpty()) line += " by " + toMarkdownEscaped(mod->authors().join(", ")); if (extraData & FileName) line += QString(" (%1)").arg(toMarkdownEscaped(mod->fileinfo().fileName())); lines << "- " + line; } return lines.join("\n"); } QString toPlainTXT(QList<Mod*> mods, OptionalData extraData) { QStringList lines; for (auto mod : mods) { auto meta = mod->metadata(); auto modName = mod->name(); auto line = modName; if (extraData & Url) { auto url = mod->homepage(); if (!url.isEmpty()) line += QString(" (%1)").arg(url); } if (extraData & Version) { auto ver = mod->version(); if (ver.isEmpty() && meta != nullptr) ver = meta->version().toString(); if (!ver.isEmpty()) line += QString(" [%1]").arg(ver); } if (extraData & Authors && !mod->authors().isEmpty()) line += " by " + mod->authors().join(", "); if (extraData & FileName) line += QString(" (%1)").arg(mod->fileinfo().fileName()); lines << line; } return lines.join("\n"); } QString toJSON(QList<Mod*> mods, OptionalData extraData) { QJsonArray lines; for (auto mod : mods) { auto meta = mod->metadata(); auto modName = mod->name(); QJsonObject line; line["name"] = modName; if (extraData & Url) { auto url = mod->homepage(); if (!url.isEmpty()) line["url"] = url; } if (extraData & Version) { auto ver = mod->version(); if (ver.isEmpty() && meta != nullptr) ver = meta->version().toString(); if (!ver.isEmpty()) line["version"] = ver; } if (extraData & Authors && !mod->authors().isEmpty()) line["authors"] = QJsonArray::fromStringList(mod->authors()); if (extraData & FileName) line["filename"] = mod->fileinfo().fileName(); lines << line; } QJsonDocument doc; doc.setArray(lines); return doc.toJson(); } QString toCSV(QList<Mod*> mods, OptionalData extraData) { QStringList lines; for (auto mod : mods) { QStringList data; auto meta = mod->metadata(); auto modName = mod->name(); data << modName; if (extraData & Url) data << mod->homepage(); if (extraData & Version) { auto ver = mod->version(); if (ver.isEmpty() && meta != nullptr) ver = meta->version().toString(); data << ver; } if (extraData & Authors) { QString authors; if (mod->authors().length() == 1) authors = mod->authors().back(); else if (mod->authors().length() > 1) authors = QString("\"%1\"").arg(mod->authors().join(",")); data << authors; } if (extraData & FileName) data << mod->fileinfo().fileName(); lines << data.join(","); } return lines.join("\n"); } QString exportToModList(QList<Mod*> mods, Formats format, OptionalData extraData) { switch (format) { case HTML: return toHTML(mods, extraData); case MARKDOWN: return toMarkdown(mods, extraData); case PLAINTXT: return toPlainTXT(mods, extraData); case JSON: return toJSON(mods, extraData); case CSV: return toCSV(mods, extraData); default: { return QString("unknown format:%1").arg(format); } } } QString exportToModList(QList<Mod*> mods, QString lineTemplate) { QStringList lines; for (auto mod : mods) { auto meta = mod->metadata(); auto modName = mod->name(); auto url = mod->homepage(); auto ver = mod->version(); if (ver.isEmpty() && meta != nullptr) ver = meta->version().toString(); auto authors = mod->authors().join(", "); auto filename = mod->fileinfo().fileName(); lines << QString(lineTemplate) .replace("{name}", modName) .replace("{url}", url) .replace("{version}", ver) .replace("{authors}", authors) .replace("{filename}", filename); } return lines.join("\n"); } } // namespace ExportToModList
7,438
C++
.cpp
209
27.110048
90
0.544611
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
29,103
NetworkResourceAPI.cpp
PrismLauncher_PrismLauncher/launcher/modplatform/helpers/NetworkResourceAPI.cpp
// SPDX-FileCopyrightText: 2023 flowln <flowlnlnln@gmail.com> // // SPDX-License-Identifier: GPL-3.0-only #include "NetworkResourceAPI.h" #include <memory> #include "Application.h" #include "net/NetJob.h" #include "modplatform/ModIndex.h" #include "net/ApiDownload.h" Task::Ptr NetworkResourceAPI::searchProjects(SearchArgs&& args, SearchCallbacks&& callbacks) const { auto search_url_optional = getSearchURL(args); if (!search_url_optional.has_value()) { callbacks.on_fail("Failed to create search URL", -1); return nullptr; } auto search_url = search_url_optional.value(); auto response = std::make_shared<QByteArray>(); auto netJob = makeShared<NetJob>(QString("%1::Search").arg(debugName()), APPLICATION->network()); netJob->addNetAction(Net::ApiDownload::makeByteArray(QUrl(search_url), response)); QObject::connect(netJob.get(), &NetJob::succeeded, [this, response, callbacks] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response from " << debugName() << " at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; callbacks.on_fail(parse_error.errorString(), -1); return; } callbacks.on_succeed(doc); }); // Capture a weak_ptr instead of a shared_ptr to avoid circular dependency issues. // This prevents the lambda from extending the lifetime of the shared resource, // as it only temporarily locks the resource when needed. auto weak = netJob.toWeakRef(); QObject::connect(netJob.get(), &NetJob::failed, [weak, callbacks](const QString& reason) { int network_error_code = -1; if (auto netJob = weak.lock()) { if (auto* failed_action = netJob->getFailedActions().at(0); failed_action) network_error_code = failed_action->replyStatusCode(); } callbacks.on_fail(reason, network_error_code); }); QObject::connect(netJob.get(), &NetJob::aborted, [callbacks] { callbacks.on_abort(); }); return netJob; } Task::Ptr NetworkResourceAPI::getProjectInfo(ProjectInfoArgs&& args, ProjectInfoCallbacks&& callbacks) const { auto response = std::make_shared<QByteArray>(); auto job = getProject(args.pack.addonId.toString(), response); QObject::connect(job.get(), &NetJob::succeeded, [response, callbacks, args] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response for mod info at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } callbacks.on_succeed(doc, args.pack); }); QObject::connect(job.get(), &NetJob::failed, [callbacks](QString reason) { callbacks.on_fail(reason); }); QObject::connect(job.get(), &NetJob::aborted, [callbacks] { callbacks.on_abort(); }); return job; } Task::Ptr NetworkResourceAPI::getProjectVersions(VersionSearchArgs&& args, VersionSearchCallbacks&& callbacks) const { auto versions_url_optional = getVersionsURL(args); if (!versions_url_optional.has_value()) return nullptr; auto versions_url = versions_url_optional.value(); auto netJob = makeShared<NetJob>(QString("%1::Versions").arg(args.pack.name), APPLICATION->network()); auto response = std::make_shared<QByteArray>(); netJob->addNetAction(Net::ApiDownload::makeByteArray(versions_url, response)); QObject::connect(netJob.get(), &NetJob::succeeded, [response, callbacks, args] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response for getting versions at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } callbacks.on_succeed(doc, args.pack); }); // Capture a weak_ptr instead of a shared_ptr to avoid circular dependency issues. // This prevents the lambda from extending the lifetime of the shared resource, // as it only temporarily locks the resource when needed. auto weak = netJob.toWeakRef(); QObject::connect(netJob.get(), &NetJob::failed, [weak, callbacks](const QString& reason) { int network_error_code = -1; if (auto netJob = weak.lock()) { if (auto* failed_action = netJob->getFailedActions().at(0); failed_action) network_error_code = failed_action->replyStatusCode(); } callbacks.on_fail(reason, network_error_code); }); return netJob; } Task::Ptr NetworkResourceAPI::getProject(QString addonId, std::shared_ptr<QByteArray> response) const { auto project_url_optional = getInfoURL(addonId); if (!project_url_optional.has_value()) return nullptr; auto project_url = project_url_optional.value(); auto netJob = makeShared<NetJob>(QString("%1::GetProject").arg(addonId), APPLICATION->network()); netJob->addNetAction(Net::ApiDownload::makeByteArray(QUrl(project_url), response)); return netJob; } Task::Ptr NetworkResourceAPI::getDependencyVersion(DependencySearchArgs&& args, DependencySearchCallbacks&& callbacks) const { auto versions_url_optional = getDependencyURL(args); if (!versions_url_optional.has_value()) return nullptr; auto versions_url = versions_url_optional.value(); auto netJob = makeShared<NetJob>(QString("%1::Dependency").arg(args.dependency.addonId.toString()), APPLICATION->network()); auto response = std::make_shared<QByteArray>(); netJob->addNetAction(Net::ApiDownload::makeByteArray(versions_url, response)); QObject::connect(netJob.get(), &NetJob::succeeded, [response, callbacks, args] { QJsonParseError parse_error{}; QJsonDocument doc = QJsonDocument::fromJson(*response, &parse_error); if (parse_error.error != QJsonParseError::NoError) { qWarning() << "Error while parsing JSON response for getting versions at " << parse_error.offset << " reason: " << parse_error.errorString(); qWarning() << *response; return; } callbacks.on_succeed(doc, args.dependency); }); // Capture a weak_ptr instead of a shared_ptr to avoid circular dependency issues. // This prevents the lambda from extending the lifetime of the shared resource, // as it only temporarily locks the resource when needed. auto weak = netJob.toWeakRef(); QObject::connect(netJob.get(), &NetJob::failed, [weak, callbacks](const QString& reason) { int network_error_code = -1; if (auto netJob = weak.lock()) { if (auto* failed_action = netJob->getFailedActions().at(0); failed_action) network_error_code = failed_action->replyStatusCode(); } callbacks.on_fail(reason, network_error_code); }); return netJob; }
7,402
C++
.cpp
144
44.118056
128
0.670683
PrismLauncher/PrismLauncher
5,558
625
571
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false