Three findings from the user's first Configure Keyboard look (OP8 gate, 2026-08-14), each root-caused against the named retail decomp: - #394 row-caption font: the synthesized action-label UiText never set DatFont and fell to the debug bitmap font. The authored row template (0x21000009/0x1000002F, retail UIOption_ActionKeyMap) carries FontDid 0x4000000A (18px serif) — Bind now takes resolveTemplateFont and applies the template's own authored font, resolved once per template pair. - #395 key captions: raw enum spellings ("Shift+ShiftLeft") replaced by the port of CInputManager_WIN32::GetNameFromKey @0x00687F40 / GetNameFromKey_Internal @0x00687800 (RetailKeyNames): DAT string-table override by DIK-name hash (key enum 4 -> 0x2300000A, meta enum 5 -> 0x2300000B, delimiter enum 3 -> 0x23000007 — GetDIDByEnum category 4, live-probed), else the OS keyboard layout's own key name ("SKIFT") via PlatformKeyNameProvider (Win32 GetKeyNameTextW — register row AD-96 for the DirectInput-vs-GetKeyNameText adaptation), else the DIK-suffix spelling. Bare modifier-key bindings show only the key name. - #396 capture feedback: clicking a mapping button now opens retail's instruction dialog (InitiateBinding @0x004899D0 -> OpenMapWarnDialog @0x00488A00): a type-2 WAIT dialog on retail's MapWarn queue key 0x10000001 with ID_ActionKeyMap_MapInstructions (0x23000004, ACTION variable interpolated), closed on key hit or ESC through the capture callback; capture is not armed if the dialog cannot open, matching retail. New RetailWaitDialogView (wait root 0x31 — same authored popup/message pair 0x3D/0x3E as the confirmation root, live-DAT probed) behind a shared IRetailDialogView presenter seam. Probe evidence (env-gated, kept): KeyboardConfigLiveMountProbeTests.ProbeKeyboardFontsAndKeyNameStrings. Register: AD-96 filed. Gate script OP8 section updated (step 4 rewritten; the "pressed/active state is enough" contract is retired). Full Release solution suite green (13,424 passed / 4 skips). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
727 lines
36 KiB
C#
727 lines
36 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.Linq;
|
||
using System.Numerics;
|
||
using AcDream.App.UI;
|
||
using AcDream.Core.Input;
|
||
using AcDream.UI.Abstractions.Input;
|
||
|
||
namespace AcDream.App.UI.Layout;
|
||
|
||
/// <summary>
|
||
/// Campaign OP slice OP8: retail's Configure Keyboard screen —
|
||
/// <c>gmKeyboardUI</c> (LayoutDesc <c>0x21000009</c>, root <c>0x1000001F</c>,
|
||
/// 800×600), its own SEPARATE full-screen window (research doc's structure
|
||
/// lane §8 / lane D §4.3, NOT a fifth tab of the four-tab Options panel —
|
||
/// "the retail keyboard screen is NOT one of the four Options tabs"). Mounted
|
||
/// the same way the Options panel opens (F11/toolbar → <c>ToggleOptionsPanel</c>
|
||
/// action <c>0x1000001A</c>): the Gameplay tab's Configure Keyboard button
|
||
/// (<c>0x10000204</c>) and this screen's own OK/Cancel buttons all carry
|
||
/// authored <c>P0x12 = 0x1000001F</c> — the SAME toggle-window pattern, byte-
|
||
/// verified against the committed <c>options_gameplay_2100002A.json</c> and
|
||
/// <c>keyboard_config_21000009.json</c> fixtures — so a single <see cref="Toggle"/>
|
||
/// callback covers the open path (the Gameplay-tab button) and both close paths
|
||
/// (OK/Cancel) without porting the generic
|
||
/// <c>UIElementManager::DoVisibilityToggleAction</c> action-broadcast machinery,
|
||
/// which nothing else in this codebase needs yet.
|
||
///
|
||
/// <para>
|
||
/// <b>Six ActionClass list boxes.</b> The screen's own Type-8 tab control
|
||
/// (<c>0x1000049B</c>) hosts six page containers — <c>0x1000049D</c> Movement
|
||
/// (default tab), <c>0x1000049F</c> Camera, <c>0x100004A1</c> Combat,
|
||
/// <c>0x100004A3</c> UI, <c>0x10000211</c> CharacterSettings, <c>0x100004A5</c>
|
||
/// Emote — EACH authoring its OWN identical child subtree: four column headers
|
||
/// (<c>0x10000021</c>-<c>0x10000024</c>, "Command"/"Mapping 1/2/3") and a
|
||
/// Type-5 ListBox (<c>0x10000025</c>) + scrollbar (<c>0x10000026</c>). <b>Every
|
||
/// one of those five ids is REUSED verbatim across all six pages</b> — the
|
||
/// live-DAT dump (<c>keyboard_config_21000009.json</c>) confirms this is the
|
||
/// SAME page-scoped-lookup trap the OP campaign has hit before (OP6's caption
|
||
/// sites): every lookup below is scoped from ITS OWN page's container root via
|
||
/// <see cref="UiElement.FindDescendant"/>, never a flat/global
|
||
/// <c>layout.FindElement</c> for these five ids.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>The row template.</b> <c>AddItemFromTemplateList(0)</c> builds the header
|
||
/// row (<c>0x1000002E</c>, plain text); <c>AddItemFromTemplateList(1)</c> builds
|
||
/// the action row (<c>0x1000002F</c>, Type <c>0x10000034</c> =
|
||
/// <c>UIOption_ActionKeyMap</c>). Its 3 authored children (<c>0x10000030</c>/
|
||
/// <c>31</c>/<c>32</c>, positioned under the "Mapping 1/2/3" columns) are the row's
|
||
/// key buttons — built automatically by <see cref="LayoutImporter"/>'s normal
|
||
/// recursive descent (the row itself is not one of OP2's special
|
||
/// <c>ConsumesDatChildren</c> widgets), so no new <see cref="DatWidgetFactory"/>
|
||
/// case was needed for Type <c>0x10000034</c>. <b>The shipped 2013 template has
|
||
/// exactly 3 key-button children and NO separate Clear-button child</b> — a real,
|
||
/// DAT-verified fact (register row): erasing a single binding is right-click on
|
||
/// its key button (<c>UIOption_ActionKeyMap::EraseBinding</c>, ported via
|
||
/// <see cref="UiButton.OnRightClick"/>); there is no authored affordance for
|
||
/// retail's OWN class-level <c>ClearAllBindings</c> (its <c>m_buttonClear</c>
|
||
/// field exists in the C++ class but nothing in this layout wires it) — its
|
||
/// EFFECT (clear every slot on a row) is still reachable one right-click at a
|
||
/// time. The row's own caption (the action label) is synthesized as a plain
|
||
/// <see cref="UiText"/> child (composition, not inheritance — <see cref="UiText"/>
|
||
/// is sealed), exactly the pattern <c>CharacterStatController.BuildHeaderRow</c>
|
||
/// already uses for a controller-synthesized label beside authored dat children.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Row identity and binding storage (D4).</b> Every row's identity is the DAT
|
||
/// pair <c>(InputMapId, ActionId)</c> — retail's own row key. Where
|
||
/// <see cref="RetailActionIdentityTable"/> resolves that pair to an acdream
|
||
/// <see cref="InputAction"/> (research: roughly half of the DAT's 306 rows — see
|
||
/// that table's class doc for the full accounting), the row's bindings ARE
|
||
/// <see cref="KeyBindings"/>'s bindings for that action: a rebind here takes
|
||
/// effect immediately for live gameplay dispatch through the SAME
|
||
/// <see cref="InputDispatcher"/> every other input path uses, and persists to
|
||
/// <c>keybinds.json</c> exactly like any other rebind (D4 — no separate
|
||
/// <c>.keymap</c> file format). Where no <see cref="InputAction"/> exists yet
|
||
/// (mostly Emotes and CharacterSettings — see the identity table's class doc),
|
||
/// the row is still fully rendered, bindable, conflict-checked, and persisted
|
||
/// (<see cref="Bindings.CurrentForUnmapped"/>/<see cref="Bindings.SetForUnmapped"/>),
|
||
/// it just has no live gameplay consumer yet (register row).
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Activation/Scope preservation (M1, 2026-08-11 review).</b> A mapped row's
|
||
/// <see cref="Bindings.CurrentForAction"/> read returns the FULL live
|
||
/// <see cref="Binding"/> list, not bare chords — a single acdream
|
||
/// <see cref="InputAction"/> consistently carries one <see cref="ActivationType"/>/
|
||
/// <see cref="InputScope"/> pair across every one of its bindings (verified
|
||
/// against every multi-chord action in <c>KeyBindings.RetailDefaults()</c>:
|
||
/// walk-mode's Hold, the three melee/missile/magic combat scopes, ...), so this
|
||
/// row captures that pair ONCE at build time (from the first live binding, or
|
||
/// <see cref="ActivationType.Press"/>/<see cref="InputScope.Game"/> if the action
|
||
/// starts wholly unbound) and reapplies it to every chord this row ever writes —
|
||
/// on a live rebind, on Cancel/Revert (<c>RestoreSavedValue</c>), and on Defaults
|
||
/// (<c>RestoreDefaultValue</c>, which restores DAT-sourced KEYS only; Activation/
|
||
/// Scope are retail-side properties of the ACTION, not of which physical key
|
||
/// triggers it, so Defaults must never touch them). Before this fix,
|
||
/// <c>SetForAction</c> reconstructed every <see cref="Binding"/> with the
|
||
/// constructor's bare defaults (<see cref="ActivationType.Press"/>/
|
||
/// <see cref="InputScope.Game"/>), so a single click of Defaults collapsed the
|
||
/// Hold/scope of every one of the ~140 mapped actions in one shot — walk-mode
|
||
/// stopped unlatching, melee/missile/magic combat holds stopped repeating, and
|
||
/// scope precedence broke for every chord shared across those three scopes by
|
||
/// design (Insert/Delete/End/PageUp/PageDown).
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Conflicts (research doc §5.4, reworked per M3/S1, 2026-08-11 review).</b>
|
||
/// Retail's conflict model is N-way and cross-input-map, with a DISTINCT refusal
|
||
/// for a chord already bound to a non-user-bindable action, checked BEFORE any
|
||
/// user-bindable conflict is even considered (retail refuses outright the instant
|
||
/// ANY conflicting target is non-user-bindable). This port's non-user-bindable
|
||
/// analogue is a chord already bound to an acdream-only action with no
|
||
/// <see cref="RetailActionIdentityTable"/> row at all (Ctrl+M mute, the debug
|
||
/// F-keys, ...) — refused via <see cref="Bindings.NonBindableRefusalText"/>
|
||
/// exactly like retail's distinct <c>OpenCantOverwriteBindingDialog</c>, with no
|
||
/// dialog (a hard stop, matching the DAT-verified refusal string). A genuine
|
||
/// cross-row conflict collects EVERY conflicting row (not just the first) and
|
||
/// opens a real confirm dialog through <see cref="Bindings.ConfirmOverwrite"/> —
|
||
/// retail's <c>OpenOverwriteBindingDialog(&conflicts)</c> — BEFORE reassigning;
|
||
/// only on accept are the losing rows' slots erased and the new chord applied.
|
||
/// </para>
|
||
///
|
||
/// <para>
|
||
/// <b>Caption dimming (AD-78, user-directed, 2026-08-11, gate 2).</b> A row
|
||
/// whose <see cref="RowView.MappedAction"/> is null (AP-203's store-only
|
||
/// set — mostly Emotes and CharacterSettings, plus every non-user-bindable
|
||
/// InputMap this screen renders) dims its synthesized caption via
|
||
/// <see cref="UiRenderContext.StoreOnlyCaptionColor"/> in
|
||
/// <see cref="BuildActionRow"/>. The row stays fully rendered, bindable,
|
||
/// conflict-checked, and persisted (per the paragraph above) — only the
|
||
/// caption color changes, so the dim is a visual "no live gameplay consumer
|
||
/// yet" marker, not a functional restriction.
|
||
/// </para>
|
||
/// </summary>
|
||
public sealed class KeyboardConfigController
|
||
{
|
||
/// <summary>The screen's own top-level LayoutDesc.</summary>
|
||
public const uint LayoutId = 0x21000009u;
|
||
|
||
/// <summary>The window root — ALSO the retail input-action id
|
||
/// (<c>0x1000001F</c>, "Show/Hide Keyboard Configuration") that opens/closes
|
||
/// it, per the Gameplay tab button and this screen's own OK/Cancel buttons
|
||
/// all authoring <c>P0x12 = 0x1000001F</c>.</summary>
|
||
public const uint WindowRootElementId = 0x1000001Fu;
|
||
|
||
private const uint LoadButtonId = 0x10000027u;
|
||
private const uint FilenameLabelId = 0x10000028u;
|
||
private const uint SaveAsButtonId = 0x10000029u;
|
||
private const uint DefaultsButtonId = 0x1000002Au;
|
||
private const uint RevertButtonId = 0x1000002Bu;
|
||
private const uint OkButtonId = 0x1000002Cu;
|
||
private const uint CancelButtonId = 0x1000002Du;
|
||
|
||
// Reused verbatim across all six page containers below — ALWAYS scoped
|
||
// per-page via UiElement.FindDescendant, never a flat layout.FindElement.
|
||
private const uint ListBoxElementId = 0x10000025u;
|
||
private const uint ScrollbarElementId = 0x10000026u;
|
||
|
||
private const int HeaderTemplateIndex = 0;
|
||
private const int RowTemplateIndex = 1;
|
||
|
||
/// <summary>The screen's own Type-8 tab control hosting the six ActionClass
|
||
/// pages (class doc §"Six ActionClass list boxes"). Its authored tab table
|
||
/// (dat property 0x2E) marks Movement (0x1000049D) as the default entry.</summary>
|
||
private const uint TabHostElementId = 0x1000049Bu;
|
||
|
||
// The row template's 3 key-button children, in "Mapping 1/2/3" column order.
|
||
private static readonly uint[] KeyButtonIds = { 0x10000030u, 0x10000031u, 0x10000032u };
|
||
|
||
private static readonly (uint PageContainerId, RetailActionClass Class)[] Pages =
|
||
{
|
||
(0x1000049Du, RetailActionClass.Movement),
|
||
(0x1000049Fu, RetailActionClass.Camera),
|
||
(0x100004A1u, RetailActionClass.Combat),
|
||
(0x100004A3u, RetailActionClass.Ui),
|
||
(0x10000211u, RetailActionClass.CharacterSettings),
|
||
(0x100004A5u, RetailActionClass.Emote),
|
||
};
|
||
|
||
/// <summary>One rendered row: its DAT identity, the built key-button
|
||
/// widgets (up to 3, "Mapping 1/2/3" order), and its
|
||
/// <see cref="ActionKeyMapOptionRow"/> model.</summary>
|
||
public sealed record RowView(
|
||
uint InputMapId,
|
||
uint ActionId,
|
||
InputAction? MappedAction,
|
||
string? Label,
|
||
ActionKeyMapOptionRow Model,
|
||
IReadOnlyList<UiButton> KeyButtons);
|
||
|
||
/// <summary>The live read/write/capture seam this screen writes bindings
|
||
/// through — mirrors every other Campaign OP page controller's
|
||
/// <c>Bindings</c> shape (a plain delegate record, no DAT/InputDispatcher
|
||
/// dependency baked into the controller itself). <see cref="CurrentForAction"/>/
|
||
/// <see cref="SetForAction"/> carry the FULL <see cref="Binding"/> (chord +
|
||
/// activation + scope), not a bare chord — M1's fix (see class doc).</summary>
|
||
public sealed record Bindings(
|
||
Func<InputAction, IReadOnlyList<Binding>> CurrentForAction,
|
||
Action<InputAction, IReadOnlyList<Binding>> SetForAction,
|
||
Func<(uint InputMapId, uint ActionId), IReadOnlyList<KeyChord>> CurrentForUnmapped,
|
||
Action<(uint InputMapId, uint ActionId), IReadOnlyList<KeyChord>> SetForUnmapped,
|
||
Action<Action<KeyChord?>> BeginCapture,
|
||
Action Save,
|
||
Action Toggle,
|
||
Action<string> DisplaySystemMessage,
|
||
string NonBindableRefusalText,
|
||
// M3 (2026-08-11 review): retail's OpenOverwriteBindingDialog — confirm
|
||
// BEFORE reassigning a chord already bound to another row on this screen.
|
||
// message is pre-composed (real row labels, no invented retail text);
|
||
// the callback receives the user's Yes(true)/No(false) choice.
|
||
Action<string, Action<bool>> ConfirmOverwrite,
|
||
// OP8 re-gate (2026-08-14): retail's capture-instruction dialog —
|
||
// UIOption_ActionKeyMap::InitiateBinding @ 0x004899D0 opens the
|
||
// MapWarn wait dialog (ID_ActionKeyMap_MapInstructions with the row's
|
||
// action label interpolated) BEFORE registering the key handler, and
|
||
// refuses to arm capture at all if the dialog could not open. Open
|
||
// receives the row label and returns the dialog context (0 = could
|
||
// not open); Close closes that context when the capture ends (key hit
|
||
// or ESC). Null keeps the pre-dialog capture behavior for hosts with
|
||
// no dialog factory (unit fixtures).
|
||
Func<string, uint>? OpenCaptureInstructions = null,
|
||
Action<uint>? CloseCaptureInstructions = null);
|
||
|
||
public OptionPage Page { get; } = new();
|
||
public IReadOnlyList<RowView> Rows => _rows;
|
||
|
||
private readonly List<RowView> _rows = new();
|
||
private readonly Dictionary<(uint LayoutId, uint ElementId), UiDatFont?> _templateFontCache = new();
|
||
private Bindings? _bindings;
|
||
private Func<KeyChord, string> _describe = DescribeChord;
|
||
private Func<uint, uint, UiDatFont?>? _resolveTemplateFont;
|
||
|
||
private KeyboardConfigController() { }
|
||
|
||
/// <summary>
|
||
/// Builds every header + row across all six pages from
|
||
/// <paramref name="snapshot"/>, wires each row's key buttons to modal
|
||
/// capture / right-click erase, and wires the screen's own six buttons
|
||
/// (Defaults/Revert/OK/Cancel; Load/Save File are INERT — D4, no
|
||
/// <c>.keymap</c> interchange). Returns null if the layout's window root
|
||
/// did not import (a missing/malformed LayoutDesc).
|
||
/// </summary>
|
||
public static KeyboardConfigController? Bind(
|
||
ImportedLayout layout,
|
||
RetailActionMapSnapshot snapshot,
|
||
Func<uint, uint, UiElement?> templateResolver,
|
||
Func<uint, uint, string?> resolveString,
|
||
Bindings bindings,
|
||
Func<uint, uint, UiDatFont?>? resolveTemplateFont = null)
|
||
{
|
||
ArgumentNullException.ThrowIfNull(layout);
|
||
ArgumentNullException.ThrowIfNull(snapshot);
|
||
ArgumentNullException.ThrowIfNull(templateResolver);
|
||
ArgumentNullException.ThrowIfNull(resolveString);
|
||
ArgumentNullException.ThrowIfNull(bindings);
|
||
|
||
if (layout.FindElement(WindowRootElementId) is null)
|
||
{
|
||
Console.WriteLine(
|
||
$"[D.2b] KeyboardConfigController: window root 0x{WindowRootElementId:X8} "
|
||
+ "not found in the built layout — Configure Keyboard will not open.");
|
||
return null;
|
||
}
|
||
|
||
var controller = new KeyboardConfigController
|
||
{
|
||
_bindings = bindings,
|
||
_resolveTemplateFont = resolveTemplateFont,
|
||
// OP8 re-gate (2026-08-14): key-button captions through retail's
|
||
// GetNameFromKey pipeline (DAT table override → OS-localized name)
|
||
// instead of raw enum spellings ("Shift+ShiftLeft").
|
||
_describe = new RetailKeyNames(resolveString).Describe,
|
||
};
|
||
|
||
var byClass = snapshot.Rows
|
||
.Where(r => r.ActionClass != RetailActionClass.None)
|
||
.GroupBy(r => r.ActionClass)
|
||
.ToDictionary(g => g.Key, g => g.ToList());
|
||
|
||
foreach ((uint pageContainerId, RetailActionClass cls) in Pages)
|
||
{
|
||
UiElement? pageRoot = UiElement.FindDescendant(layout.Root, pageContainerId);
|
||
if (pageRoot is null)
|
||
{
|
||
Console.WriteLine(
|
||
$"[D.2b] KeyboardConfigController: page container 0x{pageContainerId:X8} "
|
||
+ "not found — that ActionClass tab will have no rows.");
|
||
continue;
|
||
}
|
||
if (UiElement.FindDescendant(pageRoot, ListBoxElementId) is not UiTemplateListBox listBox)
|
||
{
|
||
Console.WriteLine(
|
||
$"[D.2b] KeyboardConfigController: ListBox 0x{ListBoxElementId:X8} not found "
|
||
+ $"(or not a UiTemplateListBox) under page 0x{pageContainerId:X8}.");
|
||
continue;
|
||
}
|
||
listBox.TemplateResolver = templateResolver;
|
||
if (UiElement.FindDescendant(pageRoot, ScrollbarElementId) is UiScrollbar scrollbar)
|
||
scrollbar.Model = listBox.Scroll;
|
||
|
||
if (!byClass.TryGetValue(cls, out List<RetailActionMapRow>? classRows))
|
||
continue;
|
||
|
||
// Group by InputMapId in first-seen order (retail's own bucket ->
|
||
// header-per-InputMapId order, research doc §5.2's InitOptions loop).
|
||
var byInputMap = classRows
|
||
.GroupBy(r => r.InputMapId)
|
||
.OrderBy(g => g.Key);
|
||
|
||
foreach (var inputMapGroup in byInputMap)
|
||
{
|
||
BuildHeaderRow(listBox, inputMapGroup.Key, resolveString);
|
||
foreach (RetailActionMapRow row in inputMapGroup)
|
||
controller.BuildActionRow(listBox, row, resolveString, bindings);
|
||
}
|
||
}
|
||
|
||
WireScreenButtons(layout, controller, bindings);
|
||
|
||
// Gate-2 screenshot finding (#375 residual): OP8 built all six pages
|
||
// but never ACTIVATED the screen's own tab control, so every page
|
||
// stayed Visible simultaneously — six stacked ListBoxes reading as
|
||
// "overlapping text", with six dead tab buttons above them.
|
||
// ActivateTabBehavior wires the authored tab clicks and performs the
|
||
// authored default-entry switch (Movement, IsDefault=true in the DAT
|
||
// table), hiding the other five pages — the exact same call
|
||
// OptionsPanelController makes on ITS Type-8 host at construction.
|
||
if (layout.FindElement(TabHostElementId) is UiTabPanel tabHost)
|
||
{
|
||
tabHost.ActivateTabBehavior();
|
||
}
|
||
else
|
||
{
|
||
Console.WriteLine(
|
||
$"[D.2b] KeyboardConfigController: tab host 0x{TabHostElementId:X8} not found "
|
||
+ "(or not a UiTabPanel) — all six ActionClass pages will render stacked.");
|
||
}
|
||
|
||
return controller;
|
||
}
|
||
|
||
private static void BuildHeaderRow(
|
||
UiTemplateListBox listBox, uint inputMapId, Func<uint, uint, string?> resolveString)
|
||
{
|
||
if (listBox.AddItemFromTemplateList(HeaderTemplateIndex) is not UiText header)
|
||
{
|
||
Console.WriteLine(
|
||
"[D.2b] KeyboardConfigController: header template did not build as UiText "
|
||
+ $"for InputMap 0x{inputMapId:X8}.");
|
||
return;
|
||
}
|
||
if (!RetailInputMapHeaders.NameByInputMapId.TryGetValue(inputMapId, out string? headerKey))
|
||
return; // Unnamed InputMap — retail never reaches this (§5.3): no bindable
|
||
// action of ours falls in one, but stay honest rather than assume.
|
||
|
||
string? label = resolveString(
|
||
RetailInputMapHeaders.StringTableId, DatStringResolver.ComputeHash(headerKey));
|
||
if (label is null)
|
||
{
|
||
Console.WriteLine(
|
||
$"[D.2b] KeyboardConfigController: header string '{headerKey}' did not resolve — "
|
||
+ "row renders with no text rather than invented English.");
|
||
return;
|
||
}
|
||
header.LinesProvider = () => new[] { new UiText.Line(label, header.DefaultColor) };
|
||
}
|
||
|
||
private void BuildActionRow(
|
||
UiTemplateListBox listBox,
|
||
RetailActionMapRow row,
|
||
Func<uint, uint, string?> resolveString,
|
||
Bindings bindings)
|
||
{
|
||
UiElement? built = listBox.AddItemFromTemplateList(RowTemplateIndex);
|
||
if (built is null)
|
||
{
|
||
Console.WriteLine(
|
||
"[D.2b] KeyboardConfigController: row template did not build for InputMap "
|
||
+ $"0x{row.InputMapId:X8} action 0x{row.ActionId:X8}.");
|
||
return;
|
||
}
|
||
|
||
var keyButtons = new List<UiButton>(KeyButtonIds.Length);
|
||
foreach (uint id in KeyButtonIds)
|
||
{
|
||
if (UiElement.FindDescendant(built, id) is UiButton button)
|
||
keyButtons.Add(button);
|
||
}
|
||
|
||
string? label = resolveString(RetailInputMapHeaders.StringTableId, row.LabelHash);
|
||
string? tooltip = resolveString(RetailInputMapHeaders.StringTableId, row.TooltipHash);
|
||
|
||
bool mapped = RetailActionIdentityTable.TryResolve(row.InputMapId, row.ActionId, out InputAction action);
|
||
InputAction? mappedAction = mapped ? action : null;
|
||
|
||
// The row's own caption — synthesized, composed beside the authored key
|
||
// buttons (UiText is sealed; see class doc). Occupies the "Command" column
|
||
// (x=0..270, matching the authored column headers). AD-78 (user-directed,
|
||
// 2026-08-11, gate 2): an unmapped row (MappedAction null — no live
|
||
// InputDispatcher consumer, AP-203) dims its caption; the key buttons
|
||
// themselves stay fully interactive (bindable/persisted/conflict-checked,
|
||
// see class doc).
|
||
var captionText = new UiText
|
||
{
|
||
Left = 0f,
|
||
Top = 0f,
|
||
Width = 260f,
|
||
Height = built.Height,
|
||
ClickThrough = true,
|
||
Centered = false,
|
||
RightAligned = false,
|
||
Padding = 2f,
|
||
Anchors = AnchorEdges.Left | AnchorEdges.Top,
|
||
DefaultColor = mapped ? Vector4.One : UiRenderContext.StoreOnlyCaptionColor,
|
||
// OP8 re-gate (2026-08-14): retail draws the row's action label
|
||
// with the row template's OWN authored font (UIOption_ActionKeyMap
|
||
// element 0x1000002F authors FontDid 0x4000000A, the 18px serif —
|
||
// live-DAT probed). The synthesized caption previously set no
|
||
// DatFont at all and fell back to the debug bitmap font.
|
||
DatFont = RowCaptionFont(listBox),
|
||
};
|
||
if (label is not null)
|
||
captionText.LinesProvider = () => new[] { new UiText.Line(label, captionText.DefaultColor) };
|
||
built.AddChild(captionText);
|
||
|
||
// M1: capture this row's live Activation/Scope ONCE, from the first
|
||
// existing binding for the action (every multi-chord action in
|
||
// KeyBindings.RetailDefaults() shares one Activation/Scope pair across
|
||
// all its bindings — see class doc). Falls back to the Binding record's
|
||
// own defaults (Press/Game) only when the action starts wholly unbound.
|
||
IReadOnlyList<Binding> liveBindings = mapped
|
||
? bindings.CurrentForAction(action)
|
||
: Array.Empty<Binding>();
|
||
(ActivationType Activation, InputScope Scope) template = liveBindings.Count > 0
|
||
? (liveBindings[0].Activation, liveBindings[0].Scope)
|
||
: (ActivationType.Press, InputScope.Game);
|
||
|
||
IReadOnlyList<KeyChord> defaults = DatDefaultsToChords(row.DefaultBindings);
|
||
IReadOnlyList<KeyChord> storedUnmapped = mapped
|
||
? Array.Empty<KeyChord>()
|
||
: bindings.CurrentForUnmapped((row.InputMapId, row.ActionId));
|
||
// OP8 re-review round 2 (SHOULD-FIX): an unmapped/store-only row with
|
||
// no persisted chords displays its DAT DEFAULTS — retail shows the
|
||
// authored bindings (the Camera Alternate rows' arrow keys) and a
|
||
// blank row misreads as "unbound". Display-only: nothing here feeds
|
||
// the InputDispatcher, and the store only gains the defaults if the
|
||
// user actually edits the row (the apply closure below).
|
||
IReadOnlyList<KeyChord> initial = mapped
|
||
? liveBindings.Select(b => b.Chord).ToArray()
|
||
: storedUnmapped.Count > 0 ? storedUnmapped : defaults;
|
||
|
||
var model = new ActionKeyMapOptionRow(initial, defaults, apply: value =>
|
||
{
|
||
// Interior/padding default(KeyChord) entries (S4 — sparse-slot
|
||
// display, see ReplaceSlotValue) are never real bindings; filter
|
||
// them out at the write boundary, not at storage time.
|
||
IReadOnlyList<KeyChord> real = value.Where(c => c != default).ToArray();
|
||
if (mapped)
|
||
bindings.SetForAction(
|
||
action,
|
||
real.Select(c => new Binding(c, action, template.Activation, template.Scope)).ToArray());
|
||
else
|
||
bindings.SetForUnmapped((row.InputMapId, row.ActionId), real);
|
||
});
|
||
Page.Register(model);
|
||
|
||
var view = new RowView(row.InputMapId, row.ActionId, mappedAction, label, model, keyButtons);
|
||
_rows.Add(view);
|
||
|
||
RefreshRowButtons(view);
|
||
|
||
for (int slot = 0; slot < keyButtons.Count; slot++)
|
||
{
|
||
int capturedSlot = slot;
|
||
keyButtons[slot].TooltipText = tooltip;
|
||
keyButtons[slot].OnClick = () => BeginSlotCapture(view, capturedSlot, bindings);
|
||
keyButtons[slot].OnRightClick = () => EraseSlot(view, capturedSlot);
|
||
}
|
||
}
|
||
|
||
/// <summary>The authored font of this ListBox's action-row template,
|
||
/// resolved once per (layout, element) pair. Null (template import or
|
||
/// font-load failure, or no resolver wired) keeps the debug-font fallback.</summary>
|
||
private UiDatFont? RowCaptionFont(UiTemplateListBox listBox)
|
||
{
|
||
if (_resolveTemplateFont is null
|
||
|| RowTemplateIndex >= listBox.Templates.Count)
|
||
return null;
|
||
(uint layoutId, uint elementId) = (
|
||
listBox.Templates[RowTemplateIndex].TemplateLayoutId,
|
||
listBox.Templates[RowTemplateIndex].TemplateElementId);
|
||
if (_templateFontCache.TryGetValue((layoutId, elementId), out UiDatFont? cached))
|
||
return cached;
|
||
UiDatFont? font = _resolveTemplateFont(layoutId, elementId);
|
||
_templateFontCache[(layoutId, elementId)] = font;
|
||
return font;
|
||
}
|
||
|
||
private static IReadOnlyList<KeyChord> DatDefaultsToChords(IReadOnlyList<RetailKeyChord> raw)
|
||
{
|
||
var result = new List<KeyChord>(raw.Count);
|
||
foreach (RetailKeyChord chord in raw)
|
||
{
|
||
Silk.NET.Input.Key? key = RetailScanCodeMap.ToSilkKey(chord.Scan, chord.Device);
|
||
if (key is null) continue; // unresolved scan code — omit rather than guess.
|
||
result.Add(new KeyChord(key.Value, RetailScanCodeMap.ToModifierMask(chord.Modifier), (byte)chord.Device));
|
||
}
|
||
return result;
|
||
}
|
||
|
||
private void RefreshRowButtons(RowView view)
|
||
{
|
||
IReadOnlyList<KeyChord> current = view.Model.Current;
|
||
for (int i = 0; i < view.KeyButtons.Count; i++)
|
||
{
|
||
bool bound = i < current.Count && current[i] != default;
|
||
view.KeyButtons[i].Label = bound ? _describe(current[i]) : null;
|
||
}
|
||
}
|
||
|
||
/// <summary>Raw enum spelling — construction-time default until Bind swaps
|
||
/// in <see cref="RetailKeyNames.Describe"/>, and that class's own fallback
|
||
/// for controls outside the DIK table.</summary>
|
||
private static string DescribeChord(KeyChord chord)
|
||
{
|
||
string mods = chord.Modifiers == ModifierMask.None ? "" : chord.Modifiers.ToString() + "+";
|
||
return mods + chord.Key;
|
||
}
|
||
|
||
private void BeginSlotCapture(RowView view, int slot, Bindings bindings)
|
||
{
|
||
// Retail InitiateBinding @ 0x004899D0: open the capture-instruction
|
||
// dialog (ID_ActionKeyMap_MapInstructions with this row's label) and
|
||
// register the input handler ONLY if the dialog opened. A host with no
|
||
// dialog seam wired (null) keeps the dialog-less capture.
|
||
uint instructionsContext = 0u;
|
||
if (bindings.OpenCaptureInstructions is { } openInstructions)
|
||
{
|
||
instructionsContext = openInstructions(view.Label ?? string.Empty);
|
||
if (instructionsContext == 0u)
|
||
{
|
||
Console.WriteLine(
|
||
"[D.2b] KeyboardConfigController: capture-instruction dialog "
|
||
+ "could not open — capture not armed (retail refuses too).");
|
||
return;
|
||
}
|
||
}
|
||
|
||
bindings.BeginCapture(captured =>
|
||
{
|
||
if (instructionsContext != 0u)
|
||
bindings.CloseCaptureInstructions?.Invoke(instructionsContext);
|
||
|
||
if (captured is not { } chord) return; // Escape — retail cancels silently.
|
||
|
||
(ConflictOutcome outcome, List<RowView> conflictRows) = FindConflicts(chord, exclude: view);
|
||
switch (outcome)
|
||
{
|
||
case ConflictOutcome.NonBindable:
|
||
// S1 / retail order: checked BEFORE any row conflict is even
|
||
// considered — retail refuses outright the instant ANY
|
||
// conflicting target is non-user-bindable. This port's
|
||
// analogue: a chord already bound to an acdream-only action
|
||
// with no DAT row at all (Ctrl+M mute, the debug F-keys, ...) —
|
||
// OpenCantOverwriteBindingDialog's ported refusal, no dialog.
|
||
bindings.DisplaySystemMessage(bindings.NonBindableRefusalText);
|
||
return;
|
||
|
||
case ConflictOutcome.Rows:
|
||
// M3: retail's OpenOverwriteBindingDialog — confirm BEFORE
|
||
// reassigning (N-way: every conflicting row is named, not just
|
||
// the first). Only on accept do the losing rows lose the slot.
|
||
string names = string.Join(", ", conflictRows.Select(r => r.Label ?? "?"));
|
||
string message =
|
||
$"'{_describe(chord)}' is already bound to {names}. "
|
||
+ $"Reassign it to '{view.Label}'?";
|
||
bindings.ConfirmOverwrite(message, accepted =>
|
||
{
|
||
if (!accepted) return;
|
||
foreach (RowView conflictRow in conflictRows)
|
||
{
|
||
ReplaceSlotValue(conflictRow, RemoveChord(conflictRow.Model.Current, chord));
|
||
RefreshRowButtons(conflictRow);
|
||
}
|
||
ApplySlot(view, slot, chord);
|
||
});
|
||
return;
|
||
|
||
case ConflictOutcome.None:
|
||
ApplySlot(view, slot, chord);
|
||
return;
|
||
}
|
||
});
|
||
}
|
||
|
||
private void ApplySlot(RowView view, int slot, KeyChord chord)
|
||
{
|
||
List<KeyChord> updated = new(view.Model.Current);
|
||
while (updated.Count <= slot) updated.Add(default);
|
||
updated[slot] = chord;
|
||
ReplaceSlotValue(view, updated);
|
||
RefreshRowButtons(view);
|
||
}
|
||
|
||
private void EraseSlot(RowView view, int slot)
|
||
{
|
||
if (slot >= view.Model.Current.Count) return;
|
||
if (view.Model.Current[slot] == default) return; // nothing bound in this display slot
|
||
var updated = new List<KeyChord>(view.Model.Current);
|
||
updated.RemoveAt(slot);
|
||
ReplaceSlotValue(view, updated);
|
||
RefreshRowButtons(view);
|
||
}
|
||
|
||
private static void ReplaceSlotValue(RowView view, IReadOnlyList<KeyChord> value)
|
||
{
|
||
// S4 (2026-08-11 review): only trim TRAILING empty slots. Retail's
|
||
// SetBinding(qc, slot) writes the SPECIFIC slot the user clicked — a row
|
||
// with no bindings whose "Mapping 3" button is set must keep the chord at
|
||
// display index 2, not collapse it onto index 0. Interior default(KeyChord)
|
||
// entries only ever come from ApplySlot's own padding, so trimming just the
|
||
// tail keeps RefreshRowButtons' positional read correct without inventing a
|
||
// nullable-chord storage type.
|
||
int lastReal = -1;
|
||
for (int i = 0; i < value.Count; i++)
|
||
if (value[i] != default) lastReal = i;
|
||
view.Model.SetCurrentValue(lastReal < 0 ? Array.Empty<KeyChord>() : value.Take(lastReal + 1).ToArray());
|
||
}
|
||
|
||
private static IReadOnlyList<KeyChord> RemoveChord(IReadOnlyList<KeyChord> from, KeyChord chord) =>
|
||
from.Where(c => c != chord).ToArray();
|
||
|
||
private enum ConflictOutcome { None, NonBindable, Rows }
|
||
|
||
/// <summary>
|
||
/// Retail's N-way, cross-input-map conflict scan (research doc §5.4:
|
||
/// <c>ICIDM::FindConflictingInputMaps</c>/<c>FindConflictingControls</c>),
|
||
/// scoped to this screen's own universe: the non-user-bindable check runs
|
||
/// FIRST (S1 — retail's own order), then EVERY OTHER row's current chord set
|
||
/// (covers BOTH mapped and unmapped rows — a chord already claimed by an
|
||
/// unmapped row is just as real a conflict as one claimed by a mapped one) is
|
||
/// collected in full, not just the first match.
|
||
/// </summary>
|
||
private (ConflictOutcome Outcome, List<RowView> Rows) FindConflicts(KeyChord chord, RowView exclude)
|
||
{
|
||
if (_bindings is not null)
|
||
{
|
||
foreach (InputAction candidate in Enum.GetValues<InputAction>())
|
||
{
|
||
if (RetailActionIdentityTable.Map.Values.Contains(candidate)) continue;
|
||
if (_bindings.CurrentForAction(candidate).Any(b => b.Chord == chord))
|
||
return (ConflictOutcome.NonBindable, new List<RowView>());
|
||
}
|
||
}
|
||
|
||
var rows = new List<RowView>();
|
||
foreach (RowView other in _rows)
|
||
{
|
||
if (ReferenceEquals(other, exclude)) continue;
|
||
// OP8 re-review round 2 R1: store-only rows (MappedAction null —
|
||
// the Camera Alternate scheme, Emote/CharacterSettings hotkeys)
|
||
// never reach the InputDispatcher, so a chord they display cannot
|
||
// actually collide with anything; counting them made the ten
|
||
// arrow-key defaults trip a false N-way confirm on any arrow
|
||
// rebind. Retail-mapped cross-context sharing (ConflictingMaps —
|
||
// the Insert/Delete/End/PageUp/PageDown combat cluster) remains
|
||
// deferred as ISSUES #373; only INERT rows are excluded here.
|
||
if (other.MappedAction is null) continue;
|
||
if (other.Model.Current.Contains(chord))
|
||
rows.Add(other);
|
||
}
|
||
return rows.Count > 0 ? (ConflictOutcome.Rows, rows) : (ConflictOutcome.None, rows);
|
||
}
|
||
|
||
private static void WireScreenButtons(
|
||
ImportedLayout layout, KeyboardConfigController controller, Bindings bindings)
|
||
{
|
||
// Load File / Save As — INERT (D4: keybinds.json only, no .keymap
|
||
// interchange). Authored, clickable, no handler — same shape as OP3's
|
||
// still-inert buttons.
|
||
_ = layout.FindElement(LoadButtonId);
|
||
_ = layout.FindElement(SaveAsButtonId);
|
||
_ = layout.FindElement(FilenameLabelId);
|
||
|
||
if (layout.FindElement(DefaultsButtonId) is UiButton defaultsButton)
|
||
defaultsButton.OnClick = () =>
|
||
{
|
||
foreach (RowView row in controller._rows)
|
||
row.Model.SetDefaultValue(row.Model.DefaultValue);
|
||
controller.Page.Defaults();
|
||
foreach (RowView row in controller._rows)
|
||
controller.RefreshRowButtons(row);
|
||
};
|
||
|
||
if (layout.FindElement(RevertButtonId) is UiButton revertButton)
|
||
revertButton.OnClick = () =>
|
||
{
|
||
controller.Page.Reset();
|
||
foreach (RowView row in controller._rows)
|
||
controller.RefreshRowButtons(row);
|
||
};
|
||
|
||
// OK — right-click release in retail (idMessage 0x19); ported as a plain
|
||
// left-click here, matching every other Campaign OP button (the asymmetry
|
||
// is authored-input-only — no user-visible affordance differs, since
|
||
// retail's own right-click-release on just this pair of buttons carries
|
||
// no distinguishing visual cue either).
|
||
if (layout.FindElement(OkButtonId) is UiButton okButton)
|
||
okButton.OnClick = () =>
|
||
{
|
||
controller.Page.Apply();
|
||
bindings.Save();
|
||
bindings.Toggle();
|
||
};
|
||
|
||
if (layout.FindElement(CancelButtonId) is UiButton cancelButton)
|
||
cancelButton.OnClick = () =>
|
||
{
|
||
controller.Page.Reset();
|
||
foreach (RowView row in controller._rows)
|
||
controller.RefreshRowButtons(row);
|
||
bindings.Toggle();
|
||
};
|
||
}
|
||
}
|