import ApplicationServices import CoreGraphics import Foundation import OSLog enum MouseTapRole: String, Sendable { case mouse, observation, escape } struct MouseTapActivation { private(set) var enabled: Bool? mutating func synchronize( enabled desired: Bool, write: (Bool) -> Void, read: () -> Bool ) throws(InputError) { guard enabled != desired else { return } write(desired) guard read() == desired else { throw .tapEnableFailed } enabled = desired } static func failure( for notification: CGEventType, role: MouseTapRole, escapeEnabled: Bool?, escapeRequested: Bool ) -> InputError? { switch notification { case .tapDisabledByTimeout: .tapTimedOut case .tapDisabledByUserInput: role == .escape && escapeEnabled == false && !escapeRequested ? nil : .tapEnableFailed default: nil } } } // Ports and sources belong to the worker; the condition protects only startup and shutdown. final class MouseEventTapThread: @unchecked Sendable { private let condition = NSCondition() private var runLoop: CFRunLoop? private var ready = false private var stopping = false private var startFailure: InputError? private let mailbox: MouseTapMailbox private var ports: [CFMachPort] = [] private var sources: [CFRunLoopSource] = [] private var escapePort: CFMachPort? private var escapeActivation = MouseTapActivation() private let logger = Logger(subsystem: "dev.vinnymac.parcel", category: "mouse-input") init(mailbox: MouseTapMailbox) throws { self.mailbox = mailbox let thread = Thread { [self] in run() } thread.name = "Parcel mouse input" thread.qualityOfService = .userInteractive thread.start() condition.lock() while !ready { condition.wait() } let failure = startFailure condition.unlock() if let failure { throw failure } } func stop() { condition.lock() stopping = true let loop = runLoop condition.unlock() if let loop { CFRunLoopStop(loop) } } func snapshotChanged() { condition.lock() let loop = runLoop condition.unlock() if let loop { CFRunLoopPerformBlock(loop, CFRunLoopMode.commonModes.rawValue) { [self] in updateEscape() } CFRunLoopWakeUp(loop) } } private func run() { let loop = CFRunLoopGetCurrent() do { try install( role: .mouse, types: [ .leftMouseDown, .leftMouseDragged, .leftMouseUp, .rightMouseDown, .rightMouseDragged, .rightMouseUp, ], options: .defaultTap, callback: Self.mouseCallback) try install( role: .observation, types: [.keyDown, .flagsChanged, .mouseMoved], options: .listenOnly, callback: Self.observeCallback) escapePort = try install( role: .escape, types: [.keyDown], options: .defaultTap, callback: Self.escapeCallback) } catch { condition.lock() startFailure = error as? InputError ?? .tapCreationFailed ready = true condition.broadcast() condition.unlock() removePorts() return } condition.lock() runLoop = loop ready = true let shouldStop = stopping condition.broadcast() condition.unlock() if !shouldStop { CFRunLoopRun() } removePorts() condition.lock() runLoop = nil condition.unlock() } @discardableResult private func install( role: MouseTapRole, types: [CGEventType], options: CGEventTapOptions, callback: CGEventTapCallBack ) throws -> CFMachPort { do { let mask = types.reduce(CGEventMask(0)) { $0 | (CGEventMask(1) << $1.rawValue) } // The window server assigns mouse hit identities after the session tap. guard let port = CGEvent.tapCreate( tap: role == .mouse ? .cgAnnotatedSessionEventTap : .cgSessionEventTap, place: .headInsertEventTap, options: options, eventsOfInterest: mask, callback: callback, userInfo: Unmanaged.passUnretained(self).toOpaque()) else { throw InputError.tapCreationFailed } guard let source = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, port, 0) else { CFMachPortInvalidate(port) throw InputError.tapRunLoopSourceFailed } ports.append(port) sources.append(source) CFRunLoopAddSource(CFRunLoopGetCurrent(), source, .commonModes) var activation = MouseTapActivation() try activation.synchronize( enabled: role == .escape ? mailbox.consumesEscape : true, write: { CGEvent.tapEnable(tap: port, enable: $0) }, read: { CGEvent.tapIsEnabled(tap: port) }) if role == .escape { escapeActivation = activation } return port } catch { logger.error( "Mouse tap \(role.rawValue, privacy: .public) installation failed: \(String(describing: error), privacy: .public)" ) throw error } } private func removePorts() { for port in ports { CGEvent.tapEnable(tap: port, enable: false) CFMachPortInvalidate(port) } for source in sources { CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, .commonModes) } ports.removeAll() sources.removeAll() escapePort = nil } private func disabled(_ type: CGEventType, role: MouseTapRole) -> Bool { guard type == .tapDisabledByTimeout || type == .tapDisabledByUserInput else { return false } if let failure = MouseTapActivation.failure( for: type, role: role, escapeEnabled: escapeActivation.enabled, escapeRequested: mailbox.consumesEscape) { logger.error( "Mouse tap \(role.rawValue, privacy: .public) disabled notification: \(String(describing: failure), privacy: .public)" ) mailbox.disable(failure) stop() } return true } private func updateEscape() { guard let escapePort else { return } let desired = mailbox.consumesEscape do { try escapeActivation.synchronize( enabled: desired, write: { CGEvent.tapEnable(tap: escapePort, enable: $0) }, read: { CGEvent.tapIsEnabled(tap: escapePort) }) } catch { logger.error( "Mouse tap escape activation failed (requested enabled: \(desired)): \(String(describing: error), privacy: .public)" ) mailbox.disable(error) stop() } } private static let mouseCallback: CGEventTapCallBack = { _, type, event, context in guard let context else { return Unmanaged.passUnretained(event) } let owner = Unmanaged.fromOpaque(context).takeUnretainedValue() guard !owner.disabled(type, role: .mouse) else { return Unmanaged.passUnretained(event) } let kind: DragSample.Kind let button: DragSample.Button switch type { case .leftMouseDown: (kind, button) = (.down, .left) case .rightMouseDown: (kind, button) = (.down, .right) case .leftMouseDragged: (kind, button) = (.dragged, .left) case .rightMouseDragged: (kind, button) = (.dragged, .right) case .leftMouseUp: (kind, button) = (.up, .left) case .rightMouseUp: (kind, button) = (.up, .right) default: return Unmanaged.passUnretained(event) } let sample = DragSample( kind: kind, location: event.location, modifiers: .init(eventFlags: event.flags), clickCount: max(0, Int(clamping: event.getIntegerValueField(.mouseEventClickState))), timestamp: Double(event.timestamp) / 1_000_000_000, button: button) let hint = UInt32(exactly: event.getIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent)) ?? 0 let consumed = owner.mailbox.receive(sample, windowHint: hint) if kind != .dragged { owner.updateEscape() owner.mailbox.refreshWindows() } return consumed ? nil : Unmanaged.passUnretained(event) } private static let observeCallback: CGEventTapCallBack = { _, type, event, context in guard let context else { return Unmanaged.passUnretained(event) } let owner = Unmanaged.fromOpaque(context).takeUnretainedValue() guard !owner.disabled(type, role: .observation) else { return Unmanaged.passUnretained(event) } if type == .mouseMoved { if owner.mailbox.needsWindowRefresh(at: event.location, modifiers: .init(eventFlags: event.flags)) { owner.mailbox.refreshWindows() } } else if let button = owner.mailbox.lastButton { owner.mailbox.reconcileButton( isDown: CGEventSource.buttonState( .combinedSessionState, button: button == .right ? .right : .left)) if type == .flagsChanged { owner.mailbox.receive( DragSample( kind: .modifiersChanged, location: event.location, modifiers: .init(eventFlags: event.flags), timestamp: Double(event.timestamp) / 1_000_000_000, button: button)) } else if type == .keyDown, event.getIntegerValueField(.keyboardEventKeycode) == 53 { owner.mailbox.receive(DragSample(kind: .cancel, location: event.location, button: button)) } } owner.updateEscape() return Unmanaged.passUnretained(event) } private static let escapeCallback: CGEventTapCallBack = { _, type, event, context in guard let context else { return Unmanaged.passUnretained(event) } let owner = Unmanaged.fromOpaque(context).takeUnretainedValue() guard !owner.disabled(type, role: .escape), type == .keyDown, event.getIntegerValueField(.keyboardEventKeycode) == 53, owner.mailbox.consumesEscape else { return Unmanaged.passUnretained(event) } let consumed = owner.mailbox.receive(DragSample(kind: .cancel, location: event.location)) owner.updateEscape() return consumed ? nil : Unmanaged.passUnretained(event) } }