fenilsonani / menu-browser / Sources/ HotkeyManager.swift

import Carbon
import AppKit
import os

// MARK: - Global Hotkey Manager (Carbon-based, no accessibility permission needed)

private let log = Logger(subsystem: "com.fenilsonani.MenuBrowser", category: "HotkeyManager")

/// Why a hotkey couldn't be claimed. `message` is user-facing.
enum HotkeyError: Error, Equatable {
    case alreadyInUse
    case handlerInstallFailed(OSStatus)
    case registrationFailed(OSStatus)

    var message: String {
        switch self {
        case .alreadyInUse:
            return "That shortcut is already used by another app. Pick a different one."
        case .handlerInstallFailed(let status):
            return "Couldn't listen for the shortcut (error \(status))."
        case .registrationFailed(let status):
            return "Couldn't register the shortcut (error \(status))."
        }
    }
}

class HotkeyManager {
    static let shared = HotkeyManager()

    private var hotKeyRef: EventHotKeyRef?
    private var eventHandlerRef: EventHandlerRef?
    var onHotKey: (() -> Void)?

    private init() {}

    /// Claims the global hotkey. Throws rather than failing silently — Carbon reports
    /// conflicts through its return status, which callers previously discarded, so a
    /// shortcut already owned by another app looked like it registered fine.
    func register(keyCode: UInt32, carbonModifiers: UInt32) throws {
        unregister()
        log.debug("Registering hotkey: keyCode=\(keyCode), carbonModifiers=\(carbonModifiers)")

        var eventType = EventTypeSpec(
            eventClass: OSType(kEventClassKeyboard),
            eventKind: UInt32(kEventHotKeyPressed)
        )

        let selfPtr = Unmanaged.passUnretained(self).toOpaque()

        let installStatus = InstallEventHandler(
            GetApplicationEventTarget(),
            hotkeyEventHandler,
            1,
            &eventType,
            selfPtr,
            &eventHandlerRef
        )
        guard installStatus == noErr else {
            eventHandlerRef = nil
            log.error("InstallEventHandler failed: \(installStatus)")
            throw HotkeyError.handlerInstallFailed(installStatus)
        }

        let hotKeyID = EventHotKeyID(
            signature: OSType(0x4D4E4252), // "MNBR"
            id: 1
        )

        let status = RegisterEventHotKey(
            keyCode,
            carbonModifiers,
            hotKeyID,
            GetApplicationEventTarget(),
            0,
            &hotKeyRef
        )
        guard status == noErr else {
            // Don't leave the event handler installed for a hotkey we never claimed.
            unregister()
            log.error("RegisterEventHotKey failed: \(status)")
            throw status == OSStatus(eventHotKeyExistsErr)
                ? HotkeyError.alreadyInUse
                : HotkeyError.registrationFailed(status)
        }
    }

    func unregister() {
        if let ref = hotKeyRef {
            UnregisterEventHotKey(ref)
            hotKeyRef = nil
            log.debug("Unregistered hotkey")
        }
        if let ref = eventHandlerRef {
            RemoveEventHandler(ref)
            eventHandlerRef = nil
        }
    }
}

// Free function as C callback for Carbon event handler
private func hotkeyEventHandler(
    _ nextHandler: EventHandlerCallRef?,
    _ event: EventRef?,
    _ userData: UnsafeMutableRawPointer?
) -> OSStatus {
    guard let userData else { return OSStatus(eventNotHandledErr) }
    let manager = Unmanaged<HotkeyManager>.fromOpaque(userData).takeUnretainedValue()
    DispatchQueue.main.async { manager.onHotKey?() }
    return noErr
}

// MARK: - Keyboard Helpers

func carbonModifiers(from flags: NSEvent.ModifierFlags) -> UInt32 {
    var carbon: UInt32 = 0
    if flags.contains(.command) { carbon |= UInt32(cmdKey) }
    if flags.contains(.shift) { carbon |= UInt32(shiftKey) }
    if flags.contains(.option) { carbon |= UInt32(optionKey) }
    if flags.contains(.control) { carbon |= UInt32(controlKey) }
    return carbon
}

// `modifierSymbols` and `keyName` live in GlobalShortcut.swift — they describe a
// shortcut rather than register one, and keeping them out of this file lets the
// persistence tests compile without linking Carbon.