Initial commit of mtgonline project
This commit is contained in:
+587
@@ -0,0 +1,587 @@
|
||||
#include "remote_connection_controller.h"
|
||||
|
||||
#include "../../settings/cache_settings.h"
|
||||
#include "../interface/widgets/dialogs/dlg_connect.h"
|
||||
#include "../interface/widgets/dialogs/dlg_forgot_password_challenge.h"
|
||||
#include "../interface/widgets/dialogs/dlg_forgot_password_request.h"
|
||||
#include "../interface/widgets/dialogs/dlg_forgot_password_reset.h"
|
||||
#include "../interface/widgets/dialogs/dlg_register.h"
|
||||
#include "../interface/widgets/utility/get_text_with_max.h"
|
||||
|
||||
#include <QDateTime>
|
||||
#include <QLineEdit>
|
||||
#include <QMessageBox>
|
||||
#include <QThread>
|
||||
#include <libcockatrice/network/client/remote/remote_client.h>
|
||||
#include <libcockatrice/protocol/pb/response.pb.h>
|
||||
|
||||
ConnectionController::ConnectionController(QWidget *dialogParent, QObject *parent)
|
||||
: QObject(parent), dialogParent(dialogParent)
|
||||
{
|
||||
remoteClient = new RemoteClient(nullptr, &SettingsCache::instance());
|
||||
|
||||
clientThread = new QThread(this);
|
||||
remoteClient->moveToThread(clientThread);
|
||||
clientThread->start();
|
||||
|
||||
wireClientSignals();
|
||||
}
|
||||
|
||||
ConnectionController::~ConnectionController()
|
||||
{
|
||||
remoteClient->deleteLater();
|
||||
clientThread->wait();
|
||||
}
|
||||
|
||||
void ConnectionController::wireClientSignals()
|
||||
{
|
||||
connect(remoteClient, &RemoteClient::connectionClosedEventReceived, this,
|
||||
&ConnectionController::onConnectionClosedEvent);
|
||||
|
||||
connect(remoteClient, &RemoteClient::serverShutdownEventReceived, this,
|
||||
&ConnectionController::onServerShutdownEvent);
|
||||
|
||||
connect(remoteClient, &RemoteClient::statusChanged, this, &ConnectionController::onStatusChanged);
|
||||
|
||||
connect(remoteClient, &RemoteClient::userInfoChanged, this, &ConnectionController::onUserInfoReceived,
|
||||
Qt::BlockingQueuedConnection);
|
||||
|
||||
connect(remoteClient, &RemoteClient::loginError, this,
|
||||
[this](Response::ResponseCode r, QString rs, quint32 et, QList<QString> mf) {
|
||||
onLoginError(static_cast<int>(r), rs, et, mf);
|
||||
});
|
||||
|
||||
connect(remoteClient, &RemoteClient::registerError, this,
|
||||
[this](Response::ResponseCode r, QString rs, quint32 et) { onRegisterError(static_cast<int>(r), rs, et); });
|
||||
|
||||
connect(remoteClient, &RemoteClient::activateError, this, &ConnectionController::onActivateError);
|
||||
connect(remoteClient, &RemoteClient::socketError, this, &ConnectionController::onSocketError);
|
||||
connect(remoteClient, &RemoteClient::serverTimeout, this, &ConnectionController::onServerTimeout);
|
||||
|
||||
connect(remoteClient, &RemoteClient::protocolVersionMismatch, this,
|
||||
&ConnectionController::onProtocolVersionMismatch);
|
||||
|
||||
connect(remoteClient, &RemoteClient::registerAccepted, this, &ConnectionController::onRegisterAccepted);
|
||||
|
||||
connect(remoteClient, &RemoteClient::registerAcceptedNeedsActivate, this,
|
||||
&ConnectionController::onRegisterAcceptedNeedsActivate);
|
||||
|
||||
connect(remoteClient, &RemoteClient::activateAccepted, this, &ConnectionController::onActivateAccepted);
|
||||
|
||||
connect(remoteClient, &RemoteClient::notifyUserAboutUpdate, this, &ConnectionController::onNotifyUserAboutUpdate);
|
||||
|
||||
connect(remoteClient, &RemoteClient::sigForgotPasswordSuccess, this,
|
||||
&ConnectionController::onForgotPasswordSuccess);
|
||||
|
||||
connect(remoteClient, &RemoteClient::sigForgotPasswordError, this, &ConnectionController::onForgotPasswordError);
|
||||
|
||||
connect(remoteClient, &RemoteClient::sigPromptForForgotPasswordReset, this,
|
||||
&ConnectionController::onPromptForgotPasswordReset);
|
||||
|
||||
connect(remoteClient, &RemoteClient::sigPromptForForgotPasswordChallenge, this,
|
||||
&ConnectionController::onPromptForgotPasswordChallenge);
|
||||
}
|
||||
|
||||
void ConnectionController::connectToServer()
|
||||
{
|
||||
dlgConnect = new DlgConnect(dialogParent);
|
||||
connect(dlgConnect, &DlgConnect::sigStartForgotPasswordRequest, this, &ConnectionController::forgotPasswordRequest);
|
||||
|
||||
if (dlgConnect->exec()) {
|
||||
remoteClient->connectToServer(dlgConnect->getHost(), static_cast<unsigned int>(dlgConnect->getPort()),
|
||||
dlgConnect->getPlayerName(), dlgConnect->getPassword());
|
||||
}
|
||||
}
|
||||
|
||||
void ConnectionController::connectToServerDirect(const QString &host,
|
||||
unsigned int port,
|
||||
const QString &playerName,
|
||||
const QString &password)
|
||||
{
|
||||
remoteClient->connectToServer(host, port, playerName, password);
|
||||
}
|
||||
|
||||
void ConnectionController::disconnectFromServer()
|
||||
{
|
||||
remoteClient->disconnectFromServer();
|
||||
}
|
||||
|
||||
void ConnectionController::registerToServer()
|
||||
{
|
||||
DlgRegister dlg(dialogParent);
|
||||
if (dlg.exec()) {
|
||||
remoteClient->registerToServer(dlg.getHost(), static_cast<unsigned int>(dlg.getPort()), dlg.getPlayerName(),
|
||||
dlg.getPassword(), dlg.getEmail(), dlg.getCountry(), dlg.getRealName());
|
||||
}
|
||||
}
|
||||
|
||||
void ConnectionController::forgotPasswordRequest()
|
||||
{
|
||||
DlgForgotPasswordRequest dlg(dialogParent);
|
||||
if (dlg.exec()) {
|
||||
remoteClient->requestForgotPasswordToServer(dlg.getHost(), static_cast<unsigned int>(dlg.getPort()),
|
||||
dlg.getPlayerName());
|
||||
}
|
||||
}
|
||||
|
||||
void ConnectionController::onConnectionClosedEvent(const Event_ConnectionClosed &event)
|
||||
{
|
||||
remoteClient->disconnectFromServer();
|
||||
|
||||
QString reasonStr;
|
||||
switch (event.reason()) {
|
||||
case Event_ConnectionClosed::USER_LIMIT_REACHED: {
|
||||
reasonStr = tr("The server has reached its maximum user capacity, please check back later.");
|
||||
break;
|
||||
}
|
||||
case Event_ConnectionClosed::TOO_MANY_CONNECTIONS: {
|
||||
reasonStr = tr("There are too many concurrent connections from your address.");
|
||||
break;
|
||||
}
|
||||
case Event_ConnectionClosed::BANNED: {
|
||||
reasonStr = tr("Banned by moderator");
|
||||
if (event.has_end_time()) {
|
||||
reasonStr.append(
|
||||
"\n" + tr("Expected end time: %1").arg(QDateTime::fromSecsSinceEpoch(event.end_time()).toString()));
|
||||
} else {
|
||||
reasonStr.append("\n" + tr("This ban lasts indefinitely."));
|
||||
}
|
||||
if (event.has_reason_str()) {
|
||||
reasonStr.append("\n\n" + QString::fromStdString(event.reason_str()));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case Event_ConnectionClosed::SERVER_SHUTDOWN: {
|
||||
reasonStr = tr("Scheduled server shutdown.");
|
||||
break;
|
||||
}
|
||||
case Event_ConnectionClosed::USERNAMEINVALID: {
|
||||
reasonStr = tr("Invalid username.");
|
||||
break;
|
||||
}
|
||||
case Event_ConnectionClosed::LOGGEDINELSEWERE: {
|
||||
reasonStr = tr("You have been logged out due to logging in at another location.");
|
||||
break;
|
||||
}
|
||||
default:
|
||||
reasonStr = QString::fromStdString(event.reason_str());
|
||||
}
|
||||
|
||||
QMessageBox::critical(dialogParent, tr("Connection closed"),
|
||||
tr("The server has terminated your connection.\nReason: %1").arg(reasonStr));
|
||||
}
|
||||
|
||||
void ConnectionController::onServerShutdownEvent(const Event_ServerShutdown &event)
|
||||
{
|
||||
serverShutdownMessageBox.setInformativeText(tr("The server is going to be restarted in %n minute(s).\nAll running "
|
||||
"games will be lost.\nReason for shutdown: %1",
|
||||
"", event.minutes())
|
||||
.arg(QString::fromStdString(event.reason())));
|
||||
serverShutdownMessageBox.setIconPixmap(QPixmap("theme:cockatrice").scaled(64, 64));
|
||||
serverShutdownMessageBox.setText(tr("Scheduled server shutdown"));
|
||||
serverShutdownMessageBox.setWindowModality(Qt::ApplicationModal);
|
||||
serverShutdownMessageBox.setVisible(true);
|
||||
}
|
||||
|
||||
void ConnectionController::onStatusChanged(ClientStatus status)
|
||||
{
|
||||
// Update the window title first, then let MainWindow handle its own UI
|
||||
// state via the forwarded signal
|
||||
updateWindowTitle();
|
||||
emit statusChanged(status);
|
||||
|
||||
// TabSupervisor::stop() needs calling on disconnect; start() is driven by
|
||||
// onUserInfoReceived → tabSupervisorStartRequested.
|
||||
if (status == StatusDisconnected) {
|
||||
emit tabSupervisorStopRequested();
|
||||
}
|
||||
}
|
||||
|
||||
void ConnectionController::onUserInfoReceived(const ServerInfo_User &info)
|
||||
{
|
||||
emit tabSupervisorStartRequested(info);
|
||||
}
|
||||
|
||||
void ConnectionController::onLoginError(int r,
|
||||
QString reasonStr,
|
||||
quint32 endTime,
|
||||
const QList<QString> &missingFeatures)
|
||||
{
|
||||
switch (static_cast<Response::ResponseCode>(r)) {
|
||||
case Response::RespClientUpdateRequired: {
|
||||
QString formatted = "Missing Features: ";
|
||||
for (int i = 0; i < missingFeatures.size(); ++i) {
|
||||
formatted.append(QString("\n %1").arg(QChar(0x2022)) + " " + missingFeatures.value(i));
|
||||
}
|
||||
|
||||
QMessageBox msgBox(dialogParent);
|
||||
msgBox.setIcon(QMessageBox::Critical);
|
||||
msgBox.setWindowTitle(tr("Failed Login"));
|
||||
msgBox.setText(tr("Your client seems to be missing features this server requires for connection.") +
|
||||
"\n\n" + tr("To update your client, go to 'Help -> Check for Client Updates'."));
|
||||
msgBox.setDetailedText(formatted);
|
||||
msgBox.exec();
|
||||
break;
|
||||
}
|
||||
|
||||
case Response::RespWrongPassword: {
|
||||
QMessageBox::critical(dialogParent, tr("Error"),
|
||||
tr("Incorrect username or password. "
|
||||
"Please check your authentication information and try again."));
|
||||
break;
|
||||
}
|
||||
|
||||
case Response::RespWouldOverwriteOldSession: {
|
||||
QMessageBox::critical(dialogParent, tr("Error"),
|
||||
tr("There is already an active session using this user name.\n"
|
||||
"Please close that session first and re-login."));
|
||||
break;
|
||||
}
|
||||
|
||||
case Response::RespUserIsBanned: {
|
||||
QString bannedStr =
|
||||
endTime ? tr("You are banned until %1.").arg(QDateTime::fromSecsSinceEpoch(endTime).toString())
|
||||
: tr("You are banned indefinitely.");
|
||||
if (!reasonStr.isEmpty()) {
|
||||
bannedStr.append("\n\n" + reasonStr);
|
||||
}
|
||||
QMessageBox::critical(dialogParent, tr("Error"), bannedStr);
|
||||
break;
|
||||
}
|
||||
|
||||
case Response::RespUsernameInvalid: {
|
||||
QMessageBox::critical(dialogParent, tr("Error"), extractInvalidUsernameMessage(reasonStr));
|
||||
break;
|
||||
}
|
||||
|
||||
case Response::RespRegistrationRequired: {
|
||||
if (QMessageBox::question(dialogParent, tr("Error"),
|
||||
tr("This server requires user registration. Do you want to register now?"),
|
||||
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) {
|
||||
registerToServer();
|
||||
}
|
||||
return; // don't re-prompt connect
|
||||
}
|
||||
|
||||
case Response::RespClientIdRequired: {
|
||||
QMessageBox::critical(dialogParent, tr("Error"),
|
||||
tr("This server requires client IDs. Your client is either failing to generate an "
|
||||
"ID or you are running a modified client.\n"
|
||||
"Please close and reopen your client to try again."));
|
||||
break;
|
||||
}
|
||||
|
||||
case Response::RespContextError: {
|
||||
QMessageBox::critical(dialogParent, tr("Error"),
|
||||
tr("An internal error has occurred, please close and reopen Cockatrice before "
|
||||
"trying again.\nIf the error persists, ensure you are running the latest "
|
||||
"version of the software and if needed contact the software developers."));
|
||||
break;
|
||||
}
|
||||
|
||||
case Response::RespAccountNotActivated: {
|
||||
bool ok = false;
|
||||
QString token =
|
||||
getTextWithMax(dialogParent, tr("Account activation"),
|
||||
tr("Your account has not been activated yet.\n"
|
||||
"You need to provide the activation token received in the activation email."),
|
||||
QLineEdit::Normal, QString(), &ok);
|
||||
|
||||
if (ok && !token.isEmpty()) {
|
||||
remoteClient->activateToServer(token);
|
||||
return;
|
||||
}
|
||||
remoteClient->disconnectFromServer();
|
||||
return;
|
||||
}
|
||||
|
||||
case Response::RespServerFull: {
|
||||
QMessageBox::critical(dialogParent, tr("Server Full"),
|
||||
tr("The server has reached its maximum user capacity, please check back later."));
|
||||
break;
|
||||
}
|
||||
|
||||
default: {
|
||||
QMessageBox::critical(dialogParent, tr("Error"),
|
||||
tr("Unknown login error: %1").arg(r) +
|
||||
tr("\nThis usually means that your client version is out of date, and the server "
|
||||
"sent a reply your client doesn't understand."));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Re-open the connect dialog after any handled error
|
||||
connectToServer();
|
||||
}
|
||||
|
||||
void ConnectionController::onRegisterError(int r, QString reasonStr, quint32 endTime)
|
||||
{
|
||||
switch (static_cast<Response::ResponseCode>(r)) {
|
||||
case Response::RespRegistrationDisabled: {
|
||||
QMessageBox::critical(dialogParent, tr("Registration denied"),
|
||||
tr("Registration is currently disabled on this server"));
|
||||
break;
|
||||
}
|
||||
case Response::RespUserAlreadyExists: {
|
||||
QMessageBox::critical(dialogParent, tr("Registration denied"),
|
||||
tr("There is already an existing account with the same user name."));
|
||||
break;
|
||||
}
|
||||
case Response::RespEmailRequiredToRegister: {
|
||||
QMessageBox::critical(dialogParent, tr("Registration denied"),
|
||||
tr("It's mandatory to specify a valid email address when registering."));
|
||||
break;
|
||||
}
|
||||
case Response::RespEmailBlackListed: {
|
||||
if (reasonStr.isEmpty()) {
|
||||
reasonStr =
|
||||
"The email address provider used during registration has been blocked from use on this server.";
|
||||
}
|
||||
QMessageBox::critical(dialogParent, tr("Registration denied"), reasonStr);
|
||||
break;
|
||||
}
|
||||
case Response::RespTooManyRequests: {
|
||||
QMessageBox::critical(dialogParent, tr("Registration denied"),
|
||||
tr("It appears you are attempting to register a new account on this server yet you "
|
||||
"already have an account registered with the email provided. This server "
|
||||
"restricts the number of accounts a user can register per address. Please "
|
||||
"contact the server operator for further assistance or to obtain your "
|
||||
"credential information."));
|
||||
break;
|
||||
}
|
||||
case Response::RespPasswordTooShort: {
|
||||
QMessageBox::critical(dialogParent, tr("Registration denied"), tr("Password too short."));
|
||||
break;
|
||||
}
|
||||
case Response::RespUserIsBanned: {
|
||||
QString bannedStr =
|
||||
endTime ? tr("You are banned until %1.").arg(QDateTime::fromSecsSinceEpoch(endTime).toString())
|
||||
: tr("You are banned indefinitely.");
|
||||
if (!reasonStr.isEmpty()) {
|
||||
bannedStr.append("\n\n" + reasonStr);
|
||||
}
|
||||
QMessageBox::critical(dialogParent, tr("Error"), bannedStr);
|
||||
break;
|
||||
}
|
||||
case Response::RespUsernameInvalid: {
|
||||
QMessageBox::critical(dialogParent, tr("Error"), extractInvalidUsernameMessage(reasonStr));
|
||||
break;
|
||||
}
|
||||
case Response::RespRegistrationFailed: {
|
||||
QMessageBox::critical(dialogParent, tr("Error"),
|
||||
tr("Registration failed for a technical problem on the server."));
|
||||
break;
|
||||
}
|
||||
case Response::RespNotConnected: {
|
||||
QMessageBox::critical(dialogParent, tr("Error"), tr("The connection to the server has been lost."));
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
QMessageBox::critical(dialogParent, tr("Error"),
|
||||
tr("Unknown registration error: %1").arg(r) +
|
||||
tr("\nThis usually means that your client version is out of date, and the server "
|
||||
"sent a reply your client doesn't understand."));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
registerToServer();
|
||||
}
|
||||
|
||||
void ConnectionController::onActivateError()
|
||||
{
|
||||
QMessageBox::critical(dialogParent, tr("Error"), tr("Account activation failed"));
|
||||
remoteClient->disconnectFromServer();
|
||||
connectToServer();
|
||||
}
|
||||
|
||||
void ConnectionController::onSocketError(const QString &errorStr)
|
||||
{
|
||||
QMessageBox::critical(dialogParent, tr("Error"), tr("Socket error: %1").arg(errorStr));
|
||||
connectToServer();
|
||||
}
|
||||
|
||||
void ConnectionController::onServerTimeout()
|
||||
{
|
||||
QMessageBox::critical(dialogParent, tr("Error"), tr("Server timeout"));
|
||||
connectToServer();
|
||||
}
|
||||
|
||||
void ConnectionController::onProtocolVersionMismatch(int localVersion, int remoteVersion)
|
||||
{
|
||||
if (localVersion > remoteVersion) {
|
||||
QMessageBox::critical(dialogParent, tr("Error"),
|
||||
tr("You are trying to connect to an obsolete server. Please downgrade your Cockatrice "
|
||||
"version or connect to a suitable server.\n"
|
||||
"Local version is %1, remote version is %2.")
|
||||
.arg(localVersion)
|
||||
.arg(remoteVersion));
|
||||
} else {
|
||||
QMessageBox::critical(dialogParent, tr("Error"),
|
||||
tr("Your Cockatrice client is obsolete. Please update your Cockatrice version.\n"
|
||||
"Local version is %1, remote version is %2.")
|
||||
.arg(localVersion)
|
||||
.arg(remoteVersion));
|
||||
}
|
||||
}
|
||||
|
||||
void ConnectionController::onRegisterAccepted()
|
||||
{
|
||||
QMessageBox::information(dialogParent, tr("Success"), tr("Registration accepted.\nWill now login."));
|
||||
}
|
||||
|
||||
void ConnectionController::onRegisterAcceptedNeedsActivate()
|
||||
{
|
||||
// Server will send activation email; nothing to display here.
|
||||
}
|
||||
|
||||
void ConnectionController::onActivateAccepted()
|
||||
{
|
||||
QMessageBox::information(dialogParent, tr("Success"), tr("Account activation accepted.\nWill now login."));
|
||||
}
|
||||
|
||||
void ConnectionController::onNotifyUserAboutUpdate()
|
||||
{
|
||||
QMessageBox::information(
|
||||
dialogParent, tr("Information"),
|
||||
tr("This server supports additional features that your client doesn't have.\n"
|
||||
"This is most likely not a problem, but this message might mean there is a new version of "
|
||||
"Cockatrice available or this server is running a custom or pre-release version.\n\n"
|
||||
"To update your client, go to Help -> Check for Updates."));
|
||||
}
|
||||
|
||||
void ConnectionController::onForgotPasswordSuccess()
|
||||
{
|
||||
QMessageBox::information(
|
||||
dialogParent, tr("Reset Password"),
|
||||
tr("Your password has been reset successfully, you can now log in using the new credentials."));
|
||||
SettingsCache::instance().servers().setFPHostName("");
|
||||
SettingsCache::instance().servers().setFPPort("");
|
||||
SettingsCache::instance().servers().setFPPlayerName("");
|
||||
}
|
||||
|
||||
void ConnectionController::onForgotPasswordError()
|
||||
{
|
||||
QMessageBox::warning(
|
||||
dialogParent, tr("Reset Password"),
|
||||
tr("Failed to reset user account password, please contact the server operator to reset your password."));
|
||||
SettingsCache::instance().servers().setFPHostName("");
|
||||
SettingsCache::instance().servers().setFPPort("");
|
||||
SettingsCache::instance().servers().setFPPlayerName("");
|
||||
}
|
||||
|
||||
void ConnectionController::onPromptForgotPasswordReset()
|
||||
{
|
||||
QMessageBox::information(dialogParent, tr("Reset Password"),
|
||||
tr("Activation request received, please check your email for an activation token."));
|
||||
DlgForgotPasswordReset dlg(dialogParent);
|
||||
if (dlg.exec()) {
|
||||
remoteClient->submitForgotPasswordResetToServer(dlg.getHost(), static_cast<unsigned int>(dlg.getPort()),
|
||||
dlg.getPlayerName(), dlg.getToken(), dlg.getPassword());
|
||||
}
|
||||
}
|
||||
|
||||
void ConnectionController::onPromptForgotPasswordChallenge()
|
||||
{
|
||||
DlgForgotPasswordChallenge dlg(dialogParent);
|
||||
if (dlg.exec()) {
|
||||
remoteClient->submitForgotPasswordChallengeToServer(dlg.getHost(), static_cast<unsigned int>(dlg.getPort()),
|
||||
dlg.getPlayerName(), dlg.getEmail());
|
||||
}
|
||||
}
|
||||
|
||||
void ConnectionController::updateWindowTitle()
|
||||
{
|
||||
const QString appName = QStringLiteral("Cockatrice");
|
||||
QString title;
|
||||
|
||||
switch (remoteClient->getStatus()) {
|
||||
case StatusConnecting: {
|
||||
title = appName + " - " + tr("Connecting to %1...").arg(remoteClient->peerName());
|
||||
break;
|
||||
}
|
||||
case StatusRegistering: {
|
||||
title = appName + " - " +
|
||||
tr("Registering to %1 as %2...").arg(remoteClient->peerName()).arg(remoteClient->getUserName());
|
||||
break;
|
||||
}
|
||||
case StatusDisconnected: {
|
||||
title = appName + " - " + tr("Disconnected");
|
||||
break;
|
||||
}
|
||||
case StatusLoggingIn: {
|
||||
title = appName + " - " + tr("Connected, logging in at %1").arg(remoteClient->peerName());
|
||||
break;
|
||||
}
|
||||
case StatusLoggedIn: {
|
||||
title = remoteClient->getUserName() + "@" + remoteClient->peerName();
|
||||
break;
|
||||
}
|
||||
case StatusRequestingForgotPassword:
|
||||
case StatusSubmitForgotPasswordChallenge:
|
||||
case StatusSubmitForgotPasswordReset:
|
||||
title = appName + " - " +
|
||||
tr("Requesting forgotten password to %1 as %2...")
|
||||
.arg(remoteClient->peerName())
|
||||
.arg(remoteClient->getUserName());
|
||||
break;
|
||||
default:
|
||||
title = appName;
|
||||
}
|
||||
|
||||
emit windowTitleChanged(title);
|
||||
}
|
||||
|
||||
// static
|
||||
QString ConnectionController::extractInvalidUsernameMessage(QString &in)
|
||||
{
|
||||
QString out = tr("Invalid username.") + "<br/>";
|
||||
QStringList rules = in.split(QChar('|'));
|
||||
|
||||
if (rules.size() == 7 || rules.size() == 9) {
|
||||
out += tr("Your username must respect these rules:") + "<ul>";
|
||||
|
||||
out += "<li>" + tr("is %1 - %2 characters long").arg(rules.at(0)).arg(rules.at(1)) + "</li>";
|
||||
out += "<li>" + tr("can %1 contain lowercase characters").arg((rules.at(2).toInt() > 0) ? "" : tr("NOT")) +
|
||||
"</li>";
|
||||
out += "<li>" + tr("can %1 contain uppercase characters").arg((rules.at(3).toInt() > 0) ? "" : tr("NOT")) +
|
||||
"</li>";
|
||||
out +=
|
||||
"<li>" + tr("can %1 contain numeric characters").arg((rules.at(4).toInt() > 0) ? "" : tr("NOT")) + "</li>";
|
||||
|
||||
if (rules.at(6).size() > 0) {
|
||||
out += "<li>" + tr("can contain the following punctuation: %1").arg(rules.at(6).toHtmlEscaped()) + "</li>";
|
||||
}
|
||||
|
||||
out += "<li>" +
|
||||
tr("first character can %1 be a punctuation mark").arg((rules.at(5).toInt() > 0) ? "" : tr("NOT")) +
|
||||
"</li>";
|
||||
|
||||
if (rules.size() == 9) {
|
||||
if (rules.at(7).size() > 0) {
|
||||
QString words = rules.at(7).toHtmlEscaped();
|
||||
if (words.startsWith("\n")) {
|
||||
out += tr("no unacceptable language as specified by these server rules:",
|
||||
"note that the following lines will not be translated");
|
||||
for (QString &line : words.split("\n", Qt::SkipEmptyParts)) {
|
||||
out += "<li>" + line + "</li>";
|
||||
}
|
||||
} else {
|
||||
out += "<li>" + tr("can not contain any of the following words: %1").arg(words) + "</li>";
|
||||
}
|
||||
}
|
||||
|
||||
if (rules.at(8).size() > 0) {
|
||||
out += "<li>" +
|
||||
tr("can not match any of the following expressions: %1").arg(rules.at(8).toHtmlEscaped()) +
|
||||
"</li>";
|
||||
}
|
||||
}
|
||||
|
||||
out += "</ul>";
|
||||
} else {
|
||||
out += tr("You may only use A-Z, a-z, 0-9, _, ., and - in your username.");
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
#ifndef COCKATRICE_REMOTE_CONNECTION_CONTROLLER_H
|
||||
#define COCKATRICE_REMOTE_CONNECTION_CONTROLLER_H
|
||||
|
||||
#include "abstract_client.h"
|
||||
|
||||
#include <QMessageBox>
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
#include <QThread>
|
||||
#include <libcockatrice/protocol/pb/event_connection_closed.pb.h>
|
||||
#include <libcockatrice/protocol/pb/event_server_shutdown.pb.h>
|
||||
|
||||
class RemoteClient;
|
||||
class ServerInfo_User;
|
||||
class DlgConnect;
|
||||
|
||||
/**
|
||||
* Owns the RemoteClient and its worker thread.
|
||||
* Encapsulates all connection, authentication, and registration logic so that
|
||||
* MainWindow only needs to react to high-level signals.
|
||||
*/
|
||||
class ConnectionController : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
explicit ConnectionController(QWidget *dialogParent, QObject *parent = nullptr);
|
||||
~ConnectionController() override;
|
||||
|
||||
RemoteClient *client() const
|
||||
{
|
||||
return remoteClient;
|
||||
}
|
||||
|
||||
void registerToServer();
|
||||
void forgotPasswordRequest();
|
||||
void connectToServer();
|
||||
void
|
||||
connectToServerDirect(const QString &host, unsigned int port, const QString &playerName, const QString &password);
|
||||
void disconnectFromServer();
|
||||
|
||||
void refreshWindowTitle()
|
||||
{
|
||||
updateWindowTitle();
|
||||
}
|
||||
|
||||
signals:
|
||||
void windowTitleChanged(const QString &title);
|
||||
|
||||
void tabSupervisorStartRequested(const ServerInfo_User &info);
|
||||
void tabSupervisorStopRequested();
|
||||
|
||||
// Passes the raw ClientStatus through so MainWindow can drive its own
|
||||
// action enable/disable logic
|
||||
void statusChanged(ClientStatus status);
|
||||
|
||||
private slots:
|
||||
// Slots wired directly to RemoteClient signals
|
||||
void onStatusChanged(ClientStatus status);
|
||||
void onUserInfoReceived(const ServerInfo_User &info);
|
||||
void onLoginError(int r, QString reasonStr, quint32 endTime, const QList<QString> &missingFeatures);
|
||||
void onRegisterAccepted();
|
||||
void onRegisterAcceptedNeedsActivate();
|
||||
void onRegisterError(int r, QString reasonStr, quint32 endTime);
|
||||
void onActivateAccepted();
|
||||
void onActivateError();
|
||||
void onProtocolVersionMismatch(int localVersion, int remoteVersion);
|
||||
void onNotifyUserAboutUpdate();
|
||||
void onConnectionClosedEvent(const Event_ConnectionClosed &event);
|
||||
void onServerShutdownEvent(const Event_ServerShutdown &event);
|
||||
void onSocketError(const QString &errorStr);
|
||||
void onServerTimeout();
|
||||
|
||||
// Forgot-password flow
|
||||
void onForgotPasswordSuccess();
|
||||
void onForgotPasswordError();
|
||||
void onPromptForgotPasswordReset();
|
||||
void onPromptForgotPasswordChallenge();
|
||||
|
||||
private:
|
||||
void wireClientSignals();
|
||||
void updateWindowTitle();
|
||||
|
||||
/** Parse the server's pipe-delimited username-rule string into HTML. */
|
||||
static QString extractInvalidUsernameMessage(QString &in);
|
||||
|
||||
RemoteClient *remoteClient{nullptr};
|
||||
QThread *clientThread{nullptr};
|
||||
QWidget *dialogParent{nullptr}; // used as parent for QMessageBox / dialog calls
|
||||
|
||||
// Persistent so it can be updated in-place by onServerShutdownEvent
|
||||
QMessageBox serverShutdownMessageBox;
|
||||
|
||||
// Kept as a member so the forgot-password signal can be wired to it
|
||||
DlgConnect *dlgConnect{nullptr};
|
||||
};
|
||||
|
||||
#endif // COCKATRICE_REMOTE_CONNECTION_CONTROLLER_H
|
||||
@@ -0,0 +1,82 @@
|
||||
#include "deck_stats_interface.h"
|
||||
|
||||
#include <QDesktopServices>
|
||||
#include <QMessageBox>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QRegularExpression>
|
||||
#include <QUrlQuery>
|
||||
#include <libcockatrice/card/database/card_database_manager.h>
|
||||
#include <libcockatrice/deck_list/deck_list.h>
|
||||
#include <libcockatrice/deck_list/tree/deck_list_card_node.h>
|
||||
#include <version_string.h>
|
||||
|
||||
DeckStatsInterface::DeckStatsInterface(QObject *parent) : QObject(parent)
|
||||
{
|
||||
manager = new QNetworkAccessManager(this);
|
||||
connect(manager, &QNetworkAccessManager::finished, this, &DeckStatsInterface::queryFinished);
|
||||
}
|
||||
|
||||
void DeckStatsInterface::queryFinished(QNetworkReply *reply)
|
||||
{
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
QMessageBox::critical(nullptr, tr("Error"), reply->errorString());
|
||||
reply->deleteLater();
|
||||
deleteLater();
|
||||
return;
|
||||
}
|
||||
|
||||
QString data(reply->readAll());
|
||||
reply->deleteLater();
|
||||
|
||||
static const QRegularExpression rx("<meta property=\"og:url\" content=\"([^\"]+)\"");
|
||||
auto match = rx.match(data);
|
||||
if (!match.hasMatch()) {
|
||||
QMessageBox::critical(nullptr, tr("Error"), tr("The reply from the server could not be parsed."));
|
||||
deleteLater();
|
||||
return;
|
||||
}
|
||||
|
||||
QString deckUrl = match.captured(1);
|
||||
QDesktopServices::openUrl(deckUrl);
|
||||
|
||||
deleteLater();
|
||||
}
|
||||
|
||||
void DeckStatsInterface::getAnalyzeRequestData(const DeckList &deck, QByteArray &data)
|
||||
{
|
||||
DeckList deckWithoutTokens;
|
||||
copyDeckWithoutTokens(deck, deckWithoutTokens);
|
||||
|
||||
QUrl params;
|
||||
QUrlQuery urlQuery;
|
||||
urlQuery.addQueryItem("deck", deckWithoutTokens.writeToString_Plain());
|
||||
urlQuery.addQueryItem("decktitle", deck.getName());
|
||||
params.setQuery(urlQuery);
|
||||
data.append(params.query(QUrl::EncodeReserved).toUtf8());
|
||||
}
|
||||
|
||||
void DeckStatsInterface::analyzeDeck(const DeckList &deck)
|
||||
{
|
||||
QByteArray data;
|
||||
getAnalyzeRequestData(deck, data);
|
||||
|
||||
QNetworkRequest request(QUrl("https://deckstats.net/index.php"));
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
|
||||
request.setHeader(QNetworkRequest::UserAgentHeader, QString("Cockatrice %1").arg(VERSION_STRING));
|
||||
|
||||
manager->post(request, data);
|
||||
}
|
||||
|
||||
void DeckStatsInterface::copyDeckWithoutTokens(const DeckList &source, DeckList &destination)
|
||||
{
|
||||
auto copyIfNotAToken = [&destination](const auto node, const auto card) {
|
||||
CardInfoPtr dbCard = CardDatabaseManager::query()->getCardInfo(card->getName());
|
||||
if (dbCard && !dbCard->getIsToken()) {
|
||||
DecklistCardNode *addedCard = destination.addCard(card->getName(), node->getName(), -1);
|
||||
addedCard->setNumber(card->getNumber());
|
||||
}
|
||||
};
|
||||
|
||||
source.forEachCard(copyIfNotAToken);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* @file deck_stats_interface.h
|
||||
* @ingroup ApiInterfaces
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef DECKSTATS_INTERFACE_H
|
||||
#define DECKSTATS_INTERFACE_H
|
||||
|
||||
#include <libcockatrice/deck_list/deck_list.h>
|
||||
|
||||
class QByteArray;
|
||||
class QNetworkAccessManager;
|
||||
class QNetworkReply;
|
||||
class DeckList;
|
||||
|
||||
class DeckStatsInterface : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
private:
|
||||
QNetworkAccessManager *manager;
|
||||
|
||||
/**
|
||||
* Deckstats doesn't recognize token cards, and instead tries to find the
|
||||
* closest non-token card instead. So we construct a new deck which has no
|
||||
* tokens.
|
||||
*/
|
||||
void copyDeckWithoutTokens(const DeckList &source, DeckList &destination);
|
||||
|
||||
private slots:
|
||||
void queryFinished(QNetworkReply *reply);
|
||||
void getAnalyzeRequestData(const DeckList &deck, QByteArray &data);
|
||||
|
||||
public:
|
||||
explicit DeckStatsInterface(QObject *parent = nullptr);
|
||||
void analyzeDeck(const DeckList &deck);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,116 @@
|
||||
#include "tapped_out_interface.h"
|
||||
|
||||
#include <QDesktopServices>
|
||||
#include <QMessageBox>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QRegularExpression>
|
||||
#include <QUrlQuery>
|
||||
#include <libcockatrice/card/database/card_database_manager.h>
|
||||
#include <libcockatrice/deck_list/deck_list.h>
|
||||
#include <libcockatrice/deck_list/tree/deck_list_card_node.h>
|
||||
#include <version_string.h>
|
||||
|
||||
TappedOutInterface::TappedOutInterface(QObject *parent) : QObject(parent)
|
||||
{
|
||||
manager = new QNetworkAccessManager(this);
|
||||
connect(manager, &QNetworkAccessManager::finished, this, &TappedOutInterface::queryFinished);
|
||||
}
|
||||
|
||||
void TappedOutInterface::queryFinished(QNetworkReply *reply)
|
||||
{
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
QMessageBox::critical(nullptr, tr("Error"), reply->errorString());
|
||||
reply->deleteLater();
|
||||
deleteLater();
|
||||
return;
|
||||
}
|
||||
|
||||
int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||||
if (reply->hasRawHeader("Location")) {
|
||||
/*
|
||||
* If the reply contains a "Location" header, a relative URL to the deck on TappedOut
|
||||
* can be extracted from the header. The http status is a 302 "redirect".
|
||||
*/
|
||||
QString deckUrl = reply->rawHeader("Location");
|
||||
qCInfo(TappedOutInterfaceLog) << "Tappedout: good reply, http status" << httpStatus << "location" << deckUrl;
|
||||
QDesktopServices::openUrl("https://tappedout.net" + deckUrl);
|
||||
} else {
|
||||
/*
|
||||
* Otherwise, the deck has not been parsed correctly. Error messages can be extracted
|
||||
* from the html. Css pseudo selector for errors: $("div.alert-danger > ul > li")
|
||||
*/
|
||||
QString data(reply->readAll());
|
||||
QStringList errorMessageList = {tr("Unable to analyze the deck.")};
|
||||
|
||||
static const QRegularExpression rx("<div class=\"alert alert-danger.*?<ul>(.*?)</ul>");
|
||||
auto match = rx.match(data);
|
||||
if (match.hasMatch()) {
|
||||
QString errors = match.captured(1);
|
||||
static const QRegularExpression rx2("<li>(.*?)</li>");
|
||||
static const QRegularExpression rxremove("<[^>]*>");
|
||||
auto matchIterator = rx2.globalMatch(errors);
|
||||
while (matchIterator.hasNext()) {
|
||||
auto match2 = matchIterator.next();
|
||||
errorMessageList.append(match2.captured(1).remove(rxremove).simplified());
|
||||
}
|
||||
}
|
||||
|
||||
QString errorMessage = errorMessageList.join("\n");
|
||||
qCWarning(TappedOutInterfaceLog) << "Tappedout: bad reply, http status" << httpStatus << "size" << data.size()
|
||||
<< "message" << errorMessage;
|
||||
|
||||
QMessageBox::critical(nullptr, tr("Error"), errorMessage);
|
||||
}
|
||||
|
||||
reply->deleteLater();
|
||||
deleteLater();
|
||||
}
|
||||
|
||||
void TappedOutInterface::getAnalyzeRequestData(const DeckList &deck, QByteArray &data)
|
||||
{
|
||||
DeckList mainboard, sideboard;
|
||||
copyDeckSplitMainAndSide(deck, mainboard, sideboard);
|
||||
|
||||
QUrl params;
|
||||
QUrlQuery urlQuery;
|
||||
urlQuery.addQueryItem("name", deck.getName());
|
||||
urlQuery.addQueryItem("mainboard", mainboard.writeToString_Plain(false, true));
|
||||
urlQuery.addQueryItem("sideboard", sideboard.writeToString_Plain(false, true));
|
||||
params.setQuery(urlQuery);
|
||||
data.append(params.query(QUrl::EncodeReserved).toUtf8());
|
||||
}
|
||||
|
||||
void TappedOutInterface::analyzeDeck(const DeckList &deck)
|
||||
{
|
||||
QByteArray data;
|
||||
getAnalyzeRequestData(deck, data);
|
||||
|
||||
QNetworkRequest request(QUrl("https://tappedout.net/mtg-decks/paste/"));
|
||||
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
|
||||
request.setHeader(QNetworkRequest::UserAgentHeader, QString("Cockatrice %1").arg(VERSION_STRING));
|
||||
// we interpret the redirect and open it in the browser instead, do not follow redirects
|
||||
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute, QNetworkRequest::ManualRedirectPolicy);
|
||||
|
||||
manager->post(request, data);
|
||||
}
|
||||
|
||||
void TappedOutInterface::copyDeckSplitMainAndSide(const DeckList &source, DeckList &mainboard, DeckList &sideboard)
|
||||
{
|
||||
auto copyMainOrSide = [&mainboard, &sideboard](const auto node, const auto card) {
|
||||
CardInfoPtr dbCard = CardDatabaseManager::query()->getCardInfo(card->getName());
|
||||
if (!dbCard || dbCard->getIsToken()) {
|
||||
return;
|
||||
}
|
||||
|
||||
DecklistCardNode *addedCard;
|
||||
if (node->getName() == DECK_ZONE_SIDE) {
|
||||
addedCard = sideboard.addCard(card->getName(), node->getName(), -1);
|
||||
} else {
|
||||
addedCard = mainboard.addCard(card->getName(), node->getName(), -1);
|
||||
}
|
||||
addedCard->setNumber(card->getNumber());
|
||||
};
|
||||
|
||||
source.forEachCard(copyMainOrSide);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* @file tapped_out_interface.h
|
||||
* @ingroup ApiInterfaces
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef TAPPEDOUT_INTERFACE_H
|
||||
#define TAPPEDOUT_INTERFACE_H
|
||||
|
||||
#include <QLoggingCategory>
|
||||
#include <QObject>
|
||||
|
||||
inline Q_LOGGING_CATEGORY(TappedOutInterfaceLog, "tapped_out_interface");
|
||||
|
||||
class QByteArray;
|
||||
class QNetworkAccessManager;
|
||||
class QNetworkReply;
|
||||
class DeckList;
|
||||
|
||||
/**
|
||||
* TappedOutInterface exists in order to support the "Analyze on TappedOut" feature.
|
||||
* An http POST request is sent and the result is retrieved from the reply. Parsing
|
||||
* logic is implemented in TappedOutInterface::queryFinished().
|
||||
*/
|
||||
|
||||
class TappedOutInterface : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
private:
|
||||
QNetworkAccessManager *manager;
|
||||
|
||||
void copyDeckSplitMainAndSide(const DeckList &source, DeckList &mainboard, DeckList &sideboard);
|
||||
private slots:
|
||||
void queryFinished(QNetworkReply *reply);
|
||||
void getAnalyzeRequestData(const DeckList &deck, QByteArray &data);
|
||||
|
||||
public:
|
||||
explicit TappedOutInterface(QObject *parent = nullptr);
|
||||
void analyzeDeck(const DeckList &deck);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,61 @@
|
||||
#include "deck_link_to_api_transformer.h"
|
||||
|
||||
#include <QRegularExpression>
|
||||
|
||||
namespace DeckLinkToApiTransformer
|
||||
{
|
||||
|
||||
static const QString TAPPEDOUT_BASE = "https://tappedout.net/mtg-decks/";
|
||||
static const QString TAPPEDOUT_SUFFIX = "/?fmt=txt";
|
||||
|
||||
static const QString ARCHIDEKT_BASE = "https://archidekt.com/api/decks/";
|
||||
static const QString ARCHIDEKT_SUFFIX = "/?format=json";
|
||||
|
||||
static const QString MOXFIELD_BASE = "https://api.moxfield.com/v2/decks/all/";
|
||||
static const QString MOXFIELD_SUFFIX = "/";
|
||||
|
||||
static const QString DECKSTATS_SUFFIX = "?include_comments=1&export_mtgarena=1";
|
||||
|
||||
bool parseDeckUrl(const QString &url, ParsedDeckInfo &outInfo)
|
||||
{
|
||||
static QRegularExpression rxTappedOut("tappedout\\.net/(?:mtg-decks/)?([^/?#]+)");
|
||||
static QRegularExpression rxArchidekt("archidekt\\.com/decks/(\\d+)");
|
||||
static QRegularExpression rxMoxfield("moxfield\\.com/decks/([a-zA-Z0-9_-]+)");
|
||||
static QRegularExpression rxDeckstats("deckstats\\.net/decks/(\\d+/[a-zA-Z0-9_-]+)");
|
||||
|
||||
QRegularExpressionMatch match;
|
||||
|
||||
if ((match = rxTappedOut.match(url)).hasMatch()) {
|
||||
QString slug = match.captured(1);
|
||||
outInfo = ParsedDeckInfo{.baseUrl = TAPPEDOUT_BASE,
|
||||
.deckID = slug,
|
||||
.fullUrl = TAPPEDOUT_BASE + slug + TAPPEDOUT_SUFFIX,
|
||||
.provider = DeckProvider::TappedOut};
|
||||
return true;
|
||||
} else if ((match = rxArchidekt.match(url)).hasMatch()) {
|
||||
QString deckID = match.captured(1);
|
||||
outInfo = ParsedDeckInfo{.baseUrl = ARCHIDEKT_BASE,
|
||||
.deckID = deckID,
|
||||
.fullUrl = ARCHIDEKT_BASE + deckID + ARCHIDEKT_SUFFIX,
|
||||
.provider = DeckProvider::Archidekt};
|
||||
return true;
|
||||
} else if ((match = rxMoxfield.match(url)).hasMatch()) {
|
||||
QString deckID = match.captured(1);
|
||||
outInfo = ParsedDeckInfo{.baseUrl = MOXFIELD_BASE,
|
||||
.deckID = deckID,
|
||||
.fullUrl = MOXFIELD_BASE + deckID + MOXFIELD_SUFFIX,
|
||||
.provider = DeckProvider::Moxfield};
|
||||
return true;
|
||||
} else if ((match = rxDeckstats.match(url)).hasMatch()) {
|
||||
QString deckPath = match.captured(1);
|
||||
outInfo = ParsedDeckInfo{.baseUrl = "https://deckstats.net/decks/",
|
||||
.deckID = deckPath,
|
||||
.fullUrl = "https://deckstats.net/decks/" + deckPath + DECKSTATS_SUFFIX,
|
||||
.provider = DeckProvider::Deckstats};
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace DeckLinkToApiTransformer
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* @file deck_link_to_api_transformer.h
|
||||
* @ingroup ApiInterfaces
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef DECK_LINK_TO_API_TRANSFORMER_H
|
||||
#define DECK_LINK_TO_API_TRANSFORMER_H
|
||||
|
||||
#include <QString>
|
||||
|
||||
enum class DeckProvider
|
||||
{
|
||||
TappedOut,
|
||||
Archidekt,
|
||||
Moxfield,
|
||||
Deckstats,
|
||||
Unknown
|
||||
};
|
||||
|
||||
struct ParsedDeckInfo
|
||||
{
|
||||
QString baseUrl;
|
||||
QString deckID;
|
||||
QString fullUrl;
|
||||
DeckProvider provider;
|
||||
};
|
||||
|
||||
namespace DeckLinkToApiTransformer
|
||||
{
|
||||
|
||||
// Returns true if the input URL is recognized and fills outInfo.
|
||||
bool parseDeckUrl(const QString &url, ParsedDeckInfo &outInfo);
|
||||
|
||||
} // namespace DeckLinkToApiTransformer
|
||||
|
||||
#endif // DECK_LINK_TO_API_TRANSFORMER_H
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* @file interface_json_deck_parser.h
|
||||
* @ingroup ApiInterfaces
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef INTERFACE_JSON_DECK_PARSER_H
|
||||
#define INTERFACE_JSON_DECK_PARSER_H
|
||||
|
||||
#include "../../../interface/deck_loader/card_node_function.h"
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonObject>
|
||||
#include <libcockatrice/card/import/card_name_normalizer.h>
|
||||
#include <libcockatrice/deck_list/deck_list.h>
|
||||
|
||||
class IJsonDeckParser
|
||||
{
|
||||
public:
|
||||
virtual ~IJsonDeckParser() = default;
|
||||
|
||||
virtual DeckList parse(const QJsonObject &obj) = 0;
|
||||
};
|
||||
|
||||
class ArchidektJsonParser : public IJsonDeckParser
|
||||
{
|
||||
public:
|
||||
DeckList parse(const QJsonObject &obj) override
|
||||
{
|
||||
DeckList deckList;
|
||||
|
||||
QString deckName = obj.value("name").toString();
|
||||
QString deckDescription = obj.value("description").toString();
|
||||
|
||||
deckList.setName(deckName);
|
||||
deckList.setComments(deckDescription);
|
||||
|
||||
QString outputText;
|
||||
QTextStream outStream(&outputText);
|
||||
|
||||
for (auto entry : obj.value("cards").toArray()) {
|
||||
auto quantity = entry.toObject().value("quantity").toInt();
|
||||
|
||||
auto card = entry.toObject().value("card").toObject();
|
||||
auto oracleCard = card.value("oracleCard").toObject();
|
||||
QString cardName = oracleCard.value("name").toString();
|
||||
QString setName = card.value("edition").toObject().value("editioncode").toString().toUpper();
|
||||
QString collectorNumber = card.value("collectorNumber").toString();
|
||||
|
||||
outStream << quantity << ' ' << cardName << " (" << setName << ") " << collectorNumber << '\n';
|
||||
}
|
||||
|
||||
deckList.loadFromStream_Plain(outStream, false, CardNameNormalizer());
|
||||
deckList.forEachCard(CardNodeFunction::ResolveProviderId());
|
||||
|
||||
return deckList;
|
||||
}
|
||||
};
|
||||
|
||||
class MoxfieldJsonParser : public IJsonDeckParser
|
||||
{
|
||||
public:
|
||||
DeckList parse(const QJsonObject &obj) override
|
||||
{
|
||||
DeckList deckList;
|
||||
|
||||
QString deckName = obj.value("name").toString();
|
||||
QString deckDescription = obj.value("description").toString();
|
||||
|
||||
deckList.setName(deckName);
|
||||
deckList.setComments(deckDescription);
|
||||
|
||||
QString outputText;
|
||||
QTextStream outStream(&outputText);
|
||||
|
||||
for (auto entry : obj.value("mainboard").toObject()) {
|
||||
auto quantity = entry.toObject().value("quantity").toInt();
|
||||
|
||||
auto card = entry.toObject().value("card").toObject();
|
||||
QString cardName = card.value("name").toString();
|
||||
QString setName = card.value("set").toString().toUpper();
|
||||
QString collectorNumber = card.value("cn").toString();
|
||||
|
||||
outStream << quantity << ' ' << cardName << " (" << setName << ") " << collectorNumber << '\n';
|
||||
}
|
||||
|
||||
outStream << '\n';
|
||||
|
||||
for (auto entry : obj.value("sideboard").toObject()) {
|
||||
auto quantity = entry.toObject().value("quantity").toInt();
|
||||
|
||||
auto card = entry.toObject().value("card").toObject();
|
||||
QString cardName = card.value("name").toString();
|
||||
QString setName = card.value("set").toString().toUpper();
|
||||
QString collectorNumber = card.value("cn").toString();
|
||||
|
||||
outStream << quantity << ' ' << cardName << " (" << setName << ") " << collectorNumber << '\n';
|
||||
}
|
||||
|
||||
deckList.loadFromStream_Plain(outStream, false, CardNameNormalizer());
|
||||
deckList.forEachCard(CardNodeFunction::ResolveProviderId());
|
||||
|
||||
QJsonObject commandersObj = obj.value("commanders").toObject();
|
||||
if (!commandersObj.isEmpty()) {
|
||||
for (auto it = commandersObj.begin(); it != commandersObj.end(); ++it) {
|
||||
QJsonObject cardData = it.value().toObject().value("card").toObject();
|
||||
QString commanderName = cardData.value("name").toString();
|
||||
QString setName = cardData.value("set").toString().toUpper();
|
||||
QString collectorNumber = cardData.value("cn").toString();
|
||||
QString providerId = cardData.value("scryfall_id").toString();
|
||||
|
||||
deckList.setBannerCard({commanderName, providerId});
|
||||
deckList.addCard(commanderName, DECK_ZONE_MAIN, -1, setName, collectorNumber, providerId);
|
||||
}
|
||||
}
|
||||
|
||||
return deckList;
|
||||
}
|
||||
};
|
||||
|
||||
#endif // INTERFACE_JSON_DECK_PARSER_H
|
||||
@@ -0,0 +1,228 @@
|
||||
#include "spoiler_background_updater.h"
|
||||
|
||||
#include "../../../../interface/window_main.h"
|
||||
#include "../../../../main.h"
|
||||
#include "../../../settings/cache_settings.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QDateTime>
|
||||
#include <QDebug>
|
||||
#include <QFile>
|
||||
#include <QLocale>
|
||||
#include <QNetworkReply>
|
||||
#include <QUrl>
|
||||
#include <QtConcurrent>
|
||||
#include <libcockatrice/card/database/card_database.h>
|
||||
#include <libcockatrice/card/database/card_database_manager.h>
|
||||
#include <version_string.h>
|
||||
|
||||
#define SPOILERS_STATUS_URL "https://raw.githubusercontent.com/Cockatrice/Magic-Spoiler/files/SpoilerSeasonEnabled"
|
||||
#define SPOILERS_URL "https://raw.githubusercontent.com/Cockatrice/Magic-Spoiler/files/spoiler.xml"
|
||||
|
||||
SpoilerBackgroundUpdater::SpoilerBackgroundUpdater(QObject *apParent) : QObject(apParent), cardUpdateProcess(nullptr)
|
||||
{
|
||||
isSpoilerDownloadEnabled = SettingsCache::instance().getDownloadSpoilersStatus();
|
||||
if (isSpoilerDownloadEnabled) {
|
||||
// Start the process of checking if we're in spoiler season
|
||||
// File exists means we're in spoiler season
|
||||
startSpoilerDownloadProcess(SPOILERS_STATUS_URL, false);
|
||||
} else {
|
||||
qCInfo(SpoilerBackgroundUpdaterLog) << "Spoilers Disabled";
|
||||
}
|
||||
}
|
||||
|
||||
void SpoilerBackgroundUpdater::startSpoilerDownloadProcess(QString url, bool saveResults)
|
||||
{
|
||||
auto spoilerURL = QUrl(url);
|
||||
downloadFromURL(spoilerURL, saveResults);
|
||||
}
|
||||
|
||||
void SpoilerBackgroundUpdater::downloadFromURL(QUrl url, bool saveResults)
|
||||
{
|
||||
auto *nam = new QNetworkAccessManager(this);
|
||||
auto request = QNetworkRequest(url);
|
||||
request.setHeader(QNetworkRequest::UserAgentHeader, QString("Cockatrice %1").arg(VERSION_STRING));
|
||||
QNetworkReply *reply = nam->get(request);
|
||||
|
||||
if (saveResults) {
|
||||
// This will write out to the file (used for spoiler.xml)
|
||||
connect(reply, &QNetworkReply::finished, this, &SpoilerBackgroundUpdater::actDownloadFinishedSpoilersFile);
|
||||
} else {
|
||||
// This will check the status (used to see if we're in spoiler season or not)
|
||||
connect(reply, &QNetworkReply::finished, this, &SpoilerBackgroundUpdater::actCheckIfSpoilerSeasonEnabled);
|
||||
}
|
||||
}
|
||||
|
||||
void SpoilerBackgroundUpdater::actDownloadFinishedSpoilersFile()
|
||||
{
|
||||
// Check for server reply
|
||||
auto *reply = dynamic_cast<QNetworkReply *>(sender());
|
||||
QNetworkReply::NetworkError errorCode = reply->error();
|
||||
|
||||
if (errorCode == QNetworkReply::NoError) {
|
||||
spoilerData = reply->readAll();
|
||||
|
||||
// Save the spoiler.xml file to the disk
|
||||
saveDownloadedFile(spoilerData);
|
||||
|
||||
reply->deleteLater();
|
||||
emit spoilerCheckerDone();
|
||||
} else {
|
||||
qCWarning(SpoilerBackgroundUpdaterLog) << "Error downloading spoilers file" << errorCode;
|
||||
emit spoilerCheckerDone();
|
||||
}
|
||||
}
|
||||
|
||||
bool SpoilerBackgroundUpdater::deleteSpoilerFile()
|
||||
{
|
||||
QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath();
|
||||
QFileInfo fi(fileName);
|
||||
QDir fileDir(fi.path());
|
||||
QFile file(fileName);
|
||||
|
||||
// Delete the spoiler.xml file
|
||||
if (file.exists() && file.remove()) {
|
||||
qCInfo(SpoilerBackgroundUpdaterLog) << "Deleting spoiler.xml";
|
||||
return true;
|
||||
}
|
||||
|
||||
qCInfo(SpoilerBackgroundUpdaterLog) << "Error: Spoiler.xml not found or not deleted";
|
||||
return false;
|
||||
}
|
||||
|
||||
void SpoilerBackgroundUpdater::actCheckIfSpoilerSeasonEnabled()
|
||||
{
|
||||
auto *response = dynamic_cast<QNetworkReply *>(sender());
|
||||
QNetworkReply::NetworkError errorCode = response->error();
|
||||
|
||||
if (errorCode == QNetworkReply::ContentNotFoundError) {
|
||||
// Spoiler season is offline at this point, so the spoiler.xml file can be safely deleted
|
||||
// The user should run Oracle to get the latest card information
|
||||
if (deleteSpoilerFile() && trayIcon) {
|
||||
trayIcon->showMessage(tr("Spoilers season has ended"), tr("Deleting spoiler.xml. Please run Oracle"));
|
||||
}
|
||||
|
||||
qCInfo(SpoilerBackgroundUpdaterLog) << "Spoiler Season Offline";
|
||||
emit spoilerCheckerDone();
|
||||
} else if (errorCode == QNetworkReply::NoError) {
|
||||
qCInfo(SpoilerBackgroundUpdaterLog) << "Spoiler Service Online";
|
||||
startSpoilerDownloadProcess(SPOILERS_URL, true);
|
||||
} else if (errorCode == QNetworkReply::HostNotFoundError) {
|
||||
if (trayIcon) {
|
||||
trayIcon->showMessage(tr("Spoilers download failed"), tr("No internet connection"));
|
||||
}
|
||||
|
||||
qCWarning(SpoilerBackgroundUpdaterLog) << "Spoiler download failed due to no internet connection";
|
||||
emit spoilerCheckerDone();
|
||||
} else {
|
||||
if (trayIcon) {
|
||||
trayIcon->showMessage(tr("Spoilers download failed"), tr("Error") + " " + (short)errorCode);
|
||||
}
|
||||
|
||||
qCWarning(SpoilerBackgroundUpdaterLog) << "Spoiler download failed with reason" << errorCode;
|
||||
emit spoilerCheckerDone();
|
||||
}
|
||||
}
|
||||
|
||||
bool SpoilerBackgroundUpdater::saveDownloadedFile(QByteArray data)
|
||||
{
|
||||
QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath();
|
||||
QFileInfo fi(fileName);
|
||||
QDir fileDir(fi.path());
|
||||
|
||||
if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the data matches. If it does, then spoilers are up to date.
|
||||
if (getHash(fileName) == getHash(data)) {
|
||||
if (trayIcon) {
|
||||
trayIcon->showMessage(tr("Spoilers already up to date"), tr("No new spoilers added"));
|
||||
}
|
||||
|
||||
qCInfo(SpoilerBackgroundUpdaterLog) << "Spoilers Up to Date";
|
||||
return false;
|
||||
}
|
||||
|
||||
QFile file(fileName);
|
||||
if (!file.open(QIODevice::WriteOnly)) {
|
||||
qCWarning(SpoilerBackgroundUpdaterLog) << "Spoiler Service Error: File open (w) failed for" << fileName;
|
||||
file.close();
|
||||
return false;
|
||||
}
|
||||
|
||||
if (file.write(data) == -1) {
|
||||
qCWarning(SpoilerBackgroundUpdaterLog) << "Spoiler Service Error: File write (w) failed for" << fileName;
|
||||
file.close();
|
||||
return false;
|
||||
}
|
||||
|
||||
file.close();
|
||||
|
||||
// Data written, so reload the card database
|
||||
qCInfo(SpoilerBackgroundUpdaterLog) << "Spoiler Service Data Written";
|
||||
const auto reloadOk = QtConcurrent::run([] { CardDatabaseManager::getInstance()->loadCardDatabases(); });
|
||||
|
||||
// If the user has notifications enabled, let them know
|
||||
// when the database was last updated
|
||||
if (trayIcon) {
|
||||
QList<QByteArray> lines = data.split('\n');
|
||||
|
||||
for (const QByteArray &line : lines) {
|
||||
if (line.contains("Created At:")) {
|
||||
QString timeStamp = QString(line).replace("Created At:", "").trimmed();
|
||||
timeStamp.chop(6); // Remove " (UTC)"
|
||||
|
||||
auto utcTime = QLocale().toDateTime(timeStamp, "ddd, MMM dd yyyy, hh:mm:ss");
|
||||
#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
|
||||
utcTime.setTimeZone(QTimeZone::UTC);
|
||||
#else
|
||||
utcTime.setTimeSpec(Qt::UTC);
|
||||
#endif
|
||||
|
||||
QString localTime = utcTime.toLocalTime().toString("MMM d, hh:mm");
|
||||
|
||||
trayIcon->showMessage(tr("Spoilers have been updated!"), tr("Last change:") + " " + localTime);
|
||||
emit spoilersUpdatedSuccessfully();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
QByteArray SpoilerBackgroundUpdater::getHash(const QString fileName)
|
||||
{
|
||||
QFile file(fileName);
|
||||
|
||||
if (file.open(QFile::ReadOnly)) {
|
||||
// Only read the first 512 bytes (enough to get the "created" tag)
|
||||
const QByteArray bytes = file.read(512);
|
||||
|
||||
QCryptographicHash hash(QCryptographicHash::Algorithm::Md5);
|
||||
hash.addData(bytes);
|
||||
|
||||
qCInfo(SpoilerBackgroundUpdaterLog) << "File Hash =" << hash.result();
|
||||
|
||||
file.close();
|
||||
return hash.result();
|
||||
} else {
|
||||
qCWarning(SpoilerBackgroundUpdaterLog) << "getHash ReadOnly failed!";
|
||||
file.close();
|
||||
return QByteArray();
|
||||
}
|
||||
}
|
||||
|
||||
QByteArray SpoilerBackgroundUpdater::getHash(QByteArray data)
|
||||
{
|
||||
// Only read the first 512 bytes (enough to get the "created" tag)
|
||||
const QByteArray bytes = data.left(512);
|
||||
|
||||
QCryptographicHash hash(QCryptographicHash::Algorithm::Md5);
|
||||
hash.addData(bytes);
|
||||
|
||||
qCInfo(SpoilerBackgroundUpdaterLog) << "Data Hash =" << hash.result();
|
||||
|
||||
return hash.result();
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* @file spoiler_background_updater.h
|
||||
* @ingroup Client
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef COCKATRICE_SPOILER_DOWNLOADER_H
|
||||
#define COCKATRICE_SPOILER_DOWNLOADER_H
|
||||
|
||||
#include <QByteArray>
|
||||
#include <QLoggingCategory>
|
||||
#include <QObject>
|
||||
#include <QProcess>
|
||||
|
||||
inline Q_LOGGING_CATEGORY(SpoilerBackgroundUpdaterLog, "spoiler_background_updater");
|
||||
|
||||
class SpoilerBackgroundUpdater : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit SpoilerBackgroundUpdater(QObject *apParent = nullptr);
|
||||
inline QString getCardUpdaterBinaryName()
|
||||
{
|
||||
return "oracle";
|
||||
}
|
||||
QByteArray getHash(const QString fileName);
|
||||
QByteArray getHash(QByteArray data);
|
||||
static bool deleteSpoilerFile();
|
||||
|
||||
private slots:
|
||||
void actDownloadFinishedSpoilersFile();
|
||||
void actCheckIfSpoilerSeasonEnabled();
|
||||
|
||||
private:
|
||||
bool isSpoilerDownloadEnabled;
|
||||
QProcess *cardUpdateProcess;
|
||||
QByteArray spoilerData;
|
||||
void startSpoilerDownloadProcess(QString url, bool saveResults);
|
||||
void downloadFromURL(QUrl url, bool saveResults);
|
||||
bool saveDownloadedFile(QByteArray data);
|
||||
|
||||
signals:
|
||||
void spoilersUpdatedSuccessfully();
|
||||
void spoilerCheckerDone();
|
||||
};
|
||||
|
||||
#endif // COCKATRICE_SPOILER_DOWNLOADER_H
|
||||
@@ -0,0 +1,35 @@
|
||||
#include "client_update_checker.h"
|
||||
|
||||
#include "../../../settings/cache_settings.h"
|
||||
#include "release_channel.h"
|
||||
|
||||
ClientUpdateChecker::ClientUpdateChecker(QObject *parent) : QObject(parent)
|
||||
{
|
||||
}
|
||||
|
||||
void ClientUpdateChecker::check()
|
||||
{
|
||||
auto releaseChannel = SettingsCache::instance().getUpdateReleaseChannel();
|
||||
|
||||
finishedCheckConnection =
|
||||
connect(releaseChannel, &ReleaseChannel::finishedCheck, this, &ClientUpdateChecker::actFinishedCheck);
|
||||
errorConnection = connect(releaseChannel, &ReleaseChannel::error, this, &ClientUpdateChecker::actError);
|
||||
|
||||
releaseChannel->checkForUpdates();
|
||||
}
|
||||
|
||||
void ClientUpdateChecker::actFinishedCheck(bool needToUpdate, bool isCompatible, Release *release)
|
||||
{
|
||||
disconnect(finishedCheckConnection);
|
||||
disconnect(errorConnection);
|
||||
|
||||
emit finishedCheck(needToUpdate, isCompatible, release);
|
||||
}
|
||||
|
||||
void ClientUpdateChecker::actError(const QString &errorString)
|
||||
{
|
||||
disconnect(finishedCheckConnection);
|
||||
disconnect(errorConnection);
|
||||
|
||||
emit error(errorString);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* @file client_update_checker.h
|
||||
* @ingroup ClientUpdate
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef CLIENT_UPDATE_CHECKER_H
|
||||
#define CLIENT_UPDATE_CHECKER_H
|
||||
#include <QObject>
|
||||
|
||||
class Release;
|
||||
|
||||
/**
|
||||
* We use a singleton instance of UpdateChannel, which can cause interference and feedback loops when multiple objects
|
||||
* connect to it.
|
||||
*
|
||||
* This class encapsulates the usage of that UpdateChannel to ensure that the check only happens once per connection and
|
||||
* the connection is destroyed after it's been used.
|
||||
*/
|
||||
class ClientUpdateChecker : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
QMetaObject::Connection finishedCheckConnection;
|
||||
QMetaObject::Connection errorConnection;
|
||||
|
||||
void actFinishedCheck(bool needToUpdate, bool isCompatible, Release *release);
|
||||
void actError(const QString &errorString);
|
||||
|
||||
public:
|
||||
explicit ClientUpdateChecker(QObject *parent = nullptr);
|
||||
/**
|
||||
* Actually performs the check, using the currently selected update channel in the settings.
|
||||
* Any resulting signals will only be sent once.
|
||||
* This method should only be called ONCE per instance.
|
||||
*/
|
||||
void check();
|
||||
|
||||
signals:
|
||||
/**
|
||||
* Forwarded from UpdateChannel::finishedCheck
|
||||
*/
|
||||
void finishedCheck(bool needToUpdate, bool isCompatible, Release *release);
|
||||
|
||||
/**
|
||||
* Forwarded from UpdateChannel::error
|
||||
*/
|
||||
void error(const QString &errorString);
|
||||
};
|
||||
|
||||
#endif // CLIENT_UPDATE_CHECKER_H
|
||||
@@ -0,0 +1,310 @@
|
||||
#include "release_channel.h"
|
||||
|
||||
#include "version_string.h"
|
||||
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QMessageBox>
|
||||
#include <QNetworkReply>
|
||||
#include <QRegularExpression>
|
||||
#include <QSysInfo>
|
||||
#include <QtGlobal>
|
||||
|
||||
#if defined(Q_OS_MACOS)
|
||||
#include <sys/sysctl.h>
|
||||
#include <sys/types.h>
|
||||
#endif
|
||||
|
||||
#define STABLERELEASE_URL "https://api.github.com/repos/Cockatrice/Cockatrice/releases/latest"
|
||||
#define STABLEMANUALDOWNLOAD_URL "https://github.com/Cockatrice/Cockatrice/releases/latest"
|
||||
#define STABLETAG_URL "https://api.github.com/repos/Cockatrice/Cockatrice/git/refs/tags/"
|
||||
|
||||
#define BETARELEASE_URL "https://api.github.com/repos/Cockatrice/Cockatrice/releases"
|
||||
#define BETAMANUALDOWNLOAD_URL "https://github.com/Cockatrice/Cockatrice/releases/"
|
||||
#define BETARELEASE_CHANGESURL "https://github.com/Cockatrice/Cockatrice/compare/%1...%2"
|
||||
|
||||
#define GIT_SHORT_HASH_LEN 7
|
||||
|
||||
ReleaseChannel::ReleaseChannel() : netMan(new QNetworkAccessManager(this)), response(nullptr), lastRelease(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
ReleaseChannel::~ReleaseChannel()
|
||||
{
|
||||
netMan->deleteLater();
|
||||
}
|
||||
|
||||
void ReleaseChannel::checkForUpdates()
|
||||
{
|
||||
QString releaseChannelUrl = getReleaseChannelUrl();
|
||||
qCInfo(ReleaseChannelLog) << "Searching for updates on the channel: " << releaseChannelUrl;
|
||||
response = netMan->get(QNetworkRequest(releaseChannelUrl));
|
||||
connect(response, &QNetworkReply::finished, this, &ReleaseChannel::releaseListFinished);
|
||||
}
|
||||
|
||||
// Different release channel checking functions for different operating systems
|
||||
bool ReleaseChannel::downloadMatchesCurrentOS(const QString &fileName)
|
||||
{
|
||||
#if defined(Q_OS_MACOS)
|
||||
static QRegularExpression version_regex("macOS(\\d+)");
|
||||
auto match = version_regex.match(fileName);
|
||||
if (!match.hasMatch()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto getSystemVersion = [] {
|
||||
// QSysInfo does not go through translation layers
|
||||
// We need to use sysctl to reliably detect the underlying architecture
|
||||
char arch[255];
|
||||
size_t len = sizeof(arch);
|
||||
if (sysctlbyname("machdep.cpu.brand_string", arch, &len, nullptr, 0) == 0) {
|
||||
// Intel mac is only supported on macOS 13 versions
|
||||
if (QString::fromUtf8(arch).contains("Intel")) {
|
||||
return 13;
|
||||
}
|
||||
}
|
||||
|
||||
return QSysInfo::productVersion().split(".")[0].toInt();
|
||||
};
|
||||
|
||||
// older(smaller) releases are compatible with a newer or the same system version
|
||||
int sys_maj = getSystemVersion();
|
||||
int rel_maj = match.captured(1).toInt();
|
||||
return rel_maj == sys_maj;
|
||||
|
||||
#elif defined(Q_OS_WIN)
|
||||
#if Q_PROCESSOR_WORDSIZE == 4
|
||||
return fileName.contains("32bit");
|
||||
#elif Q_PROCESSOR_WORDSIZE == 8
|
||||
const QString &version = QSysInfo::productVersion();
|
||||
if (version.startsWith("7") || version.startsWith("8")) {
|
||||
return fileName.contains("Win7");
|
||||
} else {
|
||||
return fileName.contains("Win10");
|
||||
}
|
||||
#else
|
||||
Q_UNUSED(fileName);
|
||||
return false;
|
||||
#endif
|
||||
|
||||
#else // If the OS doesn't fit one of the above #defines, then it will never match
|
||||
Q_UNUSED(fileName);
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
QString StableReleaseChannel::getManualDownloadUrl() const
|
||||
{
|
||||
return QString(STABLEMANUALDOWNLOAD_URL);
|
||||
}
|
||||
|
||||
QString StableReleaseChannel::getName() const
|
||||
{
|
||||
return tr("Default");
|
||||
}
|
||||
|
||||
QString StableReleaseChannel::getReleaseChannelUrl() const
|
||||
{
|
||||
return QString(STABLERELEASE_URL);
|
||||
}
|
||||
|
||||
void StableReleaseChannel::releaseListFinished()
|
||||
{
|
||||
auto *reply = static_cast<QNetworkReply *>(sender());
|
||||
QJsonParseError parseError{};
|
||||
QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError);
|
||||
reply->deleteLater();
|
||||
if (parseError.error != QJsonParseError::NoError) {
|
||||
qCWarning(ReleaseChannelLog) << "No reply received from the release update server.";
|
||||
emit error(tr("No reply received from the release update server."));
|
||||
return;
|
||||
}
|
||||
|
||||
QVariantMap resultMap = jsonResponse.toVariant().toMap();
|
||||
if (!(resultMap.contains("name") && resultMap.contains("html_url") && resultMap.contains("tag_name") &&
|
||||
resultMap.contains("published_at"))) {
|
||||
qCWarning(ReleaseChannelLog) << "Invalid received from the release update server:" << resultMap;
|
||||
emit error(tr("Invalid reply received from the release update server."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!lastRelease) {
|
||||
lastRelease = new Release;
|
||||
}
|
||||
|
||||
lastRelease->setName(resultMap["name"].toString());
|
||||
lastRelease->setDescriptionUrl(resultMap["html_url"].toString());
|
||||
lastRelease->setPublishDate(resultMap["published_at"].toDate());
|
||||
|
||||
if (resultMap.contains("assets")) {
|
||||
auto rawAssets = resultMap["assets"].toList();
|
||||
for (const auto &rawAsset : rawAssets) {
|
||||
QVariantMap asset = rawAsset.toMap();
|
||||
QString name = asset["name"].toString();
|
||||
QString url = asset["browser_download_url"].toString();
|
||||
|
||||
if (downloadMatchesCurrentOS(name)) {
|
||||
lastRelease->setDownloadUrl(url);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN);
|
||||
QString myHash = QString(VERSION_COMMIT);
|
||||
qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash;
|
||||
|
||||
qCInfo(ReleaseChannelLog) << "Got reply from release server, name=" << lastRelease->getName()
|
||||
<< "desc=" << lastRelease->getDescriptionUrl() << "date=" << lastRelease->getPublishDate()
|
||||
<< "url=" << lastRelease->getDownloadUrl();
|
||||
|
||||
const QString &tagName = resultMap["tag_name"].toString();
|
||||
QString url = QString(STABLETAG_URL) + tagName;
|
||||
qCInfo(ReleaseChannelLog) << "Searching for commit hash corresponding to stable channel tag: " << tagName;
|
||||
response = netMan->get(QNetworkRequest(url));
|
||||
connect(response, &QNetworkReply::finished, this, &StableReleaseChannel::tagListFinished);
|
||||
}
|
||||
|
||||
void StableReleaseChannel::tagListFinished()
|
||||
{
|
||||
auto *reply = static_cast<QNetworkReply *>(sender());
|
||||
QJsonParseError parseError{};
|
||||
QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError);
|
||||
reply->deleteLater();
|
||||
if (parseError.error != QJsonParseError::NoError) {
|
||||
qCWarning(ReleaseChannelLog) << "No reply received from the tag update server.";
|
||||
emit error(tr("No reply received from the tag update server."));
|
||||
return;
|
||||
}
|
||||
|
||||
QVariantMap resultMap = jsonResponse.toVariant().toMap();
|
||||
if (!(resultMap.contains("object") && resultMap["object"].toMap().contains("sha"))) {
|
||||
qCWarning(ReleaseChannelLog) << "Invalid received from the tag update server.";
|
||||
emit error(tr("Invalid reply received from the tag update server."));
|
||||
return;
|
||||
}
|
||||
|
||||
lastRelease->setCommitHash(resultMap["object"].toMap()["sha"].toString());
|
||||
qCInfo(ReleaseChannelLog) << "Got reply from tag server, commit=" << lastRelease->getCommitHash();
|
||||
|
||||
QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN);
|
||||
QString myHash = QString(VERSION_COMMIT);
|
||||
qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash;
|
||||
const bool needToUpdate = (QString::compare(shortHash, myHash, Qt::CaseInsensitive) != 0);
|
||||
|
||||
emit finishedCheck(needToUpdate, lastRelease->isCompatibleVersionFound(), lastRelease);
|
||||
}
|
||||
|
||||
void StableReleaseChannel::fileListFinished()
|
||||
{
|
||||
// Only implemented to satisfy interface
|
||||
}
|
||||
|
||||
QString BetaReleaseChannel::getManualDownloadUrl() const
|
||||
{
|
||||
return QString(BETAMANUALDOWNLOAD_URL);
|
||||
}
|
||||
|
||||
QString BetaReleaseChannel::getName() const
|
||||
{
|
||||
return tr("Beta");
|
||||
}
|
||||
|
||||
QString BetaReleaseChannel::getReleaseChannelUrl() const
|
||||
{
|
||||
return QString(BETARELEASE_URL);
|
||||
}
|
||||
|
||||
void BetaReleaseChannel::releaseListFinished()
|
||||
{
|
||||
auto *reply = static_cast<QNetworkReply *>(sender());
|
||||
QByteArray jsonData = reply->readAll();
|
||||
reply->deleteLater();
|
||||
|
||||
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
|
||||
QJsonArray array = doc.array();
|
||||
|
||||
/*
|
||||
* Get the latest release on GitHub
|
||||
* This can be either a pre-release or a published release
|
||||
* depending on timing. Both are acceptable.
|
||||
*/
|
||||
QVariantMap resultMap = array.at(0).toObject().toVariantMap();
|
||||
|
||||
if (array.empty() || resultMap.empty()) {
|
||||
qCWarning(ReleaseChannelLog) << "No reply received from the release update server:" << QString(jsonData);
|
||||
emit error(tr("No reply received from the release update server."));
|
||||
return;
|
||||
}
|
||||
|
||||
// Make sure resultMap has all elements we'll need
|
||||
if (!resultMap.contains("assets") || !resultMap.contains("author") || !resultMap.contains("tag_name") ||
|
||||
!resultMap.contains("target_commitish") || !resultMap.contains("assets_url") ||
|
||||
!resultMap.contains("published_at")) {
|
||||
qCWarning(ReleaseChannelLog) << "Invalid received from the release update server:" << resultMap;
|
||||
emit error(tr("Invalid reply received from the release update server."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (lastRelease == nullptr) {
|
||||
lastRelease = new Release;
|
||||
}
|
||||
|
||||
lastRelease->setCommitHash(resultMap["target_commitish"].toString());
|
||||
lastRelease->setPublishDate(resultMap["published_at"].toDate());
|
||||
|
||||
QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN);
|
||||
lastRelease->setName(QString("%1 (%2)").arg(resultMap["tag_name"].toString()).arg(shortHash));
|
||||
lastRelease->setDescriptionUrl(QString(BETARELEASE_CHANGESURL).arg(VERSION_COMMIT, shortHash));
|
||||
|
||||
qCInfo(ReleaseChannelLog) << "Got reply from release server, size=" << resultMap.size()
|
||||
<< "name=" << lastRelease->getName() << "desc=" << lastRelease->getDescriptionUrl()
|
||||
<< "commit=" << lastRelease->getCommitHash() << "date=" << lastRelease->getPublishDate();
|
||||
|
||||
QString betaBuildDownloadUrl = resultMap["assets_url"].toString();
|
||||
|
||||
qCInfo(ReleaseChannelLog) << "Searching for a corresponding file on the beta channel: " << betaBuildDownloadUrl;
|
||||
response = netMan->get(QNetworkRequest(betaBuildDownloadUrl));
|
||||
connect(response, &QNetworkReply::finished, this, &BetaReleaseChannel::fileListFinished);
|
||||
}
|
||||
|
||||
void BetaReleaseChannel::fileListFinished()
|
||||
{
|
||||
auto *reply = static_cast<QNetworkReply *>(sender());
|
||||
QJsonParseError parseError{};
|
||||
QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError);
|
||||
reply->deleteLater();
|
||||
if (parseError.error != QJsonParseError::NoError) {
|
||||
qCWarning(ReleaseChannelLog) << "No reply received from the file update server.";
|
||||
emit error(tr("No reply received from the file update server."));
|
||||
return;
|
||||
}
|
||||
|
||||
QVariantList resultList = jsonResponse.toVariant().toList();
|
||||
QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN);
|
||||
QString myHash = QString(VERSION_COMMIT);
|
||||
qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash;
|
||||
|
||||
bool needToUpdate = (QString::compare(shortHash, myHash, Qt::CaseInsensitive) != 0);
|
||||
bool compatibleVersion = false;
|
||||
|
||||
QStringList resultUrlList{};
|
||||
for (QVariant file : resultList) {
|
||||
QVariantMap map = file.toMap();
|
||||
resultUrlList << map["browser_download_url"].toString();
|
||||
}
|
||||
|
||||
resultUrlList.sort();
|
||||
// iterate in reverse so the first item is the latest os version
|
||||
for (auto url = resultUrlList.rbegin(); url < resultUrlList.rend(); ++url) {
|
||||
if (downloadMatchesCurrentOS(*url)) {
|
||||
compatibleVersion = true;
|
||||
lastRelease->setDownloadUrl(*url);
|
||||
qCInfo(ReleaseChannelLog) << "Found compatible version url=" << *url;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
emit finishedCheck(needToUpdate, compatibleVersion, lastRelease);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* @file release_channel.h
|
||||
* @ingroup ClientUpdate
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef RELEASECHANNEL_H
|
||||
#define RELEASECHANNEL_H
|
||||
|
||||
#include <QDate>
|
||||
#include <QLoggingCategory>
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
#include <QVariantMap>
|
||||
#include <utility>
|
||||
|
||||
inline Q_LOGGING_CATEGORY(ReleaseChannelLog, "release_channel");
|
||||
|
||||
class QNetworkReply;
|
||||
class QNetworkAccessManager;
|
||||
|
||||
class Release
|
||||
{
|
||||
friend class StableReleaseChannel;
|
||||
friend class BetaReleaseChannel;
|
||||
|
||||
public:
|
||||
Release() = default;
|
||||
~Release() = default;
|
||||
|
||||
private:
|
||||
QString name, descriptionUrl, downloadUrl, commitHash;
|
||||
QDate publishDate;
|
||||
bool compatibleVersionFound = false;
|
||||
|
||||
protected:
|
||||
void setName(QString _name)
|
||||
{
|
||||
name = std::move(_name);
|
||||
}
|
||||
void setDescriptionUrl(QString _descriptionUrl)
|
||||
{
|
||||
descriptionUrl = std::move(_descriptionUrl);
|
||||
}
|
||||
void setDownloadUrl(QString _downloadUrl)
|
||||
{
|
||||
downloadUrl = std::move(_downloadUrl);
|
||||
compatibleVersionFound = true;
|
||||
}
|
||||
void setCommitHash(QString _commitHash)
|
||||
{
|
||||
commitHash = std::move(_commitHash);
|
||||
}
|
||||
void setPublishDate(QDate _publishDate)
|
||||
{
|
||||
publishDate = _publishDate;
|
||||
}
|
||||
|
||||
public:
|
||||
[[nodiscard]] QString getName() const
|
||||
{
|
||||
return name;
|
||||
}
|
||||
[[nodiscard]] QString getDescriptionUrl() const
|
||||
{
|
||||
return descriptionUrl;
|
||||
}
|
||||
[[nodiscard]] QString getDownloadUrl() const
|
||||
{
|
||||
return downloadUrl;
|
||||
}
|
||||
[[nodiscard]] QString getCommitHash() const
|
||||
{
|
||||
return commitHash;
|
||||
}
|
||||
[[nodiscard]] QDate getPublishDate() const
|
||||
{
|
||||
return publishDate;
|
||||
}
|
||||
[[nodiscard]] bool isCompatibleVersionFound() const
|
||||
{
|
||||
return compatibleVersionFound;
|
||||
}
|
||||
};
|
||||
|
||||
class ReleaseChannel : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit ReleaseChannel();
|
||||
~ReleaseChannel() override;
|
||||
|
||||
protected:
|
||||
QNetworkAccessManager *netMan;
|
||||
QNetworkReply *response;
|
||||
Release *lastRelease;
|
||||
|
||||
protected:
|
||||
static bool downloadMatchesCurrentOS(const QString &fileName);
|
||||
[[nodiscard]] virtual QString getReleaseChannelUrl() const = 0;
|
||||
|
||||
public:
|
||||
Release *getLastRelease()
|
||||
{
|
||||
return lastRelease;
|
||||
}
|
||||
[[nodiscard]] virtual QString getManualDownloadUrl() const = 0;
|
||||
[[nodiscard]] virtual QString getName() const = 0;
|
||||
void checkForUpdates();
|
||||
signals:
|
||||
void finishedCheck(bool needToUpdate, bool isCompatible, Release *release);
|
||||
void error(QString errorString);
|
||||
protected slots:
|
||||
virtual void releaseListFinished() = 0;
|
||||
virtual void fileListFinished() = 0;
|
||||
};
|
||||
|
||||
class StableReleaseChannel : public ReleaseChannel
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit StableReleaseChannel() = default;
|
||||
~StableReleaseChannel() override = default;
|
||||
|
||||
[[nodiscard]] QString getManualDownloadUrl() const override;
|
||||
|
||||
[[nodiscard]] QString getName() const override;
|
||||
|
||||
protected:
|
||||
[[nodiscard]] QString getReleaseChannelUrl() const override;
|
||||
protected slots:
|
||||
|
||||
void releaseListFinished() override;
|
||||
void tagListFinished();
|
||||
|
||||
void fileListFinished() override;
|
||||
};
|
||||
|
||||
class BetaReleaseChannel : public ReleaseChannel
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
BetaReleaseChannel() = default;
|
||||
~BetaReleaseChannel() override = default;
|
||||
|
||||
[[nodiscard]] QString getManualDownloadUrl() const override;
|
||||
|
||||
[[nodiscard]] QString getName() const override;
|
||||
|
||||
protected:
|
||||
[[nodiscard]] QString getReleaseChannelUrl() const override;
|
||||
protected slots:
|
||||
|
||||
void releaseListFinished() override;
|
||||
|
||||
void fileListFinished() override;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,67 @@
|
||||
#include "update_downloader.h"
|
||||
|
||||
#include <QUrl>
|
||||
|
||||
UpdateDownloader::UpdateDownloader(QObject *parent) : QObject(parent), response(nullptr)
|
||||
{
|
||||
netMan = new QNetworkAccessManager(this);
|
||||
}
|
||||
|
||||
void UpdateDownloader::beginDownload(QUrl downloadUrl)
|
||||
{
|
||||
// Save the original URL because we need it for the filename
|
||||
if (originalUrl.isEmpty()) {
|
||||
originalUrl = downloadUrl;
|
||||
}
|
||||
|
||||
response = netMan->get(QNetworkRequest(downloadUrl));
|
||||
connect(response, &QNetworkReply::finished, this, &UpdateDownloader::fileFinished);
|
||||
connect(response, &QNetworkReply::downloadProgress, this, &UpdateDownloader::downloadProgress);
|
||||
connect(this, &UpdateDownloader::stopDownload, response, &QNetworkReply::abort);
|
||||
}
|
||||
|
||||
void UpdateDownloader::downloadError(QNetworkReply::NetworkError)
|
||||
{
|
||||
if (response == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
emit error(response->errorString().toUtf8());
|
||||
}
|
||||
|
||||
void UpdateDownloader::fileFinished()
|
||||
{
|
||||
// If we finished but there's a redirect, follow it
|
||||
QVariant redirect = response->attribute(QNetworkRequest::RedirectionTargetAttribute);
|
||||
if (!redirect.isNull()) {
|
||||
beginDownload(redirect.toUrl());
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle any errors we had
|
||||
if (response->error()) {
|
||||
emit error(response->errorString());
|
||||
return;
|
||||
}
|
||||
|
||||
// Work out the file name of the download
|
||||
QString fileName = QDir::temp().path() + QDir::separator() + originalUrl.toString().section('/', -1);
|
||||
|
||||
// Save the build in a temporary directory
|
||||
QFile file(fileName);
|
||||
if (!file.open(QIODevice::WriteOnly)) {
|
||||
emit error(tr("Could not open the file for reading."));
|
||||
return;
|
||||
}
|
||||
|
||||
file.write(response->readAll());
|
||||
file.close();
|
||||
|
||||
// Emit the success signal with a URL to the download file
|
||||
emit downloadSuccessful(QUrl::fromLocalFile(fileName));
|
||||
}
|
||||
|
||||
void UpdateDownloader::downloadProgress(qint64 bytesRead, qint64 totalBytes)
|
||||
{
|
||||
emit progressMade(bytesRead, totalBytes);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* @file update_downloader.h
|
||||
* @ingroup ClientUpdate
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef COCKATRICE_UPDATEDOWNLOADER_H
|
||||
#define COCKATRICE_UPDATEDOWNLOADER_H
|
||||
|
||||
#include <QObject>
|
||||
#include <QtNetwork>
|
||||
|
||||
class UpdateDownloader : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit UpdateDownloader(QObject *parent);
|
||||
void beginDownload(QUrl url);
|
||||
signals:
|
||||
void downloadSuccessful(QUrl filepath);
|
||||
void progressMade(qint64 bytesRead, qint64 totalBytes);
|
||||
void error(QString errorString);
|
||||
void stopDownload();
|
||||
|
||||
private:
|
||||
QUrl originalUrl;
|
||||
QNetworkAccessManager *netMan;
|
||||
QNetworkReply *response;
|
||||
private slots:
|
||||
void fileFinished();
|
||||
void downloadProgress(qint64 bytesRead, qint64 totalBytes);
|
||||
void downloadError(QNetworkReply::NetworkError);
|
||||
};
|
||||
|
||||
#endif // COCKATRICE_UPDATEDOWNLOADER_H
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,59 @@
|
||||
#include "card_counter_settings.h"
|
||||
|
||||
#include <QColor>
|
||||
#include <QSettings>
|
||||
#include <QtMath>
|
||||
|
||||
CardCounterSettings::CardCounterSettings(const QString &settingsPath, QObject *parent)
|
||||
: SettingsManager(settingsPath + "global.ini", "cards", "counters", parent)
|
||||
{
|
||||
}
|
||||
|
||||
void CardCounterSettings::setColor(int counterId, const QColor &color)
|
||||
{
|
||||
QSettings settings = getSettings();
|
||||
|
||||
QString key = QString("cards/counters/%1/color").arg(counterId);
|
||||
|
||||
if (settings.value(key).value<QColor>() == color) {
|
||||
return;
|
||||
}
|
||||
|
||||
settings.setValue(key, color);
|
||||
emit colorChanged(counterId, color);
|
||||
}
|
||||
|
||||
QColor CardCounterSettings::color(int counterId) const
|
||||
{
|
||||
QColor defaultColor;
|
||||
|
||||
if (counterId < 6) {
|
||||
// Preserve legacy colors
|
||||
defaultColor = QColor::fromHsv(counterId * 60, 150, 255);
|
||||
} else {
|
||||
// Future-proof support for more counters with pseudo-random colors
|
||||
int h = (counterId * 37) % 360;
|
||||
int s = 128 + 64 * qSin((counterId * 97) * 0.1); // 64-192
|
||||
int v = 196 + 32 * qSin((counterId * 101) * 0.07); // 164-228
|
||||
|
||||
defaultColor = QColor::fromHsv(h, s, v);
|
||||
}
|
||||
|
||||
return getSettings().value(QString("cards/counters/%1/color").arg(counterId), defaultColor).value<QColor>();
|
||||
}
|
||||
|
||||
QString CardCounterSettings::displayName(int counterId) const
|
||||
{
|
||||
// Currently, card counters name are fixed to A, B, ..., Z, AA, AB, ...
|
||||
|
||||
auto nChars = 1 + counterId / 26;
|
||||
QString str;
|
||||
str.resize(nChars);
|
||||
|
||||
for (auto it = str.rbegin(); it != str.rend(); ++it) {
|
||||
*it = QChar('A' + (counterId) % 26);
|
||||
counterId /= 26;
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* @file card_counter_settings.h
|
||||
* @ingroup GameSettings
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef CARD_COUNTER_SETTINGS_H
|
||||
#define CARD_COUNTER_SETTINGS_H
|
||||
|
||||
#include <libcockatrice/settings/settings_manager.h>
|
||||
|
||||
class QSettings;
|
||||
class QColor;
|
||||
|
||||
class CardCounterSettings : public SettingsManager
|
||||
{
|
||||
Q_OBJECT
|
||||
|
||||
public:
|
||||
CardCounterSettings(const QString &settingsPath, QObject *parent = nullptr);
|
||||
|
||||
[[nodiscard]] QColor color(int counterId) const;
|
||||
|
||||
[[nodiscard]] QString displayName(int counterId) const;
|
||||
|
||||
public slots:
|
||||
void setColor(int counterId, const QColor &color);
|
||||
|
||||
signals:
|
||||
void colorChanged(int counterId, const QColor &color);
|
||||
};
|
||||
|
||||
#endif // CARD_COUNTER_SETTINGS_H
|
||||
@@ -0,0 +1,162 @@
|
||||
#include "shortcut_treeview.h"
|
||||
|
||||
#include "cache_settings.h"
|
||||
#include "shortcuts_settings.h"
|
||||
|
||||
#include <QHeaderView>
|
||||
|
||||
ShortcutFilterProxyModel::ShortcutFilterProxyModel(QObject *parent) : QSortFilterProxyModel(parent)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends the parent and source row together before doing the regex match.
|
||||
*/
|
||||
bool ShortcutFilterProxyModel::filterAcceptsRow(const int sourceRow, const QModelIndex &sourceParent) const
|
||||
{
|
||||
QModelIndex nameIndex = sourceModel()->index(sourceRow, filterKeyColumn(), sourceParent);
|
||||
QModelIndex parentIndex = sourceModel()->index(sourceParent.row(), filterKeyColumn(), sourceParent.parent());
|
||||
|
||||
QString name = sourceModel()->data(nameIndex).toString();
|
||||
QString parentName = sourceModel()->data(parentIndex).toString();
|
||||
|
||||
QString searchedString = parentName + " " + name;
|
||||
|
||||
return searchedString.contains(filterRegularExpression());
|
||||
}
|
||||
|
||||
ShortcutTreeView::ShortcutTreeView(QWidget *parent) : QTreeView(parent)
|
||||
{
|
||||
// model
|
||||
shortcutsModel = new QStandardItemModel(this);
|
||||
shortcutsModel->setColumnCount(3);
|
||||
populateShortcutsModel();
|
||||
|
||||
// filter proxy
|
||||
proxyModel = new ShortcutFilterProxyModel(this);
|
||||
proxyModel->setRecursiveFilteringEnabled(true);
|
||||
proxyModel->setSourceModel(shortcutsModel);
|
||||
proxyModel->setDynamicSortFilter(true);
|
||||
proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive);
|
||||
proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive);
|
||||
proxyModel->setFilterKeyColumn(0);
|
||||
|
||||
QTreeView::setModel(proxyModel);
|
||||
|
||||
// treeview
|
||||
hideColumn(2);
|
||||
|
||||
setUniformRowHeights(true);
|
||||
setAlternatingRowColors(true);
|
||||
|
||||
setSortingEnabled(true);
|
||||
proxyModel->sort(0, Qt::AscendingOrder);
|
||||
|
||||
header()->setSectionResizeMode(QHeaderView::Interactive);
|
||||
header()->setSortIndicator(0, Qt::AscendingOrder);
|
||||
setSelectionMode(SingleSelection);
|
||||
setSelectionBehavior(SelectRows);
|
||||
|
||||
expandAll();
|
||||
|
||||
connect(&SettingsCache::instance().shortcuts(), &ShortcutsSettings::shortCutChanged, this,
|
||||
&ShortcutTreeView::refreshShortcuts);
|
||||
}
|
||||
|
||||
void ShortcutTreeView::populateShortcutsModel()
|
||||
{
|
||||
QHash<QString, QStandardItem *> parentItems;
|
||||
QStandardItem *curParent = nullptr;
|
||||
for (const auto &key : SettingsCache::instance().shortcuts().getAllShortcutKeys()) {
|
||||
QString name = SettingsCache::instance().shortcuts().getShortcut(key).getName();
|
||||
QString group = SettingsCache::instance().shortcuts().getShortcut(key).getGroupName();
|
||||
QString shortcut = SettingsCache::instance().shortcuts().getShortcutString(key);
|
||||
|
||||
if (parentItems.contains(group)) {
|
||||
curParent = parentItems.value(group);
|
||||
} else {
|
||||
curParent = new QStandardItem(group);
|
||||
static QFont font = curParent->font();
|
||||
font.setBold(true);
|
||||
curParent->setFont(font);
|
||||
parentItems.insert(group, curParent);
|
||||
}
|
||||
|
||||
QList<QStandardItem *> list = {};
|
||||
list << new QStandardItem(name) << new QStandardItem(shortcut) << new QStandardItem(key);
|
||||
curParent->appendRow(list);
|
||||
}
|
||||
|
||||
for (const auto &parent : parentItems) {
|
||||
shortcutsModel->appendRow(parent);
|
||||
}
|
||||
}
|
||||
|
||||
void ShortcutTreeView::retranslateUi()
|
||||
{
|
||||
shortcutsModel->setHeaderData(0, Qt::Horizontal, tr("Action"));
|
||||
shortcutsModel->setHeaderData(1, Qt::Horizontal, tr("Shortcut"));
|
||||
refreshShortcuts();
|
||||
}
|
||||
|
||||
/**
|
||||
* Loops over the model and reloads all rows
|
||||
*/
|
||||
static void loopOverModel(QAbstractItemModel *model, const QModelIndex &parent = QModelIndex())
|
||||
{
|
||||
for (int r = 0; r < model->rowCount(parent); ++r) {
|
||||
const auto friendlyNameIndex = model->index(r, 0, parent);
|
||||
|
||||
if (model->hasChildren(friendlyNameIndex)) {
|
||||
const auto childIndex = model->index(0, 2, friendlyNameIndex);
|
||||
const auto key = model->data(childIndex).toString();
|
||||
const auto shortcutGroupName = SettingsCache::instance().shortcuts().getShortcut(key).getGroupName();
|
||||
model->setData(friendlyNameIndex, shortcutGroupName);
|
||||
|
||||
loopOverModel(model, friendlyNameIndex);
|
||||
} else {
|
||||
const auto shortcutSequenceIndex = model->index(r, 1, parent);
|
||||
const auto keyIndex = model->index(r, 2, parent);
|
||||
const auto key = model->data(keyIndex).toString();
|
||||
|
||||
const auto shortcutKey = SettingsCache::instance().shortcuts().getShortcut(key).getName();
|
||||
const auto shortcutSequence = SettingsCache::instance().shortcuts().getShortcutString(key);
|
||||
model->setData(friendlyNameIndex, shortcutKey);
|
||||
model->setData(shortcutSequenceIndex, shortcutSequence);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ShortcutTreeView::refreshShortcuts()
|
||||
{
|
||||
loopOverModel(shortcutsModel);
|
||||
}
|
||||
|
||||
void ShortcutTreeView::currentChanged(const QModelIndex ¤t, const QModelIndex & /* previous */)
|
||||
{
|
||||
QTreeView::scrollTo(current, QAbstractItemView::EnsureVisible);
|
||||
if (current.parent().isValid()) {
|
||||
auto shortcutName = model()->data(model()->index(current.row(), 2, current.parent())).toString();
|
||||
emit currentItemChanged(shortcutName);
|
||||
} else {
|
||||
// emit empty string if the selection is a category header
|
||||
emit currentItemChanged("");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The search string is split by word.
|
||||
* A String is a match as long as it contains all the words in the search string in order
|
||||
*/
|
||||
void ShortcutTreeView::updateSearchString(const QString &searchString)
|
||||
{
|
||||
QStringList searchWords = searchString.split(" ", Qt::SkipEmptyParts);
|
||||
|
||||
auto escapeRegex = [](const QString &s) { return QRegularExpression::escape(s); };
|
||||
std::transform(searchWords.begin(), searchWords.end(), searchWords.begin(), escapeRegex);
|
||||
|
||||
auto regex = QRegularExpression(searchWords.join(".*"), QRegularExpression::CaseInsensitiveOption);
|
||||
|
||||
proxyModel->setFilterRegularExpression(regex);
|
||||
expandAll();
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* @file shortcut_treeview.h
|
||||
* @ingroup CoreSettings
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef SHORTCUT_TREEVIEW_H
|
||||
#define SHORTCUT_TREEVIEW_H
|
||||
|
||||
#include <QSortFilterProxyModel>
|
||||
#include <QStandardItemModel>
|
||||
#include <QTreeView>
|
||||
|
||||
/**
|
||||
* Custom implementation of QSortFilterProxyModel that appends the source and parent strings together when filtering
|
||||
*/
|
||||
class ShortcutFilterProxyModel : public QSortFilterProxyModel
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit ShortcutFilterProxyModel(QObject *parent = nullptr);
|
||||
|
||||
protected:
|
||||
[[nodiscard]] bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const override;
|
||||
};
|
||||
|
||||
class ShortcutTreeView : public QTreeView
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit ShortcutTreeView(QWidget *parent);
|
||||
void retranslateUi();
|
||||
|
||||
signals:
|
||||
void currentItemChanged(const QString &shortcut);
|
||||
|
||||
public slots:
|
||||
void updateSearchString(const QString &searchString);
|
||||
|
||||
private:
|
||||
QStandardItemModel *shortcutsModel;
|
||||
ShortcutFilterProxyModel *proxyModel;
|
||||
void populateShortcutsModel();
|
||||
|
||||
private slots:
|
||||
void refreshShortcuts();
|
||||
|
||||
protected:
|
||||
void currentChanged(const QModelIndex ¤t, const QModelIndex &previous) override;
|
||||
};
|
||||
|
||||
#endif // SHORTCUT_TREEVIEW_H
|
||||
@@ -0,0 +1,266 @@
|
||||
#include "shortcuts_settings.h"
|
||||
|
||||
#include <QDebug>
|
||||
#include <QFile>
|
||||
#include <QMessageBox>
|
||||
#include <QStringList>
|
||||
#include <utility>
|
||||
|
||||
ShortcutKey::ShortcutKey(const QString &_name, QList<QKeySequence> _sequence, ShortcutGroup::Groups _group)
|
||||
: QList<QKeySequence>(_sequence), name(_name), group(_group)
|
||||
{
|
||||
}
|
||||
|
||||
ShortcutsSettings::ShortcutsSettings(const QString &settingsPath, QObject *parent) : QObject(parent)
|
||||
{
|
||||
shortCuts = defaultShortCuts;
|
||||
settingsFilePath = settingsPath;
|
||||
settingsFilePath.append("shortcuts.ini");
|
||||
|
||||
bool exists = QFile(settingsFilePath).exists();
|
||||
|
||||
QSettings shortCutsFile(settingsFilePath, QSettings::IniFormat);
|
||||
|
||||
if (exists) {
|
||||
shortCutsFile.beginGroup(custom);
|
||||
const QStringList customKeys = shortCutsFile.allKeys();
|
||||
|
||||
QMap<QString, QString> invalidItems;
|
||||
for (QStringList::const_iterator it = customKeys.constBegin(); it != customKeys.constEnd(); ++it) {
|
||||
QString stringSequence = shortCutsFile.value(*it).toString();
|
||||
|
||||
// check whether shortcut name exists
|
||||
if (!shortCuts.contains(*it)) {
|
||||
qCWarning(ShortcutsSettingsLog) << "Unknown shortcut name:" << *it;
|
||||
continue;
|
||||
}
|
||||
|
||||
// check whether shortcut is forbidden
|
||||
if (isKeyAllowed(*it, stringSequence)) {
|
||||
auto shortcut = getShortcut(*it);
|
||||
shortcut.setSequence(parseSequenceString(stringSequence));
|
||||
shortCuts.insert(*it, shortcut);
|
||||
} else {
|
||||
invalidItems.insert(*it, stringSequence);
|
||||
}
|
||||
}
|
||||
|
||||
shortCutsFile.endGroup();
|
||||
|
||||
if (!invalidItems.isEmpty()) {
|
||||
// warning message in case of invalid items
|
||||
QMessageBox msgBox;
|
||||
msgBox.setIcon(QMessageBox::Warning);
|
||||
msgBox.setText(tr("Your configuration file contained invalid shortcuts.\n"
|
||||
"Please check your shortcut settings!"));
|
||||
QString detailedMessage = tr("The following shortcuts have been set to default:\n");
|
||||
for (QMap<QString, QString>::const_iterator item = invalidItems.constBegin();
|
||||
item != invalidItems.constEnd(); ++item) {
|
||||
detailedMessage += item.key() + " - \"" + item.value() + "\"\n";
|
||||
}
|
||||
msgBox.setDetailedText(detailedMessage);
|
||||
msgBox.exec();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Migrates legacy shortcut key names to current naming scheme.
|
||||
*
|
||||
* PR 5079 changed Textbox/unfocusTextBox to Player/unfocusTextBox and
|
||||
* tab_game/aFocusChat to Player/aFocusChat. This migration allows players
|
||||
* to keep their already configured shortcuts.
|
||||
*/
|
||||
void ShortcutsSettings::migrateShortcuts()
|
||||
{
|
||||
if (QFile(settingsFilePath).exists()) {
|
||||
QSettings shortCutsFile(settingsFilePath, QSettings::IniFormat);
|
||||
|
||||
shortCutsFile.beginGroup(custom);
|
||||
|
||||
if (shortCutsFile.contains("Textbox/unfocusTextBox")) {
|
||||
qCInfo(ShortcutsSettingsLog)
|
||||
<< "[ShortcutsSettings] Textbox/unfocusTextBox shortcut found. Migrating to Player/unfocusTextBox.";
|
||||
QString unfocusTextBox = shortCutsFile.value("Textbox/unfocusTextBox", "").toString();
|
||||
this->setShortcuts("Player/unfocusTextBox", unfocusTextBox);
|
||||
shortCutsFile.remove("Textbox/unfocusTextBox");
|
||||
}
|
||||
|
||||
if (shortCutsFile.contains("tab_game/aFocusChat")) {
|
||||
qCInfo(ShortcutsSettingsLog)
|
||||
<< "[ShortcutsSettings] tab_game/aFocusChat shortcut found. Migrating to Player/aFocusChat.";
|
||||
QString aFocusChat = shortCutsFile.value("tab_game/aFocusChat", "").toString();
|
||||
this->setShortcuts("Player/aFocusChat", aFocusChat);
|
||||
shortCutsFile.remove("tab_game/aFocusChat");
|
||||
}
|
||||
|
||||
// PR #5564 changes "MainWindow/aDeckEditor" to "Tabs/aTabDeckEditor"
|
||||
if (shortCutsFile.contains("MainWindow/aDeckEditor")) {
|
||||
qCInfo(ShortcutsSettingsLog) << "MainWindow/aDeckEditor shortcut found. Migrating to Tabs/aTabDeckEditor.";
|
||||
QString keySequence = shortCutsFile.value("MainWindow/aDeckEditor", "").toString();
|
||||
this->setShortcuts("Tabs/aTabDeckEditor", keySequence);
|
||||
shortCutsFile.remove("MainWindow/aDeckEditor");
|
||||
}
|
||||
|
||||
shortCutsFile.endGroup();
|
||||
}
|
||||
}
|
||||
|
||||
ShortcutKey ShortcutsSettings::getDefaultShortcut(const QString &name) const
|
||||
{
|
||||
return defaultShortCuts.value(name, ShortcutKey());
|
||||
}
|
||||
|
||||
ShortcutKey ShortcutsSettings::getShortcut(const QString &name) const
|
||||
{
|
||||
if (shortCuts.contains(name)) {
|
||||
return shortCuts.value(name);
|
||||
}
|
||||
|
||||
return getDefaultShortcut(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the first shortcut for the given action.
|
||||
*
|
||||
* NOTE: In most cases you should be using ShortcutsSettings::getShortcut instead,
|
||||
* as that will return all shortcuts if there are multiple shortcuts.
|
||||
* The only reason to use this method is if an object does not accept multiple shortcuts, such as with QButtons.
|
||||
*/
|
||||
QKeySequence ShortcutsSettings::getSingleShortcut(const QString &name) const
|
||||
{
|
||||
return getShortcut(name).at(0);
|
||||
}
|
||||
|
||||
QString ShortcutsSettings::getDefaultShortcutString(const QString &name) const
|
||||
{
|
||||
return stringifySequence(getDefaultShortcut(name));
|
||||
}
|
||||
|
||||
QString ShortcutsSettings::getShortcutString(const QString &name) const
|
||||
{
|
||||
return stringifySequence(getShortcut(name));
|
||||
}
|
||||
|
||||
QString ShortcutsSettings::getShortcutFriendlyName(const QString &shortcutName) const
|
||||
{
|
||||
for (auto it = defaultShortCuts.cbegin(); it != defaultShortCuts.cend(); ++it) {
|
||||
if (shortcutName == it.key()) {
|
||||
return it.value().getName();
|
||||
}
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
QString ShortcutsSettings::stringifySequence(const QList<QKeySequence> &Sequence) const
|
||||
{
|
||||
QStringList stringSequence;
|
||||
for (const auto &i : Sequence) {
|
||||
stringSequence.append(i.toString(QKeySequence::PortableText));
|
||||
}
|
||||
|
||||
return stringSequence.join(sep);
|
||||
}
|
||||
|
||||
QList<QKeySequence> ShortcutsSettings::parseSequenceString(const QString &stringSequence) const
|
||||
{
|
||||
QList<QKeySequence> SequenceList;
|
||||
for (const QString &shortcut : stringSequence.split(sep)) {
|
||||
SequenceList.append(QKeySequence(shortcut, QKeySequence::PortableText));
|
||||
}
|
||||
|
||||
return SequenceList;
|
||||
}
|
||||
|
||||
void ShortcutsSettings::setShortcuts(const QString &name, const QList<QKeySequence> &Sequence)
|
||||
{
|
||||
shortCuts[name].setSequence(Sequence);
|
||||
|
||||
QSettings shortCutsFile(settingsFilePath, QSettings::IniFormat);
|
||||
shortCutsFile.beginGroup(custom);
|
||||
shortCutsFile.setValue(name, stringifySequence(Sequence));
|
||||
shortCutsFile.endGroup();
|
||||
emit shortCutChanged();
|
||||
}
|
||||
|
||||
void ShortcutsSettings::setShortcuts(const QString &name, const QKeySequence &Sequence)
|
||||
{
|
||||
setShortcuts(name, QList<QKeySequence>{Sequence});
|
||||
}
|
||||
|
||||
void ShortcutsSettings::setShortcuts(const QString &name, const QString &sequences)
|
||||
{
|
||||
setShortcuts(name, parseSequenceString(sequences));
|
||||
}
|
||||
|
||||
void ShortcutsSettings::resetAllShortcuts()
|
||||
{
|
||||
shortCuts = defaultShortCuts;
|
||||
QSettings shortCutsFile(settingsFilePath, QSettings::IniFormat);
|
||||
shortCutsFile.beginGroup(custom);
|
||||
shortCutsFile.remove("");
|
||||
shortCutsFile.endGroup();
|
||||
emit shortCutChanged();
|
||||
}
|
||||
|
||||
void ShortcutsSettings::clearAllShortcuts()
|
||||
{
|
||||
QSettings shortCutsFile(settingsFilePath, QSettings::IniFormat);
|
||||
shortCutsFile.beginGroup(custom);
|
||||
for (auto it = shortCuts.begin(); it != shortCuts.end(); ++it) {
|
||||
it.value().setSequence(parseSequenceString(""));
|
||||
shortCutsFile.setValue(it.key(), "");
|
||||
}
|
||||
shortCutsFile.endGroup();
|
||||
emit shortCutChanged();
|
||||
}
|
||||
|
||||
bool ShortcutsSettings::isKeyAllowed(const QString &name, const QString &sequences) const
|
||||
{
|
||||
// if the shortcut is not to be used in deck-editor then it doesn't matter
|
||||
if (name.startsWith("Player") || name.startsWith("Replays")) {
|
||||
return true;
|
||||
}
|
||||
QString checkSequence = sequences.split(sep).last();
|
||||
QStringList forbiddenKeys{"Del", "Backspace", "Down", "Up", "Left", "Right",
|
||||
"Return", "Enter", "Menu", "Ctrl+Alt+-", "Ctrl+Alt+=", "Ctrl+Alt+[",
|
||||
"Ctrl+Alt+]", "Tab", "Space", "Shift+S", "Shift+Left", "Shift+Right"};
|
||||
return !forbiddenKeys.contains(checkSequence);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the shortcut doesn't overlap with an existing shortcut
|
||||
*
|
||||
* @param name The name of the shortcut
|
||||
* @param sequences The shortcut key sequence
|
||||
* @return Whether the shortcut is valid.
|
||||
*/
|
||||
bool ShortcutsSettings::isValid(const QString &name, const QString &sequences) const
|
||||
{
|
||||
return findOverlaps(name, sequences).isEmpty();
|
||||
}
|
||||
|
||||
/** @brief Checks if the shortcut is a shortcut that is active in all windows. */
|
||||
static bool isAlwaysActiveShortcut(const QString &shortcutName)
|
||||
{
|
||||
return shortcutName.startsWith("MainWindow") || shortcutName.startsWith("Tabs");
|
||||
}
|
||||
|
||||
QStringList ShortcutsSettings::findOverlaps(const QString &name, const QString &sequences) const
|
||||
{
|
||||
QString checkSequence = sequences.split(sep).last();
|
||||
QString checkKey = name.left(name.indexOf("/"));
|
||||
|
||||
QStringList overlaps;
|
||||
for (const auto &key : shortCuts.keys()) {
|
||||
if (key.startsWith(checkKey) || isAlwaysActiveShortcut(key) || isAlwaysActiveShortcut(checkKey)) {
|
||||
QString storedSequence = stringifySequence(shortCuts.value(key));
|
||||
if (storedSequence.split(sep).contains(checkSequence)) {
|
||||
overlaps.append(getShortcutFriendlyName(key));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return overlaps;
|
||||
}
|
||||
@@ -0,0 +1,792 @@
|
||||
/**
|
||||
* @file shortcuts_settings.h
|
||||
* @ingroup CoreSettings
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef SHORTCUTSSETTINGS_H
|
||||
#define SHORTCUTSSETTINGS_H
|
||||
|
||||
#include <QApplication>
|
||||
#include <QKeySequence>
|
||||
#include <QLoggingCategory>
|
||||
#include <QSettings>
|
||||
|
||||
inline Q_LOGGING_CATEGORY(ShortcutsSettingsLog, "shortcuts_settings");
|
||||
|
||||
class ShortcutGroup
|
||||
{
|
||||
public:
|
||||
enum Groups
|
||||
{
|
||||
Main_Window,
|
||||
Deck_Editor,
|
||||
Game_Lobby,
|
||||
Card_Counters,
|
||||
Player_Counters,
|
||||
Power_Toughness,
|
||||
Game_Phases,
|
||||
Playing_Area,
|
||||
Move_selected,
|
||||
View,
|
||||
Move_top,
|
||||
Move_bottom,
|
||||
Gameplay,
|
||||
Drawing,
|
||||
Hand,
|
||||
Chat_room,
|
||||
Game_window,
|
||||
Load_deck,
|
||||
Replays,
|
||||
Tabs
|
||||
};
|
||||
|
||||
static QString getGroupName(ShortcutGroup::Groups group)
|
||||
{
|
||||
switch (group) {
|
||||
case Main_Window:
|
||||
return QApplication::translate("shortcutsTab", "Main Window");
|
||||
case Deck_Editor:
|
||||
return QApplication::translate("shortcutsTab", "Deck Editor");
|
||||
case Game_Lobby:
|
||||
return QApplication::translate("shortcutsTab", "Game Lobby");
|
||||
case Card_Counters:
|
||||
return QApplication::translate("shortcutsTab", "Card Counters");
|
||||
case Player_Counters:
|
||||
return QApplication::translate("shortcutsTab", "Player Counters");
|
||||
case Power_Toughness:
|
||||
return QApplication::translate("shortcutsTab", "Power and Toughness");
|
||||
case Game_Phases:
|
||||
return QApplication::translate("shortcutsTab", "Game Phases");
|
||||
case Playing_Area:
|
||||
return QApplication::translate("shortcutsTab", "Playing Area");
|
||||
case Move_selected:
|
||||
return QApplication::translate("shortcutsTab", "Move Selected Card");
|
||||
case View:
|
||||
return QApplication::translate("shortcutsTab", "View");
|
||||
case Move_top:
|
||||
return QApplication::translate("shortcutsTab", "Move Top Card");
|
||||
case Move_bottom:
|
||||
return QApplication::translate("shortcutsTab", "Move Bottom Card");
|
||||
case Gameplay:
|
||||
return QApplication::translate("shortcutsTab", "Gameplay");
|
||||
case Drawing:
|
||||
return QApplication::translate("shortcutsTab", "Drawing");
|
||||
case Hand:
|
||||
return QApplication::translate("shortcutsTab", "Hand");
|
||||
case Chat_room:
|
||||
return QApplication::translate("shortcutsTab", "Chat Room");
|
||||
case Game_window:
|
||||
return QApplication::translate("shortcutsTab", "Game Window");
|
||||
case Load_deck:
|
||||
return QApplication::translate("shortcutsTab", "Load Deck from Clipboard");
|
||||
case Replays:
|
||||
return QApplication::translate("shortcutsTab", "Replays");
|
||||
case Tabs:
|
||||
return QApplication::translate("shortcutsTab", "Tabs");
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
class ShortcutKey : public QList<QKeySequence>
|
||||
{
|
||||
public:
|
||||
explicit ShortcutKey(const QString &_name = QString(),
|
||||
QList _sequence = QList(),
|
||||
ShortcutGroup::Groups _group = ShortcutGroup::Main_Window);
|
||||
void setSequence(const QList &_sequence)
|
||||
{
|
||||
QList::operator=(_sequence);
|
||||
}
|
||||
[[nodiscard]] QString getName() const
|
||||
{
|
||||
return QApplication::translate("shortcutsTab", name.toUtf8().data());
|
||||
}
|
||||
[[nodiscard]] QString getGroupName() const
|
||||
{
|
||||
return ShortcutGroup::getGroupName(group);
|
||||
}
|
||||
|
||||
private:
|
||||
QString name;
|
||||
ShortcutGroup::Groups group;
|
||||
};
|
||||
|
||||
class ShortcutsSettings : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit ShortcutsSettings(const QString &settingsFilePath, QObject *parent = nullptr);
|
||||
|
||||
[[nodiscard]] ShortcutKey getDefaultShortcut(const QString &name) const;
|
||||
[[nodiscard]] ShortcutKey getShortcut(const QString &name) const;
|
||||
[[nodiscard]] QKeySequence getSingleShortcut(const QString &name) const;
|
||||
[[nodiscard]] QString getDefaultShortcutString(const QString &name) const;
|
||||
[[nodiscard]] QString getShortcutString(const QString &name) const;
|
||||
[[nodiscard]] QString getShortcutFriendlyName(const QString &shortcutName) const;
|
||||
[[nodiscard]] QList<QString> getAllShortcutKeys() const
|
||||
{
|
||||
return shortCuts.keys();
|
||||
}
|
||||
|
||||
void setShortcuts(const QString &name, const QList<QKeySequence> &Sequence);
|
||||
void setShortcuts(const QString &name, const QKeySequence &Sequence);
|
||||
void setShortcuts(const QString &name, const QString &sequences);
|
||||
|
||||
[[nodiscard]] bool isKeyAllowed(const QString &name, const QString &sequences) const;
|
||||
[[nodiscard]] bool isValid(const QString &name, const QString &sequences) const;
|
||||
[[nodiscard]] QStringList findOverlaps(const QString &name, const QString &sequences) const;
|
||||
|
||||
void resetAllShortcuts();
|
||||
void clearAllShortcuts();
|
||||
void migrateShortcuts();
|
||||
|
||||
signals:
|
||||
void shortCutChanged();
|
||||
|
||||
private:
|
||||
const QChar sep = ';';
|
||||
const QString custom = "Custom"; // name of custom group in shortCutsFile
|
||||
QString settingsFilePath;
|
||||
QHash<QString, ShortcutKey> shortCuts;
|
||||
|
||||
[[nodiscard]] QString stringifySequence(const QList<QKeySequence> &Sequence) const;
|
||||
[[nodiscard]] QList<QKeySequence> parseSequenceString(const QString &stringSequence) const;
|
||||
|
||||
const QHash<QString, ShortcutKey> defaultShortCuts = {
|
||||
{"MainWindow/aCheckCardUpdates", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Check for Card Updates..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Main_Window)},
|
||||
{"MainWindow/aConnect", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Connect..."),
|
||||
parseSequenceString("Ctrl+L"),
|
||||
ShortcutGroup::Main_Window)},
|
||||
{"MainWindow/aDisconnect", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Disconnect"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Main_Window)},
|
||||
{"MainWindow/aExit",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Exit"), parseSequenceString(""), ShortcutGroup::Main_Window)},
|
||||
{"MainWindow/aFullScreen", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Full screen"),
|
||||
parseSequenceString("Ctrl+F"),
|
||||
ShortcutGroup::Main_Window)},
|
||||
{"MainWindow/aRegister", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Register..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Main_Window)},
|
||||
{"MainWindow/aSettings", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Settings..."),
|
||||
parseSequenceString("Ctrl+Shift+P"),
|
||||
ShortcutGroup::Main_Window)},
|
||||
{"MainWindow/aSinglePlayer", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Start a Local Game..."),
|
||||
parseSequenceString("Ctrl+Shift+L"),
|
||||
ShortcutGroup::Main_Window)},
|
||||
{"MainWindow/aWatchReplay", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Watch Replay..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Main_Window)},
|
||||
{"MainWindow/aStatusBar", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Show Status Bar"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Main_Window)},
|
||||
{"TabDeckEditor/aAnalyzeDeck", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Analyze Deck (deckstats.net)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aAnalyzeDeckTappedout",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Analyze Deck (tappedout.net)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aClearFilterAll", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Clear All Filters"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aClearFilterOne", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Clear Selected Filter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aClose",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Close"), parseSequenceString(""), ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aDecrement", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Card"),
|
||||
parseSequenceString("-"),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aManageSets", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Manage Sets..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aEditTokens", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Edit Custom Tokens..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aExportDeckDecklist",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Export Deck (decklist.org)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aExportDeckDecklistXyz",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Export Deck (decklist.xyz)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aIncrement", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Card"),
|
||||
parseSequenceString("+"),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aLoadDeck", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Load Deck..."),
|
||||
parseSequenceString("Ctrl+O"),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aLoadDeckFromWebsite",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Load deck from online service..."),
|
||||
parseSequenceString("Ctrl+Shift+O"),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aLoadDeckFromClipboard",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Load Deck from Clipboard..."),
|
||||
parseSequenceString("Ctrl+Shift+V"),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aEditDeckInClipboard",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Edit Deck in Clipboard, Annotated"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aEditDeckInClipboardRaw",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Edit Deck in Clipboard"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aNewDeck", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "New Deck"),
|
||||
parseSequenceString("Ctrl+N"),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aOpenCustomFolder",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Open Custom Pictures Folder"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aPrintDeck", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Print Deck..."),
|
||||
parseSequenceString("Ctrl+P"),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aRemoveCard", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Delete Card"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aResetLayout", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Reset Layout"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aSaveDeck", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Save Deck"),
|
||||
parseSequenceString("Ctrl+S"),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aSaveDeckAs", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Save Deck as..."),
|
||||
parseSequenceString("Ctrl+Shift+S"),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aSaveDeckToClipboard",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Save Deck to Clipboard, Annotated"),
|
||||
parseSequenceString("Ctrl+Shift+C"),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aSaveDeckToClipboardNoSetInfo",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Save Deck to Clipboard, Annotated (No Set Info)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aSaveDeckToClipboardRaw",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Save Deck to Clipboard"),
|
||||
parseSequenceString("Ctrl+Shift+R"),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"TabDeckEditor/aSaveDeckToClipboardRawNoSetInfo",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Save Deck to Clipboard (No Set Info)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Deck_Editor)},
|
||||
{"DeckViewContainer/loadLocalButton", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Load Local Deck..."),
|
||||
parseSequenceString("Ctrl+O"),
|
||||
ShortcutGroup::Game_Lobby)},
|
||||
{"DeckViewContainer/loadRemoteButton", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Load Remote Deck..."),
|
||||
parseSequenceString("Ctrl+Alt+O"),
|
||||
ShortcutGroup::Game_Lobby)},
|
||||
{"DeckViewContainer/loadFromClipboardButton",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Load Deck from Clipboard..."),
|
||||
parseSequenceString("Ctrl+Shift+V"),
|
||||
ShortcutGroup::Game_Lobby)},
|
||||
{"DeckViewContainer/loadFromWebsiteButton",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Load from website..."),
|
||||
parseSequenceString("Ctrl+Shift+O"),
|
||||
ShortcutGroup::Game_Lobby)},
|
||||
{"DeckViewContainer/unloadDeckButton", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Unload Deck"),
|
||||
parseSequenceString("Ctrl+Alt+U"),
|
||||
ShortcutGroup::Game_Lobby)},
|
||||
{"DeckViewContainer/readyStartButton", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Ready to Start"),
|
||||
parseSequenceString("Ctrl+Shift+S"),
|
||||
ShortcutGroup::Game_Lobby)},
|
||||
{"DeckViewContainer/sideboardLockButton",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Toggle Sideboard Lock"),
|
||||
parseSequenceString("Ctrl+Shift+B"),
|
||||
ShortcutGroup::Game_Lobby)},
|
||||
{"DeckViewContainer/forceStartGameButton", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Force Start"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Game_Lobby)},
|
||||
{"Player/aCCMagenta", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Card Counter (F)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aRCMagenta", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Card Counter (F)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aSCMagenta", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Card Counters (F)..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aCCPurple", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Card Counter (E)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aRCPurple", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Card Counter (E)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aSCPurple", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Card Counters (E)..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aCCCyan", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Card Counter(D)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aRCCyan", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Card Counter (D)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aSCCyan", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Card Counters (D)..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aCCGreen", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Card Counter (C)"),
|
||||
parseSequenceString("Ctrl+>"),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aRCGreen", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Card Counter (C)"),
|
||||
parseSequenceString("Ctrl+<"),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aSCGreen", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Card Counters (C)..."),
|
||||
parseSequenceString("Ctrl+?"),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aCCYellow", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Card Counter (B)"),
|
||||
parseSequenceString("Ctrl+."),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aRCYellow", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Card Counter (B)"),
|
||||
parseSequenceString("Ctrl+,"),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aSCYellow", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Card Counters (B)..."),
|
||||
parseSequenceString("Ctrl+/"),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aCCRed", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Card Counter (A)"),
|
||||
parseSequenceString("Alt+."),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aRCRed", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Card Counter (A)"),
|
||||
parseSequenceString("Alt+,"),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aSCRed", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Card Counters (A)..."),
|
||||
parseSequenceString("Alt+/"),
|
||||
ShortcutGroup::Card_Counters)},
|
||||
{"Player/aInc", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Life Counter"),
|
||||
parseSequenceString("F12"),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aDec", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Life Counter"),
|
||||
parseSequenceString("F11"),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aSet", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Life Counters..."),
|
||||
parseSequenceString("Ctrl+L"),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aIncCounter_w", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add White Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aDecCounter_w", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove White Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aSetCounter_w", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set White Counters..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aIncCounter_u", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Blue Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aDecCounter_u", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Blue Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aSetCounter_u", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Blue Counters..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aIncCounter_b", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Black Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aDecCounter_b", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Black Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aSetCounter_b", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Black Counters..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aIncCounter_r", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Red Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aDecCounter_r", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Red Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aSetCounter_r", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Red Counters..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aIncCounter_g", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Green Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aDecCounter_g", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Green Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aSetCounter_g", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Green Counters..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aIncCounter_x", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Colorless Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aDecCounter_x", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Colorless Counter"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aSetCounter_x", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Colorless Counters..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aIncCounter_storm", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Other Counter"),
|
||||
parseSequenceString("Ctrl+]"),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aDecCounter_storm", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Other Counter"),
|
||||
parseSequenceString("Ctrl+["),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aSetCounter_storm", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Other Counters..."),
|
||||
parseSequenceString("Ctrl+\\"),
|
||||
ShortcutGroup::Player_Counters)},
|
||||
{"Player/aIncrementAllCardCounters",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Increment all card counters"),
|
||||
parseSequenceString("Ctrl+Shift+A"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aIncP", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Power (+1/+0)"),
|
||||
parseSequenceString("Ctrl++;Ctrl+="),
|
||||
ShortcutGroup::Power_Toughness)},
|
||||
{"Player/aDecP", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Power (-1/-0)"),
|
||||
parseSequenceString("Ctrl+-"),
|
||||
ShortcutGroup::Power_Toughness)},
|
||||
{"Player/aFlowP", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Move Toughness to Power (+1/-1)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Power_Toughness)},
|
||||
{"Player/aIncT", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Toughness (+0/+1)"),
|
||||
parseSequenceString("Alt++;Alt+="),
|
||||
ShortcutGroup::Power_Toughness)},
|
||||
{"Player/aDecT", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Toughness (-0/-1)"),
|
||||
parseSequenceString("Alt+-"),
|
||||
ShortcutGroup::Power_Toughness)},
|
||||
{"Player/aFlowT", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Move Power to Toughness (-1/+1)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Power_Toughness)},
|
||||
{"Player/aIncPT", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Add Power and Toughness (+1/+1)"),
|
||||
parseSequenceString("Ctrl+Alt++;Ctrl+Alt+="),
|
||||
ShortcutGroup::Power_Toughness)},
|
||||
{"Player/aDecPT", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Power and Toughness (-1/-1)"),
|
||||
parseSequenceString("Ctrl+Alt+-"),
|
||||
ShortcutGroup::Power_Toughness)},
|
||||
{"Player/aSetPT", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Power and Toughness..."),
|
||||
parseSequenceString("Ctrl+P"),
|
||||
ShortcutGroup::Power_Toughness)},
|
||||
{"Player/aResetPT", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Reset Power and Toughness"),
|
||||
parseSequenceString("Ctrl+Alt+0"),
|
||||
ShortcutGroup::Power_Toughness)},
|
||||
{"Player/phase0", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Untap"),
|
||||
parseSequenceString("F5"),
|
||||
ShortcutGroup::Game_Phases)},
|
||||
{"Player/phase1",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Upkeep"), parseSequenceString(""), ShortcutGroup::Game_Phases)},
|
||||
{"Player/phase2",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Draw"), parseSequenceString("F6"), ShortcutGroup::Game_Phases)},
|
||||
{"Player/phase3", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "First Main Phase"),
|
||||
parseSequenceString("F7"),
|
||||
ShortcutGroup::Game_Phases)},
|
||||
{"Player/phase4", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Start Combat"),
|
||||
parseSequenceString("F8"),
|
||||
ShortcutGroup::Game_Phases)},
|
||||
{"Player/phase5",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Attack"), parseSequenceString(""), ShortcutGroup::Game_Phases)},
|
||||
{"Player/phase6",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Block"), parseSequenceString(""), ShortcutGroup::Game_Phases)},
|
||||
{"Player/phase7",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Damage"), parseSequenceString(""), ShortcutGroup::Game_Phases)},
|
||||
{"Player/phase8", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "End Combat"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Game_Phases)},
|
||||
{"Player/phase9", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Second Main Phase"),
|
||||
parseSequenceString("F9"),
|
||||
ShortcutGroup::Game_Phases)},
|
||||
{"Player/phase10",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "End"), parseSequenceString("F10"), ShortcutGroup::Game_Phases)},
|
||||
{"Player/aNextPhase", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Next Phase"),
|
||||
parseSequenceString("Ctrl+Space;Tab"),
|
||||
ShortcutGroup::Game_Phases)},
|
||||
{"Player/aNextPhaseAction", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Next Phase Action"),
|
||||
parseSequenceString("Shift+Tab"),
|
||||
ShortcutGroup::Game_Phases)},
|
||||
{"Player/aNextTurn", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Next Turn"),
|
||||
parseSequenceString("Ctrl+Return;Ctrl+Enter"),
|
||||
ShortcutGroup::Game_Phases)},
|
||||
{"Player/aHide", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Hide Card in Reveal Window"),
|
||||
parseSequenceString("Alt+H"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aTap", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Tap / Untap Card"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aUntapAll", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Untap All"),
|
||||
parseSequenceString("Ctrl+U"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aDoesntUntap", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Toggle Skip Untapping"),
|
||||
parseSequenceString("Alt+U"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aFlip", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Turn Card Over"),
|
||||
parseSequenceString("Alt+F"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aPeek", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Peek Card"),
|
||||
parseSequenceString("Alt+L"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aPlay", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Play Card"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aPlayFacedown", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Play Card, Face Down"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aAttach", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Attach Card..."),
|
||||
parseSequenceString("Ctrl+Alt+A"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aUnattach", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Unattach Card"),
|
||||
parseSequenceString("Ctrl+Alt+U"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aClone", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Clone Card"),
|
||||
parseSequenceString("Ctrl+J"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aCreateToken", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Create Token..."),
|
||||
parseSequenceString("Ctrl+T"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aCreateRelatedTokens", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Create All Related Tokens"),
|
||||
parseSequenceString("Ctrl+Shift+T"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aCreateAnotherToken", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Create Another Token"),
|
||||
parseSequenceString("Ctrl+G"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aSetAnnotation", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Set Annotation..."),
|
||||
parseSequenceString("Alt+N"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aReduceLifeByPower", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Reduce Life by Power"),
|
||||
parseSequenceString("Ctrl+Shift+L"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aSelectAll", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Select All Cards in Zone"),
|
||||
parseSequenceString("Ctrl+A"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aSelectRow", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Select All Cards in Row"),
|
||||
parseSequenceString("Ctrl+Shift+X"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aSelectColumn", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Select All Cards in Column"),
|
||||
parseSequenceString("Ctrl+Shift+C"),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aRevealToAll", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Reveal Selected Cards to All Players"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Playing_Area)},
|
||||
{"Player/aMoveToBottomLibrary", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Bottom of Library"),
|
||||
parseSequenceString("Ctrl+B"),
|
||||
ShortcutGroup::Move_selected)},
|
||||
{"Player/aMoveToExile", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Exile"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_selected)},
|
||||
{"Player/aMoveToGraveyard", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Graveyard"),
|
||||
parseSequenceString("Ctrl+Del"),
|
||||
ShortcutGroup::Move_selected)},
|
||||
{"Player/aMoveToHand",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Hand"), parseSequenceString(""), ShortcutGroup::Move_selected)},
|
||||
{"Player/aMoveToTopLibrary", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Top of Library"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_selected)},
|
||||
{"Player/aMoveToTable", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Battlefield"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_selected)},
|
||||
{"Player/aViewHand",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Hand"), parseSequenceString(""), ShortcutGroup::View)},
|
||||
{"Player/aViewGraveyard",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Graveyard"), parseSequenceString("F4"), ShortcutGroup::View)},
|
||||
{"Player/aViewLibrary",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Library"), parseSequenceString("F3"), ShortcutGroup::View)},
|
||||
{"Player/aViewRfg",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Exile"), parseSequenceString(""), ShortcutGroup::View)},
|
||||
{"Player/aViewSideboard", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Sideboard"),
|
||||
parseSequenceString("Ctrl+F3"),
|
||||
ShortcutGroup::View)},
|
||||
{"Player/aViewTopCards", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Top Cards of Library"),
|
||||
parseSequenceString("Ctrl+W"),
|
||||
ShortcutGroup::View)},
|
||||
{"Player/aViewBottomCards", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Bottom Cards of Library"),
|
||||
parseSequenceString("Ctrl+Shift+W"),
|
||||
ShortcutGroup::View)},
|
||||
{"Player/aCloseMostRecentZoneView", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Close Recent View"),
|
||||
parseSequenceString("Esc"),
|
||||
ShortcutGroup::View)},
|
||||
{"Player/aMoveTopToPlay", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Stack"),
|
||||
parseSequenceString("Ctrl+Y"),
|
||||
ShortcutGroup::Move_top)},
|
||||
{"Player/aMoveTopToPlayFaceDown", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Battlefield, Face Down"),
|
||||
parseSequenceString("Ctrl+Shift+E"),
|
||||
ShortcutGroup::Move_top)},
|
||||
{"Player/aMoveTopCardToGraveyard", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Graveyard"),
|
||||
parseSequenceString("Alt+Y"),
|
||||
ShortcutGroup::Move_top)},
|
||||
{"Player/aMoveTopCardsToGraveyard", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Graveyard (Multiple)"),
|
||||
parseSequenceString("Alt+M"),
|
||||
ShortcutGroup::Move_top)},
|
||||
{"Player/aMoveTopCardsToGraveyardFaceDown",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Graveyard (Multiple), Face Down"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_top)},
|
||||
{"Player/aMoveTopCardToExile",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Exile"), parseSequenceString(""), ShortcutGroup::Move_top)},
|
||||
{"Player/aMoveTopCardsToExile", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Exile (Multiple)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_top)},
|
||||
{"Player/aMoveTopCardsToExileFaceDown",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Exile (Multiple), Face Down"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_top)},
|
||||
{"Player/aMoveTopCardsUntil", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Stack Until Found"),
|
||||
parseSequenceString("Ctrl+Shift+Y"),
|
||||
ShortcutGroup::Move_top)},
|
||||
{"Player/aMoveTopCardToBottom", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Bottom of Library"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_top)},
|
||||
{"Player/aMoveBottomToPlay",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Stack"), parseSequenceString(""), ShortcutGroup::Move_bottom)},
|
||||
{"Player/aMoveBottomToPlayFaceDown", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Battlefield, Face Down"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_bottom)},
|
||||
{"Player/aMoveBottomCardToGrave", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Graveyard"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_bottom)},
|
||||
{"Player/aMoveBottomCardsToGrave", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Graveyard (Multiple)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_bottom)},
|
||||
{"Player/aMoveBottomCardsToGraveFaceDown",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Graveyard (Multiple), Face Down"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_bottom)},
|
||||
{"Player/aMoveBottomCardToExile",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Exile"), parseSequenceString(""), ShortcutGroup::Move_bottom)},
|
||||
{"Player/aMoveBottomCardsToExile", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Exile (Multiple)"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_bottom)},
|
||||
{"Player/aMoveBottomCardsToExileFaceDown",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Exile (Multiple), Face Down"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_bottom)},
|
||||
{"Player/aMoveBottomCardToTop", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Top of Library"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_bottom)},
|
||||
{"Player/aDrawBottomCard", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Draw Bottom Card"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_bottom)},
|
||||
{"Player/aDrawBottomCards", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Draw Multiple Cards from Bottom..."),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Move_bottom)},
|
||||
{"Player/aDrawArrow", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Draw Arrow..."),
|
||||
parseSequenceString("Alt+A"),
|
||||
ShortcutGroup::Gameplay)},
|
||||
{"Player/aRemoveLocalArrows", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Remove Local Arrows"),
|
||||
parseSequenceString("Ctrl+R"),
|
||||
ShortcutGroup::Gameplay)},
|
||||
{"Player/aLeaveGame", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Leave Game"),
|
||||
parseSequenceString("Ctrl+Q"),
|
||||
ShortcutGroup::Gameplay)},
|
||||
{"Player/aConcede",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Concede"), parseSequenceString("F2"), ShortcutGroup::Gameplay)},
|
||||
{"Player/aRollDie", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Roll Dice..."),
|
||||
parseSequenceString("Ctrl+I"),
|
||||
ShortcutGroup::Gameplay)},
|
||||
{"Player/aFlipCoin", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Flip Coin"),
|
||||
parseSequenceString("Ctrl+Shift+I"),
|
||||
ShortcutGroup::Gameplay)},
|
||||
{"Player/aShuffle", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Shuffle Library"),
|
||||
parseSequenceString("Ctrl+S"),
|
||||
ShortcutGroup::Gameplay)},
|
||||
{"Player/aShuffleTopCards", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Shuffle Top Cards of Library"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Gameplay)},
|
||||
{"Player/aShuffleBottomCards", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Shuffle Bottom Cards of Library"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Gameplay)},
|
||||
{"Player/aMulligan", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Mulligan"),
|
||||
parseSequenceString("Ctrl+M"),
|
||||
ShortcutGroup::Drawing)},
|
||||
{"Player/aMulliganSame", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Mulligan (Same hand size)"),
|
||||
parseSequenceString("Ctrl+Shift+M"),
|
||||
ShortcutGroup::Drawing)},
|
||||
{"Player/aMulliganMinusOne", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Mulligan (Hand size - 1)"),
|
||||
parseSequenceString("Ctrl+Shift+Alt+M"),
|
||||
ShortcutGroup::Drawing)},
|
||||
{"Player/aDrawCard", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Draw a Card"),
|
||||
parseSequenceString("Ctrl+D"),
|
||||
ShortcutGroup::Drawing)},
|
||||
{"Player/aDrawCards", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Draw Multiple Cards..."),
|
||||
parseSequenceString("Ctrl+E"),
|
||||
ShortcutGroup::Drawing)},
|
||||
{"Player/aUndoDraw", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Undo Draw"),
|
||||
parseSequenceString("Ctrl+Shift+D"),
|
||||
ShortcutGroup::Drawing)},
|
||||
{"Player/aAlwaysRevealTopCard", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Always Reveal Top Card"),
|
||||
parseSequenceString("Ctrl+N"),
|
||||
ShortcutGroup::Drawing)},
|
||||
{"Player/aAlwaysLookAtTopCard", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Always Look At Top Card"),
|
||||
parseSequenceString("Ctrl+Shift+N"),
|
||||
ShortcutGroup::Drawing)},
|
||||
{"Player/aSortHandByName", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Sort Hand by Name"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Hand)},
|
||||
{"Player/aSortHandByType", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Sort Hand by Type"),
|
||||
parseSequenceString("Ctrl+Shift+H"),
|
||||
ShortcutGroup::Hand)},
|
||||
{"Player/aSortHandByManaValue", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Sort Hand by Mana Value"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Hand)},
|
||||
{"Player/aRevealHandToAll", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Reveal Hand to All Players"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Hand)},
|
||||
{"Player/aRevealRandomHandCardToAll",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Reveal Random Card to All Players"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Hand)},
|
||||
{"Player/aRotateViewCW", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Rotate View Clockwise"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Gameplay)},
|
||||
{"Player/aRotateViewCCW", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Rotate View Counterclockwise"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Gameplay)},
|
||||
{"Player/unfocusTextBox", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Unfocus Text Box"),
|
||||
parseSequenceString("Esc"),
|
||||
ShortcutGroup::Chat_room)},
|
||||
{"Player/aFocusChat", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Focus Chat"),
|
||||
parseSequenceString("Shift+Return"),
|
||||
ShortcutGroup::Chat_room)},
|
||||
{"tab_room/aClearChat", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Clear Chat"),
|
||||
parseSequenceString("F12"),
|
||||
ShortcutGroup::Chat_room)},
|
||||
{"Player/aResetLayout", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Reset Layout"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Game_window)},
|
||||
{"DlgLoadDeckFromClipboard/refreshButton", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Refresh"),
|
||||
parseSequenceString("F5"),
|
||||
ShortcutGroup::Load_deck)},
|
||||
{"Replays/aSkipForward", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Skip Forward"),
|
||||
parseSequenceString("Right"),
|
||||
ShortcutGroup::Replays)},
|
||||
{"Replays/aSkipBackward", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Skip Backward"),
|
||||
parseSequenceString("Left"),
|
||||
ShortcutGroup::Replays)},
|
||||
{"Replays/aSkipForwardBig", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Skip Forward by a lot"),
|
||||
parseSequenceString("Ctrl+Right"),
|
||||
ShortcutGroup::Replays)},
|
||||
{"Replays/aSkipBackwardBig", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Skip Backward by a lot"),
|
||||
parseSequenceString("Ctrl+Left"),
|
||||
ShortcutGroup::Replays)},
|
||||
{"Replays/playButton", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Play/Pause"),
|
||||
parseSequenceString("Space"),
|
||||
ShortcutGroup::Replays)},
|
||||
{"Replays/fastForwardButton", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Toggle Fast Forward"),
|
||||
parseSequenceString("Ctrl+P"),
|
||||
ShortcutGroup::Replays)},
|
||||
{"Tabs/aTabDeckEditor",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Deck Editor"), parseSequenceString(""), ShortcutGroup::Tabs)},
|
||||
{"Tabs/aTabHome",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Home"), parseSequenceString(""), ShortcutGroup::Tabs)},
|
||||
{"Tabs/aTabVisualDeckStorage", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Visual Deck Storage"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Tabs)},
|
||||
{"Tabs/aTabDeckStorage",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Deck Storage"), parseSequenceString(""), ShortcutGroup::Tabs)},
|
||||
{"Tabs/aTabReplays",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Replays"), parseSequenceString(""), ShortcutGroup::Tabs)},
|
||||
{"Tabs/aTabServer",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Server"), parseSequenceString(""), ShortcutGroup::Tabs)},
|
||||
{"Tabs/aTabAccount",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Account"), parseSequenceString(""), ShortcutGroup::Tabs)},
|
||||
{"Tabs/aTabAdmin", ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Administration"),
|
||||
parseSequenceString(""),
|
||||
ShortcutGroup::Tabs)},
|
||||
{"Tabs/aTabLogs",
|
||||
ShortcutKey(QT_TRANSLATE_NOOP("shortcutsTab", "Logs"), parseSequenceString(""), ShortcutGroup::Tabs)},
|
||||
};
|
||||
};
|
||||
|
||||
#endif // SHORTCUTSSETTINGS_H
|
||||
@@ -0,0 +1,168 @@
|
||||
#include "sound_engine.h"
|
||||
|
||||
#include "settings/cache_settings.h"
|
||||
|
||||
#include <QDir>
|
||||
#include <QMediaPlayer>
|
||||
|
||||
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
|
||||
#include <QAudioOutput>
|
||||
#endif
|
||||
|
||||
#define DEFAULT_THEME_NAME "Default"
|
||||
#define TEST_SOUND_FILENAME "player_join"
|
||||
|
||||
SoundEngine::SoundEngine(QObject *parent) : QObject(parent), audioOutput(nullptr), player(nullptr)
|
||||
{
|
||||
ensureThemeDirectoryExists();
|
||||
connect(&SettingsCache::instance(), &SettingsCache::soundThemeChanged, this, &SoundEngine::themeChangedSlot);
|
||||
connect(&SettingsCache::instance(), &SettingsCache::soundEnabledChanged, this, &SoundEngine::soundEnabledChanged);
|
||||
|
||||
soundEnabledChanged();
|
||||
themeChangedSlot();
|
||||
}
|
||||
|
||||
SoundEngine::~SoundEngine()
|
||||
{
|
||||
if (player) {
|
||||
player->deleteLater();
|
||||
player = nullptr;
|
||||
}
|
||||
if (audioOutput) {
|
||||
audioOutput->deleteLater();
|
||||
audioOutput = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
void SoundEngine::soundEnabledChanged()
|
||||
{
|
||||
if (SettingsCache::instance().getSoundEnabled()) {
|
||||
qCInfo(SoundEngineLog) << "SoundEngine: enabling sound with" << audioData.size() << "sounds";
|
||||
if (!player) {
|
||||
player = new QMediaPlayer;
|
||||
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
|
||||
audioOutput = new QAudioOutput(player);
|
||||
player->setAudioOutput(audioOutput);
|
||||
#endif
|
||||
}
|
||||
} else {
|
||||
qCInfo(SoundEngineLog) << "SoundEngine: disabling sound";
|
||||
if (player) {
|
||||
player->stop();
|
||||
player->deleteLater();
|
||||
player = nullptr;
|
||||
}
|
||||
if (audioOutput) {
|
||||
audioOutput->deleteLater();
|
||||
audioOutput = nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void SoundEngine::playSound(const QString &fileName)
|
||||
{
|
||||
if (!player) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!audioData.contains(fileName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
player->stop();
|
||||
int volumeSliderValue = SettingsCache::instance().getMasterVolume();
|
||||
#if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0))
|
||||
player->audioOutput()->setVolume(qreal(volumeSliderValue) / 100);
|
||||
player->setSource(QUrl::fromLocalFile(audioData[fileName]));
|
||||
#else
|
||||
player->setVolume(volumeSliderValue);
|
||||
player->setMedia(QUrl::fromLocalFile(audioData[fileName]));
|
||||
#endif
|
||||
player->play();
|
||||
}
|
||||
|
||||
void SoundEngine::testSound()
|
||||
{
|
||||
playSound(TEST_SOUND_FILENAME);
|
||||
}
|
||||
|
||||
void SoundEngine::ensureThemeDirectoryExists()
|
||||
{
|
||||
if (SettingsCache::instance().getSoundThemeName().isEmpty() ||
|
||||
!getAvailableThemes().contains(SettingsCache::instance().getSoundThemeName())) {
|
||||
qCInfo(SoundEngineLog) << "Sounds theme name not set, setting default value";
|
||||
SettingsCache::instance().setSoundThemeName(DEFAULT_THEME_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
QStringMap &SoundEngine::getAvailableThemes()
|
||||
{
|
||||
QDir dir;
|
||||
availableThemes.clear();
|
||||
|
||||
// load themes from user profile dir
|
||||
|
||||
dir.setPath(SettingsCache::instance().getDataPath() + "/sounds");
|
||||
|
||||
for (const QString &themeName : dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) {
|
||||
if (!availableThemes.contains(themeName)) {
|
||||
availableThemes.insert(themeName, dir.absoluteFilePath(themeName));
|
||||
}
|
||||
}
|
||||
|
||||
// load themes from cockatrice system dir
|
||||
dir.setPath(qApp->applicationDirPath() +
|
||||
#ifdef Q_OS_MAC
|
||||
"/../Resources/sounds"
|
||||
#elif defined(Q_OS_WIN)
|
||||
"/sounds"
|
||||
#else // linux
|
||||
"/../share/cockatrice/sounds"
|
||||
#endif
|
||||
);
|
||||
|
||||
for (const QString &themeName : dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) {
|
||||
if (!availableThemes.contains(themeName)) {
|
||||
availableThemes.insert(themeName, dir.absoluteFilePath(themeName));
|
||||
}
|
||||
}
|
||||
|
||||
return availableThemes;
|
||||
}
|
||||
|
||||
void SoundEngine::themeChangedSlot()
|
||||
{
|
||||
QString themeName = SettingsCache::instance().getSoundThemeName();
|
||||
qCInfo(SoundEngineLog) << "Sound theme changed:" << themeName;
|
||||
|
||||
QDir dir = getAvailableThemes().value(themeName);
|
||||
|
||||
audioData.clear();
|
||||
|
||||
static const QStringList extensions = {".wav", ".mp3", ".ogg"};
|
||||
static const QStringList fileNames = {
|
||||
// Phases
|
||||
"untap_step", "upkeep_step", "draw_step", "main_1", "start_combat", "attack_step", "block_step", "damage_step",
|
||||
"end_combat", "main_2", "end_step",
|
||||
// Game Actions
|
||||
"draw_card", "play_card", "tap_card", "untap_card", "shuffle", "roll_dice", "life_change",
|
||||
// Player
|
||||
"player_join", "player_leave", "player_disconnect", "player_reconnect", "player_concede",
|
||||
// Spectator
|
||||
"spectator_join", "spectator_leave",
|
||||
// Buddy
|
||||
"buddy_join", "buddy_leave",
|
||||
// Chat & UI
|
||||
"chat_mention", "all_mention", "private_message"};
|
||||
|
||||
for (const QString &extension : extensions) {
|
||||
for (const QString &name : fileNames) {
|
||||
QFile file(dir.filePath(name + extension));
|
||||
if (file.exists()) {
|
||||
audioData.insert(name, file.fileName());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
soundEnabledChanged();
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* @file sound_engine.h
|
||||
* @ingroup Core
|
||||
*/
|
||||
//! \todo Document this file.
|
||||
|
||||
#ifndef SOUNDENGINE_H
|
||||
#define SOUNDENGINE_H
|
||||
|
||||
#include <QAudioOutput>
|
||||
#include <QLoggingCategory>
|
||||
#include <QMap>
|
||||
#include <QMediaPlayer>
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
|
||||
inline Q_LOGGING_CATEGORY(SoundEngineLog, "sound_engine");
|
||||
|
||||
class QBuffer;
|
||||
|
||||
typedef QMap<QString, QString> QStringMap;
|
||||
|
||||
class SoundEngine : public QObject
|
||||
{
|
||||
Q_OBJECT
|
||||
public:
|
||||
explicit SoundEngine(QObject *parent = nullptr);
|
||||
~SoundEngine() override;
|
||||
void playSound(const QString &fileName);
|
||||
QStringMap &getAvailableThemes();
|
||||
|
||||
private:
|
||||
QStringMap availableThemes;
|
||||
QMap<QString, QString> audioData;
|
||||
QAudioOutput *audioOutput;
|
||||
QMediaPlayer *player;
|
||||
|
||||
protected:
|
||||
void ensureThemeDirectoryExists();
|
||||
private slots:
|
||||
void soundEnabledChanged();
|
||||
void themeChangedSlot();
|
||||
public slots:
|
||||
void testSound();
|
||||
};
|
||||
|
||||
extern SoundEngine *soundEngine;
|
||||
#endif
|
||||
@@ -0,0 +1,13 @@
|
||||
#ifndef TRANSLATION_H
|
||||
#define TRANSLATION_H
|
||||
|
||||
enum GrammaticalCase
|
||||
{
|
||||
CaseNominative,
|
||||
CaseLookAtZone,
|
||||
CaseTopCardsOfZone,
|
||||
CaseRevealZone,
|
||||
CaseShuffleZone
|
||||
};
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user