Skip to content

Commit

Permalink
Refactor/fix handling of special keys in integrations
Browse files Browse the repository at this point in the history
Evaluating `globalKeyboardShortcut(_:)` revealed several issues
with related to special keys:

- Shortcuts using the `Key.space` would produce a `KeyEquivalent`
  that specified the "S" key.
  (cause: `first` being used on the `keyToCharacter()` return
  value, `"space"`)
- Shortcuts using `Key.f*` would produce a `KeyEquivalent` that
  Specified the "F" key.
  (cause: same as above)
- Shortcuts using `Key.keypad*` would produce a `KeyEquivalent`
  that was not limited to the number pad.
  (cause: neither SwiftUI nor AppKit make this distinction when
  producing menu items)

Considering these issues, a reevaluation of special keys' handling
is called for. Excepting the `Carbon` integration that drives the
actual keyboard shortcuts, there are three distinct contexts where
a `Shortcut` is used:

- `Recoder`: where an `NSString` is produced to go into the
  `TextField` displaying the shortcut's current value
- `NSMenuItem`: for specifying `keyEquivalent` and
  `keyEquivalentModifierMask`
- `toSwiftUI`: for creating a `SwiftUI.KeyboardShortcut`

Ideally, each of these three do their work in analogous ways. This
branch accomplishes this with the following:

- `SpecialKey` enumerates the cases that require extra attention.
  This is drawn directly from keys used in `keyToCharacterMapping`
  and used to ensure that each special case is handled.
- Three mappings for `SpecialKey` are created for each of the three
  contexts where the handling is important:
  `presentableDescription`, `swiftUIKeyEquivalent`, and
  `appKitMenuItemKeyEquivalent`.
- In these three contexts if there is a `SpecialKey`, the defined
  mapping is what rules. `keyToCharacter()` is used if and only if
  there is no `SpecialKey` available. An assertion to this effect
  is added.

Fixes: #192
  • Loading branch information
cweider committed Nov 30, 2024
1 parent c3c361f commit 4bdbf5c
Show file tree
Hide file tree
Showing 2 changed files with 501 additions and 120 deletions.
2 changes: 1 addition & 1 deletion Sources/KeyboardShortcuts/NSMenuItem++.swift
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ extension NSMenuItem {
return
}

keyEquivalent = shortcut.keyEquivalent
keyEquivalent = shortcut.keyEquivalent ?? ""
keyEquivalentModifierMask = shortcut.modifiers

if #available(macOS 12, *) {
Expand Down
Loading

0 comments on commit 4bdbf5c

Please sign in to comment.