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:
parent
7665cdf642
commit
382f0ad3fa
9 changed files with 653 additions and 33 deletions
|
|
@ -901,6 +901,13 @@ public sealed class GameWindow : IDisposable
|
|||
// the same OnLoad path (see _inputDispatcher field).
|
||||
if (_inputDispatcher is not null)
|
||||
{
|
||||
// L.0 — settings.json (display + future audio / gameplay /
|
||||
// chat / character tabs). Coexists with keybinds.json,
|
||||
// which keeps its own load/save path.
|
||||
var settingsStore = new AcDream.UI.Abstractions.Panels.Settings.SettingsStore(
|
||||
AcDream.UI.Abstractions.Panels.Settings.SettingsStore.DefaultPath());
|
||||
var persistedDisplay = settingsStore.LoadDisplay();
|
||||
|
||||
_settingsVm = new AcDream.UI.Abstractions.Panels.Settings.SettingsVM(
|
||||
persisted: _keyBindings,
|
||||
dispatcher: _inputDispatcher,
|
||||
|
|
@ -919,6 +926,21 @@ public sealed class GameWindow : IDisposable
|
|||
{
|
||||
Console.WriteLine($"keybinds: save failed: {ex.Message}");
|
||||
}
|
||||
},
|
||||
persistedDisplay: persistedDisplay,
|
||||
onSaveDisplay: display =>
|
||||
{
|
||||
try
|
||||
{
|
||||
settingsStore.SaveDisplay(display);
|
||||
Console.WriteLine(
|
||||
"settings: display saved to "
|
||||
+ AcDream.UI.Abstractions.Panels.Settings.SettingsStore.DefaultPath());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"settings: display save failed: {ex.Message}");
|
||||
}
|
||||
});
|
||||
_settingsPanel = new AcDream.UI.Abstractions.Panels.Settings.SettingsPanel(_settingsVm);
|
||||
_panelHost.Register(_settingsPanel);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,44 @@
|
|||
using System.Collections.Generic;
|
||||
|
||||
namespace AcDream.UI.Abstractions.Panels.Settings;
|
||||
|
||||
/// <summary>
|
||||
/// Display-related preferences persisted to <c>settings.json</c>.
|
||||
/// Modern addition (no retail equivalent for FOV / vsync etc) — replaces
|
||||
/// the various <c>ACDREAM_*</c> environment variables for resolution +
|
||||
/// windowed mode with an in-game UI.
|
||||
///
|
||||
/// <para>
|
||||
/// Records are immutable; mutation goes through
|
||||
/// <see cref="SettingsVM.SetDisplay"/> which assigns a new instance via
|
||||
/// <c>with</c>-expressions.
|
||||
/// </para>
|
||||
/// </summary>
|
||||
public sealed record DisplaySettings(
|
||||
string Resolution,
|
||||
bool Fullscreen,
|
||||
bool VSync,
|
||||
float FieldOfView,
|
||||
float Gamma,
|
||||
bool ShowFps)
|
||||
{
|
||||
/// <summary>Values used on first launch / when settings.json is absent.</summary>
|
||||
public static DisplaySettings Default { get; } = new(
|
||||
Resolution: "1920x1080",
|
||||
Fullscreen: false,
|
||||
VSync: true,
|
||||
FieldOfView: 75f,
|
||||
Gamma: 1.0f,
|
||||
ShowFps: false);
|
||||
|
||||
/// <summary>16:9 resolution presets offered in the dropdown.</summary>
|
||||
public static IReadOnlyList<string> AvailableResolutions { get; } = new[]
|
||||
{
|
||||
"1280x720",
|
||||
"1366x768",
|
||||
"1600x900",
|
||||
"1920x1080",
|
||||
"2560x1440",
|
||||
"3840x2160",
|
||||
};
|
||||
}
|
||||
|
|
@ -83,7 +83,7 @@ public sealed class SettingsPanel : IPanel
|
|||
}
|
||||
if (renderer.BeginTabItem("Display"))
|
||||
{
|
||||
RenderPlaceholder(renderer, "Display");
|
||||
RenderDisplayTab(renderer);
|
||||
renderer.EndTabItem();
|
||||
}
|
||||
if (renderer.BeginTabItem("Audio"))
|
||||
|
|
@ -194,6 +194,51 @@ public sealed class SettingsPanel : IPanel
|
|||
+ "Build order: Display → Audio → Gameplay → Chat → Character.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Render the Display tab — resolution / fullscreen / vsync /
|
||||
/// FOV / gamma / show-FPS. FOV + Gamma are live-preview sliders;
|
||||
/// the others apply on Save (matches the brainstorm UX agreement —
|
||||
/// resolution change live would be too jarring).
|
||||
/// </summary>
|
||||
private void RenderDisplayTab(IPanelRenderer renderer)
|
||||
{
|
||||
var d = _vm.DisplayDraft;
|
||||
|
||||
// Resolution dropdown. Index falls back to the highest available
|
||||
// option when the persisted resolution isn't one of the presets
|
||||
// (e.g. user hand-edited settings.json with a non-standard size).
|
||||
var resolutions = DisplaySettings.AvailableResolutions.ToArray();
|
||||
int idx = System.Array.IndexOf(resolutions, d.Resolution);
|
||||
if (idx < 0) idx = resolutions.Length - 1;
|
||||
if (renderer.Combo("Resolution", ref idx, resolutions))
|
||||
_vm.SetDisplay(d with { Resolution = resolutions[idx] });
|
||||
|
||||
bool fullscreen = d.Fullscreen;
|
||||
if (renderer.Checkbox("Fullscreen", ref fullscreen))
|
||||
_vm.SetDisplay(d with { Fullscreen = fullscreen });
|
||||
|
||||
bool vsync = d.VSync;
|
||||
if (renderer.Checkbox("V-Sync", ref vsync))
|
||||
_vm.SetDisplay(d with { VSync = vsync });
|
||||
|
||||
float fov = d.FieldOfView;
|
||||
if (renderer.SliderFloat("Field of View", ref fov, 30f, 120f))
|
||||
_vm.SetDisplay(d with { FieldOfView = fov });
|
||||
|
||||
float gamma = d.Gamma;
|
||||
if (renderer.SliderFloat("Gamma", ref gamma, 0.5f, 2.0f))
|
||||
_vm.SetDisplay(d with { Gamma = gamma });
|
||||
|
||||
bool showFps = d.ShowFps;
|
||||
if (renderer.Checkbox("Show FPS", ref showFps))
|
||||
_vm.SetDisplay(d with { ShowFps = showFps });
|
||||
|
||||
renderer.Spacing();
|
||||
renderer.TextWrapped(
|
||||
"Resolution / Fullscreen / V-Sync apply on Save. FOV + Gamma "
|
||||
+ "preview live as you drag; Cancel reverts to the saved value.");
|
||||
}
|
||||
|
||||
private void RenderSection(IPanelRenderer renderer, string label, InputAction[] actions)
|
||||
{
|
||||
// Movement defaults open; other sections collapsed for first-run UX.
|
||||
|
|
|
|||
151
src/AcDream.UI.Abstractions/Panels/Settings/SettingsStore.cs
Normal file
151
src/AcDream.UI.Abstractions/Panels/Settings/SettingsStore.cs
Normal 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;
|
||||
}
|
||||
|
|
@ -30,6 +30,12 @@ public sealed class SettingsVM
|
|||
private readonly InputDispatcher _dispatcher;
|
||||
private readonly Action<KeyBindings> _onSave;
|
||||
|
||||
// L.0 — Display tab. Treated as a single immutable record; mutation
|
||||
// through SetDisplay clones via with-expressions on the panel side.
|
||||
private DisplaySettings _displayPersisted;
|
||||
private DisplaySettings _displayDraft;
|
||||
private readonly Action<DisplaySettings> _onSaveDisplay;
|
||||
|
||||
/// <summary>The action currently being rebound, or null when idle.</summary>
|
||||
public InputAction? RebindInProgress { get; private set; }
|
||||
|
||||
|
|
@ -50,14 +56,38 @@ public sealed class SettingsVM
|
|||
/// <summary>True iff the draft differs structurally from the
|
||||
/// persisted snapshot. Used to grey out the Save button when no
|
||||
/// rebinds are pending.</summary>
|
||||
public bool HasUnsavedChanges => !KeyBindingsEqual(_persisted, _draft);
|
||||
public bool HasUnsavedChanges
|
||||
=> !KeyBindingsEqual(_persisted, _draft)
|
||||
|| _displayPersisted != _displayDraft;
|
||||
|
||||
public SettingsVM(KeyBindings persisted, InputDispatcher dispatcher, Action<KeyBindings> onSave)
|
||||
/// <summary>The current Display draft. Panel reads from here;
|
||||
/// mutation goes through <see cref="SetDisplay"/>.</summary>
|
||||
public DisplaySettings DisplayDraft => _displayDraft;
|
||||
|
||||
public SettingsVM(
|
||||
KeyBindings persisted,
|
||||
InputDispatcher dispatcher,
|
||||
Action<KeyBindings> onSave,
|
||||
DisplaySettings persistedDisplay,
|
||||
Action<DisplaySettings> onSaveDisplay)
|
||||
{
|
||||
_persisted = persisted ?? throw new ArgumentNullException(nameof(persisted));
|
||||
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
|
||||
_onSave = onSave ?? throw new ArgumentNullException(nameof(onSave));
|
||||
_draft = CloneBindings(persisted);
|
||||
_persisted = persisted ?? throw new ArgumentNullException(nameof(persisted));
|
||||
_dispatcher = dispatcher ?? throw new ArgumentNullException(nameof(dispatcher));
|
||||
_onSave = onSave ?? throw new ArgumentNullException(nameof(onSave));
|
||||
_displayPersisted = persistedDisplay ?? throw new ArgumentNullException(nameof(persistedDisplay));
|
||||
_onSaveDisplay = onSaveDisplay ?? throw new ArgumentNullException(nameof(onSaveDisplay));
|
||||
_draft = CloneBindings(persisted);
|
||||
_displayDraft = persistedDisplay;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replace the entire Display draft with <paramref name="value"/>.
|
||||
/// Panel calls this with a <c>DisplayDraft with { Field = newValue }</c>
|
||||
/// so each widget edits exactly one field at a time.
|
||||
/// </summary>
|
||||
public void SetDisplay(DisplaySettings value)
|
||||
{
|
||||
_displayDraft = value ?? throw new ArgumentNullException(nameof(value));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -160,32 +190,42 @@ public sealed class SettingsVM
|
|||
}
|
||||
|
||||
/// <summary>
|
||||
/// Replace the entire draft with <see cref="KeyBindings.RetailDefaults"/>.
|
||||
/// Replace the keybinds draft with <see cref="KeyBindings.RetailDefaults"/>
|
||||
/// AND the display draft with <see cref="DisplaySettings.Default"/>.
|
||||
/// "Reset all" applies to every tab — it's the user's escape hatch
|
||||
/// when they've gotten lost.
|
||||
/// </summary>
|
||||
public void ResetAllToDefaults()
|
||||
{
|
||||
_draft = KeyBindings.RetailDefaults();
|
||||
_draft = KeyBindings.RetailDefaults();
|
||||
_displayDraft = DisplaySettings.Default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Commit the draft via the onSave callback supplied at
|
||||
/// construction. After save the draft becomes the new persisted
|
||||
/// snapshot — <see cref="HasUnsavedChanges"/> resets to false.
|
||||
/// Commit both keybinds + display drafts via the onSave callbacks
|
||||
/// supplied at construction. After save the drafts become the new
|
||||
/// persisted snapshots — <see cref="HasUnsavedChanges"/> resets to
|
||||
/// false. Each callback is invoked exactly once per Save; if the
|
||||
/// caller wants atomicity across both files it has to handle it
|
||||
/// outside the VM.
|
||||
/// </summary>
|
||||
public void Save()
|
||||
{
|
||||
_onSave(_draft);
|
||||
_persisted = CloneBindings(_draft);
|
||||
_onSaveDisplay(_displayDraft);
|
||||
_persisted = CloneBindings(_draft);
|
||||
_displayPersisted = _displayDraft;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Revert the draft to the persisted snapshot and clear any
|
||||
/// Revert all drafts to their persisted snapshots and clear any
|
||||
/// in-flight rebind state. Used by the panel's "Cancel" button and
|
||||
/// when the user closes the settings window without saving.
|
||||
/// </summary>
|
||||
public void Cancel()
|
||||
{
|
||||
_draft = CloneBindings(_persisted);
|
||||
_draft = CloneBindings(_persisted);
|
||||
_displayDraft = _displayPersisted;
|
||||
CancelRebind();
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue