Merge op8-keyboard: Campaign OP slice OP8 — Configure Keyboard

Brings b4edee97 (slice), b1968ce9 (M1/M2/M3 rework), f1d50207 (round-2
residuals). Review chain: REJECT -> rework -> REOPEN-narrow -> coordinator
third round; findings docs 2026-08-11-op8-review.md / -op8-rereview.md.
The merge lands OP8's six ListBoxes on top of 057d8cd7's #372 viewport
fix, which auto-heals the blank-pages hazard the re-review flagged — the
OP8 connected gate was contracted to run post-merge for exactly this.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-08-11 12:37:56 +02:00
commit 1c5cd969b4
23 changed files with 36178 additions and 12 deletions

View file

@ -238,6 +238,7 @@ public sealed class InteractionRetainedUiCompositionTests
HostQuiescence: null!,
RetainedInputCapture: null!,
InputDispatcher: null,
KeyBindingsFilePath: "keybinds.json",
Settings: null!,
Runtime: runtime,
CombatAttackOperations: new NoopCombatOperations(),

View file

@ -263,6 +263,15 @@ public static class FixtureLoader
public static ElementInfo LoadOptionsPanelHostInfos()
=> LoadInfos("options_panel_2100006E_1000018D.json");
/// <summary>Configure Keyboard screen LayoutDesc <c>0x21000009</c> (standalone
/// import — its own separate full-screen window, NOT nested under the Options
/// panel's <c>0x2100006E</c> host — Campaign OP slice OP8).</summary>
public static ImportedLayout LoadKeyboardConfig()
=> LayoutImporter.Build(LoadKeyboardConfigInfos(), _ => (0u, 0, 0), null);
public static ElementInfo LoadKeyboardConfigInfos()
=> LoadInfos("keyboard_config_21000009.json");
// ── Shared loader ────────────────────────────────────────────────────────
private static AcDream.App.UI.Layout.ElementInfo LoadInfos(string fileName)

View file

@ -0,0 +1,613 @@
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>.
///
/// <para>
/// Reworked at the 2026-08-11 combined review (M1/M2/M3/S1/S4): the seam now
/// carries <see cref="Binding"/> (chord + activation + scope), the M2 fix means
/// only ONE camera InputMap context maps live, and conflicts open a real confirm
/// dialog instead of auto-reassigning silently.
/// </para>
/// </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<Binding>> Mapped { get; } = new();
public Dictionary<(uint, uint), List<KeyChord>> Unmapped { get; } = new();
public List<(InputAction Action, IReadOnlyList<Binding> 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 (string Message, Action<bool> OnResult)? PendingConfirm { get; private set; }
public void Capture(KeyChord? chord)
{
Action<KeyChord?>? cb = PendingCapture;
PendingCapture = null;
cb?.Invoke(chord);
}
public void RespondToConfirm(bool accept)
{
var pending = PendingConfirm ?? throw new InvalidOperationException("no pending confirm");
PendingConfirm = null;
pending.OnResult(accept);
}
public KeyboardConfigController.Bindings ToBindings() => new(
CurrentForAction: a => Mapped.TryGetValue(a, out var v) ? v : Array.Empty<Binding>(),
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",
ConfirmOverwrite: (message, onResult) => PendingConfirm = (message, onResult));
}
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<Binding>
{
new(ChordW, InputAction.MovementForward),
new(ChordUp, InputAction.MovementForward),
};
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);
(InputAction Action, IReadOnlyList<Binding> Value) written = Assert.Single(fake.MappedSets);
Assert.Equal(InputAction.MovementForward, written.Action);
Binding onlyBinding = Assert.Single(written.Value);
Assert.Equal(ChordW, onlyBinding.Chord);
// No live binding existed at build time — falls back to the Binding
// record's own defaults (Press/Game), same as before M1.
Assert.Equal(ActivationType.Press, onlyBinding.Activation);
Assert.Equal(InputScope.Game, onlyBinding.Scope);
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<Binding> { new(ChordW, InputAction.MovementForward) };
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<Binding>
{
new(ChordW, InputAction.MovementForward),
new(ChordUp, InputAction.MovementForward),
};
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 KeyButtonRightClick_OnAlreadyEmptySlot_IsANoOp()
{
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.Empty(row.Model.Current);
row.KeyButtons[0].OnRightClick!.Invoke();
Assert.Empty(row.Model.Current);
Assert.Empty(fake.MappedSets);
}
/// <summary>S4 (2026-08-11 review): clicking "Mapping 3" (slot index 2) on a
/// row with NO existing bindings must land the captured chord on display
/// index 2, not collapse it onto index 0.</summary>
[Fact]
public void KeyButtonClick_OnSparseRow_ThirdSlotLandsOnThirdButton()
{
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.Equal(3, row.KeyButtons.Count);
Assert.Empty(row.Model.Current);
row.KeyButtons[2].OnClick!.Invoke(); // "Mapping 3"
fake.Capture(ChordW);
Assert.Null(row.KeyButtons[0].Label);
Assert.Null(row.KeyButtons[1].Label);
Assert.Equal("W", row.KeyButtons[2].Label);
// The write to the live seam only ever carries the REAL chord — no
// default(KeyChord) padding leaks into the persisted Binding list.
(InputAction Action, IReadOnlyList<Binding> Value) written = Assert.Single(fake.MappedSets);
Binding onlyBinding = Assert.Single(written.Value);
Assert.Equal(ChordW, onlyBinding.Chord);
}
[Fact]
public void Capture_ConflictWithAnotherRow_OpensConfirmDialog_AcceptReassigns()
{
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<Binding> { new(ChordA, InputAction.MovementBackup) };
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
// M3: nothing is applied yet — a confirm dialog is pending.
Assert.NotNull(fake.PendingConfirm);
Assert.DoesNotContain(ChordA, forward.Model.Current);
Assert.Contains(ChordA, backup.Model.Current);
Assert.Empty(fake.Messages);
fake.RespondToConfirm(true);
Assert.Contains(ChordA, forward.Model.Current);
Assert.DoesNotContain(ChordA, backup.Model.Current);
}
[Fact]
public void Capture_ConflictWithAnotherRow_DeclineLeavesBothRowsUnchanged()
{
var snapshot = new RetailActionMapSnapshot(new[]
{
Row(0x4, 0x29, RetailActionClass.Movement),
Row(0x4, 0x2A, RetailActionClass.Movement),
});
var fake = new FakeBindings();
fake.Mapped[InputAction.MovementForward] = new List<Binding> { new(ChordW, InputAction.MovementForward) };
fake.Mapped[InputAction.MovementBackup] = new List<Binding> { new(ChordA, InputAction.MovementBackup) };
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);
fake.RespondToConfirm(false);
Assert.Equal(new[] { ChordW }, forward.Model.Current); // untouched
Assert.Equal(new[] { ChordA }, backup.Model.Current); // untouched
}
[Fact]
public void Capture_ConflictWithNonBindableAcdreamAction_RefusesWithoutADialog()
{
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<Binding> { new(muteChord, InputAction.AcdreamToggleAudioMute) };
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);
// S1: refused outright, no confirm dialog offered.
Assert.Null(fake.PendingConfirm);
Assert.DoesNotContain(muteChord, forward.Model.Current);
Assert.Contains("cannot overwrite", fake.Messages);
Assert.Equal(muteChord, Assert.Single(fake.Mapped[InputAction.AcdreamToggleAudioMute]).Chord);
}
/// <summary>S1: retail checks the non-user-bindable target BEFORE any
/// user-bindable row conflict, even when both exist for the same chord.</summary>
[Fact]
public void Capture_ConflictWithBothARowAndANonBindableAction_NonBindableWins()
{
var snapshot = new RetailActionMapSnapshot(new[]
{
Row(0x4, 0x29, RetailActionClass.Movement),
Row(0x4, 0x2A, RetailActionClass.Movement),
});
var fake = new FakeBindings();
var sharedChord = new KeyChord(Silk.NET.Input.Key.M, ModifierMask.Ctrl);
fake.Mapped[InputAction.MovementBackup] = new List<Binding> { new(sharedChord, InputAction.MovementBackup) };
fake.Mapped[InputAction.AcdreamToggleAudioMute] =
new List<Binding> { new(sharedChord, InputAction.AcdreamToggleAudioMute) };
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView forward = controller.Rows.Single(r => r.ActionId == 0x29u);
forward.KeyButtons[0].OnClick!.Invoke();
fake.Capture(sharedChord);
Assert.Null(fake.PendingConfirm);
Assert.Contains("cannot overwrite", fake.Messages);
Assert.DoesNotContain(sharedChord, forward.Model.Current);
}
[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<Binding> { new(ChordW, InputAction.MovementForward) };
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<Binding> { new(ChordUp, InputAction.MovementForward) };
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
}
/// <summary>M1 (2026-08-11 review): Defaults must restore the DAT-sourced
/// KEY only — the row's live Activation/Scope (Hold + MeleeCombat here,
/// captured from the action's live binding at build time) must survive the
/// click unchanged, across the FULL 306-row shape this test represents with
/// one Hold+scoped action.</summary>
[Fact]
public void DefaultsButton_PreservesActivationAndScope_ForAHoldScopedAction()
{
var snapshot = new RetailActionMapSnapshot(new[]
{
Row(0x10000003, 0x1000005D, RetailActionClass.Combat, defaults:
new[] { new RetailKeyChord(0xD3, 0, 0, 3) }), // CombatLowAttack, DIK_DELETE
});
var fake = new FakeBindings();
fake.Mapped[InputAction.CombatLowAttack] = new List<Binding>
{
new(ChordUp, InputAction.CombatLowAttack, ActivationType.Hold, InputScope.MeleeCombat),
};
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
UiButton defaultsButton = (UiButton)layout.FindElement(0x1000002Au)!;
defaultsButton.OnClick!.Invoke();
(InputAction Action, IReadOnlyList<Binding> Value) written = Assert.Single(fake.MappedSets);
Assert.Equal(InputAction.CombatLowAttack, written.Action);
Binding result = Assert.Single(written.Value);
Assert.Equal(Silk.NET.Input.Key.Delete, result.Chord.Key); // the DAT default key
Assert.Equal(ActivationType.Hold, result.Activation); // preserved, not reset to Press
Assert.Equal(InputScope.MeleeCombat, result.Scope); // preserved, not reset to Game
}
/// <summary>M1: Cancel/Revert (RestoreSavedValue) must ALSO preserve
/// Activation/Scope, not just Defaults.</summary>
[Fact]
public void CancelButton_PreservesActivationAndScope()
{
var snapshot = new RetailActionMapSnapshot(new[] { Row(0x4, 0x32, RetailActionClass.Movement) });
var fake = new FakeBindings();
fake.Mapped[InputAction.MovementWalkMode] = new List<Binding>
{
new(ChordW, InputAction.MovementWalkMode, ActivationType.Hold, InputScope.Game),
};
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); // uncommitted edit
UiButton cancel = (UiButton)layout.FindElement(0x1000002Du)!;
cancel.OnClick!.Invoke();
// MappedSets also carries the capture's own write (ChordUp) before the
// revert — take the LAST write, which is Cancel's RestoreSavedValue.
(InputAction Action, IReadOnlyList<Binding> Value) written = fake.MappedSets[^1];
Binding result = Assert.Single(written.Value);
Assert.Equal(ChordW, result.Chord); // reverted to saved
Assert.Equal(ActivationType.Hold, result.Activation);
}
/// <summary>M2 (2026-08-11 review): InputMap 0x6 (CameraAlternateControls) no
/// longer aliases InputMap 0x5's (CameraControls) InputAction — each row is
/// independent, so rebinding one never clobbers the other, and a row cannot
/// conflict with its own former twin.</summary>
[Fact]
public void CameraContext5And6_AreIndependentRows_NotAliased()
{
var snapshot = new RetailActionMapSnapshot(new[]
{
Row(0x5, 0x35, RetailActionClass.Camera, defaults: new[] { new RetailKeyChord(0x4B, 0, 0, 3) }),
Row(0x6, 0x35, RetailActionClass.Camera, defaults: new[] { new RetailKeyChord(0xCB, 0, 0, 3) }),
});
var fake = new FakeBindings();
ImportedLayout layout = FixtureLoader.LoadKeyboardConfig();
KeyboardConfigController controller = KeyboardConfigController.Bind(
layout, snapshot, MakeTemplateResolver(), (_, _) => null, fake.ToBindings())!;
KeyboardConfigController.RowView ctx5 = controller.Rows.Single(r => r.InputMapId == 0x5u);
KeyboardConfigController.RowView ctx6 = controller.Rows.Single(r => r.InputMapId == 0x6u);
Assert.Equal(InputAction.CameraRotateLeft, ctx5.MappedAction);
Assert.Null(ctx6.MappedAction); // unmapped — no live dual-binding infrastructure (M2)
// Round-2 SHOULD-FIX: an unmapped row with no persisted chords now
// DISPLAYS its DAT defaults (retail shows the arrow keys; blank read
// as "unbound"). Display-only — storage stays untouched until the
// user edits THIS row.
Assert.NotEmpty(ctx6.Model.Current);
var ctx6InitialDisplay = ctx6.Model.Current.ToArray();
// Rebinding ctx5's row must not touch ctx6's display or storage.
ctx5.KeyButtons[0].OnClick!.Invoke();
fake.Capture(ChordW);
Assert.Contains(ChordW, ctx5.Model.Current);
Assert.Equal(ctx6InitialDisplay, ctx6.Model.Current); // unchanged by ctx5's edit
Assert.Empty(fake.Unmapped); // ctx6's STORE untouched — display seeding writes nothing
ctx6.KeyButtons[0].OnClick!.Invoke();
fake.Capture(ChordA);
Assert.Contains(ChordA, ctx6.Model.Current);
Assert.Contains(ChordW, ctx5.Model.Current); // ctx5 unaffected by ctx6's edit
Assert.True(fake.Unmapped.ContainsKey((0x6u, 0x35u)));
}
[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);
}
// ── OP8 re-review round 2: identity-map injectivity is load-bearing for
// BOTH M1 (per-row activation capture) and M2 (no dual rows editing one
// action) — pin it so a future mapping addition cannot silently alias. ──
[Fact]
public void IdentityMap_IsInjective_NoTwoRowsShareOneInputAction()
{
var seen = new Dictionary<InputAction, (uint MapId, uint ActionId)>();
foreach (((uint mapId, uint actionId), InputAction action) in RetailActionIdentityTable.Map)
{
Assert.False(
seen.TryGetValue(action, out (uint MapId, uint ActionId) prior),
$"InputAction.{action} is mapped by BOTH (0x{prior.MapId:X}, 0x{prior.ActionId:X}) "
+ $"and (0x{mapId:X}, 0x{actionId:X}) — aliasing reintroduces the M2 twin-row clobber.");
seen[action] = (mapId, actionId);
}
Assert.True(seen.Count > 100, $"sanity: only {seen.Count} mapped actions seen");
}
}

View file

@ -35,6 +35,7 @@ public sealed class RetailLayoutFixtureGenerator
(0x21000028u, "options_character_21000028.json"),
(0x2100005Cu, "options_chat_2100005C.json"),
(0x21000029u, "options_config_21000029.json"),
(0x21000009u, "keyboard_config_21000009.json"),
};
[Fact]

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,150 @@
using System.Collections.Generic;
using System.Linq;
using AcDream.Content;
using AcDream.Core.Input;
using AcDream.UI.Abstractions.Input;
using DatReaderWriter;
using Xunit;
namespace AcDream.Core.Tests.Input;
/// <summary>
/// Campaign OP slice OP8: pins <see cref="RetailActionIdentityTable"/>'s agreement
/// with <see cref="KeyBindings.RetailDefaults"/> — for every <see cref="InputAction"/>
/// this slice's table resolves, the UNION of DAT default bindings across every DAT
/// row mapped to that action must equal <c>KeyBindings.RetailDefaults()</c>'s chord
/// set for it. Per the slice contract: "investigate + report any disagreement rather
/// than silently preferring one." Skips cleanly when the installed dats are
/// unavailable (CI), matching every other live-DAT conformance test in this project.
///
/// <para>
/// <b>Two real, byte-verified disagreements survive after the mechanism fixes</b>
/// (2026-08-11 investigation, updated at the M2 rework — none are bugs in this
/// slice's table; both are PRE-EXISTING <see cref="KeyBindings.RetailDefaults"/>
/// gaps/design choices this slice does not touch, listed in
/// <see cref="KnownRetailDefaultsDisagreements"/> with citations). A THIRD
/// disagreement — ten CameraAlternateControls (InputMap 0x6) actions — was RETIRED
/// at the M2 rework: <see cref="RetailActionIdentityTable"/> no longer maps InputMap
/// 0x6 to any <see cref="InputAction"/> at all (the aliasing that produced two
/// independent rows fighting over one live target — M2, 2026-08-11 review), so this
/// test never sees a ctx-0x6 row and the ctx-0x5-only union now matches
/// <c>RetailDefaults()</c> exactly for all twelve Camera actions with no allowlist
/// entry needed:
/// </para>
/// <list type="number">
/// <item><description><b>MovementWalkMode.</b> The DAT's raw <c>QualifiedControl.Modifier</c>
/// for the Shift-key binding is 0 (the key itself IS Shift — there is no separate
/// "modifier" to report when the primary key and the modifier are the same physical
/// key). <c>RetailDefaults()</c> deliberately encodes <c>Modifiers=Shift</c> anyway —
/// its own comment (K-fix1, 2026-04-26) explains the OS echoes
/// <c>CurrentModifiers=Shift</c> alongside a Shift key-DOWN event, so the chord must
/// carry the flag to match at dispatch time. Not a disagreement to fix; a raw-DAT
/// artifact this slice's reader faithfully reproduces.</description></item>
/// <item><description><b>Quickslot 1-9's Ctrl+N chord (and its SelectQuickSlot_1-9
/// counterpart).</b> The DAT's own default
/// master map binds Ctrl+1..9 to the SAME action id as bare 1..9 ("Quickslot N" —
/// <c>UseQuickSlot_N</c>), NOT to the separate "Select Quickslot N" action id
/// (<c>SelectQuickSlot_N</c>, DAT action ids <c>0x1000004E-56</c>) — those carry NO
/// default binding at all in the shipped DAT. <c>RetailDefaults()</c>'s own comment
/// (citing <c>gmToolbarUI::ListenToGlobalMessage @0x004BE4E0</c>) asserts retail's
/// CLIENT reinterprets Ctrl+N contextually as Select — a runtime behavior this raw
/// keymap-default probe cannot see (it reads bound ACTIONS, not the dispatch
/// function's own modifier branching). Both readings are independently retail-
/// sourced; reconciling them needs the decompiled dispatch function, out of scope
/// here. Reported, not silently resolved either way.</description></item>
/// </list>
/// </summary>
public sealed class RetailActionIdentityRoundTripTests
{
/// <summary>Actions with a citation-backed, pre-existing reason their DAT-union
/// default set legitimately differs from <see cref="KeyBindings.RetailDefaults"/>
/// — see class doc. Every other mapped action must match exactly.</summary>
private static readonly HashSet<InputAction> KnownRetailDefaultsDisagreements = new()
{
InputAction.MovementWalkMode,
InputAction.UseQuickSlot_1,
InputAction.UseQuickSlot_2,
InputAction.UseQuickSlot_3,
InputAction.UseQuickSlot_4,
InputAction.UseQuickSlot_5,
InputAction.UseQuickSlot_6,
InputAction.UseQuickSlot_7,
InputAction.UseQuickSlot_8,
InputAction.UseQuickSlot_9,
// Same Use-vs-Select ambiguity as the bare-numeral block above: the DAT's
// own "Select Quickslot N" action ids carry NO default binding at all —
// RetailDefaults()'s Ctrl+N->Select mapping rests on the decompiled
// dispatch function's runtime modifier check, not the raw keymap default.
InputAction.SelectQuickSlot_1,
InputAction.SelectQuickSlot_2,
InputAction.SelectQuickSlot_3,
InputAction.SelectQuickSlot_4,
InputAction.SelectQuickSlot_5,
InputAction.SelectQuickSlot_6,
InputAction.SelectQuickSlot_7,
InputAction.SelectQuickSlot_8,
InputAction.SelectQuickSlot_9,
};
[Fact]
public void MappedActions_DatUnionDefaultBindings_MatchRetailDefaults()
{
string? datDir = Conformance.ConformanceDats.ResolveDatDir();
if (datDir is null) return;
using var dats = new DatCollection(datDir);
var source = new DatCollectionAdapter(dats);
RetailActionMapSnapshot? snapshot = RetailActionMapReader.Read(source);
Assert.NotNull(snapshot);
KeyBindings retailDefaults = KeyBindings.RetailDefaults();
// Aggregate DAT default chords by resolved InputAction — a single action can
// be reached by more than one DAT row (e.g. the Camera/CameraAlternate pair).
var datChordsByAction = new Dictionary<InputAction, HashSet<KeyChord>>();
var unresolvedScanCodes = new List<string>();
foreach (RetailActionMapRow row in snapshot!.Rows)
{
if (!RetailActionIdentityTable.TryResolve(row.InputMapId, row.ActionId, out InputAction action))
continue;
if (!datChordsByAction.TryGetValue(action, out HashSet<KeyChord>? set))
datChordsByAction[action] = set = new HashSet<KeyChord>();
foreach (RetailKeyChord raw in row.DefaultBindings)
{
Silk.NET.Input.Key? key = RetailScanCodeMap.ToSilkKey(raw.Scan, raw.Device);
if (key is null)
{
unresolvedScanCodes.Add(
$"{action}: DAT default scan=0x{raw.Scan:X2} dev={raw.Device} has no "
+ "RetailScanCodeMap entry");
continue;
}
set.Add(new KeyChord(key.Value, RetailScanCodeMap.ToModifierMask(raw.Modifier), (byte)raw.Device));
}
}
Assert.True(datChordsByAction.Count > 100,
$"expected >100 mapped actions, got {datChordsByAction.Count}");
Assert.Empty(unresolvedScanCodes);
var mismatches = new List<string>();
foreach ((InputAction action, HashSet<KeyChord> datChords) in datChordsByAction)
{
if (KnownRetailDefaultsDisagreements.Contains(action)) continue;
var acdreamChords = retailDefaults.ForAction(action).Select(b => b.Chord).ToHashSet();
if (!datChords.SetEquals(acdreamChords))
{
mismatches.Add(
$"{action}: DAT union=[{string.Join(",", datChords)}] vs "
+ $"RetailDefaults()=[{string.Join(",", acdreamChords)}]");
}
}
Assert.True(mismatches.Count == 0,
$"{mismatches.Count} unexpected DAT-vs-RetailDefaults() disagreements "
+ "(not in the documented KnownRetailDefaultsDisagreements allowlist):\n"
+ string.Join("\n", mismatches));
}
}

View file

@ -0,0 +1,248 @@
using System.Collections.Generic;
using AcDream.Content;
using AcDream.Core.Content;
using AcDream.Core.Input;
using DatReaderWriter;
using DatReaderWriter.DBObjs;
using DatReaderWriter.Types;
using DatReaderWriter.Lib.IO;
using Xunit;
namespace AcDream.Core.Tests.Input;
/// <summary>
/// Campaign OP slice OP8: <see cref="RetailActionMapReader"/> conformance.
/// Hermetic tests pin the merge/filter mechanism against a synthetic
/// <see cref="FakeDatObjectSource"/> (no DAT dependency — always runs);
/// <see cref="RetailActionMapReader_LiveDatTests"/> pins the exact row
/// counts and spot-labels against the installed dats (skips cleanly when
/// unavailable, matching <c>ConformanceDats.ResolveDatDir</c>'s pattern).
/// </summary>
public sealed class RetailActionMapReaderTests
{
[Fact]
public void Read_FiltersNonUserBindableActions()
{
var actionMap = new ActionMap
{
StringTableId = 0x23000005u,
InputMaps = new Dictionary<uint, Dictionary<uint, ActionMapValue>>
{
[4u] = new Dictionary<uint, ActionMapValue>
{
// Class 0 == not user-bindable — the reader must drop this row.
[0x1u] = new ActionMapValue { UserBinding = new UserBindingData { ActionClass = 0u } },
// Class 1 (Movement) — kept.
[0x29u] = new ActionMapValue
{
UserBinding = new UserBindingData
{
ActionClass = 1u,
ActionName = 0x111u,
ActionDescription = 0x222u,
},
},
},
},
ConflictingMaps = new Dictionary<uint, InputsConflictsValue>(),
};
var dats = new FakeDatObjectSource();
dats.Add(RetailActionMapIds.ActionMapId, actionMap);
RetailActionMapSnapshot? snapshot = RetailActionMapReader.Read(dats);
Assert.NotNull(snapshot);
RetailActionMapRow row = Assert.Single(snapshot!.Rows);
Assert.Equal(4u, row.InputMapId);
Assert.Equal(0x29u, row.ActionId);
Assert.Equal(RetailActionClass.Movement, row.ActionClass);
Assert.Equal(0x111u, row.LabelHash);
Assert.Equal(0x222u, row.TooltipHash);
}
[Fact]
public void Read_UnionMergesBothMasterMapsWithoutOrderDependency()
{
// The one real collision the live probe found: context 5 exists in BOTH
// master maps with completely disjoint action-id sets (2026-08-11 probe,
// see RetailActionMap.cs class doc unknown #4). Reproduce that shape here
// and assert the merge picks up defaults from BOTH sources for the SAME
// context, order-independent.
var actionMap = new ActionMap
{
InputMaps = new Dictionary<uint, Dictionary<uint, ActionMapValue>>
{
[5u] = new Dictionary<uint, ActionMapValue>
{
[0x3Eu] = new ActionMapValue { UserBinding = new UserBindingData { ActionClass = 2u } },
[0x33u] = new ActionMapValue { UserBinding = new UserBindingData { ActionClass = 2u } },
},
},
ConflictingMaps = new Dictionary<uint, InputsConflictsValue>(),
};
var gameplayMap = new MasterInputMap
{
InputMaps = new Dictionary<uint, CInputMap>
{
[5u] = new CInputMap
{
Mappings = new List<QualifiedControl>
{
new QualifiedControl
{
Key = new ControlSpecification { Key = (0xB5u << 16) | 0u, Modifier = 0u },
Activation = 3u,
Unknown = 0x3Eu,
},
},
},
},
};
var systemMap = new MasterInputMap
{
InputMaps = new Dictionary<uint, CInputMap>
{
[5u] = new CInputMap
{
Mappings = new List<QualifiedControl>
{
new QualifiedControl
{
Key = new ControlSpecification { Key = (0x4Au << 16) | 0u, Modifier = 0u },
Activation = 3u,
Unknown = 0x33u,
},
},
},
},
};
var dats = new FakeDatObjectSource();
dats.Add(RetailActionMapIds.ActionMapId, actionMap);
dats.Add(RetailActionMapIds.GameplayMasterMapId, gameplayMap);
dats.Add(RetailActionMapIds.SystemMasterMapId, systemMap);
RetailActionMapSnapshot? snapshot = RetailActionMapReader.Read(dats);
Assert.NotNull(snapshot);
Assert.Equal(2, snapshot!.Rows.Count);
RetailActionMapRow rowFromGameplayMap = Assert.Single(snapshot.Rows, r => r.ActionId == 0x3Eu);
RetailKeyChord chord1 = Assert.Single(rowFromGameplayMap.DefaultBindings);
Assert.Equal(0xB5u, chord1.Scan);
RetailActionMapRow rowFromSystemMap = Assert.Single(snapshot.Rows, r => r.ActionId == 0x33u);
RetailKeyChord chord2 = Assert.Single(rowFromSystemMap.DefaultBindings);
Assert.Equal(0x4Au, chord2.Scan);
}
[Fact]
public void Read_MissingActionMap_ReturnsNull()
{
var dats = new FakeDatObjectSource();
Assert.Null(RetailActionMapReader.Read(dats));
}
[Fact]
public void Read_MissingMasterMaps_StillReturnsRowsWithEmptyDefaults()
{
var actionMap = new ActionMap
{
InputMaps = new Dictionary<uint, Dictionary<uint, ActionMapValue>>
{
[4u] = new Dictionary<uint, ActionMapValue>
{
[0x29u] = new ActionMapValue { UserBinding = new UserBindingData { ActionClass = 1u } },
},
},
ConflictingMaps = new Dictionary<uint, InputsConflictsValue>(),
};
var dats = new FakeDatObjectSource();
dats.Add(RetailActionMapIds.ActionMapId, actionMap);
RetailActionMapSnapshot? snapshot = RetailActionMapReader.Read(dats);
Assert.NotNull(snapshot);
RetailActionMapRow row = Assert.Single(snapshot!.Rows);
Assert.Empty(row.DefaultBindings);
}
[Fact]
public void RetailInputMapHeaders_HasAllNineteenByteVerifiedEntries()
{
// docs/research/2026-08-10-keyboard-config-and-gameplay-tab.md §5.3.
Assert.Equal(19, RetailInputMapHeaders.NameByInputMapId.Count);
Assert.Equal("ID_InputMap_MovementCommands", RetailInputMapHeaders.NameByInputMapId[0x00000004u]);
Assert.Equal("ID_InputMap_CameraControls", RetailInputMapHeaders.NameByInputMapId[0x00000005u]);
Assert.Equal("ID_InputMap_Emotes", RetailInputMapHeaders.NameByInputMapId[0x10000006u]);
Assert.Equal("ID_InputMap_CharacterOptionCommands", RetailInputMapHeaders.NameByInputMapId[0x10000008u]);
Assert.Equal("ID_InputMap_ToggleChatEntry", RetailInputMapHeaders.NameByInputMapId[0x1000000Du]);
}
/// <summary>Minimal in-memory <see cref="IDatObjectSource"/> for hermetic tests —
/// no DAT file dependency.</summary>
private sealed class FakeDatObjectSource : IDatObjectSource
{
private readonly Dictionary<uint, object> _objects = new();
public void Add<T>(uint fileId, T value) where T : IDBObj => _objects[fileId] = value!;
public T? Get<T>(uint fileId) where T : IDBObj =>
_objects.TryGetValue(fileId, out object? value) && value is T typed ? typed : default;
public bool TryGet<T>(uint fileId, out T value) where T : IDBObj
{
T? found = Get<T>(fileId);
value = found!;
return found is not null;
}
}
}
/// <summary>Live-DAT conformance: pins the exact shape of the installed
/// <c>client_portal.dat</c>/<c>client_local_English.dat</c> ActionMap +
/// MasterInputMap objects. Skips cleanly when the dats are unavailable.</summary>
public sealed class RetailActionMapReader_LiveDatTests
{
[Fact]
public void Read_AgainstInstalledDats_MatchesPinnedShape()
{
string? datDir = Conformance.ConformanceDats.ResolveDatDir();
if (datDir is null) return; // CI / no local install — skip cleanly.
using var dats = new DatCollection(datDir);
var source = new DatCollectionAdapter(dats);
RetailActionMapSnapshot? snapshot = RetailActionMapReader.Read(source);
Assert.NotNull(snapshot);
// Pinned 2026-08-11 against the installed EoR dats — 306 user-bindable rows
// across the six non-zero ActionClass buckets (1,2,3,4,5,7 — never 0 or 6).
Assert.Equal(306, snapshot!.Rows.Count);
var byClass = new Dictionary<RetailActionClass, int>();
foreach (RetailActionMapRow row in snapshot.Rows)
{
Assert.NotEqual(RetailActionClass.None, row.ActionClass);
byClass.TryGetValue(row.ActionClass, out int count);
byClass[row.ActionClass] = count + 1;
}
Assert.Equal(14, byClass[RetailActionClass.Movement]);
Assert.Equal(22, byClass[RetailActionClass.Camera]);
Assert.Equal(103, byClass[RetailActionClass.Ui]);
Assert.Equal(32, byClass[RetailActionClass.Combat]);
Assert.Equal(87, byClass[RetailActionClass.Emote]);
Assert.Equal(48, byClass[RetailActionClass.CharacterSettings]);
// Spot-pin Movement's "Move Forward" (action 0x29, InputMap 0x4): two
// default bindings (W + Up arrow), matching KeyBindings.RetailDefaults()'s
// MovementForward chords.
RetailActionMapRow moveForward = Assert.Single(
snapshot.Rows, r => r.InputMapId == 0x4u && r.ActionId == 0x29u);
Assert.Equal(2, moveForward.DefaultBindings.Count);
Assert.Contains(moveForward.DefaultBindings, c => c.Scan == 0x11u); // DIK_W
Assert.Contains(moveForward.DefaultBindings, c => c.Scan == 0xC8u); // DIK_UPARROW
}
}