public import AppKit import ParcelAnimation import ParcelConfig import QuartzCore /// Frames use the window server's global, top-left coordinate system, in points. public struct OverlayDisplay: Equatable, Sendable, Identifiable { public let id: String public let frame: CGRect public let scale: CGFloat public init(id: String, frame: CGRect, scale: CGFloat) { precondition(frame.isFiniteAndPositive && scale.isFinite && scale > 0) self.id = id self.frame = frame self.scale = scale } public func localFrame(_ globalFrame: CGRect) -> CGRect { CGRect( x: globalFrame.minX - frame.minX, y: frame.maxY - globalFrame.maxY, width: globalFrame.width, height: globalFrame.height) } public func panelFrame(primaryDisplayHeight: CGFloat) -> CGRect { CGRect(x: frame.minX, y: primaryDisplayHeight - frame.maxY, width: frame.width, height: frame.height) } } public struct OverlayWindow: Equatable, Sendable, Identifiable { public let id: UInt32 public let frame: CGRect public let cornerRadius: CGFloat public let observedFrame: CGRect? public init(id: UInt32, frame: CGRect, cornerRadius: CGFloat = 10, observedFrame: CGRect? = nil) { precondition(frame.isFiniteAndPositive && cornerRadius.isFinite && cornerRadius >= 0) precondition(observedFrame?.isFiniteAndPositive ?? true) self.id = id self.frame = frame self.observedFrame = observedFrame let visible = observedFrame ?? frame self.cornerRadius = min(cornerRadius, visible.width / 2, visible.height / 2) } var focusFrame: CGRect { observedFrame ?? frame } } public struct OverlayAccessibility: Equatable, Sendable { public var reduceMotion: Bool public var reduceTransparency: Bool public var increaseContrast: Bool public var differentiateWithoutColor: Bool public init( reduceMotion: Bool = false, reduceTransparency: Bool = false, increaseContrast: Bool = false, differentiateWithoutColor: Bool = false ) { self.reduceMotion = reduceMotion self.reduceTransparency = reduceTransparency self.increaseContrast = increaseContrast self.differentiateWithoutColor = differentiateWithoutColor } @MainActor public static var system: Self { let workspace = NSWorkspace.shared return Self( reduceMotion: workspace.accessibilityDisplayShouldReduceMotion, reduceTransparency: workspace.accessibilityDisplayShouldReduceTransparency, increaseContrast: workspace.accessibilityDisplayShouldIncreaseContrast, differentiateWithoutColor: workspace.accessibilityDisplayShouldDifferentiateWithoutColor) } } struct OverlayStyle: Equatable { let lineWidth: CGFloat let opacity: Float let fillOpacity: CGFloat let cornerTicks: Bool init(accessibility: OverlayAccessibility) { lineWidth = accessibility.increaseContrast ? 3 : 2 opacity = accessibility.increaseContrast || accessibility.reduceTransparency ? 1 : 0.9 fillOpacity = accessibility.increaseContrast || accessibility.reduceTransparency ? 1 : 0.12 cornerTicks = accessibility.differentiateWithoutColor } } struct OverlayHighlightStyle: Equatable { let width: CGFloat let opacity: Float let glow: Bool let active: Bool init(configuration: MotionConfiguration, accessibility: OverlayAccessibility, active: Bool) { precondition(MotionConfiguration.highlightWidths.contains(configuration.highlightWidth)) let solid = accessibility.increaseContrast || accessibility.reduceTransparency width = max(CGFloat(configuration.highlightWidth), accessibility.increaseContrast ? 3 : 2) opacity = solid ? 1 : active ? 0.9 : 0.65 glow = active && configuration.highlight == .glow && !solid self.active = active } var extent: CGFloat { width + (glow ? 6 : 0) } } enum OverlayHighlightGeometry { static func gaps(display: OverlayDisplay, windows: [OverlayWindow]) -> [CGRect] { gaps( in: CGRect(origin: .zero, size: display.frame.size), excluding: cutouts(display: display, windows: windows)) } static func cutouts(display: OverlayDisplay, windows: [OverlayWindow]) -> [CGRect] { let bounds = CGRect(origin: .zero, size: display.frame.size) let frames = windows.compactMap { window -> CGRect? in let frame = display.localFrame(window.focusFrame) let scale = display.scale // Round cutouts outward so fractional window edges cannot pick up a tinted pixel. let left = floor(frame.minX * scale) / scale let bottom = floor(frame.minY * scale) / scale let right = ceil(frame.maxX * scale) / scale let top = ceil(frame.maxY * scale) / scale let cutout = CGRect(x: left, y: bottom, width: right - left, height: top - bottom).intersection(bounds) return cutout.isEmpty || cutout.isNull ? nil : cutout }.sorted { if $0.minX != $1.minX { return $0.minX < $1.minX } if $0.minY != $1.minY { return $0.minY < $1.minY } if $0.width != $1.width { return $0.width < $1.width } return $0.height < $1.height } return frames.reduce(into: []) { result, frame in if result.last != frame { result.append(frame) } } } static func gaps(in bounds: CGRect, excluding cutouts: [CGRect]) -> [CGRect] { cutouts.reduce([bounds]) { regions, cutout in regions.flatMap { subtract(cutout, from: $0) } } } private static func subtract(_ cutout: CGRect, from rectangle: CGRect) -> [CGRect] { let intersection = rectangle.intersection(cutout) guard !intersection.isNull, !intersection.isEmpty else { return [rectangle] } return [ CGRect( x: rectangle.minX, y: rectangle.minY, width: rectangle.width, height: intersection.minY - rectangle.minY), CGRect( x: rectangle.minX, y: intersection.maxY, width: rectangle.width, height: rectangle.maxY - intersection.maxY), CGRect( x: rectangle.minX, y: intersection.minY, width: intersection.minX - rectangle.minX, height: intersection.height), CGRect( x: intersection.maxX, y: intersection.minY, width: rectangle.maxX - intersection.maxX, height: intersection.height), ].filter { !$0.isEmpty } } static func outline(bounds: CGRect, radius: CGFloat, distance: CGFloat) -> CGPath { CGPath( roundedRect: bounds.insetBy(dx: -distance, dy: -distance), cornerWidth: radius + distance, cornerHeight: radius + distance, transform: nil) } } @MainActor enum OverlayLayerAllocation { private(set) static var count: UInt64 = 0 static func makeLayer() -> CALayer { count += 1 return CALayer() } static func makeShape() -> CAShapeLayer { count += 1 return CAShapeLayer() } } @MainActor final class OverlayHighlightCanvas { private struct MaskInputs: Equatable { let size: CGSize let scale: CGFloat let cutouts: [CGRect] } let layer = OverlayLayerAllocation.makeLayer() let mask = OverlayLayerAllocation.makeShape() private var maskInputs: MaskInputs? private(set) var gaps: [CGRect] = [] var cutouts: [CGRect] { maskInputs?.cutouts ?? [] } private(set) var updateCount = 0 private(set) var maskBuildCount = 0 private(set) var inactive: [UInt32: OverlayTileLayer] = [:] init(parent: CALayer) { parent.addSublayer(layer) mask.fillColor = NSColor.black.cgColor layer.mask = mask } func update( display: OverlayDisplay, windows: [OverlayWindow], focusedWindow: UInt32?, cutouts: [OverlayWindow], configuration: MotionConfiguration, accessibility: OverlayAccessibility, color: NSColor ) { update( display: display, windows: windows, focusedWindow: focusedWindow, cutouts: cutouts, configuration: configuration, accessibility: accessibility, palette: .system(activeBorder: color), paletteVersion: nil) } func update( display: OverlayDisplay, windows: [OverlayWindow], focusedWindow: UInt32?, cutouts: [OverlayWindow], configuration: MotionConfiguration, accessibility: OverlayAccessibility, palette: OverlayPalette, paletteVersion: UInt64? ) { updateCount += 1 let inputs = MaskInputs( size: display.frame.size, scale: display.scale, cutouts: OverlayHighlightGeometry.cutouts(display: display, windows: cutouts)) if maskInputs != inputs { gaps = OverlayHighlightGeometry.gaps( in: CGRect(origin: .zero, size: inputs.size), excluding: inputs.cutouts) let path = CGMutablePath() for rectangle in gaps { path.addRect(rectangle) } withoutImplicitAnimations { layer.frame = CGRect(origin: .zero, size: inputs.size) layer.contentsScale = inputs.scale mask.frame = layer.bounds mask.contentsScale = inputs.scale mask.path = path } maskInputs = inputs maskBuildCount += 1 } let windows = windows.filter { configuration.highlight == .all && $0.id != focusedWindow && display.frame.intersects($0.focusFrame) } let visible = Set(windows.map(\.id)) for id in inactive.keys where !visible.contains(id) { inactive.removeValue(forKey: id)?.layer.removeFromSuperlayer() } let style = OverlayHighlightStyle(configuration: configuration, accessibility: accessibility, active: false) for window in windows { let tile = inactive[window.id] ?? OverlayTileLayer(parent: layer) inactive[window.id] = tile let frame = display.localFrame(window.focusFrame) if tile.layer.frame != frame || tile.layer.cornerRadius != window.cornerRadius { tile.place(at: frame, radius: window.cornerRadius) } tile.styleHighlight(style, palette: palette, version: paletteVersion, scale: display.scale) } } } @MainActor final class OverlayHighlightRenderer { private struct Geometry: Equatable { let bounds: CGRect let radius: CGFloat let width: CGFloat } private struct Inputs: Equatable { let bounds: CGRect let radius: CGFloat let style: OverlayHighlightStyle let color: CGColor let glowColor: CGColor let paletteVersion: UInt64? let opacity: Float let scale: CGFloat } let stroke = OverlayLayerAllocation.makeShape() private(set) var glow: [CAShapeLayer] = [] private var inputs: Inputs? private var glowGeometry: Geometry? private(set) var pathBuildCount = 0 private(set) var styleUpdateCount = 0 init(parent: CALayer) { parent.addSublayer(stroke) } func update( tile: OverlayTileLayer, style: OverlayHighlightStyle, palette: OverlayPalette, version: UInt64?, scale: CGFloat ) { let next = Inputs( bounds: tile.layer.bounds, radius: tile.layer.cornerRadius, style: style, color: style.active ? palette.activeBorder : palette.inactiveBorder, glowColor: palette.glow, paletteVersion: version, opacity: palette.borderOpacity ?? style.opacity, scale: scale) let colorsChanged = version.map { inputs?.paletteVersion != $0 } ?? (inputs?.color != next.color || inputs?.glowColor != next.glowColor) guard colorsChanged || inputs?.bounds != next.bounds || inputs?.radius != next.radius || inputs?.style != style || inputs?.scale != scale || inputs?.opacity != next.opacity else { return } let geometryChanged = inputs?.bounds != next.bounds || inputs?.radius != next.radius || inputs?.style.width != style.width let styleChanged = inputs?.style != style || inputs?.scale != scale withoutImplicitAnimations { if style.glow && glow.isEmpty { glow = (1...6).map { _ in OverlayLayerAllocation.makeShape() } } if inputs?.style.glow != style.glow { for band in glow { if style.glow { tile.highlight.insertSublayer(band, below: stroke) } else { band.removeAllAnimations() band.removeFromSuperlayer() } } } if geometryChanged { updatePath(stroke, bounds: next.bounds, radius: next.radius, distance: style.width / 2) } let geometry = Geometry(bounds: next.bounds, radius: next.radius, width: style.width) if style.glow, glowGeometry != geometry { for (index, band) in glow.enumerated() { updatePath( band, bounds: next.bounds, radius: next.radius, distance: style.width + CGFloat(6 - index) - 0.5 ) } glowGeometry = geometry } if styleChanged { tile.layer.borderWidth = 0 tile.layer.backgroundColor = nil tile.layer.contentsScale = scale tile.layer.opacity = next.opacity tile.ticks.isHidden = true updateStroke( stroke, color: next.color, width: style.width, opacity: 1, scale: scale, dashed: !style.active) if style.glow { for (index, band) in glow.enumerated() { updateStroke( band, color: next.glowColor, width: 1, opacity: Float(index + 1) / 24, scale: scale, dashed: false) } } } if colorsChanged && !styleChanged { stroke.strokeColor = next.color for band in glow { band.strokeColor = next.glowColor } } if inputs?.opacity != next.opacity { tile.layer.opacity = next.opacity } if colorsChanged || styleChanged || inputs?.opacity != next.opacity { styleUpdateCount += 1 } } inputs = next } private func updatePath(_ stroke: CAShapeLayer, bounds: CGRect, radius: CGFloat, distance: CGFloat) { stroke.path = OverlayHighlightGeometry.outline(bounds: bounds, radius: radius, distance: distance) pathBuildCount += 1 } private func updateStroke( _ stroke: CAShapeLayer, color: CGColor, width: CGFloat, opacity: Float, scale: CGFloat, dashed: Bool ) { stroke.fillColor = nil stroke.strokeColor = color stroke.lineWidth = width stroke.opacity = opacity stroke.contentsScale = scale stroke.lineDashPattern = dashed ? [6, 4] : nil } } extension OverlayTileLayer { func styleHighlight(_ style: OverlayHighlightStyle, color: NSColor, scale: CGFloat) { styleHighlight(style, palette: .system(activeBorder: color), version: nil, scale: scale) } func styleHighlight(_ style: OverlayHighlightStyle, palette: OverlayPalette, version: UInt64?, scale: CGFloat) { let renderer = highlightRenderer ?? OverlayHighlightRenderer(parent: highlight) highlightRenderer = renderer renderer.update(tile: self, style: style, palette: palette, version: version, scale: scale) } } struct OverlayMotion { let settings: MotionSettings let behavior: MotionBehavior init(configuration: MotionConfiguration, accessibility: OverlayAccessibility, geometry: Bool = true) { settings = configuration.uiMotionSettings let policy = MotionPolicy(enabled: configuration.enabled, reduceMotion: accessibility.reduceMotion) .behavior(for: .overlay, level: settings.level) behavior = !geometry && policy == .animate ? .fade(duration: MotionToken.fade.spec(settings: settings).duration) : policy } func spec(_ token: MotionToken) -> MotionSpec { token.spec(settings: settings) } }