Files
Lyrebird/Sources/LyrebirdUI/MouseTracker.swift
T
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00

274 lines
11 KiB
Swift

// MouseTracker.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
#if canImport(SwiftUI)
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<Double>` 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<Double>
private let _y: Atomic<Double>
private let _button: Atomic<Double>
// 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<Bool> = Atomic<Bool>(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 // canImport(SwiftUI)
#elseif os(Linux)
import Synchronization
import LyrebirdSynth
import BackendGTK4
/// Linux `MouseInputBridge` conformer driven by a window-local GTK pointer
/// source (`GtkEventControllerMotion` + `GtkGestureClick`), the GTK4 counterpart
/// to the macOS `NSEvent`-monitor `MouseTracker`.
///
/// Position is normalised to the window the pointer is over:
/// - `x` = 0 (left edge) … 1 (right edge)
/// - `y` = 0 (bottom edge) … 1 (top edge) — flipped from GTK's top-left origin
/// - `button` = 0.0 (released) or 1.0 (primary button held)
///
/// Values are exposed via lock-free `Synchronization.Atomic<Double>` reads,
/// safe for the audio render thread, exactly like the macOS tracker.
///
/// Install once at app startup so `Mouse.X.Control()` / `Mouse.Y.Control()` /
/// `Mouse.Click.Control()` read live values:
///
/// ```swift
/// import LyrebirdSynth
/// import LyrebirdUI
///
/// MouseTracker.installShared()
/// ```
///
/// Unlike macOS this is window-local: it reports while the pointer is over one
/// of the app's windows (SwiftOpenUI attaches the controllers to every window
/// it opens). `x` / `y` are fully covered; `button` is best-effort — a
/// window-level click gesture sees presses not consumed by an interactive child.
///
/// ## Threading
///
/// `installShared()` and the forwarded pointer callbacks run on the GTK main
/// thread. No `@MainActor` — the Linux UI is GTK-main-loop-confined, not on the
/// Swift main actor (see `LyrebirdWindow`).
public final class MouseTracker: MouseInputBridge, @unchecked Sendable {
// Sendable invariant: `_x`/`_y`/`_button`/`_installed` are immutable `Atomic`s —
// all reads/writes lock-free. The pointer-sink closures are set once (gated by
// the `_installed` CAS) and only store into those atomics.
/// Process-wide `MouseTracker` instance.
public static let shared: MouseTracker = MouseTracker()
private let _x: Atomic<Double>
private let _y: Atomic<Double>
private let _button: Atomic<Double>
private let _installed: Atomic<Bool> = Atomic<Bool>(false)
/// Allocates the atomic state slots. Does not install the pointer sink —
/// `installShared()` does that.
public override init() {
_x = Atomic(mouseTrackerInitialPosition)
_y = Atomic(mouseTrackerInitialPosition)
_button = Atomic(mouseButtonReleased)
super.init()
}
// 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: - Install
/// Installs `MouseTracker.shared` as the active `MouseInput` bridge AND
/// registers the GTK pointer sink. Idempotent via the `_installed` atomic CAS.
///
/// Install timing is not sensitive: SwiftOpenUI attaches the pointer
/// controllers to every window it opens and reads the installed sink at event
/// time, so calling this before or after `GTK4Backend().run(_:)` both work.
public static func installShared() {
shared._installIfNeeded()
}
private func _installIfNeeded() {
let (exchanged, _) = _installed.compareExchange(
expected: false, desired: true, ordering: .acquiringAndReleasing)
guard exchanged else { return }
MouseInput.install(self)
GTK4PointerTracking.install(
onMove: { [weak self] (nx: Double, ny: Double) in
// Clamp to [0, 1] to honour the normalized-range contract even if
// an edge/drag-out event reports slightly out of bounds — parity
// with the macOS tracker's clamp.
self?._x.store(min(max(nx, 0.0), 1.0), ordering: .relaxed)
self?._y.store(min(max(ny, 0.0), 1.0), ordering: .relaxed)
},
onButton: { [weak self] (pressed: Bool) in
self?._button.store(
pressed ? mouseButtonPressed : mouseButtonReleased,
ordering: .relaxed
)
}
)
}
}
// MARK: - MouseTracker constants
private let mouseTrackerInitialPosition: Double = 0.5
private let mouseButtonPressed: Double = 1.0
private let mouseButtonReleased: Double = 0.0
#endif // os(macOS) / os(Linux)