acdream/tests/AcDream.App.Tests/UI/Layout/KeyboardConfigControllerTests.cs
Erik b4edee970f feat(ui): Campaign OP slice OP8 — Configure Keyboard
Ports retail's Configure Keyboard screen (gmKeyboardUI, LayoutDesc
0x21000009) — its own separate full-screen window, not a fifth Options-
panel tab. Retires OP3's INERT contract for the Gameplay tab's Configure
Keyboard button (0x10000204).

DAT reader (src/AcDream.Core/Input/RetailActionMap.cs): reads the
ActionMap singleton (DID 0x26000000, empirically the only one — not
0x27000000 as GetDBOType's Turbine-internal tag would suggest) and both
MasterInputMap defaults (0x14000000 "gmDefaultMap"/0x14000002
"DefaultMap"), union-merged per (InputMapId, ActionId) — proven order-
independent since the two maps' one shared context (0x5) has disjoint
action-id sets. Empirically resolved three lane-D unknowns against the
live DAT: the six ActionClass values (1=Movement, 2=Camera, 3=UI,
4=Combat, 5=Emote, 7=CharacterSettings — 6 is genuinely absent), that
the six unnamed InputMaps are 100% non-bindable (render nothing, not an
unlabeled group), and that the enum-to-DID pairing for the two master
maps is inconsequential to the merge result.

Identity table (src/AcDream.UI.Abstractions/Input/RetailActionIdentityTable.cs):
maps DAT (InputMapId, ActionId) pairs to acdream's InputAction where a
live consumer exists (~140 of 306 user-bindable rows — Movement/Camera/
Combat map almost completely; UI/Quickslot/Chat partially; only 5 of 87
Emotes and none of 48 CharacterSettings hotkeys, since acdream has no
general emote player or hotkey-to-option-toggle dispatcher yet). Every
entry cross-verified by label match AND a DAT-default-vs-
KeyBindings.RetailDefaults() byte comparison (RetailActionIdentityRoundTripTests),
which caught a real off-by-one in the Quickslot 13-18 block before it
shipped and found three genuine pre-existing RetailDefaults() gaps
(walk-mode's Shift-echoed chord, ten CameraAlternateControls arrow-key
alternates, and the Quickslot Ctrl+N use-vs-select ambiguity) — none
introduced by this slice, all documented rather than silently patched.

KeyboardConfigController: six ActionClass list boxes built from the
DAT, merged with live KeyBindings for mapped rows (rebind applies
immediately through the same InputDispatcher every other input path
uses) and a new sibling RetailUnmappedKeyBindings store for rows with
no InputAction yet. Left-click a key button opens real InputDispatcher
modal capture; right-click erases that slot. N-way conflict detection
scans every other row plus the live KeyBindings table for acdream-only
actions (Ctrl+M mute, debug F-keys) as the non-user-bindable refusal
analogue, using retail's own byte-verified "Could not overwrite "
string (table 0x23000004). OK/Cancel/Defaults/Revert reuse the
OptionPage/IOptionRow verb model via a new ActionKeyMapOptionRow.
Persistence is keybinds.json only (D4 — no .keymap file interchange).

Five register rows: AP-202 (.keymap interchange narrowing), AP-203
(store-only rows with no live consumer), AP-204 (silent auto-reassign
instead of retail's confirm dialog; OK/Cancel ported as left-click not
right-click-release).

Small supporting additions: UiButton.OnRightClick (additive, no
existing behavior changed), InputDispatcher.Bindings getter (the
screen's single live-truth read seam), RetailScanCodeMap (DIK scan
code <-> Silk.NET Key, keyboard + the one mouse-device row).

19 new tests (6 ActionMap reader conformance incl. live-DAT row-count/
label pins, 1 DAT-vs-RetailDefaults round-trip, 12 controller
behavior tests against the committed keyboard_config_21000009.json
fixture) — full solution suite 13,147 passed / 4 skipped / 0 failed
(baseline 13,128/4/0, zero regressions).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-11 09:19:54 +02:00

345 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using AcDream.App.UI;
using AcDream.App.UI.Layout;
using AcDream.Core.Input;
using AcDream.UI.Abstractions.Input;
namespace AcDream.App.Tests.UI.Layout;
/// <summary>
/// Campaign OP slice OP8 conformance + behavior tests for
/// <see cref="KeyboardConfigController"/> — built against the committed
/// <c>keyboard_config_21000009.json</c> fixture (real DAT structure, no live dat
/// access at test time), fed a small synthetic <see cref="RetailActionMapSnapshot"/>
/// so the behavioral assertions stay focused. Live-DAT row-count/label conformance
/// lives in <c>AcDream.Core.Tests.Input.RetailActionMapReaderTests</c> and
/// <c>RetailActionIdentityRoundTripTests</c>.
/// </summary>
public sealed class KeyboardConfigControllerTests
{
private static (uint, int, int) NoTex(uint _) => (0, 0, 0);
private static ElementInfo? Find(ElementInfo n, uint id)
{
if (n.Id == id) return n;
foreach (ElementInfo c in n.Children)
{
ElementInfo? f = Find(c, id);
if (f is not null) return f;
}
return null;
}
private static Func<uint, uint, UiElement?> MakeTemplateResolver()
{
ElementInfo root = FixtureLoader.LoadKeyboardConfigInfos();
return (layoutId, elementId) =>
{
if (layoutId != KeyboardConfigController.LayoutId) return null;
ElementInfo? templateInfo = Find(root, elementId);
return templateInfo is null ? null : LayoutImporter.Build(templateInfo, NoTex, null).Root;
};
}
private static RetailActionMapRow Row(
uint inputMapId, uint actionId, RetailActionClass cls,
uint labelHash = 0, uint tooltipHash = 0,
params RetailKeyChord[] defaults) =>
new(inputMapId, actionId, cls, labelHash, tooltipHash, defaults);
private sealed class FakeBindings
{
public Dictionary<InputAction, List<KeyChord>> Mapped { get; } = new();
public Dictionary<(uint, uint), List<KeyChord>> Unmapped { get; } = new();
public List<(InputAction Action, IReadOnlyList<KeyChord> Value)> MappedSets { get; } = new();
public List<((uint, uint) Row, IReadOnlyList<KeyChord> Value)> UnmappedSets { get; } = new();
public List<string> Messages { get; } = new();
public int SaveCalls { get; private set; }
public int ToggleCalls { get; private set; }
public Action<KeyChord?>? PendingCapture { get; private set; }
public void Capture(KeyChord? chord)
{
Action<KeyChord?>? cb = PendingCapture;
PendingCapture = null;
cb?.Invoke(chord);
}
public KeyboardConfigController.Bindings ToBindings() => new(
CurrentForAction: a => Mapped.TryGetValue(a, out var v) ? v : Array.Empty<KeyChord>(),
SetForAction: (a, v) =>
{
Mapped[a] = v.ToList();
MappedSets.Add((a, v));
},
CurrentForUnmapped: k => Unmapped.TryGetValue(k, out var v) ? v : Array.Empty<KeyChord>(),
SetForUnmapped: (k, v) =>
{
Unmapped[k] = v.ToList();
UnmappedSets.Add((k, v));
},
BeginCapture: cb => PendingCapture = cb,
Save: () => SaveCalls++,
Toggle: () => ToggleCalls++,
DisplaySystemMessage: msg => Messages.Add(msg),
NonBindableRefusalText: "cannot overwrite",
NotifyReassigned: label => $"reassigned from {label}");
}
private static readonly KeyChord ChordW = new(Silk.NET.Input.Key.W, ModifierMask.None);
private static readonly KeyChord ChordUp = new(Silk.NET.Input.Key.Up, ModifierMask.None);
private static readonly KeyChord ChordA = new(Silk.NET.Input.Key.A, ModifierMask.None);
[Fact]
public void Bind_Succeeds_AndBuildsOneRowPerSnapshotRow()
{
var snapshot = new RetailActionMapSnapshot(new[]
{
Row(0x4, 0x29, RetailActionClass.Movement), // MovementForward
Row(0x4, 0x2A, RetailActionClass.Movement), // MovementBackup
Row(0x5, 0x33, RetailActionClass.Camera), // CameraMoveToward
});
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
var fake = new FakeBindings();
KeyboardConfigController? controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings());
Assert.NotNull(controller);
Assert.Equal(3, controller!.Rows.Count);
Assert.Equal(3, controller.Page.Rows.Count);
}
[Fact]
public void Bind_MapsKnownActionsAndLeavesUnknownOnesUnmapped()
{
var snapshot = new RetailActionMapSnapshot(new[]
{
Row(0x4, 0x29, RetailActionClass.Movement), // -> MovementForward
Row(0x10000006, 0x100000A0, RetailActionClass.Emote), // "Bow Deep" -> no InputAction
});
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
var fake = new FakeBindings();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView forward = controller.Rows.Single(r => r.ActionId == 0x29u);
Assert.Equal(InputAction.MovementForward, forward.MappedAction);
KeyboardConfigController.RowView bowDeep = controller.Rows.Single(r => r.ActionId == 0x100000A0u);
Assert.Null(bowDeep.MappedAction);
}
[Fact]
public void Bind_SeedsRowFromLiveBindings_MappedAndUnmapped()
{
var snapshot = new RetailActionMapSnapshot(new[]
{
Row(0x4, 0x29, RetailActionClass.Movement),
Row(0x10000006, 0x100000A0, RetailActionClass.Emote),
});
var fake = new FakeBindings();
fake.Mapped[InputAction.MovementForward] = new List<KeyChord> { ChordW, ChordUp };
fake.Unmapped[(0x10000006u, 0x100000A0u)] = new List<KeyChord> { ChordA };
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView forward = controller.Rows.Single(r => r.ActionId == 0x29u);
Assert.Equal(new[] { ChordW, ChordUp }, forward.Model.Current);
KeyboardConfigController.RowView bowDeep = controller.Rows.Single(r => r.ActionId == 0x100000A0u);
Assert.Equal(new[] { ChordA }, bowDeep.Model.Current);
}
[Fact]
public void KeyButtonClick_CapturesAndAppliesNewBinding()
{
var snapshot = new RetailActionMapSnapshot(new[] { Row(0x4, 0x29, RetailActionClass.Movement) });
var fake = new FakeBindings();
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView row = controller.Rows.Single();
Assert.NotEmpty(row.KeyButtons);
row.KeyButtons[0].OnClick!.Invoke();
Assert.NotNull(fake.PendingCapture);
fake.Capture(ChordW);
Assert.Contains(ChordW, row.Model.Current);
Assert.Contains((InputAction.MovementForward, (IReadOnlyList<KeyChord>)row.Model.Current), fake.MappedSets);
Assert.Equal("W", row.KeyButtons[0].Label);
}
[Fact]
public void KeyButtonCapture_EscapeCancel_LeavesBindingUnchanged()
{
var snapshot = new RetailActionMapSnapshot(new[] { Row(0x4, 0x29, RetailActionClass.Movement) });
var fake = new FakeBindings();
fake.Mapped[InputAction.MovementForward] = new List<KeyChord> { ChordW };
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView row = controller.Rows.Single();
row.KeyButtons[0].OnClick!.Invoke();
fake.Capture(null); // Escape sentinel
Assert.Equal(new[] { ChordW }, row.Model.Current);
Assert.Empty(fake.MappedSets);
}
[Fact]
public void KeyButtonRightClick_ErasesThatSlot()
{
var snapshot = new RetailActionMapSnapshot(new[] { Row(0x4, 0x29, RetailActionClass.Movement) });
var fake = new FakeBindings();
fake.Mapped[InputAction.MovementForward] = new List<KeyChord> { ChordW, ChordUp };
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView row = controller.Rows.Single();
Assert.Equal(2, row.Model.Current.Count);
row.KeyButtons[0].OnRightClick!.Invoke();
Assert.Single(row.Model.Current);
Assert.DoesNotContain(ChordW, row.Model.Current);
}
[Fact]
public void Capture_ConflictWithAnotherRow_AutoReassignsAndNotifies()
{
var snapshot = new RetailActionMapSnapshot(new[]
{
Row(0x4, 0x29, RetailActionClass.Movement), // MovementForward
Row(0x4, 0x2A, RetailActionClass.Movement), // MovementBackup — will hold ChordA
});
var fake = new FakeBindings();
fake.Mapped[InputAction.MovementBackup] = new List<KeyChord> { ChordA };
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView forward = controller.Rows.Single(r => r.ActionId == 0x29u);
KeyboardConfigController.RowView backup = controller.Rows.Single(r => r.ActionId == 0x2Au);
forward.KeyButtons[0].OnClick!.Invoke();
fake.Capture(ChordA); // steal MovementBackup's chord
Assert.Contains(ChordA, forward.Model.Current);
Assert.DoesNotContain(ChordA, backup.Model.Current);
Assert.Contains(fake.Messages, m => m.Contains("reassigned"));
}
[Fact]
public void Capture_ConflictWithNonBindableAcdreamAction_RefusesAndLeavesBoth()
{
var snapshot = new RetailActionMapSnapshot(new[] { Row(0x4, 0x29, RetailActionClass.Movement) });
var fake = new FakeBindings();
// AcdreamToggleAudioMute has no RetailActionIdentityTable row at all.
var muteChord = new KeyChord(Silk.NET.Input.Key.M, ModifierMask.Ctrl);
fake.Mapped[InputAction.AcdreamToggleAudioMute] = new List<KeyChord> { muteChord };
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView forward = controller.Rows.Single();
forward.KeyButtons[0].OnClick!.Invoke();
fake.Capture(muteChord);
Assert.DoesNotContain(muteChord, forward.Model.Current);
Assert.Contains("cannot overwrite", fake.Messages);
Assert.Equal(new[] { muteChord }, fake.Mapped[InputAction.AcdreamToggleAudioMute]);
}
[Fact]
public void OkButton_AppliesCommitsSavesAndToggles()
{
var snapshot = new RetailActionMapSnapshot(new[] { Row(0x4, 0x29, RetailActionClass.Movement) });
var fake = new FakeBindings();
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView row = controller.Rows.Single();
row.KeyButtons[0].OnClick!.Invoke();
fake.Capture(ChordW);
Assert.True(row.Model.Changed);
UiButton ok = (UiButton)layout.FindElement(0x1000002Cu)!;
ok.OnClick!.Invoke();
Assert.False(row.Model.Changed); // Apply committed saved=current
Assert.Equal(1, fake.SaveCalls);
Assert.Equal(1, fake.ToggleCalls);
}
[Fact]
public void CancelButton_RevertsUncommittedEditAndToggles()
{
var snapshot = new RetailActionMapSnapshot(new[] { Row(0x4, 0x29, RetailActionClass.Movement) });
var fake = new FakeBindings();
fake.Mapped[InputAction.MovementForward] = new List<KeyChord> { ChordW };
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView row = controller.Rows.Single();
row.KeyButtons[0].OnClick!.Invoke();
fake.Capture(ChordUp); // now [Up] uncommitted (slot 0 replaced)
UiButton cancel = (UiButton)layout.FindElement(0x1000002Du)!;
cancel.OnClick!.Invoke();
Assert.Equal(new[] { ChordW }, row.Model.Current); // reverted to Saved
Assert.Equal(1, fake.ToggleCalls);
Assert.Equal(0, fake.SaveCalls);
}
[Fact]
public void DefaultsButton_RestoresDatDefaultLive_WithoutCommitting()
{
var snapshot = new RetailActionMapSnapshot(new[]
{
Row(0x4, 0x29, RetailActionClass.Movement, defaults:
new[] { new RetailKeyChord(0x11, 0, 0, 3) }), // DIK_W
});
var fake = new FakeBindings();
fake.Mapped[InputAction.MovementForward] = new List<KeyChord> { ChordUp };
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView row = controller.Rows.Single();
Assert.Equal(new[] { ChordUp }, row.Model.Current);
UiButton defaultsButton = (UiButton)layout.FindElement(0x1000002Au)!;
defaultsButton.OnClick!.Invoke();
Assert.Equal(new[] { ChordW }, row.Model.Current);
Assert.True(row.Model.Changed); // live but uncommitted, matching retail
}
[Fact]
public void Bind_MissingWindowRoot_ReturnsNull()
{
ElementInfo empty = new() { Id = 0x99999999u, Type = 3 };
ImportedLayout emptyLayout = LayoutImporter.Build(empty, NoTex, null);
var snapshot = new RetailActionMapSnapshot(Array.Empty<RetailActionMapRow>());
var fake = new FakeBindings();
KeyboardConfigController? controller = KeyboardConfigController.Bind(
emptyLayout, snapshot, (_, _) => null, (_, _) => null, fake.ToBindings());
Assert.Null(controller);
}
}