fenilsonani / menu-browser / Sources/ GlobalShortcut.swift

import AppKit

/// The global hotkey, and the rules for persisting it.
///
/// Kept as a standalone value type (rather than inline in `PreferencesState`) so the
/// load/save rules are testable without standing up SwiftUI or an `NSApplication`.
struct GlobalShortcut: Equatable {
    var keyCode: UInt16
    var modifiers: NSEvent.ModifierFlags

    /// ⌘⇧B — used until the user records something else.
    static let fallback = GlobalShortcut(keyCode: 0x0B, modifiers: [.command, .shift])

    enum DefaultsKey {
        static let keyCode = "shortcutKeyCode"
        static let modifiers = "shortcutModifiers"
    }

    /// A shortcut is "stored" when the key is *present*, not when it is non-zero.
    /// Keycode `0x00` is `A`, so the older `integer(forKey:) != 0` test silently
    /// discarded every `A`-based shortcut and snapped the user back to ⌘⇧B on relaunch.
    static func load(from defaults: UserDefaults) -> GlobalShortcut {
        guard defaults.object(forKey: DefaultsKey.keyCode) != nil else { return .fallback }

        // A modifier-less global hotkey would swallow a bare keypress system-wide, and
        // `startRecording` never produces one — treat it as corrupt and fall back.
        let rawModifiers = defaults.integer(forKey: DefaultsKey.modifiers)
        guard rawModifiers != 0 else { return .fallback }

        return GlobalShortcut(
            keyCode: UInt16(truncatingIfNeeded: defaults.integer(forKey: DefaultsKey.keyCode)),
            modifiers: NSEvent.ModifierFlags(rawValue: UInt(rawModifiers))
        )
    }

    func save(to defaults: UserDefaults) {
        defaults.set(Int(keyCode), forKey: DefaultsKey.keyCode)
        defaults.set(Int(modifiers.rawValue), forKey: DefaultsKey.modifiers)
    }

    /// e.g. "⌘⇧B" — what the menu and the Preferences button show.
    var displayString: String {
        modifierSymbols(modifiers) + keyName(keyCode)
    }
}

// MARK: - Display Helpers

func modifierSymbols(_ flags: NSEvent.ModifierFlags) -> String {
    var s = ""
    if flags.contains(.control) { s += "⌃" }
    if flags.contains(.option) { s += "⌥" }
    if flags.contains(.shift) { s += "⇧" }
    if flags.contains(.command) { s += "⌘" }
    return s
}

func keyName(_ keyCode: UInt16) -> String {
    let map: [UInt16: String] = [
        // Letters
        0x00: "A", 0x01: "S", 0x02: "D", 0x03: "F", 0x04: "H",
        0x05: "G", 0x06: "Z", 0x07: "X", 0x08: "C", 0x09: "V",
        0x0B: "B", 0x0C: "Q", 0x0D: "W", 0x0E: "E", 0x0F: "R",
        0x10: "Y", 0x11: "T", 0x1F: "O", 0x20: "U", 0x22: "I",
        0x23: "P", 0x25: "L", 0x26: "J", 0x28: "K", 0x2D: "N",
        0x2E: "M",
        // Numbers
        0x12: "1", 0x13: "2", 0x14: "3", 0x15: "4", 0x16: "6",
        0x17: "5", 0x19: "9", 0x1A: "7", 0x1C: "8", 0x1D: "0",
        // Punctuation
        0x18: "=", 0x1B: "-", 0x1E: "]", 0x21: "[", 0x27: "'",
        0x29: ";", 0x2A: "\\", 0x2B: ",", 0x2C: "/", 0x2F: ".",
        0x32: "`",
        // Whitespace & editing
        0x24: "↩", 0x30: "Tab", 0x31: "Space", 0x33: "⌫", 0x35: "⎋",
        0x75: "⌦",
        // Arrow keys
        0x7B: "←", 0x7C: "→", 0x7D: "↓", 0x7E: "↑",
        // Navigation
        0x73: "Home", 0x77: "End", 0x74: "⇞", 0x79: "⇟",
        // Function keys
        0x7A: "F1", 0x78: "F2", 0x63: "F3", 0x76: "F4",
        0x60: "F5", 0x61: "F6", 0x62: "F7", 0x64: "F8",
        0x65: "F9", 0x6D: "F10", 0x67: "F11", 0x6F: "F12",
        0x69: "F13", 0x6B: "F14", 0x71: "F15", 0x6A: "F16",
        0x40: "F17", 0x4F: "F18", 0x50: "F19", 0x5A: "F20",
    ]
    return map[keyCode] ?? "Key\(keyCode)"
}