public import AppKit public import ParcelConfig public import ParcelCore public import ParcelEngine import ParcelPlatform import QuartzCore import os struct OverlayNotifications { let application: NotificationCenter let workspace: NotificationCenter @MainActor static var system: Self { Self(application: .default, workspace: NSWorkspace.shared.notificationCenter) } } @MainActor public final class OverlayController { public private(set) var configuration: MotionConfiguration public private(set) var accessibility: OverlayAccessibility public private(set) var focusModes: FocusModeConfiguration public var onSessionSuspended: (@MainActor () -> Void)? public var inspectionWindow: (@MainActor (WindowID) -> ManagedWindow?)? public var observedFocusedWindow: (@MainActor () -> WindowID?)? public var onDimmingNoticeCleared: (@MainActor () -> Void)? private var nativeProtectedWindows: [String: [OverlayWindow]] = [:] private let dimming: OverlayDimming private let onFailure: @MainActor (any Error) -> Void private let orderPanels: Bool private let usesDisplayLink: Bool private var privacyRead: Task? var pendingPrivacyRead: Task? { privacyRead } private var privacyRevision: UInt64 = 0 private var nativeDimmingWindows: [OverlayWindow]? private var nativeWindows: [UInt32: OverlayWindow]? private var nativeHighlightWindows: [UInt32: OverlayWindow]? private var requiresNativeHighlightWindows = false private var nativeReadPending = false private let windowReader: @Sendable () throws -> [PrivacyWindowInfo] private var frameRevision: UInt64 = 0 private var observedPrivacyFrames: [UInt32: (revision: UInt64, frame: CGRect)] = [:] private var privacySuspended = false private var cleanSpaceSuspended: Set = [] private var primaryDisplayHeight: CGFloat = 0 private var distributedObservers: [any NSObjectProtocol] = [] private(set) var privacyPanels: [String: PrivacyOverlayPanel] = [:] private(set) var backdrops: [String: CleanSpaceBackdrop] = [:] private let paletteSource: OverlayPaletteSource private var paletteObservation: UUID? private var frameClocks: [String: OverlayFrameClock] = [:] private var dirtyDisplays: Set = [] private var renderedSnapshots: [String: OverlaySnapshot] = [:] private var lastRenderTimes: [String: Double] = [:] private(set) var renderCounts: [String: Int] = [:] private var displaysInitialized = false private var trailingWindowRead = false private static let renderLog = OSLog(subsystem: "dev.vinnymac.parcel", category: "overlay") private var subscription: Task? private var observers: [(center: NotificationCenter, token: any NSObjectProtocol)] = [] private var snapshot: OverlaySnapshot? private var dragTarget: OverlayWindow? let dragLayout = DragLayoutController() let dividerHandle = DividerHandleController() private(set) var panels: [String: OverlayPanel] = [:] private(set) var focusLayers: [String: OverlayTileLayer] = [:] private var focusMotionCanvases: [String: OverlayHighlightCanvas] = [:] private let animationTime: @MainActor () -> Double private(set) var highlightCanvases: [String: OverlayHighlightCanvas] = [:] private(set) var ghostLayers: [String: [UInt32: OverlayTileLayer]] = [:] private(set) var hintLayers: [String: OverlayTileLayer] = [:] public convenience init( configuration: MotionConfiguration = MotionConfiguration(), focusModes: FocusModeConfiguration = FocusModeConfiguration(), accessibility: OverlayAccessibility = .system, brightness: (any OverlayBrightnessControlling)? = nil, color: (@MainActor () -> NSColor)? = nil, paletteSource: OverlayPaletteSource = .shared, onFailure: @escaping @MainActor (any Error) -> Void ) { self.init( configuration: configuration, focusModes: focusModes, accessibility: accessibility, brightness: brightness, color: color, paletteSource: paletteSource, notifications: .system, onFailure: onFailure) } init( configuration: MotionConfiguration = MotionConfiguration(), focusModes: FocusModeConfiguration = FocusModeConfiguration(), accessibility: OverlayAccessibility = .system, brightness: (any OverlayBrightnessControlling)? = nil, color: (@MainActor () -> NSColor)? = nil, paletteSource: OverlayPaletteSource = .shared, notifications: OverlayNotifications, animationTime: @escaping @MainActor () -> Double = { CACurrentMediaTime() }, windowReader: @escaping @Sendable () throws -> [PrivacyWindowInfo] = { try PrivacyWindowInfo.read() }, orderPanels: Bool = true, usesDisplayLink: Bool = true, onFailure: @escaping @MainActor (any Error) -> Void ) { self.configuration = configuration self.focusModes = focusModes self.accessibility = accessibility self.paletteSource = color.map { color in OverlayPaletteSource { _, _ in .system(activeBorder: color()) } } ?? paletteSource self.animationTime = animationTime self.onFailure = onFailure self.orderPanels = orderPanels self.usesDisplayLink = usesDisplayLink self.windowReader = windowReader dimming = OverlayDimming(brightness: brightness ?? PlatformOverlayBrightness(), onFailure: onFailure) dimming.onChange = { [weak self] in self?.requestRender() } paletteObservation = self.paletteSource.observe { [weak self] in guard let self else { return } for panel in privacyPanels.values { panel.invalidateAppearance() } refreshDragLayout() dividerChanged(dividerHandle.edge) requestRender() } dimming.launch(enabled: configuration.enabled && configuration.experimentalDimming) observe(NSApplication.willTerminateNotification, center: notifications.application) { $0.stop() } observe(NSApplication.didChangeScreenParametersNotification, center: notifications.application) { $0.refresh() } observe(NSWorkspace.activeSpaceDidChangeNotification, center: notifications.workspace) { $0.privacyRevision += 1 $0.privacyRead?.cancel() $0.nativeHighlightWindows = nil for id in $0.panels.keys { $0.removeLayers(display: id) } $0.clearTransientLayers() $0.dragTarget = nil $0.refreshPanelVisibility() } observe(NSWorkspace.willSleepNotification, center: notifications.workspace) { $0.suspendPrivacy() } observe(NSWorkspace.sessionDidResignActiveNotification, center: notifications.workspace) { $0.suspendPrivacy() } observe(NSWorkspace.didWakeNotification, center: notifications.workspace) { $0.resumePrivacy() } observe(NSWorkspace.sessionDidBecomeActiveNotification, center: notifications.workspace) { $0.resumePrivacy() } observeDistributed(Notification.Name("com.apple.screenIsLocked")) { $0.suspendPrivacy() } observeDistributed(Notification.Name("com.apple.screenIsUnlocked")) { $0.resumePrivacy() } #if DEBUG let environment = ProcessInfo.processInfo.environment if let notification = Self.simulatedSleepNotification(environment: environment) { observeDistributed(notification) { $0.suspendPrivacy() } } if let notification = Self.simulatedWakeNotification(environment: environment) { observeDistributed(notification) { $0.resumePrivacy() } } #endif observe( NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, center: notifications.workspace ) { $0.update(configuration: $0.configuration, accessibility: .system) } } isolated deinit { subscription?.cancel() privacyRead?.cancel() for clock in frameClocks.values { clock.stop() } if let paletteObservation { paletteSource.removeObserver(paletteObservation) } dimming.restore() for panel in panels.values { panel.close() } for panel in privacyPanels.values { panel.close() } for panel in backdrops.values { panel.close() } for observer in distributedObservers { DistributedNotificationCenter.default().removeObserver(observer) } for observer in observers { observer.center.removeObserver(observer.token) } } public func start( snapshots: AsyncStream, cornerRadius: @escaping @MainActor (WindowID) -> CGFloat = { _ in 10 } ) { subscription?.cancel() subscription = Task { [weak self] in for await value in snapshots { guard !Task.isCancelled, let self else { return } consume(value, cornerRadius: cornerRadius) } } } public func consume( _ value: EngineSnapshot, cornerRadius: @MainActor (WindowID) -> CGFloat = { _ in 10 } ) { requiresNativeHighlightWindows = true if !displaysInitialized { setDisplays(Self.systemDisplays(), primaryDisplayHeight: NSScreen.screens.first?.frame.height ?? 0) } update(OverlaySnapshot(value, transitions: configuration.transitions, cornerRadius: cornerRadius)) } public func setDisplays(_ displays: [OverlayDisplay], primaryDisplayHeight: CGFloat) { dividerHandle.clear() precondition(Set(displays.map(\.id)).count == displays.count) displaysInitialized = true self.primaryDisplayHeight = primaryDisplayHeight for id in panels.keys where !displays.contains(where: { $0.id == id }) { frameClocks.removeValue(forKey: id)?.stop() dirtyDisplays.remove(id) renderedSnapshots.removeValue(forKey: id) lastRenderTimes.removeValue(forKey: id) removeLayers(display: id) panels.removeValue(forKey: id)?.close() privacyPanels.removeValue(forKey: id)?.close() backdrops.removeValue(forKey: id)?.close() for workspace in snapshot?.privacyWorkspaces ?? [] where workspace.key.display.rawValue == id { cleanSpaceSuspended.insert(workspace.key) } } for display in displays { if let panel = panels[display.id] { if panel.display != display { removeLayers(display: display.id) } panel.update(display: display, primaryDisplayHeight: primaryDisplayHeight) } else { let panel = OverlayPanel(display: display, primaryDisplayHeight: primaryDisplayHeight) panel.onAppearanceChanged = { [weak self] in self?.paletteSource.invalidate() } panels[display.id] = panel } frameClocks.removeValue(forKey: display.id)?.stop() if usesDisplayLink, let screen = panels[display.id]?.screen { frameClocks[display.id] = OverlayFrameClock(screen: screen) { [weak self] timestamp in self?.renderPendingDisplays(at: timestamp, displays: [display.id]) } } } refreshDragLayout() requestRender() } public func update(_ next: OverlaySnapshot) { let interval = ParcelSignposts.beginIfEnabled(.overlayUpdate, value: UInt64(next.windows.count)) defer { ParcelSignposts.endIfStarted(.overlayUpdate, interval) } if snapshot?.context != next.context { clearTransientLayers() dragTarget = nil } let previous = snapshot snapshot = next cleanSpaceSuspended.formIntersection(Set(next.privacyWorkspaces.filter(\.cleanSpace).map(\.key))) if previous?.context != next.context { privacyRevision += 1 nativeProtectedWindows = [:] nativeDimmingWindows = nil nativeWindows = nil nativeHighlightWindows = nil observedPrivacyFrames = [:] } for (id, frame) in next.readbackFrames where previous?.context != next.context || previous?.readbackFrames[id] != frame { frameRevision += 1 observedPrivacyFrames[id] = (frameRevision, frame) } if !next.privacyWorkspaces.contains(where: \.noPeek), !(configuration.enabled && configuration.experimentalDimming) { onDimmingNoticeCleared?() } if previous?.context != next.context || previous?.focusedWindow != next.focusedWindow || previous.map({ Set($0.windows.map(\.id)) }) != Set(next.windows.map(\.id)) || privacyMembershipChanged(from: previous?.privacyWorkspaces ?? [], to: next.privacyWorkspaces) || previous.map({ Set($0.highlightCutouts.map(\.id)) }) != Set(next.highlightCutouts.map(\.id)) { nativeProtectedWindows = [:] privacyRevision += 1 if requiresNativeHighlightWindows { refreshPrivacyWindows() } } requestRender() } private func privacyMembershipChanged(from previous: [OverlayPrivacyWorkspace], to next: [OverlayPrivacyWorkspace]) -> Bool { guard previous.count == next.count else { return true } return zip(previous, next).contains { old, new in old.key != new.key || old.noPeek != new.noPeek || old.cleanSpace != new.cleanSpace || old.focusedWindow != new.focusedWindow || Set(old.protectedWindows.map(\.id)) != Set(new.protectedWindows.map(\.id)) } } public func update( configuration: MotionConfiguration, accessibility: OverlayAccessibility, focusModes: FocusModeConfiguration? = nil ) { self.configuration = configuration if let focusModes { self.focusModes = focusModes } let appearanceChanged = self.accessibility != accessibility self.accessibility = accessibility if appearanceChanged { paletteSource.invalidate() } if !configuration.dropHints { dragLayout.clear() } refreshDragLayout() dividerChanged(dividerHandle.edge) clearHints() clearGhosts() requestRender() if let dragTarget { dragChanged(target: dragTarget) } if requiresNativeHighlightWindows { refreshPrivacyWindows() } } /// Pass only a divider returned by the engine's native pointer hit test, or nil to dismiss. public func dividerChanged(_ edge: TileEdge?) { guard !privacySuspended else { dividerHandle.clear(); return } if !displaysInitialized { setDisplays(Self.systemDisplays(), primaryDisplayHeight: NSScreen.screens.first?.frame.height ?? 0) } dividerHandle.update( edge, displays: panels.values.map(\.display), primaryHeight: primaryDisplayHeight, configuration: configuration, accessibility: accessibility, paletteSource: paletteSource, orderPanels: orderPanels) } public func legacyDragChanged(target: OverlayWindow?) { guard dragLayout.preview == nil else { return } dragChanged(target: target) } public func layoutPreviewChanged(_ preview: DragLayoutPreview?) { if preview != nil { dragTarget = nil clearHints() refreshPanelVisibility() } guard !privacySuspended else { dragLayout.clear(); return } if !displaysInitialized { setDisplays(Self.systemDisplays(), primaryDisplayHeight: NSScreen.screens.first?.frame.height ?? 0) } renderDragLayout(preview) } private func refreshDragLayout() { renderDragLayout(dragLayout.preview) } private func renderDragLayout(_ preview: DragLayoutPreview?) { let height = NSScreen.screens.first?.frame.height ?? primaryDisplayHeight let usable = Dictionary( uniqueKeysWithValues: Self.systemDisplays().compactMap { display -> (String, CGRect)? in guard let screen = NSScreen.screens.first(where: { screen in screen.frame.minX == display.frame.minX && height - screen.frame.maxY == display.frame.minY }) else { return nil } let frame = screen.visibleFrame return ( display.id, CGRect(x: frame.minX, y: height - frame.maxY, width: frame.width, height: frame.height) ) }) dragLayout.update( preview, displays: panels.values.map(\.display), usable: usable, primaryHeight: primaryDisplayHeight, configuration: configuration, accessibility: accessibility, paletteSource: paletteSource, orderPanels: orderPanels) } public func dragChanged(target: OverlayWindow?) { if target == nil { dragLayout.clear() } dragTarget = target clearHints() guard configuration.enabled, configuration.dropHints, let target else { refreshPanelVisibility() return } for (id, panel) in panels where panel.display.frame.intersects(target.frame) { let tile = makeTile(panel: panel, filled: true) hintLayers[id] = tile tile.move( to: panel.display.localFrame(target.frame), radius: chromeRadius(target), motion: instantMotion, token: .glance) } refreshPanelVisibility() } /// Velocity is in global points per second, with positive y pointing down. public func dropped(velocity: CGVector) { precondition(velocity.dx.isFinite && velocity.dy.isFinite) dragTarget = nil dragLayout.clear() let motion = currentMotion for (id, tile) in hintLayers { let frame = tile.layer.frame tile.move( to: frame, radius: tile.layer.cornerRadius, motion: motion, token: .drop, from: frame.offsetBy(dx: -velocity.dx * 0.02, dy: velocity.dy * 0.02), velocity: CGVector(dx: velocity.dx, dy: -velocity.dy), transient: true ) { [weak self, weak tile] in guard let self, hintLayers[id] === tile else { return } tile?.layer.removeFromSuperlayer() hintLayers.removeValue(forKey: id) refreshPanelVisibility() } } refreshPanelVisibility() } public func refused(_ direction: Direction) { let motion = OverlayMotion(configuration: configuration, accessibility: accessibility, geometry: false) for tile in focusLayers.values { if tile.focusMotionID != nil { tile.fadeFocusFeedback(motion: motion) } else { tile.move(to: tile.layer.frame, radius: tile.layer.cornerRadius, motion: motion, token: .fade) } } } public var activeAnimationCount: Int { let tiles = Array(focusLayers.values) + Array(hintLayers.values) + ghostLayers.values.flatMap(\.values) return tiles.reduce(0) { $0 + ($1.layer.animationKeys()?.count ?? 0) } } public var privacyPanelCount: Int { privacyPanels.count } public var cleanSpaceBackdropCount: Int { backdrops.count } public func highlightAudit() -> OverlayHighlightAudit { OverlayHighlightAudit( ready: snapshot != nil && dirtyDisplays.isEmpty && !privacySuspended && !nativeReadPending && (!requiresNativeHighlightWindows || nativeHighlightWindows != nil), displays: highlightCanvases.keys.sorted().compactMap { id in guard let canvas = highlightCanvases[id], let display = panels[id]?.display else { return nil } let focused = focusLayers[id] == nil ? [] : snapshot?.focusedWindow.map { [$0] } ?? [] return OverlayHighlightAudit.Display( id: id, frame: display.frame, cutouts: canvas.cutouts, gaps: canvas.gaps, outlinedWindows: (Array(canvas.inactive.keys) + focused).sorted(), borderFrames: canvas.inactive.mapValues { $0.layer.frame }.merging( Dictionary( uniqueKeysWithValues: focused.compactMap { window in focusLayers[id].map { (window, $0.layer.frame) } }), uniquingKeysWith: { _, latest in latest }), renderCount: renderCounts[id, default: 0]) }) } public func stop() { dividerHandle.clear() dragLayout.clear() subscription?.cancel() subscription = nil for clock in frameClocks.values { clock.stop() } frameClocks = [:] dirtyDisplays = [] renderedSnapshots = [:] if let paletteObservation { paletteSource.removeObserver(paletteObservation) } paletteObservation = nil snapshot = nil dimming.restore() clearPrivacy() for observer in distributedObservers { DistributedNotificationCenter.default().removeObserver(observer) } distributedObservers = [] for id in panels.keys { removeLayers(display: id) } for panel in panels.values { panel.close() } panels = [:] snapshot = nil dragTarget = nil for observer in observers { observer.center.removeObserver(observer.token) } observers = [] } private func requestRender(displays: Set? = nil) { let affected = displays ?? Set(panels.keys) guard !affected.isEmpty else { renderPrivacy() return } dirtyDisplays.formUnion(affected) for id in affected { frameClocks[id]?.request() } } func renderPendingDisplays(at timestamp: Double, displays: Set? = nil) { precondition(timestamp.isFinite) for id in dirtyDisplays.intersection(displays ?? Set(panels.keys)).sorted() { guard lastRenderTimes[id].map({ timestamp > $0 }) ?? true else { frameClocks[id]?.request() continue } dirtyDisplays.remove(id) frameClocks[id]?.pause() lastRenderTimes[id] = timestamp let interval = OSSignpostID(log: Self.renderLog) os_signpost( .begin, log: Self.renderLog, name: "overlay.render", signpostID: interval, "display=%{public}@", id) renderPrivacy(displays: [id]) renderFocus(displays: [id]) if let next = snapshot, let previous = renderedSnapshots[id], previous.context == next.context, configuration.enabled, configuration.transitions == .ghost { renderGhosts(previous: previous, next: next, displays: [id]) } else { for tile in ghostLayers.removeValue(forKey: id)?.values ?? [:].values { tile.cancel() tile.layer.removeFromSuperlayer() } } renderedSnapshots[id] = snapshot restyleTransientLayers(display: id) renderCounts[id, default: 0] += 1 os_signpost(.end, log: Self.renderLog, name: "overlay.render", signpostID: interval) } refreshPanelVisibility() } private func restyleTransientLayers(display id: String) { guard let panel = panels[id] else { return } let palette = paletteSource.resolve(for: panel.effectiveAppearance, accessibility: accessibility) for tile in ghostLayers[id]?.values ?? [:].values { tile.recolor(palette.activeBorder) } hintLayers[id]?.recolor( palette.activeBorder, fillOpacity: OverlayStyle(accessibility: accessibility).fillOpacity) } private func renderPrivacy(displays: Set? = nil) { guard let snapshot else { return } let windows = (nativeDimmingWindows ?? snapshot.windows).map(latestPrivacyWindow) let solid = accessibility.reduceTransparency || accessibility.increaseContrast var offsets: [UInt32: Float] = [:] if !privacySuspended, configuration.enabled && configuration.experimentalDimming, let focused = snapshot.focusedWindow { for window in windows where window.id != focused { offsets[window.id] = -0.25 } } if !privacySuspended, !solid { for workspace in snapshot.privacyWorkspaces where workspace.noPeek && !workspace.cleanSpace { guard let display = panels[workspace.key.display.rawValue]?.display else { continue } let protected = Set(privacyCutouts(in: workspace).map(\.id)) for window in windows where display.frame.contains(window.focusFrame) && !protected.contains(window.id) { offsets[window.id] = -Float(focusModes.noPeekLevel) } } } dimming.update(offsets: offsets) for (id, panel) in panels where displays?.contains(id) ?? true { let workspace = snapshot.privacyWorkspaces.first { $0.key.display.rawValue == id } let noPeek = workspace?.noPeek == true && !privacySuspended let clean = workspace.map { $0.cleanSpace && !cleanSpaceSuspended.contains($0.key) } == true && !privacySuspended guard noPeek || clean else { privacyPanels.removeValue(forKey: id)?.close() backdrops.removeValue(forKey: id)?.close() continue } let palette = paletteSource.resolve(for: panel.effectiveAppearance, accessibility: accessibility) let backdropColor = palette.cleanSpaceBackdrop.map(OverlayPalette.appKitColor) ?? focusModes.cleanSpaceColor.backdropColor let privacy = privacyPanels[id] ?? PrivacyOverlayPanel( display: panel.display, primaryDisplayHeight: primaryDisplayHeight) privacyPanels[id] = privacy let cutouts = workspace.map { privacyCutouts(in: $0).map(\.focusFrame) } ?? [] privacy.update( display: panel.display, primaryDisplayHeight: primaryDisplayHeight, cutouts: cutouts, color: clean ? backdropColor : .black, opacity: clean ? 1 : CGFloat(focusModes.noPeekLevel), blurred: noPeek && focusModes.noPeekBlur && !solid && !clean, alreadyDimmedFrames: !solid && !clean && dimming.usesCompositor ? windows.filter { offsets[$0.id] == -Float(focusModes.noPeekLevel) }.map(\.focusFrame) : []) if orderPanels, !privacy.isVisible { privacy.orderFrontRegardless() } if clean { let backdrop = backdrops[id] ?? CleanSpaceBackdrop( display: panel.display, primaryDisplayHeight: primaryDisplayHeight, color: backdropColor) backdrops[id] = backdrop backdrop.update( display: panel.display, primaryDisplayHeight: primaryDisplayHeight, color: backdropColor) if orderPanels, !backdrop.isVisible { backdrop.orderFrontRegardless() } } else { backdrops.removeValue(forKey: id)?.close() } } } private func resumePrivacy() { privacySuspended = false requestRender() if requiresNativeHighlightWindows { refreshPrivacyWindows() } } private func suspendPrivacy() { dividerHandle.clear() dragLayout.clear() privacySuspended = true cleanSpaceSuspended.formUnion(snapshot?.privacyWorkspaces.map(\.key) ?? []) clearPrivacy() dimming.restore() for id in panels.keys { removeLayers(display: id) } refreshPanelVisibility() onSessionSuspended?() } private func clearPrivacy() { privacyRevision += 1 privacyRead?.cancel() trailingWindowRead = false nativeReadPending = false nativeDimmingWindows = nil nativeWindows = nil nativeHighlightWindows = nil observedPrivacyFrames = [:] nativeProtectedWindows = [:] for panel in privacyPanels.values { panel.close() } for panel in backdrops.values { panel.close() } privacyPanels = [:] backdrops = [:] } private func privacyCutouts(in workspace: OverlayPrivacyWorkspace) -> [OverlayWindow] { let focused = workspace.focusedWindow.flatMap { id in nativeWindows.map { $0[id] } ?? snapshot?.windows.first { $0.id == id } } let auxiliaries = nativeWindows.map { windows in workspace.protectedWindows.compactMap { windows[$0.id] } } ?? workspace.protectedWindows return ((focused.map { [$0] } ?? []) + auxiliaries + (nativeProtectedWindows[workspace.key.display.rawValue] ?? [])).map(latestPrivacyWindow) } private func latestPrivacyWindow(_ window: OverlayWindow) -> OverlayWindow { guard let frame = observedPrivacyFrames[window.id]?.frame else { return window } return OverlayWindow(id: window.id, frame: frame, cornerRadius: window.cornerRadius) } public func observePrivacyFrame(_ observed: WindowFrame) { precondition(observed.frame.isValid) guard let snapshot, needsWindowRead, !privacySuspended else { return } let id = observed.window.rawValue let previous = observedPrivacyFrames[id]?.frame ?? nativeWindows?[id]?.focusFrame ?? snapshot.windows.first { $0.id == id }?.focusFrame ?? snapshot.highlightCutouts.first { $0.id == id }?.focusFrame ?? snapshot.privacyWorkspaces.flatMap(\.protectedWindows).first { $0.id == id }?.focusFrame let frame = observed.frame let rectangle = CGRect(x: frame.minX, y: frame.minY, width: frame.size.width, height: frame.size.height) guard previous != rectangle else { return } frameRevision += 1 observedPrivacyFrames[id] = (frameRevision, rectangle) let affected = Set( panels.compactMap { id, panel in panel.display.frame.intersects(rectangle) || previous.map(panel.display.frame.intersects) == true ? id : nil }) requestRender(displays: affected) } private var needsWindowRead: Bool { configuration.highlight != .none || snapshot?.privacyWorkspaces.isEmpty == false || (configuration.enabled && configuration.experimentalDimming) } public func refreshPrivacyWindows() { guard let snapshot, needsWindowRead, !privacySuspended else { return } if privacyRead != nil { trailingWindowRead = true return } let revision = privacyRevision let readFrameRevision = frameRevision requiresNativeHighlightWindows = true nativeReadPending = true for canvas in Array(highlightCanvases.values) + Array(focusMotionCanvases.values) { withoutImplicitAnimations { canvas.layer.isHidden = true } } if nativeHighlightWindows == nil { requestRender() } let reader = windowReader privacyRead = Task { [weak self] in let result = await Task.detached { Result { try reader() } }.value guard let self else { return } privacyRead = nil nativeReadPending = false defer { if trailingWindowRead { trailingWindowRead = false refreshPrivacyWindows() } } guard !Task.isCancelled, privacyRevision == revision else { return } switch result { case .success(let windows): // Native focus may change while the window-server read is in flight. let focused = observedFocusedWindow.map { $0()?.rawValue } ?? snapshot.focusedWindow applyPrivacyWindows(windows, focusedWindow: focused, readFrameRevision: readFrameRevision) case .failure(let error): nativeHighlightWindows = nil nativeWindows = [:] nativeDimmingWindows = [] nativeProtectedWindows = [:] observedPrivacyFrames = [:] requestRender() onFailure(OverlayWindowReadError(underlying: error)) } } } func applyPrivacyWindows( _ windows: [PrivacyWindowInfo], focusedWindow: UInt32?, readFrameRevision: UInt64 = .max ) { guard let snapshot, !privacySuspended else { return } nativeReadPending = false observedPrivacyFrames = observedPrivacyFrames.filter { $0.value.revision > readFrameRevision } let ownPID = ProcessInfo.processInfo.processIdentifier nativeWindows = Dictionary( uniqueKeysWithValues: windows.map { ($0.id, OverlayWindow(id: $0.id, frame: $0.frame)) }) let decorations = Set(panels.values.compactMap { UInt32(exactly: $0.windowNumber) }) .union(privacyPanels.values.compactMap { UInt32(exactly: $0.windowNumber) }) .union(backdrops.values.compactMap { UInt32(exactly: $0.windowNumber) }) .union( [dividerHandle.panel].compactMap { panel in panel.flatMap { UInt32(exactly: $0.windowNumber) } }) // Exclude only our transparent canvases, not Parcel's own settings or other window content. nativeHighlightWindows = Dictionary( uniqueKeysWithValues: windows.compactMap { window in guard !decorations.contains(window.id) else { return nil } return (window.id, OverlayWindow(id: window.id, frame: window.frame)) }) nativeDimmingWindows = windows.compactMap { guard $0.layer == 0, $0.pid != ownPID else { return nil } return OverlayWindow(id: $0.id, frame: $0.frame) } nativeProtectedWindows = [:] if let focusedWindow, let active = windows.first(where: { $0.id == focusedWindow }) { let knownAuxiliaries = Dictionary( uniqueKeysWithValues: windows.compactMap { window -> (UInt32, Bool)? in guard window.pid == active.pid, let facts = inspectionWindow?(WindowID(rawValue: window.id)) else { return nil } return (window.id, PrivacyWindowInfo.isAuxiliary(role: facts.role, subrole: facts.subrole)) }) let protected = PrivacyWindowInfo.protectedWindows( from: windows, activePID: active.pid, focusedWindow: focusedWindow, knownAuxiliaries: knownAuxiliaries) for workspace in snapshot.privacyWorkspaces { let id = workspace.key.display.rawValue guard let display = panels[id]?.display else { continue } nativeProtectedWindows[id] = protected.filter { display.frame.intersects($0.frame) } } } requestRender() } private var currentMotion: OverlayMotion { OverlayMotion(configuration: configuration, accessibility: accessibility) } private var instantMotion: OverlayMotion { var configuration = configuration configuration.enabled = false return OverlayMotion(configuration: configuration, accessibility: accessibility) } private func highlightWindow(_ window: OverlayWindow) -> OverlayWindow? { if let nativeHighlightWindows, nativeHighlightWindows[window.id] == nil { return nil } let frame = observedPrivacyFrames[window.id]?.frame ?? nativeHighlightWindows?[window.id]?.focusFrame ?? window.focusFrame return OverlayWindow( id: window.id, frame: frame, cornerRadius: paletteSource.borderRadius ?? window.cornerRadius) } private func chromeRadius(_ window: OverlayWindow) -> CGFloat { min(paletteSource.borderRadius ?? window.cornerRadius, window.frame.width / 2, window.frame.height / 2) } private func renderFocus(displays: Set? = nil) { let windows = snapshot?.windows.compactMap(highlightWindow) ?? [] let focused = windows.first { $0.id == snapshot?.focusedWindow } let nativeCutouts = nativeHighlightWindows.map { Array($0.values) } ?? [] let protected = snapshot?.privacyWorkspaces.flatMap { privacyCutouts(in: $0) } ?? [] let cutouts = (nativeCutouts + (snapshot?.highlightCutouts ?? []) + protected).compactMap(highlightWindow) + observedPrivacyFrames.map { OverlayWindow(id: $0.key, frame: $0.value.frame) } + windows let plan = configuration.transitions == .glide && currentMotion.behavior == .animate ? snapshot?.focusedMotionPlan : nil for (id, panel) in panels where displays?.contains(id) ?? true { let palette = paletteSource.resolve(for: panel.effectiveAppearance, accessibility: accessibility) guard configuration.highlight != .none, let snapshot, !privacySuspended, !requiresNativeHighlightWindows || nativeHighlightWindows != nil else { focusLayers.removeValue(forKey: id)?.cancel() focusMotionCanvases.removeValue(forKey: id)?.layer.removeFromSuperlayer() highlightCanvases.removeValue(forKey: id)?.layer.removeFromSuperlayer() continue } let canvas = highlightCanvases[id] ?? OverlayHighlightCanvas(parent: panel.canvas) highlightCanvases[id] = canvas // Commit the outline and its content protection together, including shared-plan geometry. withoutImplicitAnimations { canvas.layer.isHidden = nativeReadPending canvas.update( display: panel.display, windows: windows, focusedWindow: snapshot.focusedWindow, cutouts: cutouts, configuration: configuration, accessibility: accessibility, palette: palette, paletteVersion: paletteSource.version) guard let focused, panel.display.frame.intersects(plan?.plan.request.screen.overlayRectangle ?? focused.focusFrame) else { let tile = focusLayers.removeValue(forKey: id) tile?.cancel() tile?.layer.removeFromSuperlayer() focusMotionCanvases.removeValue(forKey: id)?.layer.removeFromSuperlayer() if canvas.inactive.isEmpty { highlightCanvases.removeValue(forKey: id)?.layer.removeFromSuperlayer() } return } let tile = focusLayers[id] ?? OverlayTileLayer(parent: canvas.layer) focusLayers[id] = tile if let plan { do { prepareFocusMotion( tile, panel: panel, cutouts: cutouts.filter { $0.id != focused.id }, palette: palette) try tile.follow( plan: plan.plan, id: plan.id, display: panel.display, radius: focused.cornerRadius, at: animationTime()) } catch { tile.cancel() tile.layer.removeFromSuperlayer() focusLayers[id] = nil focusMotionCanvases.removeValue(forKey: id)?.layer.removeFromSuperlayer() if canvas.inactive.isEmpty { highlightCanvases.removeValue(forKey: id)?.layer.removeFromSuperlayer() } onFailure(error) return } } else { let wasFollowing = tile.focusMotionID != nil if wasFollowing { tile.cancel() } if focusMotionCanvases[id] != nil { tile.layer.mask = nil canvas.layer.addSublayer(tile.layer) focusMotionCanvases.removeValue(forKey: id)?.layer.removeFromSuperlayer() } let frame = panel.display.localFrame(focused.focusFrame) if wasFollowing || tile.layer.frame != frame || tile.layer.cornerRadius != focused.cornerRadius { tile.place(at: frame, radius: focused.cornerRadius) } let lag = max( abs(tile.layer.frame.minX - frame.minX), abs(tile.layer.frame.minY - frame.minY), abs(tile.layer.frame.width - frame.width), abs(tile.layer.frame.height - frame.height)) os_signpost( .event, log: Self.renderLog, name: "overlay.border.lag", "window=%u lag=%f", focused.id, lag) } tile.styleFocusHighlight( OverlayHighlightStyle(configuration: configuration, accessibility: accessibility, active: true), palette: palette, version: paletteSource.version, scale: panel.display.scale, at: animationTime()) } } } private func prepareFocusMotion( _ tile: OverlayTileLayer, panel: OverlayPanel, cutouts: [OverlayWindow], palette: OverlayPalette ) { let canvas = focusMotionCanvases[panel.display.id] ?? OverlayHighlightCanvas(parent: panel.canvas) canvas.layer.isHidden = nativeReadPending canvas.update( display: panel.display, windows: [], focusedWindow: nil, cutouts: cutouts, configuration: configuration, accessibility: accessibility, palette: palette, paletteVersion: paletteSource.version) tile.layer.contentsScale = panel.display.scale if tile.layer.superlayer !== canvas.layer { canvas.layer.addSublayer(tile.layer) } focusMotionCanvases[panel.display.id] = canvas } private func renderGhosts(previous: OverlaySnapshot, next: OverlaySnapshot, displays: Set) { let interval = ParcelSignposts.beginIfEnabled(.ghostRender, value: UInt64(next.windows.count)) defer { ParcelSignposts.endIfStarted(.ghostRender, interval) } let old = Dictionary(uniqueKeysWithValues: previous.windows.map { ($0.id, $0) }) let visible = Set(next.windows.map(\.id)) for (display, tiles) in ghostLayers where displays.contains(display) { for (id, tile) in tiles where !visible.contains(id) { tile.cancel() tile.layer.removeFromSuperlayer() ghostLayers[display]?.removeValue(forKey: id) } } for (index, window) in next.windows.sorted(by: { $0.id < $1.id }).enumerated() { guard let before = old[window.id], before.frame != window.frame else { continue } for (id, panel) in panels where displays.contains(id) && (panel.display.frame.intersects(before.frame) || panel.display.frame.intersects(window.frame)) { let existing = ghostLayers[id]?[window.id] let tile = existing ?? makeTile(panel: panel, filled: false) ghostLayers[id, default: [:]][window.id] = tile tile.style( OverlayStyle(accessibility: accessibility), color: paletteSource.resolve(for: panel.effectiveAppearance, accessibility: accessibility) .activeBorder, scale: panel.display.scale, filled: false) tile.move( to: panel.display.localFrame(window.frame), radius: chromeRadius(window), motion: currentMotion, token: .shuffle, from: existing == nil ? panel.display.localFrame(before.frame) : nil, staggerIndex: index, transient: true ) { [weak self, weak tile] in guard let self, ghostLayers[id]?[window.id] === tile else { return } tile?.layer.removeFromSuperlayer() ghostLayers[id]?.removeValue(forKey: window.id) refreshPanelVisibility() } } } } private func makeTile(panel: OverlayPanel, filled: Bool) -> OverlayTileLayer { let tile = OverlayTileLayer(parent: panel.canvas) tile.style( OverlayStyle(accessibility: accessibility), color: paletteSource.resolve(for: panel.effectiveAppearance, accessibility: accessibility).activeBorder, scale: panel.display.scale, filled: filled) return tile } private func clearHints() { for tile in hintLayers.values { tile.cancel() tile.layer.removeFromSuperlayer() } hintLayers = [:] } private func clearGhosts() { for tiles in ghostLayers.values { for tile in tiles.values { tile.cancel() tile.layer.removeFromSuperlayer() } } ghostLayers = [:] } private func clearTransientLayers() { dividerHandle.clear() dragLayout.clear() clearHints() clearGhosts() } private func removeLayers(display: String) { focusLayers.removeValue(forKey: display)?.cancel() focusMotionCanvases.removeValue(forKey: display)?.layer.removeFromSuperlayer() highlightCanvases.removeValue(forKey: display)?.layer.removeFromSuperlayer() hintLayers.removeValue(forKey: display)?.cancel() for tile in ghostLayers.removeValue(forKey: display)?.values ?? [UInt32: OverlayTileLayer]().values { tile.cancel() } panels[display]?.canvas.sublayers = nil } private func refreshPanelVisibility() { guard orderPanels else { return } for panel in panels.values { if panel.canvas.sublayers?.isEmpty == false { if !panel.isVisible { panel.orderFrontRegardless() } } else if panel.isVisible { panel.orderOut(nil) } } } private func refresh() { setDisplays(Self.systemDisplays(), primaryDisplayHeight: NSScreen.screens.first?.frame.height ?? 0) if let dragTarget { dragChanged(target: dragTarget) } if requiresNativeHighlightWindows { refreshPrivacyWindows() } } #if DEBUG static func simulatedSleepNotification(environment: [String: String]) -> Notification.Name? { simulatedSessionNotification("sleep", environment: environment) } static func simulatedWakeNotification(environment: [String: String]) -> Notification.Name? { simulatedSessionNotification("wake", environment: environment) } private static func simulatedSessionNotification( _ event: String, environment: [String: String] ) -> Notification.Name? { guard environment["PARCEL_E2E"] == "1", let token = environment["PARCEL_E2E_TOKEN"], !token.isEmpty else { return nil } return Notification.Name("dev.vinnymac.parcel.e2e.\(token).\(event)") } #endif private func observeDistributed( _ name: Notification.Name, action: @escaping @MainActor (OverlayController) -> Void ) { let token = DistributedNotificationCenter.default().addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { if let self { action(self) } } } distributedObservers.append(token) } private func observe( _ name: Notification.Name, center: NotificationCenter, action: @escaping @MainActor (OverlayController) -> Void ) { let token = center.addObserver(forName: name, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { if let self { action(self) } } } observers.append((center, token)) } private static func systemDisplays() -> [OverlayDisplay] { let height = NSScreen.screens.first?.frame.height ?? 0 return NSScreen.screens.compactMap { screen in guard let number = screen.deviceDescription[NSDeviceDescriptionKey("NSScreenNumber")] as? NSNumber, let uuid = CGDisplayCreateUUIDFromDisplayID(number.uint32Value)?.takeRetainedValue() else { return nil } let id = CFUUIDCreateString(nil, uuid) as String let frame = screen.frame return OverlayDisplay( id: id, frame: CGRect(x: frame.minX, y: height - frame.maxY, width: frame.width, height: frame.height), scale: screen.backingScaleFactor) } } }