From 42c614591b80b7c5b4f7506bb45a51c6ebf8f60f Mon Sep 17 00:00:00 2001 From: Guoliang Chen Date: Wed, 16 Sep 2026 02:09:27 -0700 Subject: [PATCH] input-capture: Screens and Cursor ScreenLayout is GetScreenConfig/MonitorEnumProc on CGDisplayBounds, with the four corners BlockMouseAtScreenCorners needs, refreshed on didChangeScreenParameters. Cursor is HideMouseCursor plus the macOS-only decoupling that keeps the real pointer still while a peer is controlled. Co-Authored-By: Claude Opus 5 (1M context) --- Sources/MWBMac/Cursor.swift | 133 +++++++++++++++++++++++++++++++++++ Sources/MWBMac/Screens.swift | 131 ++++++++++++++++++++++++++++++++++ 2 files changed, 264 insertions(+) create mode 100644 Sources/MWBMac/Cursor.swift create mode 100644 Sources/MWBMac/Screens.swift diff --git a/Sources/MWBMac/Cursor.swift b/Sources/MWBMac/Cursor.swift new file mode 100644 index 0000000..a8c278d --- /dev/null +++ b/Sources/MWBMac/Cursor.swift @@ -0,0 +1,133 @@ +// The real pointer: park it, hide it, unhook it from the mouse while a remote +// machine is being controlled, and put it back when control comes home. +// +// Windows parks the cursor with `SetCursorPos` and relies on the low-level hook +// swallowing every mouse event to keep it there (`Common.HideMouseCursor`, +// `Common.cs:1482-1496`). macOS needs one thing more: swallowing events in a tap +// does not stop the window server from moving the pointer, so the pointer has to +// be decoupled from the mouse with `CGAssociateMouseAndMouseCursorPosition`. +// Deltas keep arriving on the tap while it is decoupled, which is exactly what +// the virtual cursor in `RoutingState` consumes. +// +// CLAUDE.md invariant 3: everything here is reversible from `recouple`, and +// `recouple` is what every recovery path in contracts C2 ends with. + +import CoreGraphics +import Foundation +import MWBCore +import os + +/// The real mouse pointer. +public final class Cursor: Sendable { + private struct State: Sendable { + var hidden = false + var decoupled = false + } + + private let state: OSAllocatedUnfairLock + + /// A cursor controller for this session. One per process. + public init() { + state = OSAllocatedUnfairLock(initialState: State()) + } + + /// Where the pointer is parked while a remote machine has control + /// (`Common.cs:1484-1486`): the primary screen's horizontal centre, and + /// `y = 4` when `HideMouseAtScreenEdge` is on so the pointer sits in the menu + /// bar out of the way, otherwise the vertical centre. + public static func parkPosition(hideMouse: Bool, in layout: ScreenLayout) -> CGPoint { + let centre = Coordinates.centre(of: layout.primary) + return CGPoint(x: centre.x, y: hideMouse ? 4 : centre.y) + } + + /// `Common.HideMouseCursor` (`Common.cs:1482-1496`): work out the park + /// position, and move the pointer there **only** when the gate passes. + /// + /// The gate is Windows' `(desMachineID != MachineID && != ALL) || + /// byHideMouseMessage` (`:1488`), pre-evaluated by `Switcher` and handed over + /// as `SwitchAction.parkCursor(destinationIsRemote:byHideMouseMessage:)` — + /// see the session-matrix Handshakes. Moving unconditionally would jerk the + /// pointer to the top of the screen every time control comes home. + /// + /// Returns the park position either way, because Windows records it as + /// `LastPos` (the position the pointer is restored to) on every call. + @discardableResult + public func park( + hideMouse: Bool, layout: ScreenLayout, destinationIsRemote: Bool, + byHideMouseMessage: Bool + ) -> CGPoint { + let position = Cursor.parkPosition(hideMouse: hideMouse, in: layout) + if destinationIsRemote || byHideMouseMessage { warp(to: position) } + return position + } + + /// Hands the pointer to a remote machine: park it, hide it, and stop the + /// mouse from moving it. Returns the parked position. + /// + /// Call once per switch away from this Mac, from the Engine — never from the + /// tap callback, since all three calls talk to the window server. + @discardableResult + public func decouple(parkHidden: Bool, layout: ScreenLayout) -> CGPoint { + let position = park( + hideMouse: parkHidden, layout: layout, destinationIsRemote: true, + byHideMouseMessage: false) + associate(false) + hide() + return position + } + + /// Gives the pointer back to this Mac: show it, re-associate it with the + /// mouse, and put it where it was. The order matters — re-associating first + /// would let a queued delta move it before the warp lands. + public func recouple(to point: CGPoint?) { + show() + associate(true) + if let point { warp(to: point) } + } + + /// Moves the pointer without generating an event (`SetCursorPos`). + public func warp(to point: CGPoint) { + _ = CGWarpMouseCursorPosition(point) + } + + /// Hides the pointer. Balanced with `show()`: `CGDisplayHideCursor` is + /// reference counted, so an unmatched hide leaves the Mac without a pointer. + public func hide() { + let shouldHide = state.withLock { state -> Bool in + guard !state.hidden else { return false } + state.hidden = true + return true + } + if shouldHide { _ = CGDisplayHideCursor(CGMainDisplayID()) } + } + + /// Shows the pointer again, if this `Cursor` hid it. + public func show() { + let shouldShow = state.withLock { state -> Bool in + guard state.hidden else { return false } + state.hidden = false + return true + } + if shouldShow { _ = CGDisplayShowCursor(CGMainDisplayID()) } + } + + /// Whether the pointer is currently frozen by us. + public var isDecoupled: Bool { state.withLock { $0.decoupled } } + + /// Everything undone, for `atexit` and the signal handler (contracts C2, last + /// row): the Mac must never be left with a frozen or invisible pointer. + public func restoreEverything() { + show() + associate(true) + } + + private func associate(_ connected: Bool) { + let changed = state.withLock { state -> Bool in + guard state.decoupled == connected else { return false } + state.decoupled = !connected + return true + } + guard changed else { return } + _ = CGAssociateMouseAndMouseCursorPosition(connected ? 1 : 0) + } +} diff --git a/Sources/MWBMac/Screens.swift b/Sources/MWBMac/Screens.swift new file mode 100644 index 0000000..6b25198 --- /dev/null +++ b/Sources/MWBMac/Screens.swift @@ -0,0 +1,131 @@ +// The display geometry everything else measures against: which monitors exist, +// which one is primary, the union of them all, and every monitor's four corners. +// +// This is `WinAPI.GetScreenConfig` (`WinAPI.cs:115-184`) and its +// `MonitorEnumProc` (`:70-113`) on macOS. The coordinate conventions already +// match: `CGDisplayBounds` puts the main display's top-left at (0, 0), y grows +// downwards, and the rectangles are half-open the way `Rectangle.Right` is — so +// `Coordinates.bounds` reads a `CGRect` from here without conversion. +// +// Points, not pixels: a Retina display reports its logical size, which is what a +// Windows peer scaling 0..65535 wants. + +import AppKit +import CoreGraphics +import Foundation +import MWBCore +import os + +/// A snapshot of the display arrangement, in this Mac's screen coordinates. +public struct ScreenLayout: Sendable { + /// Every active display's bounds. + public var displays: [CGRect] + /// The display whose origin is (0, 0) — `CGMainDisplayID()`, the Windows + /// "primary screen" (`WinAPI.cs:70-80`). + public var primary: CGRect + /// The union of every display (`MachineStuff.desktopBounds`). + public var desktop: CGRect + /// Every display's four corners, the points `BlockMouseAtScreenCorners` + /// keeps the pointer from switching near (`WinAPI.cs:104-109`). + public var corners: [CGPoint] + + /// An empty layout, for a process that has not read its displays yet. + public init( + displays: [CGRect] = [], primary: CGRect = Coordinates.emptyRect, + desktop: CGRect = Coordinates.emptyRect, corners: [CGPoint] = [] + ) { + self.displays = displays + self.primary = primary + self.desktop = desktop + self.corners = corners + } + + /// The layout the displays currently describe. + public static func current() -> ScreenLayout { + let primary = CGDisplayBounds(CGMainDisplayID()) + let displays = activeDisplayBounds() + let desktop = displays.reduce(primary) { $0.union($1) } + var corners: [CGPoint] = [] + corners.reserveCapacity(displays.count * 4) + for bounds in displays { + corners.append(CGPoint(x: bounds.minX, y: bounds.minY)) + corners.append(CGPoint(x: bounds.maxX, y: bounds.minY)) + corners.append(CGPoint(x: bounds.maxX, y: bounds.maxY)) + corners.append(CGPoint(x: bounds.minX, y: bounds.maxY)) + } + return ScreenLayout( + displays: displays, primary: primary, desktop: desktop, corners: corners) + } + + /// The `EdgeConfig` this layout implies, ready for `Switcher.edge.config` + /// (topo.md handshakes 4 and 6). The two option flags come from settings. + public func edgeConfig(blockCorners: Bool, moveRelatively: Bool) -> EdgeConfig { + EdgeConfig( + desktop: desktop, primary: primary, corners: corners, blockCorners: blockCorners, + moveRelatively: moveRelatively) + } + + private static func activeDisplayBounds() -> [CGRect] { + var count: UInt32 = 0 + guard CGGetActiveDisplayList(0, nil, &count) == .success, count > 0 else { + return [CGDisplayBounds(CGMainDisplayID())] + } + var ids = [CGDirectDisplayID](repeating: 0, count: Int(count)) + guard CGGetActiveDisplayList(count, &ids, &count) == .success else { + return [CGDisplayBounds(CGMainDisplayID())] + } + return ids.prefix(Int(count)).map { CGDisplayBounds($0) } + } +} + +/// The current `ScreenLayout`, kept up to date as monitors come and go. +/// +/// `@unchecked Sendable`: the layout itself is behind a lock because the tap +/// callback reads it on the tap thread while `refresh()` runs on the main one; +/// the notification token is only ever touched on the main thread, in +/// `startObserving`/`stopObserving`, and is not `Sendable` only because +/// `NSObjectProtocol` is not. +public final class Screens: @unchecked Sendable { + private let state: OSAllocatedUnfairLock + private let onChange: (@Sendable () -> Void)? + private var observer: (any NSObjectProtocol)? + + /// Reads the displays once. `onChange` is called after every refresh caused + /// by a display change; it runs on the main thread. + public init(onChange: (@Sendable () -> Void)? = nil) { + state = OSAllocatedUnfairLock(initialState: ScreenLayout.current()) + self.onChange = onChange + } + + /// The last layout read. Cheap enough to call per mouse event. + public var layout: ScreenLayout { state.withLock { $0 } } + + /// Re-reads the displays. + public func refresh() { + let fresh = ScreenLayout.current() + state.withLock { $0 = fresh } + } + + /// Starts watching for monitors being added, removed or rearranged. + /// + /// Windows learns this from `WM_DISPLAYCHANGE`; macOS posts + /// `NSApplication.didChangeScreenParametersNotification`. Call on the main + /// thread, after `NSApplication.shared` exists. + public func startObserving() { + guard observer == nil else { return } + observer = NotificationCenter.default.addObserver( + forName: NSApplication.didChangeScreenParametersNotification, object: nil, + queue: .main + ) { [weak self] _ in + guard let self else { return } + self.refresh() + self.onChange?() + } + } + + /// Stops watching. Call on the main thread. + public func stopObserving() { + if let observer { NotificationCenter.default.removeObserver(observer) } + observer = nil + } +}