diff options
Diffstat (limited to 'server/lib/core')
| -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 |
6 files changed, 202 insertions, 157 deletions
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; -} |
