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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
29,211
|
MSADeviceCodeStep.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/auth/steps/MSADeviceCodeStep.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/>.
*
* 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 "MSADeviceCodeStep.h"
#include <QDateTime>
#include <QUrlQuery>
#include "Application.h"
#include "Json.h"
#include "net/RawHeaderProxy.h"
// https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-device-code
MSADeviceCodeStep::MSADeviceCodeStep(AccountData* data) : AuthStep(data)
{
m_clientId = APPLICATION->getMSAClientID();
connect(&m_expiration_timer, &QTimer::timeout, this, &MSADeviceCodeStep::abort);
connect(&m_pool_timer, &QTimer::timeout, this, &MSADeviceCodeStep::authenticateUser);
}
QString MSADeviceCodeStep::describe()
{
return tr("Logging in with Microsoft account(device code).");
}
void MSADeviceCodeStep::perform()
{
QUrlQuery data;
data.addQueryItem("client_id", m_clientId);
data.addQueryItem("scope", "XboxLive.SignIn XboxLive.offline_access");
auto payload = data.query(QUrl::FullyEncoded).toUtf8();
QUrl url("https://login.microsoftonline.com/consumers/oauth2/v2.0/devicecode");
auto headers = QList<Net::HeaderPair>{
{ "Content-Type", "application/x-www-form-urlencoded" },
{ "Accept", "application/json" },
};
m_response.reset(new QByteArray());
m_request = Net::Upload::makeByteArray(url, m_response, payload);
m_request->addHeaderProxy(new Net::RawHeaderProxy(headers));
m_task.reset(new NetJob("MSADeviceCodeStep", APPLICATION->network()));
m_task->setAskRetry(false);
m_task->addNetAction(m_request);
connect(m_task.get(), &Task::finished, this, &MSADeviceCodeStep::deviceAuthorizationFinished);
m_task->start();
}
struct DeviceAuthorizationResponse {
QString device_code;
QString user_code;
QString verification_uri;
int expires_in;
int interval;
QString error;
QString error_description;
};
DeviceAuthorizationResponse parseDeviceAuthorizationResponse(const QByteArray& data)
{
QJsonParseError err;
QJsonDocument doc = QJsonDocument::fromJson(data, &err);
if (err.error != QJsonParseError::NoError) {
qWarning() << "Failed to parse device authorization response due to err:" << err.errorString();
return {};
}
if (!doc.isObject()) {
qWarning() << "Device authorization response is not an object";
return {};
}
auto obj = doc.object();
return {
Json::ensureString(obj, "device_code"), Json::ensureString(obj, "user_code"), Json::ensureString(obj, "verification_uri"),
Json::ensureInteger(obj, "expires_in"), Json::ensureInteger(obj, "interval"), Json::ensureString(obj, "error"),
Json::ensureString(obj, "error_description"),
};
}
void MSADeviceCodeStep::deviceAuthorizationFinished()
{
auto rsp = parseDeviceAuthorizationResponse(*m_response);
if (!rsp.error.isEmpty() || !rsp.error_description.isEmpty()) {
qWarning() << "Device authorization failed:" << rsp.error;
emit finished(AccountTaskState::STATE_FAILED_HARD,
tr("Device authorization failed: %1").arg(rsp.error_description.isEmpty() ? rsp.error : rsp.error_description));
return;
}
if (!m_request->wasSuccessful() || m_request->error() != QNetworkReply::NoError) {
emit finished(AccountTaskState::STATE_FAILED_HARD, tr("Failed to retrieve device authorization"));
qDebug() << *m_response;
return;
}
if (rsp.device_code.isEmpty() || rsp.user_code.isEmpty() || rsp.verification_uri.isEmpty() || rsp.expires_in == 0) {
emit finished(AccountTaskState::STATE_FAILED_HARD, tr("Device authorization failed: required fields missing"));
return;
}
if (rsp.interval != 0) {
interval = rsp.interval;
}
m_device_code = rsp.device_code;
emit authorizeWithBrowser(rsp.verification_uri, rsp.user_code, rsp.expires_in);
m_expiration_timer.setTimerType(Qt::VeryCoarseTimer);
m_expiration_timer.setInterval(rsp.expires_in * 1000);
m_expiration_timer.setSingleShot(true);
m_expiration_timer.start();
m_pool_timer.setTimerType(Qt::VeryCoarseTimer);
m_pool_timer.setSingleShot(true);
startPoolTimer();
}
void MSADeviceCodeStep::abort()
{
m_expiration_timer.stop();
m_pool_timer.stop();
if (m_request) {
m_request->abort();
}
m_is_aborted = true;
emit finished(AccountTaskState::STATE_FAILED_HARD, tr("Task aborted"));
}
void MSADeviceCodeStep::startPoolTimer()
{
if (m_is_aborted) {
return;
}
if (m_expiration_timer.remainingTime() < interval * 1000) {
perform();
return;
}
m_pool_timer.setInterval(interval * 1000);
m_pool_timer.start();
}
void MSADeviceCodeStep::authenticateUser()
{
QUrlQuery data;
data.addQueryItem("client_id", m_clientId);
data.addQueryItem("grant_type", "urn:ietf:params:oauth:grant-type:device_code");
data.addQueryItem("device_code", m_device_code);
auto payload = data.query(QUrl::FullyEncoded).toUtf8();
QUrl url("https://login.microsoftonline.com/consumers/oauth2/v2.0/token");
auto headers = QList<Net::HeaderPair>{
{ "Content-Type", "application/x-www-form-urlencoded" },
{ "Accept", "application/json" },
};
m_response.reset(new QByteArray());
m_request = Net::Upload::makeByteArray(url, m_response, payload);
m_request->addHeaderProxy(new Net::RawHeaderProxy(headers));
connect(m_request.get(), &Task::finished, this, &MSADeviceCodeStep::authenticationFinished);
m_request->setNetwork(APPLICATION->network());
m_request->start();
}
struct AuthenticationResponse {
QString access_token;
QString token_type;
QString refresh_token;
int expires_in;
QString error;
QString error_description;
QVariantMap extra;
};
AuthenticationResponse parseAuthenticationResponse(const QByteArray& data)
{
QJsonParseError err;
QJsonDocument doc = QJsonDocument::fromJson(data, &err);
if (err.error != QJsonParseError::NoError) {
qWarning() << "Failed to parse device authorization response due to err:" << err.errorString();
return {};
}
if (!doc.isObject()) {
qWarning() << "Device authorization response is not an object";
return {};
}
auto obj = doc.object();
return { Json::ensureString(obj, "access_token"),
Json::ensureString(obj, "token_type"),
Json::ensureString(obj, "refresh_token"),
Json::ensureInteger(obj, "expires_in"),
Json::ensureString(obj, "error"),
Json::ensureString(obj, "error_description"),
obj.toVariantMap() };
}
void MSADeviceCodeStep::authenticationFinished()
{
if (m_request->error() == QNetworkReply::TimeoutError) {
// rfc8628#section-3.5
// "On encountering a connection timeout, clients MUST unilaterally
// reduce their polling frequency before retrying. The use of an
// exponential backoff algorithm to achieve this, such as doubling the
// polling interval on each such connection timeout, is RECOMMENDED."
interval *= 2;
startPoolTimer();
return;
}
auto rsp = parseAuthenticationResponse(*m_response);
if (rsp.error == "slow_down") {
// rfc8628#section-3.5
// "A variant of 'authorization_pending', the authorization request is
// still pending and polling should continue, but the interval MUST
// be increased by 5 seconds for this and all subsequent requests."
interval += 5;
startPoolTimer();
return;
}
if (rsp.error == "authorization_pending") {
// keep trying - rfc8628#section-3.5
// "The authorization request is still pending as the end user hasn't
// yet completed the user-interaction steps (Section 3.3)."
startPoolTimer();
return;
}
if (!rsp.error.isEmpty() || !rsp.error_description.isEmpty()) {
qWarning() << "Device Access failed:" << rsp.error;
emit finished(AccountTaskState::STATE_FAILED_HARD,
tr("Device Access failed: %1").arg(rsp.error_description.isEmpty() ? rsp.error : rsp.error_description));
return;
}
if (!m_request->wasSuccessful() || m_request->error() != QNetworkReply::NoError) {
startPoolTimer(); // it failed so just try again without increasing the interval
return;
}
m_expiration_timer.stop();
m_data->msaClientID = m_clientId;
m_data->msaToken.issueInstant = QDateTime::currentDateTimeUtc();
m_data->msaToken.notAfter = QDateTime::currentDateTime().addSecs(rsp.expires_in);
m_data->msaToken.extra = rsp.extra;
m_data->msaToken.refresh_token = rsp.refresh_token;
m_data->msaToken.token = rsp.access_token;
emit finished(AccountTaskState::STATE_WORKING, tr("Got"));
}
| 10,280
|
C++
|
.cpp
| 249
| 36.036145
| 136
| 0.687394
|
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,212
|
GetSkinStep.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/auth/steps/GetSkinStep.cpp
|
#include "GetSkinStep.h"
#include <QNetworkRequest>
#include "Application.h"
GetSkinStep::GetSkinStep(AccountData* data) : AuthStep(data) {}
QString GetSkinStep::describe()
{
return tr("Getting skin.");
}
void GetSkinStep::perform()
{
QUrl url(m_data->minecraftProfile.skin.url);
m_response.reset(new QByteArray());
m_request = Net::Download::makeByteArray(url, m_response);
m_task.reset(new NetJob("GetSkinStep", APPLICATION->network()));
m_task->setAskRetry(false);
m_task->addNetAction(m_request);
connect(m_task.get(), &Task::finished, this, &GetSkinStep::onRequestDone);
m_task->start();
}
void GetSkinStep::onRequestDone()
{
if (m_request->error() == QNetworkReply::NoError)
m_data->minecraftProfile.skin.data = *m_response;
emit finished(AccountTaskState::STATE_WORKING, tr("Got skin"));
}
| 860
|
C++
|
.cpp
| 25
| 30.88
| 78
| 0.717233
|
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,213
|
EntitlementsStep.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/auth/steps/EntitlementsStep.cpp
|
#include "EntitlementsStep.h"
#include <QList>
#include <QNetworkRequest>
#include <QUrl>
#include <QUuid>
#include <memory>
#include "Application.h"
#include "Logging.h"
#include "minecraft/auth/Parsers.h"
#include "net/Download.h"
#include "net/NetJob.h"
#include "net/RawHeaderProxy.h"
#include "tasks/Task.h"
EntitlementsStep::EntitlementsStep(AccountData* data) : AuthStep(data) {}
QString EntitlementsStep::describe()
{
return tr("Determining game ownership.");
}
void EntitlementsStep::perform()
{
auto uuid = QUuid::createUuid();
m_entitlements_request_id = uuid.toString().remove('{').remove('}');
QUrl url("https://api.minecraftservices.com/entitlements/license?requestId=" + m_entitlements_request_id);
auto headers = QList<Net::HeaderPair>{ { "Content-Type", "application/json" },
{ "Accept", "application/json" },
{ "Authorization", QString("Bearer %1").arg(m_data->yggdrasilToken.token).toUtf8() } };
m_response.reset(new QByteArray());
m_request = Net::Download::makeByteArray(url, m_response);
m_request->addHeaderProxy(new Net::RawHeaderProxy(headers));
m_task.reset(new NetJob("EntitlementsStep", APPLICATION->network()));
m_task->setAskRetry(false);
m_task->addNetAction(m_request);
connect(m_task.get(), &Task::finished, this, &EntitlementsStep::onRequestDone);
m_task->start();
qDebug() << "Getting entitlements...";
}
void EntitlementsStep::onRequestDone()
{
qCDebug(authCredentials()) << *m_response;
// TODO: check presence of same entitlementsRequestId?
// TODO: validate JWTs?
Parsers::parseMinecraftEntitlements(*m_response, m_data->minecraftEntitlement);
emit finished(AccountTaskState::STATE_WORKING, tr("Got entitlements"));
}
| 1,832
|
C++
|
.cpp
| 44
| 36.659091
| 130
| 0.695775
|
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,214
|
MSAStep.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/auth/steps/MSAStep.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 "MSAStep.h"
#include <QAbstractOAuth2>
#include <QNetworkRequest>
#include <QOAuthHttpServerReplyHandler>
#include <QOAuthOobReplyHandler>
#include "Application.h"
#include "BuildConfig.h"
#include "FileSystem.h"
#include <QProcess>
#include <QSettings>
#include <QStandardPaths>
bool isSchemeHandlerRegistered()
{
#ifdef Q_OS_LINUX
QProcess process;
process.start("xdg-mime", { "query", "default", "x-scheme-handler/" + BuildConfig.LAUNCHER_APP_BINARY_NAME });
process.waitForFinished();
QString output = process.readAllStandardOutput().trimmed();
return output.contains(BuildConfig.LAUNCHER_APP_BINARY_NAME);
#elif defined(Q_OS_WIN)
QString regPath = QString("HKEY_CURRENT_USER\\Software\\Classes\\%1").arg(BuildConfig.LAUNCHER_APP_BINARY_NAME);
QSettings settings(regPath, QSettings::NativeFormat);
return settings.contains("shell/open/command/.");
#endif
return true;
}
class CustomOAuthOobReplyHandler : public QOAuthOobReplyHandler {
Q_OBJECT
public:
explicit CustomOAuthOobReplyHandler(QObject* parent = nullptr) : QOAuthOobReplyHandler(parent)
{
connect(APPLICATION, &Application::oauthReplyRecieved, this, &QOAuthOobReplyHandler::callbackReceived);
}
~CustomOAuthOobReplyHandler() override
{
disconnect(APPLICATION, &Application::oauthReplyRecieved, this, &QOAuthOobReplyHandler::callbackReceived);
}
QString callback() const override { return BuildConfig.LAUNCHER_APP_BINARY_NAME + "://oauth/microsoft"; }
};
MSAStep::MSAStep(AccountData* data, bool silent) : AuthStep(data), m_silent(silent)
{
m_clientId = APPLICATION->getMSAClientID();
if (QCoreApplication::applicationFilePath().startsWith("/tmp/.mount_") || APPLICATION->isPortable() || !isSchemeHandlerRegistered())
{
auto replyHandler = new QOAuthHttpServerReplyHandler(this);
replyHandler->setCallbackText(QString(R"XXX(
<noscript>
<meta http-equiv="Refresh" content="0; URL=%1" />
</noscript>
Login Successful, redirecting...
<script>
window.location.replace("%1");
</script>
)XXX")
.arg(BuildConfig.LOGIN_CALLBACK_URL));
oauth2.setReplyHandler(replyHandler);
} else {
oauth2.setReplyHandler(new CustomOAuthOobReplyHandler(this));
}
oauth2.setAuthorizationUrl(QUrl("https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize"));
oauth2.setAccessTokenUrl(QUrl("https://login.microsoftonline.com/consumers/oauth2/v2.0/token"));
oauth2.setScope("XboxLive.SignIn XboxLive.offline_access");
oauth2.setClientIdentifier(m_clientId);
oauth2.setNetworkAccessManager(APPLICATION->network().get());
connect(&oauth2, &QOAuth2AuthorizationCodeFlow::granted, this, [this] {
m_data->msaClientID = oauth2.clientIdentifier();
m_data->msaToken.issueInstant = QDateTime::currentDateTimeUtc();
m_data->msaToken.notAfter = oauth2.expirationAt();
m_data->msaToken.extra = oauth2.extraTokens();
m_data->msaToken.refresh_token = oauth2.refreshToken();
m_data->msaToken.token = oauth2.token();
emit finished(AccountTaskState::STATE_WORKING, tr("Got "));
});
connect(&oauth2, &QOAuth2AuthorizationCodeFlow::authorizeWithBrowser, this, &MSAStep::authorizeWithBrowser);
connect(&oauth2, &QOAuth2AuthorizationCodeFlow::requestFailed, this, [this, silent](const QAbstractOAuth2::Error err) {
auto state = AccountTaskState::STATE_FAILED_HARD;
if (oauth2.status() == QAbstractOAuth::Status::Granted || silent) {
if (err == QAbstractOAuth2::Error::NetworkError) {
state = AccountTaskState::STATE_OFFLINE;
} else {
state = AccountTaskState::STATE_FAILED_SOFT;
}
}
auto message = tr("Microsoft user authentication failed.");
if (silent) {
message = tr("Failed to refresh token.");
}
qWarning() << message;
emit finished(state, message);
});
connect(&oauth2, &QOAuth2AuthorizationCodeFlow::error, this,
[this](const QString& error, const QString& errorDescription, const QUrl& uri) {
qWarning() << "Failed to login because" << error << errorDescription;
emit finished(AccountTaskState::STATE_FAILED_HARD, errorDescription);
});
connect(&oauth2, &QOAuth2AuthorizationCodeFlow::extraTokensChanged, this,
[this](const QVariantMap& tokens) { m_data->msaToken.extra = tokens; });
connect(&oauth2, &QOAuth2AuthorizationCodeFlow::clientIdentifierChanged, this,
[this](const QString& clientIdentifier) { m_data->msaClientID = clientIdentifier; });
}
QString MSAStep::describe()
{
return tr("Logging in with Microsoft account.");
}
void MSAStep::perform()
{
if (m_silent) {
if (m_data->msaClientID != m_clientId) {
emit finished(AccountTaskState::STATE_DISABLED,
tr("Microsoft user authentication failed - client identification has changed."));
return;
}
if (m_data->msaToken.refresh_token.isEmpty()) {
emit finished(AccountTaskState::STATE_DISABLED, tr("Microsoft user authentication failed - refresh token is empty."));
return;
}
oauth2.setRefreshToken(m_data->msaToken.refresh_token);
oauth2.refreshAccessToken();
} else {
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) // QMultiMap param changed in 6.0
oauth2.setModifyParametersFunction(
[](QAbstractOAuth::Stage stage, QMultiMap<QString, QVariant>* map) { map->insert("prompt", "select_account"); });
#else
oauth2.setModifyParametersFunction(
[](QAbstractOAuth::Stage stage, QMap<QString, QVariant>* map) { map->insert("prompt", "select_account"); });
#endif
*m_data = AccountData();
m_data->msaClientID = m_clientId;
oauth2.grant();
}
}
#include "MSAStep.moc"
| 7,517
|
C++
|
.cpp
| 166
| 39.457831
| 136
| 0.696713
|
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,215
|
XboxAuthorizationStep.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/auth/steps/XboxAuthorizationStep.cpp
|
#include "XboxAuthorizationStep.h"
#include <QJsonDocument>
#include <QJsonParseError>
#include <QNetworkRequest>
#include "Application.h"
#include "Logging.h"
#include "minecraft/auth/Parsers.h"
#include "net/NetUtils.h"
#include "net/RawHeaderProxy.h"
#include "net/Upload.h"
XboxAuthorizationStep::XboxAuthorizationStep(AccountData* data, Token* token, QString relyingParty, QString authorizationKind)
: AuthStep(data), m_token(token), m_relyingParty(relyingParty), m_authorizationKind(authorizationKind)
{}
QString XboxAuthorizationStep::describe()
{
return tr("Getting authorization to access %1 services.").arg(m_authorizationKind);
}
void XboxAuthorizationStep::perform()
{
QString xbox_auth_template = R"XXX(
{
"Properties": {
"SandboxId": "RETAIL",
"UserTokens": [
"%1"
]
},
"RelyingParty": "%2",
"TokenType": "JWT"
}
)XXX";
auto xbox_auth_data = xbox_auth_template.arg(m_data->userToken.token, m_relyingParty);
// http://xboxlive.com
QUrl url("https://xsts.auth.xboxlive.com/xsts/authorize");
auto headers = QList<Net::HeaderPair>{
{ "Content-Type", "application/json" },
{ "Accept", "application/json" },
};
m_response.reset(new QByteArray());
m_request = Net::Upload::makeByteArray(url, m_response, xbox_auth_data.toUtf8());
m_request->addHeaderProxy(new Net::RawHeaderProxy(headers));
m_task.reset(new NetJob("XboxAuthorizationStep", APPLICATION->network()));
m_task->setAskRetry(false);
m_task->addNetAction(m_request);
connect(m_task.get(), &Task::finished, this, &XboxAuthorizationStep::onRequestDone);
m_task->start();
qDebug() << "Getting authorization token for " << m_relyingParty;
}
void XboxAuthorizationStep::onRequestDone()
{
qCDebug(authCredentials()) << *m_response;
if (m_request->error() != QNetworkReply::NoError) {
qWarning() << "Reply error:" << m_request->error();
if (Net::isApplicationError(m_request->error())) {
if (!processSTSError()) {
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("Failed to get authorization for %1 services. Error %2.").arg(m_authorizationKind, m_request->error()));
} else {
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("Unknown STS error for %1 services: %2").arg(m_authorizationKind, m_request->errorString()));
}
} else {
emit finished(AccountTaskState::STATE_OFFLINE,
tr("Failed to get authorization for %1 services: %2").arg(m_authorizationKind, m_request->errorString()));
}
return;
}
Token temp;
if (!Parsers::parseXTokenResponse(*m_response, temp, m_authorizationKind)) {
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("Could not parse authorization response for access to %1 services.").arg(m_authorizationKind));
return;
}
if (temp.extra["uhs"] != m_data->userToken.extra["uhs"]) {
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("Server has changed %1 authorization user hash in the reply. Something is wrong.").arg(m_authorizationKind));
return;
}
auto& token = *m_token;
token = temp;
emit finished(AccountTaskState::STATE_WORKING, tr("Got authorization to access %1").arg(m_relyingParty));
}
bool XboxAuthorizationStep::processSTSError()
{
if (m_request->error() == QNetworkReply::AuthenticationRequiredError) {
QJsonParseError jsonError;
QJsonDocument doc = QJsonDocument::fromJson(*m_response, &jsonError);
if (jsonError.error) {
qWarning() << "Cannot parse error XSTS response as JSON: " << jsonError.errorString();
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("Cannot parse %1 authorization error response as JSON: %2").arg(m_authorizationKind, jsonError.errorString()));
return true;
}
int64_t errorCode = -1;
auto obj = doc.object();
if (!Parsers::getNumber(obj.value("XErr"), errorCode)) {
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("XErr element is missing from %1 authorization error response.").arg(m_authorizationKind));
return true;
}
switch (errorCode) {
case 2148916233: {
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("This Microsoft account does not have an XBox Live profile. Buy the game on %1 first.")
.arg("<a href=\"https://www.minecraft.net/en-us/store/minecraft-java-edition\">minecraft.net</a>"));
return true;
}
case 2148916235: {
// NOTE: this is the Grulovia error
emit finished(AccountTaskState::STATE_FAILED_SOFT, tr("XBox Live is not available in your country. You've been blocked."));
return true;
}
case 2148916238: {
emit finished(
AccountTaskState::STATE_FAILED_SOFT,
tr("This Microsoft account is underaged and is not linked to a family.\n\nPlease set up your account according to %1.")
.arg("<a href=\"https://help.minecraft.net/hc/en-us/articles/4408968616077\">help.minecraft.net</a>"));
return true;
}
// the following codes where copied from: https://github.com/PrismarineJS/prismarine-auth/pull/44
case 2148916236: {
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("This Microsoft account requires proof of age to play. Please login to %1 to provide proof of age.")
.arg("<a href=\"https://login.live.com/login.srf\">login.live.com</a>"));
return true;
}
case 2148916237:
emit finished(AccountTaskState::STATE_FAILED_SOFT, tr("This Microsoft account has reached its limit for playtime. This "
"Microsoft account has been blocked from logging in."));
return true;
case 2148916227: {
emit finished(AccountTaskState::STATE_FAILED_SOFT, tr("This Microsoft account was banned by Xbox for violating one or more "
"Community Standards for Xbox and is unable to be used."));
return true;
}
case 2148916229: {
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("This Microsoft account is currently restricted and your guardian has not given you permission to play "
"online. Login to %1 and have your guardian change your permissions.")
.arg("<a href=\"https://account.microsoft.com/family/\">account.microsoft.com</a>"));
return true;
}
case 2148916234: {
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("This Microsoft account has not accepted Xbox's Terms of Service. Please login and accept them."));
return true;
}
default: {
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("XSTS authentication ended with unrecognized error(s):\n\n%1").arg(errorCode));
return true;
}
}
}
return false;
}
| 7,767
|
C++
|
.cpp
| 156
| 37.961538
| 140
| 0.600895
|
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,216
|
XboxProfileStep.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/auth/steps/XboxProfileStep.cpp
|
#include "XboxProfileStep.h"
#include <QNetworkRequest>
#include <QUrlQuery>
#include "Application.h"
#include "Logging.h"
#include "net/NetUtils.h"
#include "net/RawHeaderProxy.h"
XboxProfileStep::XboxProfileStep(AccountData* data) : AuthStep(data) {}
QString XboxProfileStep::describe()
{
return tr("Fetching Xbox profile.");
}
void XboxProfileStep::perform()
{
QUrl url("https://profile.xboxlive.com/users/me/profile/settings");
QUrlQuery q;
q.addQueryItem("settings",
"GameDisplayName,AppDisplayName,AppDisplayPicRaw,GameDisplayPicRaw,"
"PublicGamerpic,ShowUserAsAvatar,Gamerscore,Gamertag,ModernGamertag,ModernGamertagSuffix,"
"UniqueModernGamertag,AccountTier,TenureLevel,XboxOneRep,"
"PreferredColor,Location,Bio,Watermarks,"
"RealName,RealNameOverride,IsQuarantined");
url.setQuery(q);
auto headers = QList<Net::HeaderPair>{
{ "Content-Type", "application/json" },
{ "Accept", "application/json" },
{ "x-xbl-contract-version", "3" },
{ "Authorization", QString("XBL3.0 x=%1;%2").arg(m_data->userToken.extra["uhs"].toString(), m_data->xboxApiToken.token).toUtf8() }
};
m_response.reset(new QByteArray());
m_request = Net::Download::makeByteArray(url, m_response);
m_request->addHeaderProxy(new Net::RawHeaderProxy(headers));
m_task.reset(new NetJob("XboxProfileStep", APPLICATION->network()));
m_task->setAskRetry(false);
m_task->addNetAction(m_request);
connect(m_task.get(), &Task::finished, this, &XboxProfileStep::onRequestDone);
m_task->start();
qDebug() << "Getting Xbox profile...";
}
void XboxProfileStep::onRequestDone()
{
if (m_request->error() != QNetworkReply::NoError) {
qWarning() << "Reply error:" << m_request->error();
qCDebug(authCredentials()) << *m_response;
if (Net::isApplicationError(m_request->error())) {
emit finished(AccountTaskState::STATE_FAILED_SOFT, tr("Failed to retrieve the Xbox profile: %1").arg(m_request->errorString()));
} else {
emit finished(AccountTaskState::STATE_OFFLINE, tr("Failed to retrieve the Xbox profile: %1").arg(m_request->errorString()));
}
return;
}
qCDebug(authCredentials()) << "XBox profile: " << *m_response;
emit finished(AccountTaskState::STATE_WORKING, tr("Got Xbox profile"));
}
| 2,440
|
C++
|
.cpp
| 54
| 38.796296
| 140
| 0.675653
|
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,217
|
XboxUserStep.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/auth/steps/XboxUserStep.cpp
|
#include "XboxUserStep.h"
#include <QNetworkRequest>
#include "Application.h"
#include "minecraft/auth/Parsers.h"
#include "net/NetUtils.h"
#include "net/RawHeaderProxy.h"
XboxUserStep::XboxUserStep(AccountData* data) : AuthStep(data) {}
QString XboxUserStep::describe()
{
return tr("Logging in as an Xbox user.");
}
void XboxUserStep::perform()
{
QString xbox_auth_template = R"XXX(
{
"Properties": {
"AuthMethod": "RPS",
"SiteName": "user.auth.xboxlive.com",
"RpsTicket": "d=%1"
},
"RelyingParty": "http://auth.xboxlive.com",
"TokenType": "JWT"
}
)XXX";
auto xbox_auth_data = xbox_auth_template.arg(m_data->msaToken.token);
QUrl url("https://user.auth.xboxlive.com/user/authenticate");
auto headers = QList<Net::HeaderPair>{
{ "Content-Type", "application/json" },
{ "Accept", "application/json" },
// set contract-version header (prevent err 400 bad-request?)
// https://learn.microsoft.com/en-us/gaming/gdk/_content/gc/reference/live/rest/additional/httpstandardheaders
{ "x-xbl-contract-version", "1" }
};
m_response.reset(new QByteArray());
m_request = Net::Upload::makeByteArray(url, m_response, xbox_auth_data.toUtf8());
m_request->addHeaderProxy(new Net::RawHeaderProxy(headers));
m_task.reset(new NetJob("XboxUserStep", APPLICATION->network()));
m_task->setAskRetry(false);
m_task->addNetAction(m_request);
connect(m_task.get(), &Task::finished, this, &XboxUserStep::onRequestDone);
m_task->start();
qDebug() << "First layer of XBox auth ... commencing.";
}
void XboxUserStep::onRequestDone()
{
if (m_request->error() != QNetworkReply::NoError) {
qWarning() << "Reply error:" << m_request->error();
if (Net::isApplicationError(m_request->error())) {
emit finished(AccountTaskState::STATE_FAILED_SOFT, tr("XBox user authentication failed: %1").arg(m_request->errorString()));
} else {
emit finished(AccountTaskState::STATE_OFFLINE, tr("XBox user authentication failed: %1").arg(m_request->errorString()));
}
return;
}
Token temp;
if (!Parsers::parseXTokenResponse(*m_response, temp, "UToken")) {
qWarning() << "Could not parse user authentication response...";
emit finished(AccountTaskState::STATE_FAILED_SOFT, tr("XBox user authentication response could not be understood."));
return;
}
m_data->userToken = temp;
emit finished(AccountTaskState::STATE_WORKING, tr("Got Xbox user token"));
}
| 2,568
|
C++
|
.cpp
| 63
| 35.52381
| 136
| 0.67081
|
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,218
|
LauncherLoginStep.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/auth/steps/LauncherLoginStep.cpp
|
#include "LauncherLoginStep.h"
#include <QNetworkRequest>
#include <QUrl>
#include "Application.h"
#include "Logging.h"
#include "minecraft/auth/Parsers.h"
#include "net/NetUtils.h"
#include "net/RawHeaderProxy.h"
#include "net/Upload.h"
LauncherLoginStep::LauncherLoginStep(AccountData* data) : AuthStep(data) {}
QString LauncherLoginStep::describe()
{
return tr("Accessing Mojang services.");
}
void LauncherLoginStep::perform()
{
QUrl url("https://api.minecraftservices.com/launcher/login");
auto uhs = m_data->mojangservicesToken.extra["uhs"].toString();
auto xToken = m_data->mojangservicesToken.token;
QString mc_auth_template = R"XXX(
{
"xtoken": "XBL3.0 x=%1;%2",
"platform": "PC_LAUNCHER"
}
)XXX";
auto requestBody = mc_auth_template.arg(uhs, xToken);
auto headers = QList<Net::HeaderPair>{
{ "Content-Type", "application/json" },
{ "Accept", "application/json" },
};
m_response.reset(new QByteArray());
m_request = Net::Upload::makeByteArray(url, m_response, requestBody.toUtf8());
m_request->addHeaderProxy(new Net::RawHeaderProxy(headers));
m_task.reset(new NetJob("LauncherLoginStep", APPLICATION->network()));
m_task->setAskRetry(false);
m_task->addNetAction(m_request);
connect(m_task.get(), &Task::finished, this, &LauncherLoginStep::onRequestDone);
m_task->start();
qDebug() << "Getting Minecraft access token...";
}
void LauncherLoginStep::onRequestDone()
{
qCDebug(authCredentials()) << *m_response;
if (m_request->error() != QNetworkReply::NoError) {
qWarning() << "Reply error:" << m_request->error();
if (Net::isApplicationError(m_request->error())) {
emit finished(AccountTaskState::STATE_FAILED_SOFT,
tr("Failed to get Minecraft access token: %1").arg(m_request->errorString()));
} else {
emit finished(AccountTaskState::STATE_OFFLINE, tr("Failed to get Minecraft access token: %1").arg(m_request->errorString()));
}
return;
}
if (!Parsers::parseMojangResponse(*m_response, m_data->yggdrasilToken)) {
qWarning() << "Could not parse login_with_xbox response...";
emit finished(AccountTaskState::STATE_FAILED_SOFT, tr("Failed to parse the Minecraft access token response."));
return;
}
emit finished(AccountTaskState::STATE_WORKING, tr(""));
}
| 2,409
|
C++
|
.cpp
| 60
| 35.1
| 137
| 0.680651
|
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,219
|
AssetUpdateTask.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/update/AssetUpdateTask.cpp
|
#include "AssetUpdateTask.h"
#include "launch/LaunchStep.h"
#include "minecraft/AssetsUtils.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/PackProfile.h"
#include "net/ChecksumValidator.h"
#include "Application.h"
#include "net/ApiDownload.h"
AssetUpdateTask::AssetUpdateTask(MinecraftInstance* inst)
{
m_inst = inst;
}
void AssetUpdateTask::executeTask()
{
setStatus(tr("Updating assets index..."));
auto components = m_inst->getPackProfile();
auto profile = components->getProfile();
auto assets = profile->getMinecraftAssets();
QUrl indexUrl = assets->url;
QString localPath = assets->id + ".json";
auto job = makeShared<NetJob>(tr("Asset index for %1").arg(m_inst->name()), APPLICATION->network());
auto metacache = APPLICATION->metacache();
auto entry = metacache->resolveEntry("asset_indexes", localPath);
entry->setStale(true);
auto hexSha1 = assets->sha1.toLatin1();
qDebug() << "Asset index SHA1:" << hexSha1;
auto dl = Net::ApiDownload::makeCached(indexUrl, entry);
dl->addValidator(new Net::ChecksumValidator(QCryptographicHash::Sha1, assets->sha1));
job->addNetAction(dl);
downloadJob.reset(job);
connect(downloadJob.get(), &NetJob::succeeded, this, &AssetUpdateTask::assetIndexFinished);
connect(downloadJob.get(), &NetJob::failed, this, &AssetUpdateTask::assetIndexFailed);
connect(downloadJob.get(), &NetJob::aborted, this, [this] { emitFailed(tr("Aborted")); });
connect(downloadJob.get(), &NetJob::progress, this, &AssetUpdateTask::progress);
connect(downloadJob.get(), &NetJob::stepProgress, this, &AssetUpdateTask::propagateStepProgress);
qDebug() << m_inst->name() << ": Starting asset index download";
downloadJob->start();
}
bool AssetUpdateTask::canAbort() const
{
return true;
}
void AssetUpdateTask::assetIndexFinished()
{
AssetsIndex index;
qDebug() << m_inst->name() << ": Finished asset index download";
auto components = m_inst->getPackProfile();
auto profile = components->getProfile();
auto assets = profile->getMinecraftAssets();
QString asset_fname = "assets/indexes/" + assets->id + ".json";
// FIXME: this looks like a job for a generic validator based on json schema?
if (!AssetsUtils::loadAssetsIndexJson(assets->id, asset_fname, index)) {
auto metacache = APPLICATION->metacache();
auto entry = metacache->resolveEntry("asset_indexes", assets->id + ".json");
metacache->evictEntry(entry);
emitFailed(tr("Failed to read the assets index!"));
}
auto job = index.getDownloadJob();
if (job) {
setStatus(tr("Getting the assets files from Mojang..."));
downloadJob = job;
connect(downloadJob.get(), &NetJob::succeeded, this, &AssetUpdateTask::emitSucceeded);
connect(downloadJob.get(), &NetJob::failed, this, &AssetUpdateTask::assetsFailed);
connect(downloadJob.get(), &NetJob::aborted, this, [this] { emitFailed(tr("Aborted")); });
connect(downloadJob.get(), &NetJob::progress, this, &AssetUpdateTask::progress);
connect(downloadJob.get(), &NetJob::stepProgress, this, &AssetUpdateTask::propagateStepProgress);
downloadJob->start();
return;
}
emitSucceeded();
}
void AssetUpdateTask::assetIndexFailed(QString reason)
{
qDebug() << m_inst->name() << ": Failed asset index download";
emitFailed(tr("Failed to download the assets index:\n%1").arg(reason));
}
void AssetUpdateTask::assetsFailed(QString reason)
{
emitFailed(tr("Failed to download assets:\n%1").arg(reason));
}
bool AssetUpdateTask::abort()
{
if (downloadJob) {
return downloadJob->abort();
} else {
qWarning() << "Prematurely aborted AssetUpdateTask";
}
return true;
}
| 3,799
|
C++
|
.cpp
| 89
| 38.123596
| 105
| 0.700514
|
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,220
|
LibrariesTask.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/update/LibrariesTask.cpp
|
#include "LibrariesTask.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/PackProfile.h"
#include "Application.h"
LibrariesTask::LibrariesTask(MinecraftInstance* inst)
{
m_inst = inst;
}
void LibrariesTask::executeTask()
{
setStatus(tr("Downloading required library files..."));
qDebug() << m_inst->name() << ": downloading libraries";
MinecraftInstance* inst = (MinecraftInstance*)m_inst;
// Build a list of URLs that will need to be downloaded.
auto components = inst->getPackProfile();
auto profile = components->getProfile();
NetJob::Ptr job{ new NetJob(tr("Libraries for instance %1").arg(inst->name()), APPLICATION->network()) };
downloadJob.reset(job);
auto metacache = APPLICATION->metacache();
auto processArtifactPool = [this, inst, metacache](const QList<LibraryPtr>& pool, QStringList& errors, const QString& localPath) {
for (auto lib : pool) {
if (!lib) {
emitFailed(tr("Null jar is specified in the metadata, aborting."));
return false;
}
auto dls = lib->getDownloads(inst->runtimeContext(), metacache.get(), errors, localPath);
for (auto dl : dls) {
downloadJob->addNetAction(dl);
}
}
return true;
};
QStringList failedLocalLibraries;
QList<LibraryPtr> libArtifactPool;
libArtifactPool.append(profile->getLibraries());
libArtifactPool.append(profile->getNativeLibraries());
libArtifactPool.append(profile->getMavenFiles());
for (auto agent : profile->getAgents()) {
libArtifactPool.append(agent->library());
}
libArtifactPool.append(profile->getMainJar());
processArtifactPool(libArtifactPool, failedLocalLibraries, inst->getLocalLibraryPath());
QStringList failedLocalJarMods;
processArtifactPool(profile->getJarMods(), failedLocalJarMods, inst->jarModsDir());
if (!failedLocalJarMods.empty() || !failedLocalLibraries.empty()) {
downloadJob.reset();
QString failed_all = (failedLocalLibraries + failedLocalJarMods).join("\n");
emitFailed(tr("Some artifacts marked as 'local' are missing their files:\n%1\n\nYou need to either add the files, or removed the "
"packages that require them.\nYou'll have to correct this problem manually.")
.arg(failed_all));
return;
}
connect(downloadJob.get(), &NetJob::succeeded, this, &LibrariesTask::emitSucceeded);
connect(downloadJob.get(), &NetJob::failed, this, &LibrariesTask::jarlibFailed);
connect(downloadJob.get(), &NetJob::aborted, this, [this] { emitFailed(tr("Aborted")); });
connect(downloadJob.get(), &NetJob::progress, this, &LibrariesTask::progress);
connect(downloadJob.get(), &NetJob::stepProgress, this, &LibrariesTask::propagateStepProgress);
downloadJob->start();
}
bool LibrariesTask::canAbort() const
{
return true;
}
void LibrariesTask::jarlibFailed(QString reason)
{
emitFailed(tr("Game update failed: it was impossible to fetch the required libraries.\nReason:\n%1").arg(reason));
}
bool LibrariesTask::abort()
{
if (downloadJob) {
return downloadJob->abort();
} else {
qWarning() << "Prematurely aborted LibrariesTask";
}
return true;
}
| 3,326
|
C++
|
.cpp
| 76
| 37.539474
| 138
| 0.686456
|
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,221
|
FoldersTask.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/update/FoldersTask.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 "FoldersTask.h"
#include <QDir>
#include "minecraft/MinecraftInstance.h"
FoldersTask::FoldersTask(MinecraftInstance* inst)
{
m_inst = inst;
}
void FoldersTask::executeTask()
{
// Make directories
QDir mcDir(m_inst->gameRoot());
if (!mcDir.exists() && !mcDir.mkpath(".")) {
emitFailed(tr("Failed to create folder for Minecraft binaries."));
return;
}
emitSucceeded();
}
| 1,914
|
C++
|
.cpp
| 51
| 35.058824
| 80
| 0.722043
|
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,222
|
FMLLibrariesTask.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/update/FMLLibrariesTask.cpp
|
#include "FMLLibrariesTask.h"
#include "FileSystem.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/PackProfile.h"
#include "minecraft/VersionFilterData.h"
#include "Application.h"
#include "BuildConfig.h"
#include "net/ApiDownload.h"
FMLLibrariesTask::FMLLibrariesTask(MinecraftInstance* inst)
{
m_inst = inst;
}
void FMLLibrariesTask::executeTask()
{
// Get the mod list
MinecraftInstance* inst = (MinecraftInstance*)m_inst;
auto components = inst->getPackProfile();
auto profile = components->getProfile();
if (!profile->hasTrait("legacyFML")) {
emitSucceeded();
return;
}
QString version = components->getComponentVersion("net.minecraft");
auto& fmlLibsMapping = g_VersionFilterData.fmlLibsMapping;
if (!fmlLibsMapping.contains(version)) {
emitSucceeded();
return;
}
auto& libList = fmlLibsMapping[version];
// determine if we need some libs for FML or forge
setStatus(tr("Checking for FML libraries..."));
if (!components->getComponent("net.minecraftforge")) {
emitSucceeded();
return;
}
// now check the lib folder inside the instance for files.
for (auto& lib : libList) {
QFileInfo libInfo(FS::PathCombine(inst->libDir(), lib.filename));
if (libInfo.exists())
continue;
fmlLibsToProcess.append(lib);
}
// if everything is in place, there's nothing to do here...
if (fmlLibsToProcess.isEmpty()) {
emitSucceeded();
return;
}
// download missing libs to our place
setStatus(tr("Downloading FML libraries..."));
NetJob::Ptr dljob{ new NetJob("FML libraries", APPLICATION->network()) };
auto metacache = APPLICATION->metacache();
Net::Download::Options options = Net::Download::Option::MakeEternal;
for (auto& lib : fmlLibsToProcess) {
auto entry = metacache->resolveEntry("fmllibs", lib.filename);
QString urlString = BuildConfig.FMLLIBS_BASE_URL + lib.filename;
dljob->addNetAction(Net::ApiDownload::makeCached(QUrl(urlString), entry, options));
}
connect(dljob.get(), &NetJob::succeeded, this, &FMLLibrariesTask::fmllibsFinished);
connect(dljob.get(), &NetJob::failed, this, &FMLLibrariesTask::fmllibsFailed);
connect(dljob.get(), &NetJob::aborted, this, [this] { emitFailed(tr("Aborted")); });
connect(dljob.get(), &NetJob::progress, this, &FMLLibrariesTask::progress);
connect(dljob.get(), &NetJob::stepProgress, this, &FMLLibrariesTask::propagateStepProgress);
downloadJob.reset(dljob);
downloadJob->start();
}
bool FMLLibrariesTask::canAbort() const
{
return true;
}
void FMLLibrariesTask::fmllibsFinished()
{
downloadJob.reset();
if (!fmlLibsToProcess.isEmpty()) {
setStatus(tr("Copying FML libraries into the instance..."));
MinecraftInstance* inst = (MinecraftInstance*)m_inst;
auto metacache = APPLICATION->metacache();
int index = 0;
for (auto& lib : fmlLibsToProcess) {
progress(index, fmlLibsToProcess.size());
auto entry = metacache->resolveEntry("fmllibs", lib.filename);
auto path = FS::PathCombine(inst->libDir(), lib.filename);
if (!FS::ensureFilePathExists(path)) {
emitFailed(tr("Failed creating FML library folder inside the instance."));
return;
}
if (!QFile::copy(entry->getFullPath(), FS::PathCombine(inst->libDir(), lib.filename))) {
emitFailed(tr("Failed copying Forge/FML library: %1.").arg(lib.filename));
return;
}
index++;
}
progress(index, fmlLibsToProcess.size());
}
emitSucceeded();
}
void FMLLibrariesTask::fmllibsFailed(QString reason)
{
QStringList failed = downloadJob->getFailedFiles();
QString failed_all = failed.join("\n");
emitFailed(tr("Failed to download the following files:\n%1\n\nReason:%2\nPlease try again.").arg(failed_all, reason));
}
bool FMLLibrariesTask::abort()
{
if (downloadJob) {
return downloadJob->abort();
} else {
qWarning() << "Prematurely aborted FMLLibrariesTask";
}
return true;
}
| 4,229
|
C++
|
.cpp
| 110
| 32.327273
| 122
| 0.669103
|
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,223
|
ModMinecraftJar.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/launch/ModMinecraftJar.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 "ModMinecraftJar.h"
#include "FileSystem.h"
#include "MMCZip.h"
#include "launch/LaunchTask.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/PackProfile.h"
void ModMinecraftJar::executeTask()
{
auto m_inst = m_parent->instance();
if (!m_inst->getJarMods().size()) {
emitSucceeded();
return;
}
// nuke obsolete stripped jar(s) if needed
if (!FS::ensureFolderPathExists(m_inst->binRoot())) {
emitFailed(tr("Couldn't create the bin folder for Minecraft.jar"));
}
auto finalJarPath = QDir(m_inst->binRoot()).absoluteFilePath("minecraft.jar");
if (!removeJar()) {
emitFailed(tr("Couldn't remove stale jar file: %1").arg(finalJarPath));
}
// create temporary modded jar, if needed
auto components = m_inst->getPackProfile();
auto profile = components->getProfile();
auto jarMods = m_inst->getJarMods();
if (jarMods.size()) {
auto mainJar = profile->getMainJar();
QStringList jars, temp1, temp2, temp3, temp4;
mainJar->getApplicableFiles(m_inst->runtimeContext(), jars, temp1, temp2, temp3, m_inst->getLocalLibraryPath());
auto sourceJarPath = jars[0];
if (!MMCZip::createModdedJar(sourceJarPath, finalJarPath, jarMods)) {
emitFailed(tr("Failed to create the custom Minecraft jar file."));
return;
}
}
emitSucceeded();
}
void ModMinecraftJar::finalize()
{
removeJar();
}
bool ModMinecraftJar::removeJar()
{
auto m_inst = m_parent->instance();
auto finalJarPath = QDir(m_inst->binRoot()).absoluteFilePath("minecraft.jar");
QFile finalJar(finalJarPath);
if (finalJar.exists()) {
if (!finalJar.remove()) {
return false;
}
}
return true;
}
| 3,277
|
C++
|
.cpp
| 87
| 33.643678
| 120
| 0.693685
|
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,224
|
ClaimAccount.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/launch/ClaimAccount.cpp
|
#include "ClaimAccount.h"
#include <launch/LaunchTask.h>
#include "Application.h"
#include "minecraft/auth/AccountList.h"
ClaimAccount::ClaimAccount(LaunchTask* parent, AuthSessionPtr session) : LaunchStep(parent)
{
if (session->status == AuthSession::Status::PlayableOnline && !session->demo) {
auto accounts = APPLICATION->accounts();
m_account = accounts->getAccountByProfileName(session->player_name);
}
}
void ClaimAccount::executeTask()
{
if (m_account) {
lock.reset(new UseLock(m_account));
emitSucceeded();
}
}
void ClaimAccount::finalize()
{
lock.reset();
}
| 623
|
C++
|
.cpp
| 22
| 24.772727
| 91
| 0.713568
|
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,225
|
ReconstructAssets.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/launch/ReconstructAssets.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 "ReconstructAssets.h"
#include "launch/LaunchTask.h"
#include "minecraft/AssetsUtils.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/PackProfile.h"
void ReconstructAssets::executeTask()
{
auto instance = m_parent->instance();
auto components = instance->getPackProfile();
auto profile = components->getProfile();
auto assets = profile->getMinecraftAssets();
if (!AssetsUtils::reconstructAssets(assets->id, instance->resourcesDir())) {
emit logLine("Failed to reconstruct Minecraft assets.", MessageLevel::Error);
}
emitSucceeded();
}
| 1,205
|
C++
|
.cpp
| 30
| 37.4
| 85
| 0.755764
|
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,226
|
MinecraftTarget.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/launch/MinecraftTarget.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 "MinecraftTarget.h"
#include <QStringList>
// FIXME: the way this is written, it can't ever do any sort of validation and can accept total junk
MinecraftTarget MinecraftTarget::parse(const QString& fullAddress, bool useWorld)
{
if (useWorld) {
MinecraftTarget target;
target.world = fullAddress;
return target;
}
QStringList split = fullAddress.split(":");
// The logic below replicates the exact logic minecraft uses for parsing server addresses.
// While the conversion is not lossless and eats errors, it ensures the same behavior
// within Minecraft and Prism Launcher when entering server addresses.
if (fullAddress.startsWith("[")) {
int bracket = fullAddress.indexOf("]");
if (bracket > 0) {
QString ipv6 = fullAddress.mid(1, bracket - 1);
QString port = fullAddress.mid(bracket + 1).trimmed();
if (port.startsWith(":") && !ipv6.isEmpty()) {
port = port.mid(1);
split = QStringList({ ipv6, port });
} else {
split = QStringList({ ipv6 });
}
}
}
if (split.size() > 2) {
split = QStringList({ fullAddress });
}
QString realAddress = split[0];
quint16 realPort = 25565;
if (split.size() > 1) {
bool ok;
realPort = split[1].toUInt(&ok);
if (!ok) {
realPort = 25565;
}
}
return MinecraftTarget{ realAddress, realPort };
}
| 2,117
|
C++
|
.cpp
| 55
| 32.2
| 100
| 0.652047
|
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,227
|
CreateGameFolders.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/launch/CreateGameFolders.cpp
|
#include "CreateGameFolders.h"
#include "FileSystem.h"
#include "launch/LaunchTask.h"
#include "minecraft/MinecraftInstance.h"
CreateGameFolders::CreateGameFolders(LaunchTask* parent) : LaunchStep(parent) {}
void CreateGameFolders::executeTask()
{
auto instance = m_parent->instance();
if (!FS::ensureFolderPathExists(instance->gameRoot())) {
emit logLine("Couldn't create the main game folder", MessageLevel::Error);
emitFailed(tr("Couldn't create the main game folder"));
return;
}
// HACK: this is a workaround for MCL-3732 - 'server-resource-packs' folder is created.
if (!FS::ensureFolderPathExists(FS::PathCombine(instance->gameRoot(), "server-resource-packs"))) {
emit logLine("Couldn't create the 'server-resource-packs' folder", MessageLevel::Error);
}
emitSucceeded();
}
| 845
|
C++
|
.cpp
| 19
| 40.105263
| 102
| 0.723844
|
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,228
|
VerifyJavaInstall.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/launch/VerifyJavaInstall.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 "VerifyJavaInstall.h"
#include <memory>
#include "Application.h"
#include "MessageLevel.h"
#include "java/JavaInstall.h"
#include "java/JavaInstallList.h"
#include "java/JavaVersion.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/PackProfile.h"
void VerifyJavaInstall::executeTask()
{
auto instance = m_parent->instance();
auto packProfile = instance->getPackProfile();
auto settings = instance->settings();
auto storedVersion = settings->get("JavaVersion").toString();
auto ignoreCompatibility = settings->get("IgnoreJavaCompatibility").toBool();
auto javaArchitecture = settings->get("JavaArchitecture").toString();
auto maxMemAlloc = settings->get("MaxMemAlloc").toInt();
if (javaArchitecture == "32" && maxMemAlloc > 2048) {
emit logLine(tr("Max memory allocation exceeds the supported value.\n"
"The selected installation of Java is 32-bit and doesn't support more than 2048MiB of RAM.\n"
"The instance may not start due to this."),
MessageLevel::Error);
}
auto compatibleMajors = packProfile->getProfile()->getCompatibleJavaMajors();
JavaVersion javaVersion(storedVersion);
if (compatibleMajors.isEmpty() || compatibleMajors.contains(javaVersion.major())) {
emitSucceeded();
return;
}
if (ignoreCompatibility) {
emit logLine(tr("Java major version is incompatible. Things might break."), MessageLevel::Warning);
emitSucceeded();
return;
}
emit logLine(tr("This instance is not compatible with Java version %1.\n"
"Please switch to one of the following Java versions for this instance:")
.arg(javaVersion.major()),
MessageLevel::Error);
for (auto major : compatibleMajors) {
emit logLine(tr("Java version %1").arg(major), MessageLevel::Error);
}
emit logLine(tr("Go to instance Java settings to change your Java version or disable the Java compatibility check if you know what "
"you're doing."),
MessageLevel::Error);
emitFailed(QString("Incompatible Java major version"));
}
| 3,710
|
C++
|
.cpp
| 81
| 40.580247
| 136
| 0.700193
|
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,229
|
ScanModFolders.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/launch/ScanModFolders.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 "ScanModFolders.h"
#include "FileSystem.h"
#include "MMCZip.h"
#include "launch/LaunchTask.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/mod/ModFolderModel.h"
void ScanModFolders::executeTask()
{
auto m_inst = m_parent->instance();
auto loaders = m_inst->loaderModList();
connect(loaders.get(), &ModFolderModel::updateFinished, this, &ScanModFolders::modsDone);
if (!loaders->update()) {
m_modsDone = true;
}
auto cores = m_inst->coreModList();
connect(cores.get(), &ModFolderModel::updateFinished, this, &ScanModFolders::coreModsDone);
if (!cores->update()) {
m_coreModsDone = true;
}
auto nils = m_inst->nilModList();
connect(nils.get(), &ModFolderModel::updateFinished, this, &ScanModFolders::nilModsDone);
if (!nils->update()) {
m_nilModsDone = true;
}
checkDone();
}
void ScanModFolders::modsDone()
{
m_modsDone = true;
checkDone();
}
void ScanModFolders::coreModsDone()
{
m_coreModsDone = true;
checkDone();
}
void ScanModFolders::nilModsDone()
{
m_nilModsDone = true;
checkDone();
}
void ScanModFolders::checkDone()
{
if (m_modsDone && m_coreModsDone && m_nilModsDone) {
emitSucceeded();
}
}
| 2,748
|
C++
|
.cpp
| 81
| 30.938272
| 95
| 0.710685
|
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,230
|
LauncherPartLaunch.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/launch/LauncherPartLaunch.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 "LauncherPartLaunch.h"
#include <QRegularExpression>
#include <QStandardPaths>
#include "Application.h"
#include "Commandline.h"
#include "FileSystem.h"
#include "launch/LaunchTask.h"
#include "minecraft/MinecraftInstance.h"
#ifdef Q_OS_LINUX
#include "gamemode_client.h"
#endif
LauncherPartLaunch::LauncherPartLaunch(LaunchTask* parent)
: LaunchStep(parent)
, m_process(parent->instance()->getJavaVersion().defaultsToUtf8() ? QTextCodec::codecForName("UTF-8") : QTextCodec::codecForLocale())
{
if (parent->instance()->settings()->get("CloseAfterLaunch").toBool()) {
std::shared_ptr<QMetaObject::Connection> connection{ new QMetaObject::Connection };
*connection = connect(
&m_process, &LoggedProcess::log, this, [connection](const QStringList& lines, [[maybe_unused]] MessageLevel::Enum level) {
qDebug() << lines;
if (lines.filter(QRegularExpression(".*Setting user.+", QRegularExpression::CaseInsensitiveOption)).length() != 0) {
APPLICATION->closeAllWindows();
disconnect(*connection);
}
});
}
connect(&m_process, &LoggedProcess::log, this, &LauncherPartLaunch::logLines);
connect(&m_process, &LoggedProcess::stateChanged, this, &LauncherPartLaunch::on_state);
}
void LauncherPartLaunch::executeTask()
{
QString jarPath = APPLICATION->getJarPath("NewLaunch.jar");
if (jarPath.isEmpty()) {
const char* reason = QT_TR_NOOP("Launcher library could not be found. Please check your installation.");
emit logLine(tr(reason), MessageLevel::Fatal);
emitFailed(tr(reason));
return;
}
auto instance = m_parent->instance();
QString legacyJarPath;
if (instance->getLauncher() == "legacy" || instance->shouldApplyOnlineFixes()) {
legacyJarPath = APPLICATION->getJarPath("NewLaunchLegacy.jar");
if (legacyJarPath.isEmpty()) {
const char* reason = QT_TR_NOOP("Legacy launcher library could not be found. Please check your installation.");
emit logLine(tr(reason), MessageLevel::Fatal);
emitFailed(tr(reason));
return;
}
}
m_launchScript = instance->createLaunchScript(m_session, m_targetToJoin);
QStringList args = instance->javaArguments();
QString allArgs = args.join(", ");
emit logLine("Java Arguments:\n[" + m_parent->censorPrivateInfo(allArgs) + "]\n\n", MessageLevel::Launcher);
auto javaPath = FS::ResolveExecutable(instance->settings()->get("JavaPath").toString());
m_process.setProcessEnvironment(instance->createLaunchEnvironment());
// make detachable - this will keep the process running even if the object is destroyed
m_process.setDetachable(true);
auto classPath = instance->getClassPath();
classPath.prepend(jarPath);
if (!legacyJarPath.isEmpty())
classPath.prepend(legacyJarPath);
auto natPath = instance->getNativePath();
#ifdef Q_OS_WIN
natPath = FS::getPathNameInLocal8bit(natPath);
#endif
args << "-Djava.library.path=" + natPath;
args << "-cp";
#ifdef Q_OS_WIN
QStringList processed;
for (auto& item : classPath) {
processed << FS::getPathNameInLocal8bit(item);
}
args << processed.join(';');
#else
args << classPath.join(':');
#endif
args << "org.prismlauncher.EntryPoint";
qDebug() << args.join(' ');
QString wrapperCommandStr = instance->getWrapperCommand().trimmed();
if (!wrapperCommandStr.isEmpty()) {
auto wrapperArgs = Commandline::splitArgs(wrapperCommandStr);
auto wrapperCommand = wrapperArgs.takeFirst();
auto realWrapperCommand = QStandardPaths::findExecutable(wrapperCommand);
if (realWrapperCommand.isEmpty()) {
const char* reason = QT_TR_NOOP("The wrapper command \"%1\" couldn't be found.");
emit logLine(QString(reason).arg(wrapperCommand), MessageLevel::Fatal);
emitFailed(tr(reason).arg(wrapperCommand));
return;
}
emit logLine("Wrapper command is:\n" + wrapperCommandStr + "\n\n", MessageLevel::Launcher);
args.prepend(javaPath);
m_process.start(wrapperCommand, wrapperArgs + args);
} else {
m_process.start(javaPath, args);
}
#ifdef Q_OS_LINUX
if (instance->settings()->get("EnableFeralGamemode").toBool() && APPLICATION->capabilities() & Application::SupportsGameMode) {
auto pid = m_process.processId();
if (pid) {
gamemode_request_start_for(pid);
}
}
#endif
}
void LauncherPartLaunch::on_state(LoggedProcess::State state)
{
switch (state) {
case LoggedProcess::FailedToStart: {
//: Error message displayed if instace can't start
const char* reason = QT_TR_NOOP("Could not launch Minecraft!");
emit logLine(reason, MessageLevel::Fatal);
emitFailed(tr(reason));
return;
}
case LoggedProcess::Aborted:
case LoggedProcess::Crashed: {
m_parent->setPid(-1);
emitFailed(tr("Game crashed."));
return;
}
case LoggedProcess::Finished: {
auto instance = m_parent->instance();
if (instance->settings()->get("CloseAfterLaunch").toBool())
APPLICATION->showMainWindow();
m_parent->setPid(-1);
m_parent->instance()->setMinecraftRunning(false);
// if the exit code wasn't 0, report this as a crash
auto exitCode = m_process.exitCode();
if (exitCode != 0) {
emitFailed(tr("Game crashed."));
return;
}
// FIXME: make this work again
// m_postlaunchprocess.processEnvironment().insert("INST_EXITCODE", QString(exitCode));
// run post-exit
emitSucceeded();
break;
}
case LoggedProcess::Running:
emit logLine(QString("Minecraft process ID: %1\n\n").arg(m_process.processId()), MessageLevel::Launcher);
m_parent->setPid(m_process.processId());
// send the launch script to the launcher part
m_process.write(m_launchScript.toUtf8());
mayProceed = true;
emit readyForLaunch();
break;
default:
break;
}
}
void LauncherPartLaunch::setWorkingDirectory(const QString& wd)
{
m_process.setWorkingDirectory(wd);
}
void LauncherPartLaunch::proceed()
{
if (mayProceed) {
m_parent->instance()->setMinecraftRunning(true);
QString launchString("launch\n");
m_process.write(launchString.toUtf8());
mayProceed = false;
}
}
bool LauncherPartLaunch::abort()
{
if (mayProceed) {
mayProceed = false;
QString launchString("abort\n");
m_process.write(launchString.toUtf8());
} else {
auto state = m_process.state();
if (state == LoggedProcess::Running || state == LoggedProcess::Starting) {
m_process.kill();
}
}
return true;
}
| 8,614
|
C++
|
.cpp
| 211
| 34.033175
| 137
| 0.656918
|
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,231
|
PrintInstanceInfo.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/launch/PrintInstanceInfo.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 <fstream>
#include <string>
#include <launch/LaunchTask.h>
#include "PrintInstanceInfo.h"
#if defined(Q_OS_LINUX) || defined(Q_OS_FREEBSD)
namespace {
#if defined(Q_OS_LINUX)
void probeProcCpuinfo(QStringList& log)
{
std::ifstream cpuin("/proc/cpuinfo");
for (std::string line; std::getline(cpuin, line);) {
if (strncmp(line.c_str(), "model name", 10) == 0) {
log << QString::fromStdString(line.substr(13, std::string::npos));
break;
}
}
}
void runLspci(QStringList& log)
{
// FIXME: fixed size buffers...
char buff[512];
int gpuline = -1;
int cline = 0;
FILE* lspci = popen("lspci -k", "r");
if (!lspci)
return;
while (fgets(buff, 512, lspci) != NULL) {
std::string str(buff);
if (str.length() < 9)
continue;
if (str.substr(8, 3) == "VGA") {
gpuline = cline;
log << QString::fromStdString(str.substr(35, std::string::npos));
}
if (gpuline > -1 && gpuline != cline) {
if (cline - gpuline < 3) {
log << QString::fromStdString(str.substr(1, std::string::npos));
}
}
cline++;
}
pclose(lspci);
}
#elif defined(Q_OS_FREEBSD)
void runSysctlHwModel(QStringList& log)
{
char buff[512];
FILE* hwmodel = popen("sysctl hw.model", "r");
while (fgets(buff, 512, hwmodel) != NULL) {
log << QString::fromUtf8(buff);
break;
}
pclose(hwmodel);
}
void runPciconf(QStringList& log)
{
char buff[512];
std::string strcard;
FILE* pciconf = popen("pciconf -lv -a vgapci0", "r");
while (fgets(buff, 512, pciconf) != NULL) {
if (strncmp(buff, " vendor", 10) == 0) {
std::string str(buff);
strcard.append(str.substr(str.find_first_of("'") + 1, str.find_last_not_of("'") - (str.find_first_of("'") + 2)));
strcard.append(" ");
} else if (strncmp(buff, " device", 10) == 0) {
std::string str2(buff);
strcard.append(str2.substr(str2.find_first_of("'") + 1, str2.find_last_not_of("'") - (str2.find_first_of("'") + 2)));
}
log << QString::fromStdString(strcard);
break;
}
pclose(pciconf);
}
#endif
void runGlxinfo(QStringList& log)
{
// FIXME: fixed size buffers...
char buff[512];
FILE* glxinfo = popen("glxinfo", "r");
if (!glxinfo)
return;
while (fgets(buff, 512, glxinfo) != NULL) {
if (strncmp(buff, "OpenGL version string:", 22) == 0) {
log << QString::fromUtf8(buff);
break;
}
}
pclose(glxinfo);
}
} // namespace
#endif
void PrintInstanceInfo::executeTask()
{
auto instance = m_parent->instance();
QStringList log;
#if defined(Q_OS_LINUX)
::probeProcCpuinfo(log);
::runLspci(log);
::runGlxinfo(log);
#elif defined(Q_OS_FREEBSD)
::runSysctlHwModel(log);
::runPciconf(log);
::runGlxinfo(log);
#endif
logLines(log, MessageLevel::Launcher);
logLines(instance->verboseDescription(m_session, m_targetToJoin), MessageLevel::Launcher);
emitSucceeded();
}
| 3,764
|
C++
|
.cpp
| 122
| 25.483607
| 129
| 0.611846
|
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,232
|
ExtractNatives.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/launch/ExtractNatives.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 "ExtractNatives.h"
#include <launch/LaunchTask.h>
#include <minecraft/MinecraftInstance.h>
#include <quazip/quazip.h>
#include <quazip/quazipdir.h>
#include <QDir>
#include "FileSystem.h"
#include "MMCZip.h"
#ifdef major
#undef major
#endif
#ifdef minor
#undef minor
#endif
static QString replaceSuffix(QString target, const QString& suffix, const QString& replacement)
{
if (!target.endsWith(suffix)) {
return target;
}
target.resize(target.length() - suffix.length());
return target + replacement;
}
static bool unzipNatives(QString source, QString targetFolder, bool applyJnilibHack)
{
QuaZip zip(source);
if (!zip.open(QuaZip::mdUnzip)) {
return false;
}
QDir directory(targetFolder);
if (!zip.goToFirstFile()) {
return false;
}
do {
QString name = zip.getCurrentFileName();
auto lowercase = name.toLower();
if (applyJnilibHack) {
name = replaceSuffix(name, ".jnilib", ".dylib");
}
QString absFilePath = directory.absoluteFilePath(name);
if (!JlCompress::extractFile(&zip, "", absFilePath)) {
return false;
}
} while (zip.goToNextFile());
zip.close();
if (zip.getZipError() != 0) {
return false;
}
return true;
}
void ExtractNatives::executeTask()
{
auto instance = m_parent->instance();
auto toExtract = instance->getNativeJars();
if (toExtract.isEmpty()) {
emitSucceeded();
return;
}
auto settings = instance->settings();
auto outputPath = instance->getNativePath();
FS::ensureFolderPathExists(outputPath);
auto javaVersion = instance->getJavaVersion();
bool jniHackEnabled = javaVersion.major() >= 8;
for (const auto& source : toExtract) {
if (!unzipNatives(source, outputPath, jniHackEnabled)) {
const char* reason = QT_TR_NOOP("Couldn't extract native jar '%1' to destination '%2'");
emit logLine(QString(reason).arg(source, outputPath), MessageLevel::Fatal);
emitFailed(tr(reason).arg(source, outputPath));
}
}
emitSucceeded();
}
void ExtractNatives::finalize()
{
auto instance = m_parent->instance();
QString target_dir = FS::PathCombine(instance->instanceRoot(), "natives/");
QDir dir(target_dir);
dir.removeRecursively();
}
| 2,968
|
C++
|
.cpp
| 92
| 27.684783
| 100
| 0.685844
|
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,233
|
AutoInstallJava.cpp
|
PrismLauncher_PrismLauncher/launcher/minecraft/launch/AutoInstallJava.cpp
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2023-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/>.
*
* 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 "AutoInstallJava.h"
#include <QDir>
#include <QFileInfo>
#include <memory>
#include "Application.h"
#include "FileSystem.h"
#include "MessageLevel.h"
#include "QObjectPtr.h"
#include "SysInfo.h"
#include "java/JavaInstall.h"
#include "java/JavaInstallList.h"
#include "java/JavaUtils.h"
#include "java/JavaVersion.h"
#include "java/download/ArchiveDownloadTask.h"
#include "java/download/ManifestDownloadTask.h"
#include "java/download/SymlinkTask.h"
#include "meta/Index.h"
#include "minecraft/MinecraftInstance.h"
#include "minecraft/PackProfile.h"
#include "net/Mode.h"
#include "tasks/SequentialTask.h"
AutoInstallJava::AutoInstallJava(LaunchTask* parent)
: LaunchStep(parent), m_instance(m_parent->instance()), m_supported_arch(SysInfo::getSupportedJavaArchitecture()) {};
void AutoInstallJava::executeTask()
{
auto settings = m_instance->settings();
if (!APPLICATION->settings()->get("AutomaticJavaSwitch").toBool() ||
(settings->get("OverrideJavaLocation").toBool() && QFileInfo::exists(settings->get("JavaPath").toString()))) {
emitSucceeded();
return;
}
auto packProfile = m_instance->getPackProfile();
if (!APPLICATION->settings()->get("AutomaticJavaDownload").toBool()) {
auto javas = APPLICATION->javalist();
m_current_task = javas->getLoadTask();
connect(m_current_task.get(), &Task::finished, this, [this, javas, packProfile] {
for (auto i = 0; i < javas->count(); i++) {
auto java = std::dynamic_pointer_cast<JavaInstall>(javas->at(i));
if (java && packProfile->getProfile()->getCompatibleJavaMajors().contains(java->id.major())) {
if (!java->is_64bit) {
emit logLine(tr("The automatic Java mechanism detected a 32-bit installation of Java."), MessageLevel::Launcher);
}
setJavaPath(java->path);
return;
}
}
emit logLine(tr("No compatible Java version was found. Using the default one."), MessageLevel::Warning);
emitSucceeded();
});
connect(m_current_task.get(), &Task::progress, this, &AutoInstallJava::setProgress);
connect(m_current_task.get(), &Task::stepProgress, this, &AutoInstallJava::propagateStepProgress);
connect(m_current_task.get(), &Task::status, this, &AutoInstallJava::setStatus);
connect(m_current_task.get(), &Task::details, this, &AutoInstallJava::setDetails);
emit progressReportingRequest();
return;
}
if (m_supported_arch.isEmpty()) {
emit logLine(tr("Your system (%1-%2) is not compatible with automatic Java installation. Using the default Java path.")
.arg(SysInfo::currentSystem(), SysInfo::useQTForArch()),
MessageLevel::Warning);
emitSucceeded();
return;
}
auto wantedJavaName = packProfile->getProfile()->getCompatibleJavaName();
if (wantedJavaName.isEmpty()) {
emit logLine(tr("Your meta information is out of date or doesn't have the information necessary to determine what installation of "
"Java should be used. "
"Using the default Java path."),
MessageLevel::Warning);
emitSucceeded();
return;
}
QDir javaDir(APPLICATION->javaPath());
auto wantedJavaPath = javaDir.absoluteFilePath(wantedJavaName);
if (QFileInfo::exists(wantedJavaPath)) {
setJavaPathFromPartial();
return;
}
auto versionList = APPLICATION->metadataIndex()->get("net.minecraft.java");
m_current_task = versionList->getLoadTask();
connect(m_current_task.get(), &Task::succeeded, this, &AutoInstallJava::tryNextMajorJava);
connect(m_current_task.get(), &Task::failed, this, &AutoInstallJava::emitFailed);
connect(m_current_task.get(), &Task::progress, this, &AutoInstallJava::setProgress);
connect(m_current_task.get(), &Task::stepProgress, this, &AutoInstallJava::propagateStepProgress);
connect(m_current_task.get(), &Task::status, this, &AutoInstallJava::setStatus);
connect(m_current_task.get(), &Task::details, this, &AutoInstallJava::setDetails);
if (!m_current_task->isRunning()) {
m_current_task->start();
}
emit progressReportingRequest();
}
void AutoInstallJava::setJavaPath(QString path)
{
auto settings = m_instance->settings();
settings->set("OverrideJavaLocation", true);
settings->set("JavaPath", path);
settings->set("AutomaticJava", true);
emit logLine(tr("Compatible Java found at: %1.").arg(path), MessageLevel::Launcher);
emitSucceeded();
}
void AutoInstallJava::setJavaPathFromPartial()
{
auto packProfile = m_instance->getPackProfile();
auto javaName = packProfile->getProfile()->getCompatibleJavaName();
QDir javaDir(APPLICATION->javaPath());
// just checking if the executable is there should suffice
// but if needed this can be achieved through refreshing the javalist
// and retrieving the path that contains the java name
auto relativeBinary = FS::PathCombine(javaName, "bin", JavaUtils::javaExecutable);
auto finalPath = javaDir.absoluteFilePath(relativeBinary);
if (QFileInfo::exists(finalPath)) {
setJavaPath(finalPath);
} else {
emit logLine(tr("No compatible Java version was found (the binary file does not exist). Using the default one."),
MessageLevel::Warning);
emitSucceeded();
}
return;
}
void AutoInstallJava::downloadJava(Meta::Version::Ptr version, QString javaName)
{
auto runtimes = version->data()->runtimes;
for (auto java : runtimes) {
if (java->runtimeOS == m_supported_arch && java->name() == javaName) {
QDir javaDir(APPLICATION->javaPath());
auto final_path = javaDir.absoluteFilePath(java->m_name);
switch (java->downloadType) {
case Java::DownloadType::Manifest:
m_current_task = makeShared<Java::ManifestDownloadTask>(java->url, final_path, java->checksumType, java->checksumHash);
break;
case Java::DownloadType::Archive:
m_current_task = makeShared<Java::ArchiveDownloadTask>(java->url, final_path, java->checksumType, java->checksumHash);
break;
case Java::DownloadType::Unknown:
emitFailed(tr("Could not determine Java download type!"));
return;
}
#if defined(Q_OS_MACOS)
auto seq = makeShared<SequentialTask>(tr("Install Java"));
seq->addTask(m_current_task);
seq->addTask(makeShared<Java::SymlinkTask>(final_path));
m_current_task = seq;
#endif
auto deletePath = [final_path] { FS::deletePath(final_path); };
connect(m_current_task.get(), &Task::failed, this, [this, deletePath](QString reason) {
deletePath();
emitFailed(reason);
});
connect(m_current_task.get(), &Task::aborted, this, [deletePath] { deletePath(); });
connect(m_current_task.get(), &Task::succeeded, this, &AutoInstallJava::setJavaPathFromPartial);
connect(m_current_task.get(), &Task::failed, this, &AutoInstallJava::tryNextMajorJava);
connect(m_current_task.get(), &Task::progress, this, &AutoInstallJava::setProgress);
connect(m_current_task.get(), &Task::stepProgress, this, &AutoInstallJava::propagateStepProgress);
connect(m_current_task.get(), &Task::status, this, &AutoInstallJava::setStatus);
connect(m_current_task.get(), &Task::details, this, &AutoInstallJava::setDetails);
m_current_task->start();
return;
}
}
tryNextMajorJava();
}
void AutoInstallJava::tryNextMajorJava()
{
if (!isRunning())
return;
auto versionList = APPLICATION->metadataIndex()->get("net.minecraft.java");
auto packProfile = m_instance->getPackProfile();
auto wantedJavaName = packProfile->getProfile()->getCompatibleJavaName();
auto majorJavaVersions = packProfile->getProfile()->getCompatibleJavaMajors();
if (m_majorJavaVersionIndex >= majorJavaVersions.length()) {
emit logLine(
tr("No versions of Java were found for your operating system: %1-%2").arg(SysInfo::currentSystem(), SysInfo::useQTForArch()),
MessageLevel::Warning);
emit logLine(tr("No compatible version of Java was found. Using the default one."), MessageLevel::Warning);
emitSucceeded();
return;
}
auto majorJavaVersion = majorJavaVersions[m_majorJavaVersionIndex];
m_majorJavaVersionIndex++;
auto javaMajor = versionList->getVersion(QString("java%1").arg(majorJavaVersion));
if (javaMajor->isLoaded()) {
downloadJava(javaMajor, wantedJavaName);
} else {
m_current_task = APPLICATION->metadataIndex()->loadVersion("net.minecraft.java", javaMajor->version(), Net::Mode::Online);
connect(m_current_task.get(), &Task::succeeded, this,
[this, javaMajor, wantedJavaName] { downloadJava(javaMajor, wantedJavaName); });
connect(m_current_task.get(), &Task::failed, this, &AutoInstallJava::tryNextMajorJava);
connect(m_current_task.get(), &Task::progress, this, &AutoInstallJava::setProgress);
connect(m_current_task.get(), &Task::stepProgress, this, &AutoInstallJava::propagateStepProgress);
connect(m_current_task.get(), &Task::status, this, &AutoInstallJava::setStatus);
connect(m_current_task.get(), &Task::details, this, &AutoInstallJava::setDetails);
if (!m_current_task->isRunning()) {
m_current_task->start();
}
}
}
bool AutoInstallJava::abort()
{
if (m_current_task && m_current_task->canAbort()) {
auto status = m_current_task->abort();
emitFailed("Aborted.");
return status;
}
return Task::abort();
}
| 11,569
|
C++
|
.cpp
| 239
| 41.171548
| 139
| 0.667845
|
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,234
|
HttpMetaCache.cpp
|
PrismLauncher_PrismLauncher/launcher/net/HttpMetaCache.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
*
* 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 "HttpMetaCache.h"
#include "FileSystem.h"
#include "Json.h"
#include <QCryptographicHash>
#include <QDateTime>
#include <QFile>
#include <QFileInfo>
#include <QDebug>
#include "net/Logging.h"
auto MetaEntry::getFullPath() -> QString
{
// FIXME: make local?
return FS::PathCombine(m_basePath, m_relativePath);
}
HttpMetaCache::HttpMetaCache(QString path) : QObject(), m_index_file(path)
{
saveBatchingTimer.setSingleShot(true);
saveBatchingTimer.setTimerType(Qt::VeryCoarseTimer);
connect(&saveBatchingTimer, &QTimer::timeout, this, &HttpMetaCache::SaveNow);
}
HttpMetaCache::~HttpMetaCache()
{
saveBatchingTimer.stop();
SaveNow();
}
auto HttpMetaCache::getEntry(QString base, QString resource_path) -> MetaEntryPtr
{
// no base. no base path. can't store
if (!m_entries.contains(base)) {
// TODO: log problem
return {};
}
EntryMap& map = m_entries[base];
if (map.entry_list.contains(resource_path)) {
return map.entry_list[resource_path];
}
return {};
}
auto HttpMetaCache::resolveEntry(QString base, QString resource_path, QString expected_etag) -> MetaEntryPtr
{
resource_path = FS::RemoveInvalidPathChars(resource_path);
auto entry = getEntry(base, resource_path);
// it's not present? generate a default stale entry
if (!entry) {
return staleEntry(base, resource_path);
}
auto& selected_base = m_entries[base];
QString real_path = FS::PathCombine(selected_base.base_path, resource_path);
QFileInfo finfo(real_path);
// is the file really there? if not -> stale
if (!finfo.isFile() || !finfo.isReadable()) {
// if the file doesn't exist, we disown the entry
selected_base.entry_list.remove(resource_path);
return staleEntry(base, resource_path);
}
if (!expected_etag.isEmpty() && expected_etag != entry->m_etag) {
// if the etag doesn't match expected, we disown the entry
selected_base.entry_list.remove(resource_path);
return staleEntry(base, resource_path);
}
// if the file changed, check md5sum
qint64 file_last_changed = finfo.lastModified().toUTC().toMSecsSinceEpoch();
if (file_last_changed != entry->m_local_changed_timestamp) {
QFile input(real_path);
input.open(QIODevice::ReadOnly);
QString md5sum = QCryptographicHash::hash(input.readAll(), QCryptographicHash::Md5).toHex().constData();
if (entry->m_md5sum != md5sum) {
selected_base.entry_list.remove(resource_path);
return staleEntry(base, resource_path);
}
// md5sums matched... keep entry and save the new state to file
entry->m_local_changed_timestamp = file_last_changed;
SaveEventually();
}
// Get rid of old entries, to prevent cache problems
auto current_time = QDateTime::currentSecsSinceEpoch();
if (entry->isExpired(current_time - (file_last_changed / 1000))) {
qCWarning(taskNetLogC) << "[HttpMetaCache]"
<< "Removing cache entry because of old age!";
selected_base.entry_list.remove(resource_path);
return staleEntry(base, resource_path);
}
// entry passed all the checks we cared about.
entry->m_basePath = getBasePath(base);
return entry;
}
auto HttpMetaCache::updateEntry(MetaEntryPtr stale_entry) -> bool
{
if (!m_entries.contains(stale_entry->m_baseId)) {
qCCritical(taskHttpMetaCacheLogC) << "Cannot add entry with unknown base: " << stale_entry->m_baseId.toLocal8Bit();
return false;
}
if (stale_entry->m_stale) {
qCCritical(taskHttpMetaCacheLogC) << "Cannot add stale entry: " << stale_entry->getFullPath().toLocal8Bit();
return false;
}
m_entries[stale_entry->m_baseId].entry_list[stale_entry->m_relativePath] = stale_entry;
SaveEventually();
return true;
}
auto HttpMetaCache::evictEntry(MetaEntryPtr entry) -> bool
{
if (!entry)
return false;
entry->m_stale = true;
SaveEventually();
return true;
}
void HttpMetaCache::evictAll()
{
for (QString& base : m_entries.keys()) {
EntryMap& map = m_entries[base];
qCDebug(taskHttpMetaCacheLogC) << "Evicting base" << base;
for (MetaEntryPtr entry : map.entry_list) {
if (!evictEntry(entry))
qCWarning(taskHttpMetaCacheLogC) << "Unexpected missing cache entry" << entry->m_basePath;
}
map.entry_list.clear();
FS::deletePath(map.base_path);
}
}
auto HttpMetaCache::staleEntry(QString base, QString resource_path) -> MetaEntryPtr
{
auto foo = new MetaEntry();
foo->m_baseId = base;
foo->m_basePath = getBasePath(base);
foo->m_relativePath = resource_path;
foo->m_stale = true;
return MetaEntryPtr(foo);
}
void HttpMetaCache::addBase(QString base, QString base_root)
{
// TODO: report error
if (m_entries.contains(base))
return;
// TODO: check if the base path is valid
EntryMap foo;
foo.base_path = base_root;
m_entries[base] = foo;
}
auto HttpMetaCache::getBasePath(QString base) -> QString
{
if (m_entries.contains(base)) {
return m_entries[base].base_path;
}
return {};
}
void HttpMetaCache::Load()
{
if (m_index_file.isNull())
return;
QFile index(m_index_file);
if (!index.open(QIODevice::ReadOnly))
return;
QJsonParseError parseError;
QJsonDocument json = QJsonDocument::fromJson(index.readAll(), &parseError);
// Fail if the JSON is invalid.
if (parseError.error != QJsonParseError::NoError) {
qCritical() << QString("Failed to parse HttpMetaCache file: %1 at offset %2")
.arg(parseError.errorString(), QString::number(parseError.offset))
.toUtf8();
return;
}
// Make sure the root is an object.
if (!json.isObject()) {
qCritical() << "HttpMetaCache root should be an object.";
return;
}
auto root = json.object();
// check file version first
auto version_val = Json::ensureString(root, "version");
if (version_val != "1")
return;
// read the entry array
auto array = Json::ensureArray(root, "entries");
for (auto element : array) {
auto element_obj = Json::ensureObject(element);
auto base = Json::ensureString(element_obj, "base");
if (!m_entries.contains(base))
continue;
auto& entrymap = m_entries[base];
auto foo = new MetaEntry();
foo->m_baseId = base;
foo->m_relativePath = Json::ensureString(element_obj, "path");
foo->m_md5sum = Json::ensureString(element_obj, "md5sum");
foo->m_etag = Json::ensureString(element_obj, "etag");
foo->m_local_changed_timestamp = Json::ensureDouble(element_obj, "last_changed_timestamp");
foo->m_remote_changed_timestamp = Json::ensureString(element_obj, "remote_changed_timestamp");
foo->makeEternal(Json::ensureBoolean(element_obj, (const QString)QStringLiteral("eternal"), false));
if (!foo->isEternal()) {
foo->m_current_age = Json::ensureDouble(element_obj, "current_age");
foo->m_max_age = Json::ensureDouble(element_obj, "max_age");
}
// presumed innocent until closer examination
foo->m_stale = false;
entrymap.entry_list[foo->m_relativePath] = MetaEntryPtr(foo);
}
}
void HttpMetaCache::SaveEventually()
{
// reset the save timer
saveBatchingTimer.stop();
saveBatchingTimer.start(30000);
}
void HttpMetaCache::SaveNow()
{
if (m_index_file.isNull())
return;
qCDebug(taskHttpMetaCacheLogC) << "Saving metacache with" << m_entries.size() << "entries";
QJsonObject toplevel;
Json::writeString(toplevel, "version", "1");
QJsonArray entriesArr;
for (auto group : m_entries) {
for (auto entry : group.entry_list) {
// do not save stale entries. they are dead.
if (entry->m_stale) {
continue;
}
QJsonObject entryObj;
Json::writeString(entryObj, "base", entry->m_baseId);
Json::writeString(entryObj, "path", entry->m_relativePath);
Json::writeString(entryObj, "md5sum", entry->m_md5sum);
Json::writeString(entryObj, "etag", entry->m_etag);
entryObj.insert("last_changed_timestamp", QJsonValue(double(entry->m_local_changed_timestamp)));
if (!entry->m_remote_changed_timestamp.isEmpty())
entryObj.insert("remote_changed_timestamp", QJsonValue(entry->m_remote_changed_timestamp));
if (entry->isEternal()) {
entryObj.insert("eternal", true);
} else {
entryObj.insert("current_age", QJsonValue(double(entry->m_current_age)));
entryObj.insert("max_age", QJsonValue(double(entry->m_max_age)));
}
entriesArr.append(entryObj);
}
}
toplevel.insert("entries", entriesArr);
try {
Json::write(toplevel, m_index_file);
} catch (const Exception& e) {
qCWarning(taskHttpMetaCacheLogC) << "Error writing cache:" << e.what();
}
}
| 10,756
|
C++
|
.cpp
| 276
| 32.880435
| 123
| 0.659954
|
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,235
|
ApiUpload.cpp
|
PrismLauncher_PrismLauncher/launcher/net/ApiUpload.cpp
|
// 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 "net/ApiUpload.h"
#include "net/ApiHeaderProxy.h"
namespace Net {
Upload::Ptr ApiUpload::makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, QByteArray m_post_data)
{
auto up = Upload::makeByteArray(url, output, m_post_data);
up->addHeaderProxy(new ApiHeaderProxy());
return up;
}
} // namespace Net
| 1,096
|
C++
|
.cpp
| 28
| 37
| 106
| 0.74718
|
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,236
|
FileSink.cpp
|
PrismLauncher_PrismLauncher/launcher/net/FileSink.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
*
* 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 "FileSink.h"
#include "FileSystem.h"
#include "net/Logging.h"
namespace Net {
Task::State FileSink::init(QNetworkRequest& request)
{
auto result = initCache(request);
if (result != Task::State::Running) {
return result;
}
// create a new save file and open it for writing
if (!FS::ensureFilePathExists(m_filename)) {
qCCritical(taskNetLogC) << "Could not create folder for " + m_filename;
return Task::State::Failed;
}
wroteAnyData = false;
m_output_file.reset(new PSaveFile(m_filename));
if (!m_output_file->open(QIODevice::WriteOnly)) {
qCCritical(taskNetLogC) << "Could not open " + m_filename + " for writing";
return Task::State::Failed;
}
if (initAllValidators(request))
return Task::State::Running;
return Task::State::Failed;
}
Task::State FileSink::write(QByteArray& data)
{
if (!writeAllValidators(data) || m_output_file->write(data) != data.size()) {
qCCritical(taskNetLogC) << "Failed writing into " + m_filename;
m_output_file->cancelWriting();
m_output_file.reset();
wroteAnyData = false;
return Task::State::Failed;
}
wroteAnyData = true;
return Task::State::Running;
}
Task::State FileSink::abort()
{
m_output_file->cancelWriting();
failAllValidators();
return Task::State::Failed;
}
Task::State FileSink::finalize(QNetworkReply& reply)
{
bool gotFile = false;
QVariant statusCodeV = reply.attribute(QNetworkRequest::HttpStatusCodeAttribute);
bool validStatus = false;
int statusCode = statusCodeV.toInt(&validStatus);
if (validStatus) {
// this leaves out 304 Not Modified
gotFile = statusCode == 200 || statusCode == 203;
}
// if we wrote any data to the save file, we try to commit the data to the real file.
// if it actually got a proper file, we write it even if it was empty
if (gotFile || wroteAnyData) {
// ask validators for data consistency
// we only do this for actual downloads, not 'your data is still the same' cache hits
if (!finalizeAllValidators(reply))
return Task::State::Failed;
// nothing went wrong...
if (!m_output_file->commit()) {
qCCritical(taskNetLogC) << "Failed to commit changes to " << m_filename;
m_output_file->cancelWriting();
return Task::State::Failed;
}
}
// then get rid of the save file
m_output_file.reset();
return finalizeCache(reply);
}
Task::State FileSink::initCache(QNetworkRequest&)
{
return Task::State::Running;
}
Task::State FileSink::finalizeCache(QNetworkReply&)
{
return Task::State::Succeeded;
}
bool FileSink::hasLocalData()
{
QFileInfo info(m_filename);
return info.exists() && info.size() != 0;
}
} // namespace Net
| 4,350
|
C++
|
.cpp
| 119
| 32.235294
| 93
| 0.68661
|
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,237
|
Logging.cpp
|
PrismLauncher_PrismLauncher/launcher/net/Logging.cpp
|
// 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 "net/Logging.h"
Q_LOGGING_CATEGORY(taskNetLogC, "launcher.task.net")
Q_LOGGING_CATEGORY(taskDownloadLogC, "launcher.task.net.download")
Q_LOGGING_CATEGORY(taskUploadLogC, "launcher.task.net.upload")
Q_LOGGING_CATEGORY(taskMCSkinsLogC, "launcher.task.minecraft.skins")
Q_LOGGING_CATEGORY(taskMetaCacheLogC, "launcher.task.net.metacache")
Q_LOGGING_CATEGORY(taskHttpMetaCacheLogC, "launcher.task.net.metacache.http")
| 1,188
|
C++
|
.cpp
| 25
| 45.8
| 77
| 0.776916
|
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,238
|
Download.cpp
|
PrismLauncher_PrismLauncher/launcher/net/Download.cpp
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
* 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 "Download.h"
#include <QUrl>
#include <QDateTime>
#include <QFileInfo>
#include <memory>
#include "ByteArraySink.h"
#include "ChecksumValidator.h"
#include "MetaCacheSink.h"
namespace Net {
#if defined(LAUNCHER_APPLICATION)
auto Download::makeCached(QUrl url, MetaEntryPtr entry, Options options) -> Download::Ptr
{
auto dl = makeShared<Download>();
dl->m_url = url;
dl->setObjectName(QString("CACHE:") + url.toString());
dl->m_options = options;
auto md5Node = new ChecksumValidator(QCryptographicHash::Md5);
auto cachedNode = new MetaCacheSink(entry, md5Node, options.testFlag(Option::MakeEternal));
dl->m_sink.reset(cachedNode);
return dl;
}
#endif
auto Download::makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, Options options) -> Download::Ptr
{
auto dl = makeShared<Download>();
dl->m_url = url;
dl->setObjectName(QString("BYTES:") + url.toString());
dl->m_options = options;
dl->m_sink.reset(new ByteArraySink(output));
return dl;
}
auto Download::makeFile(QUrl url, QString path, Options options) -> Download::Ptr
{
auto dl = makeShared<Download>();
dl->m_url = url;
dl->setObjectName(QString("FILE:") + url.toString());
dl->m_options = options;
dl->m_sink.reset(new FileSink(path));
return dl;
}
QNetworkReply* Download::getReply(QNetworkRequest& request)
{
return m_network->get(request);
}
} // namespace Net
| 3,115
|
C++
|
.cpp
| 82
| 35.439024
| 108
| 0.725289
|
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,239
|
Upload.cpp
|
PrismLauncher_PrismLauncher/launcher/net/Upload.cpp
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
* 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 "Upload.h"
#include <memory>
#include <utility>
#include "ByteArraySink.h"
namespace Net {
QNetworkReply* Upload::getReply(QNetworkRequest& request)
{
if (!request.hasRawHeader("Content-Type"))
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
return m_network->post(request, m_post_data);
}
Upload::Ptr Upload::makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, QByteArray m_post_data)
{
auto up = makeShared<Upload>();
up->m_url = std::move(url);
up->m_sink.reset(new ByteArraySink(output));
up->m_post_data = std::move(m_post_data);
return up;
}
} // namespace Net
| 2,334
|
C++
|
.cpp
| 57
| 38.614035
| 103
| 0.731074
|
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,240
|
MetaCacheSink.cpp
|
PrismLauncher_PrismLauncher/launcher/net/MetaCacheSink.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
*
* 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 "MetaCacheSink.h"
#include <QFile>
#include <QFileInfo>
#include <QRegularExpression>
#include "Application.h"
#include "net/Logging.h"
namespace Net {
/** Maximum time to hold a cache entry
* = 1 week in seconds
*/
#define MAX_TIME_TO_EXPIRE 1 * 7 * 24 * 60 * 60
MetaCacheSink::MetaCacheSink(MetaEntryPtr entry, ChecksumValidator* md5sum, bool is_eternal)
: Net::FileSink(entry->getFullPath()), m_entry(entry), m_md5Node(md5sum), m_is_eternal(is_eternal)
{
addValidator(md5sum);
}
Task::State MetaCacheSink::initCache(QNetworkRequest& request)
{
if (!m_entry->isStale()) {
return Task::State::Succeeded;
}
// check if file exists, if it does, use its information for the request
QFile current(m_filename);
if (current.exists() && current.size() != 0) {
if (m_entry->getRemoteChangedTimestamp().size()) {
request.setRawHeader(QString("If-Modified-Since").toLatin1(), m_entry->getRemoteChangedTimestamp().toLatin1());
}
if (m_entry->getETag().size()) {
request.setRawHeader(QString("If-None-Match").toLatin1(), m_entry->getETag().toLatin1());
}
}
return Task::State::Running;
}
Task::State MetaCacheSink::finalizeCache(QNetworkReply& reply)
{
QFileInfo output_file_info(m_filename);
if (wroteAnyData) {
m_entry->setMD5Sum(m_md5Node->hash().toHex().constData());
}
m_entry->setETag(reply.rawHeader("ETag").constData());
if (reply.hasRawHeader("Last-Modified")) {
m_entry->setRemoteChangedTimestamp(reply.rawHeader("Last-Modified").constData());
}
m_entry->setLocalChangedTimestamp(output_file_info.lastModified().toUTC().toMSecsSinceEpoch());
{ // Cache lifetime
if (m_is_eternal) {
qCDebug(taskMetaCacheLogC) << "Adding eternal cache entry:" << m_entry->getFullPath();
m_entry->makeEternal(true);
} else if (reply.hasRawHeader("Cache-Control")) {
auto cache_control_header = reply.rawHeader("Cache-Control");
qCDebug(taskMetaCacheLogC) << "Parsing 'Cache-Control' header with" << cache_control_header;
QRegularExpression max_age_expr("max-age=([0-9]+)");
qint64 max_age = max_age_expr.match(cache_control_header).captured(1).toLongLong();
m_entry->setMaximumAge(max_age);
} else if (reply.hasRawHeader("Expires")) {
auto expires_header = reply.rawHeader("Expires");
qCDebug(taskMetaCacheLogC) << "Parsing 'Expires' header with" << expires_header;
qint64 max_age = QDateTime::fromString(expires_header).toSecsSinceEpoch() - QDateTime::currentSecsSinceEpoch();
m_entry->setMaximumAge(max_age);
} else {
m_entry->setMaximumAge(MAX_TIME_TO_EXPIRE);
}
if (reply.hasRawHeader("Age")) {
auto age_header = reply.rawHeader("Age");
qCDebug(taskMetaCacheLogC) << "Parsing 'Age' header with" << age_header;
qint64 current_age = age_header.toLongLong();
m_entry->setCurrentAge(current_age);
} else {
m_entry->setCurrentAge(0);
}
}
m_entry->setStale(false);
APPLICATION->metacache()->updateEntry(m_entry);
return Task::State::Succeeded;
}
bool MetaCacheSink::hasLocalData()
{
QFileInfo info(m_filename);
return info.exists() && info.size() != 0;
}
} // namespace Net
| 4,914
|
C++
|
.cpp
| 115
| 37.417391
| 123
| 0.678041
|
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,241
|
NetRequest.cpp
|
PrismLauncher_PrismLauncher/launcher/net/NetRequest.cpp
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 TheKodeToad <TheKodeToad@proton.me>
* Copyright (C) 2023 Rachel Powers <508861+Ryex@users.noreply.github.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 "NetRequest.h"
#include <QDateTime>
#include <QFileInfo>
#include <QNetworkReply>
#include <QUrl>
#include <memory>
#if defined(LAUNCHER_APPLICATION)
#include "Application.h"
#endif
#include "BuildConfig.h"
#include "MMCTime.h"
#include "StringUtils.h"
namespace Net {
void NetRequest::addValidator(Validator* v)
{
m_sink->addValidator(v);
}
void NetRequest::executeTask()
{
setStatus(tr("Requesting %1").arg(StringUtils::truncateUrlHumanFriendly(m_url, 80)));
if (getState() == Task::State::AbortedByUser) {
qCWarning(logCat) << getUid().toString() << "Attempt to start an aborted Request:" << m_url.toString();
emit aborted();
emit finished();
return;
}
QNetworkRequest request(m_url);
m_state = m_sink->init(request);
switch (m_state) {
case State::Succeeded:
qCDebug(logCat) << getUid().toString() << "Request cache hit " << m_url.toString();
emit succeeded();
emit finished();
return;
case State::Running:
qCDebug(logCat) << getUid().toString() << "Runninng " << m_url.toString();
break;
case State::Inactive:
case State::Failed:
emit failed("Failed to initialize sink");
emit finished();
return;
case State::AbortedByUser:
emit aborted();
emit finished();
return;
}
#if defined(LAUNCHER_APPLICATION)
auto user_agent = APPLICATION->getUserAgent();
#else
auto user_agent = BuildConfig.USER_AGENT;
#endif
request.setHeader(QNetworkRequest::UserAgentHeader, user_agent.toUtf8());
for (auto& header_proxy : m_headerProxies) {
header_proxy->writeHeaders(request);
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
#if defined(LAUNCHER_APPLICATION)
request.setTransferTimeout(APPLICATION->settings()->get("RequestTimeout").toInt() * 1000);
#else
request.setTransferTimeout();
#endif
#endif
m_last_progress_time = m_clock.now();
m_last_progress_bytes = 0;
auto rep = getReply(request);
if (rep == nullptr) // it failed
return;
m_reply.reset(rep);
connect(rep, &QNetworkReply::uploadProgress, this, &NetRequest::onProgress);
connect(rep, &QNetworkReply::downloadProgress, this, &NetRequest::onProgress);
connect(rep, &QNetworkReply::finished, this, &NetRequest::downloadFinished);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) // QNetworkReply::errorOccurred added in 5.15
connect(rep, &QNetworkReply::errorOccurred, this, &NetRequest::downloadError);
#else
connect(rep, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error), this, &NetRequest::downloadError);
#endif
connect(rep, &QNetworkReply::sslErrors, this, &NetRequest::sslErrors);
connect(rep, &QNetworkReply::readyRead, this, &NetRequest::downloadReadyRead);
}
void NetRequest::onProgress(qint64 bytesReceived, qint64 bytesTotal)
{
auto now = m_clock.now();
auto elapsed = now - m_last_progress_time;
// use milliseconds for speed precision
auto elapsed_ms = std::chrono::duration_cast<std::chrono::milliseconds>(elapsed);
auto bytes_received_since = bytesReceived - m_last_progress_bytes;
auto dl_speed_bps = (double)bytes_received_since / elapsed_ms.count() * 1000;
auto remaining_time_s = (bytesTotal - bytesReceived) / dl_speed_bps;
//: Current amount of bytes downloaded, out of the total amount of bytes in the download
QString dl_progress =
tr("%1 / %2").arg(StringUtils::humanReadableFileSize(bytesReceived)).arg(StringUtils::humanReadableFileSize(bytesTotal));
QString dl_speed_str;
if (elapsed_ms.count() > 0) {
auto str_eta = bytesTotal > 0 ? Time::humanReadableDuration(remaining_time_s) : tr("unknown");
//: Download speed, in bytes per second (remaining download time in parenthesis)
dl_speed_str = tr("%1 /s (%2)").arg(StringUtils::humanReadableFileSize(dl_speed_bps)).arg(str_eta);
} else {
//: Download speed at 0 bytes per second
dl_speed_str = tr("0 B/s");
}
setDetails(dl_progress + "\n" + dl_speed_str);
setProgress(bytesReceived, bytesTotal);
}
void NetRequest::downloadError(QNetworkReply::NetworkError error)
{
if (error == QNetworkReply::OperationCanceledError) {
qCCritical(logCat) << getUid().toString() << "Aborted " << m_url.toString();
m_state = State::Failed;
} else {
if (m_options & Option::AcceptLocalFiles) {
if (m_sink->hasLocalData()) {
m_state = State::Succeeded;
return;
}
}
// error happened during download.
qCCritical(logCat) << getUid().toString() << "Failed" << m_url.toString() << "with reason" << error;
if (m_reply)
qCCritical(logCat) << getUid().toString() << "HTTP Status" << replyStatusCode() << ";error" << errorString();
m_state = State::Failed;
}
}
void NetRequest::sslErrors(const QList<QSslError>& errors)
{
int i = 1;
for (auto error : errors) {
qCCritical(logCat) << getUid().toString() << "Request" << m_url.toString() << "SSL Error #" << i << " : " << error.errorString();
auto cert = error.certificate();
qCCritical(logCat) << getUid().toString() << "Certificate in question:\n" << cert.toText();
i++;
}
}
auto NetRequest::handleRedirect() -> bool
{
QUrl redirect = m_reply->header(QNetworkRequest::LocationHeader).toUrl();
if (!redirect.isValid()) {
if (!m_reply->hasRawHeader("Location")) {
// no redirect -> it's fine to continue
return false;
}
// there is a Location header, but it's not correct. we need to apply some workarounds...
QByteArray redirectBA = m_reply->rawHeader("Location");
if (redirectBA.size() == 0) {
// empty, yet present redirect header? WTF?
return false;
}
QString redirectStr = QString::fromUtf8(redirectBA);
if (redirectStr.startsWith("//")) {
/*
* IF the URL begins with //, we need to insert the URL scheme.
* See: https://bugreports.qt.io/browse/QTBUG-41061
* See: http://tools.ietf.org/html/rfc3986#section-4.2
*/
redirectStr = m_reply->url().scheme() + ":" + redirectStr;
} else if (redirectStr.startsWith("/")) {
/*
* IF the URL begins with /, we need to process it as a relative URL
*/
auto url = m_reply->url();
url.setPath(redirectStr, QUrl::TolerantMode);
redirectStr = url.toString();
}
/*
* Next, make sure the URL is parsed in tolerant mode. Qt doesn't parse the location header in tolerant mode, which causes issues.
* FIXME: report Qt bug for this
*/
redirect = QUrl(redirectStr, QUrl::TolerantMode);
if (!redirect.isValid()) {
qCWarning(logCat) << getUid().toString() << "Failed to parse redirect URL:" << redirectStr;
downloadError(QNetworkReply::ProtocolFailure);
return false;
}
qCDebug(logCat) << getUid().toString() << "Fixed location header:" << redirect;
} else {
qCDebug(logCat) << getUid().toString() << "Location header:" << redirect;
}
m_url = QUrl(redirect.toString());
qCDebug(logCat) << getUid().toString() << "Following redirect to " << m_url.toString();
executeTask();
return true;
}
void NetRequest::downloadFinished()
{
// handle HTTP redirection first
if (handleRedirect()) {
qCDebug(logCat) << getUid().toString() << "Request redirected:" << m_url.toString();
return;
}
// if the download failed before this point ...
if (m_state == State::Succeeded) // pretend to succeed so we continue processing :)
{
qCDebug(logCat) << getUid().toString() << "Request failed but we are allowed to proceed:" << m_url.toString();
m_sink->abort();
emit succeeded();
emit finished();
return;
} else if (m_state == State::Failed) {
qCDebug(logCat) << getUid().toString() << "Request failed in previous step:" << m_url.toString();
m_sink->abort();
emit failed(m_reply->errorString());
emit finished();
return;
} else if (m_state == State::AbortedByUser) {
qCDebug(logCat) << getUid().toString() << "Request aborted in previous step:" << m_url.toString();
m_sink->abort();
emit aborted();
emit finished();
return;
}
// make sure we got all the remaining data, if any
auto data = m_reply->readAll();
if (data.size()) {
qCDebug(logCat) << getUid().toString() << "Writing extra" << data.size() << "bytes";
m_state = m_sink->write(data);
if (m_state != State::Succeeded) {
qCDebug(logCat) << getUid().toString() << "Request failed to write:" << m_url.toString();
m_sink->abort();
emit failed("failed to write in sink");
emit finished();
return;
}
}
// otherwise, finalize the whole graph
m_state = m_sink->finalize(*m_reply.get());
if (m_state != State::Succeeded) {
qCDebug(logCat) << getUid().toString() << "Request failed to finalize:" << m_url.toString();
m_sink->abort();
emit failed("failed to finalize the request");
emit finished();
return;
}
qCDebug(logCat) << getUid().toString() << "Request succeeded:" << m_url.toString();
emit succeeded();
emit finished();
}
void NetRequest::downloadReadyRead()
{
if (m_state == State::Running) {
auto data = m_reply->readAll();
m_state = m_sink->write(data);
if (m_state == State::Failed) {
qCCritical(logCat) << getUid().toString() << "Failed to process response chunk";
}
// qDebug() << "Request" << m_url.toString() << "gained" << data.size() << "bytes";
} else {
qCCritical(logCat) << getUid().toString() << "Cannot write download data! illegal status " << m_status;
}
}
auto NetRequest::abort() -> bool
{
m_state = State::AbortedByUser;
if (m_reply) {
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0) // QNetworkReply::errorOccurred added in 5.15
disconnect(m_reply.get(), &QNetworkReply::errorOccurred, nullptr, nullptr);
#else
disconnect(m_reply.get(), QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error), nullptr, nullptr);
#endif
m_reply->abort();
}
return true;
}
int NetRequest::replyStatusCode() const
{
return m_reply ? m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() : -1;
}
QNetworkReply::NetworkError NetRequest::error() const
{
return m_reply ? m_reply->error() : QNetworkReply::NoError;
}
QUrl NetRequest::url() const
{
return m_url;
}
QString NetRequest::errorString() const
{
return m_reply ? m_reply->errorString() : "";
}
} // namespace Net
| 12,836
|
C++
|
.cpp
| 317
| 34.422713
| 138
| 0.640253
|
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,242
|
PasteUpload.cpp
|
PrismLauncher_PrismLauncher/launcher/net/PasteUpload.cpp
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Lenny McLennington <lenny@sneed.church>
* Copyright (C) 2022 Swirl <swurl@swurl.xyz>
* 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 "PasteUpload.h"
#include "Application.h"
#include "BuildConfig.h"
#include <QDebug>
#include <QFile>
#include <QHttpPart>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QUrlQuery>
#include "net/Logging.h"
std::array<PasteUpload::PasteTypeInfo, 4> PasteUpload::PasteTypes = { { { "0x0.st", "https://0x0.st", "" },
{ "hastebin", "https://hst.sh", "/documents" },
{ "paste.gg", "https://paste.gg", "/api/v1/pastes" },
{ "mclo.gs", "https://api.mclo.gs", "/1/log" } } };
PasteUpload::PasteUpload(QWidget* window, QString text, QString baseUrl, PasteType pasteType)
: m_window(window), m_baseUrl(baseUrl), m_pasteType(pasteType), m_text(text.toUtf8())
{
if (m_baseUrl == "")
m_baseUrl = PasteTypes.at(pasteType).defaultBase;
// HACK: Paste's docs say the standard API path is at /api/<version> but the official instance paste.gg doesn't follow that??
if (pasteType == PasteGG && m_baseUrl == PasteTypes.at(pasteType).defaultBase)
m_uploadUrl = "https://api.paste.gg/v1/pastes";
else
m_uploadUrl = m_baseUrl + PasteTypes.at(pasteType).endpointPath;
}
PasteUpload::~PasteUpload() {}
void PasteUpload::executeTask()
{
QNetworkRequest request{ QUrl(m_uploadUrl) };
QNetworkReply* rep{};
request.setHeader(QNetworkRequest::UserAgentHeader, APPLICATION->getUserAgentUncached().toUtf8());
switch (m_pasteType) {
case NullPointer: {
QHttpMultiPart* multiPart = new QHttpMultiPart{ QHttpMultiPart::FormDataType };
QHttpPart filePart;
filePart.setBody(m_text);
filePart.setHeader(QNetworkRequest::ContentTypeHeader, "text/plain");
filePart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"file\"; filename=\"log.txt\"");
multiPart->append(filePart);
rep = APPLICATION->network()->post(request, multiPart);
multiPart->setParent(rep);
break;
}
case Hastebin: {
request.setHeader(QNetworkRequest::UserAgentHeader, APPLICATION->getUserAgentUncached().toUtf8());
rep = APPLICATION->network()->post(request, m_text);
break;
}
case Mclogs: {
QUrlQuery postData;
postData.addQueryItem("content", m_text);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
rep = APPLICATION->network()->post(request, postData.toString().toUtf8());
break;
}
case PasteGG: {
QJsonObject obj;
QJsonDocument doc;
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
obj.insert("expires", QDateTime::currentDateTimeUtc().addDays(100).toString(Qt::DateFormat::ISODate));
QJsonArray files;
QJsonObject logFileInfo;
QJsonObject logFileContentInfo;
logFileContentInfo.insert("format", "text");
logFileContentInfo.insert("value", QString::fromUtf8(m_text));
logFileInfo.insert("name", "log.txt");
logFileInfo.insert("content", logFileContentInfo);
files.append(logFileInfo);
obj.insert("files", files);
doc.setObject(obj);
rep = APPLICATION->network()->post(request, doc.toJson());
break;
}
}
connect(rep, &QNetworkReply::uploadProgress, this, &Task::setProgress);
connect(rep, &QNetworkReply::finished, this, &PasteUpload::downloadFinished);
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
connect(rep, &QNetworkReply::errorOccurred, this, &PasteUpload::downloadError);
#else
connect(rep, QOverload<QNetworkReply::NetworkError>::of(&QNetworkReply::error), this, &PasteUpload::downloadError);
#endif
m_reply = std::shared_ptr<QNetworkReply>(rep);
setStatus(tr("Uploading to %1").arg(m_uploadUrl));
}
void PasteUpload::downloadError(QNetworkReply::NetworkError error)
{
// error happened during download.
qCCritical(taskUploadLogC) << getUid().toString() << "Network error: " << error;
emitFailed(m_reply->errorString());
}
void PasteUpload::downloadFinished()
{
QByteArray data = m_reply->readAll();
int statusCode = m_reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
if (m_reply->error() != QNetworkReply::NetworkError::NoError) {
emitFailed(tr("Network error: %1").arg(m_reply->errorString()));
m_reply.reset();
return;
} else if (statusCode != 200 && statusCode != 201) {
QString reasonPhrase = m_reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
emitFailed(tr("Error: %1 returned unexpected status code %2 %3").arg(m_uploadUrl).arg(statusCode).arg(reasonPhrase));
qCCritical(taskUploadLogC) << getUid().toString() << m_uploadUrl << " returned unexpected status code " << statusCode
<< " with body: " << data;
m_reply.reset();
return;
}
switch (m_pasteType) {
case NullPointer:
m_pasteLink = QString::fromUtf8(data).trimmed();
break;
case Hastebin: {
QJsonDocument jsonDoc{ QJsonDocument::fromJson(data) };
QJsonObject jsonObj{ jsonDoc.object() };
if (jsonObj.contains("key") && jsonObj["key"].isString()) {
QString key = jsonDoc.object()["key"].toString();
m_pasteLink = m_baseUrl + "/" + key;
} else {
emitFailed(tr("Error: %1 returned a malformed response body").arg(m_uploadUrl));
qCCritical(taskUploadLogC) << getUid().toString() << getUid().toString() << m_uploadUrl
<< " returned malformed response body: " << data;
return;
}
break;
}
case Mclogs: {
QJsonDocument jsonDoc{ QJsonDocument::fromJson(data) };
QJsonObject jsonObj{ jsonDoc.object() };
if (jsonObj.contains("success") && jsonObj["success"].isBool()) {
bool success = jsonObj["success"].toBool();
if (success) {
m_pasteLink = jsonObj["url"].toString();
} else {
QString error = jsonObj["error"].toString();
emitFailed(tr("Error: %1 returned an error: %2").arg(m_uploadUrl, error));
qCCritical(taskUploadLogC) << getUid().toString() << m_uploadUrl << " returned error: " << error;
qCCritical(taskUploadLogC) << getUid().toString() << "Response body: " << data;
return;
}
} else {
emitFailed(tr("Error: %1 returned a malformed response body").arg(m_uploadUrl));
qCCritical(taskUploadLogC) << getUid().toString() << m_uploadUrl << " returned malformed response body: " << data;
return;
}
break;
}
case PasteGG:
QJsonDocument jsonDoc{ QJsonDocument::fromJson(data) };
QJsonObject jsonObj{ jsonDoc.object() };
if (jsonObj.contains("status") && jsonObj["status"].isString()) {
QString status = jsonObj["status"].toString();
if (status == "success") {
m_pasteLink = m_baseUrl + "/p/anonymous/" + jsonObj["result"].toObject()["id"].toString();
} else {
QString error = jsonObj["error"].toString();
QString message =
(jsonObj.contains("message") && jsonObj["message"].isString()) ? jsonObj["message"].toString() : "none";
emitFailed(tr("Error: %1 returned an error code: %2\nError message: %3").arg(m_uploadUrl, error, message));
qCCritical(taskUploadLogC) << getUid().toString() << m_uploadUrl << " returned error: " << error;
qCCritical(taskUploadLogC) << getUid().toString() << "Error message: " << message;
qCCritical(taskUploadLogC) << getUid().toString() << "Response body: " << data;
return;
}
} else {
emitFailed(tr("Error: %1 returned a malformed response body").arg(m_uploadUrl));
qCCritical(taskUploadLogC) << getUid().toString() << m_uploadUrl << " returned malformed response body: " << data;
return;
}
break;
}
emitSucceeded();
}
| 10,396
|
C++
|
.cpp
| 208
| 39.822115
| 130
| 0.608777
|
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,243
|
ApiDownload.cpp
|
PrismLauncher_PrismLauncher/launcher/net/ApiDownload.cpp
|
// 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 "net/ApiDownload.h"
#include "net/ApiHeaderProxy.h"
namespace Net {
Download::Ptr ApiDownload::makeCached(QUrl url, MetaEntryPtr entry, Download::Options options)
{
auto dl = Download::makeCached(url, entry, options);
dl->addHeaderProxy(new ApiHeaderProxy());
return dl;
}
Download::Ptr ApiDownload::makeByteArray(QUrl url, std::shared_ptr<QByteArray> output, Download::Options options)
{
auto dl = Download::makeByteArray(url, output, options);
dl->addHeaderProxy(new ApiHeaderProxy());
return dl;
}
Download::Ptr ApiDownload::makeFile(QUrl url, QString path, Download::Options options)
{
auto dl = Download::makeFile(url, path, options);
dl->addHeaderProxy(new ApiHeaderProxy());
return dl;
}
} // namespace Net
| 1,528
|
C++
|
.cpp
| 40
| 35.75
| 113
| 0.748313
|
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,244
|
NetJob.cpp
|
PrismLauncher_PrismLauncher/launcher/net/NetJob.cpp
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* 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 "NetJob.h"
#include <QNetworkReply>
#include "net/NetRequest.h"
#include "tasks/ConcurrentTask.h"
#if defined(LAUNCHER_APPLICATION)
#include "Application.h"
#include "ui/dialogs/CustomMessageBox.h"
#endif
NetJob::NetJob(QString job_name, shared_qobject_ptr<QNetworkAccessManager> network, int max_concurrent)
: ConcurrentTask(job_name), m_network(network)
{
#if defined(LAUNCHER_APPLICATION)
if (APPLICATION_DYN && max_concurrent < 0)
max_concurrent = APPLICATION->settings()->get("NumberOfConcurrentDownloads").toInt();
#endif
if (max_concurrent > 0)
setMaxConcurrent(max_concurrent);
}
auto NetJob::addNetAction(Net::NetRequest::Ptr action) -> bool
{
action->setNetwork(m_network);
addTask(action);
return true;
}
void NetJob::executeNextSubTask()
{
// We're finished, check for failures and retry if we can (up to 3 times)
if (isRunning() && m_queue.isEmpty() && m_doing.isEmpty() && !m_failed.isEmpty() && m_try < 3) {
m_try += 1;
while (!m_failed.isEmpty()) {
auto task = m_failed.take(*m_failed.keyBegin());
m_done.remove(task.get());
m_queue.enqueue(task);
}
}
ConcurrentTask::executeNextSubTask();
}
auto NetJob::size() const -> int
{
return m_queue.size() + m_doing.size() + m_done.size();
}
auto NetJob::canAbort() const -> bool
{
bool canFullyAbort = true;
// can abort the downloads on the queue?
for (auto part : m_queue)
canFullyAbort &= part->canAbort();
// can abort the active downloads?
for (auto part : m_doing)
canFullyAbort &= part->canAbort();
return canFullyAbort;
}
auto NetJob::abort() -> bool
{
bool fullyAborted = true;
// fail all downloads on the queue
for (auto task : m_queue)
m_failed.insert(task.get(), task);
m_queue.clear();
// abort active downloads
auto toKill = m_doing.values();
for (auto part : toKill) {
fullyAborted &= part->abort();
}
if (fullyAborted)
emitAborted();
else
emitFailed(tr("Failed to abort all tasks in the NetJob!"));
return fullyAborted;
}
auto NetJob::getFailedActions() -> QList<Net::NetRequest*>
{
QList<Net::NetRequest*> failed;
for (auto index : m_failed) {
failed.push_back(dynamic_cast<Net::NetRequest*>(index.get()));
}
return failed;
}
auto NetJob::getFailedFiles() -> QList<QString>
{
QList<QString> failed;
for (auto index : m_failed) {
failed.append(static_cast<Net::NetRequest*>(index.get())->url().toString());
}
return failed;
}
void NetJob::updateState()
{
emit progress(m_done.count(), totalSize());
setStatus(tr("Executing %1 task(s) (%2 out of %3 are done)")
.arg(QString::number(m_doing.count()), QString::number(m_done.count()), QString::number(totalSize())));
}
bool NetJob::isOnline()
{
// check some errors that are ussually associated with the lack of internet
for (auto job : getFailedActions()) {
auto err = job->error();
if (err != QNetworkReply::HostNotFoundError && err != QNetworkReply::NetworkSessionFailedError) {
return true;
}
}
return false;
};
void NetJob::emitFailed(QString reason)
{
#if defined(LAUNCHER_APPLICATION)
if (APPLICATION_DYN && m_ask_retry && m_manual_try < APPLICATION->settings()->get("NumberOfManualRetries").toInt() && isOnline()) {
m_manual_try++;
auto response = CustomMessageBox::selectable(nullptr, "Confirm retry",
"The tasks failed.\n"
"Failed urls\n" +
getFailedFiles().join("\n\t") +
".\n"
"If this continues to happen please check the logs of the application.\n"
"Do you want to retry?",
QMessageBox::Warning, QMessageBox::Yes | QMessageBox::No, QMessageBox::No)
->exec();
if (response == QMessageBox::Yes) {
m_try = 0;
executeNextSubTask();
return;
}
}
#endif
ConcurrentTask::emitFailed(reason);
}
void NetJob::setAskRetry(bool askRetry)
{
m_ask_retry = askRetry;
}
| 6,107
|
C++
|
.cpp
| 166
| 30.253012
| 135
| 0.632415
|
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,245
|
MurmurHash2.cpp
|
PrismLauncher_PrismLauncher/libraries/murmur2/src/MurmurHash2.cpp
|
//-----------------------------------------------------------------------------
// MurmurHash2 was written by Austin Appleby, and is placed in the public
// domain. The author hereby disclaims copyright to this source code.
//
// This was modified as to possibilitate it's usage incrementally.
// Those modifications are also placed in the public domain, and the author of
// such modifications hereby disclaims copyright to this source code.
#include "MurmurHash2.h"
namespace Murmur2 {
// 'm' and 'r' are mixing constants generated offline.
// They're not really 'magic', they just happen to work well.
const uint32_t m = 0x5bd1e995;
const int r = 24;
uint32_t hash(Reader* file_stream, std::size_t buffer_size, std::function<bool(char)> filter_out)
{
auto* buffer = new char[buffer_size];
char data[4];
int read = 0;
uint32_t size = 0;
// We need the size without the filtered out characters before actually calculating the hash,
// to setup the initial value for the hash.
do {
read = file_stream->read(buffer, buffer_size);
for (int i = 0; i < read; i++) {
if (!filter_out(buffer[i]))
size += 1;
}
} while (!file_stream->eof());
file_stream->goToBeginning();
int index = 0;
// This forces a seed of 1.
IncrementalHashInfo info{ (uint32_t)1 ^ size, (uint32_t)size };
do {
read = file_stream->read(buffer, buffer_size);
for (int i = 0; i < read; i++) {
char c = buffer[i];
if (filter_out(c))
continue;
data[index] = c;
index = (index + 1) % 4;
// Mix 4 bytes at a time into the hash
if (index == 0)
FourBytes_MurmurHash2(reinterpret_cast<unsigned char*>(&data), info);
}
} while (!file_stream->eof());
// Do one last bit shuffle in the hash
FourBytes_MurmurHash2(reinterpret_cast<unsigned char*>(&data), info);
delete[] buffer;
return info.h;
}
void FourBytes_MurmurHash2(const unsigned char* data, IncrementalHashInfo& prev)
{
if (prev.len >= 4) {
// Not the final mix
uint32_t k = *reinterpret_cast<const uint32_t*>(data);
k *= m;
k ^= k >> r;
k *= m;
prev.h *= m;
prev.h ^= k;
prev.len -= 4;
} else {
// The final mix
// Handle the last few bytes of the input array
switch (prev.len) {
case 3:
prev.h ^= data[2] << 16;
/* fall through */
case 2:
prev.h ^= data[1] << 8;
/* fall through */
case 1:
prev.h ^= data[0];
prev.h *= m;
};
// Do a few final mixes of the hash to ensure the last few
// bytes are well-incorporated.
prev.h ^= prev.h >> 13;
prev.h *= m;
prev.h ^= prev.h >> 15;
prev.len = 0;
}
}
} // namespace Murmur2
| 2,995
|
C++
|
.cpp
| 84
| 27.952381
| 97
| 0.553324
|
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,246
|
rainbow.cpp
|
PrismLauncher_PrismLauncher/libraries/rainbow/src/rainbow.cpp
|
/* This was part of the KDE project - see KGuiAddons
* Copyright (C) 2007 Matthew Woehlke <mw_triad@users.sourceforge.net>
* Copyright (C) 2007 Olaf Schmidt <ojschmidt@kde.org>
* Copyright (C) 2007 Thomas Zander <zander@kde.org>
* Copyright (C) 2007 Zack Rusin <zack@kde.org>
* Copyright (C) 2015 Petr Mrazek <peterix@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "../include/rainbow.h"
#include <QColor>
#include <QImage>
#include <QtNumeric> // qIsNaN
#include <math.h>
// BEGIN internal helper functions
static inline qreal wrap(qreal a, qreal d = 1.0)
{
qreal r = fmod(a, d);
return (r < 0.0 ? d + r : (r > 0.0 ? r : 0.0));
}
// normalize: like qBound(a, 0.0, 1.0) but without needing the args and with
// "safer" behavior on NaN (isnan(a) -> return 0.0)
static inline qreal normalize(qreal a)
{
return (a < 1.0 ? (a > 0.0 ? a : 0.0) : 1.0);
}
///////////////////////////////////////////////////////////////////////////////
// HCY color space
#define HCY_REC 709 // use 709 for now
#if HCY_REC == 601
static const qreal yc[3] = { 0.299, 0.587, 0.114 };
#elif HCY_REC == 709
static const qreal yc[3] = { 0.2126, 0.7152, 0.0722 };
#else // use Qt values
static const qreal yc[3] = { 0.34375, 0.5, 0.15625 };
#endif
class KHCY {
public:
explicit KHCY(const QColor& color)
{
qreal r = gamma(color.redF());
qreal g = gamma(color.greenF());
qreal b = gamma(color.blueF());
a = color.alphaF();
// luma component
y = lumag(r, g, b);
// hue component
qreal p = qMax(qMax(r, g), b);
qreal n = qMin(qMin(r, g), b);
qreal d = 6.0 * (p - n);
if (n == p) {
h = 0.0;
} else if (r == p) {
h = ((g - b) / d);
} else if (g == p) {
h = ((b - r) / d) + (1.0 / 3.0);
} else {
h = ((r - g) / d) + (2.0 / 3.0);
}
// chroma component
if (r == g && g == b) {
c = 0.0;
} else {
c = qMax((y - n) / y, (p - y) / (1 - y));
}
}
explicit KHCY(qreal h_, qreal c_, qreal y_, qreal a_ = 1.0)
{
h = h_;
c = c_;
y = y_;
a = a_;
}
QColor qColor() const
{
// start with sane component values
qreal _h = wrap(h);
qreal _c = normalize(c);
qreal _y = normalize(y);
// calculate some needed variables
qreal _hs = _h * 6.0, th, tm;
if (_hs < 1.0) {
th = _hs;
tm = yc[0] + yc[1] * th;
} else if (_hs < 2.0) {
th = 2.0 - _hs;
tm = yc[1] + yc[0] * th;
} else if (_hs < 3.0) {
th = _hs - 2.0;
tm = yc[1] + yc[2] * th;
} else if (_hs < 4.0) {
th = 4.0 - _hs;
tm = yc[2] + yc[1] * th;
} else if (_hs < 5.0) {
th = _hs - 4.0;
tm = yc[2] + yc[0] * th;
} else {
th = 6.0 - _hs;
tm = yc[0] + yc[2] * th;
}
// calculate RGB channels in sorted order
qreal tn, to, tp;
if (tm >= _y) {
tp = _y + _y * _c * (1.0 - tm) / tm;
to = _y + _y * _c * (th - tm) / tm;
tn = _y - (_y * _c);
} else {
tp = _y + (1.0 - _y) * _c;
to = _y + (1.0 - _y) * _c * (th - tm) / (1.0 - tm);
tn = _y - (1.0 - _y) * _c * tm / (1.0 - tm);
}
// return RGB channels in appropriate order
if (_hs < 1.0) {
return QColor::fromRgbF(igamma(tp), igamma(to), igamma(tn), a);
} else if (_hs < 2.0) {
return QColor::fromRgbF(igamma(to), igamma(tp), igamma(tn), a);
} else if (_hs < 3.0) {
return QColor::fromRgbF(igamma(tn), igamma(tp), igamma(to), a);
} else if (_hs < 4.0) {
return QColor::fromRgbF(igamma(tn), igamma(to), igamma(tp), a);
} else if (_hs < 5.0) {
return QColor::fromRgbF(igamma(to), igamma(tn), igamma(tp), a);
} else {
return QColor::fromRgbF(igamma(tp), igamma(tn), igamma(to), a);
}
}
qreal h, c, y, a;
static qreal luma(const QColor& color) { return lumag(gamma(color.redF()), gamma(color.greenF()), gamma(color.blueF())); }
private:
static qreal gamma(qreal n) { return pow(normalize(n), 2.2); }
static qreal igamma(qreal n) { return pow(normalize(n), 1.0 / 2.2); }
static qreal lumag(qreal r, qreal g, qreal b) { return r * yc[0] + g * yc[1] + b * yc[2]; }
};
static inline qreal mixQreal(qreal a, qreal b, qreal bias)
{
return a + (b - a) * bias;
}
// END internal helper functions
qreal Rainbow::luma(const QColor& color)
{
return KHCY::luma(color);
}
void Rainbow::getHcy(const QColor& color, qreal* h, qreal* c, qreal* y, qreal* a)
{
if (!c || !h || !y) {
return;
}
KHCY khcy(color);
*c = khcy.c;
*h = khcy.h;
*y = khcy.y;
if (a) {
*a = khcy.a;
}
}
static qreal contrastRatioForLuma(qreal y1, qreal y2)
{
if (y1 > y2) {
return (y1 + 0.05) / (y2 + 0.05);
} else {
return (y2 + 0.05) / (y1 + 0.05);
}
}
qreal Rainbow::contrastRatio(const QColor& c1, const QColor& c2)
{
return contrastRatioForLuma(luma(c1), luma(c2));
}
QColor Rainbow::lighten(const QColor& color, qreal ky, qreal kc)
{
KHCY c(color);
c.y = 1.0 - normalize((1.0 - c.y) * (1.0 - ky));
c.c = 1.0 - normalize((1.0 - c.c) * kc);
return c.qColor();
}
QColor Rainbow::darken(const QColor& color, qreal ky, qreal kc)
{
KHCY c(color);
c.y = normalize(c.y * (1.0 - ky));
c.c = normalize(c.c * kc);
return c.qColor();
}
QColor Rainbow::shade(const QColor& color, qreal ky, qreal kc)
{
KHCY c(color);
c.y = normalize(c.y + ky);
c.c = normalize(c.c + kc);
return c.qColor();
}
static QColor tintHelper(const QColor& base, qreal baseLuma, const QColor& color, qreal amount)
{
KHCY result(Rainbow::mix(base, color, pow(amount, 0.3)));
result.y = mixQreal(baseLuma, result.y, amount);
return result.qColor();
}
QColor Rainbow::tint(const QColor& base, const QColor& color, qreal amount)
{
if (amount <= 0.0) {
return base;
}
if (amount >= 1.0) {
return color;
}
if (qIsNaN(amount)) {
return base;
}
qreal baseLuma = luma(base); // cache value because luma call is expensive
double ri = contrastRatioForLuma(baseLuma, luma(color));
double rg = 1.0 + ((ri + 1.0) * amount * amount * amount);
double u = 1.0, l = 0.0;
QColor result;
for (int i = 12; i; --i) {
double a = 0.5 * (l + u);
result = tintHelper(base, baseLuma, color, a);
double ra = contrastRatioForLuma(baseLuma, luma(result));
if (ra > rg) {
u = a;
} else {
l = a;
}
}
return result;
}
QColor Rainbow::mix(const QColor& c1, const QColor& c2, qreal bias)
{
if (bias <= 0.0) {
return c1;
}
if (bias >= 1.0) {
return c2;
}
if (qIsNaN(bias)) {
return c1;
}
qreal r = mixQreal(c1.redF(), c2.redF(), bias);
qreal g = mixQreal(c1.greenF(), c2.greenF(), bias);
qreal b = mixQreal(c1.blueF(), c2.blueF(), bias);
qreal a = mixQreal(c1.alphaF(), c2.alphaF(), bias);
return QColor::fromRgbF(r, g, b, a);
}
QColor Rainbow::overlayColors(const QColor& base, const QColor& paint, QPainter::CompositionMode comp)
{
// This isn't the fastest way, but should be "fast enough".
// It's also the only safe way to use QPainter::CompositionMode
QImage img(1, 1, QImage::Format_ARGB32_Premultiplied);
QPainter p(&img);
QColor start = base;
start.setAlpha(255); // opaque
p.fillRect(0, 0, 1, 1, start);
p.setCompositionMode(comp);
p.fillRect(0, 0, 1, 1, paint);
p.end();
return img.pixel(0, 0);
}
| 8,658
|
C++
|
.cpp
| 266
| 26.68797
| 126
| 0.545226
|
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,247
|
distroutils.cpp
|
PrismLauncher_PrismLauncher/libraries/systeminfo/src/distroutils.cpp
|
/*
Code has been taken from https://github.com/natefoo/lionshead and loosely
translated to C++ laced with Qt.
MIT License
Copyright (c) 2017 Nate Coraor
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "distroutils.h"
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QMap>
#include <QProcess>
#include <QRegularExpression>
#include <QSettings>
#include <QStringList>
#include <functional>
Sys::DistributionInfo Sys::read_os_release()
{
Sys::DistributionInfo out;
QStringList files = { "/etc/os-release", "/usr/lib/os-release" };
QString name;
QString version;
for (auto& file : files) {
if (!QFile::exists(file)) {
continue;
}
QSettings settings(file, QSettings::IniFormat);
if (settings.contains("ID")) {
name = settings.value("ID").toString().toLower();
} else if (settings.contains("NAME")) {
name = settings.value("NAME").toString().toLower();
} else {
continue;
}
if (settings.contains("VERSION_ID")) {
version = settings.value("VERSION_ID").toString().toLower();
} else if (settings.contains("VERSION")) {
version = settings.value("VERSION").toString().toLower();
}
break;
}
if (name.isEmpty()) {
return out;
}
out.distributionName = name;
out.distributionVersion = version;
return out;
}
bool Sys::main_lsb_info(Sys::LsbInfo& out)
{
int status = 0;
QProcess lsbProcess;
QStringList arguments;
arguments << "-a";
lsbProcess.start("lsb_release", arguments);
lsbProcess.waitForFinished();
status = lsbProcess.exitStatus();
QString output = lsbProcess.readAllStandardOutput();
qDebug() << output;
lsbProcess.close();
if (status == 0) {
auto lines = output.split('\n');
for (auto line : lines) {
int index = line.indexOf(':');
auto key = line.left(index).trimmed();
auto value = line.mid(index + 1).toLower().trimmed();
if (key == "Distributor ID")
out.distributor = value;
else if (key == "Release")
out.version = value;
else if (key == "Description")
out.description = value;
else if (key == "Codename")
out.codename = value;
}
return !out.distributor.isEmpty();
}
return false;
}
bool Sys::fallback_lsb_info(Sys::LsbInfo& out)
{
// running lsb_release failed, try to read the file instead
// /etc/lsb-release format, if the file even exists, is non-standard.
// Only the `lsb_release` command is specified by LSB. Nonetheless, some
// distributions install an /etc/lsb-release as part of the base
// distribution, but `lsb_release` remains optional.
QString file = "/etc/lsb-release";
if (QFile::exists(file)) {
QSettings settings(file, QSettings::IniFormat);
if (settings.contains("DISTRIB_ID")) {
out.distributor = settings.value("DISTRIB_ID").toString().toLower();
}
if (settings.contains("DISTRIB_RELEASE")) {
out.version = settings.value("DISTRIB_RELEASE").toString().toLower();
}
return !out.distributor.isEmpty();
}
return false;
}
void Sys::lsb_postprocess(Sys::LsbInfo& lsb, Sys::DistributionInfo& out)
{
QString dist = lsb.distributor;
QString vers = lsb.version;
if (dist.startsWith("redhatenterprise")) {
dist = "rhel";
} else if (dist == "archlinux") {
dist = "arch";
} else if (dist.startsWith("suse")) {
if (lsb.description.startsWith("opensuse")) {
dist = "opensuse";
} else if (lsb.description.startsWith("suse linux enterprise")) {
dist = "sles";
}
} else if (dist == "debian" and vers == "testing") {
vers = lsb.codename;
} else {
// ubuntu, debian, gentoo, scientific, slackware, ... ?
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
auto parts = dist.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
#else
auto parts = dist.split(QRegularExpression("\\s+"), QString::SkipEmptyParts);
#endif
if (parts.size()) {
dist = parts[0];
}
}
if (!dist.isEmpty()) {
out.distributionName = dist;
out.distributionVersion = vers;
}
}
Sys::DistributionInfo Sys::read_lsb_release()
{
LsbInfo lsb;
if (!main_lsb_info(lsb)) {
if (!fallback_lsb_info(lsb)) {
return Sys::DistributionInfo();
}
}
Sys::DistributionInfo out;
lsb_postprocess(lsb, out);
return out;
}
QString Sys::_extract_distribution(const QString& x)
{
QString release = x.toLower();
if (release.startsWith("red hat enterprise")) {
return "rhel";
}
if (release.startsWith("suse linux enterprise")) {
return "sles";
}
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
QStringList list = release.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
#else
QStringList list = release.split(QRegularExpression("\\s+"), QString::SkipEmptyParts);
#endif
if (list.size()) {
return list[0];
}
return QString();
}
QString Sys::_extract_version(const QString& x)
{
QRegularExpression versionish_string(QRegularExpression::anchoredPattern("\\d+(?:\\.\\d+)*$"));
#if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)
QStringList list = x.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
#else
QStringList list = x.split(QRegularExpression("\\s+"), QString::SkipEmptyParts);
#endif
for (int i = list.size() - 1; i >= 0; --i) {
QString chunk = list[i];
if (versionish_string.match(chunk).hasMatch()) {
return chunk;
}
}
return QString();
}
Sys::DistributionInfo Sys::read_legacy_release()
{
struct checkEntry {
QString file;
std::function<QString(const QString&)> extract_distro;
std::function<QString(const QString&)> extract_version;
};
QList<checkEntry> checks = {
{ "/etc/arch-release", [](const QString&) { return "arch"; }, [](const QString&) { return "rolling"; } },
{ "/etc/slackware-version", &Sys::_extract_distribution, &Sys::_extract_version },
{ QString(), &Sys::_extract_distribution, &Sys::_extract_version },
{ "/etc/debian_version", [](const QString&) { return "debian"; }, [](const QString& x) { return x; } },
};
for (auto& check : checks) {
QStringList files;
if (check.file.isNull()) {
QDir etcDir("/etc");
etcDir.setNameFilters({ "*-release" });
etcDir.setFilter(QDir::Files | QDir::NoDot | QDir::NoDotDot | QDir::Readable | QDir::Hidden);
files = etcDir.entryList();
} else {
files.append(check.file);
}
for (auto file : files) {
QFile relfile(file);
if (!relfile.open(QIODevice::ReadOnly | QIODevice::Text))
continue;
QString contents = QString::fromUtf8(relfile.readLine()).trimmed();
QString dist = check.extract_distro(contents);
QString vers = check.extract_version(contents);
if (!dist.isEmpty()) {
Sys::DistributionInfo out;
out.distributionName = dist;
out.distributionVersion = vers;
return out;
}
}
}
return Sys::DistributionInfo();
}
| 8,500
|
C++
|
.cpp
| 233
| 29.974249
| 113
| 0.629001
|
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,248
|
sys_unix.cpp
|
PrismLauncher_PrismLauncher/libraries/systeminfo/src/sys_unix.cpp
|
#include "sys.h"
#include "distroutils.h"
#include <sys/utsname.h>
#include <fstream>
#include <limits>
#include <QDebug>
#include <QString>
#include <QStringList>
Sys::KernelInfo Sys::getKernelInfo()
{
Sys::KernelInfo out;
struct utsname buf;
uname(&buf);
// NOTE: we assume linux here. this needs further elaboration
out.kernelType = KernelType::Linux;
out.kernelName = buf.sysname;
QString release = out.kernelVersion = buf.release;
// linux binary running on WSL is cursed.
out.isCursed = release.contains("WSL", Qt::CaseInsensitive) || release.contains("Microsoft", Qt::CaseInsensitive);
out.kernelMajor = 0;
out.kernelMinor = 0;
out.kernelPatch = 0;
auto sections = release.split('-');
if (sections.size() >= 1) {
auto versionParts = sections[0].split('.');
if (versionParts.size() >= 3) {
out.kernelMajor = versionParts[0].toInt();
out.kernelMinor = versionParts[1].toInt();
out.kernelPatch = versionParts[2].toInt();
} else {
qWarning() << "Not enough version numbers in " << sections[0] << " found " << versionParts.size();
}
} else {
qWarning() << "Not enough '-' sections in " << release << " found " << sections.size();
}
return out;
}
uint64_t Sys::getSystemRam()
{
std::string token;
#ifdef Q_OS_LINUX
std::ifstream file("/proc/meminfo");
while (file >> token) {
if (token == "MemTotal:") {
uint64_t mem;
if (file >> mem) {
return mem * 1024ull;
} else {
return 0;
}
}
// ignore rest of the line
file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
#elif defined(Q_OS_FREEBSD)
char buff[512];
FILE* fp = popen("sysctl hw.physmem", "r");
if (fp != NULL) {
while (fgets(buff, 512, fp) != NULL) {
std::string str(buff);
uint64_t mem = std::stoull(str.substr(12, std::string::npos));
return mem * 1024ull;
}
}
#endif
return 0; // nothing found
}
Sys::DistributionInfo Sys::getDistributionInfo()
{
DistributionInfo systemd_info = read_os_release();
DistributionInfo lsb_info = read_lsb_release();
DistributionInfo legacy_info = read_legacy_release();
DistributionInfo result = systemd_info + lsb_info + legacy_info;
if (result.distributionName.isNull()) {
result.distributionName = "unknown";
}
if (result.distributionVersion.isNull()) {
if (result.distributionName == "arch") {
result.distributionVersion = "rolling";
} else {
result.distributionVersion = "unknown";
}
}
return result;
}
| 2,768
|
C++
|
.cpp
| 85
| 26.2
| 118
| 0.60486
|
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,249
|
sys_win32.cpp
|
PrismLauncher_PrismLauncher/libraries/systeminfo/src/sys_win32.cpp
|
#include "sys.h"
#include <windows.h>
Sys::KernelInfo Sys::getKernelInfo()
{
Sys::KernelInfo out;
out.kernelType = KernelType::Windows;
out.kernelName = "Windows";
OSVERSIONINFOW osvi;
ZeroMemory(&osvi, sizeof(OSVERSIONINFOW));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOW);
GetVersionExW(&osvi);
out.kernelVersion = QString("%1.%2").arg(osvi.dwMajorVersion).arg(osvi.dwMinorVersion);
out.kernelMajor = osvi.dwMajorVersion;
out.kernelMinor = osvi.dwMinorVersion;
out.kernelPatch = osvi.dwBuildNumber;
return out;
}
uint64_t Sys::getSystemRam()
{
MEMORYSTATUSEX status;
status.dwLength = sizeof(status);
GlobalMemoryStatusEx(&status);
// bytes
return (uint64_t)status.ullTotalPhys;
}
Sys::DistributionInfo Sys::getDistributionInfo()
{
DistributionInfo result;
return result;
}
| 860
|
C++
|
.cpp
| 30
| 25
| 91
| 0.737288
|
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,250
|
sys_test.cpp
|
PrismLauncher_PrismLauncher/libraries/systeminfo/src/sys_test.cpp
|
#include <QTest>
#include <sys.h>
class SysTest : public QObject {
Q_OBJECT
private slots:
void test_kernelNotNull()
{
auto kinfo = Sys::getKernelInfo();
QVERIFY(!kinfo.kernelName.isEmpty());
QVERIFY(kinfo.kernelVersion != "0.0");
}
/*
void test_systemDistroNotNull()
{
auto kinfo = Sys::getDistributionInfo();
QVERIFY(!kinfo.distributionName.isEmpty());
QVERIFY(!kinfo.distributionVersion.isEmpty());
qDebug() << "Distro: " << kinfo.distributionName << "version" << kinfo.distributionVersion;
}
*/
};
QTEST_GUILESS_MAIN(SysTest)
#include "sys_test.moc"
| 682
|
C++
|
.cpp
| 23
| 23.086957
| 103
| 0.617737
|
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,251
|
sys_apple.cpp
|
PrismLauncher_PrismLauncher/libraries/systeminfo/src/sys_apple.cpp
|
#include "sys.h"
#include <sys/utsname.h>
#include <QDebug>
#include <QString>
#include <QStringList>
Sys::KernelInfo Sys::getKernelInfo()
{
Sys::KernelInfo out;
struct utsname buf;
uname(&buf);
out.kernelType = KernelType::Darwin;
out.kernelName = buf.sysname;
QString release = out.kernelVersion = buf.release;
// TODO: figure out how to detect cursed-ness (macOS emulated on linux via mad hacks and so on)
out.isCursed = false;
out.kernelMajor = 0;
out.kernelMinor = 0;
out.kernelPatch = 0;
auto sections = release.split('-');
if (sections.size() >= 1) {
auto versionParts = sections[0].split('.');
if (versionParts.size() >= 3) {
out.kernelMajor = versionParts[0].toInt();
out.kernelMinor = versionParts[1].toInt();
out.kernelPatch = versionParts[2].toInt();
} else {
qWarning() << "Not enough version numbers in " << sections[0] << " found " << versionParts.size();
}
} else {
qWarning() << "Not enough '-' sections in " << release << " found " << sections.size();
}
return out;
}
#include <sys/sysctl.h>
uint64_t Sys::getSystemRam()
{
uint64_t memsize;
size_t memsizesize = sizeof(memsize);
if (!sysctlbyname("hw.memsize", &memsize, &memsizesize, NULL, 0)) {
return memsize;
} else {
return 0;
}
}
Sys::DistributionInfo Sys::getDistributionInfo()
{
DistributionInfo result;
return result;
}
| 1,501
|
C++
|
.cpp
| 49
| 25.469388
| 110
| 0.630194
|
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,252
|
qdcss.cpp
|
PrismLauncher_PrismLauncher/libraries/qdcss/src/qdcss.cpp
|
// SPDX-FileCopyrightText: 2023 kumquat-ir 66188216+kumquat-ir@users.noreply.github.com
//
// SPDX-License-Identifier: LGPL-3.0-only
#include "qdcss.h"
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QRegularExpressionMatchIterator>
QRegularExpression ruleset_re = QRegularExpression(R"([#.]?(@?\w+?)\s*\{(.*?)\})", QRegularExpression::DotMatchesEverythingOption);
QRegularExpression rule_re = QRegularExpression(R"((\S+?)\s*:\s*(?:\"(.*?)(?<!\\)\"|'(.*?)(?<!\\)'|(\S+?))\s*(?:;|$))");
QDCSS::QDCSS(QString s)
{
// not much error handling over here...
// the original java code used indeces returned by the matcher for them, but QRE does not expose those
QRegularExpressionMatchIterator ruleset_i = ruleset_re.globalMatch(s);
while (ruleset_i.hasNext()) {
QRegularExpressionMatch ruleset = ruleset_i.next();
QString selector = ruleset.captured(1);
QString rules = ruleset.captured(2);
QRegularExpressionMatchIterator rule_i = rule_re.globalMatch(rules);
while (rule_i.hasNext()) {
QRegularExpressionMatch rule = rule_i.next();
QString property = rule.captured(1);
QString value;
if (!rule.captured(2).isNull()) {
value = rule.captured(2);
} else if (!rule.captured(3).isNull()) {
value = rule.captured(3);
} else {
value = rule.captured(4);
}
QString key = selector + "." + property;
if (!m_data.contains(key)) {
m_data.insert(key, QStringList());
}
m_data.find(key)->append(value);
}
}
}
std::optional<QString>* QDCSS::get(QString key)
{
auto found = m_data.find(key);
if (found == m_data.end() || found->empty()) {
return new std::optional<QString>;
}
return new std::optional<QString>(found->back());
}
| 1,928
|
C++
|
.cpp
| 46
| 34.5
| 131
| 0.6128
|
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,257
|
ParseUtils_test.cpp
|
PrismLauncher_PrismLauncher/tests/ParseUtils_test.cpp
|
#include <QTest>
#include <minecraft/ParseUtils.h>
class ParseUtilsTest : public QObject {
Q_OBJECT
private slots:
void test_Through_data()
{
QTest::addColumn<QString>("timestamp");
const char* timestamps[] = { "2016-02-29T13:49:54+01:00", "2016-02-26T15:21:11+00:01", "2016-02-24T15:52:36+01:13",
"2016-02-18T17:41:00+00:00", "2016-02-17T15:23:19+00:00", "2016-02-16T15:22:39+09:22",
"2016-02-10T15:06:41+00:00", "2016-02-04T15:28:02-05:33" };
for (unsigned i = 0; i < (sizeof(timestamps) / sizeof(const char*)); i++) {
QTest::newRow(timestamps[i]) << QString(timestamps[i]);
}
}
void test_Through()
{
QFETCH(QString, timestamp);
auto time_parsed = timeFromS3Time(timestamp);
auto time_serialized = timeToS3Time(time_parsed);
QCOMPARE(time_serialized, timestamp);
}
};
QTEST_GUILESS_MAIN(ParseUtilsTest)
#include "ParseUtils_test.moc"
| 1,023
|
C++
|
.cpp
| 25
| 32.44
| 123
| 0.599798
|
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,258
|
CatPack_test.cpp
|
PrismLauncher_PrismLauncher/tests/CatPack_test.cpp
|
#include <QTest>
#include <QDate>
#include <QFileInfo>
#include <QList>
#include <QTemporaryFile>
#include "FileSystem.h"
#include "ui/themes/CatPack.h"
class CatPackTest : public QObject {
Q_OBJECT
private slots:
void test_catPack()
{
auto dataDir = QDir(QFINDTESTDATA("testdata/CatPacks")).absolutePath();
auto fileName = FS::PathCombine(dataDir, "index.json");
auto fileinfo = QFileInfo(fileName);
try {
auto cat = JsonCatPack(fileinfo);
QCOMPARE(cat.path(QDate(2023, 4, 12)), FS::PathCombine(fileinfo.path(), "oneDay.png"));
QCOMPARE(cat.path(QDate(2023, 4, 11)), FS::PathCombine(fileinfo.path(), "maxwell.png"));
QCOMPARE(cat.path(QDate(2023, 4, 13)), FS::PathCombine(fileinfo.path(), "maxwell.png"));
QCOMPARE(cat.path(QDate(2023, 12, 21)), FS::PathCombine(fileinfo.path(), "christmas.png"));
QCOMPARE(cat.path(QDate(2023, 12, 28)), FS::PathCombine(fileinfo.path(), "christmas.png"));
QCOMPARE(cat.path(QDate(2023, 12, 29)), FS::PathCombine(fileinfo.path(), "newyear.png"));
QCOMPARE(cat.path(QDate(2023, 12, 30)), FS::PathCombine(fileinfo.path(), "newyear2.png"));
QCOMPARE(cat.path(QDate(2023, 12, 31)), FS::PathCombine(fileinfo.path(), "newyear2.png"));
QCOMPARE(cat.path(QDate(2024, 1, 1)), FS::PathCombine(fileinfo.path(), "newyear2.png"));
QCOMPARE(cat.path(QDate(2024, 1, 2)), FS::PathCombine(fileinfo.path(), "newyear.png"));
QCOMPARE(cat.path(QDate(2024, 1, 3)), FS::PathCombine(fileinfo.path(), "newyear.png"));
QCOMPARE(cat.path(QDate(2024, 1, 4)), FS::PathCombine(fileinfo.path(), "maxwell.png"));
} catch (const Exception& e) {
QFAIL(e.cause().toLatin1());
}
}
};
QTEST_GUILESS_MAIN(CatPackTest)
#include "CatPack_test.moc"
| 1,882
|
C++
|
.cpp
| 36
| 44.638889
| 103
| 0.635179
|
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,259
|
DataPackParse_test.cpp
|
PrismLauncher_PrismLauncher/tests/DataPackParse_test.cpp
|
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com>
//
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - 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 <QTest>
#include <QTimer>
#include <FileSystem.h>
#include <minecraft/mod/DataPack.h>
#include <minecraft/mod/tasks/LocalDataPackParseTask.h>
class DataPackParseTest : public QObject {
Q_OBJECT
private slots:
void test_parseZIP()
{
QString source = QFINDTESTDATA("testdata/DataPackParse");
QString zip_dp = FS::PathCombine(source, "test_data_pack_boogaloo.zip");
DataPack pack{ QFileInfo(zip_dp) };
bool valid = DataPackUtils::processZIP(pack);
QVERIFY(pack.packFormat() == 4);
QVERIFY(pack.description() == "Some data pack 2 boobgaloo");
QVERIFY(valid == true);
}
void test_parseFolder()
{
QString source = QFINDTESTDATA("testdata/DataPackParse");
QString folder_dp = FS::PathCombine(source, "test_folder");
DataPack pack{ QFileInfo(folder_dp) };
bool valid = DataPackUtils::processFolder(pack);
QVERIFY(pack.packFormat() == 10);
QVERIFY(pack.description() == "Some data pack, maybe");
QVERIFY(valid == true);
}
void test_parseFolder2()
{
QString source = QFINDTESTDATA("testdata/DataPackParse");
QString folder_dp = FS::PathCombine(source, "another_test_folder");
DataPack pack{ QFileInfo(folder_dp) };
bool valid = DataPackUtils::process(pack);
QVERIFY(pack.packFormat() == 6);
QVERIFY(pack.description() == "Some data pack three, leaves on the tree");
QVERIFY(valid == true);
}
};
QTEST_GUILESS_MAIN(DataPackParseTest)
#include "DataPackParse_test.moc"
| 2,443
|
C++
|
.cpp
| 60
| 35.633333
| 84
| 0.696277
|
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,260
|
Packwiz_test.cpp
|
PrismLauncher_PrismLauncher/tests/Packwiz_test.cpp
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* 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/>.
*/
#include <QTemporaryDir>
#include <QTest>
#include <modplatform/packwiz/Packwiz.h>
class PackwizTest : public QObject {
Q_OBJECT
private slots:
// Files taken from https://github.com/packwiz/packwiz-example-pack
void loadFromFile_Modrinth()
{
QString source = QFINDTESTDATA("testdata/Packwiz");
QDir index_dir(source);
QString slug_mod("borderless-mining");
QString file_name = slug_mod + ".pw.toml";
QVERIFY(index_dir.entryList().contains(file_name));
auto metadata = Packwiz::V1::getIndexForMod(index_dir, slug_mod);
QVERIFY(metadata.isValid());
QCOMPARE(metadata.name, "Borderless Mining");
QCOMPARE(metadata.filename, "borderless-mining-1.1.1+1.18.jar");
QCOMPARE(metadata.side, Packwiz::V1::Side::ClientSide);
QCOMPARE(metadata.url, QUrl("https://cdn.modrinth.com/data/kYq5qkSL/versions/1.1.1+1.18/borderless-mining-1.1.1+1.18.jar"));
QCOMPARE(metadata.hash_format, "sha512");
QCOMPARE(metadata.hash,
"c8fe6e15ddea32668822dddb26e1851e5f03834be4bcb2eff9c0da7fdc086a9b6cead78e31a44d3bc66335cba11144ee0337c6d5346f1ba6362306449"
"9b3188d");
QCOMPARE(metadata.provider, ModPlatform::ResourceProvider::MODRINTH);
QCOMPARE(metadata.version(), "ug2qKTPR");
QCOMPARE(metadata.mod_id(), "kYq5qkSL");
}
void loadFromFile_Curseforge()
{
QString source = QFINDTESTDATA("testdata/Packwiz");
QDir index_dir(source);
QString name_mod("screenshot-to-clipboard-fabric.pw.toml");
QVERIFY(index_dir.entryList().contains(name_mod));
// Try without the .pw.toml at the end
name_mod.chop(8);
auto metadata = Packwiz::V1::getIndexForMod(index_dir, name_mod);
QVERIFY(metadata.isValid());
QCOMPARE(metadata.name, "Screenshot to Clipboard (Fabric)");
QCOMPARE(metadata.filename, "screenshot-to-clipboard-1.0.7-fabric.jar");
QCOMPARE(metadata.side, Packwiz::V1::Side::UniversalSide);
QCOMPARE(metadata.url, QUrl("https://edge.forgecdn.net/files/3509/43/screenshot-to-clipboard-1.0.7-fabric.jar"));
QCOMPARE(metadata.hash_format, "murmur2");
QCOMPARE(metadata.hash, "1781245820");
QCOMPARE(metadata.provider, ModPlatform::ResourceProvider::FLAME);
QCOMPARE(metadata.file_id, 3509043);
QCOMPARE(metadata.project_id, 327154);
}
};
QTEST_GUILESS_MAIN(PackwizTest)
#include "Packwiz_test.moc"
| 3,315
|
C++
|
.cpp
| 69
| 41.695652
| 140
| 0.702728
|
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,261
|
ResourceFolderModel_test.cpp
|
PrismLauncher_PrismLauncher/tests/ResourceFolderModel_test.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 <QTemporaryDir>
#include <QTest>
#include <QTimer>
#include "BaseInstance.h"
#include <FileSystem.h>
#include <minecraft/mod/ModFolderModel.h>
#include <minecraft/mod/ResourceFolderModel.h>
#define EXEC_UPDATE_TASK(EXEC, VERIFY) \
QEventLoop loop; \
\
connect(&model, &ResourceFolderModel::updateFinished, &loop, &QEventLoop::quit); \
\
QTimer expire_timer; \
expire_timer.callOnTimeout(&loop, &QEventLoop::quit); \
expire_timer.setSingleShot(true); \
expire_timer.start(4000); \
\
VERIFY(EXEC); \
loop.exec(); \
\
QVERIFY2(expire_timer.isActive(), "Timer has expired. The update never finished."); \
expire_timer.stop(); \
\
disconnect(&model, nullptr, &loop, nullptr);
class ResourceFolderModelTest : public QObject {
Q_OBJECT
private slots:
// test for GH-1178 - install a folder with files to a mod list
void test_1178()
{
// source
QString source = QFINDTESTDATA("testdata/ResourceFolderModel/test_folder");
// sanity check
QVERIFY(!source.endsWith('/'));
auto verify = [](QString path) {
QDir target_dir(FS::PathCombine(path, "test_folder"));
QVERIFY(target_dir.entryList().contains("pack.mcmeta"));
QVERIFY(target_dir.entryList().contains("assets"));
};
// 1. test with no trailing /
{
QString folder = source;
QTemporaryDir tempDir;
QEventLoop loop;
ModFolderModel m(tempDir.path(), nullptr, true, true);
connect(&m, &ModFolderModel::updateFinished, &loop, &QEventLoop::quit);
QTimer expire_timer;
expire_timer.callOnTimeout(&loop, &QEventLoop::quit);
expire_timer.setSingleShot(true);
expire_timer.start(4000);
m.installResource(folder);
loop.exec();
QVERIFY2(expire_timer.isActive(), "Timer has expired. The update never finished.");
expire_timer.stop();
verify(tempDir.path());
}
// 2. test with trailing /
{
QString folder = source + '/';
QTemporaryDir tempDir;
QEventLoop loop;
ModFolderModel m(tempDir.path(), nullptr, true, true);
connect(&m, &ModFolderModel::updateFinished, &loop, &QEventLoop::quit);
QTimer expire_timer;
expire_timer.callOnTimeout(&loop, &QEventLoop::quit);
expire_timer.setSingleShot(true);
expire_timer.start(4000);
m.installResource(folder);
loop.exec();
QVERIFY2(expire_timer.isActive(), "Timer has expired. The update never finished.");
expire_timer.stop();
verify(tempDir.path());
}
}
void test_addFromWatch()
{
QString source = QFINDTESTDATA("testdata/ResourceFolderModel");
ModFolderModel model(source, nullptr, false, true);
QCOMPARE(model.size(), 0);
EXEC_UPDATE_TASK(model.startWatching(), )
for (auto mod : model.allMods())
qDebug() << mod->name();
QCOMPARE(model.size(), 4);
model.stopWatching();
}
void test_removeResource()
{
QString folder_resource = QFINDTESTDATA("testdata/ResourceFolderModel/test_folder");
QString file_mod = QFINDTESTDATA("testdata/ResourceFolderModel/supercoolmod.jar");
QTemporaryDir tmp;
ResourceFolderModel model(QDir(tmp.path()), nullptr, false, false);
QCOMPARE(model.size(), 0);
{ EXEC_UPDATE_TASK(model.installResource(file_mod), QVERIFY) }
QCOMPARE(model.size(), 1);
qDebug() << "Added first mod.";
{ EXEC_UPDATE_TASK(model.startWatching(), ) }
QCOMPARE(model.size(), 1);
qDebug() << "Started watching the temp folder.";
{ EXEC_UPDATE_TASK(model.installResource(folder_resource), QVERIFY) }
QCOMPARE(model.size(), 2);
qDebug() << "Added second mod.";
{
EXEC_UPDATE_TASK(model.uninstallResource("supercoolmod.jar"), QVERIFY);
}
QCOMPARE(model.size(), 1);
qDebug() << "Removed first mod.";
QString mod_file_name{ model.at(0).fileinfo().fileName() };
QVERIFY(!mod_file_name.isEmpty());
{
EXEC_UPDATE_TASK(model.uninstallResource(mod_file_name), QVERIFY);
}
QCOMPARE(model.size(), 0);
qDebug() << "Removed second mod.";
model.stopWatching();
}
void test_enable_disable()
{
QString folder_resource = QFINDTESTDATA("testdata/ResourceFolderModel/test_folder");
QString file_mod = QFINDTESTDATA("testdata/ResourceFolderModel/supercoolmod.jar");
QTemporaryDir tmp;
ResourceFolderModel model(tmp.path(), nullptr, false, false);
QCOMPARE(model.size(), 0);
{
EXEC_UPDATE_TASK(model.installResource(folder_resource), QVERIFY)
}
{
EXEC_UPDATE_TASK(model.installResource(file_mod), QVERIFY)
}
for (auto res : model.allResources())
qDebug() << res->name();
QCOMPARE(model.size(), 2);
auto& res_1 = model.at(0).type() != ResourceType::FOLDER ? model.at(0) : model.at(1);
auto& res_2 = model.at(0).type() == ResourceType::FOLDER ? model.at(0) : model.at(1);
auto id_1 = res_1.internal_id();
auto id_2 = res_2.internal_id();
bool initial_enabled_res_2 = res_2.enabled();
bool initial_enabled_res_1 = res_1.enabled();
QVERIFY(res_1.type() != ResourceType::FOLDER && res_1.type() != ResourceType::UNKNOWN);
qDebug() << "res_1 is of the correct type.";
QVERIFY(res_1.enabled());
qDebug() << "res_1 is initially enabled.";
QVERIFY(res_1.enable(EnableAction::TOGGLE));
QVERIFY(res_1.enabled() == !initial_enabled_res_1);
qDebug() << "res_1 got successfully toggled.";
QVERIFY(res_1.enable(EnableAction::TOGGLE));
qDebug() << "res_1 got successfully toggled again.";
QVERIFY(res_1.enabled() == initial_enabled_res_1);
QVERIFY(res_1.internal_id() == id_1);
qDebug() << "res_1 got back to its initial state.";
QVERIFY(!res_2.enable(initial_enabled_res_2 ? EnableAction::ENABLE : EnableAction::DISABLE));
QVERIFY(res_2.enabled() == initial_enabled_res_2);
QVERIFY(res_2.internal_id() == id_2);
}
};
QTEST_GUILESS_MAIN(ResourceFolderModelTest)
#include "ResourceFolderModel_test.moc"
| 9,017
|
C++
|
.cpp
| 190
| 37.578947
| 101
| 0.567469
|
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,262
|
GZip_test.cpp
|
PrismLauncher_PrismLauncher/tests/GZip_test.cpp
|
#include <QTest>
#include <GZip.h>
#include <random>
void fib(int& prev, int& cur)
{
auto ret = prev + cur;
prev = cur;
cur = ret;
}
class GZipTest : public QObject {
Q_OBJECT
private slots:
void test_Through()
{
// test up to 10 MB
static const int size = 10 * 1024 * 1024;
QByteArray random;
QByteArray compressed;
QByteArray decompressed;
std::default_random_engine eng((std::random_device())());
std::uniform_int_distribution<uint16_t> idis(0, std::numeric_limits<uint8_t>::max());
// initialize random buffer
for (int i = 0; i < size; i++) {
random.append(static_cast<char>(idis(eng)));
}
// initialize fibonacci
int prev = 1;
int cur = 1;
// test if fibonacci long random buffers pass through GZip
do {
QByteArray copy = random;
copy.resize(cur);
compressed.clear();
decompressed.clear();
QVERIFY(GZip::zip(copy, compressed));
QVERIFY(GZip::unzip(compressed, decompressed));
QCOMPARE(decompressed, copy);
fib(prev, cur);
} while (cur < size);
}
};
QTEST_GUILESS_MAIN(GZipTest)
#include "GZip_test.moc"
| 1,284
|
C++
|
.cpp
| 43
| 22.44186
| 93
| 0.580357
|
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,263
|
WorldSaveParse_test.cpp
|
PrismLauncher_PrismLauncher/tests/WorldSaveParse_test.cpp
|
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com>
//
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - 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 <QTest>
#include <QTimer>
#include <FileSystem.h>
#include <minecraft/mod/WorldSave.h>
#include <minecraft/mod/tasks/LocalWorldSaveParseTask.h>
class WorldSaveParseTest : public QObject {
Q_OBJECT
private slots:
void test_parseZIP()
{
QString source = QFINDTESTDATA("testdata/WorldSaveParse");
QString zip_ws = FS::PathCombine(source, "minecraft_save_1.zip");
WorldSave save{ QFileInfo(zip_ws) };
bool valid = WorldSaveUtils::processZIP(save);
QVERIFY(save.saveFormat() == WorldSaveFormat::SINGLE);
QVERIFY(save.saveDirName() == "world_1");
QVERIFY(valid == true);
}
void test_parse_ZIP2()
{
QString source = QFINDTESTDATA("testdata/WorldSaveParse");
QString zip_ws = FS::PathCombine(source, "minecraft_save_2.zip");
WorldSave save{ QFileInfo(zip_ws) };
bool valid = WorldSaveUtils::processZIP(save);
QVERIFY(save.saveFormat() == WorldSaveFormat::MULTI);
QVERIFY(save.saveDirName() == "world_2");
QVERIFY(valid == true);
}
void test_parseFolder()
{
QString source = QFINDTESTDATA("testdata/WorldSaveParse");
QString folder_ws = FS::PathCombine(source, "minecraft_save_3");
WorldSave save{ QFileInfo(folder_ws) };
bool valid = WorldSaveUtils::processFolder(save);
QVERIFY(save.saveFormat() == WorldSaveFormat::SINGLE);
QVERIFY(save.saveDirName() == "world_3");
QVERIFY(valid == true);
}
void test_parseFolder2()
{
QString source = QFINDTESTDATA("testdata/WorldSaveParse");
QString folder_ws = FS::PathCombine(source, "minecraft_save_4");
WorldSave save{ QFileInfo(folder_ws) };
bool valid = WorldSaveUtils::process(save);
QVERIFY(save.saveFormat() == WorldSaveFormat::MULTI);
QVERIFY(save.saveDirName() == "world_4");
QVERIFY(valid == true);
}
};
QTEST_GUILESS_MAIN(WorldSaveParseTest)
#include "WorldSaveParse_test.moc"
| 2,879
|
C++
|
.cpp
| 70
| 35.585714
| 84
| 0.690126
|
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,264
|
ResourcePackParse_test.cpp
|
PrismLauncher_PrismLauncher/tests/ResourcePackParse_test.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 <QTest>
#include <QTimer>
#include <FileSystem.h>
#include <minecraft/mod/ResourcePack.h>
#include <minecraft/mod/tasks/LocalResourcePackParseTask.h>
class ResourcePackParseTest : public QObject {
Q_OBJECT
private slots:
void test_parseZIP()
{
QString source = QFINDTESTDATA("testdata/ResourcePackParse");
QString zip_rp = FS::PathCombine(source, "test_resource_pack_idk.zip");
ResourcePack pack{ QFileInfo(zip_rp) };
bool valid = ResourcePackUtils::processZIP(pack, ResourcePackUtils::ProcessingLevel::BasicInfoOnly);
QVERIFY(pack.packFormat() == 3);
QVERIFY(pack.description() ==
"um dois, feijão com arroz, três quatro, feijão no prato, cinco seis, café inglês, sete oito, comer biscoito, nove dez "
"comer pastéis!!");
QVERIFY(valid == true);
}
void test_parseFolder()
{
QString source = QFINDTESTDATA("testdata/ResourcePackParse");
QString folder_rp = FS::PathCombine(source, "test_folder");
ResourcePack pack{ QFileInfo(folder_rp) };
bool valid = ResourcePackUtils::processFolder(pack, ResourcePackUtils::ProcessingLevel::BasicInfoOnly);
QVERIFY(pack.packFormat() == 1);
QVERIFY(pack.description() == "Some resource pack maybe");
QVERIFY(valid == true);
}
void test_parseFolder2()
{
QString source = QFINDTESTDATA("testdata/ResourcePackParse");
QString folder_rp = FS::PathCombine(source, "another_test_folder");
ResourcePack pack{ QFileInfo(folder_rp) };
bool valid = ResourcePackUtils::process(pack, ResourcePackUtils::ProcessingLevel::BasicInfoOnly);
QVERIFY(pack.packFormat() == 6);
QVERIFY(pack.description() == "o quartel pegou fogo, policia deu sinal, acode acode acode a bandeira nacional");
QVERIFY(valid == false); // no assets dir
}
};
QTEST_GUILESS_MAIN(ResourcePackParseTest)
#include "ResourcePackParse_test.moc"
| 2,746
|
C++
|
.cpp
| 60
| 40.066667
| 136
| 0.704733
|
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,265
|
MetaComponentParse_test.cpp
|
PrismLauncher_PrismLauncher/tests/MetaComponentParse_test.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 <QJsonDocument>
#include <QJsonObject>
#include <QJsonValue>
#include <QTest>
#include <QTimer>
#include <FileSystem.h>
#include <minecraft/mod/tasks/LocalResourcePackParseTask.h>
class MetaComponentParseTest : public QObject {
Q_OBJECT
void doTest(QString name)
{
QString source = QFINDTESTDATA("testdata/MetaComponentParse");
QString comp_rp = FS::PathCombine(source, name);
QFile file;
file.setFileName(comp_rp);
QVERIFY(file.open(QIODevice::ReadOnly | QIODevice::Text));
QString data = file.readAll();
file.close();
QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());
QJsonObject obj = doc.object();
QJsonValue description_json = obj.value("description");
QJsonValue expected_json = obj.value("expected_output");
QVERIFY(!description_json.isUndefined());
QVERIFY(expected_json.isString());
QString expected = expected_json.toString();
QString processed = ResourcePackUtils::processComponent(description_json);
QCOMPARE(processed, expected);
}
private slots:
void test_parseComponentBasic() { doTest("component_basic.json"); }
void test_parseComponentWithFormat() { doTest("component_with_format.json"); }
void test_parseComponentWithExtra() { doTest("component_with_extra.json"); }
void test_parseComponentWithLink() { doTest("component_with_link.json"); }
void test_parseComponentWithMixed() { doTest("component_with_mixed.json"); }
};
QTEST_GUILESS_MAIN(MetaComponentParseTest)
#include "MetaComponentParse_test.moc"
| 3,116
|
C++
|
.cpp
| 71
| 39.859155
| 82
| 0.723341
|
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,266
|
Task_test.cpp
|
PrismLauncher_PrismLauncher/tests/Task_test.cpp
|
#include <QTest>
#include <QThread>
#include <QTimer>
#include <tasks/ConcurrentTask.h>
#include <tasks/MultipleOptionsTask.h>
#include <tasks/SequentialTask.h>
#include <tasks/Task.h>
#include <array>
/* Does nothing. Only used for testing. */
class BasicTask : public Task {
Q_OBJECT
friend class TaskTest;
public:
BasicTask(bool show_debug_log = true) : Task(show_debug_log) {}
private:
void executeTask() override { emitSucceeded(); }
};
/* Does nothing. Only used for testing. */
class BasicTask_MultiStep : public Task {
Q_OBJECT
friend class TaskTest;
private:
auto isMultiStep() const -> bool override { return true; }
void executeTask() override {}
};
class BigConcurrentTask : public ConcurrentTask {
Q_OBJECT
void executeNextSubTask() override
{
// This is here only to help fill the stack a bit more quickly (if there's an issue, of course :^))
// Each tasks thus adds 1024 * 4 bytes to the stack, at the very least.
[[maybe_unused]] volatile std::array<uint32_t, 1024> some_data_on_the_stack{};
ConcurrentTask::executeNextSubTask();
}
};
class BigConcurrentTaskThread : public QThread {
Q_OBJECT
QTimer m_deadline;
void run() override
{
BigConcurrentTask big_task;
m_deadline.setInterval(10000);
// NOTE: Arbitrary value that manages to trigger a problem when there is one.
// Considering each tasks, in a problematic state, adds 1024 * 4 bytes to the stack,
// this number is enough to fill up 16 MiB of stack, more than enough to cause a problem.
static const unsigned s_num_tasks = 1 << 12;
for (unsigned i = 0; i < s_num_tasks; i++) {
auto sub_task = makeShared<BasicTask>(false);
big_task.addTask(sub_task);
}
connect(&big_task, &Task::finished, this, &QThread::quit);
connect(&m_deadline, &QTimer::timeout, this, [this] {
passed_the_deadline = true;
quit();
});
if (thread() != QThread::currentThread()) {
QMetaObject::invokeMethod(this, &BigConcurrentTaskThread::start_timer, Qt::QueuedConnection);
}
big_task.run();
exec();
}
void start_timer() { m_deadline.start(); }
public:
bool passed_the_deadline = false;
};
class TaskTest : public QObject {
Q_OBJECT
private slots:
void test_SetStatus_NoMultiStep()
{
BasicTask t;
QString status{ "test status" };
t.setStatus(status);
QCOMPARE(t.getStatus(), status);
QCOMPARE(t.getStepProgress().isEmpty(), TaskStepProgressList{}.isEmpty());
}
void test_SetStatus_MultiStep()
{
BasicTask_MultiStep t;
QString status{ "test status" };
t.setStatus(status);
QCOMPARE(t.getStatus(), status);
// Even though it is multi step, it does not override the getStepStatus method,
// so it should remain the same.
QCOMPARE(t.getStepProgress().isEmpty(), TaskStepProgressList{}.isEmpty());
}
void test_SetProgress()
{
BasicTask t;
int current = 42;
int total = 207;
t.setProgress(current, total);
QCOMPARE(t.getProgress(), current);
QCOMPARE(t.getTotalProgress(), total);
}
void test_basicRun()
{
BasicTask t;
QObject::connect(&t, &Task::finished,
[&t] { QVERIFY2(t.wasSuccessful(), "Task finished but was not successful when it should have been."); });
t.start();
QVERIFY2(QTest::qWaitFor([&t]() { return t.isFinished(); }, 1000), "Task didn't finish as it should.");
}
void test_basicConcurrentRun()
{
auto t1 = makeShared<BasicTask>();
auto t2 = makeShared<BasicTask>();
auto t3 = makeShared<BasicTask>();
ConcurrentTask t;
t.addTask(t1);
t.addTask(t2);
t.addTask(t3);
QObject::connect(&t, &Task::finished, [&t, &t1, &t2, &t3] {
QVERIFY2(t.wasSuccessful(), "Task finished but was not successful when it should have been.");
QVERIFY(t1->wasSuccessful());
QVERIFY(t2->wasSuccessful());
QVERIFY(t3->wasSuccessful());
});
t.start();
QVERIFY2(QTest::qWaitFor([&t]() { return t.isFinished(); }, 1000), "Task didn't finish as it should.");
}
// Tests if starting new tasks after the 6 initial ones is working
void test_moreConcurrentRun()
{
auto t1 = makeShared<BasicTask>();
auto t2 = makeShared<BasicTask>();
auto t3 = makeShared<BasicTask>();
auto t4 = makeShared<BasicTask>();
auto t5 = makeShared<BasicTask>();
auto t6 = makeShared<BasicTask>();
auto t7 = makeShared<BasicTask>();
auto t8 = makeShared<BasicTask>();
auto t9 = makeShared<BasicTask>();
ConcurrentTask t;
t.addTask(t1);
t.addTask(t2);
t.addTask(t3);
t.addTask(t4);
t.addTask(t5);
t.addTask(t6);
t.addTask(t7);
t.addTask(t8);
t.addTask(t9);
QObject::connect(&t, &Task::finished, [&t, &t1, &t2, &t3, &t4, &t5, &t6, &t7, &t8, &t9] {
QVERIFY2(t.wasSuccessful(), "Task finished but was not successful when it should have been.");
QVERIFY(t1->wasSuccessful());
QVERIFY(t2->wasSuccessful());
QVERIFY(t3->wasSuccessful());
QVERIFY(t4->wasSuccessful());
QVERIFY(t5->wasSuccessful());
QVERIFY(t6->wasSuccessful());
QVERIFY(t7->wasSuccessful());
QVERIFY(t8->wasSuccessful());
QVERIFY(t9->wasSuccessful());
});
t.start();
QVERIFY2(QTest::qWaitFor([&t]() { return t.isFinished(); }, 1000), "Task didn't finish as it should.");
}
void test_basicSequentialRun()
{
auto t1 = makeShared<BasicTask>();
auto t2 = makeShared<BasicTask>();
auto t3 = makeShared<BasicTask>();
SequentialTask t;
t.addTask(t1);
t.addTask(t2);
t.addTask(t3);
QObject::connect(&t, &Task::finished, [&t, &t1, &t2, &t3] {
QVERIFY2(t.wasSuccessful(), "Task finished but was not successful when it should have been.");
QVERIFY(t1->wasSuccessful());
QVERIFY(t2->wasSuccessful());
QVERIFY(t3->wasSuccessful());
});
t.start();
QVERIFY2(QTest::qWaitFor([&t]() { return t.isFinished(); }, 1000), "Task didn't finish as it should.");
}
void test_basicMultipleOptionsRun()
{
auto t1 = makeShared<BasicTask>();
auto t2 = makeShared<BasicTask>();
auto t3 = makeShared<BasicTask>();
MultipleOptionsTask t;
t.addTask(t1);
t.addTask(t2);
t.addTask(t3);
QObject::connect(&t, &Task::finished, [&t, &t1, &t2, &t3] {
QVERIFY2(t.wasSuccessful(), "Task finished but was not successful when it should have been.");
QVERIFY(t1->wasSuccessful());
QVERIFY(!t2->wasSuccessful());
QVERIFY(!t3->wasSuccessful());
});
t.start();
QVERIFY2(QTest::qWaitFor([&t]() { return t.isFinished(); }, 1000), "Task didn't finish as it should.");
}
void test_stackOverflowInConcurrentTask()
{
QEventLoop loop;
BigConcurrentTaskThread thread;
connect(&thread, &BigConcurrentTaskThread::finished, &loop, &QEventLoop::quit);
thread.start();
loop.exec();
QVERIFY(!thread.passed_the_deadline);
}
};
QTEST_GUILESS_MAIN(TaskTest)
#include "Task_test.moc"
| 7,726
|
C++
|
.cpp
| 206
| 29.514563
| 130
| 0.602547
|
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,267
|
FileSystem_test.cpp
|
PrismLauncher_PrismLauncher/tests/FileSystem_test.cpp
|
#include <QDir>
#include <QStandardPaths>
#include <QTemporaryDir>
#include <QTest>
#include <tasks/Task.h>
#include <FileSystem.h>
#include <StringUtils.h>
// Snippet from https://github.com/gulrak/filesystem#using-it-as-single-file-header
#ifdef __APPLE__
#include <Availability.h> // for deployment target to support pre-catalina targets without std::fs
#endif // __APPLE__
#if ((defined(_MSVC_LANG) && _MSVC_LANG >= 201703L) || (defined(__cplusplus) && __cplusplus >= 201703L)) && defined(__has_include)
#if __has_include(<filesystem>) && (!defined(__MAC_OS_X_VERSION_MIN_REQUIRED) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 101500)
#define GHC_USE_STD_FS
#include <filesystem>
namespace fs = std::filesystem;
#endif // MacOS min version check
#endif // Other OSes version check
#ifndef GHC_USE_STD_FS
#include <ghc/filesystem.hpp>
namespace fs = ghc::filesystem;
#endif
#include <pathmatcher/RegexpMatcher.h>
class LinkTask : public Task {
Q_OBJECT
friend class FileSystemTest;
LinkTask(QString src, QString dst)
{
m_lnk = new FS::create_link(src, dst, this);
m_lnk->debug(true);
}
~LinkTask() { delete m_lnk; }
void matcher(const IPathMatcher* filter) { m_lnk->matcher(filter); }
void linkRecursively(bool recursive)
{
m_lnk->linkRecursively(recursive);
m_linkRecursive = recursive;
}
void whitelist(bool b) { m_lnk->whitelist(b); }
void setMaxDepth(int depth) { m_lnk->setMaxDepth(depth); }
private:
void executeTask() override
{
if (!(*m_lnk)()) {
#if defined Q_OS_WIN32
if (!m_useHard) {
qDebug() << "EXPECTED: Link failure, Windows requires permissions for symlinks";
qDebug() << "atempting to run with privelage";
connect(m_lnk, &FS::create_link::finishedPrivileged, this, [this](bool gotResults) {
if (gotResults) {
emitSucceeded();
} else {
qDebug() << "Privileged run exited without results!";
emitFailed();
}
});
m_lnk->runPrivileged();
} else {
qDebug() << "Link Failed!" << m_lnk->getOSError().value() << m_lnk->getOSError().message().c_str();
}
#else
qDebug() << "Link Failed!" << m_lnk->getOSError().value() << m_lnk->getOSError().message().c_str();
#endif
} else {
emitSucceeded();
}
}
FS::create_link* m_lnk;
[[maybe_unused]] bool m_useHard = false;
bool m_linkRecursive = true;
};
class FileSystemTest : public QObject {
Q_OBJECT
const QString bothSlash = "/foo/";
const QString trailingSlash = "foo/";
const QString leadingSlash = "/foo";
private slots:
void test_pathCombine()
{
QCOMPARE(QString("/foo/foo"), FS::PathCombine(bothSlash, bothSlash));
QCOMPARE(QString("foo/foo"), FS::PathCombine(trailingSlash, trailingSlash));
QCOMPARE(QString("/foo/foo"), FS::PathCombine(leadingSlash, leadingSlash));
QCOMPARE(QString("/foo/foo/foo"), FS::PathCombine(bothSlash, bothSlash, bothSlash));
QCOMPARE(QString("foo/foo/foo"), FS::PathCombine(trailingSlash, trailingSlash, trailingSlash));
QCOMPARE(QString("/foo/foo/foo"), FS::PathCombine(leadingSlash, leadingSlash, leadingSlash));
}
void test_PathCombine1_data()
{
QTest::addColumn<QString>("result");
QTest::addColumn<QString>("path1");
QTest::addColumn<QString>("path2");
QTest::newRow("qt 1") << "/abc/def/ghi/jkl" << "/abc/def" << "ghi/jkl";
QTest::newRow("qt 2") << "/abc/def/ghi/jkl" << "/abc/def/" << "ghi/jkl";
#if defined(Q_OS_WIN)
QTest::newRow("win native, from C:") << "C:/abc" << "C:" << "abc";
QTest::newRow("win native 1") << "C:/abc/def/ghi/jkl" << "C:\\abc\\def" << "ghi\\jkl";
QTest::newRow("win native 2") << "C:/abc/def/ghi/jkl" << "C:\\abc\\def\\" << "ghi\\jkl";
#endif
}
void test_PathCombine1()
{
QFETCH(QString, result);
QFETCH(QString, path1);
QFETCH(QString, path2);
QCOMPARE(FS::PathCombine(path1, path2), result);
}
void test_PathCombine2_data()
{
QTest::addColumn<QString>("result");
QTest::addColumn<QString>("path1");
QTest::addColumn<QString>("path2");
QTest::addColumn<QString>("path3");
QTest::newRow("qt 1") << "/abc/def/ghi/jkl" << "/abc" << "def" << "ghi/jkl";
QTest::newRow("qt 2") << "/abc/def/ghi/jkl" << "/abc/" << "def" << "ghi/jkl";
QTest::newRow("qt 3") << "/abc/def/ghi/jkl" << "/abc" << "def/" << "ghi/jkl";
QTest::newRow("qt 4") << "/abc/def/ghi/jkl" << "/abc/" << "def/" << "ghi/jkl";
#if defined(Q_OS_WIN)
QTest::newRow("win 1") << "C:/abc/def/ghi/jkl" << "C:\\abc" << "def" << "ghi\\jkl";
QTest::newRow("win 2") << "C:/abc/def/ghi/jkl" << "C:\\abc\\" << "def" << "ghi\\jkl";
QTest::newRow("win 3") << "C:/abc/def/ghi/jkl" << "C:\\abc" << "def\\" << "ghi\\jkl";
QTest::newRow("win 4") << "C:/abc/def/ghi/jkl" << "C:\\abc\\" << "def" << "ghi\\jkl";
#endif
}
void test_PathCombine2()
{
QFETCH(QString, result);
QFETCH(QString, path1);
QFETCH(QString, path2);
QFETCH(QString, path3);
QCOMPARE(FS::PathCombine(path1, path2, path3), result);
}
void test_copy()
{
QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder");
auto f = [&folder]() {
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
FS::copy c(folder, target_dir.path());
c();
for (auto entry : target_dir.entryList()) {
qDebug() << entry;
}
QVERIFY(target_dir.entryList().contains("pack.mcmeta"));
QVERIFY(target_dir.entryList().contains("assets"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_copy_with_blacklist()
{
QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder");
auto f = [&folder]() {
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
FS::copy c(folder, target_dir.path());
RegexpMatcher re("[.]?mcmeta");
c.matcher(&re);
c();
for (auto entry : target_dir.entryList()) {
qDebug() << entry;
}
QVERIFY(!target_dir.entryList().contains("pack.mcmeta"));
QVERIFY(target_dir.entryList().contains("assets"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_copy_with_whitelist()
{
QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder");
auto f = [&folder]() {
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
FS::copy c(folder, target_dir.path());
RegexpMatcher re("[.]?mcmeta");
c.matcher(&re);
c.whitelist(true);
c();
for (auto entry : target_dir.entryList()) {
qDebug() << entry;
}
QVERIFY(target_dir.entryList().contains("pack.mcmeta"));
QVERIFY(!target_dir.entryList().contains("assets"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_copy_with_dot_hidden()
{
QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder");
auto f = [&folder]() {
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
FS::copy c(folder, target_dir.path());
c();
auto filter = QDir::Filter::Files | QDir::Filter::Dirs | QDir::Filter::Hidden;
for (auto entry : target_dir.entryList(filter)) {
qDebug() << entry;
}
QVERIFY(target_dir.entryList(filter).contains(".secret_folder"));
target_dir.cd(".secret_folder");
QVERIFY(target_dir.entryList(filter).contains(".secret_file.txt"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_copy_single_file()
{
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
{
QString file = QFINDTESTDATA("testdata/FileSystem/test_folder/pack.mcmeta");
qDebug() << "From:" << file << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "pack.mcmeta"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
FS::copy c(file, target_dir.filePath("pack.mcmeta"));
c();
auto filter = QDir::Filter::Files;
for (auto entry : target_dir.entryList(filter)) {
qDebug() << entry;
}
QVERIFY(target_dir.entryList(filter).contains("pack.mcmeta"));
}
}
void test_getDesktop() { QCOMPARE(FS::getDesktopDir(), QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)); }
void test_link()
{
QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder");
auto f = [&folder]() {
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
LinkTask lnk_tsk(folder, target_dir.path());
lnk_tsk.linkRecursively(false);
QObject::connect(&lnk_tsk, &Task::finished, [&lnk_tsk] {
QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been.");
});
lnk_tsk.start();
QVERIFY2(QTest::qWaitFor([&lnk_tsk]() { return lnk_tsk.isFinished(); }, 100000), "Task didn't finish as it should.");
for (auto entry : target_dir.entryList()) {
qDebug() << entry;
QFileInfo entry_lnk_info(target_dir.filePath(entry));
if (!entry_lnk_info.isDir())
QVERIFY(!entry_lnk_info.isSymLink());
}
QFileInfo lnk_info(target_dir.path());
QVERIFY(lnk_info.exists());
QVERIFY(lnk_info.isSymLink());
QVERIFY(target_dir.entryList().contains("pack.mcmeta"));
QVERIFY(target_dir.entryList().contains("assets"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_hard_link()
{
QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder");
auto f = [&folder]() {
// use working dir to prevent makeing a hard link to a tmpfs or across devices
QTemporaryDir tempDir("./tmp");
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
FS::create_link lnk(folder, target_dir.path());
lnk.useHardLinks(true);
lnk.debug(true);
if (!lnk()) {
qDebug() << "Link Failed!" << lnk.getOSError().value() << lnk.getOSError().message().c_str();
}
for (auto entry : target_dir.entryList()) {
qDebug() << entry;
QFileInfo entry_lnk_info(target_dir.filePath(entry));
QVERIFY(!entry_lnk_info.isSymLink());
QFileInfo entry_orig_info(QDir(folder).filePath(entry));
if (!entry_lnk_info.isDir()) {
qDebug() << "hard link equivalency?" << entry_lnk_info.absoluteFilePath() << "vs" << entry_orig_info.absoluteFilePath();
QVERIFY(fs::equivalent(fs::path(StringUtils::toStdString(entry_lnk_info.absoluteFilePath())),
fs::path(StringUtils::toStdString(entry_orig_info.absoluteFilePath()))));
}
}
QFileInfo lnk_info(target_dir.path());
QVERIFY(lnk_info.exists());
QVERIFY(!lnk_info.isSymLink());
QVERIFY(target_dir.entryList().contains("pack.mcmeta"));
QVERIFY(target_dir.entryList().contains("assets"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_link_with_blacklist()
{
QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder");
auto f = [&folder]() {
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
LinkTask lnk_tsk(folder, target_dir.path());
RegexpMatcher re("[.]?mcmeta");
lnk_tsk.matcher(&re);
lnk_tsk.linkRecursively(true);
QObject::connect(&lnk_tsk, &Task::finished, [&lnk_tsk] {
QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been.");
});
lnk_tsk.start();
QVERIFY2(QTest::qWaitFor([&lnk_tsk]() { return lnk_tsk.isFinished(); }, 100000), "Task didn't finish as it should.");
for (auto entry : target_dir.entryList()) {
qDebug() << entry;
QFileInfo entry_lnk_info(target_dir.filePath(entry));
if (!entry_lnk_info.isDir())
QVERIFY(entry_lnk_info.isSymLink());
}
QFileInfo lnk_info(target_dir.path());
QVERIFY(lnk_info.exists());
QVERIFY(!target_dir.entryList().contains("pack.mcmeta"));
QVERIFY(target_dir.entryList().contains("assets"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_link_with_whitelist()
{
QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder");
auto f = [&folder]() {
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
LinkTask lnk_tsk(folder, target_dir.path());
RegexpMatcher re("[.]?mcmeta");
lnk_tsk.matcher(&re);
lnk_tsk.linkRecursively(true);
lnk_tsk.whitelist(true);
QObject::connect(&lnk_tsk, &Task::finished, [&lnk_tsk] {
QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been.");
});
lnk_tsk.start();
QVERIFY2(QTest::qWaitFor([&lnk_tsk]() { return lnk_tsk.isFinished(); }, 100000), "Task didn't finish as it should.");
for (auto entry : target_dir.entryList()) {
qDebug() << entry;
QFileInfo entry_lnk_info(target_dir.filePath(entry));
if (!entry_lnk_info.isDir())
QVERIFY(entry_lnk_info.isSymLink());
}
QFileInfo lnk_info(target_dir.path());
QVERIFY(lnk_info.exists());
QVERIFY(target_dir.entryList().contains("pack.mcmeta"));
QVERIFY(!target_dir.entryList().contains("assets"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_link_with_dot_hidden()
{
QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder");
auto f = [&folder]() {
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
LinkTask lnk_tsk(folder, target_dir.path());
lnk_tsk.linkRecursively(true);
QObject::connect(&lnk_tsk, &Task::finished, [&lnk_tsk] {
QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been.");
});
lnk_tsk.start();
QVERIFY2(QTest::qWaitFor([&lnk_tsk]() { return lnk_tsk.isFinished(); }, 100000), "Task didn't finish as it should.");
auto filter = QDir::Filter::Files | QDir::Filter::Dirs | QDir::Filter::Hidden;
for (auto entry : target_dir.entryList(filter)) {
qDebug() << entry;
QFileInfo entry_lnk_info(target_dir.filePath(entry));
if (!entry_lnk_info.isDir())
QVERIFY(entry_lnk_info.isSymLink());
}
QFileInfo lnk_info(target_dir.path());
QVERIFY(lnk_info.exists());
QVERIFY(target_dir.entryList(filter).contains(".secret_folder"));
target_dir.cd(".secret_folder");
QVERIFY(target_dir.entryList(filter).contains(".secret_file.txt"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_link_single_file()
{
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
{
QString file = QFINDTESTDATA("testdata/FileSystem/test_folder/pack.mcmeta");
qDebug() << "From:" << file << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "pack.mcmeta"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
LinkTask lnk_tsk(file, target_dir.filePath("pack.mcmeta"));
QObject::connect(&lnk_tsk, &Task::finished, [&lnk_tsk] {
QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been.");
});
lnk_tsk.start();
QVERIFY2(QTest::qWaitFor([&lnk_tsk]() { return lnk_tsk.isFinished(); }, 100000), "Task didn't finish as it should.");
auto filter = QDir::Filter::Files;
for (auto entry : target_dir.entryList(filter)) {
qDebug() << entry;
}
QFileInfo lnk_info(target_dir.filePath("pack.mcmeta"));
QVERIFY(lnk_info.exists());
QVERIFY(lnk_info.isSymLink());
QVERIFY(target_dir.entryList(filter).contains("pack.mcmeta"));
}
}
void test_link_with_max_depth()
{
QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder");
auto f = [&folder]() {
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
LinkTask lnk_tsk(folder, target_dir.path());
lnk_tsk.linkRecursively(true);
lnk_tsk.setMaxDepth(0);
QObject::connect(&lnk_tsk, &Task::finished, [&lnk_tsk] {
QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been.");
});
lnk_tsk.start();
QVERIFY2(QTest::qWaitFor([&lnk_tsk]() { return lnk_tsk.isFinished(); }, 100000), "Task didn't finish as it should.");
QVERIFY(!QFileInfo(target_dir.path()).isSymLink());
auto filter = QDir::Filter::Files | QDir::Filter::Dirs | QDir::Filter::Hidden;
for (auto entry : target_dir.entryList(filter)) {
qDebug() << entry;
if (entry == "." || entry == "..")
continue;
QFileInfo entry_lnk_info(target_dir.filePath(entry));
QVERIFY(entry_lnk_info.isSymLink());
}
QFileInfo lnk_info(target_dir.path());
QVERIFY(lnk_info.exists());
QVERIFY(!lnk_info.isSymLink());
QVERIFY(target_dir.entryList().contains("pack.mcmeta"));
QVERIFY(target_dir.entryList().contains("assets"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_link_with_no_max_depth()
{
QString folder = QFINDTESTDATA("testdata/FileSystem/test_folder");
auto f = [&folder]() {
QTemporaryDir tempDir;
tempDir.setAutoRemove(true);
qDebug() << "From:" << folder << "To:" << tempDir.path();
QDir target_dir(FS::PathCombine(tempDir.path(), "test_folder"));
qDebug() << tempDir.path();
qDebug() << target_dir.path();
LinkTask lnk_tsk(folder, target_dir.path());
lnk_tsk.linkRecursively(true);
lnk_tsk.setMaxDepth(-1);
QObject::connect(&lnk_tsk, &Task::finished, [&lnk_tsk] {
QVERIFY2(lnk_tsk.wasSuccessful(), "Task finished but was not successful when it should have been.");
});
lnk_tsk.start();
QVERIFY2(QTest::qWaitFor([&lnk_tsk]() { return lnk_tsk.isFinished(); }, 100000), "Task didn't finish as it should.");
std::function<void(QString)> verify_check = [&verify_check](QString check_path) {
QDir check_dir(check_path);
auto filter = QDir::Filter::Files | QDir::Filter::Dirs | QDir::Filter::Hidden;
for (auto entry : check_dir.entryList(filter)) {
QFileInfo entry_lnk_info(check_dir.filePath(entry));
qDebug() << entry << check_dir.filePath(entry);
if (!entry_lnk_info.isDir()) {
QVERIFY(entry_lnk_info.isSymLink());
} else if (entry != "." && entry != "..") {
qDebug() << "Decending tree to verify symlinks:" << check_dir.filePath(entry);
verify_check(entry_lnk_info.filePath());
}
}
};
verify_check(target_dir.path());
QFileInfo lnk_info(target_dir.path());
QVERIFY(lnk_info.exists());
QVERIFY(target_dir.entryList().contains("pack.mcmeta"));
QVERIFY(target_dir.entryList().contains("assets"));
};
// first try variant without trailing /
QVERIFY(!folder.endsWith('/'));
f();
// then variant with trailing /
folder.append('/');
QVERIFY(folder.endsWith('/'));
f();
}
void test_path_depth()
{
QCOMPARE(FS::pathDepth(""), 0);
QCOMPARE(FS::pathDepth("."), 0);
QCOMPARE(FS::pathDepth("foo.txt"), 0);
QCOMPARE(FS::pathDepth("./foo.txt"), 0);
QCOMPARE(FS::pathDepth("./bar/foo.txt"), 1);
QCOMPARE(FS::pathDepth("../bar/foo.txt"), 0);
QCOMPARE(FS::pathDepth("/bar/foo.txt"), 1);
QCOMPARE(FS::pathDepth("baz/bar/foo.txt"), 2);
QCOMPARE(FS::pathDepth("/baz/bar/foo.txt"), 2);
QCOMPARE(FS::pathDepth("./baz/bar/foo.txt"), 2);
QCOMPARE(FS::pathDepth("/baz/../bar/foo.txt"), 1);
}
void test_path_trunc()
{
QCOMPARE(FS::pathTruncate("", 0), QDir::toNativeSeparators(""));
QCOMPARE(FS::pathTruncate("foo.txt", 0), QDir::toNativeSeparators(""));
QCOMPARE(FS::pathTruncate("foo.txt", 1), QDir::toNativeSeparators(""));
QCOMPARE(FS::pathTruncate("./bar/foo.txt", 0), QDir::toNativeSeparators("./bar"));
QCOMPARE(FS::pathTruncate("./bar/foo.txt", 1), QDir::toNativeSeparators("./bar"));
QCOMPARE(FS::pathTruncate("/bar/foo.txt", 1), QDir::toNativeSeparators("/bar"));
QCOMPARE(FS::pathTruncate("bar/foo.txt", 1), QDir::toNativeSeparators("bar"));
QCOMPARE(FS::pathTruncate("baz/bar/foo.txt", 2), QDir::toNativeSeparators("baz/bar"));
#if defined(Q_OS_WIN)
QCOMPARE(FS::pathTruncate("C:\\bar\\foo.txt", 1), QDir::toNativeSeparators("C:\\bar"));
#endif
}
};
QTEST_GUILESS_MAIN(FileSystemTest)
#include "FileSystem_test.moc"
| 26,897
|
C++
|
.cpp
| 600
| 34.016667
| 140
| 0.551818
|
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,268
|
TexturePackParse_test.cpp
|
PrismLauncher_PrismLauncher/tests/TexturePackParse_test.cpp
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2022 flowln <flowlnlnln@gmail.com>
* 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/>.
*/
#include <QTest>
#include <QTimer>
#include "FileSystem.h"
#include "minecraft/mod/TexturePack.h"
#include "minecraft/mod/tasks/LocalTexturePackParseTask.h"
class TexturePackParseTest : public QObject {
Q_OBJECT
private slots:
void test_parseZIP()
{
QString source = QFINDTESTDATA("testdata/TexturePackParse");
QString zip_rp = FS::PathCombine(source, "test_texture_pack_idk.zip");
TexturePack pack{ QFileInfo(zip_rp) };
bool valid = TexturePackUtils::processZIP(pack);
QVERIFY(pack.description() == "joe biden, wake up");
QVERIFY(valid == true);
}
void test_parseFolder()
{
QString source = QFINDTESTDATA("testdata/TexturePackParse");
QString folder_rp = FS::PathCombine(source, "test_texturefolder");
TexturePack pack{ QFileInfo(folder_rp) };
bool valid = TexturePackUtils::processFolder(pack, TexturePackUtils::ProcessingLevel::BasicInfoOnly);
QVERIFY(pack.description() == "Some texture pack surely");
QVERIFY(valid == true);
}
void test_parseFolder2()
{
QString source = QFINDTESTDATA("testdata/TexturePackParse");
QString folder_rp = FS::PathCombine(source, "another_test_texturefolder");
TexturePack pack{ QFileInfo(folder_rp) };
bool valid = TexturePackUtils::process(pack, TexturePackUtils::ProcessingLevel::BasicInfoOnly);
QVERIFY(pack.description() == "quieres\nfor real");
QVERIFY(valid == true);
}
};
QTEST_GUILESS_MAIN(TexturePackParseTest)
#include "TexturePackParse_test.moc"
| 2,393
|
C++
|
.cpp
| 56
| 37.785714
| 109
| 0.714532
|
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,269
|
Index_test.cpp
|
PrismLauncher_PrismLauncher/tests/Index_test.cpp
|
#include <QTest>
#include <meta/Index.h>
#include <meta/VersionList.h>
class IndexTest : public QObject {
Q_OBJECT
private slots:
void test_hasUid_and_getList()
{
Meta::Index windex({ std::make_shared<Meta::VersionList>("list1"), std::make_shared<Meta::VersionList>("list2"),
std::make_shared<Meta::VersionList>("list3") });
QVERIFY(windex.hasUid("list1"));
QVERIFY(!windex.hasUid("asdf"));
QVERIFY(windex.get("list2") != nullptr);
QCOMPARE(windex.get("list2")->uid(), QString("list2"));
QVERIFY(windex.get("adsf") != nullptr);
}
void test_merge()
{
Meta::Index windex({ std::make_shared<Meta::VersionList>("list1"), std::make_shared<Meta::VersionList>("list2"),
std::make_shared<Meta::VersionList>("list3") });
QCOMPARE(windex.lists().size(), 3);
windex.merge(std::shared_ptr<Meta::Index>(
new Meta::Index({ std::make_shared<Meta::VersionList>("list1"), std::make_shared<Meta::VersionList>("list2"),
std::make_shared<Meta::VersionList>("list3") })));
QCOMPARE(windex.lists().size(), 3);
windex.merge(std::shared_ptr<Meta::Index>(
new Meta::Index({ std::make_shared<Meta::VersionList>("list4"), std::make_shared<Meta::VersionList>("list2"),
std::make_shared<Meta::VersionList>("list5") })));
QCOMPARE(windex.lists().size(), 5);
windex.merge(std::shared_ptr<Meta::Index>(new Meta::Index({ std::make_shared<Meta::VersionList>("list6") })));
QCOMPARE(windex.lists().size(), 6);
}
};
QTEST_GUILESS_MAIN(IndexTest)
#include "Index_test.moc"
| 1,726
|
C++
|
.cpp
| 35
| 40.028571
| 121
| 0.596085
|
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,270
|
Library_test.cpp
|
PrismLauncher_PrismLauncher/tests/Library_test.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 <QTest>
#include <FileSystem.h>
#include <RuntimeContext.h>
#include <minecraft/Library.h>
#include <minecraft/MojangVersionFormat.h>
#include <minecraft/OneSixVersionFormat.h>
#include <net/HttpMetaCache.h>
class LibraryTest : public QObject {
Q_OBJECT
private:
LibraryPtr readMojangJson(const QString path)
{
QFile jsonFile(path);
jsonFile.open(QIODevice::ReadOnly);
auto data = jsonFile.readAll();
jsonFile.close();
ProblemContainer problems;
return MojangVersionFormat::libraryFromJson(problems, QJsonDocument::fromJson(data).object(), path);
}
// get absolute path to expected storage, assuming default cache prefix
QStringList getStorage(QString relative) { return { FS::PathCombine(cache->getBasePath("libraries"), relative) }; }
RuntimeContext dummyContext(QString system = "linux", QString arch = "64", QString realArch = "amd64")
{
RuntimeContext r;
r.javaArchitecture = arch;
r.javaRealArchitecture = realArch;
r.system = system;
return r;
}
private slots:
void initTestCase()
{
cache.reset(new HttpMetaCache());
cache->addBase("libraries", QDir("libraries").absolutePath());
dataDir = QDir(QFINDTESTDATA("testdata/Library")).absolutePath();
}
void test_legacy()
{
RuntimeContext r = dummyContext();
Library test("test.package:testname:testversion");
QCOMPARE(test.artifactPrefix(), QString("test.package:testname"));
QCOMPARE(test.isNative(), false);
QStringList jar, native, native32, native64;
test.getApplicableFiles(r, jar, native, native32, native64, QString());
QCOMPARE(jar, getStorage("test/package/testname/testversion/testname-testversion.jar"));
QCOMPARE(native, {});
QCOMPARE(native32, {});
QCOMPARE(native64, {});
}
void test_legacy_url()
{
RuntimeContext r = dummyContext();
QStringList failedFiles;
Library test("test.package:testname:testversion");
test.setRepositoryURL("file://foo/bar");
auto downloads = test.getDownloads(r, cache.get(), failedFiles, QString());
QCOMPARE(downloads.size(), 1);
QCOMPARE(failedFiles, {});
Net::NetRequest::Ptr dl = downloads[0];
QCOMPARE(dl->url(), QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion.jar"));
}
void test_legacy_url_local_broken()
{
RuntimeContext r = dummyContext();
Library test("test.package:testname:testversion");
QCOMPARE(test.isNative(), false);
QStringList failedFiles;
test.setHint("local");
auto downloads = test.getDownloads(r, cache.get(), failedFiles, QString());
QCOMPARE(downloads.size(), 0);
QCOMPARE(failedFiles, { "testname-testversion.jar" });
}
void test_legacy_url_local_override()
{
RuntimeContext r = dummyContext();
Library test("com.paulscode:codecwav:20101023");
QCOMPARE(test.isNative(), false);
QStringList failedFiles;
test.setHint("local");
auto downloads = test.getDownloads(r, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library"));
QCOMPARE(downloads.size(), 0);
qDebug() << failedFiles;
QCOMPARE(failedFiles.size(), 0);
QStringList jar, native, native32, native64;
test.getApplicableFiles(r, jar, native, native32, native64, QFINDTESTDATA("testdata/Library"));
QCOMPARE(jar, { QFileInfo(QFINDTESTDATA("testdata/Library/codecwav-20101023.jar")).absoluteFilePath() });
QCOMPARE(native, {});
QCOMPARE(native32, {});
QCOMPARE(native64, {});
}
void test_legacy_native()
{
RuntimeContext r = dummyContext();
Library test("test.package:testname:testversion");
test.m_nativeClassifiers["linux"] = "linux";
QCOMPARE(test.isNative(), true);
test.setRepositoryURL("file://foo/bar");
{
QStringList jar, native, native32, native64;
test.getApplicableFiles(r, jar, native, native32, native64, QString());
QCOMPARE(jar, {});
QCOMPARE(native, getStorage("test/package/testname/testversion/testname-testversion-linux.jar"));
QCOMPARE(native32, {});
QCOMPARE(native64, {});
QStringList failedFiles;
auto dls = test.getDownloads(r, cache.get(), failedFiles, QString());
QCOMPARE(dls.size(), 1);
QCOMPARE(failedFiles, {});
auto dl = dls[0];
QCOMPARE(dl->url(), QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-linux.jar"));
}
}
void test_legacy_native_arch()
{
RuntimeContext r = dummyContext();
Library test("test.package:testname:testversion");
test.m_nativeClassifiers["linux"] = "linux-${arch}";
test.m_nativeClassifiers["osx"] = "osx-${arch}";
test.m_nativeClassifiers["windows"] = "windows-${arch}";
QCOMPARE(test.isNative(), true);
test.setRepositoryURL("file://foo/bar");
{
QStringList jar, native, native32, native64;
test.getApplicableFiles(r, jar, native, native32, native64, QString());
QCOMPARE(jar, {});
QCOMPARE(native, {});
QCOMPARE(native32, getStorage("test/package/testname/testversion/testname-testversion-linux-32.jar"));
QCOMPARE(native64, getStorage("test/package/testname/testversion/testname-testversion-linux-64.jar"));
QStringList failedFiles;
auto dls = test.getDownloads(r, cache.get(), failedFiles, QString());
QCOMPARE(dls.size(), 2);
QCOMPARE(failedFiles, {});
QCOMPARE(dls[0]->url(), QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-linux-32.jar"));
QCOMPARE(dls[1]->url(), QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-linux-64.jar"));
}
r.system = "windows";
{
QStringList jar, native, native32, native64;
test.getApplicableFiles(r, jar, native, native32, native64, QString());
QCOMPARE(jar, {});
QCOMPARE(native, {});
QCOMPARE(native32, getStorage("test/package/testname/testversion/testname-testversion-windows-32.jar"));
QCOMPARE(native64, getStorage("test/package/testname/testversion/testname-testversion-windows-64.jar"));
QStringList failedFiles;
auto dls = test.getDownloads(r, cache.get(), failedFiles, QString());
QCOMPARE(dls.size(), 2);
QCOMPARE(failedFiles, {});
QCOMPARE(dls[0]->url(), QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-windows-32.jar"));
QCOMPARE(dls[1]->url(), QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-windows-64.jar"));
}
r.system = "osx";
{
QStringList jar, native, native32, native64;
test.getApplicableFiles(r, jar, native, native32, native64, QString());
QCOMPARE(jar, {});
QCOMPARE(native, {});
QCOMPARE(native32, getStorage("test/package/testname/testversion/testname-testversion-osx-32.jar"));
QCOMPARE(native64, getStorage("test/package/testname/testversion/testname-testversion-osx-64.jar"));
QStringList failedFiles;
auto dls = test.getDownloads(r, cache.get(), failedFiles, QString());
QCOMPARE(dls.size(), 2);
QCOMPARE(failedFiles, {});
QCOMPARE(dls[0]->url(), QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-osx-32.jar"));
QCOMPARE(dls[1]->url(), QUrl("file://foo/bar/test/package/testname/testversion/testname-testversion-osx-64.jar"));
}
}
void test_legacy_native_arch_local_override()
{
RuntimeContext r = dummyContext();
Library test("test.package:testname:testversion");
test.m_nativeClassifiers["linux"] = "linux-${arch}";
test.setHint("local");
QCOMPARE(test.isNative(), true);
test.setRepositoryURL("file://foo/bar");
{
QStringList jar, native, native32, native64;
test.getApplicableFiles(r, jar, native, native32, native64, QFINDTESTDATA("testdata/Library"));
QCOMPARE(jar, {});
QCOMPARE(native, {});
QCOMPARE(native32, { QFileInfo(QFINDTESTDATA("testdata/Library/testname-testversion-linux-32.jar")).absoluteFilePath() });
QCOMPARE(native64, { QFileInfo(QFINDTESTDATA("testdata/Library") + "/testname-testversion-linux-64.jar").absoluteFilePath() });
QStringList failedFiles;
auto dls = test.getDownloads(r, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library"));
QCOMPARE(dls.size(), 0);
QCOMPARE(failedFiles,
{ QFileInfo(QFINDTESTDATA("testdata/Library") + "/testname-testversion-linux-64.jar").absoluteFilePath() });
}
}
void test_onenine()
{
RuntimeContext r = dummyContext("osx");
auto test = readMojangJson(QFINDTESTDATA("testdata/Library/lib-simple.json"));
{
QStringList jar, native, native32, native64;
test->getApplicableFiles(r, jar, native, native32, native64, QString());
QCOMPARE(jar, getStorage("com/paulscode/codecwav/20101023/codecwav-20101023.jar"));
QCOMPARE(native, {});
QCOMPARE(native32, {});
QCOMPARE(native64, {});
}
r.system = "linux";
{
QStringList failedFiles;
auto dls = test->getDownloads(r, cache.get(), failedFiles, QString());
QCOMPARE(dls.size(), 1);
QCOMPARE(failedFiles, {});
QCOMPARE(dls[0]->url(), QUrl("https://libraries.minecraft.net/com/paulscode/codecwav/20101023/codecwav-20101023.jar"));
}
r.system = "osx";
test->setHint("local");
{
QStringList jar, native, native32, native64;
test->getApplicableFiles(r, jar, native, native32, native64, QFINDTESTDATA("testdata/Library"));
QCOMPARE(jar, { QFileInfo(QFINDTESTDATA("testdata/Library/codecwav-20101023.jar")).absoluteFilePath() });
QCOMPARE(native, {});
QCOMPARE(native32, {});
QCOMPARE(native64, {});
}
r.system = "linux";
{
QStringList failedFiles;
auto dls = test->getDownloads(r, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library"));
QCOMPARE(dls.size(), 0);
QCOMPARE(failedFiles, {});
}
}
void test_onenine_local_override()
{
RuntimeContext r = dummyContext("osx");
auto test = readMojangJson(QFINDTESTDATA("testdata/Library/lib-simple.json"));
test->setHint("local");
{
QStringList jar, native, native32, native64;
test->getApplicableFiles(r, jar, native, native32, native64, QFINDTESTDATA("testdata/Library"));
QCOMPARE(jar, { QFileInfo(QFINDTESTDATA("testdata/Library/codecwav-20101023.jar")).absoluteFilePath() });
QCOMPARE(native, {});
QCOMPARE(native32, {});
QCOMPARE(native64, {});
}
r.system = "linux";
{
QStringList failedFiles;
auto dls = test->getDownloads(r, cache.get(), failedFiles, QFINDTESTDATA("testdata/Library"));
QCOMPARE(dls.size(), 0);
QCOMPARE(failedFiles, {});
}
}
void test_onenine_native()
{
RuntimeContext r = dummyContext("osx");
auto test = readMojangJson(QFINDTESTDATA("testdata/Library/lib-native.json"));
QStringList jar, native, native32, native64;
test->getApplicableFiles(r, jar, native, native32, native64, QString());
QCOMPARE(jar, QStringList());
QCOMPARE(native,
getStorage("org/lwjgl/lwjgl/lwjgl-platform/2.9.4-nightly-20150209/lwjgl-platform-2.9.4-nightly-20150209-natives-osx.jar"));
QCOMPARE(native32, {});
QCOMPARE(native64, {});
QStringList failedFiles;
auto dls = test->getDownloads(r, cache.get(), failedFiles, QString());
QCOMPARE(dls.size(), 1);
QCOMPARE(failedFiles, {});
QCOMPARE(dls[0]->url(), QUrl("https://libraries.minecraft.net/org/lwjgl/lwjgl/lwjgl-platform/2.9.4-nightly-20150209/"
"lwjgl-platform-2.9.4-nightly-20150209-natives-osx.jar"));
}
void test_onenine_native_arch()
{
RuntimeContext r = dummyContext("windows");
auto test = readMojangJson(QFINDTESTDATA("testdata/Library/lib-native-arch.json"));
QStringList jar, native, native32, native64;
test->getApplicableFiles(r, jar, native, native32, native64, QString());
QCOMPARE(jar, {});
QCOMPARE(native, {});
QCOMPARE(native32, getStorage("tv/twitch/twitch-platform/5.16/twitch-platform-5.16-natives-windows-32.jar"));
QCOMPARE(native64, getStorage("tv/twitch/twitch-platform/5.16/twitch-platform-5.16-natives-windows-64.jar"));
QStringList failedFiles;
auto dls = test->getDownloads(r, cache.get(), failedFiles, QString());
QCOMPARE(dls.size(), 2);
QCOMPARE(failedFiles, {});
QCOMPARE(dls[0]->url(),
QUrl("https://libraries.minecraft.net/tv/twitch/twitch-platform/5.16/twitch-platform-5.16-natives-windows-32.jar"));
QCOMPARE(dls[1]->url(),
QUrl("https://libraries.minecraft.net/tv/twitch/twitch-platform/5.16/twitch-platform-5.16-natives-windows-64.jar"));
}
private:
std::unique_ptr<HttpMetaCache> cache;
QString dataDir;
};
QTEST_GUILESS_MAIN(LibraryTest)
#include "Library_test.moc"
| 15,465
|
C++
|
.cpp
| 324
| 39.030864
| 140
| 0.642546
|
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,271
|
MojangVersionFormat_test.cpp
|
PrismLauncher_PrismLauncher/tests/MojangVersionFormat_test.cpp
|
#include <QDebug>
#include <QTest>
#include <minecraft/MojangVersionFormat.h>
class MojangVersionFormatTest : public QObject {
Q_OBJECT
static QJsonDocument readJson(const QString path)
{
QFile jsonFile(path);
jsonFile.open(QIODevice::ReadOnly);
auto data = jsonFile.readAll();
jsonFile.close();
return QJsonDocument::fromJson(data);
}
static void writeJson(const char* file, QJsonDocument doc)
{
QFile jsonFile(file);
jsonFile.open(QIODevice::WriteOnly | QIODevice::Text);
auto data = doc.toJson(QJsonDocument::Indented);
qDebug() << QString::fromUtf8(data);
jsonFile.write(data);
jsonFile.close();
}
private slots:
void test_Through_Simple()
{
QJsonDocument doc = readJson(QFINDTESTDATA("testdata/MojangVersionFormat/1.9-simple.json"));
auto vfile = MojangVersionFormat::versionFileFromJson(doc, "1.9-simple.json");
auto doc2 = MojangVersionFormat::versionFileToJson(vfile);
writeJson("1.9-simple-passthorugh.json", doc2);
QCOMPARE(doc.toJson(), doc2.toJson());
}
void test_Through()
{
QJsonDocument doc = readJson(QFINDTESTDATA("testdata/MojangVersionFormat/1.9.json"));
auto vfile = MojangVersionFormat::versionFileFromJson(doc, "1.9.json");
auto doc2 = MojangVersionFormat::versionFileToJson(vfile);
writeJson("1.9-passthorugh.json", doc2);
QCOMPARE(doc.toJson(), doc2.toJson());
}
};
QTEST_GUILESS_MAIN(MojangVersionFormatTest)
#include "MojangVersionFormat_test.moc"
| 1,605
|
C++
|
.cpp
| 42
| 31.714286
| 100
| 0.686817
|
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,272
|
JavaVersion_test.cpp
|
PrismLauncher_PrismLauncher/tests/JavaVersion_test.cpp
|
#include <QTest>
#include <java/JavaVersion.h>
class JavaVersionTest : public QObject {
Q_OBJECT
private slots:
void test_Parse_data()
{
QTest::addColumn<QString>("string");
QTest::addColumn<int>("major");
QTest::addColumn<int>("minor");
QTest::addColumn<int>("security");
QTest::addColumn<QString>("prerelease");
QTest::newRow("old format") << "1.6.0_33" << 6 << 0 << 33 << QString();
QTest::newRow("old format prerelease") << "1.9.0_1-ea" << 9 << 0 << 1 << "ea";
QTest::newRow("new format major") << "9" << 9 << 0 << 0 << QString();
QTest::newRow("new format minor") << "9.1" << 9 << 1 << 0 << QString();
QTest::newRow("new format security") << "9.0.1" << 9 << 0 << 1 << QString();
QTest::newRow("new format prerelease") << "9-ea" << 9 << 0 << 0 << "ea";
QTest::newRow("new format long prerelease") << "9.0.1-ea" << 9 << 0 << 1 << "ea";
}
void test_Parse()
{
QFETCH(QString, string);
QFETCH(int, major);
QFETCH(int, minor);
QFETCH(int, security);
QFETCH(QString, prerelease);
JavaVersion test(string);
QCOMPARE(test.m_string, string);
QCOMPARE(test.toString(), string);
QCOMPARE(test.m_major, major);
QCOMPARE(test.m_minor, minor);
QCOMPARE(test.m_security, security);
QCOMPARE(test.m_prerelease, prerelease);
}
void test_Sort_data()
{
QTest::addColumn<QString>("lhs");
QTest::addColumn<QString>("rhs");
QTest::addColumn<bool>("smaller");
QTest::addColumn<bool>("equal");
QTest::addColumn<bool>("bigger");
// old format and new format equivalence
QTest::newRow("1.6.0_33 == 6.0.33") << "1.6.0_33"
<< "6.0.33" << false << true << false;
// old format major version
QTest::newRow("1.5.0_33 < 1.6.0_33") << "1.5.0_33"
<< "1.6.0_33" << true << false << false;
// new format - first release vs first security patch
QTest::newRow("9 < 9.0.1") << "9"
<< "9.0.1" << true << false << false;
QTest::newRow("9.0.1 > 9") << "9.0.1"
<< "9" << false << false << true;
// new format - first minor vs first release/security patch
QTest::newRow("9.1 > 9.0.1") << "9.1"
<< "9.0.1" << false << false << true;
QTest::newRow("9.0.1 < 9.1") << "9.0.1"
<< "9.1" << true << false << false;
QTest::newRow("9.1 > 9") << "9.1"
<< "9" << false << false << true;
QTest::newRow("9 > 9.1") << "9"
<< "9.1" << true << false << false;
// new format - omitted numbers
QTest::newRow("9 == 9.0") << "9"
<< "9.0" << false << true << false;
QTest::newRow("9 == 9.0.0") << "9"
<< "9.0.0" << false << true << false;
QTest::newRow("9.0 == 9.0.0") << "9.0"
<< "9.0.0" << false << true << false;
// early access and prereleases compared to final release
QTest::newRow("9-ea < 9") << "9-ea"
<< "9" << true << false << false;
QTest::newRow("9 < 9.0.1-ea") << "9"
<< "9.0.1-ea" << true << false << false;
QTest::newRow("9.0.1-ea > 9") << "9.0.1-ea"
<< "9" << false << false << true;
// prerelease difference only testing
QTest::newRow("9-1 == 9-1") << "9-1"
<< "9-1" << false << true << false;
QTest::newRow("9-1 < 9-2") << "9-1"
<< "9-2" << true << false << false;
QTest::newRow("9-5 < 9-20") << "9-5"
<< "9-20" << true << false << false;
QTest::newRow("9-rc1 < 9-rc2") << "9-rc1"
<< "9-rc2" << true << false << false;
QTest::newRow("9-rc5 < 9-rc20") << "9-rc5"
<< "9-rc20" << true << false << false;
QTest::newRow("9-rc < 9-rc2") << "9-rc"
<< "9-rc2" << true << false << false;
QTest::newRow("9-ea < 9-rc") << "9-ea"
<< "9-rc" << true << false << false;
}
void test_Sort()
{
QFETCH(QString, lhs);
QFETCH(QString, rhs);
QFETCH(bool, smaller);
QFETCH(bool, equal);
QFETCH(bool, bigger);
JavaVersion lver(lhs);
JavaVersion rver(rhs);
QCOMPARE(lver < rver, smaller);
QCOMPARE(lver == rver, equal);
QCOMPARE(lver > rver, bigger);
}
void test_PermGen_data()
{
QTest::addColumn<QString>("version");
QTest::addColumn<bool>("needs_permgen");
QTest::newRow("1.6.0_33") << "1.6.0_33" << true;
QTest::newRow("1.7.0_60") << "1.7.0_60" << true;
QTest::newRow("1.8.0_22") << "1.8.0_22" << false;
QTest::newRow("9-ea") << "9-ea" << false;
QTest::newRow("9.2.4") << "9.2.4" << false;
}
void test_PermGen()
{
QFETCH(QString, version);
QFETCH(bool, needs_permgen);
JavaVersion v(version);
QCOMPARE(needs_permgen, v.requiresPermGen());
}
};
QTEST_GUILESS_MAIN(JavaVersionTest)
#include "JavaVersion_test.moc"
| 5,637
|
C++
|
.cpp
| 125
| 32.176
| 89
| 0.449391
|
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,273
|
Version_test.cpp
|
PrismLauncher_PrismLauncher/tests/Version_test.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 <QTest>
#include <Version.h>
class VersionTest : public QObject {
Q_OBJECT
QStringList m_flex_test_names = {};
void addDataColumns()
{
QTest::addColumn<QString>("first");
QTest::addColumn<QString>("second");
QTest::addColumn<bool>("lessThan");
QTest::addColumn<bool>("equal");
}
void setupVersions()
{
addDataColumns();
QTest::newRow("equal, explicit") << "1.2.0"
<< "1.2.0" << false << true;
QTest::newRow("equal, two-digit") << "1.42"
<< "1.42" << false << true;
QTest::newRow("lessThan, explicit 1") << "1.2.0"
<< "1.2.1" << true << false;
QTest::newRow("lessThan, explicit 2") << "1.2.0"
<< "1.3.0" << true << false;
QTest::newRow("lessThan, explicit 3") << "1.2.0"
<< "2.2.0" << true << false;
QTest::newRow("lessThan, implicit 1") << "1.2"
<< "1.2.0" << true << false;
QTest::newRow("lessThan, implicit 2") << "1.2"
<< "1.2.1" << true << false;
QTest::newRow("lessThan, implicit 3") << "1.2"
<< "1.3.0" << true << false;
QTest::newRow("lessThan, implicit 4") << "1.2"
<< "2.2.0" << true << false;
QTest::newRow("lessThan, two-digit") << "1.41"
<< "1.42" << true << false;
QTest::newRow("lessThan, snapshot") << "1.20.0-rc2"
<< "1.20.1" << true << false;
QTest::newRow("greaterThan, explicit 1") << "1.2.1"
<< "1.2.0" << false << false;
QTest::newRow("greaterThan, explicit 2") << "1.3.0"
<< "1.2.0" << false << false;
QTest::newRow("greaterThan, explicit 3") << "2.2.0"
<< "1.2.0" << false << false;
QTest::newRow("greaterThan, implicit 1") << "1.2.0"
<< "1.2" << false << false;
QTest::newRow("greaterThan, implicit 2") << "1.2.1"
<< "1.2" << false << false;
QTest::newRow("greaterThan, implicit 3") << "1.3.0"
<< "1.2" << false << false;
QTest::newRow("greaterThan, implicit 4") << "2.2.0"
<< "1.2" << false << false;
QTest::newRow("greaterThan, two-digit") << "1.42"
<< "1.41" << false << false;
QTest::newRow("greaterThan, snapshot") << "1.20.2-rc2"
<< "1.20.1" << false << false;
}
private slots:
void test_versionCompare_data() { setupVersions(); }
void test_versionCompare()
{
QFETCH(QString, first);
QFETCH(QString, second);
QFETCH(bool, lessThan);
QFETCH(bool, equal);
const auto v1 = Version(first);
const auto v2 = Version(second);
qDebug() << v1 << "vs" << v2;
QCOMPARE(v1 < v2, lessThan);
QCOMPARE(v1 > v2, !lessThan && !equal);
QCOMPARE(v1 == v2, equal);
}
void test_flexVerTestVector_data()
{
addDataColumns();
QDir test_vector_dir(QFINDTESTDATA("testdata/Version"));
QFile vector_file{ test_vector_dir.absoluteFilePath("test_vectors.txt") };
vector_file.open(QFile::OpenModeFlag::ReadOnly);
int test_number = 0;
const QString test_name_template{ "FlexVer test #%1 (%2)" };
for (auto line = vector_file.readLine(); !vector_file.atEnd(); line = vector_file.readLine()) {
line = line.simplified();
if (line.startsWith('#') || line.isEmpty())
continue;
test_number += 1;
auto split_line = line.split('<');
if (split_line.size() == 2) {
QString first{ split_line.first().simplified() };
QString second{ split_line.last().simplified() };
auto new_test_name = test_name_template.arg(QString::number(test_number), "lessThan");
m_flex_test_names.append(new_test_name);
QTest::newRow(m_flex_test_names.last().toLatin1().data()) << first << second << true << false;
continue;
}
split_line = line.split('=');
if (split_line.size() == 2) {
QString first{ split_line.first().simplified() };
QString second{ split_line.last().simplified() };
auto new_test_name = test_name_template.arg(QString::number(test_number), "equals");
m_flex_test_names.append(new_test_name);
QTest::newRow(m_flex_test_names.last().toLatin1().data()) << first << second << false << true;
continue;
}
split_line = line.split('>');
if (split_line.size() == 2) {
QString first{ split_line.first().simplified() };
QString second{ split_line.last().simplified() };
auto new_test_name = test_name_template.arg(QString::number(test_number), "greaterThan");
m_flex_test_names.append(new_test_name);
QTest::newRow(m_flex_test_names.last().toLatin1().data()) << first << second << false << false;
continue;
}
qCritical() << "Unexpected separator in the test vector: ";
qCritical() << line;
QVERIFY(0 != 0);
}
vector_file.close();
}
void test_flexVerTestVector()
{
QFETCH(QString, first);
QFETCH(QString, second);
QFETCH(bool, lessThan);
QFETCH(bool, equal);
const auto v1 = Version(first);
const auto v2 = Version(second);
qDebug() << v1 << "vs" << v2;
QCOMPARE(v1 < v2, lessThan);
QCOMPARE(v1 > v2, !lessThan && !equal);
QCOMPARE(v1 == v2, equal);
}
};
QTEST_GUILESS_MAIN(VersionTest)
#include "Version_test.moc"
| 7,062
|
C++
|
.cpp
| 147
| 33.612245
| 111
| 0.490621
|
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,274
|
ResourceModel_test.cpp
|
PrismLauncher_PrismLauncher/tests/ResourceModel_test.cpp
|
#include <QAbstractItemModelTester>
#include <QTest>
#include <QTimer>
#include <Json.h>
#include <ui/pages/modplatform/ResourceModel.h>
#include "DummyResourceAPI.h"
using ResourceDownload::ResourceModel;
#define EXEC_TASK(EXEC) \
QEventLoop loop; \
\
connect(model, &ResourceModel::dataChanged, &loop, &QEventLoop::quit); \
\
QTimer expire_timer; \
expire_timer.callOnTimeout(&loop, &QEventLoop::quit); \
expire_timer.setSingleShot(true); \
expire_timer.start(4000); \
\
EXEC; \
if (model->hasActiveSearchJob()) \
loop.exec(); \
\
QVERIFY2(expire_timer.isActive(), "Timer has expired. The search never finished."); \
expire_timer.stop(); \
\
disconnect(model, nullptr, &loop, nullptr)
class ResourceModelTest;
class DummyResourceModel : public ResourceModel {
Q_OBJECT
friend class ResourceModelTest;
public:
DummyResourceModel() : ResourceModel(new DummyResourceAPI) {}
~DummyResourceModel() {}
[[nodiscard]] auto metaEntryBase() const -> QString override { return ""; }
ResourceAPI::SearchArgs createSearchArguments() override { return {}; }
ResourceAPI::VersionSearchArgs createVersionsArguments(QModelIndex&) override { return {}; }
ResourceAPI::ProjectInfoArgs createInfoArguments(QModelIndex&) override { return {}; }
QJsonArray documentToArray(QJsonDocument& doc) const override { return doc.object().value("hits").toArray(); }
void loadIndexedPack(ModPlatform::IndexedPack& pack, QJsonObject& obj) override
{
pack.authors.append({ Json::requireString(obj, "author"), "" });
pack.description = Json::requireString(obj, "description");
pack.addonId = Json::requireString(obj, "project_id");
}
};
class ResourceModelTest : public QObject {
Q_OBJECT
private slots:
void test_abstract_item_model()
{
auto dummy = DummyResourceModel();
auto tester = QAbstractItemModelTester(&dummy);
}
void test_search()
{
auto model = new DummyResourceModel;
QVERIFY(model->m_packs.isEmpty());
EXEC_TASK(model->search());
QVERIFY(model->m_packs.size() == 1);
QVERIFY(model->m_search_state == DummyResourceModel::SearchState::Finished);
auto processed_pack = model->m_packs.at(0);
auto search_json = DummyResourceAPI::searchRequestResult();
auto processed_response = model->documentToArray(search_json).first().toObject();
QVERIFY(processed_pack->addonId.toString() == Json::requireString(processed_response, "project_id"));
QVERIFY(processed_pack->description == Json::requireString(processed_response, "description"));
QVERIFY(processed_pack->authors.first().name == Json::requireString(processed_response, "author"));
delete model;
}
};
QTEST_GUILESS_MAIN(ResourceModelTest)
#include "ResourceModel_test.moc"
#include "moc_DummyResourceAPI.cpp"
| 3,974
|
C++
|
.cpp
| 71
| 44.633803
| 114
| 0.517144
|
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,276
|
ShaderPackParse_test.cpp
|
PrismLauncher_PrismLauncher/tests/ShaderPackParse_test.cpp
|
// SPDX-FileCopyrightText: 2022 Rachel Powers <508861+Ryex@users.noreply.github.com>
//
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - 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 <QTest>
#include <QTimer>
#include <FileSystem.h>
#include <minecraft/mod/ShaderPack.h>
#include <minecraft/mod/tasks/LocalShaderPackParseTask.h>
class ShaderPackParseTest : public QObject {
Q_OBJECT
private slots:
void test_parseZIP()
{
QString source = QFINDTESTDATA("testdata/ShaderPackParse");
QString zip_sp = FS::PathCombine(source, "shaderpack1.zip");
ShaderPack pack{ QFileInfo(zip_sp) };
bool valid = ShaderPackUtils::processZIP(pack);
QVERIFY(pack.packFormat() == ShaderPackFormat::VALID);
QVERIFY(valid == true);
}
void test_parseFolder()
{
QString source = QFINDTESTDATA("testdata/ShaderPackParse");
QString folder_sp = FS::PathCombine(source, "shaderpack2");
ShaderPack pack{ QFileInfo(folder_sp) };
bool valid = ShaderPackUtils::processFolder(pack);
QVERIFY(pack.packFormat() == ShaderPackFormat::VALID);
QVERIFY(valid == true);
}
void test_parseZIP2()
{
QString source = QFINDTESTDATA("testdata/ShaderPackParse");
QString folder_sp = FS::PathCombine(source, "shaderpack3.zip");
ShaderPack pack{ QFileInfo(folder_sp) };
bool valid = ShaderPackUtils::process(pack);
QVERIFY(pack.packFormat() == ShaderPackFormat::INVALID);
QVERIFY(valid == false);
}
};
QTEST_GUILESS_MAIN(ShaderPackParseTest)
#include "ShaderPackParse_test.moc"
| 2,305
|
C++
|
.cpp
| 57
| 35.54386
| 84
| 0.7114
|
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,277
|
INIFile_test.cpp
|
PrismLauncher_PrismLauncher/tests/INIFile_test.cpp
|
#include <QTest>
#include <settings/INIFile.h>
#include <QList>
#include <QSettings>
#include <QTemporaryFile>
#include <QVariant>
#include "FileSystem.h"
#include <QVariantUtils.h>
class IniFileTest : public QObject {
Q_OBJECT
private slots:
void initTestCase() {}
void cleanupTestCase() {}
void test_Escape_data()
{
QTest::addColumn<QString>("through");
QTest::newRow("unix path") << "/abc/def/ghi/jkl";
QTest::newRow("windows path") << "C:\\Program files\\terrible\\name\\of something\\";
QTest::newRow("Plain text") << "Lorem ipsum dolor sit amet.";
QTest::newRow("Escape sequences") << "Lorem\n\t\n\\n\\tAAZ\nipsum dolor\n\nsit amet.";
QTest::newRow("Escape sequences 2") << "\"\n\n\"";
QTest::newRow("Hashtags") << "some data#something";
}
void test_SaveLoad()
{
QString a = "a";
QString b = "a\nb\t\n\\\\\\C:\\Program files\\terrible\\name\\of something\\#thisIsNotAComment";
QString filename = "test_SaveLoad.ini";
// save
INIFile f;
f.set("a", a);
f.set("b", b);
f.saveFile(filename);
// load
INIFile f2;
f2.loadFile(filename);
QCOMPARE(f2.get("a", "NOT SET").toString(), a);
QCOMPARE(f2.get("b", "NOT SET").toString(), b);
}
void test_SaveLoadLists()
{
QString slist_strings = "(\"a\",\"b\",\"c\")";
QStringList list_strings = { "a", "b", "c" };
QString slist_numbers = "(1,2,3,10)";
QList<int> list_numbers = { 1, 2, 3, 10 };
QString filename = "test_SaveLoadLists.ini";
INIFile f;
f.set("list_strings", list_strings);
f.set("list_numbers", QVariantUtils::fromList(list_numbers));
f.saveFile(filename);
// load
INIFile f2;
f2.loadFile(filename);
QStringList out_list_strings = f2.get("list_strings", QStringList()).toStringList();
qDebug() << "OutStringList" << out_list_strings;
QList<int> out_list_numbers = QVariantUtils::toList<int>(f2.get("list_numbers", QVariantUtils::fromList(QList<int>())));
qDebug() << "OutNumbersList" << out_list_numbers;
QCOMPARE(out_list_strings, list_strings);
QCOMPARE(out_list_numbers, list_numbers);
}
void test_SaveAlreadyExistingFile()
{
QString fileContent = R"(InstanceType=OneSix
iconKey=vanillia_icon
name=Minecraft Vanillia
OverrideCommands=true
PreLaunchCommand="$INST_JAVA" -jar packwiz-installer-bootstrap.jar link
Wrapperommand=)";
fileContent += "\"";
fileContent += +R"(\"$INST_JAVA\" -jar packwiz-installer-bootstrap.jar link =)";
fileContent += "\"\n";
#if defined(Q_OS_WIN)
QString fileName = "test_SaveAlreadyExistingFile.ini";
QFile file(fileName);
QCOMPARE(file.open(QFile::WriteOnly | QFile::Text), true);
#else
QTemporaryFile file;
QCOMPARE(file.open(), true);
QCOMPARE(file.fileName().isEmpty(), false);
QString fileName = file.fileName();
#endif
QTextStream stream(&file);
stream << fileContent;
file.close();
// load
INIFile f1;
f1.loadFile(fileName);
QCOMPARE(f1.get("PreLaunchCommand", "NOT SET").toString(), "\"$INST_JAVA\" -jar packwiz-installer-bootstrap.jar link");
QCOMPARE(f1.get("Wrapperommand", "NOT SET").toString(), "\"$INST_JAVA\" -jar packwiz-installer-bootstrap.jar link =");
f1.saveFile(fileName);
INIFile f2;
f2.loadFile(fileName);
QCOMPARE(f2.get("PreLaunchCommand", "NOT SET").toString(), "\"$INST_JAVA\" -jar packwiz-installer-bootstrap.jar link");
QCOMPARE(f2.get("Wrapperommand", "NOT SET").toString(), "\"$INST_JAVA\" -jar packwiz-installer-bootstrap.jar link =");
QCOMPARE(f2.get("ConfigVersion", "NOT SET").toString(), "1.2");
#if defined(Q_OS_WIN)
FS::deletePath(fileName);
#endif
}
void test_SaveAlreadyExistingFileWithSpecialChars()
{
#if defined(Q_OS_WIN)
QString fileName = "test_SaveAlreadyExistingFileWithSpecialChars.ini";
#else
QTemporaryFile file;
QCOMPARE(file.open(), true);
QCOMPARE(file.fileName().isEmpty(), false);
QString fileName = file.fileName();
file.close();
#endif
QSettings settings{ fileName, QSettings::Format::IniFormat };
settings.setFallbacksEnabled(false);
settings.setValue("simple", "value1");
settings.setValue("withQuotes", R"("value2" with quotes)");
settings.setValue("withSpecialCharacters", "env mesa=true");
settings.setValue("withSpecialCharacters2", "1,2,3,4");
settings.setValue("withSpecialCharacters2", "1;2;3;4");
settings.setValue("withAll", "val=\"$INST_JAVA\" -jar; ls ");
settings.sync();
QCOMPARE(settings.status(), QSettings::Status::NoError);
// load
INIFile f1;
f1.loadFile(fileName);
for (auto key : settings.allKeys())
QCOMPARE(f1.get(key, "NOT SET").toString(), settings.value(key).toString());
f1.saveFile(fileName);
INIFile f2;
f2.loadFile(fileName);
for (auto key : settings.allKeys())
QCOMPARE(f2.get(key, "NOT SET").toString(), settings.value(key).toString());
QCOMPARE(f2.get("ConfigVersion", "NOT SET").toString(), "1.2");
#if defined(Q_OS_WIN)
FS::deletePath(fileName);
#endif
}
void test_SaveAlreadyExistingFileWithSpecialCharsV1()
{
QString fileContent = R"(InstanceType=OneSix
ConfigVersion=1.1
iconKey=vanillia_icon
name=Minecraft Vanillia
OverrideCommands=true
PreLaunchCommand=)";
fileContent += "\"\\\"env mesa=true\\\"\"\n";
#if defined(Q_OS_WIN)
QString fileName = "test_SaveAlreadyExistingFileWithSpecialCharsV1.ini";
QFile file(fileName);
QCOMPARE(file.open(QFile::WriteOnly | QFile::Text), true);
#else
QTemporaryFile file;
QCOMPARE(file.open(), true);
QCOMPARE(file.fileName().isEmpty(), false);
QString fileName = file.fileName();
#endif
QTextStream stream(&file);
stream << fileContent;
file.close();
// load
INIFile f1;
f1.loadFile(fileName);
QCOMPARE(f1.get("PreLaunchCommand", "NOT SET").toString(), "env mesa=true");
QCOMPARE(f1.get("ConfigVersion", "NOT SET").toString(), "1.2");
#if defined(Q_OS_WIN)
FS::deletePath(fileName);
#endif
}
};
QTEST_GUILESS_MAIN(IniFileTest)
#include "INIFile_test.moc"
| 6,582
|
C++
|
.cpp
| 169
| 32.011834
| 128
| 0.630384
|
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,278
|
WindowsConsole.h
|
PrismLauncher_PrismLauncher/launcher/WindowsConsole.h
|
//
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - 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/>.
*
*/
#pragma once
void BindCrtHandlesToStdHandles(bool bindStdIn, bool bindStdOut, bool bindStdErr);
bool AttachWindowsConsole();
| 893
|
C++
|
.h
| 22
| 38.727273
| 82
| 0.762673
|
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,280
|
Application.h
|
PrismLauncher_PrismLauncher/launcher/Application.h
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2022 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/>.
*
* 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.
*/
#pragma once
#include <QApplication>
#include <QDateTime>
#include <QDebug>
#include <QFlag>
#include <QIcon>
#include <QMutex>
#include <QUrl>
#include <memory>
#include <BaseInstance.h>
#include "minecraft/launch/MinecraftTarget.h"
class LaunchController;
class LocalPeer;
class InstanceWindow;
class MainWindow;
class SetupWizard;
class GenericPageProvider;
class QFile;
class HttpMetaCache;
class SettingsObject;
class InstanceList;
class AccountList;
class IconList;
class QNetworkAccessManager;
class JavaInstallList;
class ExternalUpdater;
class BaseProfilerFactory;
class BaseDetachedToolFactory;
class TranslationsModel;
class ITheme;
class MCEditTool;
class ThemeManager;
class IconTheme;
namespace Meta {
class Index;
}
#if defined(APPLICATION)
#undef APPLICATION
#endif
#define APPLICATION (static_cast<Application*>(QCoreApplication::instance()))
// Used for checking if is a test
#if defined(APPLICATION_DYN)
#undef APPLICATION_DYN
#endif
#define APPLICATION_DYN (dynamic_cast<Application*>(QCoreApplication::instance()))
class Application : public QApplication {
// friends for the purpose of limiting access to deprecated stuff
Q_OBJECT
public:
enum Status { StartingUp, Failed, Succeeded, Initialized };
enum Capability {
None = 0,
SupportsMSA = 1 << 0,
SupportsFlame = 1 << 1,
SupportsGameMode = 1 << 2,
SupportsMangoHud = 1 << 3,
};
Q_DECLARE_FLAGS(Capabilities, Capability)
public:
Application(int& argc, char** argv);
virtual ~Application();
bool event(QEvent* event) override;
std::shared_ptr<SettingsObject> settings() const { return m_settings; }
qint64 timeSinceStart() const { return startTime.msecsTo(QDateTime::currentDateTime()); }
QIcon getThemedIcon(const QString& name);
ThemeManager* themeManager() { return m_themeManager.get(); }
shared_qobject_ptr<ExternalUpdater> updater() { return m_updater; }
void triggerUpdateCheck();
std::shared_ptr<TranslationsModel> translations();
std::shared_ptr<JavaInstallList> javalist();
std::shared_ptr<InstanceList> instances() const { return m_instances; }
std::shared_ptr<IconList> icons() const { return m_icons; }
MCEditTool* mcedit() const { return m_mcedit.get(); }
shared_qobject_ptr<AccountList> accounts() const { return m_accounts; }
Status status() const { return m_status; }
const QMap<QString, std::shared_ptr<BaseProfilerFactory>>& profilers() const { return m_profilers; }
void updateProxySettings(QString proxyTypeStr, QString addr, int port, QString user, QString password);
shared_qobject_ptr<QNetworkAccessManager> network();
shared_qobject_ptr<HttpMetaCache> metacache();
shared_qobject_ptr<Meta::Index> metadataIndex();
void updateCapabilities();
void detectLibraries();
/*!
* Finds and returns the full path to a jar file.
* Returns a null-string if it could not be found.
*/
QString getJarPath(QString jarFile);
QString getMSAClientID();
QString getFlameAPIKey();
QString getModrinthAPIToken();
QString getUserAgent();
QString getUserAgentUncached();
/// this is the root of the 'installation'. Used for automatic updates
const QString& root() { return m_rootPath; }
/// the data path the application is using
const QString& dataRoot() { return m_dataPath; }
/// the java installed path the application is using
const QString javaPath();
bool isPortable() { return m_portable; }
const Capabilities capabilities() { return m_capabilities; }
/*!
* Opens a json file using either a system default editor, or, if not empty, the editor
* specified in the settings
*/
bool openJsonEditor(const QString& filename);
InstanceWindow* showInstanceWindow(InstancePtr instance, QString page = QString());
MainWindow* showMainWindow(bool minimized = false);
void updateIsRunning(bool running);
bool updatesAreAllowed();
void ShowGlobalSettings(class QWidget* parent, QString open_page = QString());
bool updaterEnabled();
QString updaterBinaryName();
QUrl normalizeImportUrl(QString const& url);
signals:
void updateAllowedChanged(bool status);
void globalSettingsAboutToOpen();
void globalSettingsClosed();
int currentCatChanged(int index);
void oauthReplyRecieved(QVariantMap);
#ifdef Q_OS_MACOS
void clickedOnDock();
#endif
public slots:
bool launch(InstancePtr instance,
bool online = true,
bool demo = false,
MinecraftTarget::Ptr targetToJoin = nullptr,
MinecraftAccountPtr accountToUse = nullptr,
const QString& offlineName = QString());
bool kill(InstancePtr instance);
void closeCurrentWindow();
private slots:
void on_windowClose();
void messageReceived(const QByteArray& message);
void controllerSucceeded();
void controllerFailed(const QString& error);
void setupWizardFinished(int status);
private:
bool handleDataMigration(const QString& currentData, const QString& oldData, const QString& name, const QString& configFile) const;
bool createSetupWizard();
void performMainStartupAction();
// sets the fatal error message and m_status to Failed.
void showFatalErrorMessage(const QString& title, const QString& content);
private:
void addRunningInstance();
void subRunningInstance();
bool shouldExitNow() const;
private:
QDateTime startTime;
shared_qobject_ptr<QNetworkAccessManager> m_network;
shared_qobject_ptr<ExternalUpdater> m_updater;
shared_qobject_ptr<AccountList> m_accounts;
shared_qobject_ptr<HttpMetaCache> m_metacache;
shared_qobject_ptr<Meta::Index> m_metadataIndex;
std::shared_ptr<SettingsObject> m_settings;
std::shared_ptr<InstanceList> m_instances;
std::shared_ptr<IconList> m_icons;
std::shared_ptr<JavaInstallList> m_javalist;
std::shared_ptr<TranslationsModel> m_translations;
std::shared_ptr<GenericPageProvider> m_globalSettingsProvider;
std::unique_ptr<MCEditTool> m_mcedit;
QSet<QString> m_features;
std::unique_ptr<ThemeManager> m_themeManager;
QMap<QString, std::shared_ptr<BaseProfilerFactory>> m_profilers;
QString m_rootPath;
QString m_dataPath;
Status m_status = Application::StartingUp;
Capabilities m_capabilities;
bool m_portable = false;
#ifdef Q_OS_MACOS
Qt::ApplicationState m_prevAppState = Qt::ApplicationInactive;
#endif
#if defined Q_OS_WIN32
// used on Windows to attach the standard IO streams
bool consoleAttached = false;
#endif
// FIXME: attach to instances instead.
struct InstanceXtras {
InstanceWindow* window = nullptr;
shared_qobject_ptr<LaunchController> controller;
};
std::map<QString, InstanceXtras> m_instanceExtras;
mutable QMutex m_instanceExtrasMutex;
// main state variables
size_t m_openWindows = 0;
size_t m_runningInstances = 0;
bool m_updateRunning = false;
// main window, if any
MainWindow* m_mainWindow = nullptr;
// peer launcher instance connector - used to implement single instance launcher and signalling
LocalPeer* m_peerInstance = nullptr;
SetupWizard* m_setupWizard = nullptr;
public:
QString m_detectedGLFWPath;
QString m_detectedOpenALPath;
QString m_instanceIdToLaunch;
QString m_serverToJoin;
QString m_worldToJoin;
QString m_profileToUse;
bool m_offline = false;
QString m_offlineName;
bool m_liveCheck = false;
QList<QUrl> m_urlsToImport;
QString m_instanceIdToShowWindowOf;
std::unique_ptr<QFile> logFile;
public:
void addQSavePath(QString);
void removeQSavePath(QString);
bool checkQSavePath(QString);
private:
QHash<QString, int> m_qsaveResources;
mutable QMutex m_qsaveResourcesMutex;
};
| 9,556
|
C++
|
.h
| 249
| 34.052209
| 135
| 0.736466
|
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,281
|
InstanceList.h
|
PrismLauncher_PrismLauncher/launcher/InstanceList.h
|
// 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.
*/
#pragma once
#include <QAbstractListModel>
#include <QList>
#include <QObject>
#include <QPair>
#include <QSet>
#include <QStack>
#include "BaseInstance.h"
class QFileSystemWatcher;
class InstanceTask;
struct InstanceName;
using InstanceId = QString;
using GroupId = QString;
using InstanceLocator = std::pair<InstancePtr, int>;
enum class InstCreateError { NoCreateError = 0, NoSuchVersion, UnknownCreateError, InstExists, CantCreateDir };
enum class GroupsState { NotLoaded, Steady, Dirty };
struct TrashHistoryItem {
QString id;
QString path;
QString trashPath;
QString groupName;
};
class InstanceList : public QAbstractListModel {
Q_OBJECT
public:
explicit InstanceList(SettingsObjectPtr settings, const QString& instDir, QObject* parent = 0);
virtual ~InstanceList();
public:
QModelIndex index(int row, int column = 0, const QModelIndex& parent = QModelIndex()) const override;
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex& index, int role) const override;
Qt::ItemFlags flags(const QModelIndex& index) const override;
bool setData(const QModelIndex& index, const QVariant& value, int role) override;
enum AdditionalRoles {
GroupRole = Qt::UserRole,
InstancePointerRole = 0x34B1CB48, ///< Return pointer to real instance
InstanceIDRole = 0x34B1CB49 ///< Return id if the instance
};
/*!
* \brief Error codes returned by functions in the InstanceList class.
* NoError Indicates that no error occurred.
* UnknownError indicates that an unspecified error occurred.
*/
enum InstListError { NoError = 0, UnknownError };
InstancePtr at(int i) const { return m_instances.at(i); }
int count() const { return m_instances.count(); }
InstListError loadList();
void saveNow();
/* O(n) */
InstancePtr getInstanceById(QString id) const;
/* O(n) */
InstancePtr getInstanceByManagedName(const QString& managed_name) const;
QModelIndex getInstanceIndexById(const QString& id) const;
QStringList getGroups();
bool isGroupCollapsed(const QString& groupName);
GroupId getInstanceGroup(const InstanceId& id) const;
void setInstanceGroup(const InstanceId& id, GroupId name);
void deleteGroup(const GroupId& name);
void renameGroup(const GroupId& src, const GroupId& dst);
bool trashInstance(const InstanceId& id);
bool trashedSomething();
void undoTrashInstance();
void deleteInstance(const InstanceId& id);
// Wrap an instance creation task in some more task machinery and make it ready to be used
Task* wrapInstanceTask(InstanceTask* task);
/**
* Create a new empty staging area for instance creation and @return a path/key top commit it later.
* Used by instance manipulation tasks.
*/
QString getStagedInstancePath();
/**
* Commit the staging area given by @keyPath to the provider - used when creation succeeds.
* Used by instance manipulation tasks.
* should_override is used when another similar instance already exists, and we want to override it
* - for instance, when updating it.
*/
bool commitStagedInstance(const QString& keyPath, const InstanceName& instanceName, QString groupName, const InstanceTask&);
/**
* Destroy a previously created staging area given by @keyPath - used when creation fails.
* Used by instance manipulation tasks.
*/
bool destroyStagingPath(const QString& keyPath);
int getTotalPlayTime();
Qt::DropActions supportedDragActions() const override;
Qt::DropActions supportedDropActions() const override;
bool canDropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) const override;
bool dropMimeData(const QMimeData* data, Qt::DropAction action, int row, int column, const QModelIndex& parent) override;
QStringList mimeTypes() const override;
QMimeData* mimeData(const QModelIndexList& indexes) const override;
QStringList getLinkedInstancesById(const QString& id) const;
signals:
void dataIsInvalid();
void instancesChanged();
void instanceSelectRequest(QString instanceId);
void groupsChanged(QSet<QString> groups);
public slots:
void on_InstFolderChanged(const Setting& setting, QVariant value);
void on_GroupStateChanged(const QString& group, bool collapsed);
private slots:
void propertiesChanged(BaseInstance* inst);
void providerUpdated();
void instanceDirContentsChanged(const QString& path);
private:
int getInstIndex(BaseInstance* inst) const;
void updateTotalPlayTime();
void suspendWatch();
void resumeWatch();
void add(const QList<InstancePtr>& list);
void loadGroupList();
void saveGroupList();
QList<InstanceId> discoverInstances();
InstancePtr loadInstance(const InstanceId& id);
void increaseGroupCount(const QString& group);
void decreaseGroupCount(const QString& group);
private:
int m_watchLevel = 0;
int totalPlayTime = 0;
bool m_dirty = false;
QList<InstancePtr> m_instances;
// id -> refs
QMap<QString, int> m_groupNameCache;
SettingsObjectPtr m_globalSettings;
QString m_instDir;
QFileSystemWatcher* m_watcher;
// FIXME: this is so inefficient that looking at it is almost painful.
QSet<QString> m_collapsedGroups;
QMap<InstanceId, GroupId> m_instanceGroupIndex;
QSet<InstanceId> instanceSet;
bool m_groupsLoaded = false;
bool m_instancesProbed = false;
QStack<TrashHistoryItem> m_trashHistory;
};
| 7,159
|
C++
|
.h
| 166
| 38.885542
| 134
| 0.740474
|
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,282
|
FastFileIconProvider.h
|
PrismLauncher_PrismLauncher/launcher/FastFileIconProvider.h
|
// 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/>.
*/
#pragma once
#include <QFileIconProvider>
class FastFileIconProvider : public QFileIconProvider {
public:
QIcon icon(const QFileInfo& info) const override;
};
| 910
|
C++
|
.h
| 23
| 37.521739
| 74
| 0.759322
|
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,283
|
BaseInstance.h
|
PrismLauncher_PrismLauncher/launcher/BaseInstance.h
|
// 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) 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.
*/
#pragma once
#include <cassert>
#include <QDateTime>
#include <QMenu>
#include <QObject>
#include <QProcess>
#include <QSet>
#include "QObjectPtr.h"
#include "settings/SettingsObject.h"
#include "BaseVersionList.h"
#include "MessageLevel.h"
#include "minecraft/auth/MinecraftAccount.h"
#include "pathmatcher/IPathMatcher.h"
#include "settings/INIFile.h"
#include "net/Mode.h"
#include "RuntimeContext.h"
#include "minecraft/launch/MinecraftTarget.h"
class QDir;
class Task;
class LaunchTask;
class BaseInstance;
// pointer for lazy people
using InstancePtr = std::shared_ptr<BaseInstance>;
/*!
* \brief Base class for instances.
* This class implements many functions that are common between instances and
* provides a standard interface for all instances.
*
* To create a new instance type, create a new class inheriting from this class
* and implement the pure virtual functions.
*/
class BaseInstance : public QObject, public std::enable_shared_from_this<BaseInstance> {
Q_OBJECT
protected:
/// no-touchy!
BaseInstance(SettingsObjectPtr globalSettings, SettingsObjectPtr settings, const QString& rootDir);
public: /* types */
enum class Status {
Present,
Gone // either nuked or invalidated
};
public:
/// virtual destructor to make sure the destruction is COMPLETE
virtual ~BaseInstance() {}
virtual void saveNow() = 0;
/***
* the instance has been invalidated - it is no longer tracked by the launcher for some reason,
* but it has not necessarily been deleted.
*
* Happens when the instance folder changes to some other location, or the instance is removed by external means.
*/
void invalidate();
/// The instance's ID. The ID SHALL be determined by LAUNCHER internally. The ID IS guaranteed to
/// be unique.
virtual QString id() const;
void setMinecraftRunning(bool running);
void setRunning(bool running);
bool isRunning() const;
int64_t totalTimePlayed() const;
int64_t lastTimePlayed() const;
void resetTimePlayed();
/// get the type of this instance
QString instanceType() const;
/// Path to the instance's root directory.
QString instanceRoot() const;
/// Path to the instance's game root directory.
virtual QString gameRoot() const { return instanceRoot(); }
/// Path to the instance's mods directory.
virtual QString modsRoot() const = 0;
QString name() const;
void setName(QString val);
/// Value used for instance window titles
QString windowTitle() const;
QString iconKey() const;
void setIconKey(QString val);
QString notes() const;
void setNotes(QString val);
QString getPreLaunchCommand();
QString getPostExitCommand();
QString getWrapperCommand();
bool isManagedPack() const;
QString getManagedPackType() const;
QString getManagedPackID() const;
QString getManagedPackName() const;
QString getManagedPackVersionID() const;
QString getManagedPackVersionName() const;
void setManagedPack(const QString& type, const QString& id, const QString& name, const QString& versionId, const QString& version);
void copyManagedPack(BaseInstance& other);
/// guess log level from a line of game log
virtual MessageLevel::Enum guessLevel([[maybe_unused]] const QString& line, MessageLevel::Enum level) { return level; }
virtual QStringList extraArguments();
/// Traits. Normally inside the version, depends on instance implementation.
virtual QSet<QString> traits() const = 0;
/**
* Gets the time that the instance was last launched.
* Stored in milliseconds since epoch.
*/
qint64 lastLaunch() const;
/// Sets the last launched time to 'val' milliseconds since epoch
void setLastLaunch(qint64 val = QDateTime::currentMSecsSinceEpoch());
/*!
* \brief Gets this instance's settings object.
* This settings object stores instance-specific settings.
*
* Note that this method is not const.
* It may call loadSpecificSettings() to ensure those are loaded.
*
* \return A pointer to this instance's settings object.
*/
virtual SettingsObjectPtr settings();
/*!
* \brief Loads settings specific to an instance type if they're not already loaded.
*/
virtual void loadSpecificSettings() = 0;
/// returns a valid update task
virtual QList<Task::Ptr> createUpdateTask() = 0;
/// returns a valid launcher (task container)
virtual shared_qobject_ptr<LaunchTask> createLaunchTask(AuthSessionPtr account, MinecraftTarget::Ptr targetToJoin) = 0;
/// returns the current launch task (if any)
shared_qobject_ptr<LaunchTask> getLaunchTask();
/*!
* Create envrironment variables for running the instance
*/
virtual QProcessEnvironment createEnvironment() = 0;
virtual QProcessEnvironment createLaunchEnvironment() = 0;
/*!
* Returns a matcher that can maps relative paths within the instance to whether they are 'log files'
*/
virtual IPathMatcher::Ptr getLogFileMatcher() = 0;
/*!
* Returns the root folder to use for looking up log files
*/
virtual QString getLogFileRoot() = 0;
virtual QString getStatusbarDescription() = 0;
/// FIXME: this really should be elsewhere...
virtual QString instanceConfigFolder() const = 0;
/// get variables this instance exports
virtual QMap<QString, QString> getVariables() = 0;
virtual QString typeName() const = 0;
virtual void updateRuntimeContext();
RuntimeContext runtimeContext() const { return m_runtimeContext; }
bool hasVersionBroken() const { return m_hasBrokenVersion; }
void setVersionBroken(bool value)
{
if (m_hasBrokenVersion != value) {
m_hasBrokenVersion = value;
emit propertiesChanged(this);
}
}
bool hasUpdateAvailable() const { return m_hasUpdate; }
void setUpdateAvailable(bool value)
{
if (m_hasUpdate != value) {
m_hasUpdate = value;
emit propertiesChanged(this);
}
}
bool hasCrashed() const { return m_crashed; }
void setCrashed(bool value)
{
if (m_crashed != value) {
m_crashed = value;
emit propertiesChanged(this);
}
}
virtual bool canLaunch() const;
virtual bool canEdit() const = 0;
virtual bool canExport() const = 0;
virtual void populateLaunchMenu(QMenu* menu) = 0;
bool reloadSettings();
/**
* 'print' a verbose description of the instance into a QStringList
*/
virtual QStringList verboseDescription(AuthSessionPtr session, MinecraftTarget::Ptr targetToJoin) = 0;
Status currentStatus() const;
int getConsoleMaxLines() const;
bool shouldStopOnConsoleOverflow() const;
QStringList getLinkedInstances() const;
void setLinkedInstances(const QStringList& list);
void addLinkedInstanceId(const QString& id);
bool removeLinkedInstanceId(const QString& id);
bool isLinkedToInstanceId(const QString& id) const;
bool isLegacy();
protected:
void changeStatus(Status newStatus);
SettingsObjectPtr globalSettings() const { return m_global_settings.lock(); }
bool isSpecificSettingsLoaded() const { return m_specific_settings_loaded; }
void setSpecificSettingsLoaded(bool loaded) { m_specific_settings_loaded = loaded; }
signals:
/*!
* \brief Signal emitted when properties relevant to the instance view change
*/
void propertiesChanged(BaseInstance* inst);
void launchTaskChanged(shared_qobject_ptr<LaunchTask>);
void runningStatusChanged(bool running);
void profilerChanged();
void statusChanged(Status from, Status to);
protected slots:
void iconUpdated(QString key);
protected: /* data */
QString m_rootDir;
SettingsObjectPtr m_settings;
// InstanceFlags m_flags;
bool m_isRunning = false;
shared_qobject_ptr<LaunchTask> m_launchProcess;
QDateTime m_timeStarted;
RuntimeContext m_runtimeContext;
private: /* data */
Status m_status = Status::Present;
bool m_crashed = false;
bool m_hasUpdate = false;
bool m_hasBrokenVersion = false;
SettingsObjectWeakPtr m_global_settings;
bool m_specific_settings_loaded = false;
};
Q_DECLARE_METATYPE(shared_qobject_ptr<BaseInstance>)
// Q_DECLARE_METATYPE(BaseInstance::InstanceFlag)
// Q_DECLARE_OPERATORS_FOR_FLAGS(BaseInstance::InstanceFlags)
| 10,153
|
C++
|
.h
| 254
| 35.291339
| 135
| 0.720838
|
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,284
|
KonamiCode.h
|
PrismLauncher_PrismLauncher/launcher/KonamiCode.h
|
#pragma once
#include <QKeyEvent>
class KonamiCode : public QObject {
Q_OBJECT
public:
KonamiCode(QObject* parent = 0);
void input(QEvent* event);
signals:
void triggered();
private:
int m_progress = 0;
};
| 239
|
C++
|
.h
| 12
| 16.166667
| 36
| 0.67713
|
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,285
|
FileSystem.h
|
PrismLauncher_PrismLauncher/launcher/FileSystem.h
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2022 TheKodeToad <TheKodeToad@proton.me>
* 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/>.
*
* 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.
*/
#pragma once
#include "Exception.h"
#include "pathmatcher/IPathMatcher.h"
#include <system_error>
#include <QDir>
#include <QFlags>
#include <QLocalServer>
#include <QObject>
#include <QPair>
#include <QThread>
namespace FS {
class FileSystemException : public ::Exception {
public:
FileSystemException(const QString& message) : Exception(message) {}
};
/**
* write data to a file safely
*/
void write(const QString& filename, const QByteArray& data);
/**
* append data to a file safely
*/
void appendSafe(const QString& filename, const QByteArray& data);
/**
* append data to a file
*/
void append(const QString& filename, const QByteArray& data);
/**
* read data from a file safely
*/
QByteArray read(const QString& filename);
/**
* Update the last changed timestamp of an existing file
*/
bool updateTimestamp(const QString& filename);
/**
* Creates all the folders in a path for the specified path
* last segment of the path is treated as a file name and is ignored!
*/
bool ensureFilePathExists(QString filenamepath);
/**
* Creates all the folders in a path for the specified path
* last segment of the path is treated as a folder name and is created!
*/
bool ensureFolderPathExists(const QFileInfo folderPath);
/**
* Creates all the folders in a path for the specified path
* last segment of the path is treated as a folder name and is created!
*/
bool ensureFolderPathExists(const QString folderPathName);
/**
* @brief Copies a directory and it's contents from src to dest
*/
class copy : public QObject {
Q_OBJECT
public:
copy(const QString& src, const QString& dst, QObject* parent = nullptr) : QObject(parent)
{
m_src.setPath(src);
m_dst.setPath(dst);
}
copy& followSymlinks(const bool follow)
{
m_followSymlinks = follow;
return *this;
}
copy& matcher(const IPathMatcher* filter)
{
m_matcher = filter;
return *this;
}
copy& whitelist(bool whitelist)
{
m_whitelist = whitelist;
return *this;
}
copy& overwrite(const bool overwrite)
{
m_overwrite = overwrite;
return *this;
}
bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); }
qsizetype totalCopied() { return m_copied; }
qsizetype totalFailed() { return m_failedPaths.length(); }
QStringList failed() { return m_failedPaths; }
signals:
void fileCopied(const QString& relativeName);
void copyFailed(const QString& relativeName);
// TODO: maybe add a "shouldCopy" signal in the future?
private:
bool operator()(const QString& offset, bool dryRun = false);
private:
bool m_followSymlinks = true;
const IPathMatcher* m_matcher = nullptr;
bool m_whitelist = false;
bool m_overwrite = false;
QDir m_src;
QDir m_dst;
qsizetype m_copied;
QStringList m_failedPaths;
};
struct LinkPair {
QString src;
QString dst;
};
struct LinkResult {
QString src;
QString dst;
QString err_msg;
int err_value;
};
class ExternalLinkFileProcess : public QThread {
Q_OBJECT
public:
ExternalLinkFileProcess(QString server, bool useHardLinks, QObject* parent = nullptr)
: QThread(parent), m_useHardLinks(useHardLinks), m_server(server)
{}
void run() override
{
runLinkFile();
emit processExited();
}
signals:
void processExited();
private:
void runLinkFile();
bool m_useHardLinks = false;
QString m_server;
};
/**
* @brief links (a file / a directory and it's contents) from src to dest
*/
class create_link : public QObject {
Q_OBJECT
public:
create_link(const QList<LinkPair> path_pairs, QObject* parent = nullptr) : QObject(parent) { m_path_pairs.append(path_pairs); }
create_link(const QString& src, const QString& dst, QObject* parent = nullptr) : QObject(parent)
{
LinkPair pair = { src, dst };
m_path_pairs.append(pair);
}
create_link& useHardLinks(const bool useHard)
{
m_useHardLinks = useHard;
return *this;
}
create_link& matcher(const IPathMatcher* filter)
{
m_matcher = filter;
return *this;
}
create_link& whitelist(bool whitelist)
{
m_whitelist = whitelist;
return *this;
}
create_link& linkRecursively(bool recursive)
{
m_recursive = recursive;
return *this;
}
create_link& setMaxDepth(int depth)
{
m_max_depth = depth;
return *this;
}
create_link& debug(bool d)
{
m_debug = d;
return *this;
}
std::error_code getOSError() { return m_os_err; }
bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); }
int totalLinked() { return m_linked; }
int totalToLink() { return static_cast<int>(m_links_to_make.size()); }
void runPrivileged() { runPrivileged(QString()); }
void runPrivileged(const QString& offset);
QList<LinkResult> getResults() { return m_path_results; }
signals:
void fileLinked(const QString& srcName, const QString& dstName);
void linkFailed(const QString& srcName, const QString& dstName, const QString& err_msg, int err_value);
void finished();
void finishedPrivileged(bool gotResults);
private:
bool operator()(const QString& offset, bool dryRun = false);
void make_link_list(const QString& offset);
bool make_links();
private:
bool m_useHardLinks = false;
const IPathMatcher* m_matcher = nullptr;
bool m_whitelist = false;
bool m_recursive = true;
/// @brief >= -1 = infinite, 0 = link files at src/* to dest/*, 1 = link files at src/*/* to dest/*/*, etc.
int m_max_depth = -1;
QList<LinkPair> m_path_pairs;
QList<LinkResult> m_path_results;
QList<LinkPair> m_links_to_make;
int m_linked;
bool m_debug = false;
std::error_code m_os_err;
QLocalServer m_linkServer;
};
/**
* @brief moves a file by renaming it
* @param source source file path
* @param dest destination filepath
*
*/
bool move(const QString& source, const QString& dest);
/**
* Delete a folder recursively
*/
bool deletePath(QString path);
/**
* Trash a folder / file
*/
bool trash(QString path, QString* pathInTrash = nullptr);
QString PathCombine(const QString& path1, const QString& path2);
QString PathCombine(const QString& path1, const QString& path2, const QString& path3);
QString PathCombine(const QString& path1, const QString& path2, const QString& path3, const QString& path4);
QString AbsolutePath(const QString& path);
/**
* @brief depth of path. "foo.txt" -> 0 , "bar/foo.txt" -> 1, /baz/bar/foo.txt -> 2, etc.
*
* @param path path to measure
* @return int number of components before base path
*/
int pathDepth(const QString& path);
/**
* @brief cut off segments of path until it is a max of length depth
*
* @param path path to truncate
* @param depth max depth of new path
* @return QString truncated path
*/
QString pathTruncate(const QString& path, int depth);
/**
* Resolve an executable
*
* Will resolve:
* single executable (by name)
* relative path
* absolute path
*
* @return absolute path to executable or null string
*/
QString ResolveExecutable(QString path);
/**
* Normalize path
*
* Any paths inside the current directory will be normalized to relative paths (to current)
* Other paths will be made absolute
*
* Returns false if the path logic somehow filed (and normalizedPath in invalid)
*/
QString NormalizePath(QString path);
QString RemoveInvalidFilenameChars(QString string, QChar replaceWith = '-');
QString RemoveInvalidPathChars(QString string, QChar replaceWith = '-');
QString DirNameFromString(QString string, QString inDir = ".");
/// Checks if the a given Path contains "!"
bool checkProblemticPathJava(QDir folder);
// Get the Directory representing the User's Desktop
QString getDesktopDir();
// Overrides one folder with the contents of another, preserving items exclusive to the first folder
// Equivalent to doing QDir::rename, but allowing for overrides
bool overrideFolder(QString overwritten_path, QString override_path);
/**
* Creates a shortcut to the specified target file at the specified destination path.
*/
bool createShortcut(QString destination, QString target, QStringList args, QString name, QString icon);
enum class FilesystemType {
FAT,
NTFS,
REFS,
EXT,
EXT_2_OLD,
EXT_2_3_4,
XFS,
BTRFS,
NFS,
ZFS,
APFS,
HFS,
HFSPLUS,
HFSX,
FUSEBLK,
F2FS,
BCACHEFS,
UNKNOWN
};
/**
* @brief Ordered Mapping of enum types to reported filesystem names
* this mapping is non exsaustive, it just attempts to capture the filesystems which could be reasonalbly be in use .
* all string values are in uppercase, use `QString.toUpper()` or equivalent during lookup.
*
* QMap is ordered
*
*/
static const QMap<FilesystemType, QStringList> s_filesystem_type_names = { { FilesystemType::FAT, { "FAT" } },
{ FilesystemType::NTFS, { "NTFS" } },
{ FilesystemType::REFS, { "REFS" } },
{ FilesystemType::EXT_2_OLD, { "EXT_2_OLD", "EXT2_OLD" } },
{ FilesystemType::EXT_2_3_4,
{ "EXT2/3/4", "EXT_2_3_4", "EXT2", "EXT3", "EXT4" } },
{ FilesystemType::EXT, { "EXT" } },
{ FilesystemType::XFS, { "XFS" } },
{ FilesystemType::BTRFS, { "BTRFS" } },
{ FilesystemType::NFS, { "NFS" } },
{ FilesystemType::ZFS, { "ZFS" } },
{ FilesystemType::APFS, { "APFS" } },
{ FilesystemType::HFS, { "HFS" } },
{ FilesystemType::HFSPLUS, { "HFSPLUS" } },
{ FilesystemType::HFSX, { "HFSX" } },
{ FilesystemType::FUSEBLK, { "FUSEBLK" } },
{ FilesystemType::F2FS, { "F2FS" } },
{ FilesystemType::BCACHEFS, { "BCACHEFS" } },
{ FilesystemType::UNKNOWN, { "UNKNOWN" } } };
/**
* @brief Get the string name of Filesystem enum object
*
* @param type
* @return QString
*/
QString getFilesystemTypeName(FilesystemType type);
/**
* @brief Get the Filesystem enum object from a name
* Does a lookup of the type name and returns an exact match
*
* @param name
* @return FilesystemType
*/
FilesystemType getFilesystemType(const QString& name);
/**
* @brief Get the Filesystem enum object from a name
* Does a fuzzy lookup of the type name and returns an apropreate match
*
* @param name
* @return FilesystemType
*/
FilesystemType getFilesystemTypeFuzzy(const QString& name);
struct FilesystemInfo {
FilesystemType fsType = FilesystemType::UNKNOWN;
QString fsTypeName;
int blockSize;
qint64 bytesAvailable;
qint64 bytesFree;
qint64 bytesTotal;
QString name;
QString rootPath;
};
/**
* @brief path to the near ancestor that exists
*
*/
QString nearestExistentAncestor(const QString& path);
/**
* @brief colect information about the filesystem under a file
*
*/
FilesystemInfo statFS(const QString& path);
static const QList<FilesystemType> s_clone_filesystems = { FilesystemType::BTRFS, FilesystemType::APFS, FilesystemType::ZFS,
FilesystemType::XFS, FilesystemType::REFS, FilesystemType::BCACHEFS };
/**
* @brief if the Filesystem is reflink/clone capable
*
*/
bool canCloneOnFS(const QString& path);
bool canCloneOnFS(const FilesystemInfo& info);
bool canCloneOnFS(FilesystemType type);
/**
* @brief if the Filesystems are reflink/clone capable and both are on the same device
*
*/
bool canClone(const QString& src, const QString& dst);
/**
* @brief Copies a directory and it's contents from src to dest
*/
class clone : public QObject {
Q_OBJECT
public:
clone(const QString& src, const QString& dst, QObject* parent = nullptr) : QObject(parent)
{
m_src.setPath(src);
m_dst.setPath(dst);
}
clone& matcher(const IPathMatcher* filter)
{
m_matcher = filter;
return *this;
}
clone& whitelist(bool whitelist)
{
m_whitelist = whitelist;
return *this;
}
bool operator()(bool dryRun = false) { return operator()(QString(), dryRun); }
qsizetype totalCloned() { return m_cloned; }
qsizetype totalFailed() { return m_failedClones.length(); }
QList<QPair<QString, QString>> failed() { return m_failedClones; }
signals:
void fileCloned(const QString& src, const QString& dst);
void cloneFailed(const QString& src, const QString& dst);
private:
bool operator()(const QString& offset, bool dryRun = false);
private:
const IPathMatcher* m_matcher = nullptr;
bool m_whitelist = false;
QDir m_src;
QDir m_dst;
qsizetype m_cloned;
QList<QPair<QString, QString>> m_failedClones;
};
/**
* @brief clone/reflink file from src to dst
*
*/
bool clone_file(const QString& src, const QString& dst, std::error_code& ec);
#if defined(Q_OS_WIN)
bool win_ioctl_clone(const std::wstring& src_path, const std::wstring& dst_path, std::error_code& ec);
#elif defined(Q_OS_LINUX)
bool linux_ficlone(const std::string& src_path, const std::string& dst_path, std::error_code& ec);
#elif defined(Q_OS_MACOS) || defined(Q_OS_FREEBSD) || defined(Q_OS_OPENBSD)
bool macos_bsd_clonefile(const std::string& src_path, const std::string& dst_path, std::error_code& ec);
#endif
static const QList<FilesystemType> s_non_link_filesystems = {
FilesystemType::FAT,
};
/**
* @brief if the Filesystem is symlink capable
*
*/
bool canLinkOnFS(const QString& path);
bool canLinkOnFS(const FilesystemInfo& info);
bool canLinkOnFS(FilesystemType type);
/**
* @brief if the Filesystem is symlink capable on both ends
*
*/
bool canLink(const QString& src, const QString& dst);
uintmax_t hardLinkCount(const QString& path);
#ifdef Q_OS_WIN
QString getPathNameInLocal8bit(const QString& file);
#endif
QString getUniqueResourceName(const QString& filePath);
} // namespace FS
| 16,835
|
C++
|
.h
| 481
| 28.70894
| 134
| 0.64579
|
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,286
|
ExponentialSeries.h
|
PrismLauncher_PrismLauncher/launcher/ExponentialSeries.h
|
#pragma once
template <typename T>
inline void clamp(T& current, T min, T max)
{
if (current < min) {
current = min;
} else if (current > max) {
current = max;
}
}
// List of numbers from min to max. Next is exponent times bigger than previous.
class ExponentialSeries {
public:
ExponentialSeries(unsigned min, unsigned max, unsigned exponent = 2)
{
m_current = m_min = min;
m_max = max;
m_exponent = exponent;
}
void reset() { m_current = m_min; }
unsigned operator()()
{
unsigned retval = m_current;
m_current *= m_exponent;
clamp(m_current, m_min, m_max);
return retval;
}
unsigned m_current;
unsigned m_min;
unsigned m_max;
unsigned m_exponent;
};
| 787
|
C++
|
.h
| 32
| 19.375
| 80
| 0.608522
|
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,287
|
SeparatorPrefixTree.h
|
PrismLauncher_PrismLauncher/launcher/SeparatorPrefixTree.h
|
#pragma once
#include <QMap>
#include <QString>
#include <QStringList>
template <char Tseparator>
class SeparatorPrefixTree {
public:
SeparatorPrefixTree(QStringList paths) { insert(paths); }
SeparatorPrefixTree(bool contained = false) { m_contained = contained; }
void insert(QStringList paths)
{
for (auto& path : paths) {
insert(path);
}
}
/// insert an exact path into the tree
SeparatorPrefixTree& insert(QString path)
{
auto sepIndex = path.indexOf(Tseparator);
if (sepIndex == -1) {
children[path] = SeparatorPrefixTree(true);
return children[path];
} else {
auto prefix = path.left(sepIndex);
if (!children.contains(prefix)) {
children[prefix] = SeparatorPrefixTree(false);
}
return children[prefix].insert(path.mid(sepIndex + 1));
}
}
/// is the path fully contained in the tree?
bool contains(QString path) const
{
auto node = find(path);
return node != nullptr;
}
/// does the tree cover a path? That means the prefix of the path is contained in the tree
bool covers(QString path) const
{
// if we found some valid node, it's good enough. the tree covers the path
if (m_contained) {
return true;
}
auto sepIndex = path.indexOf(Tseparator);
if (sepIndex == -1) {
auto found = children.find(path);
if (found == children.end()) {
return false;
}
return (*found).covers(QString());
} else {
auto prefix = path.left(sepIndex);
auto found = children.find(prefix);
if (found == children.end()) {
return false;
}
return (*found).covers(path.mid(sepIndex + 1));
}
}
/// return the contained path that covers the path specified
QString cover(QString path) const
{
// if we found some valid node, it's good enough. the tree covers the path
if (m_contained) {
return QString("");
}
auto sepIndex = path.indexOf(Tseparator);
if (sepIndex == -1) {
auto found = children.find(path);
if (found == children.end()) {
return QString();
}
auto nested = (*found).cover(QString());
if (nested.isNull()) {
return nested;
}
if (nested.isEmpty())
return path;
return path + Tseparator + nested;
} else {
auto prefix = path.left(sepIndex);
auto found = children.find(prefix);
if (found == children.end()) {
return QString();
}
auto nested = (*found).cover(path.mid(sepIndex + 1));
if (nested.isNull()) {
return nested;
}
if (nested.isEmpty())
return prefix;
return prefix + Tseparator + nested;
}
}
/// Does the path-specified node exist in the tree? It does not have to be contained.
bool exists(QString path) const
{
auto sepIndex = path.indexOf(Tseparator);
if (sepIndex == -1) {
auto found = children.find(path);
if (found == children.end()) {
return false;
}
return true;
} else {
auto prefix = path.left(sepIndex);
auto found = children.find(prefix);
if (found == children.end()) {
return false;
}
return (*found).exists(path.mid(sepIndex + 1));
}
}
/// find a node in the tree by name
const SeparatorPrefixTree* find(QString path) const
{
auto sepIndex = path.indexOf(Tseparator);
if (sepIndex == -1) {
auto found = children.find(path);
if (found == children.end()) {
return nullptr;
}
return &(*found);
} else {
auto prefix = path.left(sepIndex);
auto found = children.find(prefix);
if (found == children.end()) {
return nullptr;
}
return (*found).find(path.mid(sepIndex + 1));
}
}
/// is this a leaf node?
bool leaf() const { return children.isEmpty(); }
/// is this node actually contained in the tree, or is it purely structural?
bool contained() const { return m_contained; }
/// Remove a path from the tree
bool remove(QString path) { return removeInternal(path) != Failed; }
/// Clear all children of this node tree node
void clear() { children.clear(); }
QStringList toStringList() const
{
QStringList collected;
// collecting these is more expensive.
auto iter = children.begin();
while (iter != children.end()) {
QStringList list = iter.value().toStringList();
for (int i = 0; i < list.size(); i++) {
list[i] = iter.key() + Tseparator + list[i];
}
collected.append(list);
if ((*iter).m_contained) {
collected.append(iter.key());
}
iter++;
}
return collected;
}
private:
enum Removal { Failed, Succeeded, HasChildren };
Removal removeInternal(QString path = QString())
{
if (path.isEmpty()) {
if (!m_contained) {
// remove all children - we are removing a prefix
clear();
return Succeeded;
}
m_contained = false;
if (children.size()) {
return HasChildren;
}
return Succeeded;
}
Removal remStatus = Failed;
QString childToRemove;
auto sepIndex = path.indexOf(Tseparator);
if (sepIndex == -1) {
childToRemove = path;
auto found = children.find(childToRemove);
if (found == children.end()) {
return Failed;
}
remStatus = (*found).removeInternal();
} else {
childToRemove = path.left(sepIndex);
auto found = children.find(childToRemove);
if (found == children.end()) {
return Failed;
}
remStatus = (*found).removeInternal(path.mid(sepIndex + 1));
}
switch (remStatus) {
case Failed:
case HasChildren: {
return remStatus;
}
case Succeeded: {
children.remove(childToRemove);
if (m_contained) {
return HasChildren;
}
if (children.size()) {
return HasChildren;
}
return Succeeded;
}
}
return Failed;
}
private:
QMap<QString, SeparatorPrefixTree<Tseparator>> children;
bool m_contained = false;
};
| 7,135
|
C++
|
.h
| 214
| 22.785047
| 94
| 0.521796
|
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,288
|
Commandline.h
|
PrismLauncher_PrismLauncher/launcher/Commandline.h
|
/* Copyright 2013-2021 MultiMC Contributors
*
* Authors: Orochimarufan <orochimarufan.x3@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.
*/
#pragma once
#include <QString>
#include <QStringList>
/**
* @file libutil/include/cmdutils.h
* @brief commandline parsing and processing utilities
*/
namespace Commandline {
/**
* @brief split a string into argv items like a shell would do
* @param args the argument string
* @return a QStringList containing all arguments
*/
QStringList splitArgs(QString args);
} // namespace Commandline
| 1,068
|
C++
|
.h
| 31
| 32.580645
| 75
| 0.768411
|
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,289
|
SysInfo.h
|
PrismLauncher_PrismLauncher/launcher/SysInfo.h
|
#include <QString>
namespace SysInfo {
QString currentSystem();
QString useQTForArch();
QString getSupportedJavaArchitecture();
int suitableMaxMem();
} // namespace SysInfo
| 175
|
C++
|
.h
| 7
| 23.857143
| 39
| 0.820359
|
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,290
|
InstanceImportTask.h
|
PrismLauncher_PrismLauncher/launcher/InstanceImportTask.h
|
// 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.
*/
#pragma once
#include <QFuture>
#include <QFutureWatcher>
#include <QUrl>
#include "InstanceTask.h"
class QuaZip;
class InstanceImportTask : public InstanceTask {
Q_OBJECT
public:
explicit InstanceImportTask(const QUrl& sourceUrl, QWidget* parent = nullptr, QMap<QString, QString>&& extra_info = {});
virtual ~InstanceImportTask() = default;
bool abort() override;
protected:
//! Entry point for tasks.
virtual void executeTask() override;
private:
void processMultiMC();
void processTechnic();
void processFlame();
void processModrinth();
QString getRootFromZip(QuaZip* zip, const QString& root = "");
private slots:
void processZipPack();
void extractFinished();
private: /* data */
QUrl m_sourceUrl;
QString m_archivePath;
Task::Ptr m_task;
enum class ModpackType {
Unknown,
MultiMC,
Technic,
Flame,
Modrinth,
} m_modpackType = ModpackType::Unknown;
// Extra info we might need, that's available before, but can't be derived from
// the source URL / the resource it points to alone.
QMap<QString, QString> m_extra_info;
// FIXME: nuke
QWidget* m_parent;
void downloadFromUrl();
};
| 2,738
|
C++
|
.h
| 76
| 32.486842
| 124
| 0.711916
|
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,291
|
InstancePageProvider.h
|
PrismLauncher_PrismLauncher/launcher/InstancePageProvider.h
|
#pragma once
#include <FileSystem.h>
#include "minecraft/MinecraftInstance.h"
#include "ui/pages/BasePage.h"
#include "ui/pages/BasePageProvider.h"
#include "ui/pages/instance/InstanceSettingsPage.h"
#include "ui/pages/instance/LogPage.h"
#include "ui/pages/instance/ManagedPackPage.h"
#include "ui/pages/instance/ModFolderPage.h"
#include "ui/pages/instance/NotesPage.h"
#include "ui/pages/instance/OtherLogsPage.h"
#include "ui/pages/instance/ResourcePackPage.h"
#include "ui/pages/instance/ScreenshotsPage.h"
#include "ui/pages/instance/ServersPage.h"
#include "ui/pages/instance/ShaderPackPage.h"
#include "ui/pages/instance/TexturePackPage.h"
#include "ui/pages/instance/VersionPage.h"
#include "ui/pages/instance/WorldListPage.h"
class InstancePageProvider : protected QObject, public BasePageProvider {
Q_OBJECT
public:
explicit InstancePageProvider(InstancePtr parent) { inst = parent; }
virtual ~InstancePageProvider() = default;
virtual QList<BasePage*> getPages() override
{
QList<BasePage*> values;
values.append(new LogPage(inst));
std::shared_ptr<MinecraftInstance> onesix = std::dynamic_pointer_cast<MinecraftInstance>(inst);
values.append(new VersionPage(onesix.get()));
values.append(ManagedPackPage::createPage(onesix.get()));
auto modsPage = new ModFolderPage(onesix.get(), onesix->loaderModList());
modsPage->setFilter("%1 (*.zip *.jar *.litemod *.nilmod)");
values.append(modsPage);
values.append(new CoreModFolderPage(onesix.get(), onesix->coreModList()));
values.append(new NilModFolderPage(onesix.get(), onesix->nilModList()));
values.append(new ResourcePackPage(onesix.get(), onesix->resourcePackList()));
values.append(new TexturePackPage(onesix.get(), onesix->texturePackList()));
values.append(new ShaderPackPage(onesix.get(), onesix->shaderPackList()));
values.append(new NotesPage(onesix.get()));
values.append(new WorldListPage(onesix, onesix->worldList()));
values.append(new ServersPage(onesix));
// values.append(new GameOptionsPage(onesix.get()));
values.append(new ScreenshotsPage(FS::PathCombine(onesix->gameRoot(), "screenshots")));
values.append(new InstanceSettingsPage(onesix.get()));
auto logMatcher = inst->getLogFileMatcher();
if (logMatcher) {
values.append(new OtherLogsPage(inst->getLogFileRoot(), logMatcher));
}
return values;
}
virtual QString dialogTitle() override { return tr("Edit Instance (%1)").arg(inst->name()); }
protected:
InstancePtr inst;
};
| 2,642
|
C++
|
.h
| 54
| 43.518519
| 103
| 0.722523
|
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,292
|
MessageLevel.h
|
PrismLauncher_PrismLauncher/launcher/MessageLevel.h
|
#pragma once
#include <QString>
/**
* @brief the MessageLevel Enum
* defines what level a log message is
*/
namespace MessageLevel {
enum Enum {
Unknown, /**< No idea what this is or where it came from */
StdOut, /**< Undetermined stderr messages */
StdErr, /**< Undetermined stdout messages */
Launcher, /**< Launcher Messages */
Debug, /**< Debug Messages */
Info, /**< Info Messages */
Message, /**< Standard Messages */
Warning, /**< Warnings */
Error, /**< Errors */
Fatal, /**< Fatal Errors */
};
MessageLevel::Enum getLevel(const QString& levelName);
/* Get message level from a line. Line is modified if it was successful. */
MessageLevel::Enum fromLine(QString& line);
} // namespace MessageLevel
| 773
|
C++
|
.h
| 23
| 30.608696
| 75
| 0.654618
|
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,293
|
RuntimeContext.h
|
PrismLauncher_PrismLauncher/launcher/RuntimeContext.h
|
// 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/>.
*/
#pragma once
#include <QSet>
#include <QString>
#include "SysInfo.h"
#include "settings/SettingsObject.h"
struct RuntimeContext {
QString javaArchitecture;
QString javaRealArchitecture;
QString system = SysInfo::currentSystem();
QString mappedJavaRealArchitecture() const
{
if (javaRealArchitecture == "amd64")
return "x86_64";
if (javaRealArchitecture == "i386" || javaRealArchitecture == "i686")
return "x86";
if (javaRealArchitecture == "aarch64")
return "arm64";
if (javaRealArchitecture == "arm" || javaRealArchitecture == "armhf")
return "arm32";
return javaRealArchitecture;
}
void updateFromInstanceSettings(SettingsObjectPtr instanceSettings)
{
javaArchitecture = instanceSettings->get("JavaArchitecture").toString();
javaRealArchitecture = instanceSettings->get("JavaRealArchitecture").toString();
}
QString getClassifier() const { return system + "-" + mappedJavaRealArchitecture(); }
// "Legacy" refers to the fact that Mojang assumed that these are the only two architectures
bool isLegacyArch() const
{
const QString mapped = mappedJavaRealArchitecture();
return mapped == "x86_64" || mapped == "x86";
}
bool classifierMatches(QString target) const
{
// try to match precise classifier "[os]-[arch]"
bool x = target == getClassifier();
// try to match imprecise classifier on legacy architectures "[os]"
if (!x && isLegacyArch())
x = target == system;
return x;
}
};
| 2,373
|
C++
|
.h
| 60
| 34.15
| 96
| 0.689236
|
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,294
|
QVariantUtils.h
|
PrismLauncher_PrismLauncher/launcher/QVariantUtils.h
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 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
*
* 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.
*/
#pragma once
#include <QList>
#include <QVariant>
namespace QVariantUtils {
template <typename T>
inline QList<T> toList(QVariant src)
{
QVariantList variantList = src.toList();
QList<T> list_t;
list_t.reserve(variantList.size());
for (const QVariant& v : variantList) {
list_t.append(v.value<T>());
}
return list_t;
}
template <typename T>
inline QVariant fromList(QList<T> val)
{
QVariantList variantList;
variantList.reserve(val.size());
for (const T& v : val) {
variantList.append(v);
}
return variantList;
}
} // namespace QVariantUtils
| 2,156
|
C++
|
.h
| 61
| 32.704918
| 80
| 0.720785
|
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,295
|
LoggedProcess.h
|
PrismLauncher_PrismLauncher/launcher/LoggedProcess.h
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022,2023 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.
*/
#pragma once
#include <QProcess>
#include <QTextDecoder>
#include "MessageLevel.h"
/*
* This is a basic process.
* It has line-based logging support and hides some of the nasty bits.
*/
class LoggedProcess : public QProcess {
Q_OBJECT
public:
enum State { NotRunning, Starting, FailedToStart, Running, Finished, Crashed, Aborted };
public:
explicit LoggedProcess(const QTextCodec* output_codec = QTextCodec::codecForLocale(), QObject* parent = 0);
virtual ~LoggedProcess();
State state() const;
int exitCode() const;
void setDetachable(bool detachable);
signals:
void log(QStringList lines, MessageLevel::Enum level);
void stateChanged(LoggedProcess::State state);
public slots:
/**
* @brief kill the process - equivalent to kill -9
*/
void kill();
private slots:
void on_stdErr();
void on_stdOut();
void on_exit(int exit_code, QProcess::ExitStatus status);
void on_error(QProcess::ProcessError error);
void on_stateChange(QProcess::ProcessState);
private:
void changeState(LoggedProcess::State state);
QStringList reprocess(const QByteArray& data, QTextDecoder& decoder);
private:
QTextDecoder m_err_decoder;
QTextDecoder m_out_decoder;
QString m_leftover_line;
bool m_killed = false;
State m_state = NotRunning;
int m_exit_code = 0;
bool m_is_aborting = false;
bool m_is_detachable = false;
};
| 2,944
|
C++
|
.h
| 79
| 33.962025
| 111
| 0.723449
|
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,296
|
Exception.h
|
PrismLauncher_PrismLauncher/launcher/Exception.h
|
// SPDX-License-Identifier: GPL-3.0-only AND Apache-2.0
/*
* 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/>.
*
* 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.
*/
#pragma once
#include <QDebug>
#include <QString>
#include <exception>
class Exception : public std::exception {
public:
Exception(const QString& message) : std::exception(), m_message(message.toUtf8()) { qCritical() << "Exception:" << message; }
Exception(const Exception& other) : std::exception(), m_message(other.m_message) {}
virtual ~Exception() noexcept {}
const char* what() const noexcept { return m_message.constData(); }
QString cause() const { return QString::fromUtf8(m_message); }
private:
QByteArray m_message;
};
| 2,070
|
C++
|
.h
| 48
| 40.75
| 129
| 0.72448
|
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,297
|
JavaCommon.h
|
PrismLauncher_PrismLauncher/launcher/JavaCommon.h
|
#pragma once
#include <java/JavaChecker.h>
class QWidget;
/**
* Common UI bits for the java pages to use.
*/
namespace JavaCommon {
bool checkJVMArgs(QString args, QWidget* parent);
// Show a dialog saying that the Java binary was usable
void javaWasOk(QWidget* parent, const JavaChecker::Result& result);
// Show a dialog saying that the Java binary was not usable because of bad options
void javaArgsWereBad(QWidget* parent, const JavaChecker::Result& result);
// Show a dialog saying that the Java binary was not usable
void javaBinaryWasBad(QWidget* parent, const JavaChecker::Result& result);
// Show a dialog if we couldn't find Java Checker
void javaCheckNotFound(QWidget* parent);
class TestCheck : public QObject {
Q_OBJECT
public:
TestCheck(QWidget* parent, QString path, QString args, int minMem, int maxMem, int permGen)
: m_parent(parent), m_path(path), m_args(args), m_minMem(minMem), m_maxMem(maxMem), m_permGen(permGen)
{}
virtual ~TestCheck() {};
void run();
signals:
void finished();
private slots:
void checkFinished(const JavaChecker::Result& result);
void checkFinishedWithArgs(const JavaChecker::Result& result);
private:
JavaChecker::Ptr checker;
QWidget* m_parent = nullptr;
QString m_path;
QString m_args;
int m_minMem = 0;
int m_maxMem = 0;
int m_permGen = 64;
};
} // namespace JavaCommon
| 1,407
|
C++
|
.h
| 39
| 32.769231
| 110
| 0.734559
|
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,298
|
Filter.h
|
PrismLauncher_PrismLauncher/launcher/Filter.h
|
#pragma once
#include <QRegularExpression>
#include <QString>
class Filter {
public:
virtual ~Filter() = default;
virtual bool accepts(const QString& value) = 0;
};
class ContainsFilter : public Filter {
public:
ContainsFilter(const QString& pattern);
virtual ~ContainsFilter() = default;
bool accepts(const QString& value) override;
private:
QString pattern;
};
class ExactFilter : public Filter {
public:
ExactFilter(const QString& pattern);
virtual ~ExactFilter() = default;
bool accepts(const QString& value) override;
private:
QString pattern;
};
class ExactIfPresentFilter : public Filter {
public:
ExactIfPresentFilter(const QString& pattern);
virtual ~ExactIfPresentFilter() override = default;
bool accepts(const QString& value) override;
private:
QString pattern;
};
class RegexpFilter : public Filter {
public:
RegexpFilter(const QString& regexp, bool invert);
virtual ~RegexpFilter() = default;
bool accepts(const QString& value) override;
private:
QRegularExpression pattern;
bool invert = false;
};
class ExactListFilter : public Filter {
public:
ExactListFilter(const QStringList& pattern = {});
virtual ~ExactListFilter() = default;
bool accepts(const QString& value) override;
private:
QStringList m_pattern;
};
| 1,366
|
C++
|
.h
| 49
| 24.081633
| 55
| 0.731801
|
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,299
|
LaunchController.h
|
PrismLauncher_PrismLauncher/launcher/LaunchController.h
|
// 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.
*/
#pragma once
#include <BaseInstance.h>
#include <tools/BaseProfiler.h>
#include <QObject>
#include "minecraft/auth/MinecraftAccount.h"
#include "minecraft/launch/MinecraftTarget.h"
class InstanceWindow;
class LaunchController : public Task {
Q_OBJECT
public:
void executeTask() override;
LaunchController();
virtual ~LaunchController() = default;
void setInstance(InstancePtr instance) { m_instance = instance; }
InstancePtr instance() { return m_instance; }
void setOnline(bool online) { m_online = online; }
void setOfflineName(const QString& offlineName) { m_offlineName = offlineName; }
void setDemo(bool demo) { m_demo = demo; }
void setProfiler(BaseProfilerFactory* profiler) { m_profiler = profiler; }
void setParentWidget(QWidget* widget) { m_parentWidget = widget; }
void setTargetToJoin(MinecraftTarget::Ptr targetToJoin) { m_targetToJoin = std::move(targetToJoin); }
void setAccountToUse(MinecraftAccountPtr accountToUse) { m_accountToUse = std::move(accountToUse); }
QString id() { return m_instance->id(); }
bool abort() override;
private:
void login();
void launchInstance();
void decideAccount();
bool askPlayDemo();
QString askOfflineName(QString playerName, bool demo, bool& ok);
bool reauthenticateCurrentAccount();
private slots:
void readyForLaunch();
void onSucceeded();
void onFailed(QString reason);
void onProgressRequested(Task* task);
private:
BaseProfilerFactory* m_profiler = nullptr;
bool m_online = true;
QString m_offlineName;
bool m_demo = false;
InstancePtr m_instance;
QWidget* m_parentWidget = nullptr;
InstanceWindow* m_console = nullptr;
MinecraftAccountPtr m_accountToUse = nullptr;
AuthSessionPtr m_session;
shared_qobject_ptr<LaunchTask> m_launcher;
MinecraftTarget::Ptr m_targetToJoin;
};
| 3,398
|
C++
|
.h
| 83
| 37.445783
| 105
| 0.733617
|
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,300
|
PSaveFile.h
|
PrismLauncher_PrismLauncher/launcher/PSaveFile.h
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2023-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/>.
*/
#pragma once
#include <QFileInfo>
#include <QSaveFile>
#include "Application.h"
#if defined(LAUNCHER_APPLICATION)
/* PSaveFile
* A class that mimics QSaveFile for Windows.
*
* When reading resources, we need to avoid accessing temporary files
* generated by QSaveFile. If we start reading such a file, we may
* inadvertently keep it open while QSaveFile is trying to remove it,
* or we might detect the file just before it is removed, leading to
* race conditions and errors.
*
* Unfortunately, QSaveFile doesn't provide a way to retrieve the
* temporary file name or to set a specific template for the temporary
* file name it uses. By default, QSaveFile appends a `.XXXXXX` suffix
* to the original file name, where the `XXXXXX` part is dynamically
* generated to ensure uniqueness.
*
* This class acts like a lock by adding and removing the target file
* name into/from a global string set, helping to manage access to
* files during critical operations.
*
* Note: Please do not use the `setFileName` function directly, as it
* is not virtual and cannot be overridden.
*/
class PSaveFile : public QSaveFile {
public:
PSaveFile(const QString& name) : QSaveFile(name) { addPath(name); }
PSaveFile(const QString& name, QObject* parent) : QSaveFile(name, parent) { addPath(name); }
virtual ~PSaveFile()
{
if (auto app = APPLICATION_DYN) {
app->removeQSavePath(m_absoluteFilePath);
}
}
private:
void addPath(const QString& path)
{
m_absoluteFilePath = QFileInfo(path).absoluteFilePath() + "."; // add dot for tmp files only
if (auto app = APPLICATION_DYN) {
app->addQSavePath(m_absoluteFilePath);
}
}
QString m_absoluteFilePath;
};
#else
#define PSaveFile QSaveFile
#endif
| 2,552
|
C++
|
.h
| 67
| 34.925373
| 101
| 0.731668
|
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,301
|
ProblemProvider.h
|
PrismLauncher_PrismLauncher/launcher/ProblemProvider.h
|
#pragma once
#include <QList>
#include <QString>
enum class ProblemSeverity { None, Warning, Error };
struct PatchProblem {
ProblemSeverity m_severity;
QString m_description;
};
class ProblemProvider {
public:
virtual ~ProblemProvider() {}
virtual const QList<PatchProblem> getProblems() const = 0;
virtual ProblemSeverity getProblemSeverity() const = 0;
};
class ProblemContainer : public ProblemProvider {
public:
const QList<PatchProblem> getProblems() const override { return m_problems; }
ProblemSeverity getProblemSeverity() const override { return m_problemSeverity; }
virtual void addProblem(ProblemSeverity severity, const QString& description)
{
if (severity > m_problemSeverity) {
m_problemSeverity = severity;
}
m_problems.append({ severity, description });
}
private:
QList<PatchProblem> m_problems;
ProblemSeverity m_problemSeverity = ProblemSeverity::None;
};
| 974
|
C++
|
.h
| 29
| 29.172414
| 85
| 0.732694
|
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,302
|
Markdown.h
|
PrismLauncher_PrismLauncher/launcher/Markdown.h
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2023 Joshua Goins <josh@redstrate.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/>.
*/
#pragma once
#include <cmark.h>
#include <QString>
QString markdownToHTML(const QString& markdown);
| 842
|
C++
|
.h
| 21
| 38.285714
| 74
| 0.7558
|
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,303
|
NullInstance.h
|
PrismLauncher_PrismLauncher/launcher/NullInstance.h
|
// 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.
*/
#pragma once
#include "BaseInstance.h"
#include "launch/LaunchTask.h"
class NullInstance : public BaseInstance {
Q_OBJECT
public:
NullInstance(SettingsObjectPtr globalSettings, SettingsObjectPtr settings, const QString& rootDir)
: BaseInstance(globalSettings, settings, rootDir)
{
setVersionBroken(true);
}
virtual ~NullInstance() = default;
void saveNow() override {}
void loadSpecificSettings() override { setSpecificSettingsLoaded(true); }
QString getStatusbarDescription() override { return tr("Unknown instance type"); };
QSet<QString> traits() const override { return {}; };
QString instanceConfigFolder() const override { return instanceRoot(); };
shared_qobject_ptr<LaunchTask> createLaunchTask(AuthSessionPtr, MinecraftTarget::Ptr) override { return nullptr; }
QList<Task::Ptr> createUpdateTask() override { return {}; }
QProcessEnvironment createEnvironment() override { return QProcessEnvironment(); }
QProcessEnvironment createLaunchEnvironment() override { return QProcessEnvironment(); }
QMap<QString, QString> getVariables() override { return QMap<QString, QString>(); }
IPathMatcher::Ptr getLogFileMatcher() override { return nullptr; }
QString getLogFileRoot() override { return instanceRoot(); }
QString typeName() const override { return "Null"; }
bool canExport() const override { return false; }
bool canEdit() const override { return false; }
bool canLaunch() const override { return false; }
void populateLaunchMenu(QMenu* menu) override {}
QStringList verboseDescription(AuthSessionPtr session, MinecraftTarget::Ptr targetToJoin) override
{
QStringList out;
out << "Null instance - placeholder.";
return out;
}
QString modsRoot() const override { return QString(); }
void updateRuntimeContext()
{
// NOOP
}
};
| 3,455
|
C++
|
.h
| 76
| 41.802632
| 118
| 0.729346
|
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,304
|
InstanceCopyPrefs.h
|
PrismLauncher_PrismLauncher/launcher/InstanceCopyPrefs.h
|
//
// Created by marcelohdez on 10/22/22.
//
#pragma once
#include <QStringList>
struct InstanceCopyPrefs {
public:
[[nodiscard]] bool allTrue() const;
[[nodiscard]] QString getSelectedFiltersAsRegex() const;
[[nodiscard]] QString getSelectedFiltersAsRegex(const QStringList& additionalFilters) const;
// Getters
[[nodiscard]] bool isCopySavesEnabled() const;
[[nodiscard]] bool isKeepPlaytimeEnabled() const;
[[nodiscard]] bool isCopyGameOptionsEnabled() const;
[[nodiscard]] bool isCopyResourcePacksEnabled() const;
[[nodiscard]] bool isCopyShaderPacksEnabled() const;
[[nodiscard]] bool isCopyServersEnabled() const;
[[nodiscard]] bool isCopyModsEnabled() const;
[[nodiscard]] bool isCopyScreenshotsEnabled() const;
[[nodiscard]] bool isUseSymLinksEnabled() const;
[[nodiscard]] bool isLinkRecursivelyEnabled() const;
[[nodiscard]] bool isUseHardLinksEnabled() const;
[[nodiscard]] bool isDontLinkSavesEnabled() const;
[[nodiscard]] bool isUseCloneEnabled() const;
// Setters
void enableCopySaves(bool b);
void enableKeepPlaytime(bool b);
void enableCopyGameOptions(bool b);
void enableCopyResourcePacks(bool b);
void enableCopyShaderPacks(bool b);
void enableCopyServers(bool b);
void enableCopyMods(bool b);
void enableCopyScreenshots(bool b);
void enableUseSymLinks(bool b);
void enableLinkRecursively(bool b);
void enableUseHardLinks(bool b);
void enableDontLinkSaves(bool b);
void enableUseClone(bool b);
protected: // data
bool copySaves = true;
bool keepPlaytime = true;
bool copyGameOptions = true;
bool copyResourcePacks = true;
bool copyShaderPacks = true;
bool copyServers = true;
bool copyMods = true;
bool copyScreenshots = true;
bool useSymLinks = false;
bool linkRecursively = false;
bool useHardLinks = false;
bool dontLinkSaves = false;
bool useClone = false;
};
| 1,970
|
C++
|
.h
| 53
| 32.660377
| 96
| 0.731835
|
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,305
|
MMCZip.h
|
PrismLauncher_PrismLauncher/launcher/MMCZip.h
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (c) 2023-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/>.
*
* 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.
*/
#pragma once
#include <quazip.h>
#include <quazip/JlCompress.h>
#include <QDir>
#include <QFileInfo>
#include <QFuture>
#include <QFutureWatcher>
#include <QHash>
#include <QSet>
#include <QString>
#include <functional>
#include <memory>
#include <optional>
#if defined(LAUNCHER_APPLICATION)
#include "minecraft/mod/Mod.h"
#endif
#include "tasks/Task.h"
namespace MMCZip {
using FilterFunction = std::function<bool(const QString&)>;
/**
* Merge two zip files, using a filter function
*/
bool mergeZipFiles(QuaZip* into, QFileInfo from, QSet<QString>& contained, const FilterFunction& filter = nullptr);
/**
* Compress directory, by providing a list of files to compress
* \param zip target archive
* \param dir directory that will be compressed (to compress with relative paths)
* \param files list of files to compress
* \param followSymlinks should follow symlinks when compressing file data
* \return true for success or false for failure
*/
bool compressDirFiles(QuaZip* zip, QString dir, QFileInfoList files, bool followSymlinks = false);
/**
* Compress directory, by providing a list of files to compress
* \param fileCompressed target archive file
* \param dir directory that will be compressed (to compress with relative paths)
* \param files list of files to compress
* \param followSymlinks should follow symlinks when compressing file data
* \return true for success or false for failure
*/
bool compressDirFiles(QString fileCompressed, QString dir, QFileInfoList files, bool followSymlinks = false);
#if defined(LAUNCHER_APPLICATION)
/**
* take a source jar, add mods to it, resulting in target jar
*/
bool createModdedJar(QString sourceJarPath, QString targetJarPath, const QList<Mod*>& mods);
#endif
/**
* Find a single file in archive by file name (not path)
*
* \param ignore_paths paths to skip when recursing the search
*
* \return the path prefix where the file is
*/
QString findFolderOfFileInZip(QuaZip* zip, const QString& what, const QStringList& ignore_paths = {}, const QString& root = QString(""));
/**
* Find a multiple files of the same name in archive by file name
* If a file is found in a path, no deeper paths are searched
*
* \return true if anything was found
*/
bool findFilesInZip(QuaZip* zip, const QString& what, QStringList& result, const QString& root = QString());
/**
* Extract a subdirectory from an archive
*/
std::optional<QStringList> extractSubDir(QuaZip* zip, const QString& subdir, const QString& target);
bool extractRelFile(QuaZip* zip, const QString& file, const QString& target);
/**
* Extract a whole archive.
*
* \param fileCompressed The name of the archive.
* \param dir The directory to extract to, the current directory if left empty.
* \return The list of the full paths of the files extracted, empty on failure.
*/
std::optional<QStringList> extractDir(QString fileCompressed, QString dir);
/**
* Extract a subdirectory from an archive
*
* \param fileCompressed The name of the archive.
* \param subdir The directory within the archive to extract
* \param dir The directory to extract to, the current directory if left empty.
* \return The list of the full paths of the files extracted, empty on failure.
*/
std::optional<QStringList> extractDir(QString fileCompressed, QString subdir, QString dir);
/**
* Extract a single file from an archive into a directory
*
* \param fileCompressed The name of the archive.
* \param file The file within the archive to extract
* \param dir The directory to extract to, the current directory if left empty.
* \return true for success or false for failure
*/
bool extractFile(QString fileCompressed, QString file, QString dir);
/**
* Populate a QFileInfoList with a directory tree recursively, while allowing to excludeFilter what shouldn't be included.
* \param rootDir directory to start off
* \param subDir subdirectory, should be nullptr for first invocation
* \param files resulting list of QFileInfo
* \param excludeFilter function to excludeFilter which files shouldn't be included (returning true means to excude)
* \return true for success or false for failure
*/
bool collectFileListRecursively(const QString& rootDir, const QString& subDir, QFileInfoList* files, FilterFunction excludeFilter);
#if defined(LAUNCHER_APPLICATION)
class ExportToZipTask : public Task {
Q_OBJECT
public:
ExportToZipTask(QString outputPath,
QDir dir,
QFileInfoList files,
QString destinationPrefix = "",
bool followSymlinks = false,
bool utf8Enabled = false)
: m_output_path(outputPath)
, m_output(outputPath)
, m_dir(dir)
, m_files(files)
, m_destination_prefix(destinationPrefix)
, m_follow_symlinks(followSymlinks)
{
setAbortable(true);
m_output.setUtf8Enabled(utf8Enabled);
};
ExportToZipTask(QString outputPath,
QString dir,
QFileInfoList files,
QString destinationPrefix = "",
bool followSymlinks = false,
bool utf8Enabled = false)
: ExportToZipTask(outputPath, QDir(dir), files, destinationPrefix, followSymlinks, utf8Enabled) {};
virtual ~ExportToZipTask() = default;
void setExcludeFiles(QStringList excludeFiles) { m_exclude_files = excludeFiles; }
void addExtraFile(QString fileName, QByteArray data) { m_extra_files.insert(fileName, data); }
using ZipResult = std::optional<QString>;
protected:
virtual void executeTask() override;
bool abort() override;
ZipResult exportZip();
void finish();
private:
QString m_output_path;
QuaZip m_output;
QDir m_dir;
QFileInfoList m_files;
QString m_destination_prefix;
bool m_follow_symlinks;
QStringList m_exclude_files;
QHash<QString, QByteArray> m_extra_files;
QFuture<ZipResult> m_build_zip_future;
QFutureWatcher<ZipResult> m_build_zip_watcher;
};
class ExtractZipTask : public Task {
Q_OBJECT
public:
ExtractZipTask(QString input, QDir outputDir, QString subdirectory = "")
: ExtractZipTask(std::make_shared<QuaZip>(input), outputDir, subdirectory)
{}
ExtractZipTask(std::shared_ptr<QuaZip> input, QDir outputDir, QString subdirectory = "")
: m_input(input), m_output_dir(outputDir), m_subdirectory(subdirectory)
{}
virtual ~ExtractZipTask() = default;
using ZipResult = std::optional<QString>;
protected:
virtual void executeTask() override;
bool abort() override;
ZipResult extractZip();
void finish();
private:
std::shared_ptr<QuaZip> m_input;
QDir m_output_dir;
QString m_subdirectory;
QFuture<ZipResult> m_zip_future;
QFutureWatcher<ZipResult> m_zip_watcher;
};
#endif
} // namespace MMCZip
| 8,448
|
C++
|
.h
| 210
| 36.457143
| 137
| 0.732976
|
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,306
|
VersionProxyModel.h
|
PrismLauncher_PrismLauncher/launcher/VersionProxyModel.h
|
#pragma once
#include <QAbstractProxyModel>
#include "BaseVersionList.h"
#include <Filter.h>
class VersionFilterModel;
class VersionProxyModel : public QAbstractProxyModel {
Q_OBJECT
public:
enum Column { Name, ParentVersion, Branch, Type, CPUArchitecture, Path, Time, JavaName, JavaMajor };
using FilterMap = QHash<BaseVersionList::ModelRoles, std::shared_ptr<Filter>>;
public:
VersionProxyModel(QObject* parent = 0);
virtual ~VersionProxyModel() {};
virtual int columnCount(const QModelIndex& parent = QModelIndex()) const override;
virtual int rowCount(const QModelIndex& parent = QModelIndex()) const override;
virtual QModelIndex mapFromSource(const QModelIndex& sourceIndex) const override;
virtual QModelIndex mapToSource(const QModelIndex& proxyIndex) const override;
virtual QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override;
virtual QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
virtual QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
virtual QModelIndex parent(const QModelIndex& child) const override;
virtual void setSourceModel(QAbstractItemModel* sourceModel) override;
const FilterMap& filters() const;
const QString& search() const;
void setFilter(BaseVersionList::ModelRoles column, Filter* filter);
void setSearch(const QString& search);
void clearFilters();
QModelIndex getRecommended() const;
QModelIndex getVersion(const QString& version) const;
void setCurrentVersion(const QString& version);
private slots:
void sourceDataChanged(const QModelIndex& source_top_left, const QModelIndex& source_bottom_right);
void sourceAboutToBeReset();
void sourceReset();
void sourceRowsAboutToBeInserted(const QModelIndex& parent, int first, int last);
void sourceRowsInserted(const QModelIndex& parent, int first, int last);
void sourceRowsAboutToBeRemoved(const QModelIndex& parent, int first, int last);
void sourceRowsRemoved(const QModelIndex& parent, int first, int last);
private:
QList<Column> m_columns;
FilterMap m_filters;
QString m_search;
BaseVersionList::RoleList roles;
VersionFilterModel* filterModel;
bool hasRecommended = false;
bool hasLatest = false;
QString m_currentVersion;
};
| 2,423
|
C++
|
.h
| 48
| 45.916667
| 117
| 0.771997
|
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,307
|
DataMigrationTask.h
|
PrismLauncher_PrismLauncher/launcher/DataMigrationTask.h
|
// SPDX-FileCopyrightText: 2022 Sefa Eyeoglu <contact@scrumplex.net>
//
// SPDX-License-Identifier: GPL-3.0-only
#pragma once
#include "FileSystem.h"
#include "pathmatcher/IPathMatcher.h"
#include "tasks/Task.h"
#include <QFuture>
#include <QFutureWatcher>
/*
* Migrate existing data from other MMC-like launchers.
*/
class DataMigrationTask : public Task {
Q_OBJECT
public:
explicit DataMigrationTask(const QString& sourcePath, const QString& targetPath, IPathMatcher::Ptr pathmatcher);
~DataMigrationTask() override = default;
protected:
virtual void executeTask() override;
protected slots:
void dryRunFinished();
void dryRunAborted();
void copyFinished();
void copyAborted();
private:
const QString& m_sourcePath;
const QString& m_targetPath;
const IPathMatcher::Ptr m_pathMatcher;
FS::copy m_copy;
int m_toCopy = 0;
QFuture<bool> m_copyFuture;
QFutureWatcher<bool> m_copyFutureWatcher;
};
| 977
|
C++
|
.h
| 33
| 26.090909
| 116
| 0.744385
|
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,308
|
StringUtils.h
|
PrismLauncher_PrismLauncher/launcher/StringUtils.h
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (C) 2022 Sefa Eyeoglu <contact@scrumplex.net>
* Copyright (C) 2023 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
*
* 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.
*/
#pragma once
#include <QPair>
#include <QString>
#include <QUrl>
#include <utility>
namespace StringUtils {
#if defined Q_OS_WIN32
using string = std::wstring;
inline string toStdString(QString s)
{
return s.toStdWString();
}
inline QString fromStdString(string s)
{
return QString::fromStdWString(s);
}
#else
using string = std::string;
inline string toStdString(QString s)
{
return s.toStdString();
}
inline QString fromStdString(string s)
{
return QString::fromStdString(s);
}
#endif
int naturalCompare(const QString& s1, const QString& s2, Qt::CaseSensitivity cs);
/**
* @brief Truncate a url while keeping its readability py placing the `...` in the middle of the path
* @param url Url to truncate
* @param max_len max length of url in characters
* @param hard_limit if truncating the path can't get the url short enough, truncate it normally.
*/
QString truncateUrlHumanFriendly(QUrl& url, int max_len, bool hard_limit = false);
QString humanReadableFileSize(double bytes, bool use_si = false, int decimal_points = 1);
QString getRandomAlphaNumeric();
QPair<QString, QString> splitFirst(const QString& s, const QString& sep, Qt::CaseSensitivity cs = Qt::CaseSensitive);
QPair<QString, QString> splitFirst(const QString& s, QChar sep, Qt::CaseSensitivity cs = Qt::CaseSensitive);
QPair<QString, QString> splitFirst(const QString& s, const QRegularExpression& re);
QString htmlListPatch(QString htmlStr);
} // namespace StringUtils
| 3,017
|
C++
|
.h
| 77
| 37.311688
| 117
| 0.753673
|
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,309
|
BaseVersionList.h
|
PrismLauncher_PrismLauncher/launcher/BaseVersionList.h
|
/* 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.
*/
#pragma once
#include <QAbstractListModel>
#include <QObject>
#include <QVariant>
#include "BaseVersion.h"
#include "QObjectPtr.h"
#include "tasks/Task.h"
/*!
* \brief Class that each instance type's version list derives from.
* Version lists are the lists that keep track of the available game versions
* for that instance. This list will not be loaded on startup. It will be loaded
* when the list's load function is called. Before using the version list, you
* should check to see if it has been loaded yet and if not, load the list.
*
* Note that this class also inherits from QAbstractListModel. Methods from that
* class determine how this version list shows up in a list view. Said methods
* all have a default implementation, but they can be overridden by plugins to
* change the behavior of the list.
*/
class BaseVersionList : public QAbstractListModel {
Q_OBJECT
public:
enum ModelRoles {
VersionPointerRole = Qt::UserRole,
VersionRole,
VersionIdRole,
ParentVersionRole,
RecommendedRole,
LatestRole,
TypeRole,
BranchRole,
PathRole,
JavaNameRole,
JavaMajorRole,
CPUArchitectureRole,
SortRole
};
using RoleList = QList<int>;
explicit BaseVersionList(QObject* parent = 0);
/*!
* \brief Gets a task that will reload the version list.
* Simply execute the task to load the list.
* The task returned by this function should reset the model when it's done.
* \return A pointer to a task that reloads the version list.
*/
virtual Task::Ptr getLoadTask() = 0;
//! Checks whether or not the list is loaded. If this returns false, the list should be
// loaded.
virtual bool isLoaded() = 0;
//! Gets the version at the given index.
virtual const BaseVersion::Ptr at(int i) const = 0;
//! Returns the number of versions in the list.
virtual int count() const = 0;
//////// List Model Functions ////////
QVariant data(const QModelIndex& index, int role) const override;
int rowCount(const QModelIndex& parent) const override;
int columnCount(const QModelIndex& parent) const override;
QHash<int, QByteArray> roleNames() const override;
//! which roles are provided by this version list?
virtual RoleList providesRoles() const;
/*!
* \brief Finds a version by its descriptor.
* \param descriptor The descriptor of the version to find.
* \return A const pointer to the version with the given descriptor. NULL if
* one doesn't exist.
*/
virtual BaseVersion::Ptr findVersion(const QString& descriptor);
/*!
* \brief Gets the recommended version from this list
* If the list doesn't support recommended versions, this works exactly as getLatestStable
*/
virtual BaseVersion::Ptr getRecommended() const;
/*!
* Sorts the version list.
*/
virtual void sortVersions() = 0;
protected slots:
/*!
* Updates this list with the given list of versions.
* This is done by copying each version in the given list and inserting it
* into this one.
* We need to do this so that we can set the parents of the versions are set to this
* version list. This can't be done in the load task, because the versions the load
* task creates are on the load task's thread and Qt won't allow their parents
* to be set to something created on another thread.
* To get around that problem, we invoke this method on the GUI thread, which
* then copies the versions and sets their parents correctly.
* \param versions List of versions whose parents should be set.
*/
virtual void updateListData(QList<BaseVersion::Ptr> versions) = 0;
};
| 4,386
|
C++
|
.h
| 105
| 37.009524
| 94
| 0.712846
|
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,310
|
Usable.h
|
PrismLauncher_PrismLauncher/launcher/Usable.h
|
#pragma once
#include <cstddef>
#include <memory>
#include "QObjectPtr.h"
class Usable;
/**
* Base class for things that can be used by multiple other things and we want to track the use count.
*
* @see UseLock
*/
class Usable {
friend class UseLock;
public:
virtual ~Usable() {}
std::size_t useCount() const { return m_useCount; }
bool isInUse() const { return m_useCount > 0; }
protected:
virtual void decrementUses() { m_useCount--; }
virtual void incrementUses() { m_useCount++; }
private:
std::size_t m_useCount = 0;
};
/**
* Lock class to use for keeping track of uses of other things derived from Usable
*
* @see Usable
*/
class UseLock {
public:
UseLock(shared_qobject_ptr<Usable> usable) : m_usable(usable)
{
// this doesn't use shared pointer use count, because that wouldn't be correct. this count is separate.
m_usable->incrementUses();
}
~UseLock() { m_usable->decrementUses(); }
private:
shared_qobject_ptr<Usable> m_usable;
};
| 1,039
|
C++
|
.h
| 38
| 23.789474
| 111
| 0.680121
|
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,311
|
Untar.h
|
PrismLauncher_PrismLauncher/launcher/Untar.h
|
// SPDX-License-Identifier: GPL-3.0-only
/*
* Prism Launcher - Minecraft Launcher
* Copyright (c) 2023-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/>.
*
* 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.
*/
#pragma once
#include <QIODevice>
// this is a hack used for the java downloader (feel free to remove it in favor of a library)
// both extract functions will extract the first folder inside dest(disregarding the prefix)
namespace Tar {
bool extract(QIODevice* in, QString dst);
}
namespace GZTar {
bool extract(QString src, QString dst);
}
| 1,842
|
C++
|
.h
| 44
| 40.113636
| 93
| 0.743461
|
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,312
|
ApplicationMessage.h
|
PrismLauncher_PrismLauncher/launcher/ApplicationMessage.h
|
#pragma once
#include <QByteArray>
#include <QHash>
#include <QString>
struct ApplicationMessage {
QString command;
QHash<QString, QString> args;
QByteArray serialize();
void parse(const QByteArray& input);
};
| 229
|
C++
|
.h
| 10
| 20
| 40
| 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
| false
| false
|
29,313
|
InstanceTask.h
|
PrismLauncher_PrismLauncher/launcher/InstanceTask.h
|
#pragma once
#include "settings/SettingsObject.h"
#include "tasks/Task.h"
/* Helpers */
enum class InstanceNameChange { ShouldChange, ShouldKeep };
[[nodiscard]] InstanceNameChange askForChangingInstanceName(QWidget* parent, const QString& old_name, const QString& new_name);
enum class ShouldUpdate { Update, SkipUpdating, Cancel };
[[nodiscard]] ShouldUpdate askIfShouldUpdate(QWidget* parent, QString original_version_name);
struct InstanceName {
public:
InstanceName() = default;
InstanceName(QString name, QString version) : m_original_name(std::move(name)), m_original_version(std::move(version)) {}
[[nodiscard]] QString modifiedName() const;
[[nodiscard]] QString originalName() const;
[[nodiscard]] QString name() const;
[[nodiscard]] QString version() const;
void setName(QString name) { m_modified_name = name; }
void setName(InstanceName& other);
protected:
QString m_original_name;
QString m_original_version;
QString m_modified_name;
};
class InstanceTask : public Task, public InstanceName {
Q_OBJECT
public:
InstanceTask();
~InstanceTask() override = default;
void setParentSettings(SettingsObjectPtr settings) { m_globalSettings = settings; }
void setStagingPath(const QString& stagingPath) { m_stagingPath = stagingPath; }
void setIcon(const QString& icon) { m_instIcon = icon; }
void setGroup(const QString& group) { m_instGroup = group; }
QString group() const { return m_instGroup; }
[[nodiscard]] bool shouldConfirmUpdate() const { return m_confirm_update; }
void setConfirmUpdate(bool confirm) { m_confirm_update = confirm; }
bool shouldOverride() const { return m_override_existing; }
[[nodiscard]] QString originalInstanceID() const { return m_original_instance_id; };
protected:
void setOverride(bool override, QString instance_id_to_override = {})
{
m_override_existing = override;
if (!instance_id_to_override.isEmpty())
m_original_instance_id = instance_id_to_override;
}
protected: /* data */
SettingsObjectPtr m_globalSettings;
QString m_instIcon;
QString m_instGroup;
QString m_stagingPath;
bool m_override_existing = false;
bool m_confirm_update = true;
QString m_original_instance_id;
};
| 2,316
|
C++
|
.h
| 53
| 39.037736
| 127
| 0.723708
|
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,314
|
DefaultVariable.h
|
PrismLauncher_PrismLauncher/launcher/DefaultVariable.h
|
#pragma once
template <typename T>
class DefaultVariable {
public:
DefaultVariable(const T& value) { defaultValue = value; }
DefaultVariable<T>& operator=(const T& value)
{
currentValue = value;
is_default = currentValue == defaultValue;
is_explicit = true;
return *this;
}
operator const T&() const { return is_default ? defaultValue : currentValue; }
bool isDefault() const { return is_default; }
bool isExplicit() const { return is_explicit; }
private:
T currentValue;
T defaultValue;
bool is_default = true;
bool is_explicit = false;
};
| 625
|
C++
|
.h
| 21
| 24.761905
| 82
| 0.664452
|
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,315
|
MTPixmapCache.h
|
PrismLauncher_PrismLauncher/launcher/MTPixmapCache.h
|
#pragma once
#include <QCoreApplication>
#include <QDebug>
#include <QPixmapCache>
#include <QThread>
#include <QTime>
#include <limits>
#define GET_TYPE() \
Qt::ConnectionType type; \
if (QThread::currentThread() != QCoreApplication::instance()->thread()) \
type = Qt::BlockingQueuedConnection; \
else \
type = Qt::DirectConnection;
#define DEFINE_FUNC_NO_PARAM(NAME, RET_TYPE) \
static RET_TYPE NAME() \
{ \
RET_TYPE ret; \
GET_TYPE() \
QMetaObject::invokeMethod(s_instance, "_" #NAME, type, Q_RETURN_ARG(RET_TYPE, ret)); \
return ret; \
}
#define DEFINE_FUNC_ONE_PARAM(NAME, RET_TYPE, PARAM_1_TYPE) \
static RET_TYPE NAME(PARAM_1_TYPE p1) \
{ \
RET_TYPE ret; \
GET_TYPE() \
QMetaObject::invokeMethod(s_instance, "_" #NAME, type, Q_RETURN_ARG(RET_TYPE, ret), Q_ARG(PARAM_1_TYPE, p1)); \
return ret; \
}
#define DEFINE_FUNC_TWO_PARAM(NAME, RET_TYPE, PARAM_1_TYPE, PARAM_2_TYPE) \
static RET_TYPE NAME(PARAM_1_TYPE p1, PARAM_2_TYPE p2) \
{ \
RET_TYPE ret; \
GET_TYPE() \
QMetaObject::invokeMethod(s_instance, "_" #NAME, type, Q_RETURN_ARG(RET_TYPE, ret), Q_ARG(PARAM_1_TYPE, p1), \
Q_ARG(PARAM_2_TYPE, p2)); \
return ret; \
}
/** A wrapper around QPixmapCache with thread affinity with the main thread.
*/
class PixmapCache final : public QObject {
Q_OBJECT
public:
PixmapCache(QObject* parent) : QObject(parent) {}
~PixmapCache() override = default;
static PixmapCache& instance() { return *s_instance; }
static void setInstance(PixmapCache* i) { s_instance = i; }
public:
DEFINE_FUNC_NO_PARAM(cacheLimit, int)
DEFINE_FUNC_NO_PARAM(clear, bool)
DEFINE_FUNC_TWO_PARAM(find, bool, const QString&, QPixmap*)
DEFINE_FUNC_TWO_PARAM(find, bool, const QPixmapCache::Key&, QPixmap*)
DEFINE_FUNC_TWO_PARAM(insert, bool, const QString&, const QPixmap&)
DEFINE_FUNC_ONE_PARAM(insert, QPixmapCache::Key, const QPixmap&)
DEFINE_FUNC_ONE_PARAM(remove, bool, const QString&)
DEFINE_FUNC_ONE_PARAM(remove, bool, const QPixmapCache::Key&)
DEFINE_FUNC_TWO_PARAM(replace, bool, const QPixmapCache::Key&, const QPixmap&)
DEFINE_FUNC_ONE_PARAM(setCacheLimit, bool, int)
DEFINE_FUNC_NO_PARAM(markCacheMissByEviciton, bool)
DEFINE_FUNC_ONE_PARAM(setFastEvictionThreshold, bool, int)
// NOTE: Every function returns something non-void to simplify the macros.
private slots:
int _cacheLimit() { return QPixmapCache::cacheLimit(); }
bool _clear()
{
QPixmapCache::clear();
return true;
}
bool _find(const QString& key, QPixmap* pixmap) { return QPixmapCache::find(key, pixmap); }
bool _find(const QPixmapCache::Key& key, QPixmap* pixmap) { return QPixmapCache::find(key, pixmap); }
bool _insert(const QString& key, const QPixmap& pixmap) { return QPixmapCache::insert(key, pixmap); }
QPixmapCache::Key _insert(const QPixmap& pixmap) { return QPixmapCache::insert(pixmap); }
bool _remove(const QString& key)
{
QPixmapCache::remove(key);
return true;
}
bool _remove(const QPixmapCache::Key& key)
{
QPixmapCache::remove(key);
return true;
}
bool _replace(const QPixmapCache::Key& key, const QPixmap& pixmap) { return QPixmapCache::replace(key, pixmap); }
bool _setCacheLimit(int n)
{
QPixmapCache::setCacheLimit(n);
return true;
}
/**
* Mark that a cache miss occurred because of a eviction if too many of these occur too fast the cache size is increased
* @return if the cache size was increased
*/
bool _markCacheMissByEviciton()
{
static constexpr uint maxCache = static_cast<uint>(std::numeric_limits<int>::max()) / 4;
static constexpr uint step = 10240;
static constexpr int oneSecond = 1000;
auto now = QTime::currentTime();
if (!m_last_cache_miss_by_eviciton.isNull()) {
auto diff = m_last_cache_miss_by_eviciton.msecsTo(now);
if (diff < oneSecond) { // less than a second ago
++m_consecutive_fast_evicitons;
} else {
m_consecutive_fast_evicitons = 0;
}
}
m_last_cache_miss_by_eviciton = now;
if (m_consecutive_fast_evicitons >= m_consecutive_fast_evicitons_threshold) {
// increase the cache size
uint newSize = _cacheLimit() + step;
if (newSize >= maxCache) { // increase it until you overflow :D
newSize = maxCache;
qDebug() << m_consecutive_fast_evicitons
<< tr("pixmap cache misses by eviction happened too fast, doing nothing as the cache size reached it's limit");
} else {
qDebug() << m_consecutive_fast_evicitons
<< tr("pixmap cache misses by eviction happened too fast, increasing cache size to") << static_cast<int>(newSize);
}
_setCacheLimit(static_cast<int>(newSize));
m_consecutive_fast_evicitons = 0;
return true;
}
return false;
}
bool _setFastEvictionThreshold(int threshold)
{
m_consecutive_fast_evicitons_threshold = threshold;
return true;
}
private:
static PixmapCache* s_instance;
QTime m_last_cache_miss_by_eviciton;
int m_consecutive_fast_evicitons = 0;
int m_consecutive_fast_evicitons_threshold = 15;
};
| 7,286
|
C++
|
.h
| 135
| 46.62963
| 139
| 0.484662
|
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,316
|
MMCTime.h
|
PrismLauncher_PrismLauncher/launcher/MMCTime.h
|
/*
* Copyright 2021 Jamie Mansfield <jmansfield@cadixdev.org>
*
* 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.
*/
#pragma once
#include <QString>
namespace Time {
QString prettifyDuration(int64_t duration, bool noDays = false);
/**
* @brief Returns a string with short form time duration ie. `2days 1h3m4s56.0ms`.
* miliseconds are only included if `precision` is greater than 0.
*
* @param duration a number of seconds as floating point
* @param precision number of decmial points to display on fractons of a second, defualts to 0.
* @return QString
*/
QString humanReadableDuration(double duration, int precision = 0);
} // namespace Time
| 1,165
|
C++
|
.h
| 29
| 38.275862
| 95
| 0.76481
|
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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.