internal import Foundation public enum SystemWindowPreferenceUnknownReason: Equatable, Sendable { case missingKey case malformedValue(description: String) } public enum SystemWindowPreferenceValue: Equatable, Sendable { case enabled case disabled case unknown(SystemWindowPreferenceUnknownReason) public var confirmedBoolOrNil: Bool? { switch self { case .enabled: true case .disabled: false case .unknown: nil } } } /// Stored preferences do not establish whether a feature is active on a particular display. public struct SystemWindowPreferencesSnapshot: Equatable, Sendable { public var stageManagerGloballyEnabled: SystemWindowPreferenceValue public var edgeDragTilingEnabled: SystemWindowPreferenceValue public var topDragTilingEnabled: SystemWindowPreferenceValue public var optionKeyTilingAcceleratorEnabled: SystemWindowPreferenceValue public init( stageManagerGloballyEnabled: SystemWindowPreferenceValue, edgeDragTilingEnabled: SystemWindowPreferenceValue, topDragTilingEnabled: SystemWindowPreferenceValue, optionKeyTilingAcceleratorEnabled: SystemWindowPreferenceValue ) { self.stageManagerGloballyEnabled = stageManagerGloballyEnabled self.edgeDragTilingEnabled = edgeDragTilingEnabled self.topDragTilingEnabled = topDragTilingEnabled self.optionKeyTilingAcceleratorEnabled = optionKeyTilingAcceleratorEnabled } } /// KVO observes other processes' changes; callers refresh after wake to catch missed updates. @MainActor public final class SystemWindowPreferences { public enum Key: String, CaseIterable, Sendable { case stageManagerGloballyEnabled = "GloballyEnabled" case edgeDragTiling = "EnableTilingByEdgeDrag" case topDragTiling = "EnableTopTilingByEdgeDrag" case optionKeyTilingAccelerator = "EnableTilingOptionAccelerator" } public enum InitializationError: Error, Equatable, Sendable { case suiteUnavailable(String) } public static let systemDomain = "com.apple.WindowManager" private let defaults: UserDefaults private var observer: PreferenceKeyObserver? private let notificationCenter: NotificationCenter private var notifications: [any NSObjectProtocol] = [] nonisolated static let changeNotifications: [Notification.Name] = [ UserDefaults.didChangeNotification, Notification.Name("com.apple.WindowManager.StageManagerEnablement"), Notification.Name("com.apple.ec.WindowManager.preferences"), Notification.Name("com.apple.ec.WindowManager.tilingPreferences"), ] private var latest: SystemWindowPreferencesSnapshot private var isStopped = false private var subscribers: [UUID: AsyncStream.Continuation] = [:] public convenience init() throws { try self.init(suiteName: Self.systemDomain) } public convenience init(suiteName: String) throws { try self.init(suiteName: suiteName, notificationCenter: DistributedNotificationCenter.default()) } init(suiteName: String, notificationCenter: NotificationCenter, observeKeys: Bool = true) throws { guard !suiteName.isEmpty, let defaults = UserDefaults(suiteName: suiteName) else { throw InitializationError.suiteUnavailable(suiteName) } self.defaults = defaults self.notificationCenter = notificationCenter self.latest = Self.read(from: defaults) if observeKeys { self.observer = PreferenceKeyObserver(defaults: defaults, keys: Key.allCases.map(\.rawValue)) { [weak self] in Task { @MainActor [weak self] in self?.handleExternalChange() } } } for name in Self.changeNotifications { notifications.append( notificationCenter.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in Task { @MainActor [weak self] in self?.handleExternalChange() } }) } latest = Self.read(from: defaults) } isolated deinit { observer?.stop() for notification in notifications { notificationCenter.removeObserver(notification) } for continuation in subscribers.values { continuation.finish() } } public func snapshot() -> SystemWindowPreferencesSnapshot { latest } public func refresh() { handleExternalChange() } public func changes() -> AsyncStream { let id = UUID() let (stream, continuation) = AsyncStream.makeStream( bufferingPolicy: .bufferingNewest(1)) continuation.onTermination = { [weak self] _ in Task { @MainActor [weak self] in self?.subscribers.removeValue(forKey: id) } } continuation.yield(latest) if isStopped { continuation.finish() } else { subscribers[id] = continuation } return stream } public func stop() { isStopped = true observer?.stop() observer = nil for notification in notifications { notificationCenter.removeObserver(notification) } notifications.removeAll() let active = subscribers.values subscribers.removeAll() for continuation in active { continuation.finish() } } private func handleExternalChange() { guard !isStopped else { return } let next = Self.read(from: defaults) guard next != latest else { return } latest = next for continuation in subscribers.values { continuation.yield(next) } } private static func read(from defaults: UserDefaults) -> SystemWindowPreferencesSnapshot { SystemWindowPreferencesSnapshot( stageManagerGloballyEnabled: parseValue(defaults.object(forKey: Key.stageManagerGloballyEnabled.rawValue)), edgeDragTilingEnabled: parseValue(defaults.object(forKey: Key.edgeDragTiling.rawValue)), topDragTilingEnabled: parseValue(defaults.object(forKey: Key.topDragTiling.rawValue)), optionKeyTilingAcceleratorEnabled: parseValue( defaults.object(forKey: Key.optionKeyTilingAccelerator.rawValue)) ) } private static func parseValue(_ raw: Any?) -> SystemWindowPreferenceValue { guard let raw else { return .unknown(.missingKey) } guard let number = raw as? NSNumber, let value = integralBool(number) else { return .unknown(.malformedValue(description: String(describing: raw))) } return value ? .enabled : .disabled } private static func integralBool(_ number: NSNumber) -> Bool? { guard number.doubleValue == Double(number.intValue) else { return nil } switch number.intValue { case 0: return false case 1: return true default: return nil } } } private final class PreferenceKeyObserver: NSObject, @unchecked Sendable { private let onChange: @Sendable () -> Void private let keys: [String] private weak var defaults: UserDefaults? private var isObserving = false // The callback can arrive on any thread and only hops to the main actor. init(defaults: UserDefaults, keys: [String], onChange: @escaping @Sendable () -> Void) { self.defaults = defaults self.keys = keys self.onChange = onChange super.init() for key in keys { defaults.addObserver(self, forKeyPath: key, options: [], context: nil) } isObserving = true } func stop() { guard isObserving, let defaults else { return } for key in keys { defaults.removeObserver(self, forKeyPath: key, context: nil) } isObserving = false self.defaults = nil } deinit { if isObserving, let defaults { for key in keys { defaults.removeObserver(self, forKeyPath: key, context: nil) } } } override func observeValue( forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey: Any]?, context: UnsafeMutableRawPointer? ) { onChange() } }