Repository navigation
[Keyboard Manager] Add "alone" (tap) condition for single-key remaps (dual-key / to_if_alone) - #49136
Conversation
…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>
takahashi (@MasaYan24) can you accept the policy agreement and would you mind taking a screenrecording of the new behavior? |
There was a problem hiding this comment.
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
aloneSingleKeyReMaptable and a new hook handlerHandleSingleKeyAloneRemapEventthat 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. |
| // 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). | ||
|
|
There was a problem hiding this comment.
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.
| // 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()) |
There was a problem hiding this comment.
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.
| 3. [HandleShortcutRemapEvent](#HandleShortcutRemapEvent) | ||
| 3. [HandleOSLevelShortcutRemapEvent](#HandleOSLevelShortcutRemapEvent) | ||
| 4. [HandleAppSpecificShortcutRemapEvent](#HandleAppSpecificShortcutRemapEvent) | ||
| 5. [HandleSingleKeyToggleToModEvent (Obsolete))](#HandleSingleKeyToggleToModEvent-(Obsolete---Code-from-PoC-which-is-commented-out)) |
There was a problem hiding this comment.
Fixed in 60e49d4 — renumbered the Table of Contents to be sequential (1-7).
…-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
|
/needinfo |
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
There was a problem hiding this comment.
Process / context
- CLA: the
license/clacheck 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 agreeso we can proceed? (Merge is blocked until then.) - check-spelling is failing — see inline suggestions for
pre-existing→preexistingand, otherwise→; otherwise. The test localsrctrl/lctrlinSingleKeyRemappingTests.cpp(lines ~612–636, ~811–828) are also flagged — please add them to the check-spellingexpect/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!
| 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); |
There was a problem hiding this comment.
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.
| 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. |
There was a problem hiding this comment.
Spelling: pre-existing -> preexisting
Severity: low
check-spelling flags pre-existing as a forbidden pattern (CI is currently red on this).
| // 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. |
There was a problem hiding this comment.
Spelling: pre-existing -> preexisting
Severity: low
check-spelling flags pre-existing as a forbidden pattern.
| // 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. |
There was a problem hiding this comment.
Comment grammar: , otherwise -> ; otherwise
Severity: low
A comma splice joins two independent clauses here; a semicolon reads correctly.
| // 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
|
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:
Engine unit tests: 113/113. |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
|
Thanks Niels Laute (@niels9001) for kicking off |
|
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
|
Heads-up: I've rebased this PR onto the latest Since the approval, the Keyboard Manager editor's persistence layer was refactored upstream (the What changed in the rebase (feature behavior is unchanged — Karabiner-style
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. |
✅ PR intakeAll automated intake checks now pass. Thanks for the updates! Automated PR intake; PowerToys maintainers make final decisions. |
|
Friendly ping 🙂 This PR was rebased onto the latest Whenever you have a moment, Muyuan Li (@MuyuanMS), could you take another look? Happy to address anything that comes up. Thanks so much! 🙏 |
|
/azp run |
|
Azure Pipelines: Successfully started running 1 pipeline(s). |
… 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>
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 actionwhen 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:
PR Checklist
to_if_alonetracking issue; Keyboard Manager: Add support for single-key press detection, IME switching, and flexible remapping with modifier combinations #40647 was closed as a duplicate of it)Detailed Description of the Pull Request / Additional comments
Engine (C++):
aloneSingleKeyReMap(parallel tosingleKeyReMap) withAdd/Clear/GetSingleKeyAloneRemap(MappingConfiguration).HandleSingleKeyAloneRemapEventusing 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.WH_MOUSE_LL) is installed alongsidethe 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::HasPendingAloneKeysgives the hook a cheap early-out."condition"field per single-key remap ("always"default, or"alone"). Fully backward compatible; both load and save handle it, so hand-edited orUI-created alone remaps round-trip without loss.
Editor UI (WinUI3):
SingleKeyMappingmarshaling struct).SingleKeyRemapCondition(Always / Alone) flows through the C# interop/service/model layers.remap whose action is a key/shortcut (the case the engine supports), plus a localized
"Alone" badge on such rows in the list.
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.
(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):
needs an injectable clock — deferred, noted in code).
Validation Steps Performed
Editor C++ tests: 88/88.
pass-through OK).
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.