Skip to content

[Keyboard Manager] Add "alone" (tap) condition for single-key remaps (dual-key / to_if_alone) - #49136

Merged
Muyuan Li (MuyuanMS) merged 16 commits into
microsoft:mainfrom
MasaYan24:feature/kbm-dual-key-alone
Aug 31, 2026
Merged

Muyuan Li (MuyuanMS) merged 16 commits into
microsoft:mainfrom
MasaYan24:feature/kbm-dual-key-alone

Conversation

@MasaYan24

@MasaYan24 takahashi (MasaYan24) commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary of the Pull Request

Adds an optional "alone" condition to single-key remaps in Keyboard Manager, bringing
Karabiner-style to_if_alone (dual-key / tap-vs-hold) behavior: a key can perform one action
when tapped by itself while still acting as its normal self when combined with other
keys — via the keyboard or the mouse.

Example use case: Right Ctrl → IME On when tapped alone, Left Ctrl → IME Off when tapped alone,
while Right/Left Ctrl + other keys / clicks / wheel keep working as normal Ctrl. This is the
Windows equivalent of the popular macOS "left/right ⌘ → 英数/かな" mapping.

Demo

Muted screen recording with on-screen captions (the physical keys I press aren't visible; a red ring marks the tray IME indicator あ / A so the On/Off switching is easy to follow):

PR49136-DEMO-repost-MasaYan24.mp4

What it shows:

  1. Tap Right Ctrl alone → IME On (Japanese); tap Left Ctrl alone → IME Off (English) — directional and idempotent (repeated taps keep the same state).
  2. The same keys still act as normal modifiers in combination: Right Ctrl + H/J/K/L → arrow keys (Vim-style), and Ctrl+A / Ctrl+C / Ctrl+V behave normally.
  3. Mouse combinations preserved: a plain click follows a link, while Ctrl+Click opens it in a new tab (via the companion low-level mouse hook).
  4. In Keyboard Manager the whole config is just two "Alone" single-key remaps plus the Ctrl+H/J/K/L arrows, and the edit dialog shows the new Condition → "Alone (tap)".

PR Checklist

Detailed Description of the Pull Request / Additional comments

Engine (C++):

  • New separate remap table aloneSingleKeyReMap (parallel to singleKeyReMap) with
    Add/Clear/GetSingleKeyAloneRemap (MappingConfiguration).
  • New handler HandleSingleKeyAloneRemapEvent using a lazy + release-fire strategy:
    suppress the alone key's key-down; on the first other key it flushes the original key-down
    (promoting to a normal combination); on solo release it fires the alone action. Wired into the
    hook dispatch before the normal single-key handler; per-key runtime state lives in State.
  • Mouse combinations: a companion low-level mouse hook (WH_MOUSE_LL) is installed alongside
    the keyboard hook only while alone remaps exist (reconciled on settings reload). On a
    button-down or wheel event — but not mouse-move, which must not cancel a tap — it promotes
    the held alone key(s) to a real modifier via the shared PromotePendingAloneKeysToCombination,
    so Ctrl+Click / Ctrl+Wheel work while an alone-mapped Ctrl is held. The mouse event itself is
    never suppressed; State::HasPendingAloneKeys gives the hook a cheap early-out.
  • Settings JSON: an optional "condition" field per single-key remap ("always" default, or
    "alone"). Fully backward compatible; both load and save handle it, so hand-edited or
    UI-created alone remaps round-trip without loss.

Editor UI (WinUI3):

  • Native wrapper exposes parallel alone add/get/delete over the alone table (reuses the existing
    SingleKeyMapping marshaling struct).
  • SingleKeyRemapCondition (Always / Alone) flows through the C# interop/service/model layers.
  • A localized "Condition" combo box in the add/edit dialog, shown only for a single-key
    remap whose action is a key/shortcut
    (the case the engine supports), plus a localized
    "Alone" badge on such rows in the list.
  • Modifier-conflict validation fix: two distinct modifier sides (e.g. Left Ctrl and Right
    Ctrl) are no longer flagged as a "conflicting modifier". The check now only fires when one side
    is the generic, side-agnostic modifier (Ctrl/Shift/Alt/Win) versus a specific side — which is
    exactly the left/right pairing this feature targets.
  • Duplicate-entry fix: the editor's own settings store now rejects exact-duplicate remaps
    (guarding the add path the way the engine tables already do, condition-aware so "always" vs
    "alone" stay distinct) and self-heals pre-existing duplicates on load, so a remap can no
    longer appear twice in the list after mixed GUI / hand-edited-config changes.

Known limitations / follow-ups (intentionally not in this PR):

  • Hold-timeout not implemented (holding the alone key then releasing still fires the alone action;
    needs an injectable clock — deferred, noted in code).
  • Alone target supports a single key or a shortcut (not text/URL/app).

Validation Steps Performed

  • Engine unit tests: 110/110 (alone tests + edge cases, incl. 2 new mouse-promotion cases).
    Editor C++ tests: 88/88.
  • Editor UI project compiles clean (0 warnings / 0 errors).
  • Manual E2E on real hardware (self-built x64 Release, multiple machines):
    • Right Ctrl tapped alone → IME On; Left Ctrl tapped alone → IME Off (directional, idempotent).
    • Ctrl+C / V / Z / A and existing Ctrl-based custom shortcuts unaffected (keyboard modifier
      pass-through OK).
    • Ctrl+Click and Ctrl+Wheel work while an alone-mapped Ctrl is held (mouse-combo pass-through).
    • Left Ctrl and Right Ctrl can both be mapped at once with no false "conflicting modifier" error.
    • Editor UI: opening an existing alone remap shows Condition = "Alone (tap)"; saving round-trips a
      full real-world config (single-key + dozens of global and app-specific shortcuts) with zero
      loss
      and no duplicate rows; the "Alone" badge and the show/hide gating of the Condition
      combo both behave correctly.
takahashi (MasaYan24) and others added 7 commits July 5, 2026 10:10
…y tap/hold)

Add a dual-key remap capability to the KBM engine: a single key can carry an
"Alone" action that applies only when the key is tapped alone, while using it in
combination with other keys passes the original key through as a real key/modifier
(equivalent to Karabiner's to_if_alone). Uses the lazy + release-fire approach so
the combination path has zero added latency.

- New aloneSingleKeyReMap table plus Add/Clear/GetSingleKeyAloneRemap on
  MappingConfiguration/State, kept separate from the existing singleKeyReMap.
- HandleSingleKeyAloneRemapEvent: suppresses the physical key-down (lazy); on
  another key-down it injects the original key as a real modifier (combination);
  on release with no intervening key it injects the alone action as a tap.
- Per-key runtime state (pending vs combination) tracked in State across the
  separate key-down/key-up hook invocations.
- 3 unit tests: no-injection-on-keydown, tap-alone injection, combination
  pass-through.

Timeout-based cancellation (holding too long is not a tap) is intentionally
deferred; it needs an injectable clock to be unit-testable. The handler is not
yet wired into the runtime dispatch chain.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…ition" from settings

- Call HandleSingleKeyAloneRemapEvent before HandleSingleKeyRemapEvent in the
  keyboard hook dispatch so alone-mapped keys are handled with priority (lazy
  key-down hold, tap-vs-combination decision).
- Include aloneSingleKeyReMap in HasRegisteredRemappingsUnchecked so a config
  with only alone remaps still activates the engine.
- Load an optional "condition" field on single-key remaps: "alone" routes the
  entry to the alone table; a missing field (or "always") keeps the legacy
  unconditional behavior, so existing settings files load unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…andler

- Add unit tests for a disabled alone target (tapping injects nothing) and for a
  solo tap after a prior combination cycle (per-key runtime state resets cleanly).
- Document HandleSingleKeyAloneRemapEvent and the optional "condition" settings
  field in the keyboard event handlers devdoc.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
SaveSettingsToFile previously wrote only singleKeyReMap and never persisted the
aloneSingleKeyReMap table, so an alone remap loaded from settings was silently
dropped the next time settings were saved. Add a serialization loop over
aloneSingleKeyReMap that appends each entry to the inProcess array tagged with
condition="alone", round-tripping with the (already condition-aware) loader.
Regular remaps still omit the field and load as "always", so existing settings
files are unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
…dition

Wire the "Alone" single-key remap condition through the WinUI3 editor so it can be
created, edited, saved and reloaded. Previously the engine understood the condition
and round-tripped it in settings, but the editor had no way to set or show it.

- Native wrapper: parallel GetSingleKeyAloneRemapCount / GetSingleKeyAloneRemap /
  AddSingleKeyAloneRemap / AddSingleKeyAloneToShortcutRemap / DeleteSingleKeyAloneRemap
  over the aloneSingleKeyReMap table (reuses the existing SingleKeyMapping struct, so
  no marshaling changes).
- C# interop/service: expose the alone add/get/delete and tag read-back mappings with
  IsAlone.
- Model: SingleKeyRemapCondition (Always/Alone) on Remapping and ShortcutKeyMapping
  (including Equals/GetHashCode); settings correlation carries it.
- UI: a Condition combo box on the mapping dialog; save/load/delete route to the alone
  table when the condition is Alone.

Localizing the combo box (x:Uid/resw) and gating its visibility to single-key remaps
are follow-ups. Engine (108) and editor (88) C++ unit test suites pass; the editor UI
project compiles.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Polish the "Condition" (Always / Alone) control added for single-key dual-key
remaps so it is production-ready:

- Localize the combo box: replace the hardcoded "Condition" / "Always" /
  "Alone (tap)" strings with x:Uid + resw entries (ConditionComboBox.Header,
  Condition_Always.Content, Condition_Alone.Content), matching the existing
  ElevationComboBox pattern.
- Gate visibility: the condition combo now shows only for a single-key remap
  whose action is a key/shortcut (the only case the engine supports "alone"),
  via UpdateConditionVisibility() driven off the trigger key count and action
  type. It starts collapsed and only toggles Visibility, so a condition set on
  load via SetCondition is preserved.
- Surface the condition in the list: add an "Alone" badge (localized
  AloneBadge.Text) to the single-key remap rows, bound to a new Remapping.IsAlone
  via BoolToVisibilityConverter, so alone remaps are distinguishable without
  opening the edit dialog.

Editor UI project compiles clean (0 warnings, 0 errors).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@niels9001

Copy link
Copy Markdown
Collaborator

takahashi (@MasaYan24) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"

Contributor License Agreement

takahashi (@MasaYan24) can you accept the policy agreement and would you mind taking a screenrecording of the new behavior?

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds “tap-alone” (Karabiner-style to_if_alone) behavior for single-key remaps in Keyboard Manager, allowing a key to trigger an alternate action when tapped by itself while still behaving normally when used in combinations.

Changes:

  • Engine: adds a separate aloneSingleKeyReMap table and a new hook handler HandleSingleKeyAloneRemapEvent that defers decision until another key is pressed or the key is released.
  • Settings + interop: adds a "condition" field (always/alone) for single-key remaps and exposes parallel get/add/delete APIs for the alone table.
  • Editor UI: adds a localized “Condition” combo box (Always / Alone) and an “Alone” badge in the remap list.

Reviewed changes

Copilot reviewed 25 out of 25 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/modules/keyboardmanager/KeyboardManagerEngineTest/TestHelpers.cpp Resets alone-remap state between tests.
src/modules/keyboardmanager/KeyboardManagerEngineTest/SingleKeyRemappingTests.cpp Adds unit tests covering basic alone key behavior.
src/modules/keyboardmanager/KeyboardManagerEngineLibrary/State.h Adds runtime tracking for pending vs combination alone keys + API surface.
src/modules/keyboardmanager/KeyboardManagerEngineLibrary/State.cpp Implements alone runtime state helpers and alone remap lookup.
src/modules/keyboardmanager/KeyboardManagerEngineLibrary/KeyboardManager.cpp Wires alone handler into the hook chain and includes alone table in “has remaps”.
src/modules/keyboardmanager/KeyboardManagerEngineLibrary/KeyboardEventHandlers.h Declares HandleSingleKeyAloneRemapEvent.
src/modules/keyboardmanager/KeyboardManagerEngineLibrary/KeyboardEventHandlers.cpp Implements alone remap hook logic (lazy key-down, release-fire).
src/modules/keyboardmanager/KeyboardManagerEditorUI/Strings/en-US/Resources.resw Adds localized strings for Condition UI and Alone badge.
src/modules/keyboardmanager/KeyboardManagerEditorUI/Settings/SettingsManager.cs Maps service-layer “IsAlone” into editor “Condition”.
src/modules/keyboardmanager/KeyboardManagerEditorUI/Pages/MainPage.xaml.cs Loads/saves remap condition and passes it into SaveMapping.
src/modules/keyboardmanager/KeyboardManagerEditorUI/Pages/MainPage.xaml Adds Alone badge to remap list UI.
src/modules/keyboardmanager/KeyboardManagerEditorUI/Interop/ShortcutKeyMapping.cs Introduces SingleKeyRemapCondition + includes it in equality/hash.
src/modules/keyboardmanager/KeyboardManagerEditorUI/Interop/KeyMapping.cs Tags service-returned mappings with IsAlone.
src/modules/keyboardmanager/KeyboardManagerEditorUI/Interop/KeyboardMappingService.cs Surfaces alone mappings and provides add/delete methods.
src/modules/keyboardmanager/KeyboardManagerEditorUI/Interop/KeyboardManagerInterop.cs Adds P/Invoke exports for alone remap APIs.
src/modules/keyboardmanager/KeyboardManagerEditorUI/Helpers/RemappingHelper.cs Saves/deletes single-key mappings using condition to choose table.
src/modules/keyboardmanager/KeyboardManagerEditorUI/Helpers/Remapping.cs Stores condition and computes IsAlone for list badge binding.
src/modules/keyboardmanager/KeyboardManagerEditorUI/Controls/UnifiedMappingControl.xaml.cs Adds condition getter/setter + visibility gating logic.
src/modules/keyboardmanager/KeyboardManagerEditorUI/Controls/UnifiedMappingControl.xaml Adds Condition combo box to the mapping UI.
src/modules/keyboardmanager/KeyboardManagerEditorLibraryWrapper/KeyboardManagerEditorLibraryWrapper.h Exposes alone remap APIs to the editor wrapper.
src/modules/keyboardmanager/KeyboardManagerEditorLibraryWrapper/KeyboardManagerEditorLibraryWrapper.cpp Implements alone remap enumeration/add/delete in wrapper.
src/modules/keyboardmanager/common/MappingConfiguration.h Adds alone remap table + APIs.
src/modules/keyboardmanager/common/MappingConfiguration.cpp Loads/saves alone condition via optional "condition" field and serializes alone table.
src/modules/keyboardmanager/common/KeyboardManagerConstants.h Adds "condition" setting constants (always/alone).
doc/devdocs/modules/keyboardmanager/keyboardeventhandlers.md Documents the new alone handler behavior and settings format.
Comment on lines +155 to +169
// Tapped alone: fire the remapped alone action as a tap (down + up).
std::vector<INPUT> keyEventList;
const auto& target = it->second;
if (target.index() == 0)
{
const DWORD targetKey = std::get<DWORD>(target);
// A disabled alone target means "tapping alone does nothing".
if (targetKey != CommonSharedConstants::VK_DISABLED)
{
Helpers::SetKeyEvent(keyEventList, INPUT_KEYBOARD, static_cast<WORD>(targetKey), 0, KeyboardManagerConstants::KEYBOARDMANAGER_SINGLEKEY_FLAG);
Helpers::SetKeyEvent(keyEventList, INPUT_KEYBOARD, static_cast<WORD>(targetKey), KEYEVENTF_KEYUP, KeyboardManagerConstants::KEYBOARDMANAGER_SINGLEKEY_FLAG);
}
}
// NOTE: Shortcut- and text-valued alone targets are a later phase (no producer yet).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch — fixed in 60e49d4. HandleSingleKeyAloneRemapEvent now injects a shortcut-valued alone target on tap as a full press-and-release (modifiers down -> action-key down -> action-key up -> modifiers up), mirroring the key-to-shortcut path in HandleSingleKeyRemapEvent. Covered by a new engine test AloneRemap_ShortcutTarget_ShouldInjectFullShortcut_OnTap.

Comment on lines +113 to +118
// Step 1: a key-down of a DIFFERENT key while alone keys are pending means those pending keys
// are now being used in combination. Flush them by injecting their original key-down as a real
// key/modifier so the in-combination behavior (e.g. Right Ctrl acting as Ctrl) works.
if (isKeyDown)
{
for (const DWORD pendingKey : state.GetPendingAloneKeys())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 60e49d4. A key pressed while another alone key is already held (pending or already in a combination) is now detected via the new State::HasOtherHeldAloneKey and promoted straight to a combination (its real key-down is injected), so it never becomes a solo-tap candidate and won't fire its alone action on release. Covered by a new engine test AloneRemap_SecondAloneKeyWhileFirstHeld_IsCombination_NotTap.

Comment on lines 7 to 10
3. [HandleShortcutRemapEvent](#HandleShortcutRemapEvent)
3. [HandleOSLevelShortcutRemapEvent](#HandleOSLevelShortcutRemapEvent)
4. [HandleAppSpecificShortcutRemapEvent](#HandleAppSpecificShortcutRemapEvent)
5. [HandleSingleKeyToggleToModEvent (Obsolete))](#HandleSingleKeyToggleToModEvent-(Obsolete---Code-from-PoC-which-is-commented-out))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 60e49d4 — renumbered the Table of Contents to be sequential (1-7).

takahashi (MasaYan24) and others added 2 commits July 7, 2026 10:32
…-key) remaps

An "alone" single-key remap holds the source key lazily (its real key-down is
only injected once a *keyboard* key is pressed in combination). Mouse events go
through a different hook, so clicking or scrolling while an alone-mapped key was
held never promoted it to a real modifier -- e.g. with "Left/Right Ctrl alone ->
IME Off/On", Ctrl+Click and Ctrl+Wheel stopped working.

Add a companion low-level mouse hook (WH_MOUSE_LL), installed alongside the
keyboard hook only while alone remaps exist (reconciled on settings reload). On a
button-down or wheel event -- but not mouse move, which must not cancel a tap --
it promotes the held alone key(s) to a real modifier via the shared
PromotePendingAloneKeysToCombination, so the click/scroll is seen in combination.
The mouse event itself is never suppressed. State::HasPendingAloneKeys gives the
hook a cheap early-out on the common path.

Engine unit tests: 110/110 (2 new mouse-promotion cases).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015VVMM2ad9wjWGYoE5cVYGJ
The editor's "Conflicting modifier" validation treated any two single-key
remaps of the same modifier FAMILY as a conflict, because GetKeyType() maps
VK_CONTROL, VK_LCONTROL and VK_RCONTROL all to KeyType::Ctrl. That wrongly
blocked mapping Left Ctrl and Right Ctrl at the same time -- which is exactly
the left/right-modifier use case (e.g. Left Ctrl -> IME Off, Right Ctrl ->
IME On, the Windows equivalent of macOS left/right Command -> 英数/かな).

The real ambiguity is only between the generic, side-agnostic modifier (Ctrl,
which matches either physical side at the hook level) and a specific side. Two
distinct specific sides (Left Ctrl vs Right Ctrl) are separate physical keys
and can coexist. Restrict the conflict to cases where one side is a generic
modifier (VK_SHIFT/VK_CONTROL/VK_MENU/VK_WIN_BOTH).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015VVMM2ad9wjWGYoE5cVYGJ
@MuyuanMS

Copy link
Copy Markdown
Contributor

/needinfo

@microsoft-github-policy-service microsoft-github-policy-service Bot added the Needs-Author-Feedback The original author of the issue/PR needs to come back and respond to something label Jul 9, 2026
takahashi (MasaYan24) and others added 2 commits July 10, 2026 05:47
The engine's mapping tables are keyed by the source key and silently reject a
duplicate original key, but the editor's own settings store (editorSettings.json)
had no such guard. Re-adding a mapping that already existed -- e.g. saving the
same "alone" remap twice, or mixing direct default.json edits with GUI edits --
appended a second copy, so the same Left/Right Ctrl -> IME entry appeared twice
in the remap list even though the engine only held one.

- Guard AddShortcutKeyMappingToSettings with a duplicate check.
- Compare the full mapping value (ShortcutKeyMapping.Equals, which includes the
  single-key Condition and TargetApp) so an "always" and an "alone" remap of the
  same key stay distinct while genuine duplicates are caught.
- Make IsMappingActiveInService condition-aware so alone/always variants match
  the right engine entry.
- Self-heal stores that already drifted: RemoveDuplicateMappings runs on load
  (CorrelateServiceAndEditorMappings) and drops exact-duplicate entries.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015VVMM2ad9wjWGYoE5cVYGJ
…ne chords, doc ToC

Follow-up to the Copilot review on the alone (dual-key) remap feature:

- Alone target = shortcut: HandleSingleKeyAloneRemapEvent only injected single-key
  (index 0) alone targets on tap, so an alone remap whose target is a shortcut (which
  the editor UI and wrapper DO produce, via AddSingleKeyAloneToShortcutRemap) suppressed
  the source key but injected nothing. Now a shortcut-valued target fires as a full
  press-and-release, mirroring the key-to-shortcut path in HandleSingleKeyRemapEvent.

- Two alone keys chorded: pressing a second alone-mapped key while a first was still held
  made the second a solo-tap candidate, so it wrongly fired its alone action on release.
  New State::HasOtherHeldAloneKey lets the handler treat a key pressed while another alone
  key is held as a combination (promote to a real key, never fire the alone action).

- Devdoc: fix the duplicated "3." Table-of-Contents numbering and document both behaviors.

Engine unit tests: 112/112 (2 new: shortcut-target tap, two-alone-key chord).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015VVMM2ad9wjWGYoE5cVYGJ
@microsoft-github-policy-service microsoft-github-policy-service Bot added Needs-Triage For issues raised to be triaged and prioritized by internal Microsoft teams and removed Needs-Author-Feedback The original author of the issue/PR needs to come back and respond to something labels Jul 9, 2026

@MuyuanMS Muyuan Li (MuyuanMS) left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Process / context

  • CLA: the license/cla check is still pending — it needs to be accepted by the PR author. Since the demo was shared from a different account, just confirming you're the author here: could you comment @microsoft-github-policy-service agree so we can proceed? (Merge is blocked until then.)
  • check-spelling is failing — see inline suggestions for pre-existing → preexisting and , otherwise → ; otherwise. The test locals rctrl / lctrl in SingleKeyRemappingTests.cpp (lines ~612–636, ~811–828) are also flagged — please add them to the check-spelling expect/allow list or rename them.

Code findings (design-level — left to your judgment)

1. Condition lost when an Alone mapping is toggled off/on — medium
The reactivation path (MainPage.xaml.cs ~L802) calls SaveMapping(..., false) without passing remapping.Condition, so RemappingHelper.SaveMapping recreates the entry in the regular single-key table as unconditional. Making the condition parameter required (so the compiler forces every caller to supply it) or passing remapping.Condition from every reactivation caller would prevent silent loss of the Alone behavior.

2. Engine state not reconciled on settings reload — medium
MappingConfiguration reload clears the alone remap table but not State::alonePendingKeys / aloneCombinationKeys. If settings reload while an alone key is physically held, a stale pending key can later be promoted by the mouse hook, injecting an original key-down with no matching key-up. Consider reconciling/clearing that runtime state on reload.

4. Disabled-item edit/re-enable drops the condition — low
The disabled-mapping edit/re-enable paths (MainPage.xaml.cs ~L925) always call AddSingleKeyMapping and don't preserve Condition, so editing a hand-loaded condition: "alone" disabled mapping rewrites it as Always. Routing these through the condition-aware add path would fix it.

5. Test coverage for the new condition field — low
LoadingAndSavingRemappingTests weren't extended for the new field. Adding cases for (a) a missing condition loading as Always and (b) key/shortcut Alone mappings surviving save→reload would also guard against the two tables drifting.

Thanks again for the thorough work and validation!

Comment on lines +188 to +193
const DWORD targetKey = std::get<DWORD>(target);
// A disabled alone target means "tapping alone does nothing".
if (targetKey != CommonSharedConstants::VK_DISABLED)
{
Helpers::SetKeyEvent(keyEventList, INPUT_KEYBOARD, static_cast<WORD>(targetKey), 0, KeyboardManagerConstants::KEYBOARDMANAGER_SINGLEKEY_FLAG);
Helpers::SetKeyEvent(keyEventList, INPUT_KEYBOARD, static_cast<WORD>(targetKey), KEYEVENTF_KEYUP, KeyboardManagerConstants::KEYBOARDMANAGER_SINGLEKEY_FLAG);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filter artificial key codes for "alone" tap targets

Severity: high

When an "alone" mapping targets Win (Both) (VK_WIN_BOTH, 0x104), the tap path injects that artificial KBM key code directly, so SendInput receives the invalid virtual key 0x104 and the tap silently does nothing. The single-key remap path already guards against this via Helpers::FilterArtificialKeys — mirroring it here maps VK_WIN_BOTH -> VK_LWIN before injection.

Suggested change
const DWORD targetKey = std::get<DWORD>(target);
// A disabled alone target means "tapping alone does nothing".
if (targetKey != CommonSharedConstants::VK_DISABLED)
{
Helpers::SetKeyEvent(keyEventList, INPUT_KEYBOARD, static_cast<WORD>(targetKey), 0, KeyboardManagerConstants::KEYBOARDMANAGER_SINGLEKEY_FLAG);
Helpers::SetKeyEvent(keyEventList, INPUT_KEYBOARD, static_cast<WORD>(targetKey), KEYEVENTF_KEYUP, KeyboardManagerConstants::KEYBOARDMANAGER_SINGLEKEY_FLAG);
const DWORD targetKey = std::get<DWORD>(target);
// A disabled alone target means "tapping alone does nothing".
if (targetKey != CommonSharedConstants::VK_DISABLED)
{
// Filter artificial KBM key codes (e.g. VK_WIN_BOTH -> VK_LWIN) before
// injecting, mirroring HandleSingleKeyRemapEvent; otherwise a "Win (Both)"
// alone target would inject the invalid virtual key 0x104.
const DWORD filteredTargetKey = Helpers::FilterArtificialKeys(targetKey);
Helpers::SetKeyEvent(keyEventList, INPUT_KEYBOARD, static_cast<WORD>(filteredTargetKey), 0, KeyboardManagerConstants::KEYBOARDMANAGER_SINGLEKEY_FLAG);
Helpers::SetKeyEvent(keyEventList, INPUT_KEYBOARD, static_cast<WORD>(filteredTargetKey), KEYEVENTF_KEYUP, KeyboardManagerConstants::KEYBOARDMANAGER_SINGLEKEY_FLAG);
}

bool shortcutSettingsChanged = false;
// Repair any pre-existing duplicate entries first so the store converges on load.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Spelling: pre-existing -> preexisting

Severity: low

check-spelling flags pre-existing as a forbidden pattern (CI is currently red on this).

Suggested change
// Repair any pre-existing duplicate entries first so the store converges on load.
// Repair any preexisting duplicate entries first so the store converges on load.
// If remapped to a shortcut
if (std::wstring(newRemapKey).find(L";") != std::string::npos)
// Optional dual-key condition. Missing field defaults to "always" (legacy behavior),
// so pre-existing settings files load unchanged. "alone" routes to the alone table.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Spelling: pre-existing -> preexisting

Severity: low

check-spelling flags pre-existing as a forbidden pattern.

Suggested change
// so pre-existing settings files load unchanged. "alone" routes to the alone table.
// so preexisting settings files load unchanged. "alone" routes to the alone table.
auto condition = it.GetObjectW().GetNamedString(KeyboardManagerConstants::RemapConditionSettingName, KeyboardManagerConstants::RemapConditionAlways);
const bool isAloneCondition = (std::wstring(condition) == KeyboardManagerConstants::RemapConditionAlone);

// Parse the target: a ';'-separated value is a shortcut, otherwise a single key.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment grammar: , otherwise -> ; otherwise

Severity: low

A comma splice joins two independent clauses here; a semicolon reads correctly.

Suggested change
// Parse the target: a ';'-separated value is a shortcut, otherwise a single key.
// Parse the target: a ';'-separated value is a shortcut; otherwise a single key.
…preserve condition, reset alone state on reload

Follow-up to the review on the alone (dual-key) remap PR:

- Alone tap target = "Win (Both)" (VK_WIN_BOTH, 0x104) was injected as-is, so SendInput
  received the artificial key code and the tap silently did nothing. HandleSingleKeyAloneRemapEvent
  now runs targets through Helpers::FilterArtificialKeys (VK_WIN_BOTH -> VK_LWIN) on both the
  single-key and shortcut-action-key paths, mirroring HandleSingleKeyRemapEvent.

- Toggling an alone mapping off then on recreated it as an unconditional (Always) remap, silently
  dropping the "alone" behavior. EnableShortcut / EnableDisabledMapping now pass the mapping's
  Condition so it re-registers in the alone table.

- A settings reload rebuilt the alone remap table but left State's alonePendingKeys /
  aloneCombinationKeys, so a key held across a reload could later be promoted with a stale entry
  (injecting an unmatched original key-down). New State::ClearAllAloneKeyState is called after each
  reload.

- check-spelling (CI was red): "pre-existing" -> "preexisting", a comma splice -> semicolon, and the
  test locals rctrl/lctrl added to the expect list.

Engine unit tests: 113/113 (new: alone tap to Win(Both) injects Left Win, not 0x104).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EJG9NHHEkEgFmp9W7djrnt
@MasaYan24

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, Muyuan Li (@MuyuanMS)!

On the process points: yes, I'm the author of this PR — the demo video earlier was posted from my other account by mistake, sorry for the confusion. On the CLA, I still need to confirm on my side whether the individual or corporate CLA is the right one to use for this contribution; I'll sign from this account (takahashi (@MasaYan24)) once that's settled. The code is ready for review in the meantime.

Addressed the findings:

  • Artificial key filter (high): the alone tap path now runs targets through Helpers::FilterArtificialKeys (VK_WIN_BOTH → VK_LWIN) on both the single-key and shortcut-action-key paths, mirroring HandleSingleKeyRemapEvent. Added an engine test (AloneRemap_WinBothTarget_ShouldInjectLeftWin_OnTap).
  • check-spelling: pre-existing → preexisting, the comma splice → ;, and rctrl/lctrl added to the expect list, so CI should be green now.
  • Pushing the first main update to master #1 condition lost when toggled off/on: re-enabling now passes the mapping's Condition, so an "alone" remap is recreated in the alone table instead of as an unconditional one.
  • fix a couple typos #2 engine state not reconciled on reload: added State::ClearAllAloneKeyState(), called after each settings reload, so a key held across a reload can't leave a stale pending/combination entry that a later event would promote.
  • Full window manager including specific layouts for docking and undocking laptops #4 disabled + alone re-enable: the re-enable path now routes through the alone table when the condition is "alone".
  • Full window manager, including layouts #5 (test coverage for the condition field): deferring this one for now — the condition round-trip isn't cleanly unit-testable without exposing the private JSON loader or writing to real settings files, and the alone-table routing is already exercised end-to-end. Happy to add it if you'd prefer.

Engine unit tests: 113/113.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
@MasaYan24

Copy link
Copy Markdown
Contributor Author

Thanks Niels Laute (@niels9001) for kicking off /azp run — the full Azure Pipelines build is now green on the current head (896aed8): the x64 and arm64 Release builds plus the Command Palette SDK build all pass, alongside the CLA/label/telemetry checks. All of Muyuan Li (@MuyuanMS)'s review feedback has been addressed (the edit-mode conflict item was split out to #49710 with his sign-off), so I think this is ready to merge whenever you're happy with it. Thanks again to you both for the reviews!

@MasaYan24

Copy link
Copy Markdown
Contributor Author

Thank you so much Muyuan Li (@MuyuanMS) for the approval, and for the thorough reviews across all the iterations — I really appreciate the time you put into this. 🙏

The KBM editor persistence layer was refactored on main after this PR was
approved (SettingsManager transaction/reconcile model, MainPage
Save/DeleteMappingTransaction, removal of RemappingHelper.SaveMapping/
DeleteRemapping). This merge re-ports the "Alone (tap)" single-key condition
onto the new architecture; engine behavior is unchanged.

Conflicts resolved (5 files):
- common/MappingConfiguration.h: kept our public LoadSingleKeyRemaps (for unit
  tests) and upstream's private configurationNameResolved member.
- Interop/KeyboardManagerInterop.cs: kept our alone P/Invokes; adopted upstream's
  UnmanagedType.I1 marshalling (correct for the native bool return).
- Helpers/RemappingHelper.cs: took upstream (SaveMapping/DeleteRemapping are gone;
  routing moved into MainPage's transaction helpers).
- Settings/SettingsManager.cs: thread Condition through both single-key load loops
  (from KeyMapping.IsAlone) and add Condition to HasSameTriggerAndScope so an
  Alone remap is not collapsed with its Always counterpart during reconcile.
- Pages/MainPage.xaml.cs: CreateShortcutKeyMapping sets Condition from the UI;
  AddMapping/DeleteMapping route single-key Alone to the separate native table;
  HasDuplicateEditorMapping gains a Condition discriminator; LoadRemappings and
  both edit-dialog paths round-trip the condition.

The model/service/interop/UI layers (ShortcutKeyMapping.Condition incl.
Equals/GetHashCode, KeyMapping.IsAlone, Remapping.Condition, the alone service
methods, the UI toggle) merged cleanly. Editor project compiles (0 errors);
full build + on-device round-trip verification to follow.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EJG9NHHEkEgFmp9W7djrnt
@MasaYan24

Copy link
Copy Markdown
Contributor Author

Heads-up: I've rebased this PR onto the latest main.

Since the approval, the Keyboard Manager editor's persistence layer was refactored upstream (the SettingsManager transaction/reconcile model, MainPage.SaveMappingTransaction/DeleteMappingTransaction, and the removal of RemappingHelper.SaveMapping/DeleteRemapping). That left this branch conflicting, so I re-ported the dual-key "Alone (tap)" feature onto the new architecture rather than force-fitting the old code.

What changed in the rebase (feature behavior is unchanged — Karabiner-style to_if_alone):

  • The per-entry SingleKeyRemapCondition (Always / Alone) now rides on ShortcutKeyMapping.Condition (already in Equals/GetHashCode).
  • Save/delete routing to the separate "alone" native table moved into the new MainPage.AddMapping/DeleteMapping transaction helpers (replacing the deleted RemappingHelper methods).
  • Load/reconcile: SettingsManager.CreateSettingsFromKeyboardManagerService and CorrelateServiceAndEditorMappings set Condition from the service's IsAlone flag.
  • Dedup safety: Condition was added to HasSameTriggerAndScope and HasDuplicateEditorMapping so an Alone remap and its Always counterpart on the same key are treated as distinct instead of being collapsed by reconcile/normalize.
  • The engine side (separate aloneSingleKeyReMap table, HandleSingleKeyAloneRemapEvent, JSON condition round-trip) is unchanged from the approved version.

The diff is materially the same feature on a new substrate, so a re-review of the editor-integration points above would be appreciated. CI is green and I re-verified the alone save/load/delete/edit round-trip on hardware. Thanks again Muyuan Li (@MuyuanMS) for the earlier reviews.

@github-actions github-actions Bot added the Needs-Author-Feedback The original author of the issue/PR needs to come back and respond to something label Aug 23, 2026
@github-actions

github-actions Bot commented Aug 23, 2026 •

Copy link
Copy Markdown

✅ PR intake

All automated intake checks now pass. Thanks for the updates!

Automated PR intake; PowerToys maintainers make final decisions.

@microsoft-github-policy-service microsoft-github-policy-service Bot added Needs-Team-Response An issue author responded so the team needs to follow up and removed Needs-Author-Feedback The original author of the issue/PR needs to come back and respond to something labels Aug 23, 2026
@MasaYan24

Copy link
Copy Markdown
Contributor Author

Friendly ping 🙂

This PR was rebased onto the latest main on Aug 24, and all automated intake checks pass (the demo recording is in the description). Since the earlier approval was auto-dismissed by the rebase, it's now back to REVIEW_REQUIRED.

Whenever you have a moment, Muyuan Li (@MuyuanMS), could you take another look? Happy to address anything that comes up. Thanks so much! 🙏

@MuyuanMS

Copy link
Copy Markdown
Contributor

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
@MuyuanMS
Muyuan Li (MuyuanMS) enabled auto-merge (squash) August 31, 2026 09:39
@MuyuanMS
Muyuan Li (MuyuanMS) merged commit 7c28d30 into microsoft:main Aug 31, 2026
9 of 13 checks passed
Muyuan Li (MuyuanMS) pushed a commit that referenced this pull request Sep 3, 2026
… edit mode (#50265)

<!-- Title: [Keyboard Manager] Editor: identity-based duplicate/conflict
check in edit mode -->

## Summary of the Pull Request

Adds a duplicate / conflict detection pass to the Keyboard Manager
**editor's edit mode**, keyed on the *identity* of each mapping (its
trigger key(s) **and** its condition) rather than on the row's position
in the list. This catches two classes of user error before the profile
is saved:

- **Duplicates** — the same trigger with the same condition mapped
twice.
- **Conflicts** — the same trigger competing across entries in a way the
engine cannot honour deterministically.

Resolves #49710.

This was split out of #49136 at the reviewer's request so that the
dual-key "alone" remap PR could stay focused; the identity-based check
is the follow-up tracked by #49710. #49136 is now merged, so this
rebases cleanly onto `main` as a single self-contained commit.

## PR Checklist

- [x] Closes: #49710
- [x] Communication: I've discussed this with the team via #49136 /
#49710
- [x] Tests: ran the existing KBM editor unit tests (no new tests — this
changes an
internal validation signature and its call sites; behaviour is covered
by the
manual matrix below). Happy to add unit tests if you'd like them here.
- [x] Localization: no new user-facing strings (reuses the existing
validation messages)
- [x] No regression: existing remap add/edit/save round-trip verified

## Detailed Description of the Pull Request / Additional comments

The editor previously deduped by list index, which meant two entries
with the
same trigger but different *conditions* (e.g. `Always` vs `Alone (tap)`)
could be
mis-flagged, and genuine duplicates introduced by edit could slip
through. The
check now composes a stable identity from **(trigger keys, condition)**
and
compares on that, so:

- editing an entry to collide with an existing one is reported at edit
time;
- a mapping and its `Alone (tap)` sibling are correctly treated as
distinct.

The change is editor-only; the remap engine is untouched.

## Validation Steps Performed

- Built the KBM editor and ran its unit tests (green).
- Manually: created a duplicate trigger via edit → flagged; created an
`Always` + `Alone (tap)` pair on the same key → allowed (not a
duplicate);
  saved and reloaded a full profile → no loss, no false conflict.

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Needs-Team-Response An issue author responded so the team needs to follow up Needs-Triage For issues raised to be triaged and prioritized by internal Microsoft teams Product-Keyboard Manager Ready for review

5 participants