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

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

View file

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

View file

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

View file

@ -66,8 +66,9 @@ void Logger::openLogfileSession()
void Logger::closeLogfileSession()
{
if (!logToFileEnabled)
if (!logToFileEnabled) {
return;
}
logToFileEnabled = false;
fileStream << "Log session closed at " << QDateTime::currentDateTime().toString() << Qt::endl;

View file

@ -77,8 +77,9 @@ QMap<QString, QPixmap> PhasePixmapGenerator::pmCache;
QPixmap PhasePixmapGenerator::generatePixmap(int height, QString name)
{
QString key = name + QString::number(height);
if (pmCache.contains(key))
if (pmCache.contains(key)) {
return pmCache.value(key);
}
QPixmap pixmap = tryLoadImage("theme:phases/" + name, QSize(height, height));
@ -95,19 +96,22 @@ QPixmap CounterPixmapGenerator::generatePixmap(int height, QString name, bool hi
name = "general";
}
if (highlight)
if (highlight) {
name.append("_highlight");
}
QString key = name + QString::number(height);
if (pmCache.contains(key))
if (pmCache.contains(key)) {
return pmCache.value(key);
}
QPixmap pixmap = tryLoadImage("theme:counters/" + name, QSize(height, height));
// fall back to colorless counter if the name can't be found
if (pixmap.isNull()) {
name = "general";
if (highlight)
if (highlight) {
name.append("_highlight");
}
pixmap = tryLoadImage("theme:counters/" + name, QSize(height, height));
}
@ -118,17 +122,19 @@ QPixmap CounterPixmapGenerator::generatePixmap(int height, QString name, bool hi
QPixmap PingPixmapGenerator::generatePixmap(int size, int value, int max)
{
int key = size * 1000000 + max * 1000 + value;
if (pmCache.contains(key))
if (pmCache.contains(key)) {
return pmCache.value(key);
}
QPixmap pixmap(size, size);
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
QColor color;
if ((max == -1) || (value == -1))
if ((max == -1) || (value == -1)) {
color = Qt::black;
else
} else {
color.setHsv(120 * (1.0 - ((double)value / max)), 255, 255);
}
QRadialGradient g(QPointF((double)pixmap.width() / 2, (double)pixmap.height() / 2),
qMin(pixmap.width(), pixmap.height()) / 2.0);
@ -145,11 +151,13 @@ QMap<int, QPixmap> PingPixmapGenerator::pmCache;
QPixmap CountryPixmapGenerator::generatePixmap(int height, const QString &countryCode)
{
if (countryCode.size() != 2)
if (countryCode.size() != 2) {
return QPixmap();
}
QString key = countryCode + QString::number(height);
if (pmCache.contains(key))
if (pmCache.contains(key)) {
return pmCache.value(key);
}
int width = height * 2;
QPixmap pixmap = tryLoadImage("theme:countries/" + countryCode.toLower(), QSize(width, height), true);
@ -352,8 +360,9 @@ QPixmap LockPixmapGenerator::generatePixmap(int height)
{
int key = height;
if (pmCache.contains(key))
if (pmCache.contains(key)) {
return pmCache.value(key);
}
QPixmap pixmap = tryLoadImage("theme:icons/lock", QSize(height, height), true);
pmCache.insert(key, pixmap);
@ -365,8 +374,9 @@ QMap<int, QPixmap> LockPixmapGenerator::pmCache;
QPixmap DropdownIconPixmapGenerator::generatePixmap(int height, bool expanded)
{
QString key = QString::number(expanded) + ":" + QString::number(height);
if (pmCache.contains(key))
if (pmCache.contains(key)) {
return pmCache.value(key);
}
QString name = expanded ? "dropdown_expanded" : "dropdown_collapsed";
QPixmap pixmap = tryLoadImage("theme:icons/" + name, QSize(height, height), true);

View file

@ -51,8 +51,9 @@ struct PaletteColorInfo
// Iterate through all color roles (excluding NoRole and NColorRoles)
for (int r = 0; r < QPalette::NColorRoles; ++r) {
auto role = static_cast<QPalette::ColorRole>(r);
if (role == QPalette::NoRole)
if (role == QPalette::NoRole) {
continue;
}
PaletteColorInfo info;
info.group = group;
@ -78,8 +79,9 @@ struct PaletteColorInfo
for (int r = 0; r < QPalette::NColorRoles; ++r) {
auto role = static_cast<QPalette::ColorRole>(r);
if (role == QPalette::NoRole)
if (role == QPalette::NoRole) {
continue;
}
QColor color = palette.color(group, role);
qInfo().nospace() << qPrintable(QString("%1").arg(roleEnum.valueToKey(role), -20)) << " : "

View file

@ -95,8 +95,9 @@ void CardGroupDisplayWidget::onSelectionChanged(const QItemSelection &selected,
for (auto &range : deselected) {
for (int row = range.top(); row <= range.bottom(); ++row) {
QModelIndex idx = range.model()->index(row, 0, range.parent());
if (proxyModel)
if (proxyModel) {
idx = proxyModel->mapToSource(idx);
}
auto it = indexToWidgetMap.find(QPersistentModelIndex(idx));
if (it != indexToWidgetMap.end()) {

View file

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

View file

@ -73,8 +73,9 @@ void CardInfoTextWidget::setCard(const ExactCard &exactCard)
QStringList cardProps = card->getProperties();
for (const QString &key : cardProps) {
if (key.contains("-"))
if (key.contains("-")) {
continue;
}
QString keyText = Mtg::getNicePropertyName(key).toHtmlEscaped() + ":";
text +=
QString("<tr><td>%1</td><td></td><td>%2</td></tr>").arg(keyText, card->getProperty(key).toHtmlEscaped());

View file

@ -17,8 +17,9 @@ AbstractAnalyticsPanelWidget *
AnalyticsPanelWidgetFactory::create(const QString &type, QWidget *parent, DeckListStatisticsAnalyzer *analyzer) const
{
auto it = widgets.find(type);
if (it == widgets.end())
if (it == widgets.end()) {
return nullptr;
}
auto w = it->creator(parent, analyzer);

View file

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

View file

@ -69,8 +69,9 @@ void ManaCurveConfigDialog::setFromConfig(const ManaCurveConfig &cfg)
{
groupBy->setCurrentText(cfg.groupBy);
// restore filters
for (int i = 0; i < filterList->count(); ++i)
for (int i = 0; i < filterList->count(); ++i) {
filterList->item(i)->setSelected(cfg.filters.contains(filterList->item(i)->text()));
}
showMain->setChecked(cfg.showMain);
showCatRows->setChecked(cfg.showCategoryRows);
@ -81,8 +82,9 @@ void ManaCurveConfigDialog::accept()
cfg.groupBy = groupBy->currentText();
cfg.filters.clear();
for (auto *item : filterList->selectedItems())
for (auto *item : filterList->selectedItems()) {
cfg.filters << item->text();
}
cfg.showMain = showMain->isChecked();
cfg.showCategoryRows = showCatRows->isChecked();

View file

@ -51,15 +51,17 @@ void ManaCurveTotalWidget::updateDisplay(const QString &categoryName,
for (auto it = cmcIt->cbegin(); it != cmcIt->cend(); ++it) {
const QString &category = it.key();
if (!config.filters.isEmpty() && !config.filters.contains(category))
if (!config.filters.isEmpty() && !config.filters.contains(category)) {
continue;
}
const int value = it.value();
QStringList cards;
const auto catIt = cardsMap.constFind(category);
if (catIt != cardsMap.cend())
if (catIt != cardsMap.cend()) {
cards = catIt->value(cmc);
}
segments.push_back({category, value, cards, GameSpecificColors::MTG::colorHelper(category)});
}

View file

@ -69,16 +69,18 @@ static void buildMapsByCategory(const QHash<QString, QHash<int, int>> &categoryC
const QString &category = catIt.key();
const auto &countsByCmc = catIt.value();
for (auto it = countsByCmc.cbegin(); it != countsByCmc.cend(); ++it)
for (auto it = countsByCmc.cbegin(); it != countsByCmc.cend(); ++it) {
outCmcMap[it.key()][category] = it.value();
}
}
for (auto catIt = categoryCards.cbegin(); catIt != categoryCards.cend(); ++catIt) {
const QString &category = catIt.key();
const auto &cardsByCmc = catIt.value();
for (auto it = cardsByCmc.cbegin(); it != cardsByCmc.cend(); ++it)
for (auto it = cardsByCmc.cbegin(); it != cardsByCmc.cend(); ++it) {
outCardsMap[category][it.key()] = it.value();
}
}
}
@ -88,8 +90,9 @@ static void findGlobalCmcRange(const QHash<QString, QHash<int, int>> &categoryCo
maxCmc = 0;
for (const auto &countsByCmc : categoryCounts) {
for (auto it = countsByCmc.cbegin(); it != countsByCmc.cend(); ++it)
for (auto it = countsByCmc.cbegin(); it != countsByCmc.cend(); ++it) {
maxCmc = qMax(maxCmc, it.key());
}
}
}

View file

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

View file

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

View file

@ -62,8 +62,9 @@ void ManaDistributionConfigDialog::setFromConfig(const ManaDistributionConfig &c
displayType->setCurrentText(cfg.displayType);
for (int i = 0; i < filterList->count(); ++i)
for (int i = 0; i < filterList->count(); ++i) {
filterList->item(i)->setSelected(cfg.filters.contains(filterList->item(i)->text()));
}
showColorRows->setChecked(cfg.showColorRows);
}
@ -74,8 +75,9 @@ void ManaDistributionConfigDialog::accept()
// Filters
cfg.filters.clear();
for (auto *item : filterList->selectedItems())
for (auto *item : filterList->selectedItems()) {
cfg.filters << item->text();
}
cfg.showColorRows = showColorRows->isChecked();

View file

@ -191,10 +191,12 @@ double DeckListStatisticsAnalyzer::hypergeometric(int N, int K, int n, int k)
}
auto choose = [](int n, int r) -> double {
if (r > n)
if (r > n) {
return 0.0;
if (r == 0 || r == n)
}
if (r == 0 || r == n) {
return 1.0;
}
double res = 1.0;
for (int i = 1; i <= r; ++i) {
res *= (n - r + i);

View file

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

View file

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

View file

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

View file

@ -8,8 +8,9 @@
QVariant DeckListStyleProxy::data(const QModelIndex &index, int role) const
{
QModelIndex src = mapToSource(index);
if (!src.isValid())
if (!src.isValid()) {
return {};
}
QVariant value = QIdentityProxyModel::data(index, role);

View file

@ -192,8 +192,9 @@ QModelIndex DeckStateManager::addCard(const ExactCard &card, const QString &zone
QModelIndex DeckStateManager::decrementCard(const ExactCard &card, const QString &zoneName)
{
if (!card)
if (!card) {
return {};
}
QString providerId = card.getPrinting().getUuid();
QString collectorNumber = card.getPrinting().getProperty("num");
@ -241,15 +242,17 @@ static bool doSwapCard(DeckListModel *model,
bool DeckStateManager::swapCardAtIndex(const QModelIndex &idx)
{
if (!idx.isValid())
if (!idx.isValid()) {
return false;
}
QString cardName = idx.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString();
QString providerId = idx.siblingAtColumn(DeckListModelColumns::CARD_PROVIDER_ID).data().toString();
QModelIndex gparent = idx.parent().parent();
if (!gparent.isValid())
if (!gparent.isValid()) {
return false;
}
QString zoneName = gparent.siblingAtColumn(DeckListModelColumns::CARD_NAME).data(Qt::EditRole).toString();
QString otherZoneName = zoneName == DECK_ZONE_MAIN ? DECK_ZONE_SIDE : DECK_ZONE_MAIN;

View file

@ -261,13 +261,7 @@ void DlgConnect::updateDisplayInfo(const QString &saveName)
QStringList _data = uci.getServerInfo(saveName);
if (_data.isEmpty()) {
_data << ""
<< ""
<< ""
<< ""
<< ""
<< ""
<< "";
_data << "" << "" << "" << "" << "" << "" << "";
}
bool savePasswordStatus = (_data.at(5) == "1");

View file

@ -215,8 +215,9 @@ DlgCreateGame::DlgCreateGame(const ServerInfo_Game &gameInfo, const QMap<int, QS
spectatorsSeeEverythingCheckBox->setChecked(gameInfo.spectators_omniscient());
QSet<int> types;
for (int i = 0; i < gameInfo.game_types_size(); ++i)
for (int i = 0; i < gameInfo.game_types_size(); ++i) {
types.insert(gameInfo.game_types(i));
}
QMapIterator<int, QString> gameTypeIterator(gameTypes);
while (gameTypeIterator.hasNext()) {
@ -316,9 +317,9 @@ void DlgCreateGame::checkResponse(const Response &response)
{
buttonBox->setEnabled(true);
if (response.response_code() == Response::RespOk)
if (response.response_code() == Response::RespOk) {
accept();
else {
} else {
QMessageBox::critical(this, tr("Error"), tr("Server error."));
return;
}

View file

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

View file

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

View file

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

View file

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

View file

@ -217,8 +217,9 @@ void WndSets::saveHeaderState()
void WndSets::rebuildMainLayout(int actionToTake)
{
if (mainLayout == nullptr)
if (mainLayout == nullptr) {
return;
}
switch (actionToTake) {
case NO_SETS_SELECTED:
@ -382,12 +383,14 @@ void WndSets::actUp()
std::sort(rows.begin(), rows.end(), std::less<QModelIndex>());
QSet<int> newRows;
if (rows.empty())
if (rows.empty()) {
return;
}
for (auto i : rows) {
if (i.row() <= 0)
if (i.row() <= 0) {
continue;
}
int oldRow = displayModel->mapToSource(i).row();
int newRow = i.row() - 1;
@ -405,12 +408,14 @@ void WndSets::actDown()
std::sort(rows.begin(), rows.end(), [](const QModelIndex &a, const QModelIndex &b) { return b < a; });
QSet<int> newRows;
if (rows.empty())
if (rows.empty()) {
return;
}
for (auto i : rows) {
if (i.row() >= displayModel->rowCount() - 1)
if (i.row() >= displayModel->rowCount() - 1) {
continue;
}
int oldRow = displayModel->mapToSource(i).row();
int newRow = i.row() + 1;
@ -428,8 +433,9 @@ void WndSets::actTop()
QSet<int> newRows;
int newRow = 0;
if (rows.empty())
if (rows.empty()) {
return;
}
for (int i = 0; i < rows.length(); i++) {
int oldRow = displayModel->mapToSource(rows.at(i)).row();
@ -454,8 +460,9 @@ void WndSets::actBottom()
QSet<int> newRows;
int newRow = model->rowCount() - 1;
if (rows.empty())
if (rows.empty()) {
return;
}
for (int i = 0; i < rows.length(); i++) {
int oldRow = displayModel->mapToSource(rows.at(i)).row();

View file

@ -311,8 +311,9 @@ DlgRegister::DlgRegister(QWidget *parent) : QDialog(parent)
countryEdit->addItem(QPixmap("theme:countries/zw"), "zw");
countryEdit->setCurrentIndex(0);
QStringList countries = SettingsCache::instance().getCountries();
for (const QString &c : countries)
for (const QString &c : countries) {
countryEdit->addItem(QPixmap("theme:countries/" + c.toLower()), c);
}
realnameLabel = new QLabel(tr("Real name:"));
realnameEdit = new QLineEdit();

View file

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

View file

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

View file

@ -154,8 +154,9 @@ void DlgUpdate::finishedUpdateCheck(bool needToUpdate, bool isCompatible, Releas
"</a>)<br><br>" + tr("Do you want to update now?"),
QMessageBox::Yes | QMessageBox::No);
if (reply == QMessageBox::Yes)
if (reply == QMessageBox::Yes) {
downloadUpdate(release->getName());
}
} else {
QMessageBox::information(
this, tr("Update Available"),

View file

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

View file

@ -73,8 +73,9 @@ TipsOfTheDay::~TipsOfTheDay()
QVariant TipsOfTheDay::data(const QModelIndex &index, int /*role*/) const
{
if (!index.isValid() || index.row() >= tipList->size() || index.column() >= TIPDDBMODEL_COLUMNS)
if (!index.isValid() || index.row() >= tipList->size() || index.column() >= TIPDDBMODEL_COLUMNS) {
return QVariant();
}
TipOfTheDay tip = tipList->at(index.row());
switch (index.column()) {

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -59,8 +59,9 @@ GameSelectorQuickFilterToolBar::GameSelectorQuickFilterToolBar(QWidget *parent,
if (currentTypes.size() == 1) {
int typeId = *currentTypes.begin();
int index = filterToFormatComboBox->findData(typeId);
if (index >= 0)
if (index >= 0) {
filterToFormatComboBox->setCurrentIndex(index);
}
} else {
filterToFormatComboBox->setCurrentIndex(0); // "All types" by default
}

View file

@ -63,14 +63,18 @@ GamesModel::GamesModel(const QMap<int, QString> &_rooms, const QMap<int, GameTyp
QVariant GamesModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
if (!index.isValid()) {
return QVariant();
if (role == Qt::UserRole)
}
if (role == Qt::UserRole) {
return index.row();
if (role != Qt::DisplayRole && role != SORT_ROLE && role != Qt::DecorationRole && role != Qt::TextAlignmentRole)
}
if (role != Qt::DisplayRole && role != SORT_ROLE && role != Qt::DecorationRole && role != Qt::TextAlignmentRole) {
return QVariant();
if ((index.row() >= gameList.size()) || (index.column() >= columnCount()))
}
if ((index.row() >= gameList.size()) || (index.column() >= columnCount())) {
return QVariant();
}
const ServerInfo_Game &gameentry = gameList[index.row()];
switch (index.column()) {
@ -126,8 +130,9 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
case Qt::DisplayRole: {
QStringList result;
GameTypeMap gameTypeMap = gameTypes.value(gameentry.room_id());
for (int i = gameentry.game_types_size() - 1; i >= 0; --i)
for (int i = gameentry.game_types_size() - 1; i >= 0; --i) {
result.append(gameTypeMap.value(gameentry.game_types(i)));
}
return result.join(", ");
}
case Qt::TextAlignmentRole:
@ -140,14 +145,18 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
case SORT_ROLE:
case Qt::DisplayRole: {
QStringList result;
if (gameentry.with_password())
if (gameentry.with_password()) {
result.append(tr("password"));
if (gameentry.only_buddies())
}
if (gameentry.only_buddies()) {
result.append(tr("buddies only"));
if (gameentry.only_registered())
}
if (gameentry.only_registered()) {
result.append(tr("reg. users only"));
if (gameentry.share_decklists_on_load())
}
if (gameentry.share_decklists_on_load()) {
result.append(tr("open decklists"));
}
return result.join(", ");
}
case Qt::DecorationRole: {
@ -205,8 +214,9 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const
QVariant GamesModel::headerData(int section, Qt::Orientation /*orientation*/, int role) const
{
if ((role != Qt::DisplayRole) && (role != Qt::TextAlignmentRole))
if ((role != Qt::DisplayRole) && (role != Qt::TextAlignmentRole)) {
return QVariant();
}
switch (section) {
case ROOM:
return tr("Room");
@ -296,8 +306,9 @@ void GamesProxyModel::setGameFilters(const GameFilterConfigs &_filters)
int GamesProxyModel::getNumFilteredGames() const
{
auto *model = qobject_cast<GamesModel *>(sourceModel());
if (!model)
if (!model) {
return 0;
}
int numFilteredGames = 0;
for (int row = 0; row < model->rowCount(); ++row) {
@ -384,8 +395,9 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow) const
static const QDate epochDate = QDateTime::fromSecsSinceEpoch(0, Qt::UTC).date();
#endif
auto *model = qobject_cast<GamesModel *>(sourceModel());
if (!model)
if (!model) {
return false;
}
const ServerInfo_Game &game = model->getGame(sourceRow);
@ -403,18 +415,25 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow) const
!userListProxy->isUserBuddy(QString::fromStdString(game.creator_info().name()))) {
return false;
}
if (filters.hideFullGames && game.player_count() == game.max_players())
if (filters.hideFullGames && game.player_count() == game.max_players()) {
return false;
if (filters.hideGamesThatStarted && game.started())
}
if (filters.hideGamesThatStarted && game.started()) {
return false;
if (!userListProxy->isOwnUserRegistered())
if (game.only_registered())
}
if (!userListProxy->isOwnUserRegistered()) {
if (game.only_registered()) {
return false;
if (filters.hidePasswordProtectedGames && game.with_password())
}
}
if (filters.hidePasswordProtectedGames && game.with_password()) {
return false;
if (!filters.gameNameFilter.isEmpty())
if (!QString::fromStdString(game.description()).contains(filters.gameNameFilter, Qt::CaseInsensitive))
}
if (!filters.gameNameFilter.isEmpty()) {
if (!QString::fromStdString(game.description()).contains(filters.gameNameFilter, Qt::CaseInsensitive)) {
return false;
}
}
if (!filters.creatorNameFilters.isEmpty()) {
bool found = false;
for (const auto &createNameFilter : filters.creatorNameFilters) {
@ -428,15 +447,19 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow) const
}
QSet<int> gameTypes;
for (int i = 0; i < game.game_types_size(); ++i)
for (int i = 0; i < game.game_types_size(); ++i) {
gameTypes.insert(game.game_types(i));
if (!filters.gameTypeFilter.isEmpty() && gameTypes.intersect(filters.gameTypeFilter).isEmpty())
}
if (!filters.gameTypeFilter.isEmpty() && gameTypes.intersect(filters.gameTypeFilter).isEmpty()) {
return false;
}
if (static_cast<int>(game.max_players()) < filters.maxPlayersFilterMin)
if (static_cast<int>(game.max_players()) < filters.maxPlayersFilterMin) {
return false;
if (static_cast<int>(game.max_players()) > filters.maxPlayersFilterMax)
}
if (static_cast<int>(game.max_players()) > filters.maxPlayersFilterMax) {
return false;
}
if (filters.maxGameAge.isValid()) {
QDateTime now = QDateTime::currentDateTimeUtc();
@ -451,14 +474,18 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow) const
}
if (filters.showOnlyIfSpectatorsCanWatch) {
if (!game.spectators_allowed())
if (!game.spectators_allowed()) {
return false;
if (!filters.showSpectatorPasswordProtected && game.spectators_need_password())
}
if (!filters.showSpectatorPasswordProtected && game.spectators_need_password()) {
return false;
if (filters.showOnlyIfSpectatorsCanChat && !game.spectators_can_chat())
}
if (filters.showOnlyIfSpectatorsCanChat && !game.spectators_can_chat()) {
return false;
if (filters.showOnlyIfSpectatorsCanSeeHands && !game.spectators_omniscient())
}
if (filters.showOnlyIfSpectatorsCanSeeHands && !game.spectators_omniscient()) {
return false;
}
}
return true;
}

View file

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

View file

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

View file

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

View file

@ -14,14 +14,16 @@ const int RemoteReplayList_TreeModel::numberOfColumns = 6;
RemoteReplayList_TreeModel::MatchNode::MatchNode(const ServerInfo_ReplayMatch &_matchInfo)
: RemoteReplayList_TreeModel::Node(QString::fromStdString(_matchInfo.game_name())), matchInfo(_matchInfo)
{
for (int i = 0; i < matchInfo.replay_list_size(); ++i)
for (int i = 0; i < matchInfo.replay_list_size(); ++i) {
append(new ReplayNode(matchInfo.replay_list(i), this));
}
}
RemoteReplayList_TreeModel::MatchNode::~MatchNode()
{
for (int i = 0; i < size(); ++i)
for (int i = 0; i < size(); ++i) {
delete at(i);
}
}
void RemoteReplayList_TreeModel::MatchNode::updateMatchInfo(const ServerInfo_ReplayMatch &_matchInfo)
@ -45,22 +47,26 @@ RemoteReplayList_TreeModel::~RemoteReplayList_TreeModel()
int RemoteReplayList_TreeModel::rowCount(const QModelIndex &parent) const
{
if (!parent.isValid())
if (!parent.isValid()) {
return replayMatches.size();
}
auto *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(parent.internalPointer()));
if (matchNode)
if (matchNode) {
return matchNode->size();
else
} else {
return 0;
}
}
QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
if (!index.isValid()) {
return QVariant();
if (index.column() >= numberOfColumns)
}
if (index.column() >= numberOfColumns) {
return QVariant();
}
auto *replayNode = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
if (replayNode) {
@ -103,8 +109,9 @@ QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) co
return QString::fromStdString(matchInfo.game_name());
case 2: {
QStringList playerList;
for (int i = 0; i < matchInfo.player_names_size(); ++i)
for (int i = 0; i < matchInfo.player_names_size(); ++i) {
playerList.append(QString::fromStdString(matchInfo.player_names(i)));
}
return playerList.join(", ");
}
case 4:
@ -131,8 +138,9 @@ QVariant RemoteReplayList_TreeModel::data(const QModelIndex &index, int role) co
QVariant RemoteReplayList_TreeModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation != Qt::Horizontal)
if (orientation != Qt::Horizontal) {
return QVariant();
}
switch (role) {
case Qt::TextAlignmentRole:
switch (section) {
@ -167,17 +175,20 @@ QVariant RemoteReplayList_TreeModel::headerData(int section, Qt::Orientation ori
QModelIndex RemoteReplayList_TreeModel::index(int row, int column, const QModelIndex &parent) const
{
if (!hasIndex(row, column, parent))
if (!hasIndex(row, column, parent)) {
return QModelIndex();
}
auto *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(parent.internalPointer()));
if (matchNode) {
if (row >= matchNode->size())
if (row >= matchNode->size()) {
return QModelIndex();
}
return createIndex(row, column, (void *)matchNode->at(row));
} else {
if (row >= replayMatches.size())
if (row >= replayMatches.size()) {
return QModelIndex();
}
return createIndex(row, column, (void *)replayMatches[row]);
}
}
@ -185,9 +196,9 @@ QModelIndex RemoteReplayList_TreeModel::index(int row, int column, const QModelI
QModelIndex RemoteReplayList_TreeModel::parent(const QModelIndex &ind) const
{
MatchNode const *matchNode = dynamic_cast<MatchNode *>(static_cast<Node *>(ind.internalPointer()));
if (matchNode)
if (matchNode) {
return QModelIndex();
else {
} else {
auto *replayNode = dynamic_cast<ReplayNode *>(static_cast<Node *>(ind.internalPointer()));
return createIndex(replayNode->getParent()->indexOf(replayNode), 0, replayNode->getParent());
}
@ -195,45 +206,52 @@ QModelIndex RemoteReplayList_TreeModel::parent(const QModelIndex &ind) const
Qt::ItemFlags RemoteReplayList_TreeModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
if (!index.isValid()) {
return Qt::NoItemFlags;
}
return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
ServerInfo_Replay const *RemoteReplayList_TreeModel::getReplay(const QModelIndex &index) const
{
if (!index.isValid())
if (!index.isValid()) {
return 0;
}
auto *node = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
if (!node)
if (!node) {
return 0;
}
return &node->getReplayInfo();
}
ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getReplayMatch(const QModelIndex &index) const
{
if (!index.isValid())
if (!index.isValid()) {
return nullptr;
}
auto *node = dynamic_cast<MatchNode *>(static_cast<Node *>(index.internalPointer()));
if (!node)
if (!node) {
return nullptr;
}
return &node->getMatchInfo();
}
ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getEnclosingReplayMatch(const QModelIndex &index) const
{
if (!index.isValid())
if (!index.isValid()) {
return nullptr;
}
auto *node = dynamic_cast<MatchNode *>(static_cast<Node *>(index.internalPointer()));
if (!node) {
auto *_node = dynamic_cast<ReplayNode *>(static_cast<Node *>(index.internalPointer()));
if (!_node)
if (!_node) {
return nullptr;
}
return &_node->getParent()->getMatchInfo();
}
return &node->getMatchInfo();
@ -244,8 +262,9 @@ ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getEnclosingReplayMatc
*/
void RemoteReplayList_TreeModel::clearAll()
{
for (int i = 0; i < replayMatches.size(); ++i)
for (int i = 0; i < replayMatches.size(); ++i) {
delete replayMatches[i];
}
replayMatches.clear();
}
@ -275,24 +294,26 @@ void RemoteReplayList_TreeModel::addMatchInfo(const ServerInfo_ReplayMatch &matc
void RemoteReplayList_TreeModel::updateMatchInfo(int gameId, const ServerInfo_ReplayMatch &matchInfo)
{
for (int i = 0; i < replayMatches.size(); ++i)
for (int i = 0; i < replayMatches.size(); ++i) {
if (replayMatches[i]->getMatchInfo().game_id() == gameId) {
replayMatches[i]->updateMatchInfo(matchInfo);
emit dataChanged(createIndex(i, 0, (void *)replayMatches[i]),
createIndex(i, numberOfColumns - 1, (void *)replayMatches[i]));
break;
}
}
}
void RemoteReplayList_TreeModel::removeMatchInfo(int gameId)
{
for (int i = 0; i < replayMatches.size(); ++i)
for (int i = 0; i < replayMatches.size(); ++i) {
if (replayMatches[i]->getMatchInfo().game_id() == gameId) {
beginRemoveRows(QModelIndex(), i, i);
replayMatches.removeAt(i);
endRemoveRows();
break;
}
}
}
void RemoteReplayList_TreeModel::replayListFinished(const Response &r)
@ -302,8 +323,9 @@ void RemoteReplayList_TreeModel::replayListFinished(const Response &r)
beginResetModel();
clearAll();
for (int i = 0; i < resp.match_list_size(); ++i)
for (int i = 0; i < resp.match_list_size(); ++i) {
replayMatches.append(new MatchNode(resp.match_list(i)));
}
endResetModel();
emit treeRefreshed();

View file

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

View file

@ -123,17 +123,19 @@ void UserInfoBox::updateInfo(const ServerInfo_User &user)
userLevelIcon.setPixmap(UserLevelPixmapGenerator::generatePixmap(15, userLevel, user.pawn_colors(), false,
QString::fromStdString(user.privlevel())));
QString userLevelText;
if (userLevel.testFlag(ServerInfo_User::IsAdmin))
if (userLevel.testFlag(ServerInfo_User::IsAdmin)) {
userLevelText = tr("Administrator");
else if (userLevel.testFlag(ServerInfo_User::IsModerator))
} else if (userLevel.testFlag(ServerInfo_User::IsModerator)) {
userLevelText = tr("Moderator");
else if (userLevel.testFlag(ServerInfo_User::IsRegistered))
} else if (userLevel.testFlag(ServerInfo_User::IsRegistered)) {
userLevelText = tr("Registered user");
else
} else {
userLevelText = tr("Unregistered user");
}
if (userLevel.testFlag(ServerInfo_User::IsJudge))
if (userLevel.testFlag(ServerInfo_User::IsJudge)) {
userLevelText += " | " + tr("Judge");
}
if (user.has_privlevel() && user.privlevel() != "NONE") {
userLevelText += " | " + QString("%1").arg(user.privlevel().c_str());
@ -152,15 +154,17 @@ void UserInfoBox::updateInfo(const ServerInfo_User &user)
QString UserInfoBox::getAgeString(int ageSeconds)
{
QString accountAgeString = tr("Unknown");
if (ageSeconds <= 0)
if (ageSeconds <= 0) {
return accountAgeString;
}
// secsSinceEpoch is in utc
auto secsSinceEpoch = QDateTime::currentSecsSinceEpoch() - ageSeconds;
// the date is in local time, fromSecsSinceEpoch expects a timestamp from utc and converts it to local time
auto date = QDateTime::fromSecsSinceEpoch(secsSinceEpoch).date();
if (!date.isValid())
if (!date.isValid()) {
return accountAgeString;
}
// now can be local time as the date is also local time
auto now = QDate::currentDate();
@ -218,8 +222,9 @@ void UserInfoBox::actEditInternal(const Response &r)
QString realName = QString::fromStdString(user.real_name());
DlgEditUser dlg(this, email, country, realName);
if (!dlg.exec())
if (!dlg.exec()) {
return;
}
Command_AccountEdit cmd;
cmd.set_real_name(dlg.getRealName().toStdString());
@ -231,8 +236,9 @@ void UserInfoBox::actEditInternal(const Response &r)
getTextWithMax(this, tr("Enter Password"),
tr("Password verification is required in order to change your email address"),
QLineEdit::Password, "", &ok);
if (!ok)
if (!ok) {
return;
}
cmd.set_password_check(password.toStdString());
cmd.set_email(dlg.getEmail().toStdString());
} // servers that support password hash do not require all fields to be filled anymore
@ -250,8 +256,9 @@ void UserInfoBox::actEditInternal(const Response &r)
void UserInfoBox::actPassword()
{
DlgEditPassword dlg(this);
if (!dlg.exec())
if (!dlg.exec()) {
return;
}
auto oldPassword = dlg.getOldPassword();
auto newPassword = dlg.getNewPassword();
@ -296,8 +303,9 @@ void UserInfoBox::changePassword(const QString &oldPassword, const QString &newP
void UserInfoBox::actAvatar()
{
DlgEditAvatar dlg(this);
if (!dlg.exec())
if (!dlg.exec()) {
return;
}
Command_AccountImage cmd;
cmd.set_image(dlg.getImage().data(), dlg.getImage().size());

View file

@ -53,8 +53,9 @@ QStringList UserConnection_Information::getServerInfo(const QString &find)
for (int i = 0; i < size; i++) {
QString _saveName = servers.getValue(QString("saveName%1").arg(i), "server", "server_details").toString();
if (find != _saveName)
if (find != _saveName) {
continue;
}
QString serverName = servers.getValue(QString("server%1").arg(i), "server", "server_details").toString();
QString portNum = servers.getValue(QString("port%1").arg(i), "server", "server_details").toString();
@ -73,8 +74,9 @@ QStringList UserConnection_Information::getServerInfo(const QString &find)
break;
}
if (_server.empty())
if (_server.empty()) {
qCWarning(UserInfoConnectionLog) << "There was a problem!";
}
return _server;
}

View file

@ -40,8 +40,9 @@ BanDialog::BanDialog(const ServerInfo_User &info, QWidget *parent) : QDialog(par
idBanCheckBox->setChecked(true);
idBanEdit = new QLineEdit(QString::fromStdString(info.clientid()));
idBanEdit->setMaxLength(MAX_NAME_LENGTH);
if (QString::fromStdString(info.clientid()).isEmpty())
if (QString::fromStdString(info.clientid()).isEmpty()) {
idBanCheckBox->setChecked(false);
}
QGridLayout *banTypeGrid = new QGridLayout;
banTypeGrid->addWidget(nameBanCheckBox, 0, 0);
@ -207,27 +208,30 @@ void BanDialog::okClicked()
return;
}
if (nameBanCheckBox->isChecked())
if (nameBanCheckBox->isChecked()) {
if (nameBanEdit->text().simplified() == "") {
QMessageBox::critical(this, tr("Error"),
tr("You must have a value in the name ban when selecting the name ban checkbox."));
return;
}
}
if (ipBanCheckBox->isChecked())
if (ipBanCheckBox->isChecked()) {
if (ipBanEdit->text().simplified() == "") {
QMessageBox::critical(this, tr("Error"),
tr("You must have a value in the ip ban when selecting the ip ban checkbox."));
return;
}
}
if (idBanCheckBox->isChecked())
if (idBanCheckBox->isChecked()) {
if (idBanEdit->text().simplified() == "") {
QMessageBox::critical(
this, tr("Error"),
tr("You must have a value in the clientid ban when selecting the clientid ban checkbox."));
return;
}
}
accept();
}
@ -461,14 +465,15 @@ void UserListWidget::processUserInfo(const ServerInfo_User &user, bool online)
{
const QString userName = QString::fromStdString(user.name());
UserListTWI *item = users.value(userName);
if (item)
if (item) {
item->setUserInfo(user);
else {
} else {
item = new UserListTWI(user);
users.insert(userName, item);
userTree->addTopLevelItem(item);
if (online)
if (online) {
++onlineCount;
}
updateCount();
}
item->setOnline(online);
@ -480,8 +485,9 @@ bool UserListWidget::deleteUser(const QString &userName)
if (twi) {
users.remove(userName);
userTree->takeTopLevelItem(userTree->indexOfTopLevelItem(twi));
if (twi->data(0, Qt::UserRole + 1).toBool())
if (twi->data(0, Qt::UserRole + 1).toBool()) {
--onlineCount;
}
delete twi;
updateCount();
return true;
@ -493,22 +499,25 @@ bool UserListWidget::deleteUser(const QString &userName)
void UserListWidget::setUserOnline(const QString &userName, bool online)
{
UserListTWI *twi = users.value(userName);
if (!twi)
if (!twi) {
return;
}
twi->setOnline(online);
if (online)
if (online) {
++onlineCount;
else
} else {
--onlineCount;
}
updateCount();
}
void UserListWidget::updateCount()
{
QString str = titleStr;
if ((type == BuddyList) || (type == IgnoreList))
if ((type == BuddyList) || (type == IgnoreList)) {
str = str.arg(onlineCount);
}
setTitle(str.arg(userTree->topLevelItemCount()));
}

View file

@ -144,10 +144,11 @@ void AbstractTabDeckEditor::addCardHelper(const ExactCard &card, const QString &
*/
void AbstractTabDeckEditor::actAddCard(const ExactCard &card)
{
if (QApplication::keyboardModifiers() & Qt::ControlModifier)
if (QApplication::keyboardModifiers() & Qt::ControlModifier) {
actAddCardToSideboard(card);
else
} else {
addCardHelper(card, DECK_ZONE_MAIN);
}
deckMenu->setSaveStatus(true);
}
@ -201,8 +202,9 @@ void AbstractTabDeckEditor::setDeck(const LoadedDeck &_deck)
void AbstractTabDeckEditor::actNewDeck()
{
auto deckOpenLocation = confirmOpen(false);
if (deckOpenLocation == CANCELLED)
if (deckOpenLocation == CANCELLED) {
return;
}
if (deckOpenLocation == NEW_TAB) {
emit openDeckEditor(LoadedDeck());
@ -227,22 +229,25 @@ void AbstractTabDeckEditor::cleanDeckAndResetModified()
AbstractTabDeckEditor::DeckOpenLocation AbstractTabDeckEditor::confirmOpen(const bool openInSameTabIfBlank)
{
if (SettingsCache::instance().getOpenDeckInNewTab()) {
if (openInSameTabIfBlank && deckStateManager->isBlankNewDeck())
if (openInSameTabIfBlank && deckStateManager->isBlankNewDeck()) {
return SAME_TAB;
else
} else {
return NEW_TAB;
}
}
if (!deckStateManager->isModified())
if (!deckStateManager->isModified()) {
return SAME_TAB;
}
tabSupervisor->setCurrentWidget(this);
QMessageBox *msgBox = createSaveConfirmationWindow();
QPushButton *newTabButton = msgBox->addButton(tr("Open in new tab"), QMessageBox::ApplyRole);
int ret = msgBox->exec();
if (msgBox->clickedButton() == newTabButton)
if (msgBox->clickedButton() == newTabButton) {
return NEW_TAB;
}
switch (ret) {
case QMessageBox::Save:
@ -275,12 +280,14 @@ QMessageBox *AbstractTabDeckEditor::createSaveConfirmationWindow()
void AbstractTabDeckEditor::actLoadDeck()
{
auto deckOpenLocation = confirmOpen();
if (deckOpenLocation == CANCELLED)
if (deckOpenLocation == CANCELLED) {
return;
}
DlgLoadDeck dialog(this);
if (!dialog.exec())
if (!dialog.exec()) {
return;
}
QString fileName = dialog.selectedFiles().at(0);
openDeckFromFile(fileName, deckOpenLocation);
@ -293,8 +300,9 @@ void AbstractTabDeckEditor::actLoadDeck()
void AbstractTabDeckEditor::actOpenRecent(const QString &fileName)
{
auto deckOpenLocation = confirmOpen();
if (deckOpenLocation == CANCELLED)
if (deckOpenLocation == CANCELLED) {
return;
}
openDeckFromFile(fileName, deckOpenLocation);
}
@ -347,8 +355,9 @@ bool AbstractTabDeckEditor::actSaveDeck()
return true;
}
if (loadedDeck.lastLoadInfo.fileName.isEmpty())
if (loadedDeck.lastLoadInfo.fileName.isEmpty()) {
return actSaveDeckAs();
}
if (DeckLoader::saveToFile(loadedDeck)) {
deckStateManager->setModified(false);
@ -376,8 +385,9 @@ bool AbstractTabDeckEditor::actSaveDeckAs()
dialog.setNameFilters(DeckLoader::FILE_NAME_FILTERS);
dialog.selectFile(deckList.getName().trimmed());
if (!dialog.exec())
if (!dialog.exec()) {
return false;
}
QString fileName = dialog.selectedFiles().at(0);
DeckFileFormat::Format fmt = DeckFileFormat::getFormatFromName(fileName);
@ -403,10 +413,11 @@ bool AbstractTabDeckEditor::actSaveDeckAs()
*/
void AbstractTabDeckEditor::saveDeckRemoteFinished(const Response &response)
{
if (response.response_code() != Response::RespOk)
if (response.response_code() != Response::RespOk) {
QMessageBox::critical(this, tr("Error"), tr("The deck could not be saved."));
else
} else {
deckStateManager->setModified(false);
}
}
/**
@ -416,12 +427,14 @@ void AbstractTabDeckEditor::saveDeckRemoteFinished(const Response &response)
void AbstractTabDeckEditor::actLoadDeckFromClipboard()
{
auto deckOpenLocation = confirmOpen();
if (deckOpenLocation == CANCELLED)
if (deckOpenLocation == CANCELLED) {
return;
}
DlgLoadDeckFromClipboard dlg(this);
if (!dlg.exec())
if (!dlg.exec()) {
return;
}
if (deckOpenLocation == NEW_TAB) {
emit openDeckEditor({.deckList = dlg.getDeckList()});
@ -441,8 +454,9 @@ void AbstractTabDeckEditor::editDeckInClipboard(bool annotated)
{
LoadedDeck loadedDeck = deckStateManager->toLoadedDeck();
DlgEditDeckInClipboard dlg(loadedDeck.deckList, annotated, this);
if (!dlg.exec())
if (!dlg.exec()) {
return;
}
setDeck({dlg.getDeckList(), loadedDeck.lastLoadInfo});
deckStateManager->setModified(true);
@ -500,12 +514,14 @@ void AbstractTabDeckEditor::actPrintDeck()
void AbstractTabDeckEditor::actLoadDeckFromWebsite()
{
auto deckOpenLocation = confirmOpen();
if (deckOpenLocation == CANCELLED)
if (deckOpenLocation == CANCELLED) {
return;
}
DlgLoadDeckFromWebsite dlg(this);
if (!dlg.exec())
if (!dlg.exec()) {
return;
}
if (deckOpenLocation == NEW_TAB) {
emit openDeckEditor({.deckList = dlg.getDeck()});
@ -588,10 +604,11 @@ bool AbstractTabDeckEditor::confirmClose()
if (deckStateManager->isModified()) {
tabSupervisor->setCurrentWidget(this);
int ret = createSaveConfirmationWindow()->exec();
if (ret == QMessageBox::Save)
if (ret == QMessageBox::Save) {
return actSaveDeck();
else if (ret == QMessageBox::Cancel)
} else if (ret == QMessageBox::Cancel) {
return false;
}
}
return true;
}
@ -599,7 +616,8 @@ bool AbstractTabDeckEditor::confirmClose()
/** @brief Handles close requests from outside (tab manager). */
bool AbstractTabDeckEditor::closeRequest()
{
if (!confirmClose())
if (!confirmClose()) {
return false;
}
return close();
}

View file

@ -98,55 +98,79 @@ inline static DeckFormat apiNameToFormat(const QString &name)
{
const QString n = name.trimmed();
if (n.compare("Standard", Qt::CaseInsensitive) == 0)
if (n.compare("Standard", Qt::CaseInsensitive) == 0) {
return DeckFormat::Standard;
if (n.compare("Modern", Qt::CaseInsensitive) == 0)
}
if (n.compare("Modern", Qt::CaseInsensitive) == 0) {
return DeckFormat::Modern;
if (n.compare("Commander", Qt::CaseInsensitive) == 0)
}
if (n.compare("Commander", Qt::CaseInsensitive) == 0) {
return DeckFormat::Commander;
if (n.compare("Legacy", Qt::CaseInsensitive) == 0)
}
if (n.compare("Legacy", Qt::CaseInsensitive) == 0) {
return DeckFormat::Legacy;
if (n.compare("Vintage", Qt::CaseInsensitive) == 0)
}
if (n.compare("Vintage", Qt::CaseInsensitive) == 0) {
return DeckFormat::Vintage;
if (n.compare("Pauper", Qt::CaseInsensitive) == 0)
}
if (n.compare("Pauper", Qt::CaseInsensitive) == 0) {
return DeckFormat::Pauper;
if (n.compare("Custom", Qt::CaseInsensitive) == 0)
}
if (n.compare("Custom", Qt::CaseInsensitive) == 0) {
return DeckFormat::Custom;
if (n.compare("Frontier", Qt::CaseInsensitive) == 0)
}
if (n.compare("Frontier", Qt::CaseInsensitive) == 0) {
return DeckFormat::Frontier;
if (n.compare("Future Std", Qt::CaseInsensitive) == 0)
}
if (n.compare("Future Std", Qt::CaseInsensitive) == 0) {
return DeckFormat::FutureStandard;
if (n.compare("Penny Dreadful", Qt::CaseInsensitive) == 0)
}
if (n.compare("Penny Dreadful", Qt::CaseInsensitive) == 0) {
return DeckFormat::PennyDreadful;
if (n.compare("1v1 Commander", Qt::CaseInsensitive) == 0)
}
if (n.compare("1v1 Commander", Qt::CaseInsensitive) == 0) {
return DeckFormat::Commander1v1;
if (n.compare("Dual Commander", Qt::CaseInsensitive) == 0)
}
if (n.compare("Dual Commander", Qt::CaseInsensitive) == 0) {
return DeckFormat::DualCommander;
if (n.compare("Brawl", Qt::CaseInsensitive) == 0)
}
if (n.compare("Brawl", Qt::CaseInsensitive) == 0) {
return DeckFormat::Brawl;
}
if (n.compare("Alchemy", Qt::CaseInsensitive) == 0)
if (n.compare("Alchemy", Qt::CaseInsensitive) == 0) {
return DeckFormat::Alchemy;
if (n.compare("Historic", Qt::CaseInsensitive) == 0)
}
if (n.compare("Historic", Qt::CaseInsensitive) == 0) {
return DeckFormat::Historic;
if (n.compare("Gladiator", Qt::CaseInsensitive) == 0)
}
if (n.compare("Gladiator", Qt::CaseInsensitive) == 0) {
return DeckFormat::Gladiator;
if (n.compare("Oathbreaker", Qt::CaseInsensitive) == 0)
}
if (n.compare("Oathbreaker", Qt::CaseInsensitive) == 0) {
return DeckFormat::Oathbreaker;
if (n.compare("Old School", Qt::CaseInsensitive) == 0)
}
if (n.compare("Old School", Qt::CaseInsensitive) == 0) {
return DeckFormat::OldSchool;
if (n.compare("Pauper Commander", Qt::CaseInsensitive) == 0)
}
if (n.compare("Pauper Commander", Qt::CaseInsensitive) == 0) {
return DeckFormat::PauperCommander;
if (n.compare("Pioneer", Qt::CaseInsensitive) == 0)
}
if (n.compare("Pioneer", Qt::CaseInsensitive) == 0) {
return DeckFormat::Pioneer;
if (n.compare("PreDH", Qt::CaseInsensitive) == 0)
}
if (n.compare("PreDH", Qt::CaseInsensitive) == 0) {
return DeckFormat::PreDH;
if (n.compare("Premodern", Qt::CaseInsensitive) == 0)
}
if (n.compare("Premodern", Qt::CaseInsensitive) == 0) {
return DeckFormat::Premodern;
if (n.compare("Standard Brawl", Qt::CaseInsensitive) == 0)
}
if (n.compare("Standard Brawl", Qt::CaseInsensitive) == 0) {
return DeckFormat::StandardBrawl;
if (n.compare("Timeless", Qt::CaseInsensitive) == 0)
}
if (n.compare("Timeless", Qt::CaseInsensitive) == 0) {
return DeckFormat::Timeless;
}
return DeckFormat::Unknown;
}

View file

@ -20,21 +20,27 @@ static QString timeAgo(const QString &timestamp)
{
QDateTime dt = QDateTime::fromString(timestamp, Qt::ISODate);
if (!dt.isValid())
if (!dt.isValid()) {
return timestamp; // fallback if parsing fails
}
qint64 secs = dt.secsTo(QDateTime::currentDateTimeUtc());
if (secs < 60)
if (secs < 60) {
return QString("%1 seconds ago").arg(secs);
if (secs < 3600)
}
if (secs < 3600) {
return QString("%1 minutes ago").arg(secs / 60);
if (secs < 86400)
}
if (secs < 86400) {
return QString("%1 hours ago").arg(secs / 3600);
if (secs < 30 * 86400)
}
if (secs < 30 * 86400) {
return QString("%1 days ago").arg(secs / 86400);
if (secs < 365 * 86400)
}
if (secs < 365 * 86400) {
return QString("%1 months ago").arg(secs / (30 * 86400));
}
return QString("%1 years ago").arg(secs / (365 * 86400));
}

View file

@ -93,10 +93,11 @@ void TabArchidekt::initializeUi()
colorLayout->addWidget(manaSymbol);
connect(manaSymbol, &ManaSymbolWidget::colorToggled, this, [this](QChar c, bool active) {
if (active)
if (active) {
activeColors.insert(c);
else
} else {
activeColors.remove(c);
}
doSearch();
});
}
@ -298,16 +299,18 @@ void TabArchidekt::setupFilterWidgets()
searchModel->updateSearchResults(text);
QString pattern = ".*" + QRegularExpression::escape(text) + ".*";
proxyModel->setFilterRegularExpression(QRegularExpression(pattern, QRegularExpression::CaseInsensitiveOption));
if (!text.isEmpty())
if (!text.isEmpty()) {
completer->complete();
}
});
connect(commandersField, &QLineEdit::textChanged, this, [=](const QString &text) {
searchModel->updateSearchResults(text);
QString pattern = ".*" + QRegularExpression::escape(text) + ".*";
proxyModel->setFilterRegularExpression(QRegularExpression(pattern, QRegularExpression::CaseInsensitiveOption));
if (!text.isEmpty())
if (!text.isEmpty()) {
completer->complete();
}
});
// Assemble secondary toolbar
@ -492,12 +495,13 @@ QString TabArchidekt::buildSearchUrl()
QString logic = "GTE";
QString selected = minDeckSizeLogicCombo->currentText();
if (selected == "")
if (selected == "") {
logic = "GTE";
else if (selected == "")
} else if (selected == "") {
logic = "LTE";
else
} else {
logic = "";
}
if (!logic.isEmpty()) {
query.addQueryItem("sizeLogic", logic);

View file

@ -81,8 +81,9 @@ void TabDeckEditor::createMenus()
QString TabDeckEditor::getTabText() const
{
QString result = tr("Deck: %1").arg(deckStateManager->getSimpleDeckName());
if (deckStateManager->isModified())
if (deckStateManager->isModified()) {
result.prepend("* ");
}
return result;
}
@ -137,9 +138,9 @@ void TabDeckEditor::loadLayout()
LayoutsSettings &layouts = SettingsCache::instance().layouts();
auto layoutState = layouts.getDeckEditorLayoutState();
if (layoutState.isNull())
if (layoutState.isNull()) {
restartLayout();
else {
} else {
restoreState(layoutState);
restoreGeometry(layouts.getDeckEditorGeometry());
}

View file

@ -181,8 +181,9 @@ void TabDeckStorage::retranslateUi()
QString TabDeckStorage::getTargetPath() const
{
RemoteDeckList_TreeModel::Node *curRight = serverDirView->getCurrentItem();
if (curRight == nullptr)
if (curRight == nullptr) {
return {};
}
auto *dir = dynamic_cast<RemoteDeckList_TreeModel::DirectoryNode *>(curRight);
if (dir == nullptr) {
dir = dynamic_cast<RemoteDeckList_TreeModel::DirectoryNode *>(curRight->getParent());
@ -237,13 +238,15 @@ void TabDeckStorage::actOpenLocalDeck()
{
QModelIndexList curLefts = localDirView->selectionModel()->selectedRows();
for (const auto &curLeft : curLefts) {
if (localDirModel->isDir(curLeft))
if (localDirModel->isDir(curLeft)) {
continue;
}
QString filePath = localDirModel->filePath(curLeft);
std::optional<LoadedDeck> deckOpt = DeckLoader::loadFromFile(filePath, DeckFileFormat::Cockatrice, true);
if (!deckOpt)
if (!deckOpt) {
continue;
}
emit openDeckEditor(deckOpt.value());
}
@ -320,10 +323,12 @@ void TabDeckStorage::uploadDeck(const QString &filePath, const QString &targetPa
QString deckName =
getTextWithMax(this, tr("Enter deck name"), tr("This decklist does not have a name.\nPlease enter a name:"),
QLineEdit::Normal, deckFileInfo.completeBaseName(), &ok);
if (!ok)
if (!ok) {
return;
if (deckName.isEmpty())
}
if (deckName.isEmpty()) {
deckName = tr("Unnamed deck");
}
deck.setName(deckName);
} else {
deck.setName(deck.getName().left(MAX_NAME_LENGTH));
@ -372,8 +377,9 @@ void TabDeckStorage::actNewLocalFolder()
bool ok;
QString folderName =
QInputDialog::getText(this, tr("New folder"), tr("Name of new folder:"), QLineEdit::Normal, "", &ok);
if (!ok || folderName.isEmpty())
if (!ok || folderName.isEmpty()) {
return;
}
localDirModel->mkdir(dirIndex, folderName);
}
@ -387,8 +393,9 @@ void TabDeckStorage::actDeleteLocalDeck()
}
if (QMessageBox::warning(this, tr("Delete local file"), tr("Are you sure you want to delete the selected files?"),
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes)
QMessageBox::Yes | QMessageBox::No) != QMessageBox::Yes) {
return;
}
for (const auto &curLeft : curLefts) {
if (curLeft.isValid()) {
@ -414,8 +421,9 @@ void TabDeckStorage::actOpenRemoteDeck()
{
for (const auto &curRight : serverDirView->getCurrentSelection()) {
RemoteDeckList_TreeModel::FileNode *node = dynamic_cast<RemoteDeckList_TreeModel::FileNode *>(curRight);
if (!node)
if (!node) {
continue;
}
Command_DeckDownload cmd;
cmd.set_deck_id(node->getId());
@ -428,15 +436,17 @@ void TabDeckStorage::actOpenRemoteDeck()
void TabDeckStorage::openRemoteDeckFinished(const Response &r, const CommandContainer &commandContainer)
{
if (r.response_code() != Response::RespOk)
if (r.response_code() != Response::RespOk) {
return;
}
const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext);
const Command_DeckDownload &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDownload::ext);
std::optional<LoadedDeck> deckOpt = DeckLoader::loadFromRemote(QString::fromStdString(resp.deck()), cmd.deck_id());
if (!deckOpt)
if (!deckOpt) {
return;
}
emit openDeckEditor(deckOpt.value());
}
@ -488,8 +498,9 @@ void TabDeckStorage::downloadFinished(const Response &r,
const CommandContainer & /*commandContainer*/,
const QVariant &extraData)
{
if (r.response_code() != Response::RespOk)
if (r.response_code() != Response::RespOk) {
return;
}
const Response_DeckDownload &resp = r.GetExtension(Response_DeckDownload::ext);
QString filePath = extraData.toString();
@ -504,12 +515,14 @@ void TabDeckStorage::actNewFolder()
QString targetPath = getTargetPath();
int max_length = MAX_NAME_LENGTH - targetPath.length() - 1; // generated length would be path + / + name
if (max_length < 1) // can't create path that's short enough
if (max_length < 1) { // can't create path that's short enough
return;
}
QString folderName = getTextWithMax(this, tr("New folder"), tr("Name of new folder:"), max_length);
if (folderName.isEmpty())
if (folderName.isEmpty()) {
return;
}
// '/' isn't a valid filename character on *nix so we're choosing to replace it with a different arbitrary
// character.
@ -527,8 +540,9 @@ void TabDeckStorage::actNewFolder()
void TabDeckStorage::newFolderFinished(const Response &response, const CommandContainer &commandContainer)
{
if (response.response_code() != Response::RespOk)
if (response.response_code() != Response::RespOk) {
return;
}
const Command_DeckNewDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckNewDir::ext);
serverDirView->addFolderToTree(QString::fromStdString(cmd.dir_name()),
@ -562,8 +576,9 @@ void TabDeckStorage::deleteRemoteDeck(const RemoteDeckList_TreeModel::Node *curR
PendingCommand *pend;
if (const auto *dir = dynamic_cast<const RemoteDeckList_TreeModel::DirectoryNode *>(curRight)) {
QString targetPath = dir->getPath();
if (targetPath.isEmpty())
if (targetPath.isEmpty()) {
return;
}
if (targetPath.length() > MAX_NAME_LENGTH) {
qCritical() << "target path to delete is too long" << targetPath;
return;
@ -585,22 +600,26 @@ void TabDeckStorage::deleteRemoteDeck(const RemoteDeckList_TreeModel::Node *curR
void TabDeckStorage::deleteDeckFinished(const Response &response, const CommandContainer &commandContainer)
{
if (response.response_code() != Response::RespOk)
if (response.response_code() != Response::RespOk) {
return;
}
const Command_DeckDel &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDel::ext);
RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeById(cmd.deck_id());
if (toDelete)
if (toDelete) {
serverDirView->removeNode(toDelete);
}
}
void TabDeckStorage::deleteFolderFinished(const Response &response, const CommandContainer &commandContainer)
{
if (response.response_code() != Response::RespOk)
if (response.response_code() != Response::RespOk) {
return;
}
const Command_DeckDelDir &cmd = commandContainer.session_command(0).GetExtension(Command_DeckDelDir::ext);
RemoteDeckList_TreeModel::Node *toDelete = serverDirView->getNodeByPath(QString::fromStdString(cmd.path()));
if (toDelete)
if (toDelete) {
serverDirView->removeNode(toDelete);
}
}

View file

@ -125,8 +125,9 @@ TabGame::TabGame(TabSupervisor *_tabSupervisor,
refreshShortcuts();
// append game to rooms game list for others to see
for (int i = game->getGameMetaInfo()->gameTypesSize() - 1; i >= 0; i--)
for (int i = game->getGameMetaInfo()->gameTypesSize() - 1; i >= 0; i--) {
gameTypes.append(game->getGameMetaInfo()->findRoomGameType(i));
}
QTimer::singleShot(0, this, &TabGame::loadLayout);
}
@ -282,12 +283,14 @@ void TabGame::retranslateUi()
updatePlayerListDockTitle();
cardInfoDock->setWindowTitle(tr("Card Info") + (cardInfoDock->isWindow() ? tabText : QString()));
messageLayoutDock->setWindowTitle(tr("Messages") + (messageLayoutDock->isWindow() ? tabText : QString()));
if (replayDock)
if (replayDock) {
replayDock->setWindowTitle(tr("Replay Timeline") + (replayDock->isWindow() ? tabText : QString()));
}
if (phasesMenu) {
for (int i = 0; i < phaseActions.size(); ++i)
for (int i = 0; i < phaseActions.size(); ++i) {
phaseActions[i]->setText(phasesToolbar->getLongPhaseName(i));
}
phasesMenu->setTitle(tr("&Phases"));
}
@ -313,8 +316,9 @@ void TabGame::retranslateUi()
if (aRotateViewCCW) {
aRotateViewCCW->setText(tr("Rotate View Co&unterclockwise"));
}
if (aGameInfo)
if (aGameInfo) {
aGameInfo->setText(tr("Game &information"));
}
if (aConcede) {
if (game->getPlayerManager()->isMainPlayerConceded()) {
aConcede->setText(tr("Un&concede"));
@ -361,11 +365,13 @@ void TabGame::retranslateUi()
QMapIterator<int, Player *> i(game->getPlayerManager()->getPlayers());
while (i.hasNext())
while (i.hasNext()) {
i.next().value()->getGraphicsItem()->retranslateUi();
}
QMapIterator<int, TabbedDeckViewContainer *> j(deckViewContainers);
while (j.hasNext())
while (j.hasNext()) {
j.next().value()->playerDeckView->retranslateUi();
}
scene->retranslateUi();
}
@ -484,18 +490,21 @@ void TabGame::actGameInfo()
void TabGame::actConcede()
{
Player *player = game->getPlayerManager()->getActiveLocalPlayer(game->getGameState()->getActivePlayer());
if (player == nullptr)
if (player == nullptr) {
return;
}
if (!player->getConceded()) {
if (QMessageBox::question(this, tr("Concede"), tr("Are you sure you want to concede this game?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
return;
}
emit game->getPlayerManager()->activeLocalPlayerConceded();
} else {
if (QMessageBox::question(this, tr("Unconcede"),
tr("You have already conceded. Do you want to return to this game?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
return;
}
emit game->getPlayerManager()->activeLocalPlayerUnconceded();
}
}
@ -511,20 +520,23 @@ bool TabGame::leaveGame()
if (!game->getPlayerManager()->isSpectator()) {
tabSupervisor->setCurrentWidget(this);
if (QMessageBox::question(this, tr("Leave game"), tr("Are you sure you want to leave this game?"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes)
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) != QMessageBox::Yes) {
return false;
}
}
if (!replayDock)
if (!replayDock) {
emit gameLeft();
}
}
return true;
}
void TabGame::actSay()
{
if (completer->popup()->isVisible())
if (completer->popup()->isVisible()) {
return;
}
if (sayEdit->text().startsWith("/card ")) {
cardInfoFrameWidget->setCard(sayEdit->text().mid(6));
@ -569,8 +581,9 @@ void TabGame::actPhaseAction()
void TabGame::actNextPhase()
{
int phase = game->getGameState()->getCurrentPhase();
if (++phase >= phasesToolbar->phaseCount())
if (++phase >= phasesToolbar->phaseCount()) {
phase = 0;
}
emit phaseChanged(phase);
}
@ -596,8 +609,9 @@ void TabGame::actRemoveLocalArrows()
QMapIterator<int, Player *> playerIterator(game->getPlayerManager()->getPlayers());
while (playerIterator.hasNext()) {
Player *player = playerIterator.next().value();
if (!player->getPlayerInfo()->getLocal())
if (!player->getPlayerInfo()->getLocal()) {
continue;
}
QMapIterator<int, ArrowItem *> arrowIterator(player->getArrows());
while (arrowIterator.hasNext()) {
ArrowItem *a = arrowIterator.next().value();
@ -807,8 +821,9 @@ void TabGame::startGame(bool _resuming)
if (!_resuming) {
QMapIterator<int, Player *> playerIterator(game->getPlayerManager()->getPlayers());
while (playerIterator.hasNext())
while (playerIterator.hasNext()) {
playerIterator.next().value()->setGameStarted();
}
}
playerListWidget->setGameStarted(true, game->getGameState()->isResuming());
@ -851,8 +866,9 @@ void TabGame::closeGame()
Player *TabGame::setActivePlayer(int id)
{
Player *player = game->getPlayerManager()->getPlayer(id);
if (!player)
if (!player) {
return nullptr;
}
playerListWidget->setActivePlayer(id);
QMapIterator<int, Player *> i(game->getPlayerManager()->getPlayers());
@ -894,26 +910,31 @@ QString TabGame::getTabText() const
QString gameTypeInfo;
if (!gameTypes.empty()) {
gameTypeInfo = gameTypes.at(0);
if (gameTypes.size() > 1)
if (gameTypes.size() > 1) {
gameTypeInfo.append("...");
}
}
QString gameDesc(game->getGameMetaInfo()->description());
QString gameId(QString::number(game->getGameMetaInfo()->gameId()));
QString tabText;
if (replayDock)
if (replayDock) {
tabText.append(tr("Replay") + " ");
if (!gameTypeInfo.isEmpty())
tabText.append(gameTypeInfo + " ");
if (!gameDesc.isEmpty()) {
if (gameDesc.length() >= 15)
tabText.append("| " + gameDesc.left(15) + "... ");
else
tabText.append("| " + gameDesc + " ");
}
if (!tabText.isEmpty())
if (!gameTypeInfo.isEmpty()) {
tabText.append(gameTypeInfo + " ");
}
if (!gameDesc.isEmpty()) {
if (gameDesc.length() >= 15) {
tabText.append("| " + gameDesc.left(15) + "... ");
} else {
tabText.append("| " + gameDesc + " ");
}
}
if (!tabText.isEmpty()) {
tabText.append("| ");
}
tabText.append("#" + gameId);
return tabText;
@ -1127,9 +1148,10 @@ void TabGame::actResetLayout()
void TabGame::createPlayAreaWidget(bool bReplay)
{
phasesToolbar = new PhasesToolbar;
if (!bReplay)
if (!bReplay) {
connect(phasesToolbar, &PhasesToolbar::sendGameCommand, game->getGameEventHandler(),
qOverload<const ::google::protobuf::Message &, int>(&GameEventHandler::sendGameCommand));
}
scene = new GameScene(phasesToolbar, this);
connect(game->getPlayerManager(), &PlayerManager::playerConceded, scene, &GameScene::rearrange);
connect(game->getPlayerManager(), &PlayerManager::playerCountChanged, scene, &GameScene::rearrange);

View file

@ -83,18 +83,22 @@ void TabLog::getClicked()
privateChat->setChecked(true);
}
if (maximumResults->value() == 0)
if (maximumResults->value() == 0) {
maximumResults->setValue(1000);
}
int dateRange = 0;
if (lastHour->isChecked())
if (lastHour->isChecked()) {
dateRange = 1;
}
if (today->isChecked())
if (today->isChecked()) {
dateRange = 24;
}
if (pastDays->isChecked())
if (pastDays->isChecked()) {
dateRange = pastXDays->value() * 24;
}
Command_ViewLogHistory cmd;
cmd.set_user_name(findUsername->text().toStdString());

View file

@ -72,8 +72,9 @@ void TabMessage::retranslateUi()
void TabMessage::tabActivated()
{
if (!sayEdit->hasFocus())
if (!sayEdit->hasFocus()) {
sayEdit->setFocus();
}
}
QString TabMessage::getUserName() const
@ -94,8 +95,9 @@ void TabMessage::closeEvent(QCloseEvent *event)
void TabMessage::sendMessage()
{
if (sayEdit->text().isEmpty() || !userOnline)
if (sayEdit->text().isEmpty() || !userOnline) {
return;
}
Command_Message cmd;
cmd.set_user_name(otherUserInfo->name());
@ -110,9 +112,10 @@ void TabMessage::sendMessage()
void TabMessage::messageSent(const Response &response)
{
if (response.response_code() == Response::RespInIgnoreList)
if (response.response_code() == Response::RespInIgnoreList) {
chatView->appendMessage(tr(
"This user is ignoring you, they cannot see your messages in main chat and you cannot join their games."));
}
}
void TabMessage::processUserMessageEvent(const Event_UserMessage &event)
@ -120,12 +123,15 @@ void TabMessage::processUserMessageEvent(const Event_UserMessage &event)
auto userInfo = event.sender_name() == otherUserInfo->name() ? otherUserInfo : ownUserInfo;
chatView->appendMessage(QString::fromStdString(event.message()), {}, *userInfo, true);
if (tabSupervisor->currentIndex() != tabSupervisor->indexOf(this))
if (tabSupervisor->currentIndex() != tabSupervisor->indexOf(this)) {
soundEngine->playSound("private_message");
if (SettingsCache::instance().getShowMessagePopup() && shouldShowSystemPopup(event))
}
if (SettingsCache::instance().getShowMessagePopup() && shouldShowSystemPopup(event)) {
showSystemPopup(event);
if (QString::fromStdString(event.sender_name()).toLower().simplified() == "servatrice")
}
if (QString::fromStdString(event.sender_name()).toLower().simplified() == "servatrice") {
sayEdit->setDisabled(true);
}
emit userEvent();
}

View file

@ -256,13 +256,15 @@ void TabReplays::actOpenLocalReplay()
{
QModelIndexList curLefts = localDirView->selectionModel()->selectedRows();
for (const auto &curLeft : curLefts) {
if (localDirModel->isDir(curLeft))
if (localDirModel->isDir(curLeft)) {
continue;
}
QString filePath = localDirModel->filePath(curLeft);
QFile f(filePath);
if (!f.open(QIODevice::ReadOnly))
if (!f.open(QIODevice::ReadOnly)) {
continue;
}
QByteArray _data = f.readAll();
f.close();
@ -319,8 +321,9 @@ void TabReplays::actNewLocalFolder()
bool ok;
QString folderName =
QInputDialog::getText(this, tr("New folder"), tr("Name of new folder:"), QLineEdit::Normal, "", &ok);
if (!ok || folderName.isEmpty())
if (!ok || folderName.isEmpty()) {
return;
}
localDirModel->mkdir(dirIndex, folderName);
}
@ -378,8 +381,9 @@ void TabReplays::actOpenRemoteReplay()
void TabReplays::openRemoteReplayFinished(const Response &r)
{
if (r.response_code() != Response::RespOk)
if (r.response_code() != Response::RespOk) {
return;
}
const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext);
GameReplay *replay = new GameReplay;
@ -438,8 +442,9 @@ void TabReplays::downloadFinished(const Response &r,
const CommandContainer & /* commandContainer */,
const QVariant &extraData)
{
if (r.response_code() != Response::RespOk)
if (r.response_code() != Response::RespOk) {
return;
}
const Response_ReplayDownload &resp = r.GetExtension(Response_ReplayDownload::ext);
QString filePath = extraData.toString();
@ -475,8 +480,9 @@ void TabReplays::actKeepRemoteReplay()
void TabReplays::keepRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer)
{
if (r.response_code() != Response::RespOk)
if (r.response_code() != Response::RespOk) {
return;
}
const Command_ReplayModifyMatch &cmd =
commandContainer.session_command(0).GetExtension(Command_ReplayModifyMatch::ext);
@ -513,8 +519,9 @@ void TabReplays::actDeleteRemoteReplay()
void TabReplays::deleteRemoteReplayFinished(const Response &r, const CommandContainer &commandContainer)
{
if (r.response_code() != Response::RespOk)
if (r.response_code() != Response::RespOk) {
return;
}
const Command_ReplayDeleteMatch &cmd =
commandContainer.session_command(0).GetExtension(Command_ReplayDeleteMatch::ext);

View file

@ -41,9 +41,10 @@ TabRoom::TabRoom(TabSupervisor *_tabSupervisor,
ownUser(_ownUser), userListProxy(_tabSupervisor->getUserListManager())
{
const int gameTypeListSize = info.gametype_list_size();
for (int i = 0; i < gameTypeListSize; ++i)
for (int i = 0; i < gameTypeListSize; ++i) {
gameTypes.insert(info.gametype_list(i).game_type_id(),
QString::fromStdString(info.gametype_list(i).description()));
}
QMap<int, GameTypeMap> tempMap;
tempMap.insert(info.room_id(), gameTypes);
@ -117,8 +118,9 @@ TabRoom::TabRoom(TabSupervisor *_tabSupervisor,
userList->sortItems();
const int gameListSize = info.game_list_size();
for (int i = 0; i < gameListSize; ++i)
for (int i = 0; i < gameListSize; ++i) {
gameSelector->processGameInfo(info.game_list(i));
}
completer = new QCompleter(autocompleteUserList, sayEdit);
completer->setCaseSensitivity(Qt::CaseInsensitive);
@ -182,8 +184,9 @@ void TabRoom::closeEvent(QCloseEvent *event)
void TabRoom::tabActivated()
{
if (!sayEdit->hasFocus())
if (!sayEdit->hasFocus()) {
sayEdit->setFocus();
}
}
QString TabRoom::sanitizeHtml(QString dirty) const
@ -211,8 +214,9 @@ void TabRoom::sendMessage()
void TabRoom::sayFinished(const Response &response)
{
if (response.response_code() == Response::RespChatFlood)
if (response.response_code() == Response::RespChatFlood) {
chatView->appendMessage(tr("You are flooding the chat. Please wait a couple of seconds."));
}
}
void TabRoom::actClearChat()
@ -258,8 +262,9 @@ void TabRoom::processRoomEvent(const RoomEvent &event)
void TabRoom::processListGamesEvent(const Event_ListGames &event)
{
const int gameListSize = event.game_list_size();
for (int i = 0; i < gameListSize; ++i)
for (int i = 0; i < gameListSize; ++i) {
gameSelector->processGameInfo(event.game_list(i));
}
}
void TabRoom::processJoinRoomEvent(const Event_JoinRoom &event)
@ -284,26 +289,30 @@ void TabRoom::processRoomSayEvent(const Event_RoomSay &event)
QString senderName = QString::fromStdString(event.name());
QString message = QString::fromStdString(event.message());
if (userListProxy->isUserIgnored(senderName))
if (userListProxy->isUserIgnored(senderName)) {
return;
}
UserListTWI *twi = userList->getUsers().value(senderName);
ServerInfo_User userInfo = {};
if (twi) {
userInfo = twi->getUserInfo();
if (SettingsCache::instance().getIgnoreUnregisteredUsers() &&
!UserLevelFlags(userInfo.user_level()).testFlag(ServerInfo_User::IsRegistered))
!UserLevelFlags(userInfo.user_level()).testFlag(ServerInfo_User::IsRegistered)) {
return;
}
}
if (event.message_type() == Event_RoomSay::ChatHistory && !SettingsCache::instance().getRoomHistory())
if (event.message_type() == Event_RoomSay::ChatHistory && !SettingsCache::instance().getRoomHistory()) {
return;
}
if (event.message_type() == Event_RoomSay::ChatHistory)
if (event.message_type() == Event_RoomSay::ChatHistory) {
message =
"[" +
QString(QDateTime::fromMSecsSinceEpoch(event.time_of()).toLocalTime().toString("d MMM yyyy HH:mm:ss")) +
"] " + message;
}
chatView->appendMessage(message, event.message_type(), userInfo, true);
emit userEvent(false);

View file

@ -69,27 +69,35 @@ void RoomSelector::processListRoomsEvent(const Event_ListRooms &event)
for (int j = 0; j < roomList->topLevelItemCount(); ++j) {
QTreeWidgetItem *twi = roomList->topLevelItem(j);
if (twi->data(0, Qt::UserRole).toInt() == room.room_id()) {
if (room.has_name())
if (room.has_name()) {
twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name()));
if (room.has_description())
}
if (room.has_description()) {
twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description()));
if (room.has_permissionlevel())
}
if (room.has_permissionlevel()) {
twi->setData(2, Qt::DisplayRole, getRoomPermissionDisplay(room));
if (room.has_player_count())
}
if (room.has_player_count()) {
twi->setData(3, Qt::DisplayRole, room.player_count());
if (room.has_game_count())
}
if (room.has_game_count()) {
twi->setData(4, Qt::DisplayRole, room.game_count());
}
return;
}
}
QTreeWidgetItem *twi = new QTreeWidgetItem;
twi->setData(0, Qt::UserRole, room.room_id());
if (room.has_name())
if (room.has_name()) {
twi->setData(0, Qt::DisplayRole, QString::fromStdString(room.name()));
if (room.has_description())
}
if (room.has_description()) {
twi->setData(1, Qt::DisplayRole, QString::fromStdString(room.description()));
if (room.has_permissionlevel())
}
if (room.has_permissionlevel()) {
twi->setData(2, Qt::DisplayRole, getRoomPermissionDisplay(room));
}
twi->setData(3, Qt::DisplayRole, room.player_count());
twi->setData(4, Qt::DisplayRole, room.game_count());
twi->setTextAlignment(2, Qt::AlignRight);
@ -97,9 +105,11 @@ void RoomSelector::processListRoomsEvent(const Event_ListRooms &event)
twi->setTextAlignment(4, Qt::AlignRight);
roomList->addTopLevelItem(twi);
if (room.has_auto_join())
if (room.auto_join())
if (room.has_auto_join()) {
if (room.auto_join()) {
emit joinRoomRequest(room.room_id(), false);
}
}
}
}
@ -113,10 +123,12 @@ QString RoomSelector::getRoomPermissionDisplay(const ServerInfo_Room &room)
*/
QString roomPermissionDisplay = QString::fromStdString(room.privilegelevel()).toLower();
if (QString::fromStdString(room.permissionlevel()).toLower() != "none")
if (QString::fromStdString(room.permissionlevel()).toLower() != "none") {
roomPermissionDisplay = QString::fromStdString(room.permissionlevel()).toLower();
if (roomPermissionDisplay == "") // catch all for misconfigured .ini room definitions
}
if (roomPermissionDisplay == "") { // catch all for misconfigured .ini room definitions
roomPermissionDisplay = "none";
}
return roomPermissionDisplay;
}
@ -124,8 +136,9 @@ QString RoomSelector::getRoomPermissionDisplay(const ServerInfo_Room &room)
void RoomSelector::joinClicked()
{
QTreeWidgetItem *twi = roomList->currentItem();
if (!twi)
if (!twi) {
return;
}
int id = twi->data(0, Qt::UserRole).toInt();
@ -185,8 +198,9 @@ void TabServer::joinRoom(int id, bool setCurrent)
return;
}
if (setCurrent)
if (setCurrent) {
tabSupervisor->setCurrentWidget((QWidget *)room);
}
}
void TabServer::joinRoomFinished(const Response &r,

View file

@ -86,18 +86,22 @@ void CloseButton::paintEvent(QPaintEvent * /*event*/)
QStyleOption opt;
opt.initFrom(this);
opt.state |= QStyle::State_AutoRaise;
if (isEnabled() && underMouse() && !isChecked() && !isDown())
if (isEnabled() && underMouse() && !isChecked() && !isDown()) {
opt.state |= QStyle::State_Raised;
if (isChecked())
}
if (isChecked()) {
opt.state |= QStyle::State_On;
if (isDown())
}
if (isDown()) {
opt.state |= QStyle::State_Sunken;
}
if (const auto *tb = qobject_cast<const QTabBar *>(parent())) {
int index = tb->currentIndex();
auto position = (QTabBar::ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, tb);
if (tb->tabButton(index, position) == this)
if (tb->tabButton(index, position) == this) {
opt.state |= QStyle::State_Selected;
}
}
style()->drawPrimitive(QStyle::PE_IndicatorTabClose, &opt, &p, this);
@ -228,20 +232,25 @@ void TabSupervisor::retranslateUi()
tabs.append(tabAccount);
tabs.append(tabLog);
QMapIterator<int, TabRoom *> roomIterator(roomTabs);
while (roomIterator.hasNext())
while (roomIterator.hasNext()) {
tabs.append(roomIterator.next().value());
}
QMapIterator<int, TabGame *> gameIterator(gameTabs);
while (gameIterator.hasNext())
while (gameIterator.hasNext()) {
tabs.append(gameIterator.next().value());
}
QListIterator<TabGame *> replayIterator(replayTabs);
while (replayIterator.hasNext())
while (replayIterator.hasNext()) {
tabs.append(replayIterator.next());
}
QListIterator<AbstractTabDeckEditor *> deckEditorIterator(deckEditorTabs);
while (deckEditorIterator.hasNext())
while (deckEditorIterator.hasNext()) {
tabs.append(deckEditorIterator.next());
}
QMapIterator<QString, TabMessage *> messageIterator(messageTabs);
while (messageIterator.hasNext())
while (messageIterator.hasNext()) {
tabs.append(messageIterator.next().value());
}
for (auto &tab : tabs) {
if (tab) {
@ -448,9 +457,10 @@ void TabSupervisor::startLocal(const QList<AbstractClient *> &_clients)
isLocalGame = true;
userInfo = new ServerInfo_User;
localClients = _clients;
for (int i = 0; i < localClients.size(); ++i)
for (int i = 0; i < localClients.size(); ++i) {
connect(localClients[i], &AbstractClient::gameEventContainerReceived, this,
&TabSupervisor::processGameEventContainer);
}
connect(localClients.first(), &AbstractClient::gameJoinedEventReceived, this, &TabSupervisor::localGameJoined);
}
@ -459,8 +469,9 @@ void TabSupervisor::startLocal(const QList<AbstractClient *> &_clients)
*/
void TabSupervisor::stop()
{
if ((!client) && localClients.isEmpty())
if ((!client) && localClients.isEmpty()) {
return;
}
resetTabsMenu();
@ -694,10 +705,12 @@ void TabSupervisor::openTabLog()
void TabSupervisor::updatePingTime(int value, int max)
{
if (!tabServer)
if (!tabServer) {
return;
if (tabServer->getContentsChanged())
}
if (tabServer->getContentsChanged()) {
return;
}
setTabIcon(indexOf(tabServer), QIcon(PingPixmapGenerator::generatePixmap(15, value, max)));
}
@ -706,12 +719,14 @@ void TabSupervisor::gameJoined(const Event_GameJoined &event)
{
QMap<int, QString> roomGameTypes;
TabRoom *room = roomTabs.value(event.game_info().room_id());
if (room)
if (room) {
roomGameTypes = room->getGameTypes();
else
for (int i = 0; i < event.game_types_size(); ++i)
} else {
for (int i = 0; i < event.game_types_size(); ++i) {
roomGameTypes.insert(event.game_types(i).game_type_id(),
QString::fromStdString(event.game_types(i).description()));
}
}
auto *tab = new TabGame(this, QList<AbstractClient *>() << client, event, roomGameTypes);
connect(tab, &TabGame::gameClosing, this, &TabSupervisor::gameLeft);
@ -740,14 +755,16 @@ void TabSupervisor::localGameJoined(const Event_GameJoined &event)
void TabSupervisor::gameLeft(TabGame *tab)
{
if (tab == currentWidget())
if (tab == currentWidget()) {
emit setMenu();
}
gameTabs.remove(tab->getGame()->getGameMetaInfo()->gameId());
removeTab(indexOf(tab));
if (!localClients.isEmpty())
if (!localClients.isEmpty()) {
stop();
}
}
void TabSupervisor::addRoomTab(const ServerInfo_Room &info, bool setCurrent)
@ -758,14 +775,16 @@ void TabSupervisor::addRoomTab(const ServerInfo_Room &info, bool setCurrent)
connect(tab, &TabRoom::openMessageDialog, this, &TabSupervisor::addMessageTab);
myAddTab(tab);
roomTabs.insert(info.room_id(), tab);
if (setCurrent)
if (setCurrent) {
setCurrentWidget(tab);
}
}
void TabSupervisor::roomLeft(TabRoom *tab)
{
if (tab == currentWidget())
if (tab == currentWidget()) {
emit setMenu();
}
roomTabs.remove(tab->getRoomId());
removeTab(indexOf(tab));
@ -793,16 +812,18 @@ void TabSupervisor::openReplay(GameReplay *replay)
void TabSupervisor::replayLeft(TabGame *tab)
{
if (tab == currentWidget())
if (tab == currentWidget()) {
emit setMenu();
}
replayTabs.removeOne(tab);
}
TabMessage *TabSupervisor::addMessageTab(const QString &receiverName, bool focus)
{
if (receiverName == QString::fromStdString(userInfo->name()))
if (receiverName == QString::fromStdString(userInfo->name())) {
return nullptr;
}
ServerInfo_User otherUser;
if (auto user = userListManager->getOnlineUser(receiverName)) {
@ -814,8 +835,9 @@ TabMessage *TabSupervisor::addMessageTab(const QString &receiverName, bool focus
TabMessage *tab;
tab = messageTabs.value(QString::fromStdString(otherUser.name()));
if (tab) {
if (focus)
if (focus) {
setCurrentWidget(tab);
}
return tab;
}
@ -824,8 +846,9 @@ TabMessage *TabSupervisor::addMessageTab(const QString &receiverName, bool focus
connect(tab, &TabMessage::maximizeClient, this, &TabSupervisor::maximizeMainWindow);
myAddTab(tab);
messageTabs.insert(receiverName, tab);
if (focus)
if (focus) {
setCurrentWidget(tab);
}
return tab;
}
@ -836,8 +859,9 @@ void TabSupervisor::maximizeMainWindow()
void TabSupervisor::talkLeft(TabMessage *tab)
{
if (tab == currentWidget())
if (tab == currentWidget()) {
emit setMenu();
}
messageTabs.remove(tab->getUserName());
removeTab(indexOf(tab));
@ -934,8 +958,9 @@ TabEdhRec *TabSupervisor::addEdhrecTab(const CardInfoPtr &cardToQuery, bool isCo
void TabSupervisor::deckEditorClosed(AbstractTabDeckEditor *tab)
{
if (tab == currentWidget())
if (tab == currentWidget()) {
emit setMenu();
}
deckEditorTabs.removeOne(tab);
removeTab(indexOf(tab));
@ -948,8 +973,9 @@ void TabSupervisor::tabUserEvent(bool globalEvent)
tab->setContentsChanged(true);
setTabIcon(indexOf(tab), QPixmap("theme:icons/tab_changed"));
}
if (globalEvent && SettingsCache::instance().getNotificationsEnabled())
if (globalEvent && SettingsCache::instance().getNotificationsEnabled()) {
QApplication::alert(this);
}
}
void TabSupervisor::updateTabText(Tab *tab, const QString &newTabText)
@ -962,39 +988,44 @@ void TabSupervisor::updateTabText(Tab *tab, const QString &newTabText)
void TabSupervisor::processRoomEvent(const RoomEvent &event)
{
TabRoom *tab = roomTabs.value(event.room_id(), 0);
if (tab)
if (tab) {
tab->processRoomEvent(event);
}
}
void TabSupervisor::processGameEventContainer(const GameEventContainer &cont)
{
TabGame *tab = gameTabs.value(cont.game_id());
if (tab)
if (tab) {
tab->getGame()->getGameEventHandler()->processGameEventContainer(cont, qobject_cast<AbstractClient *>(sender()),
{});
else
} else {
qCInfo(TabSupervisorLog) << "gameEvent: invalid gameId" << cont.game_id();
}
}
void TabSupervisor::processUserMessageEvent(const Event_UserMessage &event)
{
QString senderName = QString::fromStdString(event.sender_name());
TabMessage *tab = messageTabs.value(senderName);
if (!tab)
if (!tab) {
tab = messageTabs.value(QString::fromStdString(event.receiver_name()));
}
if (!tab) {
const ServerInfo_User *onlineUserInfo = userListManager->getOnlineUser(senderName);
if (onlineUserInfo) {
auto userLevel = UserLevelFlags(onlineUserInfo->user_level());
if (SettingsCache::instance().getIgnoreUnregisteredUserMessages() &&
!userLevel.testFlag(ServerInfo_User::IsRegistered))
!userLevel.testFlag(ServerInfo_User::IsRegistered)) {
// Flags are additive, so reg/mod/admin are all IsRegistered
return;
}
}
tab = addMessageTab(QString::fromStdString(event.sender_name()), false);
}
if (!tab)
if (!tab) {
return;
}
tab->processUserMessageEvent(event);
}
@ -1012,8 +1043,9 @@ void TabSupervisor::actShowPopup(const QString &message)
void TabSupervisor::processUserLeft(const QString &userName)
{
TabMessage *tab = messageTabs.value(userName);
if (tab)
if (tab) {
tab->processUserLeft();
}
}
void TabSupervisor::processUserJoined(const ServerInfo_User &userInfoJoined)
@ -1037,8 +1069,9 @@ void TabSupervisor::processUserJoined(const ServerInfo_User &userInfoJoined)
}
TabMessage *tab = messageTabs.value(userName);
if (tab)
if (tab) {
tab->processUserJoined(userInfoJoined);
}
}
void TabSupervisor::updateCurrent(int index)
@ -1051,8 +1084,9 @@ void TabSupervisor::updateCurrent(int index)
}
emit setMenu(static_cast<Tab *>(widget(index))->getTabMenus());
tab->tabActivated();
} else
} else {
emit setMenu();
}
}
/**
@ -1062,8 +1096,9 @@ void TabSupervisor::updateCurrent(int index)
*/
bool TabSupervisor::getAdminLocked() const
{
if (!tabAdmin)
if (!tabAdmin) {
return true;
}
return tabAdmin->getLocked();
}
@ -1087,12 +1122,13 @@ void TabSupervisor::processNotifyUserEvent(const Event_NotifyUser &event)
tr("You have been promoted. Please log out and back in for changes to take effect."));
break;
case Event_NotifyUser::WARNING: {
if (!QString::fromStdString(event.warning_reason()).simplified().isEmpty())
if (!QString::fromStdString(event.warning_reason()).simplified().isEmpty()) {
QMessageBox::warning(this, tr("Warned"),
tr("You have received a warning due to %1.\nPlease refrain from engaging in this "
"activity or further actions may be taken against you. If you have any "
"questions, please private message a moderator.")
.arg(QString::fromStdString(event.warning_reason()).simplified()));
}
break;
}
case Event_NotifyUser::CUSTOM: {

View file

@ -116,8 +116,9 @@ void TabDeckEditorVisual::createMenus()
QString TabDeckEditorVisual::getTabText() const
{
QString result = tr("Visual Deck: %1").arg(deckStateManager->getSimpleDeckName());
if (deckStateManager->isModified())
if (deckStateManager->isModified()) {
result.prepend("* ");
}
return result;
}

View file

@ -24,14 +24,18 @@ bool LineEditUnfocusable::isUnfocusShortcut(QKeyEvent *event)
QString modifier;
QString keyNoMod;
if (event->modifiers() & Qt::ShiftModifier)
if (event->modifiers() & Qt::ShiftModifier) {
modifier += "Shift+";
if (event->modifiers() & Qt::ControlModifier)
}
if (event->modifiers() & Qt::ControlModifier) {
modifier += "Ctrl+";
if (event->modifiers() & Qt::AltModifier)
}
if (event->modifiers() & Qt::AltModifier) {
modifier += "Alt+";
if (event->modifiers() & Qt::MetaModifier)
}
if (event->modifiers() & Qt::MetaModifier) {
modifier += "Meta+";
}
keyNoMod = QKeySequence(event->key()).toString();
@ -39,8 +43,9 @@ bool LineEditUnfocusable::isUnfocusShortcut(QKeyEvent *event)
QList<QKeySequence> unfocusShortcut = SettingsCache::instance().shortcuts().getShortcut("Player/unfocusTextBox");
for (const auto &unfocusKey : unfocusShortcut) {
if (key.matches(unfocusKey) == QKeySequence::ExactMatch)
if (key.matches(unfocusKey) == QKeySequence::ExactMatch) {
return true;
}
}
return false;
}
@ -79,10 +84,12 @@ void SearchLineEdit::keyPressEvent(QKeyEvent *event)
static const QVector<Qt::Key> forwardWhenEmpty = {Qt::Key_Home, Qt::Key_End};
Qt::Key key = static_cast<Qt::Key>(event->key());
if (treeView) {
if (forwardToTreeView.contains(key))
if (forwardToTreeView.contains(key)) {
QCoreApplication::sendEvent(treeView, event);
if (text().isEmpty() && forwardWhenEmpty.contains(key))
}
if (text().isEmpty() && forwardWhenEmpty.contains(key)) {
QCoreApplication::sendEvent(treeView, event);
}
}
LineEditUnfocusable::keyPressEvent(event);
}

View file

@ -46,8 +46,9 @@ void LineEditCompleter::keyPressEvent(QKeyEvent *event)
int lastIndexof = qMax(0, textValue.lastIndexOf(" "));
QString finalString = textValue.left(lastIndexof);
// Add a space if there's a word
if (finalString != "")
if (finalString != "") {
finalString += " ";
}
setText(finalString);
return;
}
@ -121,12 +122,14 @@ void LineEditCompleter::setCompleter(QCompleter *completer)
void LineEditCompleter::setCompletionList(QStringList completionList)
{
if (!c || c->popup()->isVisible())
if (!c || c->popup()->isVisible()) {
return;
}
QStringListModel *model;
model = (QStringListModel *)(c->model());
if (model == NULL)
if (model == NULL) {
model = new QStringListModel();
}
model->setStringList(completionList);
}

View file

@ -57,8 +57,9 @@ void VisualDatabaseDisplayFilterSaveLoadWidget::retranslateUi()
void VisualDatabaseDisplayFilterSaveLoadWidget::saveFilter()
{
QString filename = filenameInput->text().trimmed();
if (filename.isEmpty())
if (filename.isEmpty()) {
return;
}
QString filePath = SettingsCache::instance().getFiltersPath() + QDir::separator() + filename + ".json";
@ -88,19 +89,22 @@ void VisualDatabaseDisplayFilterSaveLoadWidget::loadFilter(const QString &filena
QString filePath = SettingsCache::instance().getFiltersPath() + QDir::separator() + filename;
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly))
if (!file.open(QIODevice::ReadOnly)) {
return;
}
QByteArray jsonData = file.readAll();
file.close();
QJsonDocument doc = QJsonDocument::fromJson(jsonData);
if (!doc.isObject())
if (!doc.isObject()) {
return;
}
QJsonObject root = doc.object();
if (!root.contains("filters") || !root["filters"].isArray())
if (!root.contains("filters") || !root["filters"].isArray()) {
return;
}
QJsonArray filtersArray = root["filters"].toArray();

View file

@ -64,8 +64,9 @@ void VisualDatabaseDisplayNameFilterWidget::actLoadFromDeck()
{
DeckListModel *deckListModel = deckEditor->deckStateManager->getModel();
if (!deckListModel)
if (!deckListModel) {
return;
}
QList<QString> cardNames = deckListModel->getCardNames();
for (auto cardName : cardNames) {
@ -78,8 +79,9 @@ void VisualDatabaseDisplayNameFilterWidget::actLoadFromDeck()
void VisualDatabaseDisplayNameFilterWidget::actLoadFromClipboard()
{
DlgLoadDeckFromClipboard dlg(this);
if (!dlg.exec())
if (!dlg.exec()) {
return;
}
QStringList cardsInClipboard = dlg.getDeckList().getCardList();
for (QString cardName : cardsInClipboard) {
@ -91,8 +93,9 @@ void VisualDatabaseDisplayNameFilterWidget::actLoadFromClipboard()
void VisualDatabaseDisplayNameFilterWidget::createNameFilter(const QString &name)
{
if (activeFilters.contains(name))
if (activeFilters.contains(name)) {
return;
}
// Create a button for the filter
auto *button = new QPushButton(name, flowWidget);

View file

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

View file

@ -112,13 +112,15 @@ static QList<ExactCard> cardNodesToExactCards(QList<const DecklistCardNode *> no
QList<ExactCard> VisualDeckEditorSampleHandWidget::getRandomCards(int amountToGet)
{
QList<ExactCard> randomCards;
if (!deckListModel)
if (!deckListModel) {
return randomCards;
}
QList<ExactCard> mainDeckCards = cardNodesToExactCards(deckListModel->getCardNodesForZone(DECK_ZONE_MAIN));
if (mainDeckCards.isEmpty())
if (mainDeckCards.isEmpty()) {
return randomCards;
}
// Shuffle the deck
std::random_device rd;

View file

@ -78,8 +78,9 @@ void VisualDeckEditorWidget::initializeSearchBarAndCompleter()
searchBar = new QLineEdit(searchContainer);
searchContainer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
connect(searchBar, &QLineEdit::returnPressed, this, [=, this]() {
if (!searchBar->hasFocus())
if (!searchBar->hasFocus()) {
return;
}
ExactCard card = CardDatabaseManager::query()->getCard({searchBar->text()});
if (card) {

View file

@ -126,8 +126,9 @@ void VisualDeckStorageTagFilterWidget::addTagIfNotPresent(const QString &tag)
void VisualDeckStorageTagFilterWidget::sortTags()
{
auto *flowWidget = findChild<FlowWidget *>();
if (!flowWidget)
if (!flowWidget) {
return;
}
// Get all tag widgets
QList<DeckPreviewTagDisplayWidget *> tagWidgets = findChildren<DeckPreviewTagDisplayWidget *>();

View file

@ -88,11 +88,13 @@ inline Q_LOGGING_CATEGORY(MainWindowLog, "main_window");
*/
void MainWindow::updateTabMenu(const QList<QMenu *> &newMenuList)
{
for (auto &tabMenu : tabMenus)
for (auto &tabMenu : tabMenus) {
menuBar()->removeAction(tabMenu->menuAction());
}
tabMenus = newMenuList;
for (auto &tabMenu : tabMenus)
for (auto &tabMenu : tabMenus) {
menuBar()->insertMenu(helpMenu->menuAction(), tabMenu);
}
}
void MainWindow::statusChanged(ClientStatus _status)
@ -177,13 +179,15 @@ void MainWindow::actWatchReplay()
QFileDialog dlg(this, tr("Load replay"));
dlg.setDirectory(SettingsCache::instance().getReplaysPath());
dlg.setNameFilters(QStringList() << QObject::tr("Cockatrice replays (*.cor)"));
if (!dlg.exec())
if (!dlg.exec()) {
return;
}
QString fileName = dlg.selectedFiles().at(0);
QFile file(fileName);
if (!file.open(QIODevice::ReadOnly))
if (!file.open(QIODevice::ReadOnly)) {
return;
}
QByteArray buf = file.readAll();
file.close();
@ -208,10 +212,11 @@ void MainWindow::localGameEnded()
void MainWindow::actFullScreen(bool checked)
{
if (checked)
if (checked) {
setWindowState(windowState() | Qt::WindowFullScreen);
else
} else {
setWindowState(windowState() & ~Qt::WindowFullScreen);
}
}
void MainWindow::actSettings()
@ -691,8 +696,9 @@ void MainWindow::closeEvent(QCloseEvent *event)
{
// workaround Qt bug where closeEvent gets called twice
static bool bClosingDown = false;
if (bClosingDown)
if (bClosingDown) {
return;
}
bClosingDown = true;
if (!tabSupervisor->close()) {
@ -709,9 +715,9 @@ void MainWindow::closeEvent(QCloseEvent *event)
void MainWindow::changeEvent(QEvent *event)
{
if (event->type() == QEvent::LanguageChange)
if (event->type() == QEvent::LanguageChange) {
retranslateUi();
else if (event->type() == QEvent::ActivationChange) {
} else if (event->type() == QEvent::ActivationChange) {
if (isActiveWindow() && !bHasActivated) {
bHasActivated = true;
if (!connectTo.isEmpty()) {
@ -1069,8 +1075,9 @@ int MainWindow::getNextCustomSetPrefix(QDir dataDir)
QStringList::const_iterator filesIterator;
for (filesIterator = files.constBegin(); filesIterator != files.constEnd(); ++filesIterator) {
int fileIndex = (*filesIterator).split(".").at(0).toInt();
if (fileIndex > maxIndex)
if (fileIndex > maxIndex) {
maxIndex = fileIndex;
}
}
return maxIndex + 1;