From f2d3e8133155a3b22f1a7e8d79a7f8667d5cc837 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Br=C3=BCbach=2C=20Lukas?= Date: Sat, 29 Nov 2025 15:11:22 +0100 Subject: [PATCH] [Fix-Warnings] Local variable can be made const --- .../interfaces/deck_stats_interface.cpp | 8 +- .../interfaces/tapped_out_interface.cpp | 14 +-- .../parsers/deck_link_to_api_transformer.cpp | 8 +- .../parsers/interface_json_deck_parser.h | 6 +- .../spoiler_background_updater.cpp | 22 ++-- .../update/client/client_update_checker.cpp | 2 +- .../network/update/client/release_channel.cpp | 32 ++--- .../update/client/update_downloader.cpp | 4 +- .../src/client/settings/cache_settings.cpp | 30 ++--- .../client/settings/card_counter_settings.cpp | 10 +- .../src/client/settings/shortcut_treeview.cpp | 14 +-- .../client/settings/shortcuts_settings.cpp | 18 +-- cockatrice/src/client/sound_engine.cpp | 4 +- cockatrice/src/filters/deck_filter_string.cpp | 17 +-- cockatrice/src/filters/filter_tree_model.cpp | 4 +- cockatrice/src/filters/syntax_help.cpp | 10 +- cockatrice/src/game/abstract_game.cpp | 2 +- .../game/board/abstract_card_drag_item.cpp | 2 +- .../src/game/board/abstract_card_item.cpp | 14 +-- cockatrice/src/game/board/card_drag_item.cpp | 14 +-- cockatrice/src/game/board/card_list.cpp | 6 +- cockatrice/src/game/board/counter_general.cpp | 8 +- cockatrice/src/game/deckview/deck_view.cpp | 32 ++--- .../deckview/tabbed_deck_view_container.cpp | 2 +- .../src/game/dialogs/dlg_create_token.cpp | 2 +- .../game/dialogs/dlg_move_top_cards_until.cpp | 2 +- cockatrice/src/game/game_scene.cpp | 34 +++--- cockatrice/src/game/game_state.cpp | 2 +- cockatrice/src/game/hand_counter.cpp | 2 +- cockatrice/src/game/player/menu/card_menu.cpp | 24 ++-- .../src/game/player/menu/custom_zone_menu.cpp | 2 +- .../src/game/player/menu/grave_menu.cpp | 10 +- cockatrice/src/game/player/menu/hand_menu.cpp | 12 +- .../src/game/player/menu/library_menu.cpp | 30 ++--- cockatrice/src/game/player/menu/move_menu.cpp | 2 +- cockatrice/src/game/player/menu/pt_menu.cpp | 2 +- cockatrice/src/game/player/menu/rfg_menu.cpp | 4 +- cockatrice/src/game/player/menu/say_menu.cpp | 2 +- .../src/game/player/menu/sideboard_menu.cpp | 2 +- .../src/game/player/menu/utility_menu.cpp | 6 +- cockatrice/src/game/player/player_area.cpp | 2 +- .../src/game/player/player_graphics_item.cpp | 16 +-- cockatrice/src/game/player/player_manager.cpp | 2 +- cockatrice/src/game/player/player_manager.h | 2 +- cockatrice/src/game/player/player_target.cpp | 4 +- cockatrice/src/game/zones/hand_zone.cpp | 28 ++--- .../src/game/zones/logic/view_zone_logic.cpp | 10 +- cockatrice/src/game/zones/pile_zone.cpp | 6 +- cockatrice/src/game/zones/select_zone.cpp | 12 +- cockatrice/src/game/zones/stack_zone.cpp | 20 ++-- cockatrice/src/game/zones/table_zone.cpp | 32 ++--- cockatrice/src/game/zones/view_zone.cpp | 35 +++--- .../src/game/zones/view_zone_widget.cpp | 46 ++++---- .../board/abstract_graphics_item.cpp | 10 +- .../card_picture_loader.cpp | 24 ++-- .../card_picture_loader_local.cpp | 6 +- ...ure_loader_request_status_display_widget.h | 2 +- .../card_picture_loader_worker.cpp | 12 +- .../card_picture_loader_worker_work.cpp | 22 ++-- .../card_picture_to_load.cpp | 14 +-- .../src/interface/deck_loader/deck_loader.cpp | 44 +++---- .../src/interface/layouts/flow_layout.cpp | 18 +-- .../src/interface/layouts/overlap_layout.cpp | 10 +- cockatrice/src/interface/logger.cpp | 2 +- cockatrice/src/interface/theme_manager.cpp | 8 +- .../additional_info/color_identity_widget.cpp | 12 +- .../additional_info/mana_cost_widget.cpp | 12 +- .../card_group_display_widget.cpp | 20 ++-- .../cards/card_info_display_widget.cpp | 4 +- .../card_info_picture_art_crop_widget.cpp | 8 +- .../card_info_picture_enlarged_widget.cpp | 6 +- .../cards/card_info_picture_widget.cpp | 37 +++--- .../widgets/cards/card_info_text_widget.cpp | 2 +- .../cards/deck_card_zone_display_widget.cpp | 10 +- .../deck_analytics/mana_base_widget.cpp | 10 +- .../deck_analytics/mana_curve_widget.cpp | 4 +- .../deck_analytics/mana_devotion_widget.cpp | 8 +- .../deck_editor_database_display_widget.cpp | 10 +- .../deck_editor_deck_dock_widget.cpp | 31 ++--- .../deck_editor_filter_dock_widget.cpp | 2 +- .../deck_list_history_manager_widget.cpp | 12 +- .../deck_editor/deck_list_style_proxy.cpp | 10 +- .../interface/widgets/dialogs/dlg_connect.cpp | 10 +- .../dialogs/dlg_default_tags_editor.cpp | 10 +- .../widgets/dialogs/dlg_edit_avatar.cpp | 2 +- .../widgets/dialogs/dlg_edit_tokens.cpp | 8 +- .../widgets/dialogs/dlg_filter_games.cpp | 2 +- .../dialogs/dlg_load_deck_from_website.cpp | 8 +- .../widgets/dialogs/dlg_manage_sets.cpp | 14 +-- .../dialogs/dlg_select_set_for_cards.cpp | 36 +++--- .../widgets/dialogs/dlg_settings.cpp | 111 +++++++++--------- .../dialogs/dlg_startup_card_check.cpp | 4 +- .../widgets/dialogs/dlg_tip_of_the_day.cpp | 10 +- .../interface/widgets/dialogs/dlg_update.cpp | 2 +- .../widgets/dialogs/tip_of_the_day.cpp | 2 +- .../widgets/general/display/banner_widget.cpp | 4 +- .../widgets/general/display/bar_widget.cpp | 26 ++-- .../display/dynamic_font_size_label.cpp | 4 +- .../display/dynamic_font_size_push_button.cpp | 2 +- .../general/display/percent_bar_widget.cpp | 4 +- .../display/shadow_background_label.cpp | 2 +- .../widgets/general/home_styled_button.cpp | 6 +- .../interface/widgets/general/home_widget.cpp | 30 ++--- .../general/layout_containers/flow_widget.cpp | 6 +- .../widgets/menus/deck_editor_menu.cpp | 2 +- .../printing_selector/card_amount_widget.cpp | 18 +-- .../printing_selector/printing_selector.cpp | 4 +- .../printing_selector_card_display_widget.cpp | 4 +- .../printing_selector_card_overlay_widget.cpp | 10 +- .../printing_selector_card_sorting_widget.cpp | 5 +- ...e_and_collectors_number_display_widget.cpp | 8 +- .../quick_settings/settings_button_widget.cpp | 9 +- .../quick_settings/settings_popup_widget.cpp | 8 +- .../widgets/replay/replay_timeline_widget.cpp | 8 +- .../widgets/server/chat_view/chat_view.cpp | 62 +++++----- .../game_selector_quick_filter_toolbar.cpp | 6 +- .../interface/widgets/server/games_model.cpp | 22 ++-- .../widgets/server/handle_public_servers.cpp | 8 +- .../remote/remote_decklist_tree_widget.cpp | 16 +-- .../remote/remote_replay_list_tree_widget.cpp | 8 +- .../widgets/server/user/user_context_menu.cpp | 16 +-- .../widgets/server/user/user_info_box.cpp | 32 ++--- .../server/user/user_info_connection.cpp | 26 ++-- .../widgets/server/user/user_list_widget.cpp | 4 +- .../edhrec_average_deck_api_response.cpp | 6 +- .../edhrec_api_response_card_container.cpp | 2 +- .../edhrec_commander_api_response.cpp | 4 +- .../edhrec_top_cards_api_response.cpp | 2 +- .../edhrec_top_commanders_api_response.cpp | 2 +- .../top_tags/edhrec_top_tags_api_response.cpp | 2 +- ...i_response_card_details_display_widget.cpp | 2 +- ..._api_response_card_list_display_widget.cpp | 2 +- ...ponse_commander_details_display_widget.cpp | 2 +- ..._commander_api_response_display_widget.cpp | 6 +- ...mmander_api_response_navigation_widget.cpp | 4 +- ..._top_cards_api_response_display_widget.cpp | 4 +- ...commanders_api_response_display_widget.cpp | 4 +- ...c_top_tags_api_response_display_widget.cpp | 4 +- .../widgets/tabs/api/edhrec/tab_edhrec.cpp | 12 +- .../widgets/tabs/api/edhrec/tab_edhrec.h | 2 +- .../tabs/api/edhrec/tab_edhrec_main.cpp | 38 +++--- .../widgets/tabs/api/edhrec/tab_edhrec_main.h | 2 +- cockatrice/src/interface/widgets/tabs/tab.cpp | 2 +- .../widgets/tabs/tab_deck_editor.cpp | 8 +- .../src/interface/widgets/tabs/tab_server.cpp | 4 +- .../interface/widgets/tabs/tab_supervisor.cpp | 41 +++---- .../tab_deck_editor_visual.cpp | 18 +-- .../tab_deck_editor_visual_tab_widget.cpp | 4 +- .../tab_deck_storage_visual.cpp | 2 +- .../widgets/utility/custom_line_edit.cpp | 4 +- .../widgets/utility/line_edit_completer.cpp | 22 ++-- .../widgets/utility/sequence_edit.cpp | 6 +- ...l_database_display_color_filter_widget.cpp | 6 +- ...tabase_display_filter_save_load_widget.cpp | 16 +-- ...tabase_display_main_type_filter_widget.cpp | 4 +- ...al_database_display_name_filter_widget.cpp | 8 +- ...ual_database_display_set_filter_widget.cpp | 14 +-- ...atabase_display_sub_type_filter_widget.cpp | 10 +- .../visual_database_display_widget.cpp | 20 ++-- .../visual_database_filter_display_widget.cpp | 12 +- .../visual_deck_editor_sample_hand_widget.cpp | 8 +- .../visual_deck_editor_widget.cpp | 12 +- .../deck_preview_deck_tags_display_widget.cpp | 8 +- .../deck_preview_tag_addition_widget.cpp | 16 +-- .../deck_preview/deck_preview_tag_dialog.cpp | 14 +-- .../deck_preview_tag_display_widget.cpp | 8 +- .../deck_preview/deck_preview_widget.cpp | 37 +++--- .../deck_preview/deck_preview_widget.h | 4 +- ...ual_deck_storage_folder_display_widget.cpp | 10 +- ...ual_deck_storage_quick_settings_widget.cpp | 8 +- .../visual_deck_storage_sort_widget.cpp | 16 +-- .../visual_deck_storage_tag_filter_widget.cpp | 24 ++-- cockatrice/src/main.cpp | 22 ++-- .../libcockatrice/card/card_info.cpp | 2 +- .../card/database/card_database.cpp | 12 +- .../card/database/card_database_loader.cpp | 18 +-- .../card/database/card_database_querier.cpp | 25 ++-- .../card/database/parser/cockatrice_xml_4.cpp | 8 +- .../card/printing/exact_card.cpp | 4 +- .../libcockatrice/card/set/card_set_list.cpp | 10 +- .../abstract_deck_list_card_node.cpp | 8 +- .../libcockatrice/deck_list/deck_list.cpp | 28 ++--- .../deck_list/deck_list_history_manager.cpp | 8 +- .../deck_list/inner_deck_list_node.cpp | 10 +- .../libcockatrice/filters/filter_card.cpp | 4 +- .../libcockatrice/filters/filter_string.cpp | 6 +- .../libcockatrice/filters/filter_tree.cpp | 22 ++-- .../card/card_completer_proxy_model.cpp | 4 +- .../database/card/card_search_model.cpp | 4 +- .../database/card_database_display_model.cpp | 20 ++-- .../models/database/card_database_model.cpp | 2 +- .../database/card_set/card_sets_model.cpp | 28 ++--- .../database/token/token_display_model.cpp | 2 +- .../database/token/token_edit_model.cpp | 2 +- .../models/deck_list/deck_list_model.cpp | 60 +++++----- .../deck_list_sort_filter_proxy_model.cpp | 28 ++--- .../game/server_abstract_participant.cpp | 8 +- .../remote/game/server_abstract_player.cpp | 52 ++++---- .../server/remote/game/server_cardzone.cpp | 6 +- .../server/remote/game/server_player.cpp | 22 ++-- .../network/server/remote/server.cpp | 48 ++++---- .../remote/server_abstractuserinterface.cpp | 6 +- .../protocol/debug_pb_message.cpp | 6 +- .../libcockatrice/rng/rng_abstract.cpp | 4 +- .../settings/game_filters_settings.cpp | 30 ++--- .../settings/layouts_settings.cpp | 22 ++-- .../settings/servers_settings.cpp | 52 ++++---- .../libcockatrice/utility/expression.cpp | 6 +- .../libcockatrice/utility/levenshtein.cpp | 6 +- .../libcockatrice/utility/passwordhasher.cpp | 4 +- servatrice/src/isl_interface.cpp | 12 +- servatrice/src/main.cpp | 22 ++-- servatrice/src/server_logger.cpp | 8 +- servatrice/src/smtpclient.cpp | 28 ++--- 214 files changed, 1375 insertions(+), 1355 deletions(-) diff --git a/cockatrice/src/client/network/interfaces/deck_stats_interface.cpp b/cockatrice/src/client/network/interfaces/deck_stats_interface.cpp index a5cea5358..45faed529 100644 --- a/cockatrice/src/client/network/interfaces/deck_stats_interface.cpp +++ b/cockatrice/src/client/network/interfaces/deck_stats_interface.cpp @@ -26,18 +26,18 @@ void DeckStatsInterface::queryFinished(QNetworkReply *reply) return; } - QString data(reply->readAll()); + const QString data(reply->readAll()); reply->deleteLater(); static const QRegularExpression rx("getCardInfo(card->getName()); + const CardInfoPtr dbCard = cardDatabase.query()->getCardInfo(card->getName()); if (dbCard && !dbCard->getIsToken()) { DecklistCardNode *addedCard = destination.addCard(card->getName(), node->getName(), -1); addedCard->setNumber(card->getNumber()); diff --git a/cockatrice/src/client/network/interfaces/tapped_out_interface.cpp b/cockatrice/src/client/network/interfaces/tapped_out_interface.cpp index d18d811b0..185f62eda 100644 --- a/cockatrice/src/client/network/interfaces/tapped_out_interface.cpp +++ b/cockatrice/src/client/network/interfaces/tapped_out_interface.cpp @@ -26,13 +26,13 @@ void TappedOutInterface::queryFinished(QNetworkReply *reply) return; } - int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + const int httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (reply->hasRawHeader("Location")) { /* * If the reply contains a "Location" header, a relative URL to the deck on TappedOut * can be extracted from the header. The http status is a 302 "redirect". */ - QString deckUrl = reply->rawHeader("Location"); + const QString deckUrl = reply->rawHeader("Location"); qCInfo(TappedOutInterfaceLog) << "Tappedout: good reply, http status" << httpStatus << "location" << deckUrl; QDesktopServices::openUrl("https://tappedout.net" + deckUrl); } else { @@ -40,13 +40,13 @@ void TappedOutInterface::queryFinished(QNetworkReply *reply) * Otherwise, the deck has not been parsed correctly. Error messages can be extracted * from the html. Css pseudo selector for errors: $("div.alert-danger > ul > li") */ - QString data(reply->readAll()); + const QString data(reply->readAll()); QStringList errorMessageList = {tr("Unable to analyze the deck.")}; static const QRegularExpression rx("
(.*?)"); - auto match = rx.match(data); + const auto match = rx.match(data); if (match.hasMatch()) { - QString errors = match.captured(1); + const QString errors = match.captured(1); static const QRegularExpression rx2("
  • (.*?)
  • "); static const QRegularExpression rxremove("<[^>]*>"); auto matchIterator = rx2.globalMatch(errors); @@ -56,7 +56,7 @@ void TappedOutInterface::queryFinished(QNetworkReply *reply) } } - QString errorMessage = errorMessageList.join("\n"); + const QString errorMessage = errorMessageList.join("\n"); qCWarning(TappedOutInterfaceLog) << "Tappedout: bad reply, http status" << httpStatus << "size" << data.size() << "message" << errorMessage; @@ -95,7 +95,7 @@ void TappedOutInterface::analyzeDeck(DeckList *deck) void TappedOutInterface::copyDeckSplitMainAndSide(DeckList &source, DeckList &mainboard, DeckList &sideboard) { auto copyMainOrSide = [this, &mainboard, &sideboard](const auto node, const auto card) { - CardInfoPtr dbCard = cardDatabase.query()->getCardInfo(card->getName()); + const CardInfoPtr dbCard = cardDatabase.query()->getCardInfo(card->getName()); if (!dbCard || dbCard->getIsToken()) return; diff --git a/cockatrice/src/client/network/parsers/deck_link_to_api_transformer.cpp b/cockatrice/src/client/network/parsers/deck_link_to_api_transformer.cpp index 010b63684..db392e79f 100644 --- a/cockatrice/src/client/network/parsers/deck_link_to_api_transformer.cpp +++ b/cockatrice/src/client/network/parsers/deck_link_to_api_transformer.cpp @@ -26,28 +26,28 @@ bool parseDeckUrl(const QString &url, ParsedDeckInfo &outInfo) QRegularExpressionMatch match; if ((match = rxTappedOut.match(url)).hasMatch()) { - QString slug = match.captured(1); + const QString slug = match.captured(1); outInfo = ParsedDeckInfo{.baseUrl = TAPPEDOUT_BASE, .deckID = slug, .fullUrl = TAPPEDOUT_BASE + slug + TAPPEDOUT_SUFFIX, .provider = DeckProvider::TappedOut}; return true; } else if ((match = rxArchidekt.match(url)).hasMatch()) { - QString deckID = match.captured(1); + const QString deckID = match.captured(1); outInfo = ParsedDeckInfo{.baseUrl = ARCHIDEKT_BASE, .deckID = deckID, .fullUrl = ARCHIDEKT_BASE + deckID + ARCHIDEKT_SUFFIX, .provider = DeckProvider::Archidekt}; return true; } else if ((match = rxMoxfield.match(url)).hasMatch()) { - QString deckID = match.captured(1); + const QString deckID = match.captured(1); outInfo = ParsedDeckInfo{.baseUrl = MOXFIELD_BASE, .deckID = deckID, .fullUrl = MOXFIELD_BASE + deckID + MOXFIELD_SUFFIX, .provider = DeckProvider::Moxfield}; return true; } else if ((match = rxDeckstats.match(url)).hasMatch()) { - QString deckPath = match.captured(1); + const QString deckPath = match.captured(1); outInfo = ParsedDeckInfo{.baseUrl = "https://deckstats.net/decks/", .deckID = deckPath, .fullUrl = "https://deckstats.net/decks/" + deckPath + DECKSTATS_SUFFIX, diff --git a/cockatrice/src/client/network/parsers/interface_json_deck_parser.h b/cockatrice/src/client/network/parsers/interface_json_deck_parser.h index 8ac05a84b..a84113eb3 100644 --- a/cockatrice/src/client/network/parsers/interface_json_deck_parser.h +++ b/cockatrice/src/client/network/parsers/interface_json_deck_parser.h @@ -26,8 +26,8 @@ public: { DeckLoader *loader = new DeckLoader(nullptr); - QString deckName = obj.value("name").toString(); - QString deckDescription = obj.value("description").toString(); + const QString deckName = obj.value("name").toString(); + const QString deckDescription = obj.value("description").toString(); loader->getDeckList()->setName(deckName); loader->getDeckList()->setComments(deckDescription); @@ -36,7 +36,7 @@ public: QTextStream outStream(&outputText); for (auto entry : obj.value("cards").toArray()) { - auto quantity = entry.toObject().value("quantity").toInt(); + const auto quantity = entry.toObject().value("quantity").toInt(); auto card = entry.toObject().value("card").toObject(); auto oracleCard = card.value("oracleCard").toObject(); diff --git a/cockatrice/src/client/network/update/card_spoiler/spoiler_background_updater.cpp b/cockatrice/src/client/network/update/card_spoiler/spoiler_background_updater.cpp index cfd4cbbf8..efd898999 100644 --- a/cockatrice/src/client/network/update/card_spoiler/spoiler_background_updater.cpp +++ b/cockatrice/src/client/network/update/card_spoiler/spoiler_background_updater.cpp @@ -34,14 +34,14 @@ SpoilerBackgroundUpdater::SpoilerBackgroundUpdater(QObject *apParent) : QObject( void SpoilerBackgroundUpdater::startSpoilerDownloadProcess(QString url, bool saveResults) { - auto spoilerURL = QUrl(url); + const auto spoilerURL = QUrl(url); downloadFromURL(spoilerURL, saveResults); } void SpoilerBackgroundUpdater::downloadFromURL(QUrl url, bool saveResults) { auto *nam = new QNetworkAccessManager(this); - QNetworkReply *reply = nam->get(QNetworkRequest(url)); + const QNetworkReply *reply = nam->get(QNetworkRequest(url)); if (saveResults) { // This will write out to the file (used for spoiler.xml) @@ -56,7 +56,7 @@ void SpoilerBackgroundUpdater::actDownloadFinishedSpoilersFile() { // Check for server reply auto *reply = dynamic_cast(sender()); - QNetworkReply::NetworkError errorCode = reply->error(); + const QNetworkReply::NetworkError errorCode = reply->error(); if (errorCode == QNetworkReply::NoError) { spoilerData = reply->readAll(); @@ -74,8 +74,8 @@ void SpoilerBackgroundUpdater::actDownloadFinishedSpoilersFile() bool SpoilerBackgroundUpdater::deleteSpoilerFile() { - QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath(); - QFileInfo fi(fileName); + const QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath(); + const QFileInfo fi(fileName); QDir fileDir(fi.path()); QFile file(fileName); @@ -91,8 +91,8 @@ bool SpoilerBackgroundUpdater::deleteSpoilerFile() void SpoilerBackgroundUpdater::actCheckIfSpoilerSeasonEnabled() { - auto *response = dynamic_cast(sender()); - QNetworkReply::NetworkError errorCode = response->error(); + const auto *response = dynamic_cast(sender()); + const QNetworkReply::NetworkError errorCode = response->error(); if (errorCode == QNetworkReply::ContentNotFoundError) { // Spoiler season is offline at this point, so the spoiler.xml file can be safely deleted @@ -125,9 +125,9 @@ void SpoilerBackgroundUpdater::actCheckIfSpoilerSeasonEnabled() bool SpoilerBackgroundUpdater::saveDownloadedFile(QByteArray data) { - QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath(); - QFileInfo fi(fileName); - QDir fileDir(fi.path()); + const QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath(); + const QFileInfo fi(fileName); + const QDir fileDir(fi.path()); if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) { return false; @@ -179,7 +179,7 @@ bool SpoilerBackgroundUpdater::saveDownloadedFile(QByteArray data) utcTime.setTimeSpec(Qt::UTC); #endif - QString localTime = utcTime.toLocalTime().toString("MMM d, hh:mm"); + const QString localTime = utcTime.toLocalTime().toString("MMM d, hh:mm"); trayIcon->showMessage(tr("Spoilers have been updated!"), tr("Last change:") + " " + localTime); emit spoilersUpdatedSuccessfully(); diff --git a/cockatrice/src/client/network/update/client/client_update_checker.cpp b/cockatrice/src/client/network/update/client/client_update_checker.cpp index 64709113a..b8db691f0 100644 --- a/cockatrice/src/client/network/update/client/client_update_checker.cpp +++ b/cockatrice/src/client/network/update/client/client_update_checker.cpp @@ -9,7 +9,7 @@ ClientUpdateChecker::ClientUpdateChecker(QObject *parent) : QObject(parent) void ClientUpdateChecker::check() { - auto releaseChannel = SettingsCache::instance().getUpdateReleaseChannel(); + const auto releaseChannel = SettingsCache::instance().getUpdateReleaseChannel(); finishedCheckConnection = connect(releaseChannel, &ReleaseChannel::finishedCheck, this, &ClientUpdateChecker::actFinishedCheck); diff --git a/cockatrice/src/client/network/update/client/release_channel.cpp b/cockatrice/src/client/network/update/client/release_channel.cpp index 9edfe7caf..e4ba45a21 100644 --- a/cockatrice/src/client/network/update/client/release_channel.cpp +++ b/cockatrice/src/client/network/update/client/release_channel.cpp @@ -37,7 +37,7 @@ ReleaseChannel::~ReleaseChannel() void ReleaseChannel::checkForUpdates() { - QString releaseChannelUrl = getReleaseChannelUrl(); + const QString releaseChannelUrl = getReleaseChannelUrl(); qCInfo(ReleaseChannelLog) << "Searching for updates on the channel: " << releaseChannelUrl; response = netMan->get(QNetworkRequest(releaseChannelUrl)); connect(response, &QNetworkReply::finished, this, &ReleaseChannel::releaseListFinished); @@ -113,7 +113,7 @@ void StableReleaseChannel::releaseListFinished() { auto *reply = static_cast(sender()); QJsonParseError parseError{}; - QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError); + const QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError); reply->deleteLater(); if (parseError.error != QJsonParseError::NoError) { qCWarning(ReleaseChannelLog) << "No reply received from the release update server."; @@ -141,7 +141,7 @@ void StableReleaseChannel::releaseListFinished() for (const auto &rawAsset : rawAssets) { QVariantMap asset = rawAsset.toMap(); QString name = asset["name"].toString(); - QString url = asset["browser_download_url"].toString(); + const QString url = asset["browser_download_url"].toString(); if (downloadMatchesCurrentOS(name)) { lastRelease->setDownloadUrl(url); @@ -150,8 +150,8 @@ void StableReleaseChannel::releaseListFinished() } } - QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN); - QString myHash = QString(VERSION_COMMIT); + const QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN); + const QString myHash = QString(VERSION_COMMIT); qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash; qCInfo(ReleaseChannelLog) << "Got reply from release server, name=" << lastRelease->getName() @@ -159,7 +159,7 @@ void StableReleaseChannel::releaseListFinished() << "url=" << lastRelease->getDownloadUrl(); const QString &tagName = resultMap["tag_name"].toString(); - QString url = QString(STABLETAG_URL) + tagName; + const QString url = QString(STABLETAG_URL) + tagName; qCInfo(ReleaseChannelLog) << "Searching for commit hash corresponding to stable channel tag: " << tagName; response = netMan->get(QNetworkRequest(url)); connect(response, &QNetworkReply::finished, this, &StableReleaseChannel::tagListFinished); @@ -187,8 +187,8 @@ void StableReleaseChannel::tagListFinished() lastRelease->setCommitHash(resultMap["object"].toMap()["sha"].toString()); qCInfo(ReleaseChannelLog) << "Got reply from tag server, commit=" << lastRelease->getCommitHash(); - QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN); - QString myHash = QString(VERSION_COMMIT); + const QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN); + const QString myHash = QString(VERSION_COMMIT); qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash; const bool needToUpdate = (QString::compare(shortHash, myHash, Qt::CaseInsensitive) != 0); @@ -218,11 +218,11 @@ QString BetaReleaseChannel::getReleaseChannelUrl() const void BetaReleaseChannel::releaseListFinished() { auto *reply = static_cast(sender()); - QByteArray jsonData = reply->readAll(); + const QByteArray jsonData = reply->readAll(); reply->deleteLater(); - QJsonDocument doc = QJsonDocument::fromJson(jsonData); - QJsonArray array = doc.array(); + const QJsonDocument doc = QJsonDocument::fromJson(jsonData); + const QJsonArray array = doc.array(); /* * Get the latest release on GitHub @@ -260,7 +260,7 @@ void BetaReleaseChannel::releaseListFinished() << "name=" << lastRelease->getName() << "desc=" << lastRelease->getDescriptionUrl() << "commit=" << lastRelease->getCommitHash() << "date=" << lastRelease->getPublishDate(); - QString betaBuildDownloadUrl = resultMap["assets_url"].toString(); + const QString betaBuildDownloadUrl = resultMap["assets_url"].toString(); qCInfo(ReleaseChannelLog) << "Searching for a corresponding file on the beta channel: " << betaBuildDownloadUrl; response = netMan->get(QNetworkRequest(betaBuildDownloadUrl)); @@ -271,7 +271,7 @@ void BetaReleaseChannel::fileListFinished() { auto *reply = static_cast(sender()); QJsonParseError parseError{}; - QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError); + const QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError); reply->deleteLater(); if (parseError.error != QJsonParseError::NoError) { qCWarning(ReleaseChannelLog) << "No reply received from the file update server."; @@ -280,11 +280,11 @@ void BetaReleaseChannel::fileListFinished() } QVariantList resultList = jsonResponse.toVariant().toList(); - QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN); - QString myHash = QString(VERSION_COMMIT); + const QString shortHash = lastRelease->getCommitHash().left(GIT_SHORT_HASH_LEN); + const QString myHash = QString(VERSION_COMMIT); qCInfo(ReleaseChannelLog) << "Current hash=" << myHash << "update hash=" << shortHash; - bool needToUpdate = (QString::compare(shortHash, myHash, Qt::CaseInsensitive) != 0); + const bool needToUpdate = (QString::compare(shortHash, myHash, Qt::CaseInsensitive) != 0); bool compatibleVersion = false; QStringList resultUrlList{}; diff --git a/cockatrice/src/client/network/update/client/update_downloader.cpp b/cockatrice/src/client/network/update/client/update_downloader.cpp index 40186bec4..4c6c6b4fb 100644 --- a/cockatrice/src/client/network/update/client/update_downloader.cpp +++ b/cockatrice/src/client/network/update/client/update_downloader.cpp @@ -31,7 +31,7 @@ void UpdateDownloader::downloadError(QNetworkReply::NetworkError) void UpdateDownloader::fileFinished() { // If we finished but there's a redirect, follow it - QVariant redirect = response->attribute(QNetworkRequest::RedirectionTargetAttribute); + const QVariant redirect = response->attribute(QNetworkRequest::RedirectionTargetAttribute); if (!redirect.isNull()) { beginDownload(redirect.toUrl()); return; @@ -44,7 +44,7 @@ void UpdateDownloader::fileFinished() } // Work out the file name of the download - QString fileName = QDir::temp().path() + QDir::separator() + originalUrl.toString().section('/', -1); + const QString fileName = QDir::temp().path() + QDir::separator() + originalUrl.toString().section('/', -1); // Save the build in a temporary directory QFile file(fileName); diff --git a/cockatrice/src/client/settings/cache_settings.cpp b/cockatrice/src/client/settings/cache_settings.cpp index 7a518df67..4ba17024c 100644 --- a/cockatrice/src/client/settings/cache_settings.cpp +++ b/cockatrice/src/client/settings/cache_settings.cpp @@ -63,7 +63,7 @@ void SettingsCache::translateLegacySettings() // Sets legacySetting.beginGroup("sets"); - QStringList setsGroups = legacySetting.childGroups(); + const QStringList setsGroups = legacySetting.childGroups(); for (int i = 0; i < setsGroups.size(); i++) { legacySetting.beginGroup(setsGroups.at(i)); cardDatabase()->setEnabled(setsGroups.at(i), legacySetting.value("enabled").toBool()); @@ -71,7 +71,7 @@ void SettingsCache::translateLegacySettings() cardDatabase()->setSortKey(setsGroups.at(i), legacySetting.value("sortkey").toUInt()); legacySetting.endGroup(); } - QStringList setsKeys = legacySetting.allKeys(); + const QStringList setsKeys = legacySetting.allKeys(); for (int i = 0; i < setsKeys.size(); ++i) { usedKeys.append("sets/" + setsKeys.at(i)); } @@ -86,7 +86,7 @@ void SettingsCache::translateLegacySettings() servers().setFPPort(legacySetting.value("fpport").toString()); servers().setFPPlayerName(legacySetting.value("fpplayername").toString()); usedKeys.append(legacySetting.allKeys()); - QStringList allKeysServer = legacySetting.allKeys(); + const QStringList allKeysServer = legacySetting.allKeys(); for (int i = 0; i < allKeysServer.size(); ++i) { usedKeys.append("server/" + allKeysServer.at(i)); } @@ -94,16 +94,16 @@ void SettingsCache::translateLegacySettings() // Messages legacySetting.beginGroup("messages"); - QStringList allMessages = legacySetting.allKeys(); + const QStringList allMessages = legacySetting.allKeys(); for (int i = 0; i < allMessages.size(); ++i) { if (allMessages.at(i) != "count") { QString temp = allMessages.at(i); - int index = temp.remove("msg").toInt(); + const int index = temp.remove("msg").toInt(); messages().setMessageAt(index, legacySetting.value(allMessages.at(i)).toString()); } } messages().setCount(legacySetting.value("count").toInt()); - QStringList allKeysmessages = legacySetting.allKeys(); + const QStringList allKeysmessages = legacySetting.allKeys(); for (int i = 0; i < allKeysmessages.size(); ++i) { usedKeys.append("messages/" + allKeysmessages.at(i)); } @@ -120,19 +120,19 @@ void SettingsCache::translateLegacySettings() else gameFilters().setMaxPlayers(99); // This prevents a bug where no games will show if max was not set before - QStringList allFilters = legacySetting.allKeys(); + const QStringList allFilters = legacySetting.allKeys(); for (int i = 0; i < allFilters.size(); ++i) { if (allFilters.at(i).startsWith("game_type")) { gameFilters().setGameHashedTypeEnabled(allFilters.at(i), legacySetting.value(allFilters.at(i)).toBool()); } } - QStringList allKeysfilter_games = legacySetting.allKeys(); + const QStringList allKeysfilter_games = legacySetting.allKeys(); for (int i = 0; i < allKeysfilter_games.size(); ++i) { usedKeys.append("filter_games/" + allKeysfilter_games.at(i)); } legacySetting.endGroup(); - QStringList allLegacyKeys = legacySetting.allKeys(); + const QStringList allLegacyKeys = legacySetting.allKeys(); for (int i = 0; i < allLegacyKeys.size(); ++i) { if (usedKeys.contains(allLegacyKeys.at(i))) continue; @@ -173,7 +173,7 @@ SettingsCache::SettingsCache() // define a dummy context that will be used where needed QString dummy = QT_TRANSLATE_NOOP("i18n", "English"); - QString settingsPath = getSettingsPath(); + const QString settingsPath = getSettingsPath(); settings = new QSettings(settingsPath + "global.ini", QSettings::IniFormat, this); shortcutsSettings = new ShortcutsSettings(settingsPath, this); cardDatabaseSettings = new CardDatabaseSettings(settingsPath, this); @@ -234,7 +234,7 @@ SettingsCache::SettingsCache() tabLogOpen = settings->value("tabs/log", true).toBool(); // we only want to reset the cache once, then its up to the user - bool updateCache = settings->value("revert/pixmapCacheSize", false).toBool(); + const bool updateCache = settings->value("revert/pixmapCacheSize", false).toBool(); if (!updateCache) { pixmapCacheSize = PIXMAPCACHE_SIZE_DEFAULT; settings->setValue("personal/pixmapCacheSize", pixmapCacheSize); @@ -485,7 +485,7 @@ void SettingsCache::setSeenTips(const QList &_seenTips) { seenTips = _seenTips; QList storedTipList; - for (auto tipNumber : seenTips) { + for (const auto tipNumber : seenTips) { storedTipList.append(tipNumber); } settings->setValue("tipOfDay/seenTips", storedTipList); @@ -1510,7 +1510,7 @@ void SettingsCache::setRoundCardCorners(bool _roundCardCorners) void SettingsCache::loadPaths() { - QString dataPath = getDataPath(); + const QString dataPath = getDataPath(); deckPath = getSafeConfigPath("paths/decks", dataPath + "/decks/"); filtersPath = getSafeConfigPath("paths/filters", dataPath + "/filters/"); replaysPath = getSafeConfigPath("paths/replays", dataPath + "/replays/"); @@ -1532,8 +1532,8 @@ void SettingsCache::loadPaths() void SettingsCache::resetPaths() { - QStringList databasePaths{customCardDatabasePath, cardDatabasePath, spoilerDatabasePath, tokenDatabasePath}; - QString picsPath_ = picsPath; + const QStringList databasePaths{customCardDatabasePath, cardDatabasePath, spoilerDatabasePath, tokenDatabasePath}; + const QString picsPath_ = picsPath; settings->remove("paths"); // removes all keys in paths/* loadPaths(); if (databasePaths != diff --git a/cockatrice/src/client/settings/card_counter_settings.cpp b/cockatrice/src/client/settings/card_counter_settings.cpp index 71ce4cfc6..5c61a62b3 100644 --- a/cockatrice/src/client/settings/card_counter_settings.cpp +++ b/cockatrice/src/client/settings/card_counter_settings.cpp @@ -11,7 +11,7 @@ CardCounterSettings::CardCounterSettings(const QString &settingsPath, QObject *p void CardCounterSettings::setColor(int counterId, const QColor &color) { - QString key = QString("cards/counters/%1/color").arg(counterId); + const QString key = QString("cards/counters/%1/color").arg(counterId); if (settings.value(key).value() == color) return; @@ -29,9 +29,9 @@ QColor CardCounterSettings::color(int counterId) const defaultColor = QColor::fromHsv(counterId * 60, 150, 255); } else { // Future-proof support for more counters with pseudo-random colors - int h = (counterId * 37) % 360; - int s = 128 + 64 * qSin((counterId * 97) * 0.1); // 64-192 - int v = 196 + 32 * qSin((counterId * 101) * 0.07); // 164-228 + const int h = (counterId * 37) % 360; + const int s = 128 + 64 * qSin((counterId * 97) * 0.1); // 64-192 + const int v = 196 + 32 * qSin((counterId * 101) * 0.07); // 164-228 defaultColor = QColor::fromHsv(h, s, v); } @@ -43,7 +43,7 @@ QString CardCounterSettings::displayName(int counterId) const { // Currently, card counters name are fixed to A, B, ..., Z, AA, AB, ... - auto nChars = 1 + counterId / 26; + const auto nChars = 1 + counterId / 26; QString str; str.resize(nChars); diff --git a/cockatrice/src/client/settings/shortcut_treeview.cpp b/cockatrice/src/client/settings/shortcut_treeview.cpp index 6b329b23d..05c6022c4 100644 --- a/cockatrice/src/client/settings/shortcut_treeview.cpp +++ b/cockatrice/src/client/settings/shortcut_treeview.cpp @@ -14,13 +14,13 @@ ShortcutFilterProxyModel::ShortcutFilterProxyModel(QObject *parent) : QSortFilte */ bool ShortcutFilterProxyModel::filterAcceptsRow(const int sourceRow, const QModelIndex &sourceParent) const { - QModelIndex nameIndex = sourceModel()->index(sourceRow, filterKeyColumn(), sourceParent); - QModelIndex parentIndex = sourceModel()->index(sourceParent.row(), filterKeyColumn(), sourceParent.parent()); + const QModelIndex nameIndex = sourceModel()->index(sourceRow, filterKeyColumn(), sourceParent); + const QModelIndex parentIndex = sourceModel()->index(sourceParent.row(), filterKeyColumn(), sourceParent.parent()); - QString name = sourceModel()->data(nameIndex).toString(); - QString parentName = sourceModel()->data(parentIndex).toString(); + const QString name = sourceModel()->data(nameIndex).toString(); + const QString parentName = sourceModel()->data(parentIndex).toString(); - QString searchedString = parentName + " " + name; + const QString searchedString = parentName + " " + name; return searchedString.contains(filterRegularExpression()); } @@ -136,7 +136,7 @@ void ShortcutTreeView::currentChanged(const QModelIndex ¤t, const QModelIn { QTreeView::scrollTo(current, QAbstractItemView::EnsureVisible); if (current.parent().isValid()) { - auto shortcutName = model()->data(model()->index(current.row(), 2, current.parent())).toString(); + const auto shortcutName = model()->data(model()->index(current.row(), 2, current.parent())).toString(); emit currentItemChanged(shortcutName); } else { // emit empty string if the selection is a category header @@ -160,7 +160,7 @@ void ShortcutTreeView::updateSearchString(const QString &searchString) auto escapeRegex = [](const QString &s) { return QRegularExpression::escape(s); }; std::transform(searchWords.begin(), searchWords.end(), searchWords.begin(), escapeRegex); - auto regex = QRegularExpression(searchWords.join(".*"), QRegularExpression::CaseInsensitiveOption); + const auto regex = QRegularExpression(searchWords.join(".*"), QRegularExpression::CaseInsensitiveOption); proxyModel->setFilterRegularExpression(regex); expandAll(); diff --git a/cockatrice/src/client/settings/shortcuts_settings.cpp b/cockatrice/src/client/settings/shortcuts_settings.cpp index 53c6f6a23..30be8d70b 100644 --- a/cockatrice/src/client/settings/shortcuts_settings.cpp +++ b/cockatrice/src/client/settings/shortcuts_settings.cpp @@ -17,7 +17,7 @@ ShortcutsSettings::ShortcutsSettings(const QString &settingsPath, QObject *paren settingsFilePath = settingsPath; settingsFilePath.append("shortcuts.ini"); - bool exists = QFile(settingsFilePath).exists(); + const bool exists = QFile(settingsFilePath).exists(); QSettings shortCutsFile(settingsFilePath, QSettings::IniFormat); @@ -76,7 +76,7 @@ void ShortcutsSettings::migrateShortcuts() if (shortCutsFile.contains("Textbox/unfocusTextBox")) { qCInfo(ShortcutsSettingsLog) << "[ShortcutsSettings] Textbox/unfocusTextBox shortcut found. Migrating to Player/unfocusTextBox."; - QString unfocusTextBox = shortCutsFile.value("Textbox/unfocusTextBox", "").toString(); + const QString unfocusTextBox = shortCutsFile.value("Textbox/unfocusTextBox", "").toString(); this->setShortcuts("Player/unfocusTextBox", unfocusTextBox); shortCutsFile.remove("Textbox/unfocusTextBox"); } @@ -84,7 +84,7 @@ void ShortcutsSettings::migrateShortcuts() if (shortCutsFile.contains("tab_game/aFocusChat")) { qCInfo(ShortcutsSettingsLog) << "[ShortcutsSettings] tab_game/aFocusChat shortcut found. Migrating to Player/aFocusChat."; - QString aFocusChat = shortCutsFile.value("tab_game/aFocusChat", "").toString(); + const QString aFocusChat = shortCutsFile.value("tab_game/aFocusChat", "").toString(); this->setShortcuts("Player/aFocusChat", aFocusChat); shortCutsFile.remove("tab_game/aFocusChat"); } @@ -92,7 +92,7 @@ void ShortcutsSettings::migrateShortcuts() // PR #5564 changes "MainWindow/aDeckEditor" to "Tabs/aTabDeckEditor" if (shortCutsFile.contains("MainWindow/aDeckEditor")) { qCInfo(ShortcutsSettingsLog) << "MainWindow/aDeckEditor shortcut found. Migrating to Tabs/aTabDeckEditor."; - QString keySequence = shortCutsFile.value("MainWindow/aDeckEditor", "").toString(); + const QString keySequence = shortCutsFile.value("MainWindow/aDeckEditor", "").toString(); this->setShortcuts("Tabs/aTabDeckEditor", keySequence); shortCutsFile.remove("MainWindow/aDeckEditor"); } @@ -217,9 +217,9 @@ bool ShortcutsSettings::isKeyAllowed(const QString &name, const QString &sequenc if (name.startsWith("Player") || name.startsWith("Replays")) { return true; } - QString checkSequence = sequences.split(sep).last(); - QStringList forbiddenKeys{"Del", "Backspace", "Down", "Up", "Left", "Right", - "Return", "Enter", "Menu", "Ctrl+Alt+-", "Ctrl+Alt+=", "Ctrl+Alt+[", + const QString checkSequence = sequences.split(sep).last(); + const QStringList forbiddenKeys{"Del", "Backspace", "Down", "Up", "Left", "Right", + "Return", "Enter", "Menu", "Ctrl+Alt+-", "Ctrl+Alt+=", "Ctrl+Alt+[", "Ctrl+Alt+]", "Tab", "Space", "Shift+S", "Shift+Left", "Shift+Right"}; return !forbiddenKeys.contains(checkSequence); } @@ -246,8 +246,8 @@ static bool isAlwaysActiveShortcut(const QString &shortcutName) QStringList ShortcutsSettings::findOverlaps(const QString &name, const QString &sequences) const { - QString checkSequence = sequences.split(sep).last(); - QString checkKey = name.left(name.indexOf("/")); + const QString checkSequence = sequences.split(sep).last(); + const QString checkKey = name.left(name.indexOf("/")); QStringList overlaps; for (const auto &key : shortCuts.keys()) { diff --git a/cockatrice/src/client/sound_engine.cpp b/cockatrice/src/client/sound_engine.cpp index 31cb2a35e..7788f97fe 100644 --- a/cockatrice/src/client/sound_engine.cpp +++ b/cockatrice/src/client/sound_engine.cpp @@ -130,10 +130,10 @@ QStringMap &SoundEngine::getAvailableThemes() void SoundEngine::themeChangedSlot() { - QString themeName = SettingsCache::instance().getSoundThemeName(); + const QString themeName = SettingsCache::instance().getSoundThemeName(); qCInfo(SoundEngineLog) << "Sound theme changed:" << themeName; - QDir dir = getAvailableThemes().value(themeName); + const QDir dir = getAvailableThemes().value(themeName); audioData.clear(); diff --git a/cockatrice/src/filters/deck_filter_string.cpp b/cockatrice/src/filters/deck_filter_string.cpp index c9adc17e9..ed63aae41 100644 --- a/cockatrice/src/filters/deck_filter_string.cpp +++ b/cockatrice/src/filters/deck_filter_string.cpp @@ -112,13 +112,14 @@ static void setupParserRules() // actual functionality search["DeckContentQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter { - auto cardFilter = FilterString(std::any_cast(sv[0])); - auto numberMatcher = sv.size() > 1 ? std::any_cast(sv[1]) : [](int count) { return count > 0; }; + const auto cardFilter = FilterString(std::any_cast(sv[0])); + const auto numberMatcher = + sv.size() > 1 ? std::any_cast(sv[1]) : [](int count) { return count > 0; }; return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) -> bool { int count = 0; deck->deckLoader->getDeckList()->forEachCard([&](InnerDecklistNode *, const DecklistCardNode *node) { - auto cardInfoPtr = CardDatabaseManager::query()->getCardInfo(node->getName()); + const auto cardInfoPtr = CardDatabaseManager::query()->getCardInfo(node->getName()); if (!cardInfoPtr.isNull() && cardFilter.check(cardInfoPtr)) { count += node->getNumber(); } @@ -134,29 +135,29 @@ static void setupParserRules() }; search["DeckNameQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter { - auto name = std::any_cast(sv[0]); + const auto name = std::any_cast(sv[0]); return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) { return deck->deckLoader->getDeckList()->getName().contains(name, Qt::CaseInsensitive); }; }; search["FileNameQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter { - auto name = std::any_cast(sv[0]); + const auto name = std::any_cast(sv[0]); return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) { - auto filename = QFileInfo(deck->filePath).fileName(); + const auto filename = QFileInfo(deck->filePath).fileName(); return filename.contains(name, Qt::CaseInsensitive); }; }; search["PathQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter { - auto name = std::any_cast(sv[0]); + const auto name = std::any_cast(sv[0]); return [=](const DeckPreviewWidget *, const ExtraDeckSearchInfo &info) { return info.relativeFilePath.contains(name, Qt::CaseInsensitive); }; }; search["GenericQuery"] = [](const peg::SemanticValues &sv) -> DeckFilter { - auto name = std::any_cast(sv[0]); + const auto name = std::any_cast(sv[0]); return [=](const DeckPreviewWidget *deck, const ExtraDeckSearchInfo &) { return deck->getDisplayName().contains(name, Qt::CaseInsensitive); }; diff --git a/cockatrice/src/filters/filter_tree_model.cpp b/cockatrice/src/filters/filter_tree_model.cpp index f0a02ec79..d9b16c647 100644 --- a/cockatrice/src/filters/filter_tree_model.cpp +++ b/cockatrice/src/filters/filter_tree_model.cpp @@ -216,7 +216,7 @@ bool FilterTreeModel::setData(const QModelIndex &index, const QVariant &value, i if (node == NULL || node == fTree) return false; - Qt::CheckState state = static_cast(value.toInt()); + const Qt::CheckState state = static_cast(value.toInt()); if (state == Qt::Checked) node->enable(); else @@ -288,7 +288,7 @@ QModelIndex FilterTreeModel::parent(const QModelIndex &ind) const parent = node->parent(); if (parent) { - int row = parent->index(); + const int row = parent->index(); if (row < 0) return QModelIndex(); idx = createIndex(row, 0, parent); diff --git a/cockatrice/src/filters/syntax_help.cpp b/cockatrice/src/filters/syntax_help.cpp index fa5338a41..c3154911e 100644 --- a/cockatrice/src/filters/syntax_help.cpp +++ b/cockatrice/src/filters/syntax_help.cpp @@ -23,7 +23,7 @@ static QTextBrowser *createBrowser(const QString &helpFile) file.close(); // --- Remove @page declarations at the top of the file --- - auto opts = QRegularExpression::MultilineOption; + const auto opts = QRegularExpression::MultilineOption; text = text.replace(QRegularExpression(R"(^\s*@page[^\n]*\n)", opts), ""); // Poor Markdown Converter @@ -33,7 +33,7 @@ static QTextBrowser *createBrowser(const QString &helpFile) .replace(QRegularExpression("^------*", opts), "
    ") .replace(QRegularExpression(R"(\[([^[]+)\]\(([^\)]+)\))", opts), R"(\1)"); - auto browser = new QTextBrowser(); + const auto browser = new QTextBrowser(); browser->setParent(nullptr, Qt::Window | Qt::WindowTitleHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint | Qt::WindowCloseButtonHint | Qt::WindowFullscreenButtonHint); @@ -41,7 +41,7 @@ static QTextBrowser *createBrowser(const QString &helpFile) browser->setReadOnly(true); browser->setMinimumSize({500, 600}); - QString sheet = QString("a { text-decoration: underline; color: rgb(71,158,252) };"); + const QString sheet = QString("a { text-decoration: underline; color: rgb(71,158,252) };"); browser->document()->setDefaultStyleSheet(sheet); browser->setHtml(text); @@ -58,7 +58,7 @@ static QTextBrowser *createBrowser(const QString &helpFile) */ QTextBrowser *createSearchSyntaxHelpWindow(QLineEdit *lineEdit) { - auto browser = createBrowser("theme:help/search.md"); + const auto browser = createBrowser("theme:help/search.md"); QObject::connect(browser, &QTextBrowser::anchorClicked, [lineEdit](const QUrl &link) { lineEdit->setText(link.fragment()); }); QObject::connect(lineEdit, &QObject::destroyed, browser, &QTextBrowser::close); @@ -73,7 +73,7 @@ QTextBrowser *createSearchSyntaxHelpWindow(QLineEdit *lineEdit) */ QTextBrowser *createDeckSearchSyntaxHelpWindow(QLineEdit *lineEdit) { - auto browser = createBrowser("theme:help/deck_search.md"); + const auto browser = createBrowser("theme:help/deck_search.md"); QObject::connect(browser, &QTextBrowser::anchorClicked, [lineEdit](const QUrl &link) { if (link.fragment() == "cardSearchSyntaxHelp") { createSearchSyntaxHelpWindow(lineEdit); diff --git a/cockatrice/src/game/abstract_game.cpp b/cockatrice/src/game/abstract_game.cpp index 505cd5fde..8e03c0a8d 100644 --- a/cockatrice/src/game/abstract_game.cpp +++ b/cockatrice/src/game/abstract_game.cpp @@ -42,7 +42,7 @@ void AbstractGame::setActiveCard(CardItem *card) CardItem *AbstractGame::getCard(int playerId, const QString &zoneName, int cardId) const { - Player *player = playerManager->getPlayer(playerId); + const Player *player = playerManager->getPlayer(playerId); if (!player) return nullptr; diff --git a/cockatrice/src/game/board/abstract_card_drag_item.cpp b/cockatrice/src/game/board/abstract_card_drag_item.cpp index c961cbcb6..fb6c9ca01 100644 --- a/cockatrice/src/game/board/abstract_card_drag_item.cpp +++ b/cockatrice/src/game/board/abstract_card_drag_item.cpp @@ -47,7 +47,7 @@ AbstractCardDragItem::AbstractCardDragItem(AbstractCardItem *_item, QPainterPath AbstractCardDragItem::shape() const { QPainterPath shape; - qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0; + const qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0; shape.addRoundedRect(boundingRect(), cardCornerRadius, cardCornerRadius); return shape; } diff --git a/cockatrice/src/game/board/abstract_card_item.cpp b/cockatrice/src/game/board/abstract_card_item.cpp index d5538011d..df315d3d6 100644 --- a/cockatrice/src/game/board/abstract_card_item.cpp +++ b/cockatrice/src/game/board/abstract_card_item.cpp @@ -44,7 +44,7 @@ QRectF AbstractCardItem::boundingRect() const QPainterPath AbstractCardItem::shape() const { QPainterPath shape; - qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0; + const qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0; shape.addRoundedRect(boundingRect(), cardCornerRadius, cardCornerRadius); return shape; } @@ -60,8 +60,8 @@ void AbstractCardItem::refreshCardInfo() exactCard = CardDatabaseManager::query()->getCard(cardRef); if (!exactCard && !cardRef.name.isEmpty()) { - CardInfo::UiAttributes attributes = {.tableRow = -1}; - auto info = CardInfo::newInstance(cardRef.name, "", true, {}, {}, {}, {}, attributes); + const CardInfo::UiAttributes attributes = {.tableRow = -1}; + const auto info = CardInfo::newInstance(cardRef.name, "", true, {}, {}, {}, {}, attributes); exactCard = ExactCard(info); } if (exactCard) { @@ -98,9 +98,9 @@ void AbstractCardItem::transformPainter(QPainter *painter, const QSizeF &transla const int MAX_FONT_SIZE = SettingsCache::instance().getMaxFontSize(); const int fontSize = std::max(9, MAX_FONT_SIZE); - QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect()); + const QRectF totalBoundingRect = painter->combinedTransform().mapRect(boundingRect()); - int scale = resetPainterTransform(painter); + const int scale = resetPainterTransform(painter); painter->translate(totalBoundingRect.width() / 2, totalBoundingRect.height() / 2); painter->rotate(angle); @@ -114,7 +114,7 @@ void AbstractCardItem::transformPainter(QPainter *painter, const QSizeF &transla void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedSize, int angle) { - qreal scaleFactor = translatedSize.width() / boundingRect().width(); + const qreal scaleFactor = translatedSize.width() / boundingRect().width(); QPixmap translatedPixmap; bool paintImage = true; @@ -173,7 +173,7 @@ void AbstractCardItem::paint(QPainter *painter, const QStyleOptionGraphicsItem * { painter->save(); - QSizeF translatedSize = getTranslatedSize(painter); + const QSizeF translatedSize = getTranslatedSize(painter); paintPicture(painter, translatedSize, tapAngle); painter->setRenderHint(QPainter::Antialiasing, false); diff --git a/cockatrice/src/game/board/card_drag_item.cpp b/cockatrice/src/game/board/card_drag_item.cpp index 9eadadeda..def40db8a 100644 --- a/cockatrice/src/game/board/card_drag_item.cpp +++ b/cockatrice/src/game/board/card_drag_item.cpp @@ -29,7 +29,7 @@ void CardDragItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti void CardDragItem::updatePosition(const QPointF &cursorScenePos) { - QList colliding = + const QList colliding = scene()->items(cursorScenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, static_cast(scene())->getViewTransform()); @@ -55,7 +55,7 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos) if (!cursorZone) { // Avoid the cards getting stuck visually when not over // any zone. - QPointF newPos = cursorScenePos - hotSpot; + const QPointF newPos = cursorScenePos - hotSpot; if (newPos != pos()) { for (int i = 0; i < childDrags.size(); i++) @@ -66,8 +66,8 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos) return; } - QPointF zonePos = currentZone->scenePos(); - QPointF cursorPosInZone = cursorScenePos - zonePos; + const QPointF zonePos = currentZone->scenePos(); + const QPointF cursorPosInZone = cursorScenePos - zonePos; // If we are on a Table, we center the card around the cursor, because we // snap it into place and no longer see it being dragged. @@ -82,7 +82,7 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos) else closestGridPoint = cursorPosInZone - hotSpot; - QPointF newPos = zonePos + closestGridPoint; + const QPointF newPos = zonePos + closestGridPoint; if (newPos != pos()) { for (int i = 0; i < childDrags.size(); i++) @@ -90,7 +90,7 @@ void CardDragItem::updatePosition(const QPointF &cursorScenePos) setPos(newPos); bool newOccupied = false; - TableZone *table = qobject_cast(cursorZone); + const TableZone *table = qobject_cast(cursorZone); if (table) if (table->getCardFromCoords(closestGridPoint)) newOccupied = true; @@ -105,7 +105,7 @@ void CardDragItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { setCursor(Qt::OpenHandCursor); QGraphicsScene *sc = scene(); - QPointF sp = pos(); + const QPointF sp = pos(); sc->removeItem(this); QList dragItemList; diff --git a/cockatrice/src/game/board/card_list.cpp b/cockatrice/src/game/board/card_list.cpp index c324ca10a..838eafff0 100644 --- a/cockatrice/src/game/board/card_list.cpp +++ b/cockatrice/src/game/board/card_list.cpp @@ -47,7 +47,7 @@ void CardList::sortBy(const QList &option) } auto comparator = [&option](CardItem *a, CardItem *b) { - for (auto prop : option) { + for (const auto prop : option) { auto extractor = getExtractorFor(prop); QString t1 = extractor(a); QString t2 = extractor(b); @@ -79,7 +79,7 @@ void CardList::sortBy(const QList &option) */ static QString getColorSortString(const CardInfo &c, bool appendAtEnd) { - QString colors = c.getColors(); + const QString colors = c.getColors(); switch (colors.size()) { case 0: { if (c.getCardType().contains("Land")) { @@ -135,7 +135,7 @@ std::function CardList::getExtractorFor(SortOption option) return QString(); } - auto info = c->getCardInfo(); + const auto info = c->getCardInfo(); // calculation copied from CardDatabaseModel. // we pad the cmc and also append the mana cost to the end so same cmc cards still have a sort order diff --git a/cockatrice/src/game/board/counter_general.cpp b/cockatrice/src/game/board/counter_general.cpp index d68486a1b..e7ed9213e 100644 --- a/cockatrice/src/game/board/counter_general.cpp +++ b/cockatrice/src/game/board/counter_general.cpp @@ -25,10 +25,10 @@ QRectF GeneralCounter::boundingRect() const void GeneralCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QRectF mapRect = painter->combinedTransform().mapRect(boundingRect()); - int translatedHeight = mapRect.size().height(); - qreal scaleFactor = translatedHeight / boundingRect().height(); - QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered); + const QRectF mapRect = painter->combinedTransform().mapRect(boundingRect()); + const int translatedHeight = mapRect.size().height(); + const qreal scaleFactor = translatedHeight / boundingRect().height(); + const QPixmap pixmap = CounterPixmapGenerator::generatePixmap(translatedHeight, name, hovered); painter->save(); resetPainterTransform(painter); diff --git a/cockatrice/src/game/deckview/deck_view.cpp b/cockatrice/src/game/deckview/deck_view.cpp index 64e9abc46..91cdea1e1 100644 --- a/cockatrice/src/game/deckview/deck_view.cpp +++ b/cockatrice/src/game/deckview/deck_view.cpp @@ -21,7 +21,7 @@ DeckViewCardDragItem::DeckViewCardDragItem(DeckViewCard *_item, void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos) { - QList colliding = scene()->items(cursorScenePos); + const QList colliding = scene()->items(cursorScenePos); DeckViewCardContainer *cursorZone = 0; for (int i = colliding.size() - 1; i >= 0; i--) @@ -31,7 +31,7 @@ void DeckViewCardDragItem::updatePosition(const QPointF &cursorScenePos) return; currentZone = cursorZone; - QPointF newPos = cursorScenePos; + const QPointF newPos = cursorScenePos; if (newPos != pos()) { for (int i = 0; i < childDrags.size(); i++) childDrags[i]->setPos(newPos + childDrags[i]->getHotSpot()); @@ -95,7 +95,7 @@ void DeckViewCard::paint(QPainter *painter, const QStyleOptionGraphicsItem *opti pen.setJoinStyle(Qt::MiterJoin); pen.setColor(originZone == DECK_ZONE_MAIN ? Qt::green : Qt::red); painter->setPen(pen); - qreal cardRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * (CARD_WIDTH - 3) : 0.0; + const qreal cardRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * (CARD_WIDTH - 3) : 0.0; painter->drawRoundedRect(QRectF(1.5, 1.5, CARD_WIDTH - 3., CARD_HEIGHT - 3.), cardRadius, cardRadius); painter->restore(); } @@ -115,7 +115,7 @@ void DeckViewCard::mouseMoveEvent(QGraphicsSceneMouseEvent *event) dragItem->updatePosition(event->scenePos()); dragItem->grabMouse(); - QList sel = scene()->selectedItems(); + const QList sel = scene()->selectedItems(); int j = 0; for (int i = 0; i < sel.size(); i++) { auto *c = static_cast(sel.at(i)); @@ -137,11 +137,11 @@ void DeckView::mouseDoubleClickEvent(QMouseEvent *event) if (event->button() == Qt::LeftButton) { QList result; - QList sel = scene()->selectedItems(); + const QList sel = scene()->selectedItems(); for (int i = 0; i < sel.size(); i++) { - auto *c = static_cast(sel.at(i)); - auto *zone = static_cast(c->parentItem()); + const auto *c = static_cast(sel.at(i)); + const auto *zone = static_cast(c->parentItem()); MoveCard_ToZone m; m.set_card_name(c->getName().toStdString()); m.set_start_zone(zone->getName().toStdString()); @@ -180,7 +180,7 @@ QRectF DeckViewCardContainer::boundingRect() const void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - qreal totalTextWidth = getCardTypeTextWidth(); + const qreal totalTextWidth = getCardTypeTextWidth(); painter->fillRect(boundingRect(), themeManager->getBgBrush(ThemeManager::Table)); painter->setPen(QColor(255, 255, 255, 100)); @@ -204,7 +204,7 @@ void DeckViewCardContainer::paint(QPainter *painter, const QStyleOptionGraphicsI painter->setPen(QColor(255, 255, 255, 100)); painter->drawLine(QPointF(0, yUntilNow - paddingY / 2), QPointF(width, yUntilNow - paddingY / 2)); } - qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first; + const qreal thisRowHeight = CARD_HEIGHT * currentRowsAndCols[i].first; QRectF textRect(0, yUntilNow, totalTextWidth, thisRowHeight); yUntilNow += thisRowHeight + paddingY; @@ -242,7 +242,7 @@ int DeckViewCardContainer::getCardTypeTextWidth() const f.setStyleHint(QFont::Serif); f.setPixelSize(16); f.setWeight(QFont::Bold); - QFontMetrics fm(f); + const QFontMetrics fm(f); int maxCardTypeWidth = 0; for (const auto &key : cardsByType.keys()) { @@ -280,7 +280,7 @@ void DeckViewCardContainer::rearrangeItems(const QList> &rowsAnd currentRowsAndCols = rowsAndCols; qreal yUntilNow = separatorY + paddingY; - qreal x = (qreal)getCardTypeTextWidth(); + const qreal x = (qreal)getCardTypeTextWidth(); for (int i = 0; i < rowsAndCols.size(); ++i) { const int tempRows = rowsAndCols[i].first; const int tempCols = rowsAndCols[i].second; @@ -295,7 +295,7 @@ void DeckViewCardContainer::rearrangeItems(const QList> &rowsAnd } prepareGeometryChange(); - QSizeF bRect = calculateBoundingRect(rowsAndCols); + const QSizeF bRect = calculateBoundingRect(rowsAndCols); width = bRect.width(); height = bRect.height(); } @@ -343,9 +343,9 @@ void DeckViewScene::rebuildTree() if (!deck) return; - InnerDecklistNode *listRoot = deck->getRoot(); + const InnerDecklistNode *listRoot = deck->getRoot(); for (int i = 0; i < listRoot->size(); i++) { - auto *currentZone = dynamic_cast(listRoot->at(i)); + const auto *currentZone = dynamic_cast(listRoot->at(i)); DeckViewCardContainer *container = cardContainers.value(currentZone->getName(), 0); if (!container) { @@ -355,7 +355,7 @@ void DeckViewScene::rebuildTree() } for (int j = 0; j < currentZone->size(); j++) { - auto *currentCard = dynamic_cast(currentZone->at(j)); + const auto *currentCard = dynamic_cast(currentZone->at(j)); if (!currentCard) continue; @@ -469,7 +469,7 @@ QList DeckViewScene::getSideboardPlan() const QList result; QMapIterator containerIterator(cardContainers); while (containerIterator.hasNext()) { - DeckViewCardContainer *cont = containerIterator.next().value(); + const DeckViewCardContainer *cont = containerIterator.next().value(); const QList cardList = cont->getCards(); for (int i = 0; i < cardList.size(); ++i) if (cardList[i]->getOriginZone() != cont->getName()) { diff --git a/cockatrice/src/game/deckview/tabbed_deck_view_container.cpp b/cockatrice/src/game/deckview/tabbed_deck_view_container.cpp index 2ffb214f7..ab9a4b742 100644 --- a/cockatrice/src/game/deckview/tabbed_deck_view_container.cpp +++ b/cockatrice/src/game/deckview/tabbed_deck_view_container.cpp @@ -10,7 +10,7 @@ TabbedDeckViewContainer::TabbedDeckViewContainer(int _playerId, TabGame *parent) connect(this, &QTabWidget::tabCloseRequested, this, &TabbedDeckViewContainer::closeTab); playerDeckView = new DeckViewContainer(playerId, parentGame); - int playerTabIndex = addTab(playerDeckView, "Your Deck"); + const int playerTabIndex = addTab(playerDeckView, "Your Deck"); tabBar()->setTabButton(playerTabIndex, QTabBar::RightSide, nullptr); updateTabBarVisibility(); } diff --git a/cockatrice/src/game/dialogs/dlg_create_token.cpp b/cockatrice/src/game/dialogs/dlg_create_token.cpp index 6594e339d..62f75b828 100644 --- a/cockatrice/src/game/dialogs/dlg_create_token.cpp +++ b/cockatrice/src/game/dialogs/dlg_create_token.cpp @@ -91,7 +91,7 @@ DlgCreateToken::DlgCreateToken(const QStringList &_predefinedTokens, QWidget *pa chooseTokenFromDeckRadioButton = new QRadioButton(tr("Show tokens from this &deck")); connect(chooseTokenFromDeckRadioButton, &QRadioButton::toggled, this, &DlgCreateToken::actChooseTokenFromDeck); - QByteArray deckHeaderState = SettingsCache::instance().layouts().getDeckEditorDbHeaderState(); + const QByteArray deckHeaderState = SettingsCache::instance().layouts().getDeckEditorDbHeaderState(); chooseTokenView = new QTreeView; chooseTokenView->setModel(cardDatabaseDisplayModel); chooseTokenView->setUniformRowHeights(true); diff --git a/cockatrice/src/game/dialogs/dlg_move_top_cards_until.cpp b/cockatrice/src/game/dialogs/dlg_move_top_cards_until.cpp index a9db4cef6..2f5ab3e99 100644 --- a/cockatrice/src/game/dialogs/dlg_move_top_cards_until.cpp +++ b/cockatrice/src/game/dialogs/dlg_move_top_cards_until.cpp @@ -104,7 +104,7 @@ void DlgMoveTopCardsUntil::validateAndAccept() // move currently selected text to top of history list if (exprComboBox->currentIndex() != 0) { - QString currentExpr = exprComboBox->currentText(); + const QString currentExpr = exprComboBox->currentText(); exprComboBox->removeItem(exprComboBox->currentIndex()); exprComboBox->insertItem(0, currentExpr); exprComboBox->setCurrentIndex(0); diff --git a/cockatrice/src/game/game_scene.cpp b/cockatrice/src/game/game_scene.cpp index 2175f4aa2..ee573ecff 100644 --- a/cockatrice/src/game/game_scene.cpp +++ b/cockatrice/src/game/game_scene.cpp @@ -122,8 +122,8 @@ void GameScene::rearrange() auto playersPlaying = collectActivePlayers(firstPlayerIndex); playersPlaying = rotatePlayers(playersPlaying, firstPlayerIndex); - int columns = determineColumnCount(playersPlaying.size()); - QSizeF sceneSize = computeSceneSizeAndPlayerLayout(playersPlaying, columns); + const int columns = determineColumnCount(playersPlaying.size()); + const QSizeF sceneSize = computeSceneSizeAndPlayerLayout(playersPlaying, columns); phasesToolbar->setHeight(sceneSize.height()); setSceneRect(0, 0, sceneSize.width(), sceneSize.height()); @@ -147,9 +147,9 @@ void GameScene::processViewSizeChange(const QSize &newSize) viewSize = newSize; QList minWidthByColumn = calculateMinWidthByColumn(); - qreal minWidth = std::accumulate(minWidthByColumn.begin(), minWidthByColumn.end(), phasesToolbar->getWidth()); + const qreal minWidth = std::accumulate(minWidthByColumn.begin(), minWidthByColumn.end(), phasesToolbar->getWidth()); - qreal newWidth = calculateNewSceneWidth(newSize, minWidth); + const qreal newWidth = calculateNewSceneWidth(newSize, minWidth); setSceneRect(0, 0, newWidth, sceneRect().height()); resizeColumnsAndPlayers(minWidthByColumn, newWidth); @@ -170,7 +170,7 @@ QList GameScene::collectActivePlayers(int &firstPlayerIndex) const firstPlayerIndex = 0; bool firstPlayerFound = false; - for (auto *pgItem : players) { + for (const auto *pgItem : players) { Player *p = pgItem->getPlayer(); if (p && !p->getConceded()) { activePlayers.append(p); @@ -226,7 +226,7 @@ QSizeF GameScene::computeSceneSizeAndPlayerLayout(const QList &players { playersByColumn.clear(); - int rows = qCeil((qreal)playersPlaying.size() / columns); + const int rows = qCeil((qreal)playersPlaying.size() / columns); qreal sceneHeight = 0, sceneWidth = -playerAreaSpacing; QList columnWidth; @@ -235,7 +235,7 @@ QSizeF GameScene::computeSceneSizeAndPlayerLayout(const QList &players playersByColumn.append(QList()); columnWidth.append(0); qreal thisColumnHeight = -playerAreaSpacing; - int rowsInColumn = rows - (playersPlaying.size() % columns) * col; // Adjust rows for uneven columns + const int rowsInColumn = rows - (playersPlaying.size() % columns) * col; // Adjust rows for uneven columns for (int j = 0; j < rowsInColumn; ++j) { Player *player = playersIter.next(); @@ -244,7 +244,7 @@ QSizeF GameScene::computeSceneSizeAndPlayerLayout(const QList &players else playersByColumn[col].append(player->getGraphicsItem()); - auto *pgItem = player->getGraphicsItem(); + const auto *pgItem = player->getGraphicsItem(); thisColumnHeight += pgItem->boundingRect().height() + playerAreaSpacing; columnWidth[col] = std::max(columnWidth[col], (int)pgItem->boundingRect().width()); } @@ -253,7 +253,7 @@ QSizeF GameScene::computeSceneSizeAndPlayerLayout(const QList &players sceneWidth += columnWidth[col] + playerAreaSpacing; } - qreal phasesWidth = phasesToolbar->getWidth(); + const qreal phasesWidth = phasesToolbar->getWidth(); sceneWidth += phasesWidth; // Position players horizontally and vertically @@ -281,7 +281,7 @@ QList GameScene::calculateMinWidthByColumn() const QList minWidthByColumn; for (const auto &col : playersByColumn) { qreal maxWidth = 0; - for (PlayerGraphicsItem *player : col) + for (const PlayerGraphicsItem *player : col) maxWidth = std::max(maxWidth, player->getMinimumWidth()); minWidthByColumn.append(maxWidth); } @@ -296,8 +296,8 @@ QList GameScene::calculateMinWidthByColumn() const */ qreal GameScene::calculateNewSceneWidth(const QSize &newSize, qreal minWidth) const { - qreal newRatio = (qreal)newSize.width() / newSize.height(); - qreal minRatio = minWidth / sceneRect().height(); + const qreal newRatio = (qreal)newSize.width() / newSize.height(); + const qreal minRatio = minWidth / sceneRect().height(); if (minRatio > newRatio) { return minWidth; // Table dominates width @@ -316,9 +316,9 @@ qreal GameScene::calculateNewSceneWidth(const QSize &newSize, qreal minWidth) co */ void GameScene::resizeColumnsAndPlayers(const QList &minWidthByColumn, qreal newWidth) { - qreal minWidth = std::accumulate(minWidthByColumn.begin(), minWidthByColumn.end(), phasesToolbar->getWidth()); + const qreal minWidth = std::accumulate(minWidthByColumn.begin(), minWidthByColumn.end(), phasesToolbar->getWidth()); - qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size(); + const qreal extraWidthPerColumn = (newWidth - minWidth) / playersByColumn.size(); qreal newx = phasesToolbar->getWidth(); for (int col = 0; col < playersByColumn.size(); ++col) { @@ -334,7 +334,7 @@ void GameScene::resizeColumnsAndPlayers(const QList &minWidthByColumn, qr void GameScene::updateHover(const QPointF &scenePos) { - auto itemList = items(scenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, getViewTransform()); + const auto itemList = items(scenePos, Qt::IntersectsItemBoundingRect, Qt::DescendingOrder, getViewTransform()); CardZone *zone = findTopmostZone(itemList); CardItem *topCard = zone ? findTopmostCardInZone(itemList, zone) : nullptr; @@ -396,8 +396,8 @@ CardItem *GameScene::findTopmostCardInZone(const QList &items, */ void GameScene::toggleZoneView(Player *player, const QString &zoneName, int numberCards, bool isReversed) { - for (auto &view : zoneViews) { - ZoneViewZone *temp = view->getZone(); + for (const auto &view : zoneViews) { + const ZoneViewZone *temp = view->getZone(); if (temp->getLogic()->getName() == zoneName && temp->getLogic()->getPlayer() == player && qobject_cast(temp->getLogic())->getNumberCards() == numberCards) { view->close(); diff --git a/cockatrice/src/game/game_state.cpp b/cockatrice/src/game/game_state.cpp index 854878b92..914d4046f 100644 --- a/cockatrice/src/game/game_state.cpp +++ b/cockatrice/src/game/game_state.cpp @@ -32,7 +32,7 @@ void GameState::setGameTime(int _secondsElapsed) int seconds = _secondsElapsed; int minutes = seconds / 60; seconds -= minutes * 60; - int hours = minutes / 60; + const int hours = minutes / 60; minutes -= hours * 60; emit updateTimeElapsedLabel(QString::number(hours).rightJustified(2, '0') + ":" + diff --git a/cockatrice/src/game/hand_counter.cpp b/cockatrice/src/game/hand_counter.cpp index 35989ff38..6995854cb 100644 --- a/cockatrice/src/game/hand_counter.cpp +++ b/cockatrice/src/game/hand_counter.cpp @@ -29,7 +29,7 @@ QRectF HandCounter::boundingRect() const void HandCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { painter->save(); - QSize translatedSize = painter->combinedTransform().mapRect(boundingRect()).size().toSize(); + const QSize translatedSize = painter->combinedTransform().mapRect(boundingRect()).size().toSize(); QPixmap cachedPixmap; if (!QPixmapCache::find("handCounter" + QString::number(translatedSize.width()), &cachedPixmap)) { cachedPixmap = QPixmap("theme:hand").scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); diff --git a/cockatrice/src/game/player/menu/card_menu.cpp b/cockatrice/src/game/player/menu/card_menu.cpp index ddf0a55f3..1674f9181 100644 --- a/cockatrice/src/game/player/menu/card_menu.cpp +++ b/cockatrice/src/game/player/menu/card_menu.cpp @@ -16,11 +16,11 @@ CardMenu::CardMenu(Player *_player, const CardItem *_card, bool _shortcutsActive) : player(_player), card(_card), shortcutsActive(_shortcutsActive) { - auto playerActions = player->getPlayerActions(); + const auto playerActions = player->getPlayerActions(); const QList &players = player->getGame()->getPlayerManager()->getPlayers().values(); - for (auto playerToAdd : players) { + for (const auto playerToAdd : players) { if (playerToAdd == player) { continue; } @@ -95,7 +95,7 @@ CardMenu::CardMenu(Player *_player, const CardItem *_card, bool _shortcutsActive bool revealedCard = false; bool writeableCard = player->getPlayerInfo()->getLocalOrJudge(); - if (auto *view = qobject_cast(card->getZone())) { + if (const auto *view = qobject_cast(card->getZone())) { if (view->getRevealZone()) { if (view->getWriteableRevealZone()) { writeableCard = true; @@ -155,7 +155,7 @@ void CardMenu::removePlayer(Player *playerToRemove) void CardMenu::createTableMenu() { // Card is on the battlefield - bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player; + const bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player; if (!canModifyCard) { addRelatedCardView(); @@ -213,7 +213,7 @@ void CardMenu::createTableMenu() void CardMenu::createStackMenu() { - bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player; + const bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player; // Card is on the stack if (canModifyCard) { @@ -238,7 +238,7 @@ void CardMenu::createStackMenu() void CardMenu::createGraveyardOrExileMenu() { - bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player; + const bool canModifyCard = player->getPlayerInfo()->judge || card->getOwner() == player; // Card is in the graveyard or exile if (canModifyCard) { @@ -328,7 +328,7 @@ void CardMenu::addRelatedCardView() if (!card) { return; } - auto exactCard = card->getCard(); + const auto exactCard = card->getCard(); if (!exactCard) { return; } @@ -348,12 +348,12 @@ void CardMenu::addRelatedCardView() } addSeparator(); - auto viewRelatedCards = new QMenu(tr("View related cards")); + const auto viewRelatedCards = new QMenu(tr("View related cards")); addMenu(viewRelatedCards); for (const CardRelation *relatedCard : relatedCards) { QString relatedCardName = relatedCard->getName(); CardRef cardRef = {relatedCardName, exactCard.getPrinting().getUuid()}; - QAction *viewCard = viewRelatedCards->addAction(relatedCardName); + const QAction *viewCard = viewRelatedCards->addAction(relatedCardName); Q_UNUSED(viewCard); connect(viewCard, &QAction::triggered, player->getGame(), @@ -366,7 +366,7 @@ void CardMenu::addRelatedCardActions() if (!card) { return; } - auto exactCard = card->getCard(); + const auto exactCard = card->getCard(); if (!exactCard) { return; } @@ -460,7 +460,7 @@ void CardMenu::retranslateUi() mCardCounters->setTitle(tr("Ca&rd counters")); - auto &cardCounterSettings = SettingsCache::instance().cardCounters(); + const auto &cardCounterSettings = SettingsCache::instance().cardCounters(); for (int i = 0; i < aAddCounter.size(); ++i) { aAddCounter[i]->setText(tr("&Add counter (%1)").arg(cardCounterSettings.displayName(i))); @@ -475,7 +475,7 @@ void CardMenu::retranslateUi() void CardMenu::setShortcutsActive() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aHide->setShortcuts(shortcuts.getShortcut("Player/aHide")); aPlay->setShortcuts(shortcuts.getShortcut("Player/aPlay")); diff --git a/cockatrice/src/game/player/menu/custom_zone_menu.cpp b/cockatrice/src/game/player/menu/custom_zone_menu.cpp index b0f3284c9..1c5025f04 100644 --- a/cockatrice/src/game/player/menu/custom_zone_menu.cpp +++ b/cockatrice/src/game/player/menu/custom_zone_menu.cpp @@ -19,7 +19,7 @@ void CustomZoneMenu::retranslateUi() if (player->getPlayerInfo()->getLocalOrJudge()) { - for (auto aViewZone : actions()) { + for (const auto aViewZone : actions()) { aViewZone->setText(tr("View custom zone '%1'").arg(aViewZone->data().toString())); } } diff --git a/cockatrice/src/game/player/menu/grave_menu.cpp b/cockatrice/src/game/player/menu/grave_menu.cpp index 47d01bc77..508491e91 100644 --- a/cockatrice/src/game/player/menu/grave_menu.cpp +++ b/cockatrice/src/game/player/menu/grave_menu.cpp @@ -36,7 +36,7 @@ GraveyardMenu::GraveyardMenu(Player *_player, QWidget *parent) : TearOffMenu(par void GraveyardMenu::createMoveActions() { - auto grave = player->getGraveZone(); + const auto grave = player->getGraveZone(); if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) { aMoveGraveToTopLibrary = new QAction(this); @@ -60,7 +60,7 @@ void GraveyardMenu::createMoveActions() void GraveyardMenu::createViewActions() { - PlayerActions *playerActions = player->getPlayerActions(); + const PlayerActions *playerActions = player->getPlayerActions(); aViewGraveyard = new QAction(this); connect(aViewGraveyard, &QAction::triggered, playerActions, &PlayerActions::actViewGraveyard); @@ -77,7 +77,7 @@ void GraveyardMenu::populateRevealRandomMenuWithActivePlayers() mRevealRandomGraveyardCard->addSeparator(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); - for (auto *other : players) { + for (const auto *other : players) { if (other == player) continue; QAction *a = mRevealRandomGraveyardCard->addAction(other->getPlayerInfo()->getName()); @@ -88,7 +88,7 @@ void GraveyardMenu::populateRevealRandomMenuWithActivePlayers() void GraveyardMenu::onRevealRandomTriggered() { - if (auto *a = qobject_cast(sender())) { + if (const auto *a = qobject_cast(sender())) { player->getPlayerActions()->actRevealRandomGraveyardCard(a->data().toInt()); } } @@ -112,7 +112,7 @@ void GraveyardMenu::retranslateUi() void GraveyardMenu::setShortcutsActive() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aViewGraveyard->setShortcuts(shortcuts.getShortcut("Player/aViewGraveyard")); } diff --git a/cockatrice/src/game/player/menu/hand_menu.cpp b/cockatrice/src/game/player/menu/hand_menu.cpp index e193d2e4a..2efb27b6c 100644 --- a/cockatrice/src/game/player/menu/hand_menu.cpp +++ b/cockatrice/src/game/player/menu/hand_menu.cpp @@ -74,7 +74,7 @@ HandMenu::HandMenu(Player *_player, PlayerActions *actions, QWidget *parent) : T aMoveHandToRfg = new QAction(this); aMoveHandToRfg->setData(QList() << "rfg" << 0); - auto hand = player->getHandZone(); + const auto hand = player->getHandZone(); connect(aMoveHandToTopLibrary, &QAction::triggered, hand, &HandZoneLogic::moveAllToZone); connect(aMoveHandToBottomLibrary, &QAction::triggered, hand, &HandZoneLogic::moveAllToZone); @@ -122,7 +122,7 @@ void HandMenu::retranslateUi() void HandMenu::setShortcutsActive() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aViewHand->setShortcuts(shortcuts.getShortcut("Player/aViewHand")); aSortHandByName->setShortcuts(shortcuts.getShortcut("Player/aSortHandByName")); aSortHandByType->setShortcuts(shortcuts.getShortcut("Player/aSortHandByType")); @@ -152,7 +152,7 @@ void HandMenu::populateRevealHandMenuWithActivePlayers() mRevealHand->addSeparator(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); - for (auto *other : players) { + for (const auto *other : players) { if (other == player) continue; QAction *a = mRevealHand->addAction(other->getPlayerInfo()->getName()); @@ -170,7 +170,7 @@ void HandMenu::populateRevealRandomHandCardMenuWithActivePlayers() mRevealRandomHandCard->addSeparator(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); - for (auto *other : players) { + for (const auto *other : players) { if (other == player) continue; QAction *a = mRevealRandomHandCard->addAction(other->getPlayerInfo()->getName()); @@ -181,7 +181,7 @@ void HandMenu::populateRevealRandomHandCardMenuWithActivePlayers() void HandMenu::onRevealHandTriggered() { - auto *action = qobject_cast(sender()); + const auto *action = qobject_cast(sender()); if (!action) return; @@ -191,7 +191,7 @@ void HandMenu::onRevealHandTriggered() void HandMenu::onRevealRandomHandCardTriggered() { - auto *action = qobject_cast(sender()); + const auto *action = qobject_cast(sender()); if (!action) return; diff --git a/cockatrice/src/game/player/menu/library_menu.cpp b/cockatrice/src/game/player/menu/library_menu.cpp index 749439558..62224d94f 100644 --- a/cockatrice/src/game/player/menu/library_menu.cpp +++ b/cockatrice/src/game/player/menu/library_menu.cpp @@ -90,7 +90,7 @@ void LibraryMenu::resetTopCardMenuActions() void LibraryMenu::createDrawActions() { - PlayerActions *playerActions = player->getPlayerActions(); + const PlayerActions *playerActions = player->getPlayerActions(); if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) { aDrawCard = new QAction(this); @@ -108,7 +108,7 @@ void LibraryMenu::createDrawActions() void LibraryMenu::createShuffleActions() { - PlayerActions *playerActions = player->getPlayerActions(); + const PlayerActions *playerActions = player->getPlayerActions(); if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) { aShuffle = new QAction(this); @@ -122,7 +122,7 @@ void LibraryMenu::createShuffleActions() void LibraryMenu::createMoveActions() { - PlayerActions *playerActions = player->getPlayerActions(); + const PlayerActions *playerActions = player->getPlayerActions(); if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) { aMoveTopToPlay = new QAction(this); @@ -165,7 +165,7 @@ void LibraryMenu::createMoveActions() void LibraryMenu::createViewActions() { - PlayerActions *playerActions = player->getPlayerActions(); + const PlayerActions *playerActions = player->getPlayerActions(); if (player->getPlayerInfo()->local || player->getPlayerInfo()->judge) { aViewLibrary = new QAction(this); @@ -244,7 +244,7 @@ void LibraryMenu::populateRevealLibraryMenuWithActivePlayers() mRevealLibrary->addSeparator(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); - for (auto *other : players) { + for (const auto *other : players) { if (other == player) continue; QAction *a = mRevealLibrary->addAction(other->getPlayerInfo()->getName()); @@ -258,7 +258,7 @@ void LibraryMenu::populateLendLibraryMenuWithActivePlayers() mLendLibrary->clear(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); - for (auto *other : players) { + for (const auto *other : players) { if (other == player) continue; QAction *a = mLendLibrary->addAction(other->getPlayerInfo()->getName()); @@ -278,7 +278,7 @@ void LibraryMenu::populateRevealTopCardMenuWithActivePlayers() mRevealTopCard->addSeparator(); const auto &players = player->getGame()->getPlayerManager()->getPlayers().values(); - for (auto *other : players) { + for (const auto *other : players) { if (other == player) continue; QAction *a = mRevealTopCard->addAction(other->getPlayerInfo()->getName()); @@ -289,26 +289,26 @@ void LibraryMenu::populateRevealTopCardMenuWithActivePlayers() void LibraryMenu::onRevealLibraryTriggered() { - if (auto *a = qobject_cast(sender())) { + if (const auto *a = qobject_cast(sender())) { player->getPlayerActions()->actRevealLibrary(a->data().toInt()); } } void LibraryMenu::onLendLibraryTriggered() { - if (auto *a = qobject_cast(sender())) { + if (const auto *a = qobject_cast(sender())) { player->getPlayerActions()->actLendLibrary(a->data().toInt()); } } void LibraryMenu::onRevealTopCardTriggered() { - if (auto *a = qobject_cast(sender())) { - int deckSize = player->getDeckZone()->getCards().size(); + if (const auto *a = qobject_cast(sender())) { + const int deckSize = player->getDeckZone()->getCards().size(); bool ok; - int number = QInputDialog::getInt(player->getGame()->getTab(), tr("Reveal top cards of library"), - tr("Number of cards: (max. %1)").arg(deckSize), defaultNumberTopCards, 1, - deckSize, 1, &ok); + const int number = QInputDialog::getInt(player->getGame()->getTab(), tr("Reveal top cards of library"), + tr("Number of cards: (max. %1)").arg(deckSize), defaultNumberTopCards, + 1, deckSize, 1, &ok); if (ok) { player->getPlayerActions()->actRevealTopCards(a->data().toInt(), number); defaultNumberTopCards = number; @@ -318,7 +318,7 @@ void LibraryMenu::onRevealTopCardTriggered() void LibraryMenu::setShortcutsActive() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aViewLibrary->setShortcuts(shortcuts.getShortcut("Player/aViewLibrary")); aViewTopCards->setShortcuts(shortcuts.getShortcut("Player/aViewTopCards")); diff --git a/cockatrice/src/game/player/menu/move_menu.cpp b/cockatrice/src/game/player/menu/move_menu.cpp index d27e16009..37466ddf6 100644 --- a/cockatrice/src/game/player/menu/move_menu.cpp +++ b/cockatrice/src/game/player/menu/move_menu.cpp @@ -43,7 +43,7 @@ MoveMenu::MoveMenu(Player *player) : QMenu(tr("Move to")) void MoveMenu::setShortcutsActive() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aMoveToTopLibrary->setShortcuts(shortcuts.getShortcut("Player/aMoveToTopLibrary")); aMoveToBottomLibrary->setShortcuts(shortcuts.getShortcut("Player/aMoveToBottomLibrary")); diff --git a/cockatrice/src/game/player/menu/pt_menu.cpp b/cockatrice/src/game/player/menu/pt_menu.cpp index dae03e07f..b032360e2 100644 --- a/cockatrice/src/game/player/menu/pt_menu.cpp +++ b/cockatrice/src/game/player/menu/pt_menu.cpp @@ -63,7 +63,7 @@ void PtMenu::retranslateUi() void PtMenu::setShortcutsActive() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aIncP->setShortcuts(shortcuts.getShortcut("Player/aIncP")); aDecP->setShortcuts(shortcuts.getShortcut("Player/aDecP")); diff --git a/cockatrice/src/game/player/menu/rfg_menu.cpp b/cockatrice/src/game/player/menu/rfg_menu.cpp index 25e162581..3aff9313e 100644 --- a/cockatrice/src/game/player/menu/rfg_menu.cpp +++ b/cockatrice/src/game/player/menu/rfg_menu.cpp @@ -27,7 +27,7 @@ RfgMenu::RfgMenu(Player *_player, QWidget *parent) : TearOffMenu(parent), player void RfgMenu::createMoveActions() { if (player->getPlayerInfo()->getLocalOrJudge()) { - auto rfg = player->getRfgZone(); + const auto rfg = player->getRfgZone(); aMoveRfgToTopLibrary = new QAction(this); aMoveRfgToTopLibrary->setData(QList() << "deck" << 0); @@ -47,7 +47,7 @@ void RfgMenu::createMoveActions() void RfgMenu::createViewActions() { - PlayerActions *playerActions = player->getPlayerActions(); + const PlayerActions *playerActions = player->getPlayerActions(); aViewRfg = new QAction(this); connect(aViewRfg, &QAction::triggered, playerActions, &PlayerActions::actViewRfg); diff --git a/cockatrice/src/game/player/menu/say_menu.cpp b/cockatrice/src/game/player/menu/say_menu.cpp index 3c4802aa5..6e3226e03 100644 --- a/cockatrice/src/game/player/menu/say_menu.cpp +++ b/cockatrice/src/game/player/menu/say_menu.cpp @@ -14,7 +14,7 @@ void SayMenu::initSayMenu() { clear(); - int count = SettingsCache::instance().messages().getCount(); + const int count = SettingsCache::instance().messages().getCount(); setEnabled(count > 0); for (int i = 0; i < count; ++i) { diff --git a/cockatrice/src/game/player/menu/sideboard_menu.cpp b/cockatrice/src/game/player/menu/sideboard_menu.cpp index bfc40cfd3..9b3dd5557 100644 --- a/cockatrice/src/game/player/menu/sideboard_menu.cpp +++ b/cockatrice/src/game/player/menu/sideboard_menu.cpp @@ -22,7 +22,7 @@ void SideboardMenu::retranslateUi() void SideboardMenu::setShortcutsActive() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aViewSideboard->setShortcuts(shortcuts.getShortcut("Player/aViewSideboard")); } diff --git a/cockatrice/src/game/player/menu/utility_menu.cpp b/cockatrice/src/game/player/menu/utility_menu.cpp index 15128defe..2eb9234d3 100644 --- a/cockatrice/src/game/player/menu/utility_menu.cpp +++ b/cockatrice/src/game/player/menu/utility_menu.cpp @@ -6,7 +6,7 @@ UtilityMenu::UtilityMenu(Player *_player, QMenu *playerMenu) : QMenu(playerMenu), player(_player) { - PlayerActions *playerActions = player->getPlayerActions(); + const PlayerActions *playerActions = player->getPlayerActions(); if (player->getPlayerInfo()->getLocalOrJudge()) { aUntapAll = new QAction(this); @@ -62,7 +62,7 @@ void UtilityMenu::populatePredefinedTokensMenu() return; } - InnerDecklistNode *tokenZone = + const InnerDecklistNode *tokenZone = dynamic_cast(_deck->getDeckList()->getRoot()->findChild(DECK_ZONE_TOKENS)); if (tokenZone) { @@ -95,7 +95,7 @@ void UtilityMenu::retranslateUi() void UtilityMenu::setShortcutsActive() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); if (player->getPlayerInfo()->getLocalOrJudge()) { aIncrementAllCardCounters->setShortcuts(shortcuts.getShortcut("Player/aIncrementAllCardCounters")); diff --git a/cockatrice/src/game/player/player_area.cpp b/cockatrice/src/game/player/player_area.cpp index 86b8c2d1b..5365350fb 100644 --- a/cockatrice/src/game/player/player_area.cpp +++ b/cockatrice/src/game/player/player_area.cpp @@ -18,7 +18,7 @@ void PlayerArea::updateBg() void PlayerArea::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Player, playerZoneId); + const QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Player, playerZoneId); painter->fillRect(boundingRect(), brush); } diff --git a/cockatrice/src/game/player/player_graphics_item.cpp b/cockatrice/src/game/player/player_graphics_item.cpp index 27fbc82c8..53f4f5ed2 100644 --- a/cockatrice/src/game/player/player_graphics_item.cpp +++ b/cockatrice/src/game/player/player_graphics_item.cpp @@ -14,7 +14,7 @@ PlayerGraphicsItem::PlayerGraphicsItem(Player *_player) : player(_player) playerArea = new PlayerArea(this); playerTarget = new PlayerTarget(player, playerArea); - qreal avatarMargin = (counterAreaWidth + CARD_HEIGHT + 15 - playerTarget->boundingRect().width()) / 2.0; + const qreal avatarMargin = (counterAreaWidth + CARD_HEIGHT + 15 - playerTarget->boundingRect().width()) / 2.0; playerTarget->setPos(QPointF(avatarMargin, avatarMargin)); initializeZones(); @@ -50,18 +50,18 @@ void PlayerGraphicsItem::onPlayerActiveChanged(bool _active) void PlayerGraphicsItem::initializeZones() { deckZoneGraphicsItem = new PileZone(player->getDeckZone(), this); - auto base = QPointF(counterAreaWidth + (CARD_HEIGHT - CARD_WIDTH + 15) / 2.0, - 10 + playerTarget->boundingRect().height() + 5 - (CARD_HEIGHT - CARD_WIDTH) / 2.0); + const auto base = QPointF(counterAreaWidth + (CARD_HEIGHT - CARD_WIDTH + 15) / 2.0, + 10 + playerTarget->boundingRect().height() + 5 - (CARD_HEIGHT - CARD_WIDTH) / 2.0); deckZoneGraphicsItem->setPos(base); - qreal h = deckZoneGraphicsItem->boundingRect().width() + 5; + const qreal h = deckZoneGraphicsItem->boundingRect().width() + 5; sideboardGraphicsItem = new PileZone(player->getSideboardZone(), this); player->getSideboardZone()->setGraphicsVisibility(false); auto *handCounter = new HandCounter(playerArea); handCounter->setPos(base + QPointF(0, h + 10)); - qreal h2 = handCounter->boundingRect().height(); + const qreal h2 = handCounter->boundingRect().height(); graveyardZoneGraphicsItem = new PileZone(player->getGraveZone(), this); graveyardZoneGraphicsItem->setPos(base + QPointF(0, h + h2 + 10)); @@ -127,7 +127,7 @@ void PlayerGraphicsItem::setMirrored(bool _mirrored) void PlayerGraphicsItem::rearrangeCounters() { - qreal marginTop = 80; + const qreal marginTop = 80; const qreal padding = 5; qreal ySize = boundingRect().y() + marginTop; @@ -198,9 +198,9 @@ void PlayerGraphicsItem::rearrangeZones() void PlayerGraphicsItem::updateBoundingRect() { prepareGeometryChange(); - qreal width = CARD_HEIGHT + 15 + counterAreaWidth + stackZoneGraphicsItem->boundingRect().width(); + const qreal width = CARD_HEIGHT + 15 + counterAreaWidth + stackZoneGraphicsItem->boundingRect().width(); if (SettingsCache::instance().getHorizontalHand()) { - qreal handHeight = + const qreal handHeight = player->getPlayerInfo()->getHandVisible() ? handZoneGraphicsItem->boundingRect().height() : 0; bRect = QRectF(0, 0, width + tableZoneGraphicsItem->boundingRect().width(), tableZoneGraphicsItem->boundingRect().height() + handHeight); diff --git a/cockatrice/src/game/player/player_manager.cpp b/cockatrice/src/game/player/player_manager.cpp index e283d2196..0ffafbea6 100644 --- a/cockatrice/src/game/player/player_manager.cpp +++ b/cockatrice/src/game/player/player_manager.cpp @@ -14,7 +14,7 @@ PlayerManager::PlayerManager(AbstractGame *_game, bool PlayerManager::isMainPlayerConceded() const { - Player *player = players.value(localPlayerId, nullptr); + const Player *player = players.value(localPlayerId, nullptr); return player && player->getConceded(); } diff --git a/cockatrice/src/game/player/player_manager.h b/cockatrice/src/game/player/player_manager.h index 0f813b3e4..9c264f6c7 100644 --- a/cockatrice/src/game/player/player_manager.h +++ b/cockatrice/src/game/player/player_manager.h @@ -95,7 +95,7 @@ public: void removeSpectator(int spectatorId) { - ServerInfo_User spectatorInfo = spectators.value(spectatorId); + const ServerInfo_User spectatorInfo = spectators.value(spectatorId); spectators.remove(spectatorId); emit spectatorRemoved(spectatorId, spectatorInfo); } diff --git a/cockatrice/src/game/player/player_target.cpp b/cockatrice/src/game/player/player_target.cpp index a7a5cc5e7..e4444e442 100644 --- a/cockatrice/src/game/player/player_target.cpp +++ b/cockatrice/src/game/player/player_target.cpp @@ -37,8 +37,8 @@ void PlayerCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /* painter->drawPath(path); - QRectF translatedRect = path.controlPointRect(); - QSize translatedSize = translatedRect.size().toSize(); + const QRectF translatedRect = path.controlPointRect(); + const QSize translatedSize = translatedRect.size().toSize(); QFont font("Serif"); font.setWeight(QFont::Bold); font.setPixelSize(qMax(qRound(translatedSize.height() / 1.3), 9)); diff --git a/cockatrice/src/game/zones/hand_zone.cpp b/cockatrice/src/game/zones/hand_zone.cpp index 860881f38..01f10e151 100644 --- a/cockatrice/src/game/zones/hand_zone.cpp +++ b/cockatrice/src/game/zones/hand_zone.cpp @@ -26,7 +26,7 @@ void HandZone::handleDropEvent(const QList &dragItems, CardZoneLogic *startZone, const QPoint &dropPoint) { - QPoint point = dropPoint + scenePos().toPoint(); + const QPoint point = dropPoint + scenePos().toPoint(); int x = -1; if (SettingsCache::instance().getHorizontalHand()) { for (x = 0; x < getLogic()->getCards().size(); x++) @@ -62,7 +62,7 @@ QRectF HandZone::boundingRect() const void HandZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Hand, getLogic()->getPlayer()->getZoneId()); + const QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Hand, getLogic()->getPlayer()->getZoneId()); painter->fillRect(boundingRect(), brush); } @@ -71,10 +71,10 @@ void HandZone::reorganizeCards() if (!getLogic()->getCards().isEmpty()) { const int cardCount = getLogic()->getCards().size(); if (SettingsCache::instance().getHorizontalHand()) { - bool leftJustified = SettingsCache::instance().getLeftJustified(); - qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width(); + const bool leftJustified = SettingsCache::instance().getLeftJustified(); + const qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width(); const int xPadding = leftJustified ? cardWidth * 1.4 : 5; - qreal totalWidth = + const qreal totalWidth = leftJustified ? boundingRect().width() - (1 * xPadding) - 5 : boundingRect().width() - 2 * xPadding; for (int i = 0; i < cardCount; i++) { @@ -84,7 +84,7 @@ void HandZone::reorganizeCards() if (cardWidth * cardCount > totalWidth) c->setPos(xPadding + ((qreal)i) * (totalWidth - cardWidth) / (cardCount - 1), 5); else { - qreal xPosition = + const qreal xPosition = leftJustified ? xPadding + ((qreal)i) * cardWidth : xPadding + ((qreal)i) * cardWidth + (totalWidth - cardCount * cardWidth) / 2; c->setPos(xPosition, 5); @@ -92,17 +92,17 @@ void HandZone::reorganizeCards() c->setRealZValue(i); } } else { - qreal totalWidth = boundingRect().width(); - qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width(); - qreal xspace = 5; - qreal x1 = xspace; - qreal x2 = totalWidth - xspace - cardWidth; + const qreal totalWidth = boundingRect().width(); + const qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width(); + const qreal xspace = 5; + const qreal x1 = xspace; + const qreal x2 = totalWidth - xspace - cardWidth; for (int i = 0; i < cardCount; i++) { CardItem *card = getLogic()->getCards().at(i); - qreal x = (i % 2) ? x2 : x1; - qreal y = divideCardSpaceInZone(i, cardCount, boundingRect().height(), - getLogic()->getCards().at(0)->boundingRect().height()); + const qreal x = (i % 2) ? x2 : x1; + const qreal y = divideCardSpaceInZone(i, cardCount, boundingRect().height(), + getLogic()->getCards().at(0)->boundingRect().height()); card->setPos(x, y); card->setRealZValue(i); } diff --git a/cockatrice/src/game/zones/logic/view_zone_logic.cpp b/cockatrice/src/game/zones/logic/view_zone_logic.cpp index 5a4db3163..7f0e2c863 100644 --- a/cockatrice/src/game/zones/logic/view_zone_logic.cpp +++ b/cockatrice/src/game/zones/logic/view_zone_logic.cpp @@ -44,8 +44,8 @@ bool ZoneViewZoneLogic::prepareAddCard(int x) } } else { // map x (which is in origZone indexes) to this viewZone's cardList index - int firstId = cards.isEmpty() ? origZone->getCards().size() : cards.front()->getId(); - int insertionIndex = x - firstId; + const int firstId = cards.isEmpty() ? origZone->getCards().size() : cards.front()->getId(); + const int insertionIndex = x - firstId; if (insertionIndex >= 0) { // card was put into a portion of the deck that's in the view doInsert = true; @@ -79,8 +79,8 @@ void ZoneViewZoneLogic::addCardImpl(CardItem *card, int x, int /*y*/) cards.insert(x, card); } else { // map x (which is in origZone indexes) to this viewZone's cardList index - int firstId = cards.isEmpty() ? origZone->getCards().size() : cards.front()->getId(); - int insertionIndex = x - firstId; + const int firstId = cards.isEmpty() ? origZone->getCards().size() : cards.front()->getId(); + const int insertionIndex = x - firstId; // qMin to prevent out-of-bounds error when bottoming a card that is already in the view cards.insert(qMin(insertionIndex, cards.size()), card); } @@ -99,7 +99,7 @@ void ZoneViewZoneLogic::updateCardIds(CardAction action) return; } - int cardCount = cards.size(); + const int cardCount = cards.size(); auto startId = 0; diff --git a/cockatrice/src/game/zones/pile_zone.cpp b/cockatrice/src/game/zones/pile_zone.cpp index cafb29038..f7cae3fe3 100644 --- a/cockatrice/src/game/zones/pile_zone.cpp +++ b/cockatrice/src/game/zones/pile_zone.cpp @@ -38,7 +38,7 @@ QRectF PileZone::boundingRect() const QPainterPath PileZone::shape() const { QPainterPath shape; - qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0; + const qreal cardCornerRadius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * CARD_WIDTH : 0.0; shape.addRoundedRect(boundingRect(), cardCornerRadius, cardCornerRadius); return shape; } @@ -100,8 +100,8 @@ void PileZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event) if (getLogic()->getCards().isEmpty()) return; - bool faceDown = event->modifiers().testFlag(Qt::ShiftModifier); - bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier); + const bool faceDown = event->modifiers().testFlag(Qt::ShiftModifier); + const bool bottomCard = event->modifiers().testFlag(Qt::ControlModifier); CardItem *card = bottomCard ? getLogic()->getCards().last() : getLogic()->getCards().first(); const int cardid = getLogic()->contentsKnown() ? card->getId() : (bottomCard ? getLogic()->getCards().size() - 1 : 0); diff --git a/cockatrice/src/game/zones/select_zone.cpp b/cockatrice/src/game/zones/select_zone.cpp index 719eec148..a0a8cb9ef 100644 --- a/cockatrice/src/game/zones/select_zone.cpp +++ b/cockatrice/src/game/zones/select_zone.cpp @@ -9,8 +9,8 @@ qreal divideCardSpaceInZone(qreal index, int cardCount, qreal totalHeight, qreal cardHeight, bool reverse) { - qreal cardMinOverlap = cardHeight * SettingsCache::instance().getStackCardOverlapPercent() / 100; - qreal desiredHeight = cardHeight * cardCount - cardMinOverlap * (cardCount - 1); + const qreal cardMinOverlap = cardHeight * SettingsCache::instance().getStackCardOverlapPercent() / 100; + const qreal desiredHeight = cardHeight * cardCount - cardMinOverlap * (cardCount - 1); qreal y; if (desiredHeight > totalHeight) { if (reverse) { @@ -19,7 +19,7 @@ qreal divideCardSpaceInZone(qreal index, int cardCount, qreal totalHeight, qreal y = index * (totalHeight - cardHeight) / (cardCount - 1); } } else { - qreal start = (totalHeight - desiredHeight) / 2; + const qreal start = (totalHeight - desiredHeight) / 2; if (reverse) { if (index <= start) { return 0; @@ -42,7 +42,7 @@ void SelectZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event) QPointF pos = event->pos(); if (pos.x() < 0) pos.setX(0); - QRectF br = boundingRect(); + const QRectF br = boundingRect(); if (pos.x() > br.width()) pos.setX(br.width()); if (pos.y() < 0) @@ -50,13 +50,13 @@ void SelectZone::mouseMoveEvent(QGraphicsSceneMouseEvent *event) if (pos.y() > br.height()) pos.setY(br.height()); - QRectF selectionRect = QRectF(selectionOrigin, pos).normalized(); + const QRectF selectionRect = QRectF(selectionOrigin, pos).normalized(); for (auto card : getLogic()->getCards()) { if (card->getAttachedTo() && card->getAttachedTo()->getZone() != getLogic()) { continue; } - bool inRect = selectionRect.intersects(card->mapRectToParent(card->boundingRect())); + const bool inRect = selectionRect.intersects(card->mapRectToParent(card->boundingRect())); if (inRect && !cardsInSelectionRect.contains(card)) { // selection has just expanded to cover the card cardsInSelectionRect.insert(card); diff --git a/cockatrice/src/game/zones/stack_zone.cpp b/cockatrice/src/game/zones/stack_zone.cpp index 0c0501705..efce392f8 100644 --- a/cockatrice/src/game/zones/stack_zone.cpp +++ b/cockatrice/src/game/zones/stack_zone.cpp @@ -32,7 +32,7 @@ QRectF StackZone::boundingRect() const void StackZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Stack, getLogic()->getPlayer()->getZoneId()); + const QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Stack, getLogic()->getPlayer()->getZoneId()); painter->fillRect(boundingRect(), brush); } @@ -76,7 +76,7 @@ void StackZone::handleDropEvent(const QList &dragItems, cmd.set_x(index); cmd.set_y(0); - for (CardDragItem *item : dragItems) { + for (const CardDragItem *item : dragItems) { if (item) { cmd.mutable_cards_to_move()->add_card()->set_card_id(item->getId()); } @@ -89,17 +89,17 @@ void StackZone::reorganizeCards() { if (!getLogic()->getCards().isEmpty()) { const auto cardCount = static_cast(getLogic()->getCards().size()); - qreal totalWidth = boundingRect().width(); - qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width(); - qreal xspace = 5; - qreal x1 = xspace; - qreal x2 = totalWidth - xspace - cardWidth; + const qreal totalWidth = boundingRect().width(); + const qreal cardWidth = getLogic()->getCards().at(0)->boundingRect().width(); + const qreal xspace = 5; + const qreal x1 = xspace; + const qreal x2 = totalWidth - xspace - cardWidth; for (int i = 0; i < cardCount; i++) { CardItem *card = getLogic()->getCards().at(i); - qreal x = (i % 2) ? x2 : x1; - qreal y = divideCardSpaceInZone(i, cardCount, boundingRect().height(), - getLogic()->getCards().at(0)->boundingRect().height()); + const qreal x = (i % 2) ? x2 : x1; + const qreal y = divideCardSpaceInZone(i, cardCount, boundingRect().height(), + getLogic()->getCards().at(0)->boundingRect().height()); card->setPos(x, y); card->setRealZValue(i); } diff --git a/cockatrice/src/game/zones/table_zone.cpp b/cockatrice/src/game/zones/table_zone.cpp index 55aaeaa39..083f10dee 100644 --- a/cockatrice/src/game/zones/table_zone.cpp +++ b/cockatrice/src/game/zones/table_zone.cpp @@ -58,7 +58,7 @@ bool TableZone::isInverted() const void TableZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*option*/, QWidget * /*widget*/) { - QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Table, getLogic()->getPlayer()->getZoneId()); + const QBrush brush = themeManager->getExtraBgBrush(ThemeManager::Table, getLogic()->getPlayer()->getZoneId()); painter->fillRect(boundingRect(), brush); if (active) { @@ -157,11 +157,11 @@ void TableZone::reorganizeCards() continue; QPointF mapPoint = mapFromGrid(gridPoint); - qreal x = mapPoint.x(); - qreal y = mapPoint.y(); + const qreal x = mapPoint.x(); + const qreal y = mapPoint.y(); - int numberAttachedCards = getLogic()->getCards()[i]->getAttachedCards().size(); - qreal actualX = x + numberAttachedCards * STACKED_CARD_OFFSET_X; + const int numberAttachedCards = getLogic()->getCards()[i]->getAttachedCards().size(); + const qreal actualX = x + numberAttachedCards * STACKED_CARD_OFFSET_X; qreal actualY = y; if (numberAttachedCards) actualY += 15; @@ -174,8 +174,8 @@ void TableZone::reorganizeCards() while (attachedCardIterator.hasNext()) { ++j; CardItem *attachedCard = attachedCardIterator.next(); - qreal childX = actualX - j * STACKED_CARD_OFFSET_X; - qreal childY = y + 5; + const qreal childX = actualX - j * STACKED_CARD_OFFSET_X; + const qreal childY = y + 5; attachedCard->setPos(childX, childY); attachedCard->setRealZValue((childY + CARD_HEIGHT) * 100000 + (childX + 1) * 100); } @@ -191,7 +191,7 @@ void TableZone::toggleTapped() QList selectedItems; auto isCardOnTable = [](const QGraphicsItem *item) { - if (auto card = qgraphicsitem_cast(item)) { + if (const auto card = qgraphicsitem_cast(item)) { return card->getZone()->getName() == "table"; } return false; @@ -199,12 +199,12 @@ void TableZone::toggleTapped() std::copy_if(selectedItemsRaw.begin(), selectedItemsRaw.end(), std::back_inserter(selectedItems), isCardOnTable); - bool tapAll = std::any_of(selectedItems.begin(), selectedItems.end(), [](const QGraphicsItem *item) { + const bool tapAll = std::any_of(selectedItems.begin(), selectedItems.end(), [](const QGraphicsItem *item) { return !qgraphicsitem_cast(item)->getTapped(); }); QList cmdList; for (const auto &selectedItem : selectedItems) { - CardItem *temp = qgraphicsitem_cast(selectedItem); + const CardItem *temp = qgraphicsitem_cast(selectedItem); if (temp->getTapped() != tapAll) { Command_SetCardAttr *cmd = new Command_SetCardAttr; cmd->set_zone(getLogic()->getName().toStdString()); @@ -251,7 +251,7 @@ CardItem *TableZone::getCardFromGrid(const QPoint &gridPoint) const CardItem *TableZone::getCardFromCoords(const QPointF &point) const { - QPoint gridPoint = mapToGrid(point); + const QPoint gridPoint = mapToGrid(point); return getCardFromGrid(gridPoint); } @@ -318,7 +318,7 @@ QPoint TableZone::mapToGrid(const QPointF &mapPoint) const // used for the x-coordinate. // Offset point by the margin amount to reference point within grid area. - int y = mapPoint.y() - MARGIN_TOP; + const int y = mapPoint.y() - MARGIN_TOP; // Below calculation effectively rounds to the nearest grid point. const int gridPointHeight = CARD_HEIGHT + PADDING_Y; @@ -333,7 +333,7 @@ QPoint TableZone::mapToGrid(const QPointF &mapPoint) const // widths of each card stack along the row. // Offset point by the margin amount to reference point within grid area. - int x = mapPoint.x() - MARGIN_LEFT + PADDING_X / 2; + const int x = mapPoint.x() - MARGIN_LEFT + PADDING_X / 2; // Maximum value is a card width from the right margin, referenced to the // grid area. @@ -348,13 +348,13 @@ QPoint TableZone::mapToGrid(const QPointF &mapPoint) const xNextStack += cardStackWidth.value(key, CARD_WIDTH) + PADDING_X; nextStackCol++; } - int stackCol = qMax(nextStackCol - 1, 0); + const int stackCol = qMax(nextStackCol - 1, 0); // Have the stack column, need to refine to the grid column. Take the // difference between the point and the stack point and divide by stacked // card offsets. - int xDiff = x - xStack; - int gridPointX = stackCol * 3 + qMin(xDiff / STACKED_CARD_OFFSET_X, 2); + const int xDiff = x - xStack; + const int gridPointX = stackCol * 3 + qMin(xDiff / STACKED_CARD_OFFSET_X, 2); return QPoint(gridPointX, gridPointY); } diff --git a/cockatrice/src/game/zones/view_zone.cpp b/cockatrice/src/game/zones/view_zone.cpp index d5eea9dfe..2ed845064 100644 --- a/cockatrice/src/game/zones/view_zone.cpp +++ b/cockatrice/src/game/zones/view_zone.cpp @@ -68,10 +68,10 @@ void ZoneViewZone::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*o void ZoneViewZone::initializeCards(const QList &cardList) { - int numberCards = qobject_cast(getLogic())->getNumberCards(); + const int numberCards = qobject_cast(getLogic())->getNumberCards(); if (!cardList.isEmpty()) { for (int i = 0; i < cardList.size(); ++i) { - auto card = cardList[i]; + const auto card = cardList[i]; CardRef cardRef = {QString::fromStdString(card->name()), QString::fromStdString(card->provider_id())}; getLogic()->addCard(new CardItem(getLogic()->getPlayer(), this, cardRef, card->id()), false, i); } @@ -88,9 +88,9 @@ void ZoneViewZone::initializeCards(const QList &cardLis getLogic()->getPlayer()->getPlayerActions()->sendGameCommand(pend); } else { const CardList &c = qobject_cast(getLogic())->getOriginalZone()->getCards(); - int number = numberCards == -1 ? c.size() : (numberCards < c.size() ? numberCards : c.size()); + const int number = numberCards == -1 ? c.size() : (numberCards < c.size() ? numberCards : c.size()); for (int i = 0; i < number; i++) { - CardItem *card = c.at(i); + const CardItem *card = c.at(i); getLogic()->addCard(new CardItem(getLogic()->getPlayer(), this, card->getCardRef(), card->getId()), false, i); } @@ -104,9 +104,10 @@ void ZoneViewZone::zoneDumpReceived(const Response &r) const int respCardListSize = resp.zone_info().card_list_size(); for (int i = 0; i < respCardListSize; ++i) { const ServerInfo_Card &cardInfo = resp.zone_info().card_list(i); - auto cardName = QString::fromStdString(cardInfo.name()); - auto cardProviderId = QString::fromStdString(cardInfo.provider_id()); - auto card = new CardItem(getLogic()->getPlayer(), this, {cardName, cardProviderId}, cardInfo.id(), getLogic()); + const auto cardName = QString::fromStdString(cardInfo.name()); + const auto cardProviderId = QString::fromStdString(cardInfo.provider_id()); + const auto card = + new CardItem(getLogic()->getPlayer(), this, {cardName, cardProviderId}, cardInfo.id(), getLogic()); getLogic()->rawInsertCard(card, i); } @@ -120,7 +121,7 @@ void ZoneViewZone::reorganizeCards() { // filter cards CardList cardsToDisplay = CardList(getLogic()->getCards().getContentsKnown()); - for (auto card : getLogic()->getCards()) { + for (const auto card : getLogic()->getCards()) { if (filterString.check(card->getCard().getCardPtr())) { card->show(); cardsToDisplay.append(card); @@ -158,10 +159,10 @@ void ZoneViewZone::reorganizeCards() } // determine bounding rect - qreal aleft = 0; - qreal atop = 0; - qreal awidth = gridSize.cols * CARD_WIDTH + (CARD_WIDTH / 2) + HORIZONTAL_PADDING; - qreal aheight = (gridSize.rows * CARD_HEIGHT) / 3 + CARD_HEIGHT * 1.3; + const qreal aleft = 0; + const qreal atop = 0; + const qreal awidth = gridSize.cols * CARD_WIDTH + (CARD_WIDTH / 2) + HORIZONTAL_PADDING; + const qreal aheight = (gridSize.rows * CARD_HEIGHT) / 3 + CARD_HEIGHT * 1.3; optimumRect = QRectF(aleft, atop, awidth, aheight); updateGeometry(); @@ -179,7 +180,7 @@ void ZoneViewZone::reorganizeCards() */ ZoneViewZone::GridSize ZoneViewZone::positionCardsForDisplay(CardList &cards, CardList::SortOption pileOption) { - int cardCount = cards.size(); + const int cardCount = cards.size(); if (pileOption != CardList::NoSort) { int row = 0; @@ -204,8 +205,8 @@ ZoneViewZone::GridSize ZoneViewZone::positionCardsForDisplay(CardList &cards, Ca } lastColumnProp = columnProp; - qreal x = col * CARD_WIDTH; - qreal y = row * CARD_HEIGHT / 3; + const qreal x = col * CARD_WIDTH; + const qreal y = row * CARD_HEIGHT / 3; c->setPos(HORIZONTAL_PADDING + x, VERTICAL_PADDING + y); c->setRealZValue(i); longestRow = qMax(row, longestRow); @@ -232,8 +233,8 @@ ZoneViewZone::GridSize ZoneViewZone::positionCardsForDisplay(CardList &cards, Ca for (int i = 0; i < cardCount; i++) { CardItem *c = cards.at(i); - qreal x = (i / rows) * CARD_WIDTH; - qreal y = (i % rows) * CARD_HEIGHT / 3; + const qreal x = (i / rows) * CARD_WIDTH; + const qreal y = (i % rows) * CARD_HEIGHT / 3; c->setPos(HORIZONTAL_PADDING + x, VERTICAL_PADDING + y); c->setRealZValue(i); } diff --git a/cockatrice/src/game/zones/view_zone_widget.cpp b/cockatrice/src/game/zones/view_zone_widget.cpp index e2f242883..e90550ef4 100644 --- a/cockatrice/src/game/zones/view_zone_widget.cpp +++ b/cockatrice/src/game/zones/view_zone_widget.cpp @@ -52,7 +52,7 @@ ZoneViewWidget::ZoneViewWidget(Player *_player, searchEdit.setPlaceholderText(tr("Search by card name (or search expressions)")); searchEdit.setClearButtonEnabled(true); searchEdit.addAction(loadColorAdjustedPixmap("theme:icons/search"), QLineEdit::LeadingPosition); - auto help = searchEdit.addAction(QPixmap("theme:icons/info"), QLineEdit::TrailingPosition); + const auto help = searchEdit.addAction(QPixmap("theme:icons/info"), QLineEdit::TrailingPosition); connect(help, &QAction::triggered, this, [this] { createSearchSyntaxHelpWindow(&searchEdit); }); @@ -175,7 +175,7 @@ ZoneViewWidget::ZoneViewWidget(Player *_player, void ZoneViewWidget::processGroupBy(int index) { - auto option = static_cast(groupBySelector.itemData(index).toInt()); + const auto option = static_cast(groupBySelector.itemData(index).toInt()); SettingsCache::instance().setZoneViewGroupByIndex(index); zone->setGroupBy(option); @@ -191,7 +191,7 @@ void ZoneViewWidget::processGroupBy(int index) void ZoneViewWidget::processSortBy(int index) { - auto option = static_cast(sortBySelector.itemData(index).toInt()); + const auto option = static_cast(sortBySelector.itemData(index).toInt()); // set to SortByName instead if it has the same value as groupBy if (option != CardList::NoSort && @@ -215,7 +215,7 @@ void ZoneViewWidget::retranslateUi() setWindowTitle(zone->getLogic()->getTranslatedName(false, CaseNominative)); { // We can't change the strings after they're put into the QComboBox, so this is our workaround - int oldIndex = groupBySelector.currentIndex(); + const int oldIndex = groupBySelector.currentIndex(); groupBySelector.clear(); groupBySelector.addItem(tr("Ungrouped"), CardList::NoSort); groupBySelector.addItem(tr("Group by Type"), CardList::SortByMainType); @@ -225,7 +225,7 @@ void ZoneViewWidget::retranslateUi() } { - int oldIndex = sortBySelector.currentIndex(); + const int oldIndex = sortBySelector.currentIndex(); sortBySelector.clear(); sortBySelector.addItem(tr("Unsorted"), CardList::NoSort); sortBySelector.addItem(tr("Sort by Name"), CardList::SortByName); @@ -246,14 +246,14 @@ void ZoneViewWidget::moveEvent(QGraphicsSceneMoveEvent * /* event */) if (!scene()) return; - int titleBarHeight = 24; + const int titleBarHeight = 24; QPointF scenePos = pos(); if (scenePos.x() < 0) { scenePos.setX(0); } else { - qreal maxw = scene()->sceneRect().width() - 100; + const qreal maxw = scene()->sceneRect().width() - 100; if (scenePos.x() > maxw) scenePos.setX(maxw); } @@ -261,7 +261,7 @@ void ZoneViewWidget::moveEvent(QGraphicsSceneMoveEvent * /* event */) if (scenePos.y() < titleBarHeight) { scenePos.setY(titleBarHeight); } else { - qreal maxh = scene()->sceneRect().height() - titleBarHeight; + const qreal maxh = scene()->sceneRect().height() - titleBarHeight; if (scenePos.y() > maxh) scenePos.setY(maxh); } @@ -278,8 +278,8 @@ void ZoneViewWidget::resizeEvent(QGraphicsSceneResizeEvent *event) void ZoneViewWidget::resizeScrollbar(const qreal newZoneHeight) { - qreal totalZoneHeight = zone->getOptimumRect().height(); - qreal newMax = qMax(totalZoneHeight - newZoneHeight, 0.0); + const qreal totalZoneHeight = zone->getOptimumRect().height(); + const qreal newMax = qMax(totalZoneHeight - newZoneHeight, 0.0); scrollBar->setMaximum(newMax); } @@ -320,18 +320,18 @@ static qreal determineNewZoneHeight(qreal oldZoneHeight) void ZoneViewWidget::resizeToZoneContents(bool forceInitialHeight) { - QRectF zoneRect = zone->getOptimumRect(); - qreal totalZoneHeight = zoneRect.height(); + const QRectF zoneRect = zone->getOptimumRect(); + const qreal totalZoneHeight = zoneRect.height(); - qreal width = qMax(QGraphicsWidget::layout()->effectiveSizeHint(Qt::MinimumSize, QSizeF()).width(), - zoneRect.width() + scrollBar->width() + 10); + const qreal width = qMax(QGraphicsWidget::layout()->effectiveSizeHint(Qt::MinimumSize, QSizeF()).width(), + zoneRect.width() + scrollBar->width() + 10); - QSizeF maxSize(width, zoneRect.height() + extraHeight + 10); + const QSizeF maxSize(width, zoneRect.height() + extraHeight + 10); - qreal currentZoneHeight = rect().height() - extraHeight - 10; - qreal newZoneHeight = forceInitialHeight ? calcMaxInitialHeight() : determineNewZoneHeight(currentZoneHeight); + const qreal currentZoneHeight = rect().height() - extraHeight - 10; + const qreal newZoneHeight = forceInitialHeight ? calcMaxInitialHeight() : determineNewZoneHeight(currentZoneHeight); - QSizeF initialSize(width, newZoneHeight + extraHeight + 10); + const QSizeF initialSize(width, newZoneHeight + extraHeight + 10); setMaximumSize(maxSize); resize(initialSize); @@ -378,13 +378,13 @@ void ZoneViewWidget::initStyleOption(QStyleOption *option) const */ void ZoneViewWidget::expandWindow() { - qreal maxInitialHeight = calcMaxInitialHeight(); - qreal maxExpandedHeight = rowsToHeight(SettingsCache::instance().getCardViewExpandedRowsMax()); - qreal height = rect().height() - extraHeight - 10; - qreal maxHeight = maximumHeight() - extraHeight - 10; + const qreal maxInitialHeight = calcMaxInitialHeight(); + const qreal maxExpandedHeight = rowsToHeight(SettingsCache::instance().getCardViewExpandedRowsMax()); + const qreal height = rect().height() - extraHeight - 10; + const qreal maxHeight = maximumHeight() - extraHeight - 10; // reset window to initial max height if... - bool doResetSize = + const bool doResetSize = // current height is less than that (height < maxInitialHeight) || // current height is at expanded max height diff --git a/cockatrice/src/game_graphics/board/abstract_graphics_item.cpp b/cockatrice/src/game_graphics/board/abstract_graphics_item.cpp index 8ced8d5bc..7e2d65684 100644 --- a/cockatrice/src/game_graphics/board/abstract_graphics_item.cpp +++ b/cockatrice/src/game_graphics/board/abstract_graphics_item.cpp @@ -23,7 +23,7 @@ void AbstractGraphicsItem::paintNumberEllipse(int number, #else fm.width(numStr); #endif - double h = fm.height() * 1.3; + const double h = fm.height() * 1.3; if (w < h) w = h; @@ -34,9 +34,9 @@ void AbstractGraphicsItem::paintNumberEllipse(int number, if (position == -1) textRect = QRectF((boundingRect().width() - w) / 2.0, (boundingRect().height() - h) / 2.0, w, h); else { - qreal xOffset = 10; - qreal yOffset = 20; - qreal spacing = 2; + const qreal xOffset = 10; + const qreal yOffset = 20; + const qreal spacing = 2; if (position < 2) textRect = QRectF(count == 1 ? ((boundingRect().width() - w) / 2.0) : (position % 2 == 0 ? xOffset : (boundingRect().width() - xOffset - w)), @@ -59,7 +59,7 @@ void AbstractGraphicsItem::paintNumberEllipse(int number, int resetPainterTransform(QPainter *painter) { painter->resetTransform(); - auto tx = painter->deviceTransform().inverted(); + const auto tx = painter->deviceTransform().inverted(); painter->setTransform(tx); return tx.isScaling() ? 1.0 / tx.m11() : 1; } diff --git a/cockatrice/src/interface/card_picture_loader/card_picture_loader.cpp b/cockatrice/src/interface/card_picture_loader/card_picture_loader.cpp index 296355940..46c909b33 100644 --- a/cockatrice/src/interface/card_picture_loader/card_picture_loader.cpp +++ b/cockatrice/src/interface/card_picture_loader/card_picture_loader.cpp @@ -32,7 +32,7 @@ CardPictureLoader::CardPictureLoader() : QObject(nullptr) connect(worker, &CardPictureLoaderWorker::imageLoaded, this, &CardPictureLoader::imageLoaded); statusBar = new CardPictureLoaderStatusBar(nullptr); - QMainWindow *mainWindow = qobject_cast(QApplication::activeWindow()); + const QMainWindow *mainWindow = qobject_cast(QApplication::activeWindow()); if (mainWindow) { mainWindow->statusBar()->addPermanentWidget(statusBar); } @@ -50,7 +50,8 @@ CardPictureLoader::~CardPictureLoader() void CardPictureLoader::getCardBackPixmap(QPixmap &pixmap, QSize size) { - QString backCacheKey = "_trice_card_back_" + QString::number(size.width()) + "x" + QString::number(size.height()); + const QString backCacheKey = + "_trice_card_back_" + QString::number(size.width()) + "x" + QString::number(size.height()); if (!QPixmapCache::find(backCacheKey, &pixmap)) { qCDebug(CardPictureLoaderLog) << "PictureLoader: cache miss for" << backCacheKey; QPixmap tmpPixmap("theme:cardback"); @@ -70,7 +71,7 @@ void CardPictureLoader::getCardBackPixmap(QPixmap &pixmap, QSize size) void CardPictureLoader::getCardBackLoadingInProgressPixmap(QPixmap &pixmap, QSize size) { - QString backCacheKey = + const QString backCacheKey = "_trice_card_back_inprogress_" + QString::number(size.width()) + "x" + QString::number(size.height()); if (!QPixmapCache::find(backCacheKey, &pixmap)) { qCDebug(CardPictureLoaderCardBackCacheFailLog) << "PictureLoader: cache miss for" << backCacheKey; @@ -92,7 +93,7 @@ void CardPictureLoader::getCardBackLoadingInProgressPixmap(QPixmap &pixmap, QSiz void CardPictureLoader::getCardBackLoadingFailedPixmap(QPixmap &pixmap, QSize size) { - QString backCacheKey = + const QString backCacheKey = "_trice_card_back_failed_" + QString::number(size.width()) + "x" + QString::number(size.height()); if (!QPixmapCache::find(backCacheKey, &pixmap)) { qCDebug(CardPictureLoaderCardBackCacheFailLog) << "PictureLoader: cache miss for" << backCacheKey; @@ -118,8 +119,9 @@ void CardPictureLoader::getPixmap(QPixmap &pixmap, const ExactCard &card, QSize return; } - QString key = card.getPixmapCacheKey(); - QString sizeKey = key + QLatin1Char('_') + QString::number(size.width()) + "x" + QString::number(size.height()); + const QString key = card.getPixmapCacheKey(); + const QString sizeKey = + key + QLatin1Char('_') + QString::number(size.width()) + "x" + QString::number(size.height()); if (QPixmapCache::find(sizeKey, &pixmap)) { return; // Use cached version @@ -133,8 +135,8 @@ void CardPictureLoader::getPixmap(QPixmap &pixmap, const ExactCard &card, QSize return; } - QScreen *screen = qApp->primaryScreen(); - qreal dpr = screen ? screen->devicePixelRatio() : 1.0; + const QScreen *screen = qApp->primaryScreen(); + const qreal dpr = screen ? screen->devicePixelRatio() : 1.0; qCDebug(CardPictureLoaderLog) << "Scaling cached image for" << card.getName(); pixmap = bigPixmap.scaled(size * dpr, Qt::KeepAspectRatio, Qt::SmoothTransformation); @@ -156,7 +158,7 @@ void CardPictureLoader::imageLoaded(const ExactCard &card, const QImage &image) } else { if (card.getInfo().getUiAttributes().upsideDownArt) { #if (QT_VERSION >= QT_VERSION_CHECK(6, 9, 0)) - QImage mirrorImage = image.flipped(Qt::Horizontal | Qt::Vertical); + const QImage mirrorImage = image.flipped(Qt::Horizontal | Qt::Vertical); #else QImage mirrorImage = image.mirrored(true, true); #endif @@ -188,7 +190,7 @@ void CardPictureLoader::clearNetworkCache() void CardPictureLoader::cacheCardPixmaps(const QList &cards) { QPixmap tmp; - int max = qMin(cards.size(), CACHED_CARD_PER_DECK_MAX); + const int max = qMin(cards.size(), CACHED_CARD_PER_DECK_MAX); for (int i = 0; i < max; ++i) { const ExactCard &card = cards.at(i); if (!card) { @@ -216,7 +218,7 @@ void CardPictureLoader::picsPathChanged() bool CardPictureLoader::hasCustomArt() { - auto picsPath = SettingsCache::instance().getPicsPath(); + const auto picsPath = SettingsCache::instance().getPicsPath(); QDirIterator it(picsPath, QDir::Dirs | QDir::NoDotAndDotDot); // Check if there is at least one non-directory file in the pics path, other diff --git a/cockatrice/src/interface/card_picture_loader/card_picture_loader_local.cpp b/cockatrice/src/interface/card_picture_loader/card_picture_loader_local.cpp index dd00e6e1d..a8e78d955 100644 --- a/cockatrice/src/interface/card_picture_loader/card_picture_loader_local.cpp +++ b/cockatrice/src/interface/card_picture_loader/card_picture_loader_local.cpp @@ -49,10 +49,10 @@ void CardPictureLoaderLocal::refreshIndex() QImage CardPictureLoaderLocal::tryLoad(const ExactCard &toLoad) const { - PrintingInfo setInstance = toLoad.getPrinting(); + const PrintingInfo setInstance = toLoad.getPrinting(); - QString cardName = toLoad.getName(); - QString correctedCardName = toLoad.getInfo().getCorrectedName(); + const QString cardName = toLoad.getName(); + const QString correctedCardName = toLoad.getInfo().getCorrectedName(); QString setName, collectorNumber, providerId; diff --git a/cockatrice/src/interface/card_picture_loader/card_picture_loader_request_status_display_widget.h b/cockatrice/src/interface/card_picture_loader/card_picture_loader_request_status_display_widget.h index 2e3233c2d..e9921a3c1 100644 --- a/cockatrice/src/interface/card_picture_loader/card_picture_loader_request_status_display_widget.h +++ b/cockatrice/src/interface/card_picture_loader/card_picture_loader_request_status_display_widget.h @@ -64,7 +64,7 @@ public: int queryElapsedSeconds() { if (!getFinished()) { - int elapsedSeconds = QDateTime::fromString(startTime->text()).secsTo(QDateTime::currentDateTime()); + const int elapsedSeconds = QDateTime::fromString(startTime->text()).secsTo(QDateTime::currentDateTime()); elapsedTime->setText(QString::number(elapsedSeconds)); update(); repaint(); diff --git a/cockatrice/src/interface/card_picture_loader/card_picture_loader_worker.cpp b/cockatrice/src/interface/card_picture_loader/card_picture_loader_worker.cpp index a2da3c953..c90436917 100644 --- a/cockatrice/src/interface/card_picture_loader/card_picture_loader_worker.cpp +++ b/cockatrice/src/interface/card_picture_loader/card_picture_loader_worker.cpp @@ -64,7 +64,7 @@ CardPictureLoaderWorker::~CardPictureLoaderWorker() void CardPictureLoaderWorker::queueRequest(const QUrl &url, CardPictureLoaderWorkerWork *worker) { - QUrl cachedRedirect = getCachedRedirect(url); + const QUrl cachedRedirect = getCachedRedirect(url); if (!cachedRedirect.isEmpty()) { queueRequest(cachedRedirect, worker); } else if (cache->metaData(url).isValid()) { @@ -80,7 +80,7 @@ void CardPictureLoaderWorker::queueRequest(const QUrl &url, CardPictureLoaderWor QNetworkReply *CardPictureLoaderWorker::makeRequest(const QUrl &url, CardPictureLoaderWorkerWork *worker) { // Check for cached redirects - QUrl cachedRedirect = getCachedRedirect(url); + const QUrl cachedRedirect = getCachedRedirect(url); if (!cachedRedirect.isEmpty()) { emit imageRequestSucceeded(url); return makeRequest(cachedRedirect, worker); @@ -115,7 +115,7 @@ void CardPictureLoaderWorker::processQueuedRequests() bool CardPictureLoaderWorker::processSingleRequest() { if (!requestLoadQueue.isEmpty()) { - auto request = requestLoadQueue.takeFirst(); + const auto request = requestLoadQueue.takeFirst(); makeRequest(request.first, request.second); return true; } @@ -139,7 +139,7 @@ void CardPictureLoaderWorker::handleImageLoadEnqueued(const ExactCard &card) currentlyLoading.insert(card.getPixmapCacheKey()); // try to load image from local first - QImage image = localLoader->tryLoad(card); + const QImage image = localLoader->tryLoad(card); if (!image.isNull()) { handleImageLoaded(card, image); } else { @@ -181,7 +181,7 @@ void CardPictureLoaderWorker::loadRedirectCache() QSettings settings(cacheFilePath, QSettings::IniFormat); redirectCache.clear(); - int size = settings.beginReadArray(REDIRECT_HEADER_NAME); + const int size = settings.beginReadArray(REDIRECT_HEADER_NAME); for (int i = 0; i < size; ++i) { settings.setArrayIndex(i); QUrl originalUrl = settings.value(REDIRECT_ORIGINAL_URL).toUrl(); @@ -212,7 +212,7 @@ void CardPictureLoaderWorker::saveRedirectCache() const void CardPictureLoaderWorker::cleanStaleEntries() { - QDateTime now = QDateTime::currentDateTimeUtc(); + const QDateTime now = QDateTime::currentDateTimeUtc(); auto it = redirectCache.begin(); while (it != redirectCache.end()) { diff --git a/cockatrice/src/interface/card_picture_loader/card_picture_loader_worker_work.cpp b/cockatrice/src/interface/card_picture_loader/card_picture_loader_worker_work.cpp index e74103419..d239e7d25 100644 --- a/cockatrice/src/interface/card_picture_loader/card_picture_loader_worker_work.cpp +++ b/cockatrice/src/interface/card_picture_loader/card_picture_loader_worker_work.cpp @@ -37,12 +37,12 @@ CardPictureLoaderWorkerWork::CardPictureLoaderWorkerWork(const CardPictureLoader void CardPictureLoaderWorkerWork::startNextPicDownload() { - QString picUrl = cardToDownload.getCurrentUrl(); + const QString picUrl = cardToDownload.getCurrentUrl(); if (picUrl.isEmpty()) { picDownloadFailed(); } else { - QUrl url(picUrl); + const QUrl url(picUrl); qCDebug(CardPictureLoaderWorkerWorkLog).nospace() << "PictureLoader: [card: " << cardToDownload.getCard().getInfo().getCorrectedName() << " set: " << cardToDownload.getSetName() << "]: Trying to fetch picture from url " @@ -71,9 +71,9 @@ void CardPictureLoaderWorkerWork::picDownloadFailed() void CardPictureLoaderWorkerWork::handleNetworkReply(QNetworkReply *reply) { - QVariant redirectTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); + const QVariant redirectTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute); if (redirectTarget.isValid()) { - QUrl url = reply->request().url(); + const QUrl url = reply->request().url(); QUrl redirectUrl = redirectTarget.toUrl(); if (redirectUrl.isRelative()) { redirectUrl = url.resolved(redirectUrl); @@ -93,7 +93,7 @@ void CardPictureLoaderWorkerWork::handleNetworkReply(QNetworkReply *reply) static bool imageIsBlackListed(const QByteArray &picData) { - QString md5sum = QCryptographicHash::hash(picData, QCryptographicHash::Md5).toHex(); + const QString md5sum = QCryptographicHash::hash(picData, QCryptographicHash::Md5).toHex(); return MD5_BLACKLIST.contains(md5sum); } @@ -102,7 +102,7 @@ void CardPictureLoaderWorkerWork::handleFailedReply(const QNetworkReply *reply) if (reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt() == 429) { qCWarning(CardPictureLoaderWorkerWorkLog) << "Too many requests."; } else { - bool isFromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); + const bool isFromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); if (isFromCache) { qCDebug(CardPictureLoaderWorkerWorkLog).nospace() @@ -126,13 +126,13 @@ void CardPictureLoaderWorkerWork::handleFailedReply(const QNetworkReply *reply) void CardPictureLoaderWorkerWork::handleSuccessfulReply(QNetworkReply *reply) { - bool isFromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); + const bool isFromCache = reply->attribute(QNetworkRequest::SourceIsFromCacheAttribute).toBool(); // List of status codes from https://doc.qt.io/qt-6/qnetworkreply.html#redirected - int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + const int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (statusCode == 301 || statusCode == 302 || statusCode == 303 || statusCode == 305 || statusCode == 307 || statusCode == 308) { - QUrl redirectUrl = reply->header(QNetworkRequest::LocationHeader).toUrl(); + const QUrl redirectUrl = reply->header(QNetworkRequest::LocationHeader).toUrl(); qCDebug(CardPictureLoaderWorkerWorkLog).nospace() << "PictureLoader: [card: " << cardToDownload.getCard().getName() << " set: " << cardToDownload.getSetName() << "]: following " << (isFromCache ? "cached redirect" : "redirect") << " to " @@ -153,7 +153,7 @@ void CardPictureLoaderWorkerWork::handleSuccessfulReply(QNetworkReply *reply) return; } - QImage image = tryLoadImageFromReply(reply); + const QImage image = tryLoadImageFromReply(reply); if (image.isNull()) { qCDebug(CardPictureLoaderWorkerWorkLog).nospace() @@ -175,7 +175,7 @@ void CardPictureLoaderWorkerWork::handleSuccessfulReply(QNetworkReply *reply) QImage CardPictureLoaderWorkerWork::tryLoadImageFromReply(QNetworkReply *reply) { static constexpr int riffHeaderSize = 12; // RIFF_HEADER_SIZE from webp/format_constants.h - auto replyHeader = reply->peek(riffHeaderSize); + const auto replyHeader = reply->peek(riffHeaderSize); if (replyHeader.startsWith("RIFF") && replyHeader.endsWith("WEBP")) { auto imgBuf = QBuffer(this); diff --git a/cockatrice/src/interface/card_picture_loader/card_picture_to_load.cpp b/cockatrice/src/interface/card_picture_loader/card_picture_to_load.cpp index d72226aab..7a1651e5d 100644 --- a/cockatrice/src/interface/card_picture_loader/card_picture_to_load.cpp +++ b/cockatrice/src/interface/card_picture_loader/card_picture_to_load.cpp @@ -36,9 +36,9 @@ QList CardPictureToLoad::extractSetsSorted(const ExactCard &card) // If the user hasn't disabled arts other than their personal preference... if (!SettingsCache::instance().getOverrideAllCardArtWithPersonalPreference()) { // If the pixmapCacheKey corresponds to a specific set, we have to try to load it first. - qsizetype setIndex = sortedSets.indexOf(card.getPrinting().getSet()); + const qsizetype setIndex = sortedSets.indexOf(card.getPrinting().getSet()); if (setIndex > 0) { // we don't need to move the set if it's already first - CardSetPtr setForCardProviderID = sortedSets.takeAt(setIndex); + const CardSetPtr setForCardProviderID = sortedSets.takeAt(setIndex); sortedSets.prepend(setForCardProviderID); } } @@ -83,7 +83,7 @@ void CardPictureToLoad::populateSetUrls() currentSetUrls.clear(); if (card && currentSet) { - QString setCustomURL = findPrintingForSet(card, currentSet->getShortName()).getProperty("picurl"); + const QString setCustomURL = findPrintingForSet(card, currentSet->getShortName()).getProperty("picurl"); if (!setCustomURL.isEmpty()) { currentSetUrls.append(setCustomURL); @@ -191,7 +191,7 @@ static int parse(const QString &urlTemplate, } if (!fillWith.isEmpty()) { - int fillLength = fillWith.length(); + const int fillLength = fillWith.length(); if (fillLength < propLength) { qCDebug(CardPictureToLoadLog).nospace() << "PictureLoader: [card: " << cardName << " set: " << setName << "]: Requested " << propType @@ -217,13 +217,13 @@ QString CardPictureToLoad::transformUrl(const QString &urlTemplate) const for downloading images. If information is requested by the template that is not populated for this specific card/set combination, an empty string is returned.*/ - CardSetPtr set = getCurrentSet(); + const CardSetPtr set = getCurrentSet(); QMap transformMap = QMap(); - QString setName = getSetName(); + const QString setName = getSetName(); // name - QString cardName = card.getName(); + const QString cardName = card.getName(); transformMap["!name!"] = cardName; transformMap["!name_lower!"] = card.getName().toLower(); transformMap["!corrected_name!"] = card.getInfo().getCorrectedName(); diff --git a/cockatrice/src/interface/deck_loader/deck_loader.cpp b/cockatrice/src/interface/deck_loader/deck_loader.cpp index 372aa0aa8..64079db2e 100644 --- a/cockatrice/src/interface/deck_loader/deck_loader.cpp +++ b/cockatrice/src/interface/deck_loader/deck_loader.cpp @@ -99,7 +99,7 @@ bool DeckLoader::loadFromFileAsync(const QString &fileName, FileFormat fmt, bool emit loadFinished(result); }); - QFuture future = QtConcurrent::run([=, this]() { + const QFuture future = QtConcurrent::run([=, this]() { QFile file(fileName); if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { return false; @@ -129,7 +129,7 @@ bool DeckLoader::loadFromFileAsync(const QString &fileName, FileFormat fmt, bool bool DeckLoader::loadFromRemote(const QString &nativeString, int remoteDeckId) { - bool result = deckList->loadFromString_Native(nativeString); + const bool result = deckList->loadFromString_Native(nativeString); if (result) { lastLoadInfo = { .remoteDeckId = remoteDeckId, @@ -174,13 +174,13 @@ bool DeckLoader::saveToFile(const QString &fileName, FileFormat fmt) bool DeckLoader::updateLastLoadedTimestamp(const QString &fileName, FileFormat fmt) { - QFileInfo fileInfo(fileName); + const QFileInfo fileInfo(fileName); if (!fileInfo.exists()) { qCWarning(DeckLoaderLog) << "File does not exist:" << fileName; return false; } - QDateTime originalTimestamp = fileInfo.lastModified(); + const QDateTime originalTimestamp = fileInfo.lastModified(); // Open the file for writing QFile file(fileName); @@ -285,7 +285,7 @@ QString DeckLoader::exportDeckToDecklist(const DeckList *deckList, DecklistWebsi // Set up the function to call auto formatDeckListForExport = [&mainBoardCards, &sideBoardCards](const auto *node, const auto *card) { // Get the card name - CardInfoPtr dbCard = CardDatabaseManager::query()->getCardInfo(card->getName()); + const CardInfoPtr dbCard = CardDatabaseManager::query()->getCardInfo(card->getName()); if (!dbCard || dbCard->getIsToken()) { // If it's a token, we don't care about the card. return; @@ -328,10 +328,10 @@ struct SetProviderIdToPreferred void operator()(const InnerDecklistNode *node, DecklistCardNode *card) const { Q_UNUSED(node); - PrintingInfo preferredPrinting = CardDatabaseManager::query()->getPreferredPrinting(card->getName()); - QString providerId = preferredPrinting.getUuid(); - QString setShortName = preferredPrinting.getSet()->getShortName(); - QString collectorNumber = preferredPrinting.getProperty("num"); + const PrintingInfo preferredPrinting = CardDatabaseManager::query()->getPreferredPrinting(card->getName()); + const QString providerId = preferredPrinting.getUuid(); + const QString setShortName = preferredPrinting.getSet()->getShortName(); + const QString collectorNumber = preferredPrinting.getProperty("num"); card->setCardProviderId(providerId); card->setCardCollectorNumber(collectorNumber); @@ -481,7 +481,7 @@ void DeckLoader::saveToStream_DeckZone(QTextStream &out, for (int j = 0; j < zoneNode->size(); j++) { auto *card = dynamic_cast(zoneNode->at(j)); - CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(card->getName()); + const CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(card->getName()); QString cardType = info ? info->getMainCardType() : "unknown"; cardsByType.insert(cardType, card); @@ -505,7 +505,7 @@ void DeckLoader::saveToStream_DeckZone(QTextStream &out, out << "// " << cardTotalByType[cardType] << " " << cardType << "\n"; } - QList cards = cardsByType.values(cardType); + const QList cards = cardsByType.values(cardType); saveToStream_DeckZoneCards(out, zoneNode, cards, addComments, addSetNameAndNumber); @@ -523,7 +523,7 @@ void DeckLoader::saveToStream_DeckZoneCards(QTextStream &out, { // QMultiMap sorts values in reverse order for (int i = cards.size() - 1; i >= 0; --i) { - DecklistCardNode *card = cards[i]; + const DecklistCardNode *card = cards[i]; if (zoneNode->getName() == DECK_ZONE_SIDE && addComments) { out << "SB: "; @@ -551,8 +551,8 @@ void DeckLoader::saveToStream_DeckZoneCards(QTextStream &out, bool DeckLoader::convertToCockatriceFormat(QString fileName) { // Change the file extension to .cod - QFileInfo fileInfo(fileName); - QString newFileName = QDir::toNativeSeparators(fileInfo.path() + "/" + fileInfo.completeBaseName() + ".cod"); + const QFileInfo fileInfo(fileName); + const QString newFileName = QDir::toNativeSeparators(fileInfo.path() + "/" + fileInfo.completeBaseName() + ".cod"); // Open the new file for writing QFile file(newFileName); @@ -599,7 +599,7 @@ bool DeckLoader::convertToCockatriceFormat(QString fileName) QString DeckLoader::getCardZoneFromName(const QString &cardName, QString currentZoneName) { - CardInfoPtr card = CardDatabaseManager::query()->getCardInfo(cardName); + const CardInfoPtr card = CardDatabaseManager::query()->getCardInfo(cardName); if (card && card->getIsToken()) { return DECK_ZONE_TOKENS; @@ -611,7 +611,7 @@ QString DeckLoader::getCardZoneFromName(const QString &cardName, QString current QString DeckLoader::getCompleteCardName(const QString &cardName) { if (CardDatabaseManager::getInstance()) { - ExactCard temp = CardDatabaseManager::query()->guessCard({cardName}); + const ExactCard temp = CardDatabaseManager::query()->guessCard({cardName}); if (temp) { return temp.getName(); } @@ -625,7 +625,7 @@ void DeckLoader::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node) const int totalColumns = 2; if (node->height() == 1) { - QTextBlockFormat blockFormat; + const QTextBlockFormat blockFormat; QTextCharFormat charFormat; charFormat.setFontPointSize(11); charFormat.setFontWeight(QFont::Bold); @@ -635,9 +635,9 @@ void DeckLoader::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node) tableFormat.setCellPadding(0); tableFormat.setCellSpacing(0); tableFormat.setBorder(0); - QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat); + const QTextTable *table = cursor->insertTable(node->size() + 1, totalColumns, tableFormat); for (int i = 0; i < node->size(); i++) { - auto *card = dynamic_cast(node->at(i)); + const auto *card = dynamic_cast(node->at(i)); QTextCharFormat cellCharFormat; cellCharFormat.setFontPointSize(9); @@ -653,7 +653,7 @@ void DeckLoader::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node) cellCursor.insertText(card->getName()); } } else if (node->height() == 2) { - QTextBlockFormat blockFormat; + const QTextBlockFormat blockFormat; QTextCharFormat charFormat; charFormat.setFontPointSize(14); charFormat.setFontWeight(QFont::Bold); @@ -670,7 +670,7 @@ void DeckLoader::printDeckListNode(QTextCursor *cursor, InnerDecklistNode *node) } tableFormat.setColumnWidthConstraints(constraints); - QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat); + const QTextTable *table = cursor->insertTable(1, totalColumns, tableFormat); for (int i = 0; i < node->size(); i++) { QTextCursor cellCursor = table->cellAt(0, (i * totalColumns) / node->size()).lastCursorPosition(); printDeckListNode(&cellCursor, dynamic_cast(node->at(i))); @@ -690,7 +690,7 @@ void DeckLoader::printDeckList(QPrinter *printer, const DeckList *deckList) QTextCursor cursor(&doc); - QTextBlockFormat headerBlockFormat; + const QTextBlockFormat headerBlockFormat; QTextCharFormat headerCharFormat; headerCharFormat.setFontPointSize(16); headerCharFormat.setFontWeight(QFont::Bold); diff --git a/cockatrice/src/interface/layouts/flow_layout.cpp b/cockatrice/src/interface/layouts/flow_layout.cpp index f7ebbfb79..cee8ac2b6 100644 --- a/cockatrice/src/interface/layouts/flow_layout.cpp +++ b/cockatrice/src/interface/layouts/flow_layout.cpp @@ -76,7 +76,7 @@ int FlowLayout::heightForWidth(const int width) const continue; } - int itemWidth = item->sizeHint().width() + horizontalSpacing(); + const int itemWidth = item->sizeHint().width() + horizontalSpacing(); if (rowWidth + itemWidth > width) { height += rowHeight + verticalSpacing(); rowWidth = itemWidth; @@ -98,7 +98,7 @@ int FlowLayout::heightForWidth(const int width) const continue; } - int itemHeight = item->sizeHint().height(); + const int itemHeight = item->sizeHint().height(); if (colHeight + itemHeight > width) { width += colWidth; colHeight = itemHeight; @@ -163,7 +163,7 @@ int FlowLayout::layoutAllRows(const int originX, const int originY, const int av } QSize itemSize = item->sizeHint(); // The suggested size for the current item - int itemWidth = itemSize.width() + horizontalSpacing(); // Item width plus spacing + const int itemWidth = itemSize.width() + horizontalSpacing(); // Item width plus spacing // Check if the current item fits in the remaining width of the current row if (currentXPosition + itemWidth > availableWidth) { @@ -279,7 +279,7 @@ void FlowLayout::layoutSingleColumn(const QVector &colItems, cons } // Debugging: Print the item's widget class name and size hint - QWidget *widget = item->widget(); + const QWidget *widget = item->widget(); if (widget) { qCDebug(FlowLayoutLog) << "Widget class:" << widget->metaObject()->className(); qCDebug(FlowLayoutLog) << "Widget size hint:" << widget->sizeHint(); @@ -290,7 +290,7 @@ void FlowLayout::layoutSingleColumn(const QVector &colItems, cons const QObjectList &children = widget->children(); qCDebug(FlowLayoutLog) << "Child widgets:"; for (QObject *child : children) { - if (QWidget *childWidget = qobject_cast(child)) { + if (const QWidget *childWidget = qobject_cast(child)) { qCDebug(FlowLayoutLog) << " - Child widget class:" << childWidget->metaObject()->className(); qCDebug(FlowLayoutLog) << " Size hint:" << childWidget->sizeHint(); qCDebug(FlowLayoutLog) << " Maximum size:" << childWidget->maximumSize(); @@ -365,7 +365,7 @@ QSize FlowLayout::calculateSizeHintHorizontal() const } QSize itemSize = item->sizeHint(); - int itemWidth = itemSize.width() + horizontalSpacing(); + const int itemWidth = itemSize.width() + horizontalSpacing(); qCDebug(FlowLayoutLog) << "Processing item. Size:" << itemSize << "Width with spacing:" << itemWidth; if (currentWidth + itemWidth > availableWidth) { @@ -413,7 +413,7 @@ QSize FlowLayout::calculateMinimumSizeHorizontal() const } QSize itemMinSize = item->minimumSize(); - int itemWidth = itemMinSize.width() + horizontalSpacing(); + const int itemWidth = itemMinSize.width() + horizontalSpacing(); qCDebug(FlowLayoutLog) << "Processing item. Minimum size:" << itemMinSize << "Width with spacing:" << itemWidth; if (currentWidth + itemWidth > availableWidth) { @@ -509,7 +509,7 @@ QSize FlowLayout::calculateMinimumSizeVertical() const } QSize itemMinSize = item->minimumSize(); - int itemHeight = itemMinSize.height() + verticalSpacing(); + const int itemHeight = itemMinSize.height() + verticalSpacing(); qCDebug(FlowLayoutLog) << "Processing item. Minimum size:" << itemMinSize << "Height with spacing:" << itemHeight; @@ -553,7 +553,7 @@ void FlowLayout::insertWidgetAtIndex(QWidget *toInsert, int index) addChildWidget(toInsert); // We don't want to fail on an index that violates the bounds, so we just clamp it. - int boundedIndex = qBound(0, index, qMax(0, static_cast(items.size()))); + const int boundedIndex = qBound(0, index, qMax(0, static_cast(items.size()))); items.insert(boundedIndex, new QWidgetItem(toInsert)); invalidate(); diff --git a/cockatrice/src/interface/layouts/overlap_layout.cpp b/cockatrice/src/interface/layouts/overlap_layout.cpp index 9bf5e8468..13021ee97 100644 --- a/cockatrice/src/interface/layouts/overlap_layout.cpp +++ b/cockatrice/src/interface/layouts/overlap_layout.cpp @@ -57,7 +57,7 @@ OverlapLayout::~OverlapLayout() void OverlapLayout::insertWidgetAtIndex(QWidget *toInsert, int index) { addChildWidget(toInsert); - int clampedIndex = qBound(0, index, qMax(0, static_cast(itemList.size()))); + const int clampedIndex = qBound(0, index, qMax(0, static_cast(itemList.size()))); itemList.insert(clampedIndex, new QWidgetItem(toInsert)); for (int i = clampedIndex; i < itemList.size(); ++i) { @@ -154,7 +154,7 @@ void OverlapLayout::setGeometry(const QRect &rect) // Determine the maximum item width and height among all layout items. int maxItemWidth = 0; int maxItemHeight = 0; - for (QLayoutItem *item : itemList) { + for (const QLayoutItem *item : itemList) { if (item != nullptr && item->widget()) { QSize itemSize = item->widget()->sizeHint(); maxItemWidth = qMax(maxItemWidth, itemSize.width()); @@ -266,7 +266,7 @@ QSize OverlapLayout::calculatePreferredSize() const // Determine the maximum item width and height among all layout items. int maxItemWidth = 0; int maxItemHeight = 0; - for (QLayoutItem *item : itemList) { + for (const QLayoutItem *item : itemList) { if (item != nullptr && item->widget()) { QSize itemSize = item->widget()->sizeHint(); maxItemWidth = qMax(maxItemWidth, itemSize.width()); @@ -406,7 +406,7 @@ int OverlapLayout::calculateMaxColumns() const // Determine maximum item width int maxItemWidth = 0; - for (QLayoutItem *item : itemList) { + for (const QLayoutItem *item : itemList) { if (item == nullptr || !item->widget()) { continue; } @@ -457,7 +457,7 @@ int OverlapLayout::calculateMaxRows() const // Determine maximum item height int maxItemHeight = 0; - for (QLayoutItem *item : itemList) { + for (const QLayoutItem *item : itemList) { if (item == nullptr || !item->widget()) { continue; } diff --git a/cockatrice/src/interface/logger.cpp b/cockatrice/src/interface/logger.cpp index 37e07acec..26be2d9ad 100644 --- a/cockatrice/src/interface/logger.cpp +++ b/cockatrice/src/interface/logger.cpp @@ -140,7 +140,7 @@ QString Logger::getSystemLocale() QString Logger::getClientInstallInfo() { // don't rely on settingsCache->getIsPortableBuild() since the logger is initialized earlier - bool isPortable = QFile::exists(qApp->applicationDirPath() + "/portable.dat"); + const bool isPortable = QFile::exists(qApp->applicationDirPath() + "/portable.dat"); QString result(QString("Install Mode: ") + (isPortable ? "Portable" : "Standard")); return result; } diff --git a/cockatrice/src/interface/theme_manager.cpp b/cockatrice/src/interface/theme_manager.cpp index ec52a0f6e..6825d34f8 100644 --- a/cockatrice/src/interface/theme_manager.cpp +++ b/cockatrice/src/interface/theme_manager.cpp @@ -77,7 +77,7 @@ QStringMap &ThemeManager::getAvailableThemes() QBrush ThemeManager::loadBrush(QString fileName, QColor fallbackColor) { QBrush brush; - QPixmap tmp = QPixmap("theme:zones/" + fileName); + const QPixmap tmp = QPixmap("theme:zones/" + fileName); if (tmp.isNull()) { brush.setColor(fallbackColor); brush.setStyle(Qt::SolidPattern); @@ -91,7 +91,7 @@ QBrush ThemeManager::loadBrush(QString fileName, QColor fallbackColor) QBrush ThemeManager::loadExtraBrush(QString fileName, QBrush &fallbackBrush) { QBrush brush; - QPixmap tmp = QPixmap("theme:zones/" + fileName); + const QPixmap tmp = QPixmap("theme:zones/" + fileName); if (tmp.isNull()) { brush = fallbackBrush; @@ -104,10 +104,10 @@ QBrush ThemeManager::loadExtraBrush(QString fileName, QBrush &fallbackBrush) void ThemeManager::themeChangedSlot() { - QString themeName = SettingsCache::instance().getThemeName(); + const QString themeName = SettingsCache::instance().getThemeName(); qCInfo(ThemeManagerLog) << "Theme changed:" << themeName; - QString dirPath = getAvailableThemes().value(themeName); + const QString dirPath = getAvailableThemes().value(themeName); QDir dir = dirPath; // css diff --git a/cockatrice/src/interface/widgets/cards/additional_info/color_identity_widget.cpp b/cockatrice/src/interface/widgets/cards/additional_info/color_identity_widget.cpp index 20f4b29df..07e3c3cb7 100644 --- a/cockatrice/src/interface/widgets/cards/additional_info/color_identity_widget.cpp +++ b/cockatrice/src/interface/widgets/cards/additional_info/color_identity_widget.cpp @@ -83,14 +83,14 @@ void ColorIdentityWidget::resizeEvent(QResizeEvent *event) QList manaSymbols = findChildren(); if (!manaSymbols.isEmpty()) { - int totalWidth = event->size().width(); - int totalHeight = totalWidth / 6; // Set height to 1/4 of the width + const int totalWidth = event->size().width(); + const int totalHeight = totalWidth / 6; // Set height to 1/4 of the width setFixedHeight(totalHeight); - int spacing = layout->spacing(); - int count = manaSymbols.size(); - int availableWidth = totalWidth - (spacing * (count - 1)); - int iconSize = qMin(availableWidth / count, totalHeight); // Ensure icons fit within the new height + const int spacing = layout->spacing(); + const int count = manaSymbols.size(); + const int availableWidth = totalWidth - (spacing * (count - 1)); + const int iconSize = qMin(availableWidth / count, totalHeight); // Ensure icons fit within the new height for (ManaSymbolWidget *manaSymbol : manaSymbols) { manaSymbol->setFixedSize(iconSize, iconSize); diff --git a/cockatrice/src/interface/widgets/cards/additional_info/mana_cost_widget.cpp b/cockatrice/src/interface/widgets/cards/additional_info/mana_cost_widget.cpp index e5d1127aa..bd3abb39f 100644 --- a/cockatrice/src/interface/widgets/cards/additional_info/mana_cost_widget.cpp +++ b/cockatrice/src/interface/widgets/cards/additional_info/mana_cost_widget.cpp @@ -19,7 +19,7 @@ ManaCostWidget::ManaCostWidget(QWidget *parent, CardInfoPtr _card) : QWidget(par setFixedHeight(50); // Fixed height if (card) { - QString manaCost = card->getManaCost(); // Get mana cost string + const QString manaCost = card->getManaCost(); // Get mana cost string QStringList symbols = parseManaCost(manaCost); // Parse mana cost string for (const QString &symbol : symbols) { @@ -35,13 +35,13 @@ void ManaCostWidget::resizeEvent(QResizeEvent *event) QList manaSymbols = findChildren(); if (!manaSymbols.isEmpty()) { - int totalWidth = event->size().width(); - int spacing = layout->spacing(); - int count = manaSymbols.size(); + const int totalWidth = event->size().width(); + const int spacing = layout->spacing(); + const int count = manaSymbols.size(); // Available width minus total spacing - int availableWidth = totalWidth - (spacing * (count - 1)); - int iconSize = qMin(50, availableWidth / count); + const int availableWidth = totalWidth - (spacing * (count - 1)); + const int iconSize = qMin(50, availableWidth / count); for (ManaSymbolWidget *manaSymbol : manaSymbols) { manaSymbol->setFixedSize(iconSize, iconSize); diff --git a/cockatrice/src/interface/widgets/cards/card_group_display_widgets/card_group_display_widget.cpp b/cockatrice/src/interface/widgets/cards/card_group_display_widgets/card_group_display_widget.cpp index 7734a61d0..6f9f39182 100644 --- a/cockatrice/src/interface/widgets/cards/card_group_display_widgets/card_group_display_widget.cpp +++ b/cockatrice/src/interface/widgets/cards/card_group_display_widgets/card_group_display_widget.cpp @@ -39,7 +39,7 @@ CardGroupDisplayWidget::CardGroupDisplayWidget(QWidget *parent, void CardGroupDisplayWidget::onSelectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { - auto proxyModel = qobject_cast(selectionModel->model()); + const auto proxyModel = qobject_cast(selectionModel->model()); for (auto &range : selected) { for (int row = range.top(); row <= range.bottom(); ++row) { @@ -51,7 +51,7 @@ void CardGroupDisplayWidget::onSelectionChanged(const QItemSelection &selected, auto it = indexToWidgetMap.find(QPersistentModelIndex(idx)); if (it != indexToWidgetMap.end()) { - if (auto displayWidget = qobject_cast(it.value())) { + if (const auto displayWidget = qobject_cast(it.value())) { displayWidget->setHighlighted(true); } } @@ -66,7 +66,7 @@ void CardGroupDisplayWidget::onSelectionChanged(const QItemSelection &selected, auto it = indexToWidgetMap.find(QPersistentModelIndex(idx)); if (it != indexToWidgetMap.end()) { - if (auto displayWidget = qobject_cast(it.value())) { + if (const auto displayWidget = qobject_cast(it.value())) { displayWidget->setHighlighted(false); } } @@ -77,7 +77,7 @@ void CardGroupDisplayWidget::onSelectionChanged(const QItemSelection &selected, void CardGroupDisplayWidget::clearAllDisplayWidgets() { for (auto idx : indexToWidgetMap.keys()) { - auto displayWidget = indexToWidgetMap.value(idx); + const auto displayWidget = indexToWidgetMap.value(idx); removeFromLayout(displayWidget); indexToWidgetMap.remove(idx); delete displayWidget; @@ -89,10 +89,10 @@ QWidget *CardGroupDisplayWidget::constructWidgetForIndex(QPersistentModelIndex i if (indexToWidgetMap.contains(index)) { return indexToWidgetMap[index]; } - auto cardName = deckListModel->data(index.sibling(index.row(), 1), Qt::EditRole).toString(); - auto cardProviderId = deckListModel->data(index.sibling(index.row(), 4), Qt::EditRole).toString(); + const auto cardName = deckListModel->data(index.sibling(index.row(), 1), Qt::EditRole).toString(); + const auto cardProviderId = deckListModel->data(index.sibling(index.row(), 4), Qt::EditRole).toString(); - auto widget = new CardInfoPictureWithTextOverlayWidget(getLayoutParent(), true); + const auto widget = new CardInfoPictureWithTextOverlayWidget(getLayoutParent(), true); widget->setScaleFactor(cardSizeWidget->getSlider()->value()); widget->setCard(CardDatabaseManager::query()->getCard({cardName, cardProviderId})); @@ -115,7 +115,7 @@ void CardGroupDisplayWidget::updateCardDisplays() proxy.sort(1, Qt::AscendingOrder); // 1. trackedIndex is a source index → map it to proxy space - QModelIndex proxyParent = proxy.mapFromSource(trackedIndex); + const QModelIndex proxyParent = proxy.mapFromSource(trackedIndex); // 2. iterate children under the proxy parent for (int i = 0; i < proxy.rowCount(proxyParent); ++i) { @@ -125,7 +125,7 @@ void CardGroupDisplayWidget::updateCardDisplays() QModelIndex sourceIndex = proxy.mapToSource(proxyIndex); // 4. persist the source index - QPersistentModelIndex persistent(sourceIndex); + const QPersistentModelIndex persistent(sourceIndex); addToLayout(constructWidgetForIndex(persistent)); } @@ -143,7 +143,7 @@ void CardGroupDisplayWidget::onCardAddition(const QModelIndex &parent, int first QModelIndex child = deckListModel->index(row, 0, parent); // Persist the index - QPersistentModelIndex persistent(child); + const QPersistentModelIndex persistent(child); insertIntoLayout(constructWidgetForIndex(persistent), row); } diff --git a/cockatrice/src/interface/widgets/cards/card_info_display_widget.cpp b/cockatrice/src/interface/widgets/cards/card_info_display_widget.cpp index c08e0ed3c..e1ad200a4 100644 --- a/cockatrice/src/interface/widgets/cards/card_info_display_widget.cpp +++ b/cockatrice/src/interface/widgets/cards/card_info_display_widget.cpp @@ -31,8 +31,8 @@ CardInfoDisplayWidget::CardInfoDisplayWidget(const CardRef &cardRef, QWidget *pa setFrameStyle(QFrame::Panel | QFrame::Raised); - int pixmapHeight = QGuiApplication::primaryScreen()->geometry().height() / 3; - int pixmapWidth = static_cast(pixmapHeight / aspectRatio); + const int pixmapHeight = QGuiApplication::primaryScreen()->geometry().height() / 3; + const int pixmapWidth = static_cast(pixmapHeight / aspectRatio); pic->setFixedWidth(pixmapWidth); pic->setFixedHeight(pixmapHeight); setFixedWidth(pixmapWidth + 150); diff --git a/cockatrice/src/interface/widgets/cards/card_info_picture_art_crop_widget.cpp b/cockatrice/src/interface/widgets/cards/card_info_picture_art_crop_widget.cpp index 451104d17..963a3b53e 100644 --- a/cockatrice/src/interface/widgets/cards/card_info_picture_art_crop_widget.cpp +++ b/cockatrice/src/interface/widgets/cards/card_info_picture_art_crop_widget.cpp @@ -25,16 +25,16 @@ QPixmap CardInfoPictureArtCropWidget::getProcessedBackground(const QSize &target const QSize sz = fullResPixmap.size(); - int marginX = sz.width() * 0.07; - int topMargin = sz.height() * 0.11; - int bottomMargin = sz.height() * 0.45; + const int marginX = sz.width() * 0.07; + const int topMargin = sz.height() * 0.11; + const int bottomMargin = sz.height() * 0.45; QRect foilRect(marginX, topMargin, sz.width() - 2 * marginX, sz.height() - topMargin - bottomMargin); foilRect = foilRect.intersected(fullResPixmap.rect()); // always clamp to source bounds // Crop first, then scale for best quality - QPixmap cropped = fullResPixmap.copy(foilRect); + const QPixmap cropped = fullResPixmap.copy(foilRect); QPixmap scaled = cropped.scaled(targetSize, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); return scaled; diff --git a/cockatrice/src/interface/widgets/cards/card_info_picture_enlarged_widget.cpp b/cockatrice/src/interface/widgets/cards/card_info_picture_enlarged_widget.cpp index 9a79bd32f..b665ffef4 100644 --- a/cockatrice/src/interface/widgets/cards/card_info_picture_enlarged_widget.cpp +++ b/cockatrice/src/interface/widgets/cards/card_info_picture_enlarged_widget.cpp @@ -79,14 +79,14 @@ void CardInfoPictureEnlargedWidget::paintEvent(QPaintEvent *event) } // Scale the size of the pixmap to fit the widget while maintaining the aspect ratio - QSize scaledSize = enlargedPixmap.size().scaled(size().width(), size().height(), Qt::KeepAspectRatio); + const QSize scaledSize = enlargedPixmap.size().scaled(size().width(), size().height(), Qt::KeepAspectRatio); // Calculate the position to center the scaled pixmap - QPoint topLeft{(width() - scaledSize.width()) / 2, (height() - scaledSize.height()) / 2}; + const QPoint topLeft{(width() - scaledSize.width()) / 2, (height() - scaledSize.height()) / 2}; // Define the radius for rounded corners // Adjust the radius as needed for rounded corners - qreal radius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * scaledSize.width() : 0.; + const qreal radius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * scaledSize.width() : 0.; QStylePainter painter(this); // Fill the background with transparent color to ensure rounded corners are rendered properly diff --git a/cockatrice/src/interface/widgets/cards/card_info_picture_widget.cpp b/cockatrice/src/interface/widgets/cards/card_info_picture_widget.cpp index fc1b9ebe2..5b1b5a948 100644 --- a/cockatrice/src/interface/widgets/cards/card_info_picture_widget.cpp +++ b/cockatrice/src/interface/widgets/cards/card_info_picture_widget.cpp @@ -192,27 +192,28 @@ void CardInfoPictureWidget::paintEvent(QPaintEvent *event) } // Handle DPI scaling - qreal dpr = devicePixelRatio(); // Get the actual scaling factor - QSize availableSize = size() * dpr; // Convert to physical pixel size + const qreal dpr = devicePixelRatio(); // Get the actual scaling factor + const QSize availableSize = size() * dpr; // Convert to physical pixel size // Compute final scaled size - QSize pixmapSize = transformedPixmap.size(); - QSize scaledSize = pixmapSize.scaled(availableSize, Qt::KeepAspectRatio); + const QSize pixmapSize = transformedPixmap.size(); + const QSize scaledSize = pixmapSize.scaled(availableSize, Qt::KeepAspectRatio); // Pre-scale the pixmap once before drawing QPixmap finalPixmap = transformedPixmap.scaled(scaledSize, Qt::KeepAspectRatio, Qt::SmoothTransformation); finalPixmap.setDevicePixelRatio(dpr); // Ensure correct display on high-DPI screens // Compute target rectangle with explicit integer conversion - int targetX = static_cast((availableSize.width() - scaledSize.width()) / (2 * dpr)); - int targetY = static_cast((availableSize.height() - scaledSize.height()) / (2 * dpr)); - int targetW = static_cast(scaledSize.width() / dpr); - int targetH = static_cast(scaledSize.height() / dpr); - QRect targetRect{targetX, targetY, targetW, targetH}; + const int targetX = static_cast((availableSize.width() - scaledSize.width()) / (2 * dpr)); + const int targetY = static_cast((availableSize.height() - scaledSize.height()) / (2 * dpr)); + const int targetW = static_cast(scaledSize.width() / dpr); + const int targetH = static_cast(scaledSize.height() / dpr); + const QRect targetRect{targetX, targetY, targetW, targetH}; // Compute rounded corner radius // Ensure consistent rounding - qreal radius = SettingsCache::instance().getRoundCardCorners() ? 0.05 * static_cast(targetRect.width()) : 0.; + const qreal radius = + SettingsCache::instance().getRoundCardCorners() ? 0.05 * static_cast(targetRect.width()) : 0.; // Draw the pixmap with rounded corners QStylePainter painter(this); @@ -364,7 +365,7 @@ QMenu *CardInfoPictureWidget::createRightClickMenu() QMenu *CardInfoPictureWidget::createViewRelatedCardsMenu() { - auto viewRelatedCards = new QMenu(tr("View related cards")); + const auto viewRelatedCards = new QMenu(tr("View related cards")); QList relatedCards = exactCard.getInfo().getAllRelatedCards(); @@ -372,7 +373,7 @@ QMenu *CardInfoPictureWidget::createViewRelatedCardsMenu() return CardDatabaseManager::query()->getCardInfo(cardRelation->getName()) != nullptr; }; - bool atLeastOneGoodRelationFound = std::any_of(relatedCards.begin(), relatedCards.end(), relatedCardExists); + const bool atLeastOneGoodRelationFound = std::any_of(relatedCards.begin(), relatedCards.end(), relatedCardExists); if (!atLeastOneGoodRelationFound) { viewRelatedCards->setEnabled(false); @@ -397,8 +398,8 @@ QMenu *CardInfoPictureWidget::createViewRelatedCardsMenu() */ static MainWindow *findMainWindow() { - for (auto widget : QApplication::topLevelWidgets()) { - if (auto mainWindow = qobject_cast(widget)) { + for (const auto widget : QApplication::topLevelWidgets()) { + if (const auto mainWindow = qobject_cast(widget)) { return mainWindow; } } @@ -409,9 +410,9 @@ static MainWindow *findMainWindow() QMenu *CardInfoPictureWidget::createAddToOpenDeckMenu() { - auto addToOpenDeckMenu = new QMenu(tr("Add card to deck")); + const auto addToOpenDeckMenu = new QMenu(tr("Add card to deck")); - auto mainWindow = findMainWindow(); + const auto mainWindow = findMainWindow(); QList deckEditorTabs = mainWindow->getTabSupervisor()->getDeckEditorTabs(); if (deckEditorTabs.isEmpty()) { @@ -422,13 +423,13 @@ QMenu *CardInfoPictureWidget::createAddToOpenDeckMenu() for (auto &deckEditorTab : deckEditorTabs) { auto *addCardMenu = addToOpenDeckMenu->addMenu(deckEditorTab->getTabText()); - QAction *addCard = addCardMenu->addAction(tr("Mainboard")); + const QAction *addCard = addCardMenu->addAction(tr("Mainboard")); connect(addCard, &QAction::triggered, this, [this, deckEditorTab] { deckEditorTab->updateCard(exactCard); deckEditorTab->actAddCard(exactCard); }); - QAction *addCardSideboard = addCardMenu->addAction(tr("Sideboard")); + const QAction *addCardSideboard = addCardMenu->addAction(tr("Sideboard")); connect(addCardSideboard, &QAction::triggered, this, [this, deckEditorTab] { deckEditorTab->updateCard(exactCard); deckEditorTab->actAddCardToSideboard(exactCard); diff --git a/cockatrice/src/interface/widgets/cards/card_info_text_widget.cpp b/cockatrice/src/interface/widgets/cards/card_info_text_widget.cpp index f11be533a..8277075bb 100644 --- a/cockatrice/src/interface/widgets/cards/card_info_text_widget.cpp +++ b/cockatrice/src/interface/widgets/cards/card_info_text_widget.cpp @@ -75,7 +75,7 @@ void CardInfoTextWidget::setCard(CardInfoPtr card) if (!relatedCards.empty()) { text += QString("%1").arg(tr("Related cards:")); - for (auto *relatedCard : relatedCards) { + for (const auto *relatedCard : relatedCards) { QString tmp = relatedCard->getName().toHtmlEscaped(); text += "" + tmp + "
    "; } diff --git a/cockatrice/src/interface/widgets/cards/deck_card_zone_display_widget.cpp b/cockatrice/src/interface/widgets/cards/deck_card_zone_display_widget.cpp index 5529c35b6..518f31628 100644 --- a/cockatrice/src/interface/widgets/cards/deck_card_zone_display_widget.cpp +++ b/cockatrice/src/interface/widgets/cards/deck_card_zone_display_widget.cpp @@ -81,7 +81,7 @@ void DeckCardZoneDisplayWidget::cleanupInvalidCardGroup(CardGroupDisplayWidget * void DeckCardZoneDisplayWidget::constructAppropriateWidget(QPersistentModelIndex index) { - auto categoryName = deckListModel->data(index.sibling(index.row(), 1), Qt::EditRole).toString(); + const auto categoryName = deckListModel->data(index.sibling(index.row(), 1), Qt::EditRole).toString(); if (indexToWidgetMap.contains(index)) { return; } @@ -122,7 +122,7 @@ void DeckCardZoneDisplayWidget::displayCards() proxy.sort(1, Qt::AscendingOrder); // 1. trackedIndex is a source index → map it to proxy space - QModelIndex proxyParent = proxy.mapFromSource(trackedIndex); + const QModelIndex proxyParent = proxy.mapFromSource(trackedIndex); // 2. iterate children under the proxy parent for (int i = 0; i < proxy.rowCount(proxyParent); ++i) { @@ -132,7 +132,7 @@ void DeckCardZoneDisplayWidget::displayCards() QModelIndex sourceIndex = proxy.mapToSource(proxyIndex); // 4. persist the source index - QPersistentModelIndex persistent(sourceIndex); + const QPersistentModelIndex persistent(sourceIndex); constructAppropriateWidget(persistent); } @@ -146,7 +146,7 @@ void DeckCardZoneDisplayWidget::onCategoryAddition(const QModelIndex &parent, in } if (parent == trackedIndex) { for (int i = first; i <= last; i++) { - QPersistentModelIndex index = QPersistentModelIndex(deckListModel->index(i, 0, trackedIndex)); + const QPersistentModelIndex index = QPersistentModelIndex(deckListModel->index(i, 0, trackedIndex)); constructAppropriateWidget(index); } @@ -206,7 +206,7 @@ void DeckCardZoneDisplayWidget::refreshDisplayType(const DisplayType &_displayTy // We gotta wait for all the deleteLater's to finish so we fire after the next event cycle - auto timer = new QTimer(this); + const auto timer = new QTimer(this); timer->setSingleShot(true); connect(timer, &QTimer::timeout, this, [this]() { displayCards(); }); timer->start(); diff --git a/cockatrice/src/interface/widgets/deck_analytics/mana_base_widget.cpp b/cockatrice/src/interface/widgets/deck_analytics/mana_base_widget.cpp index 568583af5..b19db2946 100644 --- a/cockatrice/src/interface/widgets/deck_analytics/mana_base_widget.cpp +++ b/cockatrice/src/interface/widgets/deck_analytics/mana_base_widget.cpp @@ -51,7 +51,7 @@ void ManaBaseWidget::updateDisplay() } int highestEntry = 0; - for (auto entry : manaBaseMap) { + for (const auto entry : manaBaseMap) { if (entry > highestEntry) { highestEntry = entry; } @@ -67,7 +67,7 @@ void ManaBaseWidget::updateDisplay() manaColors.insert("C", QColor(150, 150, 150)); for (auto manaColor : manaBaseMap.keys()) { - QColor barColor = manaColors.value(manaColor, Qt::gray); + const QColor barColor = manaColors.value(manaColor, Qt::gray); BarWidget *barWidget = new BarWidget(QString(manaColor), manaBaseMap[manaColor], highestEntry, barColor, this); barLayout->addWidget(barWidget); } @@ -80,7 +80,7 @@ QHash ManaBaseWidget::analyzeManaBase() manaBaseMap.clear(); QList cardsInDeck = deckListModel->getDeckList()->getCardNodes(); - for (auto currentCard : cardsInDeck) { + for (const auto currentCard : cardsInDeck) { for (int k = 0; k < currentCard->getNumber(); ++k) { CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); if (info) { @@ -98,7 +98,7 @@ QHash ManaBaseWidget::determineManaProduction(const QString &rules { QHash manaCounts = {{"W", 0}, {"U", 0}, {"B", 0}, {"R", 0}, {"G", 0}, {"C", 0}}; - QString text = rulesText.toLower(); // Normalize case for matching + const QString text = rulesText.toLower(); // Normalize case for matching // Quick keyword-based checks for any color and colorless mana if (text.contains("{t}: add one mana of any color") || text.contains("add one mana of any color")) { @@ -113,7 +113,7 @@ QHash ManaBaseWidget::determineManaProduction(const QString &rules // Optimized regex for specific mana symbols static const QRegularExpression specificColorRegex(R"(\{T\}:\s*Add\s*\{([WUBRG])\})"); - QRegularExpressionMatch match = specificColorRegex.match(rulesText); + const QRegularExpressionMatch match = specificColorRegex.match(rulesText); if (match.hasMatch()) { manaCounts[match.captured(1)]++; } diff --git a/cockatrice/src/interface/widgets/deck_analytics/mana_curve_widget.cpp b/cockatrice/src/interface/widgets/deck_analytics/mana_curve_widget.cpp index 4515b723b..6600d306e 100644 --- a/cockatrice/src/interface/widgets/deck_analytics/mana_curve_widget.cpp +++ b/cockatrice/src/interface/widgets/deck_analytics/mana_curve_widget.cpp @@ -47,7 +47,7 @@ std::unordered_map ManaCurveWidget::analyzeManaCurve() QList cardsInDeck = deckListModel->getDeckList()->getCardNodes(); - for (auto currentCard : cardsInDeck) { + for (const auto currentCard : cardsInDeck) { for (int k = 0; k < currentCard->getNumber(); ++k) { CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); if (info) { @@ -81,7 +81,7 @@ void ManaCurveWidget::updateDisplay() } // Convert unordered_map to ordered map to ensure sorting by CMC - std::map sortedManaCurve(manaCurveMap.begin(), manaCurveMap.end()); + const std::map sortedManaCurve(manaCurveMap.begin(), manaCurveMap.end()); // Add new widgets to the layout in sorted order for (const auto &entry : sortedManaCurve) { diff --git a/cockatrice/src/interface/widgets/deck_analytics/mana_devotion_widget.cpp b/cockatrice/src/interface/widgets/deck_analytics/mana_devotion_widget.cpp index 3cafdaeab..be38791f0 100644 --- a/cockatrice/src/interface/widgets/deck_analytics/mana_devotion_widget.cpp +++ b/cockatrice/src/interface/widgets/deck_analytics/mana_devotion_widget.cpp @@ -49,7 +49,7 @@ std::unordered_map ManaDevotionWidget::analyzeManaDevotion() QList cardsInDeck = deckListModel->getDeckList()->getCardNodes(); - for (auto currentCard : cardsInDeck) { + for (const auto currentCard : cardsInDeck) { for (int k = 0; k < currentCard->getNumber(); ++k) { CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); if (info) { @@ -73,7 +73,7 @@ void ManaDevotionWidget::updateDisplay() } int highestEntry = 0; - for (auto entry : manaDevotionMap) { + for (const auto entry : manaDevotionMap) { if (highestEntry < entry.second) { highestEntry = entry.second; } @@ -85,7 +85,7 @@ void ManaDevotionWidget::updateDisplay() {'G', QColor(0, 115, 62)}, {'C', QColor(150, 150, 150)}}; for (auto entry : manaDevotionMap) { - QColor barColor = manaColors.count(entry.first) ? manaColors[entry.first] : Qt::gray; + const QColor barColor = manaColors.count(entry.first) ? manaColors[entry.first] : Qt::gray; BarWidget *barWidget = new BarWidget(QString(entry.first), entry.second, highestEntry, barColor, this); barLayout->addWidget(barWidget); } @@ -97,7 +97,7 @@ std::unordered_map ManaDevotionWidget::countManaSymbols(const QString { std::unordered_map manaCounts = {{'W', 0}, {'U', 0}, {'B', 0}, {'R', 0}, {'G', 0}}; - int len = manaString.length(); + const int len = manaString.length(); for (int i = 0; i < len; ++i) { if (manaString[i] == '{') { ++i; // Move past '{' diff --git a/cockatrice/src/interface/widgets/deck_editor/deck_editor_database_display_widget.cpp b/cockatrice/src/interface/widgets/deck_editor/deck_editor_database_display_widget.cpp index b5aa007f0..74ec61ceb 100644 --- a/cockatrice/src/interface/widgets/deck_editor/deck_editor_database_display_widget.cpp +++ b/cockatrice/src/interface/widgets/deck_editor/deck_editor_database_display_widget.cpp @@ -37,7 +37,7 @@ DeckEditorDatabaseDisplayWidget::DeckEditorDatabaseDisplayWidget(AbstractTabDeck searchEdit->setPlaceholderText(tr("Search by card name (or search expressions)")); searchEdit->setClearButtonEnabled(true); searchEdit->addAction(loadColorAdjustedPixmap("theme:icons/search"), QLineEdit::LeadingPosition); - auto help = searchEdit->addAction(QPixmap("theme:icons/info"), QLineEdit::TrailingPosition); + const auto help = searchEdit->addAction(QPixmap("theme:icons/info"), QLineEdit::TrailingPosition); searchEdit->installEventFilter(&searchKeySignals); setFocusProxy(searchEdit); @@ -83,7 +83,7 @@ DeckEditorDatabaseDisplayWidget::DeckEditorDatabaseDisplayWidget(AbstractTabDeck &DeckEditorDatabaseDisplayWidget::updateCard); connect(databaseView, &QTreeView::doubleClicked, this, &DeckEditorDatabaseDisplayWidget::actAddCardToMainDeck); - QByteArray dbHeaderState = SettingsCache::instance().layouts().getDeckEditorDbHeaderState(); + const QByteArray dbHeaderState = SettingsCache::instance().layouts().getDeckEditorDbHeaderState(); if (dbHeaderState.isNull()) { // first run databaseView->setColumnWidth(0, 200); @@ -122,7 +122,7 @@ DeckEditorDatabaseDisplayWidget::DeckEditorDatabaseDisplayWidget(AbstractTabDeck void DeckEditorDatabaseDisplayWidget::updateSearch(const QString &search) { databaseDisplayModel->setStringFilter(search); - QModelIndexList sel = databaseView->selectionModel()->selectedRows(); + const QModelIndexList sel = databaseView->selectionModel()->selectedRows(); if (sel.isEmpty() && databaseDisplayModel->rowCount()) databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); @@ -214,7 +214,7 @@ void DeckEditorDatabaseDisplayWidget::databaseCustomMenu(QPoint point) } else { for (const CardRelation *rel : relatedCards) { const QString &relatedCardName = rel->getName(); - QAction *relatedCard = relatedMenu->addAction(relatedCardName); + const QAction *relatedCard = relatedMenu->addAction(relatedCardName); connect( relatedCard, &QAction::triggered, deckEditor->cardInfoDockWidget->cardInfo, [this, relatedCardName] { deckEditor->cardInfoDockWidget->cardInfo->setCard(relatedCardName); }); @@ -226,7 +226,7 @@ void DeckEditorDatabaseDisplayWidget::databaseCustomMenu(QPoint point) void DeckEditorDatabaseDisplayWidget::copyDatabaseCellContents() { - auto _data = databaseView->selectionModel()->currentIndex().data(); + const auto _data = databaseView->selectionModel()->currentIndex().data(); QApplication::clipboard()->setText(_data.toString()); } diff --git a/cockatrice/src/interface/widgets/deck_editor/deck_editor_deck_dock_widget.cpp b/cockatrice/src/interface/widgets/deck_editor/deck_editor_deck_dock_widget.cpp index 4db7b8774..524f7599f 100644 --- a/cockatrice/src/interface/widgets/deck_editor/deck_editor_deck_dock_widget.cpp +++ b/cockatrice/src/interface/widgets/deck_editor/deck_editor_deck_dock_widget.cpp @@ -265,7 +265,7 @@ void DeckEditorDeckDockWidget::createDeckDock() ExactCard DeckEditorDeckDockWidget::getCurrentCard() { - QModelIndex current = deckView->selectionModel()->currentIndex(); + const QModelIndex current = deckView->selectionModel()->currentIndex(); if (!current.isValid()) return {}; const QString cardName = current.sibling(current.row(), 1).data().toString(); @@ -288,7 +288,7 @@ ExactCard DeckEditorDeckDockWidget::getCurrentCard() void DeckEditorDeckDockWidget::updateCard(const QModelIndex /*¤t*/, const QModelIndex & /*previous*/) { - if (ExactCard card = getCurrentCard()) { + if (const ExactCard card = getCurrentCard()) { emit cardChanged(card); } } @@ -325,10 +325,10 @@ void DeckEditorDeckDockWidget::updateHash() void DeckEditorDeckDockWidget::updateBannerCardComboBox() { // Store current banner card identity - CardRef wanted = deckModel->getDeckList()->getBannerCard(); + const CardRef wanted = deckModel->getDeckList()->getBannerCard(); // Block signals temporarily - bool wasBlocked = bannerCardComboBox->blockSignals(true); + const bool wasBlocked = bannerCardComboBox->blockSignals(true); // Clear the existing items in the combo box bannerCardComboBox->clear(); @@ -337,7 +337,7 @@ void DeckEditorDeckDockWidget::updateBannerCardComboBox() QSet> bannerCardSet; QList cardsInDeck = deckModel->getDeckList()->getCardNodes(); - for (auto currentCard : cardsInDeck) { + for (const auto currentCard : cardsInDeck) { if (!CardDatabaseManager::query()->getCard(currentCard->toCardRef())) { continue; } @@ -359,7 +359,7 @@ void DeckEditorDeckDockWidget::updateBannerCardComboBox() } // Try to find an index with a matching card - int restoreIndex = findRestoreIndex(wanted, bannerCardComboBox); + const int restoreIndex = findRestoreIndex(wanted, bannerCardComboBox); // Handle results if (restoreIndex != -1) { @@ -576,9 +576,10 @@ bool DeckEditorDeckDockWidget::swapCard(const QModelIndex ¤tIndex) offsetCountAtIndex(currentIndex, -1); const QString otherZoneName = zoneName == DECK_ZONE_MAIN ? DECK_ZONE_SIDE : DECK_ZONE_MAIN; - ExactCard card = CardDatabaseManager::query()->getCard({cardName, cardProviderID}); - QModelIndex newCardIndex = card ? deckModel->addCard(card, otherZoneName) - // Third argument (true) says create the card no matter what, even if not in DB + const ExactCard card = CardDatabaseManager::query()->getCard({cardName, cardProviderID}); + const QModelIndex newCardIndex = card + ? deckModel->addCard(card, otherZoneName) + // Third argument (true) says create the card no matter what, even if not in DB : deckModel->addPreferredPrintingCard(cardName, otherZoneName, true); recursiveExpand(proxy->mapToSource(newCardIndex)); @@ -592,10 +593,10 @@ void DeckEditorDeckDockWidget::actDecrementCard(const ExactCard &card, QString z if (card.getInfo().getIsToken()) zoneName = DECK_ZONE_TOKENS; - QString providerId = card.getPrinting().getUuid(); - QString collectorNumber = card.getPrinting().getProperty("num"); + const QString providerId = card.getPrinting().getUuid(); + const QString collectorNumber = card.getPrinting().getProperty("num"); - QModelIndex idx = deckModel->findCard(card.getName(), zoneName, providerId, collectorNumber); + const QModelIndex idx = deckModel->findCard(card.getName(), zoneName, providerId, collectorNumber); if (!idx.isValid()) { return; } @@ -659,7 +660,7 @@ void DeckEditorDeckDockWidget::offsetCountAtIndex(const QModelIndex &idx, int of return; } - QModelIndex sourceIndex = proxy->mapToSource(idx); + const QModelIndex sourceIndex = proxy->mapToSource(idx); const QModelIndex numberIndex = sourceIndex.sibling(sourceIndex.row(), 0); const QModelIndex nameIndex = sourceIndex.sibling(sourceIndex.row(), 1); @@ -691,7 +692,7 @@ void DeckEditorDeckDockWidget::decklistCustomMenu(QPoint point) if (!SettingsCache::instance().getOverrideAllCardArtWithPersonalPreference()) { QMenu menu; - QAction *selectPrinting = menu.addAction(tr("Select Printing")); + const QAction *selectPrinting = menu.addAction(tr("Select Printing")); connect(selectPrinting, &QAction::triggered, deckEditor, &AbstractTabDeckEditor::showPrintingSelector); menu.exec(deckView->mapToGlobal(point)); @@ -700,7 +701,7 @@ void DeckEditorDeckDockWidget::decklistCustomMenu(QPoint point) void DeckEditorDeckDockWidget::refreshShortcuts() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aRemoveCard->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aRemoveCard")); aIncrement->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aIncrement")); aDecrement->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aDecrement")); diff --git a/cockatrice/src/interface/widgets/deck_editor/deck_editor_filter_dock_widget.cpp b/cockatrice/src/interface/widgets/deck_editor/deck_editor_filter_dock_widget.cpp index 4957e24ec..f9cc70b26 100644 --- a/cockatrice/src/interface/widgets/deck_editor/deck_editor_filter_dock_widget.cpp +++ b/cockatrice/src/interface/widgets/deck_editor/deck_editor_filter_dock_widget.cpp @@ -128,7 +128,7 @@ void DeckEditorFilterDockWidget::actClearFilterOne() void DeckEditorFilterDockWidget::refreshShortcuts() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aClearFilterAll->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aClearFilterAll")); aClearFilterOne->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aClearFilterOne")); diff --git a/cockatrice/src/interface/widgets/deck_editor/deck_list_history_manager_widget.cpp b/cockatrice/src/interface/widgets/deck_editor/deck_list_history_manager_widget.cpp index c68934ea6..8be0bbfca 100644 --- a/cockatrice/src/interface/widgets/deck_editor/deck_list_history_manager_widget.cpp +++ b/cockatrice/src/interface/widgets/deck_editor/deck_list_history_manager_widget.cpp @@ -70,7 +70,7 @@ void DeckListHistoryManagerWidget::refreshList() // Fill redo section first (oldest redo at top, newest redo closest to divider) const auto redoStack = historyManager->getRedoStack(); for (int i = 0; i < redoStack.size(); ++i) { // iterate forward - auto item = new QListWidgetItem(tr("[redo] ") + redoStack[i].getReason(), historyList); + const auto item = new QListWidgetItem(tr("[redo] ") + redoStack[i].getReason(), historyList); item->setData(Qt::UserRole, QVariant("redo")); item->setData(Qt::UserRole + 1, i); // index in redo stack item->setForeground(Qt::gray); @@ -79,7 +79,7 @@ void DeckListHistoryManagerWidget::refreshList() // Divider if (!historyManager->getUndoStack().isEmpty() && !historyManager->getRedoStack().isEmpty()) { - auto divider = new QListWidgetItem("──────────", historyList); + const auto divider = new QListWidgetItem("──────────", historyList); divider->setFlags(Qt::NoItemFlags); // not selectable historyList->addItem(divider); } @@ -87,7 +87,7 @@ void DeckListHistoryManagerWidget::refreshList() // Fill undo section const auto undoStack = historyManager->getUndoStack(); for (int i = undoStack.size() - 1; i >= 0; --i) { - auto item = new QListWidgetItem(tr("[undo] ") + undoStack[i].getReason(), historyList); + const auto item = new QListWidgetItem(tr("[undo] ") + undoStack[i].getReason(), historyList); item->setData(Qt::UserRole, QVariant("undo")); item->setData(Qt::UserRole + 1, i); // index in undo stack historyList->addItem(item); @@ -135,17 +135,17 @@ void DeckListHistoryManagerWidget::onListClicked(QListWidgetItem *item) } const QString mode = item->data(Qt::UserRole).toString(); - int index = item->data(Qt::UserRole + 1).toInt(); + const int index = item->data(Qt::UserRole + 1).toInt(); if (mode == "redo") { const auto redoStack = historyManager->getRedoStack(); - int steps = redoStack.size() - index; + const int steps = redoStack.size() - index; for (int i = 0; i < steps; ++i) { historyManager->redo(deckListModel->getDeckList()); } } else if (mode == "undo") { const auto undoStack = historyManager->getUndoStack(); - int steps = undoStack.size() - 1 - index; + const int steps = undoStack.size() - 1 - index; for (int i = 0; i < steps + 1; ++i) { historyManager->undo(deckListModel->getDeckList()); } diff --git a/cockatrice/src/interface/widgets/deck_editor/deck_list_style_proxy.cpp b/cockatrice/src/interface/widgets/deck_editor/deck_list_style_proxy.cpp index 9c2265dfd..ccab2581a 100644 --- a/cockatrice/src/interface/widgets/deck_editor/deck_list_style_proxy.cpp +++ b/cockatrice/src/interface/widgets/deck_editor/deck_list_style_proxy.cpp @@ -7,13 +7,13 @@ QVariant DeckListStyleProxy::data(const QModelIndex &index, int role) const { - QModelIndex src = mapToSource(index); + const QModelIndex src = mapToSource(index); if (!src.isValid()) return {}; QVariant value = QIdentityProxyModel::data(index, role); - bool isCard = src.data(DeckRoles::IsCardRole).toBool(); + const bool isCard = src.data(DeckRoles::IsCardRole).toBool(); if (role == Qt::FontRole && !isCard) { QFont f; @@ -25,11 +25,11 @@ QVariant DeckListStyleProxy::data(const QModelIndex &index, int role) const if (isCard) { const bool legal = true; // TODO: Not implemented yet. QIdentityProxyModel::data(index, DeckRoles::IsLegalRole).toBool(); - int base = 255 - (index.row() % 2) * 30; + const int base = 255 - (index.row() % 2) * 30; return legal ? QBrush(QColor(base, base, base)) : QBrush(QColor(255, base / 3, base / 3)); } else { - int depth = src.data(DeckRoles::DepthRole).toInt(); - int color = 90 + 60 * depth; + const int depth = src.data(DeckRoles::DepthRole).toInt(); + const int color = 90 + 60 * depth; return QBrush(QColor(color, 255, color)); } } diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp index ed32b356c..337c2b370 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp @@ -214,9 +214,9 @@ void DlgConnect::rebuildComboBoxList(int failure) savedHostList = uci.getServerInfo(); auto &servers = SettingsCache::instance().servers(); - bool autoConnectEnabled = servers.getAutoConnect() > 0; - QString previousHostName = servers.getPrevioushostName(); - QString autoConnectSaveName = servers.getSaveName(); + const bool autoConnectEnabled = servers.getAutoConnect() > 0; + const QString previousHostName = servers.getPrevioushostName(); + const QString autoConnectSaveName = servers.getSaveName(); int index = 0; @@ -272,7 +272,7 @@ void DlgConnect::updateDisplayInfo(const QString &saveName) << ""; } - bool savePasswordStatus = (_data.at(5) == "1"); + const bool savePasswordStatus = (_data.at(5) == "1"); saveEdit->setText(_data.at(0)); hostEdit->setText(_data.at(1)); @@ -285,7 +285,7 @@ void DlgConnect::updateDisplayInfo(const QString &saveName) } if (!_data.at(6).isEmpty()) { - QString formattedLink = "" + _data.at(6) + ""; + const QString formattedLink = "" + _data.at(6) + ""; serverContactLabel->setText(tr("Webpage") + ":"); serverContactLink->setText(formattedLink); } else { diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_default_tags_editor.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_default_tags_editor.cpp index 5b120b1e2..2af3445b6 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_default_tags_editor.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_default_tags_editor.cpp @@ -85,7 +85,7 @@ void DlgDefaultTagsEditor::loadStringList() void DlgDefaultTagsEditor::addItem() { - QString newTag = inputField->text().trimmed(); + const QString newTag = inputField->text().trimmed(); if (newTag.isEmpty()) { QMessageBox::warning(this, tr("Invalid Input"), tr("Tag name cannot be empty!")); return; @@ -93,10 +93,10 @@ void DlgDefaultTagsEditor::addItem() // Prevent duplicate tags for (int i = 0; i < listWidget->count(); ++i) { - QWidget *widget = listWidget->itemWidget(listWidget->item(i)); + const QWidget *widget = listWidget->itemWidget(listWidget->item(i)); if (!widget) continue; - QLineEdit *lineEdit = widget->findChild(); + const QLineEdit *lineEdit = widget->findChild(); if (lineEdit && lineEdit->text() == newTag) { QMessageBox::warning(this, tr("Duplicate Tag"), tr("This tag already exists.")); return; @@ -136,10 +136,10 @@ void DlgDefaultTagsEditor::confirmChanges() { QStringList updatedList; for (int i = 0; i < listWidget->count(); ++i) { - QWidget *widget = listWidget->itemWidget(listWidget->item(i)); + const QWidget *widget = listWidget->itemWidget(listWidget->item(i)); if (!widget) continue; - QLineEdit *lineEdit = widget->findChild(); + const QLineEdit *lineEdit = widget->findChild(); if (lineEdit) { updatedList.append(lineEdit->text()); } diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_edit_avatar.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_edit_avatar.cpp index 7330c749b..81c29ea1a 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_edit_avatar.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_edit_avatar.cpp @@ -49,7 +49,7 @@ void DlgEditAvatar::actOk() void DlgEditAvatar::actBrowse() { - QString fileName = + const QString fileName = QFileDialog::getOpenFileName(this, tr("Open Image"), QDir::homePath(), tr("Image Files (*.png *.jpg *.bmp)")); if (fileName.isEmpty()) { imageLabel->setText(tr("No image chosen.")); diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp index a47a8221a..4a06b9385 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp @@ -162,11 +162,11 @@ void DlgEditTokens::actAddToken() } } - QString setName = CardSet::TOKENS_SETNAME; + const QString setName = CardSet::TOKENS_SETNAME; SetToPrintingsMap sets; sets[setName].append(PrintingInfo(databaseModel->getDatabase()->getSet(setName))); - CardInfo::UiAttributes attributes = {.tableRow = -1}; - CardInfoPtr card = CardInfo::newInstance(name, "", true, {}, {}, {}, sets, attributes); + const CardInfo::UiAttributes attributes = {.tableRow = -1}; + const CardInfoPtr card = CardInfo::newInstance(name, "", true, {}, {}, {}, sets, attributes); card->setCardType("Token"); databaseModel->getDatabase()->addCard(card); @@ -175,7 +175,7 @@ void DlgEditTokens::actAddToken() void DlgEditTokens::actRemoveToken() { if (currentCard) { - CardInfoPtr cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard() + const CardInfoPtr cardToRemove = currentCard; // the currentCard property gets modified during db->removeCard() currentCard.clear(); databaseModel->getDatabase()->removeCard(cardToRemove); } diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_filter_games.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_filter_games.cpp index 1bf98822c..d85337ba2 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_filter_games.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_filter_games.cpp @@ -261,7 +261,7 @@ int DlgFilterGames::getMaxPlayersFilterMax() const QTime DlgFilterGames::getMaxGameAge() const { - int index = maxGameAgeComboBox->currentIndex(); + const int index = maxGameAgeComboBox->currentIndex(); if (index < 0 || index >= gameAgeMap.size()) { // index is out of bounds return gamesProxyModel->getMaxGameAge(); // leave the setting unchanged } diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_load_deck_from_website.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_load_deck_from_website.cpp index f29984ab0..af46a9ec5 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_load_deck_from_website.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_load_deck_from_website.cpp @@ -56,7 +56,7 @@ void DlgLoadDeckFromWebsite::accept() if (DeckLinkToApiTransformer::parseDeckUrl(urlEdit->text(), info)) { qCInfo(DlgLoadDeckFromWebsiteLog) << info.baseUrl << info.deckID << info.fullUrl; - auto jsonParser = createParserForProvider(info.provider); + const auto jsonParser = createParserForProvider(info.provider); if (!jsonParser && info.provider != DeckProvider::Deckstats && info.provider != DeckProvider::TappedOut) { qCWarning(DlgLoadDeckFromWebsiteLog) << "No parser found for provider"; QMessageBox::warning(this, tr("Load Deck from Website"), @@ -66,7 +66,7 @@ void DlgLoadDeckFromWebsite::accept() return; } - QNetworkRequest request(QUrl(info.fullUrl)); + const QNetworkRequest request(QUrl(info.fullUrl)); QNetworkReply *reply = nam->get(request); QEventLoop loop; @@ -81,7 +81,7 @@ void DlgLoadDeckFromWebsite::accept() return; } - QByteArray responseData = reply->readAll(); + const QByteArray responseData = reply->readAll(); reply->deleteLater(); // Special handling for Deckstats and TappedOut .txt @@ -107,7 +107,7 @@ void DlgLoadDeckFromWebsite::accept() // Normal JSON parsing for other providers QJsonParseError parseError; - QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError); + const QJsonDocument doc = QJsonDocument::fromJson(responseData, &parseError); if (parseError.error != QJsonParseError::NoError) { qCWarning(DlgLoadDeckFromWebsiteLog) << "JSON parse error:" << parseError.errorString(); QMessageBox::warning(this, tr("Load Deck from Website"), diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp index 2d3bc08a4..82fe314b2 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp @@ -326,19 +326,19 @@ void WndSets::actDisableSortButtons(int index) void WndSets::actToggleButtons(const QItemSelection &selected, const QItemSelection &) { - bool emptySelection = selected.empty(); + const bool emptySelection = selected.empty(); aTop->setDisabled(emptySelection || setOrderIsSorted); aUp->setDisabled(emptySelection || setOrderIsSorted); aDown->setDisabled(emptySelection || setOrderIsSorted); aBottom->setDisabled(emptySelection || setOrderIsSorted); - int rows = view->selectionModel()->selectedRows().size(); + const int rows = view->selectionModel()->selectedRows().size(); rebuildMainLayout((rows > 1) ? SOME_SETS_SELECTED : NO_SETS_SELECTED); } void WndSets::selectRows(QSet rows) { - for (auto i : rows) { + for (const auto i : rows) { QModelIndex idx = model->index(i, 0); view->selectionModel()->select(idx, QItemSelectionModel::Select | QItemSelectionModel::Rows); view->scrollTo(idx, QAbstractItemView::EnsureVisible); @@ -385,7 +385,7 @@ void WndSets::actUp() for (auto i : rows) { if (i.row() <= 0) continue; - int oldRow = displayModel->mapToSource(i).row(); + const int oldRow = displayModel->mapToSource(i).row(); int newRow = i.row() - 1; model->swapRows(oldRow, displayModel->mapToSource(displayModel->index(newRow, 0)).row()); @@ -408,7 +408,7 @@ void WndSets::actDown() for (auto i : rows) { if (i.row() >= displayModel->rowCount() - 1) continue; - int oldRow = displayModel->mapToSource(i).row(); + const int oldRow = displayModel->mapToSource(i).row(); int newRow = i.row() + 1; model->swapRows(oldRow, displayModel->mapToSource(displayModel->index(newRow, 0)).row()); @@ -429,7 +429,7 @@ void WndSets::actTop() return; for (int i = 0; i < rows.length(); i++) { - int oldRow = displayModel->mapToSource(rows.at(i)).row(); + const int oldRow = displayModel->mapToSource(rows.at(i)).row(); if (oldRow <= 0) { newRow++; @@ -455,7 +455,7 @@ void WndSets::actBottom() return; for (int i = 0; i < rows.length(); i++) { - int oldRow = displayModel->mapToSource(rows.at(i)).row(); + const int oldRow = displayModel->mapToSource(rows.at(i)).row(); if (oldRow >= newRow) { newRow--; diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_select_set_for_cards.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_select_set_for_cards.cpp index 121ce4c86..2f7ec8d7c 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_select_set_for_cards.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_select_set_for_cards.cpp @@ -144,7 +144,7 @@ void DlgSelectSetForCards::retranslateUi() void DlgSelectSetForCards::actOK() { - QMap modifiedSetsAndCardsMap = getModifiedCards(); + const QMap modifiedSetsAndCardsMap = getModifiedCards(); for (QString modifiedSet : modifiedSetsAndCardsMap.keys()) { for (QString card : modifiedSetsAndCardsMap.value(modifiedSet)) { QModelIndex find_card = model->findCard(card, DECK_ZONE_MAIN); @@ -205,13 +205,13 @@ QMap DlgSelectSetForCards::getSetsForCards() if (!model) return setCounts; - DeckList *decklist = model->getDeckList(); + const DeckList *decklist = model->getDeckList(); if (!decklist) return setCounts; QList cardsInDeck = decklist->getCardNodes(); - for (auto currentCard : cardsInDeck) { + for (const auto currentCard : cardsInDeck) { CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); if (!infoPtr) continue; @@ -248,13 +248,13 @@ void DlgSelectSetForCards::updateCardLists() } } - DeckList *decklist = model->getDeckList(); + const DeckList *decklist = model->getDeckList(); if (!decklist) return; QList cardsInDeck = decklist->getCardNodes(); - for (auto currentCard : cardsInDeck) { + for (const auto currentCard : cardsInDeck) { bool found = false; QString foundSetName; @@ -298,16 +298,16 @@ void DlgSelectSetForCards::dragEnterEvent(QDragEnterEvent *event) void DlgSelectSetForCards::dropEvent(QDropEvent *event) { - QByteArray itemData = event->mimeData()->data("application/x-setentrywidget"); - QString draggedSetName = QString::fromUtf8(itemData); + const QByteArray itemData = event->mimeData()->data("application/x-setentrywidget"); + const QString draggedSetName = QString::fromUtf8(itemData); #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) - QPoint adjustedPos = event->position().toPoint() + QPoint(0, scrollArea->verticalScrollBar()->value()); + const QPoint adjustedPos = event->position().toPoint() + QPoint(0, scrollArea->verticalScrollBar()->value()); #else QPoint adjustedPos = event->pos() + QPoint(0, scrollArea->verticalScrollBar()->value()); #endif int dropIndex = -1; for (int i = 0; i < listLayout->count(); ++i) { - QWidget *widget = listLayout->itemAt(i)->widget(); + const QWidget *widget = listLayout->itemAt(i)->widget(); if (widget && widget->geometry().contains(adjustedPos)) { dropIndex = i; break; @@ -337,13 +337,13 @@ QMap DlgSelectSetForCards::getCardsForSets() if (!model) return setCards; - DeckList *decklist = model->getDeckList(); + const DeckList *decklist = model->getDeckList(); if (!decklist) return setCards; QList cardsInDeck = decklist->getCardNodes(); - for (auto currentCard : cardsInDeck) { + for (const auto currentCard : cardsInDeck) { CardInfoPtr infoPtr = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); if (!infoPtr) continue; @@ -362,7 +362,7 @@ QMap DlgSelectSetForCards::getModifiedCards() QMap modifiedCards; for (int i = 0; i < listLayout->count(); ++i) { QWidget *widget = listLayout->itemAt(i)->widget(); - if (auto entry = qobject_cast(widget)) { + if (const auto entry = qobject_cast(widget)) { if (entry->isChecked()) { QStringList cardsInSet = entry->getAllCardsForSet(); @@ -388,7 +388,7 @@ void DlgSelectSetForCards::updateLayoutOrder() entry_widgets.clear(); for (int i = 0; i < listLayout->count(); ++i) { QWidget *widget = listLayout->itemAt(i)->widget(); - if (auto entry = qobject_cast(widget)) { + if (const auto entry = qobject_cast(widget)) { entry_widgets.append(entry); } } @@ -403,7 +403,7 @@ SetEntryWidget::SetEntryWidget(DlgSelectSetForCards *_parent, const QString &_se setLayout(layout); QHBoxLayout *headerLayout = new QHBoxLayout(); - CardSetPtr set = CardDatabaseManager::getInstance()->getSet(setName); + const CardSetPtr set = CardDatabaseManager::getInstance()->getSet(setName); checkBox = new QCheckBox("(" + set->getShortName() + ") - " + set->getLongName(), this); connect(checkBox, &QCheckBox::toggled, parent, &DlgSelectSetForCards::updateLayoutOrder); expandButton = new QPushButton("+", this); @@ -510,7 +510,7 @@ void SetEntryWidget::dragMoveEvent(QDragMoveEvent *event) // For now, we will just highlight the widget when dragged. QPainter painter(this); - QColor highlightColor(255, 255, 255, 128); // Semi-transparent white + const QColor highlightColor(255, 255, 255, 128); // Semi-transparent white painter.setBrush(QBrush(highlightColor)); painter.setPen(Qt::NoPen); painter.drawRect(this->rect()); // Highlight the widget area @@ -594,14 +594,16 @@ void SetEntryWidget::updateCardDisplayWidgets() for (const QString &cardName : possibleCards) { CardInfoPictureWidget *picture_widget = new CardInfoPictureWidget(cardListContainer); - QString providerId = CardDatabaseManager::query()->getSpecificPrinting(cardName, setName, nullptr).getUuid(); + const QString providerId = + CardDatabaseManager::query()->getSpecificPrinting(cardName, setName, nullptr).getUuid(); picture_widget->setCard(CardDatabaseManager::query()->getCard({cardName, providerId})); cardListContainer->addWidget(picture_widget); } for (const QString &cardName : unusedCards) { CardInfoPictureWidget *picture_widget = new CardInfoPictureWidget(alreadySelectedCardListContainer); - QString providerId = CardDatabaseManager::query()->getSpecificPrinting(cardName, setName, nullptr).getUuid(); + const QString providerId = + CardDatabaseManager::query()->getSpecificPrinting(cardName, setName, nullptr).getUuid(); picture_widget->setCard(CardDatabaseManager::query()->getCard({cardName, providerId})); alreadySelectedCardListContainer->addWidget(picture_widget); } diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp index e92593d55..405512f62 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp @@ -68,8 +68,8 @@ GeneralSettingsPage::GeneralSettingsPage() languageBox.addItem(langName, code); } - QString setLanguage = QCoreApplication::translate("i18n", DEFAULT_LANG_NAME); - int index = languageBox.findText(setLanguage, Qt::MatchExactly); + const QString setLanguage = QCoreApplication::translate("i18n", DEFAULT_LANG_NAME); + const int index = languageBox.findText(setLanguage, Qt::MatchExactly); if (index == -1) { qWarning() << "could not find language" << setLanguage; } else { @@ -77,7 +77,7 @@ GeneralSettingsPage::GeneralSettingsPage() } // updates - SettingsCache &settings = SettingsCache::instance(); + const SettingsCache &settings = SettingsCache::instance(); startupUpdateCheckCheckBox.setChecked(settings.getCheckUpdatesOnStartup()); startupCardUpdateCheckBehaviorSelector.addItem(""); // these will be set in retranslateUI @@ -178,7 +178,7 @@ GeneralSettingsPage::GeneralSettingsPage() // Required init here to avoid crashing on Portable builds resetAllPathsButton = new QPushButton; - bool isPortable = settings.getIsPortableBuild(); + const bool isPortable = settings.getIsPortableBuild(); if (isPortable) { deckPathEdit->setEnabled(false); filtersPathEdit->setEnabled(false); @@ -249,7 +249,7 @@ GeneralSettingsPage::GeneralSettingsPage() QStringList GeneralSettingsPage::findQmFiles() { - QDir dir(translationPath); + const QDir dir(translationPath); QStringList fileNames = dir.entryList(QStringList(translationPrefix + "_*.qm"), QDir::Files, QDir::Name); fileNames.replaceInStrings(QRegularExpression(translationPrefix + "_(.*)\\.qm"), "\\1"); return fileNames; @@ -259,8 +259,8 @@ QString GeneralSettingsPage::languageName(const QString &lang) { QTranslator qTranslator; - QString appNameHint = translationPrefix + "_" + lang; - bool appTranslationLoaded = qTranslator.load(appNameHint, translationPath); + const QString appNameHint = translationPrefix + "_" + lang; + const bool appTranslationLoaded = qTranslator.load(appNameHint, translationPath); if (!appTranslationLoaded) { qCWarning(DlgSettingsLog) << "Unable to load" << translationPrefix << "translation" << appNameHint << "at" << translationPath; @@ -271,7 +271,7 @@ QString GeneralSettingsPage::languageName(const QString &lang) void GeneralSettingsPage::deckPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), deckPathEdit->text()); + const QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), deckPathEdit->text()); if (path.isEmpty()) return; @@ -281,7 +281,7 @@ void GeneralSettingsPage::deckPathButtonClicked() void GeneralSettingsPage::filtersPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), filtersPathEdit->text()); + const QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), filtersPathEdit->text()); if (path.isEmpty()) return; @@ -291,7 +291,7 @@ void GeneralSettingsPage::filtersPathButtonClicked() void GeneralSettingsPage::replaysPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), replaysPathEdit->text()); + const QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), replaysPathEdit->text()); if (path.isEmpty()) return; @@ -301,7 +301,7 @@ void GeneralSettingsPage::replaysPathButtonClicked() void GeneralSettingsPage::picsPathButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), picsPathEdit->text()); + const QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), picsPathEdit->text()); if (path.isEmpty()) return; @@ -311,7 +311,7 @@ void GeneralSettingsPage::picsPathButtonClicked() void GeneralSettingsPage::cardDatabasePathButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), cardDatabasePathEdit->text()); + const QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), cardDatabasePathEdit->text()); if (path.isEmpty()) return; @@ -321,7 +321,7 @@ void GeneralSettingsPage::cardDatabasePathButtonClicked() void GeneralSettingsPage::customCardDatabaseButtonClicked() { - QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), customCardDatabasePathEdit->text()); + const QString path = QFileDialog::getExistingDirectory(this, tr("Choose path"), customCardDatabasePathEdit->text()); if (path.isEmpty()) return; @@ -331,7 +331,7 @@ void GeneralSettingsPage::customCardDatabaseButtonClicked() void GeneralSettingsPage::tokenDatabasePathButtonClicked() { - QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), tokenDatabasePathEdit->text()); + const QString path = QFileDialog::getOpenFileName(this, tr("Choose path"), tokenDatabasePathEdit->text()); if (path.isEmpty()) return; @@ -393,16 +393,16 @@ void GeneralSettingsPage::retranslateUi() const auto &settings = SettingsCache::instance(); - QDate lastCheckDate = settings.getLastCardUpdateCheck(); - int daysAgo = lastCheckDate.daysTo(QDate::currentDate()); + const QDate lastCheckDate = settings.getLastCardUpdateCheck(); + const int daysAgo = lastCheckDate.daysTo(QDate::currentDate()); lastCardUpdateCheckDateLabel.setText( tr("Last update check on %1 (%2 days ago)").arg(lastCheckDate.toString()).arg(daysAgo)); // We can't change the strings after they're put into the QComboBox, so this is our workaround - int oldIndex = updateReleaseChannelBox.currentIndex(); + const int oldIndex = updateReleaseChannelBox.currentIndex(); updateReleaseChannelBox.clear(); - for (ReleaseChannel *chan : settings.getUpdateReleaseChannels()) { + for (const ReleaseChannel *chan : settings.getUpdateReleaseChannels()) { updateReleaseChannelBox.addItem(tr(chan->getName().toUtf8())); } updateReleaseChannelBox.setCurrentIndex(oldIndex); @@ -410,10 +410,10 @@ void GeneralSettingsPage::retranslateUi() AppearanceSettingsPage::AppearanceSettingsPage() { - SettingsCache &settings = SettingsCache::instance(); + const SettingsCache &settings = SettingsCache::instance(); // Theme settings - QString themeName = SettingsCache::instance().getThemeName(); + const QString themeName = SettingsCache::instance().getThemeName(); QStringList themeDirs = themeManager->getAvailableThemes().keys(); for (int i = 0; i < themeDirs.size(); i++) { @@ -429,15 +429,15 @@ AppearanceSettingsPage::AppearanceSettingsPage() homeTabBackgroundSourceBox.addItem(QObject::tr(entry.trKey), QVariant::fromValue(entry.type)); } - QString homeTabBackgroundSource = SettingsCache::instance().getHomeTabBackgroundSource(); - int homeTabBackgroundSourceId = + const QString homeTabBackgroundSource = SettingsCache::instance().getHomeTabBackgroundSource(); + const int homeTabBackgroundSourceId = homeTabBackgroundSourceBox.findData(BackgroundSources::fromId(homeTabBackgroundSource)); if (homeTabBackgroundSourceId != -1) { homeTabBackgroundSourceBox.setCurrentIndex(homeTabBackgroundSourceId); } connect(&homeTabBackgroundSourceBox, QOverload::of(&QComboBox::currentIndexChanged), this, [this]() { - auto type = homeTabBackgroundSourceBox.currentData().value(); + const auto type = homeTabBackgroundSourceBox.currentData().value(); SettingsCache::instance().setHomeTabBackgroundSource(BackgroundSources::toId(type)); }); @@ -545,7 +545,7 @@ AppearanceSettingsPage::AppearanceSettingsPage() connect(pushButton, &QPushButton::clicked, this, [index, this]() { auto &cardCounterSettings = SettingsCache::instance().cardCounters(); - auto newColor = QColorDialog::getColor(cardCounterSettings.color(index), this); + const auto newColor = QColorDialog::getColor(cardCounterSettings.color(index), this); if (!newColor.isValid()) return; @@ -555,8 +555,8 @@ AppearanceSettingsPage::AppearanceSettingsPage() auto *colorName = new QLabel; cardCounterNames.append(colorName); - int row = index / 3; - int column = 2 * (index % 3); + const int row = index / 3; + const int column = 2 * (index % 3); cardCounterColorsLayout->addWidget(pushButton, row, column); cardCounterColorsLayout->addWidget(colorName, row, column + 1); @@ -628,14 +628,14 @@ AppearanceSettingsPage::AppearanceSettingsPage() void AppearanceSettingsPage::themeBoxChanged(int index) { - QStringList themeDirs = themeManager->getAvailableThemes().keys(); + const QStringList themeDirs = themeManager->getAvailableThemes().keys(); if (index >= 0 && index < themeDirs.count()) SettingsCache::instance().setThemeName(themeDirs.at(index)); } void AppearanceSettingsPage::openThemeLocation() { - QString dir = SettingsCache::instance().getThemesPath(); + const QString dir = SettingsCache::instance().getThemesPath(); QDir dirDir = dir; dirDir.cdUp(); // open if dir exists, create if parent dir does exist @@ -673,7 +673,7 @@ void AppearanceSettingsPage::overrideAllCardArtWithPersonalPreferenceToggled(QT_ "Are you sure you would like to disable this feature?"); } - QMessageBox::StandardButton result = + const QMessageBox::StandardButton result = QMessageBox::question(this, tr("Confirm Change"), message, QMessageBox::Yes | QMessageBox::No); if (result == QMessageBox::Yes) { @@ -747,7 +747,7 @@ void AppearanceSettingsPage::retranslateUi() cardCountersGroupBox->setTitle(tr("Card counters")); - auto &cardCounterSettings = SettingsCache::instance().cardCounters(); + const auto &cardCounterSettings = SettingsCache::instance().cardCounters(); for (int index = 0; index < cardCounterNames.size(); ++index) { cardCounterNames[index]->setText(tr("Counter %1").arg(cardCounterSettings.displayName(index))); } @@ -1059,17 +1059,17 @@ DeckEditorSettingsPage::DeckEditorSettingsPage() networkRedirectCacheTtlEdit.setSingleStep(1); networkRedirectCacheTtlEdit.setValue(SettingsCache::instance().getRedirectCacheTtl()); - auto networkCacheLayout = new QHBoxLayout; + const auto networkCacheLayout = new QHBoxLayout; networkCacheLayout->addStretch(); networkCacheLayout->addWidget(&networkCacheLabel); networkCacheLayout->addWidget(&networkCacheEdit); - auto networkRedirectCacheLayout = new QHBoxLayout; + const auto networkRedirectCacheLayout = new QHBoxLayout; networkRedirectCacheLayout->addStretch(); networkRedirectCacheLayout->addWidget(&networkRedirectCacheTtlLabel); networkRedirectCacheLayout->addWidget(&networkRedirectCacheTtlEdit); - auto pixmapCacheLayout = new QHBoxLayout; + const auto pixmapCacheLayout = new QHBoxLayout; pixmapCacheLayout->addStretch(); pixmapCacheLayout->addWidget(&pixmapCacheLabel); pixmapCacheLayout->addWidget(&pixmapCacheEdit); @@ -1135,7 +1135,7 @@ void DeckEditorSettingsPage::clearDownloadedPicsButtonClicked() // These are not used anymore, but we don't delete them automatically, so // we should do it here lest we leave pictures hanging around on users' // machines. - QString picsPath = SettingsCache::instance().getPicsPath() + "/downloadedPics/"; + const QString picsPath = SettingsCache::instance().getPicsPath() + "/downloadedPics/"; QStringList dirs = QDir(picsPath).entryList(QDir::AllDirs | QDir::NoDotAndDotDot); bool outerSuccessRemove = true; for (const auto &dir : dirs) { @@ -1152,7 +1152,7 @@ void DeckEditorSettingsPage::clearDownloadedPicsButtonClicked() } if (innerSuccessRemove) { - bool success = QDir(picsPath).rmdir(dir); + const bool success = QDir(picsPath).rmdir(dir); if (!success) { qInfo() << "Failed to remove inner directory" << picsPath; } else { @@ -1171,7 +1171,7 @@ void DeckEditorSettingsPage::clearDownloadedPicsButtonClicked() void DeckEditorSettingsPage::actAddURL() { bool ok; - QString msg = QInputDialog::getText(this, tr("Add URL"), tr("URL:"), QLineEdit::Normal, QString(), &ok); + const QString msg = QInputDialog::getText(this, tr("Add URL"), tr("URL:"), QLineEdit::Normal, QString(), &ok); if (ok) { urlList->addItem(msg); storeSettings(); @@ -1189,9 +1189,9 @@ void DeckEditorSettingsPage::actRemoveURL() void DeckEditorSettingsPage::actEditURL() { if (urlList->currentItem()) { - QString oldText = urlList->currentItem()->text(); + const QString oldText = urlList->currentItem()->text(); bool ok; - QString msg = QInputDialog::getText(this, tr("Edit URL"), tr("URL:"), QLineEdit::Normal, oldText, &ok); + const QString msg = QInputDialog::getText(this, tr("Edit URL"), tr("URL:"), QLineEdit::Normal, oldText, &ok); if (ok) { urlList->currentItem()->setText(msg); storeSettings(); @@ -1223,7 +1223,7 @@ void DeckEditorSettingsPage::updateSpoilers() updateNowButton->setText(tr("Updating...")); // Create a new SBU that will act as if the client was just reloaded - auto *sbu = new SpoilerBackgroundUpdater(); + const auto *sbu = new SpoilerBackgroundUpdater(); connect(sbu, &SpoilerBackgroundUpdater::spoilerCheckerDone, this, &DeckEditorSettingsPage::unlockSettings); connect(sbu, &SpoilerBackgroundUpdater::spoilersUpdatedSuccessfully, this, &DeckEditorSettingsPage::unlockSettings); } @@ -1236,10 +1236,10 @@ void DeckEditorSettingsPage::unlockSettings() QString DeckEditorSettingsPage::getLastUpdateTime() { - QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath(); - QFileInfo fi(fileName); + const QString fileName = SettingsCache::instance().getSpoilerCardDatabasePath(); + const QFileInfo fi(fileName); QDir fileDir(fi.path()); - QFile file(fileName); + const QFile file(fileName); if (file.exists()) { return fi.lastModified().toString("MMM d, hh:mm"); @@ -1250,7 +1250,8 @@ QString DeckEditorSettingsPage::getLastUpdateTime() void DeckEditorSettingsPage::spoilerPathButtonClicked() { - QString lsPath = QFileDialog::getExistingDirectory(this, tr("Choose path"), mpSpoilerSavePathLineEdit->text()); + const QString lsPath = + QFileDialog::getExistingDirectory(this, tr("Choose path"), mpSpoilerSavePathLineEdit->text()); if (lsPath.isEmpty()) { return; } @@ -1378,7 +1379,7 @@ MessagesSettingsPage::MessagesSettingsPage() messageList = new QListWidget; - int count = SettingsCache::instance().messages().getCount(); + const int count = SettingsCache::instance().messages().getCount(); for (int i = 0; i < count; i++) messageList->addItem(SettingsCache::instance().messages().getMessageAt(i)); @@ -1426,7 +1427,7 @@ MessagesSettingsPage::MessagesSettingsPage() void MessagesSettingsPage::updateColor(const QString &value) { #if (QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)) - QColor colorToSet = QColor::fromString("#" + value); + const QColor colorToSet = QColor::fromString("#" + value); #else QColor colorToSet; colorToSet.setNamedColor("#" + value); @@ -1440,7 +1441,7 @@ void MessagesSettingsPage::updateColor(const QString &value) void MessagesSettingsPage::updateHighlightColor(const QString &value) { #if (QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)) - QColor colorToSet = QColor::fromString("#" + value); + const QColor colorToSet = QColor::fromString("#" + value); #else QColor colorToSet; colorToSet.setNamedColor("#" + value); @@ -1488,7 +1489,7 @@ void MessagesSettingsPage::storeSettings() void MessagesSettingsPage::actAdd() { bool ok; - QString msg = + const QString msg = getTextWithMax(this, tr("Add message"), tr("Message:"), QLineEdit::Normal, QString(), &ok, MAX_TEXT_LENGTH); if (ok) { messageList->addItem(msg); @@ -1499,9 +1500,9 @@ void MessagesSettingsPage::actAdd() void MessagesSettingsPage::actEdit() { if (messageList->currentItem()) { - QString oldText = messageList->currentItem()->text(); + const QString oldText = messageList->currentItem()->text(); bool ok; - QString msg = + const QString msg = getTextWithMax(this, tr("Edit message"), tr("Message:"), QLineEdit::Normal, oldText, &ok, MAX_TEXT_LENGTH); if (ok) { messageList->currentItem()->setText(msg); @@ -1549,7 +1550,7 @@ SoundSettingsPage::SoundSettingsPage() connect(&soundEnabledCheckBox, &QCheckBox::QT_STATE_CHANGED, &SettingsCache::instance(), &SettingsCache::setSoundEnabled); - QString themeName = SettingsCache::instance().getSoundThemeName(); + const QString themeName = SettingsCache::instance().getSoundThemeName(); QStringList themeDirs = soundEngine->getAvailableThemes().keys(); for (int i = 0; i < themeDirs.size(); i++) { @@ -1602,7 +1603,7 @@ SoundSettingsPage::SoundSettingsPage() void SoundSettingsPage::themeBoxChanged(int index) { - QStringList themeDirs = soundEngine->getAvailableThemes().keys(); + const QStringList themeDirs = soundEngine->getAvailableThemes().keys(); if (index >= 0 && index < themeDirs.count()) SettingsCache::instance().setSoundThemeName(themeDirs.at(index)); } @@ -1702,8 +1703,8 @@ void ShortcutSettingsPage::currentItemChanged(const QString &key) currentActionName->setText(""); editTextBox->setShortcutName(""); } else { - QString group = SettingsCache::instance().shortcuts().getShortcut(key).getGroupName(); - QString action = SettingsCache::instance().shortcuts().getShortcut(key).getName(); + const QString group = SettingsCache::instance().shortcuts().getShortcut(key).getGroupName(); + const QString action = SettingsCache::instance().shortcuts().getShortcut(key).getName(); currentActionGroupName->setText(group); currentActionName->setText(action); editTextBox->setShortcutName(key); @@ -1755,7 +1756,7 @@ static QScrollArea *makeScrollable(QWidget *widget) DlgSettings::DlgSettings(QWidget *parent) : QDialog(parent) { - auto rec = QGuiApplication::primaryScreen()->availableGeometry(); + const auto rec = QGuiApplication::primaryScreen()->availableGeometry(); this->setMinimumSize(qMin(700, rec.width()), qMin(700, rec.height())); connect(&SettingsCache::instance(), &SettingsCache::langChanged, this, &DlgSettings::updateLanguage); @@ -1865,7 +1866,7 @@ void DlgSettings::closeEvent(QCloseEvent *event) { bool showLoadError = true; QString loadErrorMessage = tr("Unknown Error loading card database"); - LoadStatus loadStatus = CardDatabaseManager::getInstance()->getLoadStatus(); + const LoadStatus loadStatus = CardDatabaseManager::getInstance()->getLoadStatus(); qCInfo(DlgSettingsLog) << "Card Database load status: " << loadStatus; switch (loadStatus) { case Ok: diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_startup_card_check.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_startup_card_check.cpp index ac1922a9d..40abb7fb1 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_startup_card_check.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_startup_card_check.cpp @@ -10,8 +10,8 @@ DlgStartupCardCheck::DlgStartupCardCheck(QWidget *parent) : QDialog(parent) layout = new QVBoxLayout(this); - QDate lastCheckDate = SettingsCache::instance().getLastCardUpdateCheck(); - int daysAgo = lastCheckDate.daysTo(QDate::currentDate()); + const QDate lastCheckDate = SettingsCache::instance().getLastCardUpdateCheck(); + const int daysAgo = lastCheckDate.daysTo(QDate::currentDate()); instructionLabel = new QLabel( tr("It has been more than %2 days since you last checked your card database for updates.\nChoose how you would " diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_tip_of_the_day.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_tip_of_the_day.cpp index 0197d3dbf..9f6005933 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_tip_of_the_day.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_tip_of_the_day.cpp @@ -19,7 +19,7 @@ DlgTipOfTheDay::DlgTipOfTheDay(QWidget *parent) : QDialog(parent) { successfulInit = false; - QString xmlPath = "theme:tips/tips_of_the_day.xml"; + const QString xmlPath = "theme:tips/tips_of_the_day.xml"; tipDatabase = new TipsOfTheDay(xmlPath, this); if (tipDatabase->rowCount() == 0) { @@ -42,7 +42,7 @@ DlgTipOfTheDay::DlgTipOfTheDay(QWidget *parent) : QDialog(parent) tipNumber = new QLabel(); tipNumber->setAlignment(Qt::AlignCenter); - QList seenTips = SettingsCache::instance().getSeenTips(); + const QList seenTips = SettingsCache::instance().getSeenTips(); newTipsAvailable = false; currentTip = 0; for (int i = 0; i < tipDatabase->rowCount(); i++) { @@ -137,7 +137,7 @@ void DlgTipOfTheDay::updateTip(int tipId) SettingsCache::instance().setSeenTips(seenTips); } - TipOfTheDay tip = tipDatabase->getTip(tipId); + const TipOfTheDay tip = tipDatabase->getTip(tipId); titleText = tip.getTitle(); contentText = tip.getContent(); imagePath = tip.getImagePath(); @@ -150,8 +150,8 @@ void DlgTipOfTheDay::updateTip(int tipId) qCWarning(DlgTipOfTheDayLog) << "Image failed to load from" << imagePath; imageLabel->clear(); } else { - int h = std::min(std::max(imageLabel->height(), MIN_TIP_IMAGE_HEIGHT), MAX_TIP_IMAGE_HEIGHT); - int w = std::min(std::max(imageLabel->width(), MIN_TIP_IMAGE_WIDTH), MAX_TIP_IMAGE_WIDTH); + const int h = std::min(std::max(imageLabel->height(), MIN_TIP_IMAGE_HEIGHT), MAX_TIP_IMAGE_HEIGHT); + const int w = std::min(std::max(imageLabel->width(), MIN_TIP_IMAGE_WIDTH), MAX_TIP_IMAGE_WIDTH); imageLabel->setPixmap(image->scaled(w, h, Qt::KeepAspectRatio, Qt::SmoothTransformation)); } diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_update.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_update.cpp index 19182c55b..c4ae147a3 100644 --- a/cockatrice/src/interface/widgets/dialogs/dlg_update.cpp +++ b/cockatrice/src/interface/widgets/dialogs/dlg_update.cpp @@ -108,7 +108,7 @@ void DlgUpdate::beginUpdateCheck() progress->setMaximum(0); setLabel(tr("Checking for updates...")); - auto checker = new ClientUpdateChecker(this); + const auto checker = new ClientUpdateChecker(this); connect(checker, &ClientUpdateChecker::finishedCheck, this, &DlgUpdate::finishedUpdateCheck); connect(checker, &ClientUpdateChecker::error, this, &DlgUpdate::updateCheckError); checker->check(); diff --git a/cockatrice/src/interface/widgets/dialogs/tip_of_the_day.cpp b/cockatrice/src/interface/widgets/dialogs/tip_of_the_day.cpp index 94996e975..9289a4cdc 100644 --- a/cockatrice/src/interface/widgets/dialogs/tip_of_the_day.cpp +++ b/cockatrice/src/interface/widgets/dialogs/tip_of_the_day.cpp @@ -76,7 +76,7 @@ QVariant TipsOfTheDay::data(const QModelIndex &index, int /*role*/) const if (!index.isValid() || index.row() >= tipList->size() || index.column() >= TIPDDBMODEL_COLUMNS) return QVariant(); - TipOfTheDay tip = tipList->at(index.row()); + const TipOfTheDay tip = tipList->at(index.row()); switch (index.column()) { case TitleColumn: return tip.getTitle(); diff --git a/cockatrice/src/interface/widgets/general/display/banner_widget.cpp b/cockatrice/src/interface/widgets/general/display/banner_widget.cpp index f03869a4d..beef0c80b 100644 --- a/cockatrice/src/interface/widgets/general/display/banner_widget.cpp +++ b/cockatrice/src/interface/widgets/general/display/banner_widget.cpp @@ -10,7 +10,7 @@ BannerWidget::BannerWidget(QWidget *parent, const QString &text, Qt::Orientation orientation, int transparency) : QWidget(parent), gradientOrientation(orientation), transparency(qBound(0, transparency, 100)) { - auto layout = new QHBoxLayout(this); + const auto layout = new QHBoxLayout(this); iconLabel = new QLabel(this); iconLabel->setAlignment(Qt::AlignLeft | Qt::AlignVCenter); @@ -82,7 +82,7 @@ void BannerWidget::paintEvent(QPaintEvent *event) QPainter painter(this); // Calculate alpha based on transparency percentage - int alpha = (255 * transparency) / 100; + const int alpha = (255 * transparency) / 100; // Determine gradient direction QLinearGradient gradient; diff --git a/cockatrice/src/interface/widgets/general/display/bar_widget.cpp b/cockatrice/src/interface/widgets/general/display/bar_widget.cpp index 2194b6b03..6f37c1424 100644 --- a/cockatrice/src/interface/widgets/general/display/bar_widget.cpp +++ b/cockatrice/src/interface/widgets/general/display/bar_widget.cpp @@ -11,14 +11,14 @@ BarWidget::BarWidget(QString label, int value, int total, QColor barColor, QWidg QSize BarWidget::sizeHint() const { - QFontMetrics metrics(font()); - int labelHeight = metrics.height(); - int valueHeight = metrics.height(); + const QFontMetrics metrics(font()); + const int labelHeight = metrics.height(); + const int valueHeight = metrics.height(); // Calculate the height dynamically based on the total - int barHeight = (total > 0) ? (value * 200 / total) : 20; // Scale height proportionally - int totalHeight = barHeight + labelHeight + valueHeight + 30; // Extra space for text - return QSize(60, totalHeight); // Allow width to expand + const int barHeight = (total > 0) ? (value * 200 / total) : 20; // Scale height proportionally + const int totalHeight = barHeight + labelHeight + valueHeight + 30; // Extra space for text + return QSize(60, totalHeight); // Allow width to expand } void BarWidget::paintEvent(QPaintEvent *event) @@ -26,13 +26,13 @@ void BarWidget::paintEvent(QPaintEvent *event) QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); - int widgetWidth = width(); - int widgetHeight = height(); + const int widgetWidth = width(); + const int widgetHeight = height(); // Calculate bar dimensions - int barWidth = widgetWidth * 0.8; // Use 80% of the available width - int fullBarHeight = widgetHeight - 40; // Leave space for labels - int valueBarHeight = (total > 0) ? (value * fullBarHeight / total) : 0; + const int barWidth = widgetWidth * 0.8; // Use 80% of the available width + const int fullBarHeight = widgetHeight - 40; // Leave space for labels + const int valueBarHeight = (total > 0) ? (value * fullBarHeight / total) : 0; // Draw full bar background (gray) painter.setBrush(QColor(200, 200, 200)); @@ -44,12 +44,12 @@ void BarWidget::paintEvent(QPaintEvent *event) // Draw the CMC label painter.setPen(Qt::white); - QRect textRect(0, widgetHeight - 30, widgetWidth, 20); + const QRect textRect(0, widgetHeight - 30, widgetWidth, 20); painter.drawText(textRect, Qt::AlignCenter, label); // Draw the value count painter.setPen(Qt::black); - QRect valueRect(0, 10, widgetWidth, 20); + const QRect valueRect(0, 10, widgetWidth, 20); painter.drawText(valueRect, Qt::AlignCenter, QString::number(value)); (void)event; // Suppress unused parameter warning diff --git a/cockatrice/src/interface/widgets/general/display/dynamic_font_size_label.cpp b/cockatrice/src/interface/widgets/general/display/dynamic_font_size_label.cpp index ed4db1fd3..f76e0ed45 100644 --- a/cockatrice/src/interface/widgets/general/display/dynamic_font_size_label.cpp +++ b/cockatrice/src/interface/widgets/general/display/dynamic_font_size_label.cpp @@ -21,7 +21,7 @@ void DynamicFontSizeLabel::paintEvent(QPaintEvent *event) // timer.start(); QFont newFont = font(); - float fontSize = getWidgetMaximumFontSize(this, this->text()); + const float fontSize = getWidgetMaximumFontSize(this, this->text()); newFont.setPointSizeF(fontSize); setFont(newFont); // qDebug() << "Font size set to" << fontSize; @@ -70,7 +70,7 @@ float DynamicFontSizeLabel::getWidgetMaximumFontSize(QWidget *widget, const QStr QFontMetricsF fm(font); /* Check if widget is QLabel */ - QLabel *label = qobject_cast(widget); + const QLabel *label = qobject_cast(widget); if (label) { newFontSizeRect = fm.boundingRect(widgetRect, (label->wordWrap() ? Qt::TextWordWrap : 0) | label->alignment(), text); diff --git a/cockatrice/src/interface/widgets/general/display/dynamic_font_size_push_button.cpp b/cockatrice/src/interface/widgets/general/display/dynamic_font_size_push_button.cpp index fce4512e8..d80af10b1 100644 --- a/cockatrice/src/interface/widgets/general/display/dynamic_font_size_push_button.cpp +++ b/cockatrice/src/interface/widgets/general/display/dynamic_font_size_push_button.cpp @@ -16,7 +16,7 @@ void DynamicFontSizePushButton::paintEvent(QPaintEvent *event) // Adjust the font size dynamically based on the text QFont newFont = font(); - float fontSize = DynamicFontSizeLabel::getWidgetMaximumFontSize(this, this->text()); + const float fontSize = DynamicFontSizeLabel::getWidgetMaximumFontSize(this, this->text()); newFont.setPointSizeF(fontSize); setFont(newFont); diff --git a/cockatrice/src/interface/widgets/general/display/percent_bar_widget.cpp b/cockatrice/src/interface/widgets/general/display/percent_bar_widget.cpp index 3726dd061..5d6db211c 100644 --- a/cockatrice/src/interface/widgets/general/display/percent_bar_widget.cpp +++ b/cockatrice/src/interface/widgets/general/display/percent_bar_widget.cpp @@ -10,7 +10,7 @@ void PercentBarWidget::paintEvent(QPaintEvent *event) Q_UNUSED(event); QPainter painter(this); - QRect rect = this->rect(); + const QRect rect = this->rect(); const int midX = rect.width() / 2; const int height = rect.height(); @@ -40,7 +40,7 @@ void PercentBarWidget::paintEvent(QPaintEvent *event) const int tickHeight = 4; for (int percent = -100; percent <= 100; percent += 10) { - int x = midX + static_cast((percent / 100.0) * halfWidth); + const int x = midX + static_cast((percent / 100.0) * halfWidth); painter.drawLine(x, height - tickHeight, x, height); } } diff --git a/cockatrice/src/interface/widgets/general/display/shadow_background_label.cpp b/cockatrice/src/interface/widgets/general/display/shadow_background_label.cpp index fbca8df8d..933ca1662 100644 --- a/cockatrice/src/interface/widgets/general/display/shadow_background_label.cpp +++ b/cockatrice/src/interface/widgets/general/display/shadow_background_label.cpp @@ -52,7 +52,7 @@ void ShadowBackgroundLabel::paintEvent(QPaintEvent *event) // Adjust the rectangle to account for margins. QRect adjustedRect = this->rect(); - int margin = contentsMargins().left(); // Assuming equal margins. + const int margin = contentsMargins().left(); // Assuming equal margins. adjustedRect.adjust(margin, margin, -margin, -margin); // Draw a rounded rectangle with a corner radius of 5. diff --git a/cockatrice/src/interface/widgets/general/home_styled_button.cpp b/cockatrice/src/interface/widgets/general/home_styled_button.cpp index 07c9894c1..455dff220 100644 --- a/cockatrice/src/interface/widgets/general/home_styled_button.cpp +++ b/cockatrice/src/interface/widgets/general/home_styled_button.cpp @@ -92,9 +92,9 @@ void HomeStyledButton::paintEvent(QPaintEvent *event) font.setBold(true); painter.setFont(font); - QFontMetrics fm(font); - QSize textSize = fm.size(Qt::TextSingleLine, this->text()); - QPointF center((width() - textSize.width()) / 2.0, (height() + textSize.height() / 2.0) / 2.0); + const QFontMetrics fm(font); + const QSize textSize = fm.size(Qt::TextSingleLine, this->text()); + const QPointF center((width() - textSize.width()) / 2.0, (height() + textSize.height() / 2.0) / 2.0); QPainterPath path; path.addText(center, font, this->text()); diff --git a/cockatrice/src/interface/widgets/general/home_widget.cpp b/cockatrice/src/interface/widgets/general/home_widget.cpp index cbf53ee4f..ac7caf30e 100644 --- a/cockatrice/src/interface/widgets/general/home_widget.cpp +++ b/cockatrice/src/interface/widgets/general/home_widget.cpp @@ -57,7 +57,7 @@ void HomeWidget::initializeBackgroundFromSource() return; } - auto backgroundSourceType = BackgroundSources::fromId(SettingsCache::instance().getHomeTabBackgroundSource()); + const auto backgroundSourceType = BackgroundSources::fromId(SettingsCache::instance().getHomeTabBackgroundSource()); cardChangeTimer->stop(); @@ -80,7 +80,7 @@ void HomeWidget::initializeBackgroundFromSource() void HomeWidget::updateRandomCard() { - auto backgroundSourceType = BackgroundSources::fromId(SettingsCache::instance().getHomeTabBackgroundSource()); + const auto backgroundSourceType = BackgroundSources::fromId(SettingsCache::instance().getHomeTabBackgroundSource()); ExactCard newCard; @@ -95,7 +95,7 @@ void HomeWidget::updateRandomCard() break; case BackgroundSources::DeckFileArt: QList cardRefs = backgroundSourceDeck->getDeckList()->getCardRefList(); - ExactCard oldCard = backgroundSourceCard->getCard(); + const ExactCard oldCard = backgroundSourceCard->getCard(); if (!cardRefs.empty()) { if (cardRefs.size() == 1) { @@ -103,7 +103,7 @@ void HomeWidget::updateRandomCard() } else { // Keep picking until different do { - int idx = QRandomGenerator::global()->bounded(cardRefs.size()); + const int idx = QRandomGenerator::global()->bounded(cardRefs.size()); newCard = CardDatabaseManager::query()->getCard(cardRefs.at(idx)); } while (newCard == oldCard); } @@ -180,26 +180,26 @@ QGroupBox *HomeWidget::createButtons() connectButton = new HomeStyledButton("Connect/Play", gradientColors); boxLayout->addWidget(connectButton); - auto visualDeckEditorButton = new HomeStyledButton(tr("Create New Deck"), gradientColors); + const auto visualDeckEditorButton = new HomeStyledButton(tr("Create New Deck"), gradientColors); connect(visualDeckEditorButton, &QPushButton::clicked, tabSupervisor, [this] { tabSupervisor->openDeckInNewTab(nullptr); }); boxLayout->addWidget(visualDeckEditorButton); - auto visualDeckStorageButton = new HomeStyledButton(tr("Browse Decks"), gradientColors); + const auto visualDeckStorageButton = new HomeStyledButton(tr("Browse Decks"), gradientColors); connect(visualDeckStorageButton, &QPushButton::clicked, tabSupervisor, [this] { tabSupervisor->actTabVisualDeckStorage(true); }); boxLayout->addWidget(visualDeckStorageButton); - auto visualDatabaseDisplayButton = new HomeStyledButton(tr("Browse Card Database"), gradientColors); + const auto visualDatabaseDisplayButton = new HomeStyledButton(tr("Browse Card Database"), gradientColors); connect(visualDatabaseDisplayButton, &QPushButton::clicked, tabSupervisor, &TabSupervisor::addVisualDatabaseDisplayTab); boxLayout->addWidget(visualDatabaseDisplayButton); - auto edhrecButton = new HomeStyledButton(tr("Browse EDHRec"), gradientColors); + const auto edhrecButton = new HomeStyledButton(tr("Browse EDHRec"), gradientColors); connect(edhrecButton, &QPushButton::clicked, tabSupervisor, &TabSupervisor::addEdhrecMainTab); boxLayout->addWidget(edhrecButton); - auto replaybutton = new HomeStyledButton(tr("View Replays"), gradientColors); + const auto replaybutton = new HomeStyledButton(tr("View Replays"), gradientColors); connect(replaybutton, &QPushButton::clicked, tabSupervisor, [this] { tabSupervisor->actTabReplays(true); }); boxLayout->addWidget(replaybutton); if (qobject_cast(tabSupervisor->parentWidget())) { - auto exitButton = new HomeStyledButton(tr("Quit"), gradientColors); + const auto exitButton = new HomeStyledButton(tr("Quit"), gradientColors); connect(exitButton, &QPushButton::clicked, qobject_cast(tabSupervisor->parentWidget()), &MainWindow::actExit); boxLayout->addWidget(exitButton); @@ -294,18 +294,18 @@ void HomeWidget::paintEvent(QPaintEvent *event) background = background.scaled(size(), Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation); // Draw already-scaled background centered - QSize widgetSize = size(); - QSize bgSize = background.size(); - QPoint topLeft((widgetSize.width() - bgSize.width()) / 2, (widgetSize.height() - bgSize.height()) / 2); + const QSize widgetSize = size(); + const QSize bgSize = background.size(); + const QPoint topLeft((widgetSize.width() - bgSize.width()) / 2, (widgetSize.height() - bgSize.height()) / 2); painter.drawPixmap(topLeft, background); // Draw translucent black overlay with rounded corners - QRectF overlayRect(5, 5, width() - 10, height() - 10); // 5px inset + const QRectF overlayRect(5, 5, width() - 10, height() - 10); // 5px inset QPainterPath roundedRectPath; roundedRectPath.addRoundedRect(overlayRect, 20, 20); // 20px corner radius - QColor semiTransparentBlack(0, 0, 0, static_cast(255 * 0.33)); // 33% opacity + const QColor semiTransparentBlack(0, 0, 0, static_cast(255 * 0.33)); // 33% opacity painter.setRenderHint(QPainter::Antialiasing); painter.fillPath(roundedRectPath, semiTransparentBlack); diff --git a/cockatrice/src/interface/widgets/general/layout_containers/flow_widget.cpp b/cockatrice/src/interface/widgets/general/layout_containers/flow_widget.cpp index 75ab56b34..62a3e4939 100644 --- a/cockatrice/src/interface/widgets/general/layout_containers/flow_widget.cpp +++ b/cockatrice/src/interface/widgets/general/layout_containers/flow_widget.cpp @@ -155,8 +155,8 @@ void FlowWidget::setMinimumSizeToMaxSizeHint() // Iterate over all widgets in the flow layout to find the maximum sizeHint for (int i = 0; i < flowLayout->count(); ++i) { - if (QLayoutItem *item = flowLayout->itemAt(i)) { - if (QWidget *widget = item->widget()) { + if (const QLayoutItem *item = flowLayout->itemAt(i)) { + if (const QWidget *widget = item->widget()) { // Update the max size based on the sizeHint of each widget QSize widgetSizeHint = widget->sizeHint(); maxSize.setWidth(qMax(maxSize.width(), widgetSizeHint.width())); @@ -167,7 +167,7 @@ void FlowWidget::setMinimumSizeToMaxSizeHint() // Set the minimum size for all widgets to the max sizeHint for (int i = 0; i < flowLayout->count(); ++i) { - if (QLayoutItem *item = flowLayout->itemAt(i)) { + if (const QLayoutItem *item = flowLayout->itemAt(i)) { if (QWidget *widget = item->widget()) { widget->setMinimumSize(maxSize); } diff --git a/cockatrice/src/interface/widgets/menus/deck_editor_menu.cpp b/cockatrice/src/interface/widgets/menus/deck_editor_menu.cpp index 775efafbd..043baafb5 100644 --- a/cockatrice/src/interface/widgets/menus/deck_editor_menu.cpp +++ b/cockatrice/src/interface/widgets/menus/deck_editor_menu.cpp @@ -182,7 +182,7 @@ void DeckEditorMenu::retranslateUi() void DeckEditorMenu::refreshShortcuts() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aNewDeck->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aNewDeck")); aLoadDeck->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aLoadDeck")); aSaveDeck->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aSaveDeck")); diff --git a/cockatrice/src/interface/widgets/printing_selector/card_amount_widget.cpp b/cockatrice/src/interface/widgets/printing_selector/card_amount_widget.cpp index 416de18dc..e9fc31adf 100644 --- a/cockatrice/src/interface/widgets/printing_selector/card_amount_widget.cpp +++ b/cockatrice/src/interface/widgets/printing_selector/card_amount_widget.cpp @@ -89,8 +89,8 @@ void CardAmountWidget::showEvent(QShowEvent *event) updateCardCount(); if (parentWidget()) { - int width = parentWidget()->size().width(); - int height = parentWidget()->size().height(); + const int width = parentWidget()->size().width(); + const int height = parentWidget()->size().height(); incrementButton->setFixedSize(width / 3, height / 9); decrementButton->setFixedSize(width / 3, height / 9); @@ -145,10 +145,10 @@ void CardAmountWidget::addPrinting(const QString &zone) recursiveExpand(newCardIndex); // Check if a card without a providerId already exists in the deckModel and replace it, if so. - QModelIndex find_card = deckModel->findCard(rootCard.getName(), zone); - QString foundProviderId = deckModel->data(find_card.sibling(find_card.row(), 4), Qt::DisplayRole).toString(); + const QModelIndex find_card = deckModel->findCard(rootCard.getName(), zone); + const QString foundProviderId = deckModel->data(find_card.sibling(find_card.row(), 4), Qt::DisplayRole).toString(); if (find_card.isValid() && find_card != newCardIndex && foundProviderId == "") { - auto amount = deckModel->data(find_card, Qt::DisplayRole); + const auto amount = deckModel->data(find_card, Qt::DisplayRole); for (int i = 0; i < amount.toInt() - 1; i++) { deckModel->addCard(rootCard, zone); } @@ -239,8 +239,8 @@ void CardAmountWidget::offsetCountAtIndex(const QModelIndex &idx, int offset) */ void CardAmountWidget::decrementCardHelper(const QString &zone) { - QModelIndex idx = deckModel->findCard(rootCard.getName(), zone, rootCard.getPrinting().getUuid(), - rootCard.getPrinting().getProperty("num")); + const QModelIndex idx = deckModel->findCard(rootCard.getName(), zone, rootCard.getPrinting().getUuid(), + rootCard.getPrinting().getProperty("num")); offsetCountAtIndex(idx, -1); deckEditor->setModified(true); } @@ -261,7 +261,7 @@ int CardAmountWidget::countCardsInZone(const QString &deckZone) return -1; } - DeckList *decklist = deckModel->getDeckList(); + const DeckList *decklist = deckModel->getDeckList(); if (!decklist) { return -1; } @@ -269,7 +269,7 @@ int CardAmountWidget::countCardsInZone(const QString &deckZone) QList cardsInDeck = decklist->getCardNodes({deckZone}); int count = 0; - for (auto currentCard : cardsInDeck) { + for (const auto currentCard : cardsInDeck) { for (int k = 0; k < currentCard->getNumber(); ++k) { if (currentCard->getCardProviderId() == rootCard.getPrinting().getProperty("uuid")) { count++; diff --git a/cockatrice/src/interface/widgets/printing_selector/printing_selector.cpp b/cockatrice/src/interface/widgets/printing_selector/printing_selector.cpp index a551ac290..73a17b371 100644 --- a/cockatrice/src/interface/widgets/printing_selector/printing_selector.cpp +++ b/cockatrice/src/interface/widgets/printing_selector/printing_selector.cpp @@ -167,7 +167,7 @@ void PrintingSelector::selectCard(const int changeBy) } // Get the current index of the selected item - auto deckViewCurrentIndex = deckView->currentIndex(); + const auto deckViewCurrentIndex = deckView->currentIndex(); auto nextIndex = deckViewCurrentIndex.siblingAtRow(deckViewCurrentIndex.row() + changeBy); if (!nextIndex.isValid()) { @@ -200,7 +200,7 @@ void PrintingSelector::getAllSetsForCurrentCard() return; } - SetToPrintingsMap setMap = selectedCard->getSets(); + const SetToPrintingsMap setMap = selectedCard->getSets(); const QList sortedPrintings = sortToolBar->sortSets(setMap); const QList filteredPrintings = sortToolBar->filterSets(sortedPrintings, searchBar->getSearchText().trimmed().toLower()); diff --git a/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_display_widget.cpp b/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_display_widget.cpp index 0da80b522..c2aebbe1b 100644 --- a/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_display_widget.cpp +++ b/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_display_widget.cpp @@ -46,10 +46,10 @@ PrintingSelectorCardDisplayWidget::PrintingSelectorCardDisplayWidget(QWidget *pa connect(overlayWidget, &PrintingSelectorCardOverlayWidget::cardPreferenceChanged, this, [this]() { emit cardPreferenceChanged(); }); - CardSetPtr set = rootCard.getPrinting().getSet(); + const CardSetPtr set = rootCard.getPrinting().getSet(); // Create the widget to display the set name and collector's number - QString combinedSetName = QString(set->getLongName() + " (" + set->getShortName() + ")"); + const QString combinedSetName = QString(set->getLongName() + " (" + set->getShortName() + ")"); setNameAndCollectorsNumberDisplayWidget = new SetNameAndCollectorsNumberDisplayWidget( this, combinedSetName, rootCard.getPrinting().getProperty("num"), cardSizeSlider); diff --git a/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_overlay_widget.cpp b/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_overlay_widget.cpp index 5f3a44b30..f4b4aa077 100644 --- a/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_overlay_widget.cpp +++ b/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_overlay_widget.cpp @@ -168,8 +168,8 @@ void PrintingSelectorCardOverlayWidget::updatePinBadgeVisibility() if (isPinned) { // Keep a small margin that scales with the card size to avoid obscuring stuff. const int margin = qMax(3, int(cardInfoPicture->width() * 0.03)); - int x = qMax(0, cardInfoPicture->width() - pinBadge->width() - margin); - int y = margin * 3; + const int x = qMax(0, cardInfoPicture->width() - pinBadge->width() - margin); + const int y = margin * 3; pinBadge->move(x, y); pinBadge->raise(); } @@ -218,14 +218,14 @@ void PrintingSelectorCardOverlayWidget::customMenu(QPoint point) const auto &cardProviderId = rootCard.getPrinting().getUuid(); if (preferredProviderId.isEmpty() || preferredProviderId != cardProviderId) { - auto *pinAction = preferenceMenu->addAction(tr("Pin Printing")); + const auto *pinAction = preferenceMenu->addAction(tr("Pin Printing")); connect(pinAction, &QAction::triggered, this, [this] { SettingsCache::instance().cardOverrides().setCardPreferenceOverride( {rootCard.getName(), rootCard.getPrinting().getUuid()}); emit cardPreferenceChanged(); }); } else { - auto *unpinAction = preferenceMenu->addAction(tr("Unpin Printing")); + const auto *unpinAction = preferenceMenu->addAction(tr("Unpin Printing")); connect(unpinAction, &QAction::triggered, this, [this] { SettingsCache::instance().cardOverrides().deleteCardPreferenceOverride(rootCard.getName()); emit cardPreferenceChanged(); @@ -241,7 +241,7 @@ void PrintingSelectorCardOverlayWidget::customMenu(QPoint point) } else { for (const CardRelation *rel : relatedCards) { const QString &relatedCardName = rel->getName(); - QAction *relatedCard = relatedMenu->addAction(relatedCardName); + const QAction *relatedCard = relatedMenu->addAction(relatedCardName); connect(relatedCard, &QAction::triggered, deckEditor, [this, relatedCardName] { deckEditor->updateCard(CardDatabaseManager::query()->getCard({relatedCardName})); deckEditor->showPrintingSelector(); diff --git a/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_sorting_widget.cpp b/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_sorting_widget.cpp index af7cedbeb..3a6cdbc15 100644 --- a/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_sorting_widget.cpp +++ b/cockatrice/src/interface/widgets/printing_selector/printing_selector_card_sorting_widget.cpp @@ -219,8 +219,9 @@ QList PrintingSelectorCardSortingWidget::prependPrintingsInDeck(co // Prepend sorted sets and remove them from the original list for (const auto &pair : countList) { - auto it = std::find_if(result.begin(), result.end(), - [&pair](const PrintingInfo &item) { return item.getUuid() == pair.first.getUuid(); }); + const auto it = std::find_if(result.begin(), result.end(), [&pair](const PrintingInfo &item) { + return item.getUuid() == pair.first.getUuid(); + }); if (it != result.end()) { result.erase(it); // Remove the matching entry } diff --git a/cockatrice/src/interface/widgets/printing_selector/set_name_and_collectors_number_display_widget.cpp b/cockatrice/src/interface/widgets/printing_selector/set_name_and_collectors_number_display_widget.cpp index b1a6a61c1..791ac177d 100644 --- a/cockatrice/src/interface/widgets/printing_selector/set_name_and_collectors_number_display_widget.cpp +++ b/cockatrice/src/interface/widgets/printing_selector/set_name_and_collectors_number_display_widget.cpp @@ -90,12 +90,12 @@ void SetNameAndCollectorsNumberDisplayWidget::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); // Ensure the parent class handles the event first - QFontMetrics fm(setName->font()); - int labelWidth = setName->width(); // Get the current width of the QLabel - QString text = setName->text(); // The text to be rendered + const QFontMetrics fm(setName->font()); + const int labelWidth = setName->width(); // Get the current width of the QLabel + const QString text = setName->text(); // The text to be rendered // Calculate the height required to render the text with word wrapping - int textHeight = fm.boundingRect(0, 0, labelWidth, 0, Qt::TextWordWrap, text).height(); + const int textHeight = fm.boundingRect(0, 0, labelWidth, 0, Qt::TextWordWrap, text).height(); // Set the minimum height to accommodate the required text height setName->setMinimumHeight(textHeight); diff --git a/cockatrice/src/interface/widgets/quick_settings/settings_button_widget.cpp b/cockatrice/src/interface/widgets/quick_settings/settings_button_widget.cpp index 17087c8bc..4e3adae54 100644 --- a/cockatrice/src/interface/widgets/quick_settings/settings_button_widget.cpp +++ b/cockatrice/src/interface/widgets/quick_settings/settings_button_widget.cpp @@ -43,11 +43,12 @@ void SettingsButtonWidget::togglePopup() } else { popup->adjustSizeToFitScreen(); // Ensure proper size - QSize popupSize = popup->size(); - QPoint buttonGlobalPos = button->mapToGlobal(QPoint(0, button->height())); + const QSize popupSize = popup->size(); + const QPoint buttonGlobalPos = button->mapToGlobal(QPoint(0, button->height())); - QScreen *screen = QApplication::screenAt(buttonGlobalPos); - QRect screenGeom = screen ? screen->availableGeometry() : QApplication::primaryScreen()->availableGeometry(); + const QScreen *screen = QApplication::screenAt(buttonGlobalPos); + const QRect screenGeom = + screen ? screen->availableGeometry() : QApplication::primaryScreen()->availableGeometry(); int x = buttonGlobalPos.x(); int y = buttonGlobalPos.y(); diff --git a/cockatrice/src/interface/widgets/quick_settings/settings_popup_widget.cpp b/cockatrice/src/interface/widgets/quick_settings/settings_popup_widget.cpp index 9b2e55e0f..e065f6cb8 100644 --- a/cockatrice/src/interface/widgets/quick_settings/settings_popup_widget.cpp +++ b/cockatrice/src/interface/widgets/quick_settings/settings_popup_widget.cpp @@ -37,13 +37,13 @@ void SettingsPopupWidget::removeSettingsWidget(QWidget *toRemove) const void SettingsPopupWidget::adjustSizeToFitScreen() { - QScreen *screen = QApplication::screenAt(this->pos()); - QRect screenGeom = screen ? screen->availableGeometry() : QApplication::primaryScreen()->availableGeometry(); - int maxHeight = screenGeom.height() / 2; // Limit height to 50% of screen + const QScreen *screen = QApplication::screenAt(this->pos()); + const QRect screenGeom = screen ? screen->availableGeometry() : QApplication::primaryScreen()->availableGeometry(); + const int maxHeight = screenGeom.height() / 2; // Limit height to 50% of screen // Adjust the container widget's size hint to get the actual size of content containerWidget->adjustSize(); - int contentHeight = containerWidget->sizeHint().height(); + const int contentHeight = containerWidget->sizeHint().height(); // If content height exceeds maxHeight, we need to scroll if (contentHeight > maxHeight) { diff --git a/cockatrice/src/interface/widgets/replay/replay_timeline_widget.cpp b/cockatrice/src/interface/widgets/replay/replay_timeline_widget.cpp index fb5936cae..416e81933 100644 --- a/cockatrice/src/interface/widgets/replay/replay_timeline_widget.cpp +++ b/cockatrice/src/interface/widgets/replay/replay_timeline_widget.cpp @@ -25,7 +25,7 @@ void ReplayTimelineWidget::setTimeline(const QList &_replayTimeline) histogram.clear(); int binEndTime = BIN_LENGTH - 1; int binValue = 0; - for (int i : replayTimeline) { + for (const int i : replayTimeline) { if (i > binEndTime) { histogram.append(binValue); if (binValue > maxBinValue) @@ -51,7 +51,7 @@ void ReplayTimelineWidget::paintEvent(QPaintEvent * /* event */) QPainter painter(this); painter.drawRect(0, 0, width() - 1, height() - 1); - qreal binWidth = (qreal)width() / histogram.size(); + const qreal binWidth = (qreal)width() / histogram.size(); QPainterPath path; path.moveTo(0, height() - 1); for (int i = 0; i < histogram.size(); ++i) @@ -61,14 +61,14 @@ void ReplayTimelineWidget::paintEvent(QPaintEvent * /* event */) painter.fillPath(path, Qt::black); const QColor barColor = QColor::fromHsv(120, 255, 255, 100); - quint64 w = (quint64)(width() - 1) * (quint64)currentVisualTime / maxTime; + const quint64 w = (quint64)(width() - 1) * (quint64)currentVisualTime / maxTime; painter.fillRect(0, 0, static_cast(w), height() - 1, barColor); } void ReplayTimelineWidget::mousePressEvent(QMouseEvent *event) { #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) - int newTime = static_cast((qint64)maxTime * (qint64)event->position().x() / width()); + const int newTime = static_cast((qint64)maxTime * (qint64)event->position().x() / width()); #else int newTime = static_cast((qint64)maxTime * (qint64)event->x() / width()); #endif diff --git a/cockatrice/src/interface/widgets/server/chat_view/chat_view.cpp b/cockatrice/src/interface/widgets/server/chat_view/chat_view.cpp index c97d32d44..01e74fa5c 100644 --- a/cockatrice/src/interface/widgets/server/chat_view/chat_view.cpp +++ b/cockatrice/src/interface/widgets/server/chat_view/chat_view.cpp @@ -93,7 +93,7 @@ QTextCursor ChatView::prepareBlock(bool same) void ChatView::appendHtml(const QString &html) { - bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); + const bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); prepareBlock().insertHtml(html); if (atBottom) verticalScrollBar()->setValue(verticalScrollBar()->maximum()); @@ -101,7 +101,7 @@ void ChatView::appendHtml(const QString &html) void ChatView::appendHtmlServerMessage(const QString &html, bool optionalIsBold, QString optionalFontColor) { - bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); + const bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); QString htmlText = "" + @@ -117,7 +117,7 @@ void ChatView::appendHtmlServerMessage(const QString &html, bool optionalIsBold, void ChatView::appendCardTag(QTextCursor &cursor, const QString &cardName) { - QTextCharFormat oldFormat = cursor.charFormat(); + const QTextCharFormat oldFormat = cursor.charFormat(); QTextCharFormat anchorFormat = oldFormat; anchorFormat.setForeground(linkColor); anchorFormat.setAnchor(true); @@ -134,7 +134,7 @@ void ChatView::appendUrlTag(QTextCursor &cursor, QString url) if (!url.contains("://")) url.prepend("https://"); - QTextCharFormat oldFormat = cursor.charFormat(); + const QTextCharFormat oldFormat = cursor.charFormat(); QTextCharFormat anchorFormat = oldFormat; anchorFormat.setForeground(linkColor); anchorFormat.setAnchor(true); @@ -155,10 +155,10 @@ void ChatView::appendMessage(QString message, const QString userName = QString::fromStdString(userInfo.name()); const UserLevelFlags userLevel = UserLevelFlags(userInfo.user_level()); - bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); + const bool atBottom = verticalScrollBar()->value() >= verticalScrollBar()->maximum(); // messageType should be Event_RoomSay::UserMessage though we don't actually check - bool isUserMessage = !(userName.toLower() == "servatrice" || userName.isEmpty()); - bool sameSender = isUserMessage && userName == lastSender; + const bool isUserMessage = !(userName.toLower() == "servatrice" || userName.isEmpty()); + const bool sameSender = isUserMessage && userName == lastSender; QTextCursor cursor = prepareBlock(sameSender); lastSender = userName; @@ -189,7 +189,7 @@ void ChatView::appendMessage(QString message, cursor.insertText(" "); } else { const int pixelSize = QFontInfo(cursor.charFormat().font()).pixelSize(); - bool isBuddy = userListProxy->isUserBuddy(userName); + const bool isBuddy = userListProxy->isUserBuddy(userName); const QString privLevel = userInfo.has_privlevel() ? QString::fromStdString(userInfo.privlevel()) : "NONE"; cursor.insertImage(UserLevelPixmapGenerator::generatePixmap(pixelSize, userLevel, userInfo.pawn_colors(), isBuddy, privLevel) @@ -210,13 +210,13 @@ void ChatView::appendMessage(QString message, defaultFormat.setFontWeight(QFont::Light); defaultFormat.setFontItalic(true); static const QRegularExpression userNameRegex("^(\\[[^\\]]*\\]\\s)(\\S+):\\s"); - auto match = userNameRegex.match(message); + const auto match = userNameRegex.match(message); if (match.hasMatch()) { cursor.setCharFormat(defaultFormat); UserMessagePosition pos(cursor); pos.relativePosition = match.captured(0).length(); // set message start - auto before = match.captured(1); - auto sentBy = match.captured(2); + const auto before = match.captured(1); + const auto sentBy = match.captured(2); cursor.insertText(before); // add message timestamp QTextCharFormat senderFormat(defaultFormat); senderFormat.setAnchor(true); @@ -235,7 +235,7 @@ void ChatView::appendMessage(QString message, } cursor.setCharFormat(defaultFormat); - bool mentionEnabled = SettingsCache::instance().getChatMention(); + const bool mentionEnabled = SettingsCache::instance().getChatMention(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) highlightedWords = SettingsCache::instance().getHighlightWords().split(' ', Qt::SkipEmptyParts); #else @@ -280,8 +280,8 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message) { if (message.startsWith("[card]")) { message = message.mid(6); - int closeTagIndex = message.indexOf("[/card]"); - QString cardName = message.left(closeTagIndex); + const int closeTagIndex = message.indexOf("[/card]"); + const QString cardName = message.left(closeTagIndex); if (closeTagIndex == -1) message.clear(); else @@ -293,8 +293,8 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message) if (message.startsWith("[[")) { message = message.mid(2); - int closeTagIndex = message.indexOf("]]"); - QString cardName = message.left(closeTagIndex); + const int closeTagIndex = message.indexOf("]]"); + const QString cardName = message.left(closeTagIndex); if (closeTagIndex == -1) message.clear(); else @@ -306,8 +306,8 @@ void ChatView::checkTag(QTextCursor &cursor, QString &message) if (message.startsWith("[url]")) { message = message.mid(5); - int closeTagIndex = message.indexOf("[/url]"); - QString url = message.left(closeTagIndex); + const int closeTagIndex = message.indexOf("[/url]"); + const QString url = message.left(closeTagIndex); if (closeTagIndex == -1) message.clear(); else @@ -325,9 +325,9 @@ void ChatView::checkMention(QTextCursor &cursor, QString &message, const QString { const static auto notALetterOrNumber = QRegularExpression("[^a-zA-Z0-9]"); - int firstSpace = message.indexOf(' '); + const int firstSpace = message.indexOf(' '); QString fullMentionUpToSpaceOrEnd = (firstSpace == -1) ? message.mid(1) : message.mid(1, firstSpace - 1); - QString mentionIntact = fullMentionUpToSpaceOrEnd; + const QString mentionIntact = fullMentionUpToSpaceOrEnd; while (fullMentionUpToSpaceOrEnd.size()) { const ServerInfo_User *onlineUser = userListProxy->getOnlineUser(fullMentionUpToSpaceOrEnd); @@ -344,7 +344,7 @@ void ChatView::checkMention(QTextCursor &cursor, QString &message, const QString message = message.mid(mention.size()); showSystemPopup(userName); } else { - QString correctUserName = QString::fromStdString(onlineUser->name()); + const QString correctUserName = QString::fromStdString(onlineUser->name()); mentionFormatOtherUser.setAnchorHref("user://" + QString::number(onlineUser->user_level()) + "_" + correctUserName); cursor.insertText("@" + correctUserName, mentionFormatOtherUser); @@ -389,13 +389,13 @@ void ChatView::checkWord(QTextCursor &cursor, QString &message) { // extract the first word QString rest; - QString fullWordUpToSpaceOrEnd = extractNextWord(message, rest); + const QString fullWordUpToSpaceOrEnd = extractNextWord(message, rest); // check urls if (fullWordUpToSpaceOrEnd.startsWith("http://", Qt::CaseInsensitive) || fullWordUpToSpaceOrEnd.startsWith("https://", Qt::CaseInsensitive) || fullWordUpToSpaceOrEnd.startsWith("www.", Qt::CaseInsensitive)) { - QUrl qUrl(fullWordUpToSpaceOrEnd); + const QUrl qUrl(fullWordUpToSpaceOrEnd); if (qUrl.isValid()) { appendUrlTag(cursor, fullWordUpToSpaceOrEnd); cursor.insertText(rest, defaultFormat); @@ -425,7 +425,7 @@ QString ChatView::extractNextWord(QString &message, QString &rest) { // get the first next space and extract the word QString word; - int firstSpace = message.indexOf(' '); + const int firstSpace = message.indexOf(' '); if (firstSpace == -1) { word = message; message.clear(); @@ -448,7 +448,7 @@ QString ChatView::extractNextWord(QString &message, QString &rest) bool ChatView::isModeratorSendingGlobal(QFlags userLevelFlag, QString message) { - int userLevel = QString::number(userLevelFlag).toInt(); + const int userLevel = QString::number(userLevelFlag).toInt(); QStringList getAttentionList; getAttentionList << "/all"; // Send a message to all users @@ -473,7 +473,7 @@ void ChatView::showSystemPopup(const QString &userName) QColor ChatView::getCustomMentionColor() { #if (QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)) - QColor customColor = QColor::fromString("#" + SettingsCache::instance().getChatMentionColor()); + const QColor customColor = QColor::fromString("#" + SettingsCache::instance().getChatMentionColor()); #else QColor customColor; customColor.setNamedColor("#" + SettingsCache::instance().getChatMentionColor()); @@ -484,7 +484,7 @@ QColor ChatView::getCustomMentionColor() QColor ChatView::getCustomHighlightColor() { #if (QT_VERSION >= QT_VERSION_CHECK(6, 4, 0)) - QColor customColor = QColor::fromString("#" + SettingsCache::instance().getChatMentionColor()); + const QColor customColor = QColor::fromString("#" + SettingsCache::instance().getChatMentionColor()); #else QColor customColor; customColor.setNamedColor("#" + SettingsCache::instance().getChatMentionColor()); @@ -537,8 +537,8 @@ void ChatView::leaveEvent(QEvent * /*event*/) QTextFragment ChatView::getFragmentUnderMouse(const QPoint &pos) const { - QTextCursor cursor(cursorForPosition(pos)); - QTextBlock block(cursor.block()); + const QTextCursor cursor(cursorForPosition(pos)); + const QTextBlock block(cursor.block()); QTextBlock::iterator it; for (it = block.begin(); !(it.atEnd()); ++it) { QTextFragment frag = it.fragment(); @@ -550,7 +550,7 @@ QTextFragment ChatView::getFragmentUnderMouse(const QPoint &pos) const void ChatView::mouseMoveEvent(QMouseEvent *event) { - QString anchorHref = getFragmentUnderMouse(event->pos()).charFormat().anchorHref(); + const QString anchorHref = getFragmentUnderMouse(event->pos()).charFormat().anchorHref(); if (!anchorHref.isEmpty()) { const int delimiterIndex = anchorHref.indexOf("://"); if (delimiterIndex != -1) { @@ -594,7 +594,7 @@ void ChatView::mousePressEvent(QMouseEvent *event) const QString userName = hoveredContent.mid(delimiterIndex + 1); switch (event->button()) { case Qt::RightButton: { - UserLevelFlags userLevel(hoveredContent.left(delimiterIndex).toInt()); + const UserLevelFlags userLevel(hoveredContent.left(delimiterIndex).toInt()); #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) userContextMenu->showContextMenu(event->globalPosition().toPoint(), userName, userLevel, this); #else diff --git a/cockatrice/src/interface/widgets/server/game_selector_quick_filter_toolbar.cpp b/cockatrice/src/interface/widgets/server/game_selector_quick_filter_toolbar.cpp index c63b52450..1e94ca378 100644 --- a/cockatrice/src/interface/widgets/server/game_selector_quick_filter_toolbar.cpp +++ b/cockatrice/src/interface/widgets/server/game_selector_quick_filter_toolbar.cpp @@ -60,8 +60,8 @@ GameSelectorQuickFilterToolBar::GameSelectorQuickFilterToolBar(QWidget *parent, QSet currentTypes = model->getGameTypeFilter(); if (currentTypes.size() == 1) { - int typeId = *currentTypes.begin(); - int index = filterToFormatComboBox->findData(typeId); + const int typeId = *currentTypes.begin(); + const int index = filterToFormatComboBox->findData(typeId); if (index >= 0) filterToFormatComboBox->setCurrentIndex(index); } else { @@ -70,7 +70,7 @@ GameSelectorQuickFilterToolBar::GameSelectorQuickFilterToolBar(QWidget *parent, // Update proxy model on selection change connect(filterToFormatComboBox, QOverload::of(&QComboBox::currentIndexChanged), this, [this](int index) { - QVariant data = filterToFormatComboBox->itemData(index); + const QVariant data = filterToFormatComboBox->itemData(index); if (!data.isValid()) { model->setGameTypeFilter({}); // empty = no filter } else { diff --git a/cockatrice/src/interface/widgets/server/games_model.cpp b/cockatrice/src/interface/widgets/server/games_model.cpp index dfb41fd29..f0c484082 100644 --- a/cockatrice/src/interface/widgets/server/games_model.cpp +++ b/cockatrice/src/interface/widgets/server/games_model.cpp @@ -41,8 +41,8 @@ const QString GamesModel::getGameCreatedString(const int secs) return tr(">1 day"); } - QTime total = zeroTime.addSecs(secs); - QTime totalRounded = total.addSecs(halfMinSecs); // round up + const QTime total = zeroTime.addSecs(secs); + const QTime totalRounded = total.addSecs(halfMinSecs); // round up QString form; int amount; if (totalRounded.hour()) { @@ -55,7 +55,7 @@ const QString GamesModel::getGameCreatedString(const int secs) form = tr("%1%2 min", "short age in minutes", amount); } - for (int aggregate : {40, 20, 10, 5}) { // floor to values in this list + for (const int aggregate : {40, 20, 10, 5}) { // floor to values in this list if (amount >= aggregate) { return form.arg(">").arg(aggregate); } @@ -87,11 +87,11 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const switch (role) { case Qt::DisplayRole: { #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) - auto then = QDateTime::fromSecsSinceEpoch(gameentry.start_time(), QTimeZone::UTC); + const auto then = QDateTime::fromSecsSinceEpoch(gameentry.start_time(), QTimeZone::UTC); #else auto then = QDateTime::fromSecsSinceEpoch(gameentry.start_time(), Qt::UTC); #endif - int secs = then.secsTo(QDateTime::currentDateTimeUtc()); + const int secs = then.secsTo(QDateTime::currentDateTimeUtc()); return getGameCreatedString(secs); } case SORT_ROLE: @@ -132,7 +132,7 @@ QVariant GamesModel::data(const QModelIndex &index, int role) const case SORT_ROLE: case Qt::DisplayRole: { QStringList result; - GameTypeMap gameTypeMap = gameTypes.value(gameentry.room_id()); + const GameTypeMap gameTypeMap = gameTypes.value(gameentry.room_id()); for (int i = gameentry.game_types_size() - 1; i >= 0; --i) result.append(gameTypeMap.value(gameentry.game_types(i))); return result.join(", "); @@ -333,7 +333,7 @@ void GamesProxyModel::setGameFilters(bool _hideBuddiesOnlyGames, int GamesProxyModel::getNumFilteredGames() const { - auto *model = qobject_cast(sourceModel()); + const auto *model = qobject_cast(sourceModel()); if (!model) return 0; @@ -401,7 +401,7 @@ void GamesProxyModel::saveFilterParameters(const QMap &allGameType QMapIterator gameTypeIterator(allGameTypes); while (gameTypeIterator.hasNext()) { gameTypeIterator.next(); - bool enabled = gameTypeFilter.contains(gameTypeIterator.key()); + const bool enabled = gameTypeFilter.contains(gameTypeIterator.key()); gameFilters.setGameTypeEnabled(gameTypeIterator.value(), enabled); } @@ -483,9 +483,9 @@ bool GamesProxyModel::filterAcceptsRow(int sourceRow) const return false; if (maxGameAge.isValid()) { - QDateTime now = QDateTime::currentDateTimeUtc(); - qint64 signed_start_time = game.start_time(); // cast to 64 bit value to allow signed value - QDateTime total = now.addSecs(-signed_start_time); // a 32 bit value would wrap at 2038-1-19 + const QDateTime now = QDateTime::currentDateTimeUtc(); + const qint64 signed_start_time = game.start_time(); // cast to 64 bit value to allow signed value + const QDateTime total = now.addSecs(-signed_start_time); // a 32 bit value would wrap at 2038-1-19 // games shouldn't have negative ages but we'll not filter them // because qtime wraps after a day we consider all games older than a day to be too old if (total.isValid() && total.date() >= epochDate && (total.date() > epochDate || total.time() > maxGameAge)) { diff --git a/cockatrice/src/interface/widgets/server/handle_public_servers.cpp b/cockatrice/src/interface/widgets/server/handle_public_servers.cpp index 6a8754a79..c970ab136 100644 --- a/cockatrice/src/interface/widgets/server/handle_public_servers.cpp +++ b/cockatrice/src/interface/widgets/server/handle_public_servers.cpp @@ -17,7 +17,7 @@ HandlePublicServers::HandlePublicServers(QObject *parent) void HandlePublicServers::downloadPublicServers() { - QUrl url(QString(PUBLIC_SERVERS_JSON)); + const QUrl url(QString(PUBLIC_SERVERS_JSON)); reply = nam->get(QNetworkRequest(url)); connect(reply, &QNetworkReply::finished, this, &HandlePublicServers::actFinishParsingDownloadedData); } @@ -25,7 +25,7 @@ void HandlePublicServers::downloadPublicServers() void HandlePublicServers::actFinishParsingDownloadedData() { reply = dynamic_cast(sender()); - QNetworkReply::NetworkError errorCode = reply->error(); + const QNetworkReply::NetworkError errorCode = reply->error(); if (errorCode == QNetworkReply::NoError) { // Get current saved hosts @@ -34,9 +34,9 @@ void HandlePublicServers::actFinishParsingDownloadedData() // Downloaded data from GitHub QJsonParseError parseError{}; - QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError); + const QJsonDocument jsonResponse = QJsonDocument::fromJson(reply->readAll(), &parseError); if (parseError.error == QJsonParseError::NoError) { - QVariantMap jsonMap = jsonResponse.toVariant().toMap(); + const QVariantMap jsonMap = jsonResponse.toVariant().toMap(); updateServerINISettings(jsonMap); } else { qDebug() << "[PUBLIC SERVER HANDLER]" diff --git a/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.cpp b/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.cpp index 6ca680c3f..0f772b63a 100644 --- a/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.cpp +++ b/cockatrice/src/interface/widgets/server/remote/remote_decklist_tree_widget.cpp @@ -30,7 +30,7 @@ void RemoteDeckList_TreeModel::DirectoryNode::clearTree() QString RemoteDeckList_TreeModel::DirectoryNode::getPath() const { if (parent) { - QString parentPath = parent->getPath(); + const QString parentPath = parent->getPath(); if (parentPath.isEmpty()) return name; else @@ -63,7 +63,7 @@ RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::DirectoryNode RemoteDeckList_TreeModel::FileNode *RemoteDeckList_TreeModel::DirectoryNode::getNodeById(int id) const { for (int i = 0; i < size(); ++i) { - DirectoryNode *node = dynamic_cast(at(i)); + const DirectoryNode *node = dynamic_cast(at(i)); if (node) { FileNode *result = node->getNodeById(id); if (result) @@ -80,7 +80,7 @@ RemoteDeckList_TreeModel::FileNode *RemoteDeckList_TreeModel::DirectoryNode::get RemoteDeckList_TreeModel::RemoteDeckList_TreeModel(AbstractClient *_client, QObject *parent) : QAbstractItemModel(parent), client(_client) { - QFileIconProvider fip; + const QFileIconProvider fip; dirIcon = fip.icon(QFileIconProvider::Folder); fileIcon = fip.icon(QFileIconProvider::File); @@ -94,7 +94,7 @@ RemoteDeckList_TreeModel::~RemoteDeckList_TreeModel() int RemoteDeckList_TreeModel::rowCount(const QModelIndex &parent) const { - DirectoryNode *node = getNode(parent); + const DirectoryNode *node = getNode(parent); if (node) return node->size(); else @@ -114,9 +114,9 @@ QVariant RemoteDeckList_TreeModel::data(const QModelIndex &index, int role) cons return QVariant(); Node *temp = static_cast(index.internalPointer()); - FileNode *file = dynamic_cast(temp); + const FileNode *file = dynamic_cast(temp); if (!file) { - DirectoryNode *node = dynamic_cast(temp); + const DirectoryNode *node = dynamic_cast(temp); switch (role) { case Qt::DisplayRole: { switch (index.column()) { @@ -184,7 +184,7 @@ QModelIndex RemoteDeckList_TreeModel::index(int row, int column, const QModelInd if (!hasIndex(row, column, parent)) return QModelIndex(); - DirectoryNode *parentNode = getNode(parent); + const DirectoryNode *parentNode = getNode(parent); if (row >= parentNode->size()) return QModelIndex(); @@ -252,7 +252,7 @@ RemoteDeckList_TreeModel::DirectoryNode *RemoteDeckList_TreeModel::addNamedFolde void RemoteDeckList_TreeModel::removeNode(RemoteDeckList_TreeModel::Node *node) { - int ind = node->getParent()->indexOf(node); + const int ind = node->getParent()->indexOf(node); beginRemoveRows(nodeToIndex(node->getParent()), ind, ind); node->getParent()->removeAt(ind); endRemoveRows(); diff --git a/cockatrice/src/interface/widgets/server/remote/remote_replay_list_tree_widget.cpp b/cockatrice/src/interface/widgets/server/remote/remote_replay_list_tree_widget.cpp index 5152880d9..6df90e57d 100644 --- a/cockatrice/src/interface/widgets/server/remote/remote_replay_list_tree_widget.cpp +++ b/cockatrice/src/interface/widgets/server/remote/remote_replay_list_tree_widget.cpp @@ -32,7 +32,7 @@ void RemoteReplayList_TreeModel::MatchNode::updateMatchInfo(const ServerInfo_Rep RemoteReplayList_TreeModel::RemoteReplayList_TreeModel(AbstractClient *_client, QObject *parent) : QAbstractItemModel(parent), client(_client) { - QFileIconProvider fip; + const QFileIconProvider fip; dirIcon = fip.icon(QFileIconProvider::Folder); fileIcon = fip.icon(QFileIconProvider::File); lockIcon = QPixmap("theme:icons/lock"); @@ -48,7 +48,7 @@ int RemoteReplayList_TreeModel::rowCount(const QModelIndex &parent) const if (!parent.isValid()) return replayMatches.size(); - auto *matchNode = dynamic_cast(static_cast(parent.internalPointer())); + const auto *matchNode = dynamic_cast(static_cast(parent.internalPointer())); if (matchNode) return matchNode->size(); else @@ -170,7 +170,7 @@ QModelIndex RemoteReplayList_TreeModel::index(int row, int column, const QModelI if (!hasIndex(row, column, parent)) return QModelIndex(); - auto *matchNode = dynamic_cast(static_cast(parent.internalPointer())); + const auto *matchNode = dynamic_cast(static_cast(parent.internalPointer())); if (matchNode) { if (row >= matchNode->size()) return QModelIndex(); @@ -231,7 +231,7 @@ ServerInfo_ReplayMatch const *RemoteReplayList_TreeModel::getEnclosingReplayMatc auto *node = dynamic_cast(static_cast(index.internalPointer())); if (!node) { - auto *_node = dynamic_cast(static_cast(index.internalPointer())); + const auto *_node = dynamic_cast(static_cast(index.internalPointer())); if (!_node) return nullptr; return &_node->getParent()->getMatchInfo(); diff --git a/cockatrice/src/interface/widgets/server/user/user_context_menu.cpp b/cockatrice/src/interface/widgets/server/user/user_context_menu.cpp index cb7d2eca9..22b06ac10 100644 --- a/cockatrice/src/interface/widgets/server/user/user_context_menu.cpp +++ b/cockatrice/src/interface/widgets/server/user/user_context_menu.cpp @@ -137,8 +137,8 @@ void UserContextMenu::warnUser_processGetWarningsListResponse(const Response &r) { const Response_WarnList &response = r.GetExtension(Response_WarnList::ext); - QString user = QString::fromStdString(response.user_name()).simplified(); - QString clientid = QString::fromStdString(response.user_clientid()).simplified(); + const QString user = QString::fromStdString(response.user_name()).simplified(); + const QString clientid = QString::fromStdString(response.user_clientid()).simplified(); // The dialog needs to be non-modal in order to not block the event queue of the client. auto *dlg = new WarningDialog(user, clientid, static_cast(parent())); @@ -155,7 +155,7 @@ void UserContextMenu::warnUser_processGetWarningsListResponse(const Response &r) void UserContextMenu::warnUser_processUserInfoResponse(const Response &resp) { const Response_GetUserInfo &response = resp.GetExtension(Response_GetUserInfo::ext); - ServerInfo_User userInfo = response.user_info(); + const ServerInfo_User userInfo = response.user_info(); Command_GetWarnList cmd; cmd.set_user_name(userInfo.name()); @@ -278,7 +278,7 @@ void UserContextMenu::adjustMod_processUserResponse(const Response &resp, const void UserContextMenu::banUser_dialogFinished() { - auto *dlg = static_cast(sender()); + const auto *dlg = static_cast(sender()); Command_BanFromServer cmd; cmd.set_user_name(dlg->getBanName().toStdString()); @@ -287,7 +287,7 @@ void UserContextMenu::banUser_dialogFinished() cmd.set_reason(dlg->getReason().toStdString()); cmd.set_visible_reason(dlg->getVisibleReason().toStdString()); cmd.set_clientid(dlg->getBanId().toStdString()); - int removeAmount = dlg->getDeleteMessages(); + const int removeAmount = dlg->getDeleteMessages(); if (removeAmount != 0) { cmd.set_remove_messages(removeAmount); } @@ -297,7 +297,7 @@ void UserContextMenu::banUser_dialogFinished() void UserContextMenu::warnUser_dialogFinished() { - auto *dlg = static_cast(sender()); + const auto *dlg = static_cast(sender()); if (dlg->getName().isEmpty() || userListProxy->getOwnUsername().simplified().isEmpty()) return; @@ -306,7 +306,7 @@ void UserContextMenu::warnUser_dialogFinished() cmd.set_user_name(dlg->getName().toStdString()); cmd.set_reason(dlg->getReason().toStdString()); cmd.set_clientid(dlg->getWarnID().toStdString()); - int removeAmount = dlg->getDeleteMessages(); + const int removeAmount = dlg->getDeleteMessages(); if (removeAmount != 0) { cmd.set_remove_messages(removeAmount); } @@ -316,7 +316,7 @@ void UserContextMenu::warnUser_dialogFinished() void UserContextMenu::updateAdminNotes_dialogFinished() { - auto *dlg = static_cast(sender()); + const auto *dlg = static_cast(sender()); Command_UpdateAdminNotes cmd; cmd.set_user_name(dlg->getName().toStdString()); diff --git a/cockatrice/src/interface/widgets/server/user/user_info_box.cpp b/cockatrice/src/interface/widgets/server/user/user_info_box.cpp index 9ae4a42c2..87dd1c09b 100644 --- a/cockatrice/src/interface/widgets/server/user/user_info_box.cpp +++ b/cockatrice/src/interface/widgets/server/user/user_info_box.cpp @@ -110,7 +110,7 @@ void UserInfoBox::updateInfo(const ServerInfo_User &user) nameLabel.setText(QString::fromStdString(user.name())); realNameLabel2.setText(QString::fromStdString(user.real_name())); - QString country = QString::fromStdString(user.country()); + const QString country = QString::fromStdString(user.country()); if (country.length() != 0) { countryLabel2.setPixmap(CountryPixmapGenerator::generatePixmap(13, country)); @@ -156,17 +156,17 @@ QString UserInfoBox::getAgeString(int ageSeconds) return accountAgeString; // secsSinceEpoch is in utc - auto secsSinceEpoch = QDateTime::currentSecsSinceEpoch() - ageSeconds; + const 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(); + const auto date = QDateTime::fromSecsSinceEpoch(secsSinceEpoch).date(); if (!date.isValid()) return accountAgeString; // now can be local time as the date is also local time - auto now = QDate::currentDate(); - auto daysAndYears = getDaysAndYearsBetween(date, now); + const auto now = QDate::currentDate(); + const auto daysAndYears = getDaysAndYearsBetween(date, now); - QString dateString = QLocale().toString(date, QLocale::ShortFormat); + const QString dateString = QLocale().toString(date, QLocale::ShortFormat); QString yearString; if (daysAndYears.second > 0) { yearString = tr("%n Year(s), ", "amount of years (only shown if more than 0)", daysAndYears.second); @@ -200,7 +200,7 @@ void UserInfoBox::processResponse(const Response &r) void UserInfoBox::actEdit() { - Command_GetUserInfo cmd; + const Command_GetUserInfo cmd; PendingCommand *pend = client->prepareSessionCommand(cmd); connect(pend, &PendingCommand::finished, this, &UserInfoBox::actEditInternal); @@ -213,9 +213,9 @@ void UserInfoBox::actEditInternal(const Response &r) const Response_GetUserInfo &response = r.GetExtension(Response_GetUserInfo::ext); const ServerInfo_User &user = response.user_info(); - QString email = QString::fromStdString(user.email()); - QString country = QString::fromStdString(user.country()); - QString realName = QString::fromStdString(user.real_name()); + const QString email = QString::fromStdString(user.email()); + const QString country = QString::fromStdString(user.country()); + const QString realName = QString::fromStdString(user.real_name()); DlgEditUser dlg(this, email, country, realName); if (!dlg.exec()) @@ -227,7 +227,7 @@ void UserInfoBox::actEditInternal(const Response &r) if (email != dlg.getEmail()) { // real password is required to change email bool ok = false; - QString password = + const QString password = getTextWithMax(this, tr("Enter Password"), tr("Password verification is required in order to change your email address"), QLineEdit::Password, "", &ok); @@ -253,8 +253,8 @@ void UserInfoBox::actPassword() if (!dlg.exec()) return; - auto oldPassword = dlg.getOldPassword(); - auto newPassword = dlg.getNewPassword(); + const auto oldPassword = dlg.getOldPassword(); + const auto newPassword = dlg.getNewPassword(); if (client->getServerSupportsPasswordHash()) { Command_RequestPasswordSalt cmd; @@ -280,8 +280,8 @@ void UserInfoBox::changePassword(const QString &oldPassword, const QString &newP Command_AccountPassword cmd; cmd.set_old_password(oldPassword.toStdString()); if (client->getServerSupportsPasswordHash()) { - auto passwordSalt = PasswordHasher::generateRandomSalt(); - QString hashedPassword = PasswordHasher::computeHash(newPassword, passwordSalt); + const auto passwordSalt = PasswordHasher::generateRandomSalt(); + const QString hashedPassword = PasswordHasher::computeHash(newPassword, passwordSalt); cmd.set_hashed_new_password(hashedPassword.toStdString()); } else { cmd.set_new_password(newPassword.toStdString()); @@ -376,7 +376,7 @@ void UserInfoBox::resizeEvent(QResizeEvent *event) if (hasAvatar) { resizedPixmap = avatarPixmap.scaled(avatarPic.size(), Qt::KeepAspectRatio, Qt::SmoothTransformation); } else { - int height = qMin(avatarPic.size().width(), avatarPic.size().height()); + const int height = qMin(avatarPic.size().width(), avatarPic.size().height()); resizedPixmap = createDefaultAvatar(height, *currentUserInfo); } avatarPic.setPixmap(resizedPixmap); diff --git a/cockatrice/src/interface/widgets/server/user/user_info_connection.cpp b/cockatrice/src/interface/widgets/server/user/user_info_connection.cpp index 069e438a9..7392f5b65 100644 --- a/cockatrice/src/interface/widgets/server/user/user_info_connection.cpp +++ b/cockatrice/src/interface/widgets/server/user/user_info_connection.cpp @@ -25,16 +25,16 @@ QMap> UserConnection_Inf ServersSettings &servers = SettingsCache::instance().servers(); - int size = servers.getValue("totalServers", "server", "server_details").toInt() + 1; + const int size = servers.getValue("totalServers", "server", "server_details").toInt() + 1; for (int i = 0; i < size; i++) { QString _saveName = servers.getValue(QString("saveName%1").arg(i), "server", "server_details").toString(); 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(); - QString userName = servers.getValue(QString("username%1").arg(i), "server", "server_details").toString(); - QString pass = servers.getValue(QString("password%1").arg(i), "server", "server_details").toString(); - bool savePass = servers.getValue(QString("savePassword%1").arg(i), "server", "server_details").toBool(); - QString _site = servers.getValue(QString("site%1").arg(i), "server", "server_details").toString(); + const QString portNum = servers.getValue(QString("port%1").arg(i), "server", "server_details").toString(); + const QString userName = servers.getValue(QString("username%1").arg(i), "server", "server_details").toString(); + const QString pass = servers.getValue(QString("password%1").arg(i), "server", "server_details").toString(); + const bool savePass = servers.getValue(QString("savePassword%1").arg(i), "server", "server_details").toBool(); + const QString _site = servers.getValue(QString("site%1").arg(i), "server", "server_details").toString(); UserConnection_Information userInfo(_saveName, serverName, portNum, userName, pass, savePass, _site); serverList.insert(_saveName, std::make_pair(serverName, userInfo)); @@ -49,19 +49,19 @@ QStringList UserConnection_Information::getServerInfo(const QString &find) ServersSettings &servers = SettingsCache::instance().servers(); - int size = servers.getValue("totalServers", "server", "server_details").toInt() + 1; + const int size = servers.getValue("totalServers", "server", "server_details").toInt() + 1; for (int i = 0; i < size; i++) { QString _saveName = servers.getValue(QString("saveName%1").arg(i), "server", "server_details").toString(); 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(); - QString userName = servers.getValue(QString("username%1").arg(i), "server", "server_details").toString(); - QString pass = servers.getValue(QString("password%1").arg(i), "server", "server_details").toString(); - bool savePass = servers.getValue(QString("savePassword%1").arg(i), "server", "server_details").toBool(); - QString _site = servers.getValue(QString("site%1").arg(i), "server", "server_details").toString(); + const QString serverName = servers.getValue(QString("server%1").arg(i), "server", "server_details").toString(); + const QString portNum = servers.getValue(QString("port%1").arg(i), "server", "server_details").toString(); + const QString userName = servers.getValue(QString("username%1").arg(i), "server", "server_details").toString(); + const QString pass = servers.getValue(QString("password%1").arg(i), "server", "server_details").toString(); + const bool savePass = servers.getValue(QString("savePassword%1").arg(i), "server", "server_details").toBool(); + const QString _site = servers.getValue(QString("site%1").arg(i), "server", "server_details").toString(); _server.append(_saveName); _server.append(serverName); diff --git a/cockatrice/src/interface/widgets/server/user/user_list_widget.cpp b/cockatrice/src/interface/widgets/server/user/user_list_widget.cpp index b6d65c5fa..4a7a027f8 100644 --- a/cockatrice/src/interface/widgets/server/user/user_list_widget.cpp +++ b/cockatrice/src/interface/widgets/server/user/user_list_widget.cpp @@ -321,7 +321,7 @@ bool UserListItemDelegate::editorEvent(QEvent *event, const QModelIndex &index) { if ((event->type() == QEvent::MouseButtonPress) && index.isValid()) { - QMouseEvent *const mouseEvent = static_cast(event); + const QMouseEvent *mouseEvent = static_cast(event); if (mouseEvent->button() == Qt::RightButton) { #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) static_cast(parent())->showContextMenu(mouseEvent->globalPosition().toPoint(), index); @@ -527,7 +527,7 @@ void UserListWidget::userClicked(QTreeWidgetItem *item, int /*column*/) void UserListWidget::showContextMenu(const QPoint &pos, const QModelIndex &index) { const ServerInfo_User &userInfo = static_cast(userTree->topLevelItem(index.row()))->getUserInfo(); - bool online = index.sibling(index.row(), 0).data(Qt::UserRole + 1).toBool(); + const bool online = index.sibling(index.row(), 0).data(Qt::UserRole + 1).toBool(); userContextMenu->showContextMenu(pos, QString::fromStdString(userInfo.name()), UserLevelFlags(userInfo.user_level()), online); diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/average_deck/edhrec_average_deck_api_response.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/average_deck/edhrec_average_deck_api_response.cpp index 1297fc157..334b5626c 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/average_deck/edhrec_average_deck_api_response.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/average_deck/edhrec_average_deck_api_response.cpp @@ -9,7 +9,7 @@ void EdhrecAverageDeckApiResponse::fromJson(const QJsonObject &json) deckStats.fromJson(json); // Parse Archidekt section - QJsonArray archidektJson = json.value("archidekt").toArray(); + const QJsonArray archidektJson = json.value("archidekt").toArray(); archidekt.fromJson(archidektJson); // Parse other fields @@ -17,9 +17,9 @@ void EdhrecAverageDeckApiResponse::fromJson(const QJsonObject &json) header = json.value("header").toString(); panels = json.value("panels").toObject(); description = json.value("description").toString(); - QJsonObject containerJson = json.value("container").toObject(); + const QJsonObject containerJson = json.value("container").toObject(); container.fromJson(containerJson); - QJsonArray cardsJson = json.value("deck").toArray(); + const QJsonArray cardsJson = json.value("deck").toArray(); deck.fromJson(cardsJson); } diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/cards/edhrec_api_response_card_container.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/cards/edhrec_api_response_card_container.cpp index 3fef8be34..6cb4e6998 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/cards/edhrec_api_response_card_container.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/cards/edhrec_api_response_card_container.cpp @@ -13,7 +13,7 @@ void EdhrecApiResponseCardContainer::fromJson(const QJsonObject &json) } description = json.value("description").toString(); - QJsonObject jsonDict = json.value("json_dict").toObject(); + const QJsonObject jsonDict = json.value("json_dict").toObject(); card.fromJson(jsonDict.value("card").toObject()); QJsonArray cardlistsArray = jsonDict.value("cardlists").toArray(); diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/commander/edhrec_commander_api_response.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/commander/edhrec_commander_api_response.cpp index da2a9c052..aba681210 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/commander/edhrec_commander_api_response.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/commander/edhrec_commander_api_response.cpp @@ -9,7 +9,7 @@ void EdhrecCommanderApiResponse::fromJson(const QJsonObject &json) deckStats.fromJson(json); // Parse Archidekt section - QJsonArray archidektJson = json.value("archidekt").toArray(); + const QJsonArray archidektJson = json.value("archidekt").toArray(); archidekt.fromJson(archidektJson); // Parse other fields @@ -17,7 +17,7 @@ void EdhrecCommanderApiResponse::fromJson(const QJsonObject &json) header = json.value("header").toString(); panels = json.value("panels").toObject(); description = json.value("description").toString(); - QJsonObject containerJson = json.value("container").toObject(); + const QJsonObject containerJson = json.value("container").toObject(); container.fromJson(containerJson); } diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_cards/edhrec_top_cards_api_response.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_cards/edhrec_top_cards_api_response.cpp index 26122ce89..54eba545a 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_cards/edhrec_top_cards_api_response.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_cards/edhrec_top_cards_api_response.cpp @@ -7,7 +7,7 @@ void EdhrecTopCardsApiResponse::fromJson(const QJsonObject &json) { header = json.value("header").toString(); description = json.value("description").toString(); - QJsonObject containerJson = json.value("container").toObject(); + const QJsonObject containerJson = json.value("container").toObject(); container.fromJson(containerJson); } diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_commanders/edhrec_top_commanders_api_response.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_commanders/edhrec_top_commanders_api_response.cpp index 83b10c9e5..4bd41bbc5 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_commanders/edhrec_top_commanders_api_response.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_commanders/edhrec_top_commanders_api_response.cpp @@ -7,7 +7,7 @@ void EdhrecTopCommandersApiResponse::fromJson(const QJsonObject &json) { header = json.value("header").toString(); description = json.value("description").toString(); - QJsonObject containerJson = json.value("container").toObject(); + const QJsonObject containerJson = json.value("container").toObject(); container.fromJson(containerJson); } diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_tags/edhrec_top_tags_api_response.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_tags/edhrec_top_tags_api_response.cpp index 56eb4fa4f..0c8968a38 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_tags/edhrec_top_tags_api_response.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/api_response/top_tags/edhrec_top_tags_api_response.cpp @@ -7,7 +7,7 @@ void EdhrecTopTagsApiResponse::fromJson(const QJsonObject &json) { header = json.value("header").toString(); description = json.value("description").toString(); - QJsonObject containerJson = json.value("container").toObject(); + const QJsonObject containerJson = json.value("container").toObject(); container.fromJson(containerJson); } diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/cards/edhrec_api_response_card_details_display_widget.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/cards/edhrec_api_response_card_details_display_widget.cpp index 108694d8d..6e3f08635 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/cards/edhrec_api_response_card_details_display_widget.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/cards/edhrec_api_response_card_details_display_widget.cpp @@ -29,7 +29,7 @@ EdhrecApiResponseCardDetailsDisplayWidget::EdhrecApiResponseCardDetailsDisplayWi layout->addWidget(synergyDisplayWidget); QWidget *currentParent = parentWidget(); - TabEdhRecMain *parentTab = nullptr; + const TabEdhRecMain *parentTab = nullptr; while (currentParent) { if ((parentTab = qobject_cast(currentParent))) { diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/cards/edhrec_api_response_card_list_display_widget.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/cards/edhrec_api_response_card_list_display_widget.cpp index 841ef315b..1b3efca95 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/cards/edhrec_api_response_card_list_display_widget.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/cards/edhrec_api_response_card_list_display_widget.cpp @@ -18,7 +18,7 @@ EdhrecApiResponseCardListDisplayWidget::EdhrecApiResponseCardListDisplayWidget(Q header->setBuddy(flowWidget); foreach (EdhrecApiResponseCardDetails card_detail, toDisplay.cardViews) { - auto widget = new EdhrecApiResponseCardDetailsDisplayWidget(flowWidget, card_detail); + const auto widget = new EdhrecApiResponseCardDetailsDisplayWidget(flowWidget, card_detail); flowWidget->addWidget(widget); } diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_api_response_commander_details_display_widget.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_api_response_commander_details_display_widget.cpp index b15d559f5..07c7907c6 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_api_response_commander_details_display_widget.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_api_response_commander_details_display_widget.cpp @@ -19,7 +19,7 @@ EdhrecCommanderResponseCommanderDetailsDisplayWidget::EdhrecCommanderResponseCom commanderPicture->setCard(CardDatabaseManager::query()->getCard({commanderDetails.getName()})); QWidget *currentParent = parentWidget(); - TabEdhRecMain *parentTab = nullptr; + const TabEdhRecMain *parentTab = nullptr; while (currentParent) { if ((parentTab = qobject_cast(currentParent))) { diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_commander_api_response_display_widget.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_commander_api_response_display_widget.cpp index 230858d6c..aa1471e98 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_commander_api_response_display_widget.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_commander_api_response_display_widget.cpp @@ -64,13 +64,13 @@ EdhrecCommanderApiResponseDisplayWidget::EdhrecCommanderApiResponseDisplayWidget // Connect the list view to ensure the corresponding widget is visible connect(listView, &QListView::clicked, this, [this](const QModelIndex &index) { - int widgetIndex = index.row(); + const int widgetIndex = index.row(); qDebug() << "clicked: " << widgetIndex; - auto targetWidget = cardDisplayLayout->itemAt(widgetIndex)->widget(); + const auto targetWidget = cardDisplayLayout->itemAt(widgetIndex)->widget(); if (targetWidget) { qDebug() << "Found targetWidget" << targetWidget; // Attempt to cast the parent to QScrollArea - auto scrollArea = qobject_cast(this->scrollArea); // Use the scroll area instance + const auto scrollArea = qobject_cast(this->scrollArea); // Use the scroll area instance if (scrollArea) { qDebug() << "ScrollArea" << scrollArea; scrollArea->ensureWidgetVisible(targetWidget); diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_commander_api_response_navigation_widget.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_commander_api_response_navigation_widget.cpp index 3f3b9f1ba..45a8a8b55 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_commander_api_response_navigation_widget.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/commander/edhrec_commander_api_response_navigation_widget.cpp @@ -111,8 +111,8 @@ void EdhrecCommanderApiResponseNavigationWidget::applyOptionsFromUrl(const QStri QString gameChangerOpt, budgetOpt; // Define valid sets - QSet validGameChangers = {"core", "upgraded", "optimized"}; - QSet validBudgets = {"budget", "expensive"}; + const QSet validGameChangers = {"core", "upgraded", "optimized"}; + const QSet validBudgets = {"budget", "expensive"}; // Check remaining parts after commander for (int i = 2; i < parts.size(); ++i) { diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_cards/edhrec_top_cards_api_response_display_widget.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_cards/edhrec_top_cards_api_response_display_widget.cpp index ae07c9dc8..66e53811c 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_cards/edhrec_top_cards_api_response_display_widget.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_cards/edhrec_top_cards_api_response_display_widget.cpp @@ -15,7 +15,7 @@ EdhrecTopCardsApiResponseDisplayWidget::EdhrecTopCardsApiResponseDisplayWidget(Q // Add card list widgets auto edhrec_commander_api_response_card_lists = response.container.getCardlists(); for (const EdhrecApiResponseCardList &card_list : edhrec_commander_api_response_card_lists) { - auto cardListDisplayWidget = new EdhrecApiResponseCardListDisplayWidget(this, card_list); + const auto cardListDisplayWidget = new EdhrecApiResponseCardListDisplayWidget(this, card_list); cardDisplayLayout->addWidget(cardListDisplayWidget); } @@ -26,7 +26,7 @@ EdhrecTopCardsApiResponseDisplayWidget::EdhrecTopCardsApiResponseDisplayWidget(Q scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Set the cardDisplayLayout inside the scroll area - auto scrollWidget = new QWidget(scrollArea); + const auto scrollWidget = new QWidget(scrollArea); scrollWidget->setLayout(cardDisplayLayout); scrollArea->setWidget(scrollWidget); diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_commander/edhrec_top_commanders_api_response_display_widget.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_commander/edhrec_top_commanders_api_response_display_widget.cpp index 13f54a979..5a2a932af 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_commander/edhrec_top_commanders_api_response_display_widget.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_commander/edhrec_top_commanders_api_response_display_widget.cpp @@ -16,7 +16,7 @@ EdhrecTopCommandersApiResponseDisplayWidget::EdhrecTopCommandersApiResponseDispl // Add card list widgets auto edhrec_commander_api_response_card_lists = response.container.getCardlists(); for (const EdhrecApiResponseCardList &card_list : edhrec_commander_api_response_card_lists) { - auto cardListDisplayWidget = new EdhrecApiResponseCardListDisplayWidget(this, card_list); + const auto cardListDisplayWidget = new EdhrecApiResponseCardListDisplayWidget(this, card_list); cardDisplayLayout->addWidget(cardListDisplayWidget); } @@ -27,7 +27,7 @@ EdhrecTopCommandersApiResponseDisplayWidget::EdhrecTopCommandersApiResponseDispl scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Set the cardDisplayLayout inside the scroll area - auto scrollWidget = new QWidget(scrollArea); + const auto scrollWidget = new QWidget(scrollArea); scrollWidget->setLayout(cardDisplayLayout); scrollArea->setWidget(scrollWidget); diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_tags/edhrec_top_tags_api_response_display_widget.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_tags/edhrec_top_tags_api_response_display_widget.cpp index 91a1ce3fa..14db0bf07 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_tags/edhrec_top_tags_api_response_display_widget.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/display/top_tags/edhrec_top_tags_api_response_display_widget.cpp @@ -15,7 +15,7 @@ EdhrecTopTagsApiResponseDisplayWidget::EdhrecTopTagsApiResponseDisplayWidget(QWi // Add card list widgets auto edhrec_commander_api_response_card_lists = response.container.getCardlists(); for (const EdhrecApiResponseCardList &card_list : edhrec_commander_api_response_card_lists) { - auto cardListDisplayWidget = new EdhrecApiResponseCardListDisplayWidget(this, card_list); + const auto cardListDisplayWidget = new EdhrecApiResponseCardListDisplayWidget(this, card_list); cardDisplayLayout->addWidget(cardListDisplayWidget); } @@ -26,7 +26,7 @@ EdhrecTopTagsApiResponseDisplayWidget::EdhrecTopTagsApiResponseDisplayWidget(QWi scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Set the cardDisplayLayout inside the scroll area - auto scrollWidget = new QWidget(scrollArea); + const auto scrollWidget = new QWidget(scrollArea); scrollWidget->setLayout(cardDisplayLayout); scrollArea->setWidget(scrollWidget); diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec.cpp index 4c740e5d1..9d90c9791 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec.cpp @@ -37,8 +37,8 @@ void TabEdhRec::setCard(CardInfoPtr _cardToQuery, bool isCommander) return; } - QString cardName = cardToQuery->getName(); - QString formattedName = cardName.toLower().replace(" ", "-").remove(QRegularExpression("[^a-z0-9\\-]")); + const QString cardName = cardToQuery->getName(); + const QString formattedName = cardName.toLower().replace(" ", "-").remove(QRegularExpression("[^a-z0-9\\-]")); QString url; if (isCommander) { @@ -47,7 +47,7 @@ void TabEdhRec::setCard(CardInfoPtr _cardToQuery, bool isCommander) url = QString("https://json.edhrec.com/pages/card/%1.json").arg(formattedName); } - QNetworkRequest request{QUrl(url)}; + const QNetworkRequest request{QUrl(url)}; networkManager->get(request); } @@ -60,8 +60,8 @@ void TabEdhRec::processApiJson(QNetworkReply *reply) return; } - QByteArray responseData = reply->readAll(); - QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData); + const QByteArray responseData = reply->readAll(); + const QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData); if (!jsonDoc.isObject()) { qDebug() << "Invalid JSON response received."; @@ -69,7 +69,7 @@ void TabEdhRec::processApiJson(QNetworkReply *reply) return; } - QJsonObject jsonObj = jsonDoc.object(); + const QJsonObject jsonObj = jsonDoc.object(); // qDebug() << jsonObj; diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec.h b/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec.h index b5ee8d2ca..b07adc76a 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec.h +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec.h @@ -22,7 +22,7 @@ public: void retranslateUi() override; [[nodiscard]] QString getTabText() const override { - auto cardName = cardToQuery.isNull() ? QString() : cardToQuery->getName(); + const auto cardName = cardToQuery.isNull() ? QString() : cardToQuery->getName(); return tr("EDHREC: ") + cardName; } diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec_main.cpp b/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec_main.cpp index 0dcd5d0ae..fbe530f49 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec_main.cpp +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec_main.cpp @@ -62,8 +62,8 @@ TabEdhRecMain::TabEdhRecMain(TabSupervisor *_tabSupervisor) : Tab(_tabSupervisor connect(tagsPushButton, &QPushButton::clicked, this, &TabEdhRecMain::getTopTags); searchBar = new QLineEdit(this); - auto cardDatabaseModel = new CardDatabaseModel(CardDatabaseManager::getInstance(), false, this); - auto displayModel = new CardDatabaseDisplayModel(this); + const auto cardDatabaseModel = new CardDatabaseModel(CardDatabaseManager::getInstance(), false, this); + const auto displayModel = new CardDatabaseDisplayModel(this); displayModel->setSourceModel(cardDatabaseModel); auto *searchModel = new CardSearchModel(displayModel, this); @@ -84,7 +84,7 @@ TabEdhRecMain::TabEdhRecMain(TabSupervisor *_tabSupervisor) : Tab(_tabSupervisor connect(searchBar, &QLineEdit::textChanged, searchModel, &CardSearchModel::updateSearchResults); connect(searchBar, &QLineEdit::textChanged, this, [=](const QString &text) { // Ensure substring matching - QString pattern = ".*" + QRegularExpression::escape(text) + ".*"; + const QString pattern = ".*" + QRegularExpression::escape(text) + ".*"; proxyModel->setFilterRegularExpression(QRegularExpression(pattern, QRegularExpression::CaseInsensitiveOption)); if (!text.isEmpty()) { @@ -139,7 +139,7 @@ void TabEdhRecMain::retranslateUi() void TabEdhRecMain::doSearch() { - CardInfoPtr searchedCard = CardDatabaseManager::query()->getCardInfo(searchBar->text()); + const CardInfoPtr searchedCard = CardDatabaseManager::query()->getCardInfo(searchBar->text()); if (!searchedCard) { return; } @@ -156,8 +156,8 @@ void TabEdhRecMain::setCard(CardInfoPtr _cardToQuery, bool isCommander) return; } - QString cardName = cardToQuery->getName(); - QString formattedName = cardName.toLower().replace(" ", "-").remove(QRegularExpression("[^a-z0-9\\-]")); + const QString cardName = cardToQuery->getName(); + const QString formattedName = cardName.toLower().replace(" ", "-").remove(QRegularExpression("[^a-z0-9\\-]")); QString url; if (isCommander) { @@ -166,35 +166,35 @@ void TabEdhRecMain::setCard(CardInfoPtr _cardToQuery, bool isCommander) url = QString("https://json.edhrec.com/pages/cards/%1.json").arg(formattedName); } - QNetworkRequest request{QUrl(url)}; + const QNetworkRequest request{QUrl(url)}; networkManager->get(request); } void TabEdhRecMain::actNavigatePage(QString url) { - QNetworkRequest request{QUrl("https://json.edhrec.com/pages" + url + ".json")}; + const QNetworkRequest request{QUrl("https://json.edhrec.com/pages" + url + ".json")}; networkManager->get(request); } void TabEdhRecMain::getTopCards() { - QNetworkRequest request{QUrl("https://json.edhrec.com/pages/top/year.json")}; + const QNetworkRequest request{QUrl("https://json.edhrec.com/pages/top/year.json")}; networkManager->get(request); } void TabEdhRecMain::getTopCommanders() { - QNetworkRequest request{QUrl("https://json.edhrec.com/pages/commanders/year.json")}; + const QNetworkRequest request{QUrl("https://json.edhrec.com/pages/commanders/year.json")}; networkManager->get(request); } void TabEdhRecMain::getTopTags() { - QNetworkRequest request{QUrl("https://json.edhrec.com/pages/tags.json")}; + const QNetworkRequest request{QUrl("https://json.edhrec.com/pages/tags.json")}; networkManager->get(request); } @@ -207,8 +207,8 @@ void TabEdhRecMain::processApiJson(QNetworkReply *reply) return; } - QByteArray responseData = reply->readAll(); - QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData); + const QByteArray responseData = reply->readAll(); + const QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData); if (!jsonDoc.isObject()) { qDebug() << "Invalid JSON response received."; @@ -216,10 +216,10 @@ void TabEdhRecMain::processApiJson(QNetworkReply *reply) return; } - QJsonObject jsonObj = jsonDoc.object(); + const QJsonObject jsonObj = jsonDoc.object(); // Get the actual URL from the reply - QString responseUrl = reply->url().toString(); + const QString responseUrl = reply->url().toString(); // Check if the response URL matches a commander request if (responseUrl.startsWith("https://json.edhrec.com/pages/commanders/year.json")) { @@ -264,7 +264,7 @@ void TabEdhRecMain::processTopCardsResponse(QJsonObject reply) currentPageLayout = new QVBoxLayout(currentPageDisplay); currentPageDisplay->setLayout(currentPageLayout); - auto display = new EdhrecTopCardsApiResponseDisplayWidget(currentPageDisplay, deckData); + const auto display = new EdhrecTopCardsApiResponseDisplayWidget(currentPageDisplay, deckData); currentPageLayout->addWidget(display); mainLayout->addWidget(currentPageDisplay); @@ -291,7 +291,7 @@ void TabEdhRecMain::processTopTagsResponse(QJsonObject reply) currentPageLayout = new QVBoxLayout(currentPageDisplay); currentPageDisplay->setLayout(currentPageLayout); - auto display = new EdhrecTopTagsApiResponseDisplayWidget(currentPageDisplay, deckData); + const auto display = new EdhrecTopTagsApiResponseDisplayWidget(currentPageDisplay, deckData); currentPageLayout->addWidget(display); mainLayout->addWidget(currentPageDisplay); @@ -318,7 +318,7 @@ void TabEdhRecMain::processTopCommandersResponse(QJsonObject reply) currentPageLayout = new QVBoxLayout(currentPageDisplay); currentPageDisplay->setLayout(currentPageLayout); - auto display = new EdhrecTopCommandersApiResponseDisplayWidget(currentPageDisplay, deckData); + const auto display = new EdhrecTopCommandersApiResponseDisplayWidget(currentPageDisplay, deckData); currentPageLayout->addWidget(display); mainLayout->addWidget(currentPageDisplay); @@ -345,7 +345,7 @@ void TabEdhRecMain::processCommanderResponse(QJsonObject reply, QString response currentPageLayout = new QVBoxLayout(currentPageDisplay); currentPageDisplay->setLayout(currentPageLayout); - auto display = new EdhrecCommanderApiResponseDisplayWidget(currentPageDisplay, deckData, responseUrl); + const auto display = new EdhrecCommanderApiResponseDisplayWidget(currentPageDisplay, deckData, responseUrl); currentPageLayout->addWidget(display); mainLayout->addWidget(currentPageDisplay); diff --git a/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec_main.h b/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec_main.h index 3d4c2fa00..2e52f423c 100644 --- a/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec_main.h +++ b/cockatrice/src/interface/widgets/tabs/api/edhrec/tab_edhrec_main.h @@ -29,7 +29,7 @@ public: void doSearch(); [[nodiscard]] QString getTabText() const override { - auto cardName = cardToQuery.isNull() ? QString() : cardToQuery->getName(); + const auto cardName = cardToQuery.isNull() ? QString() : cardToQuery->getName(); return tr("EDHRec: ") + cardName; } diff --git a/cockatrice/src/interface/widgets/tabs/tab.cpp b/cockatrice/src/interface/widgets/tabs/tab.cpp index 3dcb3b523..8015c59bd 100644 --- a/cockatrice/src/interface/widgets/tabs/tab.cpp +++ b/cockatrice/src/interface/widgets/tabs/tab.cpp @@ -25,7 +25,7 @@ void Tab::showCardInfoPopup(const QPoint &pos, const CardRef &cardRef) Qt::WindowStaysOnTopHint); infoPopup->setAttribute(Qt::WA_TransparentForMouseEvents); - auto screenRect = qApp->primaryScreen()->geometry(); + const auto screenRect = qApp->primaryScreen()->geometry(); infoPopup->move(qMax(screenRect.left(), qMin(pos.x() - infoPopup->width() / 2, screenRect.left() + screenRect.width() - infoPopup->width())), qMax(screenRect.top(), qMin(pos.y() - infoPopup->height() / 2, diff --git a/cockatrice/src/interface/widgets/tabs/tab_deck_editor.cpp b/cockatrice/src/interface/widgets/tabs/tab_deck_editor.cpp index 88f08eae1..f5ce6154b 100644 --- a/cockatrice/src/interface/widgets/tabs/tab_deck_editor.cpp +++ b/cockatrice/src/interface/widgets/tabs/tab_deck_editor.cpp @@ -166,7 +166,7 @@ void TabDeckEditor::retranslateUi() /** @brief Refreshes shortcuts for deck editor menu actions. */ void TabDeckEditor::refreshShortcuts() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aResetLayout->setShortcuts(shortcuts.getShortcut("TabDeckEditor/aResetLayout")); } @@ -299,7 +299,7 @@ void TabDeckEditor::freeDocksSize() /** @brief Handles dock visibility toggling from menu actions. */ void TabDeckEditor::dockVisibleTriggered() { - QObject *o = sender(); + const QObject *o = sender(); if (o == aCardInfoDockVisible) { cardInfoDockWidget->setHidden(!aCardInfoDockVisible->isChecked()); aCardInfoDockFloating->setEnabled(aCardInfoDockVisible->isChecked()); @@ -318,7 +318,7 @@ void TabDeckEditor::dockVisibleTriggered() /** @brief Handles dock floating toggling from menu actions. */ void TabDeckEditor::dockFloatingTriggered() { - QObject *o = sender(); + const QObject *o = sender(); if (o == aCardInfoDockFloating) cardInfoDockWidget->setFloating(aCardInfoDockFloating->isChecked()); else if (o == aDeckDockFloating) @@ -332,7 +332,7 @@ void TabDeckEditor::dockFloatingTriggered() /** @brief Syncs menu state with dock floating changes. */ void TabDeckEditor::dockTopLevelChanged(bool topLevel) { - QObject *o = sender(); + const QObject *o = sender(); if (o == cardInfoDockWidget) aCardInfoDockFloating->setChecked(topLevel); else if (o == deckDockWidget) diff --git a/cockatrice/src/interface/widgets/tabs/tab_server.cpp b/cockatrice/src/interface/widgets/tabs/tab_server.cpp index bd4fa2be3..e79caeffc 100644 --- a/cockatrice/src/interface/widgets/tabs/tab_server.cpp +++ b/cockatrice/src/interface/widgets/tabs/tab_server.cpp @@ -128,11 +128,11 @@ QString RoomSelector::getRoomPermissionDisplay(const ServerInfo_Room &room) void RoomSelector::joinClicked() { - QTreeWidgetItem *twi = roomList->currentItem(); + const QTreeWidgetItem *twi = roomList->currentItem(); if (!twi) return; - int id = twi->data(0, Qt::UserRole).toInt(); + const int id = twi->data(0, Qt::UserRole).toInt(); emit joinRoomRequest(id, true); } diff --git a/cockatrice/src/interface/widgets/tabs/tab_supervisor.cpp b/cockatrice/src/interface/widgets/tabs/tab_supervisor.cpp index 902b1f589..fc4157934 100644 --- a/cockatrice/src/interface/widgets/tabs/tab_supervisor.cpp +++ b/cockatrice/src/interface/widgets/tabs/tab_supervisor.cpp @@ -94,8 +94,9 @@ void CloseButton::paintEvent(QPaintEvent * /*event*/) opt.state |= QStyle::State_Sunken; if (const auto *tb = qobject_cast(parent())) { - int index = tb->currentIndex(); - auto position = (QTabBar::ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, tb); + const int index = tb->currentIndex(); + const auto position = + (QTabBar::ButtonPosition)style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, tb); if (tb->tabButton(index, position) == this) opt.state |= QStyle::State_Selected; } @@ -190,7 +191,7 @@ TabSupervisor::~TabSupervisor() // Note: this used to call stop(), but stop() is doing a bunch of stuff including emitting some signals, // and we don't want to do that in a destructor. - for (auto &localClient : localClients) { + for (const auto &localClient : localClients) { localClient->deleteLater(); } localClients.clear(); @@ -239,10 +240,10 @@ void TabSupervisor::retranslateUi() while (messageIterator.hasNext()) tabs.append(messageIterator.next().value()); - for (auto &tab : tabs) { + for (const auto &tab : tabs) { if (tab) { - int idx = indexOf(tab); - QString tabText = tab->getTabText(); + const int idx = indexOf(tab); + const QString tabText = tab->getTabText(); setTabText(idx, sanitizeTabName(tabText)); setTabToolTip(idx, sanitizeHtml(tabText)); tab->retranslateUi(); @@ -252,7 +253,7 @@ void TabSupervisor::retranslateUi() void TabSupervisor::refreshShortcuts() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aTabDeckEditor->setShortcuts(shortcuts.getShortcut("Tabs/aTabDeckEditor")); aTabVisualDeckEditor->setShortcuts(shortcuts.getShortcut("Tabs/aTabVisualDeckEditor")); @@ -347,8 +348,8 @@ int TabSupervisor::myAddTab(Tab *tab, QAction *manager) connect(tab, &TabGame::userEvent, this, &TabSupervisor::tabUserEvent); connect(tab, &TabGame::tabTextChanged, this, &TabSupervisor::updateTabText); - QString tabText = tab->getTabText(); - int idx = addTab(tab, sanitizeTabName(tabText)); + const QString tabText = tab->getTabText(); + const int idx = addTab(tab, sanitizeTabName(tabText)); setTabToolTip(idx, sanitizeHtml(tabText)); addCloseButtonToTab(tab, idx, manager); @@ -366,7 +367,7 @@ int TabSupervisor::myAddTab(Tab *tab, QAction *manager) */ void TabSupervisor::addCloseButtonToTab(Tab *tab, int tabIndex, QAction *manager) { - auto closeSide = static_cast( + const auto closeSide = static_cast( tabBar()->style()->styleHint(QStyle::SH_TabBar_CloseButtonPosition, nullptr, tabBar())); auto *closeButton = new CloseButton(tab); if (manager) { @@ -460,7 +461,7 @@ void TabSupervisor::stop() resetTabsMenu(); if (!localClients.isEmpty()) { - for (auto &localClient : localClients) { + for (const auto &localClient : localClients) { localClient->deleteLater(); } localClients.clear(); @@ -700,7 +701,7 @@ void TabSupervisor::updatePingTime(int value, int max) void TabSupervisor::gameJoined(const Event_GameJoined &event) { QMap roomGameTypes; - TabRoom *room = roomTabs.value(event.game_info().room_id()); + const TabRoom *room = roomTabs.value(event.game_info().room_id()); if (room) roomGameTypes = room->getGameTypes(); else @@ -845,7 +846,7 @@ void TabSupervisor::talkLeft(TabMessage *tab) */ void TabSupervisor::openDeckInNewTab(DeckLoader *deckToOpen) { - int type = SettingsCache::instance().getDefaultDeckEditorType(); + const int type = SettingsCache::instance().getDefaultDeckEditorType(); switch (type) { case ClassicDeckEditor: addDeckEditorTab(deckToOpen); @@ -942,7 +943,7 @@ void TabSupervisor::tabUserEvent(bool globalEvent) void TabSupervisor::updateTabText(Tab *tab, const QString &newTabText) { - int idx = indexOf(tab); + const int idx = indexOf(tab); setTabText(idx, sanitizeTabName(newTabText)); setTabToolTip(idx, sanitizeHtml(newTabText)); } @@ -956,7 +957,7 @@ void TabSupervisor::processRoomEvent(const RoomEvent &event) void TabSupervisor::processGameEventContainer(const GameEventContainer &cont) { - TabGame *tab = gameTabs.value(cont.game_id()); + const TabGame *tab = gameTabs.value(cont.game_id()); if (tab) tab->getGame()->getGameEventHandler()->processGameEventContainer(cont, qobject_cast(sender()), {}); @@ -966,14 +967,14 @@ void TabSupervisor::processGameEventContainer(const GameEventContainer &cont) void TabSupervisor::processUserMessageEvent(const Event_UserMessage &event) { - QString senderName = QString::fromStdString(event.sender_name()); + const QString senderName = QString::fromStdString(event.sender_name()); TabMessage *tab = messageTabs.value(senderName); 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()); + const auto userLevel = UserLevelFlags(onlineUserInfo->user_level()); if (SettingsCache::instance().getIgnoreUnregisteredUserMessages() && !userLevel.testFlag(ServerInfo_User::IsRegistered)) // Flags are additive, so reg/mod/admin are all IsRegistered @@ -1006,12 +1007,12 @@ void TabSupervisor::processUserLeft(const QString &userName) void TabSupervisor::processUserJoined(const ServerInfo_User &userInfoJoined) { - QString userName = QString::fromStdString(userInfoJoined.name()); + const QString userName = QString::fromStdString(userInfoJoined.name()); if (userListManager->isUserBuddy(userName)) { if (auto *tab = getTabAccount()) { if (tab != currentWidget()) { tab->setContentsChanged(true); - QIcon avatarIcon = UserLevelPixmapGenerator::generateIcon( + const QIcon avatarIcon = UserLevelPixmapGenerator::generateIcon( 13, (UserLevelFlags)userInfoJoined.user_level(), userInfoJoined.pawn_colors(), true, QString::fromStdString(userInfoJoined.privlevel())); setTabIcon(indexOf(tab), avatarIcon); @@ -1108,7 +1109,7 @@ bool TabSupervisor::switchToGameTabIfAlreadyExists(const int gameId) bool isGameTabExists = false; if (gameTabs.contains(gameId)) { isGameTabExists = true; - TabGame *tabGame = gameTabs[gameId]; + const TabGame *tabGame = gameTabs[gameId]; const int gameTabIndex = indexOf(tabGame); setCurrentIndex(gameTabIndex); } diff --git a/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual.cpp b/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual.cpp index 7a811fd28..618ad60cc 100644 --- a/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual.cpp +++ b/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual.cpp @@ -171,7 +171,7 @@ void TabDeckEditorVisual::changeModelIndexAndCardInfo(const ExactCard &activeCar /** @brief Selects the given card in the deck view, checking main and side zones. */ void TabDeckEditorVisual::changeModelIndexToCard(const ExactCard &activeCard) { - QString cardName = activeCard.getName(); + const QString cardName = activeCard.getName(); QModelIndex index = deckDockWidget->deckModel->findCard(cardName, DECK_ZONE_MAIN); if (!index.isValid()) { index = deckDockWidget->deckModel->findCard(cardName, DECK_ZONE_SIDE); @@ -185,7 +185,7 @@ void TabDeckEditorVisual::processMainboardCardClick(QMouseEvent *event, CardInfoPictureWithTextOverlayWidget *instance, const QString &zoneName) { - auto card = instance->getCard(); + const auto card = instance->getCard(); // Get the model index for the card QModelIndex idx = deckDockWidget->deckModel->findCard(card.getName(), zoneName); @@ -219,7 +219,7 @@ void TabDeckEditorVisual::processMainboardCardClick(QMouseEvent *event, // Normal selection behavior if (event->button() == Qt::LeftButton) { - Qt::KeyboardModifiers mods = event->modifiers(); + const Qt::KeyboardModifiers mods = event->modifiers(); QItemSelectionModel::SelectionFlags flags; if (mods.testFlag(Qt::ControlModifier)) { @@ -232,7 +232,7 @@ void TabDeckEditorVisual::processMainboardCardClick(QMouseEvent *event, anchor = idx; } - QItemSelection range(anchor, idx); + const QItemSelection range(anchor, idx); sel->select(range, QItemSelectionModel::SelectCurrent); sel->setCurrentIndex(idx, QItemSelectionModel::NoUpdate); return; @@ -264,7 +264,7 @@ void TabDeckEditorVisual::processCardClickDatabaseDisplay(QMouseEvent *event, bool TabDeckEditorVisual::actSaveDeckAs() { tabContainer->visualDeckView->searchBar->setEnabled(false); - auto result = AbstractTabDeckEditor::actSaveDeckAs(); + const auto result = AbstractTabDeckEditor::actSaveDeckAs(); tabContainer->visualDeckView->searchBar->setEnabled(true); return result; } @@ -298,7 +298,7 @@ void TabDeckEditorVisual::freeDocksSize() /** @brief Refreshes keyboard shortcuts for this tab from settings. */ void TabDeckEditorVisual::refreshShortcuts() { - ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); + const ShortcutsSettings &shortcuts = SettingsCache::instance().shortcuts(); aResetLayout->setShortcuts(shortcuts.getShortcut("TabDeckEditorVisual/aResetLayout")); } @@ -455,7 +455,7 @@ bool TabDeckEditorVisual::eventFilter(QObject *o, QEvent *e) /** @brief Toggles dock visibility based on the corresponding menu action. */ void TabDeckEditorVisual::dockVisibleTriggered() { - QObject *o = sender(); + const QObject *o = sender(); if (o == aCardInfoDockVisible) { cardInfoDockWidget->setHidden(!aCardInfoDockVisible->isChecked()); aCardInfoDockFloating->setEnabled(aCardInfoDockVisible->isChecked()); @@ -484,7 +484,7 @@ void TabDeckEditorVisual::dockVisibleTriggered() /** @brief Toggles dock floating state based on the corresponding menu action. */ void TabDeckEditorVisual::dockFloatingTriggered() { - QObject *o = sender(); + const QObject *o = sender(); if (o == aCardInfoDockFloating) { cardInfoDockWidget->setFloating(aCardInfoDockFloating->isChecked()); return; @@ -509,7 +509,7 @@ void TabDeckEditorVisual::dockFloatingTriggered() /** @brief Updates menu checkboxes when a dock's top-level/floating state changes. */ void TabDeckEditorVisual::dockTopLevelChanged(bool topLevel) { - QObject *o = sender(); + const QObject *o = sender(); if (o == cardInfoDockWidget) { aCardInfoDockFloating->setChecked(topLevel); return; diff --git a/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual_tab_widget.cpp b/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual_tab_widget.cpp index 98b6aff00..b4fe57541 100644 --- a/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual_tab_widget.cpp +++ b/cockatrice/src/interface/widgets/tabs/visual_deck_editor/tab_deck_editor_visual_tab_widget.cpp @@ -113,7 +113,7 @@ void TabDeckEditorVisualTabWidget::addNewTab(QWidget *widget, const QString &tit */ void TabDeckEditorVisualTabWidget::removeCurrentTab() { - int currentIndex = this->currentIndex(); + const int currentIndex = this->currentIndex(); if (currentIndex != -1) { this->removeTab(currentIndex); } @@ -157,7 +157,7 @@ int TabDeckEditorVisualTabWidget::getTabCount() const */ void TabDeckEditorVisualTabWidget::handleTabClose(int index) { - QWidget *tab = this->widget(index); + const QWidget *tab = this->widget(index); this->removeTab(index); delete tab; } diff --git a/cockatrice/src/interface/widgets/tabs/visual_deck_storage/tab_deck_storage_visual.cpp b/cockatrice/src/interface/widgets/tabs/visual_deck_storage/tab_deck_storage_visual.cpp index bfb498909..872e22ab8 100644 --- a/cockatrice/src/interface/widgets/tabs/visual_deck_storage/tab_deck_storage_visual.cpp +++ b/cockatrice/src/interface/widgets/tabs/visual_deck_storage/tab_deck_storage_visual.cpp @@ -27,7 +27,7 @@ TabDeckStorageVisual::TabDeckStorageVisual(TabSupervisor *_tabSupervisor) void TabDeckStorageVisual::actOpenLocalDeck(const QString &filePath) { - auto deckLoader = new DeckLoader(this); + const auto deckLoader = new DeckLoader(this); if (!deckLoader->loadFromFile(filePath, DeckLoader::getFormatFromName(filePath), true)) { QMessageBox::critical(this, tr("Error"), tr("Could not open deck at %1").arg(filePath)); return; diff --git a/cockatrice/src/interface/widgets/utility/custom_line_edit.cpp b/cockatrice/src/interface/widgets/utility/custom_line_edit.cpp index c137b4f35..f2a127840 100644 --- a/cockatrice/src/interface/widgets/utility/custom_line_edit.cpp +++ b/cockatrice/src/interface/widgets/utility/custom_line_edit.cpp @@ -35,7 +35,7 @@ bool LineEditUnfocusable::isUnfocusShortcut(QKeyEvent *event) keyNoMod = QKeySequence(event->key()).toString(); - QKeySequence key(modifier + keyNoMod); + const QKeySequence key(modifier + keyNoMod); QList unfocusShortcut = SettingsCache::instance().shortcuts().getShortcut("Player/unfocusTextBox"); for (const auto &unfocusKey : unfocusShortcut) { @@ -77,7 +77,7 @@ void SearchLineEdit::keyPressEvent(QKeyEvent *event) static const QVector forwardToTreeView = {Qt::Key_Up, Qt::Key_Down, Qt::Key_PageDown, Qt::Key_PageUp}; // forward only if the search text is empty static const QVector forwardWhenEmpty = {Qt::Key_Home, Qt::Key_End}; - Qt::Key key = static_cast(event->key()); + const Qt::Key key = static_cast(event->key()); if (treeView) { if (forwardToTreeView.contains(key)) QCoreApplication::sendEvent(treeView, event); diff --git a/cockatrice/src/interface/widgets/utility/line_edit_completer.cpp b/cockatrice/src/interface/widgets/utility/line_edit_completer.cpp index 7820ad91b..35483598b 100644 --- a/cockatrice/src/interface/widgets/utility/line_edit_completer.cpp +++ b/cockatrice/src/interface/widgets/utility/line_edit_completer.cpp @@ -20,10 +20,10 @@ void LineEditCompleter::focusOutEvent(QFocusEvent *e) // Remove Popup c->popup()->hide(); // Truncate the line to last space or whole string - QString textValue = text(); - int lastIndex = textValue.length(); - int lastWordStartIndex = textValue.lastIndexOf(" ") + 1; - int leftShift = qMin(lastIndex, lastWordStartIndex); + const QString textValue = text(); + const int lastIndex = textValue.length(); + const int lastWordStartIndex = textValue.lastIndexOf(" ") + 1; + const int leftShift = qMin(lastIndex, lastWordStartIndex); setText(textValue.left(leftShift)); // Insert highlighted line from popup insert(c->completionModel()->index(c->popup()->currentIndex().row(), 0).data().toString() + " "); @@ -43,8 +43,8 @@ void LineEditCompleter::keyPressEvent(QKeyEvent *event) // Remove Popup c->popup()->hide(); // Truncate the line to last space or whole string - QString textValue = text(); - int lastIndexof = qMax(0, textValue.lastIndexOf(" ")); + const QString textValue = text(); + const int lastIndexof = qMax(0, textValue.lastIndexOf(" ")); QString finalString = textValue.left(lastIndexof); // Add a space if there's a word if (finalString != "") @@ -59,10 +59,10 @@ void LineEditCompleter::keyPressEvent(QKeyEvent *event) // Remove Popup c->popup()->hide(); // Truncate the line to last space or whole string - QString textValue = text(); - int lastIndex = textValue.length(); - int lastWordStartIndex = textValue.lastIndexOf(" ") + 1; - int leftShift = qMin(lastIndex, lastWordStartIndex); + const QString textValue = text(); + const int lastIndex = textValue.length(); + const int lastWordStartIndex = textValue.lastIndexOf(" ") + 1; + const int leftShift = qMin(lastIndex, lastWordStartIndex); setText(textValue.left(leftShift)); // Insert highlighted line from popup insert(c->completionModel()->index(c->popup()->currentIndex().row(), 0).data().toString() + " "); @@ -108,7 +108,7 @@ QString LineEditCompleter::cursorWord(const QString &line) const void LineEditCompleter::insertCompletion(QString arg) { - QString s_arg = arg + " "; + const QString s_arg = arg + " "; setText(text().replace(text().left(cursorPosition()).lastIndexOf(" ") + 1, cursorPosition() - text().left(cursorPosition()).lastIndexOf(" ") - 1, s_arg)); } diff --git a/cockatrice/src/interface/widgets/utility/sequence_edit.cpp b/cockatrice/src/interface/widgets/utility/sequence_edit.cpp index 7e14d4335..9e68cb481 100644 --- a/cockatrice/src/interface/widgets/utility/sequence_edit.cpp +++ b/cockatrice/src/interface/widgets/utility/sequence_edit.cpp @@ -59,10 +59,10 @@ QString SequenceEdit::getSequence() void SequenceEdit::removeLastShortcut() { - QString sequences = lineEdit->text(); + const QString sequences = lineEdit->text(); if (!sequences.isEmpty()) { if (sequences.lastIndexOf(";") > 0) { - QString validText = sequences.left(sequences.lastIndexOf(";")); + const QString validText = sequences.left(sequences.lastIndexOf(";")); lineEdit->setText(validText); } else { lineEdit->clear(); @@ -178,7 +178,7 @@ bool SequenceEdit::validateShortcut(const QKeySequence &sequence) } if (!shortcutsSettings.isValid(shortcutName, sequenceString)) { - auto overlaps = shortcutsSettings.findOverlaps(shortcutName, sequenceString); + const auto overlaps = shortcutsSettings.findOverlaps(shortcutName, sequenceString); QToolTip::showText(lineEdit->mapToGlobal(QPoint()), tr("Shortcut already in use by:") + " " + overlaps.join(", ")); return true; diff --git a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_color_filter_widget.cpp b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_color_filter_widget.cpp index d4947d6c5..1534abe3b 100644 --- a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_color_filter_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_color_filter_widget.cpp @@ -165,7 +165,7 @@ void VisualDatabaseDisplayColorFilterWidget::updateFilterMode() QList manaSymbolWidgets = findChildren(); - for (ManaSymbolWidget *manaSymbolWidget : manaSymbolWidgets) { + for (const ManaSymbolWidget *manaSymbolWidget : manaSymbolWidgets) { handleColorToggled(manaSymbolWidget->getSymbolChar(), manaSymbolWidget->isColorActive()); } @@ -195,7 +195,7 @@ QList VisualDatabaseDisplayColorFilterWidget::getActiveColors() QList activeColors; QList manaSymbolWidgets = findChildren(); - for (ManaSymbolWidget *manaSymbolWidget : manaSymbolWidgets) { + for (const ManaSymbolWidget *manaSymbolWidget : manaSymbolWidgets) { if (manaSymbolWidget->isColorActive()) { activeColors.append(manaSymbolWidget->getSymbolChar()); } @@ -210,7 +210,7 @@ void VisualDatabaseDisplayColorFilterWidget::syncWithFilterModel() QList manaSymbolWidgets = findChildren(); - for (ManaSymbolWidget *manaSymbolWidget : manaSymbolWidgets) { + for (const ManaSymbolWidget *manaSymbolWidget : manaSymbolWidgets) { bool found = false; for (const CardFilter *filter : allColorFilters) { if (manaSymbolWidget->getSymbolChar() == filter->term()) { diff --git a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_filter_save_load_widget.cpp b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_filter_save_load_widget.cpp index 062774969..dfee5f4c1 100644 --- a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_filter_save_load_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_filter_save_load_widget.cpp @@ -45,11 +45,11 @@ void VisualDatabaseDisplayFilterSaveLoadWidget::retranslateUi() void VisualDatabaseDisplayFilterSaveLoadWidget::saveFilter() { - QString filename = filenameInput->text().trimmed(); + const QString filename = filenameInput->text().trimmed(); if (filename.isEmpty()) return; - QString filePath = SettingsCache::instance().getFiltersPath() + QDir::separator() + filename + ".json"; + const QString filePath = SettingsCache::instance().getFiltersPath() + QDir::separator() + filename + ".json"; // Serialize the filter model to JSON QJsonArray filtersArray; @@ -74,16 +74,16 @@ void VisualDatabaseDisplayFilterSaveLoadWidget::saveFilter() void VisualDatabaseDisplayFilterSaveLoadWidget::loadFilter(const QString &filename) { - QString filePath = SettingsCache::instance().getFiltersPath() + QDir::separator() + filename; + const QString filePath = SettingsCache::instance().getFiltersPath() + QDir::separator() + filename; QFile file(filePath); if (!file.open(QIODevice::ReadOnly)) return; - QByteArray jsonData = file.readAll(); + const QByteArray jsonData = file.readAll(); file.close(); - QJsonDocument doc = QJsonDocument::fromJson(jsonData); + const QJsonDocument doc = QJsonDocument::fromJson(jsonData); if (!doc.isObject()) return; @@ -100,7 +100,7 @@ void VisualDatabaseDisplayFilterSaveLoadWidget::loadFilter(const QString &filena for (const QJsonValue &value : filtersArray) { if (value.isObject()) { QJsonObject filterObj = value.toObject(); - CardFilter *filter = CardFilter::fromJson(filterObj); + const CardFilter *filter = CardFilter::fromJson(filterObj); if (filter) { filterModel->addFilter(filter); } @@ -117,14 +117,14 @@ void VisualDatabaseDisplayFilterSaveLoadWidget::refreshFilterList() { fileListWidget->clearLayout(); // Clear existing widgets - for (auto buttonPair : fileButtons) { + for (const auto buttonPair : fileButtons) { buttonPair.first->deleteLater(); buttonPair.second->deleteLater(); } fileButtons.clear(); // Clear the list of buttons // Refresh the filter file list - QDir dir(SettingsCache::instance().getFiltersPath()); + const QDir dir(SettingsCache::instance().getFiltersPath()); QStringList filterFiles = dir.entryList(QStringList() << "*.json", QDir::Files, QDir::Name); // Loop through the filter files and create widgets for them diff --git a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_main_type_filter_widget.cpp b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_main_type_filter_widget.cpp index 32652c346..ad723dbcb 100644 --- a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_main_type_filter_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_main_type_filter_widget.cpp @@ -78,11 +78,11 @@ void VisualDatabaseDisplayMainTypeFilterWidget::createMainTypeButtons() void VisualDatabaseDisplayMainTypeFilterWidget::updateMainTypeButtonsVisibility() { - int threshold = spinBox->value(); // Get the current spinbox value + const int threshold = spinBox->value(); // Get the current spinbox value // Iterate through buttons and hide/disable those below the threshold for (auto it = typeButtons.begin(); it != typeButtons.end(); ++it) { - bool visible = allMainCardTypesWithCount[it.key()] >= threshold; + const bool visible = allMainCardTypesWithCount[it.key()] >= threshold; it.value()->setVisible(visible); it.value()->setEnabled(visible); } diff --git a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_name_filter_widget.cpp b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_name_filter_widget.cpp index 64eed8b16..ed239a645 100644 --- a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_name_filter_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_name_filter_widget.cpp @@ -20,7 +20,7 @@ VisualDatabaseDisplayNameFilterWidget::VisualDatabaseDisplayNameFilterWidget(QWi layout->addWidget(searchBox); connect(searchBox, &QLineEdit::returnPressed, this, [this]() { - QString text = searchBox->text().trimmed(); + const QString text = searchBox->text().trimmed(); if (!text.isEmpty() && !activeFilters.contains(text)) { createNameFilter(text); searchBox->clear(); @@ -60,17 +60,17 @@ void VisualDatabaseDisplayNameFilterWidget::retranslateUi() void VisualDatabaseDisplayNameFilterWidget::actLoadFromDeck() { - DeckListModel *deckListModel = deckEditor->deckDockWidget->deckModel; + const DeckListModel *deckListModel = deckEditor->deckDockWidget->deckModel; if (!deckListModel) return; - DeckList *decklist = deckListModel->getDeckList(); + const DeckList *decklist = deckListModel->getDeckList(); if (!decklist) return; QList cardsInDeck = decklist->getCardNodes(); - for (auto currentCard : cardsInDeck) { + for (const auto currentCard : cardsInDeck) { createNameFilter(currentCard->getName()); } diff --git a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_set_filter_widget.cpp b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_set_filter_widget.cpp index 1ea6e8e67..3f8a16ea9 100644 --- a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_set_filter_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_set_filter_widget.cpp @@ -126,14 +126,14 @@ void VisualDatabaseDisplaySetFilterWidget::filterToRecentSets() std::sort(allSets.begin(), allSets.end(), [](const auto &a, const auto &b) { return a->getReleaseDate() > b->getReleaseDate(); }); - int setsToPreactivate = SettingsCache::instance().getVisualDatabaseDisplayFilterToMostRecentSetsAmount(); + const int setsToPreactivate = SettingsCache::instance().getVisualDatabaseDisplayFilterToMostRecentSetsAmount(); int setsActivated = 0; for (const auto &set : allSets) { QString shortName = set->getShortName(); QString longName = set->getLongName(); - auto button = setButtons[shortName]; + const auto button = setButtons[shortName]; if (setsActivated < setsToPreactivate) { setsActivated++; @@ -153,14 +153,14 @@ void VisualDatabaseDisplaySetFilterWidget::filterToRecentSets() void VisualDatabaseDisplaySetFilterWidget::updateSetButtonsVisibility() { - QString filterText = searchBox->text().trimmed().toLower(); + const QString filterText = searchBox->text().trimmed().toLower(); for (const QString &setName : setButtons.keys()) { QPushButton *buttonForSet = setButtons[setName]; QString shortName = setName.toLower(); QString longName = buttonForSet->text().toLower(); - bool alwaysVisible = activeSets.contains(setName) && activeSets[setName]; - bool visible = + const bool alwaysVisible = activeSets.contains(setName) && activeSets[setName]; + const bool visible = alwaysVisible || filterText.isEmpty() || shortName.contains(filterText) || longName.contains(filterText); buttonForSet->setVisible(visible); } @@ -247,7 +247,7 @@ void VisualDatabaseDisplaySetFilterWidget::syncWithFilterModel() } // Determine exact match mode based on filter structure - bool newExactMatchMode = !excludedSets.isEmpty(); + const bool newExactMatchMode = !excludedSets.isEmpty(); if (newExactMatchMode != exactMatchMode) { exactMatchMode = newExactMatchMode; @@ -256,7 +256,7 @@ void VisualDatabaseDisplaySetFilterWidget::syncWithFilterModel() // Sync button states with selected sets for (const auto &key : setButtons.keys()) { - bool active = selectedSets.contains(key); + const bool active = selectedSets.contains(key); activeSets[key] = active; setButtons[key]->blockSignals(true); setButtons[key]->setChecked(active); diff --git a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_sub_type_filter_widget.cpp b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_sub_type_filter_widget.cpp index 7a88b51cf..b508d93d1 100644 --- a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_sub_type_filter_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_sub_type_filter_widget.cpp @@ -82,15 +82,15 @@ void VisualDatabaseDisplaySubTypeFilterWidget::createSubTypeButtons() void VisualDatabaseDisplaySubTypeFilterWidget::updateSubTypeButtonsVisibility() { - int threshold = spinBox->value(); - QString filterText = searchBox->text().trimmed().toLower(); + const int threshold = spinBox->value(); + const QString filterText = searchBox->text().trimmed().toLower(); // Iterate through buttons and hide/disable those below the threshold for (auto it = typeButtons.begin(); it != typeButtons.end(); ++it) { QString subType = it.key().toLower(); - bool isActive = activeSubTypes.value(it.key(), false); - bool visible = isActive || (allSubCardTypesWithCount[it.key()] >= threshold && - (filterText.isEmpty() || subType.contains(filterText))); + const bool isActive = activeSubTypes.value(it.key(), false); + const bool visible = isActive || (allSubCardTypesWithCount[it.key()] >= threshold && + (filterText.isEmpty() || subType.contains(filterText))); it.value()->setVisible(visible); it.value()->setEnabled(visible); diff --git a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_widget.cpp b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_widget.cpp index 7171d93b2..92e2bdb03 100644 --- a/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_database_display/visual_database_display_widget.cpp @@ -121,16 +121,16 @@ VisualDatabaseDisplayWidget::VisualDatabaseDisplayWidget(QWidget *parent, sortColumnCombo->adjustSize(); connect(sortColumnCombo, QOverload::of(&QComboBox::currentIndexChanged), this, [this]() { - int column = sortColumnCombo->currentData().toInt(); - Qt::SortOrder order = static_cast(sortOrderCombo->currentData().toInt()); + const int column = sortColumnCombo->currentData().toInt(); + const Qt::SortOrder order = static_cast(sortOrderCombo->currentData().toInt()); databaseView->sortByColumn(column, order); searchModelChanged(); }); connect(sortOrderCombo, QOverload::of(&QComboBox::currentIndexChanged), this, [this]() { - int column = sortColumnCombo->currentData().toInt(); - Qt::SortOrder order = static_cast(sortOrderCombo->currentData().toInt()); + const int column = sortColumnCombo->currentData().toInt(); + const Qt::SortOrder order = static_cast(sortOrderCombo->currentData().toInt()); databaseView->sortByColumn(column, order); searchModelChanged(); @@ -323,7 +323,7 @@ void VisualDatabaseDisplayWidget::addCard(const ExactCard &cardToAdd) void VisualDatabaseDisplayWidget::updateSearch(const QString &search) const { databaseDisplayModel->setStringFilter(search); - QModelIndexList sel = databaseView->selectionModel()->selectedRows(); + const QModelIndexList sel = databaseView->selectionModel()->selectedRows(); if (sel.isEmpty() && databaseDisplayModel->rowCount()) databaseView->selectionModel()->setCurrentIndex(databaseDisplayModel->index(0, 0), QItemSelectionModel::SelectCurrent | QItemSelectionModel::Rows); @@ -368,9 +368,9 @@ void VisualDatabaseDisplayWidget::populateCards() void VisualDatabaseDisplayWidget::loadNextPage() { // Calculate the start and end indices for the next page - int rowCount = databaseDisplayModel->rowCount(); - int start = currentPage * cardsPerPage; - int end = qMin(start + cardsPerPage, rowCount); + const int rowCount = databaseDisplayModel->rowCount(); + const int start = currentPage * cardsPerPage; + const int end = qMin(start + cardsPerPage, rowCount); // Load more cards if we are at the end of the current list and can fetch more if (end >= rowCount && databaseDisplayModel->canFetchMore(QModelIndex())) { @@ -433,8 +433,8 @@ void VisualDatabaseDisplayWidget::databaseDataChanged(const QModelIndex &topLeft void VisualDatabaseDisplayWidget::wheelEvent(QWheelEvent *event) { - int totalCards = databaseDisplayModel->rowCount(); // Total number of cards - int loadedCards = currentPage * cardsPerPage; + const int totalCards = databaseDisplayModel->rowCount(); // Total number of cards + const int loadedCards = currentPage * cardsPerPage; // Handle scrolling down if (event->angleDelta().y() < 0) { diff --git a/cockatrice/src/interface/widgets/visual_database_display/visual_database_filter_display_widget.cpp b/cockatrice/src/interface/widgets/visual_database_display/visual_database_filter_display_widget.cpp index 5364fa813..7ea3777b5 100644 --- a/cockatrice/src/interface/widgets/visual_database_display/visual_database_filter_display_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_database_display/visual_database_filter_display_widget.cpp @@ -38,10 +38,10 @@ FilterDisplayWidget::FilterDisplayWidget(QWidget *parent, const QString &filenam QSize FilterDisplayWidget::sizeHint() const { // Calculate the size based on the filter name and the close button - QFontMetrics fm(font()); - int textWidth = fm.horizontalAdvance(filterFilename); - int width = textWidth + 30 + 16; // Space for the filename and close button - int height = fm.height() + 10; // Height based on font size + padding + const QFontMetrics fm(font()); + const int textWidth = fm.horizontalAdvance(filterFilename); + const int width = textWidth + 30 + 16; // Space for the filename and close button + const int height = fm.height() + 10; // Height based on font size + padding return QSize(width, height); } @@ -63,12 +63,12 @@ void FilterDisplayWidget::loadFilter() void FilterDisplayWidget::deleteFilter() { // Show confirmation dialog before deleting the filter - QMessageBox::StandardButton reply = QMessageBox::question( + const QMessageBox::StandardButton reply = QMessageBox::question( this, tr("Confirm Delete"), tr("Are you sure you want to delete the filter '%1'?").arg(filterFilename), QMessageBox::Yes | QMessageBox::No); if (reply == QMessageBox::Yes) { // If confirmed, delete the filter - QString filePath = SettingsCache::instance().getFiltersPath() + QDir::separator() + filterFilename; + const QString filePath = SettingsCache::instance().getFiltersPath() + QDir::separator() + filterFilename; QFile file(filePath); if (file.remove()) { emit filterDeleted(filterFilename); // Emit signal for deletion diff --git a/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_sample_hand_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_sample_hand_widget.cpp index b1db1cf37..9dc649093 100644 --- a/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_sample_hand_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_sample_hand_widget.cpp @@ -39,7 +39,7 @@ VisualDeckEditorSampleHandWidget::VisualDeckEditorSampleHandWidget(QWidget *pare layout->addWidget(cardSizeWidget); for (const ExactCard &card : getRandomCards(handSizeSpinBox->value())) { - auto displayWidget = new CardInfoPictureWidget(this); + const auto displayWidget = new CardInfoPictureWidget(this); displayWidget->setCard(card); displayWidget->setScaleFactor(cardSizeWidget->getSlider()->value()); flowWidget->addWidget(displayWidget); @@ -65,7 +65,7 @@ void VisualDeckEditorSampleHandWidget::updateDisplay() { flowWidget->clearLayout(); for (const ExactCard &card : getRandomCards(handSizeSpinBox->value())) { - auto displayWidget = new CardInfoPictureWidget(this); + const auto displayWidget = new CardInfoPictureWidget(this); displayWidget->setCard(card); displayWidget->setScaleFactor(cardSizeWidget->getSlider()->value()); connect(cardSizeWidget->getSlider(), &QSlider::valueChanged, displayWidget, @@ -80,14 +80,14 @@ QList VisualDeckEditorSampleHandWidget::getRandomCards(int amountToGe QList randomCards; if (!deckListModel) return randomCards; - DeckList *decklist = deckListModel->getDeckList(); + const DeckList *decklist = deckListModel->getDeckList(); if (!decklist) return randomCards; QList cardsInDeck = decklist->getCardNodes({DECK_ZONE_MAIN}); // Collect all cards in the main deck, allowing duplicates based on their count - for (auto currentCard : cardsInDeck) { + for (const auto currentCard : cardsInDeck) { for (int k = 0; k < currentCard->getNumber(); ++k) { ExactCard card = CardDatabaseManager::query()->getCard(currentCard->toCardRef()); if (card) { diff --git a/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_widget.cpp index c1e5ead3a..caa45a694 100644 --- a/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_deck_editor/visual_deck_editor_widget.cpp @@ -43,7 +43,7 @@ VisualDeckEditorWidget::VisualDeckEditorWidget(QWidget *parent, if (!searchBar->hasFocus()) return; - ExactCard card = CardDatabaseManager::query()->getCard({searchBar->text()}); + const ExactCard card = CardDatabaseManager::query()->getCard({searchBar->text()}); if (card) { emit cardAdditionRequested(card); } @@ -74,7 +74,7 @@ VisualDeckEditorWidget::VisualDeckEditorWidget(QWidget *parent, connect(searchBar, &QLineEdit::textEdited, searchModel, &CardSearchModel::updateSearchResults); connect(searchBar, &QLineEdit::textEdited, this, [=, this](const QString &text) { // Ensure substring matching - QString pattern = ".*" + QRegularExpression::escape(text) + ".*"; + const QString pattern = ".*" + QRegularExpression::escape(text) + ".*"; proxyModel->setFilterRegularExpression(QRegularExpression(pattern, QRegularExpression::CaseInsensitiveOption)); if (!text.isEmpty()) { @@ -95,7 +95,7 @@ VisualDeckEditorWidget::VisualDeckEditorWidget(QWidget *parent, connect(searchBar, &QLineEdit::textEdited, this, [=, this](const QString &text) { if (searchBar->hasFocus() && !searchBar->completer()->popup()->isVisible()) { // Allow text to change when typing, but not when navigating the completer - QString pattern = ".*" + QRegularExpression::escape(text) + ".*"; + const QString pattern = ".*" + QRegularExpression::escape(text) + ".*"; proxyModel->setFilterRegularExpression( QRegularExpression(pattern, QRegularExpression::CaseInsensitiveOption)); } @@ -104,7 +104,7 @@ VisualDeckEditorWidget::VisualDeckEditorWidget(QWidget *parent, // Search button functionality searchPushButton = new QPushButton(this); connect(searchPushButton, &QPushButton::clicked, this, [=, this]() { - ExactCard card = CardDatabaseManager::query()->getCard({searchBar->text()}); + const ExactCard card = CardDatabaseManager::query()->getCard({searchBar->text()}); if (card) { emit cardAdditionRequested(card); } @@ -276,7 +276,7 @@ void VisualDeckEditorWidget::onSelectionChanged(const QItemSelection &selected, void VisualDeckEditorWidget::clearAllDisplayWidgets() { for (auto idx : indexToWidgetMap.keys()) { - auto displayWidget = indexToWidgetMap.value(idx); + const auto displayWidget = indexToWidgetMap.value(idx); zoneContainerLayout->removeWidget(displayWidget); indexToWidgetMap.remove(idx); delete displayWidget; @@ -404,7 +404,7 @@ void VisualDeckEditorWidget::actChangeActiveSortCriteria() { QStringList selectedCriteria; for (int i = 0; i < sortByListWidget->count(); ++i) { - QListWidgetItem *item = sortByListWidget->item(i); + const QListWidgetItem *item = sortByListWidget->item(i); selectedCriteria.append(item->text()); // Collect user-defined sort order } diff --git a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_deck_tags_display_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_deck_tags_display_widget.cpp index b8425e842..febd5e68a 100644 --- a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_deck_tags_display_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_deck_tags_display_widget.cpp @@ -55,7 +55,7 @@ void DeckPreviewDeckTagsDisplayWidget::refreshTags() flowWidget->addWidget(new DeckPreviewTagDisplayWidget(this, tag)); } - auto tagAdditionWidget = new DeckPreviewTagAdditionWidget(this, tr("Edit tags ...")); + const auto tagAdditionWidget = new DeckPreviewTagAdditionWidget(this, tr("Edit tags ...")); connect(tagAdditionWidget, &DeckPreviewTagAdditionWidget::tagClicked, this, &DeckPreviewDeckTagsDisplayWidget::openTagEditDlg); flowWidget->addWidget(tagAdditionWidget); @@ -80,11 +80,11 @@ static QStringList getAllFiles(const QString &filePath) bool confirmOverwriteIfExists(QWidget *parent, const QString &filePath) { - QFileInfo fileInfo(filePath); - QString newFileName = QDir::toNativeSeparators(fileInfo.path() + "/" + fileInfo.completeBaseName() + ".cod"); + const QFileInfo fileInfo(filePath); + const QString newFileName = QDir::toNativeSeparators(fileInfo.path() + "/" + fileInfo.completeBaseName() + ".cod"); if (QFile::exists(newFileName)) { - QMessageBox::StandardButton reply = + const QMessageBox::StandardButton reply = QMessageBox::question(parent, QObject::tr("Overwrite Existing File?"), QObject::tr("A .cod version of this deck already exists. Overwrite it?"), QMessageBox::Yes | QMessageBox::No); diff --git a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_addition_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_addition_widget.cpp index a221442ba..853c6abde 100644 --- a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_addition_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_addition_widget.cpp @@ -25,8 +25,8 @@ DeckPreviewTagAdditionWidget::DeckPreviewTagAdditionWidget(QWidget *_parent, QSt QSize DeckPreviewTagAdditionWidget::sizeHint() const { // Calculate the size based on the tag name - QFontMetrics fm(font()); - int textWidth = fm.horizontalAdvance(tagName_); + const QFontMetrics fm(font()); + const int textWidth = fm.horizontalAdvance(tagName_); int width = textWidth + 50; // Add extra padding int height = fm.height() + 10; // Height based on font size + padding @@ -46,7 +46,7 @@ void DeckPreviewTagAdditionWidget::paintEvent(QPaintEvent *event) QPainter painter(this); // Set background color - QColor backgroundColor = Qt::lightGray; + const QColor backgroundColor = Qt::lightGray; painter.setBrush(backgroundColor); painter.setPen(Qt::NoPen); @@ -54,20 +54,20 @@ void DeckPreviewTagAdditionWidget::paintEvent(QPaintEvent *event) painter.drawRect(rect()); // Draw border - QColor borderColor = Qt::gray; - QPen borderPen(borderColor, 1); + const QColor borderColor = Qt::gray; + const QPen borderPen(borderColor, 1); painter.setPen(borderPen); painter.drawRect(rect().adjusted(0, 0, -1, -1)); // Adjust for pen width // Calculate font size based on widget height QFont font = painter.font(); - int fontSize = std::max(10, height() / 2); // Ensure a minimum font size of 10 + const int fontSize = std::max(10, height() / 2); // Ensure a minimum font size of 10 font.setPointSize(fontSize); painter.setFont(font); // Calculate text rect with margin - int margin = 10; // Left and right margins - QRect textRect(margin, 0, width() - margin * 2, height()); + const int margin = 10; // Left and right margins + const QRect textRect(margin, 0, width() - margin * 2, height()); // Draw the text with a black border for better legibility painter.setPen(Qt::black); diff --git a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_dialog.cpp b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_dialog.cpp index df7f9738d..d06527df6 100644 --- a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_dialog.cpp +++ b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_dialog.cpp @@ -20,7 +20,7 @@ DeckPreviewTagDialog::DeckPreviewTagDialog(const QStringList &knownTags, { resize(400, 500); - QStringList defaultTags = SettingsCache::instance().getVisualDeckStorageDefaultTagsList(); + const QStringList defaultTags = SettingsCache::instance().getVisualDeckStorageDefaultTagsList(); // Merge knownTags with defaultTags, ensuring no duplicates QStringList combinedTags = defaultTags + knownTags + activeTags; @@ -115,7 +115,7 @@ void DeckPreviewTagDialog::refreshTagList() tagListView->clear(); // Get the updated list of tags from SettingsCache - QStringList defaultTags = SettingsCache::instance().getVisualDeckStorageDefaultTagsList(); + const QStringList defaultTags = SettingsCache::instance().getVisualDeckStorageDefaultTagsList(); QStringList combinedTags = defaultTags + knownTags_ + activeTags; combinedTags.removeDuplicates(); @@ -137,7 +137,7 @@ QStringList DeckPreviewTagDialog::getActiveTags() const void DeckPreviewTagDialog::addTag() { - QString newTag = newTagInput->text().trimmed(); + const QString newTag = newTagInput->text().trimmed(); if (newTag.isEmpty()) { QMessageBox::warning(this, tr("Invalid Input"), tr("Tag name cannot be empty!")); return; @@ -146,7 +146,7 @@ void DeckPreviewTagDialog::addTag() // Prevent duplicate tags for (int i = 0; i < tagListView->count(); ++i) { auto *item = tagListView->item(i); - auto *tagWidget = qobject_cast(tagListView->itemWidget(item)); + const auto *tagWidget = qobject_cast(tagListView->itemWidget(item)); if (tagWidget && tagWidget->checkBox()->text() == newTag) { QMessageBox::warning(this, tr("Duplicate Tag"), tr("This tag already exists.")); return; @@ -170,9 +170,9 @@ void DeckPreviewTagDialog::filterTags(const QString &text) { for (int i = 0; i < tagListView->count(); ++i) { auto *item = tagListView->item(i); - auto *tagWidget = qobject_cast(tagListView->itemWidget(item)); + const auto *tagWidget = qobject_cast(tagListView->itemWidget(item)); if (tagWidget) { - bool matches = tagWidget->checkBox()->text().contains(text, Qt::CaseInsensitive); + const bool matches = tagWidget->checkBox()->text().contains(text, Qt::CaseInsensitive); item->setHidden(!matches); } } @@ -183,7 +183,7 @@ void DeckPreviewTagDialog::onCheckboxStateChanged() activeTags.clear(); for (int i = 0; i < tagListView->count(); ++i) { auto *item = tagListView->item(i); - auto *tagWidget = qobject_cast(tagListView->itemWidget(item)); + const auto *tagWidget = qobject_cast(tagListView->itemWidget(item)); if (tagWidget && tagWidget->checkBox()->isChecked()) { activeTags.append(tagWidget->checkBox()->text()); } diff --git a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_display_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_display_widget.cpp index db466b77a..04cd8892f 100644 --- a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_display_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_tag_display_widget.cpp @@ -38,10 +38,10 @@ DeckPreviewTagDisplayWidget::DeckPreviewTagDisplayWidget(QWidget *parent, const QSize DeckPreviewTagDisplayWidget::sizeHint() const { // Calculate the size based on the tag name and close button - QFontMetrics fm(font()); - int textWidth = fm.horizontalAdvance(tagName); - int width = textWidth + 50; // Add extra padding - int height = fm.height() + 10; // Height based on font size + padding + const QFontMetrics fm(font()); + const int textWidth = fm.horizontalAdvance(tagName); + const int width = textWidth + 50; // Add extra padding + const int height = fm.height() + 10; // Height based on font size + padding return QSize(width, height); } diff --git a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_widget.cpp index b330b0c4c..84357f513 100644 --- a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_widget.cpp @@ -73,9 +73,9 @@ void DeckPreviewWidget::initializeUi(const bool deckLoadSuccess) if (!deckLoadSuccess) { return; } - auto bannerCard = deckLoader->getDeckList()->getBannerCard().name.isEmpty() - ? ExactCard() - : CardDatabaseManager::query()->getCard(deckLoader->getDeckList()->getBannerCard()); + const auto bannerCard = deckLoader->getDeckList()->getBannerCard().name.isEmpty() + ? ExactCard() + : CardDatabaseManager::query()->getCard(deckLoader->getDeckList()->getBannerCard()); bannerCardDisplayWidget->setCard(bannerCard); bannerCardDisplayWidget->setFontSize(24); @@ -207,7 +207,7 @@ void DeckPreviewWidget::refreshBannerCardText() void DeckPreviewWidget::refreshBannerCardToolTip() { - auto type = visualDeckStorageWidget->settings()->getDeckPreviewTooltip(); + const auto type = visualDeckStorageWidget->settings()->getDeckPreviewTooltip(); switch (type) { case VisualDeckStorageQuickSettingsWidget::TooltipType::None: bannerCardDisplayWidget->setToolTip(""); @@ -221,10 +221,10 @@ void DeckPreviewWidget::refreshBannerCardToolTip() void DeckPreviewWidget::updateBannerCardComboBox() { // Store the current text of the combo box - QString currentText = bannerCardComboBox->currentText(); + const QString currentText = bannerCardComboBox->currentText(); // Block signals temporarily - bool wasBlocked = bannerCardComboBox->blockSignals(true); + const bool wasBlocked = bannerCardComboBox->blockSignals(true); bannerCardComboBox->setUpdatesEnabled(false); // Clear the existing items in the combo box @@ -235,7 +235,7 @@ void DeckPreviewWidget::updateBannerCardComboBox() QList cardsInDeck = deckLoader->getDeckList()->getCardNodes(); - for (auto currentCard : cardsInDeck) { + for (const auto currentCard : cardsInDeck) { for (int k = 0; k < currentCard->getNumber(); ++k) { bannerCardSet.insert(QPair(currentCard->getName(), currentCard->getCardProviderId())); } @@ -262,12 +262,12 @@ void DeckPreviewWidget::updateBannerCardComboBox() bannerCardComboBox->setModel(model); // Try to restore the previous selection by finding the currentText - int restoredIndex = bannerCardComboBox->findText(currentText); + const int restoredIndex = bannerCardComboBox->findText(currentText); if (restoredIndex != -1) { bannerCardComboBox->setCurrentIndex(restoredIndex); } else { // Add a placeholder "-" and set it as the current selection - int bannerIndex = bannerCardComboBox->findText(deckLoader->getDeckList()->getBannerCard().name); + const int bannerIndex = bannerCardComboBox->findText(deckLoader->getDeckList()->getBannerCard().name); if (bannerIndex != -1) { bannerCardComboBox->setCurrentIndex(bannerIndex); } else { @@ -284,7 +284,7 @@ void DeckPreviewWidget::updateBannerCardComboBox() void DeckPreviewWidget::setBannerCard(int /* changedIndex */) { auto [name, id] = bannerCardComboBox->currentData().value>(); - CardRef cardRef = {name, id}; + const CardRef cardRef = {name, id}; deckLoader->getDeckList()->setBannerCard(cardRef); deckLoader->saveToFile(filePath, DeckLoader::getFormatFromName(filePath)); bannerCardDisplayWidget->setCard(CardDatabaseManager::query()->getCard(cardRef)); @@ -323,7 +323,7 @@ QMenu *DeckPreviewWidget::createRightClickMenu() connect(menu->addAction(tr("Rename Deck")), &QAction::triggered, this, &DeckPreviewWidget::actRenameDeck); - auto saveToClipboardMenu = menu->addMenu(tr("Save Deck to Clipboard")); + const auto saveToClipboardMenu = menu->addMenu(tr("Save Deck to Clipboard")); connect(saveToClipboardMenu->addAction(tr("Annotated")), &QAction::triggered, this, [this] { DeckLoader::saveToClipboard(deckLoader->getDeckList(), true, true); }); @@ -353,10 +353,10 @@ void DeckPreviewWidget::addSetBannerCardMenu(QMenu *menu) return; } - auto bannerCardMenu = menu->addMenu(tr("Set Banner Card")); + const auto bannerCardMenu = menu->addMenu(tr("Set Banner Card")); for (int i = 0; i < bannerCardComboBox->count(); ++i) { - auto action = bannerCardMenu->addAction(bannerCardComboBox->itemText(i)); + const auto action = bannerCardMenu->addAction(bannerCardComboBox->itemText(i)); connect(action, &QAction::triggered, this, [this, i] { bannerCardComboBox->setCurrentIndex(i); }); // the checkability is purely for visuals @@ -371,7 +371,8 @@ void DeckPreviewWidget::actRenameDeck() const QString oldName = deckLoader->getDeckList()->getName(); bool ok; - QString newName = QInputDialog::getText(this, "Rename deck", tr("New name:"), QLineEdit::Normal, oldName, &ok); + const QString newName = + QInputDialog::getText(this, "Rename deck", tr("New name:"), QLineEdit::Normal, oldName, &ok); if (!ok || oldName == newName) { return; } @@ -391,7 +392,8 @@ void DeckPreviewWidget::actRenameFile() const QString oldName = info.baseName(); bool ok; - QString newName = QInputDialog::getText(this, "Rename file", tr("New name:"), QLineEdit::Normal, oldName, &ok); + const QString newName = + QInputDialog::getText(this, "Rename file", tr("New name:"), QLineEdit::Normal, oldName, &ok); if (!ok || newName.isEmpty() || oldName == newName) { return; } @@ -420,8 +422,9 @@ void DeckPreviewWidget::actRenameFile() void DeckPreviewWidget::actDeleteFile() { // read input - auto res = QMessageBox::warning(this, tr("Delete file"), tr("Are you sure you want to delete the selected file?"), - QMessageBox::Yes | QMessageBox::No); + const auto res = + QMessageBox::warning(this, tr("Delete file"), tr("Are you sure you want to delete the selected file?"), + QMessageBox::Yes | QMessageBox::No); if (res != QMessageBox::Yes) { return; } diff --git a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_widget.h b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_widget.h index 76db9e569..aaede0205 100644 --- a/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_widget.h +++ b/cockatrice/src/interface/widgets/visual_deck_storage/deck_preview/deck_preview_widget.h @@ -84,13 +84,13 @@ protected: bool eventFilter(QObject *obj, QEvent *event) override { if (event->type() == QEvent::Wheel) { - if (auto *combo = qobject_cast(obj)) { + if (const auto *combo = qobject_cast(obj)) { // If popup is not open, forward event to parent scroll area if (!combo->view()->isVisible()) { // Try to find a scrollable parent and manually send the event QWidget *parent = combo->parentWidget(); while (parent) { - if (auto *scroll = qobject_cast(parent)) { + if (const auto *scroll = qobject_cast(parent)) { QApplication::sendEvent(scroll->viewport(), event); return true; // Mark event as handled } diff --git a/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_folder_display_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_folder_display_widget.cpp index c5758c5a6..a24141aa1 100644 --- a/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_folder_display_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_folder_display_widget.cpp @@ -42,7 +42,7 @@ VisualDeckStorageFolderDisplayWidget::VisualDeckStorageFolderDisplayWidget( void VisualDeckStorageFolderDisplayWidget::refreshUi() { QString bannerText = tr("Deck Storage"); - QString deckPath = SettingsCache::instance().getDeckPath(); + const QString deckPath = SettingsCache::instance().getDeckPath(); if (filePath != deckPath) { QString relativePath = filePath; @@ -69,7 +69,7 @@ static QStringList getAllFiles(const QString &filePath, bool recursive) QStringList allFiles; // QDirIterator with QDir::Files ensures only files are listed (no directories) - auto flags = + const auto flags = recursive ? QDirIterator::Subdirectories | QDirIterator::FollowSymlinks : QDirIterator::NoIteratorFlags; QDirIterator it(filePath, DeckLoader::ACCEPTED_FILE_EXTENSIONS, QDir::Files, flags); @@ -110,7 +110,7 @@ void VisualDeckStorageFolderDisplayWidget::createWidgetsForFiles() */ void VisualDeckStorageFolderDisplayWidget::updateVisibility(bool recursive) { - bool atLeastOneWidgetVisible = checkVisibility(); + const bool atLeastOneWidgetVisible = checkVisibility(); if (atLeastOneWidgetVisible) { setVisible(true); for (DeckPreviewWidget *display : flowWidget->findChildren()) { @@ -131,7 +131,7 @@ bool VisualDeckStorageFolderDisplayWidget::checkVisibility() bool atLeastOneWidgetVisible = false; if (flowWidget) { // Iterate through all DeckPreviewWidgets - for (DeckPreviewWidget *display : flowWidget->findChildren()) { + for (const DeckPreviewWidget *display : flowWidget->findChildren()) { if (display->checkVisibility()) { atLeastOneWidgetVisible = true; } @@ -208,7 +208,7 @@ QStringList VisualDeckStorageFolderDisplayWidget::gatherAllTagsFromFlowWidget() if (flowWidget) { // Iterate through all DeckPreviewWidgets - for (DeckPreviewWidget *display : flowWidget->findChildren()) { + for (const DeckPreviewWidget *display : flowWidget->findChildren()) { // Get tags from each DeckPreviewWidget QStringList tags = display->deckLoader->getDeckList()->getTags(); diff --git a/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_quick_settings_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_quick_settings_widget.cpp index c1e9bfa6a..0f340c6c0 100644 --- a/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_quick_settings_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_quick_settings_widget.cpp @@ -52,7 +52,7 @@ VisualDeckStorageQuickSettingsWidget::VisualDeckStorageQuickSettingsWidget(QWidg &SettingsCache::setVisualDeckStorageDrawUnusedColorIdentities); // color identity opacity selector - auto unusedColorIdentityOpacityWidget = new QWidget(this); + const auto unusedColorIdentityOpacityWidget = new QWidget(this); unusedColorIdentitiesOpacityLabel = new QLabel(unusedColorIdentityOpacityWidget); unusedColorIdentitiesOpacitySpinBox = new QSpinBox(unusedColorIdentityOpacityWidget); @@ -68,13 +68,13 @@ VisualDeckStorageQuickSettingsWidget::VisualDeckStorageQuickSettingsWidget(QWidg unusedColorIdentitiesOpacityLabel->setBuddy(unusedColorIdentitiesOpacitySpinBox); - auto unusedColorIdentityOpacityLayout = new QHBoxLayout(unusedColorIdentityOpacityWidget); + const auto unusedColorIdentityOpacityLayout = new QHBoxLayout(unusedColorIdentityOpacityWidget); unusedColorIdentityOpacityLayout->setContentsMargins(11, 0, 11, 0); unusedColorIdentityOpacityLayout->addWidget(unusedColorIdentitiesOpacityLabel); unusedColorIdentityOpacityLayout->addWidget(unusedColorIdentitiesOpacitySpinBox); // tooltip selector - auto deckPreviewTooltipWidget = new QWidget(this); + const auto deckPreviewTooltipWidget = new QWidget(this); deckPreviewTooltipLabel = new QLabel(deckPreviewTooltipWidget); deckPreviewTooltipComboBox = new QComboBox(deckPreviewTooltipWidget); @@ -88,7 +88,7 @@ VisualDeckStorageQuickSettingsWidget::VisualDeckStorageQuickSettingsWidget(QWidg connect(deckPreviewTooltipComboBox, QOverload::of(&QComboBox::currentIndexChanged), &SettingsCache::instance(), &SettingsCache::setVisualDeckStorageTooltipType); - auto deckPreviewTooltipLayout = new QHBoxLayout(deckPreviewTooltipWidget); + const auto deckPreviewTooltipLayout = new QHBoxLayout(deckPreviewTooltipWidget); deckPreviewTooltipLayout->setContentsMargins(11, 0, 11, 0); deckPreviewTooltipLayout->addWidget(deckPreviewTooltipLabel); deckPreviewTooltipLayout->addWidget(deckPreviewTooltipComboBox); diff --git a/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_sort_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_sort_widget.cpp index ad49e0065..6bbaa54a2 100644 --- a/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_sort_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_sort_widget.cpp @@ -40,7 +40,7 @@ void VisualDeckStorageSortWidget::retranslateUi() // Block signals to avoid triggering unnecessary updates while changing text sortComboBox->blockSignals(true); - int oldIndex = sortComboBox->currentIndex(); + const int oldIndex = sortComboBox->currentIndex(); // Clear and repopulate the ComboBox with translated items sortComboBox->clear(); @@ -67,8 +67,8 @@ void VisualDeckStorageSortWidget::sortFolder(VisualDeckStorageFolderDisplayWidge { auto children = folderWidget->getFlowWidget()->findChildren(QString(), Qt::FindChildOption::FindDirectChildrenOnly); - for (auto widget : children) { - auto deckPreviewWidgets = + for (const auto widget : children) { + const auto deckPreviewWidgets = widget->findChildren(QString(), Qt::FindChildOption::FindDirectChildrenOnly); auto newOrder = filterFiles(deckPreviewWidgets); for (DeckPreviewWidget *previewWidget : newOrder) { @@ -88,8 +88,8 @@ QList VisualDeckStorageSortWidget::filterFiles(QListfilePath); - QFileInfo info2(widget2->filePath); + const QFileInfo info1(widget1->filePath); + const QFileInfo info2(widget2->filePath); switch (sortOrder) { case ByName: @@ -99,8 +99,10 @@ QList VisualDeckStorageSortWidget::filterFiles(QList info2.lastModified(); case ByLastLoaded: { - QDateTime time1 = QDateTime::fromString(widget1->deckLoader->getDeckList()->getLastLoadedTimestamp()); - QDateTime time2 = QDateTime::fromString(widget2->deckLoader->getDeckList()->getLastLoadedTimestamp()); + const QDateTime time1 = + QDateTime::fromString(widget1->deckLoader->getDeckList()->getLastLoadedTimestamp()); + const QDateTime time2 = + QDateTime::fromString(widget2->deckLoader->getDeckList()->getLastLoadedTimestamp()); return time1 > time2; } } diff --git a/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_tag_filter_widget.cpp b/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_tag_filter_widget.cpp index 4e78a67c4..d2838bf69 100644 --- a/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_tag_filter_widget.cpp +++ b/cockatrice/src/interface/widgets/visual_deck_storage/visual_deck_storage_tag_filter_widget.cpp @@ -37,7 +37,7 @@ void VisualDeckStorageTagFilterWidget::filterDecksBySelectedTags(const QList()) { + for (const DeckPreviewTagDisplayWidget *tagWidget : findChildren()) { switch (tagWidget->getState()) { case TagState::Selected: selectedTags.append(tagWidget->getTagName()); @@ -61,11 +61,11 @@ void VisualDeckStorageTagFilterWidget::filterDecksBySelectedTags(const QListdeckLoader->getDeckList()->getTags(); - bool hasAllSelected = std::all_of(selectedTags.begin(), selectedTags.end(), - [&deckTags](const QString &tag) { return deckTags.contains(tag); }); + const bool hasAllSelected = std::all_of(selectedTags.begin(), selectedTags.end(), + [&deckTags](const QString &tag) { return deckTags.contains(tag); }); - bool hasAnyExcluded = std::any_of(excludedTags.begin(), excludedTags.end(), - [&deckTags](const QString &tag) { return deckTags.contains(tag); }); + const bool hasAnyExcluded = std::any_of(excludedTags.begin(), excludedTags.end(), + [&deckTags](const QString &tag) { return deckTags.contains(tag); }); // Filter out if any excluded tag is present or if any selected tag is missing deckPreview->filteredByTags = !(hasAllSelected && !hasAnyExcluded); @@ -74,7 +74,7 @@ void VisualDeckStorageTagFilterWidget::filterDecksBySelectedTags(const QList allTags = gatherAllTags(); + const QSet allTags = gatherAllTags(); removeTagsNotInList(allTags); addTagsIfNotPresent(allTags); sortTags(); @@ -82,7 +82,7 @@ void VisualDeckStorageTagFilterWidget::refreshTags() void VisualDeckStorageTagFilterWidget::removeTagsNotInList(const QSet &tags) { - auto *flowWidget = findChild(); + const auto *flowWidget = findChild(); for (DeckPreviewTagDisplayWidget *tagWidget : findChildren()) { const QString &tagName = tagWidget->getTagName(); @@ -106,7 +106,7 @@ void VisualDeckStorageTagFilterWidget::addTagIfNotPresent(const QString &tag) { // Check if the tag already exists in the flow widget bool tagExists = false; - for (DeckPreviewTagDisplayWidget *tagWidget : findChildren()) { + for (const DeckPreviewTagDisplayWidget *tagWidget : findChildren()) { if (tagWidget->getTagName() == tag) { tagExists = true; break; @@ -120,14 +120,14 @@ void VisualDeckStorageTagFilterWidget::addTagIfNotPresent(const QString &tag) &VisualDeckStorageWidget::updateTagFilter); connect(newTagWidget, &DeckPreviewTagDisplayWidget::tagClicked, this, &VisualDeckStorageTagFilterWidget::refreshTags); - auto *flowWidget = findChild(); + const auto *flowWidget = findChild(); flowWidget->addWidget(newTagWidget); } } void VisualDeckStorageTagFilterWidget::sortTags() { - auto *flowWidget = findChild(); + const auto *flowWidget = findChild(); if (!flowWidget) return; @@ -153,7 +153,7 @@ QSet VisualDeckStorageTagFilterWidget::gatherAllTags() const QSet allTags; QList deckWidgets = parent->findChildren(); - for (DeckPreviewWidget *widget : deckWidgets) { + for (const DeckPreviewWidget *widget : deckWidgets) { if (widget->checkVisibility()) { for (const QString &tag : widget->deckLoader->getDeckList()->getTags()) { allTags.insert(tag); @@ -167,7 +167,7 @@ QStringList VisualDeckStorageTagFilterWidget::getAllKnownTags() const { QStringList allTags; - for (DeckPreviewTagDisplayWidget *tagWidget : findChildren()) { + for (const DeckPreviewTagDisplayWidget *tagWidget : findChildren()) { allTags.append(tagWidget->getTagName()); } diff --git a/cockatrice/src/main.cpp b/cockatrice/src/main.cpp index f20dab6fb..df45c8455 100644 --- a/cockatrice/src/main.cpp +++ b/cockatrice/src/main.cpp @@ -62,12 +62,12 @@ static void CockatriceLogger(QtMsgType type, const QMessageLogContext &ctx, cons QString logMessage = qFormatLogMessage(type, ctx, message); // Regular expression to match the full path in the square brackets and extract only the filename and line number - QRegularExpression regex(R"(\[(?:.:)?[\/\\].*[\/\\]([^\/\\]+\:\d+)\])"); - QRegularExpressionMatch match = regex.match(logMessage); + const QRegularExpression regex(R"(\[(?:.:)?[\/\\].*[\/\\]([^\/\\]+\:\d+)\])"); + const QRegularExpressionMatch match = regex.match(logMessage); if (match.hasMatch()) { // Extract the filename and line number (e.g., "main.cpp:211") - QString filenameLine = match.captured(1); + const QString filenameLine = match.captured(1); // Replace the full path in square brackets with just the filename and line number logMessage.replace(match.captured(0), QString("[%1]").arg(filenameLine)); @@ -108,7 +108,7 @@ LONG WINAPI CockatriceUnhandledExceptionFilter(EXCEPTION_POINTERS *exceptionPoin // Create and write crash files #ifdef UNICODE - HANDLE hDumpFile = + const HANDLE hDumpFile = CreateFile(path.wstring().c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); #else HANDLE hDumpFile = @@ -131,16 +131,16 @@ LONG WINAPI CockatriceUnhandledExceptionFilter(EXCEPTION_POINTERS *exceptionPoin void installNewTranslator() { - QString lang = SettingsCache::instance().getLang(); + const QString lang = SettingsCache::instance().getLang(); - QString qtNameHint = "qt_" + lang; + const QString qtNameHint = "qt_" + lang; #if (QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)) - QString qtTranslationPath = QLibraryInfo::path(QLibraryInfo::TranslationsPath); + const QString qtTranslationPath = QLibraryInfo::path(QLibraryInfo::TranslationsPath); #else QString qtTranslationPath = QLibraryInfo::location(QLibraryInfo::TranslationsPath); #endif - bool qtTranslationLoaded = qtTranslator->load(qtNameHint, qtTranslationPath); + const bool qtTranslationLoaded = qtTranslator->load(qtNameHint, qtTranslationPath); if (!qtTranslationLoaded) { qCWarning(QtTranslatorDebug) << "Unable to load qt translation" << qtNameHint << "at" << qtTranslationPath; } else { @@ -148,8 +148,8 @@ void installNewTranslator() } qApp->installTranslator(qtTranslator); - QString appNameHint = translationPrefix + "_" + lang; - bool appTranslationLoaded = qtTranslator->load(appNameHint, translationPath); + const QString appNameHint = translationPrefix + "_" + lang; + const bool appTranslationLoaded = qtTranslator->load(appNameHint, translationPath); if (!appTranslationLoaded) { qCWarning(QtTranslatorDebug) << "Unable to load" << translationPrefix << "translation" << appNameHint << "at" << translationPath; @@ -199,7 +199,7 @@ int main(int argc, char *argv[]) "\033[0m[%{time yyyy-MM-dd h:mm:ss.zzz} " "%{if-debug}\033[36mD%{endif}%{if-info}\033[32mI%{endif}%{if-warning}\033[33mW%{endif}%{if-critical}\033[31mC%{" "endif}%{if-fatal}\033[1;31mF%{endif}\033[0m] [%{function}] - %{message} [%{file}:%{line}]"); - QApplication app(argc, argv); + const QApplication app(argc, argv); QObject::connect(&app, &QApplication::lastWindowClosed, &app, &QApplication::quit); diff --git a/libcockatrice_card/libcockatrice/card/card_info.cpp b/libcockatrice_card/libcockatrice/card/card_info.cpp index 3054a10cf..f2269f2a1 100644 --- a/libcockatrice_card/libcockatrice/card/card_info.cpp +++ b/libcockatrice_card/libcockatrice/card/card_info.cpp @@ -158,7 +158,7 @@ QString CardInfo::simplifyName(const QString &name) const QChar CardInfo::getColorChar() const { - QString colors = getColors(); + const QString colors = getColors(); switch (colors.size()) { case 0: return QChar(); diff --git a/libcockatrice_card/libcockatrice/card/database/card_database.cpp b/libcockatrice_card/libcockatrice/card/database/card_database.cpp index 57b3ce06e..1b0e7f419 100644 --- a/libcockatrice_card/libcockatrice/card/database/card_database.cpp +++ b/libcockatrice_card/libcockatrice/card/database/card_database.cpp @@ -74,8 +74,8 @@ void CardDatabase::refreshCachedReverseRelatedCards() } for (const auto &card : cards) { - for (auto *rel : card->getReverseRelatedCards()) { - if (auto target = cards.value(rel->getName())) { + for (const auto *rel : card->getReverseRelatedCards()) { + if (const auto target = cards.value(rel->getName())) { auto *newRel = new CardRelation(card->getName(), rel->getAttachType(), rel->getIsCreateAllExclusion(), rel->getIsVariable(), rel->getDefaultCount(), rel->getIsPersistent()); target->addReverseRelatedCards2Me(newRel); @@ -91,10 +91,10 @@ void CardDatabase::addCard(CardInfoPtr card) return; } - auto name = card->getName(); + const auto name = card->getName(); // If a card already exists, just add the new set property. - if (auto existing = cards.value(name)) { + if (const auto existing = cards.value(name)) { for (const auto &printings : card->getSets()) for (const auto &printing : printings) existing->addToSet(printing.getSet(), printing); @@ -161,8 +161,8 @@ void CardDatabase::checkUnknownSets() if (_sets.getEnabledSetsNum()) { // if some sets are first found on this run, ask the user - int numUnknownSets = _sets.getUnknownSetsNum(); - QStringList unknownSetNames = _sets.getUnknownSetsNames(); + const int numUnknownSets = _sets.getUnknownSetsNum(); + const QStringList unknownSetNames = _sets.getUnknownSetsNames(); if (numUnknownSets > 0) { emit cardDatabaseNewSetsFound(numUnknownSets, unknownSetNames); } else { diff --git a/libcockatrice_card/libcockatrice/card/database/card_database_loader.cpp b/libcockatrice_card/libcockatrice/card/database/card_database_loader.cpp index f56f6a0b5..3ba86dd5a 100644 --- a/libcockatrice_card/libcockatrice/card/database/card_database_loader.cpp +++ b/libcockatrice_card/libcockatrice/card/database/card_database_loader.cpp @@ -19,7 +19,7 @@ CardDatabaseLoader::CardDatabaseLoader(QObject *parent, availableParsers << new CockatriceXml4Parser(_preferenceProvider); availableParsers << new CockatriceXml3Parser; - for (auto *p : availableParsers) { + for (const auto *p : availableParsers) { // connect parser outputs to the database adders connect(p, &ICardDatabaseParser::addCard, database, &CardDatabase::addCard, Qt::DirectConnection); connect(p, &ICardDatabaseParser::addSet, database, &CardDatabase::addSet, Qt::DirectConnection); @@ -43,7 +43,7 @@ LoadStatus CardDatabaseLoader::loadFromFile(const QString &fileName) return FileError; } - for (auto parser : availableParsers) { + for (const auto parser : availableParsers) { file.reset(); if (parser->getCanParseFile(fileName, file)) { file.reset(); @@ -57,14 +57,14 @@ LoadStatus CardDatabaseLoader::loadFromFile(const QString &fileName) LoadStatus CardDatabaseLoader::loadCardDatabase(const QString &path) { - auto startTime = QTime::currentTime(); + const auto startTime = QTime::currentTime(); LoadStatus tempLoadStatus = NotLoaded; if (!path.isEmpty()) { QMutexLocker locker(loadFromFileMutex); tempLoadStatus = loadFromFile(path); } - int msecs = startTime.msecsTo(QTime::currentTime()); + const int msecs = startTime.msecsTo(QTime::currentTime()); qCInfo(CardDatabaseLoadingLog) << "Loaded card database: Path =" << path << "Status =" << tempLoadStatus << "Cards =" << (database ? database->cards.size() : 0) << "Sets =" << (database ? database->sets.size() : 0) << QString("%1ms").arg(msecs); @@ -86,9 +86,9 @@ LoadStatus CardDatabaseLoader::loadCardDatabases() database->clear(); // remove old db - LoadStatus loadStatus = loadCardDatabase(pathProvider->getCardDatabasePath()); // load main card database - loadCardDatabase(pathProvider->getTokenDatabasePath()); // load tokens database - loadCardDatabase(pathProvider->getSpoilerCardDatabasePath()); // load spoilers database + const LoadStatus loadStatus = loadCardDatabase(pathProvider->getCardDatabasePath()); // load main card database + loadCardDatabase(pathProvider->getTokenDatabasePath()); // load tokens database + loadCardDatabase(pathProvider->getSpoilerCardDatabasePath()); // load spoilers database // find all custom card databases, recursively & following symlinks // then load them alphabetically @@ -136,10 +136,10 @@ bool CardDatabaseLoader::saveCustomTokensToFile() return false; } - QString fileName = pathProvider->getCustomCardDatabasePath() + "/" + CardSet::TOKENS_SETNAME + ".xml"; + const QString fileName = pathProvider->getCustomCardDatabasePath() + "/" + CardSet::TOKENS_SETNAME + ".xml"; SetNameMap tmpSets; - CardSetPtr customTokensSet = database->getSet(CardSet::TOKENS_SETNAME); + const CardSetPtr customTokensSet = database->getSet(CardSet::TOKENS_SETNAME); tmpSets.insert(CardSet::TOKENS_SETNAME, customTokensSet); CardNameMap tmpCards; diff --git a/libcockatrice_card/libcockatrice/card/database/card_database_querier.cpp b/libcockatrice_card/libcockatrice/card/database/card_database_querier.cpp index 65999e590..d1df1d044 100644 --- a/libcockatrice_card/libcockatrice/card/database/card_database_querier.cpp +++ b/libcockatrice_card/libcockatrice/card/database/card_database_querier.cpp @@ -88,7 +88,7 @@ QList CardDatabaseQuerier::getCards(const QList &cardRefs) c */ ExactCard CardDatabaseQuerier::getCard(const CardRef &cardRef) const { - auto info = getCardInfo(cardRef.name); + const auto info = getCardInfo(cardRef.name); if (info.isNull()) { return {}; } @@ -110,8 +110,8 @@ ExactCard CardDatabaseQuerier::getCard(const CardRef &cardRef) const */ ExactCard CardDatabaseQuerier::guessCard(const CardRef &cardRef) const { - auto card = lookupCardByName(cardRef.name); - auto printing = + const auto card = lookupCardByName(cardRef.name); + const auto printing = cardRef.providerId.isEmpty() ? getPreferredPrinting(card) : findPrintingWithId(card, cardRef.providerId); return ExactCard(card, printing); @@ -123,9 +123,9 @@ ExactCard CardDatabaseQuerier::getRandomCard() const return {}; const auto keys = db->cards.keys(); - int randomIndex = QRandomGenerator::global()->bounded(keys.size()); + const int randomIndex = QRandomGenerator::global()->bounded(keys.size()); const QString &randomKey = keys.at(randomIndex); - CardInfoPtr randomCard = getCardInfo(randomKey); + const CardInfoPtr randomCard = getCardInfo(randomKey); return ExactCard{randomCard, getPreferredPrinting(randomCard)}; } @@ -138,7 +138,8 @@ ExactCard CardDatabaseQuerier::getCardFromSameSet(const QString &cardName, const } // The source card does have a printing defined, which means we can attempt to get a card from the same set. - PrintingInfo relatedPrinting = getSpecificPrinting(cardName, otherPrinting.getSet()->getCorrectedShortName(), ""); + const PrintingInfo relatedPrinting = + getSpecificPrinting(cardName, otherPrinting.getSet()->getCorrectedShortName(), ""); ExactCard relatedCard(guessCard({cardName}).getCardPtr(), relatedPrinting); // If we didn't find a card from the same set, just try to find any card with the same name. @@ -167,7 +168,7 @@ PrintingInfo CardDatabaseQuerier::findPrintingWithId(const CardInfoPtr &cardInfo PrintingInfo CardDatabaseQuerier::getSpecificPrinting(const CardRef &cardRef) const { - CardInfoPtr cardInfo = getCardInfo(cardRef.name); + const CardInfoPtr cardInfo = getCardInfo(cardRef.name); if (!cardInfo) { return PrintingInfo(nullptr); } @@ -179,7 +180,7 @@ PrintingInfo CardDatabaseQuerier::getSpecificPrinting(const QString &cardName, const QString &setShortName, const QString &collectorNumber) const { - CardInfoPtr cardInfo = getCardInfo(cardName); + const CardInfoPtr cardInfo = getCardInfo(cardName); if (!cardInfo) { return PrintingInfo(nullptr); } @@ -240,7 +241,7 @@ bool CardDatabaseQuerier::isPreferredPrinting(const CardRef &cardRef) const PrintingInfo CardDatabaseQuerier::getPreferredPrinting(const QString &cardName) const { - CardInfoPtr cardInfo = getCardInfo(cardName); + const CardInfoPtr cardInfo = getCardInfo(cardName); return getPreferredPrinting(cardInfo); } @@ -263,7 +264,7 @@ PrintingInfo CardDatabaseQuerier::getPreferredPrinting(const CardInfoPtr &cardIn CardSetPtr preferredSet = nullptr; PrintingInfo preferredPrinting; - SetPriorityComparator comparator; + const SetPriorityComparator comparator; for (const auto &printings : setMap) { for (auto &printing : printings) { @@ -284,13 +285,13 @@ PrintingInfo CardDatabaseQuerier::getPreferredPrinting(const CardInfoPtr &cardIn QString CardDatabaseQuerier::getPreferredPrintingProviderId(const QString &cardName) const { - PrintingInfo preferredPrinting = getPreferredPrinting(cardName); + const PrintingInfo preferredPrinting = getPreferredPrinting(cardName); QString uuid = preferredPrinting.getUuid(); if (!uuid.isEmpty()) { return uuid; } - CardInfoPtr defaultCardInfo = getCardInfo(cardName); + const CardInfoPtr defaultCardInfo = getCardInfo(cardName); if (defaultCardInfo.isNull()) { return cardName; } diff --git a/libcockatrice_card/libcockatrice/card/database/parser/cockatrice_xml_4.cpp b/libcockatrice_card/libcockatrice/card/database/parser/cockatrice_xml_4.cpp index ab4c8002d..0463b8b96 100644 --- a/libcockatrice_card/libcockatrice/card/database/parser/cockatrice_xml_4.cpp +++ b/libcockatrice_card/libcockatrice/card/database/parser/cockatrice_xml_4.cpp @@ -31,7 +31,7 @@ bool CockatriceXml4Parser::getCanParseFile(const QString &fileName, QIODevice &d while (!xml.atEnd()) { if (xml.readNext() == QXmlStreamReader::StartElement) { if (xml.name().toString() == COCKATRICE_XML4_TAGNAME) { - int version = xml.attributes().value("version").toString().toInt(); + const int version = xml.attributes().value("version").toString().toInt(); if (version == COCKATRICE_XML4_TAGVER) { return true; } else { @@ -73,7 +73,7 @@ void CockatriceXml4Parser::parseFile(QIODevice &device) } if (xml.hasError()) { - QString preamble = tr("Parse error at line %1 col %2:").arg(xml.lineNumber()).arg(xml.columnNumber()); + const QString preamble = tr("Parse error at line %1 col %2:").arg(xml.lineNumber()).arg(xml.columnNumber()); qCWarning(CockatriceXml4Log).noquote() << preamble << xml.errorString(); } } @@ -331,7 +331,7 @@ static QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardInfoPtr &in // related cards const QList related = info->getRelatedCards(); - for (auto i : related) { + for (const auto i : related) { xml.writeStartElement("related"); if (i->getDoesAttach()) { xml.writeAttribute("attach", i->getAttachTypeAsString()); @@ -355,7 +355,7 @@ static QXmlStreamWriter &operator<<(QXmlStreamWriter &xml, const CardInfoPtr &in xml.writeEndElement(); } const QList reverseRelated = info->getReverseRelatedCards(); - for (auto i : reverseRelated) { + for (const auto i : reverseRelated) { xml.writeStartElement("reverse-related"); if (i->getDoesAttach()) { xml.writeAttribute("attach", i->getAttachTypeAsString()); diff --git a/libcockatrice_card/libcockatrice/card/printing/exact_card.cpp b/libcockatrice_card/libcockatrice/card/printing/exact_card.cpp index 993b5b96e..f84fc5e9a 100644 --- a/libcockatrice_card/libcockatrice/card/printing/exact_card.cpp +++ b/libcockatrice_card/libcockatrice/card/printing/exact_card.cpp @@ -52,8 +52,8 @@ const CardInfo &ExactCard::getInfo() const */ QString ExactCard::getPixmapCacheKey() const { - QString uuid = printing.getUuid(); - QString suffix = uuid.isEmpty() ? "" : "_" + uuid; + const QString uuid = printing.getUuid(); + const QString suffix = uuid.isEmpty() ? "" : "_" + uuid; return QLatin1String("card_") + card->getName() + suffix; } diff --git a/libcockatrice_card/libcockatrice/card/set/card_set_list.cpp b/libcockatrice_card/libcockatrice/card/set/card_set_list.cpp index 8d6aa7365..069b9002f 100644 --- a/libcockatrice_card/libcockatrice/card/set/card_set_list.cpp +++ b/libcockatrice_card/libcockatrice/card/set/card_set_list.cpp @@ -23,7 +23,7 @@ int CardSetList::getEnabledSetsNum() { int num = 0; for (int i = 0; i < size(); ++i) { - CardSetPtr set = at(i); + const CardSetPtr set = at(i); if (set && set->getEnabled()) { ++num; } @@ -35,7 +35,7 @@ int CardSetList::getUnknownSetsNum() { int num = 0; for (int i = 0; i < size(); ++i) { - CardSetPtr set = at(i); + const CardSetPtr set = at(i); if (set && !set->getIsKnown() && !set->getIsKnownIgnored()) { ++num; } @@ -47,7 +47,7 @@ QStringList CardSetList::getUnknownSetsNames() { QStringList sets = QStringList(); for (int i = 0; i < size(); ++i) { - CardSetPtr set = at(i); + const CardSetPtr set = at(i); if (set && !set->getIsKnown() && !set->getIsKnownIgnored()) { sets << set->getShortName(); } @@ -58,7 +58,7 @@ QStringList CardSetList::getUnknownSetsNames() void CardSetList::enableAllUnknown() { for (int i = 0; i < size(); ++i) { - CardSetPtr set = at(i); + const CardSetPtr set = at(i); if (set && !set->getIsKnown() && !set->getIsKnownIgnored()) { set->setIsKnown(true); set->setEnabled(true); @@ -89,7 +89,7 @@ void CardSetList::enableAll() void CardSetList::markAllAsKnown() { for (int i = 0; i < size(); ++i) { - CardSetPtr set = at(i); + const CardSetPtr set = at(i); if (set && !set->getIsKnown() && !set->getIsKnownIgnored()) { set->setIsKnown(true); set->setEnabled(false); diff --git a/libcockatrice_deck_list/libcockatrice/deck_list/abstract_deck_list_card_node.cpp b/libcockatrice_deck_list/libcockatrice/deck_list/abstract_deck_list_card_node.cpp index b8a497c20..8c400c269 100644 --- a/libcockatrice_deck_list/libcockatrice/deck_list/abstract_deck_list_card_node.cpp +++ b/libcockatrice_deck_list/libcockatrice/deck_list/abstract_deck_list_card_node.cpp @@ -14,10 +14,10 @@ bool AbstractDecklistCardNode::compare(AbstractDecklistNode *other) const bool AbstractDecklistCardNode::compareNumber(AbstractDecklistNode *other) const { - auto *other2 = dynamic_cast(other); + const auto *other2 = dynamic_cast(other); if (other2) { - int n1 = getNumber(); - int n2 = other2->getNumber(); + const int n1 = getNumber(); + const int n2 = other2->getNumber(); return (n1 != n2) ? (n1 > n2) : compareName(other); } else { return true; @@ -26,7 +26,7 @@ bool AbstractDecklistCardNode::compareNumber(AbstractDecklistNode *other) const bool AbstractDecklistCardNode::compareName(AbstractDecklistNode *other) const { - auto *other2 = dynamic_cast(other); + const auto *other2 = dynamic_cast(other); if (other2) { return (getName() > other2->getName()); } else { diff --git a/libcockatrice_deck_list/libcockatrice/deck_list/deck_list.cpp b/libcockatrice_deck_list/libcockatrice/deck_list/deck_list.cpp index e26e55e08..106f4b6ad 100644 --- a/libcockatrice_deck_list/libcockatrice/deck_list/deck_list.cpp +++ b/libcockatrice_deck_list/libcockatrice/deck_list/deck_list.cpp @@ -98,7 +98,7 @@ DeckList::~DeckList() QList DeckList::getCurrentSideboardPlan() { - SideboardPlan *current = sideboardPlans.value(QString(), 0); + const SideboardPlan *current = sideboardPlans.value(QString(), 0); if (!current) return QList(); else @@ -127,8 +127,8 @@ bool DeckList::readElement(QXmlStreamReader *xml) } else if (childName == "comments") { comments = xml->readElementText(); } else if (childName == "bannerCard") { - QString providerId = xml->attributes().value("providerId").toString(); - QString cardName = xml->readElementText(); + const QString providerId = xml->attributes().value("providerId").toString(); + const QString cardName = xml->readElementText(); bannerCard = {cardName, providerId}; } else if (childName == "tags") { tags.clear(); // Clear existing tags @@ -513,7 +513,7 @@ void DeckList::cleanList(bool preserveMetadata) void DeckList::getCardListHelper(InnerDecklistNode *item, QSet &result) { for (int i = 0; i < item->size(); ++i) { - auto *node = dynamic_cast(item->at(i)); + const auto *node = dynamic_cast(item->at(i)); if (node) { result.insert(node->getName()); @@ -526,7 +526,7 @@ void DeckList::getCardListHelper(InnerDecklistNode *item, QSet &result) void DeckList::getCardRefListHelper(InnerDecklistNode *item, QList &result) { for (int i = 0; i < item->size(); ++i) { - auto *node = dynamic_cast(item->at(i)); + const auto *node = dynamic_cast(item->at(i)); if (node) { result.append(node->toCardRef()); @@ -577,13 +577,13 @@ int DeckList::getSideboardSize() const { int size = 0; for (int i = 0; i < root->size(); ++i) { - auto *node = dynamic_cast(root->at(i)); + const auto *node = dynamic_cast(root->at(i)); if (node->getName() != DECK_ZONE_SIDE) { continue; } for (int j = 0; j < node->size(); j++) { - auto *card = dynamic_cast(node->at(j)); + const auto *card = dynamic_cast(node->at(j)); size += card->getNumber(); } } @@ -621,7 +621,7 @@ bool DeckList::deleteNode(AbstractDecklistNode *node, InnerDecklistNode *rootNod updateHash = true; } - int index = rootNode->indexOf(node); + const int index = rootNode->indexOf(node); if (index != -1) { delete rootNode->takeAt(index); @@ -661,11 +661,11 @@ static QString computeDeckHash(const InnerDecklistNode *root) optionalZones << DECK_ZONE_TOKENS; // Optional zones in deck not included in hashing process for (int i = 0; i < root->size(); i++) { - auto *node = dynamic_cast(root->at(i)); + const auto *node = dynamic_cast(root->at(i)); for (int j = 0; j < node->size(); j++) { if (hashZones.contains(node->getName())) // Mainboard or Sideboard { - auto *card = dynamic_cast(node->at(j)); + const auto *card = dynamic_cast(node->at(j)); for (int k = 0; k < card->getNumber(); ++k) { cardList.append((node->getName() == DECK_ZONE_SIDE ? "SB:" : "") + card->getName().toLower()); } @@ -674,10 +674,10 @@ static QString computeDeckHash(const InnerDecklistNode *root) } cardList.sort(); QByteArray deckHashArray = QCryptographicHash::hash(cardList.join(";").toUtf8(), QCryptographicHash::Sha1); - quint64 number = (((quint64)(unsigned char)deckHashArray[0]) << 32) + - (((quint64)(unsigned char)deckHashArray[1]) << 24) + - (((quint64)(unsigned char)deckHashArray[2] << 16)) + - (((quint64)(unsigned char)deckHashArray[3]) << 8) + (quint64)(unsigned char)deckHashArray[4]; + const quint64 number = (((quint64)(unsigned char)deckHashArray[0]) << 32) + + (((quint64)(unsigned char)deckHashArray[1]) << 24) + + (((quint64)(unsigned char)deckHashArray[2] << 16)) + + (((quint64)(unsigned char)deckHashArray[3]) << 8) + (quint64)(unsigned char)deckHashArray[4]; return QString::number(number, 32).rightJustified(8, '0'); } diff --git a/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_history_manager.cpp b/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_history_manager.cpp index 83c9cc0bb..f7f91ac09 100644 --- a/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_history_manager.cpp +++ b/libcockatrice_deck_list/libcockatrice/deck_list/deck_list_history_manager.cpp @@ -23,11 +23,11 @@ void DeckListHistoryManager::undo(DeckList *deck) const DeckListMemento &mementoToRestore = undoStack.top(); // Save current state for redo - DeckListMemento currentState = deck->createMemento(mementoToRestore.getReason()); + const DeckListMemento currentState = deck->createMemento(mementoToRestore.getReason()); redoStack.push(currentState); // Pop the last state from undo stack and restore it - DeckListMemento memento = undoStack.pop(); + const DeckListMemento memento = undoStack.pop(); deck->restoreMemento(memento); emit undoRedoStateChanged(); @@ -42,11 +42,11 @@ void DeckListHistoryManager::redo(DeckList *deck) const DeckListMemento &mementoToRestore = redoStack.top(); // Save current state for undo - DeckListMemento currentState = deck->createMemento(mementoToRestore.getReason()); + const DeckListMemento currentState = deck->createMemento(mementoToRestore.getReason()); undoStack.push(currentState); // Pop the next state from redo stack and restore it - DeckListMemento memento = redoStack.pop(); + const DeckListMemento memento = redoStack.pop(); deck->restoreMemento(memento); emit undoRedoStateChanged(); diff --git a/libcockatrice_deck_list/libcockatrice/deck_list/inner_deck_list_node.cpp b/libcockatrice_deck_list/libcockatrice/deck_list/inner_deck_list_node.cpp index eca58963a..67e64b378 100644 --- a/libcockatrice_deck_list/libcockatrice/deck_list/inner_deck_list_node.cpp +++ b/libcockatrice_deck_list/libcockatrice/deck_list/inner_deck_list_node.cpp @@ -91,7 +91,7 @@ int InnerDecklistNode::recursiveCount(bool countTotalCards) const { int result = 0; for (int i = 0; i < size(); i++) { - auto *node = dynamic_cast(at(i)); + const auto *node = dynamic_cast(at(i)); if (node) { result += node->recursiveCount(countTotalCards); @@ -118,10 +118,10 @@ bool InnerDecklistNode::compare(AbstractDecklistNode *other) const bool InnerDecklistNode::compareNumber(AbstractDecklistNode *other) const { - auto *other2 = dynamic_cast(other); + const auto *other2 = dynamic_cast(other); if (other2) { - int n1 = recursiveCount(true); - int n2 = other2->recursiveCount(true); + const int n1 = recursiveCount(true); + const int n2 = other2->recursiveCount(true); return (n1 != n2) ? (n1 > n2) : compareName(other); } else { return false; @@ -130,7 +130,7 @@ bool InnerDecklistNode::compareNumber(AbstractDecklistNode *other) const bool InnerDecklistNode::compareName(AbstractDecklistNode *other) const { - auto *other2 = dynamic_cast(other); + const auto *other2 = dynamic_cast(other); if (other2) { return (getName() > other2->getName()); } else { diff --git a/libcockatrice_filters/libcockatrice/filters/filter_card.cpp b/libcockatrice_filters/libcockatrice/filters/filter_card.cpp index d49a1b9cb..7bba05607 100644 --- a/libcockatrice_filters/libcockatrice/filters/filter_card.cpp +++ b/libcockatrice_filters/libcockatrice/filters/filter_card.cpp @@ -14,8 +14,8 @@ QJsonObject CardFilter::toJson() const CardFilter *CardFilter::fromJson(const QJsonObject &obj) { QString term = obj["term"].toString(); - QString typeStr = obj["type"].toString(); - QString attrStr = obj["attr"].toString(); + const QString typeStr = obj["type"].toString(); + const QString attrStr = obj["attr"].toString(); Type type = TypeEnd; Attr attr = AttrEnd; diff --git a/libcockatrice_filters/libcockatrice/filters/filter_string.cpp b/libcockatrice_filters/libcockatrice/filters/filter_string.cpp index 3615729f0..10f420375 100644 --- a/libcockatrice_filters/libcockatrice/filters/filter_string.cpp +++ b/libcockatrice_filters/libcockatrice/filters/filter_string.cpp @@ -190,7 +190,7 @@ static void setupParserRules() search["StringValue"] = [](const peg::SemanticValues &sv) -> StringMatcher { // Helper function for word boundary matching auto createWordBoundaryMatcher = [](const QString &target) { - QString pattern = QString("\\b%1\\b").arg(QRegularExpression::escape(target)); + const QString pattern = QString("\\b%1\\b").arg(QRegularExpression::escape(target)); QRegularExpression regex(pattern, QRegularExpression::CaseInsensitiveOption); return [regex](const QString &s) { return regex.match(s).hasMatch(); }; }; @@ -286,8 +286,8 @@ static void setupParserRules() }; search["RegexMatcher"] = [](const peg::SemanticValues &sv) -> StringMatcher { - auto target = std::any_cast(sv[0]); - auto regex = QRegularExpression(target, QRegularExpression::CaseInsensitiveOption); + const auto target = std::any_cast(sv[0]); + const auto regex = QRegularExpression(target, QRegularExpression::CaseInsensitiveOption); return [=](const QString &s) { return regex.match(s).hasMatch(); }; }; diff --git a/libcockatrice_filters/libcockatrice/filters/filter_tree.cpp b/libcockatrice_filters/libcockatrice/filters/filter_tree.cpp index 89b772b8e..09c629508 100644 --- a/libcockatrice_filters/libcockatrice/filters/filter_tree.cpp +++ b/libcockatrice_filters/libcockatrice/filters/filter_tree.cpp @@ -84,10 +84,10 @@ int FilterItemList::termIndex(const QString &term) const FilterTreeNode *FilterItemList::termNode(const QString &term) { - int i = termIndex(term); + const int i = termIndex(term); if (i < 0) { FilterItem *fi = new FilterItem(term, this); - int count = childNodes.count(); + const int count = childNodes.count(); preInsertChild(this, count); childNodes.append(fi); @@ -199,7 +199,7 @@ bool FilterItem::acceptColor(const CardInfoPtr info) const * then we should match all of them to the card's colors */ int match_count = 0; - for (auto &it : converted_term) { + for (const auto &it : converted_term) { if (info->getColors().contains(it, Qt::CaseInsensitive)) match_count++; } @@ -280,7 +280,7 @@ bool FilterItem::acceptLoyalty(const CardInfoPtr info) const } else { bool success; // if loyalty can't be converted to "int" it must be "X" - int loyalty = info->getLoyalty().toInt(&success); + const int loyalty = info->getLoyalty().toInt(&success); if (success) { return relationCheck(loyalty); } else { @@ -291,7 +291,7 @@ bool FilterItem::acceptLoyalty(const CardInfoPtr info) const bool FilterItem::acceptPowerToughness(const CardInfoPtr info, CardFilter::Attr attr) const { - int slash = info->getPowTough().indexOf("/"); + const int slash = info->getPowTough().indexOf("/"); if (slash == -1) { return false; } @@ -306,7 +306,7 @@ bool FilterItem::acceptPowerToughness(const CardInfoPtr info, CardFilter::Attr a } // advanced filtering should only happen after fast string comparison failed bool conversion; - int value = valueString.toInt(&conversion); + const int value = valueString.toInt(&conversion); return conversion ? relationCheck(value) : false; } @@ -371,7 +371,7 @@ bool FilterItem::relationCheck(int cardInfo) const QString trimmedTerm = term.trimmed(); // check whether it's a 2 char operator (<=, >=, or ==) if (trimmedTerm[1] == '=') { - int termInt = trimmedTerm.mid(2).toInt(); + const int termInt = trimmedTerm.mid(2).toInt(); if (trimmedTerm.startsWith('<')) { result = (cardInfo <= termInt); } else if (trimmedTerm.startsWith('>')) { @@ -380,7 +380,7 @@ bool FilterItem::relationCheck(int cardInfo) const result = (cardInfo == termInt); } } else { - int termInt = trimmedTerm.mid(1).toInt(); + const int termInt = trimmedTerm.mid(1).toInt(); if (trimmedTerm.startsWith('<')) { result = (cardInfo < termInt); } else if (trimmedTerm.startsWith('>')) { @@ -523,7 +523,7 @@ bool FilterTree::acceptsCard(const CardInfoPtr info) const void FilterTree::removeFiltersByAttr(CardFilter::Attr filterType) { for (int i = childNodes.size() - 1; i >= 0; --i) { - auto *child = dynamic_cast(childNodes.at(i)); + const auto *child = dynamic_cast(childNodes.at(i)); if (child && child->attr == filterType) { deleteAt(i); @@ -542,12 +542,12 @@ void FilterTree::removeFilter(const CardFilter *toRemove) if (!typeList) continue; - int termIdx = typeList->termIndex(toRemove->term()); + const int termIdx = typeList->termIndex(toRemove->term()); if (termIdx != -1) { typeList->deleteAt(termIdx); emit typeList->nodeChanged(); if (typeList->childCount() == 0) { - int logicIndex = logicMap->childIndex(typeList); + const int logicIndex = logicMap->childIndex(typeList); if (logicIndex != -1) { logicMap->deleteAt(logicIndex); } diff --git a/libcockatrice_models/libcockatrice/models/database/card/card_completer_proxy_model.cpp b/libcockatrice_models/libcockatrice/models/database/card/card_completer_proxy_model.cpp index 387eb454f..bf14606b5 100644 --- a/libcockatrice_models/libcockatrice/models/database/card/card_completer_proxy_model.cpp +++ b/libcockatrice_models/libcockatrice/models/database/card/card_completer_proxy_model.cpp @@ -10,8 +10,8 @@ bool CardCompleterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex return true; } - QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); - QString data = index.data(Qt::DisplayRole).toString(); + const QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent); + const QString data = index.data(Qt::DisplayRole).toString(); // Ensure substring matching return data.contains(filterRegularExpression()); diff --git a/libcockatrice_models/libcockatrice/models/database/card/card_search_model.cpp b/libcockatrice_models/libcockatrice/models/database/card/card_search_model.cpp index 6a930c1da..2556af260 100644 --- a/libcockatrice_models/libcockatrice/models/database/card/card_search_model.cpp +++ b/libcockatrice_models/libcockatrice/models/database/card/card_search_model.cpp @@ -44,7 +44,7 @@ void CardSearchModel::updateSearchResults(const QString &query) for (int i = 0; i < sourceModel->rowCount(); ++i) { QModelIndex modelIndex = sourceModel->index(i, 0); QModelIndex sourceIndex = sourceModel->mapToSource(modelIndex); - CardDatabaseModel *sourceDbModel = qobject_cast(sourceModel->sourceModel()); + const CardDatabaseModel *sourceDbModel = qobject_cast(sourceModel->sourceModel()); if (!sourceDbModel || !sourceIndex.isValid()) return; @@ -54,7 +54,7 @@ void CardSearchModel::updateSearchResults(const QString &query) if (!card) continue; - int distance = levenshteinDistance(query.toLower(), card->getName().toLower()); + const int distance = levenshteinDistance(query.toLower(), card->getName().toLower()); searchResults.append({card, distance}); } diff --git a/libcockatrice_models/libcockatrice/models/database/card_database_display_model.cpp b/libcockatrice_models/libcockatrice/models/database/card_database_display_model.cpp index 5ce63a939..8432016f3 100644 --- a/libcockatrice_models/libcockatrice/models/database/card_database_display_model.cpp +++ b/libcockatrice_models/libcockatrice/models/database/card_database_display_model.cpp @@ -27,8 +27,8 @@ bool CardDatabaseDisplayModel::canFetchMore(const QModelIndex &index) const void CardDatabaseDisplayModel::fetchMore(const QModelIndex &index) { - int remainder = sourceModel()->rowCount(index) - loadedRowCount; - int itemsToFetch = qMin(100, remainder); + const int remainder = sourceModel()->rowCount(index) - loadedRowCount; + const int itemsToFetch = qMin(100, remainder); if (itemsToFetch == 0) { return; @@ -49,12 +49,12 @@ int CardDatabaseDisplayModel::rowCount(const QModelIndex &parent) const bool CardDatabaseDisplayModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - QString leftString = sourceModel()->data(left, CardDatabaseModel::SortRole).toString(); - QString rightString = sourceModel()->data(right, CardDatabaseModel::SortRole).toString(); + const QString leftString = sourceModel()->data(left, CardDatabaseModel::SortRole).toString(); + const QString rightString = sourceModel()->data(right, CardDatabaseModel::SortRole).toString(); if (!cardName.isEmpty() && left.column() == CardDatabaseModel::NameColumn) { - bool isLeftType = leftString.startsWith(cardName, Qt::CaseInsensitive); - bool isRightType = rightString.startsWith(cardName, Qt::CaseInsensitive); + const bool isLeftType = leftString.startsWith(cardName, Qt::CaseInsensitive); + const bool isRightType = rightString.startsWith(cardName, Qt::CaseInsensitive); // test for an exact match: isLeftType && leftString.size() == cardName.size() // or an exclusive start match: isLeftType && !isRightType @@ -65,13 +65,13 @@ bool CardDatabaseDisplayModel::lessThan(const QModelIndex &left, const QModelInd if (isRightType && (!isLeftType || rightString.size() == cardName.size())) return false; } else if (right.column() == CardDatabaseModel::PTColumn && left.column() == CardDatabaseModel::PTColumn) { - QStringList leftList = leftString.split("/"); - QStringList rightList = rightString.split("/"); + const QStringList leftList = leftString.split("/"); + const QStringList rightList = rightString.split("/"); if (leftList.size() == 2 && rightList.size() == 2) { // cool, have both P/T in list now - int lessThanNum = lessThanNumerically(leftList.at(0), rightList.at(0)); + const int lessThanNum = lessThanNumerically(leftList.at(0), rightList.at(0)); if (lessThanNum != 0) { return lessThanNum < 0; } else { @@ -153,7 +153,7 @@ int CardDatabaseDisplayModel::lessThanNumerically(const QString &left, const QSt } bool CardDatabaseDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const { - CardInfoPtr info = static_cast(sourceModel())->getCard(sourceRow); + const CardInfoPtr info = static_cast(sourceModel())->getCard(sourceRow); if (((isToken == ShowTrue) && !info->getIsToken()) || ((isToken == ShowFalse) && info->getIsToken())) return false; diff --git a/libcockatrice_models/libcockatrice/models/database/card_database_model.cpp b/libcockatrice_models/libcockatrice/models/database/card_database_model.cpp index e33156329..6112f9d09 100644 --- a/libcockatrice_models/libcockatrice/models/database/card_database_model.cpp +++ b/libcockatrice_models/libcockatrice/models/database/card_database_model.cpp @@ -34,7 +34,7 @@ QVariant CardDatabaseModel::data(const QModelIndex &index, int role) const (role != Qt::DisplayRole && role != SortRole)) return QVariant(); - CardInfoPtr card = cardList.at(index.row()); + const CardInfoPtr card = cardList.at(index.row()); switch (index.column()) { case NameColumn: return card->getName(); diff --git a/libcockatrice_models/libcockatrice/models/database/card_set/card_sets_model.cpp b/libcockatrice_models/libcockatrice/models/database/card_set/card_sets_model.cpp index 2af815246..dbb618a69 100644 --- a/libcockatrice_models/libcockatrice/models/database/card_set/card_sets_model.cpp +++ b/libcockatrice_models/libcockatrice/models/database/card_set/card_sets_model.cpp @@ -26,7 +26,7 @@ QVariant SetsModel::data(const QModelIndex &index, int role) const if (!index.isValid() || (index.column() >= NUM_COLS) || (index.row() >= rowCount())) return QVariant(); - CardSetPtr set = sets[index.row()]; + const CardSetPtr set = sets[index.row()]; if (index.column() == EnabledCol) { switch (role) { @@ -135,7 +135,7 @@ bool SetsModel::dropMimeData(const QMimeData *data, return false; row = parent.row(); } - int oldRow = qobject_cast(data)->getOldRow(); + const int oldRow = qobject_cast(data)->getOldRow(); if (oldRow < row) row--; @@ -146,7 +146,7 @@ bool SetsModel::dropMimeData(const QMimeData *data, void SetsModel::toggleRow(int row, bool enable) { - CardSetPtr temp = sets.at(row); + const CardSetPtr temp = sets.at(row); if (enable) enabledSets.insert(temp); @@ -158,7 +158,7 @@ void SetsModel::toggleRow(int row, bool enable) void SetsModel::toggleRow(int row) { - CardSetPtr tmp = sets.at(row); + const CardSetPtr tmp = sets.at(row); if (tmp == nullptr) return; @@ -185,7 +185,7 @@ void SetsModel::toggleAll(bool enabled) void SetsModel::swapRows(int oldRow, int newRow) { beginRemoveRows(QModelIndex(), oldRow, oldRow); - CardSetPtr temp = sets.takeAt(oldRow); + const CardSetPtr temp = sets.takeAt(oldRow); endRemoveRows(); beginInsertRows(QModelIndex(), newRow, newRow); @@ -197,7 +197,7 @@ void SetsModel::swapRows(int oldRow, int newRow) void SetsModel::restoreOriginalOrder() { - int numRows = rowCount(); + const int numRows = rowCount(); sets.defaultSort(); emit dataChanged(index(0, 0), index(numRows - 1, columnCount() - 1)); } @@ -205,13 +205,13 @@ void SetsModel::restoreOriginalOrder() void SetsModel::sort(int column, Qt::SortOrder order) { QMultiMap setMap; - int numRows = rowCount(); + const int numRows = rowCount(); int row; for (row = 0; row < numRows; ++row) setMap.insert(index(row, column).data(SetsModel::SortRole).toString(), sets.at(row)); - QList tmp = setMap.values(); + const QList tmp = setMap.values(); sets.clear(); if (order == Qt::AscendingOrder) { for (row = 0; row < tmp.size(); row++) { @@ -270,7 +270,7 @@ SetsDisplayModel::SetsDisplayModel(QObject *parent) : QSortFilterProxyModel(pare void SetsDisplayModel::fetchMore(const QModelIndex &index) { - int itemsToFetch = sourceModel()->rowCount(index); + const int itemsToFetch = sourceModel()->rowCount(index); beginInsertRows(QModelIndex(), 0, itemsToFetch - 1); @@ -279,9 +279,9 @@ void SetsDisplayModel::fetchMore(const QModelIndex &index) bool SetsDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { - auto typeIndex = sourceModel()->index(sourceRow, SetsModel::SetTypeCol, sourceParent); - auto nameIndex = sourceModel()->index(sourceRow, SetsModel::LongNameCol, sourceParent); - auto shortNameIndex = sourceModel()->index(sourceRow, SetsModel::ShortNameCol, sourceParent); + const auto typeIndex = sourceModel()->index(sourceRow, SetsModel::SetTypeCol, sourceParent); + const auto nameIndex = sourceModel()->index(sourceRow, SetsModel::LongNameCol, sourceParent); + const auto shortNameIndex = sourceModel()->index(sourceRow, SetsModel::ShortNameCol, sourceParent); #if (QT_VERSION >= QT_VERSION_CHECK(5, 12, 0)) const auto filter = filterRegularExpression(); @@ -296,8 +296,8 @@ bool SetsDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex &source bool SetsDisplayModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - QString leftString = sourceModel()->data(left, SetsModel::SortRole).toString(); - QString rightString = sourceModel()->data(right, SetsModel::SortRole).toString(); + const QString leftString = sourceModel()->data(left, SetsModel::SortRole).toString(); + const QString rightString = sourceModel()->data(right, SetsModel::SortRole).toString(); return QString::localeAwareCompare(leftString, rightString) < 0; } diff --git a/libcockatrice_models/libcockatrice/models/database/token/token_display_model.cpp b/libcockatrice_models/libcockatrice/models/database/token/token_display_model.cpp index 4282c6dc8..b2108e7e2 100644 --- a/libcockatrice_models/libcockatrice/models/database/token/token_display_model.cpp +++ b/libcockatrice_models/libcockatrice/models/database/token/token_display_model.cpp @@ -8,7 +8,7 @@ TokenDisplayModel::TokenDisplayModel(QObject *parent) : CardDatabaseDisplayModel bool TokenDisplayModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const { - CardInfoPtr info = static_cast(sourceModel())->getCard(sourceRow); + const CardInfoPtr info = static_cast(sourceModel())->getCard(sourceRow); return info->getIsToken() && rowMatchesCardName(info); } diff --git a/libcockatrice_models/libcockatrice/models/database/token/token_edit_model.cpp b/libcockatrice_models/libcockatrice/models/database/token/token_edit_model.cpp index 89a1f71b1..8f1628178 100644 --- a/libcockatrice_models/libcockatrice/models/database/token/token_edit_model.cpp +++ b/libcockatrice_models/libcockatrice/models/database/token/token_edit_model.cpp @@ -11,7 +11,7 @@ TokenEditModel::TokenEditModel(QObject *parent) : CardDatabaseDisplayModel(paren bool TokenEditModel::filterAcceptsRow(int sourceRow, const QModelIndex & /*sourceParent*/) const { - CardInfoPtr info = static_cast(sourceModel())->getCard(sourceRow); + const CardInfoPtr info = static_cast(sourceModel())->getCard(sourceRow); return info->getIsToken() && info->getSets().contains(CardSet::TOKENS_SETNAME) && rowMatchesCardName(info); } diff --git a/libcockatrice_models/libcockatrice/models/deck_list/deck_list_model.cpp b/libcockatrice_models/libcockatrice/models/deck_list/deck_list_model.cpp index e3e2de58d..b51c2a20e 100644 --- a/libcockatrice_models/libcockatrice/models/deck_list/deck_list_model.cpp +++ b/libcockatrice_models/libcockatrice/models/deck_list/deck_list_model.cpp @@ -38,10 +38,10 @@ void DeckListModel::rebuildTree() beginResetModel(); root->clearTree(); - InnerDecklistNode *listRoot = deckList->getRoot(); + const InnerDecklistNode *listRoot = deckList->getRoot(); for (int i = 0; i < listRoot->size(); i++) { - auto *currentZone = dynamic_cast(listRoot->at(i)); + const auto *currentZone = dynamic_cast(listRoot->at(i)); auto *node = new InnerDecklistNode(currentZone->getName(), root); for (int j = 0; j < currentZone->size(); j++) { @@ -52,7 +52,7 @@ void DeckListModel::rebuildTree() continue; } - CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); + const CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(currentCard->getName()); QString groupCriteria = getGroupCriteriaForCard(info); auto *groupNode = dynamic_cast(node->findChild(groupCriteria)); @@ -71,7 +71,7 @@ void DeckListModel::rebuildTree() int DeckListModel::rowCount(const QModelIndex &parent) const { // debugIndexInfo("rowCount", parent); - auto *node = getNode(parent); + const auto *node = getNode(parent); if (node) { return node->size(); } else { @@ -96,7 +96,7 @@ QVariant DeckListModel::data(const QModelIndex &index, int role) const } auto *node = static_cast(index.internalPointer()); - auto *card = dynamic_cast(node); + const auto *card = dynamic_cast(node); // Group node if (!card) { @@ -173,12 +173,12 @@ QVariant DeckListModel::data(const QModelIndex &index, int role) const void DeckListModel::emitBackgroundUpdates(const QModelIndex &parent) { - int rows = rowCount(parent); + const int rows = rowCount(parent); if (rows == 0) return; - QModelIndex topLeft = index(0, 0, parent); - QModelIndex bottomRight = index(rows - 1, columnCount() - 1, parent); + const QModelIndex topLeft = index(0, 0, parent); + const QModelIndex bottomRight = index(rows - 1, columnCount() - 1, parent); emit dataChanged(topLeft, bottomRight, {Qt::BackgroundRole}); for (int r = 0; r < rows; ++r) { @@ -220,7 +220,7 @@ QModelIndex DeckListModel::index(int row, int column, const QModelIndex &parent) return {}; } - auto *parentNode = getNode(parent); + const auto *parentNode = getNode(parent); return row >= parentNode->size() ? QModelIndex() : createIndex(row, column, parentNode->at(row)); } @@ -303,7 +303,7 @@ bool DeckListModel::removeRows(int row, int count, const QModelIndex &parent) beginRemoveRows(parent, row, row + count - 1); for (int i = 0; i < count; i++) { AbstractDecklistNode *toDelete = node->takeAt(row); - if (auto *temp = dynamic_cast(toDelete)) { + if (const auto *temp = dynamic_cast(toDelete)) { deckList->deleteNode(temp->getDataNode()); } delete toDelete; @@ -340,12 +340,12 @@ DecklistModelCardNode *DeckListModel::findCardNode(const QString &cardName, return nullptr; } - CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(cardName); + const CardInfoPtr info = CardDatabaseManager::query()->getCardInfo(cardName); if (!info) { return nullptr; } - QString groupCriteria = getGroupCriteriaForCard(info); + const QString groupCriteria = getGroupCriteriaForCard(info); InnerDecklistNode *groupNode = dynamic_cast(zoneNode->findChild(groupCriteria)); if (!groupNode) { return nullptr; @@ -395,10 +395,10 @@ QModelIndex DeckListModel::addCard(const ExactCard &card, const QString &zoneNam InnerDecklistNode *zoneNode = createNodeIfNeeded(zoneName, root); - CardInfoPtr cardInfo = card.getCardPtr(); - PrintingInfo printingInfo = card.getPrinting(); + const CardInfoPtr cardInfo = card.getCardPtr(); + const PrintingInfo printingInfo = card.getPrinting(); - QString groupCriteria = getGroupCriteriaForCard(cardInfo); + const QString groupCriteria = getGroupCriteriaForCard(cardInfo); InnerDecklistNode *groupNode = createNodeIfNeeded(groupCriteria, zoneNode); const QModelIndex parentIndex = nodeToIndex(groupNode); @@ -408,7 +408,7 @@ QModelIndex DeckListModel::addCard(const ExactCard &card, const QString &zoneNam if (!cardNode) { // Determine the correct index - int insertRow = findSortedInsertRow(groupNode, cardInfo); + const int insertRow = findSortedInsertRow(groupNode, cardInfo); auto *decklistCard = deckList->addCard(cardInfo->getName(), zoneName, insertRow, cardSetName, printingInfo.getProperty("num"), printingInfo.getProperty("uuid")); @@ -435,7 +435,7 @@ int DeckListModel::findSortedInsertRow(InnerDecklistNode *parent, CardInfoPtr ca } for (int i = 0; i < parent->size(); ++i) { - auto *existingCard = dynamic_cast(parent->at(i)); + const auto *existingCard = dynamic_cast(parent->at(i)); if (!existingCard) continue; @@ -477,11 +477,11 @@ void DeckListModel::sortHelper(InnerDecklistNode *node, Qt::SortOrder order) QVector> sortResult = node->sort(order); QModelIndexList from, to; - int columns = columnCount(); + const int columns = columnCount(); for (int i = sortResult.size() - 1; i >= 0; --i) { const int fromRow = sortResult[i].first; const int toRow = sortResult[i].second; - AbstractDecklistNode *temp = node->at(toRow); + const AbstractDecklistNode *temp = node->at(toRow); for (int j = 0; j < columns; ++j) { from << createIndex(fromRow, j, temp); to << createIndex(toRow, j, temp); @@ -546,20 +546,20 @@ void DeckListModel::setDeckList(DeckList *_deck) QList DeckListModel::getCards() const { QList cards; - DeckList *decklist = getDeckList(); + const DeckList *decklist = getDeckList(); if (!decklist) { return cards; } - InnerDecklistNode *listRoot = decklist->getRoot(); + const InnerDecklistNode *listRoot = decklist->getRoot(); if (!listRoot) return cards; for (int i = 0; i < listRoot->size(); i++) { - InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); + const InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); if (!currentZone) continue; for (int j = 0; j < currentZone->size(); j++) { - DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); + const DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); if (!currentCard) continue; for (int k = 0; k < currentCard->getNumber(); ++k) { @@ -578,21 +578,21 @@ QList DeckListModel::getCards() const QList DeckListModel::getCardsForZone(const QString &zoneName) const { QList cards; - DeckList *decklist = getDeckList(); + const DeckList *decklist = getDeckList(); if (!decklist) { return cards; } - InnerDecklistNode *listRoot = decklist->getRoot(); + const InnerDecklistNode *listRoot = decklist->getRoot(); if (!listRoot) return cards; for (int i = 0; i < listRoot->size(); i++) { - InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); + const InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); if (!currentZone) continue; if (currentZone->getName() == zoneName) { for (int j = 0; j < currentZone->size(); j++) { - DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); + const DecklistCardNode *currentCard = dynamic_cast(currentZone->at(j)); if (!currentCard) continue; for (int k = 0; k < currentCard->getNumber(); ++k) { @@ -612,16 +612,16 @@ QList DeckListModel::getCardsForZone(const QString &zoneName) const QList *DeckListModel::getZones() const { QList *zones = new QList(); - DeckList *decklist = getDeckList(); + const DeckList *decklist = getDeckList(); if (!decklist) { return zones; } - InnerDecklistNode *listRoot = decklist->getRoot(); + const InnerDecklistNode *listRoot = decklist->getRoot(); if (!listRoot) return zones; for (int i = 0; i < listRoot->size(); i++) { - InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); + const InnerDecklistNode *currentZone = dynamic_cast(listRoot->at(i)); if (!currentZone) continue; zones->append(currentZone->getName()); diff --git a/libcockatrice_models/libcockatrice/models/deck_list/deck_list_sort_filter_proxy_model.cpp b/libcockatrice_models/libcockatrice/models/deck_list/deck_list_sort_filter_proxy_model.cpp index 35fd4d9f8..3fffcd9ad 100644 --- a/libcockatrice_models/libcockatrice/models/deck_list/deck_list_sort_filter_proxy_model.cpp +++ b/libcockatrice_models/libcockatrice/models/deck_list/deck_list_sort_filter_proxy_model.cpp @@ -4,48 +4,48 @@ bool DeckListSortFilterProxyModel::lessThan(const QModelIndex &left, const QModelIndex &right) const { - auto *src = sourceModel(); + const auto *src = sourceModel(); // Inner nodes? -> sort alphabetically by column 1 - bool leftIsCard = src->data(left, Qt::UserRole + 1).toBool(); - bool rightIsCard = src->data(right, Qt::UserRole + 1).toBool(); + const bool leftIsCard = src->data(left, Qt::UserRole + 1).toBool(); + const bool rightIsCard = src->data(right, Qt::UserRole + 1).toBool(); if (!leftIsCard || !rightIsCard) { - QString lName = src->data(left.siblingAtColumn(1), Qt::EditRole).toString(); - QString rName = src->data(right.siblingAtColumn(1), Qt::EditRole).toString(); + const QString lName = src->data(left.siblingAtColumn(1), Qt::EditRole).toString(); + const QString rName = src->data(right.siblingAtColumn(1), Qt::EditRole).toString(); return lName.localeAwareCompare(rName) < 0; } // Both are cards -> apply sort criteria - auto *lNode = static_cast(left.internalPointer()); - auto *rNode = static_cast(right.internalPointer()); + const auto *lNode = static_cast(left.internalPointer()); + const auto *rNode = static_cast(right.internalPointer()); - CardInfoPtr lInfo = CardDatabaseManager::query()->guessCard({lNode->getName()}).getCardPtr(); - CardInfoPtr rInfo = CardDatabaseManager::query()->guessCard({rNode->getName()}).getCardPtr(); + const CardInfoPtr lInfo = CardDatabaseManager::query()->guessCard({lNode->getName()}).getCardPtr(); + const CardInfoPtr rInfo = CardDatabaseManager::query()->guessCard({rNode->getName()}).getCardPtr(); // Example: multiple tie-break criteria (colors > cmc > name) for (const QString &crit : sortCriteria) { if (crit == "name") { QString ln = lNode->getName(); QString rn = rNode->getName(); - int cmp = ln.localeAwareCompare(rn); + const int cmp = ln.localeAwareCompare(rn); if (cmp != 0) return cmp < 0; } else if (crit == "cmc") { - int lc = lInfo ? lInfo->getCmc().toInt() : 0; - int rc = rInfo ? rInfo->getCmc().toInt() : 0; + const int lc = lInfo ? lInfo->getCmc().toInt() : 0; + const int rc = rInfo ? rInfo->getCmc().toInt() : 0; if (lc != rc) return lc < rc; } else if (crit == "colors") { QString lr = lInfo ? lInfo->getColors() : QString(); QString rr = rInfo ? rInfo->getColors() : QString(); - int cmp = lr.localeAwareCompare(rr); + const int cmp = lr.localeAwareCompare(rr); if (cmp != 0) return cmp < 0; } else if (crit == "maintype") { QString lr = lInfo ? lInfo->getMainCardType() : QString(); QString rr = rInfo ? rInfo->getMainCardType() : QString(); - int cmp = lr.localeAwareCompare(rr); + const int cmp = lr.localeAwareCompare(rr); if (cmp != 0) return cmp < 0; } diff --git a/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_participant.cpp b/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_participant.cpp index c6a29b275..173c14a66 100644 --- a/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_participant.cpp +++ b/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_participant.cpp @@ -111,7 +111,7 @@ bool Server_AbstractParticipant::updatePingTime() // returns true if ping time c { QMutexLocker locker(&playerMutex); - int oldPingTime = pingTime; + const int oldPingTime = pingTime; if (userInterface) { pingTime = userInterface->getLastCommandTime(); } else { @@ -232,7 +232,7 @@ Server_AbstractParticipant::cmdGameSay(const Command_GameSay &cmd, ResponseConta * (b) the spectator is a moderator/administrator * (c) the spectator is a judge */ - bool isModOrJudge = (userInfo->user_level() & (ServerInfo_User::IsModerator | ServerInfo_User::IsJudge)); + const bool isModOrJudge = (userInfo->user_level() & (ServerInfo_User::IsModerator | ServerInfo_User::IsJudge)); if (!isModOrJudge && !game->getSpectatorsCanTalk()) { return Response::RespFunctionNotAllowed; } @@ -447,7 +447,7 @@ Response::ResponseCode Server_AbstractParticipant::cmdReverseTurn(const Command_ } } - bool reversedTurn = game->reverseTurnOrder(); + const bool reversedTurn = game->reverseTurnOrder(); Event_ReverseTurn event; event.set_reversed(reversedTurn); @@ -595,7 +595,7 @@ void Server_AbstractParticipant::setUserInterface(Server_AbstractUserInterface * void Server_AbstractParticipant::disconnectClient() { - bool isRegistered = userInfo->user_level() & ServerInfo_User::IsRegistered; + const bool isRegistered = userInfo->user_level() & ServerInfo_User::IsRegistered; if (!isRegistered || spectator) { game->removeParticipant(this, Event_Leave::USER_DISCONNECTED); } else { diff --git a/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_player.cpp b/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_player.cpp index aaf7f1332..d65224e32 100644 --- a/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_player.cpp +++ b/libcockatrice_network/libcockatrice/network/server/remote/game/server_abstract_player.cpp @@ -81,7 +81,7 @@ int Server_AbstractPlayer::newCardId() int Server_AbstractPlayer::newArrowId() const { int id = 0; - for (Server_Arrow *a : arrows) { + for (const Server_Arrow *a : arrows) { if (a->getId() > id) { id = a->getId(); } @@ -96,12 +96,12 @@ void Server_AbstractPlayer::setupZones() void Server_AbstractPlayer::clearZones() { - for (Server_CardZone *zone : zones) { + for (const Server_CardZone *zone : zones) { delete zone; } zones.clear(); - for (Server_Arrow *arrow : arrows) { + for (const Server_Arrow *arrow : arrows) { delete arrow; } arrows.clear(); @@ -125,7 +125,7 @@ void Server_AbstractPlayer::updateArrowId(int id) bool Server_AbstractPlayer::deleteArrow(int arrowId) { - Server_Arrow *arrow = arrows.value(arrowId, 0); + const Server_Arrow *arrow = arrows.value(arrowId, 0); if (!arrow) { return false; } @@ -449,7 +449,7 @@ void Server_AbstractPlayer::onCardBeingMoved(GameEventStorage &ges, } // set card pt - QString ptString = QString::fromStdString(thisCardProperties->pt()); + const QString ptString = QString::fromStdString(thisCardProperties->pt()); if (!ptString.isEmpty()) { setCardAttrHelper(ges, targetzone->getPlayer()->getPlayerId(), targetzone->getName(), card->getId(), AttrPT, ptString); @@ -726,7 +726,8 @@ Server_AbstractPlayer::cmdMoveCard(const Command_MoveCard &cmd, ResponseContaine return Response::RespContextError; } - Server_AbstractPlayer *startPlayer = game->getPlayer(cmd.has_start_player_id() ? cmd.start_player_id() : playerId); + const Server_AbstractPlayer *startPlayer = + game->getPlayer(cmd.has_start_player_id() ? cmd.start_player_id() : playerId); if (!startPlayer) { return Response::RespNameNotFound; } @@ -739,7 +740,7 @@ Server_AbstractPlayer::cmdMoveCard(const Command_MoveCard &cmd, ResponseContaine return Response::RespContextError; } - Server_AbstractPlayer *targetPlayer = game->getPlayer(cmd.target_player_id()); + const Server_AbstractPlayer *targetPlayer = game->getPlayer(cmd.target_player_id()); if (!targetPlayer) { return Response::RespNameNotFound; } @@ -800,7 +801,7 @@ Server_AbstractPlayer::cmdFlipCard(const Command_FlipCard &cmd, ResponseContaine event.set_face_down(faceDown); ges.enqueueGameEvent(event, playerId); - QString ptString = nameFromStdString(cmd.pt()); + const QString ptString = nameFromStdString(cmd.pt()); if (!ptString.isEmpty() && !faceDown) { setCardAttrHelper(ges, playerId, zone->getName(), card->getId(), AttrPT, ptString); } @@ -870,13 +871,13 @@ Server_AbstractPlayer::cmdAttachCard(const Command_AttachCard &cmd, ResponseCont for (auto *player : game->getPlayers()) { QList _arrows = player->getArrows().values(); QList toDelete; - for (auto a : _arrows) { - auto *tCard = qobject_cast(a->getTargetItem()); + for (const auto a : _arrows) { + const auto *tCard = qobject_cast(a->getTargetItem()); if ((tCard == card) || (a->getStartCard() == card)) { toDelete.append(a); } } - for (auto &i : toDelete) { + for (const auto &i : toDelete) { Event_DeleteArrow event; event.set_arrow_id(i->getId()); ges.enqueueGameEvent(event, player->getPlayerId()); @@ -1136,10 +1137,10 @@ void Server_AbstractPlayer::sendCreateTokenEvents(Server_CardZone *zone, } // Token is face-down. We have to send different info to each player - auto eventOthers = makeCreateTokenEvent(zone, card, xCoord, yCoord, false); + const auto eventOthers = makeCreateTokenEvent(zone, card, xCoord, yCoord, false); ges.enqueueGameEvent(eventOthers, playerId, GameEventStorageItem::SendToOthers); - auto eventPrivate = makeCreateTokenEvent(zone, card, xCoord, yCoord, true); + const auto eventPrivate = makeCreateTokenEvent(zone, card, xCoord, yCoord, true); ges.enqueueGameEvent(eventPrivate, playerId, GameEventStorageItem::SendToPrivate, playerId); // Event_CreateToken didn't use to have face_down field; send attribute event afterward for backwards compatibility @@ -1161,14 +1162,14 @@ Server_AbstractPlayer::cmdCreateArrow(const Command_CreateArrow &cmd, ResponseCo return Response::RespContextError; } - Server_AbstractPlayer *startPlayer = game->getPlayer(cmd.start_player_id()); + const Server_AbstractPlayer *startPlayer = game->getPlayer(cmd.start_player_id()); Server_AbstractPlayer *targetPlayer = game->getPlayer(cmd.target_player_id()); if (!startPlayer || !targetPlayer) { return Response::RespNameNotFound; } - QString startZoneName = nameFromStdString(cmd.start_zone()); + const QString startZoneName = nameFromStdString(cmd.start_zone()); Server_CardZone *startZone = startPlayer->getZones().value(startZoneName); - bool playerTarget = !cmd.has_target_zone(); + const bool playerTarget = !cmd.has_target_zone(); Server_CardZone *targetZone = nullptr; if (!playerTarget) { targetZone = targetPlayer->getZones().value(nameFromStdString(cmd.target_zone())); @@ -1207,9 +1208,10 @@ Server_AbstractPlayer::cmdCreateArrow(const Command_CreateArrow &cmd, ResponseCo } } - int currentPhase = game->getActivePhase(); - int deletionPhase = cmd.has_delete_in_phase() ? cmd.delete_in_phase() : currentPhase; - auto arrow = new Server_Arrow(newArrowId(), startCard, targetItem, cmd.arrow_color(), currentPhase, deletionPhase); + const int currentPhase = game->getActivePhase(); + const int deletionPhase = cmd.has_delete_in_phase() ? cmd.delete_in_phase() : currentPhase; + const auto arrow = + new Server_Arrow(newArrowId(), startCard, targetItem, cmd.arrow_color(), currentPhase, deletionPhase); addArrow(arrow); Event_CreateArrow event; @@ -1321,7 +1323,7 @@ Response::ResponseCode Server_AbstractPlayer::cmdIncCardCounter(const Command_In return Response::RespNameNotFound; } - int newValue = card->getCounter(cmd.counter_id()) + cmd.counter_delta(); + const int newValue = card->getCounter(cmd.counter_id()) + cmd.counter_delta(); card->setCounter(cmd.counter_id(), newValue); Event_SetCardCounter event; @@ -1341,7 +1343,7 @@ Server_AbstractPlayer::cmdDumpZone(const Command_DumpZone &cmd, ResponseContaine return Response::RespGameNotStarted; } - Server_AbstractPlayer *otherPlayer = game->getPlayer(cmd.player_id()); + const Server_AbstractPlayer *otherPlayer = game->getPlayer(cmd.player_id()); if (!otherPlayer) { return Response::RespNameNotFound; } @@ -1353,7 +1355,7 @@ Server_AbstractPlayer::cmdDumpZone(const Command_DumpZone &cmd, ResponseContaine return Response::RespContextError; } - int numberCards = cmd.number_cards(); + const int numberCards = cmd.number_cards(); const QList &cards = zone->getCards(); auto *re = new Response_DumpZone; @@ -1365,7 +1367,7 @@ Server_AbstractPlayer::cmdDumpZone(const Command_DumpZone &cmd, ResponseContaine for (int i = 0; (i < cards.size()) && (i < numberCards || numberCards == -1); ++i) { const auto &findId = cmd.is_reversed() ? cards.size() - numberCards + i : i; - Server_Card *card = cards[findId]; + const Server_Card *card = cards[findId]; QString displayedName = card->getFaceDown() ? QString() : card->getName(); ServerInfo_Card *cardInfo = zoneInfo->add_card_list(); cardInfo->set_provider_id(card->getProviderId().toStdString()); @@ -1554,9 +1556,9 @@ Response::ResponseCode Server_AbstractPlayer::cmdChangeZoneProperties(const Comm } // Neither value changed -> error. - bool alwaysRevealChanged = + const bool alwaysRevealChanged = cmd.has_always_reveal_top_card() && zone->getAlwaysRevealTopCard() != cmd.always_reveal_top_card(); - bool alwaysLookAtTopChanged = + const bool alwaysLookAtTopChanged = cmd.has_always_look_at_top_card() && zone->getAlwaysLookAtTopCard() != cmd.always_look_at_top_card(); if (!alwaysRevealChanged && !alwaysLookAtTopChanged) { return Response::RespContextError; diff --git a/libcockatrice_network/libcockatrice/network/server/remote/game/server_cardzone.cpp b/libcockatrice_network/libcockatrice/network/server/remote/game/server_cardzone.cpp index 68dcadd35..7231104ef 100644 --- a/libcockatrice_network/libcockatrice/network/server/remote/game/server_cardzone.cpp +++ b/libcockatrice_network/libcockatrice/network/server/remote/game/server_cardzone.cpp @@ -130,7 +130,7 @@ int Server_CardZone::removeCard(Server_Card *card) int Server_CardZone::removeCard(Server_Card *card, bool &wasLookedAt) { - int index = cards.indexOf(card); + const int index = cards.indexOf(card); wasLookedAt = isCardAtPosLookedAt(index); if (wasLookedAt && cardsBeingLookedAt > 0) { cardsBeingLookedAt -= 1; @@ -251,7 +251,7 @@ void Server_CardZone::fixFreeSpaces(GameEventStorage &ges) return; QSet> placesToLook; - for (auto &card : cards) + for (const auto &card : cards) placesToLook.insert(QPair((card->getX() / 3) * 3, card->getY())); QSetIterator> placeIterator(placesToLook); @@ -303,7 +303,7 @@ void Server_CardZone::insertCard(Server_Card *card, int x, int y) void Server_CardZone::clear() { - for (auto card : cards) + for (const auto card : cards) delete card; cards.clear(); coordinateMap.clear(); diff --git a/libcockatrice_network/libcockatrice/network/server/remote/game/server_player.cpp b/libcockatrice_network/libcockatrice/network/server/remote/game/server_player.cpp index b840a172c..ece0f7282 100644 --- a/libcockatrice_network/libcockatrice/network/server/remote/game/server_player.cpp +++ b/libcockatrice_network/libcockatrice/network/server/remote/game/server_player.cpp @@ -103,7 +103,7 @@ int Server_Player::newCounterId() const int id = 0; QMapIterator i(counters); while (i.hasNext()) { - Server_Counter *c = i.next().value(); + const Server_Counter *c = i.next().value(); if (c->getId() > id) { id = c->getId(); } @@ -141,9 +141,9 @@ void Server_Player::setupZones() // ------------------------------------------------------------------ // Assign card ids and create deck from deck list - InnerDecklistNode *listRoot = deck->getRoot(); + const InnerDecklistNode *listRoot = deck->getRoot(); for (int i = 0; i < listRoot->size(); ++i) { - auto *currentZone = dynamic_cast(listRoot->at(i)); + const auto *currentZone = dynamic_cast(listRoot->at(i)); Server_CardZone *z; if (currentZone->getName() == DECK_ZONE_MAIN) { z = deckZone; @@ -154,7 +154,7 @@ void Server_Player::setupZones() } for (int j = 0; j < currentZone->size(); ++j) { - auto *currentCard = dynamic_cast(currentZone->at(j)); + const auto *currentCard = dynamic_cast(currentZone->at(j)); if (!currentCard) { continue; } @@ -200,7 +200,7 @@ void Server_Player::setupZones() void Server_Player::clearZones() { Server_AbstractPlayer::clearZones(); - for (Server_Counter *counter : counters) { + for (const Server_Counter *counter : counters) { delete counter; } counters.clear(); @@ -241,7 +241,7 @@ Response::ResponseCode Server_Player::drawCards(GameEventStorage &ges, int numbe if (number > 0) { revealTopCardIfNeeded(deckZone, ges); - int currentKnownCards = deckZone->getCardsBeingLookedAt(); + const int currentKnownCards = deckZone->getCardsBeingLookedAt(); deckZone->setCardsBeingLookedAt(currentKnownCards - number); } @@ -256,13 +256,13 @@ void Server_Player::onCardBeingMoved(GameEventStorage &ges, { Server_AbstractPlayer::onCardBeingMoved(ges, cardStruct, startzone, targetzone, undoingDraw); - Server_Card *card = cardStruct.card; + const Server_Card *card = cardStruct.card; // "Undo draw" should only remain valid if the just-drawn card stays within the user's hand (e.g., they only // reorder their hand). If a just-drawn card leaves the hand then remove cards before it from the list // (Ignore the case where the card is currently being un-drawn.) if (startzone->getName() == "hand" && targetzone->getName() != "hand" && !undoingDraw) { - int index = lastDrawList.lastIndexOf(card->getId()); + const int index = lastDrawList.lastIndexOf(card->getId()); if (index != -1) { lastDrawList.erase(lastDrawList.begin(), lastDrawList.begin() + index); } @@ -410,7 +410,7 @@ Server_Player::cmdMulligan(const Command_Mulligan &cmd, ResponseContainer & /*rc Server_CardZone *hand = zones.value("hand"); Server_CardZone *_deck = zones.value("deck"); - int number = cmd.number(); + const int number = cmd.number(); if (!hand->getCards().isEmpty()) { auto cardsToMove = QList(); @@ -558,7 +558,7 @@ Server_Player::cmdDelCounter(const Command_DelCounter &cmd, ResponseContainer & return Response::RespContextError; } - Server_Counter *counter = counters.value(cmd.counter_id(), 0); + const Server_Counter *counter = counters.value(cmd.counter_id(), 0); if (!counter) { return Response::RespNameNotFound; } @@ -614,7 +614,7 @@ Response::ResponseCode Server_Player::cmdChangeZoneProperties(const Command_Chan ResponseContainer &rc, GameEventStorage &ges) { - auto ret = Server_AbstractPlayer::cmdChangeZoneProperties(cmd, rc, ges); + const auto ret = Server_AbstractPlayer::cmdChangeZoneProperties(cmd, rc, ges); Server_CardZone *zone = zones.value(nameFromStdString(cmd.zone_name())); if (!zone) { diff --git a/libcockatrice_network/libcockatrice/network/server/remote/server.cpp b/libcockatrice_network/libcockatrice/network/server/remote/server.cpp index 2f1232b8f..d88485bfc 100644 --- a/libcockatrice_network/libcockatrice/network/server/remote/server.cpp +++ b/libcockatrice_network/libcockatrice/network/server/remote/server.cpp @@ -98,8 +98,8 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, Server_DatabaseInterface *databaseInterface = getDatabaseInterface(); - AuthenticationResult authState = databaseInterface->checkUserPassword(session, name, password, clientid, reasonStr, - secondsLeft, passwordNeedsHash); + const AuthenticationResult authState = databaseInterface->checkUserPassword( + session, name, password, clientid, reasonStr, secondsLeft, passwordNeedsHash); if (authState == NotLoggedIn || authState == UserIsBanned || authState == UsernameInvalid || authState == UserIsInactive) return authState; @@ -117,7 +117,7 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, event.set_reason_str("You have been logged out due to logging in at another location."); event.set_end_time(QDateTime::currentDateTime().toSecsSinceEpoch()); - SessionEvent *se = users.value(name)->prepareSessionEvent(event); + const SessionEvent *se = users.value(name)->prepareSessionEvent(event); users.value(name)->sendProtocolItem(*se); delete se; @@ -163,8 +163,8 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session, Event_UserJoined event; event.mutable_user_info()->CopyFrom(session->copyUserInfo(false)); - SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); - for (auto &client : clients) + const SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); + for (const auto &client : clients) if (client->getAcceptsUserListChanges()) client->sendProtocolItem(*se); delete se; @@ -227,7 +227,7 @@ void Server::addClient(Server_ProtocolHandler *client) void Server::removeClient(Server_ProtocolHandler *client) { - int clientIndex = clients.indexOf(client); + const int clientIndex = clients.indexOf(client); if (clientIndex == -1) { qWarning() << "tried to remove non existing client"; return; @@ -241,12 +241,12 @@ void Server::removeClient(Server_ProtocolHandler *client) QWriteLocker locker(&clientsLock); clients.removeAt(clientIndex); - ServerInfo_User *data = client->getUserInfo(); + const ServerInfo_User *data = client->getUserInfo(); if (data) { Event_UserLeft event; event.set_name(data->name()); - SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); - for (auto &_client : clients) + const SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); + for (const auto &_client : clients) if (_client->getAcceptsUserListChanges()) _client->sendProtocolItem(*se); sendIsl_SessionEvent(*se); @@ -271,7 +271,7 @@ QList Server::getOnlineModeratorList() const // clients list should be locked by calling function prior to iteration otherwise sigfaults may occur QList results; for (auto &client : clients) { - ServerInfo_User *data = client->getUserInfo(); + const ServerInfo_User *data = client->getUserInfo(); // TODO: this line should be updated in the event there is any type of new user level created if (data && @@ -293,8 +293,8 @@ void Server::externalUserJoined(const ServerInfo_User &userInfo) Event_UserJoined event; event.mutable_user_info()->CopyFrom(userInfo); - SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); - for (auto &client : clients) + const SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); + for (const auto &client : clients) if (client->getAcceptsUserListChanges()) client->sendProtocolItem(*se); delete se; @@ -310,21 +310,21 @@ void Server::externalUserLeft(const QString &userName) // This function is always called from the main thread via signal/slot. clientsLock.lockForWrite(); - Server_AbstractUserInterface *user = externalUsers.take(userName); + const Server_AbstractUserInterface *user = externalUsers.take(userName); externalUsersBySessionId.remove(user->getUserInfo()->session_id()); clientsLock.unlock(); - QMap> userGames(user->getGames()); + const QMap> userGames(user->getGames()); QMapIterator> userGamesIterator(userGames); roomsLock.lockForRead(); while (userGamesIterator.hasNext()) { userGamesIterator.next(); - Server_Room *room = rooms.value(userGamesIterator.value().first); + const Server_Room *room = rooms.value(userGamesIterator.value().first); if (!room) continue; QReadLocker roomGamesLocker(&room->gamesLock); - Server_Game *game = room->getGames().value(userGamesIterator.key()); + const Server_Game *game = room->getGames().value(userGamesIterator.key()); if (!game) continue; @@ -342,9 +342,9 @@ void Server::externalUserLeft(const QString &userName) Event_UserLeft event; event.set_name(userName.toStdString()); - SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); + const SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); clientsLock.lockForRead(); - for (auto &client : clients) + for (const auto &client : clients) if (client->getAcceptsUserListChanges()) client->sendProtocolItem(*se); clientsLock.unlock(); @@ -443,7 +443,7 @@ void Server::externalJoinGameCommandReceived(const Command_JoinGame &cmd, } ResponseContainer responseContainer(cmdId); - Response::ResponseCode responseCode = room->processJoinGameCommand(cmd, responseContainer, userInterface); + const Response::ResponseCode responseCode = room->processJoinGameCommand(cmd, responseContainer, userInterface); userInterface->sendResponseContainer(responseContainer, responseCode); } catch (Response::ResponseCode &code) { Response response; @@ -466,7 +466,7 @@ void Server::externalGameCommandContainerReceived(const CommandContainer &cont, Response::ResponseCode finalResponseCode = Response::RespOk; QReadLocker roomsLocker(&roomsLock); - Server_Room *room = rooms.value(cont.room_id()); + const Server_Room *room = rooms.value(cont.room_id()); if (!room) { qDebug() << "externalGameCommandContainerReceived: room id=" << cont.room_id() << "not found"; throw Response::RespNotInRoom; @@ -491,7 +491,7 @@ void Server::externalGameCommandContainerReceived(const CommandContainer &cont, const GameCommand &sc = cont.game_command(i); qDebug() << "[ISL]" << getSafeDebugString(sc); - Response::ResponseCode resp = participant->processGameCommand(sc, responseContainer, ges); + const Response::ResponseCode resp = participant->processGameCommand(sc, responseContainer, ges); if (resp != Response::RespOk) finalResponseCode = resp; @@ -545,10 +545,10 @@ void Server::broadcastRoomUpdate(const ServerInfo_Room &roomInfo, bool sendToIsl Event_ListRooms event; event.add_room_list()->CopyFrom(roomInfo); - SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); + const SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event); clientsLock.lockForRead(); - for (auto &client : clients) + for (const auto &client : clients) if (client->getAcceptsRoomListChanges()) client->sendProtocolItem(*se); clientsLock.unlock(); @@ -581,7 +581,7 @@ int Server::getGamesCount() const QReadLocker locker(&roomsLock); QMapIterator roomIterator(rooms); while (roomIterator.hasNext()) { - Server_Room *room = roomIterator.next().value(); + const Server_Room *room = roomIterator.next().value(); QReadLocker roomLocker(&room->gamesLock); result += room->getGames().size(); } diff --git a/libcockatrice_network/libcockatrice/network/server/remote/server_abstractuserinterface.cpp b/libcockatrice_network/libcockatrice/network/server/remote/server_abstractuserinterface.cpp index e228f0128..7c3f1e9a4 100644 --- a/libcockatrice_network/libcockatrice/network/server/remote/server_abstractuserinterface.cpp +++ b/libcockatrice_network/libcockatrice/network/server/remote/server_abstractuserinterface.cpp @@ -54,7 +54,7 @@ void Server_AbstractUserInterface::sendResponseContainer(const ResponseContainer Response response; response.set_cmd_id(responseContainer.getCmdId()); response.set_response_code(responseCode); - ::google::protobuf::Message *responseExtension = responseContainer.getResponseExtension(); + const ::google::protobuf::Message *responseExtension = responseContainer.getResponseExtension(); if (responseExtension) response.GetReflection() ->MutableMessage(&response, responseExtension->GetDescriptor()->FindExtensionByName("ext")) @@ -86,14 +86,14 @@ void Server_AbstractUserInterface::playerAddedToGame(int gameId, int roomId, int void Server_AbstractUserInterface::joinPersistentGames(ResponseContainer &rc) { - QList gamesToJoin = + const QList gamesToJoin = server->getPersistentPlayerReferences(QString::fromStdString(userInfo->name())); server->roomsLock.lockForRead(); for (int i = 0; i < gamesToJoin.size(); ++i) { const PlayerReference &pr = gamesToJoin.at(i); - Server_Room *room = server->getRooms().value(pr.getRoomId()); + const Server_Room *room = server->getRooms().value(pr.getRoomId()); if (!room) continue; QReadLocker roomGamesLocker(&room->gamesLock); diff --git a/libcockatrice_protocol/libcockatrice/protocol/debug_pb_message.cpp b/libcockatrice_protocol/libcockatrice/protocol/debug_pb_message.cpp index f0c3448b5..9c6bd3650 100644 --- a/libcockatrice_protocol/libcockatrice/protocol/debug_pb_message.cpp +++ b/libcockatrice_protocol/libcockatrice/protocol/debug_pb_message.cpp @@ -32,7 +32,7 @@ public: void LimitedPrinter::PrintString(const std::string &val, ::google::protobuf::TextFormat::BaseTextGenerator *generator) const { - auto length = val.length(); + const auto length = val.length(); if (length > MAX_TEXT_LENGTH) { ::google::protobuf::TextFormat::FastFieldValuePrinter::PrintString( val.substr(0, MAX_NAME_LENGTH) + "... ---snip--- (" + std::to_string(length) + " bytes total", generator); @@ -57,7 +57,7 @@ void SafePrinter::applySafePrinter(const ::google::protobuf::Message &message, switch (field->cpp_type()) { case ::google::protobuf::FieldDescriptor::CPPTYPE_STRING: if (field->name().find("password") != std::string::npos) { // name contains password - auto *safePrinter = new SafePrinter(); + const auto *safePrinter = new SafePrinter(); if (!printer.RegisterFieldValuePrinter(field, safePrinter)) delete safePrinter; // in case safePrinter has not been taken ownership of } @@ -81,7 +81,7 @@ void SafePrinter::applySafePrinter(const ::google::protobuf::Message &message, QString getSafeDebugString(const ::google::protobuf::Message &message) { #if GOOGLE_PROTOBUF_VERSION > 3001000 - auto size = message.ByteSizeLong(); + const auto size = message.ByteSizeLong(); #else auto size = message.ByteSize(); #endif diff --git a/libcockatrice_rng/libcockatrice/rng/rng_abstract.cpp b/libcockatrice_rng/libcockatrice/rng/rng_abstract.cpp index 63072b988..edc9f49ae 100644 --- a/libcockatrice_rng/libcockatrice/rng/rng_abstract.cpp +++ b/libcockatrice_rng/libcockatrice/rng/rng_abstract.cpp @@ -7,7 +7,7 @@ QVector RNG_Abstract::makeNumbersVector(int n, int min, int max) const int bins = max - min + 1; QVector result(bins); for (int i = 0; i < n; ++i) { - int number = rand(min, max); + const int number = rand(min, max); if ((number < min) || (number > max)) qDebug() << "rand(" << min << "," << max << ") returned " << number; else @@ -21,7 +21,7 @@ double RNG_Abstract::testRandom(const QVector &numbers) const int n = 0; for (int i = 0; i < numbers.size(); ++i) n += numbers[i]; - double expected = (double)n / (double)numbers.size(); + const double expected = (double)n / (double)numbers.size(); double chisq = 0; for (int i = 0; i < numbers.size(); ++i) chisq += ((double)numbers[i] - expected) * ((double)numbers[i] - expected) / expected; diff --git a/libcockatrice_settings/libcockatrice/settings/game_filters_settings.cpp b/libcockatrice_settings/libcockatrice/settings/game_filters_settings.cpp index e5db3010d..dbac24b66 100644 --- a/libcockatrice_settings/libcockatrice/settings/game_filters_settings.cpp +++ b/libcockatrice_settings/libcockatrice/settings/game_filters_settings.cpp @@ -24,7 +24,7 @@ void GameFiltersSettings::setHideBuddiesOnlyGames(bool hide) bool GameFiltersSettings::isHideBuddiesOnlyGames() { - QVariant previous = getValue("hide_buddies_only_games"); + const QVariant previous = getValue("hide_buddies_only_games"); return previous == QVariant() ? false : previous.toBool(); } @@ -35,7 +35,7 @@ void GameFiltersSettings::setHideFullGames(bool hide) bool GameFiltersSettings::isHideFullGames() { - QVariant previous = getValue("hide_full_games"); + const QVariant previous = getValue("hide_full_games"); return previous == QVariant() ? false : previous.toBool(); } @@ -46,7 +46,7 @@ void GameFiltersSettings::setHideGamesThatStarted(bool hide) bool GameFiltersSettings::isHideGamesThatStarted() { - QVariant previous = getValue("hide_games_that_started"); + const QVariant previous = getValue("hide_games_that_started"); return previous == QVariant() ? false : previous.toBool(); } @@ -57,7 +57,7 @@ void GameFiltersSettings::setHidePasswordProtectedGames(bool hide) bool GameFiltersSettings::isHidePasswordProtectedGames() { - QVariant previous = getValue("hide_password_protected_games"); + const QVariant previous = getValue("hide_password_protected_games"); return previous == QVariant() ? false : previous.toBool(); } @@ -68,7 +68,7 @@ void GameFiltersSettings::setHideIgnoredUserGames(bool hide) bool GameFiltersSettings::isHideIgnoredUserGames() { - QVariant previous = getValue("hide_ignored_user_games"); + const QVariant previous = getValue("hide_ignored_user_games"); return previous == QVariant() ? true : previous.toBool(); } @@ -79,7 +79,7 @@ void GameFiltersSettings::setHideNotBuddyCreatedGames(bool hide) bool GameFiltersSettings::isHideNotBuddyCreatedGames() { - QVariant previous = getValue("hide_not_buddy_created_games"); + const QVariant previous = getValue("hide_not_buddy_created_games"); return previous == QVariant() ? false : previous.toBool(); } @@ -90,7 +90,7 @@ void GameFiltersSettings::setHideOpenDecklistGames(bool hide) bool GameFiltersSettings::isHideOpenDecklistGames() { - QVariant previous = getValue("hide_open_decklist_games"); + const QVariant previous = getValue("hide_open_decklist_games"); return previous == QVariant() ? false : previous.toBool(); } @@ -121,7 +121,7 @@ void GameFiltersSettings::setMinPlayers(int min) int GameFiltersSettings::getMinPlayers() { - QVariant previous = getValue("min_players"); + const QVariant previous = getValue("min_players"); return previous == QVariant() ? 1 : previous.toInt(); } @@ -132,7 +132,7 @@ void GameFiltersSettings::setMaxPlayers(int max) int GameFiltersSettings::getMaxPlayers() { - QVariant previous = getValue("max_players"); + const QVariant previous = getValue("max_players"); return previous == QVariant() ? 99 : previous.toInt(); } @@ -143,7 +143,7 @@ void GameFiltersSettings::setMaxGameAge(const QTime &maxGameAge) QTime GameFiltersSettings::getMaxGameAge() { - QVariant previous = getValue("max_game_age_time"); + const QVariant previous = getValue("max_game_age_time"); return previous.toTime(); } @@ -159,7 +159,7 @@ void GameFiltersSettings::setGameHashedTypeEnabled(QString gametypeHASHED, bool bool GameFiltersSettings::isGameTypeEnabled(QString gametype) { - QVariant previous = getValue("game_type/" + hashGameType(gametype)); + const QVariant previous = getValue("game_type/" + hashGameType(gametype)); return previous == QVariant() ? false : previous.toBool(); } @@ -170,7 +170,7 @@ void GameFiltersSettings::setShowOnlyIfSpectatorsCanWatch(bool show) bool GameFiltersSettings::isShowOnlyIfSpectatorsCanWatch() { - QVariant previous = getValue("show_only_if_spectators_can_watch"); + const QVariant previous = getValue("show_only_if_spectators_can_watch"); return previous == QVariant() ? false : previous.toBool(); } @@ -181,7 +181,7 @@ void GameFiltersSettings::setShowSpectatorPasswordProtected(bool show) bool GameFiltersSettings::isShowSpectatorPasswordProtected() { - QVariant previous = getValue("show_spectator_password_protected"); + const QVariant previous = getValue("show_spectator_password_protected"); return previous == QVariant() ? false : previous.toBool(); } @@ -192,7 +192,7 @@ void GameFiltersSettings::setShowOnlyIfSpectatorsCanChat(bool show) bool GameFiltersSettings::isShowOnlyIfSpectatorsCanChat() { - QVariant previous = getValue("show_only_if_spectators_can_chat"); + const QVariant previous = getValue("show_only_if_spectators_can_chat"); return previous == QVariant() ? false : previous.toBool(); } @@ -203,6 +203,6 @@ void GameFiltersSettings::setShowOnlyIfSpectatorsCanSeeHands(bool show) bool GameFiltersSettings::isShowOnlyIfSpectatorsCanSeeHands() { - QVariant previous = getValue("show_only_if_spectators_can_see_hands"); + const QVariant previous = getValue("show_only_if_spectators_can_see_hands"); return previous == QVariant() ? false : previous.toBool(); } \ No newline at end of file diff --git a/libcockatrice_settings/libcockatrice/settings/layouts_settings.cpp b/libcockatrice_settings/libcockatrice/settings/layouts_settings.cpp index 4b1400e0c..073a76953 100644 --- a/libcockatrice_settings/libcockatrice/settings/layouts_settings.cpp +++ b/libcockatrice_settings/libcockatrice/settings/layouts_settings.cpp @@ -27,7 +27,7 @@ void LayoutsSettings::setDeckEditorGeometry(const QByteArray &value) QSize LayoutsSettings::getDeckEditorCardSize() { - QVariant previous = getValue("layouts/deckEditor_CardSize"); + const QVariant previous = getValue("layouts/deckEditor_CardSize"); return previous == QVariant() ? QSize(250, 500) : previous.toSize(); } @@ -38,7 +38,7 @@ void LayoutsSettings::setDeckEditorCardSize(const QSize &value) QSize LayoutsSettings::getDeckEditorDeckSize() { - QVariant previous = getValue("layouts/deckEditor_DeckSize"); + const QVariant previous = getValue("layouts/deckEditor_DeckSize"); return previous == QVariant() ? QSize(250, 360) : previous.toSize(); } @@ -49,7 +49,7 @@ void LayoutsSettings::setDeckEditorDeckSize(const QSize &value) QSize LayoutsSettings::getDeckEditorPrintingSelectorSize() { - QVariant previous = getValue("layouts/deckEditor_PrintingSelectorSize"); + const QVariant previous = getValue("layouts/deckEditor_PrintingSelectorSize"); return previous == QVariant() ? QSize(525, 250) : previous.toSize(); } @@ -60,7 +60,7 @@ void LayoutsSettings::setDeckEditorPrintingSelectorSize(const QSize &value) QSize LayoutsSettings::getDeckEditorFilterSize() { - QVariant previous = getValue("layouts/deckEditor_FilterSize"); + const QVariant previous = getValue("layouts/deckEditor_FilterSize"); return previous == QVariant() ? QSize(250, 250) : previous.toSize(); } @@ -111,7 +111,7 @@ const QByteArray LayoutsSettings::getGamePlayAreaGeometry() const QSize LayoutsSettings::getGameCardInfoSize() { - QVariant previous = getValue("layouts/gameplayarea_CardInfoSize"); + const QVariant previous = getValue("layouts/gameplayarea_CardInfoSize"); return previous == QVariant() ? QSize(250, 360) : previous.toSize(); } @@ -122,7 +122,7 @@ void LayoutsSettings::setGameCardInfoSize(const QSize &value) const QSize LayoutsSettings::getGameMessageLayoutSize() { - QVariant previous = getValue("layouts/gameplayarea_MessageLayoutSize"); + const QVariant previous = getValue("layouts/gameplayarea_MessageLayoutSize"); return previous == QVariant() ? QSize(250, 250) : previous.toSize(); } @@ -133,7 +133,7 @@ void LayoutsSettings::setGameMessageLayoutSize(const QSize &value) const QSize LayoutsSettings::getGamePlayerListSize() { - QVariant previous = getValue("layouts/gameplayarea_PlayerListSize"); + const QVariant previous = getValue("layouts/gameplayarea_PlayerListSize"); return previous == QVariant() ? QSize(250, 50) : previous.toSize(); } @@ -164,7 +164,7 @@ const QByteArray LayoutsSettings::getReplayPlayAreaGeometry() const QSize LayoutsSettings::getReplayCardInfoSize() { - QVariant previous = getValue("layouts/replayplayarea_CardInfoSize"); + const QVariant previous = getValue("layouts/replayplayarea_CardInfoSize"); return previous == QVariant() ? QSize(250, 360) : previous.toSize(); } @@ -175,7 +175,7 @@ void LayoutsSettings::setReplayCardInfoSize(const QSize &value) const QSize LayoutsSettings::getReplayMessageLayoutSize() { - QVariant previous = getValue("layouts/replayplayarea_MessageLayoutSize"); + const QVariant previous = getValue("layouts/replayplayarea_MessageLayoutSize"); return previous == QVariant() ? QSize(250, 200) : previous.toSize(); } @@ -186,7 +186,7 @@ void LayoutsSettings::setReplayMessageLayoutSize(const QSize &value) const QSize LayoutsSettings::getReplayPlayerListSize() { - QVariant previous = getValue("layouts/replayplayarea_PlayerListSize"); + const QVariant previous = getValue("layouts/replayplayarea_PlayerListSize"); return previous == QVariant() ? QSize(250, 50) : previous.toSize(); } @@ -197,7 +197,7 @@ void LayoutsSettings::setReplayPlayerListSize(const QSize &value) const QSize LayoutsSettings::getReplayReplaySize() { - QVariant previous = getValue("layouts/replayplayarea_ReplaySize"); + const QVariant previous = getValue("layouts/replayplayarea_ReplaySize"); return previous == QVariant() ? QSize(900, 100) : previous.toSize(); } diff --git a/libcockatrice_settings/libcockatrice/settings/servers_settings.cpp b/libcockatrice_settings/libcockatrice/settings/servers_settings.cpp index 5f69f47c9..9320b0450 100644 --- a/libcockatrice_settings/libcockatrice/settings/servers_settings.cpp +++ b/libcockatrice_settings/libcockatrice/settings/servers_settings.cpp @@ -15,7 +15,7 @@ void ServersSettings::setPreviousHostLogin(int previous) int ServersSettings::getPreviousHostLogin() { - QVariant previous = getValue("previoushostlogin"); + const QVariant previous = getValue("previoushostlogin"); return previous == QVariant() ? 1 : previous.toInt(); } @@ -36,27 +36,27 @@ void ServersSettings::setPrevioushostName(const QString &name) QString ServersSettings::getSaveName(QString defaultname) { - int index = getPrevioushostindex(getPrevioushostName()); - QVariant saveName = getValue(QString("saveName%1").arg(index), "server", "server_details"); + const int index = getPrevioushostindex(getPrevioushostName()); + const QVariant saveName = getValue(QString("saveName%1").arg(index), "server", "server_details"); return saveName == QVariant() ? std::move(defaultname) : saveName.toString(); } QString ServersSettings::getSite(QString defaultSite) { - int index = getPrevioushostindex(getPrevioushostName()); - QVariant site = getValue(QString("site%1").arg(index), "server", "server_details"); + const int index = getPrevioushostindex(getPrevioushostName()); + const QVariant site = getValue(QString("site%1").arg(index), "server", "server_details"); return site == QVariant() ? std::move(defaultSite) : site.toString(); } QString ServersSettings::getPrevioushostName() { - QVariant value = getValue("previoushostName"); + const QVariant value = getValue("previoushostName"); return value == QVariant() ? "Rooster Ranges" : value.toString(); } int ServersSettings::getPrevioushostindex(const QString &saveName) { - int size = getValue("totalServers", "server", "server_details").toInt(); + const int size = getValue("totalServers", "server", "server_details").toInt(); for (int i = 0; i <= size; ++i) if (saveName == getValue(QString("saveName%1").arg(i), "server", "server_details").toString()) @@ -67,30 +67,30 @@ int ServersSettings::getPrevioushostindex(const QString &saveName) QString ServersSettings::getHostname(QString defaultHost) { - int index = getPrevioushostindex(getPrevioushostName()); - QVariant hostname = getValue(QString("server%1").arg(index), "server", "server_details"); + const int index = getPrevioushostindex(getPrevioushostName()); + const QVariant hostname = getValue(QString("server%1").arg(index), "server", "server_details"); return hostname == QVariant() ? std::move(defaultHost) : hostname.toString(); } QString ServersSettings::getPort(QString defaultPort) { - int index = getPrevioushostindex(getPrevioushostName()); - QVariant port = getValue(QString("port%1").arg(index), "server", "server_details"); + const int index = getPrevioushostindex(getPrevioushostName()); + const QVariant port = getValue(QString("port%1").arg(index), "server", "server_details"); qCDebug(ServersSettingsLog) << "getPort() index = " << index << " port.val = " << port.toString(); return port == QVariant() ? std::move(defaultPort) : port.toString(); } QString ServersSettings::getPlayerName(QString defaultName) { - int index = getPrevioushostindex(getPrevioushostName()); - QVariant name = getValue(QString("username%1").arg(index), "server", "server_details"); + const int index = getPrevioushostindex(getPrevioushostName()); + const QVariant name = getValue(QString("username%1").arg(index), "server", "server_details"); qCDebug(ServersSettingsLog) << "getPlayerName() index = " << index << " name.val = " << name.toString(); return name == QVariant() ? std::move(defaultName) : name.toString(); } QString ServersSettings::getPassword() { - int index = getPrevioushostindex(getPrevioushostName()); + const int index = getPrevioushostindex(getPrevioushostName()); if (getSavePassword()) return getValue(QString("password%1").arg(index), "server", "server_details").toString(); @@ -100,8 +100,8 @@ QString ServersSettings::getPassword() bool ServersSettings::getSavePassword() { - int index = getPrevioushostindex(getPrevioushostName()); - bool save = getValue(QString("savePassword%1").arg(index), "server", "server_details").toBool(); + const int index = getPrevioushostindex(getPrevioushostName()); + const bool save = getValue(QString("savePassword%1").arg(index), "server", "server_details").toBool(); return save; } @@ -112,7 +112,7 @@ void ServersSettings::setAutoConnect(int autoconnect) int ServersSettings::getAutoConnect() { - QVariant autoconnect = getValue("auto_connect"); + const QVariant autoconnect = getValue("auto_connect"); return autoconnect == QVariant() ? 0 : autoconnect.toInt(); } @@ -123,7 +123,7 @@ void ServersSettings::setFPHostName(QString hostname) QString ServersSettings::getFPHostname(QString defaultHost) { - QVariant hostname = getValue("fphostname"); + const QVariant hostname = getValue("fphostname"); return hostname == QVariant() ? std::move(defaultHost) : hostname.toString(); } @@ -134,7 +134,7 @@ void ServersSettings::setFPPort(QString port) QString ServersSettings::getFPPort(QString defaultPort) { - QVariant port = getValue("fpport"); + const QVariant port = getValue("fpport"); return port == QVariant() ? std::move(defaultPort) : port.toString(); } @@ -145,7 +145,7 @@ void ServersSettings::setFPPlayerName(QString playerName) QString ServersSettings::getFPPlayerName(QString defaultName) { - QVariant name = getValue("fpplayername"); + const QVariant name = getValue("fpplayername"); return name == QVariant() ? std::move(defaultName) : name.toString(); } @@ -156,7 +156,7 @@ void ServersSettings::setClearDebugLogStatus(bool abIsChecked) bool ServersSettings::getClearDebugLogStatus(bool abDefaultValue) { - QVariant cbFlushLog = getValue("save_debug_log"); + const QVariant cbFlushLog = getValue("save_debug_log"); return cbFlushLog == QVariant() ? abDefaultValue : cbFlushLog.toBool(); } @@ -171,7 +171,7 @@ void ServersSettings::addNewServer(const QString &saveName, if (updateExistingServer(saveName, serv, port, username, password, savePassword, site)) return; - int index = getValue("totalServers", "server", "server_details").toInt() + 1; + const int index = getValue("totalServers", "server", "server_details").toInt() + 1; setValue(saveName, QString("saveName%1").arg(index), "server", "server_details"); setValue(serv, QString("server%1").arg(index), "server", "server_details"); @@ -185,7 +185,7 @@ void ServersSettings::addNewServer(const QString &saveName, void ServersSettings::removeServer(QString servAddr) { - int size = getValue("totalServers", "server", "server_details").toInt(); + const int size = getValue("totalServers", "server", "server_details").toInt(); bool found = false; for (int i = 0; i <= size; ++i) { @@ -196,7 +196,7 @@ void ServersSettings::removeServer(QString servAddr) } } else { // move all other entries after it one back, overwriting the previous one - int previous = i - 1; // we delete only one entry + const int previous = i - 1; // we delete only one entry setValue(getValue(QString("server%1").arg(i), "server", "server_details"), QString("server%1").arg(previous), "server", "server_details"); setValue(getValue(QString("port%1").arg(i), "server", "server_details"), QString("port%1").arg(previous), @@ -234,7 +234,7 @@ void ServersSettings::removeServer(QString servAddr) */ bool ServersSettings::updateExistingServerWithoutLoss(QString saveName, QString serv, QString port, QString site) { - int size = getValue("totalServers", "server", "server_details").toInt(); + const int size = getValue("totalServers", "server", "server_details").toInt(); for (int i = 0; i <= size; ++i) { if (serv == getValue(QString("server%1").arg(i), "server", "server_details").toString()) { @@ -262,7 +262,7 @@ bool ServersSettings::updateExistingServer(QString saveName, bool savePassword, QString site) { - int size = getValue("totalServers", "server", "server_details").toInt(); + const int size = getValue("totalServers", "server", "server_details").toInt(); for (int i = 0; i <= size; ++i) { if (serv == getValue(QString("server%1").arg(i), "server", "server_details").toString()) { diff --git a/libcockatrice_utility/libcockatrice/utility/expression.cpp b/libcockatrice_utility/libcockatrice/utility/expression.cpp index 3b2e815d1..08e3eb8b0 100644 --- a/libcockatrice_utility/libcockatrice/utility/expression.cpp +++ b/libcockatrice_utility/libcockatrice/utility/expression.cpp @@ -53,7 +53,7 @@ double Expression::eval(const peg::Ast &ast) if (ast.name == "NUMBER") { return stod(std::string(ast.token)); } else if (ast.name == "FUNCTION") { - QString name = QString::fromStdString(std::string(nodes[0]->token)); + const QString name = QString::fromStdString(std::string(nodes[0]->token)); if (!fns.contains(name)) return 0; return fns[name](eval(*nodes[1])); @@ -62,8 +62,8 @@ double Expression::eval(const peg::Ast &ast) } else if (ast.name[0] == 'P') { double result = eval(*nodes[0]); for (unsigned int i = 1; i < nodes.size(); i += 2) { - double arg = eval(*nodes[i + 1]); - char operation = nodes[i]->token[0]; + const double arg = eval(*nodes[i + 1]); + const char operation = nodes[i]->token[0]; switch (operation) { case '+': result += arg; diff --git a/libcockatrice_utility/libcockatrice/utility/levenshtein.cpp b/libcockatrice_utility/libcockatrice/utility/levenshtein.cpp index cfb972f91..aa604132b 100644 --- a/libcockatrice_utility/libcockatrice/utility/levenshtein.cpp +++ b/libcockatrice_utility/libcockatrice/utility/levenshtein.cpp @@ -5,8 +5,8 @@ int levenshteinDistance(const QString &s1, const QString &s2) { - int len1 = s1.size(); - int len2 = s2.size(); + const int len1 = s1.size(); + const int len2 = s2.size(); std::vector> dp(len1 + 1, std::vector(len2 + 1)); for (int i = 0; i <= len1; i++) @@ -16,7 +16,7 @@ int levenshteinDistance(const QString &s1, const QString &s2) for (int i = 1; i <= len1; i++) { for (int j = 1; j <= len2; j++) { - int cost = (s1[i - 1] == s2[j - 1]) ? 0 : 1; + const int cost = (s1[i - 1] == s2[j - 1]) ? 0 : 1; dp[i][j] = std::min({dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + cost}); } } diff --git a/libcockatrice_utility/libcockatrice/utility/passwordhasher.cpp b/libcockatrice_utility/libcockatrice/utility/passwordhasher.cpp index c40c5f94f..4f6a64789 100644 --- a/libcockatrice_utility/libcockatrice/utility/passwordhasher.cpp +++ b/libcockatrice_utility/libcockatrice/utility/passwordhasher.cpp @@ -5,7 +5,7 @@ QString PasswordHasher::computeHash(const QString &password, const QString &salt) { - QCryptographicHash::Algorithm algo = QCryptographicHash::Sha512; + const QCryptographicHash::Algorithm algo = QCryptographicHash::Sha512; const int rounds = 1000; QByteArray hash = (salt + password).toUtf8(); @@ -23,7 +23,7 @@ QString PasswordHasher::generateRandomSalt(const int len) "abcdefghijklmnopqrstuvwxyz"; QString ret; - int size = sizeof(alphanum) - 1; + const int size = sizeof(alphanum) - 1; for (int i = 0; i < len; ++i) { ret.append(alphanum[rng->rand(0, size)]); diff --git a/servatrice/src/isl_interface.cpp b/servatrice/src/isl_interface.cpp index 2269ff314..3048a82bc 100644 --- a/servatrice/src/isl_interface.cpp +++ b/servatrice/src/isl_interface.cpp @@ -68,7 +68,7 @@ IslInterface::~IslInterface() server->roomsLock.lockForRead(); QMapIterator roomIterator(server->getRooms()); while (roomIterator.hasNext()) { - Server_Room *room = roomIterator.next().value(); + const Server_Room *room = roomIterator.next().value(); room->usersLock.lockForRead(); QMapIterator roomUsers(room->getExternalUsers()); while (roomUsers.hasNext()) { @@ -113,7 +113,7 @@ void IslInterface::initServer() socket->startServerEncryption(); if (!socket->waitForEncrypted(5000)) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)) - QList sslErrors(socket->sslHandshakeErrors()); + const QList sslErrors(socket->sslHandshakeErrors()); #else QList sslErrors(socket->sslErrors()); #endif @@ -146,7 +146,7 @@ void IslInterface::initServer() server->roomsLock.lockForRead(); QMapIterator roomIterator(server->getRooms()); while (roomIterator.hasNext()) { - Server_Room *room = roomIterator.next().value(); + const Server_Room *room = roomIterator.next().value(); room->usersLock.lockForRead(); room->gamesLock.lockForRead(); room->getInfo(*event.add_room_list(), true, true, false); @@ -194,7 +194,7 @@ void IslInterface::initClient() } if (!socket->waitForEncrypted(5000)) { #if (QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)) - QList sslErrors(socket->sslHandshakeErrors()); + const QList sslErrors(socket->sslHandshakeErrors()); #else QList sslErrors(socket->sslErrors()); #endif @@ -230,7 +230,7 @@ void IslInterface::flushOutputBuffer() void IslInterface::readClient() { - QByteArray data = socket->readAll(); + const QByteArray data = socket->readAll(); server->incRxBytes(data.size()); inputBuffer.append(data); @@ -273,7 +273,7 @@ void IslInterface::transmitMessage(const IslMessage &item) { QByteArray buf; #if GOOGLE_PROTOBUF_VERSION > 3001000 - unsigned int size = static_cast(item.ByteSizeLong()); + const unsigned int size = static_cast(item.ByteSizeLong()); #else unsigned int size = static_cast(item.ByteSize()); #endif diff --git a/servatrice/src/main.cpp b/servatrice/src/main.cpp index b1294a04c..8f5bb3faa 100644 --- a/servatrice/src/main.cpp +++ b/servatrice/src/main.cpp @@ -77,7 +77,7 @@ void testRNG() std::cerr << std::endl; } std::cerr << std::endl << "Chi^2 ="; - for (double j : chisq) + for (const double j : chisq) std::cerr << "\t" << QString::number(j, 'f', 3).toStdString(); std::cerr << std::endl << "k ="; for (int j = 0; j < chisq.size(); ++j) @@ -89,10 +89,10 @@ void testHash() { const int n = 5000; std::cerr << "Benchmarking password hash function (n =" << n << ")..." << std::endl; - QDateTime startTime = QDateTime::currentDateTime(); + const QDateTime startTime = QDateTime::currentDateTime(); for (int i = 0; i < n; ++i) PasswordHasher::computeHash("aaaaaa", "aaaaaaaaaaaaaaaa"); - QDateTime endTime = QDateTime::currentDateTime(); + const QDateTime endTime = QDateTime::currentDateTime(); std::cerr << startTime.secsTo(endTime) << "secs" << std::endl; } @@ -109,7 +109,7 @@ void myMessageOutput2(QtMsgType /*type*/, const QMessageLogContext &, const QStr int main(int argc, char *argv[]) { - QCoreApplication app(argc, argv); + const QCoreApplication app(argc, argv); QCoreApplication::setOrganizationName("Cockatrice"); QCoreApplication::setApplicationName("Servatrice"); QCoreApplication::setApplicationVersion(VERSION_STRING); @@ -118,23 +118,23 @@ int main(int argc, char *argv[]) parser.addHelpOption(); parser.addVersionOption(); - QCommandLineOption testRandomOpt("test-random", "Test PRNG (chi^2)"); + const QCommandLineOption testRandomOpt("test-random", "Test PRNG (chi^2)"); parser.addOption(testRandomOpt); - QCommandLineOption testHashFunctionOpt("test-hash", "Test password hash function"); + const QCommandLineOption testHashFunctionOpt("test-hash", "Test password hash function"); parser.addOption(testHashFunctionOpt); - QCommandLineOption logToConsoleOpt("log-to-console", "Write server logs to console"); + const QCommandLineOption logToConsoleOpt("log-to-console", "Write server logs to console"); parser.addOption(logToConsoleOpt); - QCommandLineOption configPathOpt("config", "Read server configuration from ", "file", ""); + const QCommandLineOption configPathOpt("config", "Read server configuration from ", "file", ""); parser.addOption(configPathOpt); parser.process(app); - bool testRandom = parser.isSet(testRandomOpt); - bool testHashFunction = parser.isSet(testHashFunctionOpt); - bool logToConsole = parser.isSet(logToConsoleOpt); + const bool testRandom = parser.isSet(testRandomOpt); + const bool testHashFunction = parser.isSet(testHashFunctionOpt); + const bool logToConsole = parser.isSet(logToConsoleOpt); QString configPath = parser.value(configPathOpt); qRegisterMetaType>("QList"); diff --git a/servatrice/src/server_logger.cpp b/servatrice/src/server_logger.cpp index 9e40ac7b4..9ed423dd5 100644 --- a/servatrice/src/server_logger.cpp +++ b/servatrice/src/server_logger.cpp @@ -24,8 +24,8 @@ ServerLogger::~ServerLogger() void ServerLogger::startLog(const QString &logFileName) { if (!logFileName.isEmpty()) { - QFileInfo fi(logFileName); - QDir fileDir(fi.path()); + const QFileInfo fi(logFileName); + const QDir fileDir(fi.path()); if (!fileDir.exists() && !fileDir.mkpath(fileDir.absolutePath())) { std::cerr << "ERROR: logfile folder doesn't exist and i can't create it." << std::endl; logFile = 0; @@ -55,8 +55,8 @@ void ServerLogger::logMessage(const QString &message, void *caller) callerString = QString::number((qulonglong)caller, 16) + " "; // filter out all log entries based on values in configuration file - bool shouldWeWriteLog = settingsCache->value("server/writelog", 1).toBool(); - QString logFilters = settingsCache->value("server/logfilters").toString(); + const bool shouldWeWriteLog = settingsCache->value("server/writelog", 1).toBool(); + const QString logFilters = settingsCache->value("server/logfilters").toString(); #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) QStringList listlogFilters = logFilters.split(",", Qt::SkipEmptyParts); #else diff --git a/servatrice/src/smtpclient.cpp b/servatrice/src/smtpclient.cpp index ee7214904..a9e4fb4f4 100644 --- a/servatrice/src/smtpclient.cpp +++ b/servatrice/src/smtpclient.cpp @@ -38,9 +38,9 @@ SmtpClient::~SmtpClient() bool SmtpClient::enqueueActivationTokenMail(const QString &nickname, const QString &recipient, const QString &token) { - QString email = settingsCache->value("smtp/email", "").toString(); - QString name = settingsCache->value("smtp/name", "").toString(); - QString subject = settingsCache->value("smtp/subject", "").toString(); + const QString email = settingsCache->value("smtp/email", "").toString(); + const QString name = settingsCache->value("smtp/name", "").toString(); + const QString subject = settingsCache->value("smtp/subject", "").toString(); QString body = settingsCache->value("smtp/body", "").toString(); if (email.isEmpty()) { @@ -74,16 +74,16 @@ bool SmtpClient::enqueueActivationTokenMail(const QString &nickname, const QStri message.setSubject(subject); message.setBody(body.replace("%username", nickname).replace("%token", token)); - int id = smtp->send(message); + const int id = smtp->send(message); qDebug() << "[MAIL] Enqueued mail to" << recipient << "as" << id; return true; } bool SmtpClient::enqueueForgotPasswordTokenMail(const QString &nickname, const QString &recipient, const QString &token) { - QString email = settingsCache->value("smtp/email", "").toString(); - QString name = settingsCache->value("smtp/name", "").toString(); - QString subject = settingsCache->value("forgotpassword/subject", "").toString(); + const QString email = settingsCache->value("smtp/email", "").toString(); + const QString name = settingsCache->value("smtp/name", "").toString(); + const QString subject = settingsCache->value("forgotpassword/subject", "").toString(); QString body = settingsCache->value("forgotpassword/body", "").toString(); if (email.isEmpty()) { @@ -117,7 +117,7 @@ bool SmtpClient::enqueueForgotPasswordTokenMail(const QString &nickname, const Q message.setSubject(subject); message.setBody(body.replace("%username", nickname).replace("%token", token)); - int id = smtp->send(message); + const int id = smtp->send(message); qDebug() << "[MAIL] Enqueued mail to" << recipient << "as" << id; return true; } @@ -131,12 +131,12 @@ void SmtpClient::sendAllEmails() if (smtp->pendingMessages() == 0) return; - QString connectionType = settingsCache->value("smtp/connection", "tcp").toString(); - QString host = settingsCache->value("smtp/host", "localhost").toString(); - int port = settingsCache->value("smtp/port", 25).toInt(); - QByteArray username = settingsCache->value("smtp/username", "").toByteArray(); - QByteArray password = settingsCache->value("smtp/password", "").toByteArray(); - bool acceptAllCerts = settingsCache->value("smtp/acceptallcerts", false).toBool(); + const QString connectionType = settingsCache->value("smtp/connection", "tcp").toString(); + const QString host = settingsCache->value("smtp/host", "localhost").toString(); + const int port = settingsCache->value("smtp/port", 25).toInt(); + const QByteArray username = settingsCache->value("smtp/username", "").toByteArray(); + const QByteArray password = settingsCache->value("smtp/password", "").toByteArray(); + const bool acceptAllCerts = settingsCache->value("smtp/acceptallcerts", false).toBool(); smtp->setUsername(username); smtp->setPassword(password);