Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Shortcuts follow the keyboard layout: Turkish Q's ⌘- zooms out, ⌘* does nothing (#212)

Victor370ca1a89cfe
diff --git a/Packages/CraCore/Sources/CraCore/KeyChord.swift b/Packages/CraCore/Sources/CraCore/KeyChord.swift
index 7357079..4fcb92a 100644
--- a/Packages/CraCore/Sources/CraCore/KeyChord.swift
+++ b/Packages/CraCore/Sources/CraCore/KeyChord.swift
@@ -29,6 +29,72 @@ public struct KeyChord: Codable, Hashable {
[36, 76].contains(keyCode) && Modifiers(rawValue: modifiers).intersection([.shift, .control, .option, .command]) == .command
}
+ // MARK: Matching a key press
+
+ /// What a key press gives to match against: AppKit's charactersIgnoringModifiers, the
+ /// key's virtual key code and its device-independent modifier bits.
+ public struct Press: Hashable {
+ public var characters: String
+ public var keyCode: UInt16
+ public var modifiers: UInt
+
+ public init(characters: String, keyCode: UInt16, modifiers: UInt) {
+ self.characters = characters
+ self.keyCode = keyCode
+ self.modifiers = modifiers
+ }
+
+ /// The key as a chord stores it: lowercase, with Shift's character turned back into
+ /// the key's own ("{" is "["), Shift-Tab's backtab as Tab and the Delete key's U+007F
+ /// as `delete`.
+ public var key: String {
+ let lower = characters.lowercased()
+ return KeyChord.unshift[lower] ?? lower
+ }
+ }
+
+ static let unshift: [String: String] = [
+ "\u{19}": tab, "\u{7F}": delete, "{": "[", "}": "]", "<": ",", ">": ".", "?": "/", "+": "=", "_": "-",
+ "~": "`", ":": ";", "\"": "'", "|": "\\",
+ ]
+
+ /// Where each punctuation key sits on an ANSI keyboard (virtual key codes). On layouts that
+ /// can't type the character without ⌥ (Danish and German "[" is ⌥8) the shortcut takes the
+ /// key in that place instead, as Arc and Chrome do for ⌘[ and ⌘].
+ static let ansiKeyCode: [String: UInt16] = [
+ "[": 33, "]": 30, "=": 24, "-": 27, ",": 43, ".": 47, "/": 44, ";": 41, "'": 39, "`": 50, "\\": 42,
+ ]
+
+ /// How a press matches this chord: by the character it types, or by the key's place when
+ /// the layout can't type the chord's character (`typable` says what the layout types
+ /// without ⌥, on its own or with Shift). Nil when it doesn't match. Caps Lock and the
+ /// function-key bit don't count.
+ public func match(_ press: Press, typable: (String) -> Bool) -> Match? {
+ let four: Modifiers = [.shift, .control, .option, .command]
+ guard Modifiers(rawValue: press.modifiers).intersection(four) == keys.intersection(four),
+ !press.characters.isEmpty else { return nil }
+ if press.key == key { return .character }
+ // Turkish Q types "-" on the ANSI "=" key, and "=" itself as ⇧0: matching "=" by place
+ // turned ⌘- into Zoom In (GitHub #212).
+ if let code = Self.ansiKeyCode[key], press.keyCode == code, !typable(key) { return .position }
+ return nil
+ }
+
+ public enum Match: Comparable { case character, position }
+
+ /// The first entry with a chord the press types; failing that, the first one a key matches
+ /// by place. A character match anywhere wins over a place match earlier in the list.
+ public static func first<T>(in entries: [T], chords: (T) -> [KeyChord], press: Press,
+ typable: (String) -> Bool) -> T? {
+ var byPlace: T?
+ for entry in entries {
+ let matches = chords(entry).compactMap { $0.match(press, typable: typable) }
+ if matches.contains(.character) { return entry }
+ if byPlace == nil, !matches.isEmpty { byPlace = entry }
+ }
+ return byPlace
+ }
+
public static let tab = "\t"
// AppKit's function-key characters (NSLeftArrowFunctionKey...).
public static let left = "\u{F702}"
diff --git a/Packages/CraCore/Tests/CraCoreTests/KeyChordTests.swift b/Packages/CraCore/Tests/CraCoreTests/KeyChordTests.swift
index 92b68f6..48c67b9 100644
--- a/Packages/CraCore/Tests/CraCoreTests/KeyChordTests.swift
+++ b/Packages/CraCore/Tests/CraCoreTests/KeyChordTests.swift
@@ -58,4 +58,70 @@ struct KeyChordTests {
func commandReturn(keyCode: UInt16, modifiers: UInt, matches: Bool) {
#expect(KeyChord.isCommandReturn(keyCode: keyCode, modifiers: modifiers) == matches)
}
+
+ // MARK: Key presses
+
+ static let shift = KeyChord.Modifiers.shift.rawValue
+ /// Cra's View menu, in the order the registry lists it.
+ static let zoom: [(id: String, chords: [KeyChord])] = [
+ ("resetZoom", [KeyChord(key: "0", modifiers: command)]),
+ ("zoomIn", [KeyChord(key: "=", modifiers: command), KeyChord(key: "=", modifiers: command | shift)]),
+ ("zoomOut", [KeyChord(key: "-", modifiers: command)]),
+ ("back", [KeyChord(key: "[", modifiers: command)]),
+ ]
+ /// What Turkish-QWERTY-PC types without ⌥ (UCKeyTranslate, macOS 26): "=" is ⇧0, "-" sits
+ /// on the ANSI "=" key, "*" on the ANSI "-" key, "[" and "]" need ⌥.
+ static let turkishQ: Set<String> = Set("1234567890*-qwertyuıopğüasdfghjklşi,zxcvbnmöç.\"!'^+%&/()=?_é<>;:".map(String.init))
+ /// Danish: "+" on the ANSI "-" key, "-" on the ANSI "/" key, "[" is ⌥8.
+ static let danish: Set<String> = Set("1234567890+´qwertyuiopå¨asdfghjklæø'zxcvbnm,.-<>!\"#€%&/()=?`^*;:_".map(String.init))
+
+ static func pressed(_ chars: String, _ code: UInt16, _ mods: UInt, on layout: Set<String>) -> String? {
+ KeyChord.first(in: zoom, chords: \.chords, press: .init(characters: chars, keyCode: code, modifiers: mods),
+ typable: { layout.contains($0) })?.id
+ }
+
+ /// Turkish Q: each zoom key does what the View menu says, and no other key zooms (GitHub #212).
+ @Test(.bug("https://github.com/VictorKildahl/cra/issues/212"), arguments: [
+ ("-", UInt16(24), command, "zoomOut"), // ⌘- (the ANSI "=" key) zooms out, not in
+ ("*", 27, command, nil), // ⌘* (the ANSI "-" key) does nothing
+ ("=", 29, command | shift, "zoomIn"), // ⌘= is ⌘⇧0
+ ("0", 29, command, "resetZoom"), // ⌘0
+ ("ğ", 33, command, "back"), // "[" needs ⌥: ⌘[ takes the key in its place
+ ] as [(String, UInt16, UInt, String?)])
+ func turkishQZoomKeys(chars: String, code: UInt16, mods: UInt, action: String?) {
+ #expect(Self.pressed(chars, code, mods, on: Self.turkishQ) == action)
+ }
+
+ /// US and Danish keep working: "+" is "=" with Shift, Danish ⌘[ is the key right of P.
+ @Test(arguments: [
+ ("=", UInt16(24), command, "zoomIn"),
+ ("+", 24, command | shift, "zoomIn"),
+ ("-", 27, command, "zoomOut"),
+ ("[", 33, command, "back"),
+ ] as [(String, UInt16, UInt, String?)])
+ func usKeys(chars: String, code: UInt16, mods: UInt, action: String?) {
+ let us = Set("1234567890-=qwertyuiop[]asdfghjkl;'\\`zxcvbnm,./!@#$%^&*()_+{}:\"|~<>?".map(String.init))
+ #expect(Self.pressed(chars, code, mods, on: us) == action)
+ }
+
+ @Test(arguments: [
+ ("+", UInt16(27), command, "zoomIn"), // ⌘+ ("+" is "=" with Shift, by character)
+ ("-", 44, command, "zoomOut"), // ⌘- where Danish has it
+ ("å", 33, command, "back"), // ⌘[ by place
+ ("´", 24, command, nil), // the ANSI "=" key types "´": "=" is ⇧0 here
+ ] as [(String, UInt16, UInt, String?)])
+ func danishKeys(chars: String, code: UInt16, mods: UInt, action: String?) {
+ #expect(Self.pressed(chars, code, mods, on: Self.danish) == action)
+ }
+
+ @Test func modifiersMustMatchExactlyButCapsLockDoesNotCount() {
+ let chord = KeyChord(key: "=", modifiers: Self.command)
+ let any: (String) -> Bool = { _ in true }
+ #expect(chord.match(.init(characters: "=", keyCode: 24, modifiers: Self.command | 0x10000), typable: any) == .character)
+ #expect(chord.match(.init(characters: "=", keyCode: 24, modifiers: Self.command | Self.shift), typable: any) == nil)
+ #expect(chord.match(.init(characters: "", keyCode: 24, modifiers: Self.command), typable: any) == nil)
+ #expect(KeyChord.Press(characters: "{", keyCode: 33, modifiers: 0).key == "[")
+ #expect(KeyChord.Press(characters: "\u{19}", keyCode: 48, modifiers: 0).key == KeyChord.tab)
+ #expect(KeyChord.Press(characters: "T", keyCode: 17, modifiers: 0).key == "t")
+ }
}
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index 21a115c..531112c 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -678,6 +678,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
return
}
if let st = dict["status"] { main.browserManager(statusMessage: st); return }
+ // key=<characters>,<key code>,<modifier bits>: a key press as a layout reports it
+ // (Turkish Q's ⌘- is "-",24,1048576), through the app's event queue (#212); the
+ // characters are percent-encoded. zoomLevel logs the page's zoom.
+ if let k = dict["key"]?.split(separator: ",", omittingEmptySubsequences: false), k.count == 3,
+ let code = UInt16(k[1]), let mods = UInt(k[2]), let w = main.window {
+ TestGesture.key(String(k[0]), keyCode: code, modifiers: NSEvent.ModifierFlags(rawValue: mods), in: w)
+ return
+ }
+ if dict["zoomLevel"] != nil {
+ let keys = main.window?.firstResponder.map { NSStringFromClass(type(of: $0)) } ?? "nothing"
+ CraLog.note("zoom level \(main.currentBrowser?.zoomLevel() ?? .nan), keys go to \(keys)")
+ return
+ }
// tidy: the divider's Tidy on the window's space, without hovering it; undoTidy: ⌘Z's.
if dict["tidy"] != nil { TidyTabsService.shared.tidy(store.focusedSpace(window: main.windowID).id, store: store); return }
if dict["undoTidy"] != nil { _ = store.undoTidy(); return }
@@ -1035,16 +1048,19 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
/// returning false lets CEF pass the key on to the menu bar (⌘Q, ⌘H…).
func handleUnhandledKey(_ event: NSEvent) -> Bool {
if undoClosedTab(event) { return true }
- if let action = bindings.action(for: event) {
- perform(action.id)
- return true
- }
// Chromium hands a ⌘-key the page left alone back to the menu bar through its own
// window's command dispatcher (⌘C, ⌘V, ⌘A, ⌘Z exist only as Edit menu items). An
- // embedded page sits in Cra's window, which has none: the key was dropped.
+ // embedded page sits in Cra's window, which has none, so it goes to the menu bar here,
+ // first: the menu runs the keys it shows, which AppKit fits to the keyboard layout
+ // (Turkish Q: Zoom In ⌘., Stop ⌘ç, Back ⌘ğ), the way the sidebar's keys go (GitHub #212).
if event.modifierFlags.contains(.command), let key = NSApp.keyWindow,
- !key.responds(to: NSSelectorFromString("commandDispatcher")) {
- return NSApp.mainMenu?.performKeyEquivalent(with: event) ?? false
+ !key.responds(to: NSSelectorFromString("commandDispatcher")),
+ NSApp.mainMenu?.performKeyEquivalent(with: event) == true {
+ return true
+ }
+ if let action = bindings.action(for: event) {
+ perform(action.id)
+ return true
}
return false
}
diff --git a/Sources/Cra/App/KeyBindings.swift b/Sources/Cra/App/KeyBindings.swift
index 234c196..f0647af 100644
--- a/Sources/Cra/App/KeyBindings.swift
+++ b/Sources/Cra/App/KeyBindings.swift
@@ -12,34 +12,24 @@ extension Shortcut {
var flags: NSEvent.ModifierFlags { NSEvent.ModifierFlags(rawValue: modifiers) }
- /// Shift turns "[" into "{" in charactersIgnoringModifiers; undo that.
- /// ⇧Tab arrives as backtab (U+0019), the Delete key as U+007F.
- private static let unshift: [String: String] = ["\u{19}": Shortcut.tab, "\u{7F}": Shortcut.delete, "{": "[", "}": "]", "<": ",", ">": ".", "?": "/", "+": "=", "_": "-", "~": "`", ":": ";", "\"": "'", "|": "\\"]
-
- /// Physical-key fallbacks so ⌘[ / ⌘] work on layouts (Danish, German...)
- /// where those characters live on other keys. Key codes are ANSI positions.
- private static let keyCodeFor: [String: UInt16] = ["[": 33, "]": 30, "=": 24, "-": 27, ",": 43, ".": 47, "/": 44, ";": 41, "'": 39, "`": 50, "\\": 42]
+ /// The key press an event is, for CraCore's matching (KeyChord.match). Nil for anything but a
+ /// key-down: charactersIgnoringModifiers throws on flagsChanged events, which Chromium
+ /// forwards as raw key-downs for modifier keys.
+ static func press(_ event: NSEvent) -> KeyChord.Press? {
+ guard event.type == .keyDown, let chars = event.charactersIgnoringModifiers, !chars.isEmpty else { return nil }
+ return KeyChord.Press(characters: chars, keyCode: event.keyCode,
+ modifiers: event.modifierFlags.intersection(.deviceIndependentFlagsMask).rawValue)
+ }
- func matches(_ event: NSEvent) -> Bool {
- // charactersIgnoringModifiers throws on flagsChanged events, which
- // Chromium forwards as raw key-downs for modifier keys.
- guard event.type == .keyDown else { return false }
- let evFlags = event.modifierFlags.intersection([.command, .shift, .option, .control])
- guard evFlags == flags.intersection([.command, .shift, .option, .control]) else { return false }
- guard var chars = event.charactersIgnoringModifiers, !chars.isEmpty else { return false }
- chars = chars.lowercased()
- if let u = Self.unshift[chars] { chars = u }
- if chars == key { return true }
- if let code = Self.keyCodeFor[key], event.keyCode == code { return true }
- return false
+ @MainActor func matches(_ event: NSEvent) -> Bool {
+ guard let press = Self.press(event) else { return false }
+ return match(press, typable: KeyboardLayoutCharacters.types) != nil
}
/// Build a shortcut from a recorded key press (nil for bare letters without ⌘/⌃/⌥).
static func from(event e: NSEvent) -> Shortcut? {
- guard e.type == .keyDown, var chars = e.charactersIgnoringModifiers, !chars.isEmpty else { return nil }
+ guard let chars = press(e)?.key else { return nil }
let flags = e.modifierFlags.intersection([.command, .shift, .option, .control])
- chars = chars.lowercased()
- if let u = unshift[chars] { chars = u }
let special = [tab, left, right, up, down].contains(chars) || (chars.unicodeScalars.first.map { $0.value >= 0xF704 && $0.value <= 0xF71F } ?? false)
guard special || !flags.intersection([.command, .control, .option]).isEmpty else { return nil }
return Shortcut(chars, flags)
@@ -115,10 +105,11 @@ final class KeyBindingRegistry {
NotificationCenter.default.post(name: .craKeyBindingsChanged, object: nil)
}
- /// First action whose shortcut matches the key event.
+ /// The action a key press runs: the first one whose shortcut it types, else the first one
+ /// whose key sits where the press's does (KeyChord.first).
func action(for event: NSEvent) -> KeyAction? {
- for a in actions where a.shortcuts.contains(where: { $0.matches(event) }) { return a }
- return nil
+ guard let press = Shortcut.press(event) else { return nil }
+ return KeyChord.first(in: actions, chords: \.shortcuts, press: press, typable: KeyboardLayoutCharacters.types)
}
func actions(in section: MenuSection) -> [KeyAction] { actions.filter { $0.section == section } }
diff --git a/Sources/Cra/Services/KeyboardLayoutCharacters.swift b/Sources/Cra/Services/KeyboardLayoutCharacters.swift
new file mode 100644
index 0000000..6eafa7f
--- /dev/null
+++ b/Sources/Cra/Services/KeyboardLayoutCharacters.swift
@@ -0,0 +1,44 @@
+import Carbon.HIToolbox
+
+/// The characters the current keyboard layout types without ⌥, on a key alone or with Shift.
+/// A shortcut whose character is among them matches only by character; one the layout can't
+/// type (Danish "[" is ⌥8) also takes the key in its ANSI place (KeyChord.match, GitHub #212).
+@MainActor
+enum KeyboardLayoutCharacters {
+ private static var cached: (layout: String, characters: Set<String>?)?
+
+ static func types(_ character: String) -> Bool {
+ // A layout without Unicode key data (none ship today) can't say: keep the place fallback.
+ characters?.contains(character) ?? false
+ }
+
+ private static var characters: Set<String>? {
+ guard let source = TISCopyCurrentKeyboardLayoutInputSource()?.takeRetainedValue(),
+ let idRef = TISGetInputSourceProperty(source, kTISPropertyInputSourceID) else { return nil }
+ let id = Unmanaged<CFString>.fromOpaque(idRef).takeUnretainedValue() as String
+ if let cached, cached.layout == id { return cached.characters }
+ let read = read(source)
+ cached = (id, read)
+ return read
+ }
+
+ private static func read(_ source: TISInputSource) -> Set<String>? {
+ guard let data = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) else { return nil }
+ let layout = Unmanaged<CFData>.fromOpaque(data).takeUnretainedValue() as Data
+ return layout.withUnsafeBytes { raw -> Set<String>? in
+ guard let base = raw.baseAddress?.assumingMemoryBound(to: UCKeyboardLayout.self) else { return nil }
+ var out = Set<String>()
+ for code in 0..<UInt16(128) {
+ for modifiers in [0, UInt32(shiftKey >> 8) & 0xFF] {
+ var dead: UInt32 = 0
+ var chars = [UniChar](repeating: 0, count: 4)
+ var length = 0
+ let status = UCKeyTranslate(base, code, UInt16(kUCKeyActionDown), modifiers, UInt32(LMGetKbdType()),
+ OptionBits(kUCKeyTranslateNoDeadKeysBit), &dead, chars.count, &length, &chars)
+ if status == noErr, length > 0 { out.insert(String(utf16CodeUnits: chars, count: length).lowercased()) }
+ }
+ }
+ return out
+ }
+ }
+}
diff --git a/Sources/Cra/Services/TestGesture.swift b/Sources/Cra/Services/TestGesture.swift
index 276c2ae..358920f 100644
--- a/Sources/Cra/Services/TestGesture.swift
+++ b/Sources/Cra/Services/TestGesture.swift
@@ -31,6 +31,18 @@ enum TestGesture {
}
}
+ /// A key press through the app's event queue, routed as the keyboard's are (key equivalents,
+ /// the page, then Cra's own keys), with the characters a layout gives: the test picks the
+ /// layout's characters while the menu bar's key equivalents follow the selected one.
+ static func key(_ characters: String, keyCode: UInt16, modifiers: NSEvent.ModifierFlags, in window: NSWindow) {
+ for type in [NSEvent.EventType.keyDown, .keyUp] {
+ guard let e = NSEvent.keyEvent(with: type, location: .zero, modifierFlags: modifiers, timestamp: ProcessInfo.processInfo.systemUptime,
+ windowNumber: window.windowNumber, context: nil, characters: characters,
+ charactersIgnoringModifiers: characters, isARepeat: false, keyCode: keyCode) else { return }
+ NSApp.postEvent(e, atStart: false)
+ }
+ }
+
/// Opens the menu a click (or a right-click) at a point of the window would open, without
/// the pointer: the hit view gets the mouse-down, or the nearest view with a menu(for:)
/// pops its menu. The menu tracks until Esc or a pick, so tests read it through AX.
diff --git a/Tests/promises.lock b/Tests/promises.lock
index 834c746..103df8d 100644
--- a/Tests/promises.lock
+++ b/Tests/promises.lock
@@ -328,6 +328,7 @@
#209 Packages/CraCore/Tests/CraCoreTests/BrowserLanguagesTests.swift::readsThePrefAsChromiumListsIt d7fa1a3f36a4
#209 Tests/Scenarios/accept-languages.scenario 6ca3402ebe15
#211 Packages/CraCore/Tests/CraCoreTests/FaviconKeyTests.swift::tabsOnOneHostKeepTheirOwnIcons 21d360f30e94
+#212 Packages/CraCore/Tests/CraCoreTests/KeyChordTests.swift::turkishQZoomKeys 840de09abff1
#213 Packages/CraCore/Tests/CraCoreTests/FolderPeekTests.swift::aClickOpensAClosedFolderEvenWithItsOpenTabInSight 70f9e64eb96b
#215 Tests/StoreTests.swift::arcLiveFolderImportsLive a5c462b3a9c7
#218 Tests/Scenarios/extension-popup-download.scenario ffb6285b0eee