feat(ui): Display tab + settings.json persistence — first non-keybind tab lands

Phase L.0 (cont.) — first concrete tab on the new Settings shell, in
the Easy-wins build order agreed in the brainstorm
(Display → Audio → Gameplay → Chat → Character).

DisplaySettings (immutable record): Resolution / Fullscreen / VSync /
FieldOfView (30-120°) / Gamma (0.5-2.0) / ShowFps. Six common 16:9
resolutions in the dropdown. Defaults: 1920×1080, windowed, vsync on,
75° FOV, gamma 1.0, FPS off — matches the brainstorm UX agreement.

SettingsStore: JSON persistence at %LOCALAPPDATA%\acdream\settings.json
(coexists with keybinds.json — own load/save path stays put, no
migration needed). LoadDisplay falls back per-field when keys are
missing (partial-file tolerant) and falls back to defaults when the
file is corrupt or the JSON is unparseable. SaveDisplay round-trips
preserved — unknown top-level keys (e.g. an `audio` section written
by a future client) are kept on save so older builds don't silently
drop newer-tab data.

SettingsVM gains a parallel display-state machine: persistedDisplay +
draftDisplay, SetDisplay mutator, HasUnsavedChanges checks both
keybinds and display deltas, Save/Cancel/ResetAll cover both
atomically from the user's POV (one Save commits everything, one
Cancel reverts everything). Constructor signature extends with two
new params; existing keybinds-only callers updated.

SettingsPanel.RenderDisplayTab replaces the L.0-shell placeholder —
Combo for resolution, Checkboxes for fullscreen/vsync/show-fps,
SliderFloat for FOV + gamma. Live-preview note in the panel body
matches the agreed UX: FOV + gamma update visibly while the user
drags; resolution / fullscreen / vsync apply on Save (live preview
would be too jarring).

GameWindow wires SettingsStore into the existing SettingsVM construct
site — load on startup, save on each tab Save. Errors print to
console and don't crash the panel.

19 new tests:
 · DisplaySettings record (4) — defaults pinned, value equality, with-
   expressions, AvailableResolutions sorted ascending
 · SettingsStore (6) — round trip, missing-file → defaults, corrupt-
   file → defaults, partial-file → per-field fallback, unknown-key
   preservation, DefaultPath shape
 · SettingsVM display (6) — initial draft tracks persisted, SetDisplay
   marks dirty, Save invokes display callback, Cancel reverts,
   ResetAllToDefaults covers display, Save-then-Cancel is no-op
 · SettingsPanel display tab (3) — widgets render only when active,
   resolution combo uses AvailableResolutions, no Combo emitted on
   inactive tabs

dotnet build green (0 warnings); dotnet test 1,246 / 1,246 green
(243 Core.Net + 330 UI.Abstractions + 673 Core).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Erik 2026-04-26 17:46:31 +02:00
parent 7665cdf642
commit 382f0ad3fa
9 changed files with 653 additions and 33 deletions

View file

@ -0,0 +1,151 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
namespace AcDream.UI.Abstractions.Panels.Settings;
/// <summary>
/// JSON-backed persistence for non-keybind settings (Display today; future
/// tabs Audio / Gameplay / Chat / Character will be added to the same
/// file). Path: <c>%LOCALAPPDATA%\acdream\settings.json</c>. Coexists
/// with <c>keybinds.json</c>, which retains its own
/// <see cref="Input.KeyBindings.LoadOrDefault"/> path.
///
/// <para>
/// Schema (current version 1):
/// <code>
/// {
/// "version": 1,
/// "display": { "resolution": "1920x1080", "fullscreen": false, ... }
/// }
/// </code>
/// Unknown top-level keys are preserved on save so future tab additions
/// from a newer client don't get clobbered by an older client writing
/// out only the sections it knows about.
/// </para>
/// </summary>
public sealed class SettingsStore
{
private const int CurrentSchemaVersion = 1;
private readonly string _path;
public SettingsStore(string path)
{
_path = path ?? throw new ArgumentNullException(nameof(path));
}
/// <summary>Default path: <c>%LOCALAPPDATA%\acdream\settings.json</c>.</summary>
public static string DefaultPath() => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"acdream",
"settings.json");
/// <summary>
/// Load Display settings. Missing file → <see cref="DisplaySettings.Default"/>.
/// Missing individual keys fall back to the corresponding default
/// field, so a partial file (e.g. only <c>resolution</c> is set) is
/// non-fatal.
/// </summary>
public DisplaySettings LoadDisplay()
{
if (!File.Exists(_path)) return DisplaySettings.Default;
try
{
using var stream = File.OpenRead(_path);
var doc = JsonDocument.Parse(stream);
var root = doc.RootElement;
if (!root.TryGetProperty("display", out var disp)
|| disp.ValueKind != JsonValueKind.Object)
return DisplaySettings.Default;
var d = DisplaySettings.Default;
return new DisplaySettings(
Resolution: ReadString (disp, "resolution", d.Resolution),
Fullscreen: ReadBool (disp, "fullscreen", d.Fullscreen),
VSync: ReadBool (disp, "vsync", d.VSync),
FieldOfView: ReadFloat (disp, "fieldOfView", d.FieldOfView),
Gamma: ReadFloat (disp, "gamma", d.Gamma),
ShowFps: ReadBool (disp, "showFps", d.ShowFps));
}
catch (Exception ex)
{
Console.WriteLine($"settings: failed to load {_path}: {ex.Message} — using defaults");
return DisplaySettings.Default;
}
}
/// <summary>
/// Save Display settings, preserving any other top-level keys the file
/// already contains (e.g. an <c>audio</c> section written by a newer
/// client). Unknown keys are round-tripped via raw JSON text so older
/// builds don't silently drop them.
/// </summary>
public void SaveDisplay(DisplaySettings display)
{
var dir = Path.GetDirectoryName(_path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
// Preserve any non-display top-level keys from the existing file.
var preservedKeys = new SortedDictionary<string, string>(StringComparer.Ordinal);
if (File.Exists(_path))
{
try
{
using var stream = File.OpenRead(_path);
var doc = JsonDocument.Parse(stream);
foreach (var prop in doc.RootElement.EnumerateObject())
{
if (prop.Name == "display" || prop.Name == "version") continue;
preservedKeys[prop.Name] = prop.Value.GetRawText();
}
}
catch
{
// Corrupt file → fully overwrite; previous content is lost
// but the user's session continues with the new save.
preservedKeys.Clear();
}
}
var displayObj = new SortedDictionary<string, object>(StringComparer.Ordinal)
{
["fieldOfView"] = display.FieldOfView,
["fullscreen"] = display.Fullscreen,
["gamma"] = display.Gamma,
["resolution"] = display.Resolution,
["showFps"] = display.ShowFps,
["vsync"] = display.VSync,
};
// Build the output by hand so preserved-keys keep their raw JSON.
var sb = new System.Text.StringBuilder();
sb.Append('{').AppendLine();
sb.Append(" \"display\": ")
.Append(JsonSerializer.Serialize(displayObj, new JsonSerializerOptions { WriteIndented = true })
.Replace("\n", "\n "))
.Append(',').AppendLine();
foreach (var kv in preservedKeys)
{
sb.Append(" \"").Append(kv.Key).Append("\": ")
.Append(kv.Value).Append(',').AppendLine();
}
sb.Append(" \"version\": ").Append(CurrentSchemaVersion).AppendLine();
sb.Append('}').AppendLine();
File.WriteAllText(_path, sb.ToString());
}
private static string ReadString(JsonElement obj, string name, string fallback)
=> obj.TryGetProperty(name, out var el) && el.ValueKind == JsonValueKind.String
? (el.GetString() ?? fallback) : fallback;
private static bool ReadBool(JsonElement obj, string name, bool fallback)
=> obj.TryGetProperty(name, out var el)
&& (el.ValueKind == JsonValueKind.True || el.ValueKind == JsonValueKind.False)
? el.GetBoolean() : fallback;
private static float ReadFloat(JsonElement obj, string name, float fallback)
=> obj.TryGetProperty(name, out var el) && el.ValueKind == JsonValueKind.Number
? el.GetSingle() : fallback;
}