// 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 } }