Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464internal import AppKitinternal import ColorSyncpublic import CoreGraphicspublic import Foundationinternal import Synchronizationinternal import os
public struct Display: Equatable, Sendable { public let id: UUID public let frame: CGRect public let visibleFrame: CGRect public let scale: CGFloat public let isBuiltIn: Bool
public init(id: UUID, frame: CGRect, visibleFrame: CGRect, scale: CGFloat, isBuiltIn: Bool) { self.id = id self.frame = frame self.visibleFrame = visibleFrame self.scale = scale self.isBuiltIn = isBuiltIn }}
public enum DisplayEnumerationError: Error, Equatable, Sendable { case missingDisplayID case missingDisplayUUID(UInt32)}
public enum DisplayObservationError: Error, Equatable, Sendable { case registrationFailed(Int32) case removalFailed(Int32) case stopped}
struct DisplayReconfigurationCallbacks: Sendable { let register: @Sendable (CGDisplayReconfigurationCallBack, UnsafeMutableRawPointer) -> CGError let remove: @Sendable (CGDisplayReconfigurationCallBack, UnsafeMutableRawPointer) -> CGError
static let native = Self( register: { CGDisplayRegisterReconfigurationCallback($0, $1) }, remove: { CGDisplayRemoveReconfigurationCallback($0, $1) })}
final class DisplayReconfigurationRegistration: Sendable { private final class Context: Sendable { struct State: Sendable { var handler: (@Sendable (CGDirectDisplayID, CGDisplayChangeSummaryFlags) -> Void)? var registered = false var stopRequested = false } let state: Mutex<State>
init(handler: @escaping @Sendable (CGDirectDisplayID, CGDisplayChangeSummaryFlags) -> Void) { state = Mutex(State(handler: handler)) }
func receive(display: CGDirectDisplayID, flags: CGDisplayChangeSummaryFlags) { let handler = state.withLock { $0.handler } handler?(display, flags) } }
private struct Registry { var next: UInt = 0 var contexts: [UInt: Context] = [:] } private static let registry = Mutex(Registry()) private let context: Context private let identifier: UInt private let callbacks: DisplayReconfigurationCallbacks private var pointer: UnsafeMutableRawPointer { guard let pointer = UnsafeMutableRawPointer(bitPattern: identifier) else { preconditionFailure("Display callback identifier must be nonzero") } return pointer } private static let callback: CGDisplayReconfigurationCallBack = { display, flags, pointer in guard let pointer else { preconditionFailure("Display callback context is missing") } // The opaque token is never dereferenced, even if removal races an already-dispatched callback. let context = registry.withLock { $0.contexts[UInt(bitPattern: pointer)] } context?.receive(display: display, flags: flags) }
init( callbacks: DisplayReconfigurationCallbacks, handler: @escaping @Sendable (CGDirectDisplayID, CGDisplayChangeSummaryFlags) -> Void ) throws { self.callbacks = callbacks let context = Context(handler: handler) self.context = context identifier = Self.registry.withLock { $0.next += 1 $0.contexts[$0.next] = context return $0.next } let status = callbacks.register(Self.callback, pointer) guard status == .success else { Self.registry.withLock { $0.contexts[identifier] = nil } throw DisplayObservationError.registrationFailed(status.rawValue) } context.state.withLock { $0.registered = true } }
func stop() throws { let registered = context.state.withLock { $0.stopRequested = true $0.handler = nil let registered = $0.registered $0.registered = false return registered } guard registered else { return } Self.registry.withLock { $0.contexts[identifier] = nil } let status = callbacks.remove(Self.callback, pointer) guard status == .success else { context.state.withLock { $0.registered = true } throw DisplayObservationError.removalFailed(status.rawValue) } }
deinit { precondition( context.state.withLock { !$0.registered || $0.stopRequested }, "Stop display registration before releasing its owner") }}
struct DisplayChangeDebouncer { static let interval: Duration = .milliseconds(200) private(set) var deadline: ContinuousClock.Instant?
mutating func record(at instant: ContinuousClock.Instant) -> ContinuousClock.Instant { let next = instant.advanced(by: Self.interval) deadline = next return next }
mutating func consumeIfDue(at instant: ContinuousClock.Instant) -> Bool { guard let deadline, instant >= deadline else { return false } self.deadline = nil return true }}
// Only the main actor installs tokens; deinit removes them after the last owner is gone.private final class DisplayObservers: @unchecked Sendable { private var entries: [(NotificationCenter, any NSObjectProtocol)] = []
@MainActor func append(center: NotificationCenter, token: any NSObjectProtocol) { entries.append((center, token)) }
deinit { for (center, token) in entries { center.removeObserver(token) } }}
@MainActorpublic final class Displays { private let observers = DisplayObservers() private let snapshot: @MainActor () throws -> [Display] private let now: @MainActor () -> ContinuousClock.Instant private let sleep: @MainActor (ContinuousClock.Instant) async throws -> Void private var debouncer = DisplayChangeDebouncer() private var timer: Task<Void, Never>? private var registration: DisplayReconfigurationRegistration? private var observationError: (any Error)? private var configuringDisplays: Set<CGDirectDisplayID> = [] private var configurationDeadline: ContinuousClock.Instant? private var configurationTimer: Task<Void, Never>? private static let configurationLimit: Duration = .milliseconds(500) private var publicationScheduled = false private var publicationGeneration: UInt64 = 0 private nonisolated static let changeSignposter = OSSignposter(subsystem: "com.parcel", category: "Platform") private var changeInterval: OSSignpostIntervalState? private var subscribers: [UUID: AsyncThrowingStream<[Display], any Error>.Continuation] = [:]
public convenience init() { self.init( snapshot: Self.enumerate, screenCenter: .default, workspaceCenter: NSWorkspace.shared.notificationCenter, reconfigurationCallbacks: .native ) }
init( snapshot: @escaping @MainActor () throws -> [Display], screenCenter: NotificationCenter, workspaceCenter: NotificationCenter, reconfigurationCallbacks: DisplayReconfigurationCallbacks? = nil, now: @escaping @MainActor () -> ContinuousClock.Instant = { ContinuousClock().now }, sleep: @escaping @MainActor (ContinuousClock.Instant) async throws -> Void = { try await ContinuousClock().sleep(until: $0) } ) { self.snapshot = snapshot self.now = now self.sleep = sleep observe(NSApplication.didChangeScreenParametersNotification, in: screenCenter, screenOnly: true) observe(NSWorkspace.willSleepNotification, in: workspaceCenter) observe(NSWorkspace.didWakeNotification, in: workspaceCenter) observe(NSWorkspace.screensDidSleepNotification, in: workspaceCenter) observe(NSWorkspace.screensDidWakeNotification, in: workspaceCenter) if let reconfigurationCallbacks { do { registration = try DisplayReconfigurationRegistration(callbacks: reconfigurationCallbacks) { [weak self] display, flags in DispatchQueue.main.async { [weak self] in self?.receiveReconfiguration(display: display, flags) } } } catch { observationError = error } } }
deinit { timer?.cancel() configurationTimer?.cancel() if let changeInterval { Self.changeSignposter.endInterval("display.change", changeInterval) } for continuation in subscribers.values { continuation.finish() } }
public func stop() throws { cancelPendingChange() configuringDisplays.removeAll() configurationDeadline = nil observationError = DisplayObservationError.stopped do { try registration?.stop() registration = nil } catch { observationError = error finishSubscribers(throwing: error) throw error } let active = subscribers.values subscribers.removeAll() for continuation in active { continuation.finish() } }
/// Frames use AppKit's screen coordinate space, in points. public func current() throws -> [Display] { if let observationError { throw observationError } return try snapshot() }
private static func enumerate() throws -> [Display] { try NSScreen.screens.map { screen in guard let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber else { throw DisplayEnumerationError.missingDisplayID } let displayID = number.uint32Value guard let reference = CGDisplayCreateUUIDFromDisplayID(displayID)?.takeRetainedValue() else { throw DisplayEnumerationError.missingDisplayUUID(displayID) } let bytes = CFUUIDGetUUIDBytes(reference) let id = UUID( uuid: ( bytes.byte0, bytes.byte1, bytes.byte2, bytes.byte3, bytes.byte4, bytes.byte5, bytes.byte6, bytes.byte7, bytes.byte8, bytes.byte9, bytes.byte10, bytes.byte11, bytes.byte12, bytes.byte13, bytes.byte14, bytes.byte15 )) return Display( id: id, frame: screen.frame, visibleFrame: screen.visibleFrame, scale: screen.backingScaleFactor, isBuiltIn: CGDisplayIsBuiltin(displayID) != 0 ) } }
/// Emits the current snapshot, then updates at reconfiguration completion or after screen-only changes settle. /// Keep this instance alive while consuming the stream. Observation and enumeration errors terminate it. public func changes() -> AsyncThrowingStream<[Display], any Error> { let id = UUID() let (stream, continuation) = AsyncThrowingStream<[Display], any Error>.makeStream( bufferingPolicy: .bufferingNewest(1)) continuation.onTermination = { [weak self] _ in Task { @MainActor [weak self] in self?.removeSubscriber(id) } } do { let snapshot = try current() subscribers[id] = continuation continuation.yield(snapshot) expireConfigurationIfDue() scheduleConfigurationCap() } catch { continuation.finish(throwing: error) } return stream }
private func observe(_ name: Notification.Name, in center: NotificationCenter, screenOnly: Bool = false) { let token = center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { if screenOnly { self?.scheduleScreenChange() } else { self?.scheduleActivityChange() } } } observers.append(center: center, token: token) }
func receiveReconfiguration(display: CGDirectDisplayID, _ flags: CGDisplayChangeSummaryFlags) { expireConfigurationIfDue() if flags.contains(.beginConfigurationFlag) { if configuringDisplays.isEmpty { cancelPendingChange() configurationDeadline = now().advanced(by: Self.configurationLimit) } configuringDisplays.insert(display) scheduleConfigurationCap() } else { configuringDisplays.remove(display) guard configuringDisplays.isEmpty else { return } cancelConfigurationTimer() configurationDeadline = nil cancelTimer() schedulePublication() } }
private func expireConfigurationIfDue() { guard let deadline = configurationDeadline, now() >= deadline else { return } configuringDisplays.removeAll() configurationDeadline = nil cancelConfigurationTimer() }
private func scheduleConfigurationCap() { guard !subscribers.isEmpty, configurationTimer == nil, let deadline = configurationDeadline else { return } let sleep = sleep configurationTimer = Task { @MainActor [weak self] in do { while self?.configurationDeadline == deadline { try Task.checkCancellation() try await sleep(deadline) guard !Task.isCancelled, let owner = self else { return } if owner.now() >= deadline { owner.expireConfigurationIfDue() owner.schedulePublication() return } } } catch is CancellationError { // Completion or releasing the last subscriber cancels the cap. } catch { guard !Task.isCancelled else { return } self?.finishSubscribers(throwing: error) } } }
private func cancelConfigurationTimer() { configurationTimer?.cancel() configurationTimer = nil }
private func scheduleActivityChange() { scheduleScreenChange() }
private func scheduleScreenChange() { expireConfigurationIfDue() guard !subscribers.isEmpty, configuringDisplays.isEmpty, !publicationScheduled else { return } beginChangeInterval() _ = debouncer.record(at: now()) guard timer == nil else { return } let sleep = sleep timer = Task { @MainActor [weak self] in do { while let deadline = self?.debouncer.deadline { try Task.checkCancellation() try await sleep(deadline) guard !Task.isCancelled, let owner = self else { return } if owner.debouncer.consumeIfDue(at: owner.now()) { owner.timer = nil owner.schedulePublication() return } } } catch is CancellationError { // Reconfiguration or releasing the last subscriber cancels the timer. } catch { guard !Task.isCancelled else { return } self?.finishSubscribers(throwing: error) } } }
private func schedulePublication() { guard !subscribers.isEmpty, !publicationScheduled else { return } beginChangeInterval() publicationScheduled = true let generation = publicationGeneration // Let AppKit refresh its screen cache and fold all per-display completions into one snapshot. DispatchQueue.main.async { [weak self] in guard let self, self.publicationGeneration == generation, self.publicationScheduled else { return } self.publicationScheduled = false guard self.configuringDisplays.isEmpty else { return } self.publishChange() } }
private func beginChangeInterval() { guard changeInterval == nil, Self.changeSignposter.isEnabled else { return } changeInterval = Self.changeSignposter.beginInterval("display.change") }
private func endChangeInterval() { guard let changeInterval else { return } Self.changeSignposter.endInterval("display.change", changeInterval) self.changeInterval = nil }
private func publishChange() { guard !subscribers.isEmpty else { return } defer { endChangeInterval() } do { let snapshot = try current() for continuation in subscribers.values { continuation.yield(snapshot) } } catch { finishSubscribers(throwing: error) } }
private func removeSubscriber(_ id: UUID) { subscribers.removeValue(forKey: id) if subscribers.isEmpty { cancelPendingChange() } }
private func cancelTimer() { timer?.cancel() timer = nil debouncer = DisplayChangeDebouncer() }
private func cancelPendingChange() { cancelTimer() cancelConfigurationTimer() publicationGeneration += 1 publicationScheduled = false endChangeInterval() }
private func finishSubscribers(throwing error: any Error) { cancelPendingChange() let active = subscribers.values subscribers.removeAll() for continuation in active { continuation.finish(throwing: error) } }}