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 SortIncludes: true
IncludeBlocks: Regroup IncludeBlocks: Regroup
StatementAttributeLikeMacros: [emit] StatementAttributeLikeMacros: [emit]
# requires clang-format 15
InsertBraces: true
# requires clang-format 16 # requires clang-format 16
# RemoveSemicolon: true # RemoveSemicolon: true
--- ---

View file

@ -140,13 +140,15 @@ void ConnectionController::onConnectionClosedEvent(const Event_ConnectionClosed
} }
case Event_ConnectionClosed::BANNED: { case Event_ConnectionClosed::BANNED: {
reasonStr = tr("Banned by moderator"); reasonStr = tr("Banned by moderator");
if (event.has_end_time()) if (event.has_end_time()) {
reasonStr.append( reasonStr.append(
"\n" + tr("Expected end time: %1").arg(QDateTime::fromSecsSinceEpoch(event.end_time()).toString())); "\n" + tr("Expected end time: %1").arg(QDateTime::fromSecsSinceEpoch(event.end_time()).toString()));
else } else {
reasonStr.append("\n" + tr("This ban lasts indefinitely.")); 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())); reasonStr.append("\n\n" + QString::fromStdString(event.reason_str()));
}
break; break;
} }
case Event_ConnectionClosed::SERVER_SHUTDOWN: { case Event_ConnectionClosed::SERVER_SHUTDOWN: {
@ -240,8 +242,9 @@ void ConnectionController::onLoginError(int r,
QString bannedStr = QString bannedStr =
endTime ? tr("You are banned until %1.").arg(QDateTime::fromSecsSinceEpoch(endTime).toString()) endTime ? tr("You are banned until %1.").arg(QDateTime::fromSecsSinceEpoch(endTime).toString())
: tr("You are banned indefinitely."); : tr("You are banned indefinitely.");
if (!reasonStr.isEmpty()) if (!reasonStr.isEmpty()) {
bannedStr.append("\n\n" + reasonStr); bannedStr.append("\n\n" + reasonStr);
}
QMessageBox::critical(dialogParent, tr("Error"), bannedStr); QMessageBox::critical(dialogParent, tr("Error"), bannedStr);
break; break;
} }
@ -354,8 +357,9 @@ void ConnectionController::onRegisterError(int r, QString reasonStr, quint32 end
QString bannedStr = QString bannedStr =
endTime ? tr("You are banned until %1.").arg(QDateTime::fromSecsSinceEpoch(endTime).toString()) endTime ? tr("You are banned until %1.").arg(QDateTime::fromSecsSinceEpoch(endTime).toString())
: tr("You are banned indefinitely."); : tr("You are banned indefinitely.");
if (!reasonStr.isEmpty()) if (!reasonStr.isEmpty()) {
bannedStr.append("\n\n" + reasonStr); bannedStr.append("\n\n" + reasonStr);
}
QMessageBox::critical(dialogParent, tr("Error"), bannedStr); QMessageBox::critical(dialogParent, tr("Error"), bannedStr);
break; break;
} }
@ -545,8 +549,9 @@ QString ConnectionController::extractInvalidUsernameMessage(QString &in)
out += out +=
"<li>" + tr("can %1 contain numeric characters").arg((rules.at(4).toInt() > 0) ? "" : tr("NOT")) + "</li>"; "<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("can contain the following punctuation: %1").arg(rules.at(6).toHtmlEscaped()) + "</li>";
}
out += "<li>" + out += "<li>" +
tr("first character can %1 be a punctuation mark").arg((rules.at(5).toInt() > 0) ? "" : tr("NOT")) + 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>" + out += "<li>" +
tr("can not match any of the following expressions: %1").arg(rules.at(8).toHtmlEscaped()) + tr("can not match any of the following expressions: %1").arg(rules.at(8).toHtmlEscaped()) +
"</li>"; "</li>";
}
} }
out += "</ul>"; 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) { auto copyMainOrSide = [this, &mainboard, &sideboard](const auto node, const auto card) {
CardInfoPtr dbCard = cardDatabase.query()->getCardInfo(card->getName()); CardInfoPtr dbCard = cardDatabase.query()->getCardInfo(card->getName());
if (!dbCard || dbCard->getIsToken()) if (!dbCard || dbCard->getIsToken()) {
return; return;
}
DecklistCardNode *addedCard; DecklistCardNode *addedCard;
if (node->getName() == DECK_ZONE_SIDE) if (node->getName() == DECK_ZONE_SIDE) {
addedCard = sideboard.addCard(card->getName(), node->getName(), -1); addedCard = sideboard.addCard(card->getName(), node->getName(), -1);
else } else {
addedCard = mainboard.addCard(card->getName(), node->getName(), -1); addedCard = mainboard.addCard(card->getName(), node->getName(), -1);
}
addedCard->setNumber(card->getNumber()); addedCard->setNumber(card->getNumber());
}; };

View file

@ -129,8 +129,9 @@ void StableReleaseChannel::releaseListFinished()
return; return;
} }
if (!lastRelease) if (!lastRelease) {
lastRelease = new Release; lastRelease = new Release;
}
lastRelease->setName(resultMap["name"].toString()); lastRelease->setName(resultMap["name"].toString());
lastRelease->setDescriptionUrl(resultMap["html_url"].toString()); lastRelease->setDescriptionUrl(resultMap["html_url"].toString());
@ -246,8 +247,9 @@ void BetaReleaseChannel::releaseListFinished()
return; return;
} }
if (lastRelease == nullptr) if (lastRelease == nullptr) {
lastRelease = new Release; lastRelease = new Release;
}
lastRelease->setCommitHash(resultMap["target_commitish"].toString()); lastRelease->setCommitHash(resultMap["target_commitish"].toString());
lastRelease->setPublishDate(resultMap["published_at"].toDate()); lastRelease->setPublishDate(resultMap["published_at"].toDate());

View file

@ -10,8 +10,9 @@ UpdateDownloader::UpdateDownloader(QObject *parent) : QObject(parent), response(
void UpdateDownloader::beginDownload(QUrl downloadUrl) void UpdateDownloader::beginDownload(QUrl downloadUrl)
{ {
// Save the original URL because we need it for the filename // Save the original URL because we need it for the filename
if (originalUrl.isEmpty()) if (originalUrl.isEmpty()) {
originalUrl = downloadUrl; originalUrl = downloadUrl;
}
response = netMan->get(QNetworkRequest(downloadUrl)); response = netMan->get(QNetworkRequest(downloadUrl));
connect(response, &QNetworkReply::finished, this, &UpdateDownloader::fileFinished); connect(response, &QNetworkReply::finished, this, &UpdateDownloader::fileFinished);
@ -21,8 +22,9 @@ void UpdateDownloader::beginDownload(QUrl downloadUrl)
void UpdateDownloader::downloadError(QNetworkReply::NetworkError) void UpdateDownloader::downloadError(QNetworkReply::NetworkError)
{ {
if (response == nullptr) if (response == nullptr) {
return; return;
}
emit error(response->errorString().toUtf8()); emit error(response->errorString().toUtf8());
} }

View file

@ -24,10 +24,11 @@ SettingsCache &SettingsCache::instance()
QString SettingsCache::getDataPath() QString SettingsCache::getDataPath()
{ {
if (isPortableBuild) if (isPortableBuild) {
return qApp->applicationDirPath() + "/data"; return qApp->applicationDirPath() + "/data";
else } else {
return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation); return QStandardPaths::writableLocation(QStandardPaths::AppLocalDataLocation);
}
} }
QString SettingsCache::getSettingsPath() QString SettingsCache::getSettingsPath()
@ -37,10 +38,11 @@ QString SettingsCache::getSettingsPath()
QString SettingsCache::getCachePath() const QString SettingsCache::getCachePath() const
{ {
if (isPortableBuild) if (isPortableBuild) {
return qApp->applicationDirPath() + "/cache"; return qApp->applicationDirPath() + "/cache";
else } else {
return QStandardPaths::writableLocation(QStandardPaths::CacheLocation); return QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
}
} }
QString SettingsCache::getNetworkCachePath() const QString SettingsCache::getNetworkCachePath() const
@ -50,14 +52,17 @@ QString SettingsCache::getNetworkCachePath() const
void SettingsCache::translateLegacySettings() void SettingsCache::translateLegacySettings()
{ {
if (isPortableBuild) if (isPortableBuild) {
return; return;
}
// Layouts // Layouts
QFile layoutFile(getSettingsPath() + "layouts/deckLayout.ini"); QFile layoutFile(getSettingsPath() + "layouts/deckLayout.ini");
if (layoutFile.exists()) if (layoutFile.exists()) {
if (layoutFile.copy(getSettingsPath() + "layouts.ini")) if (layoutFile.copy(getSettingsPath() + "layouts.ini")) {
layoutFile.remove(); layoutFile.remove();
}
}
QStringList usedKeys; QStringList usedKeys;
QSettings legacySetting; QSettings legacySetting;
@ -116,10 +121,11 @@ void SettingsCache::translateLegacySettings()
gameFilters().setHideIgnoredUserGames(legacySetting.value("hide_ignored_user_games").toBool()); gameFilters().setHideIgnoredUserGames(legacySetting.value("hide_ignored_user_games").toBool());
gameFilters().setMinPlayers(legacySetting.value("min_players").toInt()); 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()); 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 gameFilters().setMaxPlayers(99); // This prevents a bug where no games will show if max was not set before
}
QStringList allFilters = legacySetting.allKeys(); QStringList allFilters = legacySetting.allKeys();
for (int i = 0; i < allFilters.size(); ++i) { for (int i = 0; i < allFilters.size(); ++i) {
@ -135,8 +141,9 @@ void SettingsCache::translateLegacySettings()
QStringList allLegacyKeys = legacySetting.allKeys(); QStringList allLegacyKeys = legacySetting.allKeys();
for (int i = 0; i < allLegacyKeys.size(); ++i) { for (int i = 0; i < allLegacyKeys.size(); ++i) {
if (usedKeys.contains(allLegacyKeys.at(i))) if (usedKeys.contains(allLegacyKeys.at(i))) {
continue; continue;
}
settings->setValue(allLegacyKeys.at(i), legacySetting.value(allLegacyKeys.at(i))); 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, // if the config settings is empty or refers to a not-existing folder,
// ensure that the defaut path exists and return it // ensure that the defaut path exists and return it
if (tmp.isEmpty() || !QDir(tmp).exists()) { if (tmp.isEmpty() || !QDir(tmp).exists()) {
if (!QDir().mkpath(defaultPath)) if (!QDir().mkpath(defaultPath)) {
qCInfo(SettingsCacheLog) << "[SettingsCache] Could not create folder:" << defaultPath; qCInfo(SettingsCacheLog) << "[SettingsCache] Could not create folder:" << defaultPath;
}
tmp = defaultPath; tmp = defaultPath;
} }
return tmp; return tmp;
@ -159,8 +167,9 @@ QString SettingsCache::getSafeConfigFilePath(QString configEntry, QString defaul
QString tmp = settings->value(configEntry).toString(); QString tmp = settings->value(configEntry).toString();
// if the config settings is empty or refers to a not-existing file, // if the config settings is empty or refers to a not-existing file,
// return the default Path // return the default Path
if (!QFile::exists(tmp) || tmp.isEmpty()) if (!QFile::exists(tmp) || tmp.isEmpty()) {
tmp = std::move(defaultPath); tmp = std::move(defaultPath);
}
return tmp; return tmp;
} }
@ -168,8 +177,9 @@ SettingsCache::SettingsCache()
{ {
// first, figure out if we are running in portable mode // first, figure out if we are running in portable mode
isPortableBuild = QFile::exists(qApp->applicationDirPath() + "/portable.dat"); isPortableBuild = QFile::exists(qApp->applicationDirPath() + "/portable.dat");
if (isPortableBuild) if (isPortableBuild) {
qCInfo(SettingsCacheLog) << "Portable mode enabled"; qCInfo(SettingsCacheLog) << "Portable mode enabled";
}
// define a dummy context that will be used where needed // define a dummy context that will be used where needed
QString dummy = QT_TRANSLATE_NOOP("i18n", "English"); QString dummy = QT_TRANSLATE_NOOP("i18n", "English");
@ -189,8 +199,9 @@ SettingsCache::SettingsCache()
cardCounterSettings = new CardCounterSettings(settingsPath, this); cardCounterSettings = new CardCounterSettings(settingsPath, this);
if (!QFile(settingsPath + "global.ini").exists()) if (!QFile(settingsPath + "global.ini").exists()) {
translateLegacySettings(); translateLegacySettings();
}
// updates - don't reorder them or their index in the settings won't match // 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. // 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/pixmapCacheSize", pixmapCacheSize);
settings->setValue("personal/picturedownloadhq", false); settings->setValue("personal/picturedownloadhq", false);
settings->setValue("revert/pixmapCacheSize", true); settings->setValue("revert/pixmapCacheSize", true);
} else } else {
pixmapCacheSize = settings->value("personal/pixmapCacheSize", PIXMAPCACHE_SIZE_DEFAULT).toInt(); pixmapCacheSize = settings->value("personal/pixmapCacheSize", PIXMAPCACHE_SIZE_DEFAULT).toInt();
}
// sanity check // sanity check
if (pixmapCacheSize < PIXMAPCACHE_SIZE_MIN || pixmapCacheSize > PIXMAPCACHE_SIZE_MAX) if (pixmapCacheSize < PIXMAPCACHE_SIZE_MIN || pixmapCacheSize > PIXMAPCACHE_SIZE_MAX) {
pixmapCacheSize = PIXMAPCACHE_SIZE_DEFAULT; pixmapCacheSize = PIXMAPCACHE_SIZE_DEFAULT;
}
networkCacheSize = settings->value("personal/networkCacheSize", NETWORK_CACHE_SIZE_DEFAULT).toInt(); networkCacheSize = settings->value("personal/networkCacheSize", NETWORK_CACHE_SIZE_DEFAULT).toInt();
redirectCacheTtl = settings->value("personal/redirectCacheTtl", NETWORK_REDIRECT_CACHE_TTL_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) void SettingsCache::setIncludeRebalancedCards(bool _includeRebalancedCards)
{ {
if (includeRebalancedCards == _includeRebalancedCards) if (includeRebalancedCards == _includeRebalancedCards) {
return; return;
}
includeRebalancedCards = _includeRebalancedCards; includeRebalancedCards = _includeRebalancedCards;
settings->setValue("cards/includerebalancedcards", includeRebalancedCards); settings->setValue("cards/includerebalancedcards", includeRebalancedCards);
@ -1310,8 +1324,9 @@ void SettingsCache::setMaxFontSize(int _max)
void SettingsCache::setRoundCardCorners(bool _roundCardCorners) void SettingsCache::setRoundCardCorners(bool _roundCardCorners)
{ {
if (_roundCardCorners == roundCardCorners) if (_roundCardCorners == roundCardCorners) {
return; return;
}
roundCardCorners = _roundCardCorners; roundCardCorners = _roundCardCorners;
settings->setValue("cards/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); QString key = QString("cards/counters/%1/color").arg(counterId);
if (settings.value(key).value<QColor>() == color) if (settings.value(key).value<QColor>() == color) {
return; return;
}
settings.setValue(key, color); settings.setValue(key, color);
emit colorChanged(counterId, color); emit colorChanged(counterId, color);

View file

@ -105,8 +105,9 @@ QStringMap &SoundEngine::getAvailableThemes()
dir.setPath(SettingsCache::instance().getDataPath() + "/sounds"); dir.setPath(SettingsCache::instance().getDataPath() + "/sounds");
for (const QString &themeName : dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) { 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)); availableThemes.insert(themeName, dir.absoluteFilePath(themeName));
}
} }
// load themes from cockatrice system dir // 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)) { 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)); availableThemes.insert(themeName, dir.absoluteFilePath(themeName));
}
} }
return availableThemes; return availableThemes;

View file

@ -88,20 +88,27 @@ static void setupParserRules()
const auto arg = std::any_cast<int>(sv[1]); const auto arg = std::any_cast<int>(sv[1]);
const auto op = std::any_cast<QString>(sv[0]); const auto op = std::any_cast<QString>(sv[0]);
if (op == ">") if (op == ">") {
return [=](const int s) { return s > arg; }; return [=](const int s) { return s > arg; };
if (op == ">=") }
if (op == ">=") {
return [=](const int s) { return s >= arg; }; return [=](const int s) { return s >= arg; };
if (op == "<") }
if (op == "<") {
return [=](const int s) { return s < arg; }; return [=](const int s) { return s < arg; };
if (op == "<=") }
if (op == "<=") {
return [=](const int s) { return s <= arg; }; return [=](const int s) { return s <= arg; };
if (op == "=") }
if (op == "=") {
return [=](const int s) { return s == arg; }; return [=](const int s) { return s == arg; };
if (op == ":") }
if (op == ":") {
return [=](const int s) { return s == arg; }; return [=](const int s) { return s == arg; };
if (op == "!=") }
if (op == "!=") {
return [=](const int s) { return s != arg; }; return [=](const int s) { return s != arg; };
}
return [](int) { return false; }; return [](int) { return false; };
}; };

View file

@ -11,13 +11,15 @@ FilterBuilder::FilterBuilder(QWidget *parent) : QWidget(parent)
{ {
filterCombo = new QComboBox; filterCombo = new QComboBox;
filterCombo->setObjectName("filterCombo"); 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)); filterCombo->addItem(CardFilter::attrName(static_cast<CardFilter::Attr>(i)), QVariant(i));
}
typeCombo = new QComboBox; typeCombo = new QComboBox;
typeCombo->setObjectName("typeCombo"); 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)); typeCombo->addItem(CardFilter::typeName(static_cast<CardFilter::Type>(i)), QVariant(i));
}
QPushButton *ok = new QPushButton(QPixmap("theme:icons/increment"), QString()); QPushButton *ok = new QPushButton(QPixmap("theme:icons/increment"), QString());
ok->setObjectName("ok"); ok->setObjectName("ok");
@ -53,8 +55,9 @@ FilterBuilder::~FilterBuilder()
void FilterBuilder::destroyFilter() void FilterBuilder::destroyFilter()
{ {
if (fltr) if (fltr) {
delete fltr; delete fltr;
}
} }
static int comboCurrentIntData(const QComboBox *combo) static int comboCurrentIntData(const QComboBox *combo)
@ -67,8 +70,9 @@ void FilterBuilder::emit_add()
QString txt; QString txt;
txt = edit->text(); txt = edit->text();
if (txt.length() < 1) if (txt.length() < 1) {
return; return;
}
destroyFilter(); destroyFilter();
fltr = new CardFilter(txt, static_cast<CardFilter::Type>(comboCurrentIntData(typeCombo)), 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; int idx;
idx = node->index(); idx = node->index();
if (idx >= 0) if (idx >= 0) {
beginInsertRows(createIndex(idx, 0, (void *)node), i, i); beginInsertRows(createIndex(idx, 0, (void *)node), i, i);
}
} }
void FilterTreeModel::proxyEndInsertRow(const FilterTreeNode *node, int) void FilterTreeModel::proxyEndInsertRow(const FilterTreeNode *node, int)
@ -32,8 +33,9 @@ void FilterTreeModel::proxyEndInsertRow(const FilterTreeNode *node, int)
int idx; int idx;
idx = node->index(); idx = node->index();
if (idx >= 0) if (idx >= 0) {
endInsertRows(); endInsertRows();
}
} }
void FilterTreeModel::proxyBeginRemoveRow(const FilterTreeNode *node, int i) void FilterTreeModel::proxyBeginRemoveRow(const FilterTreeNode *node, int i)
@ -41,8 +43,9 @@ void FilterTreeModel::proxyBeginRemoveRow(const FilterTreeNode *node, int i)
int idx; int idx;
idx = node->index(); idx = node->index();
if (idx >= 0) if (idx >= 0) {
beginRemoveRows(createIndex(idx, 0, (void *)node), i, i); beginRemoveRows(createIndex(idx, 0, (void *)node), i, i);
}
} }
void FilterTreeModel::proxyEndRemoveRow(const FilterTreeNode *node, int) void FilterTreeModel::proxyEndRemoveRow(const FilterTreeNode *node, int)
@ -50,8 +53,9 @@ void FilterTreeModel::proxyEndRemoveRow(const FilterTreeNode *node, int)
int idx; int idx;
idx = node->index(); idx = node->index();
if (idx >= 0) if (idx >= 0) {
endRemoveRows(); endRemoveRows();
}
} }
FilterTreeNode *FilterTreeModel::indexToNode(const QModelIndex &idx) const FilterTreeNode *FilterTreeModel::indexToNode(const QModelIndex &idx) const
@ -59,12 +63,14 @@ FilterTreeNode *FilterTreeModel::indexToNode(const QModelIndex &idx) const
void *ip; void *ip;
FilterTreeNode *node; FilterTreeNode *node;
if (!idx.isValid()) if (!idx.isValid()) {
return fTree; return fTree;
}
ip = idx.internalPointer(); ip = idx.internalPointer();
if (ip == NULL) if (ip == NULL) {
return fTree; return fTree;
}
node = static_cast<FilterTreeNode *>(ip); node = static_cast<FilterTreeNode *>(ip);
return node; return node;
@ -145,14 +151,16 @@ int FilterTreeModel::rowCount(const QModelIndex &parent) const
const FilterTreeNode *node; const FilterTreeNode *node;
int result; int result;
if (parent.column() > 0) if (parent.column() > 0) {
return 0; return 0;
}
node = indexToNode(parent); node = indexToNode(parent);
if (node) if (node) {
result = node->childCount(); result = node->childCount();
else } else {
result = 0; result = 0;
}
return result; return result;
} }
@ -166,14 +174,17 @@ QVariant FilterTreeModel::data(const QModelIndex &index, int role) const
{ {
const FilterTreeNode *node; const FilterTreeNode *node;
if (!index.isValid()) if (!index.isValid()) {
return QVariant(); return QVariant();
if (index.column() >= columnCount()) }
if (index.column() >= columnCount()) {
return QVariant(); return QVariant();
}
node = indexToNode(index); node = indexToNode(index);
if (node == NULL) if (node == NULL) {
return QVariant(); return QVariant();
}
switch (role) { switch (role) {
case Qt::FontRole: case Qt::FontRole:
@ -190,10 +201,11 @@ QVariant FilterTreeModel::data(const QModelIndex &index, int role) const
case Qt::WhatsThisRole: case Qt::WhatsThisRole:
return node->text(); return node->text();
case Qt::CheckStateRole: case Qt::CheckStateRole:
if (node->isEnabled()) if (node->isEnabled()) {
return Qt::Checked; return Qt::Checked;
else } else {
return Qt::Unchecked; return Qt::Unchecked;
}
default: default:
return QVariant(); return QVariant();
} }
@ -205,22 +217,27 @@ bool FilterTreeModel::setData(const QModelIndex &index, const QVariant &value, i
{ {
FilterTreeNode *node; FilterTreeNode *node;
if (!index.isValid()) if (!index.isValid()) {
return false; return false;
if (index.column() >= columnCount()) }
if (index.column() >= columnCount()) {
return false; return false;
if (role != Qt::CheckStateRole) }
if (role != Qt::CheckStateRole) {
return false; return false;
}
node = indexToNode(index); node = indexToNode(index);
if (node == NULL || node == fTree) if (node == NULL || node == fTree) {
return false; return false;
}
Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt()); Qt::CheckState state = static_cast<Qt::CheckState>(value.toInt());
if (state == Qt::Checked) if (state == Qt::Checked) {
node->enable(); node->enable();
else } else {
node->disable(); node->disable();
}
emit dataChanged(index, index); emit dataChanged(index, index);
return true; return true;
@ -231,16 +248,19 @@ Qt::ItemFlags FilterTreeModel::flags(const QModelIndex &index) const
const FilterTreeNode *node; const FilterTreeNode *node;
Qt::ItemFlags result; Qt::ItemFlags result;
if (!index.isValid()) if (!index.isValid()) {
return Qt::NoItemFlags; return Qt::NoItemFlags;
}
node = indexToNode(index); node = indexToNode(index);
if (node == NULL) if (node == NULL) {
return Qt::NoItemFlags; return Qt::NoItemFlags;
}
result = Qt::ItemIsEnabled; result = Qt::ItemIsEnabled;
if (node == fTree) if (node == fTree) {
return result; return result;
}
result |= Qt::ItemIsSelectable; result |= Qt::ItemIsSelectable;
result |= Qt::ItemIsUserCheckable; result |= Qt::ItemIsUserCheckable;
@ -252,8 +272,9 @@ QModelIndex FilterTreeModel::nodeIndex(const FilterTreeNode *node, int row, int
{ {
FilterTreeNode *child; FilterTreeNode *child;
if (column > 0 || row >= node->childCount()) if (column > 0 || row >= node->childCount()) {
return QModelIndex(); return QModelIndex();
}
child = node->nodeAt(row); child = node->nodeAt(row);
return createIndex(row, column, child); return createIndex(row, column, child);
@ -263,12 +284,14 @@ QModelIndex FilterTreeModel::index(int row, int column, const QModelIndex &paren
{ {
const FilterTreeNode *node; const FilterTreeNode *node;
if (!hasIndex(row, column, parent)) if (!hasIndex(row, column, parent)) {
return QModelIndex(); return QModelIndex();
}
node = indexToNode(parent); node = indexToNode(parent);
if (node == NULL) if (node == NULL) {
return QModelIndex(); return QModelIndex();
}
return nodeIndex(node, row, column); return nodeIndex(node, row, column);
} }
@ -279,18 +302,21 @@ QModelIndex FilterTreeModel::parent(const QModelIndex &ind) const
FilterTreeNode *parent; FilterTreeNode *parent;
QModelIndex idx; QModelIndex idx;
if (!ind.isValid()) if (!ind.isValid()) {
return QModelIndex(); return QModelIndex();
}
node = indexToNode(ind); node = indexToNode(ind);
if (node == NULL || node == fTree) if (node == NULL || node == fTree) {
return QModelIndex(); return QModelIndex();
}
parent = node->parent(); parent = node->parent();
if (parent) { if (parent) {
int row = parent->index(); int row = parent->index();
if (row < 0) if (row < 0) {
return QModelIndex(); return QModelIndex();
}
idx = createIndex(row, 0, parent); idx = createIndex(row, 0, parent);
return idx; return idx;
} }
@ -304,18 +330,22 @@ bool FilterTreeModel::removeRows(int row, int count, const QModelIndex &parent)
int i, last; int i, last;
last = row + count - 1; last = row + count - 1;
if (!parent.isValid() || count < 1 || row < 0) if (!parent.isValid() || count < 1 || row < 0) {
return false; return false;
}
node = indexToNode(parent); node = indexToNode(parent);
if (node == NULL || last >= node->childCount()) if (node == NULL || last >= node->childCount()) {
return false; return false;
}
for (i = 0; i < count; i++) for (i = 0; i < count; i++) {
node->deleteAt(row); node->deleteAt(row);
}
if (node != fTree && node->childCount() < 1) if (node != fTree && node->childCount() < 1) {
return removeRow(parent.row(), parent.parent()); return removeRow(parent.row(), parent.parent());
}
return true; return true;
} }

View file

@ -24,10 +24,11 @@ AbstractClient *AbstractGame::getClientForPlayer(int playerId) const
} }
return gameState->getClients().at(playerId); return gameState->getClients().at(playerId);
} else if (gameState->getClients().isEmpty()) } else if (gameState->getClients().isEmpty()) {
return nullptr; return nullptr;
else } else {
return gameState->getClients().first(); return gameState->getClients().first();
}
} }
void AbstractGame::loadReplay(GameReplay *replay) 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 CardItem *AbstractGame::getCard(int playerId, const QString &zoneName, int cardId) const
{ {
Player *player = playerManager->getPlayer(playerId); Player *player = playerManager->getPlayer(playerId);
if (!player) if (!player) {
return nullptr; return nullptr;
}
CardZoneLogic *zone = player->getZones().value(zoneName, 0); CardZoneLogic *zone = player->getZones().value(zoneName, 0);
if (!zone) if (!zone) {
return nullptr; return nullptr;
}
return zone->getCard(cardId); return zone->getCard(cardId);
} }

View file

@ -25,11 +25,12 @@ AbstractCardDragItem::AbstractCardDragItem(AbstractCardItem *_item,
setCursor(Qt::ClosedHandCursor); setCursor(Qt::ClosedHandCursor);
setZValue(ZValues::DRAG_ITEM); setZValue(ZValues::DRAG_ITEM);
} }
if (item->getTapped()) if (item->getTapped()) {
setTransform(QTransform() setTransform(QTransform()
.translate(CardDimensions::WIDTH_HALF_F, CardDimensions::HEIGHT_HALF_F) .translate(CardDimensions::WIDTH_HALF_F, CardDimensions::HEIGHT_HALF_F)
.rotate(90) .rotate(90)
.translate(-CardDimensions::WIDTH_HALF_F, -CardDimensions::HEIGHT_HALF_F)); .translate(-CardDimensions::WIDTH_HALF_F, -CardDimensions::HEIGHT_HALF_F));
}
setCacheMode(DeviceCoordinateCache); setCacheMode(DeviceCoordinateCache);

View file

@ -88,8 +88,9 @@ void AbstractCardItem::setRealZValue(qreal _zValue)
// During hover, zValue is overridden to HOVERED_CARD. Layout operations // During hover, zValue is overridden to HOVERED_CARD. Layout operations
// like reorganizeCards() call setRealZValue() on all cards including the // like reorganizeCards() call setRealZValue() on all cards including the
// hovered one — skip setZValue() here to avoid clobbering the override. // hovered one — skip setZValue() here to avoid clobbering the override.
if (!isHovered) if (!isHovered) {
setZValue(_zValue); setZValue(_zValue);
}
} }
QSizeF AbstractCardItem::getTranslatedSize(QPainter *painter) const 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 // don't even spend time trying to load the picture if our size is too small
if (translatedSize.width() > 10) { if (translatedSize.width() > 10) {
CardPictureLoader::getPixmap(translatedPixmap, exactCard, translatedSize.toSize()); CardPictureLoader::getPixmap(translatedPixmap, exactCard, translatedSize.toSize());
if (translatedPixmap.isNull()) if (translatedPixmap.isNull()) {
paintImage = false; paintImage = false;
}
} else { } else {
paintImage = false; paintImage = false;
} }
@ -156,9 +158,9 @@ void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedS
painter->setBackground(Qt::black); painter->setBackground(Qt::black);
painter->setBackgroundMode(Qt::OpaqueMode); painter->setBackgroundMode(Qt::OpaqueMode);
QString nameStr; QString nameStr;
if (facedown) if (facedown) {
nameStr = "# " + QString::number(id); nameStr = "# " + QString::number(id);
else { } else {
QString prefix = ""; QString prefix = "";
if (SettingsCache::instance().debug().getShowCardId()) { if (SettingsCache::instance().debug().getShowCardId()) {
prefix = "#" + QString::number(id) + " "; prefix = "#" + QString::number(id) + " ";
@ -185,10 +187,12 @@ void AbstractCardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *
if (isSelected() || isHovered) { if (isSelected() || isHovered) {
QPen pen; QPen pen;
if (isHovered) if (isHovered) {
pen.setColor(Qt::yellow); pen.setColor(Qt::yellow);
if (isSelected()) }
if (isSelected()) {
pen.setColor(Qt::red); pen.setColor(Qt::red);
}
pen.setWidth(0); // Cosmetic pen pen.setWidth(0); // Cosmetic pen
painter->setPen(pen); painter->setPen(pen);
painter->drawPath(shape()); painter->drawPath(shape());
@ -214,8 +218,9 @@ void AbstractCardItem::setCardRef(const CardRef &_cardRef)
void AbstractCardItem::setHovered(bool _hovered) void AbstractCardItem::setHovered(bool _hovered)
{ {
if (isHovered == _hovered) if (isHovered == _hovered) {
return; return;
}
if (_hovered) { if (_hovered) {
processHoverEvent(); processHoverEvent();
@ -277,13 +282,14 @@ void AbstractCardItem::cacheBgColor()
void AbstractCardItem::setTapped(bool _tapped, bool canAnimate) void AbstractCardItem::setTapped(bool _tapped, bool canAnimate)
{ {
if (tapped == _tapped) if (tapped == _tapped) {
return; return;
}
tapped = _tapped; tapped = _tapped;
if (SettingsCache::instance().getTapAnimation() && canAnimate) if (SettingsCache::instance().getTapAnimation() && canAnimate) {
static_cast<GameScene *>(scene())->registerAnimationItem(this); static_cast<GameScene *>(scene())->registerAnimationItem(this);
else { } else {
tapAngle = tapped ? 90 : 0; tapAngle = tapped ? 90 : 0;
setTransform(QTransform() setTransform(QTransform()
.translate(CardDimensions::WIDTH_HALF_F, CardDimensions::HEIGHT_HALF_F) .translate(CardDimensions::WIDTH_HALF_F, CardDimensions::HEIGHT_HALF_F)
@ -309,17 +315,19 @@ void AbstractCardItem::mousePressEvent(QGraphicsSceneMouseEvent *event)
scene()->clearSelection(); scene()->clearSelection();
setSelected(true); setSelected(true);
} }
if (event->button() == Qt::LeftButton) if (event->button() == Qt::LeftButton) {
setCursor(Qt::ClosedHandCursor); setCursor(Qt::ClosedHandCursor);
else if (event->button() == Qt::MiddleButton) } else if (event->button() == Qt::MiddleButton) {
emit showCardInfoPopup(event->screenPos(), cardRef); emit showCardInfoPopup(event->screenPos(), cardRef);
}
event->accept(); event->accept();
} }
void AbstractCardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) void AbstractCardItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ {
if (event->button() == Qt::MiddleButton) if (event->button() == Qt::MiddleButton) {
emit deleteCardInfoPopup(cardRef.name); emit deleteCardInfoPopup(cardRef.name);
}
// This function ensures the parent function doesn't mess around with our selection. // This function ensures the parent function doesn't mess around with our selection.
event->accept(); event->accept();
@ -335,6 +343,7 @@ QVariant AbstractCardItem::itemChange(QGraphicsItem::GraphicsItemChange change,
if (change == ItemSelectedHasChanged) { if (change == ItemSelectedHasChanged) {
update(); update();
return value; return value;
} else } else {
return ArrowTarget::itemChange(change, value); return ArrowTarget::itemChange(change, value);
}
} }

View file

@ -43,10 +43,11 @@ AbstractCounter::AbstractCounter(Player *_player,
menu->addSeparator(); menu->addSeparator();
} else { } else {
QAction *aIncrement = new QAction(QString(i < 0 ? "%1" : "+%1").arg(i), this); QAction *aIncrement = new QAction(QString(i < 0 ? "%1" : "+%1").arg(i), this);
if (i == -1) if (i == -1) {
aDec = aIncrement; aDec = aIncrement;
else if (i == 1) } else if (i == 1) {
aInc = aIncrement; aInc = aIncrement;
}
aIncrement->setData(i); aIncrement->setData(i);
connect(aIncrement, &QAction::triggered, this, &AbstractCounter::incrementCounter); connect(aIncrement, &QAction::triggered, this, &AbstractCounter::incrementCounter);
menu->addAction(aIncrement); menu->addAction(aIncrement);
@ -69,10 +70,11 @@ AbstractCounter::~AbstractCounter()
void AbstractCounter::delCounter() void AbstractCounter::delCounter()
{ {
if (dialogSemaphore) if (dialogSemaphore) {
deleteAfterDialog = true; deleteAfterDialog = true;
else } else {
deleteLater(); deleteLater();
}
} }
void AbstractCounter::retranslateUi() void AbstractCounter::retranslateUi()
@ -136,8 +138,9 @@ void AbstractCounter::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ {
if (isUnderMouse() && player->getPlayerInfo()->getLocalOrJudge()) { if (isUnderMouse() && player->getPlayerInfo()->getLocalOrJudge()) {
if (event->button() == Qt::MiddleButton || (QApplication::keyboardModifiers() & Qt::ShiftModifier)) { if (event->button() == Qt::MiddleButton || (QApplication::keyboardModifiers() & Qt::ShiftModifier)) {
if (menu) if (menu) {
menu->exec(event->screenPos()); menu->exec(event->screenPos());
}
event->accept(); event->accept();
} else if (event->button() == Qt::LeftButton) { } else if (event->button() == Qt::LeftButton) {
Command_IncCounter cmd; Command_IncCounter cmd;
@ -152,8 +155,9 @@ void AbstractCounter::mousePressEvent(QGraphicsSceneMouseEvent *event)
player->getPlayerActions()->sendGameCommand(cmd); player->getPlayerActions()->sendGameCommand(cmd);
event->accept(); event->accept();
} }
} else } else {
event->ignore(); event->ignore();
}
} }
void AbstractCounter::hoverEnterEvent(QGraphicsSceneHoverEvent * /*event*/) void AbstractCounter::hoverEnterEvent(QGraphicsSceneHoverEvent * /*event*/)
@ -189,8 +193,9 @@ void AbstractCounter::setCounter()
} }
dialogSemaphore = false; dialogSemaphore = false;
if (!ok) if (!ok) {
return; return;
}
Expression exp(value); Expression exp(value);
int newValue = static_cast<int>(exp.parse(dialog.textValue())); int newValue = static_cast<int>(exp.parse(dialog.textValue()));
@ -231,8 +236,9 @@ void AbstractCounterDialog::changeValue(int diff)
{ {
bool ok; bool ok;
int curValue = textValue().toInt(&ok); int curValue = textValue().toInt(&ok);
if (!ok) if (!ok) {
return; return;
}
curValue += diff; curValue += diff;
setTextValue(QString::number(curValue)); setTextValue(QString::number(curValue));
} }

View file

@ -27,13 +27,16 @@ ArrowItem::ArrowItem(Player *_player, int _id, ArrowTarget *_startItem, ArrowTar
{ {
setZValue(ZValues::ARROWS); setZValue(ZValues::ARROWS);
if (startItem) if (startItem) {
startItem->addArrowFrom(this); startItem->addArrowFrom(this);
if (targetItem) }
if (targetItem) {
targetItem->addArrowTo(this); targetItem->addArrowTo(this);
}
if (startItem && targetItem) if (startItem && targetItem) {
updatePath(); updatePath();
}
} }
ArrowItem::~ArrowItem() ArrowItem::~ArrowItem()
@ -59,8 +62,9 @@ void ArrowItem::delArrow()
void ArrowItem::updatePath() void ArrowItem::updatePath()
{ {
if (!targetItem) if (!targetItem) {
return; return;
}
QPointF endPoint = targetItem->mapToScene( QPointF endPoint = targetItem->mapToScene(
QPointF(targetItem->boundingRect().width() / 2, targetItem->boundingRect().height() / 2)); 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++ headWidth / qPow(2, 0.5); // aka headWidth / sqrt (2) but this produces a compile error with MSVC++
const double phi = 15; const double phi = 15;
if (!startItem) if (!startItem) {
return; return;
}
QPointF startPoint = QPointF startPoint =
startItem->mapToScene(QPointF(startItem->boundingRect().width() / 2, startItem->boundingRect().height() / 2)); 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(); qreal lineLength = line.length();
prepareGeometryChange(); prepareGeometryChange();
if (lineLength < 30) if (lineLength < 30) {
path = QPainterPath(); path = QPainterPath();
else { } else {
QPointF c(lineLength / 2, qTan(phi * M_PI / 180) * lineLength); QPointF c(lineLength / 2, qTan(phi * M_PI / 180) * lineLength);
QPainterPath centerLine; QPainterPath centerLine;
@ -123,10 +128,11 @@ void ArrowItem::updatePath(const QPointF &endPoint)
void ArrowItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) void ArrowItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
{ {
QColor paintColor(color); QColor paintColor(color);
if (fullColor) if (fullColor) {
paintColor.setAlpha(200); paintColor.setAlpha(200);
else } else {
paintColor.setAlpha(150); paintColor.setAlpha(150);
}
painter->setBrush(paintColor); painter->setBrush(paintColor);
painter->drawPath(path); 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(), // 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. // the event will be discarded as it would create some stray pointers.
if (targetLocked || !startItem) if (targetLocked || !startItem) {
return; return;
}
QPointF endPos = event->scenePos(); QPointF endPos = event->scenePos();
@ -213,8 +220,9 @@ void ArrowDragItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
void ArrowDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) void ArrowDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ {
if (!startItem) if (!startItem) {
return; return;
}
if (targetItem && (targetItem != startItem)) { if (targetItem && (targetItem != startItem)) {
CardZoneLogic *startZone = static_cast<CardItem *>(startItem)->getZone(); CardZoneLogic *startZone = static_cast<CardItem *>(startItem)->getZone();
@ -246,10 +254,11 @@ void ArrowDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
bool playToStack = SettingsCache::instance().getPlayToStack(); bool playToStack = SettingsCache::instance().getPlayToStack();
if (ci && ((!playToStack && ci->getUiAttributes().tableRow == 3) || if (ci && ((!playToStack && ci->getUiAttributes().tableRow == 3) ||
(playToStack && ci->getUiAttributes().tableRow != 0 && (playToStack && ci->getUiAttributes().tableRow != 0 &&
startCard->getZone()->getName() != ZoneNames::STACK))) startCard->getZone()->getName() != ZoneNames::STACK))) {
cmd.set_start_zone(ZoneNames::STACK); cmd.set_start_zone(ZoneNames::STACK);
else } else {
cmd.set_start_zone(playToStack ? ZoneNames::STACK : ZoneNames::TABLE); cmd.set_start_zone(playToStack ? ZoneNames::STACK : ZoneNames::TABLE);
}
} }
if (deleteInPhase != 0) { if (deleteInPhase != 0) {
@ -277,8 +286,9 @@ void ArrowAttachItem::addChildArrow(ArrowAttachItem *childArrow)
void ArrowAttachItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) void ArrowAttachItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{ {
if (targetLocked || !startItem) if (targetLocked || !startItem) {
return; return;
}
QPointF endPos = event->scenePos(); QPointF endPos = event->scenePos();
@ -343,8 +353,9 @@ void ArrowAttachItem::attachCards(CardItem *startCard, const CardItem *targetCar
void ArrowAttachItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) void ArrowAttachItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{ {
if (!startItem) if (!startItem) {
return; return;
}
// Attaching could move startItem under the current cursor position, causing all children to retarget to it right // Attaching could move startItem under the current cursor position, causing all children to retarget to it right
// before they are processed. Prevent that. // 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) QVariant ArrowTarget::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value)
{ {
if (change == ItemScenePositionHasChanged && scene()) { if (change == ItemScenePositionHasChanged && scene()) {
for (auto *arrow : arrowsFrom) for (auto *arrow : arrowsFrom) {
arrow->updatePath(); arrow->updatePath();
}
for (auto *arrow : arrowsTo) for (auto *arrow : arrowsTo) {
arrow->updatePath(); arrow->updatePath();
}
} }
return QGraphicsItem::itemChange(change, value); return QGraphicsItem::itemChange(change, value);

View file

@ -24,8 +24,9 @@ void CardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti
{ {
AbstractCardDragItem::paint(painter, option, widget); AbstractCardDragItem::paint(painter, option, widget);
if (occupied) if (occupied) {
painter->fillPath(shape(), QColor(200, 0, 0, 100)); painter->fillPath(shape(), QColor(200, 0, 0, 100));
}
} }
void CardDragItem::updatePosition(const QPointF &cursorScenePos) void CardDragItem::updatePosition(const QPointF &cursorScenePos)
@ -38,16 +39,19 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos)
ZoneViewZone *zoneViewZone = 0; ZoneViewZone *zoneViewZone = 0;
for (int i = colliding.size() - 1; i >= 0; i--) { for (int i = colliding.size() - 1; i >= 0; i--) {
CardZone *temp = qgraphicsitem_cast<CardZone *>(colliding.at(i)); CardZone *temp = qgraphicsitem_cast<CardZone *>(colliding.at(i));
if (!cardZone) if (!cardZone) {
cardZone = temp; cardZone = temp;
if (!zoneViewZone) }
if (!zoneViewZone) {
zoneViewZone = qobject_cast<ZoneViewZone *>(temp); zoneViewZone = qobject_cast<ZoneViewZone *>(temp);
}
} }
CardZone *cursorZone = 0; CardZone *cursorZone = 0;
if (zoneViewZone) if (zoneViewZone) {
cursorZone = zoneViewZone; cursorZone = zoneViewZone;
else if (cardZone) } else if (cardZone) {
cursorZone = cardZone; cursorZone = cardZone;
}
// Always update the current zone, even if its null, to cancel the drag // Always update the current zone, even if its null, to cancel the drag
// instead of dropping cards into an non-intuitive location. // instead of dropping cards into an non-intuitive location.
@ -59,8 +63,9 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos)
QPointF newPos = cursorScenePos - hotSpot; QPointF newPos = cursorScenePos - hotSpot;
if (newPos != pos()) { 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()); childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
}
setPos(newPos); setPos(newPos);
} }
@ -78,23 +83,27 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos)
// position. // position.
TableZone *tableZone = qobject_cast<TableZone *>(cursorZone); TableZone *tableZone = qobject_cast<TableZone *>(cursorZone);
QPointF closestGridPoint; QPointF closestGridPoint;
if (tableZone) if (tableZone) {
closestGridPoint = tableZone->closestGridPoint(cursorPosInZone); closestGridPoint = tableZone->closestGridPoint(cursorPosInZone);
else } else {
closestGridPoint = cursorPosInZone - hotSpot; closestGridPoint = cursorPosInZone - hotSpot;
}
QPointF newPos = zonePos + closestGridPoint; QPointF newPos = zonePos + closestGridPoint;
if (newPos != pos()) { 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()); childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
}
setPos(newPos); setPos(newPos);
bool newOccupied = false; bool newOccupied = false;
TableZone *table = qobject_cast<TableZone *>(cursorZone); TableZone *table = qobject_cast<TableZone *>(cursorZone);
if (table) if (table) {
if (table->getCardFromCoords(closestGridPoint)) if (table->getCardFromCoords(closestGridPoint)) {
newOccupied = true; newOccupied = true;
}
}
if (newOccupied != occupied) { if (newOccupied != occupied) {
occupied = newOccupied; occupied = newOccupied;
update(); update();

View file

@ -27,8 +27,9 @@ CardItem::CardItem(Player *_owner, QGraphicsItem *parent, const CardRef &cardRef
owner->addCard(this); owner->addCard(this);
connect(&SettingsCache::instance().cardCounters(), &CardCounterSettings::colorChanged, this, [this](int counterId) { connect(&SettingsCache::instance().cardCounters(), &CardCounterSettings::colorChanged, this, [this](int counterId) {
if (counters.contains(counterId)) if (counters.contains(counterId)) {
update(); update();
}
}); });
} }
@ -56,8 +57,9 @@ void CardItem::prepareDelete()
void CardItem::deleteLater() void CardItem::deleteLater()
{ {
prepareDelete(); prepareDelete();
if (scene()) if (scene()) {
static_cast<GameScene *>(scene())->unregisterAnimationItem(this); static_cast<GameScene *>(scene())->unregisterAnimationItem(this);
}
AbstractCardItem::deleteLater(); AbstractCardItem::deleteLater();
} }
@ -152,10 +154,11 @@ void CardItem::setAttacking(bool _attacking)
void CardItem::setCounter(int _id, int _value) void CardItem::setCounter(int _id, int _value)
{ {
if (_value) if (_value) {
counters.insert(_id, _value); counters.insert(_id, _value);
else } else {
counters.remove(_id); counters.remove(_id);
}
update(); update();
} }
@ -227,8 +230,9 @@ void CardItem::resetState(bool keepAnnotations)
attachedCards.clear(); attachedCards.clear();
setTapped(false, false); setTapped(false, false);
setDoesntUntap(false); setDoesntUntap(false);
if (scene()) if (scene()) {
static_cast<GameScene *>(scene())->unregisterAnimationItem(this); static_cast<GameScene *>(scene())->unregisterAnimationItem(this);
}
update(); update();
} }
@ -275,8 +279,9 @@ void CardItem::deleteDragItem()
void CardItem::drawArrow(const QColor &arrowColor) void CardItem::drawArrow(const QColor &arrowColor)
{ {
if (owner->getGame()->getPlayerManager()->isSpectator()) if (owner->getGame()->getPlayerManager()->isSpectator()) {
return; return;
}
auto *game = owner->getGame(); auto *game = owner->getGame();
Player *arrowOwner = game->getPlayerManager()->getActiveLocalPlayer(game->getGameState()->getActivePlayer()); Player *arrowOwner = game->getPlayerManager()->getActiveLocalPlayer(game->getGameState()->getActivePlayer());
@ -291,10 +296,12 @@ void CardItem::drawArrow(const QColor &arrowColor)
for (const auto &item : scene()->selectedItems()) { for (const auto &item : scene()->selectedItems()) {
CardItem *card = qgraphicsitem_cast<CardItem *>(item); CardItem *card = qgraphicsitem_cast<CardItem *>(item);
if (card == nullptr || card == this) if (card == nullptr || card == this) {
continue; continue;
if (card->getZone() != zone) }
if (card->getZone() != zone) {
continue; continue;
}
ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, card, arrowColor, phase); ArrowDragItem *childArrow = new ArrowDragItem(arrowOwner, card, arrowColor, phase);
scene()->addItem(childArrow); scene()->addItem(childArrow);
@ -304,8 +311,9 @@ void CardItem::drawArrow(const QColor &arrowColor)
void CardItem::drawAttachArrow() void CardItem::drawAttachArrow()
{ {
if (owner->getGame()->getPlayerManager()->isSpectator()) if (owner->getGame()->getPlayerManager()->isSpectator()) {
return; return;
}
auto *arrow = new ArrowAttachItem(this); auto *arrow = new ArrowAttachItem(this);
scene()->addItem(arrow); scene()->addItem(arrow);
@ -313,10 +321,12 @@ void CardItem::drawAttachArrow()
for (const auto &item : scene()->selectedItems()) { for (const auto &item : scene()->selectedItems()) {
CardItem *card = qgraphicsitem_cast<CardItem *>(item); CardItem *card = qgraphicsitem_cast<CardItem *>(item);
if (card == nullptr) if (card == nullptr) {
continue; continue;
if (card->getZone() != zone) }
if (card->getZone() != zone) {
continue; continue;
}
ArrowAttachItem *childArrow = new ArrowAttachItem(card); ArrowAttachItem *childArrow = new ArrowAttachItem(card);
scene()->addItem(childArrow); scene()->addItem(childArrow);
@ -328,27 +338,32 @@ void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{ {
if (event->buttons().testFlag(Qt::RightButton)) { if (event->buttons().testFlag(Qt::RightButton)) {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() < if ((event->screenPos() - event->buttonDownScreenPos(Qt::RightButton)).manhattanLength() <
2 * QApplication::startDragDistance()) 2 * QApplication::startDragDistance()) {
return; return;
}
QColor arrowColor = Qt::red; QColor arrowColor = Qt::red;
if (event->modifiers().testFlag(Qt::ControlModifier)) if (event->modifiers().testFlag(Qt::ControlModifier)) {
arrowColor = Qt::yellow; arrowColor = Qt::yellow;
else if (event->modifiers().testFlag(Qt::AltModifier)) } else if (event->modifiers().testFlag(Qt::AltModifier)) {
arrowColor = Qt::blue; arrowColor = Qt::blue;
else if (event->modifiers().testFlag(Qt::ShiftModifier)) } else if (event->modifiers().testFlag(Qt::ShiftModifier)) {
arrowColor = Qt::green; arrowColor = Qt::green;
}
drawArrow(arrowColor); drawArrow(arrowColor);
} else if (event->buttons().testFlag(Qt::LeftButton)) { } else if (event->buttons().testFlag(Qt::LeftButton)) {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() <
2 * QApplication::startDragDistance()) 2 * QApplication::startDragDistance()) {
return; return;
}
if (const ZoneViewZoneLogic *view = qobject_cast<const ZoneViewZoneLogic *>(zone)) { if (const ZoneViewZoneLogic *view = qobject_cast<const ZoneViewZoneLogic *>(zone)) {
if (view->getRevealZone() && !view->getWriteableRevealZone()) if (view->getRevealZone() && !view->getWriteableRevealZone()) {
return; return;
} else if (!owner->getPlayerInfo()->getLocalOrJudge()) }
} else if (!owner->getPlayerInfo()->getLocalOrJudge()) {
return; return;
}
bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier); bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier);
@ -360,14 +375,16 @@ void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
int childIndex = 0; int childIndex = 0;
for (const auto &item : scene()->selectedItems()) { for (const auto &item : scene()->selectedItems()) {
CardItem *card = static_cast<CardItem *>(item); CardItem *card = static_cast<CardItem *>(item);
if ((card == this) || (card->getZone() != zone)) if ((card == this) || (card->getZone() != zone)) {
continue; continue;
}
++childIndex; ++childIndex;
QPointF childPos; QPointF childPos;
if (zone->getHasCardAttr()) if (zone->getHasCardAttr()) {
childPos = card->pos() - pos(); childPos = card->pos() - pos();
else } else {
childPos = QPointF(childIndex * CardDimensions::WIDTH_HALF_F, 0); childPos = QPointF(childIndex * CardDimensions::WIDTH_HALF_F, 0);
}
CardDragItem *drag = CardDragItem *drag =
new CardDragItem(card, card->getId(), childPos, card->getFaceDown() || forceFaceDown, dragItem); new CardDragItem(card, card->getId(), childPos, card->getFaceDown() || forceFaceDown, dragItem);
drag->setPos(dragItem->pos() + childPos); drag->setPos(dragItem->pos() + childPos);
@ -380,13 +397,14 @@ void CardItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
void CardItem::playCard(bool faceDown) void CardItem::playCard(bool faceDown)
{ {
// Do nothing if the card belongs to another player // Do nothing if the card belongs to another player
if (!owner->getPlayerInfo()->getLocalOrJudge()) if (!owner->getPlayerInfo()->getLocalOrJudge()) {
return; return;
}
TableZoneLogic *tz = qobject_cast<TableZoneLogic *>(zone); TableZoneLogic *tz = qobject_cast<TableZoneLogic *>(zone);
if (tz) if (tz) {
emit tz->toggleTapped(); emit tz->toggleTapped();
else { } else {
if (SettingsCache::instance().getClickPlaysAllSelected()) { if (SettingsCache::instance().getClickPlaysAllSelected()) {
faceDown ? zone->getPlayer()->getPlayerActions()->actPlayFacedown() faceDown ? zone->getPlayer()->getPlayerActions()->actPlayFacedown()
: zone->getPlayer()->getPlayerActions()->actPlay(); : zone->getPlayer()->getPlayerActions()->actPlay();
@ -493,8 +511,9 @@ bool CardItem::animationEvent()
{ {
int rotation = ROTATION_DEGREES_PER_FRAME; int rotation = ROTATION_DEGREES_PER_FRAME;
bool animationIncomplete = true; bool animationIncomplete = true;
if (!tapped) if (!tapped) {
rotation *= -1; rotation *= -1;
}
tapAngle += rotation; tapAngle += rotation;
if (tapped && (tapAngle > 90)) { if (tapped && (tapAngle > 90)) {

View file

@ -24,17 +24,21 @@ void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos)
QList<QGraphicsItem *> colliding = scene()->items(cursorScenePos); QList<QGraphicsItem *> colliding = scene()->items(cursorScenePos);
DeckViewCardContainer *cursorZone = 0; DeckViewCardContainer *cursorZone = 0;
for (int i = colliding.size() - 1; i >= 0; i--) for (int i = colliding.size() - 1; i >= 0; i--) {
if ((cursorZone = qgraphicsitem_cast<DeckViewCardContainer *>(colliding.at(i)))) if ((cursorZone = qgraphicsitem_cast<DeckViewCardContainer *>(colliding.at(i)))) {
break; break;
if (!cursorZone) }
}
if (!cursorZone) {
return; return;
}
currentZone = cursorZone; currentZone = cursorZone;
QPointF newPos = cursorScenePos; QPointF newPos = cursorScenePos;
if (newPos != pos()) { 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()); childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot());
}
setPos(newPos); setPos(newPos);
} }
} }
@ -104,11 +108,13 @@ void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti
void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event) void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{ {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() <
2 * QApplication::startDragDistance()) 2 * QApplication::startDragDistance()) {
return; return;
}
if (static_cast<DeckViewScene *>(scene())->getLocked()) if (static_cast<DeckViewScene *>(scene())->getLocked()) {
return; return;
}
delete dragItem; delete dragItem;
dragItem = new DeckViewCardDragItem(this, event->pos()); dragItem = new DeckViewCardDragItem(this, event->pos());
@ -120,8 +126,9 @@ void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
int j = 0; int j = 0;
for (int i = 0; i < sel.size(); i++) { for (int i = 0; i < sel.size(); i++) {
auto *c = static_cast<DeckViewCard *>(sel.at(i)); auto *c = static_cast<DeckViewCard *>(sel.at(i));
if (c == this) if (c == this) {
continue; continue;
}
++j; ++j;
auto childPos = QPointF(j * CardDimensions::WIDTH_HALF_F, 0); auto childPos = QPointF(j * CardDimensions::WIDTH_HALF_F, 0);
auto *drag = new DeckViewCardDragItem(c, childPos, dragItem); auto *drag = new DeckViewCardDragItem(c, childPos, dragItem);
@ -133,8 +140,9 @@ void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
void DeckView::mouseDoubleClickEvent(QMouseEvent *event) void DeckView::mouseDoubleClickEvent(QMouseEvent *event)
{ {
if (static_cast<DeckViewScene *>(scene())->getLocked()) if (static_cast<DeckViewScene *>(scene())->getLocked()) {
return; return;
}
if (event->button() == Qt::LeftButton) { if (event->button() == Qt::LeftButton) {
QList<MoveCard_ToZone> result; QList<MoveCard_ToZone> result;
@ -147,12 +155,13 @@ void DeckView::mouseDoubleClickEvent(QMouseEvent *event)
m.set_card_name(c->getName().toStdString()); m.set_card_name(c->getName().toStdString());
m.set_start_zone(zone->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); 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); 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()); m.set_target_zone(zone->getName().toStdString());
}
result.append(m); result.append(m);
} }
@ -232,8 +241,9 @@ QList<QPair<int, int>> DeckViewCardContainer::getRowsAndCols() const
{ {
QList<QPair<int, int>> result; QList<QPair<int, int>> result;
QList<QString> cardTypeList = cardsByType.uniqueKeys(); 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]))); result.append(QPair<int, int>(1, cardsByType.count(cardTypeList[i])));
}
return result; return result;
} }
@ -262,8 +272,9 @@ QSizeF DeckViewCardContainer::calculateBoundingRect(const QList<QPair<int, int>>
// Calculate space needed for cards // Calculate space needed for cards
for (int i = 0; i < rowsAndCols.size(); ++i) { for (int i = 0; i < rowsAndCols.size(); ++i) {
totalHeight += CardDimensions::HEIGHT_F * rowsAndCols[i].first + paddingY; 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; totalWidth = CardDimensions::WIDTH_F * rowsAndCols[i].second;
}
} }
return QSizeF(getCardTypeTextWidth() + totalWidth, totalHeight + separatorY + paddingY); 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) bool DeckViewCardContainer::sortCardsByName(DeckViewCard *c1, DeckViewCard *c2)
{ {
if (c1 && c2) if (c1 && c2) {
return c1->getName() < c2->getName(); return c1->getName() < c2->getName();
}
return false; return false;
} }
@ -322,15 +334,17 @@ DeckViewScene::~DeckViewScene()
void DeckViewScene::clearContents() void DeckViewScene::clearContents()
{ {
QMapIterator<QString, DeckViewCardContainer *> i(cardContainers); QMapIterator<QString, DeckViewCardContainer *> i(cardContainers);
while (i.hasNext()) while (i.hasNext()) {
delete i.next().value(); delete i.next().value();
}
cardContainers.clear(); cardContainers.clear();
} }
void DeckViewScene::setDeck(const DeckList &_deck) void DeckViewScene::setDeck(const DeckList &_deck)
{ {
if (deck) if (deck) {
delete deck; delete deck;
}
deck = new DeckList(_deck.writeToString_Native()); deck = new DeckList(_deck.writeToString_Native());
rebuildTree(); rebuildTree();
@ -342,8 +356,9 @@ void DeckViewScene::rebuildTree()
{ {
clearContents(); clearContents();
if (!deck) if (!deck) {
return; return;
}
for (auto *currentZone : deck->getZoneNodes()) { for (auto *currentZone : deck->getZoneNodes()) {
DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0); DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0);
@ -355,8 +370,9 @@ void DeckViewScene::rebuildTree()
for (int j = 0; j < currentZone->size(); j++) { for (int j = 0; j < currentZone->size(); j++) {
auto *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j)); auto *currentCard = dynamic_cast<DecklistCardNode *>(currentZone->at(j));
if (!currentCard) if (!currentCard) {
continue; continue;
}
for (int k = 0; k < currentCard->getNumber(); ++k) { for (int k = 0; k < currentCard->getNumber(); ++k) {
auto *newCard = new DeckViewCard(container, currentCard->toCardRef(), currentZone->getName()); 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]; const MoveCard_ToZone &m = plan[i];
DeckViewCardContainer *start = cardContainers.value(QString::fromStdString(m.start_zone())); DeckViewCardContainer *start = cardContainers.value(QString::fromStdString(m.start_zone()));
DeckViewCardContainer *target = cardContainers.value(QString::fromStdString(m.target_zone())); DeckViewCardContainer *target = cardContainers.value(QString::fromStdString(m.target_zone()));
if (!start || !target) if (!start || !target) {
continue; continue;
}
DeckViewCard *card = 0; DeckViewCard *card = 0;
const QList<DeckViewCard *> &cardList = start->getCards(); 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())) { if (cardList[j]->getName() == QString::fromStdString(m.card_name())) {
card = cardList[j]; card = cardList[j];
break; break;
} }
if (!card) }
if (!card) {
continue; continue;
}
start->removeCard(card); start->removeCard(card);
target->addCard(card); target->addCard(card);
@ -405,8 +424,9 @@ void DeckViewScene::rearrangeItems()
rowsAndColsList.append(rowsAndCols); rowsAndColsList.append(rowsAndCols);
cardCountList.append(QList<int>()); 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); cardCountList[i].append(rowsAndCols[j].second);
}
} }
qreal totalHeight, totalWidth; qreal totalHeight, totalWidth;
@ -417,23 +437,27 @@ void DeckViewScene::rearrangeItems()
for (int i = 0; i < contList.size(); ++i) { for (int i = 0; i < contList.size(); ++i) {
QSizeF contSize = contList[i]->calculateBoundingRect(rowsAndColsList[i]); QSizeF contSize = contList[i]->calculateBoundingRect(rowsAndColsList[i]);
totalHeight += contSize.height() + spacing; totalHeight += contSize.height() + spacing;
if (contSize.width() > totalWidth) if (contSize.width() > totalWidth) {
totalWidth = contSize.width(); totalWidth = contSize.width();
}
} }
// We're done when the aspect ratio shifts from too high to too low. // We're done when the aspect ratio shifts from too high to too low.
if (totalWidth / totalHeight <= optimalAspectRatio) if (totalWidth / totalHeight <= optimalAspectRatio) {
break; break;
}
// Find category with highest column count // Find category with highest column count
int maxIndex1 = -1, maxIndex2 = -1, maxCols = 0; int maxIndex1 = -1, maxIndex2 = -1, maxCols = 0;
for (int i = 0; i < rowsAndColsList.size(); ++i) for (int i = 0; i < rowsAndColsList.size(); ++i) {
for (int j = 0; j < rowsAndColsList[i].size(); ++j) for (int j = 0; j < rowsAndColsList[i].size(); ++j) {
if (rowsAndColsList[i][j].second > maxCols) { if (rowsAndColsList[i][j].second > maxCols) {
maxIndex1 = i; maxIndex1 = i;
maxIndex2 = j; maxIndex2 = j;
maxCols = rowsAndColsList[i][j].second; maxCols = rowsAndColsList[i][j].second;
} }
}
}
// Add row to category // Add row to category
const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first; const int maxRows = rowsAndColsList[maxIndex1][maxIndex2].first;
@ -451,8 +475,9 @@ void DeckViewScene::rearrangeItems()
} }
totalWidth = totalHeight * optimalAspectRatio; totalWidth = totalHeight * optimalAspectRatio;
for (int i = 0; i < contList.size(); ++i) for (int i = 0; i < contList.size(); ++i) {
contList[i]->setWidth(totalWidth); contList[i]->setWidth(totalWidth);
}
setSceneRect(QRectF(0, 0, totalWidth, totalHeight)); setSceneRect(QRectF(0, 0, totalWidth, totalHeight));
} }
@ -470,7 +495,7 @@ QList<MoveCard_ToZone> DeckViewScene::getSideboardPlan() const
while (containerIterator.hasNext()) { while (containerIterator.hasNext()) {
DeckViewCardContainer *cont = containerIterator.next().value(); DeckViewCardContainer *cont = containerIterator.next().value();
const QList<DeckViewCard *> cardList = cont->getCards(); 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()) { if (cardList[i]->getOriginZone() != cont->getName()) {
MoveCard_ToZone m; MoveCard_ToZone m;
m.set_card_name(cardList[i]->getName().toStdString()); 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()); m.set_target_zone(cont->getName().toStdString());
result.append(m); result.append(m);
} }
}
} }
return result; return result;
} }

View file

@ -251,8 +251,9 @@ void DeckViewContainer::unloadDeck()
void DeckViewContainer::loadLocalDeck() void DeckViewContainer::loadLocalDeck()
{ {
DlgLoadDeck dialog(this); DlgLoadDeck dialog(this);
if (!dialog.exec()) if (!dialog.exec()) {
return; return;
}
loadDeckFromFile(dialog.selectedFiles().at(0)); loadDeckFromFile(dialog.selectedFiles().at(0));
} }
@ -364,8 +365,9 @@ void DeckViewContainer::sideboardPlanChanged()
{ {
Command_SetSideboardPlan cmd; Command_SetSideboardPlan cmd;
const QList<MoveCard_ToZone> &newPlan = deckView->getSideboardPlan(); const QList<MoveCard_ToZone> &newPlan = deckView->getSideboardPlan();
for (const auto &i : newPlan) for (const auto &i : newPlan) {
cmd.add_move_list()->CopyFrom(i); cmd.add_move_list()->CopyFrom(i);
}
parentGame->getGame()->getGameEventHandler()->sendGameCommand(cmd, playerId); parentGame->getGame()->getGameEventHandler()->sendGameCommand(cmd, playerId);
} }
@ -404,8 +406,9 @@ void DeckViewContainer::setSideboardLocked(bool locked)
{ {
sideboardLockButton->setState(!locked); sideboardLockButton->setState(!locked);
deckView->setLocked(readyStartButton->getState() || !sideboardLockButton->getState()); deckView->setLocked(readyStartButton->getState() || !sideboardLockButton->getState());
if (locked) if (locked) {
deckView->resetSideboardPlan(); deckView->resetSideboardPlan();
}
} }
void DeckViewContainer::setDeck(const DeckList &deck) void DeckViewContainer::setDeck(const DeckList &deck)

View file

@ -101,8 +101,9 @@ DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *pa
chooseTokenView->resizeColumnToContents(0); chooseTokenView->resizeColumnToContents(0);
chooseTokenView->setWordWrap(true); chooseTokenView->setWordWrap(true);
if (!deckHeaderState.isNull()) if (!deckHeaderState.isNull()) {
chooseTokenView->header()->restoreState(deckHeaderState); chooseTokenView->header()->restoreState(deckHeaderState);
}
chooseTokenView->header()->setStretchLastSection(false); chooseTokenView->header()->setStretchLastSection(false);
chooseTokenView->header()->hideSection(1); // Sets chooseTokenView->header()->hideSection(1); // Sets
@ -185,8 +186,9 @@ void DlgCreateToken::tokenSelectionChanged(const QModelIndex &current, const QMo
const QChar cardColor = cardInfo->getColorChar(); const QChar cardColor = cardInfo->getColorChar();
colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString)); colorEdit->setCurrentIndex(colorEdit->findData(cardColor, Qt::UserRole, Qt::MatchFixedString));
ptEdit->setText(cardInfo->getPowTough()); ptEdit->setText(cardInfo->getPowTough());
if (SettingsCache::instance().getAnnotateTokens()) if (SettingsCache::instance().getAnnotateTokens()) {
annotationEdit->setText(cardInfo->getText()); annotationEdit->setText(cardInfo->getText());
}
} else { } else {
nameEdit->setText(""); nameEdit->setText("");
colorEdit->setCurrentIndex(colorEdit->findData(QString(), Qt::UserRole, Qt::MatchFixedString)); 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) void GameEventHandler::sendGameCommand(PendingCommand *pend, int playerId)
{ {
AbstractClient *client = game->getClientForPlayer(playerId); AbstractClient *client = game->getClientForPlayer(playerId);
if (!client) if (!client) {
return; return;
}
connect(pend, &PendingCommand::finished, this, &GameEventHandler::commandFinished); connect(pend, &PendingCommand::finished, this, &GameEventHandler::commandFinished);
client->sendCommand(pend); client->sendCommand(pend);
@ -46,8 +47,9 @@ void GameEventHandler::sendGameCommand(PendingCommand *pend, int playerId)
void GameEventHandler::sendGameCommand(const google::protobuf::Message &command, int playerId) void GameEventHandler::sendGameCommand(const google::protobuf::Message &command, int playerId)
{ {
AbstractClient *client = game->getClientForPlayer(playerId); AbstractClient *client = game->getClientForPlayer(playerId);
if (!client) if (!client) {
return; return;
}
PendingCommand *pend = prepareGameCommand(command); PendingCommand *pend = prepareGameCommand(command);
connect(pend, &PendingCommand::finished, this, &GameEventHandler::commandFinished); 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) void GameEventHandler::commandFinished(const Response &response)
{ {
if (response.response_code() == Response::RespChatFlood) if (response.response_code() == Response::RespChatFlood) {
emit gameFlooded(); emit gameFlooded();
}
} }
PendingCommand *GameEventHandler::prepareGameCommand(const ::google::protobuf::Message &cmd) PendingCommand *GameEventHandler::prepareGameCommand(const ::google::protobuf::Message &cmd)
@ -117,9 +120,11 @@ void GameEventHandler::processGameEventContainer(const GameEventContainer &cont,
break; break;
} }
} else { } else {
if ((game->getGameState()->getClients().size() > 1) && (playerId != -1)) if ((game->getGameState()->getClients().size() > 1) && (playerId != -1)) {
if (game->getGameState()->getClients().at(playerId) != client) if (game->getGameState()->getClients().at(playerId) != client) {
continue; continue;
}
}
switch (eventType) { switch (eventType) {
case GameEvent::GAME_STATE_CHANGED: case GameEvent::GAME_STATE_CHANGED:
@ -284,8 +289,9 @@ void GameEventHandler::eventGameStateChanged(const Event_GameStateChanged &event
if (event.game_started() && !game->getGameMetaInfo()->started()) { if (event.game_started() && !game->getGameMetaInfo()->started()) {
game->getGameState()->setResuming(!game->getGameState()->isGameStateKnown()); game->getGameState()->setResuming(!game->getGameState()->isGameStateKnown());
game->getGameMetaInfo()->setStarted(event.game_started()); game->getGameMetaInfo()->setStarted(event.game_started());
if (game->getGameState()->isGameStateKnown()) if (game->getGameState()->isGameStateKnown()) {
emit logGameStart(); emit logGameStart();
}
game->getGameState()->setActivePlayer(event.active_player_id()); game->getGameState()->setActivePlayer(event.active_player_id());
game->getGameState()->setCurrentPhase(event.active_phase()); game->getGameState()->setCurrentPhase(event.active_phase());
} else if (!event.game_started() && game->getGameMetaInfo()->started()) { } else if (!event.game_started() && game->getGameMetaInfo()->started()) {
@ -305,8 +311,9 @@ void GameEventHandler::processCardAttachmentsForPlayers(const Event_GameStateCha
const ServerInfo_PlayerProperties &prop = playerInfo.properties(); const ServerInfo_PlayerProperties &prop = playerInfo.properties();
if (!prop.spectator()) { if (!prop.spectator()) {
Player *player = game->getPlayerManager()->getPlayers().value(prop.player_id(), 0); Player *player = game->getPlayerManager()->getPlayers().value(prop.player_id(), 0);
if (!player) if (!player) {
continue; continue;
}
player->processCardAttachment(playerInfo); player->processCardAttachment(playerInfo);
} }
} }
@ -317,8 +324,9 @@ void GameEventHandler::eventPlayerPropertiesChanged(const Event_PlayerProperties
const GameEventContext &context) const GameEventContext &context)
{ {
Player *player = game->getPlayerManager()->getPlayers().value(eventPlayerId, 0); Player *player = game->getPlayerManager()->getPlayers().value(eventPlayerId, 0);
if (!player) if (!player) {
return; return;
}
const ServerInfo_PlayerProperties &prop = event.player_properties(); const ServerInfo_PlayerProperties &prop = event.player_properties();
emit playerPropertiesChanged(prop, eventPlayerId); emit playerPropertiesChanged(prop, eventPlayerId);
@ -326,8 +334,9 @@ void GameEventHandler::eventPlayerPropertiesChanged(const Event_PlayerProperties
switch (contextType) { switch (contextType) {
case GameEventContext::READY_START: { case GameEventContext::READY_START: {
bool ready = prop.ready_start(); bool ready = prop.ready_start();
if (player->getPlayerInfo()->getLocal()) if (player->getPlayerInfo()->getLocal()) {
emit localPlayerReadyStateChanged(player->getPlayerInfo()->getId(), ready); emit localPlayerReadyStateChanged(player->getPlayerInfo()->getId(), ready);
}
if (ready) { if (ready) {
emit logReadyStart(player); emit logReadyStart(player);
} else { } else {
@ -339,8 +348,9 @@ void GameEventHandler::eventPlayerPropertiesChanged(const Event_PlayerProperties
player->setConceded(true); player->setConceded(true);
QMapIterator<int, Player *> playerIterator(game->getPlayerManager()->getPlayers()); QMapIterator<int, Player *> playerIterator(game->getPlayerManager()->getPlayers());
while (playerIterator.hasNext()) while (playerIterator.hasNext()) {
playerIterator.next().value()->updateZones(); playerIterator.next().value()->updateZones();
}
emit logConcede(eventPlayerId); emit logConcede(eventPlayerId);
@ -350,8 +360,9 @@ void GameEventHandler::eventPlayerPropertiesChanged(const Event_PlayerProperties
player->setConceded(false); player->setConceded(false);
QMapIterator<int, Player *> playerIterator(game->getPlayerManager()->getPlayers()); QMapIterator<int, Player *> playerIterator(game->getPlayerManager()->getPlayers());
while (playerIterator.hasNext()) while (playerIterator.hasNext()) {
playerIterator.next().value()->updateZones(); playerIterator.next().value()->updateZones();
}
emit logUnconcede(eventPlayerId); emit logUnconcede(eventPlayerId);
@ -389,8 +400,9 @@ void GameEventHandler::eventJoin(const Event_Join &event, int /*eventPlayerId*/,
QString playerName = QString::fromStdString(playerInfo.user_info().name()); QString playerName = QString::fromStdString(playerInfo.user_info().name());
emit addPlayerToAutoCompleteList(playerName); emit addPlayerToAutoCompleteList(playerName);
if (game->getPlayerManager()->getPlayers().contains(playerId)) if (game->getPlayerManager()->getPlayers().contains(playerId)) {
return; return;
}
if (playerInfo.spectator()) { if (playerInfo.spectator()) {
game->getPlayerManager()->addSpectator(playerId, playerInfo); 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*/) void GameEventHandler::eventLeave(const Event_Leave &event, int eventPlayerId, const GameEventContext & /*context*/)
{ {
Player *player = game->getPlayerManager()->getPlayers().value(eventPlayerId, 0); Player *player = game->getPlayerManager()->getPlayers().value(eventPlayerId, 0);
if (!player) if (!player) {
return; return;
}
player->clear(); player->clear();
emit playerLeft(eventPlayerId); 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 // Rearrange all remaining zones so that attachment relationship updates take place
QMapIterator<int, Player *> playerIterator(game->getPlayerManager()->getPlayers()); QMapIterator<int, Player *> playerIterator(game->getPlayerManager()->getPlayers());
while (playerIterator.hasNext()) while (playerIterator.hasNext()) {
playerIterator.next().value()->updateZones(); playerIterator.next().value()->updateZones();
}
emitUserEvent(); emitUserEvent();
} }
@ -461,8 +475,9 @@ void GameEventHandler::eventReverseTurn(const Event_ReverseTurn &event,
const GameEventContext & /*context*/) const GameEventContext & /*context*/)
{ {
Player *player = game->getPlayerManager()->getPlayers().value(eventPlayerId, 0); Player *player = game->getPlayerManager()->getPlayers().value(eventPlayerId, 0);
if (!player) if (!player) {
return; return;
}
emit logTurnReversed(player, event.reversed()); emit logTurnReversed(player, event.reversed());
} }
@ -491,8 +506,9 @@ void GameEventHandler::eventSetActivePlayer(const Event_SetActivePlayer &event,
{ {
game->getGameState()->setActivePlayer(event.active_player_id()); game->getGameState()->setActivePlayer(event.active_player_id());
Player *player = game->getPlayerManager()->getPlayer(event.active_player_id()); Player *player = game->getPlayerManager()->getPlayer(event.active_player_id());
if (!player) if (!player) {
return; return;
}
emit logActivePlayer(player); emit logActivePlayer(player);
emitUserEvent(); emitUserEvent();
} }

View file

@ -87,15 +87,17 @@ public:
public slots: public slots:
void setStarted(bool s) void setStarted(bool s)
{ {
if (gameInfo_.started() == s) if (gameInfo_.started() == s) {
return; return;
}
gameInfo_.set_started(s); gameInfo_.set_started(s);
emit startedChanged(s); emit startedChanged(s);
} }
void setSpectatorsOmniscient(bool v) void setSpectatorsOmniscient(bool v)
{ {
if (gameInfo_.spectators_omniscient() == v) if (gameInfo_.spectators_omniscient() == v) {
return; return;
}
gameInfo_.set_spectators_omniscient(v); gameInfo_.set_spectators_omniscient(v);
emit spectatorsOmniscienceChanged(v); emit spectatorsOmniscienceChanged(v);
} }

View file

@ -55,8 +55,9 @@ GameScene::~GameScene()
*/ */
void GameScene::retranslateUi() void GameScene::retranslateUi()
{ {
for (ZoneViewWidget *view : zoneViews) for (ZoneViewWidget *view : zoneViews) {
view->retranslateUi(); view->retranslateUi();
}
} }
QList<CardItem *> GameScene::selectedCards() const QList<CardItem *> GameScene::selectedCards() const
@ -209,10 +210,12 @@ QList<Player *> GameScene::rotatePlayers(const QList<Player *> &activePlayers, i
QList<Player *> rotated = activePlayers; QList<Player *> rotated = activePlayers;
if (!rotated.isEmpty()) { if (!rotated.isEmpty()) {
int totalRotation = firstPlayerIndex + playerRotation; int totalRotation = firstPlayerIndex + playerRotation;
while (totalRotation < 0) while (totalRotation < 0) {
totalRotation += rotated.size(); totalRotation += rotated.size();
for (int i = 0; i < totalRotation; ++i) }
for (int i = 0; i < totalRotation; ++i) {
rotated.append(rotated.takeFirst()); rotated.append(rotated.takeFirst());
}
} }
return rotated; return rotated;
} }
@ -252,10 +255,11 @@ QSizeF GameScene::computeSceneSizeAndPlayerLayout(const QList<Player *> &players
for (int j = 0; j < rowsInColumn; ++j) { for (int j = 0; j < rowsInColumn; ++j) {
Player *player = playersIter.next(); Player *player = playersIter.next();
if (col == 0) if (col == 0) {
playersByColumn[col].prepend(player->getGraphicsItem()); playersByColumn[col].prepend(player->getGraphicsItem());
else } else {
playersByColumn[col].append(player->getGraphicsItem()); playersByColumn[col].append(player->getGraphicsItem());
}
auto *pgItem = player->getGraphicsItem(); auto *pgItem = player->getGraphicsItem();
thisColumnHeight += pgItem->boundingRect().height() + playerAreaSpacing; thisColumnHeight += pgItem->boundingRect().height() + playerAreaSpacing;
@ -294,8 +298,9 @@ QList<qreal> GameScene::calculateMinWidthByColumn() const
QList<qreal> minWidthByColumn; QList<qreal> minWidthByColumn;
for (const auto &col : playersByColumn) { for (const auto &col : playersByColumn) {
qreal maxWidth = 0; qreal maxWidth = 0;
for (PlayerGraphicsItem *player : col) for (PlayerGraphicsItem *player : col) {
maxWidth = std::max(maxWidth, player->getMinimumWidth()); maxWidth = std::max(maxWidth, player->getMinimumWidth());
}
minWidthByColumn.append(maxWidth); minWidthByColumn.append(maxWidth);
} }
return minWidthByColumn; return minWidthByColumn;
@ -356,32 +361,38 @@ void GameScene::updateHover(const QPointF &scenePos)
void GameScene::updateHoveredCard(CardItem *newCard) void GameScene::updateHoveredCard(CardItem *newCard)
{ {
if (hoveredCard && (newCard != hoveredCard)) if (hoveredCard && (newCard != hoveredCard)) {
endCardHover(hoveredCard); endCardHover(hoveredCard);
if (newCard && (newCard != hoveredCard)) }
if (newCard && (newCard != hoveredCard)) {
beginCardHover(newCard); beginCardHover(newCard);
}
hoveredCard = newCard; hoveredCard = newCard;
} }
void GameScene::beginCardHover(CardItem *card) void GameScene::beginCardHover(CardItem *card)
{ {
card->setHovered(true); card->setHovered(true);
if (auto *zone = SelectZone::findOwningSelectZone(card)) if (auto *zone = SelectZone::findOwningSelectZone(card)) {
zone->escapeClipForHover(card); zone->escapeClipForHover(card);
}
} }
void GameScene::endCardHover(CardItem *card) void GameScene::endCardHover(CardItem *card)
{ {
if (auto *zone = SelectZone::findOwningSelectZone(card)) if (auto *zone = SelectZone::findOwningSelectZone(card)) {
zone->restoreClipAfterHover(card); zone->restoreClipAfterHover(card);
}
card->setHovered(false); card->setHovered(false);
} }
CardZone *GameScene::findTopmostZone(const QList<QGraphicsItem *> &items) CardZone *GameScene::findTopmostZone(const QList<QGraphicsItem *> &items)
{ {
for (QGraphicsItem *item : items) for (QGraphicsItem *item : items) {
if (auto *zone = qgraphicsitem_cast<CardZone *>(item)) if (auto *zone = qgraphicsitem_cast<CardZone *>(item)) {
return zone; return zone;
}
}
return nullptr; return nullptr;
} }
@ -392,14 +403,17 @@ CardItem *GameScene::findTopmostCardInZone(const QList<QGraphicsItem *> &items,
for (QGraphicsItem *item : items) { for (QGraphicsItem *item : items) {
CardItem *card = qgraphicsitem_cast<CardItem *>(item); CardItem *card = qgraphicsitem_cast<CardItem *>(item);
if (!card) if (!card) {
continue; continue;
}
if (card->getAttachedTo()) { if (card->getAttachedTo()) {
if (card->getAttachedTo()->getZone() != zone->getLogic()) if (card->getAttachedTo()->getZone() != zone->getLogic()) {
continue; continue;
} else if (card->getZone() != zone->getLogic()) }
} else if (card->getZone() != zone->getLogic()) {
continue; continue;
}
if (card->getRealZValue() > maxZ) { if (card->getRealZValue() > maxZ) {
maxZ = card->getRealZValue(); maxZ = card->getRealZValue();
@ -438,12 +452,13 @@ void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numb
connect(item, &ZoneViewWidget::closePressed, this, &GameScene::removeZoneView); connect(item, &ZoneViewWidget::closePressed, this, &GameScene::removeZoneView);
addItem(item); addItem(item);
if (zoneName == ZoneNames::GRAVE) if (zoneName == ZoneNames::GRAVE) {
item->setPos(360, 100); item->setPos(360, 100);
else if (zoneName == ZoneNames::EXILE) } else if (zoneName == ZoneNames::EXILE) {
item->setPos(380, 120); item->setPos(380, 120);
else } else {
item->setPos(340, 80); item->setPos(340, 80);
}
} }
/** /**
@ -480,8 +495,9 @@ void GameScene::removeZoneView(ZoneViewWidget *item)
*/ */
void GameScene::clearViews() void GameScene::clearViews()
{ {
while (!zoneViews.isEmpty()) while (!zoneViews.isEmpty()) {
zoneViews.first()->close(); zoneViews.first()->close();
}
} }
/** /**
@ -489,8 +505,9 @@ void GameScene::clearViews()
*/ */
void GameScene::closeMostRecentZoneView() void GameScene::closeMostRecentZoneView()
{ {
if (!zoneViews.isEmpty()) if (!zoneViews.isEmpty()) {
zoneViews.last()->close(); zoneViews.last()->close();
}
} }
// ---------- View Transforms ---------- // ---------- View Transforms ----------
@ -509,10 +526,11 @@ QTransform GameScene::getViewportTransform() const
bool GameScene::event(QEvent *event) bool GameScene::event(QEvent *event)
{ {
if (event->type() == QEvent::GraphicsSceneMouseMove) if (event->type() == QEvent::GraphicsSceneMouseMove) {
updateHover(static_cast<QGraphicsSceneMouseEvent *>(event)->scenePos()); updateHover(static_cast<QGraphicsSceneMouseEvent *>(event)->scenePos());
else if (event->type() == QEvent::Leave) } else if (event->type() == QEvent::Leave) {
updateHoveredCard(nullptr); updateHoveredCard(nullptr);
}
return QGraphicsScene::event(event); return QGraphicsScene::event(event);
} }
@ -522,25 +540,29 @@ void GameScene::timerEvent(QTimerEvent * /*event*/)
QMutableSetIterator<CardItem *> i(cardsToAnimate); QMutableSetIterator<CardItem *> i(cardsToAnimate);
while (i.hasNext()) { while (i.hasNext()) {
i.next(); i.next();
if (!i.value()->animationEvent()) if (!i.value()->animationEvent()) {
i.remove(); i.remove();
}
} }
if (cardsToAnimate.isEmpty()) if (cardsToAnimate.isEmpty()) {
animationTimer->stop(); animationTimer->stop();
}
} }
void GameScene::registerAnimationItem(AbstractCardItem *card) void GameScene::registerAnimationItem(AbstractCardItem *card)
{ {
cardsToAnimate.insert(static_cast<CardItem *>(card)); cardsToAnimate.insert(static_cast<CardItem *>(card));
if (!animationTimer->isActive()) if (!animationTimer->isActive()) {
animationTimer->start(10, this); animationTimer->start(10, this);
}
} }
void GameScene::unregisterAnimationItem(AbstractCardItem *card) void GameScene::unregisterAnimationItem(AbstractCardItem *card)
{ {
cardsToAnimate.remove(static_cast<CardItem *>(card)); cardsToAnimate.remove(static_cast<CardItem *>(card));
if (cardsToAnimate.isEmpty()) if (cardsToAnimate.isEmpty()) {
animationTimer->stop(); animationTimer->stop();
}
} }
// ---------- Rubber Band ---------- // ---------- Rubber Band ----------

View file

@ -75,8 +75,9 @@ void GameView::resizeEvent(QResizeEvent *event)
QGraphicsView::resizeEvent(event); QGraphicsView::resizeEvent(event);
GameScene *s = dynamic_cast<GameScene *>(scene()); GameScene *s = dynamic_cast<GameScene *>(scene());
if (s) if (s) {
s->processViewSizeChange(event->size()); s->processViewSizeChange(event->size());
}
updateSceneRect(scene()->sceneRect()); updateSceneRect(scene()->sceneRect());
updateTotalSelectionCount(event->size()); updateTotalSelectionCount(event->size());
@ -89,8 +90,9 @@ void GameView::updateSceneRect(const QRectF &rect)
void GameView::startRubberBand(const QPointF &_selectionOrigin) void GameView::startRubberBand(const QPointF &_selectionOrigin)
{ {
if (!rubberBand) if (!rubberBand) {
return; return;
}
selectionOrigin = _selectionOrigin; selectionOrigin = _selectionOrigin;
rubberBand->setGeometry(QRect(mapFromScene(selectionOrigin), QSize(0, 0))); 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) void GameView::resizeRubberBand(const QPointF &cursorPoint, int selectedCount)
{ {
if (!rubberBand) if (!rubberBand) {
return; return;
}
constexpr int kLabelPaddingInPixels = 4; constexpr int kLabelPaddingInPixels = 4;
@ -145,8 +148,9 @@ void GameView::resizeRubberBand(const QPointF &cursorPoint, int selectedCount)
void GameView::stopRubberBand() void GameView::stopRubberBand()
{ {
if (!rubberBand) if (!rubberBand) {
return; return;
}
rubberBand->hide(); rubberBand->hide();
dragCountLabel->hide(); dragCountLabel->hide();

View file

@ -21,8 +21,9 @@ PhaseButton::PhaseButton(const QString &_name, QGraphicsItem *parent, QAction *_
activeAnimationTimer = new QTimer(this); activeAnimationTimer = new QTimer(this);
connect(activeAnimationTimer, &QTimer::timeout, this, &PhaseButton::updateAnimation); connect(activeAnimationTimer, &QTimer::timeout, this, &PhaseButton::updateAnimation);
activeAnimationTimer->setSingleShot(false); activeAnimationTimer->setSingleShot(false);
} else } else {
activeAnimationCounter = 9; activeAnimationCounter = 9;
}
setCacheMode(DeviceCoordinateCache); setCacheMode(DeviceCoordinateCache);
} }
@ -63,8 +64,9 @@ void PhaseButton::setWidth(double _width)
void PhaseButton::setActive(bool _active) void PhaseButton::setActive(bool _active)
{ {
if ((active == _active) || !highlightable) if ((active == _active) || !highlightable) {
return; return;
}
active = _active; active = _active;
activeAnimationTimer->start(25); activeAnimationTimer->start(25);
@ -72,8 +74,9 @@ void PhaseButton::setActive(bool _active)
void PhaseButton::updateAnimation() void PhaseButton::updateAnimation()
{ {
if (!highlightable) if (!highlightable) {
return; return;
}
// the counter ticks up to 10 when active and down to 0 when inactive // the counter ticks up to 10 when active and down to 0 when inactive
if (active && activeAnimationCounter < 10) { if (active && activeAnimationCounter < 10) {
@ -99,8 +102,9 @@ void PhaseButton::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * /*event*/)
void PhaseButton::triggerDoubleClickAction() void PhaseButton::triggerDoubleClickAction()
{ {
if (doubleClickAction) if (doubleClickAction) {
doubleClickAction->trigger(); doubleClickAction->trigger();
}
} }
PhasesToolbar::PhasesToolbar(QGraphicsItem *parent) PhasesToolbar::PhasesToolbar(QGraphicsItem *parent)
@ -126,8 +130,9 @@ PhasesToolbar::PhasesToolbar(QGraphicsItem *parent)
buttonList << untapButton << upkeepButton << drawButton << main1Button << combatStartButton << combatAttackersButton buttonList << untapButton << upkeepButton << drawButton << main1Button << combatStartButton << combatAttackersButton
<< combatBlockersButton << combatDamageButton << combatEndButton << main2Button << cleanupButton; << combatBlockersButton << combatDamageButton << combatEndButton << main2Button << cleanupButton;
for (auto &i : buttonList) for (auto &i : buttonList) {
connect(i, &PhaseButton::clicked, this, &PhasesToolbar::phaseButtonClicked); connect(i, &PhaseButton::clicked, this, &PhasesToolbar::phaseButtonClicked);
}
nextTurnButton = new PhaseButton("nextturn", this, nullptr, false); nextTurnButton = new PhaseButton("nextturn", this, nullptr, false);
connect(nextTurnButton, &PhaseButton::clicked, this, &PhasesToolbar::actNextTurn); connect(nextTurnButton, &PhaseButton::clicked, this, &PhasesToolbar::actNextTurn);
@ -144,8 +149,9 @@ QRectF PhasesToolbar::boundingRect() const
void PhasesToolbar::retranslateUi() void PhasesToolbar::retranslateUi()
{ {
for (int i = 0; i < buttonList.size(); ++i) for (int i = 0; i < buttonList.size(); ++i) {
buttonList[i]->setToolTip(getLongPhaseName(i)); buttonList[i]->setToolTip(getLongPhaseName(i));
}
} }
QString PhasesToolbar::getLongPhaseName(int phase) const QString PhasesToolbar::getLongPhaseName(int phase) const
@ -187,8 +193,9 @@ const double PhasesToolbar::marginSize = 3;
void PhasesToolbar::rearrangeButtons() void PhasesToolbar::rearrangeButtons()
{ {
for (auto &i : buttonList) for (auto &i : buttonList) {
i->setWidth(symbolSize); i->setWidth(symbolSize);
}
nextTurnButton->setWidth(symbolSize); nextTurnButton->setWidth(symbolSize);
double y = marginSize; double y = marginSize;
@ -226,11 +233,13 @@ void PhasesToolbar::setHeight(double _height)
void PhasesToolbar::setActivePhase(int phase) void PhasesToolbar::setActivePhase(int phase)
{ {
if (phase >= buttonList.size()) if (phase >= buttonList.size()) {
return; return;
}
for (int i = 0; i < buttonList.size(); ++i) for (int i = 0; i < buttonList.size(); ++i) {
buttonList[i]->setActive(i == phase); buttonList[i]->setActive(i == phase);
}
} }
void PhasesToolbar::triggerPhaseAction(int phase) void PhasesToolbar::triggerPhaseAction(int phase)
@ -243,8 +252,9 @@ void PhasesToolbar::triggerPhaseAction(int phase)
void PhasesToolbar::phaseButtonClicked() void PhasesToolbar::phaseButtonClicked()
{ {
auto *button = qobject_cast<PhaseButton *>(sender()); auto *button = qobject_cast<PhaseButton *>(sender());
if (button->getActive()) if (button->getActive()) {
button->triggerDoubleClickAction(); button->triggerDoubleClickAction();
}
Command_SetActivePhase cmd; Command_SetActivePhase cmd;
cmd.set_phase(static_cast<google::protobuf::uint32>(buttonList.indexOf(button))); 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(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (auto *other : players) {
if (other == player) if (other == player) {
continue; continue;
}
QAction *a = mRevealRandomGraveyardCard->addAction(other->getPlayerInfo()->getName()); QAction *a = mRevealRandomGraveyardCard->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId()); a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &GraveyardMenu::onRevealRandomTriggered); connect(a, &QAction::triggered, this, &GraveyardMenu::onRevealRandomTriggered);

View file

@ -168,8 +168,9 @@ void HandMenu::populateRevealHandMenuWithActivePlayers()
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (auto *other : players) {
if (other == player) if (other == player) {
continue; continue;
}
QAction *a = mRevealHand->addAction(other->getPlayerInfo()->getName()); QAction *a = mRevealHand->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId()); a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &HandMenu::onRevealHandTriggered); connect(a, &QAction::triggered, this, &HandMenu::onRevealHandTriggered);
@ -186,8 +187,9 @@ void HandMenu::populateRevealRandomHandCardMenuWithActivePlayers()
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (auto *other : players) {
if (other == player) if (other == player) {
continue; continue;
}
QAction *a = mRevealRandomHandCard->addAction(other->getPlayerInfo()->getName()); QAction *a = mRevealRandomHandCard->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId()); a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &HandMenu::onRevealRandomHandCardTriggered); connect(a, &QAction::triggered, this, &HandMenu::onRevealRandomHandCardTriggered);
@ -197,8 +199,9 @@ void HandMenu::populateRevealRandomHandCardMenuWithActivePlayers()
void HandMenu::onRevealHandTriggered() void HandMenu::onRevealHandTriggered()
{ {
auto *action = qobject_cast<QAction *>(sender()); auto *action = qobject_cast<QAction *>(sender());
if (!action) if (!action) {
return; return;
}
const int targetId = action->data().toInt(); const int targetId = action->data().toInt();
player->getPlayerActions()->actRevealHand(targetId); player->getPlayerActions()->actRevealHand(targetId);
@ -207,8 +210,9 @@ void HandMenu::onRevealHandTriggered()
void HandMenu::onRevealRandomHandCardTriggered() void HandMenu::onRevealRandomHandCardTriggered()
{ {
auto *action = qobject_cast<QAction *>(sender()); auto *action = qobject_cast<QAction *>(sender());
if (!action) if (!action) {
return; return;
}
const int targetId = action->data().toInt(); const int targetId = action->data().toInt();
player->getPlayerActions()->actRevealRandomHandCard(targetId); player->getPlayerActions()->actRevealRandomHandCard(targetId);

View file

@ -265,8 +265,9 @@ void LibraryMenu::populateRevealLibraryMenuWithActivePlayers()
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (auto *other : players) {
if (other == player) if (other == player) {
continue; continue;
}
QAction *a = mRevealLibrary->addAction(other->getPlayerInfo()->getName()); QAction *a = mRevealLibrary->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId()); a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &LibraryMenu::onRevealLibraryTriggered); connect(a, &QAction::triggered, this, &LibraryMenu::onRevealLibraryTriggered);
@ -279,8 +280,9 @@ void LibraryMenu::populateLendLibraryMenuWithActivePlayers()
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (auto *other : players) {
if (other == player) if (other == player) {
continue; continue;
}
QAction *a = mLendLibrary->addAction(other->getPlayerInfo()->getName()); QAction *a = mLendLibrary->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId()); a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &LibraryMenu::onLendLibraryTriggered); connect(a, &QAction::triggered, this, &LibraryMenu::onLendLibraryTriggered);
@ -299,8 +301,9 @@ void LibraryMenu::populateRevealTopCardMenuWithActivePlayers()
const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values();
for (auto *other : players) { for (auto *other : players) {
if (other == player) if (other == player) {
continue; continue;
}
QAction *a = mRevealTopCard->addAction(other->getPlayerInfo()->getName()); QAction *a = mRevealTopCard->addAction(other->getPlayerInfo()->getName());
a->setData(other->getPlayerInfo()->getId()); a->setData(other->getPlayerInfo()->getId());
connect(a, &QAction::triggered, this, &LibraryMenu::onRevealTopCardTriggered); connect(a, &QAction::triggered, this, &LibraryMenu::onRevealTopCardTriggered);

View file

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

View file

@ -85,8 +85,9 @@ void PlayerActions::playCard(CardItem *card, bool faceDown)
cardToMove->set_pt(info.getPowTough().toStdString()); cardToMove->set_pt(info.getPowTough().toStdString());
} }
cardToMove->set_tapped(!faceDown && info.getUiAttributes().cipt); cardToMove->set_tapped(!faceDown && info.getUiAttributes().cipt);
if (tableRow != 3) if (tableRow != 3) {
cmd.set_target_zone(ZoneNames::TABLE); cmd.set_target_zone(ZoneNames::TABLE);
}
cmd.set_x(gridPoint.x()); cmd.set_x(gridPoint.x());
cmd.set_y(gridPoint.y()); cmd.set_y(gridPoint.y());
} }

View file

@ -43,8 +43,9 @@ PlayerListTWI::PlayerListTWI() : QTreeWidgetItem(Type)
bool PlayerListTWI::operator<(const QTreeWidgetItem &other) const bool PlayerListTWI::operator<(const QTreeWidgetItem &other) const
{ {
// Sort by spectator/player // 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(); return data(1, Qt::UserRole).toBool();
}
// Sort by player ID // Sort by player ID
return data(4, Qt::UserRole + 1).toInt() < other.data(4, Qt::UserRole + 1).toInt(); 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) void PlayerListWidget::updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId)
{ {
if (playerId == -1) if (playerId == -1) {
playerId = prop.player_id(); playerId = prop.player_id();
}
QTreeWidgetItem *player = players.value(playerId, 0); QTreeWidgetItem *player = players.value(playerId, 0);
if (!player) if (!player) {
return; return;
}
bool isSpectator = prop.has_spectator() && prop.spectator(); bool isSpectator = prop.has_spectator() && prop.spectator();
if (prop.has_judge() || prop.has_spectator()) { if (prop.has_judge() || prop.has_spectator()) {
@ -126,13 +129,16 @@ void PlayerListWidget::updatePlayerProperties(const ServerInfo_PlayerProperties
} }
if (!isSpectator) { if (!isSpectator) {
if (prop.has_conceded()) if (prop.has_conceded()) {
player->setData(2, Qt::UserRole, prop.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()); 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()) player->setIcon(2, gameStarted ? (prop.conceded() ? concededIcon : QIcon())
: (prop.ready_start() ? readyIcon : notReadyIcon)); : (prop.ready_start() ? readyIcon : notReadyIcon));
}
} }
if (prop.has_user_info()) { if (prop.has_user_info()) {
player->setData(3, Qt::UserRole, prop.user_info().user_level()); 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()))); QString::fromStdString(prop.user_info().privlevel())));
player->setText(4, QString::fromStdString(prop.user_info().name())); player->setText(4, QString::fromStdString(prop.user_info().name()));
const QString country = QString::fromStdString(prop.user_info().country()); const QString country = QString::fromStdString(prop.user_info().country());
if (!country.isEmpty()) if (!country.isEmpty()) {
player->setIcon(4, QIcon(CountryPixmapGenerator::generatePixmap(12, country))); player->setIcon(4, QIcon(CountryPixmapGenerator::generatePixmap(12, country)));
}
player->setData(4, Qt::UserRole, QString::fromStdString(prop.user_info().name())); 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()); player->setData(4, Qt::UserRole + 1, prop.player_id());
}
if (!isSpectator) { if (!isSpectator) {
if (prop.has_deck_hash()) { if (prop.has_deck_hash()) {
player->setText(5, QString::fromStdString(prop.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()); 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))); player->setIcon(0, QIcon(PingPixmapGenerator::generatePixmap(12, prop.ping_seconds(), 10)));
}
} }
void PlayerListWidget::removePlayer(int playerId) void PlayerListWidget::removePlayer(int playerId)
{ {
QTreeWidgetItem *player = players.value(playerId, 0); QTreeWidgetItem *player = players.value(playerId, 0);
if (!player) if (!player) {
return; return;
}
players.remove(playerId); players.remove(playerId);
delete takeTopLevelItem(indexOfTopLevelItem(player)); delete takeTopLevelItem(indexOfTopLevelItem(player));
} }
@ -193,13 +204,14 @@ void PlayerListWidget::setGameStarted(bool _gameStarted, bool resuming)
QTreeWidgetItem *twi = i.next().value(); QTreeWidgetItem *twi = i.next().value();
bool isPlayer = twi->data(1, Qt::UserRole).toBool(); bool isPlayer = twi->data(1, Qt::UserRole).toBool();
if (!isPlayer) if (!isPlayer) {
continue; continue;
}
if (gameStarted) { if (gameStarted) {
if (resuming) if (resuming) {
twi->setIcon(2, twi->data(2, Qt::UserRole).toBool() ? concededIcon : QIcon()); twi->setIcon(2, twi->data(2, Qt::UserRole).toBool() ? concededIcon : QIcon());
else { } else {
twi->setData(2, Qt::UserRole, false); twi->setData(2, Qt::UserRole, false);
twi->setIcon(2, QIcon()); twi->setIcon(2, QIcon());
} }
@ -211,8 +223,9 @@ void PlayerListWidget::setGameStarted(bool _gameStarted, bool resuming)
void PlayerListWidget::showContextMenu(const QPoint &pos, const QModelIndex &index) void PlayerListWidget::showContextMenu(const QPoint &pos, const QModelIndex &index)
{ {
if (!userContextMenu) if (!userContextMenu) {
return; return;
}
const QString &userName = index.sibling(index.row(), 4).data(Qt::UserRole).toString(); const QString &userName = index.sibling(index.row(), 4).data(Qt::UserRole).toString();
int playerId = index.sibling(index.row(), 4).data(Qt::UserRole + 1).toInt(); 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 *PlayerManager::getActiveLocalPlayer(int activePlayer) const
{ {
Player *active = players.value(activePlayer, 0); Player *active = players.value(activePlayer, 0);
if (active) if (active) {
if (active->getPlayerInfo()->getLocal()) if (active->getPlayerInfo()->getLocal()) {
return active; return active;
}
}
QMapIterator<int, Player *> playerIterator(players); QMapIterator<int, Player *> playerIterator(players);
while (playerIterator.hasNext()) { while (playerIterator.hasNext()) {
Player *temp = playerIterator.next().value(); Player *temp = playerIterator.next().value();
if (temp->getPlayerInfo()->getLocal()) if (temp->getPlayerInfo()->getLocal()) {
return temp; return temp;
}
} }
return nullptr; return nullptr;
@ -66,8 +69,9 @@ void PlayerManager::removePlayer(int playerId)
Player *PlayerManager::getPlayer(int playerId) const Player *PlayerManager::getPlayer(int playerId) const
{ {
Player *player = players.value(playerId, 0); Player *player = players.value(playerId, 0);
if (!player) if (!player) {
return nullptr; return nullptr;
}
return player; return player;
} }

View file

@ -128,8 +128,9 @@ void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*o
resetPainterTransform(painter); resetPainterTransform(painter);
QString name = QString::fromStdString(info->name()); QString name = QString::fromStdString(info->name());
if (name.size() > 13) if (name.size() > 13) {
name = name.mid(0, 10) + "..."; name = name.mid(0, 10) + "...";
}
QFont font; QFont font;
font.setPixelSize(qMax(qRound(translatedNameRect.height() / 1.5), 9)); 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->setPen(pen);
painter->drawRect(boundingRect().adjusted(border / 2, border / 2, -border / 2, -border / 2)); 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))); painter->fillRect(boundingRect(), QBrush(QColor(255, 0, 0, 100)));
}
} }
AbstractCounter *PlayerTarget::addCounter(int _counterId, const QString &_name, int _value) AbstractCounter *PlayerTarget::addCounter(int _counterId, const QString &_name, int _value)

View file

@ -25,14 +25,16 @@ void CardZone::onCardAdded(CardItem *addedCard)
void CardZone::retranslateUi() 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(); getLogic()->getCards()[i]->retranslateUi();
}
} }
void CardZone::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * /*event*/) void CardZone::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * /*event*/)
{ {
if (doubleClickAction) if (doubleClickAction) {
doubleClickAction->trigger(); doubleClickAction->trigger();
}
} }
bool CardZone::showContextMenu(const QPoint &screenPos) bool CardZone::showContextMenu(const QPoint &screenPos)
@ -47,12 +49,14 @@ bool CardZone::showContextMenu(const QPoint &screenPos)
void CardZone::mousePressEvent(QGraphicsSceneMouseEvent *event) void CardZone::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ {
if (event->button() == Qt::RightButton) { if (event->button() == Qt::RightButton) {
if (showContextMenu(event->screenPos())) if (showContextMenu(event->screenPos())) {
event->accept(); event->accept();
else } else {
event->ignore(); event->ignore();
} else }
} else {
event->ignore(); event->ignore();
}
} }
QPointF CardZone::closestGridPoint(const QPointF &point) QPointF CardZone::closestGridPoint(const QPointF &point)

View file

@ -34,9 +34,11 @@ void HandZone::handleDropEvent(const QList<CardDragItem *> &dragItems,
QPoint point = dropPoint + scenePos().toPoint(); QPoint point = dropPoint + scenePos().toPoint();
int x = -1; int x = -1;
if (SettingsCache::instance().getHorizontalHand()) { if (SettingsCache::instance().getHorizontalHand()) {
for (x = 0; x < getLogic()->getCards().size(); x++) for (x = 0; x < getLogic()->getCards().size(); x++) {
if (point.x() < static_cast<CardItem *>(getLogic()->getCards().at(x))->scenePos().x()) if (point.x() < static_cast<CardItem *>(getLogic()->getCards().at(x))->scenePos().x()) {
break; break;
}
}
} else { } else {
x = calcDropIndexFromY(dropPoint.y()); x = calcDropIndexFromY(dropPoint.y());
} }
@ -49,18 +51,20 @@ void HandZone::handleDropEvent(const QList<CardDragItem *> &dragItems,
cmd.set_x(x); cmd.set_x(x);
cmd.set_y(-1); 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()); cmd.mutable_cards_to_move()->add_card()->set_card_id(dragItems[i]->getId());
}
getLogic()->getPlayer()->getPlayerActions()->sendGameCommand(cmd); getLogic()->getPlayer()->getPlayerActions()->sendGameCommand(cmd);
} }
QRectF HandZone::boundingRect() const QRectF HandZone::boundingRect() const
{ {
if (SettingsCache::instance().getHorizontalHand()) if (SettingsCache::instance().getHorizontalHand()) {
return QRectF(0, 0, width, CardDimensions::HEIGHT_F + 10); return QRectF(0, 0, width, CardDimensions::HEIGHT_F + 10);
else } else {
return QRectF(0, 0, CardDimensions::WIDTH_F * 1.5, zoneHeight); return QRectF(0, 0, CardDimensions::WIDTH_F * 1.5, zoneHeight);
}
} }
void HandZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) void HandZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/)
@ -90,9 +94,9 @@ void HandZone::reorganizeCards()
CardItem *c = getLogic()->getCards().at(i); CardItem *c = getLogic()->getCards().at(i);
// If the total width of the cards is smaller than the available width, // 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. // 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); c->setPos(xPadding + ((qreal)i) * (totalWidth - cardWidth) / (cardCount - 1), 5);
else { } else {
qreal xPosition = leftJustified ? xPadding + ((qreal)i) * cardWidth qreal xPosition = leftJustified ? xPadding + ((qreal)i) * cardWidth
: xPadding + ((qreal)i) * cardWidth + : xPadding + ((qreal)i) * cardWidth +
(totalWidth - cardCount * cardWidth) / 2; (totalWidth - cardCount * cardWidth) / 2;

View file

@ -55,8 +55,9 @@ void CardZoneLogic::addCard(CardItem *card, const bool reorganize, const int x,
emit cardAdded(card); emit cardAdded(card);
addCardImpl(card, x, y); addCardImpl(card, x, y);
if (reorganize) if (reorganize) {
emit reorganizeCards(); emit reorganizeCards();
}
emit cardCountChanged(); emit cardCountChanged();
} }
@ -66,16 +67,19 @@ CardItem *CardZoneLogic::takeCard(int position, int cardId, bool toNewZone)
if (position == -1) { if (position == -1) {
// position == -1 means either that the zone is indexed by card id // position == -1 means either that the zone is indexed by card id
// or that it doesn't matter which card you take. // 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) { if (cards[i]->getId() == cardId) {
position = i; position = i;
break; break;
} }
if (position == -1) }
if (position == -1) {
position = 0; position = 0;
}
} }
if (position >= cards.size()) if (position >= cards.size()) {
return nullptr; return nullptr;
}
for (auto *view : views) { for (auto *view : views) {
qobject_cast<ZoneViewZoneLogic *>(view->getLogic())->removeCard(position, toNewZone); qobject_cast<ZoneViewZoneLogic *>(view->getLogic())->removeCard(position, toNewZone);
@ -142,8 +146,9 @@ void CardZoneLogic::moveAllToZone()
cmd.set_target_zone(targetZone.toStdString()); cmd.set_target_zone(targetZone.toStdString());
cmd.set_x(targetX); 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()); cmd.mutable_cards_to_move()->add_card()->set_card_id(cards[i]->getId());
}
player->getPlayerActions()->sendGameCommand(cmd); player->getPlayerActions()->sendGameCommand(cmd);
} }
@ -175,9 +180,9 @@ void CardZoneLogic::clearContents()
QString CardZoneLogic::getTranslatedName(bool theirOwn, GrammaticalCase gc) const QString CardZoneLogic::getTranslatedName(bool theirOwn, GrammaticalCase gc) const
{ {
QString ownerName = player->getPlayerInfo()->getName(); 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)); 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) { switch (gc) {
case CaseLookAtZone: case CaseLookAtZone:
return (theirOwn ? tr("their library", "look at zone") return (theirOwn ? tr("their library", "look at zone")
@ -193,11 +198,11 @@ QString CardZoneLogic::getTranslatedName(bool theirOwn, GrammaticalCase gc) cons
default: default:
return (theirOwn ? tr("their library", "nominative") : tr("%1's library", "nominative").arg(ownerName)); 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)); 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)); 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) { switch (gc) {
case CaseLookAtZone: case CaseLookAtZone:
return (theirOwn ? tr("their sideboard", "look at zone") return (theirOwn ? tr("their sideboard", "look at zone")
@ -208,7 +213,7 @@ QString CardZoneLogic::getTranslatedName(bool theirOwn, GrammaticalCase gc) cons
default: default:
break; break;
} }
else { } else {
return (theirOwn ? tr("their custom zone '%1'", "nominative").arg(name) return (theirOwn ? tr("their custom zone '%1'", "nominative").arg(name)
: tr("%1's custom zone '%2'", "nominative").arg(ownerName).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->setCardRef({});
card->setId(-1); card->setId(-1);
// If we obscure a previously revealed card, its name has to be forgotten // 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({}); cards.at(x + 1)->setCardRef({});
}
} }
card->setVisible(false); card->setVisible(false);
card->resetState(); card->resetState();

View file

@ -29,7 +29,8 @@ CardItem *TableZoneLogic::takeCard(int position, int cardId, bool toNewZone)
{ {
CardItem *result = CardZoneLogic::takeCard(position, cardId); CardItem *result = CardZoneLogic::takeCard(position, cardId);
if (toNewZone) if (toNewZone) {
emit contentSizeChanged(); emit contentSizeChanged();
}
return result; return result;
} }

View file

@ -48,9 +48,10 @@ void PileZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*optio
{ {
painter->drawPath(shape()); painter->drawPath(shape());
if (!getLogic()->getCards().isEmpty()) if (!getLogic()->getCards().isEmpty()) {
getLogic()->getCards().at(0)->paintPicture(painter, getLogic()->getCards().at(0)->getTranslatedSize(painter), getLogic()->getCards().at(0)->paintPicture(painter, getLogic()->getCards().at(0)->getTranslatedSize(painter),
90); 90);
}
painter->translate(CardDimensions::WIDTH_HALF_F, CardDimensions::HEIGHT_HALF_F); painter->translate(CardDimensions::WIDTH_HALF_F, CardDimensions::HEIGHT_HALF_F);
painter->rotate(-90); painter->rotate(-90);
@ -87,24 +88,28 @@ void PileZone::reorganizeCards()
void PileZone::mousePressEvent(QGraphicsSceneMouseEvent *event) void PileZone::mousePressEvent(QGraphicsSceneMouseEvent *event)
{ {
CardZone::mousePressEvent(event); CardZone::mousePressEvent(event);
if (event->isAccepted()) if (event->isAccepted()) {
return; return;
}
if (event->button() == Qt::LeftButton) { if (event->button() == Qt::LeftButton) {
setCursor(Qt::ClosedHandCursor); setCursor(Qt::ClosedHandCursor);
event->accept(); event->accept();
} else } else {
event->ignore(); event->ignore();
}
} }
void PileZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event) void PileZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{ {
if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() < if ((event->screenPos() - event->buttonDownScreenPos(Qt::LeftButton)).manhattanLength() <
QApplication::startDragDistance()) QApplication::startDragDistance()) {
return; return;
}
if (getLogic()->getCards().isEmpty()) if (getLogic()->getCards().isEmpty()) {
return; return;
}
bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier); bool forceFaceDown = event->modifiers().testFlag(Qt::ShiftModifier);
bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier); bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier);
@ -123,7 +128,8 @@ void PileZone::mouseReleaseEvent(QGraphicsSceneMouseEvent * /*event*/)
void PileZone::hoverEnterEvent(QGraphicsSceneHoverEvent *event) void PileZone::hoverEnterEvent(QGraphicsSceneHoverEvent *event)
{ {
if (!getLogic()->getCards().isEmpty()) if (!getLogic()->getCards().isEmpty()) {
getLogic()->getCards()[0]->processHoverEvent(); getLogic()->getCards()[0]->processHoverEvent();
}
QGraphicsItem::hoverEnterEvent(event); QGraphicsItem::hoverEnterEvent(event);
} }

View file

@ -69,8 +69,9 @@ SelectZone *SelectZone::findOwningSelectZone(const QGraphicsItem *card)
SelectZone::StackLayoutParams SelectZone::buildStackParams(qreal minOffset) const SelectZone::StackLayoutParams SelectZone::buildStackParams(qreal minOffset) const
{ {
const auto &cards = getLogic()->getCards(); const auto &cards = getLogic()->getCards();
if (cards.isEmpty()) if (cards.isEmpty()) {
return {0, boundingRect().height(), 0.0, 0.0, minOffset}; return {0, boundingRect().height(), 0.0, 0.0, minOffset};
}
const auto cardCount = static_cast<int>(cards.size()); const auto cardCount = static_cast<int>(cards.size());
const qreal cardHeight = cards.at(0)->boundingRect().height(); const qreal cardHeight = cards.at(0)->boundingRect().height();
const qreal offset = stackingOffset(cardHeight); const qreal offset = stackingOffset(cardHeight);
@ -93,8 +94,9 @@ int SelectZone::calcDropIndexFromY(qreal dropY, qreal minOffset) const
void SelectZone::restoreStaleEscapedCards() void SelectZone::restoreStaleEscapedCards()
{ {
if (!cardClipContainer) if (!cardClipContainer) {
return; return;
}
for (auto *card : getLogic()->getCards()) { for (auto *card : getLogic()->getCards()) {
// A card parented to the zone (instead of the clip container) should // A card parented to the zone (instead of the clip container) should
// only occur while it is actively hovered. If hover cleanup was // only occur while it is actively hovered. If hover cleanup was
@ -108,10 +110,12 @@ void SelectZone::restoreStaleEscapedCards()
void SelectZone::layoutCardsVertically(const StackLayoutParams &params) void SelectZone::layoutCardsVertically(const StackLayoutParams &params)
{ {
const auto &cards = getLogic()->getCards(); const auto &cards = getLogic()->getCards();
if (cards.isEmpty() || params.cardCount <= 0) if (cards.isEmpty() || params.cardCount <= 0) {
return; return;
if (params.cardCount > cards.size()) }
if (params.cardCount > cards.size()) {
return; return;
}
constexpr qreal xspace = 5; constexpr qreal xspace = 5;
const qreal cardWidth = cards.at(0)->boundingRect().width(); const qreal cardWidth = cards.at(0)->boundingRect().width();
@ -163,8 +167,9 @@ void SelectZone::onCardAdded(CardItem *addedCard)
void SelectZone::setupClipContainer(std::optional<qreal> zValue) void SelectZone::setupClipContainer(std::optional<qreal> zValue)
{ {
if (cardClipContainer) if (cardClipContainer) {
return; return;
}
setFlag(QGraphicsItem::ItemClipsChildrenToShape, false); setFlag(QGraphicsItem::ItemClipsChildrenToShape, false);
@ -209,15 +214,19 @@ void SelectZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{ {
if (event->buttons().testFlag(Qt::LeftButton)) { if (event->buttons().testFlag(Qt::LeftButton)) {
QPointF pos = event->pos(); QPointF pos = event->pos();
if (pos.x() < 0) if (pos.x() < 0) {
pos.setX(0); pos.setX(0);
}
QRectF br = boundingRect(); QRectF br = boundingRect();
if (pos.x() > br.width()) if (pos.x() > br.width()) {
pos.setX(br.width()); pos.setX(br.width());
if (pos.y() < 0) }
if (pos.y() < 0) {
pos.setY(0); pos.setY(0);
if (pos.y() > br.height()) }
if (pos.y() > br.height()) {
pos.setY(br.height()); pos.setY(br.height());
}
QRectF selectionRect = QRectF(selectionOrigin, pos).normalized(); QRectF selectionRect = QRectF(selectionOrigin, pos).normalized();
for (auto card : getLogic()->getCards()) { for (auto card : getLogic()->getCards()) {
@ -253,8 +262,9 @@ void SelectZone::mousePressEvent(QGraphicsSceneMouseEvent *event)
selectionOrigin = event->pos(); selectionOrigin = event->pos();
static_cast<GameScene *>(scene())->startRubberBand(event->scenePos()); static_cast<GameScene *>(scene())->startRubberBand(event->scenePos());
event->accept(); event->accept();
} else } else {
CardZone::mousePressEvent(event); CardZone::mousePressEvent(event);
}
} }
void SelectZone::mouseReleaseEvent(QGraphicsSceneMouseEvent *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 // 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. // 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; qreal separatorY = MARGIN_TOP + 2 * (CardDimensions::HEIGHT + PADDING_Y) - STACKED_CARD_OFFSET_Y / 2;
if (isInverted()) if (isInverted()) {
separatorY = height - separatorY; separatorY = height - separatorY;
}
painter->setPen(QColor(255, 255, 255, 40)); painter->setPen(QColor(255, 255, 255, 40));
painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY)); painter->drawLine(QPointF(0, separatorY), QPointF(width, separatorY));
} }
@ -157,8 +158,9 @@ void TableZone::reorganizeCards()
for (int i = 0; i < getLogic()->getCards().size(); ++i) { for (int i = 0; i < getLogic()->getCards().size(); ++i) {
QPoint gridPoint = getLogic()->getCards()[i]->getGridPos(); QPoint gridPoint = getLogic()->getCards()[i]->getGridPos();
if (gridPoint.x() == -1) if (gridPoint.x() == -1) {
continue; continue;
}
QPointF mapPoint = mapFromGrid(gridPoint); QPointF mapPoint = mapFromGrid(gridPoint);
qreal x = mapPoint.x(); qreal x = mapPoint.x();
@ -167,8 +169,9 @@ void TableZone::reorganizeCards()
int numberAttachedCards = getLogic()->getCards()[i]->getAttachedCards().size(); int numberAttachedCards = getLogic()->getCards()[i]->getAttachedCards().size();
qreal actualX = x + numberAttachedCards * STACKED_CARD_OFFSET_X; qreal actualX = x + numberAttachedCards * STACKED_CARD_OFFSET_X;
qreal actualY = y; qreal actualY = y;
if (numberAttachedCards) if (numberAttachedCards) {
actualY += 15; actualY += 15;
}
getLogic()->getCards()[i]->setPos(actualX, actualY); getLogic()->getCards()[i]->setPos(actualX, actualY);
getLogic()->getCards()[i]->setRealZValue(ZValues::tableCardZValue(actualX, actualY)); getLogic()->getCards()[i]->setRealZValue(ZValues::tableCardZValue(actualX, actualY));
@ -227,16 +230,19 @@ void TableZone::resizeToContents()
int xMax = 0; int xMax = 0;
// Find rightmost card position, which includes the left margin amount. // Find rightmost card position, which includes the left margin amount.
for (int i = 0; i < getLogic()->getCards().size(); ++i) for (int i = 0; i < getLogic()->getCards().size(); ++i) {
if (getLogic()->getCards()[i]->pos().x() > xMax) if (getLogic()->getCards()[i]->pos().x() > xMax) {
xMax = (int)getLogic()->getCards()[i]->pos().x(); xMax = (int)getLogic()->getCards()[i]->pos().x();
}
}
// Minimum width is the rightmost card position plus enough room for // Minimum width is the rightmost card position plus enough room for
// another card with padding, then margin. // another card with padding, then margin.
currentMinimumWidth = xMax + (2 * CardDimensions::WIDTH) + PADDING_X + MARGIN_RIGHT; currentMinimumWidth = xMax + (2 * CardDimensions::WIDTH) + PADDING_X + MARGIN_RIGHT;
if (currentMinimumWidth < MIN_WIDTH) if (currentMinimumWidth < MIN_WIDTH) {
currentMinimumWidth = MIN_WIDTH; currentMinimumWidth = MIN_WIDTH;
}
if (currentMinimumWidth != width) { if (currentMinimumWidth != width) {
prepareGeometryChange(); prepareGeometryChange();
@ -247,9 +253,11 @@ void TableZone::resizeToContents()
CardItem *TableZone::getCardFromGrid(const QPoint &gridPoint) const CardItem *TableZone::getCardFromGrid(const QPoint &gridPoint) const
{ {
for (int i = 0; i < getLogic()->getCards().size(); i++) for (int i = 0; i < getLogic()->getCards().size(); i++) {
if (getLogic()->getCards().at(i)->getGridPoint() == gridPoint) if (getLogic()->getCards().at(i)->getGridPoint() == gridPoint) {
return getLogic()->getCards().at(i); return getLogic()->getCards().at(i);
}
}
return 0; return 0;
} }
@ -266,8 +274,9 @@ void TableZone::computeCardStackWidths()
QMap<int, int> cardStackCount; QMap<int, int> cardStackCount;
for (int i = 0; i < getLogic()->getCards().size(); ++i) { for (int i = 0; i < getLogic()->getCards().size(); ++i) {
const QPoint &gridPoint = getLogic()->getCards()[i]->getGridPos(); const QPoint &gridPoint = getLogic()->getCards()[i]->getGridPos();
if (gridPoint.x() == -1) if (gridPoint.x() == -1) {
continue; continue;
}
const int key = getCardStackMapKey(gridPoint.x() / 3, gridPoint.y()); const int key = getCardStackMapKey(gridPoint.x() / 3, gridPoint.y());
cardStackCount.insert(key, cardStackCount.value(key, 0) + 1); cardStackCount.insert(key, cardStackCount.value(key, 0) + 1);
@ -277,16 +286,18 @@ void TableZone::computeCardStackWidths()
cardStackWidth.clear(); cardStackWidth.clear();
for (int i = 0; i < getLogic()->getCards().size(); ++i) { for (int i = 0; i < getLogic()->getCards().size(); ++i) {
const QPoint &gridPoint = getLogic()->getCards()[i]->getGridPos(); const QPoint &gridPoint = getLogic()->getCards()[i]->getGridPos();
if (gridPoint.x() == -1) if (gridPoint.x() == -1) {
continue; continue;
}
const int key = getCardStackMapKey(gridPoint.x() / 3, gridPoint.y()); const int key = getCardStackMapKey(gridPoint.x() / 3, gridPoint.y());
const int stackCount = cardStackCount.value(key, 0); const int stackCount = cardStackCount.value(key, 0);
if (stackCount == 1) if (stackCount == 1) {
cardStackWidth.insert(key, CardDimensions::WIDTH + getLogic()->getCards()[i]->getAttachedCards().size() * cardStackWidth.insert(key, CardDimensions::WIDTH + getLogic()->getCards()[i]->getAttachedCards().size() *
STACKED_CARD_OFFSET_X); STACKED_CARD_OFFSET_X);
else } else {
cardStackWidth.insert(key, CardDimensions::WIDTH + (stackCount - 1) * STACKED_CARD_OFFSET_X); 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; x += cardStackWidth.value(key, CardDimensions::WIDTH) + PADDING_X;
} }
if (isInverted()) if (isInverted()) {
gridPoint.setY(TABLEROWS - 1 - gridPoint.y()); gridPoint.setY(TABLEROWS - 1 - gridPoint.y());
}
// Start with margin plus stacked card offset // Start with margin plus stacked card offset
y = MARGIN_TOP + (gridPoint.x() % 3) * STACKED_CARD_OFFSET_Y; y = MARGIN_TOP + (gridPoint.x() % 3) * STACKED_CARD_OFFSET_Y;
// Add in card size and padding for each row // 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; y += CardDimensions::HEIGHT + PADDING_Y;
}
return QPointF(x, y); return QPointF(x, y);
} }
@ -330,8 +343,9 @@ QPoint TableZone::mapToGrid(const QPointF &mapPoint) const
gridPointY = clampValidTableRow(gridPointY); gridPointY = clampValidTableRow(gridPointY);
if (isInverted()) if (isInverted()) {
gridPointY = TABLEROWS - 1 - gridPointY; gridPointY = TABLEROWS - 1 - gridPointY;
}
// Calculating the x-coordinate of the grid space requires adding up the // Calculating the x-coordinate of the grid space requires adding up the
// widths of each card stack along the row. // widths of each card stack along the row.
@ -367,19 +381,23 @@ QPointF TableZone::closestGridPoint(const QPointF &point)
{ {
QPoint gridPoint = mapToGrid(point); QPoint gridPoint = mapToGrid(point);
gridPoint.setX((gridPoint.x() / 3) * 3); gridPoint.setX((gridPoint.x() / 3) * 3);
if (getCardFromGrid(gridPoint)) if (getCardFromGrid(gridPoint)) {
gridPoint.setX(gridPoint.x() + 1); gridPoint.setX(gridPoint.x() + 1);
if (getCardFromGrid(gridPoint)) }
if (getCardFromGrid(gridPoint)) {
gridPoint.setX(gridPoint.x() + 1); gridPoint.setX(gridPoint.x() + 1);
}
return mapFromGrid(gridPoint); return mapFromGrid(gridPoint);
} }
int TableZone::clampValidTableRow(const int row) int TableZone::clampValidTableRow(const int row)
{ {
if (row < 0) if (row < 0) {
return 0; return 0;
if (row >= TABLEROWS) }
if (row >= TABLEROWS) {
return TABLEROWS - 1; return TABLEROWS - 1;
}
return row; return row;
} }

View file

@ -203,9 +203,9 @@ ZoneViewZone::GridSize ZoneViewZone::positionCardsForDisplay(CardList &cards, Ca
QString columnProp = extractor(c); QString columnProp = extractor(c);
if (i) { // if not the first card if (i) { // if not the first card
if (columnProp == lastColumnProp) if (columnProp == lastColumnProp) {
row++; // add below current card 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++; col++;
row = 0; row = 0;
} }
@ -233,8 +233,9 @@ ZoneViewZone::GridSize ZoneViewZone::positionCardsForDisplay(CardList &cards, Ca
cols = qCeil((double)cardCount / minRows); cols = qCeil((double)cardCount / minRows);
} }
if (cols < 2) if (cols < 2) {
cols = 2; cols = 2;
}
qCDebug(ViewZoneLog) << "reorganizeCards: rows=" << rows << "cols=" << cols; qCDebug(ViewZoneLog) << "reorganizeCards: rows=" << rows << "cols=" << cols;

View file

@ -252,8 +252,9 @@ void ZoneViewWidget::retranslateUi()
void ZoneViewWidget::stopWindowDrag() void ZoneViewWidget::stopWindowDrag()
{ {
if (!draggingWindow) if (!draggingWindow) {
return; return;
}
draggingWindow = false; draggingWindow = false;
ungrabMouse(); ungrabMouse();
@ -312,13 +313,15 @@ QGraphicsView *ZoneViewWidget::findDragView(QWidget *eventWidget) const
{ {
QWidget *current = eventWidget; QWidget *current = eventWidget;
while (current) { while (current) {
if (auto *view = qobject_cast<QGraphicsView *>(current)) if (auto *view = qobject_cast<QGraphicsView *>(current)) {
return view; return view;
}
current = current->parentWidget(); current = current->parentWidget();
} }
if (scene() && !scene()->views().isEmpty()) if (scene() && !scene()->views().isEmpty()) {
return scene()->views().constFirst(); return scene()->views().constFirst();
}
return nullptr; return nullptr;
} }
@ -346,8 +349,9 @@ bool ZoneViewWidget::windowFrameEvent(QEvent *event)
} }
auto *me = dynamic_cast<QGraphicsSceneMouseEvent *>(event); auto *me = dynamic_cast<QGraphicsSceneMouseEvent *>(event);
if (!me) if (!me) {
return QGraphicsWidget::windowFrameEvent(event); return QGraphicsWidget::windowFrameEvent(event);
}
switch (event->type()) { switch (event->type()) {
case QEvent::GraphicsSceneMousePress: case QEvent::GraphicsSceneMousePress:
@ -506,8 +510,9 @@ void ZoneViewWidget::resizeToZoneContents(bool forceInitialHeight)
zone->setGeometry(QRectF(0, -scrollBar->value(), zoneContainer->size().width(), totalZoneHeight)); zone->setGeometry(QRectF(0, -scrollBar->value(), zoneContainer->size().width(), totalZoneHeight));
if (layout()) if (layout()) {
layout()->invalidate(); layout()->invalidate();
}
} }
void ZoneViewWidget::handleScrollBarChange(int value) void ZoneViewWidget::handleScrollBarChange(int value)
@ -521,8 +526,9 @@ void ZoneViewWidget::closeEvent(QCloseEvent *event)
disconnect(zone, &ZoneViewZone::closed, this, 0); disconnect(zone, &ZoneViewZone::closed, this, 0);
// manually call zone->close in order to remove it from the origZones views // manually call zone->close in order to remove it from the origZones views
zone->close(); zone->close();
if (shuffleCheckBox.isChecked()) if (shuffleCheckBox.isChecked()) {
player->getPlayerActions()->sendGameCommand(Command_Shuffle()); player->getPlayerActions()->sendGameCommand(Command_Shuffle());
}
zoneDeleted(); zoneDeleted();
event->accept(); event->accept();
} }
@ -536,8 +542,9 @@ void ZoneViewWidget::zoneDeleted()
void ZoneViewWidget::initStyleOption(QStyleOption *option) const void ZoneViewWidget::initStyleOption(QStyleOption *option) const
{ {
QStyleOptionTitleBar *titleBar = qstyleoption_cast<QStyleOptionTitleBar *>(option); QStyleOptionTitleBar *titleBar = qstyleoption_cast<QStyleOptionTitleBar *>(option);
if (titleBar) if (titleBar) {
titleBar->icon = QPixmap("theme:cockatrice"); titleBar->icon = QPixmap("theme:cockatrice");
}
} }
/** /**

View file

@ -19,27 +19,29 @@ void AbstractGraphicsItem::paintNumberEllipse(int number,
QFontMetrics fm(font); QFontMetrics fm(font);
double w = 1.3 * fm.horizontalAdvance(numStr); double w = 1.3 * fm.horizontalAdvance(numStr);
double h = fm.height() * 1.3; double h = fm.height() * 1.3;
if (w < h) if (w < h) {
w = h; w = h;
}
painter->setPen(QColor(255, 255, 255, 0)); painter->setPen(QColor(255, 255, 255, 0));
painter->setBrush(QBrush(QColor(color))); painter->setBrush(QBrush(QColor(color)));
QRectF textRect; QRectF textRect;
if (position == -1) if (position == -1) {
textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h); textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h);
else { } else {
qreal xOffset = 10; qreal xOffset = 10;
qreal yOffset = 20; qreal yOffset = 20;
qreal spacing = 2; qreal spacing = 2;
if (position < 2) if (position < 2) {
textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0) textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0)
: (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)),
yOffset, w, h); yOffset, w, h);
else } else {
textRect = QRectF(count == 3 ? ((boundingRect().width() - w) / 2.0) textRect = QRectF(count == 3 ? ((boundingRect().width() - w) / 2.0)
: (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)),
yOffset + (spacing + h) * (position / 2), w, h); yOffset + (spacing + h) * (position / 2), w, h);
}
} }
painter->drawEllipse(textRect); painter->drawEllipse(textRect);

View file

@ -230,8 +230,9 @@ bool CardPictureLoader::hasCustomArt()
QFileInfo dir(it.next()); QFileInfo dir(it.next());
#endif #endif
if (it.fileName() == "downloadedPics") if (it.fileName() == "downloadedPics") {
continue; continue;
}
QDirIterator subIt(it.filePath(), QDir::Files, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks); QDirIterator subIt(it.filePath(), QDir::Files, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);
if (subIt.hasNext()) { if (subIt.hasNext()) {

View file

@ -63,8 +63,9 @@ static PrintingInfo findPrintingForSet(const ExactCard &card, const QString &set
{ {
SetToPrintingsMap setsToPrintings = card.getInfo().getSets(); SetToPrintingsMap setsToPrintings = card.getInfo().getSets();
if (!setsToPrintings.contains(setName)) if (!setsToPrintings.contains(setName)) {
return PrintingInfo(); return PrintingInfo();
}
for (const auto &printing : setsToPrintings[setName]) { for (const auto &printing : setsToPrintings[setName]) {
if (printing.getUuid() == card.getPrinting().getUuid()) { if (printing.getUuid() == card.getPrinting().getUuid()) {

View file

@ -6,29 +6,33 @@ bool KeySignals::eventFilter(QObject * /*object*/, QEvent *event)
{ {
QKeyEvent *kevent; QKeyEvent *kevent;
if (event->type() != QEvent::KeyPress) if (event->type() != QEvent::KeyPress) {
return false; return false;
}
kevent = static_cast<QKeyEvent *>(event); kevent = static_cast<QKeyEvent *>(event);
switch (kevent->key()) { switch (kevent->key()) {
case Qt::Key_Return: case Qt::Key_Return:
case Qt::Key_Enter: 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(); emit onCtrlAltEnter();
else if (kevent->modifiers() & Qt::ControlModifier) } else if (kevent->modifiers() & Qt::ControlModifier) {
emit onCtrlEnter(); emit onCtrlEnter();
else } else {
emit onEnter(); emit onEnter();
}
break; break;
case Qt::Key_Right: case Qt::Key_Right:
if (kevent->modifiers() & Qt::ShiftModifier) if (kevent->modifiers() & Qt::ShiftModifier) {
emit onShiftRight(); emit onShiftRight();
}
break; break;
case Qt::Key_Left: case Qt::Key_Left:
if (kevent->modifiers() & Qt::ShiftModifier) if (kevent->modifiers() & Qt::ShiftModifier) {
emit onShiftLeft(); emit onShiftLeft();
}
break; break;
case Qt::Key_Delete: case Qt::Key_Delete:
@ -37,33 +41,39 @@ bool KeySignals::eventFilter(QObject * /*object*/, QEvent *event)
break; break;
case Qt::Key_Minus: 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(); emit onCtrlAltMinus();
}
break; break;
case Qt::Key_Equal: 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(); emit onCtrlAltEqual();
}
break; break;
case Qt::Key_BracketLeft: 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(); emit onCtrlAltLBracket();
}
break; break;
case Qt::Key_BracketRight: 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(); emit onCtrlAltRBracket();
}
break; break;
case Qt::Key_S: case Qt::Key_S:
if (kevent->modifiers() & Qt::ShiftModifier) if (kevent->modifiers() & Qt::ShiftModifier) {
emit onShiftS(); emit onShiftS();
}
break; break;
case Qt::Key_C: case Qt::Key_C:
if (kevent->modifiers() & Qt::ControlModifier) if (kevent->modifiers() & Qt::ControlModifier) {
emit onCtrlC(); emit onCtrlC();
}
break; break;
default: default:

View file

@ -66,8 +66,9 @@ void Logger::openLogfileSession()
void Logger::closeLogfileSession() void Logger::closeLogfileSession()
{ {
if (!logToFileEnabled) if (!logToFileEnabled) {
return; return;
}
logToFileEnabled = false; logToFileEnabled = false;
fileStream << "Log session closed at " << QDateTime::currentDateTime().toString() << Qt::endl; 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) QPixmap PhasePixmapGenerator::generatePixmap(int height, QString name)
{ {
QString key = name + QString::number(height); QString key = name + QString::number(height);
if (pmCache.contains(key)) if (pmCache.contains(key)) {
return pmCache.value(key); return pmCache.value(key);
}
QPixmap pixmap = tryLoadImage("theme:phases/" + name, QSize(height, height)); QPixmap pixmap = tryLoadImage("theme:phases/" + name, QSize(height, height));
@ -95,19 +96,22 @@ QPixmap CounterPixmapGenerator::generatePixmap(int height, QString name, bool hi
name = "general"; name = "general";
} }
if (highlight) if (highlight) {
name.append("_highlight"); name.append("_highlight");
}
QString key = name + QString::number(height); QString key = name + QString::number(height);
if (pmCache.contains(key)) if (pmCache.contains(key)) {
return pmCache.value(key); return pmCache.value(key);
}
QPixmap pixmap = tryLoadImage("theme:counters/" + name, QSize(height, height)); QPixmap pixmap = tryLoadImage("theme:counters/" + name, QSize(height, height));
// fall back to colorless counter if the name can't be found // fall back to colorless counter if the name can't be found
if (pixmap.isNull()) { if (pixmap.isNull()) {
name = "general"; name = "general";
if (highlight) if (highlight) {
name.append("_highlight"); name.append("_highlight");
}
pixmap = tryLoadImage("theme:counters/" + name, QSize(height, height)); 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) QPixmap PingPixmapGenerator::generatePixmap(int size, int value, int max)
{ {
int key = size * 1000000 + max * 1000 + value; int key = size * 1000000 + max * 1000 + value;
if (pmCache.contains(key)) if (pmCache.contains(key)) {
return pmCache.value(key); return pmCache.value(key);
}
QPixmap pixmap(size, size); QPixmap pixmap(size, size);
pixmap.fill(Qt::transparent); pixmap.fill(Qt::transparent);
QPainter painter(&pixmap); QPainter painter(&pixmap);
QColor color; QColor color;
if ((max == -1) || (value == -1)) if ((max == -1) || (value == -1)) {
color = Qt::black; color = Qt::black;
else } else {
color.setHsv(120 * (1.0 - ((double)value / max)), 255, 255); color.setHsv(120 * (1.0 - ((double)value / max)), 255, 255);
}
QRadialGradient g(QPointF((double)pixmap.width() / 2, (double)pixmap.height() / 2), QRadialGradient g(QPointF((double)pixmap.width() / 2, (double)pixmap.height() / 2),
qMin(pixmap.width(), pixmap.height()) / 2.0); qMin(pixmap.width(), pixmap.height()) / 2.0);
@ -145,11 +151,13 @@ QMap<int, QPixmap> PingPixmapGenerator::pmCache;
QPixmap CountryPixmapGenerator::generatePixmap(int height, const QString &countryCode) QPixmap CountryPixmapGenerator::generatePixmap(int height, const QString &countryCode)
{ {
if (countryCode.size() != 2) if (countryCode.size() != 2) {
return QPixmap(); return QPixmap();
}
QString key = countryCode + QString::number(height); QString key = countryCode + QString::number(height);
if (pmCache.contains(key)) if (pmCache.contains(key)) {
return pmCache.value(key); return pmCache.value(key);
}
int width = height * 2; int width = height * 2;
QPixmap pixmap = tryLoadImage("theme:countries/" + countryCode.toLower(), QSize(width, height), true); QPixmap pixmap = tryLoadImage("theme:countries/" + countryCode.toLower(), QSize(width, height), true);
@ -352,8 +360,9 @@ QPixmap LockPixmapGenerator::generatePixmap(int height)
{ {
int key = height; int key = height;
if (pmCache.contains(key)) if (pmCache.contains(key)) {
return pmCache.value(key); return pmCache.value(key);
}
QPixmap pixmap = tryLoadImage("theme:icons/lock", QSize(height, height), true); QPixmap pixmap = tryLoadImage("theme:icons/lock", QSize(height, height), true);
pmCache.insert(key, pixmap); pmCache.insert(key, pixmap);
@ -365,8 +374,9 @@ QMap<int, QPixmap> LockPixmapGenerator::pmCache;
QPixmap DropdownIconPixmapGenerator::generatePixmap(int height, bool expanded) QPixmap DropdownIconPixmapGenerator::generatePixmap(int height, bool expanded)
{ {
QString key = QString::number(expanded) + ":" + QString::number(height); QString key = QString::number(expanded) + ":" + QString::number(height);
if (pmCache.contains(key)) if (pmCache.contains(key)) {
return pmCache.value(key); return pmCache.value(key);
}
QString name = expanded ? "dropdown_expanded" : "dropdown_collapsed"; QString name = expanded ? "dropdown_expanded" : "dropdown_collapsed";
QPixmap pixmap = tryLoadImage("theme:icons/" + name, QSize(height, height), true); 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) // Iterate through all color roles (excluding NoRole and NColorRoles)
for (int r = 0; r < QPalette::NColorRoles; ++r) { for (int r = 0; r < QPalette::NColorRoles; ++r) {
auto role = static_cast<QPalette::ColorRole>(r); auto role = static_cast<QPalette::ColorRole>(r);
if (role == QPalette::NoRole) if (role == QPalette::NoRole) {
continue; continue;
}
PaletteColorInfo info; PaletteColorInfo info;
info.group = group; info.group = group;
@ -78,8 +79,9 @@ struct PaletteColorInfo
for (int r = 0; r < QPalette::NColorRoles; ++r) { for (int r = 0; r < QPalette::NColorRoles; ++r) {
auto role = static_cast<QPalette::ColorRole>(r); auto role = static_cast<QPalette::ColorRole>(r);
if (role == QPalette::NoRole) if (role == QPalette::NoRole) {
continue; continue;
}
QColor color = palette.color(group, role); QColor color = palette.color(group, role);
qInfo().nospace() << qPrintable(QString("%1").arg(roleEnum.valueToKey(role), -20)) << " : " 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 (auto &range : deselected) {
for (int row = range.top(); row <= range.bottom(); ++row) { for (int row = range.top(); row <= range.bottom(); ++row) {
QModelIndex idx = range.model()->index(row, 0, range.parent()); QModelIndex idx = range.model()->index(row, 0, range.parent());
if (proxyModel) if (proxyModel) {
idx = proxyModel->mapToSource(idx); idx = proxyModel->mapToSource(idx);
}
auto it = indexToWidgetMap.find(QPersistentModelIndex(idx)); auto it = indexToWidgetMap.find(QPersistentModelIndex(idx));
if (it != indexToWidgetMap.end()) { if (it != indexToWidgetMap.end()) {

View file

@ -43,11 +43,13 @@ CardInfoDisplayWidget::CardInfoDisplayWidget(const CardRef &cardRef, QWidget *pa
void CardInfoDisplayWidget::setCard(const ExactCard &card) void CardInfoDisplayWidget::setCard(const ExactCard &card)
{ {
if (exactCard) if (exactCard) {
disconnect(exactCard.getCardPtr().data(), nullptr, this, nullptr); disconnect(exactCard.getCardPtr().data(), nullptr, this, nullptr);
}
exactCard = card; exactCard = card;
if (exactCard) if (exactCard) {
connect(exactCard.getCardPtr().data(), &QObject::destroyed, this, &CardInfoDisplayWidget::clear); connect(exactCard.getCardPtr().data(), &QObject::destroyed, this, &CardInfoDisplayWidget::clear);
}
text->setCard(exactCard); text->setCard(exactCard);
pic->setCard(exactCard); pic->setCard(exactCard);

View file

@ -73,8 +73,9 @@ void CardInfoTextWidget::setCard(const ExactCard &exactCard)
QStringList cardProps = card->getProperties(); QStringList cardProps = card->getProperties();
for (const QString &key : cardProps) { for (const QString &key : cardProps) {
if (key.contains("-")) if (key.contains("-")) {
continue; continue;
}
QString keyText = Mtg::getNicePropertyName(key).toHtmlEscaped() + ":"; QString keyText = Mtg::getNicePropertyName(key).toHtmlEscaped() + ":";
text += text +=
QString("<tr><td>%1</td><td></td><td>%2</td></tr>").arg(keyText, card->getProperty(key).toHtmlEscaped()); 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 AnalyticsPanelWidgetFactory::create(const QString &type, QWidget *parent, DeckListStatisticsAnalyzer *analyzer) const
{ {
auto it = widgets.find(type); auto it = widgets.find(type);
if (it == widgets.end()) if (it == widgets.end()) {
return nullptr; return nullptr;
}
auto w = it->creator(parent, analyzer); auto w = it->creator(parent, analyzer);

View file

@ -28,8 +28,9 @@ ManaBaseConfigDialog::ManaBaseConfigDialog(DeckListStatisticsAnalyzer *analyzer,
// select initial filters // select initial filters
for (int i = 0; i < filterList->count(); ++i) { 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); filterList->item(i)->setSelected(true);
}
} }
buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this); buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);

View file

@ -69,8 +69,9 @@ void ManaCurveConfigDialog::setFromConfig(const ManaCurveConfig &cfg)
{ {
groupBy->setCurrentText(cfg.groupBy); groupBy->setCurrentText(cfg.groupBy);
// restore filters // 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())); filterList->item(i)->setSelected(cfg.filters.contains(filterList->item(i)->text()));
}
showMain->setChecked(cfg.showMain); showMain->setChecked(cfg.showMain);
showCatRows->setChecked(cfg.showCategoryRows); showCatRows->setChecked(cfg.showCategoryRows);
@ -81,8 +82,9 @@ void ManaCurveConfigDialog::accept()
cfg.groupBy = groupBy->currentText(); cfg.groupBy = groupBy->currentText();
cfg.filters.clear(); cfg.filters.clear();
for (auto *item : filterList->selectedItems()) for (auto *item : filterList->selectedItems()) {
cfg.filters << item->text(); cfg.filters << item->text();
}
cfg.showMain = showMain->isChecked(); cfg.showMain = showMain->isChecked();
cfg.showCategoryRows = showCatRows->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) { for (auto it = cmcIt->cbegin(); it != cmcIt->cend(); ++it) {
const QString &category = it.key(); const QString &category = it.key();
if (!config.filters.isEmpty() && !config.filters.contains(category)) if (!config.filters.isEmpty() && !config.filters.contains(category)) {
continue; continue;
}
const int value = it.value(); const int value = it.value();
QStringList cards; QStringList cards;
const auto catIt = cardsMap.constFind(category); const auto catIt = cardsMap.constFind(category);
if (catIt != cardsMap.cend()) if (catIt != cardsMap.cend()) {
cards = catIt->value(cmc); cards = catIt->value(cmc);
}
segments.push_back({category, value, cards, GameSpecificColors::MTG::colorHelper(category)}); 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 QString &category = catIt.key();
const auto &countsByCmc = catIt.value(); 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(); outCmcMap[it.key()][category] = it.value();
}
} }
for (auto catIt = categoryCards.cbegin(); catIt != categoryCards.cend(); ++catIt) { for (auto catIt = categoryCards.cbegin(); catIt != categoryCards.cend(); ++catIt) {
const QString &category = catIt.key(); const QString &category = catIt.key();
const auto &cardsByCmc = catIt.value(); 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(); outCardsMap[category][it.key()] = it.value();
}
} }
} }
@ -88,8 +90,9 @@ static void findGlobalCmcRange(const QHash<QString, QHash<int, int>> &categoryCo
maxCmc = 0; maxCmc = 0;
for (const auto &countsByCmc : categoryCounts) { 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()); maxCmc = qMax(maxCmc, it.key());
}
} }
} }

View file

@ -26,8 +26,9 @@ ManaDevotionConfigDialog::ManaDevotionConfigDialog(DeckListStatisticsAnalyzer *a
// select initial filters // select initial filters
for (int i = 0; i < filterList->count(); ++i) { 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); filterList->item(i)->setSelected(true);
}
} }
buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this); buttons = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);

View file

@ -24,8 +24,9 @@ ManaDistributionConfig ManaDistributionConfig::fromJson(const QJsonObject &o)
if (o.contains("filters")) { if (o.contains("filters")) {
config.filters.clear(); config.filters.clear();
for (auto v : o["filters"].toArray()) for (auto v : o["filters"].toArray()) {
config.filters << v.toString(); config.filters << v.toString();
}
} }
if (o.contains("showColorRows")) { if (o.contains("showColorRows")) {

View file

@ -62,8 +62,9 @@ void ManaDistributionConfigDialog::setFromConfig(const ManaDistributionConfig &c
displayType->setCurrentText(cfg.displayType); 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())); filterList->item(i)->setSelected(cfg.filters.contains(filterList->item(i)->text()));
}
showColorRows->setChecked(cfg.showColorRows); showColorRows->setChecked(cfg.showColorRows);
} }
@ -74,8 +75,9 @@ void ManaDistributionConfigDialog::accept()
// Filters // Filters
cfg.filters.clear(); cfg.filters.clear();
for (auto *item : filterList->selectedItems()) for (auto *item : filterList->selectedItems()) {
cfg.filters << item->text(); cfg.filters << item->text();
}
cfg.showColorRows = showColorRows->isChecked(); 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 { auto choose = [](int n, int r) -> double {
if (r > n) if (r > n) {
return 0.0; return 0.0;
if (r == 0 || r == n) }
if (r == 0 || r == n) {
return 1.0; return 1.0;
}
double res = 1.0; double res = 1.0;
for (int i = 1; i <= r; ++i) { for (int i = 1; i <= r; ++i) {
res *= (n - r + i); res *= (n - r + i);

View file

@ -121,9 +121,10 @@ void DeckEditorDatabaseDisplayWidget::updateSearch(const QString &search)
{ {
databaseDisplayModel->setStringFilter(search); databaseDisplayModel->setStringFilter(search);
QModelIndexList sel = databaseView->selectionModel()->selectedRows(); QModelIndexList sel = databaseView->selectionModel()->selectedRows();
if (sel.isEmpty() && databaseDisplayModel->rowCount()) if (sel.isEmpty() && databaseDisplayModel->rowCount()) {
databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0), databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0),
QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows);
}
} }
void DeckEditorDatabaseDisplayWidget::clearAllDatabaseFilters() void DeckEditorDatabaseDisplayWidget::clearAllDatabaseFilters()

View file

@ -314,8 +314,9 @@ void DeckEditorDeckDockWidget::initializeFormats()
ExactCard DeckEditorDeckDockWidget::getCurrentCard() ExactCard DeckEditorDeckDockWidget::getCurrentCard()
{ {
QModelIndex current = deckView->selectionModel()->currentIndex(); QModelIndex current = deckView->selectionModel()->currentIndex();
if (!current.isValid()) if (!current.isValid()) {
return {}; return {};
}
const QString cardName = current.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString(); const QString cardName = current.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString();
const QString cardProviderID = current.siblingAtColumn(DeckListModelColumns::CARD_PROVIDER_ID).data().toString(); const QString cardProviderID = current.siblingAtColumn(DeckListModelColumns::CARD_PROVIDER_ID).data().toString();
const QModelIndex gparent = current.parent().parent(); const QModelIndex gparent = current.parent().parent();
@ -651,10 +652,12 @@ void DeckEditorDeckDockWidget::actSwapSelection()
void DeckEditorDeckDockWidget::actDecrementCard(const ExactCard &card, QString zoneName) void DeckEditorDeckDockWidget::actDecrementCard(const ExactCard &card, QString zoneName)
{ {
if (!card) if (!card) {
return; return;
if (card.getInfo().getIsToken()) }
if (card.getInfo().getIsToken()) {
zoneName = DECK_ZONE_TOKENS; zoneName = DECK_ZONE_TOKENS;
}
deckStateManager->decrementCard(card, zoneName); deckStateManager->decrementCard(card, zoneName);
} }

View file

@ -89,8 +89,9 @@ void DeckEditorFilterDockWidget::filterViewCustomContextMenu(const QPoint &point
QModelIndex idx; QModelIndex idx;
idx = filterView->indexAt(point); idx = filterView->indexAt(point);
if (!idx.isValid()) if (!idx.isValid()) {
return; return;
}
action = menu.addAction(QString("delete")); action = menu.addAction(QString("delete"));
action->setData(point); action->setData(point);
@ -105,8 +106,9 @@ void DeckEditorFilterDockWidget::filterRemove(const QAction *action)
point = action->data().toPoint(); point = action->data().toPoint();
idx = filterView->indexAt(point); idx = filterView->indexAt(point);
if (!idx.isValid()) if (!idx.isValid()) {
return; return;
}
filterModel->removeRow(idx.row(), idx.parent()); filterModel->removeRow(idx.row(), idx.parent());
} }

View file

@ -8,8 +8,9 @@
QVariant DeckListStyleProxy::data(const QModelIndex &index, int role) const QVariant DeckListStyleProxy::data(const QModelIndex &index, int role) const
{ {
QModelIndex src = mapToSource(index); QModelIndex src = mapToSource(index);
if (!src.isValid()) if (!src.isValid()) {
return {}; return {};
}
QVariant value = QIdentityProxyModel::data(index, role); 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) QModelIndex DeckStateManager::decrementCard(const ExactCard &card, const QString &zoneName)
{ {
if (!card) if (!card) {
return {}; return {};
}
QString providerId = card.getPrinting().getUuid(); QString providerId = card.getPrinting().getUuid();
QString collectorNumber = card.getPrinting().getProperty("num"); QString collectorNumber = card.getPrinting().getProperty("num");
@ -241,15 +242,17 @@ static bool doSwapCard(DeckListModel *model,
bool DeckStateManager::swapCardAtIndex(const QModelIndex &idx) bool DeckStateManager::swapCardAtIndex(const QModelIndex &idx)
{ {
if (!idx.isValid()) if (!idx.isValid()) {
return false; return false;
}
QString cardName = idx.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString(); QString cardName = idx.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString();
QString providerId = idx.siblingAtColumn(DeckListModelColumns::CARD_PROVIDER_ID).data().toString(); QString providerId = idx.siblingAtColumn(DeckListModelColumns::CARD_PROVIDER_ID).data().toString();
QModelIndex gparent = idx.parent().parent(); QModelIndex gparent = idx.parent().parent();
if (!gparent.isValid()) if (!gparent.isValid()) {
return false; return false;
}
QString zoneName = gparent.siblingAtColumn(DeckListModelColumns::CARD_NAME).data(Qt::EditRole).toString(); QString zoneName = gparent.siblingAtColumn(DeckListModelColumns::CARD_NAME).data(Qt::EditRole).toString();
QString otherZoneName = zoneName == DECK_ZONE_MAIN ? DECK_ZONE_SIDE : DECK_ZONE_MAIN; 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); QStringList _data = uci.getServerInfo(saveName);
if (_data.isEmpty()) { if (_data.isEmpty()) {
_data << "" _data << "" << "" << "" << "" << "" << "" << "";
<< ""
<< ""
<< ""
<< ""
<< ""
<< "";
} }
bool savePasswordStatus = (_data.at(5) == "1"); 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()); spectatorsSeeEverythingCheckBox->setChecked(gameInfo.spectators_omniscient());
QSet<int> types; 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)); types.insert(gameInfo.game_types(i));
}
QMapIterator<int, QString> gameTypeIterator(gameTypes); QMapIterator<int, QString> gameTypeIterator(gameTypes);
while (gameTypeIterator.hasNext()) { while (gameTypeIterator.hasNext()) {
@ -316,9 +317,9 @@ void DlgCreateGame::checkResponse(const Response &response)
{ {
buttonBox->setEnabled(true); buttonBox->setEnabled(true);
if (response.response_code() == Response::RespOk) if (response.response_code() == Response::RespOk) {
accept(); accept();
else { } else {
QMessageBox::critical(this, tr("Error"), tr("Server error.")); QMessageBox::critical(this, tr("Error"), tr("Server error."));
return; return;
} }

View file

@ -95,8 +95,9 @@ void DlgDefaultTagsEditor::addItem()
// Prevent duplicate tags // Prevent duplicate tags
for (int i = 0; i < listWidget->count(); ++i) { for (int i = 0; i < listWidget->count(); ++i) {
QWidget *widget = listWidget->itemWidget(listWidget->item(i)); QWidget *widget = listWidget->itemWidget(listWidget->item(i));
if (!widget) if (!widget) {
continue; continue;
}
QLineEdit *lineEdit = widget->findChild<QLineEdit *>(); QLineEdit *lineEdit = widget->findChild<QLineEdit *>();
if (lineEdit && lineEdit->text() == newTag) { if (lineEdit && lineEdit->text() == newTag) {
QMessageBox::warning(this, tr("Duplicate Tag"), tr("This tag already exists.")); QMessageBox::warning(this, tr("Duplicate Tag"), tr("This tag already exists."));
@ -138,8 +139,9 @@ void DlgDefaultTagsEditor::confirmChanges()
QStringList updatedList; QStringList updatedList;
for (int i = 0; i < listWidget->count(); ++i) { for (int i = 0; i < listWidget->count(); ++i) {
QWidget *widget = listWidget->itemWidget(listWidget->item(i)); QWidget *widget = listWidget->itemWidget(listWidget->item(i));
if (!widget) if (!widget) {
continue; continue;
}
QLineEdit *lineEdit = widget->findChild<QLineEdit *>(); QLineEdit *lineEdit = widget->findChild<QLineEdit *>();
if (lineEdit) { if (lineEdit) {
updatedList.append(lineEdit->text()); updatedList.append(lineEdit->text());

View file

@ -149,8 +149,9 @@ void DlgEditTokens::actAddToken()
QString name; QString name;
for (;;) { for (;;) {
name = getTextWithMax(this, tr("Add token"), tr("Please enter the name of the token:")); name = getTextWithMax(this, tr("Add token"), tr("Please enter the name of the token:"));
if (name.isEmpty()) if (name.isEmpty()) {
return; return;
}
if (databaseModel->getDatabase()->query()->getCardInfo(name)) { if (databaseModel->getDatabase()->query()->getCardInfo(name)) {
QMessageBox::critical(this, tr("Error"), QMessageBox::critical(this, tr("Error"),
tr("The chosen name conflicts with an existing card or token.\nMake sure to enable " 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) void DlgEditTokens::colorChanged(int colorIndex)
{ {
if (currentCard) if (currentCard) {
currentCard->setColors(QString(colorEdit->itemData(colorIndex).toChar())); currentCard->setColors(QString(colorEdit->itemData(colorIndex).toChar()));
}
} }
void DlgEditTokens::ptChanged(const QString &_pt) void DlgEditTokens::ptChanged(const QString &_pt)
{ {
if (currentCard) if (currentCard) {
currentCard->setPowTough(_pt); currentCard->setPowTough(_pt);
}
} }
void DlgEditTokens::annotationChanged(const QString &_annotation) void DlgEditTokens::annotationChanged(const QString &_annotation)
{ {
if (currentCard) if (currentCard) {
currentCard->setText(_annotation); currentCard->setText(_annotation);
}
} }

View file

@ -26,8 +26,9 @@ DlgEditUser::DlgEditUser(QWidget *parent, QString email, QString country, QStrin
int i = 1; int i = 1;
for (const QString &c : countries) { for (const QString &c : countries) {
countryEdit->addItem(QPixmap("theme:countries/" + c.toLower()), c); countryEdit->addItem(QPixmap("theme:countries/" + c.toLower()), c);
if (c == country) if (c == country) {
countryEdit->setCurrentIndex(i); countryEdit->setCurrentIndex(i);
}
++i; ++i;
} }

View file

@ -87,8 +87,9 @@ DlgFilterGames::DlgFilterGames(const QMap<int, QString> &_allGameTypes,
if (!allGameTypes.isEmpty()) { if (!allGameTypes.isEmpty()) {
gameTypeFilterGroupBox = new QGroupBox(tr("&Game types")); gameTypeFilterGroupBox = new QGroupBox(tr("&Game types"));
gameTypeFilterGroupBox->setLayout(gameTypeFilterLayout); gameTypeFilterGroupBox->setLayout(gameTypeFilterLayout);
} else } else {
gameTypeFilterGroupBox = nullptr; gameTypeFilterGroupBox = nullptr;
}
auto *maxPlayersFilterMinLabel = new QLabel(tr("at &least:")); auto *maxPlayersFilterMinLabel = new QLabel(tr("at &least:"));
maxPlayersFilterMinSpinBox = new QSpinBox; maxPlayersFilterMinSpinBox = new QSpinBox;
@ -226,8 +227,9 @@ QSet<int> DlgFilterGames::getGameTypeFilter() const
QMapIterator<int, QCheckBox *> i(gameTypeFilterCheckBoxes); QMapIterator<int, QCheckBox *> i(gameTypeFilterCheckBoxes);
while (i.hasNext()) { while (i.hasNext()) {
i.next(); i.next();
if (i.value()->isChecked()) if (i.value()->isChecked()) {
result.insert(i.key()); result.insert(i.key());
}
} }
return result; return result;
} }

View file

@ -217,8 +217,9 @@ void WndSets::saveHeaderState()
void WndSets::rebuildMainLayout(int actionToTake) void WndSets::rebuildMainLayout(int actionToTake)
{ {
if (mainLayout == nullptr) if (mainLayout == nullptr) {
return; return;
}
switch (actionToTake) { switch (actionToTake) {
case NO_SETS_SELECTED: case NO_SETS_SELECTED:
@ -382,12 +383,14 @@ void WndSets::actUp()
std::sort(rows.begin(), rows.end(), std::less<QModelIndex>()); std::sort(rows.begin(), rows.end(), std::less<QModelIndex>());
QSet<int> newRows; QSet<int> newRows;
if (rows.empty()) if (rows.empty()) {
return; return;
}
for (auto i : rows) { for (auto i : rows) {
if (i.row() <= 0) if (i.row() <= 0) {
continue; continue;
}
int oldRow = displayModel->mapToSource(i).row(); int oldRow = displayModel->mapToSource(i).row();
int newRow = i.row() - 1; 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; }); std::sort(rows.begin(), rows.end(), [](const QModelIndex &a, const QModelIndex &b) { return b < a; });
QSet<int> newRows; QSet<int> newRows;
if (rows.empty()) if (rows.empty()) {
return; return;
}
for (auto i : rows) { for (auto i : rows) {
if (i.row() >= displayModel->rowCount() - 1) if (i.row() >= displayModel->rowCount() - 1) {
continue; continue;
}
int oldRow = displayModel->mapToSource(i).row(); int oldRow = displayModel->mapToSource(i).row();
int newRow = i.row() + 1; int newRow = i.row() + 1;
@ -428,8 +433,9 @@ void WndSets::actTop()
QSet<int> newRows; QSet<int> newRows;
int newRow = 0; int newRow = 0;
if (rows.empty()) if (rows.empty()) {
return; return;
}
for (int i = 0; i < rows.length(); i++) { for (int i = 0; i < rows.length(); i++) {
int oldRow = displayModel->mapToSource(rows.at(i)).row(); int oldRow = displayModel->mapToSource(rows.at(i)).row();
@ -454,8 +460,9 @@ void WndSets::actBottom()
QSet<int> newRows; QSet<int> newRows;
int newRow = model->rowCount() - 1; int newRow = model->rowCount() - 1;
if (rows.empty()) if (rows.empty()) {
return; return;
}
for (int i = 0; i < rows.length(); i++) { for (int i = 0; i < rows.length(); i++) {
int oldRow = displayModel->mapToSource(rows.at(i)).row(); 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->addItem(QPixmap("theme:countries/zw"), "zw");
countryEdit->setCurrentIndex(0); countryEdit->setCurrentIndex(0);
QStringList countries = SettingsCache::instance().getCountries(); QStringList countries = SettingsCache::instance().getCountries();
for (const QString &c : countries) for (const QString &c : countries) {
countryEdit->addItem(QPixmap("theme:countries/" + c.toLower()), c); countryEdit->addItem(QPixmap("theme:countries/" + c.toLower()), c);
}
realnameLabel = new QLabel(tr("Real name:")); realnameLabel = new QLabel(tr("Real name:"));
realnameEdit = new QLineEdit(); realnameEdit = new QLineEdit();

View file

@ -237,8 +237,9 @@ QMap<QString, int> DlgSelectSetForCards::getSetsForCards()
for (auto cardName : cardNames) { for (auto cardName : cardNames) {
CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(cardName); CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(cardName);
if (!infoPtr) if (!infoPtr) {
continue; continue;
}
SetToPrintingsMap setMap = infoPtr->getSets(); SetToPrintingsMap setMap = infoPtr->getSets();
for (auto &setName : setMap.keys()) { for (auto &setName : setMap.keys()) {
@ -359,8 +360,9 @@ QMap<QString, QStringList> DlgSelectSetForCards::getCardsForSets()
for (auto cardName : cardNames) { for (auto cardName : cardNames) {
CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(cardName); CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(cardName);
if (!infoPtr) if (!infoPtr) {
continue; continue;
}
SetToPrintingsMap setMap = infoPtr->getSets(); SetToPrintingsMap setMap = infoPtr->getSets();
for (auto it = setMap.begin(); it != setMap.end(); ++it) { for (auto it = setMap.begin(); it != setMap.end(); ++it) {

View file

@ -272,8 +272,9 @@ QString GeneralSettingsPage::languageName(const QString &lang)
void GeneralSettingsPage::deckPathButtonClicked() void GeneralSettingsPage::deckPathButtonClicked()
{ {
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), deckPathEdit->text()); QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), deckPathEdit->text());
if (path.isEmpty()) if (path.isEmpty()) {
return; return;
}
deckPathEdit->setText(path); deckPathEdit->setText(path);
SettingsCache::instance().setDeckPath(path); SettingsCache::instance().setDeckPath(path);
@ -282,8 +283,9 @@ void GeneralSettingsPage::deckPathButtonClicked()
void GeneralSettingsPage::filtersPathButtonClicked() void GeneralSettingsPage::filtersPathButtonClicked()
{ {
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), filtersPathEdit->text()); QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), filtersPathEdit->text());
if (path.isEmpty()) if (path.isEmpty()) {
return; return;
}
filtersPathEdit->setText(path); filtersPathEdit->setText(path);
SettingsCache::instance().setFiltersPath(path); SettingsCache::instance().setFiltersPath(path);
@ -292,8 +294,9 @@ void GeneralSettingsPage::filtersPathButtonClicked()
void GeneralSettingsPage::replaysPathButtonClicked() void GeneralSettingsPage::replaysPathButtonClicked()
{ {
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), replaysPathEdit->text()); QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), replaysPathEdit->text());
if (path.isEmpty()) if (path.isEmpty()) {
return; return;
}
replaysPathEdit->setText(path); replaysPathEdit->setText(path);
SettingsCache::instance().setReplaysPath(path); SettingsCache::instance().setReplaysPath(path);
@ -302,8 +305,9 @@ void GeneralSettingsPage::replaysPathButtonClicked()
void GeneralSettingsPage::picsPathButtonClicked() void GeneralSettingsPage::picsPathButtonClicked()
{ {
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), picsPathEdit->text()); QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), picsPathEdit->text());
if (path.isEmpty()) if (path.isEmpty()) {
return; return;
}
picsPathEdit->setText(path); picsPathEdit->setText(path);
SettingsCache::instance().setPicsPath(path); SettingsCache::instance().setPicsPath(path);
@ -312,8 +316,9 @@ void GeneralSettingsPage::picsPathButtonClicked()
void GeneralSettingsPage::cardDatabasePathButtonClicked() void GeneralSettingsPage::cardDatabasePathButtonClicked()
{ {
QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), cardDatabasePathEdit->text()); QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), cardDatabasePathEdit->text());
if (path.isEmpty()) if (path.isEmpty()) {
return; return;
}
cardDatabasePathEdit->setText(path); cardDatabasePathEdit->setText(path);
SettingsCache::instance().setCardDatabasePath(path); SettingsCache::instance().setCardDatabasePath(path);
@ -322,8 +327,9 @@ void GeneralSettingsPage::cardDatabasePathButtonClicked()
void GeneralSettingsPage::customCardDatabaseButtonClicked() void GeneralSettingsPage::customCardDatabaseButtonClicked()
{ {
QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), customCardDatabasePathEdit->text()); QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), customCardDatabasePathEdit->text());
if (path.isEmpty()) if (path.isEmpty()) {
return; return;
}
customCardDatabasePathEdit->setText(path); customCardDatabasePathEdit->setText(path);
SettingsCache::instance().setCustomCardDatabasePath(path); SettingsCache::instance().setCustomCardDatabasePath(path);
@ -332,8 +338,9 @@ void GeneralSettingsPage::customCardDatabaseButtonClicked()
void GeneralSettingsPage::tokenDatabasePathButtonClicked() void GeneralSettingsPage::tokenDatabasePathButtonClicked()
{ {
QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), tokenDatabasePathEdit->text()); QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), tokenDatabasePathEdit->text());
if (path.isEmpty()) if (path.isEmpty()) {
return; return;
}
tokenDatabasePathEdit->setText(path); tokenDatabasePathEdit->setText(path);
SettingsCache::instance().setTokenDatabasePath(path); SettingsCache::instance().setTokenDatabasePath(path);
@ -418,8 +425,9 @@ AppearanceSettingsPage::AppearanceSettingsPage()
QStringList themeDirs = themeManager->getAvailableThemes().keys(); QStringList themeDirs = themeManager->getAvailableThemes().keys();
for (int i = 0; i < themeDirs.size(); i++) { for (int i = 0; i < themeDirs.size(); i++) {
themeBox.addItem(themeDirs[i]); themeBox.addItem(themeDirs[i]);
if (themeDirs[i] == themeName) if (themeDirs[i] == themeName) {
themeBox.setCurrentIndex(i); themeBox.setCurrentIndex(i);
}
} }
connect(&themeBox, qOverload<int>(&QComboBox::currentIndexChanged), this, &AppearanceSettingsPage::themeBoxChanged); connect(&themeBox, qOverload<int>(&QComboBox::currentIndexChanged), this, &AppearanceSettingsPage::themeBoxChanged);
@ -560,8 +568,9 @@ AppearanceSettingsPage::AppearanceSettingsPage()
auto &cardCounterSettings = SettingsCache::instance().cardCounters(); auto &cardCounterSettings = SettingsCache::instance().cardCounters();
auto newColor = QColorDialog::getColor(cardCounterSettings.color(index), this); auto newColor = QColorDialog::getColor(cardCounterSettings.color(index), this);
if (!newColor.isValid()) if (!newColor.isValid()) {
return; return;
}
cardCounterSettings.setColor(index, newColor); cardCounterSettings.setColor(index, newColor);
}); });
@ -643,8 +652,9 @@ AppearanceSettingsPage::AppearanceSettingsPage()
void AppearanceSettingsPage::themeBoxChanged(int index) void AppearanceSettingsPage::themeBoxChanged(int index)
{ {
QStringList themeDirs = themeManager->getAvailableThemes().keys(); QStringList themeDirs = themeManager->getAvailableThemes().keys();
if (index >= 0 && index < themeDirs.count()) if (index >= 0 && index < themeDirs.count()) {
SettingsCache::instance().setThemeName(themeDirs.at(index)); SettingsCache::instance().setThemeName(themeDirs.at(index));
}
} }
void AppearanceSettingsPage::openThemeLocation() void AppearanceSettingsPage::openThemeLocation()
@ -1395,8 +1405,9 @@ MessagesSettingsPage::MessagesSettingsPage()
messageList = new QListWidget; messageList = new QListWidget;
int count = SettingsCache::instance().messages().getCount(); 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)); messageList->addItem(SettingsCache::instance().messages().getMessageAt(i));
}
aAdd = new QAction(this); aAdd = new QAction(this);
aAdd->setIcon(QPixmap("theme:icons/increment")); aAdd->setIcon(QPixmap("theme:icons/increment"));
@ -1496,8 +1507,9 @@ void MessagesSettingsPage::updateHighlightPreview()
void MessagesSettingsPage::storeSettings() void MessagesSettingsPage::storeSettings()
{ {
SettingsCache::instance().messages().setCount(messageList->count()); 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()); SettingsCache::instance().messages().setMessageAt(i, messageList->item(i)->text());
}
emit SettingsCache::instance().messages().messageMacrosChanged(); emit SettingsCache::instance().messages().messageMacrosChanged();
} }
@ -1570,8 +1582,9 @@ SoundSettingsPage::SoundSettingsPage()
QStringList themeDirs = soundEngine->getAvailableThemes().keys(); QStringList themeDirs = soundEngine->getAvailableThemes().keys();
for (int i = 0; i < themeDirs.size(); i++) { for (int i = 0; i < themeDirs.size(); i++) {
themeBox.addItem(themeDirs[i]); themeBox.addItem(themeDirs[i]);
if (themeDirs[i] == themeName) if (themeDirs[i] == themeName) {
themeBox.setCurrentIndex(i); themeBox.setCurrentIndex(i);
}
} }
connect(&themeBox, qOverload<int>(&QComboBox::currentIndexChanged), this, &SoundSettingsPage::themeBoxChanged); connect(&themeBox, qOverload<int>(&QComboBox::currentIndexChanged), this, &SoundSettingsPage::themeBoxChanged);
@ -1619,8 +1632,9 @@ SoundSettingsPage::SoundSettingsPage()
void SoundSettingsPage::themeBoxChanged(int index) void SoundSettingsPage::themeBoxChanged(int index)
{ {
QStringList themeDirs = soundEngine->getAvailableThemes().keys(); QStringList themeDirs = soundEngine->getAvailableThemes().keys();
if (index >= 0 && index < themeDirs.count()) if (index >= 0 && index < themeDirs.count()) {
SettingsCache::instance().setSoundThemeName(themeDirs.at(index)); SettingsCache::instance().setSoundThemeName(themeDirs.at(index));
}
} }
void SoundSettingsPage::masterVolumeChanged(int value) void SoundSettingsPage::masterVolumeChanged(int value)
@ -1857,8 +1871,9 @@ void DlgSettings::createIcons()
void DlgSettings::changePage(QListWidgetItem *current, QListWidgetItem *previous) void DlgSettings::changePage(QListWidgetItem *current, QListWidgetItem *previous)
{ {
if (!current) if (!current) {
current = previous; current = previous;
}
pagesWidget->setCurrentIndex(contentsWidget->row(current)); 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?"), "</a>)<br><br>" + tr("Do you want to update now?"),
QMessageBox::Yes | QMessageBox::No); QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes) if (reply == QMessageBox::Yes) {
downloadUpdate(release->getName()); downloadUpdate(release->getName());
}
} else { } else {
QMessageBox::information( QMessageBox::information(
this, tr("Update Available"), this, tr("Update Available"),

View file

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

View file

@ -73,8 +73,9 @@ TipsOfTheDay::~TipsOfTheDay()
QVariant TipsOfTheDay::data(const QModelIndex &index, int /*role*/) const 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(); return QVariant();
}
TipOfTheDay tip = tipList->at(index.row()); TipOfTheDay tip = tipList->at(index.row());
switch (index.column()) { switch (index.column()) {

View file

@ -40,8 +40,9 @@ public:
static QString toId(Type type) static QString toId(Type type)
{ {
for (const auto &e : all()) { for (const auto &e : all()) {
if (e.type == type) if (e.type == type) {
return e.id; return e.id;
}
} }
return {}; return {};
} }
@ -49,8 +50,9 @@ public:
static Type fromId(const QString &id) static Type fromId(const QString &id)
{ {
for (const auto &e : all()) { for (const auto &e : all()) {
if (id == e.id) if (id == e.id) {
return e.type; return e.type;
}
} }
return Theme; // default return Theme; // default
} }
@ -58,8 +60,9 @@ public:
static QString toDisplay(Type type) static QString toDisplay(Type type)
{ {
for (const auto &e : all()) { for (const auto &e : all()) {
if (e.type == type) if (e.type == type) {
return QObject::tr(e.trKey); return QObject::tr(e.trKey);
}
} }
return {}; return {};
} }

View file

@ -52,8 +52,9 @@ void BarChartWidget::paintEvent(QPaintEvent *)
int barAreaWidth = right - left; int barAreaWidth = right - left;
int barCount = bars.size(); int barCount = bars.size();
if (barCount == 0) if (barCount == 0) {
return; return;
}
int spacing = 6; int spacing = 6;
int barWidth = (barAreaWidth - (barCount - 1) * spacing) / barCount; int barWidth = (barAreaWidth - (barCount - 1) * spacing) / barCount;
@ -91,8 +92,9 @@ void BarChartWidget::paintEvent(QPaintEvent *)
for (int j = 0; j < bar.segments.size(); j++) { for (int j = 0; j < bar.segments.size(); j++) {
const auto &seg = bar.segments[j]; const auto &seg = bar.segments[j];
int segHeight = (seg.value * barAreaHeight / highest); int segHeight = (seg.value * barAreaHeight / highest);
if (segHeight < 2 && seg.value > 0) if (segHeight < 2 && seg.value > 0) {
segHeight = 2; segHeight = 2;
}
int topY = yCurrent - segHeight; int topY = yCurrent - segHeight;
@ -189,8 +191,9 @@ void BarChartWidget::mouseMoveEvent(QMouseEvent *e)
for (int i = 0; i < segments.size(); i++) { for (int i = 0; i < segments.size(); i++) {
const auto &seg = segments[i]; const auto &seg = segments[i];
int segHeight = (seg.value * barAreaHeight / highest); int segHeight = (seg.value * barAreaHeight / highest);
if (segHeight < 2 && seg.value > 0) if (segHeight < 2 && seg.value > 0) {
segHeight = 2; segHeight = 2;
}
int topY = yCurrent - segHeight; int topY = yCurrent - segHeight;
int bottomY = yCurrent; int bottomY = yCurrent;

View file

@ -26,16 +26,19 @@ QSize ColorBar::minimumSizeHint() const
void ColorBar::paintEvent(QPaintEvent *) void ColorBar::paintEvent(QPaintEvent *)
{ {
if (colors.isEmpty()) if (colors.isEmpty()) {
return; return;
}
int total = 0; int total = 0;
for (const auto &pair : colors) for (const auto &pair : colors) {
total += pair.second; total += pair.second;
}
// Prevent divide-by-zero // Prevent divide-by-zero
if (total == 0) if (total == 0) {
return; return;
}
QPainter p(this); QPainter p(this);
p.setRenderHint(QPainter::Antialiasing, true); p.setRenderHint(QPainter::Antialiasing, true);
@ -63,8 +66,9 @@ void ColorBar::paintEvent(QPaintEvent *)
int segmentWidth = int(ratio * w); int segmentWidth = int(ratio * w);
// Ensure the segment width is at least 1 to avoid degenerate rectangles // Ensure the segment width is at least 1 to avoid degenerate rectangles
if (segmentWidth < 1) if (segmentWidth < 1) {
segmentWidth = 1; segmentWidth = 1;
}
QColor base = colorFromName(key); QColor base = colorFromName(key);
@ -100,8 +104,9 @@ void ColorBar::leaveEvent(QEvent *)
void ColorBar::mouseMoveEvent(QMouseEvent *event) void ColorBar::mouseMoveEvent(QMouseEvent *event)
{ {
if (!isHovered || colors.isEmpty()) if (!isHovered || colors.isEmpty()) {
return; return;
}
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
int x = int(event->position().x()); int x = int(event->position().x());
@ -112,18 +117,21 @@ void ColorBar::mouseMoveEvent(QMouseEvent *event)
#endif #endif
QString text = tooltipForPosition(x); QString text = tooltipForPosition(x);
if (!text.isEmpty()) if (!text.isEmpty()) {
QToolTip::showText(gp, text, this); QToolTip::showText(gp, text, this);
}
} }
QString ColorBar::tooltipForPosition(int x) const QString ColorBar::tooltipForPosition(int x) const
{ {
int total = 0; int total = 0;
for (const auto &pair : colors) for (const auto &pair : colors) {
total += pair.second; total += pair.second;
}
if (total == 0) if (total == 0) {
return {}; return {};
}
int pos = 0; int pos = 0;
@ -149,12 +157,14 @@ QColor ColorBar::colorFromName(const QString &name) const
{"W", QColor(235, 235, 230)}, {"B", QColor(30, 30, 30)}, {"W", QColor(235, 235, 230)}, {"B", QColor(30, 30, 30)},
}; };
if (map.contains(name)) if (map.contains(name)) {
return map[name]; return map[name];
}
QColor c(name); QColor c(name);
if (!c.isValid()) if (!c.isValid()) {
c = Qt::gray; c = Qt::gray;
}
return c; return c;
} }

View file

@ -44,8 +44,9 @@ void SegmentedBarWidget::paintEvent(QPaintEvent *)
const auto &seg = segments[i]; const auto &seg = segments[i];
int segHeight = total > 0 ? (seg.value * barHeight / total) : 0; int segHeight = total > 0 ? (seg.value * barHeight / total) : 0;
if (segHeight < 2) if (segHeight < 2) {
segHeight = 2; segHeight = 2;
}
QRect r(barX, yCurrent - segHeight, barWidth, segHeight); QRect r(barX, yCurrent - segHeight, barWidth, segHeight);
bool isTop = (i == segments.size() - 1); bool isTop = (i == segments.size() - 1);
@ -110,8 +111,9 @@ int SegmentedBarWidget::segmentAt(int y) const
int top = currentTop - segHeight; int top = currentTop - segHeight;
int bottom = currentTop; int bottom = currentTop;
if (y >= top && y <= bottom) if (y >= top && y <= bottom) {
return i; return i;
}
currentTop -= segHeight; currentTop -= segHeight;
} }

View file

@ -157,8 +157,9 @@ QString ColorPie::tooltipForPoint(const QPoint &pt) const
QPointF v = pt - center; QPointF v = pt - center;
double distance = std::hypot(v.x(), v.y()); double distance = std::hypot(v.x(), v.y());
if (distance > size / 2.0) if (distance > size / 2.0) {
return {}; return {};
}
double angle = std::atan2(-v.y(), v.x()) * 180.0 / M_PI; double angle = std::atan2(-v.y(), v.x()) * 180.0 / M_PI;
if (angle < 0) { if (angle < 0) {

View file

@ -139,8 +139,9 @@ void HomeWidget::updateRandomCard()
} }
break; break;
} }
if (!newCard) if (!newCard) {
return; return;
}
connect(newCard.getCardPtr().data(), &CardInfo::pixmapUpdated, this, &HomeWidget::updateBackgroundProperties); connect(newCard.getCardPtr().data(), &CardInfo::pixmapUpdated, this, &HomeWidget::updateBackgroundProperties);
backgroundSourceCard->setCard(newCard); backgroundSourceCard->setCard(newCard);

View file

@ -147,8 +147,9 @@ void PrintingSelectorCardOverlayWidget::updateVisibility()
*/ */
void PrintingSelectorCardOverlayWidget::updatePinBadgeVisibility() void PrintingSelectorCardOverlayWidget::updatePinBadgeVisibility()
{ {
if (!pinBadge || !cardInfoPicture) if (!pinBadge || !cardInfoPicture) {
return; return;
}
// Query the persisted preference override to decide whether this printing is pinned. // Query the persisted preference override to decide whether this printing is pinned.
const auto &preferredProviderId = const auto &preferredProviderId =

View file

@ -19,16 +19,19 @@ ReplayManager::ReplayManager(TabGame *parent, GameReplay *_replay)
const int eventCount = replay->event_list_size(); const int eventCount = replay->event_list_size();
for (int i = 0; i < eventCount; ++i) { for (int i = 0; i < eventCount; ++i) {
int j = i + 1; 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; ++j;
}
const int numberEventsThisSecond = j - i; 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 + replayTimeline.append(replay->event_list(i + k).seconds_elapsed() * 1000 +
(int)((qreal)k / (qreal)numberEventsThisSecond * 1000)); (int)((qreal)k / (qreal)numberEventsThisSecond * 1000));
}
if (j < eventCount) if (j < eventCount) {
lastEventTimestamp = replay->event_list(j).seconds_elapsed(); lastEventTimestamp = replay->event_list(j).seconds_elapsed();
}
i += numberEventsThisSecond - 1; i += numberEventsThisSecond - 1;
} }
} }

View file

@ -27,20 +27,23 @@ void ReplayTimelineWidget::setTimeline(const QList<int> &_replayTimeline)
for (int i : replayTimeline) { for (int i : replayTimeline) {
if (i > binEndTime) { if (i > binEndTime) {
histogram.append(binValue); histogram.append(binValue);
if (binValue > maxBinValue) if (binValue > maxBinValue) {
maxBinValue = binValue; maxBinValue = binValue;
}
while (i > binEndTime + BIN_LENGTH) { while (i > binEndTime + BIN_LENGTH) {
histogram.append(0); histogram.append(0);
binEndTime += BIN_LENGTH; binEndTime += BIN_LENGTH;
} }
binValue = 1; binValue = 1;
binEndTime += BIN_LENGTH; binEndTime += BIN_LENGTH;
} else } else {
++binValue; ++binValue;
}
} }
histogram.append(binValue); histogram.append(binValue);
if (!replayTimeline.isEmpty()) if (!replayTimeline.isEmpty()) {
maxTime = replayTimeline.last(); maxTime = replayTimeline.last();
}
update(); update();
} }
@ -53,8 +56,9 @@ void ReplayTimelineWidget::paintEvent(QPaintEvent * /* event */)
qreal binWidth = (qreal)width() / histogram.size(); qreal binWidth = (qreal)width() / histogram.size();
QPainterPath path; QPainterPath path;
path.moveTo(0, height() - 1); 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(qRound(i * binWidth), (height() - 1) * (1.0 - (qreal)histogram[i] / maxBinValue));
}
path.lineTo(width() - 1, height() - 1); path.lineTo(width() - 1, height() - 1);
path.lineTo(0, height() - 1); path.lineTo(0, height() - 1);
painter.fillPath(path, Qt::black); painter.fillPath(path, Qt::black);
@ -142,8 +146,9 @@ void ReplayTimelineWidget::replayTimerTimeout()
processNewEvents(NORMAL_PLAYBACK); processNewEvents(NORMAL_PLAYBACK);
if (!(currentVisualTime % 1000)) if (!(currentVisualTime % 1000)) {
update(); update();
}
} }
/// Processes all unprocessed events up to the current time. /// Processes all unprocessed events up to the current time.
@ -156,12 +161,14 @@ void ReplayTimelineWidget::processNewEvents(PlaybackMode playbackMode)
// backwards skip => always skip reveal windows // backwards skip => always skip reveal windows
// forwards skip => skip reveal windows that don't happen within a big skip of the target // 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; options |= SKIP_REVEAL_WINDOW;
}
// backwards skip => always skip tap animation // backwards skip => always skip tap animation
if (playbackMode == BACKWARD_SKIP) if (playbackMode == BACKWARD_SKIP) {
options |= SKIP_TAP_ANIMATION; options |= SKIP_TAP_ANIMATION;
}
emit processNextEvent(options); emit processNextEvent(options);
++currentEvent; ++currentEvent;

View file

@ -88,10 +88,11 @@ void ChatView::refreshBlockColors()
for (QTextBlock block = doc->begin(); block.isValid(); block = block.next()) { for (QTextBlock block = doc->begin(); block.isValid(); block = block.next()) {
QTextBlockFormat fmt = block.blockFormat(); QTextBlockFormat fmt = block.blockFormat();
if (even) if (even) {
fmt.setBackground(palette().base()); fmt.setBackground(palette().base());
else } else {
fmt.setBackground(palette().window()); fmt.setBackground(palette().window());
}
fmt.setForeground(palette().text()); fmt.setForeground(palette().text());
@ -121,10 +122,11 @@ QTextCursor ChatView::prepareBlock(bool same)
cursor.insertHtml("<br>"); cursor.insertHtml("<br>");
} else { } else {
QTextBlockFormat blockFormat; QTextBlockFormat blockFormat;
if (evenNumber) if (evenNumber) {
blockFormat.setBackground(palette().base()); blockFormat.setBackground(palette().base());
else } else {
blockFormat.setBackground(palette().window()); blockFormat.setBackground(palette().window());
}
evenNumber = !evenNumber; evenNumber = !evenNumber;
@ -144,8 +146,9 @@ void ChatView::appendHtml(const QString &html)
{ {
bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum();
prepareBlock().insertHtml(html); prepareBlock().insertHtml(html);
if (atBottom) if (atBottom) {
verticalScrollBar()->setValue(verticalScrollBar()->maximum()); verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
} }
void ChatView::appendHtmlServerMessage(const QString &html, bool optionalIsBold, QString optionalFontColor) 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()) + ">" + "<font color=" + ((optionalFontColor.size() > 0) ? optionalFontColor : serverMessageColor.name()) + ">" +
QDateTime::currentDateTime().toString("[hh:mm:ss] ") + html + "</font>"; QDateTime::currentDateTime().toString("[hh:mm:ss] ") + html + "</font>";
if (optionalIsBold) if (optionalIsBold) {
htmlText = "<b>" + htmlText + "</b>"; htmlText = "<b>" + htmlText + "</b>";
}
prepareBlock().insertHtml(htmlText); prepareBlock().insertHtml(htmlText);
if (atBottom) if (atBottom) {
verticalScrollBar()->setValue(verticalScrollBar()->maximum()); verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
} }
void ChatView::appendCardTag(QTextCursor &cursor, const QString &cardName) 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) void ChatView::appendUrlTag(QTextCursor &cursor, QString url)
{ {
if (!url.contains("://")) if (!url.contains("://")) {
url.prepend("https://"); url.prepend("https://");
}
QTextCharFormat oldFormat = cursor.charFormat(); QTextCharFormat oldFormat = cursor.charFormat();
QTextCharFormat anchorFormat = oldFormat; QTextCharFormat anchorFormat = oldFormat;
@ -317,8 +323,9 @@ void ChatView::appendMessage(QString message,
} }
} }
if (atBottom) if (atBottom) {
verticalScrollBar()->setValue(verticalScrollBar()->maximum()); verticalScrollBar()->setValue(verticalScrollBar()->maximum());
}
} }
void ChatView::checkTag(QTextCursor &cursor, QString &message) void ChatView::checkTag(QTextCursor &cursor, QString &message)
@ -327,10 +334,11 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message)
message = message.mid(6); message = message.mid(6);
int closeTagIndex = message.indexOf("[/card]"); int closeTagIndex = message.indexOf("[/card]");
QString cardName = message.left(closeTagIndex); QString cardName = message.left(closeTagIndex);
if (closeTagIndex == -1) if (closeTagIndex == -1) {
message.clear(); message.clear();
else } else {
message = message.mid(closeTagIndex + 7); message = message.mid(closeTagIndex + 7);
}
appendCardTag(cursor, cardName); appendCardTag(cursor, cardName);
return; return;
@ -340,10 +348,11 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message)
message = message.mid(2); message = message.mid(2);
int closeTagIndex = message.indexOf("]]"); int closeTagIndex = message.indexOf("]]");
QString cardName = message.left(closeTagIndex); QString cardName = message.left(closeTagIndex);
if (closeTagIndex == -1) if (closeTagIndex == -1) {
message.clear(); message.clear();
else } else {
message = message.mid(closeTagIndex + 2); message = message.mid(closeTagIndex + 2);
}
appendCardTag(cursor, cardName); appendCardTag(cursor, cardName);
return; return;
@ -353,10 +362,11 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message)
message = message.mid(5); message = message.mid(5);
int closeTagIndex = message.indexOf("[/url]"); int closeTagIndex = message.indexOf("[/url]");
QString url = message.left(closeTagIndex); QString url = message.left(closeTagIndex);
if (closeTagIndex == -1) if (closeTagIndex == -1) {
message.clear(); message.clear();
else } else {
message = message.mid(closeTagIndex + 6); message = message.mid(closeTagIndex + 6);
}
appendUrlTag(cursor, url); appendUrlTag(cursor, url);
return; return;
@ -587,8 +597,9 @@ QTextFragment ChatView::getFragmentUnderMouse(const QPoint &pos) const
QTextBlock::iterator it; QTextBlock::iterator it;
for (it = block.begin(); !(it.atEnd()); ++it) { for (it = block.begin(); !(it.atEnd()); ++it) {
QTextFragment frag = it.fragment(); QTextFragment frag = it.fragment();
if (frag.contains(cursor.position())) if (frag.contains(cursor.position())) {
return frag; return frag;
}
} }
return QTextFragment(); return QTextFragment();
} }
@ -604,10 +615,11 @@ void ChatView::mouseMoveEvent(QMouseEvent *event)
if (scheme == "card") { if (scheme == "card") {
hoveredItemType = HoveredCard; hoveredItemType = HoveredCard;
emit cardNameHovered(hoveredContent); emit cardNameHovered(hoveredContent);
} else if (scheme == "user") } else if (scheme == "user") {
hoveredItemType = HoveredUser; hoveredItemType = HoveredUser;
else } else {
hoveredItemType = HoveredUrl; hoveredItemType = HoveredUrl;
}
viewport()->setCursor(Qt::PointingHandCursor); viewport()->setCursor(Qt::PointingHandCursor);
} else { } else {
hoveredItemType = HoveredNothing; hoveredItemType = HoveredNothing;
@ -650,8 +662,9 @@ void ChatView::mousePressEvent(QMouseEvent *event)
case Qt::LeftButton: { case Qt::LeftButton: {
if (event->modifiers() == Qt::ControlModifier) { if (event->modifiers() == Qt::ControlModifier) {
emit openMessageDialog(userName, true); emit openMessageDialog(userName, true);
} else } else {
emit addMentionTag("@" + userName); emit addMentionTag("@" + userName);
}
break; break;
} }
default: default:
@ -668,16 +681,18 @@ void ChatView::mousePressEvent(QMouseEvent *event)
void ChatView::mouseReleaseEvent(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("_")); emit deleteCardInfoPopup(QString("_"));
}
QTextBrowser::mouseReleaseEvent(event); QTextBrowser::mouseReleaseEvent(event);
} }
void ChatView::openLink(const QUrl &link) void ChatView::openLink(const QUrl &link)
{ {
if ((link.scheme() == "card") || (link.scheme() == "user")) if ((link.scheme() == "card") || (link.scheme() == "user")) {
return; return;
}
QDesktopServices::openUrl(link); QDesktopServices::openUrl(link);
} }

View file

@ -61,14 +61,17 @@ GameSelector::GameSelector(AbstractClient *_client,
gameListView->setColumnWidth(3, gameListView->columnWidth(3) * 1.2); gameListView->setColumnWidth(3, gameListView->columnWidth(3) * 1.2);
// game type width // game type width
gameListView->setColumnWidth(4, gameListView->columnWidth(4) * 1.4); gameListView->setColumnWidth(4, gameListView->columnWidth(4) * 1.4);
if (_room) if (_room) {
gameListView->header()->hideSection(gameListModel->roomColIndex()); gameListView->header()->hideSection(gameListModel->roomColIndex());
}
if (room) if (room) {
gameTypeMap = gameListModel->getGameTypes().value(room->getRoomId()); gameTypeMap = gameListModel->getGameTypes().value(room->getRoomId());
}
if (showFilters && restoresettings) if (showFilters && restoresettings) {
gameListProxyModel->loadFilterParameters(gameTypeMap); gameListProxyModel->loadFilterParameters(gameTypeMap);
}
gameListView->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents); gameListView->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
@ -111,8 +114,9 @@ GameSelector::GameSelector(AbstractClient *_client,
buttonLayout->addWidget(clearFilterButton); buttonLayout->addWidget(clearFilterButton);
} }
buttonLayout->addStretch(); buttonLayout->addStretch();
if (room) if (room) {
buttonLayout->addWidget(createButton); buttonLayout->addWidget(createButton);
}
buttonLayout->addWidget(joinButton); buttonLayout->addWidget(joinButton);
if (tabSupervisor->getUserInfo()->user_level() & ServerInfo_User::IsJudge) { if (tabSupervisor->getUserInfo()->user_level() & ServerInfo_User::IsJudge) {
buttonLayout->addWidget(joinAsJudgeButton); buttonLayout->addWidget(joinAsJudgeButton);
@ -178,8 +182,9 @@ void GameSelector::actSetFilter()
{ {
DlgFilterGames dlg(gameTypeMap, gameListProxyModel, this); DlgFilterGames dlg(gameTypeMap, gameListProxyModel, this);
if (!dlg.exec()) if (!dlg.exec()) {
return; return;
}
gameListProxyModel->setGameFilters(dlg.getFilters()); gameListProxyModel->setGameFilters(dlg.getFilters());
gameListProxyModel->saveFilterParameters(gameTypeMap); gameListProxyModel->saveFilterParameters(gameTypeMap);
@ -373,8 +378,9 @@ void GameSelector::joinGame(const bool asSpectator, const bool asJudge)
void GameSelector::disableButtons() void GameSelector::disableButtons()
{ {
if (createButton) if (createButton) {
createButton->setEnabled(false); createButton->setEnabled(false);
}
joinButton->setEnabled(false); joinButton->setEnabled(false);
spectateButton->setEnabled(false); spectateButton->setEnabled(false);
@ -382,8 +388,9 @@ void GameSelector::disableButtons()
void GameSelector::enableButtons() void GameSelector::enableButtons()
{ {
if (createButton) if (createButton) {
createButton->setEnabled(true); createButton->setEnabled(true);
}
// Enable buttons for the currently selected game // Enable buttons for the currently selected game
enableButtonsForIndex(gameListView->currentIndex()); enableButtonsForIndex(gameListView->currentIndex());
@ -391,8 +398,9 @@ void GameSelector::enableButtons()
void GameSelector::enableButtonsForIndex(const QModelIndex &current) void GameSelector::enableButtonsForIndex(const QModelIndex &current)
{ {
if (!current.isValid()) if (!current.isValid()) {
return; return;
}
const ServerInfo_Game &game = gameListModel->getGame(current.data(Qt::UserRole).toInt()); const ServerInfo_Game &game = gameListModel->getGame(current.data(Qt::UserRole).toInt());
bool overrideRestrictions = !tabSupervisor->getAdminLocked(); bool overrideRestrictions = !tabSupervisor->getAdminLocked();
@ -405,8 +413,9 @@ void GameSelector::retranslateUi()
{ {
filterButton->setText(tr("&Filter games")); filterButton->setText(tr("&Filter games"));
clearFilterButton->setText(tr("C&lear filter")); clearFilterButton->setText(tr("C&lear filter"));
if (createButton) if (createButton) {
createButton->setText(tr("C&reate")); createButton->setText(tr("C&reate"));
}
joinButton->setText(tr("&Join")); joinButton->setText(tr("&Join"));
joinAsJudgeButton->setText(tr("Join as judge")); joinAsJudgeButton->setText(tr("Join as judge"));
spectateButton->setText(tr("J&oin as spectator")); spectateButton->setText(tr("J&oin as spectator"));

View file

@ -59,8 +59,9 @@ GameSelectorQuickFilterToolBar::GameSelectorQuickFilterToolBar(QWidget *parent,
if (currentTypes.size() == 1) { if (currentTypes.size() == 1) {
int typeId = *currentTypes.begin(); int typeId = *currentTypes.begin();
int index = filterToFormatComboBox->findData(typeId); int index = filterToFormatComboBox->findData(typeId);
if (index >= 0) if (index >= 0) {
filterToFormatComboBox->setCurrentIndex(index); filterToFormatComboBox->setCurrentIndex(index);
}
} else { } else {
filterToFormatComboBox->setCurrentIndex(0); // "All types" by default 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 QVariant GamesModel::data(const QModelIndex &index, int role) const
{ {
if (!index.isValid()) if (!index.isValid()) {
return QVariant(); return QVariant();
if (role == Qt::UserRole) }
if (role == Qt::UserRole) {
return index.row(); 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(); return QVariant();
if ((index.row() >= gameList.size()) || (index.column() >= columnCount())) }
if ((index.row() >= gameList.size()) || (index.column() >= columnCount())) {
return QVariant(); return QVariant();
}
const ServerInfo_Game &gameentry = gameList[index.row()]; const ServerInfo_Game &gameentry = gameList[index.row()];
switch (index.column()) { switch (index.column()) {
@ -126,8 +130,9 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
case Qt::DisplayRole: { case Qt::DisplayRole: {
QStringList result; QStringList result;
GameTypeMap gameTypeMap = gameTypes.value(gameentry.room_id()); 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))); result.append(gameTypeMap.value(gameentry.game_types(i)));
}
return result.join(", "); return result.join(", ");
} }
case Qt::TextAlignmentRole: case Qt::TextAlignmentRole:
@ -140,14 +145,18 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
case SORT_ROLE: case SORT_ROLE:
case Qt::DisplayRole: { case Qt::DisplayRole: {
QStringList result; QStringList result;
if (gameentry.with_password()) if (gameentry.with_password()) {
result.append(tr("password")); result.append(tr("password"));
if (gameentry.only_buddies()) }
if (gameentry.only_buddies()) {
result.append(tr("buddies only")); result.append(tr("buddies only"));
if (gameentry.only_registered()) }
if (gameentry.only_registered()) {
result.append(tr("reg. users only")); result.append(tr("reg. users only"));
if (gameentry.share_decklists_on_load()) }
if (gameentry.share_decklists_on_load()) {
result.append(tr("open decklists")); result.append(tr("open decklists"));
}
return result.join(", "); return result.join(", ");
} }
case Qt::DecorationRole: { 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 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(); return QVariant();
}
switch (section) { switch (section) {
case ROOM: case ROOM:
return tr("Room"); return tr("Room");
@ -296,8 +306,9 @@ void GamesProxyModel::setGameFilters(const GameFilterConfigs &_filters)
int GamesProxyModel::getNumFilteredGames() const int GamesProxyModel::getNumFilteredGames() const
{ {
auto *model = qobject_cast<GamesModel *>(sourceModel()); auto *model = qobject_cast<GamesModel *>(sourceModel());
if (!model) if (!model) {
return 0; return 0;
}
int numFilteredGames = 0; int numFilteredGames = 0;
for (int row = 0; row < model->rowCount(); ++row) { 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(); static const QDate epochDate = QDateTime::fromSecsSinceEpoch(0, Qt::UTC).date();
#endif #endif
auto *model = qobject_cast<GamesModel *>(sourceModel()); auto *model = qobject_cast<GamesModel *>(sourceModel());
if (!model) if (!model) {
return false; return false;
}
const ServerInfo_Game &game = model->getGame(sourceRow); 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()))) { !userListProxy->isUserBuddy(QString::fromStdString(game.creator_info().name()))) {
return false; return false;
} }
if (filters.hideFullGames && game.player_count() == game.max_players()) if (filters.hideFullGames && game.player_count() == game.max_players()) {
return false; return false;
if (filters.hideGamesThatStarted && game.started()) }
if (filters.hideGamesThatStarted && game.started()) {
return false; return false;
if (!userListProxy->isOwnUserRegistered()) }
if (game.only_registered()) if (!userListProxy->isOwnUserRegistered()) {
if (game.only_registered()) {
return false; return false;
if (filters.hidePasswordProtectedGames && game.with_password()) }
}
if (filters.hidePasswordProtectedGames && game.with_password()) {
return false; 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; return false;
}
}
if (!filters.creatorNameFilters.isEmpty()) { if (!filters.creatorNameFilters.isEmpty()) {
bool found = false; bool found = false;
for (const auto &createNameFilter : filters.creatorNameFilters) { for (const auto &createNameFilter : filters.creatorNameFilters) {
@ -428,15 +447,19 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow) const
} }
QSet<int> gameTypes; 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)); 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; return false;
}
if (static_cast<int>(game.max_players()) < filters.maxPlayersFilterMin) if (static_cast<int>(game.max_players()) < filters.maxPlayersFilterMin) {
return false; return false;
if (static_cast<int>(game.max_players()) > filters.maxPlayersFilterMax) }
if (static_cast<int>(game.max_players()) > filters.maxPlayersFilterMax) {
return false; return false;
}
if (filters.maxGameAge.isValid()) { if (filters.maxGameAge.isValid()) {
QDateTime now = QDateTime::currentDateTimeUtc(); QDateTime now = QDateTime::currentDateTimeUtc();
@ -451,14 +474,18 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow) const
} }
if (filters.showOnlyIfSpectatorsCanWatch) { if (filters.showOnlyIfSpectatorsCanWatch) {
if (!game.spectators_allowed()) if (!game.spectators_allowed()) {
return false; return false;
if (!filters.showSpectatorPasswordProtected && game.spectators_need_password()) }
if (!filters.showSpectatorPasswordProtected && game.spectators_need_password()) {
return false; return false;
if (filters.showOnlyIfSpectatorsCanChat && !game.spectators_can_chat()) }
if (filters.showOnlyIfSpectatorsCanChat && !game.spectators_can_chat()) {
return false; return false;
if (filters.showOnlyIfSpectatorsCanSeeHands && !game.spectators_omniscient()) }
if (filters.showOnlyIfSpectatorsCanSeeHands && !game.spectators_omniscient()) {
return false; return false;
}
} }
return true; return true;
} }

View file

@ -37,13 +37,11 @@ void HandlePublicServers::actFinishParsingDownloadedData()
QVariantMap jsonMap = jsonResponse.toVariant().toMap(); QVariantMap jsonMap = jsonResponse.toVariant().toMap();
updateServerINISettings(jsonMap); updateServerINISettings(jsonMap);
} else { } else {
qDebug() << "[PUBLIC SERVER HANDLER]" qDebug() << "[PUBLIC SERVER HANDLER]" << "JSON Parsing Error:" << parseError.errorString();
<< "JSON Parsing Error:" << parseError.errorString();
emit sigPublicServersDownloadedUnsuccessfully(errorCode); emit sigPublicServersDownloadedUnsuccessfully(errorCode);
} }
} else { } else {
qDebug() << "[PUBLIC SERVER HANDLER]" qDebug() << "[PUBLIC SERVER HANDLER]" << "Error Downloading Public Servers" << errorCode;
<< "Error Downloading Public Servers" << errorCode;
emit sigPublicServersDownloadedUnsuccessfully(errorCode); emit sigPublicServersDownloadedUnsuccessfully(errorCode);
} }

View file

@ -22,8 +22,9 @@ RemoteDeckList_TreeModel::DirectoryNode::~DirectoryNode()
void RemoteDeckList_TreeModel::DirectoryNode::clearTree() void RemoteDeckList_TreeModel::DirectoryNode::clearTree()
{ {
for (int i = 0; i < size(); ++i) for (int i = 0; i < size(); ++i) {
delete at(i); delete at(i);
}
clear(); clear();
} }
@ -31,31 +32,37 @@ QString RemoteDeckList_TreeModel::DirectoryNode::getPath() const
{ {
if (parent) { if (parent) {
QString parentPath = parent->getPath(); QString parentPath = parent->getPath();
if (parentPath.isEmpty()) if (parentPath.isEmpty()) {
return name; return name;
else } else {
return parentPath + "/" + name; return parentPath + "/" + name;
} else }
} else {
return name; return name;
}
} }
RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::DirectoryNode::getNodeByPath(QStringList path) RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::DirectoryNode::getNodeByPath(QStringList path)
{ {
QString pathItem; QString pathItem;
if (parent) { if (parent) {
if (path.isEmpty()) if (path.isEmpty()) {
return this; return this;
}
pathItem = path.takeFirst(); pathItem = path.takeFirst();
if (pathItem.isEmpty() && name.isEmpty()) if (pathItem.isEmpty() && name.isEmpty()) {
return this; return this;
}
} }
for (int i = 0; i < size(); ++i) { for (int i = 0; i < size(); ++i) {
DirectoryNode *node = dynamic_cast<DirectoryNode *>(at(i)); DirectoryNode *node = dynamic_cast<DirectoryNode *>(at(i));
if (!node) if (!node) {
continue; continue;
if (node->getName() == pathItem) }
if (node->getName() == pathItem) {
return node->getNodeByPath(path); return node->getNodeByPath(path);
}
} }
return 0; return 0;
} }
@ -66,12 +73,14 @@ RemoteDeckList_TreeModel::FileNode *RemoteDeckList_TreeModel::DirectoryNode::get
DirectoryNode *node = dynamic_cast<DirectoryNode *>(at(i)); DirectoryNode *node = dynamic_cast<DirectoryNode *>(at(i));
if (node) { if (node) {
FileNode *result = node->getNodeById(id); FileNode *result = node->getNodeById(id);
if (result) if (result) {
return result; return result;
}
} else { } else {
FileNode *file = dynamic_cast<FileNode *>(at(i)); FileNode *file = dynamic_cast<FileNode *>(at(i));
if (file->getId() == id) if (file->getId() == id) {
return file; return file;
}
} }
} }
return 0; return 0;
@ -95,10 +104,11 @@ RemoteDeckList_TreeModel::~RemoteDeckList_TreeModel()
int RemoteDeckList_TreeModel::rowCount(const QModelIndex &parent) const int RemoteDeckList_TreeModel::rowCount(const QModelIndex &parent) const
{ {
DirectoryNode *node = getNode<DirectoryNode *>(parent); DirectoryNode *node = getNode<DirectoryNode *>(parent);
if (node) if (node) {
return node->size(); return node->size();
else } else {
return 0; return 0;
}
} }
int RemoteDeckList_TreeModel::columnCount(const QModelIndex & /*parent*/) const 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 QVariant RemoteDeckList_TreeModel::data(const QModelIndex &index, int role) const
{ {
if (!index.isValid()) if (!index.isValid()) {
return QVariant(); return QVariant();
if (index.column() >= 3) }
if (index.column() >= 3) {
return QVariant(); return QVariant();
}
Node *temp = static_cast<Node *>(index.internalPointer()); Node *temp = static_cast<Node *>(index.internalPointer());
FileNode *file = dynamic_cast<FileNode *>(temp); 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 QVariant RemoteDeckList_TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{ {
if (orientation != Qt::Horizontal) if (orientation != Qt::Horizontal) {
return QVariant(); return QVariant();
}
switch (role) { switch (role) {
case Qt::TextAlignmentRole: case Qt::TextAlignmentRole:
return section == 1 ? Qt::AlignRight : Qt::AlignLeft; 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 QModelIndex RemoteDeckList_TreeModel::index(int row, int column, const QModelIndex &parent) const
{ {
if (!hasIndex(row, column, parent)) if (!hasIndex(row, column, parent)) {
return QModelIndex(); return QModelIndex();
}
DirectoryNode *parentNode = getNode<DirectoryNode *>(parent); DirectoryNode *parentNode = getNode<DirectoryNode *>(parent);
if (row >= parentNode->size()) if (row >= parentNode->size()) {
return QModelIndex(); return QModelIndex();
}
return createIndex(row, column, parentNode->at(row)); return createIndex(row, column, parentNode->at(row));
} }
QModelIndex RemoteDeckList_TreeModel::parent(const QModelIndex &ind) const QModelIndex RemoteDeckList_TreeModel::parent(const QModelIndex &ind) const
{ {
if (!ind.isValid()) if (!ind.isValid()) {
return QModelIndex(); return QModelIndex();
}
return nodeToIndex(static_cast<Node *>(ind.internalPointer())->getParent()); 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 QModelIndex RemoteDeckList_TreeModel::nodeToIndex(Node *node) const
{ {
if (node == nullptr || node == root) if (node == nullptr || node == root) {
return QModelIndex(); return QModelIndex();
}
return createIndex(node->getParent()->indexOf(node), 0, node); 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(); const int folderItemsSize = folderInfo.items_size();
for (int i = 0; i < folderItemsSize; ++i) { for (int i = 0; i < folderItemsSize; ++i) {
const ServerInfo_DeckStorage_TreeItem &subItem = folderInfo.items(i); const ServerInfo_DeckStorage_TreeItem &subItem = folderInfo.items(i);
if (subItem.has_folder()) if (subItem.has_folder()) {
addFolderToTree(subItem, newItem); addFolderToTree(subItem, newItem);
else } else {
addFileToTree(subItem, newItem); addFileToTree(subItem, newItem);
}
} }
} }

View file

@ -75,8 +75,9 @@ public:
template <typename T> [[nodiscard]] T getNode(const QModelIndex &index) const 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>(root);
}
return dynamic_cast<T>(static_cast<Node *>(index.internalPointer())); 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::MatchNode::MatchNode(const ServerInfo_ReplayMatch &_matchInfo)
: RemoteReplayList_TreeModel::Node(QString::fromStdString(_matchInfo.game_name())), matchInfo(_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)); append(new ReplayNode(matchInfo.replay_list(i), this));
}
} }
RemoteReplayList_TreeModel::MatchNode::~MatchNode() RemoteReplayList_TreeModel::MatchNode::~MatchNode()
{ {
for (int i = 0; i < size(); ++i) for (int i = 0; i < size(); ++i) {
delete at(i); delete at(i);
}
} }
void RemoteReplayList_TreeModel::MatchNode::updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo) 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 int RemoteReplayList_TreeModel::rowCount(const QModelIndex &parent) const
{ {
if (!parent.isValid()) if (!parent.isValid()) {
return replayMatches.size(); return replayMatches.size();
}
auto *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(parent.internalPointer())); auto *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(parent.internalPointer()));
if (matchNode) if (matchNode) {
return matchNode->size(); return matchNode->size();
else } else {
return 0; return 0;
}
} }
QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) const QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) const
{ {
if (!index.isValid()) if (!index.isValid()) {
return QVariant(); return QVariant();
if (index.column() >= numberOfColumns) }
if (index.column() >= numberOfColumns) {
return QVariant(); return QVariant();
}
auto *replayNode = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer())); auto *replayNode = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
if (replayNode) { if (replayNode) {
@ -103,8 +109,9 @@ QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) co
return QString::fromStdString(matchInfo.game_name()); return QString::fromStdString(matchInfo.game_name());
case 2: { case 2: {
QStringList playerList; 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))); playerList.append(QString::fromStdString(matchInfo.player_names(i)));
}
return playerList.join(", "); return playerList.join(", ");
} }
case 4: 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 QVariant RemoteReplayList_TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{ {
if (orientation != Qt::Horizontal) if (orientation != Qt::Horizontal) {
return QVariant(); return QVariant();
}
switch (role) { switch (role) {
case Qt::TextAlignmentRole: case Qt::TextAlignmentRole:
switch (section) { 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 QModelIndex RemoteReplayList_TreeModel::index(int row, int column, const QModelIndex &parent) const
{ {
if (!hasIndex(row, column, parent)) if (!hasIndex(row, column, parent)) {
return QModelIndex(); return QModelIndex();
}
auto *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(parent.internalPointer())); auto *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(parent.internalPointer()));
if (matchNode) { if (matchNode) {
if (row >= matchNode->size()) if (row >= matchNode->size()) {
return QModelIndex(); return QModelIndex();
}
return createIndex(row, column, (void *)matchNode->at(row)); return createIndex(row, column, (void *)matchNode->at(row));
} else { } else {
if (row >= replayMatches.size()) if (row >= replayMatches.size()) {
return QModelIndex(); return QModelIndex();
}
return createIndex(row, column, (void *)replayMatches[row]); 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 QModelIndex RemoteReplayList_TreeModel::parent(const QModelIndex &ind) const
{ {
MatchNode const *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(ind.internalPointer())); MatchNode const *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(ind.internalPointer()));
if (matchNode) if (matchNode) {
return QModelIndex(); return QModelIndex();
else { } else {
auto *replayNode = dynamic_cast<ReplayNode *>(static_cast<Node *>(ind.internalPointer())); auto *replayNode = dynamic_cast<ReplayNode *>(static_cast<Node *>(ind.internalPointer()));
return createIndex(replayNode->getParent()->indexOf(replayNode), 0, replayNode->getParent()); 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 Qt::ItemFlags RemoteReplayList_TreeModel::flags(const QModelIndex &index) const
{ {
if (!index.isValid()) if (!index.isValid()) {
return Qt::NoItemFlags; return Qt::NoItemFlags;
}
return Qt::ItemIsEnabled | Qt::ItemIsSelectable; return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
} }
ServerInfo_Replay const *RemoteReplayList_TreeModel::getReplay(const QModelIndex &index) const ServerInfo_Replay const *RemoteReplayList_TreeModel::getReplay(const QModelIndex &index) const
{ {
if (!index.isValid()) if (!index.isValid()) {
return 0; return 0;
}
auto *node = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer())); auto *node = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
if (!node) if (!node) {
return 0; return 0;
}
return &node->getReplayInfo(); return &node->getReplayInfo();
} }
ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getReplayMatch(const QModelIndex &index) const ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getReplayMatch(const QModelIndex &index) const
{ {
if (!index.isValid()) if (!index.isValid()) {
return nullptr; return nullptr;
}
auto *node = dynamic_cast<MatchNode *>(static_cast<Node *>(index.internalPointer())); auto *node = dynamic_cast<MatchNode *>(static_cast<Node *>(index.internalPointer()));
if (!node) if (!node) {
return nullptr; return nullptr;
}
return &node->getMatchInfo(); return &node->getMatchInfo();
} }
ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getEnclosingReplayMatch(const QModelIndex &index) const ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getEnclosingReplayMatch(const QModelIndex &index) const
{ {
if (!index.isValid()) if (!index.isValid()) {
return nullptr; return nullptr;
}
auto *node = dynamic_cast<MatchNode *>(static_cast<Node *>(index.internalPointer())); auto *node = dynamic_cast<MatchNode *>(static_cast<Node *>(index.internalPointer()));
if (!node) { if (!node) {
auto *_node = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer())); auto *_node = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
if (!_node) if (!_node) {
return nullptr; return nullptr;
}
return &_node->getParent()->getMatchInfo(); return &_node->getParent()->getMatchInfo();
} }
return &node->getMatchInfo(); return &node->getMatchInfo();
@ -244,8 +262,9 @@ ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getEnclosingReplayMatc
*/ */
void RemoteReplayList_TreeModel::clearAll() void RemoteReplayList_TreeModel::clearAll()
{ {
for (int i = 0; i < replayMatches.size(); ++i) for (int i = 0; i < replayMatches.size(); ++i) {
delete replayMatches[i]; delete replayMatches[i];
}
replayMatches.clear(); replayMatches.clear();
} }
@ -275,24 +294,26 @@ void RemoteReplayList_TreeModel::addMatchInfo(const ServerInfo_ReplayMatch &matc
void RemoteReplayList_TreeModel::updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo) 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) { if (replayMatches[i]->getMatchInfo().game_id() == gameId) {
replayMatches[i]->updateMatchInfo(matchInfo); replayMatches[i]->updateMatchInfo(matchInfo);
emit dataChanged(createIndex(i, 0, (void *)replayMatches[i]), emit dataChanged(createIndex(i, 0, (void *)replayMatches[i]),
createIndex(i, numberOfColumns - 1, (void *)replayMatches[i])); createIndex(i, numberOfColumns - 1, (void *)replayMatches[i]));
break; break;
} }
}
} }
void RemoteReplayList_TreeModel::removeMatchInfo(int gameId) 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) { if (replayMatches[i]->getMatchInfo().game_id() == gameId) {
beginRemoveRows(QModelIndex(), i, i); beginRemoveRows(QModelIndex(), i, i);
replayMatches.removeAt(i); replayMatches.removeAt(i);
endRemoveRows(); endRemoveRows();
break; break;
} }
}
} }
void RemoteReplayList_TreeModel::replayListFinished(const Response &r) void RemoteReplayList_TreeModel::replayListFinished(const Response &r)
@ -302,8 +323,9 @@ void RemoteReplayList_TreeModel::replayListFinished(const Response &r)
beginResetModel(); beginResetModel();
clearAll(); 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))); replayMatches.append(new MatchNode(resp.match_list(i)));
}
endResetModel(); endResetModel();
emit treeRefreshed(); emit treeRefreshed();

View file

@ -192,13 +192,15 @@ void UserContextMenu::banUserHistory_processResponse(const Response &resp)
table->setMinimumSize(table->horizontalHeader()->length() + (table->columnCount() * 5), table->setMinimumSize(table->horizontalHeader()->length() + (table->columnCount() * 5),
table->verticalHeader()->length() + (table->rowCount() * 3)); table->verticalHeader()->length() + (table->rowCount() * 3));
table->show(); table->show();
} else } else {
QMessageBox::information(static_cast<QWidget *>(parent()), tr("Ban History"), QMessageBox::information(static_cast<QWidget *>(parent()), tr("Ban History"),
tr("User has never been banned.")); tr("User has never been banned."));
}
} else } else {
QMessageBox::critical(static_cast<QWidget *>(parent()), tr("Ban History"), QMessageBox::critical(static_cast<QWidget *>(parent()), tr("Ban History"),
tr("Failed to collect ban information.")); tr("Failed to collect ban information."));
}
} }
void UserContextMenu::warnUserHistory_processResponse(const Response &resp) 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->setMinimumSize(table->horizontalHeader()->length() + (table->columnCount() * 5),
table->verticalHeader()->length() + (table->rowCount() * 3)); table->verticalHeader()->length() + (table->rowCount() * 3));
table->show(); table->show();
} else } else {
QMessageBox::information(static_cast<QWidget *>(parent()), tr("Warning History"), QMessageBox::information(static_cast<QWidget *>(parent()), tr("Warning History"),
tr("User has never been warned.")); tr("User has never been warned."));
}
} else } else {
QMessageBox::critical(static_cast<QWidget *>(parent()), tr("Warning History"), QMessageBox::critical(static_cast<QWidget *>(parent()), tr("Warning History"),
tr("Failed to collect warning information.")); tr("Failed to collect warning information."));
}
} }
void UserContextMenu::getAdminNotes_processResponse(const Response &resp) void UserContextMenu::getAdminNotes_processResponse(const Response &resp)
@ -297,8 +301,9 @@ void UserContextMenu::warnUser_dialogFinished()
{ {
auto *dlg = static_cast<WarningDialog *>(sender()); auto *dlg = static_cast<WarningDialog *>(sender());
if (dlg->getName().isEmpty() || userListProxy->getOwnUsername().simplified().isEmpty()) if (dlg->getName().isEmpty() || userListProxy->getOwnUsername().simplified().isEmpty()) {
return; return;
}
Command_WarnUser cmd; Command_WarnUser cmd;
cmd.set_user_name(dlg->getName().toStdString()); cmd.set_user_name(dlg->getName().toStdString());

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