diff options
Diffstat (limited to 'server')
| -rw-r--r-- | server/bin/main.dart | 10 | ||||
| -rw-r--r-- | server/lib/core/action_handler.dart | 30 | ||||
| -rw-r--r-- | server/lib/core/l10n/app_localizations.dart | 8 | ||||
| -rw-r--r-- | server/lib/core/service_locator.dart | 11 | ||||
| -rw-r--r-- | server/lib/core/settings.dart | 242 | ||||
| -rw-r--r-- | server/lib/core/settings_store.dart | 56 | ||||
| -rw-r--r-- | server/lib/core/ui_utils.dart | 12 | ||||
| -rw-r--r-- | server/lib/net/game_server.dart | 308 | ||||
| -rw-r--r-- | server/lib/net/protocol.dart | 101 | ||||
| -rw-r--r-- | server/test/net/multiplayer_test.dart | 9 | ||||
| -rw-r--r-- | server/test/net/settings_test.dart | 560 | ||||
| -rw-r--r-- | server/test/net/ws_test_helpers.dart | 13 | ||||
| -rw-r--r-- | server/test/resource/ui_utils_test.dart | 48 |
13 files changed, 1183 insertions, 225 deletions
diff --git a/server/bin/main.dart b/server/bin/main.dart index 7be16e2..60910a9 100644 --- a/server/bin/main.dart +++ b/server/bin/main.dart @@ -11,6 +11,8 @@ import 'package:logging/logging.dart'; import 'package:x_haven_server/core/game_data.dart'; import 'package:x_haven_server/core/save_store.dart'; import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/settings_store.dart'; import 'package:x_haven_server/core/state/game_state.dart'; import 'package:x_haven_server/net/app.dart'; import 'package:x_haven_server/net/game_server.dart'; @@ -60,10 +62,16 @@ Future<void> main(List<String> args) async { /// Registers the core singletons (file-backed save), loads the game data, /// initializes the game state, and restores the most recent save. Future<void> _bootGameCore({String dataDir = 'assets/data/'}) async { - setupCore(saveStore: FileSaveStore('saves')); + setupCore( + saveStore: FileSaveStore('saves'), + settingsStore: FileSettingsStore('saves'), + ); await getIt<GameData>().loadData(dataDir); final gameState = getIt<GameState>(); gameState.init(); + // Restore the persisted settings (saves/settings.json; no-op on first + // run) before the server answers the first `welcome` with them. + getIt<Settings>().loadFromDisk(); gameState.load(); _log.info('game core booted (command index ${gameState.commandIndex})'); } diff --git a/server/lib/core/action_handler.dart b/server/lib/core/action_handler.dart index 2c73bb1..5b3f8d4 100644 --- a/server/lib/core/action_handler.dart +++ b/server/lib/core/action_handler.dart @@ -89,10 +89,18 @@ class ActionHandler { saveState.load(_gameState); saveState.saveToDisk(_gameState); updateAllUI(); - _sendState('undo'); } lastEvent = const NoEvent(); + // The broadcast travels the undone action's description (as the + // reference's undo envelope does) but the *post-decrement* index: the + // reference reports the pre-decrement index because its clients keep + // local state and reconcile it; our stateless web clients take the + // wire index at face value, so it must equal the state position. + final undoneDescription = commandIndex < _commandDescriptions.length + ? _commandDescriptions[commandIndex] + : ''; commandIndex--; + if (saveState != null) _sendState('undo', description: undoneDescription); } } @@ -115,17 +123,17 @@ class ActionHandler { /// Broadcasts the current command index + description after an undo/redo, /// mirroring the reference app's server-side `StateEnvelope` send. - void _sendState(String action) { + /// [description] overrides the one at the current index (the undo path + /// sends the undone action's name; the redo path sends the redone one). + void _sendState(String action, {String? description}) { final idx = commandIndex; - if (idx >= 0 && idx < _commandDescriptions.length) { - _log.info( - 'server sends, $action index: $idx, description:${_commandDescriptions[idx]}', - ); - onAction?.call( - idx, - _commandDescriptions[idx], - const NoEvent().toJsonString(), - ); + // idx -1 is the baseline (empty history). The reference skips the send + // there because its clients keep local state; the stateless web clients + // only ever see what the server pushes, so the baseline goes out too. + if (idx >= -1 && idx < _commandDescriptions.length) { + final desc = description ?? (idx >= 0 ? _commandDescriptions[idx] : ''); + _log.info('server sends, $action index: $idx, description:$desc'); + onAction?.call(idx, desc, const NoEvent().toJsonString()); } } diff --git a/server/lib/core/l10n/app_localizations.dart b/server/lib/core/l10n/app_localizations.dart index dbf62a4..7a979d5 100644 --- a/server/lib/core/l10n/app_localizations.dart +++ b/server/lib/core/l10n/app_localizations.dart @@ -2018,6 +2018,14 @@ abstract class AppLocalizations { } AppLocalizations lookupAppLocalizations(Locale locale) { + // Lookup logic when language+script codes are specified (the reference + // app's gen-l10n output keys zh-Hant off the script code; this minimal + // [Locale] port carries it in [Locale.countryCode] — `Locale('zh', 'Hant')` + // from the `zh_Hant` setting). + if (locale.languageCode == 'zh' && locale.countryCode == 'Hant') { + return AppLocalizationsZhHant(); + } + // Lookup logic when only language code is specified. switch (locale.languageCode) { case 'de': diff --git a/server/lib/core/service_locator.dart b/server/lib/core/service_locator.dart index 8046359..08d0df3 100644 --- a/server/lib/core/service_locator.dart +++ b/server/lib/core/service_locator.dart @@ -3,6 +3,7 @@ import 'package:get_it/get_it.dart'; import 'game_data.dart'; import 'save_store.dart'; import 'settings.dart'; +import 'settings_store.dart'; import 'state/game_state.dart'; import 'translation_service.dart'; @@ -12,12 +13,16 @@ final getIt = GetIt.instance; /// /// The reference app's `setupGetIt()` registered the network services too /// (Communication, Network, Connection, Client) — those are replaced by the -/// WebSocket layer in Phase 2. [saveStore] defaults to in-memory; -/// `bin/main.dart` passes a [FileSaveStore] rooted at `saves/`. -void setupCore({SaveStore? saveStore}) { +/// WebSocket layer in Phase 2. [saveStore]/[settingsStore] default to +/// in-memory; `bin/main.dart` passes the [FileSaveStore]/[FileSettingsStore] +/// pair rooted at `saves/`. +void setupCore({SaveStore? saveStore, SettingsStore? settingsStore}) { getIt.registerLazySingleton<SaveStore>( () => saveStore ?? InMemorySaveStore(), ); + getIt.registerLazySingleton<SettingsStore>( + () => settingsStore ?? InMemorySettingsStore(), + ); getIt.registerLazySingleton<GameData>(() => GameData()); getIt.registerLazySingleton<Settings>(() => Settings()); getIt.registerLazySingleton<GameState>(() => GameState()); diff --git a/server/lib/core/settings.dart b/server/lib/core/settings.dart index 1f48a87..3f25afe 100644 --- a/server/lib/core/settings.dart +++ b/server/lib/core/settings.dart @@ -1,68 +1,56 @@ import 'dart:convert'; -import 'dart:io'; import 'package:x_haven_server/core/commands/load_character_save_command.dart'; import 'package:x_haven_server/core/commands/load_save_command.dart'; import 'package:x_haven_server/core/service_locator.dart'; import 'enums.dart'; +import 'settings_store.dart'; import 'state/game_state.dart'; -/// Server-side settings. +/// Server-side settings (Phase 6 split, PLAN.md section 4). /// -/// Ported from the reference app with the Flutter-specific parts removed: -/// no `ValueNotifier`s (plain fields), no window management, no -/// shared_preferences persistence (server settings persistence lands in -/// Phase 6). The `server`/`client` network settings are gone — this process -/// is always the server. +/// Only the **game-relevant** settings live here — everything the engine +/// reads: initiative gating, standee tracking/spawning, condition expiry, +/// the loot deck, the style, the reminder flags, AMD visibility, the +/// OG-Gloom hazard-terrain calculation, and [locale] (the command +/// descriptions are localized server-side via `command_l10n`). +/// +/// The reference app's pure-UI settings (list/bar scaling, fullscreen, +/// dark mode, the soft numpad, no-calculations display, the health wheel, +/// sections-in-main-view, character-AMD display, custom-content display, +/// scenario-name display, the power-mode display behaviour) are per-browser +/// preferences now and live in the web client's `localStorage` +/// (`web/src/lib/settings.ts`) — they no longer cross the wire. class Settings { - static const double _kDesktopBarScale = 1.6; - - double userScalingMainList = 1.0; - double userScalingBars = - (Platform.isWindows || Platform.isLinux || Platform.isMacOS) - ? _kDesktopBarScale - : 1.0; - double userScalingMenus = 1.0; - bool fullScreen = true; - bool darkMode = false; bool noInit = true; bool noStandees = false; bool randomStandees = false; - bool noCalculation = false; bool expireConditions = true; - bool hideLootDeck = false; - bool shimmer = Platform.isWindows || Platform.isLinux || Platform.isMacOS; - - /// Opt-in display power saving, in escalating tiers. Defaults to - /// [PowerMode.normal]: the higher tiers trade away polish or convenience, so - /// they are the user's choice to make. - /// - /// Most of the codebase should not read this directly — use - /// `reducePowerEnabled()` in `ui_utils.dart`, which asks the narrower - /// question "may I degrade visual quality?". - PowerMode powerMode = PowerMode.normal; - bool showScenarioNames = true; - bool showCustomContent = true; - bool showSectionsInMainView = true; - bool showReminders = true; bool autoAddStandees = true; bool autoAddSpawns = true; - bool showAmdDeck = true; + bool hideLootDeck = false; + Style style = Style.original; bool showBattleGoalReminder = true; + bool showReminders = true; + bool showAmdDeck = true; bool fhHazTerrainCalcInOGGloom = true; - bool showCharacterAMD = true; - bool enableHeathWheel = true; - - //used for both initiative and search menus - bool softNumpadInput = false; - Style style = Style.original; + /// The locale the command descriptions are generated in (the reference + /// app's `settings.locale`, ported with `command_l10n`). String locale = 'en'; + /// Multi-save game states: save name → serialized [GameState]. final Map<String, String> saves = {}; + + /// Character saves: `"$saveName\n${character.id}"` → `Character.toSave()`. + /// The `\n`-joined key is the reference app's save-id format (the save + /// name is human-visible, the character id is not). final Map<String, String> characterSaves = {}; + // --- save / load ---------------------------------------------------------- + + /// Loads the named save into the game state (an undoable command). void loadSave(String saveName, {GameState? gameState}) { String? save = saves[saveName]; if (save != null) { @@ -71,56 +59,100 @@ class Settings { } } + /// Stores a snapshot of the current game state under [saveName]. void saveState(String saveName, {GameState? gameState}) { saves[saveName] = (gameState ?? getIt<GameState>()).toString(); + saveToDisk(); } void deleteSave(String saveName) { saves.remove(saveName); + saveToDisk(); } - void loadCharacterSave(String saveName, {GameState? gameState}) { - String? save = characterSaves[saveName]; + /// Loads the named character save (an undoable command). + void loadCharacterSave(String saveId, {GameState? gameState}) { + String? save = characterSaves[saveId]; if (save != null) { final gs = gameState ?? getIt<GameState>(); - gs.action(LoadCharacterSaveCommand(saveName, save, gameState: gs)); + final name = saveId.split('\n').first; + gs.action(LoadCharacterSaveCommand(name, save, gameState: gs)); } } void saveCharacterState(String saveName, Character character) { characterSaves['$saveName\n${character.id}'] = character.toSave(); + saveToDisk(); } void deleteCharacterSave(String saveId) { characterSaves.remove(saveId); + saveToDisk(); + } + + // --- persistence ----------------------------------------------------------- + + /// Writes the settings to disk (the reference app's `saveToDisk` — called + /// after every change, so a restart restores the full settings + save list). + void saveToDisk() { + getIt<SettingsStore>().write(toString()); + } + + /// Restores the settings from disk (no-op when nothing was stored). + void loadFromDisk() { + final stored = getIt<SettingsStore>().read(); + if (stored == null) return; + try { + loadFromData(stored); + } catch (_) { + // A corrupt settings file must not take the server down — start from + // the defaults (the reference app fails the same lookup silently). + } + } + + // --- wire payload ------------------------------------------------------------ + + /// The payload the server sends to every client (the `settings` message + /// and the `welcome` field): the game-relevant fields plus the save *names* + /// and character-save entries. The save **content** never crosses the wire + /// — it can be large, and only the server needs it. + Map<String, dynamic> forClient() { + return { + 'noInit': noInit, + 'noStandees': noStandees, + 'randomStandees': randomStandees, + 'expireConditions': expireConditions, + 'autoAddStandees': autoAddStandees, + 'autoAddSpawns': autoAddSpawns, + 'hideLootDeck': hideLootDeck, + 'style': style.index, + 'showBattleGoalReminder': showBattleGoalReminder, + 'showReminders': showReminders, + 'showAmdDeck': showAmdDeck, + 'fhHazTerrainCalcInOGGloom': fhHazTerrainCalcInOGGloom, + 'locale': locale, + 'saves': saves.keys.toList(), + 'characterSaves': [ + for (final entry in characterSaves.entries) + { + 'name': entry.key.split('\n').first, + 'characterId': entry.key.split('\n').last, + }, + ], + }; } + // --- disk format -------------------------------------------------------------- + /// Applies a settings JSON previously produced by [toString]. /// /// Ported from the reference app's `loadFromDisk` field parsing, minus the - /// network/settings persistence parts. (Server settings persistence lands - /// in Phase 6.) + /// client-only fields (Phase 6 split). Unknown fields are ignored, so a + /// file written by the pre-split server still loads. void loadFromData(String state) { - Map<String, dynamic> data = jsonDecode(state); + final data = jsonDecode(state); + if (data is! Map<String, dynamic>) return; - if (data["userScalingMainList"] != null) { - userScalingMainList = (data["userScalingMainList"] as num).toDouble(); - } - if (data["userScalingBars"] != null) { - userScalingBars = (data["userScalingBars"] as num).toDouble(); - } - if (data["userScalingMenus"] != null) { - userScalingMenus = (data["userScalingMenus"] as num).toDouble(); - } - if (data["fullScreen"] != null) { - fullScreen = data["fullScreen"] as bool; - } - if (data["softNumpadInput"] != null) { - softNumpadInput = data["softNumpadInput"] as bool; - } - if (data["darkMode"] != null) { - darkMode = data["darkMode"] as bool; - } if (data["noInit"] != null) { noInit = data["noInit"] as bool; } @@ -130,84 +162,46 @@ class Settings { if (data["randomStandees"] != null) { randomStandees = data["randomStandees"] as bool; } - if (data["noCalculation"] != null) { - noCalculation = data["noCalculation"] as bool; - } - if (data["hideLootDeck"] != null) { - hideLootDeck = data["hideLootDeck"] as bool; - } - if (data["style"] != null) { - style = Style.values[data["style"] as int]; - } if (data["expireConditions"] != null) { expireConditions = data["expireConditions"] as bool; } - - if (data["shimmer"] != null) { - shimmer = data["shimmer"] as bool; + if (data["autoAddStandees"] != null) { + autoAddStandees = data["autoAddStandees"] as bool; } - final powerModeIdx = data["powerMode"] as int?; - if (powerModeIdx != null && - powerModeIdx >= 0 && - powerModeIdx < PowerMode.values.length) { - powerMode = PowerMode.values[powerModeIdx]; + if (data["autoAddSpawns"] != null) { + autoAddSpawns = data["autoAddSpawns"] as bool; } - if (data["showScenarioNames"] != null) { - showScenarioNames = data["showScenarioNames"] as bool; + if (data["hideLootDeck"] != null) { + hideLootDeck = data["hideLootDeck"] as bool; } - if (data["showCustomContent"] != null) { - showCustomContent = data["showCustomContent"] as bool; + if (data["style"] != null) { + style = Style.values[data["style"] as int]; } - - if (data["showSectionsInMainView"] != null) { - showSectionsInMainView = data["showSectionsInMainView"] as bool; + if (data["showBattleGoalReminder"] != null) { + showBattleGoalReminder = data["showBattleGoalReminder"] as bool; } - if (data["showReminders"] != null) { showReminders = data["showReminders"] as bool; } - - if (data["autoAddStandees"] != null) { - autoAddStandees = data["autoAddStandees"] as bool; - } - - if (data["autoAddSpawns"] != null) { - autoAddSpawns = data["autoAddSpawns"] as bool; - } - if (data["showAmdDeck"] != null) { showAmdDeck = data["showAmdDeck"] as bool; } - - if (data["showBattleGoalReminder"] != null) { - showBattleGoalReminder = data["showBattleGoalReminder"] as bool; - } - if (data["fhHazTerrainCalcInOGGloom"] != null) { fhHazTerrainCalcInOGGloom = data["fhHazTerrainCalcInOGGloom"] as bool; } - - if (data["showCharacterAMD"] != null) { - showCharacterAMD = data["showCharacterAMD"] as bool; - } - - if (data["enableHeathWheel"] != null) { - enableHeathWheel = data["enableHeathWheel"] as bool; - } - if (data["locale"] != null) { locale = data["locale"] as String; } if (data["saves"] != null) { - Map<String, dynamic> map = data["saves"] as Map<String, dynamic>; + final map = data["saves"] as Map<String, dynamic>; for (final key in map.keys) { saves[key] = map[key] as String; } } if (data["characterSaves"] != null) { - Map<String, dynamic> map = data["characterSaves"] as Map<String, dynamic>; + final map = data["characterSaves"] as Map<String, dynamic>; for (final key in map.keys) { characterSaves[key] = map[key] as String; } @@ -217,32 +211,18 @@ class Settings { @override String toString() { return '{' - '"userScalingMainList": $userScalingMainList, ' - '"userScalingBars": $userScalingBars, ' - '"userScalingMenus": $userScalingMenus, ' - '"fullScreen": $fullScreen, ' - '"softNumpadInput": $softNumpadInput, ' '"noInit": $noInit, ' '"noStandees": $noStandees, ' '"randomStandees": $randomStandees, ' - '"noCalculation": $noCalculation, ' '"expireConditions": $expireConditions, ' + '"autoAddStandees": $autoAddStandees, ' + '"autoAddSpawns": $autoAddSpawns, ' '"hideLootDeck": $hideLootDeck, ' '"style": ${style.index}, ' - '"darkMode": $darkMode, ' - '"shimmer": $shimmer, ' - '"powerMode": ${powerMode.index}, ' - '"showScenarioNames": $showScenarioNames, ' - '"showCustomContent": $showCustomContent, ' - '"showSectionsInMainView": $showSectionsInMainView, ' + '"showBattleGoalReminder": $showBattleGoalReminder, ' '"showReminders": $showReminders, ' - '"autoAddStandees": $autoAddStandees, ' - '"autoAddSpawns": $autoAddSpawns, ' '"showAmdDeck": $showAmdDeck, ' - '"showBattleGoalReminder": $showBattleGoalReminder, ' '"fhHazTerrainCalcInOGGloom": $fhHazTerrainCalcInOGGloom, ' - '"showCharacterAMD": $showCharacterAMD, ' - '"enableHeathWheel": $enableHeathWheel, ' '"locale": "$locale", ' '"saves": ${jsonEncode(saves)}, ' '"characterSaves": ${jsonEncode(characterSaves)} ' diff --git a/server/lib/core/settings_store.dart b/server/lib/core/settings_store.dart new file mode 100644 index 0000000..520ed97 --- /dev/null +++ b/server/lib/core/settings_store.dart @@ -0,0 +1,56 @@ +import 'dart:io'; + +import 'package:path/path.dart' as p; + +/// Persistent store for the server settings JSON (Phase 6: the settings +/// split). Same contract as [SaveStore]: the server changes a setting, and +/// "written through on every change" must be on disk when [write] returns. +abstract class SettingsStore { + /// Returns the stored settings JSON, or null if nothing has been saved yet. + String? read(); + + /// Writes the settings JSON. + void write(String data); + + /// Removes the stored settings. + void clear(); +} + +/// In-memory [SettingsStore] — used by tests. +class InMemorySettingsStore implements SettingsStore { + String? _data; + + @override + String? read() => _data; + + @override + void write(String data) => _data = data; + + @override + void clear() => _data = null; +} + +/// File-backed [SettingsStore] writing one JSON document into [directory]. +class FileSettingsStore implements SettingsStore { + final File _file; + + FileSettingsStore(String directory) + : _file = File(p.join(directory, 'settings.json')); + + @override + String? read() => _file.existsSync() ? _file.readAsStringSync() : null; + + @override + void write(String data) { + final dir = _file.parent; + if (!dir.existsSync()) dir.createSync(recursive: true); + // Synchronous write: the same kill −9 race the save store had — the + // settings must be on disk when [write] returns. + _file.writeAsStringSync(data, flush: true); + } + + @override + void clear() { + if (_file.existsSync()) _file.deleteSync(); + } +} diff --git a/server/lib/core/ui_utils.dart b/server/lib/core/ui_utils.dart deleted file mode 100644 index f6900d8..0000000 --- a/server/lib/core/ui_utils.dart +++ /dev/null @@ -1,12 +0,0 @@ -import 'package:x_haven_server/core/service_locator.dart'; - -import 'enums.dart'; -import 'settings.dart'; - -/// Minimal port of the reference app's `ui_utils.dart` for the headless -/// engine: only [reducePowerEnabled], which `line_builder` consults. -/// The rest of the reference file is pure widget styling (Phase 3+). -bool reducePowerEnabled({Settings? settings}) { - final resolved = settings ?? getIt<Settings>(); - return resolved.powerMode == PowerMode.reducePower; -} diff --git a/server/lib/net/game_server.dart b/server/lib/net/game_server.dart index aa9aee3..5a95194 100644 --- a/server/lib/net/game_server.dart +++ b/server/lib/net/game_server.dart @@ -17,8 +17,11 @@ import 'package:web_socket_channel/web_socket_channel.dart'; import 'package:x_haven_server/core/commands/add_character_command.dart'; import 'package:x_haven_server/core/commands/command_registry.dart'; +import 'package:x_haven_server/core/commands/track_standees_command.dart'; import 'package:x_haven_server/core/enums.dart'; import 'package:x_haven_server/core/game_methods.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/settings.dart'; import 'package:x_haven_server/core/state/game_state.dart'; import 'protocol.dart'; @@ -205,6 +208,20 @@ class GameServer { _handleUndoRedo(connection, undo: true); case Protocol.redo: _handleUndoRedo(connection, undo: false); + case Protocol.setSetting: + _handleSetSetting(connection, message); + case Protocol.save: + _handleSave(connection, message); + case Protocol.loadSave: + _handleLoadSave(connection, message); + case Protocol.deleteSave: + _handleDeleteSave(connection, message); + case Protocol.saveCharacter: + _handleSaveCharacter(connection, message); + case Protocol.loadCharacterSave: + _handleLoadCharacterSave(connection, message); + case Protocol.deleteCharacterSave: + _handleDeleteCharacterSave(connection, message); default: connection.send( Protocol.errorMessage( @@ -258,23 +275,44 @@ class GameServer { Map<String, dynamic> _welcomeFor(_Connection connection) { final session = connection.session; - final index = _gameState.commandIndex; - final descriptions = _gameState.commandDescriptions; - final String? description = - index >= 0 && index < descriptions.length - ? descriptions[index] - : null; return Protocol.welcomeMessage( session: session.id, role: session.role, - index: index, - description: description, + index: _gameState.commandIndex, + description: _currentDescription(), event: null, state: _serializeFor(connection), seats: _sessions.seatsForState(_gameState), + settings: _settings().forClient(), + historyLength: _gameState.commandDescriptions.length, + redoDescription: _redoDescription(), + undoDescription: _undoDescription(), ); } + /// The description of the action at the current index (null at the + /// baseline), for the client's undo label. + String? _currentDescription() { + final index = _gameState.commandIndex; + final descriptions = _gameState.commandDescriptions; + if (index < 0 || index >= descriptions.length) return null; + return descriptions[index]; + } + + /// The description of the next action (null when nothing can be redone), + /// for the client's `Redo: …` label. + String? _redoDescription() { + final index = _gameState.commandIndex + 1; + final descriptions = _gameState.commandDescriptions; + if (index < 0 || index >= descriptions.length) return null; + return descriptions[index]; + } + + /// The description of the action at the current index — what an undo would + /// undo (null at the baseline), for the client's `Undo: …` label. The + /// reference app's `MainMenuViewModel.undoDescription` getter, ported. + String? _undoDescription() => _currentDescription(); + // --- claims --------------------------------------------------------------- /// `{t: claim, characterId}` — any session may claim an unclaimed @@ -442,23 +480,262 @@ class GameServer { } void _handleUndoRedo(_Connection connection, {required bool undo}) { + if (!_requirePlayer(connection, 'undo or redo')) return; + if (undo) { + _gameState.undo(); + } else { + _gameState.redo(); + } + } + + // --- Phase 6: settings and multi-save -------------------------------------- + + /// The server-side settings (the game-relevant half of the reference + /// app's `Settings`; Phase 6 split, PLAN.md section 4). + Settings _settings() => getIt<Settings>(); + + /// The locales the client may select (the reference app's `supportedLocales` + /// plus `zh_Hant`, which the gen-l10n arb set covers). + static const List<String> _kSettableLocales = [ + 'en', 'de', 'es', 'fr', 'ko', 'pl', 'ru', 'th', 'zh', 'zh_Hant', + ]; + + /// Gate for player-only messages (undo/redo, settings, saves): answers the + /// sender with a clear `error` when the session has no seat. + bool _requirePlayer(_Connection connection, String what) { if (!connection.handshaken) { _notHandshaken(connection); - return; + return false; } if (!connection.session.isPlayer) { connection.send( Protocol.errorMessage( Protocol.errForbidden, - 'spectators cannot undo or redo — claim a character first', + 'spectators cannot $what — claim a character first', + ), + ); + return false; + } + return true; + } + + /// `{t: setSetting, name, value}` — one server-side (game-relevant) setting + /// (Phase 6). Persisted immediately and broadcast to every screen, since + /// the setting changes game behaviour for everyone (e.g. standee tracking, + /// the loot deck, reminders). + /// + /// `noStandees` additionally runs `TrackStandeesCommand` (the reference + /// app's settings menu does the same — the command itself writes the + /// setting and adjusts the already-added monsters' standees). + void _handleSetSetting(_Connection connection, Map<String, dynamic> message) { + if (!_requirePlayer(connection, 'change settings')) return; + final name = message['name']; + final value = message['value']; + if (name is! String || name.isEmpty) { + connection.send( + Protocol.errorMessage( + Protocol.errBadRequest, + 'setSetting requires a non-empty "name" string', ), ); return; } - if (undo) { - _gameState.undo(); - } else { - _gameState.redo(); + final s = _settings(); + var ok = true; + switch (name) { + case 'noInit': + ok = value is bool && (s.noInit = value); + case 'noStandees': + ok = value is bool && (s.noStandees = value); + case 'randomStandees': + ok = value is bool && (s.randomStandees = value); + case 'expireConditions': + ok = value is bool && (s.expireConditions = value); + case 'autoAddStandees': + ok = value is bool && (s.autoAddStandees = value); + case 'autoAddSpawns': + ok = value is bool && (s.autoAddSpawns = value); + case 'hideLootDeck': + ok = value is bool && (s.hideLootDeck = value); + case 'showBattleGoalReminder': + ok = value is bool && (s.showBattleGoalReminder = value); + case 'showReminders': + ok = value is bool && (s.showReminders = value); + case 'showAmdDeck': + ok = value is bool && (s.showAmdDeck = value); + case 'fhHazTerrainCalcInOGGloom': + ok = value is bool && (s.fhHazTerrainCalcInOGGloom = value); + case 'style': + ok = value is int && value >= 0 && value < Style.values.length; + if (ok) s.style = Style.values[value]; + case 'locale': + ok = value is String && _kSettableLocales.contains(value); + if (ok) s.locale = value; + default: + ok = false; + } + if (!ok) { + connection.send( + Protocol.errorMessage( + Protocol.errRejected, + 'invalid setting "$name" (value $value)', + ), + ); + return; + } + if (name == 'noStandees') { + // The reference toggles this through the command so the standing + // monsters' standees are adjusted; the command writes the setting + // itself (track = !noStandees), so the value survives the execute. + _gameState.action( + TrackStandeesCommand(!s.noStandees, gameState: _gameState, settings: s), + ); + } + s.saveToDisk(); + _broadcastSettings(); + } + + /// `{t: save, name}` — snapshot the current game state under [name] + /// (multi-save; the content lives only on the server). + void _handleSave(_Connection connection, Map<String, dynamic> message) { + if (!_requirePlayer(connection, 'save game states')) return; + final name = _nonEmptyName(connection, message, 'save'); + if (name == null) return; + _settings().saveState(name); + _broadcastSettings(); + } + + /// `{t: loadSave, name}` — runs `LoadSaveCommand` (an undoable action, so + /// the index advances and every screen receives the loaded state). + void _handleLoadSave(_Connection connection, Map<String, dynamic> message) { + if (!_requirePlayer(connection, 'load save states')) return; + final name = _nonEmptyName(connection, message, 'loadSave'); + if (name == null) return; + final s = _settings(); + if (!s.saves.containsKey(name)) { + connection.send( + Protocol.errorMessage(Protocol.errRejected, 'no save named "$name"'), + ); + return; + } + s.loadSave(name); + // The loaded state may contain different characters — prune stale seats. + _syncSeats(); + } + + /// `{t: deleteSave, name}`. + void _handleDeleteSave(_Connection connection, Map<String, dynamic> message) { + if (!_requirePlayer(connection, 'delete save states')) return; + final name = _nonEmptyName(connection, message, 'deleteSave'); + if (name == null) return; + _settings().deleteSave(name); + _broadcastSettings(); + } + + /// `{t: saveCharacter, name, characterId}` — snapshot one character's + /// state (the reference `saveCharacterState`). + void _handleSaveCharacter(_Connection connection, Map<String, dynamic> message) { + if (!_requirePlayer(connection, 'save characters')) return; + final name = _nonEmptyName(connection, message, 'saveCharacter'); + if (name == null) return; + final characterId = message['characterId']; + if (characterId is! String || characterId.isEmpty) { + connection.send( + Protocol.errorMessage( + Protocol.errBadRequest, + 'saveCharacter requires a non-empty "characterId" string', + ), + ); + return; + } + final item = _gameState.currentList.firstWhereOrNull( + (item) => item is Character && item.id == characterId, + ); + final character = item is Character ? item : null; + if (character == null) { + connection.send( + Protocol.errorMessage( + Protocol.errRejected, + 'no character with id "$characterId" in the current list', + ), + ); + return; + } + _settings().saveCharacterState(name, character); + _broadcastSettings(); + } + + /// `{t: loadCharacterSave, saveId}` — runs `LoadCharacterSaveCommand` + /// (undoable). [saveId] is the `"$name\n${characterId}"` key. + void _handleLoadCharacterSave(_Connection connection, Map<String, dynamic> message) { + if (!_requirePlayer(connection, 'load character saves')) return; + final saveId = message['saveId']; + if (saveId is! String || saveId.isEmpty) { + connection.send( + Protocol.errorMessage( + Protocol.errBadRequest, + 'loadCharacterSave requires a non-empty "saveId" string', + ), + ); + return; + } + final s = _settings(); + if (!s.characterSaves.containsKey(saveId)) { + connection.send( + Protocol.errorMessage( + Protocol.errRejected, + 'no character save with id "$saveId"', + ), + ); + return; + } + s.loadCharacterSave(saveId); + _syncSeats(); + } + + /// `{t: deleteCharacterSave, saveId}`. + void _handleDeleteCharacterSave(_Connection connection, Map<String, dynamic> message) { + if (!_requirePlayer(connection, 'delete character saves')) return; + final saveId = message['saveId']; + if (saveId is! String || saveId.isEmpty) { + connection.send( + Protocol.errorMessage( + Protocol.errBadRequest, + 'deleteCharacterSave requires a non-empty "saveId" string', + ), + ); + return; + } + _settings().deleteCharacterSave(saveId); + _broadcastSettings(); + } + + /// The `"name"` field of a save message, with the bad-request answer sent + /// when it is missing/wrong-typed (returns null in that case). + String? _nonEmptyName( + _Connection connection, + Map<String, dynamic> message, + String verb, + ) { + final name = message['name']; + if (name is! String || name.isEmpty) { + connection.send( + Protocol.errorMessage( + Protocol.errBadRequest, + '$verb requires a non-empty "name" string', + ), + ); + return null; + } + return name; + } + + /// Broadcasts the current settings payload to every connection (after a + /// setting change or a save-list change). + void _broadcastSettings() { + final payload = _settings().forClient(); + for (final connection in _activeConnections()) { + connection.send(Protocol.settingsMessage(payload)); } } @@ -476,6 +753,9 @@ class GameServer { description: description, event: event, state: _serializeFor(connection), + historyLength: _gameState.commandDescriptions.length, + redoDescription: _redoDescription(), + undoDescription: _undoDescription(), ), ); } diff --git a/server/lib/net/protocol.dart b/server/lib/net/protocol.dart index c3030e1..9356cf1 100644 --- a/server/lib/net/protocol.dart +++ b/server/lib/net/protocol.dart @@ -18,10 +18,20 @@ abstract class Protocol { static const String redo = 'redo'; static const String ping = 'ping'; + // Phase 6 (settings + multi-save) — players only. + static const String setSetting = 'setSetting'; + static const String save = 'save'; + static const String loadSave = 'loadSave'; + static const String deleteSave = 'deleteSave'; + static const String saveCharacter = 'saveCharacter'; + static const String loadCharacterSave = 'loadCharacterSave'; + static const String deleteCharacterSave = 'deleteCharacterSave'; + // Server -> client message types. static const String welcome = 'welcome'; static const String update = 'update'; static const String seats = 'seats'; + static const String settings = 'settings'; static const String error = 'error'; static const String pong = 'pong'; @@ -72,13 +82,24 @@ abstract class Protocol { /// secrets included and everyone else's masked (PLAN.md section 3.4). /// [seats] maps every character in the current list to its owning session /// id, or null when unclaimed. + /// + /// [settings] carries the server-side (game-relevant) settings + save + /// names (Phase 6). [historyLength] / [redoDescription] / + /// [undoDescription] let the client render the undo/redo UI without + /// holding the history itself (the labels are the reference app's + /// `MainMenuViewModel.undoDescription` / `redoDescription` — null when + /// that direction is exhausted). static Map<String, dynamic> welcomeMessage({ required String session, required String role, required int index, required Map<String, dynamic> state, required Map<String, dynamic> seats, + required Map<String, dynamic> settings, + required int historyLength, String? description, + String? redoDescription, + String? undoDescription, Object? event, }) { return { @@ -88,30 +109,110 @@ abstract class Protocol { 'role': role, 'index': index, 'description': description, + 'historyLength': historyLength, + 'redoDescription': redoDescription, + 'undoDescription': undoDescription, 'event': event, 'state': state, 'seats': seats, + 'settings': settings, }; } /// Full-state push sent to every connection after a command, undo or redo /// (the equivalent of the reference app's `{i, d, e, s}` envelope). /// [state] is serialized per connection by the server. + /// + /// [index] always equals the state position (the undo path reports the + /// post-decrement index; see `ActionHandler.undo`). [historyLength] / + /// [redoDescription] / [undoDescription] let the client render the + /// undo/redo UI (enablement + labels) from the snapshot alone. static Map<String, dynamic> updateMessage({ required int index, required String description, required Object? event, required Map<String, dynamic> state, + required int historyLength, + String? redoDescription, + String? undoDescription, }) { return { 't': update, 'index': index, 'description': description, + 'historyLength': historyLength, + 'redoDescription': redoDescription, + 'undoDescription': undoDescription, 'event': event, 'state': state, }; } + /// Settings broadcast (Phase 6): the server-side settings + save names, + /// sent to every connection when a setting changes or the save list does. + /// Also embedded in `welcome`. The save *content* never crosses the wire. + static Map<String, dynamic> settingsMessage(Map<String, dynamic> settings) => + { + 't': Protocol.settings, + 'settings': settings, + }; + + // --- Phase 6 client messages (players only) ------------------------------- + + /// Client message setting one server-side (game-relevant) setting. + /// [name] is one of the known setting names; [value] its new value + /// (booleans, or the style enum index / locale code strings). + static Map<String, dynamic> setSettingMessage( + String name, + Object value, + ) => { + 't': setSetting, + 'name': name, + 'value': value, + }; + + /// Client message saving the current game state to a named save slot. + static Map<String, dynamic> saveMessage(String name) => { + 't': save, + 'name': name, + }; + + /// Client message loading a named save (runs `LoadSaveCommand` — an + /// undoable action, so it advances the command index). + static Map<String, dynamic> loadSaveMessage(String name) => { + 't': loadSave, + 'name': name, + }; + + /// Client message deleting a named save. + static Map<String, dynamic> deleteSaveMessage(String name) => { + 't': deleteSave, + 'name': name, + }; + + /// Client message saving one character's state under [name]. + static Map<String, dynamic> saveCharacterMessage( + String name, + String characterId, + ) => { + 't': saveCharacter, + 'name': name, + 'characterId': characterId, + }; + + /// Client message loading a character save. [saveId] is the + /// `"$name\n${characterId}"` key the server stores it under. + static Map<String, dynamic> loadCharacterSaveMessage(String saveId) => { + 't': loadCharacterSave, + 'saveId': saveId, + }; + + /// Client message deleting a character save. + static Map<String, dynamic> deleteCharacterSaveMessage(String saveId) => { + 't': deleteCharacterSave, + 'saveId': saveId, + }; + /// Seat-ownership broadcast: every character in the current list mapped to /// its owning session id, or null when unclaimed. The UI enables inputs /// only on the owning player's screen from this map. diff --git a/server/test/net/multiplayer_test.dart b/server/test/net/multiplayer_test.dart index e3bb225..b336501 100644 --- a/server/test/net/multiplayer_test.dart +++ b/server/test/net/multiplayer_test.dart @@ -376,13 +376,16 @@ void main() { reason: 'current', ); - // undo: the state rolls back (the index carries the undone action's - // index, exactly like the reference app's server-side send). + // undo: the state rolls back. The wire index is the post-decrement one + // (the reference reports the pre-decrement index — its clients keep + // local state; our stateless web clients take the index at face value, + // so it must equal the state position). The description is the undone + // action's, as in the reference. table.bob.send({'t': 'undo'}); for (final client in table.everyone) { final update = await client.nextOf('update'); state = stateOf(update); - expect(update['index'], indexAtTurnDone); + expect(update['index'], indexAtTurnDone - 1); expect( TestClient.characterIn(state, 'Banner Spear')?['turnState'], 1, diff --git a/server/test/net/settings_test.dart b/server/test/net/settings_test.dart new file mode 100644 index 0000000..677af11 --- /dev/null +++ b/server/test/net/settings_test.dart @@ -0,0 +1,560 @@ +/// Phase 6 / Milestone M6: the settings split and multi-save over the wire +/// (PLAN.md section 4): +/// +/// * the `welcome` carries the server-side settings + save names +/// * `setSetting` is validated, broadcast to every screen, and persisted +/// * spectators cannot change settings or manage saves (role gate) +/// * `noStandees` toggles through `TrackStandeesCommand` (undoable) +/// * the locale setting localizes subsequent command descriptions +/// * `historyLength` / `redoDescription` drive the client undo/redo UI +/// * save → load (an undoable action) → delete of game states +/// * save → load → delete of character saves +/// * settings + saves survive a server restart (file-backed store) +library; + +import 'dart:io'; + +import 'package:test/test.dart'; +import 'package:x_haven_server/core/enums.dart'; +import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/settings_store.dart'; +import 'package:x_haven_server/net/protocol.dart'; + +import 'ws_test_helpers.dart'; + +/// A table: one player (alice, owns 'Blinkblade') and one spectator (bob). +class Table { + late TestGameServer server; + late TestClient alice; + late TestClient bob; + late Map<String, dynamic> aliceWelcome; + + Future<Table> setup({SettingsStore? settingsStore}) async { + server = await TestGameServer.boot(settingsStore: settingsStore); + try { + alice = await TestClient.connect(server.wsUrl); + bob = await TestClient.connect(server.wsUrl); + alice.sendHello(); + bob.sendHello(); + aliceWelcome = await alice.nextOf('welcome'); + await bob.nextOf('welcome'); + + // Alice adds a character: the session that adds one owns it and + // becomes a player (bob stays a spectator). + alice.sendCmd( + 'addCharacter', + {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, + ); + for (final client in [alice, bob]) { + await client.nextOf('update'); + await client.nextOf('seats'); + } + return this; + } catch (_) { + await server.shutdown(); + rethrow; + } + } + + Future<void> teardown() async { + await alice.close(); + await bob.close(); + await server.shutdown(); + } +} + +void main() { + group('settings over the wire', () { + test('welcome carries the settings payload with empty save lists', + () async { + final table = await Table().setup(); + try { + final settings = table.aliceWelcome['settings'] as Map; + expect(settings['locale'], 'en'); + expect(settings['style'], 2, reason: 'Style.original'); + expect(settings['saves'], isEmpty); + expect(settings['characterSaves'], isEmpty); + // Every server-side (game-relevant) field is present. + for (final field in [ + 'noInit', 'noStandees', 'randomStandees', 'expireConditions', + 'autoAddStandees', 'autoAddSpawns', 'hideLootDeck', + 'showBattleGoalReminder', 'showReminders', 'showAmdDeck', + 'fhHazTerrainCalcInOGGloom', + ]) { + expect(settings[field], isA<bool>(), reason: field); + } + } finally { + await table.teardown(); + } + }); + + test('setSetting is broadcast to every screen, persisted, and welcome-served', + () async { + final table = await Table().setup(); + try { + table.alice.send(Protocol.setSettingMessage('hideLootDeck', true)); + + final aliceGot = await table.alice.nextOf('settings'); + final bobGot = await table.bob.nextOf('settings'); + expect(aliceGot['settings']['hideLootDeck'], isTrue); + expect(bobGot['settings']['hideLootDeck'], isTrue); + expect(getIt<Settings>().hideLootDeck, isTrue); + + // A reconnecting client sees it in the welcome too. + final carol = await TestClient.connect(table.server.wsUrl); + carol.sendHello(); + final welcome = await carol.nextOf('welcome'); + expect((welcome['settings'] as Map)['hideLootDeck'], isTrue); + await carol.close(); + } finally { + await table.teardown(); + } + }); + + test('spectators cannot change settings or manage saves', () async { + final table = await Table().setup(); + try { + table.bob.send(Protocol.setSettingMessage('noInit', false)); + final error = await table.bob.nextOf('error'); + expect(error['code'], Protocol.errForbidden); + expect(getIt<Settings>().noInit, isTrue, reason: 'unchanged'); + + table.bob.send(Protocol.saveMessage('slot')); + expect((await table.bob.nextOf('error'))['code'], Protocol.errForbidden); + + table.bob.send(Protocol.loadSaveMessage('slot')); + expect((await table.bob.nextOf('error'))['code'], Protocol.errForbidden); + + table.bob.send(Protocol.saveCharacterMessage('slot', 'Blinkblade')); + expect((await table.bob.nextOf('error'))['code'], Protocol.errForbidden); + } finally { + await table.teardown(); + } + }); + + test('invalid setting names and values are rejected', () async { + final table = await Table().setup(); + try { + // Unknown name → rejected (the switch has no matching case). + table.alice.send(Protocol.setSettingMessage('bogus', true)); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + + // Wrong value types → rejected. + table.alice.send(Protocol.setSettingMessage('style', 'notAnInt')); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + table.alice.send(Protocol.setSettingMessage('locale', 'xx')); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + table.alice.send(Protocol.setSettingMessage('noInit', 'yes')); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + + // Missing name → bad request. + table.alice.send(Protocol.setSettingMessage('', true)); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errBadRequest, + ); + + // Nothing was applied. + final settings = getIt<Settings>(); + expect(settings.style, Style.original); + expect(settings.locale, 'en'); + expect(settings.noInit, isTrue); + } finally { + await table.teardown(); + } + }); + + test('style and locale are settable', () async { + final table = await Table().setup(); + try { + table.alice.send(Protocol.setSettingMessage('style', 1)); + final styleUpdate = await table.alice.nextOf('settings'); + expect((styleUpdate['settings'] as Map)['style'], 1); + expect(getIt<Settings>().style, Style.gloomhaven); + + table.alice.send(Protocol.setSettingMessage('locale', 'de')); + await table.bob.nextOf('settings'); // drain bob's copy + final localeUpdate = await table.alice.nextOf('settings'); + expect((localeUpdate['settings'] as Map)['locale'], 'de'); + } finally { + await table.teardown(); + } + }); + + test('noStandees toggles through TrackStandeesCommand (undoable)', () async { + final table = await Table().setup(); + try { + // After addCharacter the index is 0; the toggle adds one action. + table.alice.send(Protocol.setSettingMessage('noStandees', true)); + + // The command runs first: an update broadcast … + final update = await table.alice.nextOf('update'); + expect(update['index'], 1); + expect(update['description'], "Don't track standees"); + // … then the settings broadcast. + final settings = await table.alice.nextOf('settings'); + expect((settings['settings'] as Map)['noStandees'], isTrue); + + // The underlying command is undoable: the wire index is the + // post-decrement one, the description the undone action's. (As in + // the reference app, the setting itself is app state, not part of + // the undoable game snapshot — it stays true after the undo.) + table.alice.send({'t': 'undo'}); + final undo = await table.alice.nextOf('update'); + expect(undo['index'], 0); + expect(undo['description'], "Don't track standees"); + expect(getIt<Settings>().noStandees, isTrue, + reason: 'settings are not part of the undoable game state'); + } finally { + await table.teardown(); + } + }); + + test('the locale setting localizes command descriptions', () async { + final table = await Table().setup(); + try { + table.alice.send(Protocol.setSettingMessage('locale', 'de')); + await table.alice.nextOf('settings'); + await table.bob.nextOf('settings'); + + table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + final update = await table.alice.nextOf('update'); + expect( + update['description'], + 'Initiative von Blinkblade festlegen', + reason: 'the German command description', + ); + } finally { + await table.teardown(); + } + }); + }); + + group('history metadata (undo/redo UI)', () { + test('historyLength and redoDescription travel in welcome and updates', + () async { + final server = await TestGameServer.boot(); + try { + final client = await TestClient.connect(server.wsUrl); + client.sendHello(); + final welcome = await client.nextOf('welcome'); + + // Fresh game: baseline (index -1), no history yet. + expect(welcome['index'], -1); + expect(welcome['historyLength'], 0); + expect(welcome['description'], isNull); + expect(welcome['redoDescription'], isNull); + expect(welcome['undoDescription'], isNull); + + // Add a character (index 0). + client.sendCmd( + 'addCharacter', + {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, + ); + final add = await client.nextOf('update'); + final addDescription = add['description'] as String; + expect(add['description'], 'Add Blinkblade'); + expect(add['historyLength'], 1); + expect(add['redoDescription'], isNull); + expect(add['undoDescription'], addDescription); + + // Set initiative (index 1). + client.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + final setInit = await client.nextOf('update'); + final setInitDescription = setInit['description'] as String; + expect(setInit['historyLength'], 2); + expect(setInit['redoDescription'], isNull); + expect(setInit['undoDescription'], setInitDescription); + + // Undo to index 0: the wire index is the post-decrement one, the + // description the undone action's; redo becomes available. + client.send({'t': 'undo'}); + final undo1 = await client.nextOf('update'); + expect(undo1['index'], 0); + expect(undo1['description'], setInitDescription); + expect(undo1['historyLength'], 2); + expect(undo1['redoDescription'], setInitDescription); + expect(undo1['undoDescription'], addDescription); + + // Undo to the baseline (index -1): the stateless clients still get + // the push (the reference skips it — its clients keep local state). + client.send({'t': 'undo'}); + final baseline = await client.nextOf('update'); + expect(baseline['index'], -1); + expect(baseline['description'], addDescription); + expect(baseline['historyLength'], 2); + expect(baseline['redoDescription'], addDescription); + expect(baseline['undoDescription'], isNull); + + // Redo forward: the redo label empties out again. + client.send({'t': 'redo'}); + final redo1 = await client.nextOf('update'); + expect(redo1['index'], 0); + expect(redo1['description'], addDescription); + expect(redo1['redoDescription'], setInitDescription); + client.send({'t': 'redo'}); + final redo2 = await client.nextOf('update'); + expect(redo2['index'], 1); + expect(redo2['redoDescription'], isNull); + expect(redo2['undoDescription'], setInitDescription); + + // A fresh welcome carries the same metadata. + client.sendHello(); + final resync = await client.nextOf('welcome'); + expect(resync['historyLength'], 2); + expect(resync['redoDescription'], isNull); + expect(resync['undoDescription'], setInitDescription); + await client.close(); + } finally { + await server.shutdown(); + } + }); + }); + + group('multi-save', () { + test('save -> load (undoable) -> delete', () async { + final table = await Table().setup(); + try { + // State A: Blinkblade with initiative 5 (index 1). + table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + await table.alice.nextOf('update'); + await table.bob.nextOf('update'); + + table.alice.send(Protocol.saveMessage('alpha')); + final saved = await table.alice.nextOf('settings'); + expect(saved['settings']['saves'], ['alpha']); + expect(getIt<Settings>().saves.keys, contains('alpha')); + + // Change the state: add a monster (index 2). + table.alice.sendCmd( + 'addMonster', + {'name': 'Test Boss (FH)', 'isAlly': false}, + ); + final added = await table.alice.nextOf('update'); + await table.bob.nextOf('update'); + expect(added['index'], 2); + + // Load 'alpha': an undoable action — the index advances and the + // monster is gone again. + table.alice.send(Protocol.loadSaveMessage('alpha')); + final loaded = await table.alice.nextOf('update'); + expect(loaded['index'], 3); + expect(loaded['description'], 'Load saved game: alpha'); + final state = loaded['state'] as Map<String, dynamic>; + expect( + TestClient.characterIn(state, 'Test Boss (FH)'), + isNull, + reason: 'the loaded state has no monster', + ); + expect(TestClient.characterIn(state, 'Blinkblade'), isNotNull); + + // Every screen received the load. + final bobLoad = await table.bob.nextOf('update'); + expect(bobLoad['index'], 3); + + // Undo: back to the state with the monster (index 2). + table.alice.send({'t': 'undo'}); + final undone = await table.alice.nextOf('update'); + expect(undone['index'], 2); + expect( + TestClient.characterIn(undone['state'] as Map<String, dynamic>, 'Test Boss (FH)'), + isNotNull, + ); + + // Delete the save; loading it after is rejected. + table.alice.send(Protocol.deleteSaveMessage('alpha')); + final deleted = await table.alice.nextOf('settings'); + expect(deleted['settings']['saves'], isEmpty); + expect(getIt<Settings>().saves.keys, isEmpty); + + table.alice.send(Protocol.loadSaveMessage('alpha')); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + } finally { + await table.teardown(); + } + }); + + test('save names with missing fields get a clear error', () async { + final table = await Table().setup(); + try { + table.alice.send(Protocol.saveMessage('')); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errBadRequest, + ); + table.alice.send(Protocol.deleteSaveMessage('missing')); + // No error: deleting an unknown save is a silent no-op (the + // reference's deleteSave just removes from the map). + final settings = await table.alice.nextOf('settings'); + expect(settings['settings']['saves'], isEmpty); + } finally { + await table.teardown(); + } + }); + + test('character saves: save -> load (undoable) -> delete', () async { + final table = await Table().setup(); + try { + table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 7}); + await table.alice.nextOf('update'); + await table.bob.nextOf('update'); + + table.alice.send( + Protocol.saveCharacterMessage('Blinky backup', 'Blinkblade'), + ); + final saved = await table.alice.nextOf('settings'); + final characterSaves = saved['settings']['characterSaves'] as List; + expect( + characterSaves, + [{ + 'name': 'Blinky backup', + 'characterId': 'Blinkblade', + }], + ); + + // Change the character, then load the save back (an undoable + // action — the index advances). As in the reference app, a + // character save restores the identity (level/display/perks) and + // re-adds the character with a fresh battle state. + table.alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 9}); + await table.alice.nextOf('update'); + await table.bob.nextOf('update'); + + table.alice.send( + Protocol.loadCharacterSaveMessage('Blinky backup\nBlinkblade'), + ); + final loaded = await table.alice.nextOf('update'); + expect(loaded['description'], 'Load saved character: Blinky backup'); + final state = loaded['state'] as Map<String, dynamic>; + final character = TestClient.characterIn(state, 'Blinkblade')!; + final characterState = character['characterState'] as Map; + expect(characterState['display'], 'Blinky'); + expect(characterState['initiative'], 0, reason: 'fresh battle state'); + + // Delete; loading again is rejected. + table.alice.send( + Protocol.deleteCharacterSaveMessage('Blinky backup\nBlinkblade'), + ); + final deleted = await table.alice.nextOf('settings'); + expect(deleted['settings']['characterSaves'], isEmpty); + + table.alice.send( + Protocol.loadCharacterSaveMessage('Blinky backup\nBlinkblade'), + ); + expect( + (await table.alice.nextOf('error'))['code'], + Protocol.errRejected, + ); + } finally { + await table.teardown(); + } + }); + + test('saving a character not in the list is rejected', () async { + final table = await Table().setup(); + try { + table.alice.send( + Protocol.saveCharacterMessage('ghost', 'No Such Character'), + ); + final error = await table.alice.nextOf('error'); + expect(error['code'], Protocol.errRejected); + expect( + (error['message'] as String).contains('No Such Character'), + isTrue, + ); + } finally { + await table.teardown(); + } + }); + }); + + group('persistence across a restart', () { + late Directory dir; + + setUp(() { + dir = Directory.systemTemp.createTempSync('x-haven-settings-'); + }); + + tearDown(() { + if (dir.existsSync()) dir.deleteSync(recursive: true); + }); + + test('settings and save names survive a server restart', () async { + // First boot: change a setting, make a state save and a character + // save — all persisted into dir/saves/settings.json. + final first = await TestGameServer.boot( + settingsStore: FileSettingsStore(dir.path), + ); + final alice = await TestClient.connect(first.wsUrl); + alice.sendHello(); + await alice.nextOf('welcome'); + alice.sendCmd( + 'addCharacter', + {'id': 'Blinkblade', 'edition': 'Frosthaven', 'display': 'Blinky', 'level': 1}, + ); + await alice.nextOf('update'); + await alice.nextOf('seats'); + + alice.sendCmd('setInit', {'characterId': 'Blinkblade', 'init': 5}); + await alice.nextOf('update'); + + alice.send(Protocol.setSettingMessage('hideLootDeck', true)); + await alice.nextOf('settings'); + alice.send(Protocol.setSettingMessage('locale', 'de')); + await alice.nextOf('settings'); + alice.send(Protocol.saveMessage('restart')); + await alice.nextOf('settings'); + alice.send(Protocol.saveCharacterMessage('backup', 'Blinkblade')); + await alice.nextOf('settings'); + + await alice.close(); + await first.shutdown(); + + // Second boot from the same directory: the settings are restored, + // and a fresh welcome serves them. + final second = await TestGameServer.boot( + settingsStore: FileSettingsStore(dir.path), + ); + try { + final settings = getIt<Settings>(); + expect(settings.hideLootDeck, isTrue); + expect(settings.locale, 'de'); + expect(settings.saves.keys, contains('restart')); + expect( + settings.characterSaves.keys, + contains('backup\nBlinkblade'), + ); + + final client = await TestClient.connect(second.wsUrl); + client.sendHello(); + final welcome = await client.nextOf('welcome'); + final payload = welcome['settings'] as Map; + expect(payload['hideLootDeck'], isTrue); + expect(payload['locale'], 'de'); + expect(payload['saves'], ['restart']); + expect(payload['characterSaves'], [ + {'name': 'backup', 'characterId': 'Blinkblade'}, + ]); + await client.close(); + } finally { + await second.shutdown(); + } + }); + }); +} diff --git a/server/test/net/ws_test_helpers.dart b/server/test/net/ws_test_helpers.dart index 1903567..36d87c8 100644 --- a/server/test/net/ws_test_helpers.dart +++ b/server/test/net/ws_test_helpers.dart @@ -16,6 +16,8 @@ import 'package:web_socket_channel/web_socket_channel.dart'; import 'package:x_haven_server/core/game_data.dart'; import 'package:x_haven_server/core/save_store.dart'; import 'package:x_haven_server/core/service_locator.dart'; +import 'package:x_haven_server/core/settings.dart'; +import 'package:x_haven_server/core/settings_store.dart'; import 'package:x_haven_server/core/state/game_state.dart'; import 'package:x_haven_server/net/app.dart'; import 'package:x_haven_server/net/game_server.dart'; @@ -37,15 +39,22 @@ class TestGameServer { static Future<TestGameServer> boot({ SaveStore? saveStore, SeatStore? seatStore, + SettingsStore? settingsStore, Duration heartbeatInterval = const Duration(seconds: 20), Duration deadTimeout = const Duration(seconds: 90), String dataDir = 'assets/testData/', }) async { // Same bootstrap as test/command/test_helpers.dart's setUpGame(), but - // with the caller's [saveStore] (persistence tests pass a FileSaveStore). - setupCore(saveStore: saveStore ?? InMemorySaveStore()); + // with the caller's stores (persistence tests pass the File* variants). + setupCore( + saveStore: saveStore ?? InMemorySaveStore(), + settingsStore: settingsStore ?? InMemorySettingsStore(), + ); final gs = getIt<GameState>(); gs.init(); + // Same as bin/main.dart: restore the persisted settings (no-op when the + // store is empty, i.e. first run). + getIt<Settings>().loadFromDisk(); await getIt<GameData>().loadData(dataDir); gs.load(); final instance = TestGameServer._(); diff --git a/server/test/resource/ui_utils_test.dart b/server/test/resource/ui_utils_test.dart deleted file mode 100644 index fc44c02..0000000 --- a/server/test/resource/ui_utils_test.dart +++ /dev/null @@ -1,48 +0,0 @@ -// ignore_for_file: no-magic-number - -import 'package:test/test.dart'; -import 'package:x_haven_server/core/enums.dart'; -import 'package:x_haven_server/core/settings.dart'; -import 'package:x_haven_server/core/service_locator.dart'; -import 'package:x_haven_server/core/ui_utils.dart'; - -import '../command/test_helpers.dart'; - -/// The reference `ui_utils_test.dart` has no `reducePowerEnabled` group — -/// its groups (`hasGHVersion`, text-style helpers, dialog/toast widget -/// functions) all exercise unported widget code. This file instead covers -/// the single ported `ui_utils` function, `reducePowerEnabled`, mirroring -/// the reference implementation's documented semantics. -void main() { - setUpAll(() async { - await setUpGame(); - }); - - // ── reducePowerEnabled ──────────────────────────────────────────────────── - - group('reducePowerEnabled', () { - test('returns false by default (PowerMode.normal)', () { - expect(reducePowerEnabled(), isFalse); - }); - - test('returns true when powerMode is reducePower', () { - getIt<Settings>().powerMode = PowerMode.reducePower; - expect(reducePowerEnabled(), isTrue); - getIt<Settings>().powerMode = PowerMode.normal; - }); - - test('returns false for dimWhenIdle (top tier only)', () { - getIt<Settings>().powerMode = PowerMode.dimWhenIdle; - expect(reducePowerEnabled(), isFalse); - getIt<Settings>().powerMode = PowerMode.normal; - }); - - test('honors an explicitly passed Settings instance', () { - final settings = Settings(); - settings.powerMode = PowerMode.reducePower; - expect(reducePowerEnabled(settings: settings), isTrue); - settings.powerMode = PowerMode.normal; - expect(reducePowerEnabled(settings: settings), isFalse); - }); - }); -} |
