diff --git a/.github/workflows/desktop-build.yml b/.github/workflows/desktop-build.yml
index b631f32d3..6ca634389 100644
--- a/.github/workflows/desktop-build.yml
+++ b/.github/workflows/desktop-build.yml
@@ -152,7 +152,7 @@ jobs:
env:
CACHE: ${{ github.workspace }}/.cache/${{ matrix.distro }}${{ matrix.version }} # directory for caching docker image and ccache
CCACHE_EVICTION_AGE: 7d
- CCACHE_SIZE: 550M # space of all repo is 10Gi: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#usage-limits-and-eviction-policy
+ CCACHE_SIZE: 600M # space of all repo is 10Gi: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#usage-limits-and-eviction-policy
CMAKE_GENERATOR: 'Ninja'
NAME: ${{ matrix.distro }}${{ matrix.version }}
@@ -342,7 +342,7 @@ jobs:
timeout-minutes: 100
env:
CCACHE_DIR: ${{ github.workspace }}/.cache/
- CCACHE_SIZE: 550M # space of all repo is 10Gi: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#usage-limits-and-eviction-policy
+ CCACHE_SIZE: 600M # space of all repo is 10Gi: https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows#usage-limits-and-eviction-policy
steps:
- name: "Checkout"
diff --git a/README.md b/README.md
index f22df461f..5935bb540 100644
--- a/README.md
+++ b/README.md
@@ -149,15 +149,15 @@ You can then
The following flags (with their non-default values) can be passed to `cmake`:
-| Flag | Description |
-| --- | --- |
-| `-DWITH_SERVER=1` | Build Servatrice server |
-| `-DWITH_CLIENT=0` | Don't build Cockatrice client |
-| `-DWITH_ORACLE=0` | Don't build Oracle card database tool |
-| `-DCMAKE_BUILD_TYPE=Debug` | Compile in debug mode
Enables extra logging output, debug symbols, and much more verbose compiler warnings |
-| `-DWARNING_AS_ERROR=0` | Don't treat compilation warnings as errors in debug mode |
-| `-DUPDATE_TRANSLATIONS=1` | Configure `make` to update the translation .ts files for new strings in the source code
**Note:** `make clean` will remove the .ts files |
-| `-DTEST=1` | Enable regression tests
**Note:** `make test` to run tests, *googletest* will be downloaded if not available |
+| Flag | Description |
+| -------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
+| `-DWITH_SERVER=1` | Build Servatrice server |
+| `-DWITH_CLIENT=0` | Don't build Cockatrice client |
+| `-DWITH_ORACLE=0` | Don't build Oracle card database tool |
+| `-DCMAKE_BUILD_TYPE=Debug` | Compile in debug mode
Enables extra logging output, debug symbols, and much more verbose compiler warnings |
+| `-DWARNING_AS_ERROR=0` | Don't treat compilation warnings as errors in debug mode |
+| `-DUPDATE_TRANSLATIONS=1` | Configure `make` to update the translation .ts files for new strings in the source code
**Note:** `make clean` will remove the .ts files |
+| `-DTEST=1` | Enable regression tests
**Note:** `make test` to run tests, *googletest* will be downloaded if not available |
# Run
diff --git a/cmake/FindQtRuntime.cmake b/cmake/FindQtRuntime.cmake
index 0259d12e1..971c9094d 100644
--- a/cmake/FindQtRuntime.cmake
+++ b/cmake/FindQtRuntime.cmake
@@ -28,7 +28,7 @@ if(WITH_CLIENT)
)
endif()
if(WITH_ORACLE)
- set(_ORACLE_NEEDED Concurrent Network Svg Widgets)
+ set(_ORACLE_NEEDED Concurrent Network Svg Widgets Xml)
endif()
if(TEST)
# Union of Qt modules required across all test targets (independent of application targets).
diff --git a/cockatrice/CMakeLists.txt b/cockatrice/CMakeLists.txt
index b6050a1bd..cfc684d5f 100644
--- a/cockatrice/CMakeLists.txt
+++ b/cockatrice/CMakeLists.txt
@@ -45,11 +45,14 @@ set(cockatrice_SOURCES
src/interface/widgets/dialogs/dlg_load_deck_from_website.cpp
src/interface/widgets/dialogs/dlg_load_remote_deck.cpp
src/interface/widgets/dialogs/dlg_local_game_options.cpp
+ src/interface/widgets/dialogs/dlg_login_prompt.cpp
src/interface/widgets/dialogs/dlg_manage_sets.cpp
src/interface/widgets/dialogs/dlg_my_reports.cpp
src/interface/widgets/dialogs/dlg_register.cpp
src/interface/widgets/dialogs/dlg_report_user.cpp
src/interface/widgets/dialogs/dlg_select_set_for_cards.cpp
+ src/interface/widgets/dialogs/dlg_share_deck.cpp
+ src/interface/widgets/dialogs/dlg_shared_decks_preview.cpp
src/interface/widgets/dialogs/dlg_settings.cpp
src/interface/widgets/dialogs/dlg_startup_card_check.cpp
src/interface/widgets/dialogs/dlg_tip_of_the_day.cpp
@@ -57,6 +60,9 @@ set(cockatrice_SOURCES
src/interface/widgets/dialogs/dlg_view_log.cpp
src/interface/widgets/dialogs/override_printing_warning.cpp
src/interface/widgets/dialogs/tip_of_the_day.cpp
+ src/interface/widgets/deck_share/deck_share_utils.cpp
+ src/interface/widgets/deck_share/shared_deck_preview_widget.cpp
+ src/interface/widgets/deck_share/share_bar_widget.cpp
src/filters/deck_filter_string.cpp
src/filters/filter_builder.cpp
src/filters/filter_tree_model.cpp
@@ -163,9 +169,11 @@ set(cockatrice_SOURCES
src/interface/palette_editor/palette_grid_widget.cpp
src/interface/palette_editor/palette_editor_dialog.cpp
src/interface/widgets/cards/additional_info/color_identity_widget.cpp
+ src/interface/widgets/cards/additional_info/deck_color_identity.cpp
src/interface/widgets/cards/additional_info/mana_cost_widget.cpp
src/interface/widgets/cards/additional_info/mana_symbol_widget.cpp
src/interface/widgets/cards/art_crop_attribution.cpp
+ src/interface/widgets/cards/card_art_utils.cpp
src/interface/widgets/cards/card_group_display_widgets/card_group_display_widget.cpp
src/interface/widgets/cards/card_group_display_widgets/flat_card_group_display_widget.cpp
src/interface/widgets/cards/card_group_display_widgets/overlapped_card_group_display_widget.cpp
@@ -381,6 +389,7 @@ set(cockatrice_SOURCES
src/interface/widgets/tabs/tab_card_art_rules.cpp
src/interface/widgets/tabs/tab_deck_editor.cpp
src/interface/widgets/tabs/tab_deck_storage.cpp
+ src/interface/widgets/tabs/tab_developer.cpp
src/interface/widgets/tabs/tab_game.cpp
src/interface/widgets/tabs/tab_home.cpp
src/interface/widgets/tabs/tab_logs.cpp
@@ -401,6 +410,7 @@ set(cockatrice_SOURCES
src/interface/widgets/tabs/api/commander_spellbook/commander_bracket_widget.cpp
src/interface/widgets/tabs/api/commander_spellbook/handle_commander_brackets.cpp
src/interface/widgets/onboarding/banner_shader_config.h
+ src/interface/widgets/onboarding/brand_colors.h
src/interface/widgets/onboarding/first_run_wizard.cpp
src/interface/widgets/onboarding/first_run_wizard.h
src/interface/widgets/onboarding/first_run_wizard_page.cpp
@@ -441,6 +451,8 @@ set(cockatrice_SOURCES
src/interface/intents/intent_login.h
src/interface/intents/intent_open_server_room_by_name.cpp
src/interface/intents/intent_open_server_room_by_name.h
+ src/interface/intents/intent_open_shared_deck.cpp
+ src/interface/intents/intent_open_shared_deck.h
src/interface/intents/url_parser.cpp
src/interface/intents/url_parser.h
src/interface/widgets/server/user/user_info_popup.cpp
@@ -528,6 +540,7 @@ qt6_add_shaders(
"src/interface/widgets/onboarding/shaders"
FILES
src/interface/widgets/onboarding/shaders/brand_banner.frag
+ src/interface/widgets/onboarding/shaders/brand_plate.frag
)
qt6_add_resources(
diff --git a/cockatrice/cockatrice.qrc b/cockatrice/cockatrice.qrc
index e21bdb0be..14cf15b2f 100644
--- a/cockatrice/cockatrice.qrc
+++ b/cockatrice/cockatrice.qrc
@@ -63,6 +63,8 @@
resources/icons/mana/W.svg
resources/backgrounds/home.png
+ resources/backgrounds/home-dark.png
+ resources/backgrounds/home-light.png
resources/backgrounds/card_triplet.svg
resources/backgrounds/placeholder_printing_selector.svg
@@ -363,6 +365,8 @@
resources/usericons/pawn_single.svg
resources/usericons/pawn_double.svg
+ resources/usericons/pawn_dev_single.svg
+ resources/usericons/pawn_dev_double.svg
resources/usericons/pawn_donator_single.svg
resources/usericons/pawn_donator_double.svg
resources/usericons/pawn_judge_single.svg
diff --git a/cockatrice/resources/backgrounds/home-dark.png b/cockatrice/resources/backgrounds/home-dark.png
new file mode 100644
index 000000000..68f48e2c2
Binary files /dev/null and b/cockatrice/resources/backgrounds/home-dark.png differ
diff --git a/cockatrice/resources/backgrounds/home-light.png b/cockatrice/resources/backgrounds/home-light.png
new file mode 100644
index 000000000..eaaaba932
Binary files /dev/null and b/cockatrice/resources/backgrounds/home-light.png differ
diff --git a/cockatrice/resources/backgrounds/home.png b/cockatrice/resources/backgrounds/home.png
index 68f48e2c2..eaaaba932 100644
Binary files a/cockatrice/resources/backgrounds/home.png and b/cockatrice/resources/backgrounds/home.png differ
diff --git a/cockatrice/resources/usericons/pawn_dev_double.svg b/cockatrice/resources/usericons/pawn_dev_double.svg
new file mode 100644
index 000000000..57ed5c2da
--- /dev/null
+++ b/cockatrice/resources/usericons/pawn_dev_double.svg
@@ -0,0 +1,343 @@
+
+
+
+
diff --git a/cockatrice/resources/usericons/pawn_dev_single.svg b/cockatrice/resources/usericons/pawn_dev_single.svg
new file mode 100644
index 000000000..f7c4e7018
--- /dev/null
+++ b/cockatrice/resources/usericons/pawn_dev_single.svg
@@ -0,0 +1,211 @@
+
+
+
+
diff --git a/cockatrice/src/client/network/connection_controller/remote_connection_controller.cpp b/cockatrice/src/client/network/connection_controller/remote_connection_controller.cpp
index 890a621c8..c1598bd25 100644
--- a/cockatrice/src/client/network/connection_controller/remote_connection_controller.cpp
+++ b/cockatrice/src/client/network/connection_controller/remote_connection_controller.cpp
@@ -1,5 +1,6 @@
#include "remote_connection_controller.h"
+#include "../../../interface/pixel_map_generator.h"
#include "../../settings/cache_settings.h"
#include "../interface/widgets/dialogs/dlg_connect.h"
#include "../interface/widgets/dialogs/dlg_forgot_password_challenge.h"
@@ -180,7 +181,7 @@ void ConnectionController::onServerShutdownEvent(const Event_ServerShutdown &eve
"games will be lost.\nReason for shutdown: %1",
"", event.minutes())
.arg(QString::fromStdString(event.reason())));
- serverShutdownMessageBox.setIconPixmap(QPixmap("theme:cockatrice").scaled(64, 64));
+ serverShutdownMessageBox.setIconPixmap(themePixmap(QStringLiteral("cockatrice")).scaled(64, 64));
serverShutdownMessageBox.setText(tr("Scheduled server shutdown"));
serverShutdownMessageBox.setWindowModality(Qt::ApplicationModal);
serverShutdownMessageBox.setVisible(true);
diff --git a/cockatrice/src/client/sound_engine.cpp b/cockatrice/src/client/sound_engine.cpp
index 18de2264d..96cafa3d3 100644
--- a/cockatrice/src/client/sound_engine.cpp
+++ b/cockatrice/src/client/sound_engine.cpp
@@ -94,7 +94,7 @@ QStringMap &SoundEngine::getAvailableThemes()
QDir dir;
availableThemes.clear();
- // load themes from user profile dir
+ // Load themes from user profile dir
dir.setPath(SettingsCache::instance().getDataPath() + "/sounds");
@@ -104,7 +104,7 @@ QStringMap &SoundEngine::getAvailableThemes()
}
}
- // load themes from cockatrice system dir
+ // Load themes from Cockatrice system dir
dir.setPath(qApp->applicationDirPath() +
#ifdef Q_OS_MAC
"/../Resources/sounds"
diff --git a/cockatrice/src/filters/filter_builder.cpp b/cockatrice/src/filters/filter_builder.cpp
index 785f753e7..f109fbcd3 100644
--- a/cockatrice/src/filters/filter_builder.cpp
+++ b/cockatrice/src/filters/filter_builder.cpp
@@ -1,5 +1,6 @@
#include "filter_builder.h"
+#include "../interface/pixel_map_generator.h"
#include "../interface/widgets/utility/custom_line_edit.h"
#include
@@ -21,7 +22,7 @@ FilterBuilder::FilterBuilder(QWidget *parent) : QWidget(parent)
typeCombo->addItem(CardFilter::typeName(static_cast(i)), QVariant(i));
}
- QPushButton *ok = new QPushButton(QPixmap("theme:icons/increment"), QString());
+ QPushButton *ok = new QPushButton(themePixmap(QStringLiteral("icons/increment")), QString());
ok->setObjectName("ok");
ok->setMaximumSize(20, 20);
diff --git a/cockatrice/src/game/board/counter_state.cpp b/cockatrice/src/game/board/counter_state.cpp
index 6da18b662..0970e4272 100644
--- a/cockatrice/src/game/board/counter_state.cpp
+++ b/cockatrice/src/game/board/counter_state.cpp
@@ -13,12 +13,12 @@ CounterState *CounterState::fromProto(const ServerInfo_Counter &counter, QObject
convertColorToQColor(counter.counter_color()), counter.radius(), counter.count(), parent);
}
-void CounterState::setValue(int newValue)
+void CounterState::setValue(int newValue, bool skipDamageAnimation)
{
if (newValue == value) {
return;
}
int old = value;
value = newValue;
- emit valueChanged(old, newValue);
+ emit valueChanged(old, newValue, skipDamageAnimation);
}
\ No newline at end of file
diff --git a/cockatrice/src/game/board/counter_state.h b/cockatrice/src/game/board/counter_state.h
index 0f2f16b55..4c7b34473 100644
--- a/cockatrice/src/game/board/counter_state.h
+++ b/cockatrice/src/game/board/counter_state.h
@@ -35,10 +35,23 @@ public:
return value;
}
- void setValue(int newValue);
+ /**
+ * @brief Set the counter value.
+ * @param newValue The new value.
+ * @param skipDamageAnimation When true, valueChanged is emitted with skipDamageAnimation=true, letting views
+ * suppress damage-related feedback (e.g. battlefield shimmer, life counter flash) for values set during replay
+ * rewinds.
+ */
+ void setValue(int newValue, bool skipDamageAnimation = false);
signals:
- void valueChanged(int oldValue, int newValue);
+ /**
+ * @brief Emitted whenever the value changes.
+ * @param oldValue The previous value.
+ * @param newValue The new value.
+ * @param skipDamageAnimation True when the change should not trigger damage/life-change feedback in views.
+ */
+ void valueChanged(int oldValue, int newValue, bool skipDamageAnimation);
private:
int id;
diff --git a/cockatrice/src/game/game_event_handler.cpp b/cockatrice/src/game/game_event_handler.cpp
index bc68d4d7c..f146cdbb4 100644
--- a/cockatrice/src/game/game_event_handler.cpp
+++ b/cockatrice/src/game/game_event_handler.cpp
@@ -430,12 +430,13 @@ void GameEventHandler::eventJoin(const Event_Join &event, int /*eventPlayerId*/,
QString playerName = QString::fromStdString(playerInfo.user_info().name());
emit addPlayerToAutoCompleteList(playerName);
- if (game->getPlayerManager()->getPlayers().contains(playerId)) {
+ PlayerManager *playerManager = game->getPlayerManager();
+ if (playerManager->getPlayers().contains(playerId) || playerManager->getSpectators().contains(playerId)) {
return;
}
if (playerInfo.spectator()) {
- game->getPlayerManager()->addSpectator(playerId, playerInfo);
+ playerManager->addSpectator(playerId, playerInfo);
emit logJoinSpectator(playerName);
emit spectatorJoined(playerInfo);
} else {
diff --git a/cockatrice/src/game/player/event_processing_options.h b/cockatrice/src/game/player/event_processing_options.h
index 4c7663789..06238d77e 100644
--- a/cockatrice/src/game/player/event_processing_options.h
+++ b/cockatrice/src/game/player/event_processing_options.h
@@ -13,7 +13,8 @@
enum EventProcessingOption
{
SKIP_REVEAL_WINDOW = 0x0001,
- SKIP_TAP_ANIMATION = 0x0002
+ SKIP_TAP_ANIMATION = 0x0002,
+ SKIP_DAMAGE_ANIMATION = 0x0004
};
// Wrap it in a QFlags typedef
diff --git a/cockatrice/src/game/player/player_event_handler.cpp b/cockatrice/src/game/player/player_event_handler.cpp
index bc48298f7..277b8b1d4 100644
--- a/cockatrice/src/game/player/player_event_handler.cpp
+++ b/cockatrice/src/game/player/player_event_handler.cpp
@@ -262,14 +262,15 @@ void PlayerEventHandler::eventCreateCounter(const Event_CreateCounter &event)
player->addCounter(event.counter_info());
}
-void PlayerEventHandler::eventSetCounter(const Event_SetCounter &event)
+void PlayerEventHandler::eventSetCounter(const Event_SetCounter &event, EventProcessingOptions options)
{
CounterState *ctr = player->getCounters().value(event.counter_id(), nullptr);
if (!ctr) {
return;
}
int oldValue = ctr->getValue();
- ctr->setValue(event.value());
+ const bool skipDamageAnimation = options.testFlag(SKIP_DAMAGE_ANIMATION);
+ ctr->setValue(event.value(), skipDamageAnimation);
emit logSetCounter(player, ctr->getName(), event.value(), oldValue);
}
@@ -625,7 +626,7 @@ void PlayerEventHandler::processGameEvent(GameEvent::GameEventType type,
eventCreateCounter(event.GetExtension(Event_CreateCounter::ext));
break;
case GameEvent::SET_COUNTER:
- eventSetCounter(event.GetExtension(Event_SetCounter::ext));
+ eventSetCounter(event.GetExtension(Event_SetCounter::ext), options);
break;
case GameEvent::DEL_COUNTER:
eventDelCounter(event.GetExtension(Event_DelCounter::ext));
diff --git a/cockatrice/src/game/player/player_event_handler.h b/cockatrice/src/game/player/player_event_handler.h
index 48ad85e88..300cacd08 100644
--- a/cockatrice/src/game/player/player_event_handler.h
+++ b/cockatrice/src/game/player/player_event_handler.h
@@ -153,7 +153,7 @@ public:
void eventCreateCounter(const Event_CreateCounter &event);
/// Set a player-level counter value.
- void eventSetCounter(const Event_SetCounter &event);
+ void eventSetCounter(const Event_SetCounter &event, EventProcessingOptions options);
/// Delete a player-level counter.
void eventDelCounter(const Event_DelCounter &event);
diff --git a/cockatrice/src/game/player/player_logic.cpp b/cockatrice/src/game/player/player_logic.cpp
index 45ba09aac..143df5c57 100644
--- a/cockatrice/src/game/player/player_logic.cpp
+++ b/cockatrice/src/game/player/player_logic.cpp
@@ -175,7 +175,15 @@ void PlayerLogic::processPlayerInfo(const ServerInfo_Player &info)
const ServerInfo_Card &cardInfo = zoneInfo.card_list(j);
auto *card = new CardItem(this);
card->processCardInfo(cardInfo);
- zone->addCard(card, false, cardInfo.x(), cardInfo.y());
+ // Zones without coordinates (hand, piles, stack) preserve the order
+ // they arrive in on the server in the positions of their cards list.
+ // The x coordinate of such cards is always 0, so inserting at it
+ // would reverse the list on reconnect. Append instead.
+ if (zoneInfo.with_coords()) {
+ zone->addCard(card, false, cardInfo.x(), cardInfo.y());
+ } else {
+ zone->addCard(card, false, -1);
+ }
}
}
if (zoneInfo.has_always_reveal_top_card()) {
diff --git a/cockatrice/src/game/player/player_manager.cpp b/cockatrice/src/game/player/player_manager.cpp
index 6772d3ff1..8486efbeb 100644
--- a/cockatrice/src/game/player/player_manager.cpp
+++ b/cockatrice/src/game/player/player_manager.cpp
@@ -75,6 +75,14 @@ PlayerLogic *PlayerManager::getPlayer(int playerId) const
return player;
}
+void PlayerManager::clearSpectators()
+{
+ const QList spectatorIds = spectators.keys();
+ for (int spectatorId : spectatorIds) {
+ removeSpectator(spectatorId);
+ }
+}
+
void PlayerManager::onPlayerConceded(int playerId, bool conceded)
{
// Everything else cares about this
diff --git a/cockatrice/src/game/player/player_manager.h b/cockatrice/src/game/player/player_manager.h
index 2f8b87af8..504e65396 100644
--- a/cockatrice/src/game/player/player_manager.h
+++ b/cockatrice/src/game/player/player_manager.h
@@ -100,6 +100,9 @@ public:
emit spectatorRemoved(spectatorId, spectatorInfo);
}
+ /** @brief Remove all spectators, emitting the removal signal for each. */
+ void clearSpectators();
+
[[nodiscard]] AbstractGame *getGame() const
{
return game;
diff --git a/cockatrice/src/game_graphics/board/abstract_card_item.cpp b/cockatrice/src/game_graphics/board/abstract_card_item.cpp
index 1410d0c80..3969b7d03 100644
--- a/cockatrice/src/game_graphics/board/abstract_card_item.cpp
+++ b/cockatrice/src/game_graphics/board/abstract_card_item.cpp
@@ -1,6 +1,7 @@
#include "abstract_card_item.h"
#include "../../client/settings/cache_settings.h"
+#include "../../interface/card_localization.h"
#include "../../interface/card_picture_loader/card_picture_loader.h"
#include "../game_scene.h"
#include "../z_values.h"
@@ -26,6 +27,8 @@ AbstractCardItem::AbstractCardItem(QGraphicsItem *parent, const CardRef &cardRef
connect(&SettingsCache::instance().cardsDisplay(), &CardsDisplaySettings::displayCardNamesChanged, this,
[this] { update(); });
+ connect(&SettingsCache::instance().cardsDisplay(), &CardsDisplaySettings::cardLangChanged, this,
+ [this] { update(); });
refreshCardInfo();
connect(&SettingsCache::instance().cardsDisplay(), &CardsDisplaySettings::roundCardCornersChanged, this,
@@ -171,7 +174,7 @@ void AbstractCardItem::paintPicture(QPainter *painter, const QSizeF &translatedS
if (SettingsCache::instance().debug().getShowCardId()) {
prefix = "#" + QString::number(id) + " ";
}
- nameStr = prefix + cardRef.name;
+ nameStr = prefix + CardLocalization::displayName(getCardInfo());
}
painter->drawText(QRectF(3 * scaleFactor, 3 * scaleFactor, translatedSize.width() - 6 * scaleFactor,
translatedSize.height() - 6 * scaleFactor),
diff --git a/cockatrice/src/game_graphics/board/abstract_counter.cpp b/cockatrice/src/game_graphics/board/abstract_counter.cpp
index e63117e13..4ba04804f 100644
--- a/cockatrice/src/game_graphics/board/abstract_counter.cpp
+++ b/cockatrice/src/game_graphics/board/abstract_counter.cpp
@@ -29,9 +29,9 @@ AbstractCounter::AbstractCounter(CounterState *state,
{
setAcceptHoverEvents(true);
- connect(state, &CounterState::valueChanged, this, [this](int oldValue, int newValue) {
+ connect(state, &CounterState::valueChanged, this, [this](int oldValue, int newValue, bool skipDamageAnimation) {
value = newValue;
- onValueChanged(oldValue, newValue);
+ onValueChanged(oldValue, newValue, skipDamageAnimation);
update();
});
@@ -230,7 +230,7 @@ void AbstractCounterDialog::changeValue(int diff)
setTextValue(QString::number(curValue));
}
-void AbstractCounter::onValueChanged(int /*oldValue*/, int /*newValue*/)
+void AbstractCounter::onValueChanged(int /*oldValue*/, int /*newValue*/, bool /*skipDamageAnimation*/)
{
// Default: no feedback. Subclasses such as PlayerCounter override this to
// flash the counter on meaningful changes (life gain/loss).
diff --git a/cockatrice/src/game_graphics/board/abstract_counter.h b/cockatrice/src/game_graphics/board/abstract_counter.h
index 9ddcc6d58..67b5b4074 100644
--- a/cockatrice/src/game_graphics/board/abstract_counter.h
+++ b/cockatrice/src/game_graphics/board/abstract_counter.h
@@ -39,8 +39,9 @@ protected:
* @brief Hook for subclasses that need per-value-change feedback (e.g. life-total flash).
*
* Called whenever the counter's value changes, before the item repaints.
+ * @param skipDamageAnimation True when damage-related feedback should be suppressed (replay rewinds).
*/
- virtual void onValueChanged(int oldValue, int newValue);
+ virtual void onValueChanged(int oldValue, int newValue, bool skipDamageAnimation);
void mousePressEvent(QGraphicsSceneMouseEvent *event) override;
void hoverEnterEvent(QGraphicsSceneHoverEvent *event) override;
diff --git a/cockatrice/src/game_graphics/board/card_item.cpp b/cockatrice/src/game_graphics/board/card_item.cpp
index c40c8c214..c2dc455cc 100644
--- a/cockatrice/src/game_graphics/board/card_item.cpp
+++ b/cockatrice/src/game_graphics/board/card_item.cpp
@@ -316,7 +316,7 @@ void CardItem::drawAttachArrow()
for (const auto &item : scene()->selectedItems()) {
CardItem *card = qgraphicsitem_cast(item);
- if (card == nullptr) {
+ if (card == nullptr || card == this) {
continue;
}
if (card->getZone() != state->getZone()) {
diff --git a/cockatrice/src/game_graphics/game_scene.cpp b/cockatrice/src/game_graphics/game_scene.cpp
index 457f1b3f7..17af7618b 100644
--- a/cockatrice/src/game_graphics/game_scene.cpp
+++ b/cockatrice/src/game_graphics/game_scene.cpp
@@ -221,7 +221,12 @@ void GameScene::removePlayer(PlayerLogic *player)
clearArrowsForPlayer(player->getPlayerInfo()->getId());
- for (ZoneViewWidget *zone : zoneViews) {
+ // Closing a view removes it from zoneViews synchronously, so iterate over a
+ // copy: otherwise a player with several open views (e.g. library and hand)
+ // only has the first one closed here and the remaining views are left
+ // pointing at a player that is about to be deleted.
+ const QList zoneViewCopy = zoneViews;
+ for (ZoneViewWidget *zone : zoneViewCopy) {
if (zone->getPlayer() == player) {
zone->close();
}
@@ -664,7 +669,10 @@ CardItem *GameScene::findTopmostCardInZone(const QList &items,
*/
void GameScene::toggleZoneView(PlayerLogic *player, const QString &zoneName, int numberCards, bool isReversed)
{
- for (auto &view : zoneViews) {
+ // Closing a view removes it from zoneViews synchronously, so iterate over a
+ // copy to make sure every already-open matching view is closed.
+ const QList zoneViewCopy = zoneViews;
+ for (auto *view : zoneViewCopy) {
ZoneViewZone *temp = view->getZone();
if (temp->getLogic()->getName() == zoneName && temp->getLogic()->getPlayer() == player &&
qobject_cast(temp->getLogic())->getNumberCards() == numberCards) {
diff --git a/cockatrice/src/game_graphics/hand_counter.cpp b/cockatrice/src/game_graphics/hand_counter.cpp
index 35989ff38..8dcbcfdaa 100644
--- a/cockatrice/src/game_graphics/hand_counter.cpp
+++ b/cockatrice/src/game_graphics/hand_counter.cpp
@@ -1,5 +1,6 @@
#include "hand_counter.h"
+#include "../interface/pixel_map_generator.h"
#include "zones/card_zone.h"
#include
@@ -32,7 +33,8 @@ void HandCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*op
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);
+ cachedPixmap =
+ themePixmap(QStringLiteral("hand")).scaled(translatedSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
QPixmapCache::insert("handCounter" + QString::number(translatedSize.width()), cachedPixmap);
}
resetPainterTransform(painter);
diff --git a/cockatrice/src/game_graphics/player/player_graphics_item.cpp b/cockatrice/src/game_graphics/player/player_graphics_item.cpp
index 8bf2703e1..122ab83be 100644
--- a/cockatrice/src/game_graphics/player/player_graphics_item.cpp
+++ b/cockatrice/src/game_graphics/player/player_graphics_item.cpp
@@ -3,6 +3,7 @@
#include "../../game/player/player_actions.h"
#include "../../interface/card_picture_loader/card_picture_loader.h"
#include "../../interface/widgets/cards/art_crop_attribution.h"
+#include "../../interface/widgets/cards/card_art_utils.h"
#include "../../interface/widgets/playmat/playmat_utils.h"
#include "../../interface/widgets/tabs/tab_game.h"
#include "../board/abstract_card_item.h"
@@ -251,8 +252,8 @@ void PlayerGraphicsItem::onCounterAdded(CounterState *state)
AbstractCounter *widget;
if (state->getName() == "life") {
widget = playerTarget->addCounter(state);
- connect(state, &CounterState::valueChanged, this, [this](int oldValue, int newValue) {
- if (newValue < oldValue) {
+ connect(state, &CounterState::valueChanged, this, [this](int oldValue, int newValue, bool skipDamageAnimation) {
+ if (newValue < oldValue && !skipDamageAnimation) {
tableZoneGraphicsItem->triggerDamageShimmer();
}
});
@@ -442,7 +443,7 @@ void PlayerGraphicsItem::updatePlaymat()
hasPlaymat = true;
emit playmatChanged(true);
}
- playmatPixmap = fullRes;
+ playmatPixmap = CardArtUtils::rotateSidewaysLayoutArt(fullRes, card);
update();
}
diff --git a/cockatrice/src/game_graphics/player/player_list_widget.cpp b/cockatrice/src/game_graphics/player/player_list_widget.cpp
index 4268e1019..a7ec2e4a9 100644
--- a/cockatrice/src/game_graphics/player/player_list_widget.cpp
+++ b/cockatrice/src/game_graphics/player/player_list_widget.cpp
@@ -53,13 +53,13 @@ PlayerListWidget::PlayerListWidget(TabSupervisor *_tabSupervisor,
QWidget *parent)
: QTreeWidget(parent), tabSupervisor(_tabSupervisor), client(_client), game(_game), gameStarted(false)
{
- readyIcon = QPixmap("theme:icons/ready_start");
- notReadyIcon = QPixmap("theme:icons/not_ready_start");
- concededIcon = QPixmap("theme:icons/conceded");
+ readyIcon = themePixmap(QStringLiteral("icons/ready_start"));
+ notReadyIcon = themePixmap(QStringLiteral("icons/not_ready_start"));
+ concededIcon = themePixmap(QStringLiteral("icons/conceded"));
playerIcon = loadColorAdjustedPixmap("theme:icons/player");
judgeIcon = loadColorAdjustedPixmap("theme:icons/scales");
spectatorIcon = loadColorAdjustedPixmap("theme:icons/spectator");
- lockIcon = QPixmap("theme:icons/lock");
+ lockIcon = themePixmap(QStringLiteral("icons/lock"));
if (tabSupervisor) {
itemDelegate = new PlayerListItemDelegate(this);
@@ -92,6 +92,11 @@ void PlayerListWidget::retranslateUi()
void PlayerListWidget::addPlayer(const ServerInfo_PlayerProperties &player)
{
+ if (players.contains(player.player_id())) {
+ updatePlayerProperties(player);
+ return;
+ }
+
QTreeWidgetItem *newPlayer = new PlayerListTWI;
players.insert(player.player_id(), newPlayer);
updatePlayerProperties(player);
@@ -176,6 +181,17 @@ void PlayerListWidget::removePlayer(int playerId)
delete takeTopLevelItem(indexOfTopLevelItem(player));
}
+void PlayerListWidget::clearSpectators()
+{
+ const QList playerIds = players.keys();
+ for (int playerId : playerIds) {
+ QTreeWidgetItem *player = players.value(playerId, 0);
+ if (player && !player->data(1, Qt::UserRole).toBool()) {
+ removePlayer(playerId);
+ }
+ }
+}
+
void PlayerListWidget::setActivePlayer(int playerId)
{
QMapIterator i(players);
diff --git a/cockatrice/src/game_graphics/player/player_list_widget.h b/cockatrice/src/game_graphics/player/player_list_widget.h
index a53cfa989..f2f0be5fd 100644
--- a/cockatrice/src/game_graphics/player/player_list_widget.h
+++ b/cockatrice/src/game_graphics/player/player_list_widget.h
@@ -66,6 +66,7 @@ public slots:
void addPlayer(const ServerInfo_PlayerProperties &player);
void removePlayer(int playerId);
void updatePlayerProperties(const ServerInfo_PlayerProperties &prop, int playerId = -1);
+ void clearSpectators();
};
#endif
diff --git a/cockatrice/src/game_graphics/player/player_target.cpp b/cockatrice/src/game_graphics/player/player_target.cpp
index 910ee9c17..d6c28370d 100644
--- a/cockatrice/src/game_graphics/player/player_target.cpp
+++ b/cockatrice/src/game_graphics/player/player_target.cpp
@@ -69,7 +69,7 @@ void PlayerCounter::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*
}
}
-void PlayerCounter::onValueChanged(int oldValue, int newValue)
+void PlayerCounter::onValueChanged(int oldValue, int newValue, bool skipDamageAnimation)
{
flashDelta = newValue - oldValue;
if (flashDelta == 0) {
@@ -81,6 +81,11 @@ void PlayerCounter::onValueChanged(int oldValue, int newValue)
return;
}
+ if (skipDamageAnimation) {
+ flashAlpha = 0.0;
+ return;
+ }
+
flashAlpha = 1.0;
flashClock.start();
if (scene()) {
@@ -132,8 +137,18 @@ void PlayerTarget::paint(QPainter *painter, const QStyleOptionGraphicsItem * /*o
QRectF translatedRect = painter->combinedTransform().mapRect(avatarBoundingRect);
QSize translatedSize = translatedRect.size().toSize();
QPixmap cachedPixmap;
+ // The key must cover everything the generated pawn depends on: the rendered
+ // size, the user level, and the pixmap being drawn. fullPixmap.cacheKey() is
+ // 0 for every null pixmap, so the default-pawn branch additionally needs the
+ // pawn's privlevel (lowercased, matching UserLevelPixmapGenerator) and colors
+ // in the key — otherwise two players without a custom avatar (and the same
+ // user level) would share one cached pawn.
const QString cacheKey = "avatar" + QString::number(translatedSize.width()) + "_" +
- QString::number(info->user_level()) + "_" + QString::number(fullPixmap.cacheKey());
+ QString::number(translatedSize.height()) + "_" + QString::number(info->user_level()) +
+ "_" + QString::number(fullPixmap.cacheKey()) + "_" +
+ QString::fromStdString(info->privlevel()).toLower() + "_" +
+ QString::fromStdString(info->pawn_colors().left_side()) + "_" +
+ QString::fromStdString(info->pawn_colors().right_side());
if (!QPixmapCache::find(cacheKey, &cachedPixmap)) {
cachedPixmap = QPixmap(translatedSize.width(), translatedSize.height());
diff --git a/cockatrice/src/game_graphics/player/player_target.h b/cockatrice/src/game_graphics/player/player_target.h
index af0e9c8b7..1d06c6274 100644
--- a/cockatrice/src/game_graphics/player/player_target.h
+++ b/cockatrice/src/game_graphics/player/player_target.h
@@ -21,7 +21,7 @@ class PlayerCounter : public AbstractCounter, public IAnimatedItem
{
Q_OBJECT
protected:
- void onValueChanged(int oldValue, int newValue) override;
+ void onValueChanged(int oldValue, int newValue, bool skipDamageAnimation) override;
private:
static constexpr qreal flashDurationMs = 450.0;
diff --git a/cockatrice/src/game_graphics/zones/view_zone_widget.cpp b/cockatrice/src/game_graphics/zones/view_zone_widget.cpp
index 17118e80d..c13b79fea 100644
--- a/cockatrice/src/game_graphics/zones/view_zone_widget.cpp
+++ b/cockatrice/src/game_graphics/zones/view_zone_widget.cpp
@@ -62,7 +62,7 @@ ZoneViewWidget::ZoneViewWidget(PlayerLogic *_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);
+ auto help = searchEdit.addAction(themePixmap(QStringLiteral("icons/info")), QLineEdit::TrailingPosition);
connect(help, &QAction::triggered, this, [this] { createSearchSyntaxHelpWindow(&searchEdit); });
@@ -549,7 +549,7 @@ void ZoneViewWidget::initStyleOption(QStyleOption *option) const
{
QStyleOptionTitleBar *titleBar = qstyleoption_cast(option);
if (titleBar) {
- titleBar->icon = QPixmap("theme:cockatrice");
+ titleBar->icon = themePixmap(QStringLiteral("cockatrice"));
}
}
diff --git a/cockatrice/src/interface/card_localization.h b/cockatrice/src/interface/card_localization.h
new file mode 100644
index 000000000..0bfe4a764
--- /dev/null
+++ b/cockatrice/src/interface/card_localization.h
@@ -0,0 +1,59 @@
+#ifndef COCKATRICE_CARD_LOCALIZATION_H
+#define COCKATRICE_CARD_LOCALIZATION_H
+
+#include "../client/settings/cache_settings.h"
+
+#include
+#include
+#include
+
+namespace CardLocalization
+{
+/**
+ * @brief The language code selected for localized card text and images.
+ */
+inline QString displayLang()
+{
+ return SettingsCache::instance().cardsDisplay().getCardLang();
+}
+
+/**
+ * @brief Card name in the configured display language, falling back to English.
+ * @param card The card to display.
+ * @return The localized name, or an empty string for a null card.
+ */
+inline QString displayName(const CardInfoPtr &card)
+{
+ return card.isNull() ? QString() : card->getLocalizedName(displayLang());
+}
+
+/**
+ * @brief Card rules text in the configured display language, falling back to English.
+ * @param card The card to display.
+ * @return The localized text, or an empty string for a null card.
+ */
+inline QString displayText(const CardInfoPtr &card)
+{
+ return card.isNull() ? QString() : card->getLocalizedText(displayLang());
+}
+
+/**
+ * @brief Card name in the configured display language, falling back to English.
+ * @param card The card to display.
+ */
+inline QString displayName(const CardInfo &card)
+{
+ return card.getLocalizedName(displayLang());
+}
+
+/**
+ * @brief Card rules text in the configured display language, falling back to English.
+ * @param card The card to display.
+ */
+inline QString displayText(const CardInfo &card)
+{
+ return card.getLocalizedText(displayLang());
+}
+} // namespace CardLocalization
+
+#endif // COCKATRICE_CARD_LOCALIZATION_H
\ No newline at end of file
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 2f46e7941..b8a54761a 100644
--- a/cockatrice/src/interface/card_picture_loader/card_picture_loader.cpp
+++ b/cockatrice/src/interface/card_picture_loader/card_picture_loader.cpp
@@ -1,13 +1,14 @@
#include "card_picture_loader.h"
#include "../../client/settings/cache_settings.h"
+#include "../pixel_map_generator.h"
#include "card_picture_loader_cache_method.h"
#include "card_picture_loader_local_schemes.h"
#include
#include
#include
-#include
+#include
#include
#include
#include
@@ -19,6 +20,7 @@
#include
#include
#include
+#include
#include
#include
#include
@@ -36,8 +38,10 @@ CardPictureLoader::CardPictureLoader() : QObject(nullptr)
&CardPictureLoader::picsPathChanged);
connect(&SettingsCache::instance().downloads(), &DownloadSettings::picDownloadChanged, this,
&CardPictureLoader::picDownloadChanged);
+ connect(&SettingsCache::instance().cardsDisplay(), &CardsDisplaySettings::cardLangChanged, this,
+ &CardPictureLoader::cardLangChanged);
- qRegisterMetaType();
+ qRegisterMetaType("ExactCard");
connect(worker, &CardPictureLoaderWorker::imageLoaded, this, &CardPictureLoader::imageLoaded);
statusBar = new CardPictureLoaderStatusBar(nullptr);
@@ -62,7 +66,7 @@ void CardPictureLoader::getCardBackPixmap(QPixmap &pixmap, QSize size)
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");
+ QPixmap tmpPixmap = themePixmap(QStringLiteral("cardback"));
if (tmpPixmap.isNull()) {
qCWarning(CardPictureLoaderLog) << "Failed to load 'theme:cardback'! Using fallback pixmap.";
@@ -83,7 +87,7 @@ void CardPictureLoader::getCardBackLoadingInProgressPixmap(QPixmap &pixmap, QSiz
"_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;
- QPixmap tmpPixmap("theme:cardback");
+ QPixmap tmpPixmap = themePixmap(QStringLiteral("cardback"));
if (tmpPixmap.isNull()) {
qCWarning(CardPictureLoaderLog) << "Failed to load 'theme:cardback' for in-progress state! Using fallback.";
@@ -105,7 +109,7 @@ void CardPictureLoader::getCardBackLoadingFailedPixmap(QPixmap &pixmap, QSize si
"_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;
- QPixmap tmpPixmap("theme:cardback");
+ QPixmap tmpPixmap = themePixmap(QStringLiteral("cardback"));
if (tmpPixmap.isNull()) {
qCWarning(CardPictureLoaderLog) << "Failed to load 'theme:cardback' for failed state! Using fallback.";
@@ -138,7 +142,8 @@ void CardPictureLoader::getPixmap(QPixmap &pixmap, const ExactCard &card, QSize
QPixmap bigPixmap;
if (QPixmapCache::find(key, &bigPixmap)) {
if (bigPixmap.isNull()) {
- getCardBackLoadingFailedPixmap(pixmap, size);
+ // Leave the pixmap null so callers fall back to a solid color
+ // instead of showing the card back.
QDateTime failedAtTime = getInstance().failedAt.value(key);
if (!failedAtTime.isValid() ||
failedAtTime.addSecs(RETRY_FAILED_CARDS_SECS) < QDateTime::currentDateTime()) {
@@ -204,7 +209,49 @@ void CardPictureLoader::imageLoaded(const ExactCard &card, const QImage &image)
card.emitPixmapUpdated();
}
-void CardPictureLoader::saveCardImageToLocalStorage(const ExactCard &card, const QPixmap &pixmap)
+void CardPictureLoader::deleteAllLocalOverrides(const ExactCard &card)
+{
+ const QString picsRoot = SettingsCache::instance().paths().getPicsPath();
+ if (picsRoot.isEmpty() || !card) {
+ return;
+ }
+
+ QDir baseDir(picsRoot);
+ if (!baseDir.cd("downloadedPics")) {
+ return;
+ }
+
+ const QString name = card.getInfo().getCorrectedName();
+
+ QString set, collector, uuid;
+ auto printing = card.getPrinting();
+ if (printing.getSet()) {
+ set = printing.getSet()->getCorrectedShortName();
+ collector = printing.getProperty("num");
+ uuid = printing.getUuid();
+ }
+
+ for (const auto &scheme : CardPictureLoaderLocalSchemes::exportSchemes()) {
+ QString rel = CardPictureLoaderLocalSchemes::expandPattern(scheme.pattern, name, set, collector, uuid);
+
+ if (rel.isEmpty()) {
+ continue;
+ }
+
+ rel += ".png";
+ rel = QDir::cleanPath(rel);
+
+ QString fullPath = baseDir.filePath(rel);
+
+ if (QFile::exists(fullPath)) {
+ QFile::remove(fullPath);
+ }
+ }
+}
+
+void CardPictureLoader::saveCardImageToLocalStorage(const ExactCard &card,
+ const QPixmap &pixmap,
+ const bool allowOverwrite)
{
if (pixmap.isNull() || !card) {
return;
@@ -264,8 +311,9 @@ void CardPictureLoader::saveCardImageToLocalStorage(const ExactCard &card, const
QFileInfo outInfo(baseDir.filePath(relativePath));
- // Do not overwrite existing files
- if (outInfo.exists()) {
+ // Automatic cache writes (FILESYSTEM_CACHE) must never clobber an explicit user override.
+ // Only the explicit override paths pass allowOverwrite == true.
+ if (!allowOverwrite && outInfo.exists()) {
return;
}
@@ -286,6 +334,122 @@ void CardPictureLoader::saveCardImageToLocalStorage(const ExactCard &card, const
}
}
+void CardPictureLoader::installPrintingOverrideOnLoad(const ExactCard &originalCard, const ExactCard &overrideCard)
+{
+ // Overriding a card with itself is the reset case, not a real override: every code path below
+ // would re-enter itself through emitPixmapUpdated(). Reject it outright.
+ if (originalCard == overrideCard) {
+ return;
+ }
+
+ CardInfoPtr cardPtr = overrideCard.getCardPtr();
+ if (!cardPtr) {
+ return;
+ }
+
+ // Heap-allocate so the lambda can capture it before the connection is made
+ auto *connectionHandle = new QMetaObject::Connection;
+
+ *connectionHandle =
+ connect(cardPtr.data(), &CardInfo::pixmapUpdated, cardPtr.data(),
+ [originalCard, overrideCard, connectionHandle, this](const PrintingInfo &printing) {
+ // All printings share the same CardInfo, so ignore updates triggered by any
+ // other printing (e.g., the original card re-loading from disk).
+ if (printing != overrideCard.getPrinting()) {
+ return;
+ }
+
+ QPixmap pixmap;
+ if (QPixmapCache::find(overrideCard.getPixmapCacheKey(), &pixmap) && !pixmap.isNull()) {
+ // The override art has resolved — persist it and reflect it immediately.
+ // Retire the connection before emitting so the refresh can't re-enter.
+ saveCardImageToLocalStorage(originalCard, pixmap, /*allowOverwrite=*/true);
+
+ QObject::disconnect(*connectionHandle);
+ delete connectionHandle;
+
+ QPixmapCache::clear();
+ originalCard.emitPixmapUpdated();
+ return;
+ }
+
+ // The art could not be resolved. Keep the connection armed so a late resolution
+ // still lands, and surface a visible refusal instead of a silent no-op. An
+ // override already on disk is left untouched and simply re-displayed.
+ QPixmapCache::clear();
+ if (!hasLocalOverrides(originalCard)) {
+ QPixmap refusedPixmap;
+ getCardBackLoadingFailedPixmap(refusedPixmap, QSize(480, 672));
+ QPixmapCache::insert(originalCard.getPixmapCacheKey(), refusedPixmap);
+ }
+ originalCard.emitPixmapUpdated();
+ });
+
+ // Now enqueue; if the image is already loading (deduplicated in the worker),
+ // the signal will still fire when it completes
+ CardPictureLoader::getInstance().worker->enqueueImageLoad(overrideCard);
+}
+
+void CardPictureLoader::installPrintingOverride(const ExactCard &originalCard, const ExactCard &overrideCard)
+{
+ // Same guard as installPrintingOverrideOnLoad: self-override is the reset case.
+ if (originalCard == overrideCard) {
+ return;
+ }
+
+ QPixmap pixmap;
+ const QString key = overrideCard.getPixmapCacheKey();
+
+ if (QPixmapCache::find(key, &pixmap) && !pixmap.isNull()) {
+ // Already cached — save immediately; the caller refreshes the card.
+ saveCardImageToLocalStorage(originalCard, pixmap, /*allowOverwrite=*/true);
+ return;
+ }
+
+ // Cache miss or previously failed load — enqueue load and wait for the signal.
+ installPrintingOverrideOnLoad(originalCard, overrideCard);
+}
+
+bool CardPictureLoader::hasLocalOverrides(const ExactCard &card)
+{
+ const QString picsRoot = SettingsCache::instance().paths().getPicsPath();
+ if (picsRoot.isEmpty() || !card) {
+ return false;
+ }
+
+ QDir baseDir(picsRoot);
+ if (!baseDir.cd("downloadedPics")) {
+ return false;
+ }
+
+ const QString name = card.getInfo().getCorrectedName();
+
+ QString set, collector, uuid;
+ const PrintingInfo printing = card.getPrinting();
+ if (printing.getSet()) {
+ set = printing.getSet()->getCorrectedShortName();
+ collector = printing.getProperty("num");
+ uuid = printing.getUuid();
+ }
+
+ for (const auto &scheme : CardPictureLoaderLocalSchemes::exportSchemes()) {
+ QString rel = CardPictureLoaderLocalSchemes::expandPattern(scheme.pattern, name, set, collector, uuid);
+
+ if (rel.isEmpty()) {
+ continue;
+ }
+
+ rel += ".png";
+ rel = QDir::cleanPath(rel);
+
+ if (QFile::exists(baseDir.filePath(rel))) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
void CardPictureLoader::clearPixmapCache()
{
QPixmapCache::clear();
@@ -325,31 +489,11 @@ void CardPictureLoader::picsPathChanged()
QPixmapCache::clear();
}
-bool CardPictureLoader::hasCustomArt()
+void CardPictureLoader::cardLangChanged()
{
- auto picsPath = SettingsCache::instance().paths().getPicsPath();
- QDirIterator it(picsPath, QDir::Dirs | QDir::NoDotAndDotDot);
-
- // Check if there is at least one non-directory file in the pics path, other
- // than in the "downloadedPics" subdirectory.
- while (it.hasNext()) {
-#if (QT_VERSION >= QT_VERSION_CHECK(6, 3, 0))
- QFileInfo dir(it.nextFileInfo());
-#else
- // nextFileInfo() is only available in Qt 6.3+, for previous versions, we build
- // the QFileInfo from a QString which requires more system calls.
- QFileInfo dir(it.next());
-#endif
-
- if (it.fileName() == "downloadedPics") {
- continue;
- }
-
- QDirIterator subIt(it.filePath(), QDir::Files, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);
- if (subIt.hasNext()) {
- return true;
- }
- }
-
- return false;
+ // Localized images are fetched via a different URL, but the in-memory
+ // pixmap cache is keyed by card name/uuid, so drop everything cached
+ // (including failure timestamps) to force a reload in the new language.
+ QPixmapCache::clear();
+ failedAt.clear();
}
diff --git a/cockatrice/src/interface/card_picture_loader/card_picture_loader.h b/cockatrice/src/interface/card_picture_loader/card_picture_loader.h
index 5c3ac84a3..0a4934e6d 100644
--- a/cockatrice/src/interface/card_picture_loader/card_picture_loader.h
+++ b/cockatrice/src/interface/card_picture_loader/card_picture_loader.h
@@ -97,10 +97,17 @@ public:
static void cacheCardPixmaps(const QList &cards);
/**
- * @brief Check if the user has custom card art in the picsPath directory.
- * @return True if any custom art exists.
+ * @brief Check if a local override image already exists for the card.
+ * @param card The card to check.
+ * @return True if the card has at least one locally stored override image.
*/
- static bool hasCustomArt();
+ static bool hasLocalOverrides(const ExactCard &card);
+
+ /**
+ * @brief Removes all locally stored override images for the card.
+ * @param card The card to remove the override images of.
+ */
+ static void deleteAllLocalOverrides(const ExactCard &card);
/**
* @brief Clears the in-memory QPixmap cache for all cards.
@@ -120,7 +127,9 @@ public slots:
* @param image Loaded QImage.
*/
void imageLoaded(const ExactCard &card, const QImage &image);
- void saveCardImageToLocalStorage(const ExactCard &card, const QPixmap &pixmap);
+ void saveCardImageToLocalStorage(const ExactCard &card, const QPixmap &pixmap, bool allowOverwrite = false);
+ void installPrintingOverride(const ExactCard &originalCard, const ExactCard &overrideCard);
+ void installPrintingOverrideOnLoad(const ExactCard &originalCard, const ExactCard &overrideCard);
private slots:
/**
@@ -134,6 +143,12 @@ private slots:
* Clears the QPixmap cache to reload images.
*/
void picsPathChanged();
+
+ /**
+ * @brief Triggered when the card language setting changes.
+ * Clears the in-memory picture caches so images reload in the new language.
+ */
+ void cardLangChanged();
};
#endif
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 39621839a..c82fca403 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
@@ -94,6 +94,10 @@ QImage CardPictureLoaderLocal::tryLoadCardImageFromDisk(const QString &setName,
candidatePaths << picsPath + "/downloadedPics/" + setName + "/" + nameVariant;
}
+ // Non-set-folder export schemes (e.g., Name_Set_Collector) write straight into
+ // downloadedPics/; check there as a fallback so local overrides round-trip.
+ candidatePaths << picsPath + "/downloadedPics/" + nameVariant;
+
for (const QString &path : candidatePaths) {
QFileInfo fileInfo(path);
QDir dir = fileInfo.dir();
@@ -105,7 +109,8 @@ QImage CardPictureLoaderLocal::tryLoadCardImageFromDisk(const QString &setName,
QStringList files = dir.entryList(QDir::Files);
for (const QString &file : files) {
- if (!file.startsWith(baseName)) {
+ QFileInfo fi(file);
+ if (fi.completeBaseName() != baseName) {
continue;
}
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 d288236d2..34092f361 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
@@ -84,8 +84,8 @@ void CardPictureLoaderWorker::queueRequest(const QUrl &url, CardPictureLoaderWor
SettingsCache::instance().cacheStorage().getCardPictureLoaderCacheMethod()) ==
CardPictureLoaderCacheMethod::CacheMethod::NETWORK_CACHE &&
cache->metaData(url).isValid()) {
- // If we hit a cached url, we get to make the request for free, since it won't contribute towards the
- // rate-limit
+ // A request that will be served from the disk cache never touches the network and therefore
+ // doesn't use up any of the rate limit, so it gets to skip the queue.
makeRequest(url, worker);
return;
}
@@ -107,10 +107,13 @@ QNetworkReply *CardPictureLoaderWorker::makeRequest(const QUrl &url, CardPicture
req.setHeader(QNetworkRequest::UserAgentHeader, QString("Cockatrice %1").arg(VERSION_STRING));
req.setRawHeader("Accept", "image/avif,image/webp,image/apng,image/,/*;q=0.8");
- bool useNetworkCache =
- !picDownload && static_cast(
- SettingsCache::instance().cacheStorage().getCardPictureLoaderCacheMethod()) ==
- CardPictureLoaderCacheMethod::CacheMethod::NETWORK_CACHE;
+ // Cached entries are served straight from the disk cache even when picture downloads are
+ // enabled: re-fetching an already-cached image would burn the rate limit for nothing. Only a
+ // genuine cache miss goes to the network, and only when downloads are enabled.
+ bool useNetworkCache = static_cast(
+ SettingsCache::instance().cacheStorage().getCardPictureLoaderCacheMethod()) ==
+ CardPictureLoaderCacheMethod::CacheMethod::NETWORK_CACHE &&
+ (cache->metaData(url).isValid() || !picDownload);
req.setAttribute(QNetworkRequest::CacheLoadControlAttribute,
useNetworkCache ? QNetworkRequest::AlwaysCache : QNetworkRequest::AlwaysNetwork);
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 5f4ff0bbd..7cb502e92 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
@@ -94,7 +94,8 @@ void CardPictureToLoad::populateSetUrls()
}
}
- for (const QString &urlTemplate : urlTemplates) {
+ const QStringList orderedTemplates = urlTemplates;
+ for (const QString &urlTemplate : orderedTemplates) {
QString transformedUrl = transformUrl(urlTemplate);
if (!transformedUrl.isEmpty()) {
@@ -282,8 +283,15 @@ QString CardPictureToLoad::transformUrl(const QString &urlTemplate) const
}
// language setting
- transformMap["!sflang!"] = QString(QCoreApplication::translate(
- "PictureLoader", "en", "code for scryfall's language property, not available for all languages"));
+ const QString cardLang = SettingsCache::instance().cardsDisplay().getCardLang();
+ transformMap["!sflang!"] = cardLang;
+
+ // The localized printing's own id is unknown, so Scryfall must resolve it by
+ // its translated name (see populateSetUrls); expose that name for the
+ // `/cards/named` template.
+ if (cardLang != "en") {
+ transformMap["!localizedName!"] = card.getInfo().getLocalizedName(cardLang);
+ }
QString transformedUrl = urlTemplate;
for (const QString &prop : transformMap.keys()) {
diff --git a/cockatrice/src/interface/deck_loader/deck_file_format.h b/cockatrice/src/interface/deck_loader/deck_file_format.h
index 995de32c0..3a25797ec 100644
--- a/cockatrice/src/interface/deck_loader/deck_file_format.h
+++ b/cockatrice/src/interface/deck_loader/deck_file_format.h
@@ -17,7 +17,7 @@ enum Format
PlainText,
/**
- * This is cockatrice's native deck file format, and supports deck metadata such as banner cards and tags.
+ * This is Cockatrice's native deck file format, and supports deck metadata such as banner cards and tags.
* Stored as .cod files.
*/
Cockatrice
diff --git a/cockatrice/src/interface/deck_loader/deck_loader.cpp b/cockatrice/src/interface/deck_loader/deck_loader.cpp
index f03339da8..f29b4eed2 100644
--- a/cockatrice/src/interface/deck_loader/deck_loader.cpp
+++ b/cockatrice/src/interface/deck_loader/deck_loader.cpp
@@ -50,7 +50,7 @@ DeckLoader::loadFromFile(const QString &fileName, DeckFileFormat::Format fmt, bo
result = deckList.loadFromFile_Native(&file);
if (!result) {
qCInfo(DeckLoaderLog) << "Failed to load " << fileName
- << "as cockatrice format; retrying as plain format";
+ << "as Cockatrice format; retrying as plain format";
file.seek(0);
result = deckList.loadFromFile_Plain(&file, CardNameNormalizer());
fmt = DeckFileFormat::PlainText;
diff --git a/cockatrice/src/interface/deck_loader/deck_loader.h b/cockatrice/src/interface/deck_loader/deck_loader.h
index b851c6895..be0df311d 100644
--- a/cockatrice/src/interface/deck_loader/deck_loader.h
+++ b/cockatrice/src/interface/deck_loader/deck_loader.h
@@ -131,7 +131,7 @@ public:
static void printDeckList(QPrinter *printer, const DeckList &deckList);
/**
- * Converts the given deck's file to the cockatrice file format.
+ * Converts the given deck's file to the Cockatrice file format.
* Uses the lastLoadInfo in the LoadedDeck to determine the current name of the file and where to save to.
* @param deck The deck to convert. Should have valid lastLoadInfo. Will update the lastLoadInfo.
* @return Whether the conversion succeeded.
diff --git a/cockatrice/src/interface/intents/contexts/context_open_deck.h b/cockatrice/src/interface/intents/contexts/context_open_deck.h
new file mode 100644
index 000000000..03dca088e
--- /dev/null
+++ b/cockatrice/src/interface/intents/contexts/context_open_deck.h
@@ -0,0 +1,14 @@
+#ifndef COCKATRICE_CONTEXT_OPEN_DECK_H
+#define COCKATRICE_CONTEXT_OPEN_DECK_H
+
+#include "context_connect_to_server.h"
+
+#include
+
+struct ContextOpenDeck
+{
+ ContextConnectToServer serverContext;
+ QString shareToken;
+};
+
+#endif // COCKATRICE_CONTEXT_OPEN_DECK_H
diff --git a/cockatrice/src/interface/intents/intent.cpp b/cockatrice/src/interface/intents/intent.cpp
index c02a89f35..db0d13b2c 100644
--- a/cockatrice/src/interface/intents/intent.cpp
+++ b/cockatrice/src/interface/intents/intent.cpp
@@ -2,10 +2,11 @@
Intent::Intent(QObject *parent) : QObject(parent)
{
- // An intent is done as soon as it reports success or failure. Deleting it
- // also tears down its dependency chain and disconnects any signal wiring.
+ // An intent is done as soon as it reports success, failure, or cancellation.
+ // Deleting it also tears down its dependency chain and disconnects any signal wiring.
connect(this, &Intent::finished, this, &QObject::deleteLater);
connect(this, &Intent::failed, this, &QObject::deleteLater);
+ connect(this, &Intent::cancelled, this, &QObject::deleteLater);
}
Intent::~Intent() = default;
@@ -27,6 +28,7 @@ void Intent::runDependency(Intent *dependency)
this->execute();
});
connect(dependency, &Intent::failed, this, &Intent::failed);
+ connect(dependency, &Intent::cancelled, this, &Intent::cancelled);
dependency->execute();
}
@@ -46,3 +48,11 @@ void Intent::emitFailed(const QString &reason)
emit failed(reason);
}
}
+
+void Intent::emitCancelled()
+{
+ if (!completed) {
+ completed = true;
+ emit cancelled();
+ }
+}
diff --git a/cockatrice/src/interface/intents/intent.h b/cockatrice/src/interface/intents/intent.h
index 125900ecd..5d9fdd3d6 100644
--- a/cockatrice/src/interface/intents/intent.h
+++ b/cockatrice/src/interface/intents/intent.h
@@ -16,6 +16,7 @@ public:
signals:
void finished();
void failed(QString reason);
+ void cancelled();
protected:
// --- Subclasses must implement these ---
@@ -29,6 +30,7 @@ protected:
// Emit the outcome exactly once; ignore late signals after the intent is done.
void emitFinished();
void emitFailed(const QString &reason);
+ void emitCancelled();
private:
bool completed = false;
diff --git a/cockatrice/src/interface/intents/intent_join_server_game.cpp b/cockatrice/src/interface/intents/intent_join_server_game.cpp
index 205c4dc70..6bf46ec72 100644
--- a/cockatrice/src/interface/intents/intent_join_server_game.cpp
+++ b/cockatrice/src/interface/intents/intent_join_server_game.cpp
@@ -19,13 +19,10 @@ bool IntentJoinServerGame::checkPrecondition() const
if (remoteClient->getStatus() != ClientStatus::StatusLoggedIn) {
return false;
}
- // peerPort() reflects the actual TCP peer, which may differ from the
- // configured server port (e.g. when connecting through a proxy), so only
- // the hostname is compared here.
- if (remoteClient->peerName() != context->roomContext.serverContext.hostname) {
- return false;
- }
- if (QString::number(remoteClient->peerPort()) != context->roomContext.serverContext.port) {
+ // serverName() reflects the server the client was configured to connect to,
+ // which may differ from the actual TCP peer (e.g. when connecting through a
+ // proxy), so only the hostname is compared here.
+ if (remoteClient->serverName().compare(context->roomContext.serverContext.hostname, Qt::CaseInsensitive) != 0) {
return false;
}
diff --git a/cockatrice/src/interface/intents/intent_login.cpp b/cockatrice/src/interface/intents/intent_login.cpp
index ff871fd03..d3431bb07 100644
--- a/cockatrice/src/interface/intents/intent_login.cpp
+++ b/cockatrice/src/interface/intents/intent_login.cpp
@@ -1,9 +1,14 @@
#include "intent_login.h"
#include "../../client/settings/cache_settings.h"
+#include "../widgets/dialogs/dlg_login_prompt.h"
#include "libcockatrice/settings/servers_settings.h"
-IntentGetLoginCredentials::IntentGetLoginCredentials(ContextConnectToServer *_context) : Intent(), context(_context)
+#include
+
+IntentGetLoginCredentials::IntentGetLoginCredentials(ContextConnectToServer *_context,
+ bool _promptForMissingCredentials)
+ : Intent(), context(_context), promptForMissingCredentials(_promptForMissingCredentials)
{
}
@@ -29,5 +34,35 @@ void IntentGetLoginCredentials::onPreconditionSatisfied()
void IntentGetLoginCredentials::onPreconditionNotSatisfied()
{
- emitFailed(tr("No saved credentials for this server"));
+ // MainWindow::applyStartupDestination runs this intent on every launch for
+ // users whose startup tab is Server / Server Room; keep that path quiet, as
+ // it was before the link-driven sign-in dialog existed.
+ if (!promptForMissingCredentials) {
+ emitFailed(tr("No saved credentials for this server"));
+ return;
+ }
+
+ // No credentials saved for the target server: ask the user for them. They
+ // opt into saving them so later links to the same server connect directly.
+ const QString serverText = context->hostname + ":" + context->port;
+ DlgLoginPrompt dialog(serverText);
+ // ApplicationModal: the dialog has no parent (the intent is not a widget),
+ // so WindowModal would not actually block any other window.
+ dialog.setWindowModality(Qt::ApplicationModal);
+
+ if (dialog.exec() != QDialog::Accepted) {
+ emitCancelled();
+ return;
+ }
+
+ context->username = dialog.username();
+ context->password = dialog.password();
+
+ if (dialog.savePassword() && !context->username.isEmpty()) {
+ ServersSettings &servers = SettingsCache::instance().servers();
+ servers.addNewServer(context->hostname, context->hostname, context->port, context->username, context->password,
+ true);
+ }
+
+ emitFinished();
}
diff --git a/cockatrice/src/interface/intents/intent_login.h b/cockatrice/src/interface/intents/intent_login.h
index c7fec92b7..8ffd91a0a 100644
--- a/cockatrice/src/interface/intents/intent_login.h
+++ b/cockatrice/src/interface/intents/intent_login.h
@@ -9,7 +9,10 @@ class IntentGetLoginCredentials : public Intent
Q_OBJECT
public:
- IntentGetLoginCredentials(ContextConnectToServer *_context);
+ // When promptForMissingCredentials is false (the default) a server without
+ // saved credentials fails silently; only intent chains from cockatrice://
+ // links opt into the interactive sign-in dialog.
+ explicit IntentGetLoginCredentials(ContextConnectToServer *_context, bool _promptForMissingCredentials = false);
protected:
bool checkPrecondition() const override;
@@ -18,6 +21,7 @@ protected:
private:
ContextConnectToServer *context;
+ bool promptForMissingCredentials;
};
#endif // COCKATRICE_INTENT_LOGIN_H
diff --git a/cockatrice/src/interface/intents/intent_open_shared_deck.cpp b/cockatrice/src/interface/intents/intent_open_shared_deck.cpp
new file mode 100644
index 000000000..9ecb4520d
--- /dev/null
+++ b/cockatrice/src/interface/intents/intent_open_shared_deck.cpp
@@ -0,0 +1,203 @@
+#include "intent_open_shared_deck.h"
+
+#include "../deck_loader/deck_loader.h"
+#include "../widgets/dialogs/dlg_shared_decks_preview.h"
+#include "../widgets/tabs/tab_supervisor.h"
+#include "intent_connect_to_server.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+IntentOpenSharedDeck::IntentOpenSharedDeck(TabSupervisor *_tabSupervisor,
+ RemoteClient *_remoteClient,
+ const CardDatabaseQuerier *_querier,
+ std::unique_ptr _context)
+ : Intent(), tabSupervisor(_tabSupervisor), remoteClient(_remoteClient), querier(_querier),
+ context(_context.release())
+{
+ downloadTimer = new QTimer(this);
+ downloadTimer->setSingleShot(true);
+ downloadTimer->setInterval(15000);
+ connect(downloadTimer, &QTimer::timeout, this, &IntentOpenSharedDeck::onDownloadTimeout);
+}
+
+bool IntentOpenSharedDeck::checkPrecondition() const
+{
+ if (remoteClient->getStatus() != ClientStatus::StatusLoggedIn) {
+ return false;
+ }
+ // serverName() reflects the server the client was configured to connect to,
+ // which may differ from the actual TCP peer (e.g. when connecting through a
+ // proxy), so only the hostname is compared here.
+ return remoteClient->serverName().compare(context->serverContext.hostname, Qt::CaseInsensitive) == 0;
+}
+
+void IntentOpenSharedDeck::onPreconditionSatisfied()
+{
+ // Resolve the share token to its items first; a share can contain more than
+ // one deck, and each item is downloaded by id. Time the round trip like the
+ // downloads, so a silent server cannot hang the chain forever.
+ listPhase = true;
+ downloadTimer->start();
+
+ Command_DeckShareList cmd;
+ cmd.set_token(context->shareToken.toStdString());
+
+ PendingCommand *pend = AbstractClient::prepareSessionCommand(cmd);
+ connect(pend, &PendingCommand::finished, this, &IntentOpenSharedDeck::listShareFinished);
+ remoteClient->sendCommand(pend);
+}
+
+void IntentOpenSharedDeck::onPreconditionNotSatisfied()
+{
+ runDependency(new IntentConnectToServer(remoteClient, &context->serverContext));
+}
+
+void IntentOpenSharedDeck::listShareFinished(const Response &response, const CommandContainer & /* commandContainer */)
+{
+ downloadTimer->stop();
+ listPhase = false;
+
+ if (response.response_code() != Response::RespOk) {
+ emitFailed(tr("The shared deck could not be found or has expired"));
+ return;
+ }
+
+ const Response_DeckShareList &resp = response.GetExtension(Response_DeckShareList::ext);
+ if (resp.items_size() == 0) {
+ emitFailed(tr("The shared deck is empty"));
+ return;
+ }
+
+ QList items;
+ items.reserve(resp.items_size());
+ for (const ServerInfo_DeckShareItem &item : resp.items()) {
+ items.append(item);
+ itemNames.insert(item.id(), QString::fromStdString(item.name()));
+ }
+
+ const QString serverText = context->serverContext.hostname + ":" + context->serverContext.port;
+
+ // Ask the user which decks to open before downloading anything.
+ previewDialog = new DlgSharedDecksPreview(tabSupervisor, querier, QString::fromStdString(resp.name()),
+ resp.expires_at(), serverText, items);
+ connect(previewDialog, &DlgSharedDecksPreview::openRequested, this, &IntentOpenSharedDeck::startDownloads);
+ connect(previewDialog, &DlgSharedDecksPreview::cancelled, this, &IntentOpenSharedDeck::emitCancelled);
+ connect(previewDialog, &DlgSharedDecksPreview::cancelled, previewDialog, &QWidget::deleteLater);
+ previewDialog->show();
+ previewDialog->raise();
+ previewDialog->activateWindow();
+}
+
+void IntentOpenSharedDeck::startDownloads(const QList &itemIds)
+{
+ pendingItemIds = itemIds;
+ totalItems = itemIds.size();
+ completedItems = 0;
+ loadedDecks.clear();
+ downloadNextItem();
+}
+
+void IntentOpenSharedDeck::downloadNextItem()
+{
+ if (pendingItemIds.isEmpty()) {
+ finishAll();
+ return;
+ }
+
+ currentItemId = pendingItemIds.takeFirst();
+ downloadTimer->start();
+
+ Command_DeckShareDownload cmd;
+ cmd.set_token(context->shareToken.toStdString());
+ cmd.set_item_id(currentItemId);
+
+ PendingCommand *pend = AbstractClient::prepareSessionCommand(cmd);
+ connect(pend, &PendingCommand::finished, this, &IntentOpenSharedDeck::downloadShareFinished);
+ remoteClient->sendCommand(pend);
+}
+
+void IntentOpenSharedDeck::downloadShareFinished(const Response &response,
+ const CommandContainer & /* commandContainer */)
+{
+ downloadTimer->stop();
+
+ QString failureReason;
+ if (response.response_code() != Response::RespOk) {
+ failureReason = tr("Failed to download the shared deck");
+ } else {
+ const Response_DeckShareDownload &resp = response.GetExtension(Response_DeckShareDownload::ext);
+ const QString deckString = QString::fromStdString(resp.deck());
+ if (deckString.isEmpty()) {
+ failureReason = tr("The shared deck is empty");
+ } else {
+ std::optional deckOpt =
+ DeckLoader::loadFromRemote(deckString, LoadedDeck::LoadInfo::NON_REMOTE_ID);
+ if (!deckOpt) {
+ failureReason = tr("The shared deck could not be loaded");
+ } else {
+ loadedDecks.append(deckOpt.value());
+ ++completedItems;
+ previewDialog->setDownloadProgress(completedItems, totalItems,
+ itemNames.value(currentItemId, tr("Unknown deck")));
+ downloadNextItem();
+ return;
+ }
+ }
+ }
+
+ onItemFailure(failureReason);
+}
+
+void IntentOpenSharedDeck::onItemFailure(const QString &reason)
+{
+ downloadTimer->stop();
+
+ if (loadedDecks.isEmpty()) {
+ previewDialog->deleteLater();
+ emitFailed(reason);
+ return;
+ }
+
+ const int downloadedCount = loadedDecks.size();
+ const QMessageBox::StandardButton answer = QMessageBox::question(
+ previewDialog, tr("Open shared decks"),
+ tr("Could not download the deck \"%1\".\n\n%n deck(s) were already downloaded. Open them?", "", downloadedCount)
+ .arg(itemNames.value(currentItemId, tr("Unknown deck"))),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
+
+ if (answer == QMessageBox::Yes) {
+ finishAll();
+ } else {
+ previewDialog->deleteLater();
+ emitCancelled();
+ }
+}
+
+void IntentOpenSharedDeck::onDownloadTimeout()
+{
+ // The list phase has no preview dialog yet to report progress into; fail the
+ // whole intent instead of letting the shared deck hang in limbo.
+ if (listPhase) {
+ emitFailed(tr("Timed out while loading the shared deck"));
+ return;
+ }
+ onItemFailure(tr("Timed out while downloading the shared deck"));
+}
+
+void IntentOpenSharedDeck::finishAll()
+{
+ previewDialog->deleteLater();
+ for (const LoadedDeck &deck : loadedDecks) {
+ tabSupervisor->openDeckInNewTab(deck);
+ }
+ emitFinished();
+}
diff --git a/cockatrice/src/interface/intents/intent_open_shared_deck.h b/cockatrice/src/interface/intents/intent_open_shared_deck.h
new file mode 100644
index 000000000..87812bdea
--- /dev/null
+++ b/cockatrice/src/interface/intents/intent_open_shared_deck.h
@@ -0,0 +1,60 @@
+#ifndef COCKATRICE_INTENT_OPEN_SHARED_DECK_H
+#define COCKATRICE_INTENT_OPEN_SHARED_DECK_H
+
+#include "contexts/context_open_deck.h"
+#include "intent.h"
+#include "remote_client.h"
+
+#include
+#include
+#include
+#include
+
+class TabSupervisor;
+struct LoadedDeck;
+class CardDatabaseQuerier;
+class DlgSharedDecksPreview;
+class QTimer;
+
+class IntentOpenSharedDeck : public Intent
+{
+ Q_OBJECT
+
+public:
+ IntentOpenSharedDeck(TabSupervisor *_tabSupervisor,
+ RemoteClient *_remoteClient,
+ const CardDatabaseQuerier *_querier,
+ std::unique_ptr _context);
+
+protected:
+ bool checkPrecondition() const override;
+ void onPreconditionSatisfied() override;
+ void onPreconditionNotSatisfied() override;
+
+private slots:
+ void listShareFinished(const Response &response, const CommandContainer &commandContainer);
+ void downloadShareFinished(const Response &response, const CommandContainer &commandContainer);
+ void onDownloadTimeout();
+
+private:
+ void startDownloads(const QList &itemIds);
+ void downloadNextItem();
+ void onItemFailure(const QString &reason);
+ void finishAll();
+
+ TabSupervisor *tabSupervisor;
+ RemoteClient *remoteClient;
+ const CardDatabaseQuerier *querier;
+ QScopedPointer context;
+ DlgSharedDecksPreview *previewDialog = nullptr;
+ QTimer *downloadTimer;
+ QMap itemNames;
+ QList pendingItemIds;
+ QList loadedDecks;
+ bool listPhase = true;
+ int currentItemId = 0;
+ int totalItems = 0;
+ int completedItems = 0;
+};
+
+#endif // COCKATRICE_INTENT_OPEN_SHARED_DECK_H
diff --git a/cockatrice/src/interface/intents/url_parser.cpp b/cockatrice/src/interface/intents/url_parser.cpp
index 509390611..120e72b2a 100644
--- a/cockatrice/src/interface/intents/url_parser.cpp
+++ b/cockatrice/src/interface/intents/url_parser.cpp
@@ -1,19 +1,28 @@
#include "url_parser.h"
+#include "../../client/settings/cache_settings.h"
#include "../widgets/tabs/tab_room.h"
#include "../widgets/tabs/tab_supervisor.h"
#include "../window_main.h"
#include "contexts/context_join_game.h"
+#include "contexts/context_open_deck.h"
+#include "intent.h"
#include "intent_join_server_game.h"
#include "intent_login.h"
+#include "intent_open_shared_deck.h"
#include
+#include
#include
#include
#include
+#include
#include
+#include
#include
+inline Q_LOGGING_CATEGORY(UrlParserLog, "url_parser");
+
IntentUrlParser::IntentUrlParser(QObject *parent, MainWindow *_mainWindow) : QObject(parent), mainWindow(_mainWindow)
{
}
@@ -29,16 +38,33 @@ void IntentUrlParser::handle(const QString &urlStr)
const QString action = url.host();
QUrlQuery query(url);
+ qCDebug(UrlParserLog) << "Parsing intent URL, action:" << action;
+
+ PendingIntentChain chain;
+ Intent *firstIntent = nullptr;
if (action == "joingame") {
- handleJoinGame(query);
+ firstIntent = createJoinGameIntent(query, chain);
} else if (action == "opendeck") {
- // handleOpenDeck(query);
+ firstIntent = createOpenDeckIntent(query, chain);
} else {
qWarning() << "Unknown intent:" << action;
}
+
+ if (firstIntent == nullptr) {
+ // The link was invalid or the user declined the confirm: nothing runs.
+ // Report the idle state when no other chain is queued so that a startup
+ // launch (which skipped its own connection for this URL) falls back to it.
+ if (!chainRunning && pendingChains.isEmpty()) {
+ emit urlChainFinished(mainWindow->getRemoteClient()->getStatus() == StatusLoggedIn);
+ }
+ return;
+ }
+
+ pendingChains.append(chain);
+ startNextChain();
}
-void IntentUrlParser::handleJoinGame(const QUrlQuery &query)
+Intent *IntentUrlParser::createJoinGameIntent(const QUrlQuery &query, PendingIntentChain &chain)
{
auto showError = [this](const QString &message) { QMessageBox::warning(mainWindow, tr("Open game"), message); };
@@ -49,21 +75,21 @@ void IntentUrlParser::handleJoinGame(const QUrlQuery &query)
if (ctx->roomContext.serverContext.hostname.isEmpty()) {
showError(tr("Missing or empty hostname in the game link"));
- return;
+ return nullptr;
}
bool ok = false;
ctx->roomContext.serverContext.port.toUShort(&ok);
if (!ok) {
showError(tr("Invalid or missing port in the game link"));
- return;
+ return nullptr;
}
ctx->roomContext.roomId = query.queryItemValue("roomid").toInt(&ok);
if (!ok) {
showError(tr("Invalid or missing room id in the game link"));
- return;
+ return nullptr;
}
ok = false;
@@ -71,7 +97,7 @@ void IntentUrlParser::handleJoinGame(const QUrlQuery &query)
if (!ok) {
showError(tr("Invalid or missing game id in the game link"));
- return;
+ return nullptr;
}
const QString gameDescription = query.queryItemValue("game", QUrl::FullyDecoded);
@@ -80,24 +106,33 @@ void IntentUrlParser::handleJoinGame(const QUrlQuery &query)
const QMessageBox::StandardButton answer = QMessageBox::question(
mainWindow, tr("Join game"), message, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if (answer != QMessageBox::Yes) {
- return;
+ return nullptr;
}
+ RemoteClient *client = mainWindow->getRemoteClient();
+ ContextConnectToServer *serverContext = &ctx->roomContext.serverContext;
+
// The join game intent owns the context and the credential lookup; once the
// chain finishes (or fails) it deletes the whole tree.
- ContextConnectToServer *serverContext = &ctx->roomContext.serverContext;
- auto joinGameIntent =
- new IntentJoinServerGame(mainWindow->getTabSupervisor(), mainWindow->getRemoteClient(), std::move(ctx));
+ auto joinGameIntent = new IntentJoinServerGame(mainWindow->getTabSupervisor(), client, std::move(ctx));
joinGameIntent->setParent(this);
-
- auto getLoginCredentialsIntent = new IntentGetLoginCredentials(serverContext);
- getLoginCredentialsIntent->setParent(joinGameIntent);
-
- connect(getLoginCredentialsIntent, &Intent::finished, joinGameIntent, &Intent::execute);
- connect(getLoginCredentialsIntent, &Intent::failed, joinGameIntent, &Intent::failed);
+ chain.intents.append(joinGameIntent);
connect(joinGameIntent, &Intent::failed, this, [showError](const QString &reason) { showError(reason); });
- getLoginCredentialsIntent->execute();
+ Intent *firstIntent = joinGameIntent;
+ if (!isConnectedTo(serverContext->hostname, serverContext->port)) {
+ auto getLoginCredentialsIntent =
+ new IntentGetLoginCredentials(serverContext, /*promptForMissingCredentials=*/true);
+ getLoginCredentialsIntent->setParent(joinGameIntent);
+ chain.intents.insert(0, getLoginCredentialsIntent);
+
+ connect(getLoginCredentialsIntent, &Intent::finished, joinGameIntent, &Intent::execute);
+ connect(getLoginCredentialsIntent, &Intent::failed, joinGameIntent, &Intent::failed);
+ connect(getLoginCredentialsIntent, &Intent::cancelled, joinGameIntent, &Intent::cancelled);
+ firstIntent = getLoginCredentialsIntent;
+ }
+
+ return firstIntent;
}
QString IntentUrlParser::generateJoinGameMessage(const ContextJoinGame &context, const QString &gameDescription)
@@ -134,3 +169,264 @@ QString IntentUrlParser::generateJoinGameMessage(const ContextJoinGame &context,
.arg(gameDescription, gameIdStr, roomTab->getRoomName(), server)
: tr("Join game \"%1\" (#%2) on %3?").arg(gameDescription, gameIdStr, server);
}
+
+Intent *IntentUrlParser::createOpenDeckIntent(const QUrlQuery &query, PendingIntentChain &chain)
+{
+ auto showError = [this](const QString &message) {
+ QMessageBox::warning(mainWindow, tr("Open shared deck"), message);
+ };
+
+ auto ctx = std::make_unique();
+
+ ctx->serverContext.hostname = query.queryItemValue("hostname");
+ ctx->serverContext.port = query.queryItemValue("port");
+ ctx->shareToken = query.queryItemValue("share");
+
+ qCDebug(UrlParserLog) << "Open-deck intent: host" << ctx->serverContext.hostname << "port"
+ << ctx->serverContext.port << "token length" << ctx->shareToken.length();
+
+ if (ctx->serverContext.hostname.isEmpty()) {
+ showError(tr("Missing or empty hostname in the share link"));
+ return nullptr;
+ }
+
+ bool ok = false;
+ const quint16 port = ctx->serverContext.port.toUShort(&ok);
+ if (!ok || port == 0) {
+ showError(tr("Invalid or missing port in the share link"));
+ return nullptr;
+ }
+
+ if (ctx->shareToken.isEmpty()) {
+ showError(tr("Missing or empty share value in the share link"));
+ return nullptr;
+ }
+
+ RemoteClient *client = mainWindow->getRemoteClient();
+
+ // The open deck download needs a connection to the link's server. Ask before
+ // taking the session anywhere it isn't already, naming the host we would
+ // connect to. Remember the link's target when it moves us away from a live
+ // session so a failed or cancelled chain can restore the session it left.
+ const bool alreadyConnected = isConnectedTo(ctx->serverContext.hostname, ctx->serverContext.port);
+ if (!alreadyConnected) {
+ const QString target = QStringLiteral("%1:%2").arg(ctx->serverContext.hostname, ctx->serverContext.port);
+
+ if (client->getStatus() == StatusLoggedIn) {
+ const QString current =
+ QStringLiteral("%1:%2").arg(client->serverName(), QString::number(client->serverPort()));
+ const QMessageBox::StandardButton answer = QMessageBox::question(
+ mainWindow, tr("Open shared deck"),
+ tr("Opening this share link connects you to %1 instead of %2.\n\nContinue?").arg(target, current),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
+ if (answer != QMessageBox::Yes) {
+ return nullptr;
+ }
+ chain.migrationTargetHost = ctx->serverContext.hostname;
+ chain.migrationTargetPort = ctx->serverContext.port;
+ chain.pendingRestore = true;
+ } else {
+ // Fresh connection is harmless to wander away from, but a server the
+ // client has never been configured for deserves a harder warning (no
+ // by default) so a stray link cannot silently steer the client there.
+ const bool knownHost = SettingsCache::instance().servers().findHostIndex(ctx->serverContext.hostname) >= 0;
+ const QMessageBox::StandardButton answer =
+ knownHost
+ ? QMessageBox::question(mainWindow, tr("Open shared deck"),
+ tr("Opening this share link connects you to %1.\n\nContinue?").arg(target))
+ : QMessageBox::warning(mainWindow, tr("Open shared deck"),
+ tr("Opening this share link connects you to %1, a server you have "
+ "never connected to before.\n\nContinue?")
+ .arg(target),
+ QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
+ if (answer != QMessageBox::Yes) {
+ return nullptr;
+ }
+ }
+ }
+
+ ContextConnectToServer *serverContext = &ctx->serverContext;
+
+ // The open deck intent owns the context and the credential lookup; once
+ // the chain finishes (or fails) it deletes the whole tree.
+ auto openDeckIntent =
+ new IntentOpenSharedDeck(mainWindow->getTabSupervisor(), client, CardDatabaseManager::query(), std::move(ctx));
+ openDeckIntent->setParent(this);
+ chain.intents.append(openDeckIntent);
+ connect(openDeckIntent, &Intent::failed, this, [showError](const QString &reason) { showError(reason); });
+
+ Intent *firstIntent = openDeckIntent;
+ if (!isConnectedTo(serverContext->hostname, serverContext->port)) {
+ auto getLoginCredentialsIntent =
+ new IntentGetLoginCredentials(serverContext, /*promptForMissingCredentials=*/true);
+ getLoginCredentialsIntent->setParent(openDeckIntent);
+ chain.intents.insert(0, getLoginCredentialsIntent);
+
+ connect(getLoginCredentialsIntent, &Intent::finished, openDeckIntent, &Intent::execute);
+ connect(getLoginCredentialsIntent, &Intent::failed, openDeckIntent, &Intent::failed);
+ connect(getLoginCredentialsIntent, &Intent::cancelled, openDeckIntent, &Intent::cancelled);
+ firstIntent = getLoginCredentialsIntent;
+ }
+
+ return firstIntent;
+}
+
+bool IntentUrlParser::isConnectedTo(const QString &hostname, const QString &port) const
+{
+ Q_UNUSED(port);
+ // Deliberately hostname-only (no port): the intents' preconditions apply the
+ // same rule, so a link to the same host on another port still connects
+ // rather than silently reusing an existing session on a different server.
+ RemoteClient *client = mainWindow->getRemoteClient();
+ return client->getStatus() == StatusLoggedIn && client->serverName().compare(hostname, Qt::CaseInsensitive) == 0;
+}
+
+void IntentUrlParser::startNextChain()
+{
+ if (chainRunning || pendingChains.isEmpty()) {
+ return;
+ }
+ chainRunning = true;
+
+ PendingIntentChain &chain = pendingChains.first();
+ if (chain.intents.isEmpty()) {
+ pendingChains.removeFirst();
+ chainRunning = false;
+ startNextChain();
+ return;
+ }
+
+ // Snapshot the session this chain moves away from now that it actually
+ // runs. Chains are parsed while earlier ones are still queued, so a capture
+ // at parse time would follow whichever server the chain before it settled
+ // on, not the one the user is really on when this link is handled.
+ if (chain.pendingRestore) {
+ RemoteClient *client = mainWindow->getRemoteClient();
+ chain.previousServerHost = client->serverName();
+ chain.previousServerPort = QString::number(client->serverPort());
+ }
+
+ // Only the last intent completes the chain; its terminal signal ends the
+ // whole run. Cancellation of an intermediate intent (e.g. declined login
+ // prompt) is forwarded onto the last intent in the chain builders above.
+ Intent *finalIntent = chain.intents.last();
+ connect(finalIntent, &Intent::finished, this, [this]() { chainEnded(true); });
+ connect(finalIntent, &Intent::failed, this, [this]() { chainEnded(false); });
+ connect(finalIntent, &Intent::cancelled, this, [this]() { chainEnded(false); });
+ // Backstop: if the final intent is destroyed without emitting a terminal
+ // signal (e.g. a network error dropped it while running), end the chain so
+ // later links are not queued and dropped for the rest of the session.
+ chainBackstopConnection = connect(finalIntent, &QObject::destroyed, this, &IntentUrlParser::onChainIntentDestroyed);
+
+ chain.intents.first()->execute();
+}
+
+void IntentUrlParser::chainEnded(bool chainSucceeded)
+{
+ chainRunning = false;
+ QObject::disconnect(chainBackstopConnection);
+
+ const PendingIntentChain chain = pendingChains.takeFirst();
+
+ // Only a failed or cancelled chain restores the session the link migrated
+ // away from; a successful one leaves the user where they are.
+ if (chain.pendingRestore && !chainSucceeded) {
+ restorePreviousServer(chain);
+ }
+
+ startNextChain();
+
+ // Only report the terminal state once the queue has fully drained, so a
+ // queued follow-up link keeps the startup fallback out of the picture.
+ if (!chainRunning && pendingChains.isEmpty()) {
+ emit urlChainFinished(mainWindow->getRemoteClient()->getStatus() == StatusLoggedIn);
+ }
+}
+
+void IntentUrlParser::onChainIntentDestroyed()
+{
+ if (!chainRunning) {
+ return;
+ }
+ qCWarning(UrlParserLog) << "Share-link intent destroyed without a terminal signal; ending its chain";
+ chainEnded(false);
+}
+
+void IntentUrlParser::restorePreviousServer(const PendingIntentChain &chain)
+{
+ if (chain.previousServerHost.isEmpty()) {
+ return;
+ }
+
+ RemoteClient *client = mainWindow->getRemoteClient();
+ const ClientStatus status = client->getStatus();
+
+ // A failed/cancelled chain can fire while the client is still settling the
+ // in-flight connection attempt (wrong password, connect timeout). Only
+ // decide once the client has settled into logged-in or disconnected;
+ // deciding mid-connect would strand the user offline from their previous
+ // server.
+ if (status == StatusDisconnected || status == StatusLoggedIn) {
+ restoreToPreviousServer(chain);
+ return;
+ }
+ auto waitConnection = std::make_shared();
+ *waitConnection = connect(client, &RemoteClient::statusChanged, this, [this, chain, client, waitConnection]() {
+ const ClientStatus settled = client->getStatus();
+ if (settled == StatusDisconnected || settled == StatusLoggedIn) {
+ QObject::disconnect(*waitConnection);
+ restoreToPreviousServer(chain);
+ }
+ });
+}
+
+void IntentUrlParser::restoreToPreviousServer(const PendingIntentChain &chain)
+{
+ RemoteClient *client = mainWindow->getRemoteClient();
+
+ // Back on the previous server already → nothing to undo.
+ if (client->serverName().compare(chain.previousServerHost, Qt::CaseInsensitive) == 0 &&
+ QString::number(client->serverPort()) == chain.previousServerPort) {
+ return;
+ }
+
+ // When logged in somewhere, only intervene if that somewhere is the server
+ // the link moved us to; if the user went elsewhere on their own, leave them.
+ if (client->getStatus() == StatusLoggedIn) {
+ const bool onMigrationTarget =
+ client->serverName().compare(chain.migrationTargetHost, Qt::CaseInsensitive) == 0 &&
+ QString::number(client->serverPort()) == chain.migrationTargetPort;
+ if (!onMigrationTarget) {
+ return;
+ }
+
+ ServersSettings &servers = SettingsCache::instance().servers();
+ const int index = servers.findServerIndex(chain.previousServerHost, chain.previousServerPort);
+ if (index >= 0 && servers.hasLoginData(chain.previousServerHost, chain.previousServerPort)) {
+ const QString username =
+ servers.getValue(QString("username%1").arg(index), "server", "server_details").toString();
+ const QString password =
+ servers.getValue(QString("password%1").arg(index), "server", "server_details").toString();
+ client->connectToServer(chain.previousServerHost, chain.previousServerPort.toUInt(), username, password);
+ return;
+ }
+ client->disconnectFromServer();
+ return;
+ }
+
+ if (client->getStatus() != StatusDisconnected) {
+ return;
+ }
+
+ // The link's connection attempt failed: reconnect to the previous server
+ // when credentials are saved, otherwise stay offline.
+ ServersSettings &servers = SettingsCache::instance().servers();
+ const int index = servers.findServerIndex(chain.previousServerHost, chain.previousServerPort);
+ if (index >= 0 && servers.hasLoginData(chain.previousServerHost, chain.previousServerPort)) {
+ const QString username =
+ servers.getValue(QString("username%1").arg(index), "server", "server_details").toString();
+ const QString password =
+ servers.getValue(QString("password%1").arg(index), "server", "server_details").toString();
+ client->connectToServer(chain.previousServerHost, chain.previousServerPort.toUInt(), username, password);
+ }
+}
diff --git a/cockatrice/src/interface/intents/url_parser.h b/cockatrice/src/interface/intents/url_parser.h
index 6d705e013..ea29fed53 100644
--- a/cockatrice/src/interface/intents/url_parser.h
+++ b/cockatrice/src/interface/intents/url_parser.h
@@ -1,10 +1,46 @@
#ifndef COCKATRICE_URL_PARSER_H
#define COCKATRICE_URL_PARSER_H
+
+#include
#include
#include
+class Intent;
class MainWindow;
struct ContextJoinGame;
+
+/**
+ * @brief One queued intent chain with the session-migration bookkeeping for it.
+ *
+ * The restore fields are per-chain on purpose: chains are parsed while earlier
+ * ones are still queued, so parser-wide state would let one chain's failure
+ * consume the restore data another chain recorded.
+ */
+struct PendingIntentChain
+{
+ QList intents;
+
+ // Snapshot of the session in place when this chain started running, so a
+ // queued chain follows whichever server the chain before it settled on.
+ QString previousServerHost;
+ QString previousServerPort;
+
+ // Recorded at parse time when the user confirmed migrating away from a live
+ // session to the host/port named by the link.
+ QString migrationTargetHost;
+ QString migrationTargetPort;
+ bool pendingRestore = false;
+};
+
+/**
+ * @brief Parses cockatrice:// links and runs them as serialized intent chains.
+ *
+ * Links are parsed by action (joingame/opendeck) and translated into an intent
+ * chain. Chains are queued and run one at a time: a document can hand multiple
+ * links to the window while an earlier chain still connects, and running two
+ * connect chains concurrently tears the connection down. urlChainFinished is
+ * emitted once the queue has fully drained.
+ */
class IntentUrlParser : public QObject
{
Q_OBJECT
@@ -12,12 +48,28 @@ class IntentUrlParser : public QObject
public:
IntentUrlParser(QObject *parent, MainWindow *mainWindow);
void handle(const QString &urlStr);
- void handleJoinGame(const QUrlQuery &query);
+
+signals:
+ /** @brief Emitted when the last queued chain ended; carries whether the client is logged in. */
+ void urlChainFinished(bool connected);
private:
+ Intent *createJoinGameIntent(const QUrlQuery &query, PendingIntentChain &chain);
+ Intent *createOpenDeckIntent(const QUrlQuery &query, PendingIntentChain &chain);
QString generateJoinGameMessage(const ContextJoinGame &context, const QString &gameDescription);
+ [[nodiscard]] bool isConnectedTo(const QString &hostname, const QString &port) const;
+ void startNextChain();
+ void chainEnded(bool chainSucceeded);
+ void onChainIntentDestroyed();
+ void restorePreviousServer(const PendingIntentChain &chain);
+ void restoreToPreviousServer(const PendingIntentChain &chain);
MainWindow *mainWindow;
+ QList pendingChains;
+ bool chainRunning = false;
+ // Disconnects the destroyed-signal backstop once a chain ends, so an old
+ // intent's deferred deletion cannot end the chain that runs after it.
+ QMetaObject::Connection chainBackstopConnection;
};
#endif // COCKATRICE_URL_PARSER_H
diff --git a/cockatrice/src/interface/palette_editor/palette_editor_dialog.cpp b/cockatrice/src/interface/palette_editor/palette_editor_dialog.cpp
index 9cde72c01..d5a168708 100644
--- a/cockatrice/src/interface/palette_editor/palette_editor_dialog.cpp
+++ b/cockatrice/src/interface/palette_editor/palette_editor_dialog.cpp
@@ -1,6 +1,5 @@
#include "palette_editor_dialog.h"
-#include "../../client/settings/cache_settings.h"
#include "../theme_manager.h"
#include "palette_generator.h"
#include "palette_grid_widget.h"
@@ -11,31 +10,11 @@
#include
#include
#include
-#include
#include
-#include
#include
-#include
#include
#include
-#include
#include
-#include
-
-// Probe whether a directory is truly writable by trying to create and remove a
-// temporary file. QFileInfo::isWritable() on a directory is unreliable (notably
-// on Windows where UAC VirtualStore can make a system dir appear writable).
-static bool isDirReallyWritable(const QString &dirPath)
-{
- const QString probe = QDir(dirPath).absoluteFilePath(".cockatrice_write_test");
- QFile f(probe);
- if (!f.open(QIODevice::WriteOnly)) {
- return false;
- }
- f.close();
- f.remove();
- return true;
-}
PaletteEditorDialog::PaletteEditorDialog(const QString &_themeDirPath, const QString &_themeName, QWidget *parent)
: QDialog(parent), themeDirPath(_themeDirPath), themeName(_themeName)
@@ -46,14 +25,7 @@ PaletteEditorDialog::PaletteEditorDialog(const QString &_themeDirPath, const QSt
// Resolve a writable directory for saving. Built-in (Default / Fusion) and
// other read-only theme directories must be customised in the user-writable
// themes directory; otherwise the write would fail or be lost on upgrade.
- if (!themeDirPath.isEmpty() && isDirReallyWritable(themeDirPath)) {
- saveDir = themeDirPath;
- } else {
- saveDir = QDir(SettingsCache::instance().paths().getThemesPath()).absoluteFilePath(themeName);
- if (!QDir().mkpath(saveDir)) {
- qWarning() << "Failed to create palette save directory:" << saveDir;
- }
- }
+ saveDir = ThemeManager::writableThemeDir(themeName);
// Load both scheme configs upfront so switching is instant
loadSchemes();
@@ -214,7 +186,7 @@ void PaletteEditorDialog::retranslateUi()
resetBtn->setToolTip(tr("Discard unsaved edits and restore the last saved palette"));
saveBtn->setToolTip(tr("Write palette-%1.toml and reload the theme").arg(loadedScheme.toLower()));
- if (saveDir.isEmpty() || !isDirReallyWritable(saveDir)) {
+ if (saveDir.isEmpty() || !ThemeManager::isDirReallyWritable(saveDir)) {
saveBtn->setEnabled(false);
saveBtn->setToolTip(tr("Cannot save: this theme has no writable directory"));
}
@@ -297,7 +269,7 @@ void PaletteEditorDialog::onSave()
if (it.key() == loadedScheme) {
continue;
}
- if (it.value().colors == savedConfig.value(it.key()).colors) {
+ if (it.value() == savedConfig.value(it.key())) {
continue;
}
if (!ThemeManager::commitPalette(saveDir, it.key(), it.value())) {
@@ -308,7 +280,7 @@ void PaletteEditorDialog::onSave()
}
// Commit the active scheme last so the global colour scheme matches.
- if (workingConfig[loadedScheme].colors != savedConfig.value(loadedScheme).colors) {
+ if (workingConfig[loadedScheme] != savedConfig.value(loadedScheme)) {
if (!ThemeManager::commitPalette(saveDir, loadedScheme, workingConfig[loadedScheme])) {
QMessageBox::warning(this, tr("Save failed"),
tr("Could not write %1 to:\n%2").arg(PaletteConfig::fileName(loadedScheme), saveDir));
diff --git a/cockatrice/src/interface/palette_editor/palette_generator.cpp b/cockatrice/src/interface/palette_editor/palette_generator.cpp
index d30dd14f1..822e57250 100644
--- a/cockatrice/src/interface/palette_editor/palette_generator.cpp
+++ b/cockatrice/src/interface/palette_editor/palette_generator.cpp
@@ -150,6 +150,17 @@ PaletteConfig fromAccent(const QColor &accent, int intensity, const QString &sch
cfg.colors[CG::Disabled][CR::HighlightedText] = disText;
cfg.colors[CG::Inactive][CR::HighlightedText] = dark ? Qt::white : Qt::black;
+ // Accent: same primary hue as Highlight, so palettes derived from a
+ // QuickSetup accent always carry a matching Accent role.
+#if QT_VERSION >= QT_VERSION_CHECK(6, 6, 0)
+ set3(CR::Accent, hl, disText, hl);
+#endif
+
+ // Application role colors: Strong tracks the primary accent, while Soft is
+ // the lightened, desaturated companion used for button-gradient highlights.
+ cfg.appColors[AppColor::AccentStrong] = hl;
+ cfg.appColors[AppColor::AccentSoft] = hsl(accent.lightness() + 60, qRound(accent.hslSaturation() * 70 / 100.0));
+
// BrightText
QColor bright;
if (achromatic) {
diff --git a/cockatrice/src/interface/palette_editor/palette_grid_widget.cpp b/cockatrice/src/interface/palette_editor/palette_grid_widget.cpp
index 67294cd98..97d28b731 100644
--- a/cockatrice/src/interface/palette_editor/palette_grid_widget.cpp
+++ b/cockatrice/src/interface/palette_editor/palette_grid_widget.cpp
@@ -1,5 +1,7 @@
#include "palette_grid_widget.h"
+#include "../theme_manager.h"
+
#include
#include
#include
@@ -45,6 +47,11 @@ static const QMap ROLE_DESCRIPTIONS = {
{QPalette::Shadow, QT_TR_NOOP("Very dark shadow colour")},
};
+static const QMap APP_ROLE_DESCRIPTIONS = {
+ {AppColor::AccentStrong, QT_TR_NOOP("Vivid primary accent (e.g. home-tab button gradient start)")},
+ {AppColor::AccentSoft, QT_TR_NOOP("Lightened, desaturated accent (e.g. home-tab button gradient end)")},
+};
+
PaletteGridWidget::PaletteGridWidget(QWidget *parent) : QWidget(parent)
{
scroll = new QScrollArea(this);
@@ -122,6 +129,46 @@ void PaletteGridWidget::buildGrid(QWidget *host)
grid->addWidget(btn, row + 1, col + 1, Qt::AlignHCenter | Qt::AlignVCenter);
}
}
+
+ // Application color section: one ColorButton per role below the role grid.
+ // These are not tied to a color group, so a single button spans the row.
+ QMetaEnum appEnum = QMetaEnum::fromType();
+
+ const int appHeaderRow = roles.size() + 1;
+
+ auto *appHeader = new QLabel(tr("App colors"), host);
+ appHeader->setToolTip(tr("Application-specific colors layered on top of the Qt palette"));
+ QFont appHeaderFont = appHeader->font();
+ appHeaderFont.setBold(true);
+ appHeader->setFont(appHeaderFont);
+ appHeader->setAutoFillBackground(true);
+ appHeader->setContentsMargins(4, 4, 4, 4);
+ grid->addWidget(appHeader, appHeaderRow, 0, 1, 4);
+ headerLabels.append(appHeader);
+
+ for (int i = 0; i < appEnum.keyCount(); ++i) {
+ auto role = static_cast(appEnum.value(i));
+ const int row = appHeaderRow + 1 + i;
+
+ if (i % 2 == 0) {
+ for (int col = 0; col < 4; ++col) {
+ auto *shade = new QWidget(host);
+ shade->setAutoFillBackground(true);
+ grid->addWidget(shade, row, col);
+ rowShadeWidgets.push_back(shade);
+ }
+ }
+
+ auto *label = new QLabel(QString(appEnum.valueToKey(role)), host);
+ label->setToolTip(APP_ROLE_DESCRIPTIONS.value(role, {}));
+ label->setContentsMargins(4, 2, 8, 2);
+ grid->addWidget(label, row, 0);
+
+ auto *btn = new ColorButton(host);
+ connect(btn, &ColorButton::colorChanged, this, [this] { emit paletteChanged(); });
+ appColorButtons[role] = btn;
+ grid->addWidget(btn, row, 1, Qt::AlignHCenter | Qt::AlignVCenter);
+ }
}
void PaletteGridWidget::changeEvent(QEvent *e)
@@ -166,6 +213,16 @@ void PaletteGridWidget::loadPalette(const PaletteConfig &cfg)
colorButtons[group][role]->setColor(color);
}
}
+
+ QMetaEnum appEnum = QMetaEnum::fromType();
+ for (int i = 0; i < appEnum.keyCount(); ++i) {
+ auto role = static_cast(appEnum.value(i));
+ QColor color = cfg.appColors.value(role);
+ if (!color.isValid()) {
+ color = themeManager->appColor(role);
+ }
+ appColorButtons[role]->setColor(color);
+ }
}
PaletteConfig PaletteGridWidget::currentPaletteConfig() const
@@ -176,5 +233,12 @@ PaletteConfig PaletteGridWidget::currentPaletteConfig() const
cfg.colors[group][role] = colorButtons[group][role]->getColor();
}
}
+
+ QMetaEnum appEnum = QMetaEnum::fromType();
+ for (int i = 0; i < appEnum.keyCount(); ++i) {
+ auto role = static_cast(appEnum.value(i));
+ cfg.appColors[role] = appColorButtons[role]->getColor();
+ }
+
return cfg;
}
\ No newline at end of file
diff --git a/cockatrice/src/interface/palette_editor/palette_grid_widget.h b/cockatrice/src/interface/palette_editor/palette_grid_widget.h
index 1a665971a..77cbf1c62 100644
--- a/cockatrice/src/interface/palette_editor/palette_grid_widget.h
+++ b/cockatrice/src/interface/palette_editor/palette_grid_widget.h
@@ -31,6 +31,7 @@ private:
void refreshChromePalettes();
QMap> colorButtons;
+ QMap appColorButtons;
QScrollArea *scroll;
QWidget *gridHost;
QVBoxLayout *layout;
diff --git a/cockatrice/src/interface/pixel_map_generator.cpp b/cockatrice/src/interface/pixel_map_generator.cpp
index 9b8c4bcdc..b70dc576f 100644
--- a/cockatrice/src/interface/pixel_map_generator.cpp
+++ b/cockatrice/src/interface/pixel_map_generator.cpp
@@ -1,5 +1,7 @@
#include "pixel_map_generator.h"
+#include "theme_manager.h"
+
#include
#include
#include
@@ -82,7 +84,13 @@ static QPixmap loadSvg(const QString &svgPath, const QSize &size, bool expandOnl
/**
* Try to load path image from non-SVG formats, otherwise fall back to SVG.
* This is to allow custom themes to support non-SVG format type overrides, since SVG requires custom loading.
- * @param path The path to the file, with no file extension. File formats will be automatically detected.
+ *
+ * The path may already carry the resolved file extension (e.g. via
+ * ThemeManager::assetPath); such paths are loaded directly. Otherwise a
+ * format-agnostic lookup probes png, jpg and finally svg.
+ *
+ * @param path The path to the file, with no file extension unless the caller
+ * already resolved it. File formats will be automatically detected.
* @param size The desired size of the pixmap.
* @param expandOnly If true, then keep the size of the initial pixmap to at least the size (Only relevant if SVG).
*
@@ -90,6 +98,19 @@ static QPixmap loadSvg(const QString &svgPath, const QSize &size, bool expandOnl
*/
static QPixmap tryLoadImage(const QString &path, const QSize &size, bool expandOnly = false)
{
+ if (path.endsWith(QLatin1String(".svg"), Qt::CaseInsensitive)) {
+ return loadSvg(path, size, expandOnly);
+ }
+ if (path.endsWith(QLatin1String(".png"), Qt::CaseInsensitive) ||
+ path.endsWith(QLatin1String(".jpg"), Qt::CaseInsensitive) ||
+ path.endsWith(QLatin1String(".jpeg"), Qt::CaseInsensitive)) {
+ QPixmap pix(path);
+ if (!pix.isNull()) {
+ return pix.scaled(size, Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ }
+ return {};
+ }
+
const auto formats = {"png", "jpg"};
QPixmap returnPixmap;
@@ -111,7 +132,8 @@ QPixmap PhasePixmapGenerator::generatePixmap(int height, QString name)
return pmCache.value(key);
}
- QPixmap pixmap = tryLoadImage("theme:phases/" + name, QSize(height, height));
+ QPixmap pixmap = tryLoadImage(QStringLiteral("theme:") + themeManager->assetPath(QStringLiteral("phases/") + name),
+ QSize(height, height));
pmCache.insert(key, pixmap);
return pixmap;
@@ -339,6 +361,10 @@ static QString getIconType(const bool isBuddy, const UserLevelFlags &userLevelFl
return "pawn_judge";
}
+ if (userLevelFlags.testFlag(ServerInfo_User::IsDeveloper)) {
+ return "pawn_dev";
+ }
+
if (!privLevel.isEmpty() && privLevel.toLower() != "none") {
return QString("pawn_%1").arg(privLevel.toLower());
}
@@ -396,7 +422,8 @@ QPixmap LockPixmapGenerator::generatePixmap(int height)
return pmCache.value(key);
}
- QPixmap pixmap = tryLoadImage("theme:icons/lock", QSize(height, height), true);
+ QPixmap pixmap = tryLoadImage(QStringLiteral("theme:") + themeManager->assetPath(QStringLiteral("icons/lock")),
+ QSize(height, height), true);
pmCache.insert(key, pixmap);
return pixmap;
}
@@ -411,7 +438,8 @@ QPixmap DropdownIconPixmapGenerator::generatePixmap(int height, bool expanded)
}
QString name = expanded ? "dropdown_expanded" : "dropdown_collapsed";
- QPixmap pixmap = tryLoadImage("theme:icons/" + name, QSize(height, height), true);
+ QPixmap pixmap = tryLoadImage(QStringLiteral("theme:") + themeManager->assetPath(QStringLiteral("icons/") + name),
+ QSize(height, height), true);
pmCache.insert(key, pixmap);
return pixmap;
@@ -472,6 +500,13 @@ QHash ManaSymbolPixmapGenerator::scaledCache;
QPixmap loadColorAdjustedPixmap(const QString &name)
{
+ // Prefer an authored scheme-qualified variant when one exists for this asset.
+ const QString variant = themeManager->schemeVariantPath(QStringView(name).mid(QStringLiteral("theme:").size()));
+ if (!variant.isEmpty()) {
+ return QPixmap(QStringLiteral("theme:") + variant);
+ }
+
+ // Legacy fallback: runtime-invert for dark mode when no authored variant.
if (qApp->palette().windowText().color().lightness() > 200) {
QImage img(name);
img.invertPixels();
@@ -482,3 +517,21 @@ QPixmap loadColorAdjustedPixmap(const QString &name)
return QPixmap(name);
}
}
+
+QPixmap themePixmap(QStringView prefix)
+{
+ const QString resolved = themeManager->assetPath(prefix);
+ return QPixmap(QStringLiteral("theme:") + resolved);
+}
+
+void clearPixmapGeneratorCaches()
+{
+ PhasePixmapGenerator::clear();
+ CounterPixmapGenerator::clear();
+ PingPixmapGenerator::clear();
+ CountryPixmapGenerator::clear();
+ UserLevelPixmapGenerator::clear();
+ LockPixmapGenerator::clear();
+ DropdownIconPixmapGenerator::clear();
+ ManaSymbolPixmapGenerator::clear();
+}
diff --git a/cockatrice/src/interface/pixel_map_generator.h b/cockatrice/src/interface/pixel_map_generator.h
index 17720166a..b6e822fd9 100644
--- a/cockatrice/src/interface/pixel_map_generator.h
+++ b/cockatrice/src/interface/pixel_map_generator.h
@@ -156,4 +156,15 @@ public:
QPixmap loadColorAdjustedPixmap(const QString &name);
+// Loads a "theme:" asset (with no file extension in prefix), preferring the
+// scheme-qualified variant (prefix-dark / prefix-light, resolved via
+// ThemeManager::assetPath) and falling back to the plain asset. Callers load
+// the returned path directly. Use for scheme-sensitive pixmaps like
+// backgrounds, the card back, and the app logo.
+QPixmap themePixmap(QStringView prefix);
+
+// Clears every PixmapGenerator's static cache so scheme variants are
+// re-resolved when the active theme or color scheme changes.
+void clearPixmapGeneratorCaches();
+
#endif
diff --git a/cockatrice/src/interface/theme_config.cpp b/cockatrice/src/interface/theme_config.cpp
index 3c43c467d..8293a82cf 100644
--- a/cockatrice/src/interface/theme_config.cpp
+++ b/cockatrice/src/interface/theme_config.cpp
@@ -16,7 +16,7 @@ QString ThemeConfig::toIni() const
out += "[Appearance]\n";
out += QString("ColorScheme = %1\n").arg(colorScheme.isEmpty() ? "System" : colorScheme);
out += "\n[Style]\n";
- out += QString("Name = %1\n").arg(styleName.isEmpty() ? "Default" : styleName);
+ out += QString("Name = %1\n").arg(styleName.isEmpty() ? "System" : styleName);
return out;
}
@@ -96,7 +96,7 @@ bool ThemeConfig::save(const QString &themeDirPath) const
bool PaletteConfig::hasPalette() const
{
- return !colors.isEmpty();
+ return !colors.isEmpty() || !appColors.isEmpty();
}
QString PaletteConfig::toToml() const
@@ -133,6 +133,24 @@ QString PaletteConfig::toToml() const
out += "\n";
}
+ if (!appColors.isEmpty()) {
+ QMetaEnum appEnum = QMetaEnum::fromType();
+
+ out += "[AppColors]\n";
+
+ for (auto it = appColors.cbegin(); it != appColors.cend(); ++it) {
+ const char *roleName = appEnum.valueToKey(it.key());
+
+ if (!roleName) {
+ continue;
+ }
+
+ out += QString("%1 = %2\n").arg(QString(roleName), -20).arg(it.value().name(QColor::HexArgb));
+ }
+
+ out += "\n";
+ }
+
return out;
}
@@ -152,6 +170,7 @@ PaletteConfig PaletteConfig::fromFile(const QString &filePath)
}
QMetaEnum roleEnum = QMetaEnum::fromType();
+ QMetaEnum appEnum = QMetaEnum::fromType();
QString currentSection;
QPalette::ColorGroup currentGroup = QPalette::Active;
@@ -202,6 +221,26 @@ PaletteConfig PaletteConfig::fromFile(const QString &filePath)
}
}
+ QColor color(value);
+
+ if (!color.isValid()) {
+ continue;
+ }
+
+ if (currentSection.compare("AppColors", Qt::CaseInsensitive) == 0) {
+ if (key.startsWith("AppColor::")) {
+ key = key.mid(10);
+ }
+
+ int appRoleInt = appEnum.keyToValue(key.toUtf8().constData());
+
+ if (appRoleInt >= 0) {
+ cfg.appColors[static_cast(appRoleInt)] = color;
+ }
+
+ continue;
+ }
+
if (!currentSection.startsWith("Palette", Qt::CaseInsensitive)) {
continue;
}
@@ -216,11 +255,7 @@ PaletteConfig PaletteConfig::fromFile(const QString &filePath)
continue;
}
- QColor color(value);
-
- if (color.isValid()) {
- cfg.colors[currentGroup][static_cast(roleInt)] = color;
- }
+ cfg.colors[currentGroup][static_cast(roleInt)] = color;
}
return cfg;
diff --git a/cockatrice/src/interface/theme_config.h b/cockatrice/src/interface/theme_config.h
index 07bf55b7a..567aeccda 100644
--- a/cockatrice/src/interface/theme_config.h
+++ b/cockatrice/src/interface/theme_config.h
@@ -3,9 +3,25 @@
#include
#include
+#include
#include
#include
+// Application-specific color roles, layered on top of the fixed QPalette role
+// set. Stored in the same palette-.toml under an [AppColors] section
+// and editable from the palette editor, so theme authors can control colors
+// beyond what Qt's palette can express.
+namespace AppColor
+{
+Q_NAMESPACE
+enum Role
+{
+ AccentStrong,
+ AccentSoft,
+};
+Q_ENUM_NS(Role)
+} // namespace AppColor
+
struct ThemeConfig
{
QString colorScheme;
@@ -21,7 +37,16 @@ struct ThemeConfig
struct PaletteConfig
{
QMap> colors;
+ QMap appColors;
+ bool operator==(const PaletteConfig &rhs) const
+ {
+ return colors == rhs.colors && appColors == rhs.appColors;
+ }
+ bool operator!=(const PaletteConfig &rhs) const
+ {
+ return !(*this == rhs);
+ }
bool hasPalette() const;
QString toToml() const;
diff --git a/cockatrice/src/interface/theme_manager.cpp b/cockatrice/src/interface/theme_manager.cpp
index e6b4b3c7f..d86ed77f9 100644
--- a/cockatrice/src/interface/theme_manager.cpp
+++ b/cockatrice/src/interface/theme_manager.cpp
@@ -1,10 +1,13 @@
#include "theme_manager.h"
#include "../../client/settings/cache_settings.h"
+#include "pixel_map_generator.h"
#include
#include
#include
+#include
+#include
#include
#include
#include
@@ -19,7 +22,7 @@
#include
#include
-#define NONE_THEME_NAME "Default"
+#define SYSTEM_THEME_NAME "System"
#define FUSION_THEME_NAME "Fusion"
#define STYLE_CSS_NAME "style.css"
#define HANDZONE_BG_NAME "handzone"
@@ -93,7 +96,7 @@ struct PaletteColorInfo
static QString usableDefaultStyle(const QString &style)
{
// The Windows 11 native style is broken: when the OS default
- // ("Default" theme selection) would use it, fall back to the Vista style.
+ // ("System" theme selection) would use it, fall back to the Vista style.
// Explicitly choosing "windows11" in a theme is still honored.
return style.compare("windows11", Qt::CaseInsensitive) == 0 ? QStringLiteral("windowsvista") : style;
}
@@ -116,10 +119,16 @@ ThemeManager::ThemeManager(QObject *parent) : QObject(parent)
void ThemeManager::ensureThemeDirectoryExists()
{
- if (SettingsCache::instance().getThemeName().isEmpty() ||
- !getAvailableThemes().contains(SettingsCache::instance().getThemeName())) {
+ auto &settings = SettingsCache::instance();
+
+ // Migrate the old "Default" theme name to "System"
+ if (settings.getThemeName() == "Default") {
+ settings.setThemeName(SYSTEM_THEME_NAME);
+ }
+
+ if (settings.getThemeName().isEmpty() || !getAvailableThemes().contains(settings.getThemeName())) {
qCInfo(ThemeManagerLog) << "Theme name not set, setting default value";
- SettingsCache::instance().setThemeName(NONE_THEME_NAME);
+ settings.setThemeName(FUSION_THEME_NAME);
}
}
@@ -140,11 +149,74 @@ bool ThemeManager::isDarkMode(const QString &themeDirPath) const
}
}
-bool ThemeManager::isBuiltInTheme()
+QString ThemeManager::schemeVariantPath(QStringView prefix) const
{
- const auto themeName = SettingsCache::instance().getThemeName();
+ static const QStringList formats = {QStringLiteral(".png"), QStringLiteral(".jpg"), QStringLiteral(".jpeg"),
+ QStringLiteral(".svg")};
+ const QString scheme = isDarkMode(currentThemePath) ? QStringLiteral("dark") : QStringLiteral("light");
+ const QString variantStem = prefix.toString() + QLatin1Char('-') + scheme;
- return themeName == NONE_THEME_NAME || themeName == FUSION_THEME_NAME;
+ for (const QString &format : formats) {
+ if (QFileInfo::exists(QStringLiteral("theme:") + variantStem + format)) {
+ return variantStem + format;
+ }
+ }
+ return QString();
+}
+
+QString ThemeManager::assetPath(QStringView prefix) const
+{
+ // Probe order mirrors tryLoadImage: a theme may override the default SVG
+ // with a raster of the same stem, so raster wins over SVG within a stem.
+ static const QStringList formats = {QStringLiteral(".png"), QStringLiteral(".jpg"), QStringLiteral(".jpeg"),
+ QStringLiteral(".svg")};
+
+ auto findExisting = [](const QString &stem) {
+ for (const QString &format : formats) {
+ if (QFileInfo::exists(QStringLiteral("theme:") + stem + format)) {
+ return stem + format;
+ }
+ }
+ return QString();
+ };
+
+ // Prefer the scheme-qualified variant when it exists, else the plain
+ // asset as the super fallback. Both return the resolved path including
+ // its file extension so callers can load it directly.
+ const QString variant = schemeVariantPath(prefix);
+ if (!variant.isEmpty()) {
+ return variant;
+ }
+ const QString resolvedPlain = findExisting(prefix.toString());
+ return resolvedPlain.isEmpty() ? prefix.toString() : resolvedPlain;
+}
+
+// Probe whether a directory is truly writable by trying to create and remove a
+// temporary file. QFileInfo::isWritable() on a directory is unreliable (notably
+// on Windows where UAC VirtualStore can make a system dir appear writable).
+bool ThemeManager::isDirReallyWritable(const QString &dirPath)
+{
+ const QString probe = QDir(dirPath).absoluteFilePath(".cockatrice_write_test");
+ QFile f(probe);
+ if (!f.open(QIODevice::WriteOnly)) {
+ return false;
+ }
+ f.close();
+ f.remove();
+ return true;
+}
+
+QString ThemeManager::writableThemeDir(const QString &themeName)
+{
+ // All theme writes go to the user themes directory regardless of whether
+ // the resolved (system) theme directory happens to be writable. Even when a
+ // write would succeed in-place, routing it to the user directory keeps the
+ // install intact and guarantees changes survive upgrades.
+ const QString dirPath = QDir(SettingsCache::instance().paths().getThemesPath()).absoluteFilePath(themeName);
+ if (!QDir().mkpath(dirPath)) {
+ qWarning() << "Failed to create theme save directory:" << dirPath;
+ }
+ return dirPath;
}
// System (read-only) themes location, relative to the application binary.
@@ -169,9 +241,7 @@ QStringMap &ThemeManager::getAvailableThemes()
// load themes from user profile dir
dir.setPath(SettingsCache::instance().paths().getThemesPath());
- // add default value
- availableThemes.insert(NONE_THEME_NAME, dir.absoluteFilePath("Default"));
-
+ availableThemes.insert(SYSTEM_THEME_NAME, dir.absoluteFilePath("System"));
availableThemes.insert(FUSION_THEME_NAME, dir.absoluteFilePath("Fusion"));
for (QString themeName : dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) {
@@ -180,7 +250,7 @@ QStringMap &ThemeManager::getAvailableThemes()
}
}
- // load themes from cockatrice system dir
+ // Load themes from Cockatrice system dir
dir.setPath(systemThemesBasePath());
for (QString themeName : dir.entryList(QDir::AllDirs | QDir::NoDotAndDotDot, QDir::Name)) {
@@ -195,7 +265,7 @@ QStringMap &ThemeManager::getAvailableThemes()
QBrush ThemeManager::loadBrush(QString fileName, QColor fallbackColor)
{
QBrush brush;
- QPixmap tmp = QPixmap("theme:zones/" + fileName);
+ QPixmap tmp = QPixmap("theme:" + assetPath(QStringLiteral("zones/") + fileName));
if (tmp.isNull()) {
brush.setColor(fallbackColor);
brush.setStyle(Qt::SolidPattern);
@@ -209,7 +279,7 @@ QBrush ThemeManager::loadBrush(QString fileName, QColor fallbackColor)
QBrush ThemeManager::loadExtraBrush(QString fileName, QBrush &fallbackBrush)
{
QBrush brush;
- QPixmap tmp = QPixmap("theme:zones/" + fileName);
+ QPixmap tmp = QPixmap("theme:" + assetPath(QStringLiteral("zones/") + fileName));
if (tmp.isNull()) {
brush = fallbackBrush;
@@ -287,7 +357,7 @@ bool ThemeManager::commitPalette(const QString &themeDirPath, const QString &col
void ThemeManager::setColorScheme(const QString &scheme)
{
- const QString dirPath = getAvailableThemes().value(SettingsCache::instance().getThemeName());
+ const QString dirPath = writableThemeDir(SettingsCache::instance().getThemeName());
ThemeConfig cfg = ThemeConfig::fromThemeDir(dirPath);
cfg.colorScheme = scheme;
@@ -298,7 +368,7 @@ void ThemeManager::setColorScheme(const QString &scheme)
void ThemeManager::setStyleName(const QString &styleName)
{
- const QString dirPath = getAvailableThemes().value(SettingsCache::instance().getThemeName());
+ const QString dirPath = writableThemeDir(SettingsCache::instance().getThemeName());
ThemeConfig cfg = ThemeConfig::fromThemeDir(dirPath);
cfg.styleName = styleName;
@@ -329,7 +399,7 @@ void ThemeManager::applyStyleAndPalette(const QString &themeName,
Q_UNUSED(activeScheme)
#endif
QString styleName = themeCfg.styleName;
- if (styleName.isEmpty() || styleName.compare("Default", Qt::CaseInsensitive) == 0) {
+ if (styleName.isEmpty() || styleName.compare("System", Qt::CaseInsensitive) == 0) {
if (themeName == FUSION_THEME_NAME) {
styleName = "Fusion";
} else {
@@ -372,6 +442,8 @@ void ThemeManager::applyStyleAndPalette(const QString &themeName,
qApp->setPalette(base);
qApp->setStyle(style);
+ currentAppColors = palCfg.appColors;
+
// Force every widget to re-polish and repaint immediately rather than
// waiting for natural expose events, which produces a patchwork of old
// and new colours during a live preview.
@@ -384,6 +456,35 @@ void ThemeManager::applyStyleAndPalette(const QString &themeName,
style->polish(widget);
widget->update();
}
+
+ emit paletteChanged();
+}
+
+QColor ThemeManager::appColor(AppColor::Role role) const
+{
+ const auto it = currentAppColors.constFind(role);
+ if (it != currentAppColors.constEnd()) {
+ return it.value();
+ }
+
+ // QPalette::Accent was introduced in Qt 6.6 and several shipped palettes
+ // set it to a value barely distinguishable from Window, so it is not a
+ // reliable accent source. The selection highlight is the stable accent
+ // (Accent defaults to Highlight when unset), and deriving from it
+ // unconditionally keeps every Qt version rendering identically.
+ const QColor accent = qApp->palette().color(QPalette::Active, QPalette::Highlight);
+
+ if (role == AppColor::AccentSoft) {
+ constexpr int SOFT_SATURATION_PERCENT = 70;
+ constexpr int SOFT_LIGHTNESS_OFFSET = 60;
+
+ // Light end of the gradient: same hue, softened and lightened
+ return QColor::fromHsl(qMax(0, accent.hslHue()),
+ qBound(0, qRound(accent.hslSaturation() * SOFT_SATURATION_PERCENT / 100.0), 255),
+ qBound(0, accent.lightness() + SOFT_LIGHTNESS_OFFSET, 255));
+ }
+
+ return accent;
}
void ThemeManager::themeChangedSlot()
@@ -393,9 +494,19 @@ void ThemeManager::themeChangedSlot()
currentThemePath = dirPath;
QDir dir(dirPath);
- // CSS
- if (!dirPath.isEmpty() && dir.exists(STYLE_CSS_NAME)) {
- qApp->setStyleSheet("file:///" + dir.absoluteFilePath(STYLE_CSS_NAME));
+ // CSS — prefer the scheme-qualified stylesheet (style-dark.css /
+ // style-light.css) when present, else the plain style.css as fallback.
+ if (!dirPath.isEmpty()) {
+ const QString scheme = isDarkMode(dirPath) ? QStringLiteral("dark") : QStringLiteral("light");
+ const QString schemeCss = QFileInfo(QStringLiteral(STYLE_CSS_NAME)).completeBaseName() + QLatin1Char('-') +
+ scheme + QStringLiteral(".css");
+ if (dir.exists(schemeCss)) {
+ qApp->setStyleSheet("file:///" + dir.absoluteFilePath(schemeCss));
+ } else if (dir.exists(STYLE_CSS_NAME)) {
+ qApp->setStyleSheet("file:///" + dir.absoluteFilePath(STYLE_CSS_NAME));
+ } else {
+ qApp->setStyleSheet("");
+ }
} else {
qApp->setStyleSheet("");
}
@@ -410,8 +521,19 @@ void ThemeManager::themeChangedSlot()
// ── Load palette: custom first, then theme default ────────────────────
PaletteConfig palette = PaletteConfig::fromScheme(dirPath, activeScheme);
- if (!palette.hasPalette()) {
- palette = ThemeManager::loadDefaultPaletteConfig(dirPath, themeName, activeScheme);
+ const PaletteConfig themeDefault = ThemeManager::loadDefaultPaletteConfig(dirPath, themeName, activeScheme);
+ if (palette.hasPalette()) {
+ // A custom palette written before [AppColors] existed carries no app
+ // colors; merge the theme's shipped defaults so the identity colors
+ // survive (hasPalette() counts an app-colors-only file as a palette,
+ // so those are kept wholesale and never reach here empty).
+ for (auto it = themeDefault.appColors.cbegin(); it != themeDefault.appColors.cend(); ++it) {
+ if (!palette.appColors.contains(it.key())) {
+ palette.appColors.insert(it.key(), it.value());
+ }
+ }
+ } else {
+ palette = themeDefault;
}
applyStyleAndPalette(themeName, themeCfg, palette, activeScheme);
@@ -446,6 +568,7 @@ void ThemeManager::themeChangedSlot()
}
QPixmapCache::clear();
+ clearPixmapGeneratorCaches();
emit themeChanged();
}
diff --git a/cockatrice/src/interface/theme_manager.h b/cockatrice/src/interface/theme_manager.h
index 79a1b6470..aadb38ee9 100644
--- a/cockatrice/src/interface/theme_manager.h
+++ b/cockatrice/src/interface/theme_manager.h
@@ -50,6 +50,7 @@ private:
QString currentThemePath;
std::array brushes;
QStringMap availableThemes;
+ QMap currentAppColors;
/*
Internal cache for multiple backgrounds
*/
@@ -65,7 +66,16 @@ protected:
const QString &activeScheme);
public:
- bool isBuiltInTheme();
+ // Resolves the directory to write theme changes to for the given theme
+ // name. The resolved theme dir (user or system) is used when writable;
+ // read-only system themes fall back to the user themes directory, creating
+ // it if needed, so customisations never get lost on upgrade.
+ static QString writableThemeDir(const QString &themeName);
+ // Probe whether a directory is truly writable by trying to create and remove
+ // a temporary file. QFileInfo::isWritable() on a directory is unreliable
+ // (notably on Windows where UAC VirtualStore can make a system dir appear
+ // writable).
+ static bool isDirReallyWritable(const QString &dirPath);
// Explicit color scheme of the theme: theme.cfg's ColorScheme setting
// (Dark/Light), falling back to the OS color scheme when it is "System".
bool isDarkMode(const QString &themeDirPath) const;
@@ -87,6 +97,20 @@ public:
// Load/save per-scheme palette colors
static PaletteConfig loadPaletteConfig(const QString &themeDirPath, const QString &colorScheme);
static bool savePaletteConfig(const QString &themeDirPath, const QString &colorScheme, const PaletteConfig &cfg);
+ // Resolve prefix to a scheme-qualified "theme:" path. Existence is probed
+ // internally across the formats themes may ship (.png/.jpg/.svg), so
+ // callers load the returned path directly. Prefers "-"
+ // when a file exists at that stem, otherwise the plain "" as the
+ // super fallback. The resolved scheme covers explicit light/dark as well
+ // as OS-resolved "system". Returns the path with its file extension when a
+ // match is found; unqualified assets keep working unchanged.
+ QString assetPath(QStringView prefix) const;
+ // Like assetPath, but resolves only the scheme-qualified variant
+ // ("-.") and returns an empty string when no
+ // variant exists — it never falls back to the plain "" asset.
+ // Callers that must distinguish "no authored variant" (e.g. to keep a
+ // legacy runtime fallback alive) should use this instead of assetPath.
+ QString schemeVariantPath(QStringView prefix) const;
// Load the theme's shipped default palette, falling back to the system
// theme directory when it is absent from the resolved (user) directory.
static PaletteConfig
@@ -101,12 +125,17 @@ public:
void reloadCurrentTheme();
void previewPalette(const PaletteConfig &cfg, const QString &scheme);
+ // Resolves an application color role: the theme's stored [AppColors] value
+ // when present, otherwise a palette-accent-derived fallback.
+ QColor appColor(AppColor::Role role) const;
+
QBrush &getBgBrush(Role zone);
QBrush getExtraBgBrush(Role zone, int zoneId = 0);
protected slots:
void themeChangedSlot();
signals:
void themeChanged();
+ void paletteChanged();
};
extern ThemeManager *themeManager;
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 1ea1bcb10..2199faf30 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
@@ -85,7 +85,7 @@ void ColorIdentityWidget::resizeEvent(QResizeEvent *event)
}
lastWidth = totalWidth;
- const int totalHeight = totalWidth / 6; // Set height to 1/4 of the width
+ const int totalHeight = qMax(0, totalWidth / 6); // Set height to 1/4 of the width
setFixedHeight(totalHeight);
const int count = layout->count();
@@ -97,6 +97,10 @@ void ColorIdentityWidget::resizeEvent(QResizeEvent *event)
const int availableWidth = totalWidth - (spacing * (count - 1));
const int iconSize = qMin(availableWidth / count, totalHeight); // Ensure icons fit within the new height
+ if (iconSize <= 0) {
+ lastIconSize = iconSize;
+ return;
+ }
if (iconSize == lastIconSize) {
return;
}
diff --git a/cockatrice/src/interface/widgets/cards/additional_info/deck_color_identity.cpp b/cockatrice/src/interface/widgets/cards/additional_info/deck_color_identity.cpp
new file mode 100644
index 000000000..62b01511e
--- /dev/null
+++ b/cockatrice/src/interface/widgets/cards/additional_info/deck_color_identity.cpp
@@ -0,0 +1,37 @@
+#include "deck_color_identity.h"
+
+#include
+#include
+#include
+#include
+
+QString getDeckColorIdentity(const DeckList &deck, const CardDatabaseQuerier *db)
+{
+ const QStringList cardList = deck.getCardList({DECK_ZONE_MAIN, DECK_ZONE_SIDE});
+ if (cardList.isEmpty()) {
+ return {};
+ }
+
+ QSet colorSet; // A set to collect unique color symbols (e.g., W, U, B, R, G)
+
+ for (const QString &cardName : cardList) {
+ CardInfoPtr currentCard = db->getCardInfo(cardName);
+ if (currentCard) {
+ const QString colors = currentCard->getColors(); // returns something like "WUB"
+ for (const QChar &color : colors) {
+ colorSet.insert(color);
+ }
+ }
+ }
+
+ // Ensure the color identity is in WUBRG order
+ QString colorIdentity;
+ const QString wubrgOrder = "WUBRG";
+ for (const QChar &color : wubrgOrder) {
+ if (colorSet.contains(color)) {
+ colorIdentity.append(color);
+ }
+ }
+
+ return colorIdentity;
+}
diff --git a/cockatrice/src/interface/widgets/cards/additional_info/deck_color_identity.h b/cockatrice/src/interface/widgets/cards/additional_info/deck_color_identity.h
new file mode 100644
index 000000000..04294cb1c
--- /dev/null
+++ b/cockatrice/src/interface/widgets/cards/additional_info/deck_color_identity.h
@@ -0,0 +1,20 @@
+#ifndef COCKATRICE_DECK_COLOR_IDENTITY_H
+#define COCKATRICE_DECK_COLOR_IDENTITY_H
+
+#include
+
+class CardDatabaseQuerier;
+class DeckList;
+
+/**
+ * @brief Computes the color identity of a deck (e.g. "WUBRG") from the color
+ * symbols of all cards in the main deck and sideboard, ordered WUBRG.
+ *
+ * Shared as a free function so the deck storage previews and the deck share
+ * dialog compute identities identically.
+ *
+ * @param db Card database used to look up card color symbols.
+ */
+QString getDeckColorIdentity(const DeckList &deck, const CardDatabaseQuerier *db);
+
+#endif // COCKATRICE_DECK_COLOR_IDENTITY_H
diff --git a/cockatrice/src/interface/widgets/cards/card_art_utils.cpp b/cockatrice/src/interface/widgets/cards/card_art_utils.cpp
new file mode 100644
index 000000000..b26b73593
--- /dev/null
+++ b/cockatrice/src/interface/widgets/cards/card_art_utils.cpp
@@ -0,0 +1,18 @@
+#include "card_art_utils.h"
+
+#include
+#include
+
+namespace CardArtUtils
+{
+QPixmap rotateSidewaysLayoutArt(const QPixmap &art, const ExactCard &card)
+{
+ if (!card.getInfo().getUiAttributes().landscapeOrientation) {
+ return art;
+ }
+
+ QTransform transform;
+ transform.rotate(90);
+ return art.transformed(transform, Qt::SmoothTransformation);
+}
+} // namespace CardArtUtils
\ No newline at end of file
diff --git a/cockatrice/src/interface/widgets/cards/card_art_utils.h b/cockatrice/src/interface/widgets/cards/card_art_utils.h
new file mode 100644
index 000000000..5c331a12c
--- /dev/null
+++ b/cockatrice/src/interface/widgets/cards/card_art_utils.h
@@ -0,0 +1,25 @@
+#ifndef CARD_ART_UTILS_H
+#define CARD_ART_UTILS_H
+
+#include
+
+class ExactCard;
+
+namespace CardArtUtils
+{
+/**
+ * @brief Rotates a card's art upright when its layout shows sideways.
+ *
+ * Sideways-layout cards (planes, sieges/battles, split cards) store their
+ * landscape artwork rotated 90° inside a portrait frame. Art-crop displays,
+ * playmat art, and the card-info picture must show such art upright before
+ * sampling or painting. Portrait cards are returned unchanged.
+ *
+ * @param art The card pixmap to orient.
+ * @param card The card describing the art orientation.
+ * @return @p art rotated 90° clockwise for sideways-layout cards, else @p art.
+ */
+QPixmap rotateSidewaysLayoutArt(const QPixmap &art, const ExactCard &card);
+} // namespace CardArtUtils
+
+#endif // CARD_ART_UTILS_H
\ No newline at end of file
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 79ae087d7..2dd21e78a 100644
--- a/cockatrice/src/interface/widgets/cards/card_info_picture_widget.cpp
+++ b/cockatrice/src/interface/widgets/cards/card_info_picture_widget.cpp
@@ -5,6 +5,7 @@
#include "../../../interface/card_picture_loader/card_picture_loader.h"
#include "../../../interface/widgets/tabs/tab_supervisor.h"
#include "../../window_main.h"
+#include "card_art_utils.h"
#include
#include
@@ -73,6 +74,8 @@ CardInfoPictureWidget::CardInfoPictureWidget(QWidget *parent, const bool _hoverT
update();
});
+ connect(&SettingsCache::instance().cardsDisplay(), &CardsDisplaySettings::cardLangChanged, this,
+ &CardInfoPictureWidget::updatePixmap);
}
/**
@@ -193,12 +196,7 @@ void CardInfoPictureWidget::paintEvent(QPaintEvent *event)
QPixmap transformedPixmap = resizedPixmap; // Default pixmap
if (SettingsCache::instance().cardsDisplay().getAutoRotateSidewaysLayoutCards()) {
- if (exactCard.getInfo().getUiAttributes().landscapeOrientation) {
- // Rotate pixmap 90 degrees to the left
- QTransform transform;
- transform.rotate(90);
- transformedPixmap = resizedPixmap.transformed(transform, Qt::SmoothTransformation);
- }
+ transformedPixmap = CardArtUtils::rotateSidewaysLayoutArt(resizedPixmap, exactCard);
}
// Handle DPI scaling
diff --git a/cockatrice/src/interface/widgets/cards/card_info_picture_with_text_overlay_widget.cpp b/cockatrice/src/interface/widgets/cards/card_info_picture_with_text_overlay_widget.cpp
index c5cb59b3b..000a88b2f 100644
--- a/cockatrice/src/interface/widgets/cards/card_info_picture_with_text_overlay_widget.cpp
+++ b/cockatrice/src/interface/widgets/cards/card_info_picture_with_text_overlay_widget.cpp
@@ -133,12 +133,14 @@ void CardInfoPictureWithTextOverlayWidget::paintEvent(QPaintEvent *event)
path.addRoundedRect(glowRect, radius, radius);
// Soft outer glow
- QColor glowColor(0, 150, 255, 80); // subtle blu
+ QColor glowColor = palette().color(QPalette::Highlight);
+ glowColor.setAlpha(80);
painter.setPen(QPen(glowColor, 6));
painter.drawPath(path);
// Thin inner border for crispness
- QColor borderColor(0, 150, 255, 200);
+ QColor borderColor = palette().color(QPalette::Highlight);
+ borderColor.setAlpha(200);
painter.setPen(QPen(borderColor, 2));
painter.drawRoundedRect(pixmapRect, radius, radius);
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 c6af5320b..e98c3c02a 100644
--- a/cockatrice/src/interface/widgets/cards/card_info_text_widget.cpp
+++ b/cockatrice/src/interface/widgets/cards/card_info_text_widget.cpp
@@ -1,6 +1,7 @@
#include "card_info_text_widget.h"
#include "../../../game_graphics/board/card_item.h"
+#include "../../card_localization.h"
#include
#include
@@ -10,7 +11,7 @@
#include
#include
-CardInfoTextWidget::CardInfoTextWidget(QWidget *parent) : QFrame(parent), info(nullptr)
+CardInfoTextWidget::CardInfoTextWidget(QWidget *parent) : QFrame(parent)
{
propsLabel = new QLabel;
propsLabel->setOpenExternalLinks(false);
@@ -39,6 +40,12 @@ CardInfoTextWidget::CardInfoTextWidget(QWidget *parent) : QFrame(parent), info(n
grid->setRowStretch(1, 1);
retranslateUi();
+
+ connect(&SettingsCache::instance().cardsDisplay(), &CardsDisplaySettings::cardLangChanged, this, [this] {
+ if (currentCard) {
+ setCard(currentCard);
+ }
+ });
}
void CardInfoTextWidget::setTexts(const QString &propsText, const QString &textText)
@@ -60,7 +67,7 @@ void CardInfoTextWidget::setCard(const ExactCard &exactCard)
QString text = "";
text += QString("| %1 | | %2 |
")
- .arg(tr("Name:"), card->getName().toHtmlEscaped());
+ .arg(tr("Name:"), CardLocalization::displayName(card).toHtmlEscaped());
if (!exactCard.getPrinting().isEmpty()) {
QString setShort = exactCard.getPrinting().getSet()->getShortName().toHtmlEscaped();
@@ -94,7 +101,8 @@ void CardInfoTextWidget::setCard(const ExactCard &exactCard)
}
text += "
";
- setTexts(text, card->getText());
+ setTexts(text, CardLocalization::displayText(card));
+ currentCard = exactCard;
}
void CardInfoTextWidget::setInvalidCardName(const QString &cardName)
diff --git a/cockatrice/src/interface/widgets/cards/card_info_text_widget.h b/cockatrice/src/interface/widgets/cards/card_info_text_widget.h
index a9c29da37..683be5ab5 100644
--- a/cockatrice/src/interface/widgets/cards/card_info_text_widget.h
+++ b/cockatrice/src/interface/widgets/cards/card_info_text_widget.h
@@ -23,7 +23,7 @@ private:
QLabel *propsLabel;
QScrollArea *propsScroll;
QTextEdit *textLabel;
- CardInfoPtr info;
+ ExactCard currentCard; ///< Last card set, re-rendered when the card language changes.
void setTexts(const QString &propsText, const QString &textText);
public:
diff --git a/cockatrice/src/interface/widgets/cards/deck_preview_card_picture_widget.cpp b/cockatrice/src/interface/widgets/cards/deck_preview_card_picture_widget.cpp
index 1614836fc..147143e7f 100644
--- a/cockatrice/src/interface/widgets/cards/deck_preview_card_picture_widget.cpp
+++ b/cockatrice/src/interface/widgets/cards/deck_preview_card_picture_widget.cpp
@@ -27,18 +27,23 @@ DeckPreviewCardPictureWidget::DeckPreviewCardPictureWidget(QWidget *parent,
const QColor &textColor,
const QColor &outlineColor,
const int fontSize,
- const Qt::Alignment alignment)
+ const Qt::Alignment alignment,
+ const bool _emitClickImmediately)
: CardInfoPictureWithTextOverlayWidget(parent,
hoverToZoomEnabled,
raiseOnEnter,
textColor,
outlineColor,
fontSize,
- alignment)
+ alignment),
+ emitClickImmediately(_emitClickImmediately)
{
singleClickTimer = new QTimer(this);
singleClickTimer->setSingleShot(true);
- connect(singleClickTimer, &QTimer::timeout, this, [this]() { emit imageClicked(lastMouseEvent, this); });
+ connect(singleClickTimer, &QTimer::timeout, this, [this]() {
+ emit imageClicked(lastMouseEvent, this);
+ emit imageSingleClicked();
+ });
connect(&SettingsCache::instance().visualDeckStorage(),
&VisualDeckStorageSettings::visualDeckStorageSelectionAnimationChanged, this,
&CardInfoPictureWidget::setRaiseOnEnterEnabled);
@@ -47,8 +52,13 @@ DeckPreviewCardPictureWidget::DeckPreviewCardPictureWidget(QWidget *parent,
void DeckPreviewCardPictureWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
- lastMouseEvent = event;
- singleClickTimer->start(QApplication::doubleClickInterval());
+ if (emitClickImmediately) {
+ emit imageClicked(event, this);
+ emit imageSingleClicked();
+ } else {
+ lastMouseEvent = event;
+ singleClickTimer->start(QApplication::doubleClickInterval());
+ }
} else {
emit imageClicked(event, this);
event->accept();
@@ -58,7 +68,14 @@ void DeckPreviewCardPictureWidget::mousePressEvent(QMouseEvent *event)
void DeckPreviewCardPictureWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton) {
- singleClickTimer->stop(); // Prevent single-click logic
- emit imageDoubleClicked(lastMouseEvent, this);
+ if (emitClickImmediately) {
+ // Do not report a second single click for the second press of the
+ // double-click; the consumer maps the double-click to select+open.
+ lastMouseEvent = event;
+ emit imageDoubleClicked(event, this);
+ } else {
+ singleClickTimer->stop(); // Prevent single-click logic
+ emit imageDoubleClicked(lastMouseEvent, this);
+ }
}
}
diff --git a/cockatrice/src/interface/widgets/cards/deck_preview_card_picture_widget.h b/cockatrice/src/interface/widgets/cards/deck_preview_card_picture_widget.h
index 154e938aa..7571bc256 100644
--- a/cockatrice/src/interface/widgets/cards/deck_preview_card_picture_widget.h
+++ b/cockatrice/src/interface/widgets/cards/deck_preview_card_picture_widget.h
@@ -20,21 +20,38 @@ class DeckPreviewCardPictureWidget final : public CardInfoPictureWithTextOverlay
Q_OBJECT
public:
+ /**
+ * @brief Constructs a DeckPreviewCardPictureWidget.
+ * @param parent The parent widget.
+ * @param hoverToZoomEnabled If this widget will spawn a larger widget when hovered over.
+ * @param raiseOnEnter If the widget raises its border when the mouse enters.
+ * @param textColor The color of the overlay text.
+ * @param outlineColor The color of the outline around the text.
+ * @param fontSize The font size of the overlay text.
+ * @param alignment The alignment of the text within the overlay.
+ * @param emitClickImmediately If true, a left click is reported immediately on click
+ * instead of after the double-click interval. Use this for selection surfaces
+ * where reacting to a double-click (select-and-open) would needlessly delay the
+ * single-click feedback. The double-click signal is still emitted.
+ */
explicit DeckPreviewCardPictureWidget(QWidget *parent,
bool hoverToZoomEnabled = false,
bool raiseOnEnter = false,
const QColor &textColor = Qt::white,
const QColor &outlineColor = Qt::black,
int fontSize = 12,
- Qt::Alignment alignment = Qt::AlignCenter);
+ Qt::Alignment alignment = Qt::AlignCenter,
+ bool _emitClickImmediately = false);
signals:
void imageClicked(QMouseEvent *event, DeckPreviewCardPictureWidget *instance);
+ void imageSingleClicked();
void imageDoubleClicked(QMouseEvent *event, DeckPreviewCardPictureWidget *instance);
private:
QTimer *singleClickTimer;
QMouseEvent *lastMouseEvent = nullptr; // Store the last mouse event
+ bool emitClickImmediately;
protected:
void mousePressEvent(QMouseEvent *event) override;
diff --git a/cockatrice/src/interface/widgets/deck_analytics/abstract_analytics_panel_widget.cpp b/cockatrice/src/interface/widgets/deck_analytics/abstract_analytics_panel_widget.cpp
index 089abc5c8..483fc71b0 100644
--- a/cockatrice/src/interface/widgets/deck_analytics/abstract_analytics_panel_widget.cpp
+++ b/cockatrice/src/interface/widgets/deck_analytics/abstract_analytics_panel_widget.cpp
@@ -1,5 +1,6 @@
#include "abstract_analytics_panel_widget.h"
+#include "../../pixel_map_generator.h"
#include "deck_list_statistics_analyzer.h"
#include
@@ -20,7 +21,7 @@ AbstractAnalyticsPanelWidget::AbstractAnalyticsPanelWidget(QWidget *parent, Deck
// config button
configureButton = new QPushButton(this);
- configureButton->setIcon(QPixmap("theme:icons/cogwheel"));
+ configureButton->setIcon(themePixmap(QStringLiteral("icons/cogwheel")));
configureButton->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
connect(configureButton, &QPushButton::clicked, this, &AbstractAnalyticsPanelWidget::applyConfigFromDialog);
bannerAndSettingsLayout->addWidget(configureButton, 0);
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 9da821813..c8bdacf0d 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
@@ -28,7 +28,7 @@ DeckEditorDatabaseDisplayWidget::DeckEditorDatabaseDisplayWidget(QWidget *parent
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);
+ auto help = searchEdit->addAction(themePixmap(QStringLiteral("icons/info")), QLineEdit::TrailingPosition);
setFocusProxy(searchEdit);
setFocusPolicy(Qt::ClickFocus);
@@ -59,13 +59,13 @@ DeckEditorDatabaseDisplayWidget::DeckEditorDatabaseDisplayWidget(QWidget *parent
&DeckEditorDatabaseDisplayWidget::onRelatedCardClicked);
aAddCard = new QAction(QString(), this);
- aAddCard->setIcon(QPixmap("theme:icons/arrow_right_green"));
+ aAddCard->setIcon(themePixmap(QStringLiteral("icons/arrow_right_green")));
connect(aAddCard, &QAction::triggered, this, &DeckEditorDatabaseDisplayWidget::actAddCardToMainDeck);
auto *tbAddCard = new QToolButton(this);
tbAddCard->setDefaultAction(aAddCard);
aAddCardToSideboard = new QAction(QString(), this);
- aAddCardToSideboard->setIcon(QPixmap("theme:icons/arrow_right_blue"));
+ aAddCardToSideboard->setIcon(themePixmap(QStringLiteral("icons/arrow_right_blue")));
connect(aAddCardToSideboard, &QAction::triggered, this, &DeckEditorDatabaseDisplayWidget::actAddCardToSideboard);
auto *tbAddCardToSideboard = new QToolButton(this);
tbAddCardToSideboard->setDefaultAction(aAddCardToSideboard);
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 e2175a358..b0b31074c 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
@@ -2,6 +2,7 @@
#include "../../../client/settings/cache_settings.h"
#include "../../../client/settings/shortcuts_settings.h"
+#include "../../pixel_map_generator.h"
#include "../playmat/playmat_settings_dialog.h"
#include "../settings_page/user_interface_settings_page.h"
#include "../tabs/api/commander_spellbook/commander_bracket_widget.h"
@@ -192,25 +193,25 @@ void DeckEditorDeckDockWidget::createDeckDock()
&DeckEditorDeckDockWidget::applyActiveGroupCriteria);
aIncrement = new QAction(QString(), this);
- aIncrement->setIcon(QPixmap("theme:icons/increment"));
+ aIncrement->setIcon(themePixmap(QStringLiteral("icons/increment")));
connect(aIncrement, &QAction::triggered, this, &DeckEditorDeckDockWidget::actIncrementSelection);
auto *tbIncrement = new QToolButton(this);
tbIncrement->setDefaultAction(aIncrement);
aDecrement = new QAction(QString(), this);
- aDecrement->setIcon(QPixmap("theme:icons/decrement"));
+ aDecrement->setIcon(themePixmap(QStringLiteral("icons/decrement")));
connect(aDecrement, &QAction::triggered, this, &DeckEditorDeckDockWidget::actDecrementSelection);
auto *tbDecrement = new QToolButton(this);
tbDecrement->setDefaultAction(aDecrement);
aRemoveCard = new QAction(QString(), this);
- aRemoveCard->setIcon(QPixmap("theme:icons/remove_row"));
+ aRemoveCard->setIcon(themePixmap(QStringLiteral("icons/remove_row")));
connect(aRemoveCard, &QAction::triggered, this, &DeckEditorDeckDockWidget::actRemoveCard);
auto *tbRemoveCard = new QToolButton(this);
tbRemoveCard->setDefaultAction(aRemoveCard);
aSwapCard = new QAction(QString(), this);
- aSwapCard->setIcon(QPixmap("theme:icons/swap"));
+ aSwapCard->setIcon(themePixmap(QStringLiteral("icons/swap")));
connect(aSwapCard, &QAction::triggered, this, &DeckEditorDeckDockWidget::actSwapSelection);
auto *tbSwapCard = new QToolButton(this);
tbSwapCard->setDefaultAction(aSwapCard);
@@ -344,7 +345,9 @@ ExactCard DeckEditorDeckDockWidget::getCurrentCard()
if (!current.isValid()) {
return {};
}
- const QString cardName = current.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString();
+ // The display role holds the localized card name; the edit role always carries the
+ // canonical English name needed to look the card up in the database.
+ const QString cardName = current.siblingAtColumn(DeckListModelColumns::CARD_NAME).data(Qt::EditRole).toString();
const QString cardProviderID = current.siblingAtColumn(DeckListModelColumns::CARD_PROVIDER_ID).data().toString();
const QModelIndex gparent = current.parent().parent();
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 2d4fb60e8..c6b6e4416 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
@@ -4,6 +4,7 @@
#include "../../../client/settings/shortcuts_settings.h"
#include "../../../filters/filter_builder.h"
#include "../../../filters/filter_tree_model.h"
+#include "../../pixel_map_generator.h"
#include
#include
@@ -42,11 +43,11 @@ void DeckEditorFilterDockWidget::createFiltersDock()
connect(filterBuilder, &FilterBuilder::add, filterModel, &FilterTreeModel::addFilter);
aClearFilterOne = new QAction(QString(), this);
- aClearFilterOne->setIcon(QPixmap("theme:icons/decrement"));
+ aClearFilterOne->setIcon(themePixmap(QStringLiteral("icons/decrement")));
connect(aClearFilterOne, &QAction::triggered, this, &DeckEditorFilterDockWidget::actClearFilterOne);
aClearFilterAll = new QAction(QString(), this);
- aClearFilterAll->setIcon(QPixmap("theme:icons/clearsearch"));
+ aClearFilterAll->setIcon(themePixmap(QStringLiteral("icons/clearsearch")));
connect(aClearFilterAll, &QAction::triggered, this, &DeckEditorFilterDockWidget::actClearFilterAll);
auto *filterDelOne = new QToolButton();
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 cef459752..c93f12b34 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
@@ -1,5 +1,6 @@
#include "deck_list_history_manager_widget.h"
+#include "../../pixel_map_generator.h"
#include "deck_state_manager.h"
DeckListHistoryManagerWidget::DeckListHistoryManagerWidget(DeckStateManager *_deckStateManager,
@@ -10,7 +11,7 @@ DeckListHistoryManagerWidget::DeckListHistoryManagerWidget(DeckStateManager *_de
layout = new QHBoxLayout(this);
aUndo = new QAction(QString(), this);
- aUndo->setIcon(QPixmap("theme:icons/arrow_undo"));
+ aUndo->setIcon(themePixmap(QStringLiteral("icons/arrow_undo")));
aUndo->setShortcut(QKeySequence::Undo);
aUndo->setShortcutContext(Qt::ApplicationShortcut);
connect(aUndo, &QAction::triggered, this, &DeckListHistoryManagerWidget::doUndo);
@@ -19,7 +20,7 @@ DeckListHistoryManagerWidget::DeckListHistoryManagerWidget(DeckStateManager *_de
undoButton->setDefaultAction(aUndo);
aRedo = new QAction(QString(), this);
- aRedo->setIcon(QPixmap("theme:icons/arrow_redo"));
+ aRedo->setIcon(themePixmap(QStringLiteral("icons/arrow_redo")));
aRedo->setShortcut(QKeySequence::Redo);
aRedo->setShortcutContext(Qt::ApplicationShortcut);
connect(aRedo, &QAction::triggered, this, &DeckListHistoryManagerWidget::doRedo);
@@ -31,7 +32,7 @@ DeckListHistoryManagerWidget::DeckListHistoryManagerWidget(DeckStateManager *_de
layout->addWidget(redoButton);
historyButton = new SettingsButtonWidget(this);
- historyButton->setButtonIcon(QPixmap("theme:icons/arrow_history"));
+ historyButton->setButtonIcon(themePixmap(QStringLiteral("icons/arrow_history")));
historyLabel = new QLabel(this);
diff --git a/cockatrice/src/interface/widgets/deck_editor/deck_state_manager.cpp b/cockatrice/src/interface/widgets/deck_editor/deck_state_manager.cpp
index e563729a4..cfe989e9f 100644
--- a/cockatrice/src/interface/widgets/deck_editor/deck_state_manager.cpp
+++ b/cockatrice/src/interface/widgets/deck_editor/deck_state_manager.cpp
@@ -1,13 +1,20 @@
#include "deck_state_manager.h"
+#include "../../../client/settings/cache_settings.h"
+
#include
#include
#include
+#include
DeckStateManager::DeckStateManager(QObject *parent)
: QObject(parent), deckList(QSharedPointer(new DeckList)),
deckListModel(new DeckListModel(this, deckList)), historyManager(new DeckListHistoryManager(this))
{
+ deckListModel->setDisplayLanguage(SettingsCache::instance().cardsDisplay().getCardLang());
+ connect(&SettingsCache::instance().cardsDisplay(), &CardsDisplaySettings::cardLangChanged, deckListModel,
+ [this](const QString &lang) { deckListModel->setDisplayLanguage(lang); });
+
connect(historyManager, &DeckListHistoryManager::undoRedoStateChanged, this, [this] {
setModified(true);
emit historyChanged();
@@ -260,7 +267,10 @@ bool DeckStateManager::swapCardAtIndex(const QModelIndex &idx)
return false;
}
- QString cardName = idx.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString();
+ // The display role holds the localized card name; the edit role always carries the
+ // canonical English name needed to look the card up in the database.
+ QString displayCardName = idx.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString();
+ QString cardName = idx.siblingAtColumn(DeckListModelColumns::CARD_NAME).data(Qt::EditRole).toString();
QString providerId = idx.siblingAtColumn(DeckListModelColumns::CARD_PROVIDER_ID).data().toString();
QModelIndex gparent = idx.parent().parent();
@@ -277,7 +287,7 @@ bool DeckStateManager::swapCardAtIndex(const QModelIndex &idx)
QString reason = tr("Moved to %1 1 × \"%2\" (%3)") //
.arg(otherZoneName)
- .arg(cardName)
+ .arg(displayCardName)
.arg(providerId);
return modifyDeck(reason, [&idx, &cardName, &providerId, &otherZoneName](auto model) {
@@ -291,9 +301,8 @@ bool DeckStateManager::removeCardAtIndex(const QModelIndex &idx)
return false;
}
- QString cardName = idx.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString();
-
- QString reason = tr("Removed \"%1\" (all copies)").arg(cardName);
+ QString reason =
+ tr("Removed \"%1\" (all copies)").arg(idx.siblingAtColumn(DeckListModelColumns::CARD_NAME).data().toString());
return modifyDeck(reason, [&idx](auto model) { return model->removeRow(idx.row(), idx.parent()); });
}
diff --git a/cockatrice/src/interface/widgets/deck_share/deck_share_utils.cpp b/cockatrice/src/interface/widgets/deck_share/deck_share_utils.cpp
new file mode 100644
index 000000000..4343f0aab
--- /dev/null
+++ b/cockatrice/src/interface/widgets/deck_share/deck_share_utils.cpp
@@ -0,0 +1,59 @@
+#include "deck_share_utils.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+namespace DeckShareUtils
+{
+
+QString buildShareLink(const AbstractClient *client, const QString &token)
+{
+ QUrl url;
+ url.setScheme(QStringLiteral("cockatrice"));
+ url.setHost(QStringLiteral("opendeck"));
+
+ QUrlQuery query;
+ query.addQueryItem(QStringLiteral("share"), token);
+ query.addQueryItem(QStringLiteral("hostname"), client->serverName());
+ query.addQueryItem(QStringLiteral("port"), QString::number(client->serverPort()));
+ url.setQuery(query);
+
+ return url.toString(QUrl::FullyEncoded);
+}
+
+QString copyShareLinkToClipboard(const QString &link)
+{
+ QGuiApplication::clipboard()->setText(link);
+ return link;
+}
+
+QString formatShareExpiry(const QDateTime &expiry)
+{
+ return QLocale().toString(expiry.toLocalTime(), QLocale::ShortFormat);
+}
+
+ShareResponse handleShareResponse(const AbstractClient *client, const Response &response)
+{
+ const Response_DeckShareCreate &resp = response.GetExtension(Response_DeckShareCreate::ext);
+ const QString token = QString::fromStdString(resp.token());
+
+ const QString link = buildShareLink(client, token);
+ copyShareLinkToClipboard(link);
+
+#if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
+ const QDateTime expiry = QDateTime::fromSecsSinceEpoch(resp.expires_at(), QTimeZone::UTC);
+#else
+ const QDateTime expiry = QDateTime::fromSecsSinceEpoch(resp.expires_at(), Qt::UTC);
+#endif
+
+ return {link, expiry};
+}
+
+} // namespace DeckShareUtils
diff --git a/cockatrice/src/interface/widgets/deck_share/deck_share_utils.h b/cockatrice/src/interface/widgets/deck_share/deck_share_utils.h
new file mode 100644
index 000000000..c9f7afa8b
--- /dev/null
+++ b/cockatrice/src/interface/widgets/deck_share/deck_share_utils.h
@@ -0,0 +1,59 @@
+/**
+ * @file deck_share_utils.h
+ * @ingroup DeckShareWidgets
+ */
+//! \todo Document this file.
+
+#ifndef DECK_SHARE_UTILS_H
+#define DECK_SHARE_UTILS_H
+
+#include
+#include
+
+class AbstractClient;
+class Response;
+
+/**
+ * @brief Shared helpers for creating temporary deck shares.
+ */
+namespace DeckShareUtils
+{
+
+/**
+ * @brief The outcome of a successful share-create response.
+ */
+struct ShareResponse
+{
+ QString link; ///< The share link that was copied to the clipboard.
+ QDateTime expiry; ///< When the share expires (UTC).
+};
+
+/**
+ * @brief Builds the cockatrice:// link for a freshly created deck share.
+ * @param client Used to embed the target server's hostname and port.
+ * @param token The share token from Response_DeckShareCreate.
+ */
+QString buildShareLink(const AbstractClient *client, const QString &token);
+
+/**
+ * @brief Copies the share link to the clipboard.
+ * @return The link that was copied.
+ */
+QString copyShareLinkToClipboard(const QString &link);
+
+/**
+ * @brief Formats the expiration timestamp for a share.
+ */
+QString formatShareExpiry(const QDateTime &expiry);
+
+/**
+ * @brief Handles a successful Response_DeckShareCreate: builds the share link,
+ * copies it to the clipboard, and derives the share expiry.
+ * @param client Used to embed the target server's hostname and port.
+ * @param response The successful response carrying the share token and expiry.
+ */
+ShareResponse handleShareResponse(const AbstractClient *client, const Response &response);
+
+} // namespace DeckShareUtils
+
+#endif // DECK_SHARE_UTILS_H
diff --git a/cockatrice/src/interface/widgets/deck_share/share_bar_widget.cpp b/cockatrice/src/interface/widgets/deck_share/share_bar_widget.cpp
new file mode 100644
index 000000000..5aca343ca
--- /dev/null
+++ b/cockatrice/src/interface/widgets/deck_share/share_bar_widget.cpp
@@ -0,0 +1,77 @@
+#include "share_bar_widget.h"
+
+#include
+#include
+#include
+#include
+
+ShareBarWidget::ShareBarWidget(QWidget *parent) : QWidget(parent)
+{
+ auto *layout = new QHBoxLayout(this);
+ layout->setContentsMargins(12, 10, 12, 10);
+ layout->setSpacing(8);
+
+ hintLabel = new QLabel(this);
+ hintLabel->setWordWrap(true);
+
+ nameEdit = new QLineEdit(this);
+ nameEdit->setMaximumWidth(260);
+
+ countLabel = new QLabel(this);
+
+ cancelButton = new QPushButton(this);
+ connect(cancelButton, &QPushButton::clicked, this, &ShareBarWidget::cancelRequested);
+
+ createButton = new QPushButton(this);
+ createButton->setDefault(true);
+ connect(createButton, &QPushButton::clicked, this, &ShareBarWidget::createRequested);
+
+ layout->addWidget(hintLabel, 1);
+ layout->addWidget(nameEdit);
+ layout->addWidget(countLabel);
+ layout->addStretch();
+ layout->addWidget(cancelButton);
+ layout->addWidget(createButton);
+
+ setLayout(layout);
+
+ retranslateUi();
+}
+
+void ShareBarWidget::retranslateUi()
+{
+ nameEdit->setPlaceholderText(tr("Share name"));
+ cancelButton->setText(tr("Cancel"));
+ createButton->setText(tr("Create share link"));
+}
+
+QString ShareBarWidget::name() const
+{
+ return nameEdit->text().trimmed();
+}
+
+void ShareBarWidget::setName(const QString &value)
+{
+ nameEdit->setText(value);
+}
+
+void ShareBarWidget::setCountText(const QString &text)
+{
+ countLabel->setText(text);
+}
+
+void ShareBarWidget::setHintText(const QString &text, bool visible)
+{
+ hintLabel->setText(text);
+ hintLabel->setVisible(visible);
+}
+
+void ShareBarWidget::setCreateEnabled(bool enabled)
+{
+ createButton->setEnabled(enabled);
+}
+
+void ShareBarWidget::focusName()
+{
+ nameEdit->setFocus();
+}
diff --git a/cockatrice/src/interface/widgets/deck_share/share_bar_widget.h b/cockatrice/src/interface/widgets/deck_share/share_bar_widget.h
new file mode 100644
index 000000000..ede9fb41b
--- /dev/null
+++ b/cockatrice/src/interface/widgets/deck_share/share_bar_widget.h
@@ -0,0 +1,63 @@
+/**
+ * @file share_bar_widget.h
+ * @ingroup DeckShareWidgets
+ */
+//! \todo Document this file.
+
+#ifndef SHARE_BAR_WIDGET_H
+#define SHARE_BAR_WIDGET_H
+
+#include
+
+class QLabel;
+class QLineEdit;
+class QPushButton;
+
+/**
+ * @brief The activated toolbar used to create a temporary deck share.
+ *
+ * A single reusable component shared by the local visual deck storage and the
+ * remote server deck storage tabs, so the share workflow renders identically in
+ * both places. It owns its own widgets, strings, and layout; the owning tab only
+ * sets the count/hint text and reacts to the create/cancel signals.
+ */
+class ShareBarWidget final : public QWidget
+{
+ Q_OBJECT
+
+public:
+ explicit ShareBarWidget(QWidget *parent = nullptr);
+
+ void retranslateUi();
+
+ /** @return The trimmed name entered by the user. */
+ [[nodiscard]] QString name() const;
+
+ /** @brief Resets the name field to the given default. */
+ void setName(const QString &name);
+
+ /** @brief Sets the selected-count summary label text. */
+ void setCountText(const QString &text);
+
+ /** @brief Sets the explainer hint text, showing it when @p visible is true. */
+ void setHintText(const QString &text, bool visible);
+
+ /** @brief Enables or disables the create-share-link button (guards double submission). */
+ void setCreateEnabled(bool enabled);
+
+ /** @brief Moves keyboard focus to the name field. */
+ void focusName();
+
+signals:
+ void createRequested();
+ void cancelRequested();
+
+private:
+ QLabel *hintLabel;
+ QLineEdit *nameEdit;
+ QLabel *countLabel;
+ QPushButton *cancelButton;
+ QPushButton *createButton;
+};
+
+#endif // SHARE_BAR_WIDGET_H
diff --git a/cockatrice/src/interface/widgets/deck_share/shared_deck_preview_widget.cpp b/cockatrice/src/interface/widgets/deck_share/shared_deck_preview_widget.cpp
new file mode 100644
index 000000000..ef77df9ec
--- /dev/null
+++ b/cockatrice/src/interface/widgets/deck_share/shared_deck_preview_widget.cpp
@@ -0,0 +1,139 @@
+#include "shared_deck_preview_widget.h"
+
+#include "../cards/additional_info/color_identity_widget.h"
+#include "../cards/deck_preview_card_picture_widget.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+SharedDeckPreviewWidget::SharedDeckPreviewWidget(QWidget *parent,
+ const CardDatabaseQuerier *querier,
+ const QString &deckName,
+ const QString &bannerCardName,
+ const QString &colorIdentity,
+ const QString &gameFormat,
+ const QString &deckToolTip)
+ : QWidget(parent)
+{
+ bannerCardDisplayWidget =
+ new DeckPreviewCardPictureWidget(this, false, false, Qt::white, Qt::black, 12, Qt::AlignCenter, true);
+ bannerCardDisplayWidget->setScaleFactor(100);
+ const ExactCard bannerCard = bannerCardName.isEmpty() ? ExactCard() : querier->getCard(CardRef{bannerCardName, {}});
+ bannerCardDisplayWidget->setCard(bannerCard);
+ bannerCardDisplayWidget->setOverlayText(deckName);
+ setToolTip(deckToolTip.isEmpty() ? deckName : deckToolTip);
+ setFocusPolicy(Qt::StrongFocus);
+ setBaseAccessibleName(deckName);
+
+ colorIdentityWidget = new ColorIdentityWidget(this, colorIdentity);
+ colorIdentityWidget->setVisible(!colorIdentity.isEmpty());
+
+ gameFormatLabel = new QLabel(gameFormat, this);
+ gameFormatLabel->setAlignment(Qt::AlignCenter);
+ gameFormatLabel->setVisible(!gameFormat.isEmpty());
+
+ selectionCheckBox = new QCheckBox(this);
+ selectionCheckBox->setToolTip(tr("Select this deck"));
+ // The tile itself is focusable (Space/Enter toggles); keep the checkbox
+ // from creating a second tab stop per tile.
+ selectionCheckBox->setFocusPolicy(Qt::NoFocus);
+
+ // Selection frame reused from the deck-preview selection covenant: a
+ // palette(highlight) border around the banner card, shown while selected.
+ selectionFrame = new QFrame(bannerCardDisplayWidget);
+ selectionFrame->setAttribute(Qt::WA_TransparentForMouseEvents);
+ selectionFrame->setStyleSheet(QStringLiteral(
+ "QFrame { border: 2px solid palette(highlight); border-radius: 4px; background: transparent; }"));
+ selectionFrame->setVisible(false);
+
+ auto *selectionRow = new QHBoxLayout;
+ selectionRow->addWidget(selectionCheckBox);
+ selectionRow->addStretch(1);
+
+ auto *layout = new QVBoxLayout(this);
+ layout->setContentsMargins(0, 0, 0, 0);
+ layout->addLayout(selectionRow);
+ layout->addWidget(bannerCardDisplayWidget, 0, Qt::AlignHCenter);
+ layout->addWidget(colorIdentityWidget, 0, Qt::AlignHCenter);
+ layout->addWidget(gameFormatLabel, 0, Qt::AlignHCenter);
+ setLayout(layout);
+
+ connect(selectionCheckBox, &QCheckBox::toggled, this, [this](bool checked) {
+ updateSelectionVisual(checked);
+ emit selectionToggled(checked);
+ });
+ connect(bannerCardDisplayWidget, &DeckPreviewCardPictureWidget::imageClicked, this,
+ &SharedDeckPreviewWidget::toggleSelection);
+ connect(bannerCardDisplayWidget, &DeckPreviewCardPictureWidget::imageDoubleClicked, this,
+ &SharedDeckPreviewWidget::activate);
+}
+
+bool SharedDeckPreviewWidget::isSelected() const
+{
+ return selectionCheckBox->isChecked();
+}
+
+void SharedDeckPreviewWidget::setSelected(bool selected)
+{
+ if (isSelected() == selected) {
+ return;
+ }
+ selectionCheckBox->setChecked(selected);
+}
+
+void SharedDeckPreviewWidget::updateSelectionVisual(bool selected)
+{
+ selectionFrame->setVisible(selected);
+ selectionFrame->raise();
+ if (selected) {
+ setAccessibleName(baseAccessibleName + tr(" (selected)"));
+ } else {
+ setAccessibleName(baseAccessibleName);
+ }
+}
+
+void SharedDeckPreviewWidget::setBaseAccessibleName(const QString &name)
+{
+ baseAccessibleName = name;
+ setAccessibleName(name);
+}
+
+void SharedDeckPreviewWidget::toggleSelection()
+{
+ setSelected(!isSelected());
+}
+
+void SharedDeckPreviewWidget::activate()
+{
+ setSelected(true);
+ emit activated();
+}
+
+void SharedDeckPreviewWidget::resizeEvent(QResizeEvent *event)
+{
+ QWidget::resizeEvent(event);
+ updateSelectionFrameGeometry();
+}
+
+void SharedDeckPreviewWidget::updateSelectionFrameGeometry()
+{
+ if (selectionFrame == nullptr || bannerCardDisplayWidget == nullptr) {
+ return;
+ }
+ selectionFrame->setGeometry(bannerCardDisplayWidget->rect().adjusted(1, 1, -1, -1));
+}
+
+void SharedDeckPreviewWidget::keyPressEvent(QKeyEvent *event)
+{
+ if (event->key() == Qt::Key_Space || event->key() == Qt::Key_Return || event->key() == Qt::Key_Enter) {
+ toggleSelection();
+ event->accept();
+ return;
+ }
+ QWidget::keyPressEvent(event);
+}
diff --git a/cockatrice/src/interface/widgets/deck_share/shared_deck_preview_widget.h b/cockatrice/src/interface/widgets/deck_share/shared_deck_preview_widget.h
new file mode 100644
index 000000000..bd4c4ee5f
--- /dev/null
+++ b/cockatrice/src/interface/widgets/deck_share/shared_deck_preview_widget.h
@@ -0,0 +1,77 @@
+/**
+ * @file shared_deck_preview_widget.h
+ * @ingroup DeckShareWidgets
+ */
+//! \todo Document this file.
+
+#ifndef SHARED_DECK_PREVIEW_WIDGET_H
+#define SHARED_DECK_PREVIEW_WIDGET_H
+
+#include
+
+class ColorIdentityWidget;
+class DeckPreviewCardPictureWidget;
+class QCheckBox;
+class QFrame;
+class QKeyEvent;
+class QLabel;
+class QResizeEvent;
+class CardDatabaseQuerier;
+
+/**
+ * @brief A selectable preview tile for a deck that has no local file.
+ *
+ * Renders a banner card picture (looked up by name in the card database), the
+ * deck name, color identity and game format. Used to preview decks shared via a
+ * cockatrice:// link (metadata from Command_DeckShareList) and the deck
+ * currently open in the deck editor.
+ *
+ * Selection follows the deck-preview covenant: the tile reports its click
+ * immediately (no double-click interval delay), a palette(highlight) frame
+ * marks the selected tile, and Space/Enter toggles selection from the keyboard.
+ * A double click selects the tile and emits activated() so the caller can open
+ * just that deck.
+ */
+class SharedDeckPreviewWidget : public QWidget
+{
+ Q_OBJECT
+
+public:
+ explicit SharedDeckPreviewWidget(QWidget *parent,
+ const CardDatabaseQuerier *querier,
+ const QString &deckName,
+ const QString &bannerCardName,
+ const QString &colorIdentity,
+ const QString &gameFormat = QString(),
+ const QString &deckToolTip = QString());
+
+ [[nodiscard]] bool isSelected() const;
+ void setSelected(bool selected);
+
+ void setBaseAccessibleName(const QString &name);
+
+signals:
+ void selectionToggled(bool selected);
+ void activated();
+
+protected:
+ void resizeEvent(QResizeEvent *event) override;
+ void keyPressEvent(QKeyEvent *event) override;
+
+private slots:
+ void toggleSelection();
+ void activate();
+
+private:
+ void updateSelectionVisual(bool selected);
+ void updateSelectionFrameGeometry();
+
+ DeckPreviewCardPictureWidget *bannerCardDisplayWidget;
+ ColorIdentityWidget *colorIdentityWidget;
+ QLabel *gameFormatLabel;
+ QCheckBox *selectionCheckBox;
+ QFrame *selectionFrame;
+ QString baseAccessibleName;
+};
+
+#endif // SHARED_DECK_PREVIEW_WIDGET_H
\ No newline at end of file
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp
index aa8a916f8..700012d45 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_connect.cpp
@@ -1,6 +1,7 @@
#include "dlg_connect.h"
#include "../../../client/settings/cache_settings.h"
+#include "../../pixel_map_generator.h"
#include
#include
@@ -21,7 +22,7 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
previousHosts = new QComboBox(this);
btnDeleteServer = new QPushButton(this);
- btnDeleteServer->setIcon(QPixmap("theme:icons/remove_row"));
+ btnDeleteServer->setIcon(themePixmap(QStringLiteral("icons/remove_row")));
btnDeleteServer->setToolTip(tr("Delete the currently selected saved server"));
btnDeleteServer->setFixedWidth(30);
@@ -29,7 +30,7 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
hps = new HandlePublicServers(this);
btnRefreshServers = new QPushButton(this);
- btnRefreshServers->setIcon(QPixmap("theme:icons/sync"));
+ btnRefreshServers->setIcon(themePixmap(QStringLiteral("icons/sync")));
btnRefreshServers->setToolTip(tr("Refresh the server list with known public servers"));
btnRefreshServers->setFixedWidth(30);
@@ -99,7 +100,7 @@ DlgConnect::DlgConnect(QWidget *parent) : QDialog(parent)
updateDisplayInfo(previousHosts->currentText());
btnForgotPassword = new QPushButton(this);
- btnForgotPassword->setIcon(QPixmap("theme:icons/forgot_password"));
+ btnForgotPassword->setIcon(themePixmap(QStringLiteral("icons/forgot_password")));
btnForgotPassword->setToolTip(tr("Reset Password"));
btnForgotPassword->setFixedWidth(30);
connect(btnForgotPassword, &QPushButton::released, this, &DlgConnect::actForgotPassword);
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp
index f249976c2..a56aa8e35 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_edit_tokens.cpp
@@ -1,5 +1,6 @@
#include "dlg_edit_tokens.h"
+#include "../../pixel_map_generator.h"
#include "../interface/widgets/utility/get_text_with_max.h"
#include
@@ -90,10 +91,10 @@ DlgEditTokens::DlgEditTokens(QWidget *parent) : QDialog(parent), currentCard(nul
&DlgEditTokens::tokenSelectionChanged);
QAction *aAddToken = new QAction(tr("Add token"), this);
- aAddToken->setIcon(QPixmap("theme:icons/increment"));
+ aAddToken->setIcon(themePixmap(QStringLiteral("icons/increment")));
connect(aAddToken, &QAction::triggered, this, &DlgEditTokens::actAddToken);
QAction *aRemoveToken = new QAction(tr("Remove token"), this);
- aRemoveToken->setIcon(QPixmap("theme:icons/decrement"));
+ aRemoveToken->setIcon(themePixmap(QStringLiteral("icons/decrement")));
connect(aRemoveToken, &QAction::triggered, this, &DlgEditTokens::actRemoveToken);
auto *databaseToolBar = new QToolBar;
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_login_prompt.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_login_prompt.cpp
new file mode 100644
index 000000000..86647ef26
--- /dev/null
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_login_prompt.cpp
@@ -0,0 +1,50 @@
+#include "dlg_login_prompt.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+
+DlgLoginPrompt::DlgLoginPrompt(const QString &serverText, QWidget *parent) : QDialog(parent)
+{
+ setWindowTitle(tr("Sign in"));
+
+ auto *mainLayout = new QVBoxLayout(this);
+ mainLayout->addWidget(
+ new QLabel(tr("This link requires you to be signed in.\nSign in to %1:").arg(serverText), this));
+
+ auto *formLayout = new QFormLayout;
+ usernameEdit = new QLineEdit(this);
+ passwordEdit = new QLineEdit(this);
+ passwordEdit->setEchoMode(QLineEdit::Password);
+ formLayout->addRow(tr("Username:"), usernameEdit);
+ formLayout->addRow(tr("Password:"), passwordEdit);
+ mainLayout->addLayout(formLayout);
+
+ savePasswordCheckBox = new QCheckBox(tr("Save password for this server"), this);
+ mainLayout->addWidget(savePasswordCheckBox);
+
+ auto *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
+ connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
+ connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
+ mainLayout->addWidget(buttonBox);
+
+ usernameEdit->setFocus();
+}
+
+QString DlgLoginPrompt::username() const
+{
+ return usernameEdit->text().trimmed();
+}
+
+QString DlgLoginPrompt::password() const
+{
+ return passwordEdit->text();
+}
+
+bool DlgLoginPrompt::savePassword() const
+{
+ return savePasswordCheckBox->isChecked();
+}
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_login_prompt.h b/cockatrice/src/interface/widgets/dialogs/dlg_login_prompt.h
new file mode 100644
index 000000000..e47924058
--- /dev/null
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_login_prompt.h
@@ -0,0 +1,40 @@
+/**
+ * @file dlg_login_prompt.h
+ * @ingroup ConnectionDialogs
+ */
+//! \todo Document this file.
+
+#ifndef DLG_LOGIN_PROMPT_H
+#define DLG_LOGIN_PROMPT_H
+
+#include
+
+class QCheckBox;
+class QLineEdit;
+
+/**
+ * @brief Small sign-in dialog used when a cockatrice:// link needs credentials
+ * that are not saved for the target server.
+ *
+ * The entered name and password are handed to the intent chain; when the user
+ * opts to save them, they are stored in the server settings so that later links
+ * to the same server connect seamlessly.
+ */
+class DlgLoginPrompt : public QDialog
+{
+ Q_OBJECT
+
+public:
+ explicit DlgLoginPrompt(const QString &serverText, QWidget *parent = nullptr);
+
+ [[nodiscard]] QString username() const;
+ [[nodiscard]] QString password() const;
+ [[nodiscard]] bool savePassword() const;
+
+private:
+ QLineEdit *usernameEdit;
+ QLineEdit *passwordEdit;
+ QCheckBox *savePasswordCheckBox;
+};
+
+#endif // DLG_LOGIN_PROMPT_H
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp
index 7c107eb2f..556c270be 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_manage_sets.cpp
@@ -1,6 +1,7 @@
#include "dlg_manage_sets.h"
#include "../../../client/settings/cache_settings.h"
+#include "../../pixel_map_generator.h"
#include "../interface/card_picture_loader/card_picture_loader.h"
#include "../interface/widgets/utility/custom_line_edit.h"
@@ -35,28 +36,28 @@ WndSets::WndSets(QWidget *parent) : QMainWindow(parent)
setsEditToolBar->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
aTop = new QAction(QString(), this);
- aTop->setIcon(QPixmap("theme:icons/arrow_top_green"));
+ aTop->setIcon(themePixmap(QStringLiteral("icons/arrow_top_green")));
aTop->setToolTip(tr("Move selected set to the top"));
aTop->setEnabled(false);
connect(aTop, &QAction::triggered, this, &WndSets::actTop);
setsEditToolBar->addAction(aTop);
aUp = new QAction(QString(), this);
- aUp->setIcon(QPixmap("theme:icons/arrow_up_green"));
+ aUp->setIcon(themePixmap(QStringLiteral("icons/arrow_up_green")));
aUp->setToolTip(tr("Move selected set up"));
aUp->setEnabled(false);
connect(aUp, &QAction::triggered, this, &WndSets::actUp);
setsEditToolBar->addAction(aUp);
aDown = new QAction(QString(), this);
- aDown->setIcon(QPixmap("theme:icons/arrow_down_green"));
+ aDown->setIcon(themePixmap(QStringLiteral("icons/arrow_down_green")));
aDown->setToolTip(tr("Move selected set down"));
aDown->setEnabled(false);
connect(aDown, &QAction::triggered, this, &WndSets::actDown);
setsEditToolBar->addAction(aDown);
aBottom = new QAction(QString(), this);
- aBottom->setIcon(QPixmap("theme:icons/arrow_bottom_green"));
+ aBottom->setIcon(themePixmap(QStringLiteral("icons/arrow_bottom_green")));
aBottom->setToolTip(tr("Move selected set to the bottom"));
aBottom->setEnabled(false);
connect(aBottom, &QAction::triggered, this, &WndSets::actBottom);
@@ -66,7 +67,7 @@ WndSets::WndSets(QWidget *parent) : QMainWindow(parent)
searchField = new LineEditUnfocusable;
searchField->setObjectName("searchEdit");
searchField->setPlaceholderText(tr("Search by set name, code, type, or release date"));
- searchField->addAction(QPixmap("theme:icons/search"), LineEditUnfocusable::LeadingPosition);
+ searchField->addAction(themePixmap(QStringLiteral("icons/search")), LineEditUnfocusable::LeadingPosition);
searchField->setClearButtonEnabled(true);
setFocusProxy(searchField);
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_register.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_register.cpp
index 6ae8c9adb..6d022861c 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_register.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_register.cpp
@@ -1,6 +1,7 @@
#include "dlg_register.h"
#include "../../../client/settings/cache_settings.h"
+#include "../../pixel_map_generator.h"
#include "../server/handle_public_servers.h"
#include "../server/user/user_info_connection.h"
@@ -24,7 +25,7 @@ DlgRegister::DlgRegister(QWidget *parent) : QDialog(parent)
previousHosts = new QComboBox(this);
btnDeleteServer = new QPushButton(this);
- btnDeleteServer->setIcon(QPixmap("theme:icons/remove_row"));
+ btnDeleteServer->setIcon(themePixmap(QStringLiteral("icons/remove_row")));
btnDeleteServer->setToolTip(tr("Delete the currently selected saved server"));
btnDeleteServer->setFixedWidth(30);
@@ -32,7 +33,7 @@ DlgRegister::DlgRegister(QWidget *parent) : QDialog(parent)
hps = new HandlePublicServers(this);
btnRefreshServers = new QPushButton(this);
- btnRefreshServers->setIcon(QPixmap("theme:icons/sync"));
+ btnRefreshServers->setIcon(themePixmap(QStringLiteral("icons/sync")));
btnRefreshServers->setToolTip(tr("Refresh the server list with known public servers"));
btnRefreshServers->setFixedWidth(30);
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp
index 883cfcd03..581920dbc 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_settings.cpp
@@ -6,6 +6,7 @@
#include "dlg_settings.h"
#include "../../../client/settings/cache_settings.h"
+#include "../../pixel_map_generator.h"
#include "../main.h"
#include "../settings_page/appearance_settings_page.h"
#include "../settings_page/deck_editor_settings_page.h"
@@ -96,7 +97,7 @@ void DlgSettings::setupUi()
// Search bar
searchEdit = new QLineEdit;
searchEdit->setClearButtonEnabled(true);
- searchEdit->addAction(QPixmap("theme:icons/search"), QLineEdit::LeadingPosition);
+ searchEdit->addAction(themePixmap(QStringLiteral("icons/search")), QLineEdit::LeadingPosition);
searchEdit->installEventFilter(this);
connect(searchEdit, &QLineEdit::textChanged, this, &DlgSettings::onSearchTextChanged);
@@ -132,7 +133,7 @@ void DlgSettings::setupUi()
pagesWidget->addWidget(makeScrollable(userInterfacePage));
pagesWidget->addWidget(makeScrollable(deckEditorPage));
pagesWidget->addWidget(makeScrollable(storagePage));
- pagesWidget->addWidget(messagesPage);
+ pagesWidget->addWidget(makeScrollable(messagesPage));
pagesWidget->addWidget(soundPage);
pagesWidget->addWidget(shortcutsPage);
@@ -415,6 +416,11 @@ void DlgSettings::setTab(int index)
}
}
+AbstractSettingsPage *DlgSettings::page(SettingsPage which) const
+{
+ return pages.value(static_cast(which));
+}
+
void DlgSettings::updateLanguage()
{
qApp->removeTranslator(translator); // NOLINT(cppcoreguidelines-pro-type-static-cast-downcast)
@@ -477,13 +483,13 @@ void DlgSettings::closeEvent(QCloseEvent *event)
case Invalid:
loadErrorMessage = tr("Your card database is invalid.\n\n"
"Cockatrice may not function correctly with an invalid database\n\n"
- "You may need to rerun oracle to update your card database.\n\n"
+ "You may need to rerun Oracle to update your card database.\n\n"
"Would you like to change your database location setting?");
break;
case VersionTooOld:
loadErrorMessage = tr("Your card database version is too old.\n\n"
"This can cause problems loading card information or images\n\n"
- "Usually this can be fixed by rerunning oracle to to update your card database.\n\n"
+ "Usually this can be fixed by rerunning Oracle to to update your card database.\n\n"
"Would you like to change your database location setting?");
break;
case NotLoaded:
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_settings.h b/cockatrice/src/interface/widgets/dialogs/dlg_settings.h
index b700f7af9..845c0b4d6 100644
--- a/cockatrice/src/interface/widgets/dialogs/dlg_settings.h
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_settings.h
@@ -54,6 +54,7 @@ public:
explicit DlgSettings(QWidget *parent = nullptr);
void setTab(int index);
+ AbstractSettingsPage *page(SettingsPage which) const;
private slots:
void onTabClicked(int index);
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_share_deck.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_share_deck.cpp
new file mode 100644
index 000000000..897d32062
--- /dev/null
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_share_deck.cpp
@@ -0,0 +1,96 @@
+#include "dlg_share_deck.h"
+
+#include "../../../client/settings/cache_settings.h"
+#include "../cards/additional_info/deck_color_identity.h"
+#include "../deck_share/deck_share_utils.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+DlgShareDeck::DlgShareDeck(AbstractClient *_client, const QSharedPointer &_deck, QWidget *_parent)
+ : QDialog(_parent), client(_client), deck(_deck), shareTimeoutTimer(new QTimer(this))
+{
+ setWindowTitle(tr("Share deck"));
+
+ auto *layout = new QVBoxLayout(this);
+
+ nameEdit = new QLineEdit(this);
+ nameEdit->setText(tr("Shared deck"));
+
+ auto *form = new QFormLayout;
+ form->addRow(tr("Share name:"), nameEdit);
+ layout->addLayout(form);
+
+ auto *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel, this);
+ buttonBox->button(QDialogButtonBox::Ok)->setText(tr("Create share link"));
+ buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("Cancel"));
+ connect(buttonBox, &QDialogButtonBox::accepted, this, &DlgShareDeck::actShare);
+ connect(buttonBox, &QDialogButtonBox::rejected, this, &DlgShareDeck::reject);
+ this->buttonBox = buttonBox;
+ layout->addWidget(buttonBox);
+
+ shareTimeoutTimer->setSingleShot(true);
+ shareTimeoutTimer->setInterval(
+ static_cast((static_cast(SettingsCache::instance().network().getTimeOut()) + 1) *
+ SettingsCache::instance().network().getKeepAlive() * 1000));
+ connect(shareTimeoutTimer, &QTimer::timeout, this, &DlgShareDeck::onShareTimeout);
+}
+
+void DlgShareDeck::actShare()
+{
+ buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
+
+ Command_DeckShareCreate cmd;
+ cmd.set_name(nameEdit->text().trimmed().toStdString());
+ if (cmd.name().empty()) {
+ cmd.set_name(tr("Shared deck").toStdString());
+ }
+
+ DeckShareItem *item = cmd.add_items();
+ item->set_deck_list(deck->writeToString_Native().toStdString());
+ item->set_color_identity(getDeckColorIdentity(*deck, CardDatabaseManager::query()).toStdString());
+
+ PendingCommand *pend = client->prepareSessionCommand(cmd);
+ connect(pend, &PendingCommand::finished, this, &DlgShareDeck::shareFinished);
+ client->sendCommand(pend);
+ shareTimeoutTimer->start();
+}
+
+void DlgShareDeck::shareFinished(const Response &response, const CommandContainer & /*commandContainer*/)
+{
+ shareTimeoutTimer->stop();
+ if (response.response_code() != Response::RespOk) {
+ buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
+ QMessageBox::critical(this, tr("Share deck"),
+ tr("Failed to create the share link (server response code %1).")
+ .arg(QString::number(static_cast(response.response_code()))));
+ return;
+ }
+
+ const DeckShareUtils::ShareResponse share = DeckShareUtils::handleShareResponse(client, response);
+
+ QMessageBox::information(this, tr("Share deck"),
+ tr("Share link created and copied to the clipboard:\n\n%1\n\n"
+ "The share expires on %2.")
+ .arg(share.link, DeckShareUtils::formatShareExpiry(share.expiry)));
+ accept();
+}
+
+void DlgShareDeck::onShareTimeout()
+{
+ buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
+ QMessageBox::warning(this, tr("Share deck"), tr("The server did not respond in time. Try again."));
+}
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_share_deck.h b/cockatrice/src/interface/widgets/dialogs/dlg_share_deck.h
new file mode 100644
index 000000000..162fa3677
--- /dev/null
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_share_deck.h
@@ -0,0 +1,46 @@
+/**
+ * @file dlg_share_deck.h
+ * @ingroup Dialogs
+ */
+//! \todo Document this file.
+
+#ifndef DLG_SHARE_DECK_H
+#define DLG_SHARE_DECK_H
+
+#include
+#include
+
+class AbstractClient;
+class CommandContainer;
+class DeckList;
+class QDialogButtonBox;
+class QLineEdit;
+class QTimer;
+class Response;
+
+/**
+ * @brief Slim dialog to create a temporary share for the deck open in the editor.
+ *
+ * Asks for a share name, sends Command_DeckShareCreate for the single inline
+ * deck, and copies the resulting link to the clipboard.
+ */
+class DlgShareDeck : public QDialog
+{
+ Q_OBJECT
+public:
+ DlgShareDeck(AbstractClient *_client, const QSharedPointer &_deck, QWidget *parent = nullptr);
+
+private slots:
+ void actShare();
+ void shareFinished(const Response &response, const CommandContainer &commandContainer);
+ void onShareTimeout();
+
+private:
+ AbstractClient *client;
+ QSharedPointer deck;
+ QLineEdit *nameEdit;
+ QDialogButtonBox *buttonBox;
+ QTimer *shareTimeoutTimer;
+};
+
+#endif // DLG_SHARE_DECK_H
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_shared_decks_preview.cpp b/cockatrice/src/interface/widgets/dialogs/dlg_shared_decks_preview.cpp
new file mode 100644
index 000000000..e84602cd6
--- /dev/null
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_shared_decks_preview.cpp
@@ -0,0 +1,178 @@
+#include "dlg_shared_decks_preview.h"
+
+#include "../deck_share/shared_deck_preview_widget.h"
+#include "../general/layout_containers/flow_widget.h"
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+
+DlgSharedDecksPreview::DlgSharedDecksPreview(QWidget *parent,
+ const CardDatabaseQuerier *querier,
+ const QString &shareName,
+ qint64 expiresAt,
+ const QString &serverText,
+ const QList &items)
+ : QDialog(parent)
+{
+ setWindowTitle(tr("Open shared decks"));
+ resize(700, 500);
+
+ auto *mainLayout = new QVBoxLayout(this);
+
+ auto *titleLabel = new QLabel(tr("Share: %1").arg(shareName.isEmpty() ? tr("Untitled") : shareName), this);
+ QFont titleFont = titleLabel->font();
+ titleFont.setBold(true);
+ titleFont.setPointSize(titleFont.pointSize() + 2);
+ titleLabel->setFont(titleFont);
+ mainLayout->addWidget(titleLabel);
+
+ if (!serverText.isEmpty()) {
+ mainLayout->addWidget(new QLabel(tr("From %1").arg(serverText), this));
+ }
+
+ if (expiresAt > 0) {
+ const QString expiryText = QDateTime::fromSecsSinceEpoch(expiresAt).toLocalTime().toString(Qt::TextDate);
+ mainLayout->addWidget(new QLabel(tr("This share link expires on %1").arg(expiryText), this));
+ }
+
+ downloadStatusLabel = new QLabel(this);
+ downloadStatusLabel->setVisible(false);
+ mainLayout->addWidget(downloadStatusLabel);
+
+ flowWidget = new FlowWidget(this, Qt::Horizontal, Qt::ScrollBarAlwaysOff, Qt::ScrollBarAsNeeded);
+ mainLayout->addWidget(flowWidget, 1);
+
+ for (const ServerInfo_DeckShareItem &item : items) {
+ QStringList tags;
+ for (const auto &tag : item.tags()) {
+ tags.append(QString::fromStdString(tag));
+ }
+
+ auto *tile = new SharedDeckPreviewWidget(
+ this, querier, QString::fromStdString(item.name()), QString::fromStdString(item.banner_card()),
+ QString::fromStdString(item.color_identity()), QString::fromStdString(item.game_format()), tags.join(", "));
+ flowWidget->addWidget(tile);
+ tiles.append(tile);
+ itemIds.append(item.id());
+ }
+
+ if (tiles.size() == 1) {
+ tiles.first()->setSelected(true);
+ }
+
+ auto *buttonBox = new QDialogButtonBox(this);
+ openSelectedButton = buttonBox->addButton(tr("Open selected"), QDialogButtonBox::AcceptRole);
+ openAllButton = buttonBox->addButton(tr("Open all"), QDialogButtonBox::ActionRole);
+ buttonBox->addButton(tr("Cancel"), QDialogButtonBox::RejectRole);
+ mainLayout->addWidget(buttonBox);
+
+ connect(buttonBox, &QDialogButtonBox::rejected, this, [this]() {
+ onCancel();
+ close();
+ });
+
+ // Esc calls QDialog::reject() directly (which hides the dialog without a
+ // close event), so route it through the same guarded cancel as the button.
+ connect(this, &QDialog::rejected, this, [this]() {
+ onCancel();
+ close();
+ });
+
+ connect(openSelectedButton, &QPushButton::clicked, this, &DlgSharedDecksPreview::openSelected);
+ connect(buttonBox, &QDialogButtonBox::clicked, this, [this, buttonBox](QAbstractButton *button) {
+ if (buttonBox->buttonRole(button) == QDialogButtonBox::ActionRole) {
+ openAll();
+ }
+ });
+
+ for (SharedDeckPreviewWidget *tile : tiles) {
+ connect(tile, &SharedDeckPreviewWidget::selectionToggled, this,
+ &DlgSharedDecksPreview::updateOpenSelectedEnabled);
+ }
+ for (int i = 0; i < tiles.size(); ++i) {
+ const int itemId = itemIds.at(i);
+ // Double-clicking a tile selects it and opens just that deck.
+ connect(tiles.at(i), &SharedDeckPreviewWidget::activated, this, [this, itemId]() {
+ resultEmitted = true;
+ setDownloading(true);
+ emit openRequested(QList{itemId});
+ });
+ }
+ updateOpenSelectedEnabled();
+}
+
+QList DlgSharedDecksPreview::selectedItemIds() const
+{
+ QList selectedIds;
+ for (int i = 0; i < tiles.size(); ++i) {
+ if (tiles.at(i)->isSelected()) {
+ selectedIds.append(itemIds.at(i));
+ }
+ }
+ return selectedIds;
+}
+
+void DlgSharedDecksPreview::openSelected()
+{
+ const QList selectedIds = selectedItemIds();
+ if (selectedIds.isEmpty()) {
+ return;
+ }
+ resultEmitted = true;
+ setDownloading(true);
+ emit openRequested(selectedIds);
+}
+
+void DlgSharedDecksPreview::openAll()
+{
+ resultEmitted = true;
+ setDownloading(true);
+ emit openRequested(itemIds);
+}
+
+void DlgSharedDecksPreview::setDownloading(bool downloading)
+{
+ if (downloadInProgress == downloading) {
+ return;
+ }
+ downloadInProgress = downloading;
+ downloadStatusLabel->setVisible(downloading);
+ for (SharedDeckPreviewWidget *tile : tiles) {
+ tile->setEnabled(!downloading);
+ }
+ openSelectedButton->setEnabled(!downloading);
+ openAllButton->setEnabled(!downloading);
+}
+
+void DlgSharedDecksPreview::setDownloadProgress(int done, int total, const QString ¤tDeckName)
+{
+ if (!downloadInProgress) {
+ return;
+ }
+ downloadStatusLabel->setText(tr("Downloading deck %1 of %2: %3").arg(done).arg(total).arg(currentDeckName));
+}
+
+void DlgSharedDecksPreview::updateOpenSelectedEnabled()
+{
+ openSelectedButton->setEnabled(!selectedItemIds().isEmpty());
+}
+
+void DlgSharedDecksPreview::onCancel()
+{
+ if (!resultEmitted || downloadInProgress) {
+ resultEmitted = true;
+ emit cancelled();
+ }
+}
+
+void DlgSharedDecksPreview::closeEvent(QCloseEvent *event)
+{
+ onCancel();
+ QDialog::closeEvent(event);
+}
diff --git a/cockatrice/src/interface/widgets/dialogs/dlg_shared_decks_preview.h b/cockatrice/src/interface/widgets/dialogs/dlg_shared_decks_preview.h
new file mode 100644
index 000000000..31820e3a0
--- /dev/null
+++ b/cockatrice/src/interface/widgets/dialogs/dlg_shared_decks_preview.h
@@ -0,0 +1,68 @@
+#ifndef COCKATRICE_DLG_SHARED_DECKS_PREVIEW_H
+#define COCKATRICE_DLG_SHARED_DECKS_PREVIEW_H
+
+#include
+#include
+
+class FlowWidget;
+class QCloseEvent;
+class QLabel;
+class QPushButton;
+class ServerInfo_DeckShareItem;
+class SharedDeckPreviewWidget;
+class CardDatabaseQuerier;
+
+/**
+ * @brief Non-modal preview of the decks contained in a shared-deck link.
+ *
+ * Lets the user pick which of the shared decks to open before anything is
+ * downloaded. Emits openRequested with the ids of the chosen decks, or
+ * cancelled when the user closes the dialog without choosing. Once the user
+ * picks, the dialog switches into a "downloading" state: the tiles and open
+ * buttons are disabled, a progress label shows the current download and Cancel
+ * stays functional so the download can be aborted.
+ */
+class DlgSharedDecksPreview : public QDialog
+{
+ Q_OBJECT
+
+public:
+ explicit DlgSharedDecksPreview(QWidget *parent,
+ const CardDatabaseQuerier *querier,
+ const QString &shareName,
+ qint64 expiresAt,
+ const QString &serverText,
+ const QList &items);
+
+ void setDownloadProgress(int done, int total, const QString ¤tDeckName);
+
+public slots:
+ void setDownloading(bool downloading);
+
+signals:
+ void openRequested(const QList &itemIds);
+ void cancelled();
+
+protected:
+ void closeEvent(QCloseEvent *event) override;
+
+private slots:
+ void openSelected();
+ void openAll();
+ void updateOpenSelectedEnabled();
+ void onCancel();
+
+private:
+ QList selectedItemIds() const;
+
+ FlowWidget *flowWidget;
+ QList tiles;
+ QList itemIds;
+ QPushButton *openSelectedButton;
+ QPushButton *openAllButton;
+ QLabel *downloadStatusLabel;
+ bool resultEmitted = false;
+ bool downloadInProgress = false;
+};
+
+#endif // COCKATRICE_DLG_SHARED_DECKS_PREVIEW_H
\ No newline at end of file
diff --git a/cockatrice/src/interface/widgets/general/home_tab_button_color.h b/cockatrice/src/interface/widgets/general/home_tab_button_color.h
index 1550b57e7..b45bd7a92 100644
--- a/cockatrice/src/interface/widgets/general/home_tab_button_color.h
+++ b/cockatrice/src/interface/widgets/general/home_tab_button_color.h
@@ -11,8 +11,8 @@ namespace HomeTabButtonColor
*/
enum Source
{
- Automatic, ///< Extract color from background, or use theme color if no background
- FromBackground, ///< Always extract color from background
+ FromThemeColors, ///< Use the theme's identity accent colors
+ FromBackground, ///< Extract colour from the background image
};
struct Entry
@@ -23,7 +23,7 @@ struct Entry
inline QList all()
{
- static QList entries = {{Automatic, QT_TR_NOOP("Automatic")},
+ static QList entries = {{FromThemeColors, QT_TR_NOOP("From theme colors")},
{FromBackground, QT_TR_NOOP("Extract from background")}};
return entries;
@@ -33,12 +33,12 @@ inline QList all()
* Safely converts an int into the corresponding Source.
*
* @param value The int value
- * @return The Source. Returns Source::Automatic if the value is not within range
+ * @return The Source. Returns Source::FromThemeColors if the value is not within range
*/
inline Source intToSource(int value)
{
if (value > FromBackground) {
- return Automatic; // default
+ return FromThemeColors; // default
}
return static_cast(value);
diff --git a/cockatrice/src/interface/widgets/general/home_widget.cpp b/cockatrice/src/interface/widgets/general/home_widget.cpp
index 10fcdcb43..648d315f9 100644
--- a/cockatrice/src/interface/widgets/general/home_widget.cpp
+++ b/cockatrice/src/interface/widgets/general/home_widget.cpp
@@ -2,6 +2,7 @@
#include "../../../client/settings/cache_settings.h"
#include "../../../interface/widgets/tabs/tab_supervisor.h"
+#include "../../pixel_map_generator.h"
#include "../../theme_manager.h"
#include "../../window_main.h"
#include "../cards/art_crop_attribution.h"
@@ -10,6 +11,8 @@
#include "home_tab_button_color.h"
#include
+#include
+#include
#include
#include
#include
@@ -20,7 +23,7 @@
#include
HomeWidget::HomeWidget(QWidget *parent, TabSupervisor *_tabSupervisor)
- : QWidget(parent), tabSupervisor(_tabSupervisor), background("theme:backgrounds/home"), overlay("theme:cockatrice")
+ : QWidget(parent), tabSupervisor(_tabSupervisor), background(themePixmap(QStringLiteral("backgrounds/home")))
{
layout = new QGridLayout(this);
@@ -52,16 +55,27 @@ HomeWidget::HomeWidget(QWidget *parent, TabSupervisor *_tabSupervisor)
// Lambda is cleaner to read than overloading this
connect(&SettingsCache::instance().appearance(), &AppearanceSettings::homeTabDisplayCardNameChanged, this,
[this] { repaint(); });
+ connect(&SettingsCache::instance().appearance(), &AppearanceSettings::homeTabBackgroundDimChanged, this,
+ [this] { repaint(); });
connect(&SettingsCache::instance(), &SettingsCache::themeChanged, this,
&HomeWidget::initializeBackgroundFromSource);
connect(&SettingsCache::instance(), &SettingsCache::themeChanged, this,
&HomeWidget::updateButtonsToBackgroundColor);
+ // Scheme flips (light/dark/system with an OS switch) fire on themeManager,
+ // not on SettingsCache::themeChanged, so re-resolve the variant background.
+ connect(themeManager, &ThemeManager::themeChanged, this, &HomeWidget::initializeBackgroundFromSource);
+ connect(themeManager, &ThemeManager::paletteChanged, this, &HomeWidget::updateButtonsToBackgroundColor);
+ connect(themeManager, &ThemeManager::paletteChanged, this, &HomeWidget::updateLogoOverlay);
connect(&SettingsCache::instance().appearance(), &AppearanceSettings::homeTabButtonColorChanged, this,
&HomeWidget::updateButtonsToBackgroundColor);
}
void HomeWidget::initializeBackgroundFromSource()
{
+ // The featured logo is theme/scheme-derived too; reload it alongside the
+ // background so a theme or appearance switch doesn't leave it stale.
+ updateLogoOverlay();
+
if (CardDatabaseManager::getInstance()->getLoadStatus() != LoadStatus::Ok) {
connect(CardDatabaseManager::getInstance(), &CardDatabase::cardDatabaseLoadingFinished, this,
&HomeWidget::initializeBackgroundFromSource);
@@ -74,7 +88,7 @@ void HomeWidget::initializeBackgroundFromSource()
switch (backgroundSourceType) {
case BackgroundSources::Theme:
cardChangeTimer->stop();
- background = QPixmap("theme:backgrounds/home");
+ background = themePixmap(QStringLiteral("backgrounds/home"));
backgroundSourceDeck = DeckList();
backgroundSourceCard->setCard(ExactCard());
updateButtonsToBackgroundColor();
@@ -100,32 +114,24 @@ void HomeWidget::loadBackgroundSourceDeck()
backgroundSourceDeck = deckOpt.has_value() ? deckOpt.value().deckList : DeckList();
}
-static bool isDefaultBackgroundAndTheme()
+static QPair paletteDerivedButtonColors()
{
- QString sourceId = SettingsCache::instance().appearance().getHomeTabBackgroundSource();
- return themeManager->isBuiltInTheme() && BackgroundSources::fromId(sourceId) == BackgroundSources::Theme;
+ return {themeManager->appColor(AppColor::AccentStrong), themeManager->appColor(AppColor::AccentSoft)};
}
QPair