diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt index 52159ef4..f7299897 100644 --- a/cockatrice/CMakeLists.txt +++ b/cockatrice/CMakeLists.txt @@ -119,6 +119,7 @@ SET(cockatrice_SOURCES src/releasechannel.cpp src/userconnection_information.cpp src/spoilerbackgroundupdater.cpp + src/handle_public_servers.cpp ${VERSION_STRING_CPP} ) diff --git a/cockatrice/src/dlg_connect.cpp b/cockatrice/src/dlg_connect.cpp index dcfb0442..167e568b 100644 --- a/cockatrice/src/dlg_connect.cpp +++ b/cockatrice/src/dlg_connect.cpp @@ -3,6 +3,7 @@ #include "userconnection_information.h" #include #include +#include #include #include #include @@ -21,7 +22,18 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent) previousHosts = new QComboBox(this); previousHosts->installEventFilter(new DeleteHighlightedItemWhenShiftDelPressedEventFilter); - rebuildComboBoxList(); + hps = new HandlePublicServers(this); + btnRefreshServers = new QPushButton(this); + btnRefreshServers->setIcon(QPixmap("theme:icons/update")); + btnRefreshServers->setToolTip(tr("Refresh the server list with known public servers")); + btnRefreshServers->setFixedWidth(50); + + connect(hps, SIGNAL(sigPublicServersDownloadedSuccessfully()), this, SLOT(rebuildComboBoxList())); + connect(hps, SIGNAL(sigPublicServersDownloadedUnsuccessfully(int)), this, SLOT(rebuildComboBoxList(int))); + connect(btnRefreshServers, SIGNAL(released()), this, SLOT(downloadThePublicServers())); + + connect(this, SIGNAL(sigPublicServersDownloaded()), this, SLOT(rebuildComboBoxList())); + preRebuildComboBoxList(); newHostButton = new QRadioButton(tr("New Host"), this); @@ -52,15 +64,6 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent) autoConnectCheckBox = new QCheckBox(tr("A&uto connect")); autoConnectCheckBox->setToolTip(tr("Automatically connect to the most recent login when Cockatrice opens")); - publicServersLabel = - new QLabel(QString("(%2)").arg(PUBLIC_SERVERS_URL).arg(tr("Public Servers"))); - publicServersLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed); - publicServersLabel->setWordWrap(true); - publicServersLabel->setTextFormat(Qt::RichText); - publicServersLabel->setTextInteractionFlags(Qt::TextBrowserInteraction); - publicServersLabel->setOpenExternalLinks(true); - publicServersLabel->setAlignment(Qt::AlignCenter); - if (savePasswordCheckBox->isChecked()) { autoConnectCheckBox->setChecked(static_cast(settingsCache->servers().getAutoConnect())); autoConnectCheckBox->setEnabled(true); @@ -83,14 +86,14 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent) btnCancel->setFixedWidth(100); connect(btnCancel, SIGNAL(released()), this, SLOT(actCancel())); - auto *newHostLayout = new QGridLayout; - newHostLayout->addWidget(newHostButton, 0, 1); - newHostLayout->addWidget(publicServersLabel, 0, 2); + newHolderLayout = new QHBoxLayout; + newHolderLayout->addWidget(previousHosts); + newHolderLayout->addWidget(btnRefreshServers); - auto *connectionLayout = new QGridLayout; + connectionLayout = new QGridLayout; connectionLayout->addWidget(previousHostButton, 0, 1); - connectionLayout->addWidget(previousHosts, 1, 1); - connectionLayout->addLayout(newHostLayout, 2, 1, 1, 2); + connectionLayout->addLayout(newHolderLayout, 1, 1, 1, 2); + connectionLayout->addWidget(newHostButton, 2, 1); connectionLayout->addWidget(saveLabel, 3, 0); connectionLayout->addWidget(saveEdit, 3, 1); connectionLayout->addWidget(hostLabel, 4, 0); @@ -99,33 +102,33 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent) connectionLayout->addWidget(portEdit, 5, 1); connectionLayout->addWidget(autoConnectCheckBox, 6, 1); - auto *buttons = new QGridLayout; + buttons = new QGridLayout; buttons->addWidget(btnOk, 0, 0); buttons->addWidget(btnForgotPassword, 0, 1); buttons->addWidget(btnCancel, 0, 2); - QGroupBox *restrictionsGroupBox = new QGroupBox(tr("Server")); + restrictionsGroupBox = new QGroupBox(tr("Server")); restrictionsGroupBox->setLayout(connectionLayout); - auto *loginLayout = new QGridLayout; + loginLayout = new QGridLayout; loginLayout->addWidget(playernameLabel, 0, 0); loginLayout->addWidget(playernameEdit, 0, 1); loginLayout->addWidget(passwordLabel, 1, 0); loginLayout->addWidget(passwordEdit, 1, 1); loginLayout->addWidget(savePasswordCheckBox, 2, 1); - QGroupBox *loginGroupBox = new QGroupBox(tr("Login")); + loginGroupBox = new QGroupBox(tr("Login")); loginGroupBox->setLayout(loginLayout); - QGroupBox *btnGroupBox = new QGroupBox(tr("")); + btnGroupBox = new QGroupBox(tr("")); btnGroupBox->setLayout(buttons); - auto *grid = new QGridLayout; + grid = new QGridLayout; grid->addWidget(restrictionsGroupBox, 0, 0); grid->addWidget(loginGroupBox, 1, 0); grid->addWidget(btnGroupBox, 2, 0); - auto *mainLayout = new QVBoxLayout; + mainLayout = new QVBoxLayout; mainLayout->addLayout(grid); setLayout(mainLayout); @@ -144,6 +147,8 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent) playernameEdit->setFocus(); } +DlgConnect::~DlgConnect() = default; + void DlgConnect::actSaveConfig() { bool updateSuccess = settingsCache->servers().updateExistingServer( @@ -156,30 +161,41 @@ void DlgConnect::actSaveConfig() passwordEdit->text(), savePasswordCheckBox->isChecked()); } - rebuildComboBoxList(); + preRebuildComboBoxList(); } -void DlgConnect::rebuildComboBoxList() +void DlgConnect::downloadThePublicServers() { + btnRefreshServers->setDisabled(true); + previousHosts->clear(); + previousHosts->addItem(placeHolderText); + hps->downloadPublicServers(); +} + +void DlgConnect::preRebuildComboBoxList() +{ + UserConnection_Information uci; + savedHostList = uci.getServerInfo(); + + if (savedHostList.size() == 1) { + downloadThePublicServers(); + } else { + rebuildComboBoxList(); + } +} + +void DlgConnect::rebuildComboBoxList(int failure) +{ + Q_UNUSED(failure); + previousHosts->clear(); UserConnection_Information uci; savedHostList = uci.getServerInfo(); - if (savedHostList.size() == 1) { - settingsCache->servers().addNewServer("Rooster Ranges", "server.cockatrice.us", "4747", "", "", false); - settingsCache->servers().addNewServer("Chickatrice", "chickatrice.net", "4747", "", "", false); - settingsCache->servers().addNewServer("dr4ft", "cockatrice.dr4ft.com", "4747", "", "", false); - settingsCache->servers().addNewServer("Tetrarch", "mtg.tetrarch.co", "4747", "", "", false); - } else if (!savedHostList.contains("Rooster Ranges")) { - settingsCache->servers().addNewServer("Rooster Ranges", "server.cockatrice.us", "4747", "", "", false); - settingsCache->servers().removeServer("Woogerworks"); - } - - savedHostList = uci.getServerInfo(); - int i = 0; - for (UserConnection_Information tmp : savedHostList) { + for (auto pair : savedHostList) { + auto tmp = pair.second; QString saveName = tmp.getSaveName(); if (saveName.size()) { previousHosts->addItem(saveName); @@ -191,6 +207,8 @@ void DlgConnect::rebuildComboBoxList() i++; } } + + btnRefreshServers->setDisabled(false); } void DlgConnect::previousHostSelected(bool state) @@ -198,12 +216,13 @@ void DlgConnect::previousHostSelected(bool state) if (state) { saveEdit->setDisabled(true); previousHosts->setDisabled(false); + btnRefreshServers->setDisabled(false); } } void DlgConnect::updateDisplayInfo(const QString &saveName) { - if (saveEdit == nullptr) { + if (saveEdit == nullptr || saveName == placeHolderText) { return; } @@ -227,6 +246,7 @@ void DlgConnect::newHostSelected(bool state) { if (state) { previousHosts->setDisabled(true); + btnRefreshServers->setDisabled(true); hostEdit->clear(); portEdit->clear(); playernameEdit->clear(); @@ -236,7 +256,7 @@ void DlgConnect::newHostSelected(bool state) saveEdit->setPlaceholderText("New Menu Name"); saveEdit->setDisabled(false); } else { - rebuildComboBoxList(); + preRebuildComboBoxList(); } } @@ -310,4 +330,4 @@ void DlgConnect::actForgotPassword() { emit sigStartForgotPasswordRequest(); reject(); -} +} \ No newline at end of file diff --git a/cockatrice/src/dlg_connect.h b/cockatrice/src/dlg_connect.h index 885df027..5bea38ee 100644 --- a/cockatrice/src/dlg_connect.h +++ b/cockatrice/src/dlg_connect.h @@ -1,21 +1,26 @@ #ifndef DLG_CONNECT_H #define DLG_CONNECT_H +#include "handle_public_servers.h" #include "userconnection_information.h" #include #include -class QLabel; -class QPushButton; class QCheckBox; class QComboBox; +class QGridLayout; +class QGroupBox; +class QHBoxLayout; +class QLabel; +class QPushButton; class QRadioButton; +class QVBoxLayout; class DeleteHighlightedItemWhenShiftDelPressedEventFilter : public QObject { Q_OBJECT protected: - bool eventFilter(QObject *obj, QEvent *event); + bool eventFilter(QObject *obj, QEvent *event) override; }; class DlgConnect : public QDialog @@ -23,9 +28,11 @@ class DlgConnect : public QDialog Q_OBJECT signals: void sigStartForgotPasswordRequest(); + void sigPublicServersDownloaded(); public: - DlgConnect(QWidget *parent = 0); + explicit DlgConnect(QWidget *parent = nullptr); + ~DlgConnect() override; QString getHost() const; int getPort() const { @@ -39,6 +46,7 @@ public: { return passwordEdit->text(); } + private slots: void actOk(); void actCancel(); @@ -48,15 +56,23 @@ private slots: void newHostSelected(bool state); void actForgotPassword(); void updateDisplayInfo(const QString &saveName); - void rebuildComboBoxList(); + void preRebuildComboBoxList(); + void rebuildComboBoxList(int failure = -1); + void downloadThePublicServers(); private: - QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel, *saveLabel, *publicServersLabel; + QGridLayout *newHostLayout, *connectionLayout, *buttons, *loginLayout, *grid; + QHBoxLayout *newHolderLayout; + QGroupBox *loginGroupBox, *btnGroupBox, *restrictionsGroupBox; + QVBoxLayout *mainLayout; + QLabel *hostLabel, *portLabel, *playernameLabel, *passwordLabel, *saveLabel; QLineEdit *hostEdit, *portEdit, *playernameEdit, *passwordEdit, *saveEdit; QCheckBox *savePasswordCheckBox, *autoConnectCheckBox; QComboBox *previousHosts; QRadioButton *newHostButton, *previousHostButton; - QPushButton *btnOk, *btnCancel, *btnForgotPassword; - QMap savedHostList; + QPushButton *btnOk, *btnCancel, *btnForgotPassword, *btnRefreshServers; + QMap> savedHostList; + HandlePublicServers *hps; + const QString placeHolderText = tr("Downloading..."); }; #endif diff --git a/cockatrice/src/handle_public_servers.cpp b/cockatrice/src/handle_public_servers.cpp new file mode 100644 index 00000000..08d1cc8d --- /dev/null +++ b/cockatrice/src/handle_public_servers.cpp @@ -0,0 +1,104 @@ +#include "handle_public_servers.h" +#include "qt-json/json.h" +#include "settingscache.h" +#include +#include +#include +#include + +#define PUBLIC_SERVERS_JSON "https://cockatrice.github.io/public-servers.json" + +HandlePublicServers::HandlePublicServers(QObject *parent) + : QObject(parent), nam(new QNetworkAccessManager(this)), reply(nullptr) +{ +} + +void HandlePublicServers::downloadPublicServers() +{ + QUrl url(QString(PUBLIC_SERVERS_JSON)); + reply = nam->get(QNetworkRequest(url)); + connect(reply, SIGNAL(finished()), this, SLOT(actFinishParsingDownloadedData())); +} + +void HandlePublicServers::actFinishParsingDownloadedData() +{ + reply = dynamic_cast(sender()); + QNetworkReply::NetworkError errorCode = reply->error(); + + if (errorCode == QNetworkReply::NoError) { + // Get current saved hosts + UserConnection_Information uci; + savedHostList = uci.getServerInfo(); + + // Downloaded data from GitHub + bool jsonSuccessful; + QString jsonData = QString(reply->readAll()); + + auto jsonMap = QtJson::Json::parse(jsonData, jsonSuccessful).toMap(); + + if (jsonSuccessful) { + updateServerINISettings(jsonMap); + } else { + qDebug() << "[PUBLIC SERVER HANDLER]" + << "JSON Parsing Error"; + emit sigPublicServersDownloadedUnsuccessfully(errorCode); + } + + } else { + qDebug() << "[PUBLIC SERVER HANDLER]" + << "Error Downloading Public Servers" << errorCode; + emit sigPublicServersDownloadedUnsuccessfully(errorCode); + } + + reply->deleteLater(); // After an emit() occurs, this object will be deleted +} + +void HandlePublicServers::updateServerINISettings(QMap jsonMap) +{ + // Servers available + auto publicServersJSONList = jsonMap["servers"].toList(); + + for (const auto &server : publicServersJSONList) { + // Data inside one server at a time + // server: [{ ... }, ..., { ... }] + const auto serverMap = server.toMap(); + + QString serverAddress = serverMap["host"].toString(); + + if (serverMap["isInactive"].toBool()) { + publicServersToRemove.append(serverAddress); + continue; + } + + QString serverName = serverMap["name"].toString(); + QString serverPort = serverMap["port"].toString(); + + bool serverFound = false; + for (const auto &iter : savedHostList) { + // If the URL/IP matches + if (iter.second.getServer() == serverAddress) { + serverFound = true; + break; + } + } + + if (serverFound) { + settingsCache->servers().updateExistingServerWithoutLoss(serverName, serverAddress, serverPort); + } else { + settingsCache->servers().addNewServer(serverName, serverAddress, serverPort, "", "", false); + } + } + + // If a server was removed from the public list, + // we will delete it from the local system. + // Will not delete "unofficial" servers + for (const auto &pair : savedHostList) { + QString serverAddr = pair.first; + + if (publicServersToRemove.indexOf(serverAddr) != -1) { + settingsCache->servers().removeServer(serverAddr); + } + } + + emit sigPublicServersDownloadedSuccessfully(); +} diff --git a/cockatrice/src/handle_public_servers.h b/cockatrice/src/handle_public_servers.h new file mode 100644 index 00000000..177b9032 --- /dev/null +++ b/cockatrice/src/handle_public_servers.h @@ -0,0 +1,40 @@ +#ifndef COCKATRICE_HANDLE_PUBLIC_SERVERS_H +#define COCKATRICE_HANDLE_PUBLIC_SERVERS_H + +#include "userconnection_information.h" + +class QNetworkReply; +class QNetworkAccessManager; + +/** + * This class is used to update the servers.ini file and ensure + * the list of public servers has up-to-date information. + * Servers that are added manually by users are not modified. + */ +class HandlePublicServers : public QObject +{ + Q_OBJECT +signals: + void sigPublicServersDownloadedSuccessfully(); + void sigPublicServersDownloadedUnsuccessfully(int); + +public: + explicit HandlePublicServers(QObject *parent = nullptr); + ~HandlePublicServers() override = default; + +public slots: + void downloadPublicServers(); + +private slots: + void actFinishParsingDownloadedData(); + +private: + void updateServerINISettings(QMap); + + QStringList publicServersToRemove; + QMap> savedHostList; + QNetworkAccessManager *nam; + QNetworkReply *reply; +}; + +#endif // COCKATRICE_HANDLE_PUBLIC_SERVERS_H diff --git a/cockatrice/src/settings/serverssettings.cpp b/cockatrice/src/settings/serverssettings.cpp index 999a941c..340fb81f 100644 --- a/cockatrice/src/settings/serverssettings.cpp +++ b/cockatrice/src/settings/serverssettings.cpp @@ -1,5 +1,6 @@ #include "serverssettings.h" #include +#include ServersSettings::ServersSettings(QString settingPath, QObject *parent) : SettingsManager(settingPath + "servers.ini", parent) @@ -36,7 +37,7 @@ QString ServersSettings::getSaveName(QString defaultname) { int index = getPrevioushostindex(getPrevioushostName()); QVariant saveName = getValue(QString("saveName%1").arg(index), "server", "server_details"); - return saveName == QVariant() ? defaultname : saveName.toString(); + return saveName == QVariant() ? std::move(defaultname) : saveName.toString(); } QString ServersSettings::getPrevioushostName() @@ -64,7 +65,7 @@ QString ServersSettings::getHostname(QString defaultHost) { int index = getPrevioushostindex(getPrevioushostName()); QVariant hostname = getValue(QString("server%1").arg(index), "server", "server_details"); - return hostname == QVariant() ? defaultHost : hostname.toString(); + return hostname == QVariant() ? std::move(defaultHost) : hostname.toString(); } void ServersSettings::setPort(QString port) @@ -77,7 +78,7 @@ QString ServersSettings::getPort(QString defaultPort) int index = getPrevioushostindex(getPrevioushostName()); QVariant port = getValue(QString("port%1").arg(index), "server", "server_details"); qDebug() << "getPort() index = " << index << " port.val = " << port.toString(); - return port == QVariant() ? defaultPort : port.toString(); + return port == QVariant() ? std::move(defaultPort) : port.toString(); } void ServersSettings::setPlayerName(QString playerName) @@ -90,7 +91,7 @@ QString ServersSettings::getPlayerName(QString defaultName) int index = getPrevioushostindex(getPrevioushostName()); QVariant name = getValue(QString("username%1").arg(index), "server", "server_details"); qDebug() << "getPlayerName() index = " << index << " name.val = " << name.toString(); - return name == QVariant() ? defaultName : name.toString(); + return name == QVariant() ? std::move(defaultName) : name.toString(); } QString ServersSettings::getPassword() @@ -139,7 +140,7 @@ void ServersSettings::setFPHostName(QString hostname) QString ServersSettings::getFPHostname(QString defaultHost) { QVariant hostname = getValue("fphostname", "server"); - return hostname == QVariant() ? defaultHost : hostname.toString(); + return hostname == QVariant() ? std::move(defaultHost) : hostname.toString(); } void ServersSettings::setFPPort(QString port) @@ -150,7 +151,7 @@ void ServersSettings::setFPPort(QString port) QString ServersSettings::getFPPort(QString defaultPort) { QVariant port = getValue("fpport", "server"); - return port == QVariant() ? defaultPort : port.toString(); + return port == QVariant() ? std::move(defaultPort) : port.toString(); } void ServersSettings::setFPPlayerName(QString playerName) @@ -161,7 +162,7 @@ void ServersSettings::setFPPlayerName(QString playerName) QString ServersSettings::getFPPlayerName(QString defaultName) { QVariant name = getValue("fpplayername", "server"); - return name == QVariant() ? defaultName : name.toString(); + return name == QVariant() ? std::move(defaultName) : name.toString(); } void ServersSettings::setClearDebugLogStatus(bool abIsChecked) @@ -175,11 +176,11 @@ bool ServersSettings::getClearDebugLogStatus(bool abDefaultValue) return cbFlushLog == QVariant() ? abDefaultValue : cbFlushLog.toBool(); } -void ServersSettings::addNewServer(QString saveName, - QString serv, - QString port, - QString username, - QString password, +void ServersSettings::addNewServer(const QString &saveName, + const QString &serv, + const QString &port, + const QString &username, + const QString &password, bool savePassword) { if (updateExistingServer(saveName, serv, port, username, password, savePassword)) @@ -196,12 +197,12 @@ void ServersSettings::addNewServer(QString saveName, setValue(password, QString("password%1").arg(index), "server", "server_details"); } -void ServersSettings::removeServer(QString saveName) +void ServersSettings::removeServer(QString servAddr) { int size = getValue("totalServers", "server", "server_details").toInt() + 1; for (int i = 0; i < size; i++) { - if (saveName == getValue(QString("saveName%1").arg(i), "server", "server_details").toString()) { + if (servAddr == getValue(QString("server%1").arg(i), "server", "server_details").toString()) { deleteValue(QString("server%1").arg(i), "server", "server_details"); deleteValue(QString("port%1").arg(i), "server", "server_details"); deleteValue(QString("username%1").arg(i), "server", "server_details"); @@ -213,6 +214,44 @@ void ServersSettings::removeServer(QString saveName) } } +/** + * Will only update fields with new values, ignores empty values + */ +bool ServersSettings::updateExistingServerWithoutLoss(QString saveName, + QString serv, + QString port, + QString username, + QString password, + bool savePassword) +{ + int size = getValue("totalServers", "server", "server_details").toInt() + 1; + + for (int i = 0; i < size; i++) { + if (serv == getValue(QString("server%1").arg(i), "server", "server_details").toString()) { + + if (!port.isEmpty()) { + setValue(port, QString("port%1").arg(i), "server", "server_details"); + } + + if (!username.isEmpty()) { + setValue(username, QString("username%1").arg(i), "server", "server_details"); + } + + if (savePassword && !password.isEmpty()) { + setValue(password, QString("password%1").arg(i), "server", "server_details"); + } else { + setValue(QString(), QString("password%1").arg(i), "server", "server_details"); + } + + setValue(savePassword, QString("savePassword%1").arg(i), "server", "server_details"); + setValue(saveName, QString("saveName%1").arg(i), "server", "server_details"); + + return true; + } + } + return false; +} + bool ServersSettings::updateExistingServer(QString saveName, QString serv, QString port, @@ -220,17 +259,6 @@ bool ServersSettings::updateExistingServer(QString saveName, QString password, bool savePassword) { - int size = getValue("totalServers", "server", "server_details").toInt() + 1; - - for (int i = 0; i < size; i++) { - if (saveName == getValue(QString("saveName%1").arg(i), "server", "server_details").toString()) { - setValue(serv, QString("server%1").arg(i), "server", "server_details"); - setValue(port, QString("port%1").arg(i), "server", "server_details"); - setValue(username, QString("username%1").arg(i), "server", "server_details"); - setValue(savePassword, QString("savePassword%1").arg(i), "server", "server_details"); - setValue(password, QString("password%1").arg(i), "server", "server_details"); - return true; - } - } - return false; + return updateExistingServerWithoutLoss(std::move(saveName), std::move(serv), std::move(port), std::move(username), + std::move(password), savePassword); } diff --git a/cockatrice/src/settings/serverssettings.h b/cockatrice/src/settings/serverssettings.h index 4eacd0e2..c3098a94 100644 --- a/cockatrice/src/settings/serverssettings.h +++ b/cockatrice/src/settings/serverssettings.h @@ -37,22 +37,29 @@ public: void setFPPort(QString port); void setSavePassword(int save); void setFPPlayerName(QString playerName); - void - addNewServer(QString saveName, QString serv, QString port, QString username, QString password, bool savePassword); - void removeServer(QString saveName); + void addNewServer(const QString &saveName, + const QString &serv, + const QString &port, + const QString &username, + const QString &password, + bool savePassword); + void removeServer(QString servAddr); bool updateExistingServer(QString saveName, QString serv, QString port, QString username, QString password, bool savePassword); + + bool updateExistingServerWithoutLoss(QString saveName, + QString serv = QString(), + QString port = QString(), + QString username = QString(), + QString password = QString(), + bool savePassword = true); void setClearDebugLogStatus(bool abIsChecked); bool getClearDebugLogStatus(bool abDefaultValue); -signals: - -public slots: - private: explicit ServersSettings(QString settingPath, QObject *parent = nullptr); ServersSettings(const ServersSettings & /*other*/); diff --git a/cockatrice/src/settingscache.cpp b/cockatrice/src/settingscache.cpp index e039fb08..76c573f1 100644 --- a/cockatrice/src/settingscache.cpp +++ b/cockatrice/src/settingscache.cpp @@ -7,6 +7,7 @@ #include #include #include +#include QString SettingsCache::getDataPath() { @@ -140,7 +141,7 @@ QString SettingsCache::getSafeConfigFilePath(QString configEntry, QString defaul // if the config settings is empty or refers to a not-existing file, // return the default Path if (!QFile::exists(tmp) || tmp.isEmpty()) - tmp = defaultPath; + tmp = std::move(defaultPath); return tmp; } @@ -182,7 +183,7 @@ SettingsCache::SettingsCache() // tip of the day settings showTipsOnStartup = settings->value("tipOfDay/showTips", true).toBool(); - for (auto tipNumber : settings->value("tipOfDay/seenTips").toList()) { + for (const auto &tipNumber : settings->value("tipOfDay/seenTips").toList()) { seenTips.append(tipNumber.toInt()); } @@ -281,7 +282,7 @@ SettingsCache::SettingsCache() void SettingsCache::setKnownMissingFeatures(QString _knownMissingFeatures) { - knownMissingFeatures = _knownMissingFeatures; + knownMissingFeatures = std::move(_knownMissingFeatures); settings->setValue("interface/knownmissingfeatures", knownMissingFeatures); } @@ -306,32 +307,32 @@ void SettingsCache::setMasterVolume(int _masterVolume) void SettingsCache::setLeftJustified(const int _leftJustified) { - leftJustified = _leftJustified; + leftJustified = (bool)_leftJustified; settings->setValue("interface/leftjustified", leftJustified); emit handJustificationChanged(); } void SettingsCache::setCardScaling(const int _scaleCards) { - scaleCards = _scaleCards; + scaleCards = (bool)_scaleCards; settings->setValue("cards/scaleCards", scaleCards); } void SettingsCache::setShowMessagePopups(const int _showMessagePopups) { - showMessagePopups = _showMessagePopups; + showMessagePopups = (bool)_showMessagePopups; settings->setValue("chat/showmessagepopups", showMessagePopups); } void SettingsCache::setShowMentionPopups(const int _showMentionPopus) { - showMentionPopups = _showMentionPopus; + showMentionPopups = (bool)_showMentionPopus; settings->setValue("chat/showmentionpopups", showMentionPopups); } void SettingsCache::setRoomHistory(const int _roomHistory) { - roomHistory = _roomHistory; + roomHistory = (bool)_roomHistory; settings->setValue("chat/roomhistory", roomHistory); } @@ -409,7 +410,7 @@ void SettingsCache::setThemeName(const QString &_themeName) void SettingsCache::setPicDownload(int _picDownload) { - picDownload = _picDownload; + picDownload = static_cast(_picDownload); settings->setValue("personal/picturedownload", picDownload); emit picDownloadChanged(); } @@ -428,31 +429,31 @@ void SettingsCache::setPicUrlFallback(const QString &_picUrlFallback) void SettingsCache::setNotificationsEnabled(int _notificationsEnabled) { - notificationsEnabled = _notificationsEnabled; + notificationsEnabled = static_cast(_notificationsEnabled); settings->setValue("interface/notificationsenabled", notificationsEnabled); } void SettingsCache::setSpectatorNotificationsEnabled(int _spectatorNotificationsEnabled) { - spectatorNotificationsEnabled = _spectatorNotificationsEnabled; + spectatorNotificationsEnabled = static_cast(_spectatorNotificationsEnabled); settings->setValue("interface/specnotificationsenabled", spectatorNotificationsEnabled); } void SettingsCache::setDoubleClickToPlay(int _doubleClickToPlay) { - doubleClickToPlay = _doubleClickToPlay; + doubleClickToPlay = static_cast(_doubleClickToPlay); settings->setValue("interface/doubleclicktoplay", doubleClickToPlay); } void SettingsCache::setPlayToStack(int _playToStack) { - playToStack = _playToStack; + playToStack = static_cast(_playToStack); settings->setValue("interface/playtostack", playToStack); } void SettingsCache::setAnnotateTokens(int _annotateTokens) { - annotateTokens = _annotateTokens; + annotateTokens = static_cast(_annotateTokens); settings->setValue("interface/annotatetokens", annotateTokens); } @@ -464,21 +465,21 @@ void SettingsCache::setTabGameSplitterSizes(const QByteArray &_tabGameSplitterSi void SettingsCache::setDisplayCardNames(int _displayCardNames) { - displayCardNames = _displayCardNames; + displayCardNames = static_cast(_displayCardNames); settings->setValue("cards/displaycardnames", displayCardNames); emit displayCardNamesChanged(); } void SettingsCache::setHorizontalHand(int _horizontalHand) { - horizontalHand = _horizontalHand; + horizontalHand = static_cast(_horizontalHand); settings->setValue("hand/horizontal", horizontalHand); emit horizontalHandChanged(); } void SettingsCache::setInvertVerticalCoordinate(int _invertVerticalCoordinate) { - invertVerticalCoordinate = _invertVerticalCoordinate; + invertVerticalCoordinate = static_cast(_invertVerticalCoordinate); settings->setValue("table/invert_vertical", invertVerticalCoordinate); emit invertVerticalCoordinateChanged(); } @@ -492,32 +493,32 @@ void SettingsCache::setMinPlayersForMultiColumnLayout(int _minPlayersForMultiCol void SettingsCache::setTapAnimation(int _tapAnimation) { - tapAnimation = _tapAnimation; + tapAnimation = static_cast(_tapAnimation); settings->setValue("cards/tapanimation", tapAnimation); } void SettingsCache::setChatMention(int _chatMention) { - chatMention = _chatMention; + chatMention = static_cast(_chatMention); settings->setValue("chat/mention", chatMention); } void SettingsCache::setChatMentionCompleter(const int _enableMentionCompleter) { - chatMentionCompleter = _enableMentionCompleter; + chatMentionCompleter = (bool)_enableMentionCompleter; settings->setValue("chat/mentioncompleter", chatMentionCompleter); emit chatMentionCompleterChanged(); } void SettingsCache::setChatMentionForeground(int _chatMentionForeground) { - chatMentionForeground = _chatMentionForeground; + chatMentionForeground = static_cast(_chatMentionForeground); settings->setValue("chat/mentionforeground", chatMentionForeground); } void SettingsCache::setChatHighlightForeground(int _chatHighlightForeground) { - chatHighlightForeground = _chatHighlightForeground; + chatHighlightForeground = static_cast(_chatHighlightForeground); settings->setValue("chat/highlightforeground", chatHighlightForeground); } @@ -535,25 +536,25 @@ void SettingsCache::setChatHighlightColor(const QString &_chatHighlightColor) void SettingsCache::setZoneViewSortByName(int _zoneViewSortByName) { - zoneViewSortByName = _zoneViewSortByName; + zoneViewSortByName = static_cast(_zoneViewSortByName); settings->setValue("zoneview/sortbyname", zoneViewSortByName); } void SettingsCache::setZoneViewSortByType(int _zoneViewSortByType) { - zoneViewSortByType = _zoneViewSortByType; + zoneViewSortByType = static_cast(_zoneViewSortByType); settings->setValue("zoneview/sortbytype", zoneViewSortByType); } void SettingsCache::setZoneViewPileView(int _zoneViewPileView) { - zoneViewPileView = _zoneViewPileView; + zoneViewPileView = static_cast(_zoneViewPileView); settings->setValue("zoneview/pileview", zoneViewPileView); } void SettingsCache::setSoundEnabled(int _soundEnabled) { - soundEnabled = _soundEnabled; + soundEnabled = static_cast(_soundEnabled); settings->setValue("sound/enabled", soundEnabled); emit soundEnabledChanged(); } @@ -567,13 +568,13 @@ void SettingsCache::setSoundThemeName(const QString &_soundThemeName) void SettingsCache::setIgnoreUnregisteredUsers(int _ignoreUnregisteredUsers) { - ignoreUnregisteredUsers = _ignoreUnregisteredUsers; + ignoreUnregisteredUsers = static_cast(_ignoreUnregisteredUsers); settings->setValue("chat/ignore_unregistered", ignoreUnregisteredUsers); } void SettingsCache::setIgnoreUnregisteredUserMessages(int _ignoreUnregisteredUserMessages) { - ignoreUnregisteredUserMessages = _ignoreUnregisteredUserMessages; + ignoreUnregisteredUserMessages = static_cast(_ignoreUnregisteredUserMessages); settings->setValue("chat/ignore_unregistered_messages", ignoreUnregisteredUserMessages); } @@ -598,7 +599,7 @@ void SettingsCache::setPixmapCacheSize(const int _pixmapCacheSize) void SettingsCache::setClientID(QString _clientID) { - clientID = _clientID; + clientID = std::move(_clientID); settings->setValue("personal/clientid", clientID); } diff --git a/cockatrice/src/shortcutssettings.cpp b/cockatrice/src/shortcutssettings.cpp index c0d8eb6b..4296b687 100644 --- a/cockatrice/src/shortcutssettings.cpp +++ b/cockatrice/src/shortcutssettings.cpp @@ -150,10 +150,7 @@ bool ShortcutsSettings::isKeyAllowed(QString name, QString Sequences) << "Shift+S" << "Shift+Left" << "Shift+Right"); - if (forbiddenKeys.contains(checkSequence)) { - return false; - } - return true; + return !forbiddenKeys.contains(checkSequence); } bool ShortcutsSettings::isValid(QString name, QString Sequences) diff --git a/cockatrice/src/userconnection_information.cpp b/cockatrice/src/userconnection_information.cpp index 48b7f53b..16ee1417 100644 --- a/cockatrice/src/userconnection_information.cpp +++ b/cockatrice/src/userconnection_information.cpp @@ -1,10 +1,9 @@ #include "userconnection_information.h" #include "settingscache.h" #include +#include -UserConnection_Information::UserConnection_Information() -{ -} +UserConnection_Information::UserConnection_Information() = default; UserConnection_Information::UserConnection_Information(QString _saveName, QString _serverName, @@ -12,14 +11,14 @@ UserConnection_Information::UserConnection_Information(QString _saveName, QString _userName, QString _pass, bool _savePass) - : saveName(_saveName), server(_serverName), port(_portNum), username(_userName), password(_pass), - savePassword(_savePass) + : saveName(std::move(_saveName)), server(std::move(_serverName)), port(std::move(_portNum)), + username(std::move(_userName)), password(std::move(_pass)), savePassword(_savePass) { } -QMap UserConnection_Information::getServerInfo() +QMap> UserConnection_Information::getServerInfo() { - QMap serverList; + QMap> serverList; int size = settingsCache->servers().getValue("totalServers", "server", "server_details").toInt() + 1; @@ -38,7 +37,7 @@ QMap UserConnection_Information::getServerI settingsCache->servers().getValue(QString("savePassword%1").arg(i), "server", "server_details").toBool(); UserConnection_Information userInfo(saveName, serverName, portNum, userName, pass, savePass); - serverList.insert(saveName, userInfo); + serverList.insert(saveName, std::make_pair(serverName, userInfo)); } return serverList; @@ -76,7 +75,7 @@ QStringList UserConnection_Information::getServerInfo(const QString &find) break; } - if (!server.size()) + if (server.empty()) qDebug() << "There was a problem!"; return server; diff --git a/cockatrice/src/userconnection_information.h b/cockatrice/src/userconnection_information.h index 1dbf0e4a..ebb35c7a 100644 --- a/cockatrice/src/userconnection_information.h +++ b/cockatrice/src/userconnection_information.h @@ -16,35 +16,36 @@ private: QString username; QString password; bool savePassword; + bool isCustom; public: UserConnection_Information(); UserConnection_Information(QString, QString, QString, QString, QString, bool); - QString getSaveName() + QString getSaveName() const { return saveName; } - QString getServer() + QString getServer() const { return server; } - QString getPort() + QString getPort() const { return port; } - QString getUsername() + QString getUsername() const { return username; } - QString getPassword() + QString getPassword() const { return password; } - bool getSavePassword() + bool getSavePassword() const { return savePassword; } - QMap getServerInfo(); + QMap> getServerInfo(); QStringList getServerInfo(const QString &find); }; #endif diff --git a/cockatrice/src/window_main.cpp b/cockatrice/src/window_main.cpp index 854b5d6f..f7ca5924 100644 --- a/cockatrice/src/window_main.cpp +++ b/cockatrice/src/window_main.cpp @@ -183,11 +183,13 @@ void MainWindow::activateAccepted() void MainWindow::actConnect() { - auto *dlg = new DlgConnect(this); - connect(dlg, SIGNAL(sigStartForgotPasswordRequest()), this, SLOT(actForgotPasswordRequest())); - if (dlg->exec()) - client->connectToServer(dlg->getHost(), static_cast(dlg->getPort()), dlg->getPlayerName(), - dlg->getPassword()); + dlgConnect = new DlgConnect(this); + connect(dlgConnect, SIGNAL(sigStartForgotPasswordRequest()), this, SLOT(actForgotPasswordRequest())); + + if (dlgConnect->exec()) { + client->connectToServer(dlgConnect->getHost(), static_cast(dlgConnect->getPort()), + dlgConnect->getPlayerName(), dlgConnect->getPassword()); + } } void MainWindow::actRegister() @@ -233,7 +235,7 @@ void MainWindow::actSinglePlayer() Command_CreateGame createCommand; createCommand.set_max_players(static_cast(numberPlayers)); - mainClient->sendCommand(mainClient->prepareRoomCommand(createCommand, 0)); + mainClient->sendCommand(LocalClient::prepareRoomCommand(createCommand, 0)); } void MainWindow::actWatchReplay() @@ -251,7 +253,7 @@ void MainWindow::actWatchReplay() QByteArray buf = file.readAll(); file.close(); - auto *replay = new GameReplay; + replay = new GameReplay; replay->ParseFromArray(buf.data(), buf.size()); tabSupervisor->openReplay(replay); @@ -832,7 +834,7 @@ MainWindow::~MainWindow() void MainWindow::createTrayIcon() { - auto *trayIconMenu = new QMenu(this); + trayIconMenu = new QMenu(this); trayIconMenu->addAction(closeAction); trayIcon = new QSystemTrayIcon(this); @@ -1205,9 +1207,9 @@ int MainWindow::getNextCustomSetPrefix(QDir dataDir) void MainWindow::actManageSets() { - auto *w = new WndSets; - w->setWindowModality(Qt::WindowModal); - w->show(); + wndSets = new WndSets; + wndSets->setWindowModality(Qt::WindowModal); + wndSets->show(); } void MainWindow::actEditTokens() diff --git a/cockatrice/src/window_main.h b/cockatrice/src/window_main.h index 6122ba4b..f573978b 100644 --- a/cockatrice/src/window_main.h +++ b/cockatrice/src/window_main.h @@ -30,13 +30,17 @@ #include "abstractclient.h" #include "pb/response.pb.h" -class TabSupervisor; -class RemoteClient; +class DlgConnect; +class DlgViewLog; +class GameReplay; +class HandlePublicServers; class LocalClient; class LocalServer; -class ServerInfo_User; class QThread; -class DlgViewLog; +class RemoteClient; +class ServerInfo_User; +class TabSupervisor; +class WndSets; class MainWindow : public QMainWindow { @@ -114,34 +118,29 @@ private: }; QList tabMenus; - QMenu *cockatriceMenu, *dbMenu, *helpMenu; + QMenu *cockatriceMenu, *dbMenu, *helpMenu, *trayIconMenu; QAction *aConnect, *aDisconnect, *aSinglePlayer, *aWatchReplay, *aDeckEditor, *aFullScreen, *aSettings, *aExit, - *aAbout, *aTips, *aCheckCardUpdates, *aRegister, *aUpdate, *aViewLog; + *aAbout, *aTips, *aCheckCardUpdates, *aRegister, *aUpdate, *aViewLog, *closeAction; QAction *aManageSets, *aEditTokens, *aOpenCustomFolder, *aOpenCustomsetsFolder, *aAddCustomSet; TabSupervisor *tabSupervisor; - - QMenu *trayIconMenu; - - QAction *closeAction; - + WndSets *wndSets; RemoteClient *client; QThread *clientThread; - LocalServer *localServer; bool bHasActivated; - QMessageBox serverShutdownMessageBox; QProcess *cardUpdateProcess; - DlgViewLog *logviewDialog; + DlgConnect *dlgConnect; + GameReplay *replay; public: - MainWindow(QWidget *parent = 0); - ~MainWindow(); + explicit MainWindow(QWidget *parent = nullptr); + ~MainWindow() override; protected: - void closeEvent(QCloseEvent *event); - void changeEvent(QEvent *event); + void closeEvent(QCloseEvent *event) override; + void changeEvent(QEvent *event) override; QString extractInvalidUsernameMessage(QString &in); };