// MouseTracker.swift // Lyrebird // // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT #if os(macOS) import AppKit import Synchronization import LyrebirdSynth /// macOS `MouseInputBridge` conformer driven by AppKit `NSEvent` global monitors. /// /// Tracks mouse position and button state on the main thread, exposing the values via /// lock-free `Synchronization.Atomic` reads suitable for the audio render thread. /// /// Mouse position is normalised to `[0, 1]` against the main screen bounds: /// - `x` = 0 (left edge) … 1 (right edge) /// - `y` = 0 (bottom edge) … 1 (top edge) — screen Y is inverted from AppKit's coords /// - `button` = 0.0 (released) or 1.0 (left button held) /// /// Install once at app startup so `Mouse.X.Control()` / `Mouse.Y.Control()` / /// `Mouse.Click.Control()` generators read live values: /// /// ```swift /// import LyrebirdSynth /// import LyrebirdUI /// /// MouseTracker.installShared() /// ``` /// /// Without this call the generators output the no-op default constants from /// `Lyrebird.MouseInputBridge`. public final class MouseTracker: MouseInputBridge, @unchecked Sendable { // Sendable invariant: `_x`, `_y`, `_button`, and `_monitorsInstalled` are immutable // `Atomic`s — all reads/writes lock-free. Monitor token vars are written once on the // main thread via the dispatched `_installMonitors()` and never read after install // (kept only to retain the monitor-handler closures for the process lifetime). /// Installs `MouseTracker.shared` as the active `MouseInput` bridge AND triggers /// the one-time `NSEvent` global-monitor install on the main thread. /// /// Must be called from the main thread — traps in debug builds otherwise. Off-main /// callers would register the bridge synchronously while the monitor install runs /// in a deferred main-queue dispatch, leading to a window where `Mouse.*.Control` /// generators read the 0.5/0.5/0.0 init values until the dispatch fires. /// /// Idempotent: both sides are gated by the `_monitorsInstalled` atomic CAS, so /// repeat calls are a pure no-op (no retain churn, no extra `dispatch_async`). /// Subject to the engine-stopped invariant documented on `MouseInput.install(_:)`. public static func installShared() { assert(Thread.isMainThread, "MouseTracker.installShared() must be called from the main thread") shared._installMonitorsIfNeeded() } /// Process-wide `MouseTracker` instance. Touching this property does NOT install /// `NSEvent` monitors — call `installShared()` to wire monitors AND register as /// the `MouseInput` bridge. public static let shared: MouseTracker = MouseTracker() // MARK: - Atomic state (RT-readable without locks) private let _x: Atomic private let _y: Atomic private let _button: Atomic // MARK: - NSEvent monitor tokens // // `Any?` storage that exists solely to retain the closure registered with // `NSEvent.addGlobalMonitorForEvents` — the API returns an opaque token whose // lifetime owns the handler closure. Written once from the main thread via the // `_installMonitorsOnMain` dispatch and never read afterwards (no `removeMonitor` // path because the singleton is process-lifetime). private var _moveMonitorToken: Any? private var _downMonitorToken: Any? private var _upMonitorToken: Any? private let _monitorsInstalled: Atomic = Atomic(false) // MARK: - Init /// Allocates the atomic state slots. Does not install `NSEvent` monitors — /// `installShared()` does that. public override init() { _x = Atomic(mouseTrackerInitialPosition) _y = Atomic(mouseTrackerInitialPosition) _button = Atomic(mouseButtonReleased) super.init() } // No `deinit`: `shared` retains the singleton for the process lifetime, so the // installed `NSEvent` monitors are released only at process exit. There is no // public init path that would create a second tracker to dispose. // MARK: - MouseInputBridge overrides public override var x: Double { _x.load(ordering: .relaxed) } public override var y: Double { _y.load(ordering: .relaxed) } public override var button: Double { _button.load(ordering: .relaxed) } // MARK: - Monitor installation /// Installs `NSEvent` global monitors on the main thread AND registers `self` as /// the active `MouseInput` bridge. Idempotent via `_monitorsInstalled` atomic CAS — /// repeat calls are a pure no-op. private func _installMonitorsIfNeeded() { let (exchanged, _) = _monitorsInstalled.compareExchange( expected: false, desired: true, ordering: .acquiringAndReleasing) guard exchanged else { return } MouseInput.install(self) DispatchQueue.main.async { [weak self] in self?._installMonitorsOnMain() } } private func _installMonitorsOnMain() { let moveMask: NSEvent.EventTypeMask = [.mouseMoved, .leftMouseDragged, .rightMouseDragged] _moveMonitorToken = NSEvent.addGlobalMonitorForEvents(matching: moveMask) { [weak self] event in self?.handleMouseMove(event) } _downMonitorToken = NSEvent.addGlobalMonitorForEvents(matching: .leftMouseDown) { [weak self] _ in self?._button.store(mouseButtonPressed, ordering: .relaxed) } _upMonitorToken = NSEvent.addGlobalMonitorForEvents(matching: .leftMouseUp) { [weak self] _ in self?._button.store(mouseButtonReleased, ordering: .relaxed) } } // MARK: - Event handling private func handleMouseMove(_ event: NSEvent) { guard let screen: NSScreen = NSScreen.main else { return } let screenBounds: NSRect = screen.frame let screenWidth: CGFloat = screenBounds.width let screenHeight: CGFloat = screenBounds.height guard screenWidth > 0, screenHeight > 0 else { return } let screenX: CGFloat = event.locationInWindow.x - screenBounds.minX let screenY: CGFloat = event.locationInWindow.y - screenBounds.minY let normX: Double = min(max(screenX / screenWidth, normalizedMin), normalizedMax) let normY: Double = min(max(screenY / screenHeight, normalizedMin), normalizedMax) _x.store(normX, ordering: .relaxed) _y.store(normY, ordering: .relaxed) } } // MARK: - MouseTracker constants private let mouseTrackerInitialPosition: Double = 0.5 private let mouseButtonPressed: Double = 1.0 private let mouseButtonReleased: Double = 0.0 private let normalizedMin: Double = 0.0 private let normalizedMax: Double = 1.0 #endif // os(macOS)