import ApplicationServices import Carbon import Foundation import OSLog struct MenuKeyResolver: Sendable { private static let logger = Logger(subsystem: "dev.vinnymac.parcel", category: "menu-shortcuts") struct Candidate: Equatable, Sendable { let code: UInt16 let modifiers: HotKey.Modifiers } let characters: [String: [Candidate]] func resolve(virtualKey: Int?, character: String?, modifiers: UInt32, glyph: Int? = nil) throws -> [HotKey] { let flags = HotKey.Modifiers(menuModifiers: modifiers) if let virtualKey { guard let code = UInt16(exactly: virtualKey), code <= 127 else { Self.logger.debug( "\(Self.rejectedVirtualKeyDiagnostic(virtualKey: virtualKey, character: character, modifiers: modifiers, glyph: glyph), privacy: .public)" ) throw InputError.unexpectedAccessibilityValue(kAXMenuItemCmdVirtualKeyAttribute) } return [HotKey(keyCode: code, modifiers: flags)] } if let character, !character.isEmpty, let candidates = characters[character.lowercased()], !candidates.isEmpty { var seen: Set = [] return candidates.map { HotKey(keyCode: $0.code, modifiers: flags.union($0.modifiers)) } .filter { seen.insert($0).inserted } } if let glyph, glyph != 0 { guard let code = Self.glyphs[glyph] else { throw InputError.unsupportedMenuGlyph(glyph) } return [HotKey(keyCode: code, modifiers: flags)] } if let character, !character.isEmpty { throw InputError.unresolvedMenuCharacter(character) } return [] } static func rejectedVirtualKeyDiagnostic(virtualKey: Int, character: String?, modifiers: UInt32, glyph: Int?) -> String { let codePoints = character.map { "[" + $0.unicodeScalars.map { "U+" + String($0.value, radix: 16, uppercase: true) }.joined( separator: ",") + "]" } ?? "absent" let glyphValue = glyph.map { String($0) } ?? "absent" return "Rejected AXMenuItemCmdVirtualKey value \(virtualKey), character code points \(codePoints), glyph \(glyphValue), modifiers \(modifiers)" } @MainActor static func currentLayout() throws -> Self { guard let source = TISCopyCurrentKeyboardLayoutInputSource()?.takeRetainedValue(), let property = TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) else { throw InputError.keyboardLayoutUnavailable } let data = Unmanaged.fromOpaque(property).takeUnretainedValue() return try withExtendedLifetime((source, data)) { guard let bytes = CFDataGetBytePtr(data) else { throw InputError.keyboardLayoutUnavailable } let layout = UnsafeRawPointer(bytes).assumingMemoryBound(to: UCKeyboardLayout.self) var characters: [String: [Candidate]] = [:] // Prefer the main keyboard, but keep keypad equivalents for conflict detection. for range in [UInt16(0)...64, UInt16(65)...127] { for flags: HotKey.Modifiers in [[], .shift, .option, [.shift, .option]] { for code in range { let text = try translate(code: code, flags: flags, layout: layout) guard !text.isEmpty else { continue } let candidate = Candidate(code: code, modifiers: flags) var candidates = characters[text, default: []] if !candidates.contains(where: { $0.code == code && flags.isSuperset(of: $0.modifiers) }) { candidates.append(candidate) } characters[text] = candidates } } } // Menu equivalents use different delete characters from key-down events. characters["\u{8}"] = [Candidate(code: UInt16(kVK_Delete), modifiers: [])] characters["\u{7F}"] = [Candidate(code: UInt16(kVK_ForwardDelete), modifiers: [])] return Self(characters: characters) } } private static func translate(code: UInt16, flags: HotKey.Modifiers, layout: UnsafePointer) throws -> String { var deadKey: UInt32 = 0 var length = 0 var output = [UniChar](repeating: 0, count: 16) let status = UCKeyTranslate( layout, code, UInt16(kUCKeyActionDown), flags.carbonModifiers >> 8, UInt32(LMGetKbdType()), OptionBits(kUCKeyTranslateNoDeadKeysMask), &deadKey, output.count, &length, &output) guard status == noErr else { throw InputError.keyboardTranslationFailed(status) } return String(utf16CodeUnits: output, count: length).lowercased() } private static let glyphs: [Int: UInt16] = [ kMenuTabRightGlyph: UInt16(kVK_Tab), kMenuTabLeftGlyph: UInt16(kVK_Tab), kMenuEnterGlyph: UInt16(kVK_ANSI_KeypadEnter), kMenuReturnGlyph: UInt16(kVK_Return), kMenuReturnR2LGlyph: UInt16(kVK_Return), kMenuNonmarkingReturnGlyph: UInt16(kVK_Return), kMenuDeleteLeftGlyph: UInt16(kVK_Delete), kMenuDeleteRightGlyph: UInt16(kVK_ForwardDelete), kMenuEscapeGlyph: UInt16(kVK_Escape), kMenuClearGlyph: UInt16(kVK_ANSI_KeypadClear), kMenuPageUpGlyph: UInt16(kVK_PageUp), kMenuPageDownGlyph: UInt16(kVK_PageDown), kMenuNorthwestArrowGlyph: UInt16(kVK_Home), kMenuSoutheastArrowGlyph: UInt16(kVK_End), kMenuLeftArrowGlyph: UInt16(kVK_LeftArrow), kMenuRightArrowGlyph: UInt16(kVK_RightArrow), kMenuUpArrowGlyph: UInt16(kVK_UpArrow), kMenuDownArrowGlyph: UInt16(kVK_DownArrow), kMenuF1Glyph: UInt16(kVK_F1), kMenuF2Glyph: UInt16(kVK_F2), kMenuF3Glyph: UInt16(kVK_F3), kMenuF4Glyph: UInt16(kVK_F4), kMenuF5Glyph: UInt16(kVK_F5), kMenuF6Glyph: UInt16(kVK_F6), kMenuF7Glyph: UInt16(kVK_F7), kMenuF8Glyph: UInt16(kVK_F8), kMenuF9Glyph: UInt16(kVK_F9), kMenuF10Glyph: UInt16(kVK_F10), kMenuF11Glyph: UInt16(kVK_F11), kMenuF12Glyph: UInt16(kVK_F12), kMenuF13Glyph: UInt16(kVK_F13), kMenuF14Glyph: UInt16(kVK_F14), kMenuF15Glyph: UInt16(kVK_F15), kMenuF16Glyph: UInt16(kVK_F16), kMenuF17Glyph: UInt16(kVK_F17), kMenuF18Glyph: UInt16(kVK_F18), kMenuF19Glyph: UInt16(kVK_F19), ] }