diff --git a/.clang-format b/.clang-format
index 1ef3ca6db..4be096155 100644
--- a/.clang-format
+++ b/.clang-format
@@ -26,6 +26,8 @@ PointerAlignment: Right
SortIncludes: true
IncludeBlocks: Regroup
StatementAttributeLikeMacros: [emit]
+# requires clang-format 15
+InsertBraces: true
# requires clang-format 16
# RemoveSemicolon: true
---
diff --git a/cockatrice/src/client/network/connection_controller/remote_connection_controller.cpp b/cockatrice/src/client/network/connection_controller/remote_connection_controller.cpp
index f517acdc4..75cedcafc 100644
--- a/cockatrice/src/client/network/connection_controller/remote_connection_controller.cpp
+++ b/cockatrice/src/client/network/connection_controller/remote_connection_controller.cpp
@@ -140,13 +140,15 @@ void ConnectionController::onConnectionClosedEvent(const Event_ConnectionClosed
}
case Event_ConnectionClosed::BANNED: {
reasonStr = tr("Banned by moderator");
- if (event.has_end_time())
+ if (event.has_end_time()) {
reasonStr.append(
"\n" + tr("Expected end time: %1").arg(QDateTime::fromSecsSinceEpoch(event.end_time()).toString()));
- else
+ } else {
reasonStr.append("\n" + tr("This ban lasts indefinitely."));
- if (event.has_reason_str())
+ }
+ if (event.has_reason_str()) {
reasonStr.append("\n\n" + QString::fromStdString(event.reason_str()));
+ }
break;
}
case Event_ConnectionClosed::SERVER_SHUTDOWN: {
@@ -240,8 +242,9 @@ void ConnectionController::onLoginError(int r,
QString bannedStr =
endTime ? tr("You are banned until %1.").arg(QDateTime::fromSecsSinceEpoch(endTime).toString())
: tr("You are banned indefinitely.");
- if (!reasonStr.isEmpty())
+ if (!reasonStr.isEmpty()) {
bannedStr.append("\n\n" + reasonStr);
+ }
QMessageBox::critical(dialogParent, tr("Error"), bannedStr);
break;
}
@@ -354,8 +357,9 @@ void ConnectionController::onRegisterError(int r, QString reasonStr, quint32 end
QString bannedStr =
endTime ? tr("You are banned until %1.").arg(QDateTime::fromSecsSinceEpoch(endTime).toString())
: tr("You are banned indefinitely.");
- if (!reasonStr.isEmpty())
+ if (!reasonStr.isEmpty()) {
bannedStr.append("\n\n" + reasonStr);
+ }
QMessageBox::critical(dialogParent, tr("Error"), bannedStr);
break;
}
@@ -545,8 +549,9 @@ QString ConnectionController::extractInvalidUsernameMessage(QString &in)
out +=
"
" + tr("can %1 contain numeric characters").arg((rules.at(4).toInt() > 0) ? "" : tr("NOT")) + "";
- if (rules.at(6).size() > 0)
+ if (rules.at(6).size() > 0) {
out += "" + tr("can contain the following punctuation: %1").arg(rules.at(6).toHtmlEscaped()) + "";
+ }
out += "" +
tr("first character can %1 be a punctuation mark").arg((rules.at(5).toInt() > 0) ? "" : tr("NOT")) +
@@ -566,10 +571,11 @@ QString ConnectionController::extractInvalidUsernameMessage(QString &in)
}
}
- if (rules.at(8).size() > 0)
+ if (rules.at(8).size() > 0) {
out += "" +
tr("can not match any of the following expressions: %1").arg(rules.at(8).toHtmlEscaped()) +
"";
+ }
}
out += "";
diff --git a/cockatrice/src/client/network/interfaces/tapped_out_interface.cpp b/cockatrice/src/client/network/interfaces/tapped_out_interface.cpp
index af377d176..cd39ea251 100644
--- a/cockatrice/src/client/network/interfaces/tapped_out_interface.cpp
+++ b/cockatrice/src/client/network/interfaces/tapped_out_interface.cpp
@@ -99,14 +99,16 @@ void TappedOutInterface::copyDeckSplitMainAndSide(const DeckList &source, DeckLi
{
auto copyMainOrSide = [this, &mainboard, &sideboard](const auto node, const auto card) {
CardInfoPtr dbCard = cardDatabase.query()->getCardInfo(card->getName());
- if (!dbCard || dbCard->getIsToken())
+ if (!dbCard || dbCard->getIsToken()) {
return;
+ }
DecklistCardNode *addedCard;
- if (node->getName() == DECK_ZONE_SIDE)
+ if (node->getName() == DECK_ZONE_SIDE) {
addedCard = sideboard.addCard(card->getName(), node->getName(), -1);
- else
+ } else {
addedCard = mainboard.addCard(card->getName(), node->getName(), -1);
+ }
addedCard->setNumber(card->getNumber());
};
diff --git a/cockatrice/src/client/network/update/client/release_channel.cpp b/cockatrice/src/client/network/update/client/release_channel.cpp
index 9edfe7caf..260167bc8 100644
--- a/cockatrice/src/client/network/update/client/release_channel.cpp
+++ b/cockatrice/src/client/network/update/client/release_channel.cpp
@@ -129,8 +129,9 @@ void StableReleaseChannel::releaseListFinished()
return;
}
- if (!lastRelease)
+ if (!lastRelease) {
lastRelease = new Release;
+ }
lastRelease->setName(resultMap["name"].toString());
lastRelease->setDescriptionUrl(resultMap["html_url"].toString());
@@ -246,8 +247,9 @@ void BetaReleaseChannel::releaseListFinished()
return;
}
- if (lastRelease == nullptr)
+ if (lastRelease == nullptr) {
lastRelease = new Release;
+ }
lastRelease->setCommitHash(resultMap["target_commitish"].toString());
lastRelease->setPublishDate(resultMap["published_at"].toDate());
diff --git a/cockatrice/src/client/network/update/client/update_downloader.cpp b/cockatrice/src/client/network/update/client/update_downloader.cpp
index c0f3e945c..a71bcf8f8 100644
--- a/cockatrice/src/client/network/update/client/update_downloader.cpp
+++ b/cockatrice/src/client/network/update/client/update_downloader.cpp
@@ -10,8 +10,9 @@ UpdateDownloader::UpdateDownloader(QObject *parent) : QObject(parent), response(
void UpdateDownloader::beginDownload(QUrl downloadUrl)
{
// Save the original URL because we need it for the filename
- if (originalUrl.isEmpty())
+ if (originalUrl.isEmpty()) {
originalUrl = downloadUrl;
+ }
response = netMan->get(QNetworkRequest(downloadUrl));
connect(response, &QNetworkReply::finished, this, &UpdateDownloader::fileFinished);
@@ -21,8 +22,9 @@ void UpdateDownloader::beginDownload(QUrl downloadUrl)
void UpdateDownloader::downloadError(QNetworkReply::NetworkError)
{
- if (response == nullptr)
+ if (response == nullptr) {
return;
+ }
emit error(response->errorString().toUtf8());
}
diff --git a/cockatrice/src/client/settings/cache_settings.cpp b/cockatrice/src/client/settings/cache_settings.cpp
index 9a46c6426..779522b72 100644
--- a/cockatrice/src/client/settings/cache_settings.cpp
+++ b/cockatrice/src/client/settings/cache_settings.cpp
@@ -24,10 +24,11 @@ SettingsCache &SettingsCache::instance()
QString SettingsCache::getDataPath()
{
- if (isPortableBuild)
+ if (isPortableBuild) {
return qApp->applicationDirPath() + "/data";
- else
+ } else {
return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
+ }
}
QString SettingsCache::getSettingsPath()
@@ -37,10 +38,11 @@ QString SettingsCache::getSettingsPath()
QString SettingsCache::getCachePath() const
{
- if (isPortableBuild)
+ if (isPortableBuild) {
return qApp->applicationDirPath() + "/cache";
- else
+ } else {
return QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
+ }
}
QString SettingsCache::getNetworkCachePath() const
@@ -50,14 +52,17 @@ QString SettingsCache::getNetworkCachePath() const
void SettingsCache::translateLegacySettings()
{
- if (isPortableBuild)
+ if (isPortableBuild) {
return;
+ }
// Layouts
QFile layoutFile(getSettingsPath() + "layouts/deckLayout.ini");
- if (layoutFile.exists())
- if (layoutFile.copy(getSettingsPath() + "layouts.ini"))
+ if (layoutFile.exists()) {
+ if (layoutFile.copy(getSettingsPath() + "layouts.ini")) {
layoutFile.remove();
+ }
+ }
QStringList usedKeys;
QSettings legacySetting;
@@ -116,10 +121,11 @@ void SettingsCache::translateLegacySettings()
gameFilters().setHideIgnoredUserGames(legacySetting.value("hide_ignored_user_games").toBool());
gameFilters().setMinPlayers(legacySetting.value("min_players").toInt());
- if (legacySetting.value("max_players").toInt() > 1)
+ if (legacySetting.value("max_players").toInt() > 1) {
gameFilters().setMaxPlayers(legacySetting.value("max_players").toInt());
- else
+ } else {
gameFilters().setMaxPlayers(99); // This prevents a bug where no games will show if max was not set before
+ }
QStringList allFilters = legacySetting.allKeys();
for (int i = 0; i < allFilters.size(); ++i) {
@@ -135,8 +141,9 @@ void SettingsCache::translateLegacySettings()
QStringList allLegacyKeys = legacySetting.allKeys();
for (int i = 0; i < allLegacyKeys.size(); ++i) {
- if (usedKeys.contains(allLegacyKeys.at(i)))
+ if (usedKeys.contains(allLegacyKeys.at(i))) {
continue;
+ }
settings->setValue(allLegacyKeys.at(i), legacySetting.value(allLegacyKeys.at(i)));
}
}
@@ -147,8 +154,9 @@ QString SettingsCache::getSafeConfigPath(QString configEntry, QString defaultPat
// if the config settings is empty or refers to a not-existing folder,
// ensure that the defaut path exists and return it
if (tmp.isEmpty() || !QDir(tmp).exists()) {
- if (!QDir().mkpath(defaultPath))
+ if (!QDir().mkpath(defaultPath)) {
qCInfo(SettingsCacheLog) << "[SettingsCache] Could not create folder:" << defaultPath;
+ }
tmp = defaultPath;
}
return tmp;
@@ -159,8 +167,9 @@ QString SettingsCache::getSafeConfigFilePath(QString configEntry, QString defaul
QString tmp = settings->value(configEntry).toString();
// if the config settings is empty or refers to a not-existing file,
// return the default Path
- if (!QFile::exists(tmp) || tmp.isEmpty())
+ if (!QFile::exists(tmp) || tmp.isEmpty()) {
tmp = std::move(defaultPath);
+ }
return tmp;
}
@@ -168,8 +177,9 @@ SettingsCache::SettingsCache()
{
// first, figure out if we are running in portable mode
isPortableBuild = QFile::exists(qApp->applicationDirPath() + "/portable.dat");
- if (isPortableBuild)
+ if (isPortableBuild) {
qCInfo(SettingsCacheLog) << "Portable mode enabled";
+ }
// define a dummy context that will be used where needed
QString dummy = QT_TRANSLATE_NOOP("i18n", "English");
@@ -189,8 +199,9 @@ SettingsCache::SettingsCache()
cardCounterSettings = new CardCounterSettings(settingsPath, this);
- if (!QFile(settingsPath + "global.ini").exists())
+ if (!QFile(settingsPath + "global.ini").exists()) {
translateLegacySettings();
+ }
// updates - don't reorder them or their index in the settings won't match
// append channels one by one, or msvc will add them in the wrong order.
@@ -257,11 +268,13 @@ SettingsCache::SettingsCache()
settings->setValue("personal/pixmapCacheSize", pixmapCacheSize);
settings->setValue("personal/picturedownloadhq", false);
settings->setValue("revert/pixmapCacheSize", true);
- } else
+ } else {
pixmapCacheSize = settings->value("personal/pixmapCacheSize", PIXMAPCACHE_SIZE_DEFAULT).toInt();
+ }
// sanity check
- if (pixmapCacheSize < PIXMAPCACHE_SIZE_MIN || pixmapCacheSize > PIXMAPCACHE_SIZE_MAX)
+ if (pixmapCacheSize < PIXMAPCACHE_SIZE_MIN || pixmapCacheSize > PIXMAPCACHE_SIZE_MAX) {
pixmapCacheSize = PIXMAPCACHE_SIZE_DEFAULT;
+ }
networkCacheSize = settings->value("personal/networkCacheSize", NETWORK_CACHE_SIZE_DEFAULT).toInt();
redirectCacheTtl = settings->value("personal/redirectCacheTtl", NETWORK_REDIRECT_CACHE_TTL_DEFAULT).toInt();
@@ -770,8 +783,9 @@ void SettingsCache::setPrintingSelectorCardSize(int _printingSelectorCardSize)
void SettingsCache::setIncludeRebalancedCards(bool _includeRebalancedCards)
{
- if (includeRebalancedCards == _includeRebalancedCards)
+ if (includeRebalancedCards == _includeRebalancedCards) {
return;
+ }
includeRebalancedCards = _includeRebalancedCards;
settings->setValue("cards/includerebalancedcards", includeRebalancedCards);
@@ -1310,8 +1324,9 @@ void SettingsCache::setMaxFontSize(int _max)
void SettingsCache::setRoundCardCorners(bool _roundCardCorners)
{
- if (_roundCardCorners == roundCardCorners)
+ if (_roundCardCorners == roundCardCorners) {
return;
+ }
roundCardCorners = _roundCardCorners;
settings->setValue("cards/roundcardcorners", _roundCardCorners);
diff --git a/cockatrice/src/client/settings/card_counter_settings.cpp b/cockatrice/src/client/settings/card_counter_settings.cpp
index 399365c99..662ae0c7d 100644
--- a/cockatrice/src/client/settings/card_counter_settings.cpp
+++ b/cockatrice/src/client/settings/card_counter_settings.cpp
@@ -15,8 +15,9 @@ void CardCounterSettings::setColor(int counterId, const QColor &color)
QString key = QString("cards/counters/%1/color").arg(counterId);
- if (settings.value(key).value() == color)
+ if (settings.value(key).value() == color) {
return;
+ }
settings.setValue(key, color);
emit colorChanged(counterId, color);
diff --git a/cockatrice/src/client/sound_engine.cpp b/cockatrice/src/client/sound_engine.cpp
index 31cb2a35e..e592b5ea0 100644
--- a/cockatrice/src/client/sound_engine.cpp
+++ b/cockatrice/src/client/sound_engine.cpp
@@ -105,8 +105,9 @@ QStringMap &SoundEngine::getAvailableThemes()
dir.setPath(SettingsCache::instance().getDataPath() + "/sounds");
for (const QString &themeName : dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) {
- if (!availableThemes.contains(themeName))
+ if (!availableThemes.contains(themeName)) {
availableThemes.insert(themeName, dir.absoluteFilePath(themeName));
+ }
}
// load themes from cockatrice system dir
@@ -121,8 +122,9 @@ QStringMap &SoundEngine::getAvailableThemes()
);
for (const QString &themeName : dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) {
- if (!availableThemes.contains(themeName))
+ if (!availableThemes.contains(themeName)) {
availableThemes.insert(themeName, dir.absoluteFilePath(themeName));
+ }
}
return availableThemes;
diff --git a/cockatrice/src/filters/deck_filter_string.cpp b/cockatrice/src/filters/deck_filter_string.cpp
index 6b671831d..dd873cfa5 100644
--- a/cockatrice/src/filters/deck_filter_string.cpp
+++ b/cockatrice/src/filters/deck_filter_string.cpp
@@ -88,20 +88,27 @@ static void setupParserRules()
const auto arg = std::any_cast(sv[1]);
const auto op = std::any_cast(sv[0]);
- if (op == ">")
+ if (op == ">") {
return [=](const int s) { return s > arg; };
- if (op == ">=")
+ }
+ if (op == ">=") {
return [=](const int s) { return s >= arg; };
- if (op == "<")
+ }
+ if (op == "<") {
return [=](const int s) { return s < arg; };
- if (op == "<=")
+ }
+ if (op == "<=") {
return [=](const int s) { return s <= arg; };
- if (op == "=")
+ }
+ if (op == "=") {
return [=](const int s) { return s == arg; };
- if (op == ":")
+ }
+ if (op == ":") {
return [=](const int s) { return s == arg; };
- if (op == "!=")
+ }
+ if (op == "!=") {
return [=](const int s) { return s != arg; };
+ }
return [](int) { return false; };
};
diff --git a/cockatrice/src/filters/filter_builder.cpp b/cockatrice/src/filters/filter_builder.cpp
index 7178ce95a..785f753e7 100644
--- a/cockatrice/src/filters/filter_builder.cpp
+++ b/cockatrice/src/filters/filter_builder.cpp
@@ -11,13 +11,15 @@ FilterBuilder::FilterBuilder(QWidget *parent) : QWidget(parent)
{
filterCombo = new QComboBox;
filterCombo->setObjectName("filterCombo");
- for (int i = 0; i < CardFilter::AttrEnd; i++)
+ for (int i = 0; i < CardFilter::AttrEnd; i++) {
filterCombo->addItem(CardFilter::attrName(static_cast(i)), QVariant(i));
+ }
typeCombo = new QComboBox;
typeCombo->setObjectName("typeCombo");
- for (int i = 0; i < CardFilter::TypeEnd; i++)
+ for (int i = 0; i < CardFilter::TypeEnd; i++) {
typeCombo->addItem(CardFilter::typeName(static_cast(i)), QVariant(i));
+ }
QPushButton *ok = new QPushButton(QPixmap("theme:icons/increment"), QString());
ok->setObjectName("ok");
@@ -53,8 +55,9 @@ FilterBuilder::~FilterBuilder()
void FilterBuilder::destroyFilter()
{
- if (fltr)
+ if (fltr) {
delete fltr;
+ }
}
static int comboCurrentIntData(const QComboBox *combo)
@@ -67,8 +70,9 @@ void FilterBuilder::emit_add()
QString txt;
txt = edit->text();
- if (txt.length() < 1)
+ if (txt.length() < 1) {
return;
+ }
destroyFilter();
fltr = new CardFilter(txt, static_cast(comboCurrentIntData(typeCombo)),
diff --git a/cockatrice/src/filters/filter_tree_model.cpp b/cockatrice/src/filters/filter_tree_model.cpp
index f0a02ec79..33b54530e 100644
--- a/cockatrice/src/filters/filter_tree_model.cpp
+++ b/cockatrice/src/filters/filter_tree_model.cpp
@@ -23,8 +23,9 @@ void FilterTreeModel::proxyBeginInsertRow(const FilterTreeNode *node, int i)
int idx;
idx = node->index();
- if (idx >= 0)
+ if (idx >= 0) {
beginInsertRows(createIndex(idx, 0, (void *)node), i, i);
+ }
}
void FilterTreeModel::proxyEndInsertRow(const FilterTreeNode *node, int)
@@ -32,8 +33,9 @@ void FilterTreeModel::proxyEndInsertRow(const FilterTreeNode *node, int)
int idx;
idx = node->index();
- if (idx >= 0)
+ if (idx >= 0) {
endInsertRows();
+ }
}
void FilterTreeModel::proxyBeginRemoveRow(const FilterTreeNode *node, int i)
@@ -41,8 +43,9 @@ void FilterTreeModel::proxyBeginRemoveRow(const FilterTreeNode *node, int i)
int idx;
idx = node->index();
- if (idx >= 0)
+ if (idx >= 0) {
beginRemoveRows(createIndex(idx, 0, (void *)node), i, i);
+ }
}
void FilterTreeModel::proxyEndRemoveRow(const FilterTreeNode *node, int)
@@ -50,8 +53,9 @@ void FilterTreeModel::proxyEndRemoveRow(const FilterTreeNode *node, int)
int idx;
idx = node->index();
- if (idx >= 0)
+ if (idx >= 0) {
endRemoveRows();
+ }
}
FilterTreeNode *FilterTreeModel::indexToNode(const QModelIndex &idx) const
@@ -59,12 +63,14 @@ FilterTreeNode *FilterTreeModel::indexToNode(const QModelIndex &idx) const
void *ip;
FilterTreeNode *node;
- if (!idx.isValid())
+ if (!idx.isValid()) {
return fTree;
+ }
ip = idx.internalPointer();
- if (ip == NULL)
+ if (ip == NULL) {
return fTree;
+ }
node = static_cast(ip);
return node;
@@ -145,14 +151,16 @@ int FilterTreeModel::rowCount(const QModelIndex &parent) const
const FilterTreeNode *node;
int result;
- if (parent.column() > 0)
+ if (parent.column() > 0) {
return 0;
+ }
node = indexToNode(parent);
- if (node)
+ if (node) {
result = node->childCount();
- else
+ } else {
result = 0;
+ }
return result;
}
@@ -166,14 +174,17 @@ QVariant FilterTreeModel::data(const QModelIndex &index, int role) const
{
const FilterTreeNode *node;
- if (!index.isValid())
+ if (!index.isValid()) {
return QVariant();
- if (index.column() >= columnCount())
+ }
+ if (index.column() >= columnCount()) {
return QVariant();
+ }
node = indexToNode(index);
- if (node == NULL)
+ if (node == NULL) {
return QVariant();
+ }
switch (role) {
case Qt::FontRole:
@@ -190,10 +201,11 @@ QVariant FilterTreeModel::data(const QModelIndex &index, int role) const
case Qt::WhatsThisRole:
return node->text();
case Qt::CheckStateRole:
- if (node->isEnabled())
+ if (node->isEnabled()) {
return Qt::Checked;
- else
+ } else {
return Qt::Unchecked;
+ }
default:
return QVariant();
}
@@ -205,22 +217,27 @@ bool FilterTreeModel::setData(const QModelIndex &index, const QVariant &value, i
{
FilterTreeNode *node;
- if (!index.isValid())
+ if (!index.isValid()) {
return false;
- if (index.column() >= columnCount())
+ }
+ if (index.column() >= columnCount()) {
return false;
- if (role != Qt::CheckStateRole)
+ }
+ if (role != Qt::CheckStateRole) {
return false;
+ }
node = indexToNode(index);
- if (node == NULL || node == fTree)
+ if (node == NULL || node == fTree) {
return false;
+ }
Qt::CheckState state = static_cast(value.toInt());
- if (state == Qt::Checked)
+ if (state == Qt::Checked) {
node->enable();
- else
+ } else {
node->disable();
+ }
emit dataChanged(index, index);
return true;
@@ -231,16 +248,19 @@ Qt::ItemFlags FilterTreeModel::flags(const QModelIndex &index) const
const FilterTreeNode *node;
Qt::ItemFlags result;
- if (!index.isValid())
+ if (!index.isValid()) {
return Qt::NoItemFlags;
+ }
node = indexToNode(index);
- if (node == NULL)
+ if (node == NULL) {
return Qt::NoItemFlags;
+ }
result = Qt::ItemIsEnabled;
- if (node == fTree)
+ if (node == fTree) {
return result;
+ }
result |= Qt::ItemIsSelectable;
result |= Qt::ItemIsUserCheckable;
@@ -252,8 +272,9 @@ QModelIndex FilterTreeModel::nodeIndex(const FilterTreeNode *node, int row, int
{
FilterTreeNode *child;
- if (column > 0 || row >= node->childCount())
+ if (column > 0 || row >= node->childCount()) {
return QModelIndex();
+ }
child = node->nodeAt(row);
return createIndex(row, column, child);
@@ -263,12 +284,14 @@ QModelIndex FilterTreeModel::index(int row, int column, const QModelIndex &paren
{
const FilterTreeNode *node;
- if (!hasIndex(row, column, parent))
+ if (!hasIndex(row, column, parent)) {
return QModelIndex();
+ }
node = indexToNode(parent);
- if (node == NULL)
+ if (node == NULL) {
return QModelIndex();
+ }
return nodeIndex(node, row, column);
}
@@ -279,18 +302,21 @@ QModelIndex FilterTreeModel::parent(const QModelIndex &ind) const
FilterTreeNode *parent;
QModelIndex idx;
- if (!ind.isValid())
+ if (!ind.isValid()) {
return QModelIndex();
+ }
node = indexToNode(ind);
- if (node == NULL || node == fTree)
+ if (node == NULL || node == fTree) {
return QModelIndex();
+ }
parent = node->parent();
if (parent) {
int row = parent->index();
- if (row < 0)
+ if (row < 0) {
return QModelIndex();
+ }
idx = createIndex(row, 0, parent);
return idx;
}
@@ -304,18 +330,22 @@ bool FilterTreeModel::removeRows(int row, int count, const QModelIndex &parent)
int i, last;
last = row + count - 1;
- if (!parent.isValid() || count < 1 || row < 0)
+ if (!parent.isValid() || count < 1 || row < 0) {
return false;
+ }
node = indexToNode(parent);
- if (node == NULL || last >= node->childCount())
+ if (node == NULL || last >= node->childCount()) {
return false;
+ }
- for (i = 0; i < count; i++)
+ for (i = 0; i < count; i++) {
node->deleteAt(row);
+ }
- if (node != fTree && node->childCount() < 1)
+ if (node != fTree && node->childCount() < 1) {
return removeRow(parent.row(), parent.parent());
+ }
return true;
}
diff --git a/cockatrice/src/game/abstract_game.cpp b/cockatrice/src/game/abstract_game.cpp
index 9216f9174..8c777d587 100644
--- a/cockatrice/src/game/abstract_game.cpp
+++ b/cockatrice/src/game/abstract_game.cpp
@@ -24,10 +24,11 @@ AbstractClient *AbstractGame::getClientForPlayer(int playerId) const
}
return gameState->getClients().at(playerId);
- } else if (gameState->getClients().isEmpty())
+ } else if (gameState->getClients().isEmpty()) {
return nullptr;
- else
+ } else {
return gameState->getClients().first();
+ }
}
void AbstractGame::loadReplay(GameReplay *replay)
@@ -44,12 +45,14 @@ void AbstractGame::setActiveCard(CardItem *card)
CardItem *AbstractGame::getCard(int playerId, const QString &zoneName, int cardId) const
{
Player *player = playerManager->getPlayer(playerId);
- if (!player)
+ if (!player) {
return nullptr;
+ }
CardZoneLogic *zone = player->getZones().value(zoneName, 0);
- if (!zone)
+ if (!zone) {
return nullptr;
+ }
return zone->getCard(cardId);
}
\ No newline at end of file
diff --git a/cockatrice/src/game/board/abstract_card_drag_item.cpp b/cockatrice/src/game/board/abstract_card_drag_item.cpp
index 8e3def4ca..026efd60d 100644
--- a/cockatrice/src/game/board/abstract_card_drag_item.cpp
+++ b/cockatrice/src/game/board/abstract_card_drag_item.cpp
@@ -25,11 +25,12 @@ AbstractCardDragItem::AbstractCardDragItem(AbstractCardItem *_item,
setCursor(Qt::ClosedHandCursor);
setZValue(ZValues::DRAG_ITEM);
}
- if (item->getTapped())
+ if (item->getTapped()) {
setTransform(QTransform()
.translate(CardDimensions::WIDTH_HALF_F, CardDimensions::HEIGHT_HALF_F)
.rotate(90)
.translate(-CardDimensions::WIDTH_HALF_F, -CardDimensions::HEIGHT_HALF_F));
+ }
setCacheMode(DeviceCoordinateCache);
diff --git a/cockatrice/src/game/board/abstract_card_item.cpp b/cockatrice/src/game/board/abstract_card_item.cpp
index a519fa4b6..d9458990b 100644
--- a/cockatrice/src/game/board/abstract_card_item.cpp
+++ b/cockatrice/src/game/board/abstract_card_item.cpp
@@ -88,8 +88,9 @@ void AbstractCardItem::setRealZValue(qreal _zValue)
// During hover, zValue is overridden to HOVERED_CARD. Layout operations
// like reorganizeCards() call setRealZValue() on all cards including the
// hovered one — skip setZValue() here to avoid clobbering the override.
- if (!isHovered)
+ if (!isHovered) {
setZValue(_zValue);
+ }
}
QSizeF AbstractCardItem::getTranslatedSize(QPainter *painter) const
@@ -130,8 +131,9 @@ void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedS
// don't even spend time trying to load the picture if our size is too small
if (translatedSize.width() > 10) {
CardPictureLoader::getPixmap(translatedPixmap, exactCard, translatedSize.toSize());
- if (translatedPixmap.isNull())
+ if (translatedPixmap.isNull()) {
paintImage = false;
+ }
} else {
paintImage = false;
}
@@ -156,9 +158,9 @@ void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedS
painter->setBackground(Qt::black);
painter->setBackgroundMode(Qt::OpaqueMode);
QString nameStr;
- if (facedown)
+ if (facedown) {
nameStr = "# " + QString::number(id);
- else {
+ } else {
QString prefix = "";
if (SettingsCache::instance().debug().getShowCardId()) {
prefix = "#" + QString::number(id) + " ";
@@ -185,10 +187,12 @@ void AbstractCardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *
if (isSelected() || isHovered) {
QPen pen;
- if (isHovered)
+ if (isHovered) {
pen.setColor(Qt::yellow);
- if (isSelected())
+ }
+ if (isSelected()) {
pen.setColor(Qt::red);
+ }
pen.setWidth(0); // Cosmetic pen
painter->setPen(pen);
painter->drawPath(shape());
@@ -214,8 +218,9 @@ void AbstractCardItem::setCardRef(const CardRef &_cardRef)
void AbstractCardItem::setHovered(bool _hovered)
{
- if (isHovered == _hovered)
+ if (isHovered == _hovered) {
return;
+ }
if (_hovered) {
processHoverEvent();
@@ -277,13 +282,14 @@ void AbstractCardItem::cacheBgColor()
void AbstractCardItem::setTapped(bool _tapped, bool canAnimate)
{
- if (tapped == _tapped)
+ if (tapped == _tapped) {
return;
+ }
tapped = _tapped;
- if (SettingsCache::instance().getTapAnimation() && canAnimate)
+ if (SettingsCache::instance().getTapAnimation() && canAnimate) {
static_cast(scene())->registerAnimationItem(this);
- else {
+ } else {
tapAngle = tapped ? 90 : 0;
setTransform(QTransform()
.translate(CardDimensions::WIDTH_HALF_F, CardDimensions::HEIGHT_HALF_F)
@@ -309,17 +315,19 @@ void AbstractCardItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
scene()->clearSelection();
setSelected(true);
}
- if (event->button() == Qt::LeftButton)
+ if (event->button() == Qt::LeftButton) {
setCursor(Qt::ClosedHandCursor);
- else if (event->button() == Qt::MiddleButton)
+ } else if (event->button() == Qt::MiddleButton) {
emit showCardInfoPopup(event->screenPos(), cardRef);
+ }
event->accept();
}
void AbstractCardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
- if (event->button() == Qt::MiddleButton)
+ if (event->button() == Qt::MiddleButton) {
emit deleteCardInfoPopup(cardRef.name);
+ }
// This function ensures the parent function doesn't mess around with our selection.
event->accept();
@@ -335,6 +343,7 @@ QVariant AbstractCardItem::itemChange(QGraphicsItem::GraphicsItemChange change,
if (change == ItemSelectedHasChanged) {
update();
return value;
- } else
+ } else {
return ArrowTarget::itemChange(change, value);
+ }
}
diff --git a/cockatrice/src/game/board/abstract_counter.cpp b/cockatrice/src/game/board/abstract_counter.cpp
index 08d19ec8a..ef3efb539 100644
--- a/cockatrice/src/game/board/abstract_counter.cpp
+++ b/cockatrice/src/game/board/abstract_counter.cpp
@@ -43,10 +43,11 @@ AbstractCounter::AbstractCounter(Player *_player,
menu->addSeparator();
} else {
QAction *aIncrement = new QAction(QString(i < 0 ? "%1" : "+%1").arg(i), this);
- if (i == -1)
+ if (i == -1) {
aDec = aIncrement;
- else if (i == 1)
+ } else if (i == 1) {
aInc = aIncrement;
+ }
aIncrement->setData(i);
connect(aIncrement, &QAction::triggered, this, &AbstractCounter::incrementCounter);
menu->addAction(aIncrement);
@@ -69,10 +70,11 @@ AbstractCounter::~AbstractCounter()
void AbstractCounter::delCounter()
{
- if (dialogSemaphore)
+ if (dialogSemaphore) {
deleteAfterDialog = true;
- else
+ } else {
deleteLater();
+ }
}
void AbstractCounter::retranslateUi()
@@ -136,8 +138,9 @@ void AbstractCounter::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (isUnderMouse() && player->getPlayerInfo()->getLocalOrJudge()) {
if (event->button() == Qt::MiddleButton || (QApplication::keyboardModifiers() & Qt::ShiftModifier)) {
- if (menu)
+ if (menu) {
menu->exec(event->screenPos());
+ }
event->accept();
} else if (event->button() == Qt::LeftButton) {
Command_IncCounter cmd;
@@ -152,8 +155,9 @@ void AbstractCounter::mousePressEvent(QGraphicsSceneMouseEvent *event)
player->getPlayerActions()->sendGameCommand(cmd);
event->accept();
}
- } else
+ } else {
event->ignore();
+ }
}
void AbstractCounter::hoverEnterEvent(QGraphicsSceneHoverEvent * /*event*/)
@@ -189,8 +193,9 @@ void AbstractCounter::setCounter()
}
dialogSemaphore = false;
- if (!ok)
+ if (!ok) {
return;
+ }
Expression exp(value);
int newValue = static_cast(exp.parse(dialog.textValue()));
@@ -231,8 +236,9 @@ void AbstractCounterDialog::changeValue(int diff)
{
bool ok;
int curValue = textValue().toInt(&ok);
- if (!ok)
+ if (!ok) {
return;
+ }
curValue += diff;
setTextValue(QString::number(curValue));
}
diff --git a/cockatrice/src/game/board/arrow_item.cpp b/cockatrice/src/game/board/arrow_item.cpp
index 60585a774..53d8ea33e 100644
--- a/cockatrice/src/game/board/arrow_item.cpp
+++ b/cockatrice/src/game/board/arrow_item.cpp
@@ -27,13 +27,16 @@ ArrowItem::ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTar
{
setZValue(ZValues::ARROWS);
- if (startItem)
+ if (startItem) {
startItem->addArrowFrom(this);
- if (targetItem)
+ }
+ if (targetItem) {
targetItem->addArrowTo(this);
+ }
- if (startItem && targetItem)
+ if (startItem && targetItem) {
updatePath();
+ }
}
ArrowItem::~ArrowItem()
@@ -59,8 +62,9 @@ void ArrowItem::delArrow()
void ArrowItem::updatePath()
{
- if (!targetItem)
+ if (!targetItem) {
return;
+ }
QPointF endPoint = targetItem->mapToScene(
QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2));
@@ -75,8 +79,9 @@ void ArrowItem::updatePath(const QPointF &endPoint)
headWidth / qPow(2, 0.5); // aka headWidth / sqrt (2) but this produces a compile error with MSVC++
const double phi = 15;
- if (!startItem)
+ if (!startItem) {
return;
+ }
QPointF startPoint =
startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2));
@@ -84,9 +89,9 @@ void ArrowItem::updatePath(const QPointF &endPoint)
qreal lineLength = line.length();
prepareGeometryChange();
- if (lineLength < 30)
+ if (lineLength < 30) {
path = QPainterPath();
- else {
+ } else {
QPointF c(lineLength / 2, qTan(phi * M_PI / 180) * lineLength);
QPainterPath centerLine;
@@ -123,10 +128,11 @@ void ArrowItem::updatePath(const QPointF &endPoint)
void ArrowItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
{
QColor paintColor(color);
- if (fullColor)
+ if (fullColor) {
paintColor.setAlpha(200);
- else
+ } else {
paintColor.setAlpha(150);
+ }
painter->setBrush(paintColor);
painter->drawPath(path);
}
@@ -168,8 +174,9 @@ void ArrowDragItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
// This ensures that if a mouse move event happens after a call to delArrow(),
// the event will be discarded as it would create some stray pointers.
- if (targetLocked || !startItem)
+ if (targetLocked || !startItem) {
return;
+ }
QPointF endPos = event->scenePos();
@@ -213,8 +220,9 @@ void ArrowDragItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
void ArrowDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
- if (!startItem)
+ if (!startItem) {
return;
+ }
if (targetItem && (targetItem != startItem)) {
CardZoneLogic *startZone = static_cast(startItem)->getZone();
@@ -246,10 +254,11 @@ void ArrowDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
bool playToStack = SettingsCache::instance().getPlayToStack();
if (ci && ((!playToStack && ci->getUiAttributes().tableRow == 3) ||
(playToStack && ci->getUiAttributes().tableRow != 0 &&
- startCard->getZone()->getName() != ZoneNames::STACK)))
+ startCard->getZone()->getName() != ZoneNames::STACK))) {
cmd.set_start_zone(ZoneNames::STACK);
- else
+ } else {
cmd.set_start_zone(playToStack ? ZoneNames::STACK : ZoneNames::TABLE);
+ }
}
if (deleteInPhase != 0) {
@@ -277,8 +286,9 @@ void ArrowAttachItem::addChildArrow(ArrowAttachItem *childArrow)
void ArrowAttachItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
- if (targetLocked || !startItem)
+ if (targetLocked || !startItem) {
return;
+ }
QPointF endPos = event->scenePos();
@@ -343,8 +353,9 @@ void ArrowAttachItem::attachCards(CardItem *startCard, const CardItem *targetCar
void ArrowAttachItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
- if (!startItem)
+ if (!startItem) {
return;
+ }
// Attaching could move startItem under the current cursor position, causing all children to retarget to it right
// before they are processed. Prevent that.
diff --git a/cockatrice/src/game/board/arrow_target.cpp b/cockatrice/src/game/board/arrow_target.cpp
index 2dbd913fa..2c7cdfec8 100644
--- a/cockatrice/src/game/board/arrow_target.cpp
+++ b/cockatrice/src/game/board/arrow_target.cpp
@@ -30,11 +30,13 @@ void ArrowTarget::setBeingPointedAt(bool _beingPointedAt)
QVariant ArrowTarget::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{
if (change == ItemScenePositionHasChanged && scene()) {
- for (auto *arrow : arrowsFrom)
+ for (auto *arrow : arrowsFrom) {
arrow->updatePath();
+ }
- for (auto *arrow : arrowsTo)
+ for (auto *arrow : arrowsTo) {
arrow->updatePath();
+ }
}
return QGraphicsItem::itemChange(change, value);
diff --git a/cockatrice/src/game/board/card_drag_item.cpp b/cockatrice/src/game/board/card_drag_item.cpp
index 5ae56ccba..49467c5c9 100644
--- a/cockatrice/src/game/board/card_drag_item.cpp
+++ b/cockatrice/src/game/board/card_drag_item.cpp
@@ -24,8 +24,9 @@ void CardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti
{
AbstractCardDragItem::paint(painter, option, widget);
- if (occupied)
+ if (occupied) {
painter->fillPath(shape(), QColor(200, 0, 0, 100));
+ }
}
void CardDragItem::updatePosition(const QPointF &cursorScenePos)
@@ -38,16 +39,19 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos)
ZoneViewZone *zoneViewZone = 0;
for (int i = colliding.size() - 1; i >= 0; i--) {
CardZone *temp = qgraphicsitem_cast(colliding.at(i));
- if (!cardZone)
+ if (!cardZone) {
cardZone = temp;
- if (!zoneViewZone)
+ }
+ if (!zoneViewZone) {
zoneViewZone = qobject_cast(temp);
+ }
}
CardZone *cursorZone = 0;
- if (zoneViewZone)
+ if (zoneViewZone) {
cursorZone = zoneViewZone;
- else if (cardZone)
+ } else if (cardZone) {
cursorZone = cardZone;
+ }
// Always update the current zone, even if its null, to cancel the drag
// instead of dropping cards into an non-intuitive location.
@@ -59,8 +63,9 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos)
QPointF newPos = cursorScenePos - hotSpot;
if (newPos != pos()) {
- for (int i = 0; i < childDrags.size(); i++)
+ for (int i = 0; i < childDrags.size(); i++) {
childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
+ }
setPos(newPos);
}
@@ -78,23 +83,27 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos)
// position.
TableZone *tableZone = qobject_cast(cursorZone);
QPointF closestGridPoint;
- if (tableZone)
+ if (tableZone) {
closestGridPoint = tableZone->closestGridPoint(cursorPosInZone);
- else
+ } else {
closestGridPoint = cursorPosInZone - hotSpot;
+ }
QPointF newPos = zonePos + closestGridPoint;
if (newPos != pos()) {
- for (int i = 0; i < childDrags.size(); i++)
+ for (int i = 0; i < childDrags.size(); i++) {
childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
+ }
setPos(newPos);
bool newOccupied = false;
TableZone *table = qobject_cast(cursorZone);
- if (table)
- if (table->getCardFromCoords(closestGridPoint))
+ if (table) {
+ if (table->getCardFromCoords(closestGridPoint)) {
newOccupied = true;
+ }
+ }
if (newOccupied != occupied) {
occupied = newOccupied;
update();
diff --git a/cockatrice/src/game/board/card_item.cpp b/cockatrice/src/game/board/card_item.cpp
index 072c1a231..695e94a3a 100644
--- a/cockatrice/src/game/board/card_item.cpp
+++ b/cockatrice/src/game/board/card_item.cpp
@@ -27,8 +27,9 @@ CardItem::CardItem(Player *_owner, QGraphicsItem *parent, const CardRef &cardRef
owner->addCard(this);
connect(&SettingsCache::instance().cardCounters(), &CardCounterSettings::colorChanged, this, [this](int counterId) {
- if (counters.contains(counterId))
+ if (counters.contains(counterId)) {
update();
+ }
});
}
@@ -56,8 +57,9 @@ void CardItem::prepareDelete()
void CardItem::deleteLater()
{
prepareDelete();
- if (scene())
+ if (scene()) {
static_cast(scene())->unregisterAnimationItem(this);
+ }
AbstractCardItem::deleteLater();
}
@@ -152,10 +154,11 @@ void CardItem::setAttacking(bool _attacking)
void CardItem::setCounter(int _id, int _value)
{
- if (_value)
+ if (_value) {
counters.insert(_id, _value);
- else
+ } else {
counters.remove(_id);
+ }
update();
}
@@ -227,8 +230,9 @@ void CardItem::resetState(bool keepAnnotations)
attachedCards.clear();
setTapped(false, false);
setDoesntUntap(false);
- if (scene())
+ if (scene()) {
static_cast(scene())->unregisterAnimationItem(this);
+ }
update();
}
@@ -275,8 +279,9 @@ void CardItem::deleteDragItem()
void CardItem::drawArrow(const QColor &arrowColor)
{
- if (owner->getGame()->getPlayerManager()->isSpectator())
+ if (owner->getGame()->getPlayerManager()->isSpectator()) {
return;
+ }
auto *game = owner->getGame();
Player *arrowOwner = game->getPlayerManager()->getActiveLocalPlayer(game->getGameState()->getActivePlayer());
@@ -291,10 +296,12 @@ void CardItem::drawArrow(const QColor &arrowColor)
for (const auto &item : scene()->selectedItems()) {
CardItem *card = qgraphicsitem_cast(item);
- if (card == nullptr || card == this)
+ if (card == nullptr || card == this) {
continue;
- if (card->getZone() != zone)
+ }
+ if (card->getZone() != zone) {
continue;
+ }
ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, card, arrowColor, phase);
scene()->addItem(childArrow);
@@ -304,8 +311,9 @@ void CardItem::drawArrow(const QColor &arrowColor)
void CardItem::drawAttachArrow()
{
- if (owner->getGame()->getPlayerManager()->isSpectator())
+ if (owner->getGame()->getPlayerManager()->isSpectator()) {
return;
+ }
auto *arrow = new ArrowAttachItem(this);
scene()->addItem(arrow);
@@ -313,10 +321,12 @@ void CardItem::drawAttachArrow()
for (const auto &item : scene()->selectedItems()) {
CardItem *card = qgraphicsitem_cast(item);
- if (card == nullptr)
+ if (card == nullptr) {
continue;
- if (card->getZone() != zone)
+ }
+ if (card->getZone() != zone) {
continue;
+ }
ArrowAttachItem *childArrow = new ArrowAttachItem(card);
scene()->addItem(childArrow);
@@ -328,27 +338,32 @@ void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if (event->buttons().testFlag(Qt::RightButton)) {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() <
- 2 * QApplication::startDragDistance())
+ 2 * QApplication::startDragDistance()) {
return;
+ }
QColor arrowColor = Qt::red;
- if (event->modifiers().testFlag(Qt::ControlModifier))
+ if (event->modifiers().testFlag(Qt::ControlModifier)) {
arrowColor = Qt::yellow;
- else if (event->modifiers().testFlag(Qt::AltModifier))
+ } else if (event->modifiers().testFlag(Qt::AltModifier)) {
arrowColor = Qt::blue;
- else if (event->modifiers().testFlag(Qt::ShiftModifier))
+ } else if (event->modifiers().testFlag(Qt::ShiftModifier)) {
arrowColor = Qt::green;
+ }
drawArrow(arrowColor);
} else if (event->buttons().testFlag(Qt::LeftButton)) {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() <
- 2 * QApplication::startDragDistance())
+ 2 * QApplication::startDragDistance()) {
return;
+ }
if (const ZoneViewZoneLogic *view = qobject_cast(zone)) {
- if (view->getRevealZone() && !view->getWriteableRevealZone())
+ if (view->getRevealZone() && !view->getWriteableRevealZone()) {
return;
- } else if (!owner->getPlayerInfo()->getLocalOrJudge())
+ }
+ } else if (!owner->getPlayerInfo()->getLocalOrJudge()) {
return;
+ }
bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier);
@@ -360,14 +375,16 @@ void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
int childIndex = 0;
for (const auto &item : scene()->selectedItems()) {
CardItem *card = static_cast(item);
- if ((card == this) || (card->getZone() != zone))
+ if ((card == this) || (card->getZone() != zone)) {
continue;
+ }
++childIndex;
QPointF childPos;
- if (zone->getHasCardAttr())
+ if (zone->getHasCardAttr()) {
childPos = card->pos() - pos();
- else
+ } else {
childPos = QPointF(childIndex * CardDimensions::WIDTH_HALF_F, 0);
+ }
CardDragItem *drag =
new CardDragItem(card, card->getId(), childPos, card->getFaceDown() || forceFaceDown, dragItem);
drag->setPos(dragItem->pos() + childPos);
@@ -380,13 +397,14 @@ void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
void CardItem::playCard(bool faceDown)
{
// Do nothing if the card belongs to another player
- if (!owner->getPlayerInfo()->getLocalOrJudge())
+ if (!owner->getPlayerInfo()->getLocalOrJudge()) {
return;
+ }
TableZoneLogic *tz = qobject_cast(zone);
- if (tz)
+ if (tz) {
emit tz->toggleTapped();
- else {
+ } else {
if (SettingsCache::instance().getClickPlaysAllSelected()) {
faceDown ? zone->getPlayer()->getPlayerActions()->actPlayFacedown()
: zone->getPlayer()->getPlayerActions()->actPlay();
@@ -493,8 +511,9 @@ bool CardItem::animationEvent()
{
int rotation = ROTATION_DEGREES_PER_FRAME;
bool animationIncomplete = true;
- if (!tapped)
+ if (!tapped) {
rotation *= -1;
+ }
tapAngle += rotation;
if (tapped && (tapAngle > 90)) {
diff --git a/cockatrice/src/game/deckview/deck_view.cpp b/cockatrice/src/game/deckview/deck_view.cpp
index 620dfaa5f..ced02c8db 100644
--- a/cockatrice/src/game/deckview/deck_view.cpp
+++ b/cockatrice/src/game/deckview/deck_view.cpp
@@ -24,17 +24,21 @@ void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos)
QList colliding = scene()->items(cursorScenePos);
DeckViewCardContainer *cursorZone = 0;
- for (int i = colliding.size() - 1; i >= 0; i--)
- if ((cursorZone = qgraphicsitem_cast(colliding.at(i))))
+ for (int i = colliding.size() - 1; i >= 0; i--) {
+ if ((cursorZone = qgraphicsitem_cast(colliding.at(i)))) {
break;
- if (!cursorZone)
+ }
+ }
+ if (!cursorZone) {
return;
+ }
currentZone = cursorZone;
QPointF newPos = cursorScenePos;
if (newPos != pos()) {
- for (int i = 0; i < childDrags.size(); i++)
+ for (int i = 0; i < childDrags.size(); i++) {
childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
+ }
setPos(newPos);
}
}
@@ -104,11 +108,13 @@ void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti
void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() <
- 2 * QApplication::startDragDistance())
+ 2 * QApplication::startDragDistance()) {
return;
+ }
- if (static_cast(scene())->getLocked())
+ if (static_cast(scene())->getLocked()) {
return;
+ }
delete dragItem;
dragItem = new DeckViewCardDragItem(this, event->pos());
@@ -120,8 +126,9 @@ void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
int j = 0;
for (int i = 0; i < sel.size(); i++) {
auto *c = static_cast(sel.at(i));
- if (c == this)
+ if (c == this) {
continue;
+ }
++j;
auto childPos = QPointF(j * CardDimensions::WIDTH_HALF_F, 0);
auto *drag = new DeckViewCardDragItem(c, childPos, dragItem);
@@ -133,8 +140,9 @@ void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
void DeckView::mouseDoubleClickEvent(QMouseEvent *event)
{
- if (static_cast(scene())->getLocked())
+ if (static_cast(scene())->getLocked()) {
return;
+ }
if (event->button() == Qt::LeftButton) {
QList result;
@@ -147,12 +155,13 @@ void DeckView::mouseDoubleClickEvent(QMouseEvent *event)
m.set_card_name(c->getName().toStdString());
m.set_start_zone(zone->getName().toStdString());
- if (zone->getName() == DECK_ZONE_MAIN)
+ if (zone->getName() == DECK_ZONE_MAIN) {
m.set_target_zone(DECK_ZONE_SIDE);
- else if (zone->getName() == DECK_ZONE_SIDE)
+ } else if (zone->getName() == DECK_ZONE_SIDE) {
m.set_target_zone(DECK_ZONE_MAIN);
- else // Trying to move from another zone
+ } else { // Trying to move from another zone
m.set_target_zone(zone->getName().toStdString());
+ }
result.append(m);
}
@@ -232,8 +241,9 @@ QList> DeckViewCardContainer::getRowsAndCols() const
{
QList> result;
QList cardTypeList = cardsByType.uniqueKeys();
- for (int i = 0; i < cardTypeList.size(); ++i)
+ for (int i = 0; i < cardTypeList.size(); ++i) {
result.append(QPair(1, cardsByType.count(cardTypeList[i])));
+ }
return result;
}
@@ -262,8 +272,9 @@ QSizeF DeckViewCardContainer::calculateBoundingRect(const QList>
// Calculate space needed for cards
for (int i = 0; i < rowsAndCols.size(); ++i) {
totalHeight += CardDimensions::HEIGHT_F * rowsAndCols[i].first + paddingY;
- if (CardDimensions::WIDTH_F * rowsAndCols[i].second > totalWidth)
+ if (CardDimensions::WIDTH_F * rowsAndCols[i].second > totalWidth) {
totalWidth = CardDimensions::WIDTH_F * rowsAndCols[i].second;
+ }
}
return QSizeF(getCardTypeTextWidth() + totalWidth, totalHeight + separatorY + paddingY);
@@ -271,8 +282,9 @@ QSizeF DeckViewCardContainer::calculateBoundingRect(const QList>
bool DeckViewCardContainer::sortCardsByName(DeckViewCard *c1, DeckViewCard *c2)
{
- if (c1 && c2)
+ if (c1 && c2) {
return c1->getName() < c2->getName();
+ }
return false;
}
@@ -322,15 +334,17 @@ DeckViewScene::~DeckViewScene()
void DeckViewScene::clearContents()
{
QMapIterator i(cardContainers);
- while (i.hasNext())
+ while (i.hasNext()) {
delete i.next().value();
+ }
cardContainers.clear();
}
void DeckViewScene::setDeck(const DeckList &_deck)
{
- if (deck)
+ if (deck) {
delete deck;
+ }
deck = new DeckList(_deck.writeToString_Native());
rebuildTree();
@@ -342,8 +356,9 @@ void DeckViewScene::rebuildTree()
{
clearContents();
- if (!deck)
+ if (!deck) {
return;
+ }
for (auto *currentZone : deck->getZoneNodes()) {
DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0);
@@ -355,8 +370,9 @@ void DeckViewScene::rebuildTree()
for (int j = 0; j < currentZone->size(); j++) {
auto *currentCard = dynamic_cast(currentZone->at(j));
- if (!currentCard)
+ if (!currentCard) {
continue;
+ }
for (int k = 0; k < currentCard->getNumber(); ++k) {
auto *newCard = new DeckViewCard(container, currentCard->toCardRef(), currentZone->getName());
@@ -373,18 +389,21 @@ void DeckViewScene::applySideboardPlan(const QList &plan)
const MoveCard_ToZone &m = plan[i];
DeckViewCardContainer *start = cardContainers.value(QString::fromStdString(m.start_zone()));
DeckViewCardContainer *target = cardContainers.value(QString::fromStdString(m.target_zone()));
- if (!start || !target)
+ if (!start || !target) {
continue;
+ }
DeckViewCard *card = 0;
const QList &cardList = start->getCards();
- for (int j = 0; j < cardList.size(); ++j)
+ for (int j = 0; j < cardList.size(); ++j) {
if (cardList[j]->getName() == QString::fromStdString(m.card_name())) {
card = cardList[j];
break;
}
- if (!card)
+ }
+ if (!card) {
continue;
+ }
start->removeCard(card);
target->addCard(card);
@@ -405,8 +424,9 @@ void DeckViewScene::rearrangeItems()
rowsAndColsList.append(rowsAndCols);
cardCountList.append(QList());
- for (int j = 0; j < rowsAndCols.size(); ++j)
+ for (int j = 0; j < rowsAndCols.size(); ++j) {
cardCountList[i].append(rowsAndCols[j].second);
+ }
}
qreal totalHeight, totalWidth;
@@ -417,23 +437,27 @@ void DeckViewScene::rearrangeItems()
for (int i = 0; i < contList.size(); ++i) {
QSizeF contSize = contList[i]->calculateBoundingRect(rowsAndColsList[i]);
totalHeight += contSize.height() + spacing;
- if (contSize.width() > totalWidth)
+ if (contSize.width() > totalWidth) {
totalWidth = contSize.width();
+ }
}
// We're done when the aspect ratio shifts from too high to too low.
- if (totalWidth / totalHeight <= optimalAspectRatio)
+ if (totalWidth / totalHeight <= optimalAspectRatio) {
break;
+ }
// Find category with highest column count
int maxIndex1 = -1, maxIndex2 = -1, maxCols = 0;
- for (int i = 0; i < rowsAndColsList.size(); ++i)
- for (int j = 0; j < rowsAndColsList[i].size(); ++j)
+ for (int i = 0; i < rowsAndColsList.size(); ++i) {
+ for (int j = 0; j < rowsAndColsList[i].size(); ++j) {
if (rowsAndColsList[i][j].second > maxCols) {
maxIndex1 = i;
maxIndex2 = j;
maxCols = rowsAndColsList[i][j].second;
}
+ }
+ }
// Add row to category
const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first;
@@ -451,8 +475,9 @@ void DeckViewScene::rearrangeItems()
}
totalWidth = totalHeight * optimalAspectRatio;
- for (int i = 0; i < contList.size(); ++i)
+ for (int i = 0; i < contList.size(); ++i) {
contList[i]->setWidth(totalWidth);
+ }
setSceneRect(QRectF(0, 0, totalWidth, totalHeight));
}
@@ -470,7 +495,7 @@ QList DeckViewScene::getSideboardPlan() const
while (containerIterator.hasNext()) {
DeckViewCardContainer *cont = containerIterator.next().value();
const QList cardList = cont->getCards();
- for (int i = 0; i < cardList.size(); ++i)
+ for (int i = 0; i < cardList.size(); ++i) {
if (cardList[i]->getOriginZone() != cont->getName()) {
MoveCard_ToZone m;
m.set_card_name(cardList[i]->getName().toStdString());
@@ -478,6 +503,7 @@ QList DeckViewScene::getSideboardPlan() const
m.set_target_zone(cont->getName().toStdString());
result.append(m);
}
+ }
}
return result;
}
diff --git a/cockatrice/src/game/deckview/deck_view_container.cpp b/cockatrice/src/game/deckview/deck_view_container.cpp
index 44b2be6d1..cbd6c2bad 100644
--- a/cockatrice/src/game/deckview/deck_view_container.cpp
+++ b/cockatrice/src/game/deckview/deck_view_container.cpp
@@ -251,8 +251,9 @@ void DeckViewContainer::unloadDeck()
void DeckViewContainer::loadLocalDeck()
{
DlgLoadDeck dialog(this);
- if (!dialog.exec())
+ if (!dialog.exec()) {
return;
+ }
loadDeckFromFile(dialog.selectedFiles().at(0));
}
@@ -364,8 +365,9 @@ void DeckViewContainer::sideboardPlanChanged()
{
Command_SetSideboardPlan cmd;
const QList &newPlan = deckView->getSideboardPlan();
- for (const auto &i : newPlan)
+ for (const auto &i : newPlan) {
cmd.add_move_list()->CopyFrom(i);
+ }
parentGame->getGame()->getGameEventHandler()->sendGameCommand(cmd, playerId);
}
@@ -404,8 +406,9 @@ void DeckViewContainer::setSideboardLocked(bool locked)
{
sideboardLockButton->setState(!locked);
deckView->setLocked(readyStartButton->getState() || !sideboardLockButton->getState());
- if (locked)
+ if (locked) {
deckView->resetSideboardPlan();
+ }
}
void DeckViewContainer::setDeck(const DeckList &deck)
diff --git a/cockatrice/src/game/dialogs/dlg_create_token.cpp b/cockatrice/src/game/dialogs/dlg_create_token.cpp
index df264f065..11c24b72e 100644
--- a/cockatrice/src/game/dialogs/dlg_create_token.cpp
+++ b/cockatrice/src/game/dialogs/dlg_create_token.cpp
@@ -101,8 +101,9 @@ DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *pa
chooseTokenView->resizeColumnToContents(0);
chooseTokenView->setWordWrap(true);
- if (!deckHeaderState.isNull())
+ if (!deckHeaderState.isNull()) {
chooseTokenView->header()->restoreState(deckHeaderState);
+ }
chooseTokenView->header()->setStretchLastSection(false);
chooseTokenView->header()->hideSection(1); // Sets
@@ -185,8 +186,9 @@ void DlgCreateToken::tokenSelectionChanged(const QModelIndex ¤t, const QMo
const QChar cardColor = cardInfo->getColorChar();
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
ptEdit->setText(cardInfo->getPowTough());
- if (SettingsCache::instance().getAnnotateTokens())
+ if (SettingsCache::instance().getAnnotateTokens()) {
annotationEdit->setText(cardInfo->getText());
+ }
} else {
nameEdit->setText("");
colorEdit->setCurrentIndex(colorEdit->findData(QString(), Qt::UserRole, Qt::MatchFixedString));
diff --git a/cockatrice/src/game/game_event_handler.cpp b/cockatrice/src/game/game_event_handler.cpp
index 42dd49458..82fa2b911 100644
--- a/cockatrice/src/game/game_event_handler.cpp
+++ b/cockatrice/src/game/game_event_handler.cpp
@@ -36,8 +36,9 @@ GameEventHandler::GameEventHandler(AbstractGame *_game) : QObject(_game), game(_
void GameEventHandler::sendGameCommand(PendingCommand *pend, int playerId)
{
AbstractClient *client = game->getClientForPlayer(playerId);
- if (!client)
+ if (!client) {
return;
+ }
connect(pend, &PendingCommand::finished, this, &GameEventHandler::commandFinished);
client->sendCommand(pend);
@@ -46,8 +47,9 @@ void GameEventHandler::sendGameCommand(PendingCommand *pend, int playerId)
void GameEventHandler::sendGameCommand(const google::protobuf::Message &command, int playerId)
{
AbstractClient *client = game->getClientForPlayer(playerId);
- if (!client)
+ if (!client) {
return;
+ }
PendingCommand *pend = prepareGameCommand(command);
connect(pend, &PendingCommand::finished, this, &GameEventHandler::commandFinished);
@@ -56,8 +58,9 @@ void GameEventHandler::sendGameCommand(const google::protobuf::Message &command,
void GameEventHandler::commandFinished(const Response &response)
{
- if (response.response_code() == Response::RespChatFlood)
+ if (response.response_code() == Response::RespChatFlood) {
emit gameFlooded();
+ }
}
PendingCommand *GameEventHandler::prepareGameCommand(const ::google::protobuf::Message &cmd)
@@ -117,9 +120,11 @@ void GameEventHandler::processGameEventContainer(const GameEventContainer &cont,
break;
}
} else {
- if ((game->getGameState()->getClients().size() > 1) && (playerId != -1))
- if (game->getGameState()->getClients().at(playerId) != client)
+ if ((game->getGameState()->getClients().size() > 1) && (playerId != -1)) {
+ if (game->getGameState()->getClients().at(playerId) != client) {
continue;
+ }
+ }
switch (eventType) {
case GameEvent::GAME_STATE_CHANGED:
@@ -284,8 +289,9 @@ void GameEventHandler::eventGameStateChanged(const Event_GameStateChanged &event
if (event.game_started() && !game->getGameMetaInfo()->started()) {
game->getGameState()->setResuming(!game->getGameState()->isGameStateKnown());
game->getGameMetaInfo()->setStarted(event.game_started());
- if (game->getGameState()->isGameStateKnown())
+ if (game->getGameState()->isGameStateKnown()) {
emit logGameStart();
+ }
game->getGameState()->setActivePlayer(event.active_player_id());
game->getGameState()->setCurrentPhase(event.active_phase());
} else if (!event.game_started() && game->getGameMetaInfo()->started()) {
@@ -305,8 +311,9 @@ void GameEventHandler::processCardAttachmentsForPlayers(const Event_GameStateCha
const ServerInfo_PlayerProperties &prop = playerInfo.properties();
if (!prop.spectator()) {
Player *player = game->getPlayerManager()->getPlayers().value(prop.player_id(), 0);
- if (!player)
+ if (!player) {
continue;
+ }
player->processCardAttachment(playerInfo);
}
}
@@ -317,8 +324,9 @@ void GameEventHandler::eventPlayerPropertiesChanged(const Event_PlayerProperties
const GameEventContext &context)
{
Player *player = game->getPlayerManager()->getPlayers().value(eventPlayerId, 0);
- if (!player)
+ if (!player) {
return;
+ }
const ServerInfo_PlayerProperties &prop = event.player_properties();
emit playerPropertiesChanged(prop, eventPlayerId);
@@ -326,8 +334,9 @@ void GameEventHandler::eventPlayerPropertiesChanged(const Event_PlayerProperties
switch (contextType) {
case GameEventContext::READY_START: {
bool ready = prop.ready_start();
- if (player->getPlayerInfo()->getLocal())
+ if (player->getPlayerInfo()->getLocal()) {
emit localPlayerReadyStateChanged(player->getPlayerInfo()->getId(), ready);
+ }
if (ready) {
emit logReadyStart(player);
} else {
@@ -339,8 +348,9 @@ void GameEventHandler::eventPlayerPropertiesChanged(const Event_PlayerProperties
player->setConceded(true);
QMapIterator playerIterator(game->getPlayerManager()->getPlayers());
- while (playerIterator.hasNext())
+ while (playerIterator.hasNext()) {
playerIterator.next().value()->updateZones();
+ }
emit logConcede(eventPlayerId);
@@ -350,8 +360,9 @@ void GameEventHandler::eventPlayerPropertiesChanged(const Event_PlayerProperties
player->setConceded(false);
QMapIterator playerIterator(game->getPlayerManager()->getPlayers());
- while (playerIterator.hasNext())
+ while (playerIterator.hasNext()) {
playerIterator.next().value()->updateZones();
+ }
emit logUnconcede(eventPlayerId);
@@ -389,8 +400,9 @@ void GameEventHandler::eventJoin(const Event_Join &event, int /*eventPlayerId*/,
QString playerName = QString::fromStdString(playerInfo.user_info().name());
emit addPlayerToAutoCompleteList(playerName);
- if (game->getPlayerManager()->getPlayers().contains(playerId))
+ if (game->getPlayerManager()->getPlayers().contains(playerId)) {
return;
+ }
if (playerInfo.spectator()) {
game->getPlayerManager()->addSpectator(playerId, playerInfo);
@@ -426,8 +438,9 @@ QString GameEventHandler::getLeaveReason(Event_Leave::LeaveReason reason)
void GameEventHandler::eventLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext & /*context*/)
{
Player *player = game->getPlayerManager()->getPlayers().value(eventPlayerId, 0);
- if (!player)
+ if (!player) {
return;
+ }
player->clear();
emit playerLeft(eventPlayerId);
@@ -440,8 +453,9 @@ void GameEventHandler::eventLeave(const Event_Leave &event, int eventPlayerId, c
// Rearrange all remaining zones so that attachment relationship updates take place
QMapIterator playerIterator(game->getPlayerManager()->getPlayers());
- while (playerIterator.hasNext())
+ while (playerIterator.hasNext()) {
playerIterator.next().value()->updateZones();
+ }
emitUserEvent();
}
@@ -461,8 +475,9 @@ void GameEventHandler::eventReverseTurn(const Event_ReverseTurn &event,
const GameEventContext & /*context*/)
{
Player *player = game->getPlayerManager()->getPlayers().value(eventPlayerId, 0);
- if (!player)
+ if (!player) {
return;
+ }
emit logTurnReversed(player, event.reversed());
}
@@ -491,8 +506,9 @@ void GameEventHandler::eventSetActivePlayer(const Event_SetActivePlayer &event,
{
game->getGameState()->setActivePlayer(event.active_player_id());
Player *player = game->getPlayerManager()->getPlayer(event.active_player_id());
- if (!player)
+ if (!player) {
return;
+ }
emit logActivePlayer(player);
emitUserEvent();
}
diff --git a/cockatrice/src/game/game_meta_info.h b/cockatrice/src/game/game_meta_info.h
index b5f5bfe4f..8226af2ae 100644
--- a/cockatrice/src/game/game_meta_info.h
+++ b/cockatrice/src/game/game_meta_info.h
@@ -87,15 +87,17 @@ public:
public slots:
void setStarted(bool s)
{
- if (gameInfo_.started() == s)
+ if (gameInfo_.started() == s) {
return;
+ }
gameInfo_.set_started(s);
emit startedChanged(s);
}
void setSpectatorsOmniscient(bool v)
{
- if (gameInfo_.spectators_omniscient() == v)
+ if (gameInfo_.spectators_omniscient() == v) {
return;
+ }
gameInfo_.set_spectators_omniscient(v);
emit spectatorsOmniscienceChanged(v);
}
diff --git a/cockatrice/src/game/game_scene.cpp b/cockatrice/src/game/game_scene.cpp
index aa6f1e6f1..9141a9d54 100644
--- a/cockatrice/src/game/game_scene.cpp
+++ b/cockatrice/src/game/game_scene.cpp
@@ -55,8 +55,9 @@ GameScene::~GameScene()
*/
void GameScene::retranslateUi()
{
- for (ZoneViewWidget *view : zoneViews)
+ for (ZoneViewWidget *view : zoneViews) {
view->retranslateUi();
+ }
}
QList GameScene::selectedCards() const
@@ -209,10 +210,12 @@ QList GameScene::rotatePlayers(const QList &activePlayers, i
QList rotated = activePlayers;
if (!rotated.isEmpty()) {
int totalRotation = firstPlayerIndex + playerRotation;
- while (totalRotation < 0)
+ while (totalRotation < 0) {
totalRotation += rotated.size();
- for (int i = 0; i < totalRotation; ++i)
+ }
+ for (int i = 0; i < totalRotation; ++i) {
rotated.append(rotated.takeFirst());
+ }
}
return rotated;
}
@@ -252,10 +255,11 @@ QSizeF GameScene::computeSceneSizeAndPlayerLayout(const QList &players
for (int j = 0; j < rowsInColumn; ++j) {
Player *player = playersIter.next();
- if (col == 0)
+ if (col == 0) {
playersByColumn[col].prepend(player->getGraphicsItem());
- else
+ } else {
playersByColumn[col].append(player->getGraphicsItem());
+ }
auto *pgItem = player->getGraphicsItem();
thisColumnHeight += pgItem->boundingRect().height() + playerAreaSpacing;
@@ -294,8 +298,9 @@ QList GameScene::calculateMinWidthByColumn() const
QList minWidthByColumn;
for (const auto &col : playersByColumn) {
qreal maxWidth = 0;
- for (PlayerGraphicsItem *player : col)
+ for (PlayerGraphicsItem *player : col) {
maxWidth = std::max(maxWidth, player->getMinimumWidth());
+ }
minWidthByColumn.append(maxWidth);
}
return minWidthByColumn;
@@ -356,32 +361,38 @@ void GameScene::updateHover(const QPointF &scenePos)
void GameScene::updateHoveredCard(CardItem *newCard)
{
- if (hoveredCard && (newCard != hoveredCard))
+ if (hoveredCard && (newCard != hoveredCard)) {
endCardHover(hoveredCard);
- if (newCard && (newCard != hoveredCard))
+ }
+ if (newCard && (newCard != hoveredCard)) {
beginCardHover(newCard);
+ }
hoveredCard = newCard;
}
void GameScene::beginCardHover(CardItem *card)
{
card->setHovered(true);
- if (auto *zone = SelectZone::findOwningSelectZone(card))
+ if (auto *zone = SelectZone::findOwningSelectZone(card)) {
zone->escapeClipForHover(card);
+ }
}
void GameScene::endCardHover(CardItem *card)
{
- if (auto *zone = SelectZone::findOwningSelectZone(card))
+ if (auto *zone = SelectZone::findOwningSelectZone(card)) {
zone->restoreClipAfterHover(card);
+ }
card->setHovered(false);
}
CardZone *GameScene::findTopmostZone(const QList &items)
{
- for (QGraphicsItem *item : items)
- if (auto *zone = qgraphicsitem_cast(item))
+ for (QGraphicsItem *item : items) {
+ if (auto *zone = qgraphicsitem_cast(item)) {
return zone;
+ }
+ }
return nullptr;
}
@@ -392,14 +403,17 @@ CardItem *GameScene::findTopmostCardInZone(const QList &items,
for (QGraphicsItem *item : items) {
CardItem *card = qgraphicsitem_cast(item);
- if (!card)
+ if (!card) {
continue;
+ }
if (card->getAttachedTo()) {
- if (card->getAttachedTo()->getZone() != zone->getLogic())
+ if (card->getAttachedTo()->getZone() != zone->getLogic()) {
continue;
- } else if (card->getZone() != zone->getLogic())
+ }
+ } else if (card->getZone() != zone->getLogic()) {
continue;
+ }
if (card->getRealZValue() > maxZ) {
maxZ = card->getRealZValue();
@@ -438,12 +452,13 @@ void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numb
connect(item, &ZoneViewWidget::closePressed, this, &GameScene::removeZoneView);
addItem(item);
- if (zoneName == ZoneNames::GRAVE)
+ if (zoneName == ZoneNames::GRAVE) {
item->setPos(360, 100);
- else if (zoneName == ZoneNames::EXILE)
+ } else if (zoneName == ZoneNames::EXILE) {
item->setPos(380, 120);
- else
+ } else {
item->setPos(340, 80);
+ }
}
/**
@@ -480,8 +495,9 @@ void GameScene::removeZoneView(ZoneViewWidget *item)
*/
void GameScene::clearViews()
{
- while (!zoneViews.isEmpty())
+ while (!zoneViews.isEmpty()) {
zoneViews.first()->close();
+ }
}
/**
@@ -489,8 +505,9 @@ void GameScene::clearViews()
*/
void GameScene::closeMostRecentZoneView()
{
- if (!zoneViews.isEmpty())
+ if (!zoneViews.isEmpty()) {
zoneViews.last()->close();
+ }
}
// ---------- View Transforms ----------
@@ -509,10 +526,11 @@ QTransform GameScene::getViewportTransform() const
bool GameScene::event(QEvent *event)
{
- if (event->type() == QEvent::GraphicsSceneMouseMove)
+ if (event->type() == QEvent::GraphicsSceneMouseMove) {
updateHover(static_cast(event)->scenePos());
- else if (event->type() == QEvent::Leave)
+ } else if (event->type() == QEvent::Leave) {
updateHoveredCard(nullptr);
+ }
return QGraphicsScene::event(event);
}
@@ -522,25 +540,29 @@ void GameScene::timerEvent(QTimerEvent * /*event*/)
QMutableSetIterator i(cardsToAnimate);
while (i.hasNext()) {
i.next();
- if (!i.value()->animationEvent())
+ if (!i.value()->animationEvent()) {
i.remove();
+ }
}
- if (cardsToAnimate.isEmpty())
+ if (cardsToAnimate.isEmpty()) {
animationTimer->stop();
+ }
}
void GameScene::registerAnimationItem(AbstractCardItem *card)
{
cardsToAnimate.insert(static_cast(card));
- if (!animationTimer->isActive())
+ if (!animationTimer->isActive()) {
animationTimer->start(10, this);
+ }
}
void GameScene::unregisterAnimationItem(AbstractCardItem *card)
{
cardsToAnimate.remove(static_cast(card));
- if (cardsToAnimate.isEmpty())
+ if (cardsToAnimate.isEmpty()) {
animationTimer->stop();
+ }
}
// ---------- Rubber Band ----------
diff --git a/cockatrice/src/game/game_view.cpp b/cockatrice/src/game/game_view.cpp
index ce53828a7..4ba41cffb 100644
--- a/cockatrice/src/game/game_view.cpp
+++ b/cockatrice/src/game/game_view.cpp
@@ -75,8 +75,9 @@ void GameView::resizeEvent(QResizeEvent *event)
QGraphicsView::resizeEvent(event);
GameScene *s = dynamic_cast(scene());
- if (s)
+ if (s) {
s->processViewSizeChange(event->size());
+ }
updateSceneRect(scene()->sceneRect());
updateTotalSelectionCount(event->size());
@@ -89,8 +90,9 @@ void GameView::updateSceneRect(const QRectF &rect)
void GameView::startRubberBand(const QPointF &_selectionOrigin)
{
- if (!rubberBand)
+ if (!rubberBand) {
return;
+ }
selectionOrigin = _selectionOrigin;
rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), QSize(0, 0)));
@@ -99,8 +101,9 @@ void GameView::startRubberBand(const QPointF &_selectionOrigin)
void GameView::resizeRubberBand(const QPointF &cursorPoint, int selectedCount)
{
- if (!rubberBand)
+ if (!rubberBand) {
return;
+ }
constexpr int kLabelPaddingInPixels = 4;
@@ -145,8 +148,9 @@ void GameView::resizeRubberBand(const QPointF &cursorPoint, int selectedCount)
void GameView::stopRubberBand()
{
- if (!rubberBand)
+ if (!rubberBand) {
return;
+ }
rubberBand->hide();
dragCountLabel->hide();
diff --git a/cockatrice/src/game/phases_toolbar.cpp b/cockatrice/src/game/phases_toolbar.cpp
index 2341a1d7f..3361f9d55 100644
--- a/cockatrice/src/game/phases_toolbar.cpp
+++ b/cockatrice/src/game/phases_toolbar.cpp
@@ -21,8 +21,9 @@ PhaseButton::PhaseButton(const QString &_name, QGraphicsItem *parent, QAction *_
activeAnimationTimer = new QTimer(this);
connect(activeAnimationTimer, &QTimer::timeout, this, &PhaseButton::updateAnimation);
activeAnimationTimer->setSingleShot(false);
- } else
+ } else {
activeAnimationCounter = 9;
+ }
setCacheMode(DeviceCoordinateCache);
}
@@ -63,8 +64,9 @@ void PhaseButton::setWidth(double _width)
void PhaseButton::setActive(bool _active)
{
- if ((active == _active) || !highlightable)
+ if ((active == _active) || !highlightable) {
return;
+ }
active = _active;
activeAnimationTimer->start(25);
@@ -72,8 +74,9 @@ void PhaseButton::setActive(bool _active)
void PhaseButton::updateAnimation()
{
- if (!highlightable)
+ if (!highlightable) {
return;
+ }
// the counter ticks up to 10 when active and down to 0 when inactive
if (active && activeAnimationCounter < 10) {
@@ -99,8 +102,9 @@ void PhaseButton::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * /*event*/)
void PhaseButton::triggerDoubleClickAction()
{
- if (doubleClickAction)
+ if (doubleClickAction) {
doubleClickAction->trigger();
+ }
}
PhasesToolbar::PhasesToolbar(QGraphicsItem *parent)
@@ -126,8 +130,9 @@ PhasesToolbar::PhasesToolbar(QGraphicsItem *parent)
buttonList << untapButton << upkeepButton << drawButton << main1Button << combatStartButton << combatAttackersButton
<< combatBlockersButton << combatDamageButton << combatEndButton << main2Button << cleanupButton;
- for (auto &i : buttonList)
+ for (auto &i : buttonList) {
connect(i, &PhaseButton::clicked, this, &PhasesToolbar::phaseButtonClicked);
+ }
nextTurnButton = new PhaseButton("nextturn", this, nullptr, false);
connect(nextTurnButton, &PhaseButton::clicked, this, &PhasesToolbar::actNextTurn);
@@ -144,8 +149,9 @@ QRectF PhasesToolbar::boundingRect() const
void PhasesToolbar::retranslateUi()
{
- for (int i = 0; i < buttonList.size(); ++i)
+ for (int i = 0; i < buttonList.size(); ++i) {
buttonList[i]->setToolTip(getLongPhaseName(i));
+ }
}
QString PhasesToolbar::getLongPhaseName(int phase) const
@@ -187,8 +193,9 @@ const double PhasesToolbar::marginSize = 3;
void PhasesToolbar::rearrangeButtons()
{
- for (auto &i : buttonList)
+ for (auto &i : buttonList) {
i->setWidth(symbolSize);
+ }
nextTurnButton->setWidth(symbolSize);
double y = marginSize;
@@ -226,11 +233,13 @@ void PhasesToolbar::setHeight(double _height)
void PhasesToolbar::setActivePhase(int phase)
{
- if (phase >= buttonList.size())
+ if (phase >= buttonList.size()) {
return;
+ }
- for (int i = 0; i < buttonList.size(); ++i)
+ for (int i = 0; i < buttonList.size(); ++i) {
buttonList[i]->setActive(i == phase);
+ }
}
void PhasesToolbar::triggerPhaseAction(int phase)
@@ -243,8 +252,9 @@ void PhasesToolbar::triggerPhaseAction(int phase)
void PhasesToolbar::phaseButtonClicked()
{
auto *button = qobject_cast(sender());
- if (button->getActive())
+ if (button->getActive()) {
button->triggerDoubleClickAction();
+ }
Command_SetActivePhase cmd;
cmd.set_phase(static_cast(buttonList.indexOf(button)));
diff --git a/cockatrice/src/game/player/menu/grave_menu.cpp b/cockatrice/src/game/player/menu/grave_menu.cpp
index 2af62c08a..c3a5eb433 100644
--- a/cockatrice/src/game/player/menu/grave_menu.cpp
+++ b/cockatrice/src/game/player/menu/grave_menu.cpp
@@ -78,8 +78,9 @@ void GraveyardMenu::populateRevealRandomMenuWithActivePlayers()
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) {
- if (other == player)
+ if (other == player) {
continue;
+ }
QAction *a = mRevealRandomGraveyardCard->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &GraveyardMenu::onRevealRandomTriggered);
diff --git a/cockatrice/src/game/player/menu/hand_menu.cpp b/cockatrice/src/game/player/menu/hand_menu.cpp
index d65c136bf..1b1ec27d6 100644
--- a/cockatrice/src/game/player/menu/hand_menu.cpp
+++ b/cockatrice/src/game/player/menu/hand_menu.cpp
@@ -168,8 +168,9 @@ void HandMenu::populateRevealHandMenuWithActivePlayers()
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) {
- if (other == player)
+ if (other == player) {
continue;
+ }
QAction *a = mRevealHand->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &HandMenu::onRevealHandTriggered);
@@ -186,8 +187,9 @@ void HandMenu::populateRevealRandomHandCardMenuWithActivePlayers()
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) {
- if (other == player)
+ if (other == player) {
continue;
+ }
QAction *a = mRevealRandomHandCard->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &HandMenu::onRevealRandomHandCardTriggered);
@@ -197,8 +199,9 @@ void HandMenu::populateRevealRandomHandCardMenuWithActivePlayers()
void HandMenu::onRevealHandTriggered()
{
auto *action = qobject_cast(sender());
- if (!action)
+ if (!action) {
return;
+ }
const int targetId = action->data().toInt();
player->getPlayerActions()->actRevealHand(targetId);
@@ -207,8 +210,9 @@ void HandMenu::onRevealHandTriggered()
void HandMenu::onRevealRandomHandCardTriggered()
{
auto *action = qobject_cast(sender());
- if (!action)
+ if (!action) {
return;
+ }
const int targetId = action->data().toInt();
player->getPlayerActions()->actRevealRandomHandCard(targetId);
diff --git a/cockatrice/src/game/player/menu/library_menu.cpp b/cockatrice/src/game/player/menu/library_menu.cpp
index 1bb647d06..72591575f 100644
--- a/cockatrice/src/game/player/menu/library_menu.cpp
+++ b/cockatrice/src/game/player/menu/library_menu.cpp
@@ -265,8 +265,9 @@ void LibraryMenu::populateRevealLibraryMenuWithActivePlayers()
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) {
- if (other == player)
+ if (other == player) {
continue;
+ }
QAction *a = mRevealLibrary->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &LibraryMenu::onRevealLibraryTriggered);
@@ -279,8 +280,9 @@ void LibraryMenu::populateLendLibraryMenuWithActivePlayers()
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) {
- if (other == player)
+ if (other == player) {
continue;
+ }
QAction *a = mLendLibrary->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &LibraryMenu::onLendLibraryTriggered);
@@ -299,8 +301,9 @@ void LibraryMenu::populateRevealTopCardMenuWithActivePlayers()
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) {
- if (other == player)
+ if (other == player) {
continue;
+ }
QAction *a = mRevealTopCard->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &LibraryMenu::onRevealTopCardTriggered);
diff --git a/cockatrice/src/game/player/player.cpp b/cockatrice/src/game/player/player.cpp
index 8f5067eae..b130bcf75 100644
--- a/cockatrice/src/game/player/player.cpp
+++ b/cockatrice/src/game/player/player.cpp
@@ -63,8 +63,9 @@ Player::~Player()
qCInfo(PlayerLog) << "Player destructor:" << getPlayerInfo()->getName();
QMapIterator i(zones);
- while (i.hasNext())
+ while (i.hasNext()) {
delete i.next().value();
+ }
zones.clear();
delete playerMenu;
diff --git a/cockatrice/src/game/player/player_actions.cpp b/cockatrice/src/game/player/player_actions.cpp
index 24da37c82..2be9c90ba 100644
--- a/cockatrice/src/game/player/player_actions.cpp
+++ b/cockatrice/src/game/player/player_actions.cpp
@@ -85,8 +85,9 @@ void PlayerActions::playCard(CardItem *card, bool faceDown)
cardToMove->set_pt(info.getPowTough().toStdString());
}
cardToMove->set_tapped(!faceDown && info.getUiAttributes().cipt);
- if (tableRow != 3)
+ if (tableRow != 3) {
cmd.set_target_zone(ZoneNames::TABLE);
+ }
cmd.set_x(gridPoint.x());
cmd.set_y(gridPoint.y());
}
diff --git a/cockatrice/src/game/player/player_list_widget.cpp b/cockatrice/src/game/player/player_list_widget.cpp
index 9506e0729..6b1cf6cc6 100644
--- a/cockatrice/src/game/player/player_list_widget.cpp
+++ b/cockatrice/src/game/player/player_list_widget.cpp
@@ -43,8 +43,9 @@ PlayerListTWI::PlayerListTWI() : QTreeWidgetItem(Type)
bool PlayerListTWI::operator<(const QTreeWidgetItem &other) const
{
// Sort by spectator/player
- if (data(1, Qt::UserRole) != other.data(1, Qt::UserRole))
+ if (data(1, Qt::UserRole) != other.data(1, Qt::UserRole)) {
return data(1, Qt::UserRole).toBool();
+ }
// Sort by player ID
return data(4, Qt::UserRole + 1).toInt() < other.data(4, Qt::UserRole + 1).toInt();
@@ -106,12 +107,14 @@ void PlayerListWidget::addPlayer(const ServerInfo_PlayerProperties &player)
void PlayerListWidget::updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId)
{
- if (playerId == -1)
+ if (playerId == -1) {
playerId = prop.player_id();
+ }
QTreeWidgetItem *player = players.value(playerId, 0);
- if (!player)
+ if (!player) {
return;
+ }
bool isSpectator = prop.has_spectator() && prop.spectator();
if (prop.has_judge() || prop.has_spectator()) {
@@ -126,13 +129,16 @@ void PlayerListWidget::updatePlayerProperties(const ServerInfo_PlayerProperties
}
if (!isSpectator) {
- if (prop.has_conceded())
+ if (prop.has_conceded()) {
player->setData(2, Qt::UserRole, prop.conceded());
- if (prop.has_ready_start())
+ }
+ if (prop.has_ready_start()) {
player->setData(2, Qt::UserRole + 1, prop.ready_start());
- if (prop.has_conceded() || prop.has_ready_start())
+ }
+ if (prop.has_conceded() || prop.has_ready_start()) {
player->setIcon(2, gameStarted ? (prop.conceded() ? concededIcon : QIcon())
: (prop.ready_start() ? readyIcon : notReadyIcon));
+ }
}
if (prop.has_user_info()) {
player->setData(3, Qt::UserRole, prop.user_info().user_level());
@@ -141,30 +147,35 @@ void PlayerListWidget::updatePlayerProperties(const ServerInfo_PlayerProperties
QString::fromStdString(prop.user_info().privlevel())));
player->setText(4, QString::fromStdString(prop.user_info().name()));
const QString country = QString::fromStdString(prop.user_info().country());
- if (!country.isEmpty())
+ if (!country.isEmpty()) {
player->setIcon(4, QIcon(CountryPixmapGenerator::generatePixmap(12, country)));
+ }
player->setData(4, Qt::UserRole, QString::fromStdString(prop.user_info().name()));
}
- if (prop.has_player_id())
+ if (prop.has_player_id()) {
player->setData(4, Qt::UserRole + 1, prop.player_id());
+ }
if (!isSpectator) {
if (prop.has_deck_hash()) {
player->setText(5, QString::fromStdString(prop.deck_hash()));
}
- if (prop.has_sideboard_locked())
+ if (prop.has_sideboard_locked()) {
player->setIcon(5, prop.sideboard_locked() ? lockIcon : QIcon());
+ }
}
- if (prop.has_ping_seconds())
+ if (prop.has_ping_seconds()) {
player->setIcon(0, QIcon(PingPixmapGenerator::generatePixmap(12, prop.ping_seconds(), 10)));
+ }
}
void PlayerListWidget::removePlayer(int playerId)
{
QTreeWidgetItem *player = players.value(playerId, 0);
- if (!player)
+ if (!player) {
return;
+ }
players.remove(playerId);
delete takeTopLevelItem(indexOfTopLevelItem(player));
}
@@ -193,13 +204,14 @@ void PlayerListWidget::setGameStarted(bool _gameStarted, bool resuming)
QTreeWidgetItem *twi = i.next().value();
bool isPlayer = twi->data(1, Qt::UserRole).toBool();
- if (!isPlayer)
+ if (!isPlayer) {
continue;
+ }
if (gameStarted) {
- if (resuming)
+ if (resuming) {
twi->setIcon(2, twi->data(2, Qt::UserRole).toBool() ? concededIcon : QIcon());
- else {
+ } else {
twi->setData(2, Qt::UserRole, false);
twi->setIcon(2, QIcon());
}
@@ -211,8 +223,9 @@ void PlayerListWidget::setGameStarted(bool _gameStarted, bool resuming)
void PlayerListWidget::showContextMenu(const QPoint &pos, const QModelIndex &index)
{
- if (!userContextMenu)
+ if (!userContextMenu) {
return;
+ }
const QString &userName = index.sibling(index.row(), 4).data(Qt::UserRole).toString();
int playerId = index.sibling(index.row(), 4).data(Qt::UserRole + 1).toInt();
diff --git a/cockatrice/src/game/player/player_manager.cpp b/cockatrice/src/game/player/player_manager.cpp
index e283d2196..bd50703de 100644
--- a/cockatrice/src/game/player/player_manager.cpp
+++ b/cockatrice/src/game/player/player_manager.cpp
@@ -21,15 +21,18 @@ bool PlayerManager::isMainPlayerConceded() const
Player *PlayerManager::getActiveLocalPlayer(int activePlayer) const
{
Player *active = players.value(activePlayer, 0);
- if (active)
- if (active->getPlayerInfo()->getLocal())
+ if (active) {
+ if (active->getPlayerInfo()->getLocal()) {
return active;
+ }
+ }
QMapIterator playerIterator(players);
while (playerIterator.hasNext()) {
Player *temp = playerIterator.next().value();
- if (temp->getPlayerInfo()->getLocal())
+ if (temp->getPlayerInfo()->getLocal()) {
return temp;
+ }
}
return nullptr;
@@ -66,8 +69,9 @@ void PlayerManager::removePlayer(int playerId)
Player *PlayerManager::getPlayer(int playerId) const
{
Player *player = players.value(playerId, 0);
- if (!player)
+ if (!player) {
return nullptr;
+ }
return player;
}
diff --git a/cockatrice/src/game/player/player_target.cpp b/cockatrice/src/game/player/player_target.cpp
index a7a5cc5e7..36c9ae953 100644
--- a/cockatrice/src/game/player/player_target.cpp
+++ b/cockatrice/src/game/player/player_target.cpp
@@ -128,8 +128,9 @@ void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*o
resetPainterTransform(painter);
QString name = QString::fromStdString(info->name());
- if (name.size() > 13)
+ if (name.size() > 13) {
name = name.mid(0, 10) + "...";
+ }
QFont font;
font.setPixelSize(qMax(qRound(translatedNameRect.height() / 1.5), 9));
@@ -144,8 +145,9 @@ void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*o
painter->setPen(pen);
painter->drawRect(boundingRect().adjusted(border / 2, border / 2, -border / 2, -border / 2));
- if (getBeingPointedAt())
+ if (getBeingPointedAt()) {
painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100)));
+ }
}
AbstractCounter *PlayerTarget::addCounter(int _counterId, const QString &_name, int _value)
diff --git a/cockatrice/src/game/zones/card_zone.cpp b/cockatrice/src/game/zones/card_zone.cpp
index cd7ae6a56..3457b681e 100644
--- a/cockatrice/src/game/zones/card_zone.cpp
+++ b/cockatrice/src/game/zones/card_zone.cpp
@@ -25,14 +25,16 @@ void CardZone::onCardAdded(CardItem *addedCard)
void CardZone::retranslateUi()
{
- for (int i = 0; i < getLogic()->getCards().size(); ++i)
+ for (int i = 0; i < getLogic()->getCards().size(); ++i) {
getLogic()->getCards()[i]->retranslateUi();
+ }
}
void CardZone::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * /*event*/)
{
- if (doubleClickAction)
+ if (doubleClickAction) {
doubleClickAction->trigger();
+ }
}
bool CardZone::showContextMenu(const QPoint &screenPos)
@@ -47,12 +49,14 @@ bool CardZone::showContextMenu(const QPoint &screenPos)
void CardZone::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
if (event->button() == Qt::RightButton) {
- if (showContextMenu(event->screenPos()))
+ if (showContextMenu(event->screenPos())) {
event->accept();
- else
+ } else {
event->ignore();
- } else
+ }
+ } else {
event->ignore();
+ }
}
QPointF CardZone::closestGridPoint(const QPointF &point)
diff --git a/cockatrice/src/game/zones/hand_zone.cpp b/cockatrice/src/game/zones/hand_zone.cpp
index 506a26a80..3d676dbb5 100644
--- a/cockatrice/src/game/zones/hand_zone.cpp
+++ b/cockatrice/src/game/zones/hand_zone.cpp
@@ -34,9 +34,11 @@ void HandZone::handleDropEvent(const QList &dragItems,
QPoint point = dropPoint + scenePos().toPoint();
int x = -1;
if (SettingsCache::instance().getHorizontalHand()) {
- for (x = 0; x < getLogic()->getCards().size(); x++)
- if (point.x() < static_cast(getLogic()->getCards().at(x))->scenePos().x())
+ for (x = 0; x < getLogic()->getCards().size(); x++) {
+ if (point.x() < static_cast(getLogic()->getCards().at(x))->scenePos().x()) {
break;
+ }
+ }
} else {
x = calcDropIndexFromY(dropPoint.y());
}
@@ -49,18 +51,20 @@ void HandZone::handleDropEvent(const QList &dragItems,
cmd.set_x(x);
cmd.set_y(-1);
- for (int i = 0; i < dragItems.size(); ++i)
+ for (int i = 0; i < dragItems.size(); ++i) {
cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId());
+ }
getLogic()->getPlayer()->getPlayerActions()->sendGameCommand(cmd);
}
QRectF HandZone::boundingRect() const
{
- if (SettingsCache::instance().getHorizontalHand())
+ if (SettingsCache::instance().getHorizontalHand()) {
return QRectF(0, 0, width, CardDimensions::HEIGHT_F + 10);
- else
+ } else {
return QRectF(0, 0, CardDimensions::WIDTH_F * 1.5, zoneHeight);
+ }
}
void HandZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
@@ -90,9 +94,9 @@ void HandZone::reorganizeCards()
CardItem *c = getLogic()->getCards().at(i);
// If the total width of the cards is smaller than the available width,
// the cards do not need to overlap and are displayed in the center of the area.
- if (cardWidth * cardCount > totalWidth)
+ if (cardWidth * cardCount > totalWidth) {
c->setPos(xPadding + ((qreal)i) * (totalWidth - cardWidth) / (cardCount - 1), 5);
- else {
+ } else {
qreal xPosition = leftJustified ? xPadding + ((qreal)i) * cardWidth
: xPadding + ((qreal)i) * cardWidth +
(totalWidth - cardCount * cardWidth) / 2;
diff --git a/cockatrice/src/game/zones/logic/card_zone_logic.cpp b/cockatrice/src/game/zones/logic/card_zone_logic.cpp
index e917e4ad7..9d9b3767f 100644
--- a/cockatrice/src/game/zones/logic/card_zone_logic.cpp
+++ b/cockatrice/src/game/zones/logic/card_zone_logic.cpp
@@ -55,8 +55,9 @@ void CardZoneLogic::addCard(CardItem *card, const bool reorganize, const int x,
emit cardAdded(card);
addCardImpl(card, x, y);
- if (reorganize)
+ if (reorganize) {
emit reorganizeCards();
+ }
emit cardCountChanged();
}
@@ -66,16 +67,19 @@ CardItem *CardZoneLogic::takeCard(int position, int cardId, bool toNewZone)
if (position == -1) {
// position == -1 means either that the zone is indexed by card id
// or that it doesn't matter which card you take.
- for (int i = 0; i < cards.size(); ++i)
+ for (int i = 0; i < cards.size(); ++i) {
if (cards[i]->getId() == cardId) {
position = i;
break;
}
- if (position == -1)
+ }
+ if (position == -1) {
position = 0;
+ }
}
- if (position >= cards.size())
+ if (position >= cards.size()) {
return nullptr;
+ }
for (auto *view : views) {
qobject_cast(view->getLogic())->removeCard(position, toNewZone);
@@ -142,8 +146,9 @@ void CardZoneLogic::moveAllToZone()
cmd.set_target_zone(targetZone.toStdString());
cmd.set_x(targetX);
- for (int i = 0; i < cards.size(); ++i)
+ for (int i = 0; i < cards.size(); ++i) {
cmd.mutable_cards_to_move()->add_card()->set_card_id(cards[i]->getId());
+ }
player->getPlayerActions()->sendGameCommand(cmd);
}
@@ -175,9 +180,9 @@ void CardZoneLogic::clearContents()
QString CardZoneLogic::getTranslatedName(bool theirOwn, GrammaticalCase gc) const
{
QString ownerName = player->getPlayerInfo()->getName();
- if (name == ZoneNames::HAND)
+ if (name == ZoneNames::HAND) {
return (theirOwn ? tr("their hand", "nominative") : tr("%1's hand", "nominative").arg(ownerName));
- else if (name == ZoneNames::DECK)
+ } else if (name == ZoneNames::DECK) {
switch (gc) {
case CaseLookAtZone:
return (theirOwn ? tr("their library", "look at zone")
@@ -193,11 +198,11 @@ QString CardZoneLogic::getTranslatedName(bool theirOwn, GrammaticalCase gc) cons
default:
return (theirOwn ? tr("their library", "nominative") : tr("%1's library", "nominative").arg(ownerName));
}
- else if (name == ZoneNames::GRAVE)
+ } else if (name == ZoneNames::GRAVE) {
return (theirOwn ? tr("their graveyard", "nominative") : tr("%1's graveyard", "nominative").arg(ownerName));
- else if (name == ZoneNames::EXILE)
+ } else if (name == ZoneNames::EXILE) {
return (theirOwn ? tr("their exile", "nominative") : tr("%1's exile", "nominative").arg(ownerName));
- else if (name == ZoneNames::SIDEBOARD)
+ } else if (name == ZoneNames::SIDEBOARD) {
switch (gc) {
case CaseLookAtZone:
return (theirOwn ? tr("their sideboard", "look at zone")
@@ -208,7 +213,7 @@ QString CardZoneLogic::getTranslatedName(bool theirOwn, GrammaticalCase gc) cons
default:
break;
}
- else {
+ } else {
return (theirOwn ? tr("their custom zone '%1'", "nominative").arg(name)
: tr("%1's custom zone '%2'", "nominative").arg(ownerName).arg(name));
}
diff --git a/cockatrice/src/game/zones/logic/pile_zone_logic.cpp b/cockatrice/src/game/zones/logic/pile_zone_logic.cpp
index c5ffd5fd5..d445ad90c 100644
--- a/cockatrice/src/game/zones/logic/pile_zone_logic.cpp
+++ b/cockatrice/src/game/zones/logic/pile_zone_logic.cpp
@@ -25,8 +25,9 @@ void PileZoneLogic::addCardImpl(CardItem *card, int x, int /*y*/)
card->setCardRef({});
card->setId(-1);
// If we obscure a previously revealed card, its name has to be forgotten
- if (cards.size() > x + 1)
+ if (cards.size() > x + 1) {
cards.at(x + 1)->setCardRef({});
+ }
}
card->setVisible(false);
card->resetState();
diff --git a/cockatrice/src/game/zones/logic/table_zone_logic.cpp b/cockatrice/src/game/zones/logic/table_zone_logic.cpp
index 42caf2ec8..d01a756a3 100644
--- a/cockatrice/src/game/zones/logic/table_zone_logic.cpp
+++ b/cockatrice/src/game/zones/logic/table_zone_logic.cpp
@@ -29,7 +29,8 @@ CardItem *TableZoneLogic::takeCard(int position, int cardId, bool toNewZone)
{
CardItem *result = CardZoneLogic::takeCard(position, cardId);
- if (toNewZone)
+ if (toNewZone) {
emit contentSizeChanged();
+ }
return result;
}
\ No newline at end of file
diff --git a/cockatrice/src/game/zones/pile_zone.cpp b/cockatrice/src/game/zones/pile_zone.cpp
index d85b5f4e2..33538ab28 100644
--- a/cockatrice/src/game/zones/pile_zone.cpp
+++ b/cockatrice/src/game/zones/pile_zone.cpp
@@ -48,9 +48,10 @@ void PileZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*optio
{
painter->drawPath(shape());
- if (!getLogic()->getCards().isEmpty())
+ if (!getLogic()->getCards().isEmpty()) {
getLogic()->getCards().at(0)->paintPicture(painter, getLogic()->getCards().at(0)->getTranslatedSize(painter),
90);
+ }
painter->translate(CardDimensions::WIDTH_HALF_F, CardDimensions::HEIGHT_HALF_F);
painter->rotate(-90);
@@ -87,24 +88,28 @@ void PileZone::reorganizeCards()
void PileZone::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
CardZone::mousePressEvent(event);
- if (event->isAccepted())
+ if (event->isAccepted()) {
return;
+ }
if (event->button() == Qt::LeftButton) {
setCursor(Qt::ClosedHandCursor);
event->accept();
- } else
+ } else {
event->ignore();
+ }
}
void PileZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() <
- QApplication::startDragDistance())
+ QApplication::startDragDistance()) {
return;
+ }
- if (getLogic()->getCards().isEmpty())
+ if (getLogic()->getCards().isEmpty()) {
return;
+ }
bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier);
bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier);
@@ -123,7 +128,8 @@ void PileZone::mouseReleaseEvent(QGraphicsSceneMouseEvent * /*event*/)
void PileZone::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{
- if (!getLogic()->getCards().isEmpty())
+ if (!getLogic()->getCards().isEmpty()) {
getLogic()->getCards()[0]->processHoverEvent();
+ }
QGraphicsItem::hoverEnterEvent(event);
}
diff --git a/cockatrice/src/game/zones/select_zone.cpp b/cockatrice/src/game/zones/select_zone.cpp
index fd733e01f..e85ec17ae 100644
--- a/cockatrice/src/game/zones/select_zone.cpp
+++ b/cockatrice/src/game/zones/select_zone.cpp
@@ -69,8 +69,9 @@ SelectZone *SelectZone::findOwningSelectZone(const QGraphicsItem *card)
SelectZone::StackLayoutParams SelectZone::buildStackParams(qreal minOffset) const
{
const auto &cards = getLogic()->getCards();
- if (cards.isEmpty())
+ if (cards.isEmpty()) {
return {0, boundingRect().height(), 0.0, 0.0, minOffset};
+ }
const auto cardCount = static_cast(cards.size());
const qreal cardHeight = cards.at(0)->boundingRect().height();
const qreal offset = stackingOffset(cardHeight);
@@ -93,8 +94,9 @@ int SelectZone::calcDropIndexFromY(qreal dropY, qreal minOffset) const
void SelectZone::restoreStaleEscapedCards()
{
- if (!cardClipContainer)
+ if (!cardClipContainer) {
return;
+ }
for (auto *card : getLogic()->getCards()) {
// A card parented to the zone (instead of the clip container) should
// only occur while it is actively hovered. If hover cleanup was
@@ -108,10 +110,12 @@ void SelectZone::restoreStaleEscapedCards()
void SelectZone::layoutCardsVertically(const StackLayoutParams ¶ms)
{
const auto &cards = getLogic()->getCards();
- if (cards.isEmpty() || params.cardCount <= 0)
+ if (cards.isEmpty() || params.cardCount <= 0) {
return;
- if (params.cardCount > cards.size())
+ }
+ if (params.cardCount > cards.size()) {
return;
+ }
constexpr qreal xspace = 5;
const qreal cardWidth = cards.at(0)->boundingRect().width();
@@ -163,8 +167,9 @@ void SelectZone::onCardAdded(CardItem *addedCard)
void SelectZone::setupClipContainer(std::optional zValue)
{
- if (cardClipContainer)
+ if (cardClipContainer) {
return;
+ }
setFlag(QGraphicsItem::ItemClipsChildrenToShape, false);
@@ -209,15 +214,19 @@ void SelectZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
if (event->buttons().testFlag(Qt::LeftButton)) {
QPointF pos = event->pos();
- if (pos.x() < 0)
+ if (pos.x() < 0) {
pos.setX(0);
+ }
QRectF br = boundingRect();
- if (pos.x() > br.width())
+ if (pos.x() > br.width()) {
pos.setX(br.width());
- if (pos.y() < 0)
+ }
+ if (pos.y() < 0) {
pos.setY(0);
- if (pos.y() > br.height())
+ }
+ if (pos.y() > br.height()) {
pos.setY(br.height());
+ }
QRectF selectionRect = QRectF(selectionOrigin, pos).normalized();
for (auto card : getLogic()->getCards()) {
@@ -253,8 +262,9 @@ void SelectZone::mousePressEvent(QGraphicsSceneMouseEvent *event)
selectionOrigin = event->pos();
static_cast(scene())->startRubberBand(event->scenePos());
event->accept();
- } else
+ } else {
CardZone::mousePressEvent(event);
+ }
}
void SelectZone::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
diff --git a/cockatrice/src/game/zones/table_zone.cpp b/cockatrice/src/game/zones/table_zone.cpp
index 2a382fafe..5e7db3d09 100644
--- a/cockatrice/src/game/zones/table_zone.cpp
+++ b/cockatrice/src/game/zones/table_zone.cpp
@@ -108,8 +108,9 @@ void TableZone::paintLandDivider(QPainter *painter)
// Place the line 2 grid heights down then back it off just enough to allow
// some space between a 3-card stack and the land area.
qreal separatorY = MARGIN_TOP + 2 * (CardDimensions::HEIGHT + PADDING_Y) - STACKED_CARD_OFFSET_Y / 2;
- if (isInverted())
+ if (isInverted()) {
separatorY = height - separatorY;
+ }
painter->setPen(QColor(255, 255, 255, 40));
painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY));
}
@@ -157,8 +158,9 @@ void TableZone::reorganizeCards()
for (int i = 0; i < getLogic()->getCards().size(); ++i) {
QPoint gridPoint = getLogic()->getCards()[i]->getGridPos();
- if (gridPoint.x() == -1)
+ if (gridPoint.x() == -1) {
continue;
+ }
QPointF mapPoint = mapFromGrid(gridPoint);
qreal x = mapPoint.x();
@@ -167,8 +169,9 @@ void TableZone::reorganizeCards()
int numberAttachedCards = getLogic()->getCards()[i]->getAttachedCards().size();
qreal actualX = x + numberAttachedCards * STACKED_CARD_OFFSET_X;
qreal actualY = y;
- if (numberAttachedCards)
+ if (numberAttachedCards) {
actualY += 15;
+ }
getLogic()->getCards()[i]->setPos(actualX, actualY);
getLogic()->getCards()[i]->setRealZValue(ZValues::tableCardZValue(actualX, actualY));
@@ -227,16 +230,19 @@ void TableZone::resizeToContents()
int xMax = 0;
// Find rightmost card position, which includes the left margin amount.
- for (int i = 0; i < getLogic()->getCards().size(); ++i)
- if (getLogic()->getCards()[i]->pos().x() > xMax)
+ for (int i = 0; i < getLogic()->getCards().size(); ++i) {
+ if (getLogic()->getCards()[i]->pos().x() > xMax) {
xMax = (int)getLogic()->getCards()[i]->pos().x();
+ }
+ }
// Minimum width is the rightmost card position plus enough room for
// another card with padding, then margin.
currentMinimumWidth = xMax + (2 * CardDimensions::WIDTH) + PADDING_X + MARGIN_RIGHT;
- if (currentMinimumWidth < MIN_WIDTH)
+ if (currentMinimumWidth < MIN_WIDTH) {
currentMinimumWidth = MIN_WIDTH;
+ }
if (currentMinimumWidth != width) {
prepareGeometryChange();
@@ -247,9 +253,11 @@ void TableZone::resizeToContents()
CardItem *TableZone::getCardFromGrid(const QPoint &gridPoint) const
{
- for (int i = 0; i < getLogic()->getCards().size(); i++)
- if (getLogic()->getCards().at(i)->getGridPoint() == gridPoint)
+ for (int i = 0; i < getLogic()->getCards().size(); i++) {
+ if (getLogic()->getCards().at(i)->getGridPoint() == gridPoint) {
return getLogic()->getCards().at(i);
+ }
+ }
return 0;
}
@@ -266,8 +274,9 @@ void TableZone::computeCardStackWidths()
QMap cardStackCount;
for (int i = 0; i < getLogic()->getCards().size(); ++i) {
const QPoint &gridPoint = getLogic()->getCards()[i]->getGridPos();
- if (gridPoint.x() == -1)
+ if (gridPoint.x() == -1) {
continue;
+ }
const int key = getCardStackMapKey(gridPoint.x() / 3, gridPoint.y());
cardStackCount.insert(key, cardStackCount.value(key, 0) + 1);
@@ -277,16 +286,18 @@ void TableZone::computeCardStackWidths()
cardStackWidth.clear();
for (int i = 0; i < getLogic()->getCards().size(); ++i) {
const QPoint &gridPoint = getLogic()->getCards()[i]->getGridPos();
- if (gridPoint.x() == -1)
+ if (gridPoint.x() == -1) {
continue;
+ }
const int key = getCardStackMapKey(gridPoint.x() / 3, gridPoint.y());
const int stackCount = cardStackCount.value(key, 0);
- if (stackCount == 1)
+ if (stackCount == 1) {
cardStackWidth.insert(key, CardDimensions::WIDTH + getLogic()->getCards()[i]->getAttachedCards().size() *
STACKED_CARD_OFFSET_X);
- else
+ } else {
cardStackWidth.insert(key, CardDimensions::WIDTH + (stackCount - 1) * STACKED_CARD_OFFSET_X);
+ }
}
}
@@ -303,15 +314,17 @@ QPointF TableZone::mapFromGrid(QPoint gridPoint) const
x += cardStackWidth.value(key, CardDimensions::WIDTH) + PADDING_X;
}
- if (isInverted())
+ if (isInverted()) {
gridPoint.setY(TABLEROWS - 1 - gridPoint.y());
+ }
// Start with margin plus stacked card offset
y = MARGIN_TOP + (gridPoint.x() % 3) * STACKED_CARD_OFFSET_Y;
// Add in card size and padding for each row
- for (int i = 0; i < gridPoint.y(); ++i)
+ for (int i = 0; i < gridPoint.y(); ++i) {
y += CardDimensions::HEIGHT + PADDING_Y;
+ }
return QPointF(x, y);
}
@@ -330,8 +343,9 @@ QPoint TableZone::mapToGrid(const QPointF &mapPoint) const
gridPointY = clampValidTableRow(gridPointY);
- if (isInverted())
+ if (isInverted()) {
gridPointY = TABLEROWS - 1 - gridPointY;
+ }
// Calculating the x-coordinate of the grid space requires adding up the
// widths of each card stack along the row.
@@ -367,19 +381,23 @@ QPointF TableZone::closestGridPoint(const QPointF &point)
{
QPoint gridPoint = mapToGrid(point);
gridPoint.setX((gridPoint.x() / 3) * 3);
- if (getCardFromGrid(gridPoint))
+ if (getCardFromGrid(gridPoint)) {
gridPoint.setX(gridPoint.x() + 1);
- if (getCardFromGrid(gridPoint))
+ }
+ if (getCardFromGrid(gridPoint)) {
gridPoint.setX(gridPoint.x() + 1);
+ }
return mapFromGrid(gridPoint);
}
int TableZone::clampValidTableRow(const int row)
{
- if (row < 0)
+ if (row < 0) {
return 0;
- if (row >= TABLEROWS)
+ }
+ if (row >= TABLEROWS) {
return TABLEROWS - 1;
+ }
return row;
}
diff --git a/cockatrice/src/game/zones/view_zone.cpp b/cockatrice/src/game/zones/view_zone.cpp
index d2fd1e971..803f80f48 100644
--- a/cockatrice/src/game/zones/view_zone.cpp
+++ b/cockatrice/src/game/zones/view_zone.cpp
@@ -203,9 +203,9 @@ ZoneViewZone::GridSize ZoneViewZone::positionCardsForDisplay(CardList &cards, Ca
QString columnProp = extractor(c);
if (i) { // if not the first card
- if (columnProp == lastColumnProp)
+ if (columnProp == lastColumnProp) {
row++; // add below current card
- else { // if no match then move card to next column
+ } else { // if no match then move card to next column
col++;
row = 0;
}
@@ -233,8 +233,9 @@ ZoneViewZone::GridSize ZoneViewZone::positionCardsForDisplay(CardList &cards, Ca
cols = qCeil((double)cardCount / minRows);
}
- if (cols < 2)
+ if (cols < 2) {
cols = 2;
+ }
qCDebug(ViewZoneLog) << "reorganizeCards: rows=" << rows << "cols=" << cols;
diff --git a/cockatrice/src/game/zones/view_zone_widget.cpp b/cockatrice/src/game/zones/view_zone_widget.cpp
index 23d7d6a19..5893b8405 100644
--- a/cockatrice/src/game/zones/view_zone_widget.cpp
+++ b/cockatrice/src/game/zones/view_zone_widget.cpp
@@ -252,8 +252,9 @@ void ZoneViewWidget::retranslateUi()
void ZoneViewWidget::stopWindowDrag()
{
- if (!draggingWindow)
+ if (!draggingWindow) {
return;
+ }
draggingWindow = false;
ungrabMouse();
@@ -312,13 +313,15 @@ QGraphicsView *ZoneViewWidget::findDragView(QWidget *eventWidget) const
{
QWidget *current = eventWidget;
while (current) {
- if (auto *view = qobject_cast(current))
+ if (auto *view = qobject_cast(current)) {
return view;
+ }
current = current->parentWidget();
}
- if (scene() && !scene()->views().isEmpty())
+ if (scene() && !scene()->views().isEmpty()) {
return scene()->views().constFirst();
+ }
return nullptr;
}
@@ -346,8 +349,9 @@ bool ZoneViewWidget::windowFrameEvent(QEvent *event)
}
auto *me = dynamic_cast(event);
- if (!me)
+ if (!me) {
return QGraphicsWidget::windowFrameEvent(event);
+ }
switch (event->type()) {
case QEvent::GraphicsSceneMousePress:
@@ -506,8 +510,9 @@ void ZoneViewWidget::resizeToZoneContents(bool forceInitialHeight)
zone->setGeometry(QRectF(0, -scrollBar->value(), zoneContainer->size().width(), totalZoneHeight));
- if (layout())
+ if (layout()) {
layout()->invalidate();
+ }
}
void ZoneViewWidget::handleScrollBarChange(int value)
@@ -521,8 +526,9 @@ void ZoneViewWidget::closeEvent(QCloseEvent *event)
disconnect(zone, &ZoneViewZone::closed, this, 0);
// manually call zone->close in order to remove it from the origZones views
zone->close();
- if (shuffleCheckBox.isChecked())
+ if (shuffleCheckBox.isChecked()) {
player->getPlayerActions()->sendGameCommand(Command_Shuffle());
+ }
zoneDeleted();
event->accept();
}
@@ -536,8 +542,9 @@ void ZoneViewWidget::zoneDeleted()
void ZoneViewWidget::initStyleOption(QStyleOption *option) const
{
QStyleOptionTitleBar *titleBar = qstyleoption_cast(option);
- if (titleBar)
+ if (titleBar) {
titleBar->icon = QPixmap("theme:cockatrice");
+ }
}
/**
diff --git a/cockatrice/src/game_graphics/board/abstract_graphics_item.cpp b/cockatrice/src/game_graphics/board/abstract_graphics_item.cpp
index 05f4a41ab..8da8ab708 100644
--- a/cockatrice/src/game_graphics/board/abstract_graphics_item.cpp
+++ b/cockatrice/src/game_graphics/board/abstract_graphics_item.cpp
@@ -19,27 +19,29 @@ void AbstractGraphicsItem::paintNumberEllipse(int number,
QFontMetrics fm(font);
double w = 1.3 * fm.horizontalAdvance(numStr);
double h = fm.height() * 1.3;
- if (w < h)
+ if (w < h) {
w = h;
+ }
painter->setPen(QColor(255, 255, 255, 0));
painter->setBrush(QBrush(QColor(color)));
QRectF textRect;
- if (position == -1)
+ if (position == -1) {
textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h);
- else {
+ } else {
qreal xOffset = 10;
qreal yOffset = 20;
qreal spacing = 2;
- if (position < 2)
+ if (position < 2) {
textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0)
: (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)),
yOffset, w, h);
- else
+ } else {
textRect = QRectF(count == 3 ? ((boundingRect().width() - w) / 2.0)
: (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)),
yOffset + (spacing + h) * (position / 2), w, h);
+ }
}
painter->drawEllipse(textRect);
diff --git a/cockatrice/src/interface/card_picture_loader/card_picture_loader.cpp b/cockatrice/src/interface/card_picture_loader/card_picture_loader.cpp
index dbd51b973..2cd28c4d3 100644
--- a/cockatrice/src/interface/card_picture_loader/card_picture_loader.cpp
+++ b/cockatrice/src/interface/card_picture_loader/card_picture_loader.cpp
@@ -230,8 +230,9 @@ bool CardPictureLoader::hasCustomArt()
QFileInfo dir(it.next());
#endif
- if (it.fileName() == "downloadedPics")
+ if (it.fileName() == "downloadedPics") {
continue;
+ }
QDirIterator subIt(it.filePath(), QDir::Files, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);
if (subIt.hasNext()) {
diff --git a/cockatrice/src/interface/card_picture_loader/card_picture_to_load.cpp b/cockatrice/src/interface/card_picture_loader/card_picture_to_load.cpp
index d72226aab..f95d8ec8f 100644
--- a/cockatrice/src/interface/card_picture_loader/card_picture_to_load.cpp
+++ b/cockatrice/src/interface/card_picture_loader/card_picture_to_load.cpp
@@ -63,8 +63,9 @@ static PrintingInfo findPrintingForSet(const ExactCard &card, const QString &set
{
SetToPrintingsMap setsToPrintings = card.getInfo().getSets();
- if (!setsToPrintings.contains(setName))
+ if (!setsToPrintings.contains(setName)) {
return PrintingInfo();
+ }
for (const auto &printing : setsToPrintings[setName]) {
if (printing.getUuid() == card.getPrinting().getUuid()) {
diff --git a/cockatrice/src/interface/key_signals.cpp b/cockatrice/src/interface/key_signals.cpp
index b4a38fad5..a78997cc2 100644
--- a/cockatrice/src/interface/key_signals.cpp
+++ b/cockatrice/src/interface/key_signals.cpp
@@ -6,29 +6,33 @@ bool KeySignals::eventFilter(QObject * /*object*/, QEvent *event)
{
QKeyEvent *kevent;
- if (event->type() != QEvent::KeyPress)
+ if (event->type() != QEvent::KeyPress) {
return false;
+ }
kevent = static_cast(event);
switch (kevent->key()) {
case Qt::Key_Return:
case Qt::Key_Enter:
- if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier))
+ if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier)) {
emit onCtrlAltEnter();
- else if (kevent->modifiers() & Qt::ControlModifier)
+ } else if (kevent->modifiers() & Qt::ControlModifier) {
emit onCtrlEnter();
- else
+ } else {
emit onEnter();
+ }
break;
case Qt::Key_Right:
- if (kevent->modifiers() & Qt::ShiftModifier)
+ if (kevent->modifiers() & Qt::ShiftModifier) {
emit onShiftRight();
+ }
break;
case Qt::Key_Left:
- if (kevent->modifiers() & Qt::ShiftModifier)
+ if (kevent->modifiers() & Qt::ShiftModifier) {
emit onShiftLeft();
+ }
break;
case Qt::Key_Delete:
@@ -37,33 +41,39 @@ bool KeySignals::eventFilter(QObject * /*object*/, QEvent *event)
break;
case Qt::Key_Minus:
- if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier))
+ if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier)) {
emit onCtrlAltMinus();
+ }
break;
case Qt::Key_Equal:
- if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier))
+ if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier)) {
emit onCtrlAltEqual();
+ }
break;
case Qt::Key_BracketLeft:
- if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier))
+ if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier)) {
emit onCtrlAltLBracket();
+ }
break;
case Qt::Key_BracketRight:
- if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier))
+ if (kevent->modifiers().testFlag(Qt::AltModifier) && kevent->modifiers().testFlag(Qt::ControlModifier)) {
emit onCtrlAltRBracket();
+ }
break;
case Qt::Key_S:
- if (kevent->modifiers() & Qt::ShiftModifier)
+ if (kevent->modifiers() & Qt::ShiftModifier) {
emit onShiftS();
+ }
break;
case Qt::Key_C:
- if (kevent->modifiers() & Qt::ControlModifier)
+ if (kevent->modifiers() & Qt::ControlModifier) {
emit onCtrlC();
+ }
break;
default:
diff --git a/cockatrice/src/interface/logger.cpp b/cockatrice/src/interface/logger.cpp
index d6df065e8..3e00a0b24 100644
--- a/cockatrice/src/interface/logger.cpp
+++ b/cockatrice/src/interface/logger.cpp
@@ -66,8 +66,9 @@ void Logger::openLogfileSession()
void Logger::closeLogfileSession()
{
- if (!logToFileEnabled)
+ if (!logToFileEnabled) {
return;
+ }
logToFileEnabled = false;
fileStream << "Log session closed at " << QDateTime::currentDateTime().toString() << Qt::endl;
diff --git a/cockatrice/src/interface/pixel_map_generator.cpp b/cockatrice/src/interface/pixel_map_generator.cpp
index 382fff317..d3b0252a6 100644
--- a/cockatrice/src/interface/pixel_map_generator.cpp
+++ b/cockatrice/src/interface/pixel_map_generator.cpp
@@ -77,8 +77,9 @@ QMap PhasePixmapGenerator::pmCache;
QPixmap PhasePixmapGenerator::generatePixmap(int height, QString name)
{
QString key = name + QString::number(height);
- if (pmCache.contains(key))
+ if (pmCache.contains(key)) {
return pmCache.value(key);
+ }
QPixmap pixmap = tryLoadImage("theme:phases/" + name, QSize(height, height));
@@ -95,19 +96,22 @@ QPixmap CounterPixmapGenerator::generatePixmap(int height, QString name, bool hi
name = "general";
}
- if (highlight)
+ if (highlight) {
name.append("_highlight");
+ }
QString key = name + QString::number(height);
- if (pmCache.contains(key))
+ if (pmCache.contains(key)) {
return pmCache.value(key);
+ }
QPixmap pixmap = tryLoadImage("theme:counters/" + name, QSize(height, height));
// fall back to colorless counter if the name can't be found
if (pixmap.isNull()) {
name = "general";
- if (highlight)
+ if (highlight) {
name.append("_highlight");
+ }
pixmap = tryLoadImage("theme:counters/" + name, QSize(height, height));
}
@@ -118,17 +122,19 @@ QPixmap CounterPixmapGenerator::generatePixmap(int height, QString name, bool hi
QPixmap PingPixmapGenerator::generatePixmap(int size, int value, int max)
{
int key = size * 1000000 + max * 1000 + value;
- if (pmCache.contains(key))
+ if (pmCache.contains(key)) {
return pmCache.value(key);
+ }
QPixmap pixmap(size, size);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
QColor color;
- if ((max == -1) || (value == -1))
+ if ((max == -1) || (value == -1)) {
color = Qt::black;
- else
+ } else {
color.setHsv(120 * (1.0 - ((double)value / max)), 255, 255);
+ }
QRadialGradient g(QPointF((double)pixmap.width() / 2, (double)pixmap.height() / 2),
qMin(pixmap.width(), pixmap.height()) / 2.0);
@@ -145,11 +151,13 @@ QMap PingPixmapGenerator::pmCache;
QPixmap CountryPixmapGenerator::generatePixmap(int height, const QString &countryCode)
{
- if (countryCode.size() != 2)
+ if (countryCode.size() != 2) {
return QPixmap();
+ }
QString key = countryCode + QString::number(height);
- if (pmCache.contains(key))
+ if (pmCache.contains(key)) {
return pmCache.value(key);
+ }
int width = height * 2;
QPixmap pixmap = tryLoadImage("theme:countries/" + countryCode.toLower(), QSize(width, height), true);
@@ -352,8 +360,9 @@ QPixmap LockPixmapGenerator::generatePixmap(int height)
{
int key = height;
- if (pmCache.contains(key))
+ if (pmCache.contains(key)) {
return pmCache.value(key);
+ }
QPixmap pixmap = tryLoadImage("theme:icons/lock", QSize(height, height), true);
pmCache.insert(key, pixmap);
@@ -365,8 +374,9 @@ QMap LockPixmapGenerator::pmCache;
QPixmap DropdownIconPixmapGenerator::generatePixmap(int height, bool expanded)
{
QString key = QString::number(expanded) + ":" + QString::number(height);
- if (pmCache.contains(key))
+ if (pmCache.contains(key)) {
return pmCache.value(key);
+ }
QString name = expanded ? "dropdown_expanded" : "dropdown_collapsed";
QPixmap pixmap = tryLoadImage("theme:icons/" + name, QSize(height, height), true);
diff --git a/cockatrice/src/interface/theme_manager.cpp b/cockatrice/src/interface/theme_manager.cpp
index c7f259ec0..58fb62362 100644
--- a/cockatrice/src/interface/theme_manager.cpp
+++ b/cockatrice/src/interface/theme_manager.cpp
@@ -51,8 +51,9 @@ struct PaletteColorInfo
// Iterate through all color roles (excluding NoRole and NColorRoles)
for (int r = 0; r < QPalette::NColorRoles; ++r) {
auto role = static_cast(r);
- if (role == QPalette::NoRole)
+ if (role == QPalette::NoRole) {
continue;
+ }
PaletteColorInfo info;
info.group = group;
@@ -78,8 +79,9 @@ struct PaletteColorInfo
for (int r = 0; r < QPalette::NColorRoles; ++r) {
auto role = static_cast(r);
- if (role == QPalette::NoRole)
+ if (role == QPalette::NoRole) {
continue;
+ }
QColor color = palette.color(group, role);
qInfo().nospace() << qPrintable(QString("%1").arg(roleEnum.valueToKey(role), -20)) << " : "
diff --git a/cockatrice/src/interface/widgets/cards/card_group_display_widgets/card_group_display_widget.cpp b/cockatrice/src/interface/widgets/cards/card_group_display_widgets/card_group_display_widget.cpp
index fa304816f..5fb0cb343 100644
--- a/cockatrice/src/interface/widgets/cards/card_group_display_widgets/card_group_display_widget.cpp
+++ b/cockatrice/src/interface/widgets/cards/card_group_display_widgets/card_group_display_widget.cpp
@@ -95,8 +95,9 @@ void CardGroupDisplayWidget::onSelectionChanged(const QItemSelection &selected,
for (auto &range : deselected) {
for (int row = range.top(); row <= range.bottom(); ++row) {
QModelIndex idx = range.model()->index(row, 0, range.parent());
- if (proxyModel)
+ if (proxyModel) {
idx = proxyModel->mapToSource(idx);
+ }
auto it = indexToWidgetMap.find(QPersistentModelIndex(idx));
if (it != indexToWidgetMap.end()) {
diff --git a/cockatrice/src/interface/widgets/cards/card_info_display_widget.cpp b/cockatrice/src/interface/widgets/cards/card_info_display_widget.cpp
index 4930fbbfd..509a2d92f 100644
--- a/cockatrice/src/interface/widgets/cards/card_info_display_widget.cpp
+++ b/cockatrice/src/interface/widgets/cards/card_info_display_widget.cpp
@@ -43,11 +43,13 @@ CardInfoDisplayWidget::CardInfoDisplayWidget(const CardRef &cardRef, QWidget *pa
void CardInfoDisplayWidget::setCard(const ExactCard &card)
{
- if (exactCard)
+ if (exactCard) {
disconnect(exactCard.getCardPtr().data(), nullptr, this, nullptr);
+ }
exactCard = card;
- if (exactCard)
+ if (exactCard) {
connect(exactCard.getCardPtr().data(), &QObject::destroyed, this, &CardInfoDisplayWidget::clear);
+ }
text->setCard(exactCard);
pic->setCard(exactCard);
diff --git a/cockatrice/src/interface/widgets/cards/card_info_text_widget.cpp b/cockatrice/src/interface/widgets/cards/card_info_text_widget.cpp
index f5f343807..345eb9909 100644
--- a/cockatrice/src/interface/widgets/cards/card_info_text_widget.cpp
+++ b/cockatrice/src/interface/widgets/cards/card_info_text_widget.cpp
@@ -73,8 +73,9 @@ void CardInfoTextWidget::setCard(const ExactCard &exactCard)
QStringList cardProps = card->getProperties();
for (const QString &key : cardProps) {
- if (key.contains("-"))
+ if (key.contains("-")) {
continue;
+ }
QString keyText = Mtg::getNicePropertyName(key).toHtmlEscaped() + ":";
text +=
QString("| %1 | | %2 |
").arg(keyText, card->getProperty(key).toHtmlEscaped());
diff --git a/cockatrice/src/interface/widgets/deck_analytics/analytics_panel_widget_factory.cpp b/cockatrice/src/interface/widgets/deck_analytics/analytics_panel_widget_factory.cpp
index 7af641689..e807e9d47 100644
--- a/cockatrice/src/interface/widgets/deck_analytics/analytics_panel_widget_factory.cpp
+++ b/cockatrice/src/interface/widgets/deck_analytics/analytics_panel_widget_factory.cpp
@@ -17,8 +17,9 @@ AbstractAnalyticsPanelWidget *
AnalyticsPanelWidgetFactory::create(const QString &type, QWidget *parent, DeckListStatisticsAnalyzer *analyzer) const
{
auto it = widgets.find(type);
- if (it == widgets.end())
+ if (it == widgets.end()) {
return nullptr;
+ }
auto w = it->creator(parent, analyzer);
diff --git a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_base/mana_base_config_dialog.cpp b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_base/mana_base_config_dialog.cpp
index 3317486ea..83e35d57d 100644
--- a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_base/mana_base_config_dialog.cpp
+++ b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_base/mana_base_config_dialog.cpp
@@ -28,8 +28,9 @@ ManaBaseConfigDialog::ManaBaseConfigDialog(DeckListStatisticsAnalyzer *analyzer,
// select initial filters
for (int i = 0; i < filterList->count(); ++i) {
- if (config.filters.contains(filterList->item(i)->text()))
+ if (config.filters.contains(filterList->item(i)->text())) {
filterList->item(i)->setSelected(true);
+ }
}
buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
diff --git a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_config_dialog.cpp b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_config_dialog.cpp
index 38199656c..9e9ae98a6 100644
--- a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_config_dialog.cpp
+++ b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_config_dialog.cpp
@@ -69,8 +69,9 @@ void ManaCurveConfigDialog::setFromConfig(const ManaCurveConfig &cfg)
{
groupBy->setCurrentText(cfg.groupBy);
// restore filters
- for (int i = 0; i < filterList->count(); ++i)
+ for (int i = 0; i < filterList->count(); ++i) {
filterList->item(i)->setSelected(cfg.filters.contains(filterList->item(i)->text()));
+ }
showMain->setChecked(cfg.showMain);
showCatRows->setChecked(cfg.showCategoryRows);
@@ -81,8 +82,9 @@ void ManaCurveConfigDialog::accept()
cfg.groupBy = groupBy->currentText();
cfg.filters.clear();
- for (auto *item : filterList->selectedItems())
+ for (auto *item : filterList->selectedItems()) {
cfg.filters << item->text();
+ }
cfg.showMain = showMain->isChecked();
cfg.showCategoryRows = showCatRows->isChecked();
diff --git a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_total_widget.cpp b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_total_widget.cpp
index f059ff873..c04767015 100644
--- a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_total_widget.cpp
+++ b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_total_widget.cpp
@@ -51,15 +51,17 @@ void ManaCurveTotalWidget::updateDisplay(const QString &categoryName,
for (auto it = cmcIt->cbegin(); it != cmcIt->cend(); ++it) {
const QString &category = it.key();
- if (!config.filters.isEmpty() && !config.filters.contains(category))
+ if (!config.filters.isEmpty() && !config.filters.contains(category)) {
continue;
+ }
const int value = it.value();
QStringList cards;
const auto catIt = cardsMap.constFind(category);
- if (catIt != cardsMap.cend())
+ if (catIt != cardsMap.cend()) {
cards = catIt->value(cmc);
+ }
segments.push_back({category, value, cards, GameSpecificColors::MTG::colorHelper(category)});
}
diff --git a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_widget.cpp b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_widget.cpp
index e09ecfe87..b182bf954 100644
--- a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_widget.cpp
+++ b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_curve/mana_curve_widget.cpp
@@ -69,16 +69,18 @@ static void buildMapsByCategory(const QHash> &categoryC
const QString &category = catIt.key();
const auto &countsByCmc = catIt.value();
- for (auto it = countsByCmc.cbegin(); it != countsByCmc.cend(); ++it)
+ for (auto it = countsByCmc.cbegin(); it != countsByCmc.cend(); ++it) {
outCmcMap[it.key()][category] = it.value();
+ }
}
for (auto catIt = categoryCards.cbegin(); catIt != categoryCards.cend(); ++catIt) {
const QString &category = catIt.key();
const auto &cardsByCmc = catIt.value();
- for (auto it = cardsByCmc.cbegin(); it != cardsByCmc.cend(); ++it)
+ for (auto it = cardsByCmc.cbegin(); it != cardsByCmc.cend(); ++it) {
outCardsMap[category][it.key()] = it.value();
+ }
}
}
@@ -88,8 +90,9 @@ static void findGlobalCmcRange(const QHash> &categoryCo
maxCmc = 0;
for (const auto &countsByCmc : categoryCounts) {
- for (auto it = countsByCmc.cbegin(); it != countsByCmc.cend(); ++it)
+ for (auto it = countsByCmc.cbegin(); it != countsByCmc.cend(); ++it) {
maxCmc = qMax(maxCmc, it.key());
+ }
}
}
diff --git a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_devotion/mana_devotion_config_dialog.cpp b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_devotion/mana_devotion_config_dialog.cpp
index 80fd03928..b01c33ba5 100644
--- a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_devotion/mana_devotion_config_dialog.cpp
+++ b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_devotion/mana_devotion_config_dialog.cpp
@@ -26,8 +26,9 @@ ManaDevotionConfigDialog::ManaDevotionConfigDialog(DeckListStatisticsAnalyzer *a
// select initial filters
for (int i = 0; i < filterList->count(); ++i) {
- if (config.filters.contains(filterList->item(i)->text()))
+ if (config.filters.contains(filterList->item(i)->text())) {
filterList->item(i)->setSelected(true);
+ }
}
buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
diff --git a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_distribution/mana_distribution_config.cpp b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_distribution/mana_distribution_config.cpp
index f70f32d5b..01af9329c 100644
--- a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_distribution/mana_distribution_config.cpp
+++ b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_distribution/mana_distribution_config.cpp
@@ -24,8 +24,9 @@ ManaDistributionConfig ManaDistributionConfig::fromJson(const QJsonObject &o)
if (o.contains("filters")) {
config.filters.clear();
- for (auto v : o["filters"].toArray())
+ for (auto v : o["filters"].toArray()) {
config.filters << v.toString();
+ }
}
if (o.contains("showColorRows")) {
diff --git a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_distribution/mana_distribution_config_dialog.cpp b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_distribution/mana_distribution_config_dialog.cpp
index 7fe4d94e4..325c70028 100644
--- a/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_distribution/mana_distribution_config_dialog.cpp
+++ b/cockatrice/src/interface/widgets/deck_analytics/analyzer_modules/mana_distribution/mana_distribution_config_dialog.cpp
@@ -62,8 +62,9 @@ void ManaDistributionConfigDialog::setFromConfig(const ManaDistributionConfig &c
displayType->setCurrentText(cfg.displayType);
- for (int i = 0; i < filterList->count(); ++i)
+ for (int i = 0; i < filterList->count(); ++i) {
filterList->item(i)->setSelected(cfg.filters.contains(filterList->item(i)->text()));
+ }
showColorRows->setChecked(cfg.showColorRows);
}
@@ -74,8 +75,9 @@ void ManaDistributionConfigDialog::accept()
// Filters
cfg.filters.clear();
- for (auto *item : filterList->selectedItems())
+ for (auto *item : filterList->selectedItems()) {
cfg.filters << item->text();
+ }
cfg.showColorRows = showColorRows->isChecked();
diff --git a/cockatrice/src/interface/widgets/deck_analytics/deck_list_statistics_analyzer.cpp b/cockatrice/src/interface/widgets/deck_analytics/deck_list_statistics_analyzer.cpp
index 073b6d25c..add13ff21 100644
--- a/cockatrice/src/interface/widgets/deck_analytics/deck_list_statistics_analyzer.cpp
+++ b/cockatrice/src/interface/widgets/deck_analytics/deck_list_statistics_analyzer.cpp
@@ -191,10 +191,12 @@ double DeckListStatisticsAnalyzer::hypergeometric(int N, int K, int n, int k)
}
auto choose = [](int n, int r) -> double {
- if (r > n)
+ if (r > n) {
return 0.0;
- if (r == 0 || r == n)
+ }
+ if (r == 0 || r == n) {
return 1.0;
+ }
double res = 1.0;
for (int i = 1; i <= r; ++i) {
res *= (n - r + i);
diff --git a/cockatrice/src/interface/widgets/deck_editor/deck_editor_database_display_widget.cpp b/cockatrice/src/interface/widgets/deck_editor/deck_editor_database_display_widget.cpp
index 20eef180a..580db67f4 100644
--- a/cockatrice/src/interface/widgets/deck_editor/deck_editor_database_display_widget.cpp
+++ b/cockatrice/src/interface/widgets/deck_editor/deck_editor_database_display_widget.cpp
@@ -121,9 +121,10 @@ void DeckEditorDatabaseDisplayWidget::updateSearch(const QString &search)
{
databaseDisplayModel->setStringFilter(search);
QModelIndexList sel = databaseView->selectionModel()->selectedRows();
- if (sel.isEmpty() && databaseDisplayModel->rowCount())
+ if (sel.isEmpty() && databaseDisplayModel->rowCount()) {
databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0),
QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
+ }
}
void DeckEditorDatabaseDisplayWidget::clearAllDatabaseFilters()
diff --git a/cockatrice/src/interface/widgets/deck_editor/deck_editor_deck_dock_widget.cpp b/cockatrice/src/interface/widgets/deck_editor/deck_editor_deck_dock_widget.cpp
index f939ae99d..25d9db079 100644
--- a/cockatrice/src/interface/widgets/deck_editor/deck_editor_deck_dock_widget.cpp
+++ b/cockatrice/src/interface/widgets/deck_editor/deck_editor_deck_dock_widget.cpp
@@ -314,8 +314,9 @@ void DeckEditorDeckDockWidget::initializeFormats()
ExactCard DeckEditorDeckDockWidget::getCurrentCard()
{
QModelIndex current = deckView->selectionModel()->currentIndex();
- if (!current.isValid())
+ if (!current.isValid()) {
return {};
+ }
const QString cardName = current.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString();
const QString cardProviderID = current.siblingAtColumn(DeckListModelColumns::CARD_PROVIDER_ID).data().toString();
const QModelIndex gparent = current.parent().parent();
@@ -651,10 +652,12 @@ void DeckEditorDeckDockWidget::actSwapSelection()
void DeckEditorDeckDockWidget::actDecrementCard(const ExactCard &card, QString zoneName)
{
- if (!card)
+ if (!card) {
return;
- if (card.getInfo().getIsToken())
+ }
+ if (card.getInfo().getIsToken()) {
zoneName = DECK_ZONE_TOKENS;
+ }
deckStateManager->decrementCard(card, zoneName);
}
diff --git a/cockatrice/src/interface/widgets/deck_editor/deck_editor_filter_dock_widget.cpp b/cockatrice/src/interface/widgets/deck_editor/deck_editor_filter_dock_widget.cpp
index 8a9a6cdaa..6b18db82e 100644
--- a/cockatrice/src/interface/widgets/deck_editor/deck_editor_filter_dock_widget.cpp
+++ b/cockatrice/src/interface/widgets/deck_editor/deck_editor_filter_dock_widget.cpp
@@ -89,8 +89,9 @@ void DeckEditorFilterDockWidget::filterViewCustomContextMenu(const QPoint &point
QModelIndex idx;
idx = filterView->indexAt(point);
- if (!idx.isValid())
+ if (!idx.isValid()) {
return;
+ }
action = menu.addAction(QString("delete"));
action->setData(point);
@@ -105,8 +106,9 @@ void DeckEditorFilterDockWidget::filterRemove(const QAction *action)
point = action->data().toPoint();
idx = filterView->indexAt(point);
- if (!idx.isValid())
+ if (!idx.isValid()) {
return;
+ }
filterModel->removeRow(idx.row(), idx.parent());
}
diff --git a/cockatrice/src/interface/widgets/deck_editor/deck_list_style_proxy.cpp b/cockatrice/src/interface/widgets/deck_editor/deck_list_style_proxy.cpp
index 14c5faae7..e41529b22 100644
--- a/cockatrice/src/interface/widgets/deck_editor/deck_list_style_proxy.cpp
+++ b/cockatrice/src/interface/widgets/deck_editor/deck_list_style_proxy.cpp
@@ -8,8 +8,9 @@
QVariant DeckListStyleProxy::data(const QModelIndex &index, int role) const
{
QModelIndex src = mapToSource(index);
- if (!src.isValid())
+ if (!src.isValid()) {
return {};
+ }
QVariant value = QIdentityProxyModel::data(index, role);
diff --git a/cockatrice/src/interface/widgets/deck_editor/deck_state_manager.cpp b/cockatrice/src/interface/widgets/deck_editor/deck_state_manager.cpp
index 8da27b63c..6db8e5623 100644
--- a/cockatrice/src/interface/widgets/deck_editor/deck_state_manager.cpp
+++ b/cockatrice/src/interface/widgets/deck_editor/deck_state_manager.cpp
@@ -192,8 +192,9 @@ QModelIndex DeckStateManager::addCard(const ExactCard &card, const QString &zone
QModelIndex DeckStateManager::decrementCard(const ExactCard &card, const QString &zoneName)
{
- if (!card)
+ if (!card) {
return {};
+ }
QString providerId = card.getPrinting().getUuid();
QString collectorNumber = card.getPrinting().getProperty("num");
@@ -241,15 +242,17 @@ static bool doSwapCard(DeckListModel *model,
bool DeckStateManager::swapCardAtIndex(const QModelIndex &idx)
{
- if (!idx.isValid())
+ if (!idx.isValid()) {
return false;
+ }
QString cardName = idx.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString();
QString providerId = idx.siblingAtColumn(DeckListModelColumns::CARD_PROVIDER_ID).data().toString();
QModelIndex gparent = idx.parent().parent();
- if (!gparent.isValid())
+ if (!gparent.isValid()) {
return false;
+ }
QString zoneName = gparent.siblingAtColumn(DeckListModelColumns::CARD_NAME).data(Qt::EditRole).toString();
QString otherZoneName = zoneName == DECK_ZONE_MAIN ? DECK_ZONE_SIDE : DECK_ZONE_MAIN;
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp
index 0bb0eb1c9..fdbc90542 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp
@@ -261,13 +261,7 @@ void DlgConnect::updateDisplayInfo(const QString &saveName)
QStringList _data = uci.getServerInfo(saveName);
if (_data.isEmpty()) {
- _data << ""
- << ""
- << ""
- << ""
- << ""
- << ""
- << "";
+ _data << "" << "" << "" << "" << "" << "" << "";
}
bool savePasswordStatus = (_data.at(5) == "1");
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_create_game.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_create_game.cpp
index 7f109f600..30364f242 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_create_game.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_create_game.cpp
@@ -215,8 +215,9 @@ DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMapsetChecked(gameInfo.spectators_omniscient());
QSet types;
- for (int i = 0; i < gameInfo.game_types_size(); ++i)
+ for (int i = 0; i < gameInfo.game_types_size(); ++i) {
types.insert(gameInfo.game_types(i));
+ }
QMapIterator gameTypeIterator(gameTypes);
while (gameTypeIterator.hasNext()) {
@@ -316,9 +317,9 @@ void DlgCreateGame::checkResponse(const Response &response)
{
buttonBox->setEnabled(true);
- if (response.response_code() == Response::RespOk)
+ if (response.response_code() == Response::RespOk) {
accept();
- else {
+ } else {
QMessageBox::critical(this, tr("Error"), tr("Server error."));
return;
}
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_default_tags_editor.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_default_tags_editor.cpp
index 349f4ca4c..2d6ee7909 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_default_tags_editor.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_default_tags_editor.cpp
@@ -95,8 +95,9 @@ void DlgDefaultTagsEditor::addItem()
// Prevent duplicate tags
for (int i = 0; i < listWidget->count(); ++i) {
QWidget *widget = listWidget->itemWidget(listWidget->item(i));
- if (!widget)
+ if (!widget) {
continue;
+ }
QLineEdit *lineEdit = widget->findChild();
if (lineEdit && lineEdit->text() == newTag) {
QMessageBox::warning(this, tr("Duplicate Tag"), tr("This tag already exists."));
@@ -138,8 +139,9 @@ void DlgDefaultTagsEditor::confirmChanges()
QStringList updatedList;
for (int i = 0; i < listWidget->count(); ++i) {
QWidget *widget = listWidget->itemWidget(listWidget->item(i));
- if (!widget)
+ if (!widget) {
continue;
+ }
QLineEdit *lineEdit = widget->findChild();
if (lineEdit) {
updatedList.append(lineEdit->text());
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp
index fe9cd181c..381aa2b11 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp
@@ -149,8 +149,9 @@ void DlgEditTokens::actAddToken()
QString name;
for (;;) {
name = getTextWithMax(this, tr("Add token"), tr("Please enter the name of the token:"));
- if (name.isEmpty())
+ if (name.isEmpty()) {
return;
+ }
if (databaseModel->getDatabase()->query()->getCardInfo(name)) {
QMessageBox::critical(this, tr("Error"),
tr("The chosen name conflicts with an existing card or token.\nMake sure to enable "
@@ -181,18 +182,21 @@ void DlgEditTokens::actRemoveToken()
void DlgEditTokens::colorChanged(int colorIndex)
{
- if (currentCard)
+ if (currentCard) {
currentCard->setColors(QString(colorEdit->itemData(colorIndex).toChar()));
+ }
}
void DlgEditTokens::ptChanged(const QString &_pt)
{
- if (currentCard)
+ if (currentCard) {
currentCard->setPowTough(_pt);
+ }
}
void DlgEditTokens::annotationChanged(const QString &_annotation)
{
- if (currentCard)
+ if (currentCard) {
currentCard->setText(_annotation);
+ }
}
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_edit_user.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_edit_user.cpp
index dcfbc91e9..7015f9d47 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_edit_user.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_edit_user.cpp
@@ -26,8 +26,9 @@ DlgEditUser::DlgEditUser(QWidget *parent, QString email, QString country, QStrin
int i = 1;
for (const QString &c : countries) {
countryEdit->addItem(QPixmap("theme:countries/" + c.toLower()), c);
- if (c == country)
+ if (c == country) {
countryEdit->setCurrentIndex(i);
+ }
++i;
}
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_filter_games.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_filter_games.cpp
index 043b7a1cd..8f498cc2c 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_filter_games.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_filter_games.cpp
@@ -87,8 +87,9 @@ DlgFilterGames::DlgFilterGames(const QMap &_allGameTypes,
if (!allGameTypes.isEmpty()) {
gameTypeFilterGroupBox = new QGroupBox(tr("&Game types"));
gameTypeFilterGroupBox->setLayout(gameTypeFilterLayout);
- } else
+ } else {
gameTypeFilterGroupBox = nullptr;
+ }
auto *maxPlayersFilterMinLabel = new QLabel(tr("at &least:"));
maxPlayersFilterMinSpinBox = new QSpinBox;
@@ -226,8 +227,9 @@ QSet DlgFilterGames::getGameTypeFilter() const
QMapIterator i(gameTypeFilterCheckBoxes);
while (i.hasNext()) {
i.next();
- if (i.value()->isChecked())
+ if (i.value()->isChecked()) {
result.insert(i.key());
+ }
}
return result;
}
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp
index 6c46c7faf..c693fb02e 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp
@@ -217,8 +217,9 @@ void WndSets::saveHeaderState()
void WndSets::rebuildMainLayout(int actionToTake)
{
- if (mainLayout == nullptr)
+ if (mainLayout == nullptr) {
return;
+ }
switch (actionToTake) {
case NO_SETS_SELECTED:
@@ -382,12 +383,14 @@ void WndSets::actUp()
std::sort(rows.begin(), rows.end(), std::less());
QSet newRows;
- if (rows.empty())
+ if (rows.empty()) {
return;
+ }
for (auto i : rows) {
- if (i.row() <= 0)
+ if (i.row() <= 0) {
continue;
+ }
int oldRow = displayModel->mapToSource(i).row();
int newRow = i.row() - 1;
@@ -405,12 +408,14 @@ void WndSets::actDown()
std::sort(rows.begin(), rows.end(), [](const QModelIndex &a, const QModelIndex &b) { return b < a; });
QSet newRows;
- if (rows.empty())
+ if (rows.empty()) {
return;
+ }
for (auto i : rows) {
- if (i.row() >= displayModel->rowCount() - 1)
+ if (i.row() >= displayModel->rowCount() - 1) {
continue;
+ }
int oldRow = displayModel->mapToSource(i).row();
int newRow = i.row() + 1;
@@ -428,8 +433,9 @@ void WndSets::actTop()
QSet newRows;
int newRow = 0;
- if (rows.empty())
+ if (rows.empty()) {
return;
+ }
for (int i = 0; i < rows.length(); i++) {
int oldRow = displayModel->mapToSource(rows.at(i)).row();
@@ -454,8 +460,9 @@ void WndSets::actBottom()
QSet newRows;
int newRow = model->rowCount() - 1;
- if (rows.empty())
+ if (rows.empty()) {
return;
+ }
for (int i = 0; i < rows.length(); i++) {
int oldRow = displayModel->mapToSource(rows.at(i)).row();
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_register.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_register.cpp
index a3f232d9b..7b84a9a06 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_register.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_register.cpp
@@ -311,8 +311,9 @@ DlgRegister::DlgRegister(QWidget *parent) : QDialog(parent)
countryEdit->addItem(QPixmap("theme:countries/zw"), "zw");
countryEdit->setCurrentIndex(0);
QStringList countries = SettingsCache::instance().getCountries();
- for (const QString &c : countries)
+ for (const QString &c : countries) {
countryEdit->addItem(QPixmap("theme:countries/" + c.toLower()), c);
+ }
realnameLabel = new QLabel(tr("Real name:"));
realnameEdit = new QLineEdit();
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_select_set_for_cards.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_select_set_for_cards.cpp
index 5d9e2679c..bc846bf3d 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_select_set_for_cards.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_select_set_for_cards.cpp
@@ -237,8 +237,9 @@ QMap DlgSelectSetForCards::getSetsForCards()
for (auto cardName : cardNames) {
CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(cardName);
- if (!infoPtr)
+ if (!infoPtr) {
continue;
+ }
SetToPrintingsMap setMap = infoPtr->getSets();
for (auto &setName : setMap.keys()) {
@@ -359,8 +360,9 @@ QMap DlgSelectSetForCards::getCardsForSets()
for (auto cardName : cardNames) {
CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(cardName);
- if (!infoPtr)
+ if (!infoPtr) {
continue;
+ }
SetToPrintingsMap setMap = infoPtr->getSets();
for (auto it = setMap.begin(); it != setMap.end(); ++it) {
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp
index 6238bc80b..d6b5aa213 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp
@@ -272,8 +272,9 @@ QString GeneralSettingsPage::languageName(const QString &lang)
void GeneralSettingsPage::deckPathButtonClicked()
{
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), deckPathEdit->text());
- if (path.isEmpty())
+ if (path.isEmpty()) {
return;
+ }
deckPathEdit->setText(path);
SettingsCache::instance().setDeckPath(path);
@@ -282,8 +283,9 @@ void GeneralSettingsPage::deckPathButtonClicked()
void GeneralSettingsPage::filtersPathButtonClicked()
{
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), filtersPathEdit->text());
- if (path.isEmpty())
+ if (path.isEmpty()) {
return;
+ }
filtersPathEdit->setText(path);
SettingsCache::instance().setFiltersPath(path);
@@ -292,8 +294,9 @@ void GeneralSettingsPage::filtersPathButtonClicked()
void GeneralSettingsPage::replaysPathButtonClicked()
{
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), replaysPathEdit->text());
- if (path.isEmpty())
+ if (path.isEmpty()) {
return;
+ }
replaysPathEdit->setText(path);
SettingsCache::instance().setReplaysPath(path);
@@ -302,8 +305,9 @@ void GeneralSettingsPage::replaysPathButtonClicked()
void GeneralSettingsPage::picsPathButtonClicked()
{
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), picsPathEdit->text());
- if (path.isEmpty())
+ if (path.isEmpty()) {
return;
+ }
picsPathEdit->setText(path);
SettingsCache::instance().setPicsPath(path);
@@ -312,8 +316,9 @@ void GeneralSettingsPage::picsPathButtonClicked()
void GeneralSettingsPage::cardDatabasePathButtonClicked()
{
QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), cardDatabasePathEdit->text());
- if (path.isEmpty())
+ if (path.isEmpty()) {
return;
+ }
cardDatabasePathEdit->setText(path);
SettingsCache::instance().setCardDatabasePath(path);
@@ -322,8 +327,9 @@ void GeneralSettingsPage::cardDatabasePathButtonClicked()
void GeneralSettingsPage::customCardDatabaseButtonClicked()
{
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), customCardDatabasePathEdit->text());
- if (path.isEmpty())
+ if (path.isEmpty()) {
return;
+ }
customCardDatabasePathEdit->setText(path);
SettingsCache::instance().setCustomCardDatabasePath(path);
@@ -332,8 +338,9 @@ void GeneralSettingsPage::customCardDatabaseButtonClicked()
void GeneralSettingsPage::tokenDatabasePathButtonClicked()
{
QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), tokenDatabasePathEdit->text());
- if (path.isEmpty())
+ if (path.isEmpty()) {
return;
+ }
tokenDatabasePathEdit->setText(path);
SettingsCache::instance().setTokenDatabasePath(path);
@@ -418,8 +425,9 @@ AppearanceSettingsPage::AppearanceSettingsPage()
QStringList themeDirs = themeManager->getAvailableThemes().keys();
for (int i = 0; i < themeDirs.size(); i++) {
themeBox.addItem(themeDirs[i]);
- if (themeDirs[i] == themeName)
+ if (themeDirs[i] == themeName) {
themeBox.setCurrentIndex(i);
+ }
}
connect(&themeBox, qOverload(&QComboBox::currentIndexChanged), this, &AppearanceSettingsPage::themeBoxChanged);
@@ -560,8 +568,9 @@ AppearanceSettingsPage::AppearanceSettingsPage()
auto &cardCounterSettings = SettingsCache::instance().cardCounters();
auto newColor = QColorDialog::getColor(cardCounterSettings.color(index), this);
- if (!newColor.isValid())
+ if (!newColor.isValid()) {
return;
+ }
cardCounterSettings.setColor(index, newColor);
});
@@ -643,8 +652,9 @@ AppearanceSettingsPage::AppearanceSettingsPage()
void AppearanceSettingsPage::themeBoxChanged(int index)
{
QStringList themeDirs = themeManager->getAvailableThemes().keys();
- if (index >= 0 && index < themeDirs.count())
+ if (index >= 0 && index < themeDirs.count()) {
SettingsCache::instance().setThemeName(themeDirs.at(index));
+ }
}
void AppearanceSettingsPage::openThemeLocation()
@@ -1395,8 +1405,9 @@ MessagesSettingsPage::MessagesSettingsPage()
messageList = new QListWidget;
int count = SettingsCache::instance().messages().getCount();
- for (int i = 0; i < count; i++)
+ for (int i = 0; i < count; i++) {
messageList->addItem(SettingsCache::instance().messages().getMessageAt(i));
+ }
aAdd = new QAction(this);
aAdd->setIcon(QPixmap("theme:icons/increment"));
@@ -1496,8 +1507,9 @@ void MessagesSettingsPage::updateHighlightPreview()
void MessagesSettingsPage::storeSettings()
{
SettingsCache::instance().messages().setCount(messageList->count());
- for (int i = 0; i < messageList->count(); i++)
+ for (int i = 0; i < messageList->count(); i++) {
SettingsCache::instance().messages().setMessageAt(i, messageList->item(i)->text());
+ }
emit SettingsCache::instance().messages().messageMacrosChanged();
}
@@ -1570,8 +1582,9 @@ SoundSettingsPage::SoundSettingsPage()
QStringList themeDirs = soundEngine->getAvailableThemes().keys();
for (int i = 0; i < themeDirs.size(); i++) {
themeBox.addItem(themeDirs[i]);
- if (themeDirs[i] == themeName)
+ if (themeDirs[i] == themeName) {
themeBox.setCurrentIndex(i);
+ }
}
connect(&themeBox, qOverload(&QComboBox::currentIndexChanged), this, &SoundSettingsPage::themeBoxChanged);
@@ -1619,8 +1632,9 @@ SoundSettingsPage::SoundSettingsPage()
void SoundSettingsPage::themeBoxChanged(int index)
{
QStringList themeDirs = soundEngine->getAvailableThemes().keys();
- if (index >= 0 && index < themeDirs.count())
+ if (index >= 0 && index < themeDirs.count()) {
SettingsCache::instance().setSoundThemeName(themeDirs.at(index));
+ }
}
void SoundSettingsPage::masterVolumeChanged(int value)
@@ -1857,8 +1871,9 @@ void DlgSettings::createIcons()
void DlgSettings::changePage(QListWidgetItem *current, QListWidgetItem *previous)
{
- if (!current)
+ if (!current) {
current = previous;
+ }
pagesWidget->setCurrentIndex(contentsWidget->row(current));
}
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_update.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_update.cpp
index c9adeb270..417dcb3eb 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_update.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_update.cpp
@@ -154,8 +154,9 @@ void DlgUpdate::finishedUpdateCheck(bool needToUpdate, bool isCompatible, Releas
")
" + tr("Do you want to update now?"),
QMessageBox::Yes | QMessageBox::No);
- if (reply == QMessageBox::Yes)
+ if (reply == QMessageBox::Yes) {
downloadUpdate(release->getName());
+ }
} else {
QMessageBox::information(
this, tr("Update Available"),
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_view_log.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_view_log.cpp
index 3dd0fedb3..4eb054647 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_view_log.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_view_log.cpp
@@ -60,8 +60,9 @@ void DlgViewLog::actCopyToClipboard()
void DlgViewLog::loadInitialLogBuffer()
{
QList logBuffer = Logger::getInstance().getLogBuffer();
- for (const QString &message : logBuffer)
+ for (const QString &message : logBuffer) {
appendLogEntry(message);
+ }
}
void DlgViewLog::appendLogEntry(const QString &message)
diff --git a/cockatrice/src/interface/widgets/dialogs/tip_of_the_day.cpp b/cockatrice/src/interface/widgets/dialogs/tip_of_the_day.cpp
index 94996e975..66170792a 100644
--- a/cockatrice/src/interface/widgets/dialogs/tip_of_the_day.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/tip_of_the_day.cpp
@@ -73,8 +73,9 @@ TipsOfTheDay::~TipsOfTheDay()
QVariant TipsOfTheDay::data(const QModelIndex &index, int /*role*/) const
{
- if (!index.isValid() || index.row() >= tipList->size() || index.column() >= TIPDDBMODEL_COLUMNS)
+ if (!index.isValid() || index.row() >= tipList->size() || index.column() >= TIPDDBMODEL_COLUMNS) {
return QVariant();
+ }
TipOfTheDay tip = tipList->at(index.row());
switch (index.column()) {
diff --git a/cockatrice/src/interface/widgets/general/background_sources.h b/cockatrice/src/interface/widgets/general/background_sources.h
index 15bf1d377..04cafe830 100644
--- a/cockatrice/src/interface/widgets/general/background_sources.h
+++ b/cockatrice/src/interface/widgets/general/background_sources.h
@@ -40,8 +40,9 @@ public:
static QString toId(Type type)
{
for (const auto &e : all()) {
- if (e.type == type)
+ if (e.type == type) {
return e.id;
+ }
}
return {};
}
@@ -49,8 +50,9 @@ public:
static Type fromId(const QString &id)
{
for (const auto &e : all()) {
- if (id == e.id)
+ if (id == e.id) {
return e.type;
+ }
}
return Theme; // default
}
@@ -58,8 +60,9 @@ public:
static QString toDisplay(Type type)
{
for (const auto &e : all()) {
- if (e.type == type)
+ if (e.type == type) {
return QObject::tr(e.trKey);
+ }
}
return {};
}
diff --git a/cockatrice/src/interface/widgets/general/display/charts/bars/bar_chart_widget.cpp b/cockatrice/src/interface/widgets/general/display/charts/bars/bar_chart_widget.cpp
index 998808307..d9e108e6a 100644
--- a/cockatrice/src/interface/widgets/general/display/charts/bars/bar_chart_widget.cpp
+++ b/cockatrice/src/interface/widgets/general/display/charts/bars/bar_chart_widget.cpp
@@ -52,8 +52,9 @@ void BarChartWidget::paintEvent(QPaintEvent *)
int barAreaWidth = right - left;
int barCount = bars.size();
- if (barCount == 0)
+ if (barCount == 0) {
return;
+ }
int spacing = 6;
int barWidth = (barAreaWidth - (barCount - 1) * spacing) / barCount;
@@ -91,8 +92,9 @@ void BarChartWidget::paintEvent(QPaintEvent *)
for (int j = 0; j < bar.segments.size(); j++) {
const auto &seg = bar.segments[j];
int segHeight = (seg.value * barAreaHeight / highest);
- if (segHeight < 2 && seg.value > 0)
+ if (segHeight < 2 && seg.value > 0) {
segHeight = 2;
+ }
int topY = yCurrent - segHeight;
@@ -189,8 +191,9 @@ void BarChartWidget::mouseMoveEvent(QMouseEvent *e)
for (int i = 0; i < segments.size(); i++) {
const auto &seg = segments[i];
int segHeight = (seg.value * barAreaHeight / highest);
- if (segHeight < 2 && seg.value > 0)
+ if (segHeight < 2 && seg.value > 0) {
segHeight = 2;
+ }
int topY = yCurrent - segHeight;
int bottomY = yCurrent;
diff --git a/cockatrice/src/interface/widgets/general/display/charts/bars/color_bar.cpp b/cockatrice/src/interface/widgets/general/display/charts/bars/color_bar.cpp
index ed91ba03d..12ab5bb3b 100644
--- a/cockatrice/src/interface/widgets/general/display/charts/bars/color_bar.cpp
+++ b/cockatrice/src/interface/widgets/general/display/charts/bars/color_bar.cpp
@@ -26,16 +26,19 @@ QSize ColorBar::minimumSizeHint() const
void ColorBar::paintEvent(QPaintEvent *)
{
- if (colors.isEmpty())
+ if (colors.isEmpty()) {
return;
+ }
int total = 0;
- for (const auto &pair : colors)
+ for (const auto &pair : colors) {
total += pair.second;
+ }
// Prevent divide-by-zero
- if (total == 0)
+ if (total == 0) {
return;
+ }
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true);
@@ -63,8 +66,9 @@ void ColorBar::paintEvent(QPaintEvent *)
int segmentWidth = int(ratio * w);
// Ensure the segment width is at least 1 to avoid degenerate rectangles
- if (segmentWidth < 1)
+ if (segmentWidth < 1) {
segmentWidth = 1;
+ }
QColor base = colorFromName(key);
@@ -100,8 +104,9 @@ void ColorBar::leaveEvent(QEvent *)
void ColorBar::mouseMoveEvent(QMouseEvent *event)
{
- if (!isHovered || colors.isEmpty())
+ if (!isHovered || colors.isEmpty()) {
return;
+ }
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
int x = int(event->position().x());
@@ -112,18 +117,21 @@ void ColorBar::mouseMoveEvent(QMouseEvent *event)
#endif
QString text = tooltipForPosition(x);
- if (!text.isEmpty())
+ if (!text.isEmpty()) {
QToolTip::showText(gp, text, this);
+ }
}
QString ColorBar::tooltipForPosition(int x) const
{
int total = 0;
- for (const auto &pair : colors)
+ for (const auto &pair : colors) {
total += pair.second;
+ }
- if (total == 0)
+ if (total == 0) {
return {};
+ }
int pos = 0;
@@ -149,12 +157,14 @@ QColor ColorBar::colorFromName(const QString &name) const
{"W", QColor(235, 235, 230)}, {"B", QColor(30, 30, 30)},
};
- if (map.contains(name))
+ if (map.contains(name)) {
return map[name];
+ }
QColor c(name);
- if (!c.isValid())
+ if (!c.isValid()) {
c = Qt::gray;
+ }
return c;
}
\ No newline at end of file
diff --git a/cockatrice/src/interface/widgets/general/display/charts/bars/segmented_bar_widget.cpp b/cockatrice/src/interface/widgets/general/display/charts/bars/segmented_bar_widget.cpp
index e027aabdd..9bad32bda 100644
--- a/cockatrice/src/interface/widgets/general/display/charts/bars/segmented_bar_widget.cpp
+++ b/cockatrice/src/interface/widgets/general/display/charts/bars/segmented_bar_widget.cpp
@@ -44,8 +44,9 @@ void SegmentedBarWidget::paintEvent(QPaintEvent *)
const auto &seg = segments[i];
int segHeight = total > 0 ? (seg.value * barHeight / total) : 0;
- if (segHeight < 2)
+ if (segHeight < 2) {
segHeight = 2;
+ }
QRect r(barX, yCurrent - segHeight, barWidth, segHeight);
bool isTop = (i == segments.size() - 1);
@@ -110,8 +111,9 @@ int SegmentedBarWidget::segmentAt(int y) const
int top = currentTop - segHeight;
int bottom = currentTop;
- if (y >= top && y <= bottom)
+ if (y >= top && y <= bottom) {
return i;
+ }
currentTop -= segHeight;
}
diff --git a/cockatrice/src/interface/widgets/general/display/charts/pies/color_pie.cpp b/cockatrice/src/interface/widgets/general/display/charts/pies/color_pie.cpp
index 84232b36f..b129fbe18 100644
--- a/cockatrice/src/interface/widgets/general/display/charts/pies/color_pie.cpp
+++ b/cockatrice/src/interface/widgets/general/display/charts/pies/color_pie.cpp
@@ -157,8 +157,9 @@ QString ColorPie::tooltipForPoint(const QPoint &pt) const
QPointF v = pt - center;
double distance = std::hypot(v.x(), v.y());
- if (distance > size / 2.0)
+ if (distance > size / 2.0) {
return {};
+ }
double angle = std::atan2(-v.y(), v.x()) * 180.0 / M_PI;
if (angle < 0) {
diff --git a/cockatrice/src/interface/widgets/general/home_widget.cpp b/cockatrice/src/interface/widgets/general/home_widget.cpp
index a87d69119..e1687f997 100644
--- a/cockatrice/src/interface/widgets/general/home_widget.cpp
+++ b/cockatrice/src/interface/widgets/general/home_widget.cpp
@@ -139,8 +139,9 @@ void HomeWidget::updateRandomCard()
}
break;
}
- if (!newCard)
+ if (!newCard) {
return;
+ }
connect(newCard.getCardPtr().data(), &CardInfo::pixmapUpdated, this, &HomeWidget::updateBackgroundProperties);
backgroundSourceCard->setCard(newCard);
diff --git a/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_overlay_widget.cpp b/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_overlay_widget.cpp
index 1508b5243..69334d6f3 100644
--- a/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_overlay_widget.cpp
+++ b/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_overlay_widget.cpp
@@ -147,8 +147,9 @@ void PrintingSelectorCardOverlayWidget::updateVisibility()
*/
void PrintingSelectorCardOverlayWidget::updatePinBadgeVisibility()
{
- if (!pinBadge || !cardInfoPicture)
+ if (!pinBadge || !cardInfoPicture) {
return;
+ }
// Query the persisted preference override to decide whether this printing is pinned.
const auto &preferredProviderId =
diff --git a/cockatrice/src/interface/widgets/replay/replay_manager.cpp b/cockatrice/src/interface/widgets/replay/replay_manager.cpp
index fac3576f2..525b703db 100644
--- a/cockatrice/src/interface/widgets/replay/replay_manager.cpp
+++ b/cockatrice/src/interface/widgets/replay/replay_manager.cpp
@@ -19,16 +19,19 @@ ReplayManager::ReplayManager(TabGame *parent, GameReplay *_replay)
const int eventCount = replay->event_list_size();
for (int i = 0; i < eventCount; ++i) {
int j = i + 1;
- while ((j < eventCount) && (replay->event_list(j).seconds_elapsed() == lastEventTimestamp))
+ while ((j < eventCount) && (replay->event_list(j).seconds_elapsed() == lastEventTimestamp)) {
++j;
+ }
const int numberEventsThisSecond = j - i;
- for (int k = 0; k < numberEventsThisSecond; ++k)
+ for (int k = 0; k < numberEventsThisSecond; ++k) {
replayTimeline.append(replay->event_list(i + k).seconds_elapsed() * 1000 +
(int)((qreal)k / (qreal)numberEventsThisSecond * 1000));
+ }
- if (j < eventCount)
+ if (j < eventCount) {
lastEventTimestamp = replay->event_list(j).seconds_elapsed();
+ }
i += numberEventsThisSecond - 1;
}
}
diff --git a/cockatrice/src/interface/widgets/replay/replay_timeline_widget.cpp b/cockatrice/src/interface/widgets/replay/replay_timeline_widget.cpp
index 25ee58b67..508d45666 100644
--- a/cockatrice/src/interface/widgets/replay/replay_timeline_widget.cpp
+++ b/cockatrice/src/interface/widgets/replay/replay_timeline_widget.cpp
@@ -27,20 +27,23 @@ void ReplayTimelineWidget::setTimeline(const QList &_replayTimeline)
for (int i : replayTimeline) {
if (i > binEndTime) {
histogram.append(binValue);
- if (binValue > maxBinValue)
+ if (binValue > maxBinValue) {
maxBinValue = binValue;
+ }
while (i > binEndTime + BIN_LENGTH) {
histogram.append(0);
binEndTime += BIN_LENGTH;
}
binValue = 1;
binEndTime += BIN_LENGTH;
- } else
+ } else {
++binValue;
+ }
}
histogram.append(binValue);
- if (!replayTimeline.isEmpty())
+ if (!replayTimeline.isEmpty()) {
maxTime = replayTimeline.last();
+ }
update();
}
@@ -53,8 +56,9 @@ void ReplayTimelineWidget::paintEvent(QPaintEvent * /* event */)
qreal binWidth = (qreal)width() / histogram.size();
QPainterPath path;
path.moveTo(0, height() - 1);
- for (int i = 0; i < histogram.size(); ++i)
+ for (int i = 0; i < histogram.size(); ++i) {
path.lineTo(qRound(i * binWidth), (height() - 1) * (1.0 - (qreal)histogram[i] / maxBinValue));
+ }
path.lineTo(width() - 1, height() - 1);
path.lineTo(0, height() - 1);
painter.fillPath(path, Qt::black);
@@ -142,8 +146,9 @@ void ReplayTimelineWidget::replayTimerTimeout()
processNewEvents(NORMAL_PLAYBACK);
- if (!(currentVisualTime % 1000))
+ if (!(currentVisualTime % 1000)) {
update();
+ }
}
/// Processes all unprocessed events up to the current time.
@@ -156,12 +161,14 @@ void ReplayTimelineWidget::processNewEvents(PlaybackMode playbackMode)
// backwards skip => always skip reveal windows
// forwards skip => skip reveal windows that don't happen within a big skip of the target
- if (playbackMode == BACKWARD_SKIP || currentProcessedTime - replayTimeline[currentEvent] > BIG_SKIP_MS)
+ if (playbackMode == BACKWARD_SKIP || currentProcessedTime - replayTimeline[currentEvent] > BIG_SKIP_MS) {
options |= SKIP_REVEAL_WINDOW;
+ }
// backwards skip => always skip tap animation
- if (playbackMode == BACKWARD_SKIP)
+ if (playbackMode == BACKWARD_SKIP) {
options |= SKIP_TAP_ANIMATION;
+ }
emit processNextEvent(options);
++currentEvent;
diff --git a/cockatrice/src/interface/widgets/server/chat_view/chat_view.cpp b/cockatrice/src/interface/widgets/server/chat_view/chat_view.cpp
index 731f30942..1fe77e278 100644
--- a/cockatrice/src/interface/widgets/server/chat_view/chat_view.cpp
+++ b/cockatrice/src/interface/widgets/server/chat_view/chat_view.cpp
@@ -88,10 +88,11 @@ void ChatView::refreshBlockColors()
for (QTextBlock block = doc->begin(); block.isValid(); block = block.next()) {
QTextBlockFormat fmt = block.blockFormat();
- if (even)
+ if (even) {
fmt.setBackground(palette().base());
- else
+ } else {
fmt.setBackground(palette().window());
+ }
fmt.setForeground(palette().text());
@@ -121,10 +122,11 @@ QTextCursor ChatView::prepareBlock(bool same)
cursor.insertHtml("
");
} else {
QTextBlockFormat blockFormat;
- if (evenNumber)
+ if (evenNumber) {
blockFormat.setBackground(palette().base());
- else
+ } else {
blockFormat.setBackground(palette().window());
+ }
evenNumber = !evenNumber;
@@ -144,8 +146,9 @@ void ChatView::appendHtml(const QString &html)
{
bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
prepareBlock().insertHtml(html);
- if (atBottom)
+ if (atBottom) {
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
+ }
}
void ChatView::appendHtmlServerMessage(const QString &html, bool optionalIsBold, QString optionalFontColor)
@@ -156,12 +159,14 @@ void ChatView::appendHtmlServerMessage(const QString &html, bool optionalIsBold,
"" +
QDateTime::currentDateTime().toString("[hh:mm:ss] ") + html + "";
- if (optionalIsBold)
+ if (optionalIsBold) {
htmlText = "" + htmlText + "";
+ }
prepareBlock().insertHtml(htmlText);
- if (atBottom)
+ if (atBottom) {
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
+ }
}
void ChatView::appendCardTag(QTextCursor &cursor, const QString &cardName)
@@ -180,8 +185,9 @@ void ChatView::appendCardTag(QTextCursor &cursor, const QString &cardName)
void ChatView::appendUrlTag(QTextCursor &cursor, QString url)
{
- if (!url.contains("://"))
+ if (!url.contains("://")) {
url.prepend("https://");
+ }
QTextCharFormat oldFormat = cursor.charFormat();
QTextCharFormat anchorFormat = oldFormat;
@@ -317,8 +323,9 @@ void ChatView::appendMessage(QString message,
}
}
- if (atBottom)
+ if (atBottom) {
verticalScrollBar()->setValue(verticalScrollBar()->maximum());
+ }
}
void ChatView::checkTag(QTextCursor &cursor, QString &message)
@@ -327,10 +334,11 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message)
message = message.mid(6);
int closeTagIndex = message.indexOf("[/card]");
QString cardName = message.left(closeTagIndex);
- if (closeTagIndex == -1)
+ if (closeTagIndex == -1) {
message.clear();
- else
+ } else {
message = message.mid(closeTagIndex + 7);
+ }
appendCardTag(cursor, cardName);
return;
@@ -340,10 +348,11 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message)
message = message.mid(2);
int closeTagIndex = message.indexOf("]]");
QString cardName = message.left(closeTagIndex);
- if (closeTagIndex == -1)
+ if (closeTagIndex == -1) {
message.clear();
- else
+ } else {
message = message.mid(closeTagIndex + 2);
+ }
appendCardTag(cursor, cardName);
return;
@@ -353,10 +362,11 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message)
message = message.mid(5);
int closeTagIndex = message.indexOf("[/url]");
QString url = message.left(closeTagIndex);
- if (closeTagIndex == -1)
+ if (closeTagIndex == -1) {
message.clear();
- else
+ } else {
message = message.mid(closeTagIndex + 6);
+ }
appendUrlTag(cursor, url);
return;
@@ -587,8 +597,9 @@ QTextFragment ChatView::getFragmentUnderMouse(const QPoint &pos) const
QTextBlock::iterator it;
for (it = block.begin(); !(it.atEnd()); ++it) {
QTextFragment frag = it.fragment();
- if (frag.contains(cursor.position()))
+ if (frag.contains(cursor.position())) {
return frag;
+ }
}
return QTextFragment();
}
@@ -604,10 +615,11 @@ void ChatView::mouseMoveEvent(QMouseEvent *event)
if (scheme == "card") {
hoveredItemType = HoveredCard;
emit cardNameHovered(hoveredContent);
- } else if (scheme == "user")
+ } else if (scheme == "user") {
hoveredItemType = HoveredUser;
- else
+ } else {
hoveredItemType = HoveredUrl;
+ }
viewport()->setCursor(Qt::PointingHandCursor);
} else {
hoveredItemType = HoveredNothing;
@@ -650,8 +662,9 @@ void ChatView::mousePressEvent(QMouseEvent *event)
case Qt::LeftButton: {
if (event->modifiers() == Qt::ControlModifier) {
emit openMessageDialog(userName, true);
- } else
+ } else {
emit addMentionTag("@" + userName);
+ }
break;
}
default:
@@ -668,16 +681,18 @@ void ChatView::mousePressEvent(QMouseEvent *event)
void ChatView::mouseReleaseEvent(QMouseEvent *event)
{
- if ((event->button() == Qt::MiddleButton) || (event->button() == Qt::LeftButton))
+ if ((event->button() == Qt::MiddleButton) || (event->button() == Qt::LeftButton)) {
emit deleteCardInfoPopup(QString("_"));
+ }
QTextBrowser::mouseReleaseEvent(event);
}
void ChatView::openLink(const QUrl &link)
{
- if ((link.scheme() == "card") || (link.scheme() == "user"))
+ if ((link.scheme() == "card") || (link.scheme() == "user")) {
return;
+ }
QDesktopServices::openUrl(link);
}
diff --git a/cockatrice/src/interface/widgets/server/game_selector.cpp b/cockatrice/src/interface/widgets/server/game_selector.cpp
index dd29f4fc6..9a41ca6ce 100644
--- a/cockatrice/src/interface/widgets/server/game_selector.cpp
+++ b/cockatrice/src/interface/widgets/server/game_selector.cpp
@@ -61,14 +61,17 @@ GameSelector::GameSelector(AbstractClient *_client,
gameListView->setColumnWidth(3, gameListView->columnWidth(3) * 1.2);
// game type width
gameListView->setColumnWidth(4, gameListView->columnWidth(4) * 1.4);
- if (_room)
+ if (_room) {
gameListView->header()->hideSection(gameListModel->roomColIndex());
+ }
- if (room)
+ if (room) {
gameTypeMap = gameListModel->getGameTypes().value(room->getRoomId());
+ }
- if (showFilters && restoresettings)
+ if (showFilters && restoresettings) {
gameListProxyModel->loadFilterParameters(gameTypeMap);
+ }
gameListView->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
@@ -111,8 +114,9 @@ GameSelector::GameSelector(AbstractClient *_client,
buttonLayout->addWidget(clearFilterButton);
}
buttonLayout->addStretch();
- if (room)
+ if (room) {
buttonLayout->addWidget(createButton);
+ }
buttonLayout->addWidget(joinButton);
if (tabSupervisor->getUserInfo()->user_level() & ServerInfo_User::IsJudge) {
buttonLayout->addWidget(joinAsJudgeButton);
@@ -178,8 +182,9 @@ void GameSelector::actSetFilter()
{
DlgFilterGames dlg(gameTypeMap, gameListProxyModel, this);
- if (!dlg.exec())
+ if (!dlg.exec()) {
return;
+ }
gameListProxyModel->setGameFilters(dlg.getFilters());
gameListProxyModel->saveFilterParameters(gameTypeMap);
@@ -373,8 +378,9 @@ void GameSelector::joinGame(const bool asSpectator, const bool asJudge)
void GameSelector::disableButtons()
{
- if (createButton)
+ if (createButton) {
createButton->setEnabled(false);
+ }
joinButton->setEnabled(false);
spectateButton->setEnabled(false);
@@ -382,8 +388,9 @@ void GameSelector::disableButtons()
void GameSelector::enableButtons()
{
- if (createButton)
+ if (createButton) {
createButton->setEnabled(true);
+ }
// Enable buttons for the currently selected game
enableButtonsForIndex(gameListView->currentIndex());
@@ -391,8 +398,9 @@ void GameSelector::enableButtons()
void GameSelector::enableButtonsForIndex(const QModelIndex ¤t)
{
- if (!current.isValid())
+ if (!current.isValid()) {
return;
+ }
const ServerInfo_Game &game = gameListModel->getGame(current.data(Qt::UserRole).toInt());
bool overrideRestrictions = !tabSupervisor->getAdminLocked();
@@ -405,8 +413,9 @@ void GameSelector::retranslateUi()
{
filterButton->setText(tr("&Filter games"));
clearFilterButton->setText(tr("C&lear filter"));
- if (createButton)
+ if (createButton) {
createButton->setText(tr("C&reate"));
+ }
joinButton->setText(tr("&Join"));
joinAsJudgeButton->setText(tr("Join as judge"));
spectateButton->setText(tr("J&oin as spectator"));
diff --git a/cockatrice/src/interface/widgets/server/game_selector_quick_filter_toolbar.cpp b/cockatrice/src/interface/widgets/server/game_selector_quick_filter_toolbar.cpp
index 0e8a0d4c7..d668b1c33 100644
--- a/cockatrice/src/interface/widgets/server/game_selector_quick_filter_toolbar.cpp
+++ b/cockatrice/src/interface/widgets/server/game_selector_quick_filter_toolbar.cpp
@@ -59,8 +59,9 @@ GameSelectorQuickFilterToolBar::GameSelectorQuickFilterToolBar(QWidget *parent,
if (currentTypes.size() == 1) {
int typeId = *currentTypes.begin();
int index = filterToFormatComboBox->findData(typeId);
- if (index >= 0)
+ if (index >= 0) {
filterToFormatComboBox->setCurrentIndex(index);
+ }
} else {
filterToFormatComboBox->setCurrentIndex(0); // "All types" by default
}
diff --git a/cockatrice/src/interface/widgets/server/games_model.cpp b/cockatrice/src/interface/widgets/server/games_model.cpp
index e894ac4fd..1d30aa7ac 100644
--- a/cockatrice/src/interface/widgets/server/games_model.cpp
+++ b/cockatrice/src/interface/widgets/server/games_model.cpp
@@ -63,14 +63,18 @@ GamesModel::GamesModel(const QMap &_rooms, const QMap= gameList.size()) || (index.column() >= columnCount()))
+ }
+ if ((index.row() >= gameList.size()) || (index.column() >= columnCount())) {
return QVariant();
+ }
const ServerInfo_Game &gameentry = gameList[index.row()];
switch (index.column()) {
@@ -126,8 +130,9 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
case Qt::DisplayRole: {
QStringList result;
GameTypeMap gameTypeMap = gameTypes.value(gameentry.room_id());
- for (int i = gameentry.game_types_size() - 1; i >= 0; --i)
+ for (int i = gameentry.game_types_size() - 1; i >= 0; --i) {
result.append(gameTypeMap.value(gameentry.game_types(i)));
+ }
return result.join(", ");
}
case Qt::TextAlignmentRole:
@@ -140,14 +145,18 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
case SORT_ROLE:
case Qt::DisplayRole: {
QStringList result;
- if (gameentry.with_password())
+ if (gameentry.with_password()) {
result.append(tr("password"));
- if (gameentry.only_buddies())
+ }
+ if (gameentry.only_buddies()) {
result.append(tr("buddies only"));
- if (gameentry.only_registered())
+ }
+ if (gameentry.only_registered()) {
result.append(tr("reg. users only"));
- if (gameentry.share_decklists_on_load())
+ }
+ if (gameentry.share_decklists_on_load()) {
result.append(tr("open decklists"));
+ }
return result.join(", ");
}
case Qt::DecorationRole: {
@@ -205,8 +214,9 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
QVariant GamesModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const
{
- if ((role != Qt::DisplayRole) && (role != Qt::TextAlignmentRole))
+ if ((role != Qt::DisplayRole) && (role != Qt::TextAlignmentRole)) {
return QVariant();
+ }
switch (section) {
case ROOM:
return tr("Room");
@@ -296,8 +306,9 @@ void GamesProxyModel::setGameFilters(const GameFilterConfigs &_filters)
int GamesProxyModel::getNumFilteredGames() const
{
auto *model = qobject_cast(sourceModel());
- if (!model)
+ if (!model) {
return 0;
+ }
int numFilteredGames = 0;
for (int row = 0; row < model->rowCount(); ++row) {
@@ -384,8 +395,9 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow) const
static const QDate epochDate = QDateTime::fromSecsSinceEpoch(0, Qt::UTC).date();
#endif
auto *model = qobject_cast(sourceModel());
- if (!model)
+ if (!model) {
return false;
+ }
const ServerInfo_Game &game = model->getGame(sourceRow);
@@ -403,18 +415,25 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow) const
!userListProxy->isUserBuddy(QString::fromStdString(game.creator_info().name()))) {
return false;
}
- if (filters.hideFullGames && game.player_count() == game.max_players())
+ if (filters.hideFullGames && game.player_count() == game.max_players()) {
return false;
- if (filters.hideGamesThatStarted && game.started())
+ }
+ if (filters.hideGamesThatStarted && game.started()) {
return false;
- if (!userListProxy->isOwnUserRegistered())
- if (game.only_registered())
+ }
+ if (!userListProxy->isOwnUserRegistered()) {
+ if (game.only_registered()) {
return false;
- if (filters.hidePasswordProtectedGames && game.with_password())
+ }
+ }
+ if (filters.hidePasswordProtectedGames && game.with_password()) {
return false;
- if (!filters.gameNameFilter.isEmpty())
- if (!QString::fromStdString(game.description()).contains(filters.gameNameFilter, Qt::CaseInsensitive))
+ }
+ if (!filters.gameNameFilter.isEmpty()) {
+ if (!QString::fromStdString(game.description()).contains(filters.gameNameFilter, Qt::CaseInsensitive)) {
return false;
+ }
+ }
if (!filters.creatorNameFilters.isEmpty()) {
bool found = false;
for (const auto &createNameFilter : filters.creatorNameFilters) {
@@ -428,15 +447,19 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow) const
}
QSet gameTypes;
- for (int i = 0; i < game.game_types_size(); ++i)
+ for (int i = 0; i < game.game_types_size(); ++i) {
gameTypes.insert(game.game_types(i));
- if (!filters.gameTypeFilter.isEmpty() && gameTypes.intersect(filters.gameTypeFilter).isEmpty())
+ }
+ if (!filters.gameTypeFilter.isEmpty() && gameTypes.intersect(filters.gameTypeFilter).isEmpty()) {
return false;
+ }
- if (static_cast(game.max_players()) < filters.maxPlayersFilterMin)
+ if (static_cast(game.max_players()) < filters.maxPlayersFilterMin) {
return false;
- if (static_cast(game.max_players()) > filters.maxPlayersFilterMax)
+ }
+ if (static_cast(game.max_players()) > filters.maxPlayersFilterMax) {
return false;
+ }
if (filters.maxGameAge.isValid()) {
QDateTime now = QDateTime::currentDateTimeUtc();
@@ -451,14 +474,18 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow) const
}
if (filters.showOnlyIfSpectatorsCanWatch) {
- if (!game.spectators_allowed())
+ if (!game.spectators_allowed()) {
return false;
- if (!filters.showSpectatorPasswordProtected && game.spectators_need_password())
+ }
+ if (!filters.showSpectatorPasswordProtected && game.spectators_need_password()) {
return false;
- if (filters.showOnlyIfSpectatorsCanChat && !game.spectators_can_chat())
+ }
+ if (filters.showOnlyIfSpectatorsCanChat && !game.spectators_can_chat()) {
return false;
- if (filters.showOnlyIfSpectatorsCanSeeHands && !game.spectators_omniscient())
+ }
+ if (filters.showOnlyIfSpectatorsCanSeeHands && !game.spectators_omniscient()) {
return false;
+ }
}
return true;
}
diff --git a/cockatrice/src/interface/widgets/server/handle_public_servers.cpp b/cockatrice/src/interface/widgets/server/handle_public_servers.cpp
index f37c957a4..8ebb70e83 100644
--- a/cockatrice/src/interface/widgets/server/handle_public_servers.cpp
+++ b/cockatrice/src/interface/widgets/server/handle_public_servers.cpp
@@ -37,13 +37,11 @@ void HandlePublicServers::actFinishParsingDownloadedData()
QVariantMap jsonMap = jsonResponse.toVariant().toMap();
updateServerINISettings(jsonMap);
} else {
- qDebug() << "[PUBLIC SERVER HANDLER]"
- << "JSON Parsing Error:" << parseError.errorString();
+ qDebug() << "[PUBLIC SERVER HANDLER]" << "JSON Parsing Error:" << parseError.errorString();
emit sigPublicServersDownloadedUnsuccessfully(errorCode);
}
} else {
- qDebug() << "[PUBLIC SERVER HANDLER]"
- << "Error Downloading Public Servers" << errorCode;
+ qDebug() << "[PUBLIC SERVER HANDLER]" << "Error Downloading Public Servers" << errorCode;
emit sigPublicServersDownloadedUnsuccessfully(errorCode);
}
diff --git a/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.cpp b/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.cpp
index 6ca680c3f..a6add3fca 100644
--- a/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.cpp
+++ b/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.cpp
@@ -22,8 +22,9 @@ RemoteDeckList_TreeModel::DirectoryNode::~DirectoryNode()
void RemoteDeckList_TreeModel::DirectoryNode::clearTree()
{
- for (int i = 0; i < size(); ++i)
+ for (int i = 0; i < size(); ++i) {
delete at(i);
+ }
clear();
}
@@ -31,31 +32,37 @@ QString RemoteDeckList_TreeModel::DirectoryNode::getPath() const
{
if (parent) {
QString parentPath = parent->getPath();
- if (parentPath.isEmpty())
+ if (parentPath.isEmpty()) {
return name;
- else
+ } else {
return parentPath + "/" + name;
- } else
+ }
+ } else {
return name;
+ }
}
RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::DirectoryNode::getNodeByPath(QStringList path)
{
QString pathItem;
if (parent) {
- if (path.isEmpty())
+ if (path.isEmpty()) {
return this;
+ }
pathItem = path.takeFirst();
- if (pathItem.isEmpty() && name.isEmpty())
+ if (pathItem.isEmpty() && name.isEmpty()) {
return this;
+ }
}
for (int i = 0; i < size(); ++i) {
DirectoryNode *node = dynamic_cast(at(i));
- if (!node)
+ if (!node) {
continue;
- if (node->getName() == pathItem)
+ }
+ if (node->getName() == pathItem) {
return node->getNodeByPath(path);
+ }
}
return 0;
}
@@ -66,12 +73,14 @@ RemoteDeckList_TreeModel::FileNode *RemoteDeckList_TreeModel::DirectoryNode::get
DirectoryNode *node = dynamic_cast(at(i));
if (node) {
FileNode *result = node->getNodeById(id);
- if (result)
+ if (result) {
return result;
+ }
} else {
FileNode *file = dynamic_cast(at(i));
- if (file->getId() == id)
+ if (file->getId() == id) {
return file;
+ }
}
}
return 0;
@@ -95,10 +104,11 @@ RemoteDeckList_TreeModel::~RemoteDeckList_TreeModel()
int RemoteDeckList_TreeModel::rowCount(const QModelIndex &parent) const
{
DirectoryNode *node = getNode(parent);
- if (node)
+ if (node) {
return node->size();
- else
+ } else {
return 0;
+ }
}
int RemoteDeckList_TreeModel::columnCount(const QModelIndex & /*parent*/) const
@@ -108,10 +118,12 @@ int RemoteDeckList_TreeModel::columnCount(const QModelIndex & /*parent*/) const
QVariant RemoteDeckList_TreeModel::data(const QModelIndex &index, int role) const
{
- if (!index.isValid())
+ if (!index.isValid()) {
return QVariant();
- if (index.column() >= 3)
+ }
+ if (index.column() >= 3) {
return QVariant();
+ }
Node *temp = static_cast(index.internalPointer());
FileNode *file = dynamic_cast(temp);
@@ -157,8 +169,9 @@ QVariant RemoteDeckList_TreeModel::data(const QModelIndex &index, int role) cons
QVariant RemoteDeckList_TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
- if (orientation != Qt::Horizontal)
+ if (orientation != Qt::Horizontal) {
return QVariant();
+ }
switch (role) {
case Qt::TextAlignmentRole:
return section == 1 ? Qt::AlignRight : Qt::AlignLeft;
@@ -181,20 +194,23 @@ QVariant RemoteDeckList_TreeModel::headerData(int section, Qt::Orientation orien
QModelIndex RemoteDeckList_TreeModel::index(int row, int column, const QModelIndex &parent) const
{
- if (!hasIndex(row, column, parent))
+ if (!hasIndex(row, column, parent)) {
return QModelIndex();
+ }
DirectoryNode *parentNode = getNode(parent);
- if (row >= parentNode->size())
+ if (row >= parentNode->size()) {
return QModelIndex();
+ }
return createIndex(row, column, parentNode->at(row));
}
QModelIndex RemoteDeckList_TreeModel::parent(const QModelIndex &ind) const
{
- if (!ind.isValid())
+ if (!ind.isValid()) {
return QModelIndex();
+ }
return nodeToIndex(static_cast(ind.internalPointer())->getParent());
}
@@ -210,8 +226,9 @@ Qt::ItemFlags RemoteDeckList_TreeModel::flags(const QModelIndex &index) const
QModelIndex RemoteDeckList_TreeModel::nodeToIndex(Node *node) const
{
- if (node == nullptr || node == root)
+ if (node == nullptr || node == root) {
return QModelIndex();
+ }
return createIndex(node->getParent()->indexOf(node), 0, node);
}
@@ -233,10 +250,11 @@ void RemoteDeckList_TreeModel::addFolderToTree(const ServerInfo_DeckStorage_Tree
const int folderItemsSize = folderInfo.items_size();
for (int i = 0; i < folderItemsSize; ++i) {
const ServerInfo_DeckStorage_TreeItem &subItem = folderInfo.items(i);
- if (subItem.has_folder())
+ if (subItem.has_folder()) {
addFolderToTree(subItem, newItem);
- else
+ } else {
addFileToTree(subItem, newItem);
+ }
}
}
diff --git a/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.h b/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.h
index 8254eb57b..bca46fd47 100644
--- a/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.h
+++ b/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.h
@@ -75,8 +75,9 @@ public:
template [[nodiscard]] T getNode(const QModelIndex &index) const
{
- if (!index.isValid())
+ if (!index.isValid()) {
return dynamic_cast(root);
+ }
return dynamic_cast(static_cast(index.internalPointer()));
}
diff --git a/cockatrice/src/interface/widgets/server/remote/remote_replay_list_tree_widget.cpp b/cockatrice/src/interface/widgets/server/remote/remote_replay_list_tree_widget.cpp
index 5152880d9..1f034b767 100644
--- a/cockatrice/src/interface/widgets/server/remote/remote_replay_list_tree_widget.cpp
+++ b/cockatrice/src/interface/widgets/server/remote/remote_replay_list_tree_widget.cpp
@@ -14,14 +14,16 @@ const int RemoteReplayList_TreeModel::numberOfColumns = 6;
RemoteReplayList_TreeModel::MatchNode::MatchNode(const ServerInfo_ReplayMatch &_matchInfo)
: RemoteReplayList_TreeModel::Node(QString::fromStdString(_matchInfo.game_name())), matchInfo(_matchInfo)
{
- for (int i = 0; i < matchInfo.replay_list_size(); ++i)
+ for (int i = 0; i < matchInfo.replay_list_size(); ++i) {
append(new ReplayNode(matchInfo.replay_list(i), this));
+ }
}
RemoteReplayList_TreeModel::MatchNode::~MatchNode()
{
- for (int i = 0; i < size(); ++i)
+ for (int i = 0; i < size(); ++i) {
delete at(i);
+ }
}
void RemoteReplayList_TreeModel::MatchNode::updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo)
@@ -45,22 +47,26 @@ RemoteReplayList_TreeModel::~RemoteReplayList_TreeModel()
int RemoteReplayList_TreeModel::rowCount(const QModelIndex &parent) const
{
- if (!parent.isValid())
+ if (!parent.isValid()) {
return replayMatches.size();
+ }
auto *matchNode = dynamic_cast(static_cast(parent.internalPointer()));
- if (matchNode)
+ if (matchNode) {
return matchNode->size();
- else
+ } else {
return 0;
+ }
}
QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) const
{
- if (!index.isValid())
+ if (!index.isValid()) {
return QVariant();
- if (index.column() >= numberOfColumns)
+ }
+ if (index.column() >= numberOfColumns) {
return QVariant();
+ }
auto *replayNode = dynamic_cast(static_cast(index.internalPointer()));
if (replayNode) {
@@ -103,8 +109,9 @@ QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) co
return QString::fromStdString(matchInfo.game_name());
case 2: {
QStringList playerList;
- for (int i = 0; i < matchInfo.player_names_size(); ++i)
+ for (int i = 0; i < matchInfo.player_names_size(); ++i) {
playerList.append(QString::fromStdString(matchInfo.player_names(i)));
+ }
return playerList.join(", ");
}
case 4:
@@ -131,8 +138,9 @@ QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) co
QVariant RemoteReplayList_TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
- if (orientation != Qt::Horizontal)
+ if (orientation != Qt::Horizontal) {
return QVariant();
+ }
switch (role) {
case Qt::TextAlignmentRole:
switch (section) {
@@ -167,17 +175,20 @@ QVariant RemoteReplayList_TreeModel::headerData(int section, Qt::Orientation ori
QModelIndex RemoteReplayList_TreeModel::index(int row, int column, const QModelIndex &parent) const
{
- if (!hasIndex(row, column, parent))
+ if (!hasIndex(row, column, parent)) {
return QModelIndex();
+ }
auto *matchNode = dynamic_cast(static_cast(parent.internalPointer()));
if (matchNode) {
- if (row >= matchNode->size())
+ if (row >= matchNode->size()) {
return QModelIndex();
+ }
return createIndex(row, column, (void *)matchNode->at(row));
} else {
- if (row >= replayMatches.size())
+ if (row >= replayMatches.size()) {
return QModelIndex();
+ }
return createIndex(row, column, (void *)replayMatches[row]);
}
}
@@ -185,9 +196,9 @@ QModelIndex RemoteReplayList_TreeModel::index(int row, int column, const QModelI
QModelIndex RemoteReplayList_TreeModel::parent(const QModelIndex &ind) const
{
MatchNode const *matchNode = dynamic_cast(static_cast(ind.internalPointer()));
- if (matchNode)
+ if (matchNode) {
return QModelIndex();
- else {
+ } else {
auto *replayNode = dynamic_cast(static_cast(ind.internalPointer()));
return createIndex(replayNode->getParent()->indexOf(replayNode), 0, replayNode->getParent());
}
@@ -195,45 +206,52 @@ QModelIndex RemoteReplayList_TreeModel::parent(const QModelIndex &ind) const
Qt::ItemFlags RemoteReplayList_TreeModel::flags(const QModelIndex &index) const
{
- if (!index.isValid())
+ if (!index.isValid()) {
return Qt::NoItemFlags;
+ }
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
ServerInfo_Replay const *RemoteReplayList_TreeModel::getReplay(const QModelIndex &index) const
{
- if (!index.isValid())
+ if (!index.isValid()) {
return 0;
+ }
auto *node = dynamic_cast(static_cast(index.internalPointer()));
- if (!node)
+ if (!node) {
return 0;
+ }
return &node->getReplayInfo();
}
ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getReplayMatch(const QModelIndex &index) const
{
- if (!index.isValid())
+ if (!index.isValid()) {
return nullptr;
+ }
auto *node = dynamic_cast(static_cast(index.internalPointer()));
- if (!node)
+ if (!node) {
return nullptr;
+ }
return &node->getMatchInfo();
}
ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getEnclosingReplayMatch(const QModelIndex &index) const
{
- if (!index.isValid())
+ if (!index.isValid()) {
return nullptr;
+ }
auto *node = dynamic_cast(static_cast(index.internalPointer()));
if (!node) {
auto *_node = dynamic_cast(static_cast(index.internalPointer()));
- if (!_node)
+ if (!_node) {
return nullptr;
+ }
return &_node->getParent()->getMatchInfo();
}
return &node->getMatchInfo();
@@ -244,8 +262,9 @@ ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getEnclosingReplayMatc
*/
void RemoteReplayList_TreeModel::clearAll()
{
- for (int i = 0; i < replayMatches.size(); ++i)
+ for (int i = 0; i < replayMatches.size(); ++i) {
delete replayMatches[i];
+ }
replayMatches.clear();
}
@@ -275,24 +294,26 @@ void RemoteReplayList_TreeModel::addMatchInfo(const ServerInfo_ReplayMatch &matc
void RemoteReplayList_TreeModel::updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo)
{
- for (int i = 0; i < replayMatches.size(); ++i)
+ for (int i = 0; i < replayMatches.size(); ++i) {
if (replayMatches[i]->getMatchInfo().game_id() == gameId) {
replayMatches[i]->updateMatchInfo(matchInfo);
emit dataChanged(createIndex(i, 0, (void *)replayMatches[i]),
createIndex(i, numberOfColumns - 1, (void *)replayMatches[i]));
break;
}
+ }
}
void RemoteReplayList_TreeModel::removeMatchInfo(int gameId)
{
- for (int i = 0; i < replayMatches.size(); ++i)
+ for (int i = 0; i < replayMatches.size(); ++i) {
if (replayMatches[i]->getMatchInfo().game_id() == gameId) {
beginRemoveRows(QModelIndex(), i, i);
replayMatches.removeAt(i);
endRemoveRows();
break;
}
+ }
}
void RemoteReplayList_TreeModel::replayListFinished(const Response &r)
@@ -302,8 +323,9 @@ void RemoteReplayList_TreeModel::replayListFinished(const Response &r)
beginResetModel();
clearAll();
- for (int i = 0; i < resp.match_list_size(); ++i)
+ for (int i = 0; i < resp.match_list_size(); ++i) {
replayMatches.append(new MatchNode(resp.match_list(i)));
+ }
endResetModel();
emit treeRefreshed();
diff --git a/cockatrice/src/interface/widgets/server/user/user_context_menu.cpp b/cockatrice/src/interface/widgets/server/user/user_context_menu.cpp
index 7083ac899..195b1cc8d 100644
--- a/cockatrice/src/interface/widgets/server/user/user_context_menu.cpp
+++ b/cockatrice/src/interface/widgets/server/user/user_context_menu.cpp
@@ -192,13 +192,15 @@ void UserContextMenu::banUserHistory_processResponse(const Response &resp)
table->setMinimumSize(table->horizontalHeader()->length() + (table->columnCount() * 5),
table->verticalHeader()->length() + (table->rowCount() * 3));
table->show();
- } else
+ } else {
QMessageBox::information(static_cast(parent()), tr("Ban History"),
tr("User has never been banned."));
+ }
- } else
+ } else {
QMessageBox::critical(static_cast(parent()), tr("Ban History"),
tr("Failed to collect ban information."));
+ }
}
void UserContextMenu::warnUserHistory_processResponse(const Response &resp)
@@ -228,13 +230,15 @@ void UserContextMenu::warnUserHistory_processResponse(const Response &resp)
table->setMinimumSize(table->horizontalHeader()->length() + (table->columnCount() * 5),
table->verticalHeader()->length() + (table->rowCount() * 3));
table->show();
- } else
+ } else {
QMessageBox::information(static_cast(parent()), tr("Warning History"),
tr("User has never been warned."));
+ }
- } else
+ } else {
QMessageBox::critical(static_cast(parent()), tr("Warning History"),
tr("Failed to collect warning information."));
+ }
}
void UserContextMenu::getAdminNotes_processResponse(const Response &resp)
@@ -297,8 +301,9 @@ void UserContextMenu::warnUser_dialogFinished()
{
auto *dlg = static_cast(sender());
- if (dlg->getName().isEmpty() || userListProxy->getOwnUsername().simplified().isEmpty())
+ if (dlg->getName().isEmpty() || userListProxy->getOwnUsername().simplified().isEmpty()) {
return;
+ }
Command_WarnUser cmd;
cmd.set_user_name(dlg->getName().toStdString());
diff --git a/cockatrice/src/interface/widgets/server/user/user_info_box.cpp b/cockatrice/src/interface/widgets/server/user/user_info_box.cpp
index 9ae4a42c2..a9955ff3d 100644
--- a/cockatrice/src/interface/widgets/server/user/user_info_box.cpp
+++ b/cockatrice/src/interface/widgets/server/user/user_info_box.cpp
@@ -123,17 +123,19 @@ void UserInfoBox::updateInfo(const ServerInfo_User &user)
userLevelIcon.setPixmap(UserLevelPixmapGenerator::generatePixmap(15, userLevel, user.pawn_colors(), false,
QString::fromStdString(user.privlevel())));
QString userLevelText;
- if (userLevel.testFlag(ServerInfo_User::IsAdmin))
+ if (userLevel.testFlag(ServerInfo_User::IsAdmin)) {
userLevelText = tr("Administrator");
- else if (userLevel.testFlag(ServerInfo_User::IsModerator))
+ } else if (userLevel.testFlag(ServerInfo_User::IsModerator)) {
userLevelText = tr("Moderator");
- else if (userLevel.testFlag(ServerInfo_User::IsRegistered))
+ } else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) {
userLevelText = tr("Registered user");
- else
+ } else {
userLevelText = tr("Unregistered user");
+ }
- if (userLevel.testFlag(ServerInfo_User::IsJudge))
+ if (userLevel.testFlag(ServerInfo_User::IsJudge)) {
userLevelText += " | " + tr("Judge");
+ }
if (user.has_privlevel() && user.privlevel() != "NONE") {
userLevelText += " | " + QString("%1").arg(user.privlevel().c_str());
@@ -152,15 +154,17 @@ void UserInfoBox::updateInfo(const ServerInfo_User &user)
QString UserInfoBox::getAgeString(int ageSeconds)
{
QString accountAgeString = tr("Unknown");
- if (ageSeconds <= 0)
+ if (ageSeconds <= 0) {
return accountAgeString;
+ }
// secsSinceEpoch is in utc
auto secsSinceEpoch = QDateTime::currentSecsSinceEpoch() - ageSeconds;
// the date is in local time, fromSecsSinceEpoch expects a timestamp from utc and converts it to local time
auto date = QDateTime::fromSecsSinceEpoch(secsSinceEpoch).date();
- if (!date.isValid())
+ if (!date.isValid()) {
return accountAgeString;
+ }
// now can be local time as the date is also local time
auto now = QDate::currentDate();
@@ -218,8 +222,9 @@ void UserInfoBox::actEditInternal(const Response &r)
QString realName = QString::fromStdString(user.real_name());
DlgEditUser dlg(this, email, country, realName);
- if (!dlg.exec())
+ if (!dlg.exec()) {
return;
+ }
Command_AccountEdit cmd;
cmd.set_real_name(dlg.getRealName().toStdString());
@@ -231,8 +236,9 @@ void UserInfoBox::actEditInternal(const Response &r)
getTextWithMax(this, tr("Enter Password"),
tr("Password verification is required in order to change your email address"),
QLineEdit::Password, "", &ok);
- if (!ok)
+ if (!ok) {
return;
+ }
cmd.set_password_check(password.toStdString());
cmd.set_email(dlg.getEmail().toStdString());
} // servers that support password hash do not require all fields to be filled anymore
@@ -250,8 +256,9 @@ void UserInfoBox::actEditInternal(const Response &r)
void UserInfoBox::actPassword()
{
DlgEditPassword dlg(this);
- if (!dlg.exec())
+ if (!dlg.exec()) {
return;
+ }
auto oldPassword = dlg.getOldPassword();
auto newPassword = dlg.getNewPassword();
@@ -296,8 +303,9 @@ void UserInfoBox::changePassword(const QString &oldPassword, const QString &newP
void UserInfoBox::actAvatar()
{
DlgEditAvatar dlg(this);
- if (!dlg.exec())
+ if (!dlg.exec()) {
return;
+ }
Command_AccountImage cmd;
cmd.set_image(dlg.getImage().data(), dlg.getImage().size());
diff --git a/cockatrice/src/interface/widgets/server/user/user_info_connection.cpp b/cockatrice/src/interface/widgets/server/user/user_info_connection.cpp
index 069e438a9..919bc2707 100644
--- a/cockatrice/src/interface/widgets/server/user/user_info_connection.cpp
+++ b/cockatrice/src/interface/widgets/server/user/user_info_connection.cpp
@@ -53,8 +53,9 @@ QStringList UserConnection_Information::getServerInfo(const QString &find)
for (int i = 0; i < size; i++) {
QString _saveName = servers.getValue(QString("saveName%1").arg(i), "server", "server_details").toString();
- if (find != _saveName)
+ if (find != _saveName) {
continue;
+ }
QString serverName = servers.getValue(QString("server%1").arg(i), "server", "server_details").toString();
QString portNum = servers.getValue(QString("port%1").arg(i), "server", "server_details").toString();
@@ -73,8 +74,9 @@ QStringList UserConnection_Information::getServerInfo(const QString &find)
break;
}
- if (_server.empty())
+ if (_server.empty()) {
qCWarning(UserInfoConnectionLog) << "There was a problem!";
+ }
return _server;
}
diff --git a/cockatrice/src/interface/widgets/server/user/user_list_widget.cpp b/cockatrice/src/interface/widgets/server/user/user_list_widget.cpp
index 852743479..11c9b60eb 100644
--- a/cockatrice/src/interface/widgets/server/user/user_list_widget.cpp
+++ b/cockatrice/src/interface/widgets/server/user/user_list_widget.cpp
@@ -40,8 +40,9 @@ BanDialog::BanDialog(const ServerInfo_User &info, QWidget *parent) : QDialog(par
idBanCheckBox->setChecked(true);
idBanEdit = new QLineEdit(QString::fromStdString(info.clientid()));
idBanEdit->setMaxLength(MAX_NAME_LENGTH);
- if (QString::fromStdString(info.clientid()).isEmpty())
+ if (QString::fromStdString(info.clientid()).isEmpty()) {
idBanCheckBox->setChecked(false);
+ }
QGridLayout *banTypeGrid = new QGridLayout;
banTypeGrid->addWidget(nameBanCheckBox, 0, 0);
@@ -207,27 +208,30 @@ void BanDialog::okClicked()
return;
}
- if (nameBanCheckBox->isChecked())
+ if (nameBanCheckBox->isChecked()) {
if (nameBanEdit->text().simplified() == "") {
QMessageBox::critical(this, tr("Error"),
tr("You must have a value in the name ban when selecting the name ban checkbox."));
return;
}
+ }
- if (ipBanCheckBox->isChecked())
+ if (ipBanCheckBox->isChecked()) {
if (ipBanEdit->text().simplified() == "") {
QMessageBox::critical(this, tr("Error"),
tr("You must have a value in the ip ban when selecting the ip ban checkbox."));
return;
}
+ }
- if (idBanCheckBox->isChecked())
+ if (idBanCheckBox->isChecked()) {
if (idBanEdit->text().simplified() == "") {
QMessageBox::critical(
this, tr("Error"),
tr("You must have a value in the clientid ban when selecting the clientid ban checkbox."));
return;
}
+ }
accept();
}
@@ -461,14 +465,15 @@ void UserListWidget::processUserInfo(const ServerInfo_User &user, bool online)
{
const QString userName = QString::fromStdString(user.name());
UserListTWI *item = users.value(userName);
- if (item)
+ if (item) {
item->setUserInfo(user);
- else {
+ } else {
item = new UserListTWI(user);
users.insert(userName, item);
userTree->addTopLevelItem(item);
- if (online)
+ if (online) {
++onlineCount;
+ }
updateCount();
}
item->setOnline(online);
@@ -480,8 +485,9 @@ bool UserListWidget::deleteUser(const QString &userName)
if (twi) {
users.remove(userName);
userTree->takeTopLevelItem(userTree->indexOfTopLevelItem(twi));
- if (twi->data(0, Qt::UserRole + 1).toBool())
+ if (twi->data(0, Qt::UserRole + 1).toBool()) {
--onlineCount;
+ }
delete twi;
updateCount();
return true;
@@ -493,22 +499,25 @@ bool UserListWidget::deleteUser(const QString &userName)
void UserListWidget::setUserOnline(const QString &userName, bool online)
{
UserListTWI *twi = users.value(userName);
- if (!twi)
+ if (!twi) {
return;
+ }
twi->setOnline(online);
- if (online)
+ if (online) {
++onlineCount;
- else
+ } else {
--onlineCount;
+ }
updateCount();
}
void UserListWidget::updateCount()
{
QString str = titleStr;
- if ((type == BuddyList) || (type == IgnoreList))
+ if ((type == BuddyList) || (type == IgnoreList)) {
str = str.arg(onlineCount);
+ }
setTitle(str.arg(userTree->topLevelItemCount()));
}
diff --git a/cockatrice/src/interface/widgets/tabs/abstract_tab_deck_editor.cpp b/cockatrice/src/interface/widgets/tabs/abstract_tab_deck_editor.cpp
index a739ac83b..66609456e 100644
--- a/cockatrice/src/interface/widgets/tabs/abstract_tab_deck_editor.cpp
+++ b/cockatrice/src/interface/widgets/tabs/abstract_tab_deck_editor.cpp
@@ -144,10 +144,11 @@ void AbstractTabDeckEditor::addCardHelper(const ExactCard &card, const QString &
*/
void AbstractTabDeckEditor::actAddCard(const ExactCard &card)
{
- if (QApplication::keyboardModifiers() & Qt::ControlModifier)
+ if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
actAddCardToSideboard(card);
- else
+ } else {
addCardHelper(card, DECK_ZONE_MAIN);
+ }
deckMenu->setSaveStatus(true);
}
@@ -201,8 +202,9 @@ void AbstractTabDeckEditor::setDeck(const LoadedDeck &_deck)
void AbstractTabDeckEditor::actNewDeck()
{
auto deckOpenLocation = confirmOpen(false);
- if (deckOpenLocation == CANCELLED)
+ if (deckOpenLocation == CANCELLED) {
return;
+ }
if (deckOpenLocation == NEW_TAB) {
emit openDeckEditor(LoadedDeck());
@@ -227,22 +229,25 @@ void AbstractTabDeckEditor::cleanDeckAndResetModified()
AbstractTabDeckEditor::DeckOpenLocation AbstractTabDeckEditor::confirmOpen(const bool openInSameTabIfBlank)
{
if (SettingsCache::instance().getOpenDeckInNewTab()) {
- if (openInSameTabIfBlank && deckStateManager->isBlankNewDeck())
+ if (openInSameTabIfBlank && deckStateManager->isBlankNewDeck()) {
return SAME_TAB;
- else
+ } else {
return NEW_TAB;
+ }
}
- if (!deckStateManager->isModified())
+ if (!deckStateManager->isModified()) {
return SAME_TAB;
+ }
tabSupervisor->setCurrentWidget(this);
QMessageBox *msgBox = createSaveConfirmationWindow();
QPushButton *newTabButton = msgBox->addButton(tr("Open in new tab"), QMessageBox::ApplyRole);
int ret = msgBox->exec();
- if (msgBox->clickedButton() == newTabButton)
+ if (msgBox->clickedButton() == newTabButton) {
return NEW_TAB;
+ }
switch (ret) {
case QMessageBox::Save:
@@ -275,12 +280,14 @@ QMessageBox *AbstractTabDeckEditor::createSaveConfirmationWindow()
void AbstractTabDeckEditor::actLoadDeck()
{
auto deckOpenLocation = confirmOpen();
- if (deckOpenLocation == CANCELLED)
+ if (deckOpenLocation == CANCELLED) {
return;
+ }
DlgLoadDeck dialog(this);
- if (!dialog.exec())
+ if (!dialog.exec()) {
return;
+ }
QString fileName = dialog.selectedFiles().at(0);
openDeckFromFile(fileName, deckOpenLocation);
@@ -293,8 +300,9 @@ void AbstractTabDeckEditor::actLoadDeck()
void AbstractTabDeckEditor::actOpenRecent(const QString &fileName)
{
auto deckOpenLocation = confirmOpen();
- if (deckOpenLocation == CANCELLED)
+ if (deckOpenLocation == CANCELLED) {
return;
+ }
openDeckFromFile(fileName, deckOpenLocation);
}
@@ -347,8 +355,9 @@ bool AbstractTabDeckEditor::actSaveDeck()
return true;
}
- if (loadedDeck.lastLoadInfo.fileName.isEmpty())
+ if (loadedDeck.lastLoadInfo.fileName.isEmpty()) {
return actSaveDeckAs();
+ }
if (DeckLoader::saveToFile(loadedDeck)) {
deckStateManager->setModified(false);
@@ -376,8 +385,9 @@ bool AbstractTabDeckEditor::actSaveDeckAs()
dialog.setNameFilters(DeckLoader::FILE_NAME_FILTERS);
dialog.selectFile(deckList.getName().trimmed());
- if (!dialog.exec())
+ if (!dialog.exec()) {
return false;
+ }
QString fileName = dialog.selectedFiles().at(0);
DeckFileFormat::Format fmt = DeckFileFormat::getFormatFromName(fileName);
@@ -403,10 +413,11 @@ bool AbstractTabDeckEditor::actSaveDeckAs()
*/
void AbstractTabDeckEditor::saveDeckRemoteFinished(const Response &response)
{
- if (response.response_code() != Response::RespOk)
+ if (response.response_code() != Response::RespOk) {
QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved."));
- else
+ } else {
deckStateManager->setModified(false);
+ }
}
/**
@@ -416,12 +427,14 @@ void AbstractTabDeckEditor::saveDeckRemoteFinished(const Response &response)
void AbstractTabDeckEditor::actLoadDeckFromClipboard()
{
auto deckOpenLocation = confirmOpen();
- if (deckOpenLocation == CANCELLED)
+ if (deckOpenLocation == CANCELLED) {
return;
+ }
DlgLoadDeckFromClipboard dlg(this);
- if (!dlg.exec())
+ if (!dlg.exec()) {
return;
+ }
if (deckOpenLocation == NEW_TAB) {
emit openDeckEditor({.deckList = dlg.getDeckList()});
@@ -441,8 +454,9 @@ void AbstractTabDeckEditor::editDeckInClipboard(bool annotated)
{
LoadedDeck loadedDeck = deckStateManager->toLoadedDeck();
DlgEditDeckInClipboard dlg(loadedDeck.deckList, annotated, this);
- if (!dlg.exec())
+ if (!dlg.exec()) {
return;
+ }
setDeck({dlg.getDeckList(), loadedDeck.lastLoadInfo});
deckStateManager->setModified(true);
@@ -500,12 +514,14 @@ void AbstractTabDeckEditor::actPrintDeck()
void AbstractTabDeckEditor::actLoadDeckFromWebsite()
{
auto deckOpenLocation = confirmOpen();
- if (deckOpenLocation == CANCELLED)
+ if (deckOpenLocation == CANCELLED) {
return;
+ }
DlgLoadDeckFromWebsite dlg(this);
- if (!dlg.exec())
+ if (!dlg.exec()) {
return;
+ }
if (deckOpenLocation == NEW_TAB) {
emit openDeckEditor({.deckList = dlg.getDeck()});
@@ -588,10 +604,11 @@ bool AbstractTabDeckEditor::confirmClose()
if (deckStateManager->isModified()) {
tabSupervisor->setCurrentWidget(this);
int ret = createSaveConfirmationWindow()->exec();
- if (ret == QMessageBox::Save)
+ if (ret == QMessageBox::Save) {
return actSaveDeck();
- else if (ret == QMessageBox::Cancel)
+ } else if (ret == QMessageBox::Cancel) {
return false;
+ }
}
return true;
}
@@ -599,7 +616,8 @@ bool AbstractTabDeckEditor::confirmClose()
/** @brief Handles close requests from outside (tab manager). */
bool AbstractTabDeckEditor::closeRequest()
{
- if (!confirmClose())
+ if (!confirmClose()) {
return false;
+ }
return close();
}
diff --git a/cockatrice/src/interface/widgets/tabs/api/archidekt/api_response/archidekt_formats.h b/cockatrice/src/interface/widgets/tabs/api/archidekt/api_response/archidekt_formats.h
index ac1b66e14..5b5c16302 100644
--- a/cockatrice/src/interface/widgets/tabs/api/archidekt/api_response/archidekt_formats.h
+++ b/cockatrice/src/interface/widgets/tabs/api/archidekt/api_response/archidekt_formats.h
@@ -98,55 +98,79 @@ inline static DeckFormat apiNameToFormat(const QString &name)
{
const QString n = name.trimmed();
- if (n.compare("Standard", Qt::CaseInsensitive) == 0)
+ if (n.compare("Standard", Qt::CaseInsensitive) == 0) {
return DeckFormat::Standard;
- if (n.compare("Modern", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Modern", Qt::CaseInsensitive) == 0) {
return DeckFormat::Modern;
- if (n.compare("Commander", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Commander", Qt::CaseInsensitive) == 0) {
return DeckFormat::Commander;
- if (n.compare("Legacy", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Legacy", Qt::CaseInsensitive) == 0) {
return DeckFormat::Legacy;
- if (n.compare("Vintage", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Vintage", Qt::CaseInsensitive) == 0) {
return DeckFormat::Vintage;
- if (n.compare("Pauper", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Pauper", Qt::CaseInsensitive) == 0) {
return DeckFormat::Pauper;
- if (n.compare("Custom", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Custom", Qt::CaseInsensitive) == 0) {
return DeckFormat::Custom;
- if (n.compare("Frontier", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Frontier", Qt::CaseInsensitive) == 0) {
return DeckFormat::Frontier;
- if (n.compare("Future Std", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Future Std", Qt::CaseInsensitive) == 0) {
return DeckFormat::FutureStandard;
- if (n.compare("Penny Dreadful", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Penny Dreadful", Qt::CaseInsensitive) == 0) {
return DeckFormat::PennyDreadful;
- if (n.compare("1v1 Commander", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("1v1 Commander", Qt::CaseInsensitive) == 0) {
return DeckFormat::Commander1v1;
- if (n.compare("Dual Commander", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Dual Commander", Qt::CaseInsensitive) == 0) {
return DeckFormat::DualCommander;
- if (n.compare("Brawl", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Brawl", Qt::CaseInsensitive) == 0) {
return DeckFormat::Brawl;
+ }
- if (n.compare("Alchemy", Qt::CaseInsensitive) == 0)
+ if (n.compare("Alchemy", Qt::CaseInsensitive) == 0) {
return DeckFormat::Alchemy;
- if (n.compare("Historic", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Historic", Qt::CaseInsensitive) == 0) {
return DeckFormat::Historic;
- if (n.compare("Gladiator", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Gladiator", Qt::CaseInsensitive) == 0) {
return DeckFormat::Gladiator;
- if (n.compare("Oathbreaker", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Oathbreaker", Qt::CaseInsensitive) == 0) {
return DeckFormat::Oathbreaker;
- if (n.compare("Old School", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Old School", Qt::CaseInsensitive) == 0) {
return DeckFormat::OldSchool;
- if (n.compare("Pauper Commander", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Pauper Commander", Qt::CaseInsensitive) == 0) {
return DeckFormat::PauperCommander;
- if (n.compare("Pioneer", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Pioneer", Qt::CaseInsensitive) == 0) {
return DeckFormat::Pioneer;
- if (n.compare("PreDH", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("PreDH", Qt::CaseInsensitive) == 0) {
return DeckFormat::PreDH;
- if (n.compare("Premodern", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Premodern", Qt::CaseInsensitive) == 0) {
return DeckFormat::Premodern;
- if (n.compare("Standard Brawl", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Standard Brawl", Qt::CaseInsensitive) == 0) {
return DeckFormat::StandardBrawl;
- if (n.compare("Timeless", Qt::CaseInsensitive) == 0)
+ }
+ if (n.compare("Timeless", Qt::CaseInsensitive) == 0) {
return DeckFormat::Timeless;
+ }
return DeckFormat::Unknown;
}
diff --git a/cockatrice/src/interface/widgets/tabs/api/archidekt/display/archidekt_api_response_deck_entry_display_widget.cpp b/cockatrice/src/interface/widgets/tabs/api/archidekt/display/archidekt_api_response_deck_entry_display_widget.cpp
index c26220869..70156df79 100644
--- a/cockatrice/src/interface/widgets/tabs/api/archidekt/display/archidekt_api_response_deck_entry_display_widget.cpp
+++ b/cockatrice/src/interface/widgets/tabs/api/archidekt/display/archidekt_api_response_deck_entry_display_widget.cpp
@@ -20,21 +20,27 @@ static QString timeAgo(const QString ×tamp)
{
QDateTime dt = QDateTime::fromString(timestamp, Qt::ISODate);
- if (!dt.isValid())
+ if (!dt.isValid()) {
return timestamp; // fallback if parsing fails
+ }
qint64 secs = dt.secsTo(QDateTime::currentDateTimeUtc());
- if (secs < 60)
+ if (secs < 60) {
return QString("%1 seconds ago").arg(secs);
- if (secs < 3600)
+ }
+ if (secs < 3600) {
return QString("%1 minutes ago").arg(secs / 60);
- if (secs < 86400)
+ }
+ if (secs < 86400) {
return QString("%1 hours ago").arg(secs / 3600);
- if (secs < 30 * 86400)
+ }
+ if (secs < 30 * 86400) {
return QString("%1 days ago").arg(secs / 86400);
- if (secs < 365 * 86400)
+ }
+ if (secs < 365 * 86400) {
return QString("%1 months ago").arg(secs / (30 * 86400));
+ }
return QString("%1 years ago").arg(secs / (365 * 86400));
}
diff --git a/cockatrice/src/interface/widgets/tabs/api/archidekt/tab_archidekt.cpp b/cockatrice/src/interface/widgets/tabs/api/archidekt/tab_archidekt.cpp
index 352d55c79..9cac74d50 100644
--- a/cockatrice/src/interface/widgets/tabs/api/archidekt/tab_archidekt.cpp
+++ b/cockatrice/src/interface/widgets/tabs/api/archidekt/tab_archidekt.cpp
@@ -93,10 +93,11 @@ void TabArchidekt::initializeUi()
colorLayout->addWidget(manaSymbol);
connect(manaSymbol, &ManaSymbolWidget::colorToggled, this, [this](QChar c, bool active) {
- if (active)
+ if (active) {
activeColors.insert(c);
- else
+ } else {
activeColors.remove(c);
+ }
doSearch();
});
}
@@ -298,16 +299,18 @@ void TabArchidekt::setupFilterWidgets()
searchModel->updateSearchResults(text);
QString pattern = ".*" + QRegularExpression::escape(text) + ".*";
proxyModel->setFilterRegularExpression(QRegularExpression(pattern, QRegularExpression::CaseInsensitiveOption));
- if (!text.isEmpty())
+ if (!text.isEmpty()) {
completer->complete();
+ }
});
connect(commandersField, &QLineEdit::textChanged, this, [=](const QString &text) {
searchModel->updateSearchResults(text);
QString pattern = ".*" + QRegularExpression::escape(text) + ".*";
proxyModel->setFilterRegularExpression(QRegularExpression(pattern, QRegularExpression::CaseInsensitiveOption));
- if (!text.isEmpty())
+ if (!text.isEmpty()) {
completer->complete();
+ }
});
// Assemble secondary toolbar
@@ -492,12 +495,13 @@ QString TabArchidekt::buildSearchUrl()
QString logic = "GTE";
QString selected = minDeckSizeLogicCombo->currentText();
- if (selected == "≥")
+ if (selected == "≥") {
logic = "GTE";
- else if (selected == "≤")
+ } else if (selected == "≤") {
logic = "LTE";
- else
+ } else {
logic = "";
+ }
if (!logic.isEmpty()) {
query.addQueryItem("sizeLogic", logic);
diff --git a/cockatrice/src/interface/widgets/tabs/tab_deck_editor.cpp b/cockatrice/src/interface/widgets/tabs/tab_deck_editor.cpp
index 59ee6bdeb..77dfddb4a 100644
--- a/cockatrice/src/interface/widgets/tabs/tab_deck_editor.cpp
+++ b/cockatrice/src/interface/widgets/tabs/tab_deck_editor.cpp
@@ -81,8 +81,9 @@ void TabDeckEditor::createMenus()
QString TabDeckEditor::getTabText() const
{
QString result = tr("Deck: %1").arg(deckStateManager->getSimpleDeckName());
- if (deckStateManager->isModified())
+ if (deckStateManager->isModified()) {
result.prepend("* ");
+ }
return result;
}
@@ -137,9 +138,9 @@ void TabDeckEditor::loadLayout()
LayoutsSettings &layouts = SettingsCache::instance().layouts();
auto layoutState = layouts.getDeckEditorLayoutState();
- if (layoutState.isNull())
+ if (layoutState.isNull()) {
restartLayout();
- else {
+ } else {
restoreState(layoutState);
restoreGeometry(layouts.getDeckEditorGeometry());
}
diff --git a/cockatrice/src/interface/widgets/tabs/tab_deck_storage.cpp b/cockatrice/src/interface/widgets/tabs/tab_deck_storage.cpp
index 26e3f2ecf..bdf7901f1 100644
--- a/cockatrice/src/interface/widgets/tabs/tab_deck_storage.cpp
+++ b/cockatrice/src/interface/widgets/tabs/tab_deck_storage.cpp
@@ -181,8 +181,9 @@ void TabDeckStorage::retranslateUi()
QString TabDeckStorage::getTargetPath() const
{
RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem();
- if (curRight == nullptr)
+ if (curRight == nullptr) {
return {};
+ }
auto *dir = dynamic_cast(curRight);
if (dir == nullptr) {
dir = dynamic_cast(curRight->getParent());
@@ -237,13 +238,15 @@ void TabDeckStorage::actOpenLocalDeck()
{
QModelIndexList curLefts = localDirView->selectionModel()->selectedRows();
for (const auto &curLeft : curLefts) {
- if (localDirModel->isDir(curLeft))
+ if (localDirModel->isDir(curLeft)) {
continue;
+ }
QString filePath = localDirModel->filePath(curLeft);
std::optional deckOpt = DeckLoader::loadFromFile(filePath, DeckFileFormat::Cockatrice, true);
- if (!deckOpt)
+ if (!deckOpt) {
continue;
+ }
emit openDeckEditor(deckOpt.value());
}
@@ -320,10 +323,12 @@ void TabDeckStorage::uploadDeck(const QString &filePath, const QString &targetPa
QString deckName =
getTextWithMax(this, tr("Enter deck name"), tr("This decklist does not have a name.\nPlease enter a name:"),
QLineEdit::Normal, deckFileInfo.completeBaseName(), &ok);
- if (!ok)
+ if (!ok) {
return;
- if (deckName.isEmpty())
+ }
+ if (deckName.isEmpty()) {
deckName = tr("Unnamed deck");
+ }
deck.setName(deckName);
} else {
deck.setName(deck.getName().left(MAX_NAME_LENGTH));
@@ -372,8 +377,9 @@ void TabDeckStorage::actNewLocalFolder()
bool ok;
QString folderName =
QInputDialog::getText(this, tr("New folder"), tr("Name of new folder:"), QLineEdit::Normal, "", &ok);
- if (!ok || folderName.isEmpty())
+ if (!ok || folderName.isEmpty()) {
return;
+ }
localDirModel->mkdir(dirIndex, folderName);
}
@@ -387,8 +393,9 @@ void TabDeckStorage::actDeleteLocalDeck()
}
if (QMessageBox::warning(this, tr("Delete local file"), tr("Are you sure you want to delete the selected files?"),
- QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
+ QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
return;
+ }
for (const auto &curLeft : curLefts) {
if (curLeft.isValid()) {
@@ -414,8 +421,9 @@ void TabDeckStorage::actOpenRemoteDeck()
{
for (const auto &curRight : serverDirView->getCurrentSelection()) {
RemoteDeckList_TreeModel::FileNode *node = dynamic_cast(curRight);
- if (!node)
+ if (!node) {
continue;
+ }
Command_DeckDownload cmd;
cmd.set_deck_id(node->getId());
@@ -428,15 +436,17 @@ void TabDeckStorage::actOpenRemoteDeck()
void TabDeckStorage::openRemoteDeckFinished(const Response &r, const CommandContainer &commandContainer)
{
- if (r.response_code() != Response::RespOk)
+ if (r.response_code() != Response::RespOk) {
return;
+ }
const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext);
const Command_DeckDownload &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDownload::ext);
std::optional deckOpt = DeckLoader::loadFromRemote(QString::fromStdString(resp.deck()), cmd.deck_id());
- if (!deckOpt)
+ if (!deckOpt) {
return;
+ }
emit openDeckEditor(deckOpt.value());
}
@@ -488,8 +498,9 @@ void TabDeckStorage::downloadFinished(const Response &r,
const CommandContainer & /*commandContainer*/,
const QVariant &extraData)
{
- if (r.response_code() != Response::RespOk)
+ if (r.response_code() != Response::RespOk) {
return;
+ }
const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext);
QString filePath = extraData.toString();
@@ -504,12 +515,14 @@ void TabDeckStorage::actNewFolder()
QString targetPath = getTargetPath();
int max_length = MAX_NAME_LENGTH - targetPath.length() - 1; // generated length would be path + / + name
- if (max_length < 1) // can't create path that's short enough
+ if (max_length < 1) { // can't create path that's short enough
return;
+ }
QString folderName = getTextWithMax(this, tr("New folder"), tr("Name of new folder:"), max_length);
- if (folderName.isEmpty())
+ if (folderName.isEmpty()) {
return;
+ }
// '/' isn't a valid filename character on *nix so we're choosing to replace it with a different arbitrary
// character.
@@ -527,8 +540,9 @@ void TabDeckStorage::actNewFolder()
void TabDeckStorage::newFolderFinished(const Response &response, const CommandContainer &commandContainer)
{
- if (response.response_code() != Response::RespOk)
+ if (response.response_code() != Response::RespOk) {
return;
+ }
const Command_DeckNewDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckNewDir::ext);
serverDirView->addFolderToTree(QString::fromStdString(cmd.dir_name()),
@@ -562,8 +576,9 @@ void TabDeckStorage::deleteRemoteDeck(const RemoteDeckList_TreeModel::Node *curR
PendingCommand *pend;
if (const auto *dir = dynamic_cast(curRight)) {
QString targetPath = dir->getPath();
- if (targetPath.isEmpty())
+ if (targetPath.isEmpty()) {
return;
+ }
if (targetPath.length() > MAX_NAME_LENGTH) {
qCritical() << "target path to delete is too long" << targetPath;
return;
@@ -585,22 +600,26 @@ void TabDeckStorage::deleteRemoteDeck(const RemoteDeckList_TreeModel::Node *curR
void TabDeckStorage::deleteDeckFinished(const Response &response, const CommandContainer &commandContainer)
{
- if (response.response_code() != Response::RespOk)
+ if (response.response_code() != Response::RespOk) {
return;
+ }
const Command_DeckDel &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDel::ext);
RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeById(cmd.deck_id());
- if (toDelete)
+ if (toDelete) {
serverDirView->removeNode(toDelete);
+ }
}
void TabDeckStorage::deleteFolderFinished(const Response &response, const CommandContainer &commandContainer)
{
- if (response.response_code() != Response::RespOk)
+ if (response.response_code() != Response::RespOk) {
return;
+ }
const Command_DeckDelDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDelDir::ext);
RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeByPath(QString::fromStdString(cmd.path()));
- if (toDelete)
+ if (toDelete) {
serverDirView->removeNode(toDelete);
+ }
}
diff --git a/cockatrice/src/interface/widgets/tabs/tab_game.cpp b/cockatrice/src/interface/widgets/tabs/tab_game.cpp
index 161829b35..90756dad2 100644
--- a/cockatrice/src/interface/widgets/tabs/tab_game.cpp
+++ b/cockatrice/src/interface/widgets/tabs/tab_game.cpp
@@ -125,8 +125,9 @@ TabGame::TabGame(TabSupervisor *_tabSupervisor,
refreshShortcuts();
// append game to rooms game list for others to see
- for (int i = game->getGameMetaInfo()->gameTypesSize() - 1; i >= 0; i--)
+ for (int i = game->getGameMetaInfo()->gameTypesSize() - 1; i >= 0; i--) {
gameTypes.append(game->getGameMetaInfo()->findRoomGameType(i));
+ }
QTimer::singleShot(0, this, &TabGame::loadLayout);
}
@@ -282,12 +283,14 @@ void TabGame::retranslateUi()
updatePlayerListDockTitle();
cardInfoDock->setWindowTitle(tr("Card Info") + (cardInfoDock->isWindow() ? tabText : QString()));
messageLayoutDock->setWindowTitle(tr("Messages") + (messageLayoutDock->isWindow() ? tabText : QString()));
- if (replayDock)
+ if (replayDock) {
replayDock->setWindowTitle(tr("Replay Timeline") + (replayDock->isWindow() ? tabText : QString()));
+ }
if (phasesMenu) {
- for (int i = 0; i < phaseActions.size(); ++i)
+ for (int i = 0; i < phaseActions.size(); ++i) {
phaseActions[i]->setText(phasesToolbar->getLongPhaseName(i));
+ }
phasesMenu->setTitle(tr("&Phases"));
}
@@ -313,8 +316,9 @@ void TabGame::retranslateUi()
if (aRotateViewCCW) {
aRotateViewCCW->setText(tr("Rotate View Co&unterclockwise"));
}
- if (aGameInfo)
+ if (aGameInfo) {
aGameInfo->setText(tr("Game &information"));
+ }
if (aConcede) {
if (game->getPlayerManager()->isMainPlayerConceded()) {
aConcede->setText(tr("Un&concede"));
@@ -361,11 +365,13 @@ void TabGame::retranslateUi()
QMapIterator i(game->getPlayerManager()->getPlayers());
- while (i.hasNext())
+ while (i.hasNext()) {
i.next().value()->getGraphicsItem()->retranslateUi();
+ }
QMapIterator j(deckViewContainers);
- while (j.hasNext())
+ while (j.hasNext()) {
j.next().value()->playerDeckView->retranslateUi();
+ }
scene->retranslateUi();
}
@@ -484,18 +490,21 @@ void TabGame::actGameInfo()
void TabGame::actConcede()
{
Player *player = game->getPlayerManager()->getActiveLocalPlayer(game->getGameState()->getActivePlayer());
- if (player == nullptr)
+ if (player == nullptr) {
return;
+ }
if (!player->getConceded()) {
if (QMessageBox::question(this, tr("Concede"), tr("Are you sure you want to concede this game?"),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
return;
+ }
emit game->getPlayerManager()->activeLocalPlayerConceded();
} else {
if (QMessageBox::question(this, tr("Unconcede"),
tr("You have already conceded. Do you want to return to this game?"),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
return;
+ }
emit game->getPlayerManager()->activeLocalPlayerUnconceded();
}
}
@@ -511,20 +520,23 @@ bool TabGame::leaveGame()
if (!game->getPlayerManager()->isSpectator()) {
tabSupervisor->setCurrentWidget(this);
if (QMessageBox::question(this, tr("Leave game"), tr("Are you sure you want to leave this game?"),
- QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
return false;
+ }
}
- if (!replayDock)
+ if (!replayDock) {
emit gameLeft();
+ }
}
return true;
}
void TabGame::actSay()
{
- if (completer->popup()->isVisible())
+ if (completer->popup()->isVisible()) {
return;
+ }
if (sayEdit->text().startsWith("/card ")) {
cardInfoFrameWidget->setCard(sayEdit->text().mid(6));
@@ -569,8 +581,9 @@ void TabGame::actPhaseAction()
void TabGame::actNextPhase()
{
int phase = game->getGameState()->getCurrentPhase();
- if (++phase >= phasesToolbar->phaseCount())
+ if (++phase >= phasesToolbar->phaseCount()) {
phase = 0;
+ }
emit phaseChanged(phase);
}
@@ -596,8 +609,9 @@ void TabGame::actRemoveLocalArrows()
QMapIterator playerIterator(game->getPlayerManager()->getPlayers());
while (playerIterator.hasNext()) {
Player *player = playerIterator.next().value();
- if (!player->getPlayerInfo()->getLocal())
+ if (!player->getPlayerInfo()->getLocal()) {
continue;
+ }
QMapIterator arrowIterator(player->getArrows());
while (arrowIterator.hasNext()) {
ArrowItem *a = arrowIterator.next().value();
@@ -807,8 +821,9 @@ void TabGame::startGame(bool _resuming)
if (!_resuming) {
QMapIterator playerIterator(game->getPlayerManager()->getPlayers());
- while (playerIterator.hasNext())
+ while (playerIterator.hasNext()) {
playerIterator.next().value()->setGameStarted();
+ }
}
playerListWidget->setGameStarted(true, game->getGameState()->isResuming());
@@ -851,8 +866,9 @@ void TabGame::closeGame()
Player *TabGame::setActivePlayer(int id)
{
Player *player = game->getPlayerManager()->getPlayer(id);
- if (!player)
+ if (!player) {
return nullptr;
+ }
playerListWidget->setActivePlayer(id);
QMapIterator i(game->getPlayerManager()->getPlayers());
@@ -894,26 +910,31 @@ QString TabGame::getTabText() const
QString gameTypeInfo;
if (!gameTypes.empty()) {
gameTypeInfo = gameTypes.at(0);
- if (gameTypes.size() > 1)
+ if (gameTypes.size() > 1) {
gameTypeInfo.append("...");
+ }
}
QString gameDesc(game->getGameMetaInfo()->description());
QString gameId(QString::number(game->getGameMetaInfo()->gameId()));
QString tabText;
- if (replayDock)
+ if (replayDock) {
tabText.append(tr("Replay") + " ");
- if (!gameTypeInfo.isEmpty())
- tabText.append(gameTypeInfo + " ");
- if (!gameDesc.isEmpty()) {
- if (gameDesc.length() >= 15)
- tabText.append("| " + gameDesc.left(15) + "... ");
- else
- tabText.append("| " + gameDesc + " ");
}
- if (!tabText.isEmpty())
+ if (!gameTypeInfo.isEmpty()) {
+ tabText.append(gameTypeInfo + " ");
+ }
+ if (!gameDesc.isEmpty()) {
+ if (gameDesc.length() >= 15) {
+ tabText.append("| " + gameDesc.left(15) + "... ");
+ } else {
+ tabText.append("| " + gameDesc + " ");
+ }
+ }
+ if (!tabText.isEmpty()) {
tabText.append("| ");
+ }
tabText.append("#" + gameId);
return tabText;
@@ -1127,9 +1148,10 @@ void TabGame::actResetLayout()
void TabGame::createPlayAreaWidget(bool bReplay)
{
phasesToolbar = new PhasesToolbar;
- if (!bReplay)
+ if (!bReplay) {
connect(phasesToolbar, &PhasesToolbar::sendGameCommand, game->getGameEventHandler(),
qOverload(&GameEventHandler::sendGameCommand));
+ }
scene = new GameScene(phasesToolbar, this);
connect(game->getPlayerManager(), &PlayerManager::playerConceded, scene, &GameScene::rearrange);
connect(game->getPlayerManager(), &PlayerManager::playerCountChanged, scene, &GameScene::rearrange);
diff --git a/cockatrice/src/interface/widgets/tabs/tab_logs.cpp b/cockatrice/src/interface/widgets/tabs/tab_logs.cpp
index e4f699160..9a030e7d9 100644
--- a/cockatrice/src/interface/widgets/tabs/tab_logs.cpp
+++ b/cockatrice/src/interface/widgets/tabs/tab_logs.cpp
@@ -83,18 +83,22 @@ void TabLog::getClicked()
privateChat->setChecked(true);
}
- if (maximumResults->value() == 0)
+ if (maximumResults->value() == 0) {
maximumResults->setValue(1000);
+ }
int dateRange = 0;
- if (lastHour->isChecked())
+ if (lastHour->isChecked()) {
dateRange = 1;
+ }
- if (today->isChecked())
+ if (today->isChecked()) {
dateRange = 24;
+ }
- if (pastDays->isChecked())
+ if (pastDays->isChecked()) {
dateRange = pastXDays->value() * 24;
+ }
Command_ViewLogHistory cmd;
cmd.set_user_name(findUsername->text().toStdString());
diff --git a/cockatrice/src/interface/widgets/tabs/tab_message.cpp b/cockatrice/src/interface/widgets/tabs/tab_message.cpp
index bd0457990..d77cb0391 100644
--- a/cockatrice/src/interface/widgets/tabs/tab_message.cpp
+++ b/cockatrice/src/interface/widgets/tabs/tab_message.cpp
@@ -72,8 +72,9 @@ void TabMessage::retranslateUi()
void TabMessage::tabActivated()
{
- if (!sayEdit->hasFocus())
+ if (!sayEdit->hasFocus()) {
sayEdit->setFocus();
+ }
}
QString TabMessage::getUserName() const
@@ -94,8 +95,9 @@ void TabMessage::closeEvent(QCloseEvent *event)
void TabMessage::sendMessage()
{
- if (sayEdit->text().isEmpty() || !userOnline)
+ if (sayEdit->text().isEmpty() || !userOnline) {
return;
+ }
Command_Message cmd;
cmd.set_user_name(otherUserInfo->name());
@@ -110,9 +112,10 @@ void TabMessage::sendMessage()
void TabMessage::messageSent(const Response &response)
{
- if (response.response_code() == Response::RespInIgnoreList)
+ if (response.response_code() == Response::RespInIgnoreList) {
chatView->appendMessage(tr(
"This user is ignoring you, they cannot see your messages in main chat and you cannot join their games."));
+ }
}
void TabMessage::processUserMessageEvent(const Event_UserMessage &event)
@@ -120,12 +123,15 @@ void TabMessage::processUserMessageEvent(const Event_UserMessage &event)
auto userInfo = event.sender_name() == otherUserInfo->name() ? otherUserInfo : ownUserInfo;
chatView->appendMessage(QString::fromStdString(event.message()), {}, *userInfo, true);
- if (tabSupervisor->currentIndex() != tabSupervisor->indexOf(this))
+ if (tabSupervisor->currentIndex() != tabSupervisor->indexOf(this)) {
soundEngine->playSound("private_message");
- if (SettingsCache::instance().getShowMessagePopup() && shouldShowSystemPopup(event))
+ }
+ if (SettingsCache::instance().getShowMessagePopup() && shouldShowSystemPopup(event)) {
showSystemPopup(event);
- if (QString::fromStdString(event.sender_name()).toLower().simplified() == "servatrice")
+ }
+ if (QString::fromStdString(event.sender_name()).toLower().simplified() == "servatrice") {
sayEdit->setDisabled(true);
+ }
emit userEvent();
}
diff --git a/cockatrice/src/interface/widgets/tabs/tab_replays.cpp b/cockatrice/src/interface/widgets/tabs/tab_replays.cpp
index 570677ada..af52c038f 100644
--- a/cockatrice/src/interface/widgets/tabs/tab_replays.cpp
+++ b/cockatrice/src/interface/widgets/tabs/tab_replays.cpp
@@ -256,13 +256,15 @@ void TabReplays::actOpenLocalReplay()
{
QModelIndexList curLefts = localDirView->selectionModel()->selectedRows();
for (const auto &curLeft : curLefts) {
- if (localDirModel->isDir(curLeft))
+ if (localDirModel->isDir(curLeft)) {
continue;
+ }
QString filePath = localDirModel->filePath(curLeft);
QFile f(filePath);
- if (!f.open(QIODevice::ReadOnly))
+ if (!f.open(QIODevice::ReadOnly)) {
continue;
+ }
QByteArray _data = f.readAll();
f.close();
@@ -319,8 +321,9 @@ void TabReplays::actNewLocalFolder()
bool ok;
QString folderName =
QInputDialog::getText(this, tr("New folder"), tr("Name of new folder:"), QLineEdit::Normal, "", &ok);
- if (!ok || folderName.isEmpty())
+ if (!ok || folderName.isEmpty()) {
return;
+ }
localDirModel->mkdir(dirIndex, folderName);
}
@@ -378,8 +381,9 @@ void TabReplays::actOpenRemoteReplay()
void TabReplays::openRemoteReplayFinished(const Response &r)
{
- if (r.response_code() != Response::RespOk)
+ if (r.response_code() != Response::RespOk) {
return;
+ }
const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext);
GameReplay *replay = new GameReplay;
@@ -438,8 +442,9 @@ void TabReplays::downloadFinished(const Response &r,
const CommandContainer & /* commandContainer */,
const QVariant &extraData)
{
- if (r.response_code() != Response::RespOk)
+ if (r.response_code() != Response::RespOk) {
return;
+ }
const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext);
QString filePath = extraData.toString();
@@ -475,8 +480,9 @@ void TabReplays::actKeepRemoteReplay()
void TabReplays::keepRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer)
{
- if (r.response_code() != Response::RespOk)
+ if (r.response_code() != Response::RespOk) {
return;
+ }
const Command_ReplayModifyMatch &cmd =
commandContainer.session_command(0).GetExtension(Command_ReplayModifyMatch::ext);
@@ -513,8 +519,9 @@ void TabReplays::actDeleteRemoteReplay()
void TabReplays::deleteRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer)
{
- if (r.response_code() != Response::RespOk)
+ if (r.response_code() != Response::RespOk) {
return;
+ }
const Command_ReplayDeleteMatch &cmd =
commandContainer.session_command(0).GetExtension(Command_ReplayDeleteMatch::ext);
diff --git a/cockatrice/src/interface/widgets/tabs/tab_room.cpp b/cockatrice/src/interface/widgets/tabs/tab_room.cpp
index 92e38662b..424742e9b 100644
--- a/cockatrice/src/interface/widgets/tabs/tab_room.cpp
+++ b/cockatrice/src/interface/widgets/tabs/tab_room.cpp
@@ -41,9 +41,10 @@ TabRoom::TabRoom(TabSupervisor *_tabSupervisor,
ownUser(_ownUser), userListProxy(_tabSupervisor->getUserListManager())
{
const int gameTypeListSize = info.gametype_list_size();
- for (int i = 0; i < gameTypeListSize; ++i)
+ for (int i = 0; i < gameTypeListSize; ++i) {
gameTypes.insert(info.gametype_list(i).game_type_id(),
QString::fromStdString(info.gametype_list(i).description()));
+ }
QMap tempMap;
tempMap.insert(info.room_id(), gameTypes);
@@ -117,8 +118,9 @@ TabRoom::TabRoom(TabSupervisor *_tabSupervisor,
userList->sortItems();
const int gameListSize = info.game_list_size();
- for (int i = 0; i < gameListSize; ++i)
+ for (int i = 0; i < gameListSize; ++i) {
gameSelector->processGameInfo(info.game_list(i));
+ }
completer = new QCompleter(autocompleteUserList, sayEdit);
completer->setCaseSensitivity(Qt::CaseInsensitive);
@@ -182,8 +184,9 @@ void TabRoom::closeEvent(QCloseEvent *event)
void TabRoom::tabActivated()
{
- if (!sayEdit->hasFocus())
+ if (!sayEdit->hasFocus()) {
sayEdit->setFocus();
+ }
}
QString TabRoom::sanitizeHtml(QString dirty) const
@@ -211,8 +214,9 @@ void TabRoom::sendMessage()
void TabRoom::sayFinished(const Response &response)
{
- if (response.response_code() == Response::RespChatFlood)
+ if (response.response_code() == Response::RespChatFlood) {
chatView->appendMessage(tr("You are flooding the chat. Please wait a couple of seconds."));
+ }
}
void TabRoom::actClearChat()
@@ -258,8 +262,9 @@ void TabRoom::processRoomEvent(const RoomEvent &event)
void TabRoom::processListGamesEvent(const Event_ListGames &event)
{
const int gameListSize = event.game_list_size();
- for (int i = 0; i < gameListSize; ++i)
+ for (int i = 0; i < gameListSize; ++i) {
gameSelector->processGameInfo(event.game_list(i));
+ }
}
void TabRoom::processJoinRoomEvent(const Event_JoinRoom &event)
@@ -284,26 +289,30 @@ void TabRoom::processRoomSayEvent(const Event_RoomSay &event)
QString senderName = QString::fromStdString(event.name());
QString message = QString::fromStdString(event.message());
- if (userListProxy->isUserIgnored(senderName))
+ if (userListProxy->isUserIgnored(senderName)) {
return;
+ }
UserListTWI *twi = userList->getUsers().value(senderName);
ServerInfo_User userInfo = {};
if (twi) {
userInfo = twi->getUserInfo();
if (SettingsCache::instance().getIgnoreUnregisteredUsers() &&
- !UserLevelFlags(userInfo.user_level()).testFlag(ServerInfo_User::IsRegistered))
+ !UserLevelFlags(userInfo.user_level()).testFlag(ServerInfo_User::IsRegistered)) {
return;
+ }
}
- if (event.message_type() == Event_RoomSay::ChatHistory && !SettingsCache::instance().getRoomHistory())
+ if (event.message_type() == Event_RoomSay::ChatHistory && !SettingsCache::instance().getRoomHistory()) {
return;
+ }
- if (event.message_type() == Event_RoomSay::ChatHistory)
+ if (event.message_type() == Event_RoomSay::ChatHistory) {
message =
"[" +
QString(QDateTime::fromMSecsSinceEpoch(event.time_of()).toLocalTime().toString("d MMM yyyy HH:mm:ss")) +
"] " + message;
+ }
chatView->appendMessage(message, event.message_type(), userInfo, true);
emit userEvent(false);
diff --git a/cockatrice/src/interface/widgets/tabs/tab_server.cpp b/cockatrice/src/interface/widgets/tabs/tab_server.cpp
index aa52b4b1a..2fce5c1fa 100644
--- a/cockatrice/src/interface/widgets/tabs/tab_server.cpp
+++ b/cockatrice/src/interface/widgets/tabs/tab_server.cpp
@@ -69,27 +69,35 @@ void RoomSelector::processListRoomsEvent(const Event_ListRooms &event)
for (int j = 0; j < roomList->topLevelItemCount(); ++j) {
QTreeWidgetItem *twi = roomList->topLevelItem(j);
if (twi->data(0, Qt::UserRole).toInt() == room.room_id()) {
- if (room.has_name())
+ if (room.has_name()) {
twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name()));
- if (room.has_description())
+ }
+ if (room.has_description()) {
twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description()));
- if (room.has_permissionlevel())
+ }
+ if (room.has_permissionlevel()) {
twi->setData(2, Qt::DisplayRole, getRoomPermissionDisplay(room));
- if (room.has_player_count())
+ }
+ if (room.has_player_count()) {
twi->setData(3, Qt::DisplayRole, room.player_count());
- if (room.has_game_count())
+ }
+ if (room.has_game_count()) {
twi->setData(4, Qt::DisplayRole, room.game_count());
+ }
return;
}
}
QTreeWidgetItem *twi = new QTreeWidgetItem;
twi->setData(0, Qt::UserRole, room.room_id());
- if (room.has_name())
+ if (room.has_name()) {
twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name()));
- if (room.has_description())
+ }
+ if (room.has_description()) {
twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description()));
- if (room.has_permissionlevel())
+ }
+ if (room.has_permissionlevel()) {
twi->setData(2, Qt::DisplayRole, getRoomPermissionDisplay(room));
+ }
twi->setData(3, Qt::DisplayRole, room.player_count());
twi->setData(4, Qt::DisplayRole, room.game_count());
twi->setTextAlignment(2, Qt::AlignRight);
@@ -97,9 +105,11 @@ void RoomSelector::processListRoomsEvent(const Event_ListRooms &event)
twi->setTextAlignment(4, Qt::AlignRight);
roomList->addTopLevelItem(twi);
- if (room.has_auto_join())
- if (room.auto_join())
+ if (room.has_auto_join()) {
+ if (room.auto_join()) {
emit joinRoomRequest(room.room_id(), false);
+ }
+ }
}
}
@@ -113,10 +123,12 @@ QString RoomSelector::getRoomPermissionDisplay(const ServerInfo_Room &room)
*/
QString roomPermissionDisplay = QString::fromStdString(room.privilegelevel()).toLower();
- if (QString::fromStdString(room.permissionlevel()).toLower() != "none")
+ if (QString::fromStdString(room.permissionlevel()).toLower() != "none") {
roomPermissionDisplay = QString::fromStdString(room.permissionlevel()).toLower();
- if (roomPermissionDisplay == "") // catch all for misconfigured .ini room definitions
+ }
+ if (roomPermissionDisplay == "") { // catch all for misconfigured .ini room definitions
roomPermissionDisplay = "none";
+ }
return roomPermissionDisplay;
}
@@ -124,8 +136,9 @@ QString RoomSelector::getRoomPermissionDisplay(const ServerInfo_Room &room)
void RoomSelector::joinClicked()
{
QTreeWidgetItem *twi = roomList->currentItem();
- if (!twi)
+ if (!twi) {
return;
+ }
int id = twi->data(0, Qt::UserRole).toInt();
@@ -185,8 +198,9 @@ void TabServer::joinRoom(int id, bool setCurrent)
return;
}
- if (setCurrent)
+ if (setCurrent) {
tabSupervisor->setCurrentWidget((QWidget *)room);
+ }
}
void TabServer::joinRoomFinished(const Response &r,
diff --git a/cockatrice/src/interface/widgets/tabs/tab_supervisor.cpp b/cockatrice/src/interface/widgets/tabs/tab_supervisor.cpp
index b10d615ff..3566d6939 100644
--- a/cockatrice/src/interface/widgets/tabs/tab_supervisor.cpp
+++ b/cockatrice/src/interface/widgets/tabs/tab_supervisor.cpp
@@ -86,18 +86,22 @@ void CloseButton::paintEvent(QPaintEvent * /*event*/)
QStyleOption opt;
opt.initFrom(this);
opt.state |= QStyle::State_AutoRaise;
- if (isEnabled() && underMouse() && !isChecked() && !isDown())
+ if (isEnabled() && underMouse() && !isChecked() && !isDown()) {
opt.state |= QStyle::State_Raised;
- if (isChecked())
+ }
+ if (isChecked()) {
opt.state |= QStyle::State_On;
- if (isDown())
+ }
+ if (isDown()) {
opt.state |= QStyle::State_Sunken;
+ }
if (const auto *tb = qobject_cast(parent())) {
int index = tb->currentIndex();
auto position = (QTabBar::ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, tb);
- if (tb->tabButton(index, position) == this)
+ if (tb->tabButton(index, position) == this) {
opt.state |= QStyle::State_Selected;
+ }
}
style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &p, this);
@@ -228,20 +232,25 @@ void TabSupervisor::retranslateUi()
tabs.append(tabAccount);
tabs.append(tabLog);
QMapIterator roomIterator(roomTabs);
- while (roomIterator.hasNext())
+ while (roomIterator.hasNext()) {
tabs.append(roomIterator.next().value());
+ }
QMapIterator gameIterator(gameTabs);
- while (gameIterator.hasNext())
+ while (gameIterator.hasNext()) {
tabs.append(gameIterator.next().value());
+ }
QListIterator replayIterator(replayTabs);
- while (replayIterator.hasNext())
+ while (replayIterator.hasNext()) {
tabs.append(replayIterator.next());
+ }
QListIterator deckEditorIterator(deckEditorTabs);
- while (deckEditorIterator.hasNext())
+ while (deckEditorIterator.hasNext()) {
tabs.append(deckEditorIterator.next());
+ }
QMapIterator messageIterator(messageTabs);
- while (messageIterator.hasNext())
+ while (messageIterator.hasNext()) {
tabs.append(messageIterator.next().value());
+ }
for (auto &tab : tabs) {
if (tab) {
@@ -448,9 +457,10 @@ void TabSupervisor::startLocal(const QList &_clients)
isLocalGame = true;
userInfo = new ServerInfo_User;
localClients = _clients;
- for (int i = 0; i < localClients.size(); ++i)
+ for (int i = 0; i < localClients.size(); ++i) {
connect(localClients[i], &AbstractClient::gameEventContainerReceived, this,
&TabSupervisor::processGameEventContainer);
+ }
connect(localClients.first(), &AbstractClient::gameJoinedEventReceived, this, &TabSupervisor::localGameJoined);
}
@@ -459,8 +469,9 @@ void TabSupervisor::startLocal(const QList &_clients)
*/
void TabSupervisor::stop()
{
- if ((!client) && localClients.isEmpty())
+ if ((!client) && localClients.isEmpty()) {
return;
+ }
resetTabsMenu();
@@ -694,10 +705,12 @@ void TabSupervisor::openTabLog()
void TabSupervisor::updatePingTime(int value, int max)
{
- if (!tabServer)
+ if (!tabServer) {
return;
- if (tabServer->getContentsChanged())
+ }
+ if (tabServer->getContentsChanged()) {
return;
+ }
setTabIcon(indexOf(tabServer), QIcon(PingPixmapGenerator::generatePixmap(15, value, max)));
}
@@ -706,12 +719,14 @@ void TabSupervisor::gameJoined(const Event_GameJoined &event)
{
QMap roomGameTypes;
TabRoom *room = roomTabs.value(event.game_info().room_id());
- if (room)
+ if (room) {
roomGameTypes = room->getGameTypes();
- else
- for (int i = 0; i < event.game_types_size(); ++i)
+ } else {
+ for (int i = 0; i < event.game_types_size(); ++i) {
roomGameTypes.insert(event.game_types(i).game_type_id(),
QString::fromStdString(event.game_types(i).description()));
+ }
+ }
auto *tab = new TabGame(this, QList() << client, event, roomGameTypes);
connect(tab, &TabGame::gameClosing, this, &TabSupervisor::gameLeft);
@@ -740,14 +755,16 @@ void TabSupervisor::localGameJoined(const Event_GameJoined &event)
void TabSupervisor::gameLeft(TabGame *tab)
{
- if (tab == currentWidget())
+ if (tab == currentWidget()) {
emit setMenu();
+ }
gameTabs.remove(tab->getGame()->getGameMetaInfo()->gameId());
removeTab(indexOf(tab));
- if (!localClients.isEmpty())
+ if (!localClients.isEmpty()) {
stop();
+ }
}
void TabSupervisor::addRoomTab(const ServerInfo_Room &info, bool setCurrent)
@@ -758,14 +775,16 @@ void TabSupervisor::addRoomTab(const ServerInfo_Room &info, bool setCurrent)
connect(tab, &TabRoom::openMessageDialog, this, &TabSupervisor::addMessageTab);
myAddTab(tab);
roomTabs.insert(info.room_id(), tab);
- if (setCurrent)
+ if (setCurrent) {
setCurrentWidget(tab);
+ }
}
void TabSupervisor::roomLeft(TabRoom *tab)
{
- if (tab == currentWidget())
+ if (tab == currentWidget()) {
emit setMenu();
+ }
roomTabs.remove(tab->getRoomId());
removeTab(indexOf(tab));
@@ -793,16 +812,18 @@ void TabSupervisor::openReplay(GameReplay *replay)
void TabSupervisor::replayLeft(TabGame *tab)
{
- if (tab == currentWidget())
+ if (tab == currentWidget()) {
emit setMenu();
+ }
replayTabs.removeOne(tab);
}
TabMessage *TabSupervisor::addMessageTab(const QString &receiverName, bool focus)
{
- if (receiverName == QString::fromStdString(userInfo->name()))
+ if (receiverName == QString::fromStdString(userInfo->name())) {
return nullptr;
+ }
ServerInfo_User otherUser;
if (auto user = userListManager->getOnlineUser(receiverName)) {
@@ -814,8 +835,9 @@ TabMessage *TabSupervisor::addMessageTab(const QString &receiverName, bool focus
TabMessage *tab;
tab = messageTabs.value(QString::fromStdString(otherUser.name()));
if (tab) {
- if (focus)
+ if (focus) {
setCurrentWidget(tab);
+ }
return tab;
}
@@ -824,8 +846,9 @@ TabMessage *TabSupervisor::addMessageTab(const QString &receiverName, bool focus
connect(tab, &TabMessage::maximizeClient, this, &TabSupervisor::maximizeMainWindow);
myAddTab(tab);
messageTabs.insert(receiverName, tab);
- if (focus)
+ if (focus) {
setCurrentWidget(tab);
+ }
return tab;
}
@@ -836,8 +859,9 @@ void TabSupervisor::maximizeMainWindow()
void TabSupervisor::talkLeft(TabMessage *tab)
{
- if (tab == currentWidget())
+ if (tab == currentWidget()) {
emit setMenu();
+ }
messageTabs.remove(tab->getUserName());
removeTab(indexOf(tab));
@@ -934,8 +958,9 @@ TabEdhRec *TabSupervisor::addEdhrecTab(const CardInfoPtr &cardToQuery, bool isCo
void TabSupervisor::deckEditorClosed(AbstractTabDeckEditor *tab)
{
- if (tab == currentWidget())
+ if (tab == currentWidget()) {
emit setMenu();
+ }
deckEditorTabs.removeOne(tab);
removeTab(indexOf(tab));
@@ -948,8 +973,9 @@ void TabSupervisor::tabUserEvent(bool globalEvent)
tab->setContentsChanged(true);
setTabIcon(indexOf(tab), QPixmap("theme:icons/tab_changed"));
}
- if (globalEvent && SettingsCache::instance().getNotificationsEnabled())
+ if (globalEvent && SettingsCache::instance().getNotificationsEnabled()) {
QApplication::alert(this);
+ }
}
void TabSupervisor::updateTabText(Tab *tab, const QString &newTabText)
@@ -962,39 +988,44 @@ void TabSupervisor::updateTabText(Tab *tab, const QString &newTabText)
void TabSupervisor::processRoomEvent(const RoomEvent &event)
{
TabRoom *tab = roomTabs.value(event.room_id(), 0);
- if (tab)
+ if (tab) {
tab->processRoomEvent(event);
+ }
}
void TabSupervisor::processGameEventContainer(const GameEventContainer &cont)
{
TabGame *tab = gameTabs.value(cont.game_id());
- if (tab)
+ if (tab) {
tab->getGame()->getGameEventHandler()->processGameEventContainer(cont, qobject_cast(sender()),
{});
- else
+ } else {
qCInfo(TabSupervisorLog) << "gameEvent: invalid gameId" << cont.game_id();
+ }
}
void TabSupervisor::processUserMessageEvent(const Event_UserMessage &event)
{
QString senderName = QString::fromStdString(event.sender_name());
TabMessage *tab = messageTabs.value(senderName);
- if (!tab)
+ if (!tab) {
tab = messageTabs.value(QString::fromStdString(event.receiver_name()));
+ }
if (!tab) {
const ServerInfo_User *onlineUserInfo = userListManager->getOnlineUser(senderName);
if (onlineUserInfo) {
auto userLevel = UserLevelFlags(onlineUserInfo->user_level());
if (SettingsCache::instance().getIgnoreUnregisteredUserMessages() &&
- !userLevel.testFlag(ServerInfo_User::IsRegistered))
+ !userLevel.testFlag(ServerInfo_User::IsRegistered)) {
// Flags are additive, so reg/mod/admin are all IsRegistered
return;
+ }
}
tab = addMessageTab(QString::fromStdString(event.sender_name()), false);
}
- if (!tab)
+ if (!tab) {
return;
+ }
tab->processUserMessageEvent(event);
}
@@ -1012,8 +1043,9 @@ void TabSupervisor::actShowPopup(const QString &message)
void TabSupervisor::processUserLeft(const QString &userName)
{
TabMessage *tab = messageTabs.value(userName);
- if (tab)
+ if (tab) {
tab->processUserLeft();
+ }
}
void TabSupervisor::processUserJoined(const ServerInfo_User &userInfoJoined)
@@ -1037,8 +1069,9 @@ void TabSupervisor::processUserJoined(const ServerInfo_User &userInfoJoined)
}
TabMessage *tab = messageTabs.value(userName);
- if (tab)
+ if (tab) {
tab->processUserJoined(userInfoJoined);
+ }
}
void TabSupervisor::updateCurrent(int index)
@@ -1051,8 +1084,9 @@ void TabSupervisor::updateCurrent(int index)
}
emit setMenu(static_cast(widget(index))->getTabMenus());
tab->tabActivated();
- } else
+ } else {
emit setMenu();
+ }
}
/**
@@ -1062,8 +1096,9 @@ void TabSupervisor::updateCurrent(int index)
*/
bool TabSupervisor::getAdminLocked() const
{
- if (!tabAdmin)
+ if (!tabAdmin) {
return true;
+ }
return tabAdmin->getLocked();
}
@@ -1087,12 +1122,13 @@ void TabSupervisor::processNotifyUserEvent(const Event_NotifyUser &event)
tr("You have been promoted. Please log out and back in for changes to take effect."));
break;
case Event_NotifyUser::WARNING: {
- if (!QString::fromStdString(event.warning_reason()).simplified().isEmpty())
+ if (!QString::fromStdString(event.warning_reason()).simplified().isEmpty()) {
QMessageBox::warning(this, tr("Warned"),
tr("You have received a warning due to %1.\nPlease refrain from engaging in this "
"activity or further actions may be taken against you. If you have any "
"questions, please private message a moderator.")
.arg(QString::fromStdString(event.warning_reason()).simplified()));
+ }
break;
}
case Event_NotifyUser::CUSTOM: {
diff --git a/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual.cpp b/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual.cpp
index d03ac483b..081766cdf 100644
--- a/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual.cpp
+++ b/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual.cpp
@@ -116,8 +116,9 @@ void TabDeckEditorVisual::createMenus()
QString TabDeckEditorVisual::getTabText() const
{
QString result = tr("Visual Deck: %1").arg(deckStateManager->getSimpleDeckName());
- if (deckStateManager->isModified())
+ if (deckStateManager->isModified()) {
result.prepend("* ");
+ }
return result;
}
diff --git a/cockatrice/src/interface/widgets/utility/custom_line_edit.cpp b/cockatrice/src/interface/widgets/utility/custom_line_edit.cpp
index c137b4f35..05f56c275 100644
--- a/cockatrice/src/interface/widgets/utility/custom_line_edit.cpp
+++ b/cockatrice/src/interface/widgets/utility/custom_line_edit.cpp
@@ -24,14 +24,18 @@ bool LineEditUnfocusable::isUnfocusShortcut(QKeyEvent *event)
QString modifier;
QString keyNoMod;
- if (event->modifiers() & Qt::ShiftModifier)
+ if (event->modifiers() & Qt::ShiftModifier) {
modifier += "Shift+";
- if (event->modifiers() & Qt::ControlModifier)
+ }
+ if (event->modifiers() & Qt::ControlModifier) {
modifier += "Ctrl+";
- if (event->modifiers() & Qt::AltModifier)
+ }
+ if (event->modifiers() & Qt::AltModifier) {
modifier += "Alt+";
- if (event->modifiers() & Qt::MetaModifier)
+ }
+ if (event->modifiers() & Qt::MetaModifier) {
modifier += "Meta+";
+ }
keyNoMod = QKeySequence(event->key()).toString();
@@ -39,8 +43,9 @@ bool LineEditUnfocusable::isUnfocusShortcut(QKeyEvent *event)
QList unfocusShortcut = SettingsCache::instance().shortcuts().getShortcut("Player/unfocusTextBox");
for (const auto &unfocusKey : unfocusShortcut) {
- if (key.matches(unfocusKey) == QKeySequence::ExactMatch)
+ if (key.matches(unfocusKey) == QKeySequence::ExactMatch) {
return true;
+ }
}
return false;
}
@@ -79,10 +84,12 @@ void SearchLineEdit::keyPressEvent(QKeyEvent *event)
static const QVector forwardWhenEmpty = {Qt::Key_Home, Qt::Key_End};
Qt::Key key = static_cast(event->key());
if (treeView) {
- if (forwardToTreeView.contains(key))
+ if (forwardToTreeView.contains(key)) {
QCoreApplication::sendEvent(treeView, event);
- if (text().isEmpty() && forwardWhenEmpty.contains(key))
+ }
+ if (text().isEmpty() && forwardWhenEmpty.contains(key)) {
QCoreApplication::sendEvent(treeView, event);
+ }
}
LineEditUnfocusable::keyPressEvent(event);
}
\ No newline at end of file
diff --git a/cockatrice/src/interface/widgets/utility/line_edit_completer.cpp b/cockatrice/src/interface/widgets/utility/line_edit_completer.cpp
index 389e69d57..13f475a61 100644
--- a/cockatrice/src/interface/widgets/utility/line_edit_completer.cpp
+++ b/cockatrice/src/interface/widgets/utility/line_edit_completer.cpp
@@ -46,8 +46,9 @@ void LineEditCompleter::keyPressEvent(QKeyEvent *event)
int lastIndexof = qMax(0, textValue.lastIndexOf(" "));
QString finalString = textValue.left(lastIndexof);
// Add a space if there's a word
- if (finalString != "")
+ if (finalString != "") {
finalString += " ";
+ }
setText(finalString);
return;
}
@@ -121,12 +122,14 @@ void LineEditCompleter::setCompleter(QCompleter *completer)
void LineEditCompleter::setCompletionList(QStringList completionList)
{
- if (!c || c->popup()->isVisible())
+ if (!c || c->popup()->isVisible()) {
return;
+ }
QStringListModel *model;
model = (QStringListModel *)(c->model());
- if (model == NULL)
+ if (model == NULL) {
model = new QStringListModel();
+ }
model->setStringList(completionList);
}
diff --git a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_filter_save_load_widget.cpp b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_filter_save_load_widget.cpp
index 44b275afd..7ee57b1e9 100644
--- a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_filter_save_load_widget.cpp
+++ b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_filter_save_load_widget.cpp
@@ -57,8 +57,9 @@ void VisualDatabaseDisplayFilterSaveLoadWidget::retranslateUi()
void VisualDatabaseDisplayFilterSaveLoadWidget::saveFilter()
{
QString filename = filenameInput->text().trimmed();
- if (filename.isEmpty())
+ if (filename.isEmpty()) {
return;
+ }
QString filePath = SettingsCache::instance().getFiltersPath() + QDir::separator() + filename + ".json";
@@ -88,19 +89,22 @@ void VisualDatabaseDisplayFilterSaveLoadWidget::loadFilter(const QString &filena
QString filePath = SettingsCache::instance().getFiltersPath() + QDir::separator() + filename;
QFile file(filePath);
- if (!file.open(QIODevice::ReadOnly))
+ if (!file.open(QIODevice::ReadOnly)) {
return;
+ }
QByteArray jsonData = file.readAll();
file.close();
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
- if (!doc.isObject())
+ if (!doc.isObject()) {
return;
+ }
QJsonObject root = doc.object();
- if (!root.contains("filters") || !root["filters"].isArray())
+ if (!root.contains("filters") || !root["filters"].isArray()) {
return;
+ }
QJsonArray filtersArray = root["filters"].toArray();
diff --git a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_name_filter_widget.cpp b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_name_filter_widget.cpp
index 2751ee971..fd03e17e6 100644
--- a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_name_filter_widget.cpp
+++ b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_name_filter_widget.cpp
@@ -64,8 +64,9 @@ void VisualDatabaseDisplayNameFilterWidget::actLoadFromDeck()
{
DeckListModel *deckListModel = deckEditor->deckStateManager->getModel();
- if (!deckListModel)
+ if (!deckListModel) {
return;
+ }
QList cardNames = deckListModel->getCardNames();
for (auto cardName : cardNames) {
@@ -78,8 +79,9 @@ void VisualDatabaseDisplayNameFilterWidget::actLoadFromDeck()
void VisualDatabaseDisplayNameFilterWidget::actLoadFromClipboard()
{
DlgLoadDeckFromClipboard dlg(this);
- if (!dlg.exec())
+ if (!dlg.exec()) {
return;
+ }
QStringList cardsInClipboard = dlg.getDeckList().getCardList();
for (QString cardName : cardsInClipboard) {
@@ -91,8 +93,9 @@ void VisualDatabaseDisplayNameFilterWidget::actLoadFromClipboard()
void VisualDatabaseDisplayNameFilterWidget::createNameFilter(const QString &name)
{
- if (activeFilters.contains(name))
+ if (activeFilters.contains(name)) {
return;
+ }
// Create a button for the filter
auto *button = new QPushButton(name, flowWidget);
diff --git a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_widget.cpp b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_widget.cpp
index f9a783a3c..027092990 100644
--- a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_widget.cpp
+++ b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_widget.cpp
@@ -240,9 +240,10 @@ void VisualDatabaseDisplayWidget::updateSearch(const QString &search) const
{
databaseDisplayModel->setStringFilter(search);
QModelIndexList sel = databaseView->selectionModel()->selectedRows();
- if (sel.isEmpty() && databaseDisplayModel->rowCount())
+ if (sel.isEmpty() && databaseDisplayModel->rowCount()) {
databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0),
QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
+ }
}
bool VisualDatabaseDisplayWidget::isVisualDisplayMode() const
diff --git a/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_sample_hand_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_sample_hand_widget.cpp
index cc35372b0..8417ffa34 100644
--- a/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_sample_hand_widget.cpp
+++ b/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_sample_hand_widget.cpp
@@ -112,13 +112,15 @@ static QList cardNodesToExactCards(QList no
QList VisualDeckEditorSampleHandWidget::getRandomCards(int amountToGet)
{
QList randomCards;
- if (!deckListModel)
+ if (!deckListModel) {
return randomCards;
+ }
QList mainDeckCards = cardNodesToExactCards(deckListModel->getCardNodesForZone(DECK_ZONE_MAIN));
- if (mainDeckCards.isEmpty())
+ if (mainDeckCards.isEmpty()) {
return randomCards;
+ }
// Shuffle the deck
std::random_device rd;
diff --git a/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_widget.cpp
index 19a99d3e9..971498af1 100644
--- a/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_widget.cpp
+++ b/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_widget.cpp
@@ -78,8 +78,9 @@ void VisualDeckEditorWidget::initializeSearchBarAndCompleter()
searchBar = new QLineEdit(searchContainer);
searchContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
connect(searchBar, &QLineEdit::returnPressed, this, [=, this]() {
- if (!searchBar->hasFocus())
+ if (!searchBar->hasFocus()) {
return;
+ }
ExactCard card = CardDatabaseManager::query()->getCard({searchBar->text()});
if (card) {
diff --git a/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_tag_filter_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_tag_filter_widget.cpp
index 28fd7a5ca..c4c8d18a8 100644
--- a/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_tag_filter_widget.cpp
+++ b/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_tag_filter_widget.cpp
@@ -126,8 +126,9 @@ void VisualDeckStorageTagFilterWidget::addTagIfNotPresent(const QString &tag)
void VisualDeckStorageTagFilterWidget::sortTags()
{
auto *flowWidget = findChild();
- if (!flowWidget)
+ if (!flowWidget) {
return;
+ }
// Get all tag widgets
QList tagWidgets = findChildren();
diff --git a/cockatrice/src/interface/window_main.cpp b/cockatrice/src/interface/window_main.cpp
index bd7a5904e..69d3260bc 100644
--- a/cockatrice/src/interface/window_main.cpp
+++ b/cockatrice/src/interface/window_main.cpp
@@ -88,11 +88,13 @@ inline Q_LOGGING_CATEGORY(MainWindowLog, "main_window");
*/
void MainWindow::updateTabMenu(const QList &newMenuList)
{
- for (auto &tabMenu : tabMenus)
+ for (auto &tabMenu : tabMenus) {
menuBar()->removeAction(tabMenu->menuAction());
+ }
tabMenus = newMenuList;
- for (auto &tabMenu : tabMenus)
+ for (auto &tabMenu : tabMenus) {
menuBar()->insertMenu(helpMenu->menuAction(), tabMenu);
+ }
}
void MainWindow::statusChanged(ClientStatus _status)
@@ -177,13 +179,15 @@ void MainWindow::actWatchReplay()
QFileDialog dlg(this, tr("Load replay"));
dlg.setDirectory(SettingsCache::instance().getReplaysPath());
dlg.setNameFilters(QStringList() << QObject::tr("Cockatrice replays (*.cor)"));
- if (!dlg.exec())
+ if (!dlg.exec()) {
return;
+ }
QString fileName = dlg.selectedFiles().at(0);
QFile file(fileName);
- if (!file.open(QIODevice::ReadOnly))
+ if (!file.open(QIODevice::ReadOnly)) {
return;
+ }
QByteArray buf = file.readAll();
file.close();
@@ -208,10 +212,11 @@ void MainWindow::localGameEnded()
void MainWindow::actFullScreen(bool checked)
{
- if (checked)
+ if (checked) {
setWindowState(windowState() | Qt::WindowFullScreen);
- else
+ } else {
setWindowState(windowState() & ~Qt::WindowFullScreen);
+ }
}
void MainWindow::actSettings()
@@ -691,8 +696,9 @@ void MainWindow::closeEvent(QCloseEvent *event)
{
// workaround Qt bug where closeEvent gets called twice
static bool bClosingDown = false;
- if (bClosingDown)
+ if (bClosingDown) {
return;
+ }
bClosingDown = true;
if (!tabSupervisor->close()) {
@@ -709,9 +715,9 @@ void MainWindow::closeEvent(QCloseEvent *event)
void MainWindow::changeEvent(QEvent *event)
{
- if (event->type() == QEvent::LanguageChange)
+ if (event->type() == QEvent::LanguageChange) {
retranslateUi();
- else if (event->type() == QEvent::ActivationChange) {
+ } else if (event->type() == QEvent::ActivationChange) {
if (isActiveWindow() && !bHasActivated) {
bHasActivated = true;
if (!connectTo.isEmpty()) {
@@ -1069,8 +1075,9 @@ int MainWindow::getNextCustomSetPrefix(QDir dataDir)
QStringList::const_iterator filesIterator;
for (filesIterator = files.constBegin(); filesIterator != files.constEnd(); ++filesIterator) {
int fileIndex = (*filesIterator).split(".").at(0).toInt();
- if (fileIndex > maxIndex)
+ if (fileIndex > maxIndex) {
maxIndex = fileIndex;
+ }
}
return maxIndex + 1;
diff --git a/cockatrice/src/main.cpp b/cockatrice/src/main.cpp
index 7092a3fd7..ad68d4be9 100644
--- a/cockatrice/src/main.cpp
+++ b/cockatrice/src/main.cpp
@@ -158,9 +158,11 @@ QString const generateClientID()
{
QString macList;
for (const QNetworkInterface &networkInterface : QNetworkInterface::allInterfaces()) {
- if (networkInterface.hardwareAddress() != "")
- if (networkInterface.hardwareAddress() != "00:00:00:00:00:00:00:E0")
+ if (networkInterface.hardwareAddress() != "") {
+ if (networkInterface.hardwareAddress() != "00:00:00:00:00:00:00:E0") {
macList += networkInterface.hardwareAddress() + ".";
+ }
+ }
}
QString strClientID = QCryptographicHash::hash(macList.toUtf8(), QCryptographicHash::Sha1).toHex().right(15);
return strClientID;
diff --git a/libcockatrice_card/libcockatrice/card/database/card_database.cpp b/libcockatrice_card/libcockatrice/card/database/card_database.cpp
index 13dece626..951381aa4 100644
--- a/libcockatrice_card/libcockatrice/card/database/card_database.cpp
+++ b/libcockatrice_card/libcockatrice/card/database/card_database.cpp
@@ -103,9 +103,11 @@ void CardDatabase::addCard(CardInfoPtr card)
// If a card already exists, just add the new set property.
if (auto existing = cards.value(name)) {
- for (const auto &printings : card->getSets())
- for (const auto &printing : printings)
+ for (const auto &printings : card->getSets()) {
+ for (const auto &printing : printings) {
existing->addToSet(printing.getSet(), printing);
+ }
+ }
return;
}
@@ -123,14 +125,17 @@ void CardDatabase::removeCard(CardInfoPtr card)
return;
}
- for (auto *cardRelation : card->getRelatedCards())
+ for (auto *cardRelation : card->getRelatedCards()) {
cardRelation->deleteLater();
+ }
- for (auto *cardRelation : card->getReverseRelatedCards())
+ for (auto *cardRelation : card->getReverseRelatedCards()) {
cardRelation->deleteLater();
+ }
- for (auto *cardRelation : card->getReverseRelatedCards2Me())
+ for (auto *cardRelation : card->getReverseRelatedCards2Me()) {
cardRelation->deleteLater();
+ }
QMutexLocker locker(removeCardMutex);
cards.remove(card->getName());
diff --git a/libcockatrice_card/libcockatrice/card/database/card_database_loader.cpp b/libcockatrice_card/libcockatrice/card/database/card_database_loader.cpp
index 716477a59..76abf87ce 100644
--- a/libcockatrice_card/libcockatrice/card/database/card_database_loader.cpp
+++ b/libcockatrice_card/libcockatrice/card/database/card_database_loader.cpp
@@ -125,8 +125,9 @@ QStringList CardDatabaseLoader::collectCustomDatabasePaths() const
QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);
QStringList paths;
- while (it.hasNext())
+ while (it.hasNext()) {
paths << it.next();
+ }
paths.sort();
return paths;
}
diff --git a/libcockatrice_card/libcockatrice/card/database/card_database_querier.cpp b/libcockatrice_card/libcockatrice/card/database/card_database_querier.cpp
index 021e8d12d..174943333 100644
--- a/libcockatrice_card/libcockatrice/card/database/card_database_querier.cpp
+++ b/libcockatrice_card/libcockatrice/card/database/card_database_querier.cpp
@@ -36,8 +36,9 @@ QList CardDatabaseQuerier::getCardInfos(const QStringList &cardName
QList cardInfos;
for (const QString &cardName : cardNames) {
CardInfoPtr ptr = db->cards.value(cardName);
- if (ptr)
+ if (ptr) {
cardInfos.append(ptr);
+ }
}
return cardInfos;
@@ -50,10 +51,12 @@ CardInfoPtr CardDatabaseQuerier::getCardBySimpleName(const QString &cardName) co
CardInfoPtr CardDatabaseQuerier::lookupCardByName(const QString &name) const
{
- if (auto info = getCardInfo(name))
+ if (auto info = getCardInfo(name)) {
return info;
- if (auto info = getCardBySimpleName(name))
+ }
+ if (auto info = getCardBySimpleName(name)) {
return info;
+ }
return getCardBySimpleName(CardInfo::simplifyName(name));
}
@@ -71,8 +74,9 @@ QList CardDatabaseQuerier::getCards(const QList &cardRefs) c
QList cards;
for (const auto &cardRef : cardRefs) {
ExactCard card = getCard(cardRef);
- if (card)
+ if (card) {
cards.append(card);
+ }
}
return cards;
@@ -119,8 +123,9 @@ ExactCard CardDatabaseQuerier::guessCard(const CardRef &cardRef) const
ExactCard CardDatabaseQuerier::getRandomCard() const
{
- if (db->cards.isEmpty())
+ if (db->cards.isEmpty()) {
return {};
+ }
const auto keys = db->cards.keys();
int randomIndex = QRandomGenerator::global()->bounded(keys.size());
diff --git a/libcockatrice_card/libcockatrice/card/database/parser/cockatrice_xml_4.cpp b/libcockatrice_card/libcockatrice/card/database/parser/cockatrice_xml_4.cpp
index cc0220526..96a5ac104 100644
--- a/libcockatrice_card/libcockatrice/card/database/parser/cockatrice_xml_4.cpp
+++ b/libcockatrice_card/libcockatrice/card/database/parser/cockatrice_xml_4.cpp
@@ -306,8 +306,9 @@ void CockatriceXml4Parser::loadCardsFromXml(QXmlStreamReader &xml)
PrintingInfo printingInfo(set);
for (QXmlStreamAttribute attr : attrs) {
QString attrName = attr.name().toString();
- if (attrName == "picURL")
+ if (attrName == "picURL") {
attrName = "picurl";
+ }
printingInfo.setProperty(attrName, attr.value().toString());
}
diff --git a/libcockatrice_card/libcockatrice/card/format/format_legality_rules.h b/libcockatrice_card/libcockatrice/card/format/format_legality_rules.h
index 16f2359ab..8778ab17e 100644
--- a/libcockatrice_card/libcockatrice/card/format/format_legality_rules.h
+++ b/libcockatrice_card/libcockatrice/card/format/format_legality_rules.h
@@ -51,16 +51,21 @@ enum class CardMatchType
// convert string to enum
inline CardMatchType matchTypeFromString(const QString &str)
{
- if (str == "equals")
+ if (str == "equals") {
return CardMatchType::Equals;
- if (str == "notEquals")
+ }
+ if (str == "notEquals") {
return CardMatchType::NotEquals;
- if (str == "contains")
+ }
+ if (str == "contains") {
return CardMatchType::Contains;
- if (str == "notContains")
+ }
+ if (str == "notContains") {
return CardMatchType::NotContains;
- if (str == "regex")
+ }
+ if (str == "regex") {
return CardMatchType::Regex;
+ }
return CardMatchType::Equals; // fallback default
}
diff --git a/libcockatrice_card/libcockatrice/card/game_specific_terms.h b/libcockatrice_card/libcockatrice/card/game_specific_terms.h
index 2931365ad..3616745be 100644
--- a/libcockatrice_card/libcockatrice/card/game_specific_terms.h
+++ b/libcockatrice_card/libcockatrice/card/game_specific_terms.h
@@ -31,26 +31,36 @@ QString const ColorIdentity("coloridentity");
inline static const QString getNicePropertyName(QString key)
{
- if (key == CardType)
+ if (key == CardType) {
return QCoreApplication::translate("Mtg", "Card Type");
- if (key == ConvertedManaCost)
+ }
+ if (key == ConvertedManaCost) {
return QCoreApplication::translate("Mtg", "Mana Value");
- if (key == Colors)
+ }
+ if (key == Colors) {
return QCoreApplication::translate("Mtg", "Color(s)");
- if (key == Loyalty)
+ }
+ if (key == Loyalty) {
return QCoreApplication::translate("Mtg", "Loyalty");
- if (key == MainCardType)
+ }
+ if (key == MainCardType) {
return QCoreApplication::translate("Mtg", "Main Card Type");
- if (key == ManaCost)
+ }
+ if (key == ManaCost) {
return QCoreApplication::translate("Mtg", "Mana Cost");
- if (key == PowTough)
+ }
+ if (key == PowTough) {
return QCoreApplication::translate("Mtg", "P/T");
- if (key == Side)
+ }
+ if (key == Side) {
return QCoreApplication::translate("Mtg", "Side");
- if (key == Layout)
+ }
+ if (key == Layout) {
return QCoreApplication::translate("Mtg", "Layout");
- if (key == ColorIdentity)
+ }
+ if (key == ColorIdentity) {
return QCoreApplication::translate("Mtg", "Color Identity");
+ }
return key;
}
} // namespace Mtg
diff --git a/libcockatrice_card/libcockatrice/card/set/card_set.cpp b/libcockatrice_card/libcockatrice/card/set/card_set.cpp
index 20d0aced8..6eea220bb 100644
--- a/libcockatrice_card/libcockatrice/card/set/card_set.cpp
+++ b/libcockatrice_card/libcockatrice/card/set/card_set.cpp
@@ -33,28 +33,9 @@ QString CardSet::getCorrectedShortName() const
{
// For Windows machines.
QSet invalidFileNames;
- invalidFileNames << "CON"
- << "PRN"
- << "AUX"
- << "NUL"
- << "COM1"
- << "COM2"
- << "COM3"
- << "COM4"
- << "COM5"
- << "COM6"
- << "COM7"
- << "COM8"
- << "COM9"
- << "LPT1"
- << "LPT2"
- << "LPT3"
- << "LPT4"
- << "LPT5"
- << "LPT6"
- << "LPT7"
- << "LPT8"
- << "LPT9";
+ invalidFileNames << "CON" << "PRN" << "AUX" << "NUL" << "COM1" << "COM2" << "COM3" << "COM4" << "COM5" << "COM6"
+ << "COM7" << "COM8" << "COM9" << "LPT1" << "LPT2" << "LPT3" << "LPT4" << "LPT5" << "LPT6" << "LPT7"
+ << "LPT8" << "LPT9";
return invalidFileNames.contains(shortName) ? shortName + "_" : shortName;
}
diff --git a/libcockatrice_deck_list/libcockatrice/deck_list/deck_list.cpp b/libcockatrice_deck_list/libcockatrice/deck_list/deck_list.cpp
index e3e7b41c0..d41713302 100644
--- a/libcockatrice_deck_list/libcockatrice/deck_list/deck_list.cpp
+++ b/libcockatrice_deck_list/libcockatrice/deck_list/deck_list.cpp
@@ -143,12 +143,14 @@ bool DeckList::loadFromXml(QXmlStreamReader *xml)
while (!xml->atEnd()) {
xml->readNext();
if (xml->isStartElement()) {
- if (xml->name().toString() != "cockatrice_deck")
+ if (xml->name().toString() != "cockatrice_deck") {
return false;
+ }
while (!xml->atEnd()) {
xml->readNext();
- if (!readElement(xml))
+ if (!readElement(xml)) {
break;
+ }
}
}
}
@@ -291,8 +293,9 @@ bool DeckList::loadFromStream_Plain(QTextStream &in,
for (; index < max_line; ++index) {
// check if line is a card
match = reCardLine.match(inputs.at(index));
- if (!match.hasMatch())
+ if (!match.hasMatch()) {
continue;
+ }
QString cardName = match.captured().simplified();
bool sideboard = false;
@@ -305,8 +308,9 @@ bool DeckList::loadFromStream_Plain(QTextStream &in,
cardName = match.captured(1);
}
} else {
- if (index == sBStart)
+ if (index == sBStart) {
continue;
+ }
sideboard = index > sBStart;
}
diff --git a/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_history_manager.cpp b/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_history_manager.cpp
index 83c9cc0bb..acf4707ab 100644
--- a/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_history_manager.cpp
+++ b/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_history_manager.cpp
@@ -16,8 +16,9 @@ void DeckListHistoryManager::clear()
void DeckListHistoryManager::undo(DeckList *deck)
{
- if (undoStack.isEmpty())
+ if (undoStack.isEmpty()) {
return;
+ }
// Peek at the memento we are going to restore
const DeckListMemento &mementoToRestore = undoStack.top();
@@ -35,8 +36,9 @@ void DeckListHistoryManager::undo(DeckList *deck)
void DeckListHistoryManager::redo(DeckList *deck)
{
- if (redoStack.isEmpty())
+ if (redoStack.isEmpty()) {
return;
+ }
// Peek at the memento we are going to restore
const DeckListMemento &mementoToRestore = redoStack.top();
diff --git a/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_node_tree.cpp b/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_node_tree.cpp
index 644e0851a..196416cde 100644
--- a/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_node_tree.cpp
+++ b/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_node_tree.cpp
@@ -58,8 +58,9 @@ QList DecklistNodeTree::getZoneNodes(const QSet zones;
for (auto *node : *root) {
InnerDecklistNode *currentZone = dynamic_cast(node);
- if (!currentZone)
+ if (!currentZone) {
continue;
+ }
if (!restrictToZones.isEmpty() && !restrictToZones.contains(currentZone->getName())) {
continue;
}
diff --git a/libcockatrice_deck_list/libcockatrice/deck_list/sideboard_plan.cpp b/libcockatrice_deck_list/libcockatrice/deck_list/sideboard_plan.cpp
index d991ec98e..a76fed619 100644
--- a/libcockatrice_deck_list/libcockatrice/deck_list/sideboard_plan.cpp
+++ b/libcockatrice_deck_list/libcockatrice/deck_list/sideboard_plan.cpp
@@ -18,28 +18,30 @@ bool SideboardPlan::readElement(QXmlStreamReader *xml)
xml->readNext();
const QString childName = xml->name().toString();
if (xml->isStartElement()) {
- if (childName == "name")
+ if (childName == "name") {
name = xml->readElementText();
- else if (childName == "move_card_to_zone") {
+ } else if (childName == "move_card_to_zone") {
MoveCard_ToZone m;
while (!xml->atEnd()) {
xml->readNext();
const QString childName2 = xml->name().toString();
if (xml->isStartElement()) {
- if (childName2 == "card_name")
+ if (childName2 == "card_name") {
m.set_card_name(xml->readElementText().toStdString());
- else if (childName2 == "start_zone")
+ } else if (childName2 == "start_zone") {
m.set_start_zone(xml->readElementText().toStdString());
- else if (childName2 == "target_zone")
+ } else if (childName2 == "target_zone") {
m.set_target_zone(xml->readElementText().toStdString());
+ }
} else if (xml->isEndElement() && (childName2 == "move_card_to_zone")) {
moveList.append(m);
break;
}
}
}
- } else if (xml->isEndElement() && (childName == "sideboard_plan"))
+ } else if (xml->isEndElement() && (childName == "sideboard_plan")) {
return true;
+ }
}
return false;
}
diff --git a/libcockatrice_deck_list/libcockatrice/deck_list/tree/abstract_deck_list_card_node.cpp b/libcockatrice_deck_list/libcockatrice/deck_list/tree/abstract_deck_list_card_node.cpp
index b8a497c20..705dfae4c 100644
--- a/libcockatrice_deck_list/libcockatrice/deck_list/tree/abstract_deck_list_card_node.cpp
+++ b/libcockatrice_deck_list/libcockatrice/deck_list/tree/abstract_deck_list_card_node.cpp
@@ -38,8 +38,9 @@ bool AbstractDecklistCardNode::readElement(QXmlStreamReader *xml)
{
while (!xml->atEnd()) {
xml->readNext();
- if (xml->isEndElement() && xml->name().toString() == "card")
+ if (xml->isEndElement() && xml->name().toString() == "card") {
return false;
+ }
}
return true;
}
diff --git a/libcockatrice_deck_list/libcockatrice/deck_list/tree/inner_deck_list_node.cpp b/libcockatrice_deck_list/libcockatrice/deck_list/tree/inner_deck_list_node.cpp
index eca58963a..602ea6aec 100644
--- a/libcockatrice_deck_list/libcockatrice/deck_list/tree/inner_deck_list_node.cpp
+++ b/libcockatrice_deck_list/libcockatrice/deck_list/tree/inner_deck_list_node.cpp
@@ -48,8 +48,9 @@ QString InnerDecklistNode::getVisibleName() const
void InnerDecklistNode::clearTree()
{
- for (int i = 0; i < size(); i++)
+ for (int i = 0; i < size(); i++) {
delete at(i);
+ }
clear();
}
@@ -154,8 +155,9 @@ bool InnerDecklistNode::readElement(QXmlStreamReader *xml)
xml->attributes().value("collectorNumber").toString(), xml->attributes().value("uuid").toString());
newCard->readElement(xml);
}
- } else if (xml->isEndElement() && (childName == "zone"))
+ } else if (xml->isEndElement() && (childName == "zone")) {
return false;
+ }
}
return true;
}
@@ -164,8 +166,9 @@ void InnerDecklistNode::writeElement(QXmlStreamWriter *xml)
{
xml->writeStartElement("zone");
xml->writeAttribute("name", name);
- for (int i = 0; i < size(); i++)
+ for (int i = 0; i < size(); i++) {
at(i)->writeElement(xml);
+ }
xml->writeEndElement(); // zone
}
diff --git a/libcockatrice_network/libcockatrice/network/client/abstract/abstract_client.cpp b/libcockatrice_network/libcockatrice/network/client/abstract/abstract_client.cpp
index 11458768d..916f4351b 100644
--- a/libcockatrice_network/libcockatrice/network/client/abstract/abstract_client.cpp
+++ b/libcockatrice_network/libcockatrice/network/client/abstract/abstract_client.cpp
@@ -66,8 +66,9 @@ void AbstractClient::processProtocolItem(const ServerMessage &item)
const int cmdId = response.cmd_id();
PendingCommand *pend = pendingCommands.value(cmdId, 0);
- if (!pend)
+ if (!pend) {
return;
+ }
pendingCommands.remove(cmdId);
pend->processResponse(response);
diff --git a/libcockatrice_network/libcockatrice/network/client/remote/remote_client.cpp b/libcockatrice_network/libcockatrice/network/client/remote/remote_client.cpp
index 3e3ec889d..0ef211b94 100644
--- a/libcockatrice_network/libcockatrice/network/client/remote/remote_client.cpp
+++ b/libcockatrice_network/libcockatrice/network/client/remote/remote_client.cpp
@@ -213,8 +213,9 @@ Command_Login RemoteClient::generateCommandLogin()
if (!clientFeatures.isEmpty()) {
QMap::iterator i;
- for (i = clientFeatures.begin(); i != clientFeatures.end(); ++i)
+ for (i = clientFeatures.begin(); i != clientFeatures.end(); ++i) {
cmdLogin.add_clientfeatures(i.key().toStdString().c_str());
+ }
}
return cmdLogin;
@@ -284,8 +285,9 @@ void RemoteClient::loginResponse(const Response &response)
QString possibleMissingFeatures;
if (resp.missing_features_size() > 0) {
- for (int i = 0; i < resp.missing_features_size(); ++i)
+ for (int i = 0; i < resp.missing_features_size(); ++i) {
possibleMissingFeatures.append("," + QString::fromStdString(resp.missing_features(i)));
+ }
}
if (response.response_code() == Response::RespOk) {
@@ -293,13 +295,15 @@ void RemoteClient::loginResponse(const Response &response)
emit userInfoChanged(resp.user_info());
QList buddyList;
- for (int i = resp.buddy_list_size() - 1; i >= 0; --i)
+ for (int i = resp.buddy_list_size() - 1; i >= 0; --i) {
buddyList.append(resp.buddy_list(i));
+ }
emit buddyListReceived(buddyList);
QList ignoreList;
- for (int i = resp.ignore_list_size() - 1; i >= 0; --i)
+ for (int i = resp.ignore_list_size() - 1; i >= 0; --i) {
ignoreList.append(resp.ignore_list(i));
+ }
emit ignoreListReceived(ignoreList);
if (newMissingFeatureFound(possibleMissingFeatures) && resp.missing_features_size() > 0 &&
@@ -311,8 +315,9 @@ void RemoteClient::loginResponse(const Response &response)
} else if (response.response_code() != Response::RespNotConnected) {
QList missingFeatures;
if (resp.missing_features_size() > 0) {
- for (int i = 0; i < resp.missing_features_size(); ++i)
+ for (int i = 0; i < resp.missing_features_size(); ++i) {
missingFeatures << QString::fromStdString(resp.missing_features(i));
+ }
}
emit loginError(response.response_code(), QString::fromStdString(resp.denied_reason_str()),
static_cast(resp.denied_end_time()), missingFeatures);
@@ -383,11 +388,13 @@ void RemoteClient::readData()
inputBuffer.remove(0, 4);
messageInProgress = true;
}
- } else
+ } else {
return;
+ }
}
- if (inputBuffer.size() < messageLength)
+ if (inputBuffer.size() < messageLength) {
return;
+ }
ServerMessage newServerMessage;
bool ok = newServerMessage.ParseFromArray(inputBuffer.data(), messageLength);
@@ -403,8 +410,9 @@ void RemoteClient::readData()
qCDebug(RemoteClientLog) << "parsing error!";
}
- if (getStatus() == StatusDisconnecting) // use thread-safe getter
+ if (getStatus() == StatusDisconnecting) { // use thread-safe getter
doDisconnectFromServer();
+ }
} while (!inputBuffer.isEmpty());
}
@@ -537,8 +545,9 @@ void RemoteClient::doDisconnectFromServer()
pendingCommands.clear();
setStatus(StatusDisconnected);
- if (websocket->isValid())
+ if (websocket->isValid()) {
websocket->close();
+ }
socket->close();
}
@@ -615,8 +624,9 @@ bool RemoteClient::newMissingFeatureFound(const QString &_serversMissingFeatures
QStringList serversMissingFeaturesList = _serversMissingFeatures.split(",");
for (const QString &feature : serversMissingFeaturesList) {
if (!feature.isEmpty()) {
- if (!networkSettingsProvider->getKnownMissingFeatures().contains(feature))
+ if (!networkSettingsProvider->getKnownMissingFeatures().contains(feature)) {
return true;
+ }
}
}
return newMissingFeature;
@@ -628,8 +638,9 @@ void RemoteClient::clearNewClientFeatures()
QStringList existingKnownMissingFeatures = networkSettingsProvider->getKnownMissingFeatures().split(",");
for (const QString &existingKnownFeature : existingKnownMissingFeatures) {
if (!existingKnownFeature.isEmpty()) {
- if (!clientFeatures.contains(existingKnownFeature))
+ if (!clientFeatures.contains(existingKnownFeature)) {
newKnownMissingFeatures.append("," + existingKnownFeature);
+ }
}
}
networkSettingsProvider->setKnownMissingFeatures(newKnownMissingFeatures);
@@ -667,10 +678,12 @@ void RemoteClient::requestForgotPasswordResponse(const Response &response)
if (response.response_code() == Response::RespOk) {
if (resp.challenge_email()) {
emit sigPromptForForgotPasswordChallenge();
- } else
+ } else {
emit sigPromptForForgotPasswordReset();
- } else
+ }
+ } else {
emit sigForgotPasswordError();
+ }
doDisconnectFromServer();
}
@@ -698,8 +711,9 @@ void RemoteClient::submitForgotPasswordResetResponse(const Response &response)
{
if (response.response_code() == Response::RespOk) {
emit sigForgotPasswordSuccess();
- } else
+ } else {
emit sigForgotPasswordError();
+ }
doDisconnectFromServer();
}
@@ -732,8 +746,9 @@ void RemoteClient::submitForgotPasswordChallengeResponse(const Response &respons
{
if (response.response_code() == Response::RespOk) {
emit sigPromptForForgotPasswordReset();
- } else
+ } else {
emit sigForgotPasswordError();
+ }
doDisconnectFromServer();
}
diff --git a/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_player.cpp b/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_player.cpp
index 1b1135ead..36ab75675 100644
--- a/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_player.cpp
+++ b/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_player.cpp
@@ -391,8 +391,9 @@ void Server_AbstractPlayer::processMoveCard(GameEventStorage &ges,
for (auto *player : game->getPlayers().values()) {
QList arrowsToDelete;
for (Server_Arrow *arrow : player->getArrows()) {
- if ((arrow->getStartCard() == card) || (arrow->getTargetItem() == card))
+ if ((arrow->getStartCard() == card) || (arrow->getTargetItem() == card)) {
arrowsToDelete.append(arrow->getId());
+ }
}
for (int j : arrowsToDelete) {
player->deleteArrow(j);
@@ -1472,8 +1473,9 @@ Server_AbstractPlayer::cmdRevealCards(const Command_RevealCards &cmd, ResponseCo
if (cmd.has_player_id()) {
Server_AbstractPlayer *otherPlayer = game->getPlayer(cmd.player_id());
- if (!otherPlayer)
+ if (!otherPlayer) {
return Response::RespNameNotFound;
+ }
}
Server_CardZone *zone = zones.value(nameFromStdString(cmd.zone_name()));
if (!zone) {
diff --git a/libcockatrice_network/libcockatrice/network/server/remote/game/server_arrow.cpp b/libcockatrice_network/libcockatrice/network/server/remote/game/server_arrow.cpp
index f6787baa2..2ad38b977 100644
--- a/libcockatrice_network/libcockatrice/network/server/remote/game/server_arrow.cpp
+++ b/libcockatrice_network/libcockatrice/network/server/remote/game/server_arrow.cpp
@@ -30,6 +30,7 @@ void Server_Arrow::getInfo(ServerInfo_Arrow *info)
info->set_target_player_id(targetCard->getZone()->getPlayer()->getPlayerId());
info->set_target_zone(targetCard->getZone()->getName().toStdString());
info->set_target_card_id(targetCard->getId());
- } else
+ } else {
info->set_target_player_id(static_cast(targetItem)->getPlayerId());
+ }
}
diff --git a/libcockatrice_network/libcockatrice/network/server/remote/game/server_card.cpp b/libcockatrice_network/libcockatrice/network/server/remote/game/server_card.cpp
index 86ff2f008..e3d53ace8 100644
--- a/libcockatrice_network/libcockatrice/network/server/remote/game/server_card.cpp
+++ b/libcockatrice_network/libcockatrice/network/server/remote/game/server_card.cpp
@@ -36,11 +36,13 @@ Server_Card::Server_Card(const CardRef &cardRef, int _id, int _coord_x, int _coo
Server_Card::~Server_Card()
{
// setParentCard(0) leads to the item being removed from our list, so we can't iterate properly
- while (!attachedCards.isEmpty())
+ while (!attachedCards.isEmpty()) {
attachedCards.first()->setParentCard(0);
+ }
- if (parentCard)
+ if (parentCard) {
parentCard->removeAttachedCard(this);
+ }
if (stashedCard) {
stashedCard->deleteLater();
@@ -62,16 +64,18 @@ void Server_Card::resetState(bool keepAnnotations)
QString Server_Card::setAttribute(CardAttribute attribute, const QString &avalue, bool allCards)
{
- if (attribute == AttrTapped && avalue != "1" && allCards && doesntUntap)
+ if (attribute == AttrTapped && avalue != "1" && allCards && doesntUntap) {
return QVariant(tapped).toString();
+ }
return setAttribute(attribute, avalue);
}
QString Server_Card::setAttribute(CardAttribute attribute, const QString &avalue, Event_SetCardAttr *event)
{
- if (event)
+ if (event) {
event->set_attribute(attribute);
+ }
switch (attribute) {
case AttrTapped: {
@@ -89,8 +93,9 @@ QString Server_Card::setAttribute(CardAttribute attribute, const QString &avalue
break;
case AttrPT:
setPT(avalue);
- if (event)
+ if (event) {
event->set_attr_value(getPT().toStdString());
+ }
return getPT();
case AttrAnnotation:
setAnnotation(avalue);
@@ -99,17 +104,19 @@ QString Server_Card::setAttribute(CardAttribute attribute, const QString &avalue
setDoesntUntap(avalue == "1");
break;
}
- if (event)
+ if (event) {
event->set_attr_value(avalue.toStdString());
+ }
return avalue;
}
void Server_Card::setCounter(int _id, int value, Event_SetCardCounter *event)
{
- if (value)
+ if (value) {
counters.insert(_id, value);
- else
+ } else {
counters.remove(_id);
+ }
if (event) {
event->set_counter_id(_id);
@@ -119,11 +126,13 @@ void Server_Card::setCounter(int _id, int value, Event_SetCardCounter *event)
void Server_Card::setParentCard(Server_Card *_parentCard)
{
- if (parentCard)
+ if (parentCard) {
parentCard->removeAttachedCard(this);
+ }
parentCard = _parentCard;
- if (parentCard)
+ if (parentCard) {
parentCard->addAttachedCard(this);
+ }
}
void Server_Card::getInfo(ServerInfo_Card *info)
diff --git a/libcockatrice_network/libcockatrice/network/server/remote/game/server_cardzone.cpp b/libcockatrice_network/libcockatrice/network/server/remote/game/server_cardzone.cpp
index f2a35e548..1db4f9c4c 100644
--- a/libcockatrice_network/libcockatrice/network/server/remote/game/server_cardzone.cpp
+++ b/libcockatrice_network/libcockatrice/network/server/remote/game/server_cardzone.cpp
@@ -47,19 +47,23 @@ void Server_CardZone::shuffle(int start, int end)
cardsBeingLookedAt = 0;
// Size 0 or 1 decks are sorted
- if (cards.size() < 2)
+ if (cards.size() < 2) {
return;
+ }
// Negative numbers signify positions starting at the end of the
// zone convert these to actual indexes.
- if (end < 0)
+ if (end < 0) {
end += cards.size();
+ }
- if (start < 0)
+ if (start < 0) {
start += cards.size();
+ }
- if (start < 0 || end < 0 || start >= cards.size() || end >= cards.size())
+ if (start < 0 || end < 0 || start >= cards.size() || end >= cards.size()) {
return;
+ }
for (int i = end; i > start; i--) {
int j = rng->rand(start, i);
@@ -70,40 +74,47 @@ void Server_CardZone::shuffle(int start, int end)
void Server_CardZone::removeCardFromCoordMap(Server_Card *card, int oldX, int oldY)
{
- if (oldX < 0)
+ if (oldX < 0) {
return;
+ }
const int baseX = (oldX / 3) * 3;
QMap &coordMap = coordinateMap[oldY];
- if (coordMap.contains(baseX) && coordMap.contains(baseX + 1) && coordMap.contains(baseX + 2))
+ if (coordMap.contains(baseX) && coordMap.contains(baseX + 1) && coordMap.contains(baseX + 2)) {
// If the removal of this card has opened up a previously full pile...
freePilesMap[oldY].insert(coordMap.value(baseX)->getName(), baseX);
+ }
coordMap.remove(oldX);
if (!(coordMap.contains(baseX) && coordMap.value(baseX)->getName() == card->getName()) &&
!(coordMap.contains(baseX + 1) && coordMap.value(baseX + 1)->getName() == card->getName()) &&
- !(coordMap.contains(baseX + 2) && coordMap.value(baseX + 2)->getName() == card->getName()))
+ !(coordMap.contains(baseX + 2) && coordMap.value(baseX + 2)->getName() == card->getName())) {
// If this card was the last one with this name...
freePilesMap[oldY].remove(card->getName(), baseX);
+ }
if (!coordMap.contains(baseX) && !coordMap.contains(baseX + 1) && !coordMap.contains(baseX + 2)) {
// If the removal of this card has freed a whole pile, i.e. it was the last card in it...
- if (baseX < freeSpaceMap[oldY])
+ if (baseX < freeSpaceMap[oldY]) {
freeSpaceMap[oldY] = baseX;
+ }
}
}
void Server_CardZone::insertCardIntoCoordMap(Server_Card *card, int x, int y)
{
- if (x < 0)
+ if (x < 0) {
return;
+ }
coordinateMap[y].insert(x, card);
if (!(x % 3)) {
- if (!card->getFaceDown() && !freePilesMap[y].contains(card->getName(), x) && card->getAttachedCards().isEmpty())
+ if (!card->getFaceDown() && !freePilesMap[y].contains(card->getName(), x) &&
+ card->getAttachedCards().isEmpty()) {
freePilesMap[y].insert(card->getName(), x);
+ }
if (freeSpaceMap[y] == x) {
int nextFreeX = x;
do {
@@ -146,8 +157,9 @@ Server_Card *Server_CardZone::getCard(int id, int *position, bool remove)
for (int i = 0; i < cards.size(); ++i) {
Server_Card *tmp = cards[i];
if (tmp->getId() == id) {
- if (position)
+ if (position) {
*position = i;
+ }
if (remove) {
cards.removeAt(i);
tmp->setZone(nullptr);
@@ -157,11 +169,13 @@ Server_Card *Server_CardZone::getCard(int id, int *position, bool remove)
}
return nullptr;
} else {
- if ((id >= cards.size()) || (id < 0))
+ if ((id >= cards.size()) || (id < 0)) {
return nullptr;
+ }
Server_Card *tmp = cards[id];
- if (position)
+ if (position) {
*position = id;
+ }
if (remove) {
cards.removeAt(id);
tmp->setZone(nullptr);
@@ -184,32 +198,35 @@ int Server_CardZone::getFreeGridColumn(int x, int y, const QString &cardName, bo
if (coordMap.contains(x) && (coordMap[x]->getFaceDown() || !coordMap[x]->getAttachedCards().isEmpty())) {
// don't pile up on: 1. facedown cards 2. cards with attached cards
- } else if (!coordMap.contains(x))
+ } else if (!coordMap.contains(x)) {
return x;
- else if (!coordMap.contains(x + 1))
+ } else if (!coordMap.contains(x + 1)) {
return x + 1;
- else
+ } else {
return x + 2;
+ }
}
} else if (x >= 0) {
int resultX = 0;
x = (x / 3) * 3;
- if (!coordMap.contains(x))
+ if (!coordMap.contains(x)) {
resultX = x;
- else if (!coordMap.value(x)->getAttachedCards().isEmpty()) {
+ } else if (!coordMap.value(x)->getAttachedCards().isEmpty()) {
resultX = x;
x = -1;
- } else if (!coordMap.contains(x + 1))
+ } else if (!coordMap.contains(x + 1)) {
resultX = x + 1;
- else if (!coordMap.contains(x + 2))
+ } else if (!coordMap.contains(x + 2)) {
resultX = x + 2;
- else {
+ } else {
resultX = x;
x = -1;
}
- if (x < 0)
- while (coordMap.contains(resultX))
+ if (x < 0) {
+ while (coordMap.contains(resultX)) {
resultX += 3;
+ }
+ }
return resultX;
}
@@ -219,16 +236,18 @@ int Server_CardZone::getFreeGridColumn(int x, int y, const QString &cardName, bo
bool Server_CardZone::isColumnStacked(int x, int y) const
{
- if (!has_coords)
+ if (!has_coords) {
return false;
+ }
return coordinateMap[y].contains((x / 3) * 3 + 1);
}
bool Server_CardZone::isColumnEmpty(int x, int y) const
{
- if (!has_coords)
+ if (!has_coords) {
return true;
+ }
return !coordinateMap[y].contains((x / 3) * 3);
}
@@ -243,12 +262,14 @@ void Server_CardZone::moveCardInRow(GameEventStorage &ges, Server_Card *card, in
void Server_CardZone::fixFreeSpaces(GameEventStorage &ges)
{
- if (!has_coords)
+ if (!has_coords) {
return;
+ }
QSet> placesToLook;
- for (auto &card : cards)
+ for (auto &card : cards) {
placesToLook.insert(QPair((card->getX() / 3) * 3, card->getY()));
+ }
QSetIterator> placeIterator(placesToLook);
while (placeIterator.hasNext()) {
@@ -257,26 +278,30 @@ void Server_CardZone::fixFreeSpaces(GameEventStorage &ges)
int y = foo.second;
if (!coordinateMap[y].contains(baseX)) {
- if (coordinateMap[y].contains(baseX + 1))
+ if (coordinateMap[y].contains(baseX + 1)) {
moveCardInRow(ges, coordinateMap[y].value(baseX + 1), baseX, y);
- else if (coordinateMap[y].contains(baseX + 2)) {
+ } else if (coordinateMap[y].contains(baseX + 2)) {
moveCardInRow(ges, coordinateMap[y].value(baseX + 2), baseX, y);
continue;
- } else
+ } else {
continue;
+ }
}
- if (!coordinateMap[y].contains(baseX + 1) && coordinateMap[y].contains(baseX + 2))
+ if (!coordinateMap[y].contains(baseX + 1) && coordinateMap[y].contains(baseX + 2)) {
moveCardInRow(ges, coordinateMap[y].value(baseX + 2), baseX + 1, y);
+ }
}
}
void Server_CardZone::updateCardCoordinates(Server_Card *card, int oldX, int oldY)
{
- if (!has_coords)
+ if (!has_coords) {
return;
+ }
- if (oldX != -1)
+ if (oldX != -1) {
removeCardFromCoordMap(card, oldX, oldY);
+ }
insertCardIntoCoordMap(card, card->getX(), card->getY());
}
@@ -299,8 +324,9 @@ void Server_CardZone::insertCard(Server_Card *card, int x, int y)
void Server_CardZone::clear()
{
- for (auto card : cards)
+ for (auto card : cards) {
delete card;
+ }
cards.clear();
coordinateMap.clear();
freePilesMap.clear();
@@ -329,7 +355,8 @@ void Server_CardZone::getInfo(ServerInfo_Zone *info, Server_AbstractParticipant
const bool zonesOthersCanSee = type == ServerInfo_Zone::PublicZone;
if ((selfPlayerAsking && zonesSelfCanSee) || (otherPlayerAsking && zonesOthersCanSee)) {
QListIterator cardIterator(cards);
- while (cardIterator.hasNext())
+ while (cardIterator.hasNext()) {
cardIterator.next()->getInfo(info->add_card_list());
+ }
}
}
diff --git a/libcockatrice_network/libcockatrice/network/server/remote/game/server_game.cpp b/libcockatrice_network/libcockatrice/network/server/remote/game/server_game.cpp
index 28d06c6be..f5a4889d0 100644
--- a/libcockatrice_network/libcockatrice/network/server/remote/game/server_game.cpp
+++ b/libcockatrice_network/libcockatrice/network/server/remote/game/server_game.cpp
@@ -147,8 +147,9 @@ void Server_Game::storeGameInformation()
const QStringList &allGameTypes = room->getGameTypes();
QStringList _gameTypes;
- for (int i = gameInfo.game_types_size() - 1; i >= 0; --i)
+ for (int i = gameInfo.game_types_size() - 1; i >= 0; --i) {
_gameTypes.append(allGameTypes[gameInfo.game_types(i)]);
+ }
for (const auto &playerName : allPlayersEver) {
replayMatchInfo->add_player_names(playerName.toStdString());
@@ -166,8 +167,9 @@ void Server_Game::storeGameInformation()
server->clientsLock.lockForRead();
for (auto userName : allPlayersEver + allSpectatorsEver) {
Server_AbstractUserInterface *userHandler = server->findUser(userName);
- if (userHandler && server->getStoreReplaysEnabled())
+ if (userHandler && server->getStoreReplaysEnabled()) {
userHandler->sendProtocolItem(*sessionEvent);
+ }
}
server->clientsLock.unlock();
delete sessionEvent;
@@ -189,8 +191,9 @@ void Server_Game::pingClockTimeout()
bool allPlayersInactive = true;
int playerCount = 0;
for (auto *participant : participants) {
- if (participant == nullptr)
+ if (participant == nullptr) {
continue;
+ }
if (!participant->isSpectator()) {
++playerCount;
@@ -253,8 +256,9 @@ int Server_Game::getSpectatorCount() const
int result = 0;
for (Server_AbstractParticipant *participant : participants.values()) {
- if (participant->isSpectator())
+ if (participant->isSpectator()) {
++result;
+ }
}
return result;
}
@@ -269,8 +273,9 @@ void Server_Game::createGameStateChangedEvent(Event_GameStateChanged *event,
event->set_game_started(true);
event->set_active_player_id(0);
event->set_active_phase(0);
- } else
+ } else {
event->set_game_started(false);
+ }
for (Server_AbstractParticipant *participant : participants.values()) {
participant->getInfo(event->add_player_list(), recipient, omniscient, withUserInfo);
@@ -367,8 +372,9 @@ void Server_Game::doStartGameIfReady(bool forceStartGame)
delete replayCont;
startTimeOfThisGame = secondsElapsed;
- } else
+ } else {
firstGameStarted = true;
+ }
sendGameStateToPlayers();
@@ -396,11 +402,13 @@ void Server_Game::stopGameIfFinished()
int playing = 0;
auto players = getPlayers();
for (auto *player : players.values()) {
- if (!player->getConceded())
+ if (!player->getConceded()) {
++playing;
+ }
}
- if (playing > 1)
+ if (playing > 1) {
return;
+ }
gameStarted = false;
@@ -428,32 +436,40 @@ Response::ResponseCode Server_Game::checkJoin(ServerInfo_User *user,
{
Server_DatabaseInterface *databaseInterface = room->getServer()->getDatabaseInterface();
for (auto *participant : participants.values()) {
- if (participant->getUserInfo()->name() == user->name())
+ if (participant->getUserInfo()->name() == user->name()) {
return Response::RespContextError;
+ }
}
if (asJudge && !(user->user_level() & ServerInfo_User::IsJudge)) {
return Response::RespUserLevelTooLow;
}
if (!(overrideRestrictions && (user->user_level() & ServerInfo_User::IsModerator))) {
- if ((_password != password) && !(spectator && !spectatorsNeedPassword))
+ if ((_password != password) && !(spectator && !spectatorsNeedPassword)) {
return Response::RespWrongPassword;
- if (!(user->user_level() & ServerInfo_User::IsRegistered) && onlyRegistered)
+ }
+ if (!(user->user_level() & ServerInfo_User::IsRegistered) && onlyRegistered) {
return Response::RespUserLevelTooLow;
- if (onlyBuddies && (user->name() != creatorInfo->name()))
+ }
+ if (onlyBuddies && (user->name() != creatorInfo->name())) {
if (!databaseInterface->isInBuddyList(QString::fromStdString(creatorInfo->name()),
- QString::fromStdString(user->name())))
+ QString::fromStdString(user->name()))) {
return Response::RespOnlyBuddies;
+ }
+ }
if (databaseInterface->isInIgnoreList(QString::fromStdString(creatorInfo->name()),
- QString::fromStdString(user->name())))
+ QString::fromStdString(user->name()))) {
return Response::RespInIgnoreList;
+ }
if (spectator) {
- if (!spectatorsAllowed)
+ if (!spectatorsAllowed) {
return Response::RespSpectatorsNotAllowed;
+ }
}
}
- if (!spectator && (gameStarted || (getPlayerCount() >= getMaxPlayers())))
+ if (!spectator && (gameStarted || (getPlayerCount() >= getMaxPlayers()))) {
return Response::RespGameFull;
+ }
return Response::RespOk;
}
@@ -463,8 +479,9 @@ bool Server_Game::containsUser(const QString &userName) const
QMutexLocker locker(&gameMutex);
for (auto *participant : participants.values()) {
- if (participant->getUserInfo()->name() == userName.toStdString())
+ if (participant->getUserInfo()->name() == userName.toStdString()) {
return true;
+ }
}
return false;
}
@@ -516,8 +533,9 @@ void Server_Game::addPlayer(Server_AbstractUserInterface *userInterface,
emit gameInfoChanged(gameInfo);
}
- if ((newParticipant->getUserInfo()->user_level() & ServerInfo_User::IsRegistered) && !spectator)
+ if ((newParticipant->getUserInfo()->user_level() & ServerInfo_User::IsRegistered) && !spectator) {
room->getServer()->addPersistentPlayer(playerName, room->getId(), gameId, newParticipant->getPlayerId());
+ }
userInterface->playerAddedToGame(gameId, room->getId(), newParticipant->getPlayerId());
@@ -564,8 +582,9 @@ void Server_Game::removeParticipant(Server_AbstractParticipant *participant, Eve
}
if (!spectator) {
stopGameIfFinished();
- if (gameStarted && playerActive)
+ if (gameStarted && playerActive) {
nextTurn();
+ }
}
ServerInfo_Game gameInfo;
@@ -588,15 +607,18 @@ void Server_Game::removeArrowsRelatedToPlayer(GameEventStorage &ges, Server_Abst
for (auto *arrow : anyPlayer->getArrows().values()) {
auto *targetCard = qobject_cast(arrow->getTargetItem());
if (targetCard) {
- if (targetCard->getZone() != nullptr && targetCard->getZone()->getPlayer() == player)
+ if (targetCard->getZone() != nullptr && targetCard->getZone()->getPlayer() == player) {
toDelete.append(arrow);
+ }
} else if (arrow->getTargetItem() == player) {
toDelete.append(arrow);
}
// Don't use else here! It has to happen regardless of whether targetCard == 0.
- if (arrow->getStartCard()->getZone() != nullptr && arrow->getStartCard()->getZone()->getPlayer() == player)
+ if (arrow->getStartCard()->getZone() != nullptr &&
+ arrow->getStartCard()->getZone()->getPlayer() == player) {
toDelete.append(arrow);
+ }
}
for (auto *arrow : toDelete) {
Event_DeleteArrow event;
@@ -635,8 +657,9 @@ bool Server_Game::kickParticipant(int playerId)
QMutexLocker locker(&gameMutex);
auto *participant = participants.value(playerId);
- if (!participant)
+ if (!participant) {
return false;
+ }
GameEventContainer *gec = prepareGameEvent(Event_Kicked(), -1);
participant->sendGameEvent(*gec);
@@ -769,8 +792,9 @@ void Server_Game::sendGameEventContainer(GameEventContainer *cont,
const bool playerPrivate = (participant->getPlayerId() == privatePlayerId) || participant->isJudge() ||
(participant->isSpectator() && spectatorsSeeEverything);
if ((recipients.testFlag(GameEventStorageItem::SendToPrivate) && playerPrivate) ||
- (recipients.testFlag(GameEventStorageItem::SendToOthers) && !playerPrivate))
+ (recipients.testFlag(GameEventStorageItem::SendToOthers) && !playerPrivate)) {
participant->sendGameEvent(*cont);
+ }
}
if (recipients.testFlag(GameEventStorageItem::SendToPrivate)) {
cont->set_seconds_elapsed(secondsElapsed - startTimeOfThisGame);
@@ -786,11 +810,13 @@ Server_Game::prepareGameEvent(const ::google::protobuf::Message &gameEvent, int
{
auto *cont = new GameEventContainer;
cont->set_game_id(gameId);
- if (context)
+ if (context) {
cont->mutable_context()->CopyFrom(*context);
+ }
GameEvent *event = cont->add_event_list();
- if (playerId != -1)
+ if (playerId != -1) {
event->set_player_id(playerId);
+ }
event->GetReflection()
->MutableMessage(event, gameEvent.GetDescriptor()->FindExtensionByName("ext"))
->CopyFrom(gameEvent);
diff --git a/libcockatrice_network/libcockatrice/network/server/remote/server.cpp b/libcockatrice_network/libcockatrice/network/server/remote/server.cpp
index a5a74c54c..904637797 100644
--- a/libcockatrice_network/libcockatrice/network/server/remote/server.cpp
+++ b/libcockatrice_network/libcockatrice/network/server/remote/server.cpp
@@ -56,8 +56,9 @@ void Server::prepareDestroy()
{
roomsLock.lockForWrite();
QMapIterator roomIterator(rooms);
- while (roomIterator.hasNext())
+ while (roomIterator.hasNext()) {
delete roomIterator.next().value();
+ }
rooms.clear();
roomsLock.unlock();
}
@@ -86,22 +87,25 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session,
bool hasClientId = false;
if (clientid.isEmpty()) {
// client id is empty, either out dated client or client has been modified
- if (getClientIDRequiredEnabled())
+ if (getClientIDRequiredEnabled()) {
return ClientIdRequired;
+ }
} else {
hasClientId = true;
}
- if (name.size() > 35)
+ if (name.size() > 35) {
name = name.left(35);
+ }
Server_DatabaseInterface *databaseInterface = getDatabaseInterface();
AuthenticationResult authState = databaseInterface->checkUserPassword(session, name, password, clientid, reasonStr,
secondsLeft, passwordNeedsHash);
if (authState == NotLoggedIn || authState == UserIsBanned || authState == UsernameInvalid ||
- authState == UserIsInactive)
+ authState == UserIsInactive) {
return authState;
+ }
ServerInfo_User data = databaseInterface->getUserData(name, true);
data.set_address(session->getAddress().toStdString());
@@ -140,8 +144,9 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session,
QString tempName = name;
int i = 0;
while (users.contains(tempName) || databaseInterface->activeUserExists(tempName) ||
- databaseInterface->userSessionExists(tempName))
+ databaseInterface->userSessionExists(tempName)) {
tempName = name + "_" + QString::number(++i);
+ }
name = tempName;
data.set_name(name.toStdString());
}
@@ -163,9 +168,11 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session,
Event_UserJoined event;
event.mutable_user_info()->CopyFrom(session->copyUserInfo(false));
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
- for (auto &client : clients)
- if (client->getAcceptsUserListChanges())
+ for (auto &client : clients) {
+ if (client->getAcceptsUserListChanges()) {
client->sendProtocolItem(*se);
+ }
+ }
delete se;
event.mutable_user_info()->CopyFrom(session->copyUserInfo(true, true, true));
@@ -206,19 +213,22 @@ Server_AbstractUserInterface *Server::findUser(const QString &userName) const
// Call this only with clientsLock set.
Server_AbstractUserInterface *userHandler = users.value(userName);
- if (userHandler)
+ if (userHandler) {
return userHandler;
- else
+ } else {
return externalUsers.value(userName);
+ }
}
void Server::addClient(Server_ProtocolHandler *client)
{
- if (client->getConnectionType() == "tcp")
+ if (client->getConnectionType() == "tcp") {
tcpUserCount++;
+ }
- if (client->getConnectionType() == "websocket")
+ if (client->getConnectionType() == "websocket") {
webSocketUserCount++;
+ }
QWriteLocker locker(&clientsLock);
clients << client;
@@ -232,11 +242,13 @@ void Server::removeClient(Server_ProtocolHandler *client)
return;
}
- if (client->getConnectionType() == "tcp")
+ if (client->getConnectionType() == "tcp") {
tcpUserCount--;
+ }
- if (client->getConnectionType() == "websocket")
+ if (client->getConnectionType() == "websocket") {
webSocketUserCount--;
+ }
QWriteLocker locker(&clientsLock);
clients.removeAt(clientIndex);
@@ -245,9 +257,11 @@ void Server::removeClient(Server_ProtocolHandler *client)
Event_UserLeft event;
event.set_name(data->name());
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
- for (auto &_client : clients)
- if (_client->getAcceptsUserListChanges())
+ for (auto &_client : clients) {
+ if (_client->getAcceptsUserListChanges()) {
_client->sendProtocolItem(*se);
+ }
+ }
sendIsl_SessionEvent(*se);
delete se;
@@ -274,8 +288,9 @@ QList Server::getOnlineModeratorList() const
// TODO: this line should be updated in the event there is any type of new user level created
if (data &&
- (data->user_level() & ServerInfo_User::IsModerator || data->user_level() & ServerInfo_User::IsAdmin))
+ (data->user_level() & ServerInfo_User::IsModerator || data->user_level() & ServerInfo_User::IsAdmin)) {
results << QString::fromStdString(data->name()).simplified();
+ }
}
return results;
}
@@ -293,9 +308,11 @@ void Server::externalUserJoined(const ServerInfo_User &userInfo)
event.mutable_user_info()->CopyFrom(userInfo);
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
- for (auto &client : clients)
- if (client->getAcceptsUserListChanges())
+ for (auto &client : clients) {
+ if (client->getAcceptsUserListChanges()) {
client->sendProtocolItem(*se);
+ }
+ }
delete se;
clientsLock.unlock();
@@ -319,18 +336,21 @@ void Server::externalUserLeft(const QString &userName)
while (userGamesIterator.hasNext()) {
userGamesIterator.next();
Server_Room *room = rooms.value(userGamesIterator.value().first);
- if (!room)
+ if (!room) {
continue;
+ }
QReadLocker roomGamesLocker(&room->gamesLock);
Server_Game *game = room->getGames().value(userGamesIterator.key());
- if (!game)
+ if (!game) {
continue;
+ }
QMutexLocker gameLocker(&game->gameMutex);
auto *participant = game->getParticipants().value(userGamesIterator.value().second);
- if (!participant)
+ if (!participant) {
continue;
+ }
participant->disconnectClient();
}
@@ -343,9 +363,11 @@ void Server::externalUserLeft(const QString &userName)
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
clientsLock.lockForRead();
- for (auto &client : clients)
- if (client->getAcceptsUserListChanges())
+ for (auto &client : clients) {
+ if (client->getAcceptsUserListChanges()) {
client->sendProtocolItem(*se);
+ }
+ }
clientsLock.unlock();
delete se;
}
@@ -492,8 +514,9 @@ void Server::externalGameCommandContainerReceived(const CommandContainer &cont,
Response::ResponseCode resp = participant->processGameCommand(sc, responseContainer, ges);
- if (resp != Response::RespOk)
+ if (resp != Response::RespOk) {
finalResponseCode = resp;
+ }
}
ges.sendToGame(game);
@@ -547,13 +570,16 @@ void Server::broadcastRoomUpdate(const ServerInfo_Room &roomInfo, bool sendToIsl
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
clientsLock.lockForRead();
- for (auto &client : clients)
- if (client->getAcceptsRoomListChanges())
+ for (auto &client : clients) {
+ if (client->getAcceptsRoomListChanges()) {
client->sendProtocolItem(*se);
+ }
+ }
clientsLock.unlock();
- if (sendToIsl)
+ if (sendToIsl) {
sendIsl_SessionEvent(*se);
+ }
delete se;
}
@@ -591,8 +617,9 @@ void Server::sendIsl_Response(const Response &item, int serverId, qint64 session
{
IslMessage msg;
msg.set_message_type(IslMessage::RESPONSE);
- if (sessionId != -1)
+ if (sessionId != -1) {
msg.set_session_id(static_cast(sessionId));
+ }
msg.mutable_response()->CopyFrom(item);
emit sigSendIslMessage(msg, serverId);
@@ -602,8 +629,9 @@ void Server::sendIsl_SessionEvent(const SessionEvent &item, int serverId, qint64
{
IslMessage msg;
msg.set_message_type(IslMessage::SESSION_EVENT);
- if (sessionId != -1)
+ if (sessionId != -1) {
msg.set_session_id(static_cast(sessionId));
+ }
msg.mutable_session_event()->CopyFrom(item);
emit sigSendIslMessage(msg, serverId);
@@ -613,8 +641,9 @@ void Server::sendIsl_GameEventContainer(const GameEventContainer &item, int serv
{
IslMessage msg;
msg.set_message_type(IslMessage::GAME_EVENT_CONTAINER);
- if (sessionId != -1)
+ if (sessionId != -1) {
msg.set_session_id(static_cast(sessionId));
+ }
msg.mutable_game_event_container()->CopyFrom(item);
emit sigSendIslMessage(msg, serverId);
@@ -624,8 +653,9 @@ void Server::sendIsl_RoomEvent(const RoomEvent &item, int serverId, qint64 sessi
{
IslMessage msg;
msg.set_message_type(IslMessage::ROOM_EVENT);
- if (sessionId != -1)
+ if (sessionId != -1) {
msg.set_session_id(static_cast(sessionId));
+ }
msg.mutable_room_event()->CopyFrom(item);
emit sigSendIslMessage(msg, serverId);
diff --git a/libcockatrice_network/libcockatrice/network/server/remote/server_abstractuserinterface.cpp b/libcockatrice_network/libcockatrice/network/server/remote/server_abstractuserinterface.cpp
index f9b61ab48..641be1eed 100644
--- a/libcockatrice_network/libcockatrice/network/server/remote/server_abstractuserinterface.cpp
+++ b/libcockatrice_network/libcockatrice/network/server/remote/server_abstractuserinterface.cpp
@@ -45,25 +45,28 @@ void Server_AbstractUserInterface::sendResponseContainer(const ResponseContainer
{
const QList> &preResponseQueue =
responseContainer.getPreResponseQueue();
- for (int i = 0; i < preResponseQueue.size(); ++i)
+ for (int i = 0; i < preResponseQueue.size(); ++i) {
sendProtocolItemByType(preResponseQueue[i].first, *preResponseQueue[i].second);
+ }
if (responseCode != Response::RespNothing) {
Response response;
response.set_cmd_id(responseContainer.getCmdId());
response.set_response_code(responseCode);
::google::protobuf::Message *responseExtension = responseContainer.getResponseExtension();
- if (responseExtension)
+ if (responseExtension) {
response.GetReflection()
->MutableMessage(&response, responseExtension->GetDescriptor()->FindExtensionByName("ext"))
->CopyFrom(*responseExtension);
+ }
sendProtocolItem(response);
}
const QList> &postResponseQueue =
responseContainer.getPostResponseQueue();
- for (int i = 0; i < postResponseQueue.size(); ++i)
+ for (int i = 0; i < postResponseQueue.size(); ++i) {
sendProtocolItemByType(postResponseQueue[i].first, *postResponseQueue[i].second);
+ }
}
void Server_AbstractUserInterface::playerRemovedFromGame(Server_Game *game)
@@ -92,18 +95,21 @@ void Server_AbstractUserInterface::joinPersistentGames(ResponseContainer &rc)
const PlayerReference &pr = gamesToJoin.at(i);
Server_Room *room = server->getRooms().value(pr.getRoomId());
- if (!room)
+ if (!room) {
continue;
+ }
QReadLocker roomGamesLocker(&room->gamesLock);
Server_Game *game = room->getGames().value(pr.getGameId());
- if (!game)
+ if (!game) {
continue;
+ }
QMutexLocker gameLocker(&game->gameMutex);
auto *participant = game->getParticipants().value(pr.getPlayerId());
- if (!participant)
+ if (!participant) {
continue;
+ }
participant->setUserInterface(this);
playerAddedToGame(game->getGameId(), room->getId(), participant->getPlayerId());
diff --git a/libcockatrice_network/libcockatrice/network/server/remote/server_protocolhandler.cpp b/libcockatrice_network/libcockatrice/network/server/remote/server_protocolhandler.cpp
index bfd8d113c..27ebaf228 100644
--- a/libcockatrice_network/libcockatrice/network/server/remote/server_protocolhandler.cpp
+++ b/libcockatrice_network/libcockatrice/network/server/remote/server_protocolhandler.cpp
@@ -48,8 +48,9 @@ Server_ProtocolHandler::~Server_ProtocolHandler()
// The thread must not hold any server locks when calling this (e.g. clientsLock, roomsLock).
void Server_ProtocolHandler::prepareDestroy()
{
- if (deleted)
+ if (deleted) {
return;
+ }
deleted = true;
for (auto *room : rooms.values()) {
@@ -64,8 +65,9 @@ void Server_ProtocolHandler::prepareDestroy()
gameIterator.next();
Server_Room *room = server->getRooms().value(gameIterator.value().first);
- if (!room)
+ if (!room) {
continue;
+ }
room->gamesLock.lockForRead();
Server_Game *game = room->getGames().value(gameIterator.key());
if (!game) {
@@ -167,8 +169,9 @@ Response::ResponseCode Server_ProtocolHandler::processSessionCommandContainer(co
default:
resp = processExtendedSessionCommand(num, sc, rc);
}
- if (resp != Response::RespOk)
+ if (resp != Response::RespOk) {
finalResponseCode = resp;
+ }
}
return finalResponseCode;
}
@@ -176,13 +179,15 @@ Response::ResponseCode Server_ProtocolHandler::processSessionCommandContainer(co
Response::ResponseCode Server_ProtocolHandler::processRoomCommandContainer(const CommandContainer &cont,
ResponseContainer &rc)
{
- if (authState == NotLoggedIn)
+ if (authState == NotLoggedIn) {
return Response::RespLoginNeeded;
+ }
QReadLocker locker(&server->roomsLock);
Server_Room *room = rooms.value(cont.room_id(), 0);
- if (!room)
+ if (!room) {
return Response::RespNotInRoom;
+ }
resetIdleTimer();
@@ -206,8 +211,9 @@ Response::ResponseCode Server_ProtocolHandler::processRoomCommandContainer(const
resp = cmdJoinGame(sc.GetExtension(Command_JoinGame::ext), room, rc);
break;
}
- if (resp != Response::RespOk)
+ if (resp != Response::RespOk) {
finalResponseCode = resp;
+ }
}
return finalResponseCode;
}
@@ -232,18 +238,21 @@ Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const
// allows a user to sideboard without receiving flooding message
<< GameCommand::MOVE_CARD;
- if (authState == NotLoggedIn)
+ if (authState == NotLoggedIn) {
return Response::RespLoginNeeded;
+ }
QMap> gameMap = getGames();
- if (!gameMap.contains(cont.game_id()))
+ if (!gameMap.contains(cont.game_id())) {
return Response::RespNotInRoom;
+ }
const QPair roomIdAndPlayerId = gameMap.value(cont.game_id());
QReadLocker roomsLocker(&server->roomsLock);
Server_Room *room = server->getRooms().value(roomIdAndPlayerId.first);
- if (!room)
+ if (!room) {
return Response::RespNotInRoom;
+ }
QReadLocker roomGamesLocker(&room->gamesLock);
Server_Game *game = room->getGames().value(cont.game_id());
@@ -258,8 +267,9 @@ Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const
QMutexLocker gameLocker(&game->gameMutex);
auto *participant = game->getParticipants().value(roomIdAndPlayerId.second);
- if (!participant)
+ if (!participant) {
return Response::RespNotInRoom;
+ }
resetIdleTimer();
@@ -274,11 +284,13 @@ Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const
if (commandCountingInterval > 0) {
int totalCount = 0;
- if (commandCountOverTime.isEmpty())
+ if (commandCountOverTime.isEmpty()) {
commandCountOverTime.prepend(0);
+ }
- if (!antifloodCommandsWhiteList.contains((GameCommand::GameCommandType)getPbExtension(sc)))
+ if (!antifloodCommandsWhiteList.contains((GameCommand::GameCommandType)getPbExtension(sc))) {
++commandCountOverTime[0];
+ }
for (int count : commandCountOverTime) {
totalCount += count;
@@ -291,8 +303,9 @@ Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const
Response::ResponseCode resp = participant->processGameCommand(sc, rc, ges);
- if (resp != Response::RespOk)
+ if (resp != Response::RespOk) {
finalResponseCode = resp;
+ }
}
ges.sendToGame(game);
@@ -302,10 +315,12 @@ Response::ResponseCode Server_ProtocolHandler::processGameCommandContainer(const
Response::ResponseCode Server_ProtocolHandler::processModeratorCommandContainer(const CommandContainer &cont,
ResponseContainer &rc)
{
- if (!userInfo)
+ if (!userInfo) {
return Response::RespLoginNeeded;
- if (!(userInfo->user_level() & ServerInfo_User::IsModerator))
+ }
+ if (!(userInfo->user_level() & ServerInfo_User::IsModerator)) {
return Response::RespLoginNeeded;
+ }
resetIdleTimer();
@@ -317,8 +332,9 @@ Response::ResponseCode Server_ProtocolHandler::processModeratorCommandContainer(
logDebugMessage(getSafeDebugString(sc));
resp = processExtendedModeratorCommand(num, sc, rc);
- if (resp != Response::RespOk)
+ if (resp != Response::RespOk) {
finalResponseCode = resp;
+ }
}
return finalResponseCode;
}
@@ -326,10 +342,12 @@ Response::ResponseCode Server_ProtocolHandler::processModeratorCommandContainer(
Response::ResponseCode Server_ProtocolHandler::processAdminCommandContainer(const CommandContainer &cont,
ResponseContainer &rc)
{
- if (!userInfo)
+ if (!userInfo) {
return Response::RespLoginNeeded;
- if (!(userInfo->user_level() & ServerInfo_User::IsAdmin))
+ }
+ if (!(userInfo->user_level() & ServerInfo_User::IsAdmin)) {
return Response::RespLoginNeeded;
+ }
resetIdleTimer();
@@ -341,8 +359,9 @@ Response::ResponseCode Server_ProtocolHandler::processAdminCommandContainer(cons
logDebugMessage(getSafeDebugString(sc));
resp = processExtendedAdminCommand(num, sc, rc);
- if (resp != Response::RespOk)
+ if (resp != Response::RespOk) {
finalResponseCode = resp;
+ }
}
return finalResponseCode;
}
@@ -350,29 +369,32 @@ Response::ResponseCode Server_ProtocolHandler::processAdminCommandContainer(cons
void Server_ProtocolHandler::processCommandContainer(const CommandContainer &cont)
{
// Command processing must be disabled after prepareDestroy() has been called.
- if (deleted)
+ if (deleted) {
return;
+ }
lastDataReceived = timeRunning;
ResponseContainer responseContainer(cont.has_cmd_id() ? cont.cmd_id() : -1);
Response::ResponseCode finalResponseCode;
- if (cont.game_command_size())
+ if (cont.game_command_size()) {
finalResponseCode = processGameCommandContainer(cont, responseContainer);
- else if (cont.room_command_size())
+ } else if (cont.room_command_size()) {
finalResponseCode = processRoomCommandContainer(cont, responseContainer);
- else if (cont.session_command_size())
+ } else if (cont.session_command_size()) {
finalResponseCode = processSessionCommandContainer(cont, responseContainer);
- else if (cont.moderator_command_size())
+ } else if (cont.moderator_command_size()) {
finalResponseCode = processModeratorCommandContainer(cont, responseContainer);
- else if (cont.admin_command_size())
+ } else if (cont.admin_command_size()) {
finalResponseCode = processAdminCommandContainer(cont, responseContainer);
- else
+ } else {
finalResponseCode = Response::RespInvalidCommand;
+ }
- if ((finalResponseCode != Response::RespNothing))
+ if ((finalResponseCode != Response::RespNothing)) {
sendResponseContainer(responseContainer, finalResponseCode);
+ }
}
void Server_ProtocolHandler::pingClockTimeout()
@@ -386,11 +408,13 @@ void Server_ProtocolHandler::pingClockTimeout()
if (interval > 0) {
if (pingclockinterval > 0) {
messageSizeOverTime.prepend(0);
- if (messageSizeOverTime.size() > (msgcountinterval / pingclockinterval))
+ if (messageSizeOverTime.size() > (msgcountinterval / pingclockinterval)) {
messageSizeOverTime.removeLast();
+ }
messageCountOverTime.prepend(0);
- if (messageCountOverTime.size() > (msgcountinterval / pingclockinterval))
+ if (messageCountOverTime.size() > (msgcountinterval / pingclockinterval)) {
messageCountOverTime.removeLast();
+ }
}
}
@@ -398,13 +422,15 @@ void Server_ProtocolHandler::pingClockTimeout()
if (interval > 0) {
if (pingclockinterval > 0) {
commandCountOverTime.prepend(0);
- if (commandCountOverTime.size() > (cmdcountinterval / pingclockinterval))
+ if (commandCountOverTime.size() > (cmdcountinterval / pingclockinterval)) {
commandCountOverTime.removeLast();
+ }
}
}
- if (timeRunning - lastDataReceived > server->getMaxPlayerInactivityTime())
+ if (timeRunning - lastDataReceived > server->getMaxPlayerInactivityTime()) {
prepareDestroy();
+ }
// PrivLevel users, Moderators, and Admins are not subject to the server idle timeout policy
const bool hasPrivLevel = userInfo && QString::fromStdString(userInfo->privlevel()).toLower() != "none";
@@ -444,8 +470,9 @@ Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd
QString password;
bool needsHash = false;
if (cmd.has_password()) {
- if (cmd.password().length() > MAX_NAME_LENGTH)
+ if (cmd.password().length() > MAX_NAME_LENGTH) {
return Response::RespWrongPassword;
+ }
password = QString::fromStdString(cmd.password());
needsHash = true;
} else if (cmd.hashed_password().length() > MAX_NAME_LENGTH) {
@@ -493,8 +520,9 @@ Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd
case UserIsBanned: {
auto *re = new Response_Login;
re->set_denied_reason_str(reasonStr.toStdString());
- if (banSecondsLeft != 0)
+ if (banSecondsLeft != 0) {
re->set_denied_end_time(QDateTime::currentDateTime().addSecs(banSecondsLeft).toSecsSinceEpoch());
+ }
rc.setResponseExtension(re);
return Response::RespUserIsBanned;
}
@@ -539,19 +567,22 @@ Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd
if (authState == PasswordRight) {
QMapIterator buddyIterator(databaseInterface->getBuddyList(userName));
- while (buddyIterator.hasNext())
+ while (buddyIterator.hasNext()) {
re->add_buddy_list()->CopyFrom(buddyIterator.next().value());
+ }
QMapIterator ignoreIterator(databaseInterface->getIgnoreList(userName));
- while (ignoreIterator.hasNext())
+ while (ignoreIterator.hasNext()) {
re->add_ignore_list()->CopyFrom(ignoreIterator.next().value());
+ }
}
// return to client any missing features the server has that the client does not
if (!missingClientFeatures.isEmpty()) {
QMap::iterator i;
- for (i = missingClientFeatures.begin(); i != missingClientFeatures.end(); ++i)
+ for (i = missingClientFeatures.begin(); i != missingClientFeatures.end(); ++i) {
re->add_missing_features(i.key().toStdString().c_str());
+ }
}
joinPersistentGames(rc);
@@ -562,8 +593,9 @@ Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd
Response::ResponseCode Server_ProtocolHandler::cmdMessage(const Command_Message &cmd, ResponseContainer &rc)
{
- if (authState == NotLoggedIn)
+ if (authState == NotLoggedIn) {
return Response::RespLoginNeeded;
+ }
QReadLocker locker(&server->clientsLock);
@@ -599,8 +631,9 @@ Response::ResponseCode Server_ProtocolHandler::cmdMessage(const Command_Message
Response::ResponseCode Server_ProtocolHandler::cmdGetGamesOfUser(const Command_GetGamesOfUser &cmd,
ResponseContainer &rc)
{
- if (authState == NotLoggedIn)
+ if (authState == NotLoggedIn) {
return Response::RespLoginNeeded;
+ }
// Do not show games to someone on the ignore list of that user, except for mods
QString target_user = nameFromStdString(cmd.user_name());
@@ -624,8 +657,9 @@ Response::ResponseCode Server_ProtocolHandler::cmdGetGamesOfUser(const Command_G
room->gamesLock.lockForRead();
room->getInfo(*re->add_room_list(), false, true);
QListIterator gameIterator(room->getGamesOfUser(nameFromStdString(cmd.user_name())));
- while (gameIterator.hasNext())
+ while (gameIterator.hasNext()) {
re->add_game_list()->CopyFrom(gameIterator.next());
+ }
room->gamesLock.unlock();
}
server->roomsLock.unlock();
@@ -636,14 +670,15 @@ Response::ResponseCode Server_ProtocolHandler::cmdGetGamesOfUser(const Command_G
Response::ResponseCode Server_ProtocolHandler::cmdGetUserInfo(const Command_GetUserInfo &cmd, ResponseContainer &rc)
{
- if (authState == NotLoggedIn)
+ if (authState == NotLoggedIn) {
return Response::RespLoginNeeded;
+ }
QString userName = nameFromStdString(cmd.user_name());
auto *re = new Response_GetUserInfo;
- if (userName.isEmpty())
+ if (userName.isEmpty()) {
re->mutable_user_info()->CopyFrom(*userInfo);
- else {
+ } else {
QReadLocker locker(&server->clientsLock);
@@ -662,13 +697,15 @@ Response::ResponseCode Server_ProtocolHandler::cmdGetUserInfo(const Command_GetU
Response::ResponseCode Server_ProtocolHandler::cmdListRooms(const Command_ListRooms & /*cmd*/, ResponseContainer &rc)
{
- if (authState == NotLoggedIn)
+ if (authState == NotLoggedIn) {
return Response::RespLoginNeeded;
+ }
Event_ListRooms event;
QMapIterator roomIterator(server->getRooms());
- while (roomIterator.hasNext())
+ while (roomIterator.hasNext()) {
roomIterator.next().value()->getInfo(*event.add_room_list(), false);
+ }
rc.enqueuePreResponseItem(ServerMessage::SESSION_EVENT, prepareSessionEvent(event));
acceptsRoomListChanges = true;
@@ -677,20 +714,25 @@ Response::ResponseCode Server_ProtocolHandler::cmdListRooms(const Command_ListRo
Response::ResponseCode Server_ProtocolHandler::cmdJoinRoom(const Command_JoinRoom &cmd, ResponseContainer &rc)
{
- if (authState == NotLoggedIn)
+ if (authState == NotLoggedIn) {
return Response::RespLoginNeeded;
+ }
- if (rooms.contains(cmd.room_id()))
+ if (rooms.contains(cmd.room_id())) {
return Response::RespContextError;
+ }
QReadLocker serverLocker(&server->roomsLock);
Server_Room *room = server->getRooms().value(cmd.room_id(), 0);
- if (!room)
+ if (!room) {
return Response::RespNameNotFound;
+ }
- if (!(userInfo->user_level() & ServerInfo_User::IsModerator))
- if (!(room->userMayJoin(*userInfo)))
+ if (!(userInfo->user_level() & ServerInfo_User::IsModerator)) {
+ if (!(room->userMayJoin(*userInfo))) {
return Response::RespUserLevelTooLow;
+ }
+ }
room->addClient(this);
rooms.insert(room->getId(), room);
@@ -722,17 +764,20 @@ Response::ResponseCode Server_ProtocolHandler::cmdJoinRoom(const Command_JoinRoo
Response::ResponseCode Server_ProtocolHandler::cmdListUsers(const Command_ListUsers & /*cmd*/, ResponseContainer &rc)
{
- if (authState == NotLoggedIn)
+ if (authState == NotLoggedIn) {
return Response::RespLoginNeeded;
+ }
auto *re = new Response_ListUsers;
server->clientsLock.lockForRead();
QMapIterator userIterator = server->getUsers();
- while (userIterator.hasNext())
+ while (userIterator.hasNext()) {
re->add_user_list()->CopyFrom(userIterator.next().value()->copyUserInfo(false));
+ }
QMapIterator extIterator = server->getExternalUsers();
- while (extIterator.hasNext())
+ while (extIterator.hasNext()) {
re->add_user_list()->CopyFrom(extIterator.next().value()->copyUserInfo(false));
+ }
acceptsUserListChanges = true;
server->clientsLock.unlock();
@@ -799,10 +844,12 @@ Server_ProtocolHandler::cmdRoomSay(const Command_RoomSay &cmd, Server_Room *room
Response::ResponseCode
Server_ProtocolHandler::cmdCreateGame(const Command_CreateGame &cmd, Server_Room *room, ResponseContainer &rc)
{
- if (authState == NotLoggedIn)
+ if (authState == NotLoggedIn) {
return Response::RespLoginNeeded;
- if (cmd.password().length() > MAX_NAME_LENGTH)
+ }
+ if (cmd.password().length() > MAX_NAME_LENGTH) {
return Response::RespContextError;
+ }
auto level = userInfo->user_level();
bool isJudge = level & ServerInfo_User::IsJudge;
@@ -852,8 +899,9 @@ Server_ProtocolHandler::cmdCreateGame(const Command_CreateGame &cmd, Server_Room
Response::ResponseCode
Server_ProtocolHandler::cmdJoinGame(const Command_JoinGame &cmd, Server_Room *room, ResponseContainer &rc)
{
- if (authState == NotLoggedIn)
+ if (authState == NotLoggedIn) {
return Response::RespLoginNeeded;
+ }
return room->processJoinGameCommand(cmd, rc, this);
}
diff --git a/libcockatrice_network/libcockatrice/network/server/remote/server_response_containers.cpp b/libcockatrice_network/libcockatrice/network/server/remote/server_response_containers.cpp
index 9b07bdb91..22fb199fb 100644
--- a/libcockatrice_network/libcockatrice/network/server/remote/server_response_containers.cpp
+++ b/libcockatrice_network/libcockatrice/network/server/remote/server_response_containers.cpp
@@ -25,8 +25,9 @@ GameEventStorage::GameEventStorage() : gameEventContext(0), privatePlayerId(0)
GameEventStorage::~GameEventStorage()
{
delete gameEventContext;
- for (int i = 0; i < gameEventList.size(); ++i)
+ for (int i = 0; i < gameEventList.size(); ++i) {
delete gameEventList[i];
+ }
}
void GameEventStorage::setGameEventContext(const ::google::protobuf::Message &_gameEventContext)
@@ -44,14 +45,16 @@ void GameEventStorage::enqueueGameEvent(const ::google::protobuf::Message &event
int _privatePlayerId)
{
gameEventList.append(new GameEventStorageItem(event, playerId, recipients));
- if (_privatePlayerId != -1)
+ if (_privatePlayerId != -1) {
privatePlayerId = _privatePlayerId;
+ }
}
void GameEventStorage::sendToGame(Server_Game *game)
{
- if (gameEventList.isEmpty())
+ if (gameEventList.isEmpty()) {
return;
+ }
auto *contPrivate = new GameEventContainer;
auto *contOthers = new GameEventContainer;
@@ -68,10 +71,12 @@ void GameEventStorage::sendToGame(Server_Game *game)
for (const auto &i : gameEventList) {
const GameEvent &event = i->getGameEvent();
const GameEventStorageItem::EventRecipients recipients = i->getRecipients();
- if (recipients.testFlag(GameEventStorageItem::SendToPrivate))
+ if (recipients.testFlag(GameEventStorageItem::SendToPrivate)) {
contPrivate->add_event_list()->CopyFrom(event);
- if (recipients.testFlag(GameEventStorageItem::SendToOthers))
+ }
+ if (recipients.testFlag(GameEventStorageItem::SendToOthers)) {
contOthers->add_event_list()->CopyFrom(event);
+ }
}
if (gameEventContext) {
contPrivate->mutable_context()->CopyFrom(*gameEventContext);
@@ -88,8 +93,10 @@ ResponseContainer::ResponseContainer(int _cmdId) : cmdId(_cmdId), responseExtens
ResponseContainer::~ResponseContainer()
{
delete responseExtension;
- for (int i = 0; i < preResponseQueue.size(); ++i)
+ for (int i = 0; i < preResponseQueue.size(); ++i) {
delete preResponseQueue[i].second;
- for (int i = 0; i < postResponseQueue.size(); ++i)
+ }
+ for (int i = 0; i < postResponseQueue.size(); ++i) {
delete postResponseQueue[i].second;
+ }
}
diff --git a/libcockatrice_network/libcockatrice/network/server/remote/server_room.cpp b/libcockatrice_network/libcockatrice/network/server/remote/server_room.cpp
index bfa8912b1..1bd928e09 100644
--- a/libcockatrice_network/libcockatrice/network/server/remote/server_room.cpp
+++ b/libcockatrice_network/libcockatrice/network/server/remote/server_room.cpp
@@ -42,8 +42,9 @@ Server_Room::~Server_Room()
gamesLock.lockForWrite();
const QList gameList = games.values();
- for (int i = 0; i < gameList.size(); ++i)
+ for (int i = 0; i < gameList.size(); ++i) {
delete gameList[i];
+ }
games.clear();
gamesLock.unlock();
@@ -55,19 +56,23 @@ Server_Room::~Server_Room()
bool Server_Room::userMayJoin(const ServerInfo_User &userInfo)
{
- if (permissionLevel.toLower() == "administrator" || permissionLevel.toLower() == "moderator")
+ if (permissionLevel.toLower() == "administrator" || permissionLevel.toLower() == "moderator") {
return false;
+ }
- if (permissionLevel.toLower() == "registered" && !(userInfo.user_level() & ServerInfo_User::IsRegistered))
+ if (permissionLevel.toLower() == "registered" && !(userInfo.user_level() & ServerInfo_User::IsRegistered)) {
return false;
+ }
if (privilegeLevel.toLower() != "none") {
if (privilegeLevel.toLower() == "privileged") {
- if (privilegeLevel.toLower() == "none")
+ if (privilegeLevel.toLower() == "none") {
return false;
+ }
} else {
- if (privilegeLevel.toLower() != QString::fromStdString(userInfo.privlevel()).toLower())
+ if (privilegeLevel.toLower() != QString::fromStdString(userInfo.privlevel()).toLower()) {
return false;
+ }
}
}
return true;
@@ -92,12 +97,14 @@ Server_Room::getInfo(ServerInfo_Room &result, bool complete, bool showGameTypes,
result.set_game_count(games.size() + externalGames.size());
if (complete) {
QMapIterator gameIterator(games);
- while (gameIterator.hasNext())
+ while (gameIterator.hasNext()) {
gameIterator.next().value()->getInfo(*result.add_game_list());
+ }
if (includeExternalData) {
QMapIterator externalGameIterator(externalGames);
- while (externalGameIterator.hasNext())
+ while (externalGameIterator.hasNext()) {
result.add_game_list()->CopyFrom(externalGameIterator.next().value());
+ }
}
}
gamesLock.unlock();
@@ -106,22 +113,25 @@ Server_Room::getInfo(ServerInfo_Room &result, bool complete, bool showGameTypes,
result.set_player_count(users.size() + externalUsers.size());
if (complete) {
QMapIterator userIterator(users);
- while (userIterator.hasNext())
+ while (userIterator.hasNext()) {
result.add_user_list()->CopyFrom(userIterator.next().value()->copyUserInfo(false));
+ }
if (includeExternalData) {
QMapIterator externalUserIterator(externalUsers);
- while (externalUserIterator.hasNext())
+ while (externalUserIterator.hasNext()) {
result.add_user_list()->CopyFrom(externalUserIterator.next().value().copyUserInfo(false));
+ }
}
}
usersLock.unlock();
- if (complete || showGameTypes)
+ if (complete || showGameTypes) {
for (int i = 0; i < gameTypes.size(); ++i) {
ServerInfo_GameType *gameTypeInfo = result.add_gametype_list();
gameTypeInfo->set_game_type_id(i);
gameTypeInfo->set_description(gameTypes[i].toStdString());
}
+ }
return result;
}
@@ -208,8 +218,9 @@ void Server_Room::removeExternalUser(const QString &_name)
roomInfo.set_room_id(id);
usersLock.lockForWrite();
- if (externalUsers.contains(_name))
+ if (externalUsers.contains(_name)) {
externalUsers.remove(_name);
+ }
roomInfo.set_player_count(users.size() + externalUsers.size());
usersLock.unlock();
@@ -227,10 +238,11 @@ void Server_Room::updateExternalGameList(const ServerInfo_Game &gameInfo)
roomInfo.set_room_id(id);
gamesLock.lockForWrite();
- if (!gameInfo.has_player_count() && externalGames.contains(gameInfo.game_id()))
+ if (!gameInfo.has_player_count() && externalGames.contains(gameInfo.game_id())) {
externalGames.remove(gameInfo.game_id());
- else
+ } else {
externalGames.insert(gameInfo.game_id(), gameInfo);
+ }
roomInfo.set_game_count(games.size() + externalGames.size());
gamesLock.unlock();
@@ -242,8 +254,9 @@ Response::ResponseCode Server_Room::processJoinGameCommand(const Command_JoinGam
ResponseContainer &rc,
Server_AbstractUserInterface *userInterface)
{
- if (cmd.password().length() > MAX_NAME_LENGTH)
+ if (cmd.password().length() > MAX_NAME_LENGTH) {
return Response::RespWrongPassword;
+ }
// This function is called from the Server thread and from the S_PH thread.
// server->roomsMutex is always locked.
@@ -271,8 +284,9 @@ Response::ResponseCode Server_Room::processJoinGameCommand(const Command_JoinGam
Response::ResponseCode result =
game->checkJoin(userInterface->getUserInfo(), QString::fromStdString(cmd.password()), cmd.spectator(),
cmd.override_restrictions(), cmd.join_as_judge());
- if (result == Response::RespOk)
+ if (result == Response::RespOk) {
game->addPlayer(userInterface, rc, cmd.spectator(), cmd.join_as_judge());
+ }
return result;
}
@@ -329,13 +343,15 @@ void Server_Room::sendRoomEvent(RoomEvent *event, bool sendToIsl)
usersLock.lockForRead();
{
QMapIterator userIterator(users);
- while (userIterator.hasNext())
+ while (userIterator.hasNext()) {
userIterator.next().value()->sendProtocolItem(*event);
+ }
}
usersLock.unlock();
- if (sendToIsl)
+ if (sendToIsl) {
static_cast(parent())->sendIsl_RoomEvent(*event);
+ }
delete event;
}
@@ -405,9 +421,11 @@ int Server_Room::getGamesCreatedByUser(const QString &userName) const
QMapIterator gamesIterator(games);
int result = 0;
- while (gamesIterator.hasNext())
- if (gamesIterator.next().value()->getCreatorInfo()->name() == userName.toStdString())
+ while (gamesIterator.hasNext()) {
+ if (gamesIterator.next().value()->getCreatorInfo()->name() == userName.toStdString()) {
++result;
+ }
+ }
return result;
}
diff --git a/libcockatrice_network/libcockatrice/network/server/remote/serverinfo_user_container.cpp b/libcockatrice_network/libcockatrice/network/server/remote/serverinfo_user_container.cpp
index 77ff38906..24e734a4e 100644
--- a/libcockatrice_network/libcockatrice/network/server/remote/serverinfo_user_container.cpp
+++ b/libcockatrice_network/libcockatrice/network/server/remote/serverinfo_user_container.cpp
@@ -13,10 +13,11 @@ ServerInfo_User_Container::ServerInfo_User_Container(const ServerInfo_User &_use
ServerInfo_User_Container::ServerInfo_User_Container(const ServerInfo_User_Container &other)
{
- if (other.userInfo)
+ if (other.userInfo) {
userInfo = new ServerInfo_User(*other.userInfo);
- else
+ } else {
userInfo = nullptr;
+ }
}
ServerInfo_User_Container::~ServerInfo_User_Container()
@@ -45,8 +46,9 @@ ServerInfo_User &ServerInfo_User_Container::copyUserInfo(ServerInfo_User &result
result.clear_id();
result.clear_email();
}
- if (!complete)
+ if (!complete) {
result.clear_avatar_bmp();
+ }
}
return result;
}
diff --git a/libcockatrice_protocol/libcockatrice/protocol/debug_pb_message.cpp b/libcockatrice_protocol/libcockatrice/protocol/debug_pb_message.cpp
index 718487c18..c419a68d4 100644
--- a/libcockatrice_protocol/libcockatrice/protocol/debug_pb_message.cpp
+++ b/libcockatrice_protocol/libcockatrice/protocol/debug_pb_message.cpp
@@ -58,8 +58,9 @@ void SafePrinter::applySafePrinter(const ::google::protobuf::Message &message,
case ::google::protobuf::FieldDescriptor::CPPTYPE_STRING:
if (field->name().find("password") != std::string::npos) { // name contains password
auto *safePrinter = new SafePrinter();
- if (!printer.RegisterFieldValuePrinter(field, safePrinter))
+ if (!printer.RegisterFieldValuePrinter(field, safePrinter)) {
delete safePrinter; // in case safePrinter has not been taken ownership of
+ }
}
break;
case google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE:
diff --git a/libcockatrice_protocol/libcockatrice/protocol/featureset.cpp b/libcockatrice_protocol/libcockatrice/protocol/featureset.cpp
index 1b08c4040..3e687ef56 100644
--- a/libcockatrice_protocol/libcockatrice/protocol/featureset.cpp
+++ b/libcockatrice_protocol/libcockatrice/protocol/featureset.cpp
@@ -33,14 +33,16 @@ void FeatureSet::initalizeFeatureList(QMap &_featureList)
void FeatureSet::enableRequiredFeature(QMap &_featureList, const QString &featureName)
{
- if (_featureList.contains(featureName))
+ if (_featureList.contains(featureName)) {
_featureList.insert(featureName, true);
+ }
}
void FeatureSet::disableRequiredFeature(QMap &_featureList, const QString &featureName)
{
- if (_featureList.contains(featureName))
+ if (_featureList.contains(featureName)) {
_featureList.insert(featureName, false);
+ }
}
QMap
diff --git a/libcockatrice_protocol/libcockatrice/protocol/get_pb_extension.cpp b/libcockatrice_protocol/libcockatrice/protocol/get_pb_extension.cpp
index d6235858a..a693ea5a7 100644
--- a/libcockatrice_protocol/libcockatrice/protocol/get_pb_extension.cpp
+++ b/libcockatrice_protocol/libcockatrice/protocol/get_pb_extension.cpp
@@ -7,8 +7,10 @@ int getPbExtension(const ::google::protobuf::Message &message)
{
std::vector fieldList;
message.GetReflection()->ListFields(message, &fieldList);
- for (unsigned int j = 0; j < fieldList.size(); ++j)
- if (fieldList[j]->is_extension())
+ for (unsigned int j = 0; j < fieldList.size(); ++j) {
+ if (fieldList[j]->is_extension()) {
return fieldList[j]->number();
+ }
+ }
return -1;
}
diff --git a/libcockatrice_rng/libcockatrice/rng/rng_abstract.cpp b/libcockatrice_rng/libcockatrice/rng/rng_abstract.cpp
index 63072b988..82404d351 100644
--- a/libcockatrice_rng/libcockatrice/rng/rng_abstract.cpp
+++ b/libcockatrice_rng/libcockatrice/rng/rng_abstract.cpp
@@ -8,10 +8,11 @@ QVector RNG_Abstract::makeNumbersVector(int n, int min, int max)
QVector result(bins);
for (int i = 0; i < n; ++i) {
int number = rand(min, max);
- if ((number < min) || (number > max))
+ if ((number < min) || (number > max)) {
qDebug() << "rand(" << min << "," << max << ") returned " << number;
- else
+ } else {
result[number - min]++;
+ }
}
return result;
}
@@ -19,12 +20,14 @@ QVector RNG_Abstract::makeNumbersVector(int n, int min, int max)
double RNG_Abstract::testRandom(const QVector &numbers) const
{
int n = 0;
- for (int i = 0; i < numbers.size(); ++i)
+ for (int i = 0; i < numbers.size(); ++i) {
n += numbers[i];
+ }
double expected = (double)n / (double)numbers.size();
double chisq = 0;
- for (int i = 0; i < numbers.size(); ++i)
+ for (int i = 0; i < numbers.size(); ++i) {
chisq += ((double)numbers[i] - expected) * ((double)numbers[i] - expected) / expected;
+ }
return chisq;
}
diff --git a/libcockatrice_rng/libcockatrice/rng/rng_sfmt.cpp b/libcockatrice_rng/libcockatrice/rng/rng_sfmt.cpp
index 5a6d8c862..5b38deb3f 100644
--- a/libcockatrice_rng/libcockatrice/rng/rng_sfmt.cpp
+++ b/libcockatrice_rng/libcockatrice/rng/rng_sfmt.cpp
@@ -40,8 +40,9 @@ unsigned int RNG_SFMT::rand(int min, int max)
}
// For complete fairness and equal timing, this should be a roll, but let's skip it anyway
- if (min == max)
+ if (min == max) {
return max;
+ }
// This is actually not used in Cockatrice:
// Someone wants rand() % -foo, so we should compute -rand(0, +foo)
diff --git a/libcockatrice_settings/libcockatrice/settings/servers_settings.cpp b/libcockatrice_settings/libcockatrice/settings/servers_settings.cpp
index 0140182be..d9b98e036 100644
--- a/libcockatrice_settings/libcockatrice/settings/servers_settings.cpp
+++ b/libcockatrice_settings/libcockatrice/settings/servers_settings.cpp
@@ -58,9 +58,11 @@ int ServersSettings::getPrevioushostindex(const QString &saveName) const
{
int size = getValue("totalServers", "server", "server_details").toInt();
- for (int i = 0; i <= size; ++i)
- if (saveName == getValue(QString("saveName%1").arg(i), "server", "server_details").toString())
+ for (int i = 0; i <= size; ++i) {
+ if (saveName == getValue(QString("saveName%1").arg(i), "server", "server_details").toString()) {
return i;
+ }
+ }
return -1;
}
@@ -92,8 +94,9 @@ QString ServersSettings::getPassword()
{
int index = getPrevioushostindex(getPrevioushostName());
- if (getSavePassword())
+ if (getSavePassword()) {
return getValue(QString("password%1").arg(index), "server", "server_details").toString();
+ }
return QString();
}
@@ -168,8 +171,9 @@ void ServersSettings::addNewServer(const QString &saveName,
bool savePassword,
const QString &site)
{
- if (updateExistingServer(saveName, serv, port, username, password, savePassword, site))
+ if (updateExistingServer(saveName, serv, port, username, password, savePassword, site)) {
return;
+ }
int index = getValue("totalServers", "server", "server_details").toInt() + 1;
diff --git a/libcockatrice_utility/libcockatrice/utility/color.h b/libcockatrice_utility/libcockatrice/utility/color.h
index f02df3a0e..31bcb3734 100644
--- a/libcockatrice_utility/libcockatrice/utility/color.h
+++ b/libcockatrice_utility/libcockatrice/utility/color.h
@@ -45,11 +45,13 @@ inline QColor colorHelper(const QString &name)
{"Land", QColor(110, 80, 50)},
};
- if (colorMap.contains(name))
+ if (colorMap.contains(name)) {
return colorMap[name];
+ }
- if (name.length() == 1 && colorMap.contains(name.toUpper()))
+ if (name.length() == 1 && colorMap.contains(name.toUpper())) {
return colorMap[name.toUpper()];
+ }
uint h = qHash(name);
int r = 100 + (h % 120);
diff --git a/libcockatrice_utility/libcockatrice/utility/expression.cpp b/libcockatrice_utility/libcockatrice/utility/expression.cpp
index 42073670c..718b0fe18 100644
--- a/libcockatrice_utility/libcockatrice/utility/expression.cpp
+++ b/libcockatrice_utility/libcockatrice/utility/expression.cpp
@@ -54,8 +54,9 @@ double Expression::eval(const peg::Ast &ast)
return stod(std::string(ast.token));
} else if (ast.name == "FUNCTION") {
QString name = QString::fromStdString(std::string(nodes[0]->token));
- if (!fns.contains(name))
+ if (!fns.contains(name)) {
return 0;
+ }
return fns[name](eval(*nodes[1]));
} else if (ast.name == "VARIABLE") {
return value;
diff --git a/libcockatrice_utility/libcockatrice/utility/levenshtein.cpp b/libcockatrice_utility/libcockatrice/utility/levenshtein.cpp
index cfb972f91..f39d325fb 100644
--- a/libcockatrice_utility/libcockatrice/utility/levenshtein.cpp
+++ b/libcockatrice_utility/libcockatrice/utility/levenshtein.cpp
@@ -9,10 +9,12 @@ int levenshteinDistance(const QString &s1, const QString &s2)
int len2 = s2.size();
std::vector> dp(len1 + 1, std::vector