style: Add braces to all control flow statements (#6887)

* style: Add braces to all control flow statements

  Standardize code style by adding explicit braces to all single-statement
  control flow blocks (if, else, for, while) across the entire codebase.

  Also documents the InsertBraces clang-format option (requires v15+) for
  future automated enforcement.

* InsertBraces-check-enabled
This commit is contained in:
DawnFire42 2026-05-16 13:19:53 -04:00 committed by GitHub
parent 7153f7d4c1
commit aadee34238
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
173 changed files with 2725 additions and 1461 deletions

View file

@ -26,6 +26,8 @@ PointerAlignment: Right
SortIncludes: true
IncludeBlocks: Regroup
StatementAttributeLikeMacros: [emit]
# requires clang-format 15
InsertBraces: true
# requires clang-format 16
# RemoveSemicolon: true
---

View file

@ -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 +=
"<li>" + tr("can %1 contain numeric characters").arg((rules.at(4).toInt() > 0) ? "" : tr("NOT")) + "</li>";
if (rules.at(6).size() > 0)
if (rules.at(6).size() > 0) {
out += "<li>" + tr("can contain the following punctuation: %1").arg(rules.at(6).toHtmlEscaped()) + "</li>";
}
out += "<li>" +
tr("first character can %1 be a punctuation mark").arg((rules.at(5).toInt() > 0) ? "" : tr("NOT")) +
@ -566,10 +571,11 @@ QString ConnectionController::extractInvalidUsernameMessage(QString &in)
}
}
if (rules.at(8).size() > 0)
if (rules.at(8).size() > 0) {
out += "<li>" +
tr("can not match any of the following expressions: %1").arg(rules.at(8).toHtmlEscaped()) +
"</li>";
}
}
out += "</ul>";

View file

@ -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());
};

View file

@ -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());

View file

@ -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());
}

View file

@ -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);

View file

@ -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<QColor>() == color)
if (settings.value(key).value<QColor>() == color) {
return;
}
settings.setValue(key, color);
emit colorChanged(counterId, color);

View file

@ -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;

View file

@ -88,20 +88,27 @@ static void setupParserRules()
const auto arg = std::any_cast<int>(sv[1]);
const auto op = std::any_cast<QString>(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; };
};

View file

@ -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<CardFilter::Attr>(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<CardFilter::Type>(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<CardFilter::Type>(comboCurrentIntData(typeCombo)),

View file

@ -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<FilterTreeNode *>(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<Qt::CheckState>(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;
}

View file

@ -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);
}

View file

@ -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);

View file

@ -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<GameScene *>(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);
}
}

View file

@ -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<int>(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));
}

View file

@ -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<CardItem *>(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.

View file

@ -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);

View file

@ -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<CardZone *>(colliding.at(i));
if (!cardZone)
if (!cardZone) {
cardZone = temp;
if (!zoneViewZone)
}
if (!zoneViewZone) {
zoneViewZone = qobject_cast<ZoneViewZone *>(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<TableZone *>(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<TableZone *>(cursorZone);
if (table)
if (table->getCardFromCoords(closestGridPoint))
if (table) {
if (table->getCardFromCoords(closestGridPoint)) {
newOccupied = true;
}
}
if (newOccupied != occupied) {
occupied = newOccupied;
update();

View file

@ -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<GameScene *>(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<GameScene *>(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<CardItem *>(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<CardItem *>(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<const ZoneViewZoneLogic *>(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<CardItem *>(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<TableZoneLogic *>(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)) {

View file

@ -24,17 +24,21 @@ void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos)
QList<QGraphicsItem *> colliding = scene()->items(cursorScenePos);
DeckViewCardContainer *cursorZone = 0;
for (int i = colliding.size() - 1; i >= 0; i--)
if ((cursorZone = qgraphicsitem_cast<DeckViewCardContainer *>(colliding.at(i))))
for (int i = colliding.size() - 1; i >= 0; i--) {
if ((cursorZone = qgraphicsitem_cast<DeckViewCardContainer *>(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<DeckViewScene *>(scene())->getLocked())
if (static_cast<DeckViewScene *>(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<DeckViewCard *>(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<DeckViewScene *>(scene())->getLocked())
if (static_cast<DeckViewScene *>(scene())->getLocked()) {
return;
}
if (event->button() == Qt::LeftButton) {
QList<MoveCard_ToZone> 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<QPair<int, int>> DeckViewCardContainer::getRowsAndCols() const
{
QList<QPair<int, int>> result;
QList<QString> cardTypeList = cardsByType.uniqueKeys();
for (int i = 0; i < cardTypeList.size(); ++i)
for (int i = 0; i < cardTypeList.size(); ++i) {
result.append(QPair<int, int>(1, cardsByType.count(cardTypeList[i])));
}
return result;
}
@ -262,8 +272,9 @@ QSizeF DeckViewCardContainer::calculateBoundingRect(const QList<QPair<int, int>>
// 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<QPair<int, int>>
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<QString, DeckViewCardContainer *> 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<DecklistCardNode *>(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<MoveCard_ToZone> &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<DeckViewCard *> &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<int>());
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<MoveCard_ToZone> DeckViewScene::getSideboardPlan() const
while (containerIterator.hasNext()) {
DeckViewCardContainer *cont = containerIterator.next().value();
const QList<DeckViewCard *> 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<MoveCard_ToZone> DeckViewScene::getSideboardPlan() const
m.set_target_zone(cont->getName().toStdString());
result.append(m);
}
}
}
return result;
}

View file

@ -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<MoveCard_ToZone> &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)

View file

@ -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 &current, 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));

View file

@ -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<int, Player *> 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<int, Player *> 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<int, Player *> 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();
}

View file

@ -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);
}

View file

@ -55,8 +55,9 @@ GameScene::~GameScene()
*/
void GameScene::retranslateUi()
{
for (ZoneViewWidget *view : zoneViews)
for (ZoneViewWidget *view : zoneViews) {
view->retranslateUi();
}
}
QList<CardItem *> GameScene::selectedCards() const
@ -209,10 +210,12 @@ QList<Player *> GameScene::rotatePlayers(const QList<Player *> &activePlayers, i
QList<Player *> 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<Player *> &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<qreal> GameScene::calculateMinWidthByColumn() const
QList<qreal> 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<QGraphicsItem *> &items)
{
for (QGraphicsItem *item : items)
if (auto *zone = qgraphicsitem_cast<CardZone *>(item))
for (QGraphicsItem *item : items) {
if (auto *zone = qgraphicsitem_cast<CardZone *>(item)) {
return zone;
}
}
return nullptr;
}
@ -392,14 +403,17 @@ CardItem *GameScene::findTopmostCardInZone(const QList<QGraphicsItem *> &items,
for (QGraphicsItem *item : items) {
CardItem *card = qgraphicsitem_cast<CardItem *>(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<QGraphicsSceneMouseEvent *>(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<CardItem *> 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<CardItem *>(card));
if (!animationTimer->isActive())
if (!animationTimer->isActive()) {
animationTimer->start(10, this);
}
}
void GameScene::unregisterAnimationItem(AbstractCardItem *card)
{
cardsToAnimate.remove(static_cast<CardItem *>(card));
if (cardsToAnimate.isEmpty())
if (cardsToAnimate.isEmpty()) {
animationTimer->stop();
}
}
// ---------- Rubber Band ----------

View file

@ -75,8 +75,9 @@ void GameView::resizeEvent(QResizeEvent *event)
QGraphicsView::resizeEvent(event);
GameScene *s = dynamic_cast<GameScene *>(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();

View file

@ -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<PhaseButton *>(sender());
if (button->getActive())
if (button->getActive()) {
button->triggerDoubleClickAction();
}
Command_SetActivePhase cmd;
cmd.set_phase(static_cast<google::protobuf::uint32>(buttonList.indexOf(button)));

View file

@ -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);

View file

@ -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<QAction *>(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<QAction *>(sender());
if (!action)
if (!action) {
return;
}
const int targetId = action->data().toInt();
player->getPlayerActions()->actRevealRandomHandCard(targetId);

View file

@ -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);

View file

@ -63,8 +63,9 @@ Player::~Player()
qCInfo(PlayerLog) << "Player destructor:" << getPlayerInfo()->getName();
QMapIterator<QString, CardZoneLogic *> i(zones);
while (i.hasNext())
while (i.hasNext()) {
delete i.next().value();
}
zones.clear();
delete playerMenu;

View file

@ -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());
}

View file

@ -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();

View file

@ -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<int, Player *> 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;
}

View file

@ -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)

View file

@ -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)

View file

@ -34,9 +34,11 @@ void HandZone::handleDropEvent(const QList<CardDragItem *> &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<CardItem *>(getLogic()->getCards().at(x))->scenePos().x())
for (x = 0; x < getLogic()->getCards().size(); x++) {
if (point.x() < static_cast<CardItem *>(getLogic()->getCards().at(x))->scenePos().x()) {
break;
}
}
} else {
x = calcDropIndexFromY(dropPoint.y());
}
@ -49,18 +51,20 @@ void HandZone::handleDropEvent(const QList<CardDragItem *> &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;

View file

@ -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<ZoneViewZoneLogic *>(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));
}

View file

@ -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();

View file

@ -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;
}

View file

@ -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);
}

View file

@ -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<int>(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 &params)
{
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<qreal> 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<GameScene *>(scene())->startRubberBand(event->scenePos());
event->accept();
} else
} else {
CardZone::mousePressEvent(event);
}
}
void SelectZone::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)

View file

@ -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<int, int> 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;
}

View file

@ -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;

View file

@ -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<QGraphicsView *>(current))
if (auto *view = qobject_cast<QGraphicsView *>(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<QGraphicsSceneMouseEvent *>(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<QStyleOptionTitleBar *>(option);
if (titleBar)
if (titleBar) {
titleBar->icon = QPixmap("theme:cockatrice");
}
}
/**

View file

@ -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);

View file

@ -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()) {

View file

@ -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()) {

View file

@ -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<QKeyEvent *>(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:

View file

@ -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;

View file

@ -77,8 +77,9 @@ QMap<QString, QPixmap> 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<int, QPixmap> 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<int, QPixmap> 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);

View file

@ -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<QPalette::ColorRole>(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<QPalette::ColorRole>(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)) << " : "

View file

@ -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()) {

View file

@ -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);

View file

@ -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("<tr><td>%1</td><td></td><td>%2</td></tr>").arg(keyText, card->getProperty(key).toHtmlEscaped());

View file

@ -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);

View file

@ -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);

View file

@ -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();

View file

@ -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)});
}

View file

@ -69,16 +69,18 @@ static void buildMapsByCategory(const QHash<QString, QHash<int, int>> &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<QString, QHash<int, int>> &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());
}
}
}

View file

@ -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);

View file

@ -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")) {

View file

@ -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();

View file

@ -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);

View file

@ -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()

View file

@ -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);
}

View file

@ -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());
}

View file

@ -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);

View file

@ -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;

View file

@ -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");

View file

@ -215,8 +215,9 @@ DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMap<int, QS
spectatorsSeeEverythingCheckBox->setChecked(gameInfo.spectators_omniscient());
QSet<int> 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<int, QString> 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;
}

View file

@ -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<QLineEdit *>();
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<QLineEdit *>();
if (lineEdit) {
updatedList.append(lineEdit->text());

View file

@ -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);
}
}

View file

@ -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;
}

View file

@ -87,8 +87,9 @@ DlgFilterGames::DlgFilterGames(const QMap<int, QString> &_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<int> DlgFilterGames::getGameTypeFilter() const
QMapIterator<int, QCheckBox *> i(gameTypeFilterCheckBoxes);
while (i.hasNext()) {
i.next();
if (i.value()->isChecked())
if (i.value()->isChecked()) {
result.insert(i.key());
}
}
return result;
}

View file

@ -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<QModelIndex>());
QSet<int> 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<int> 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<int> 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<int> 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();

View file

@ -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();

View file

@ -237,8 +237,9 @@ QMap<QString, int> 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<QString, QStringList> 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) {

View file

@ -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<int>(&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<int>(&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));
}

View file

@ -154,8 +154,9 @@ void DlgUpdate::finishedUpdateCheck(bool needToUpdate, bool isCompatible, Releas
"</a>)<br><br>" + 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"),

View file

@ -60,8 +60,9 @@ void DlgViewLog::actCopyToClipboard()
void DlgViewLog::loadInitialLogBuffer()
{
QList<QString> logBuffer = Logger::getInstance().getLogBuffer();
for (const QString &message : logBuffer)
for (const QString &message : logBuffer) {
appendLogEntry(message);
}
}
void DlgViewLog::appendLogEntry(const QString &message)

View file

@ -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()) {

View file

@ -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 {};
}

View file

@ -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;

View file

@ -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;
}

View file

@ -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;
}

View file

@ -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) {

View file

@ -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);

View file

@ -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 =

View file

@ -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;
}
}

View file

@ -27,20 +27,23 @@ void ReplayTimelineWidget::setTimeline(const QList<int> &_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;

View file

@ -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("<br>");
} 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,
"<font color=" + ((optionalFontColor.size() > 0) ? optionalFontColor : serverMessageColor.name()) + ">" +
QDateTime::currentDateTime().toString("[hh:mm:ss] ") + html + "</font>";
if (optionalIsBold)
if (optionalIsBold) {
htmlText = "<b>" + htmlText + "</b>";
}
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);
}

View file

@ -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 &current)
{
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"));

View file

@ -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
}

View file

@ -63,14 +63,18 @@ GamesModel::GamesModel(const QMap<int, QString> &_rooms, const QMap<int, GameTyp
QVariant GamesModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
if (!index.isValid()) {
return QVariant();
if (role == Qt::UserRole)
}
if (role == Qt::UserRole) {
return index.row();
if (role != Qt::DisplayRole && role != SORT_ROLE && role != Qt::DecorationRole && role != Qt::TextAlignmentRole)
}
if (role != Qt::DisplayRole && role != SORT_ROLE && role != Qt::DecorationRole && role != Qt::TextAlignmentRole) {
return QVariant();
if ((index.row() >= 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<GamesModel *>(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<GamesModel *>(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<int> 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<int>(game.max_players()) < filters.maxPlayersFilterMin)
if (static_cast<int>(game.max_players()) < filters.maxPlayersFilterMin) {
return false;
if (static_cast<int>(game.max_players()) > filters.maxPlayersFilterMax)
}
if (static_cast<int>(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;
}

View file

@ -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);
}

View file

@ -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<DirectoryNode *>(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<DirectoryNode *>(at(i));
if (node) {
FileNode *result = node->getNodeById(id);
if (result)
if (result) {
return result;
}
} else {
FileNode *file = dynamic_cast<FileNode *>(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<DirectoryNode *>(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<Node *>(index.internalPointer());
FileNode *file = dynamic_cast<FileNode *>(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<DirectoryNode *>(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<Node *>(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);
}
}
}

View file

@ -75,8 +75,9 @@ public:
template <typename T> [[nodiscard]] T getNode(const QModelIndex &index) const
{
if (!index.isValid())
if (!index.isValid()) {
return dynamic_cast<T>(root);
}
return dynamic_cast<T>(static_cast<Node *>(index.internalPointer()));
}

View file

@ -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<MatchNode *>(static_cast<Node *>(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<ReplayNode *>(static_cast<Node *>(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<MatchNode *>(static_cast<Node *>(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<MatchNode *>(static_cast<Node *>(ind.internalPointer()));
if (matchNode)
if (matchNode) {
return QModelIndex();
else {
} else {
auto *replayNode = dynamic_cast<ReplayNode *>(static_cast<Node *>(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<ReplayNode *>(static_cast<Node *>(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<MatchNode *>(static_cast<Node *>(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<MatchNode *>(static_cast<Node *>(index.internalPointer()));
if (!node) {
auto *_node = dynamic_cast<ReplayNode *>(static_cast<Node *>(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();

View file

@ -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<QWidget *>(parent()), tr("Ban History"),
tr("User has never been banned."));
}
} else
} else {
QMessageBox::critical(static_cast<QWidget *>(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<QWidget *>(parent()), tr("Warning History"),
tr("User has never been warned."));
}
} else
} else {
QMessageBox::critical(static_cast<QWidget *>(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<WarningDialog *>(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());

Some files were not shown because too many files have changed in this diff Show more