import AppKit import ParcelAnimation import QuartzCore @MainActor final class OverlayPanel: NSPanel { let canvas = OverlayLayerAllocation.makeLayer() private(set) var display: OverlayDisplay var onAppearanceChanged: (@MainActor () -> Void)? init(display: OverlayDisplay, primaryDisplayHeight: CGFloat) { self.display = display super.init( contentRect: display.panelFrame(primaryDisplayHeight: primaryDisplayHeight), styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false) isReleasedWhenClosed = false isOpaque = false backgroundColor = .clear hasShadow = false ignoresMouseEvents = true acceptsMouseMovedEvents = false hidesOnDeactivate = false isFloatingPanel = true animationBehavior = .none level = .floating collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle] setAccessibilityElement(false) let view = OverlayAppearanceView(frame: CGRect(origin: .zero, size: display.frame.size)) view.changed = { [weak self] in self?.onAppearanceChanged?() } view.setAccessibilityElement(false) view.setAccessibilityChildren([]) view.wantsLayer = true view.layer = canvas contentView = view canvas.masksToBounds = true update(display: display, primaryDisplayHeight: primaryDisplayHeight) } override var canBecomeKey: Bool { false } override var canBecomeMain: Bool { false } func update(display: OverlayDisplay, primaryDisplayHeight: CGFloat) { self.display = display let next = display.panelFrame(primaryDisplayHeight: primaryDisplayHeight) if frame != next { setFrame(next, display: false) } withoutImplicitAnimations { canvas.frame = CGRect(origin: .zero, size: display.frame.size) canvas.contentsScale = display.scale } } } @MainActor private final class OverlayAppearanceView: NSView { var changed: (@MainActor () -> Void)? override func viewDidChangeEffectiveAppearance() { super.viewDidChangeEffectiveAppearance() changed?() } } @MainActor func withoutImplicitAnimations(_ body: () -> Void) { CATransaction.begin() CATransaction.setDisableActions(true) body() CATransaction.commit() } struct OverlayAxisMotion { let initial: SpringState let target: Double let spring: SpringParameters let startTime: Double let duration: Double func sample(at time: Double) -> SpringState { if time >= startTime + duration { return SpringState(value: target) } return initial.advanced(to: target, by: max(0, time - startTime), using: spring) } } struct OverlayFocusKeyframes { let startTime: Double let duration: Double let frames: [CGRect] let keyTimes: [Double] init(plan: FramePlan, display: OverlayDisplay) throws { precondition(plan.request.surface == .window) startTime = plan.startTime duration = plan.duration var previous = (progress: 0.0, frame: try Self.frame(plan, display: display, progress: 0)) var frames = [previous.frame] var times = [previous.progress] let segments = 16 for index in 1...segments { let progress = Double(index) / Double(segments) let next = (progress: progress, frame: try Self.frame(plan, display: display, progress: progress)) try Self.appendSegment( plan, display: display, from: previous, to: next, depth: 0, frames: &frames, times: ×) previous = next } self.frames = frames keyTimes = times } private static func frame(_ plan: FramePlan, display: OverlayDisplay, progress: Double) throws -> CGRect { let time = plan.duration == 0 ? plan.endTime : min(plan.endTime.nextDown, plan.startTime + plan.duration * progress) return display.localFrame(try plan.sample(at: time).frame.rect.overlayRectangle) } private static func appendSegment( _ plan: FramePlan, display: OverlayDisplay, from start: (progress: Double, frame: CGRect), to end: (progress: Double, frame: CGRect), depth: Int, frames: inout [CGRect], times: inout [Double] ) throws { let progress = (start.progress + end.progress) / 2 let middle = try frame(plan, display: display, progress: progress) let error = max( abs(middle.midX - (start.frame.midX + end.frame.midX) / 2), abs(middle.midY - (start.frame.midY + end.frame.midY) / 2)) // Screen clamps can introduce a sharp corner even in an otherwise smooth glide. if error > 0.75 { guard depth < 16 else { throw MotionError.invalidGeometry } let midpoint = (progress: progress, frame: middle) try appendSegment( plan, display: display, from: start, to: midpoint, depth: depth + 1, frames: &frames, times: ×) try appendSegment( plan, display: display, from: midpoint, to: end, depth: depth + 1, frames: &frames, times: ×) } else { frames.append(end.frame) times.append(end.progress) } } } extension MotionRect { var overlayRectangle: CGRect { CGRect(x: originX, y: originY, width: width, height: height) } } private struct OverlayFocusGeometry { let bounds: CGRect let radius: CGFloat let startTime: Double let duration: Double } private struct OverlayFocusAppearance: Equatable { let motionID: UInt64 let pathBuildCount: Int let style: OverlayHighlightStyle let scale: CGFloat } private struct OverlayComponent { let key: String let start: Double let target: Double let speed: Double } @MainActor final class OverlayAnimationCompletion: NSObject, CAAnimationDelegate { let finish: @MainActor () -> Void init(finish: @escaping @MainActor () -> Void) { self.finish = finish } nonisolated func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { guard flag else { return } Task { @MainActor in finish() } } } @MainActor final class OverlayTileLayer { let layer = OverlayLayerAllocation.makeLayer() let ticks = OverlayLayerAllocation.makeShape() let highlight = OverlayLayerAllocation.makeLayer() var highlightRenderer: OverlayHighlightRenderer? private var axes: [String: OverlayAxisMotion] = [:] private var completion: OverlayAnimationCompletion? private var revision = 0 private(set) var focusMotionID: UInt64? private var focusGeometry: OverlayFocusGeometry? private var focusAppearance: OverlayFocusAppearance? private var focusMask: CAShapeLayer? init(parent: CALayer) { parent.addSublayer(layer) layer.addSublayer(ticks) layer.addSublayer(highlight) layer.masksToBounds = false ticks.fillColor = nil } func style(_ style: OverlayStyle, color: NSColor, scale: CGFloat, filled: Bool) { self.style(style, color: color.cgColor, scale: scale, filled: filled) } func style(_ style: OverlayStyle, color: CGColor, scale: CGFloat, filled: Bool) { withoutImplicitAnimations { layer.contentsScale = scale layer.borderWidth = style.lineWidth layer.borderColor = color layer.opacity = style.opacity if filled { guard let fill = color.copy(alpha: style.fillOpacity) else { preconditionFailure("Invalid overlay fill color") } layer.backgroundColor = fill } else { layer.backgroundColor = nil } ticks.contentsScale = scale ticks.strokeColor = color ticks.lineWidth = style.lineWidth ticks.isHidden = !style.cornerTicks } } func recolor(_ color: CGColor, fillOpacity: CGFloat? = nil) { withoutImplicitAnimations { if layer.borderColor != color { layer.borderColor = color } if ticks.strokeColor != color { ticks.strokeColor = color } if let fillOpacity { guard let fill = color.copy(alpha: fillOpacity) else { preconditionFailure("Invalid overlay fill color") } layer.backgroundColor = fill } } } func place(at frame: CGRect, radius: CGFloat) { if layer.animationKeys()?.isEmpty == false { cancel() } withoutImplicitAnimations { let geometryChanged = layer.bounds.size != frame.size || layer.cornerRadius != radius layer.frame = frame layer.cornerRadius = radius layer.transform = CATransform3DIdentity if geometryChanged { updateTicks() } } } func move( to frame: CGRect, radius: CGFloat, motion: OverlayMotion, token: MotionToken, from initialFrame: CGRect? = nil, velocity: CGVector = .zero, staggerIndex: Int = 0, transient: Bool = false, nudgeDirection: CGVector = CGVector(dx: 1, dy: 0), completion finish: (@MainActor () -> Void)? = nil ) { clearFocusMotion() let time = CACurrentMediaTime() let oldFrame = initialFrame ?? layer.presentation()?.frame ?? layer.frame let oldRadius = layer.presentation()?.cornerRadius ?? layer.cornerRadius let oldOpacity = layer.presentation()?.opacity ?? layer.opacity let inherited = axes.mapValues { $0.sample(at: time) } let retargeting = !axes.isEmpty && layer.animation(forKey: "motion") != nil revision += 1 let currentRevision = revision layer.removeAllAnimations() axes = [:] completion = nil withoutImplicitAnimations { let geometryChanged = layer.bounds.size != frame.size || layer.cornerRadius != radius layer.bounds = CGRect(origin: .zero, size: frame.size) layer.position = CGPoint(x: frame.midX, y: frame.midY) layer.cornerRadius = radius layer.transform = CATransform3DIdentity layer.opacity = transient ? 0 : layer.opacity if geometryChanged { updateTicks() } } var animations: [CAAnimation] = [] let spec = motion.spec(token) let delay: Double let duration: Double switch motion.behavior { case .instant: if transient { finish?() } return case .fade(let fadeDuration): delay = 0 duration = fadeDuration animations.append( Self.fade(from: transient ? oldOpacity : 0, to: transient ? 0 : layer.opacity, duration: duration)) case .animate: delay = retargeting ? 0 : spec.delay(for: staggerIndex) duration = spec.duration let components = [ OverlayComponent(key: "position.x", start: oldFrame.midX, target: frame.midX, speed: velocity.dx), OverlayComponent(key: "position.y", start: oldFrame.midY, target: frame.midY, speed: velocity.dy), OverlayComponent(key: "bounds.size.width", start: oldFrame.width, target: frame.width, speed: 0), OverlayComponent(key: "bounds.size.height", start: oldFrame.height, target: frame.height, speed: 0), OverlayComponent(key: "cornerRadius", start: oldRadius, target: radius, speed: 0), ] for component in components { let state = inherited[component.key] ?? SpringState(value: component.start, velocity: component.speed) addSpring( key: component.key, state: state, target: component.target, spec: spec, at: time + delay, to: &animations) } switch spec.accent { case .scale(let from): addSpring( key: "transform.scale", state: inherited["transform.scale"] ?? SpringState(value: from), target: 1, spec: spec, at: time + delay, to: &animations) case .offset(let horizontal, let vertical): let offsetX = token == .nudge ? horizontal * nudgeDirection.dx : horizontal let offsetY = token == .nudge ? horizontal * nudgeDirection.dy : vertical addSpring( key: "transform.translation.x", state: SpringState(value: offsetX), target: 0, spec: spec, at: time + delay, to: &animations) addSpring( key: "transform.translation.y", state: SpringState(value: offsetY), target: 0, spec: spec, at: time + delay, to: &animations) case .none: break } if transient { let fade = Self.fade(from: oldOpacity, to: 0, duration: motion.spec(.fade).duration) fade.beginTime = duration fade.fillMode = .backwards animations.append(fade) } } let group = CAAnimationGroup() group.animations = animations group.beginTime = layer.convertTime(time + delay, from: nil) group.duration = duration + (transient && motion.behavior == .animate ? motion.spec(.fade).duration : 0) group.fillMode = .backwards let delegate = OverlayAnimationCompletion { [weak self] in guard let self, self.revision == currentRevision else { return } self.axes = [:] self.completion = nil finish?() } completion = delegate group.delegate = delegate layer.add(group, forKey: "motion") } func follow( plan: FramePlan, id: UInt64, display: OverlayDisplay, radius: CGFloat, at timestamp: Double = CACurrentMediaTime() ) throws { guard timestamp.isFinite else { throw MotionError.invalidTimestamp } guard focusMotionID != id else { return } let target = display.localFrame(try plan.sample(at: plan.endTime).frame.rect.overlayRectangle) let keyframes = timestamp < plan.endTime && plan.duration > 0 ? try OverlayFocusKeyframes(plan: plan, display: display) : nil cancel() focusMotionID = id withoutImplicitAnimations { layer.bounds = CGRect(origin: .zero, size: target.size) layer.position = CGPoint(x: target.midX, y: target.midY) layer.cornerRadius = min(radius, target.width / 2, target.height / 2) layer.transform = CATransform3DIdentity updateTicks() } guard let keyframes, let held = keyframes.frames.first else { return } let position = CAKeyframeAnimation(keyPath: "position") position.values = keyframes.frames.map { NSValue(point: CGPoint(x: $0.midX, y: $0.midY)) } position.keyTimes = keyframes.keyTimes.map { NSNumber(value: $0) } position.calculationMode = .linear position.timingFunction = CAMediaTimingFunction(name: .linear) position.duration = keyframes.duration var animations: [CAAnimation] = [position] if held.size != target.size { focusGeometry = OverlayFocusGeometry( bounds: CGRect(origin: .zero, size: held.size), radius: min(radius, held.width / 2, held.height / 2), startTime: keyframes.startTime, duration: keyframes.duration) let size = CABasicAnimation(keyPath: "bounds.size") size.fromValue = NSValue(size: held.size) size.toValue = size.fromValue size.duration = keyframes.duration animations.append(size) } let group = CAAnimationGroup() group.animations = animations group.beginTime = layer.convertTime(keyframes.startTime, from: nil) group.duration = keyframes.duration group.fillMode = .backwards layer.add(group, forKey: "focus-plan") } func styleFocusHighlight( _ style: OverlayHighlightStyle, palette: OverlayPalette, version: UInt64?, scale: CGFloat, at timestamp: Double ) { styleHighlight(style, palette: palette, version: version, scale: scale) guard let motionID = focusMotionID else { return } let mask = clipFocusContent(extent: style.extent) guard let geometry = focusGeometry, timestamp < geometry.startTime + geometry.duration else { clearHeldFocusPaths() return } guard let renderer = highlightRenderer else { preconditionFailure("Focus renderer is missing") } let appearance = OverlayFocusAppearance( motionID: motionID, pathBuildCount: renderer.pathBuildCount, style: style, scale: scale) guard focusAppearance != appearance else { return } clearHeldFocusPaths() for case let stroke as CAShapeLayer in highlight.sublayers ?? [] { guard let path = stroke.path else { preconditionFailure("Focus stroke is missing its outline") } let held = OverlayHighlightGeometry.outline( bounds: geometry.bounds, radius: geometry.radius, distance: max(0, -path.boundingBoxOfPath.minX)) holdFocusPath(held, on: stroke, geometry: geometry) } holdFocusPath(Self.focusClipPath(bounds: geometry.bounds, extent: style.extent), on: mask, geometry: geometry) focusAppearance = appearance } private func holdFocusPath(_ path: CGPath, on shape: CAShapeLayer, geometry: OverlayFocusGeometry) { let animation = CABasicAnimation(keyPath: "path") animation.fromValue = path animation.toValue = path animation.beginTime = shape.convertTime(geometry.startTime, from: nil) animation.duration = geometry.duration animation.fillMode = .backwards shape.add(animation, forKey: "focus-plan") } private static func focusClipPath(bounds: CGRect, extent: CGFloat) -> CGPath { let path = CGMutablePath() path.addRect(bounds.insetBy(dx: -extent, dy: -extent)) path.addRect(bounds) return path } @discardableResult func clipFocusContent(extent: CGFloat) -> CAShapeLayer { let mask = focusMask ?? CAShapeLayer() let bounds = layer.bounds.insetBy(dx: -extent, dy: -extent) withoutImplicitAnimations { if mask.bounds != bounds { mask.bounds = bounds mask.position = CGPoint(x: layer.bounds.midX, y: layer.bounds.midY) mask.path = Self.focusClipPath(bounds: layer.bounds, extent: extent) mask.fillRule = .evenOdd mask.fillColor = NSColor.black.cgColor } if mask.contentsScale != layer.contentsScale { mask.contentsScale = layer.contentsScale } if layer.mask !== mask { layer.mask = mask } } focusMask = mask return mask } private func clearFocusMotion() { guard focusMotionID != nil else { return } focusMotionID = nil focusGeometry = nil clearHeldFocusPaths() } private func clearHeldFocusPaths() { guard focusAppearance != nil else { return } focusAppearance = nil focusMask?.removeAnimation(forKey: "focus-plan") guard let renderer = highlightRenderer else { return } for stroke in [renderer.stroke] + renderer.glow { stroke.removeAnimation(forKey: "focus-plan") } } func fadeFocusFeedback(motion: OverlayMotion) { guard case .fade(let duration) = motion.behavior else { return } layer.add(Self.fade(from: 0, to: layer.opacity, duration: duration), forKey: "focus-feedback") } func nudge(horizontal: Double, vertical: Double, motion: OverlayMotion) { guard motion.behavior == .animate, focusMotionID == nil else { return } move( to: layer.frame, radius: layer.cornerRadius, motion: motion, token: .nudge, nudgeDirection: CGVector(dx: horizontal, dy: vertical)) } func cancel() { clearFocusMotion() revision += 1 layer.removeAllAnimations() axes = [:] completion = nil } private func addSpring( key: String, state: SpringState, target: Double, spec: MotionSpec, at time: Double, to animations: inout [CAAnimation] ) { guard state.value != target || state.velocity != 0 else { return } let spring = CASpringAnimation(keyPath: key) spring.mass = spec.spring.mass spring.stiffness = spec.spring.stiffness spring.damping = spec.spring.damping spring.initialVelocity = state.value == target ? 0 : state.velocity / (target - state.value) spring.fromValue = state.value spring.toValue = target spring.duration = spec.duration spring.fillMode = .forwards axes[key] = OverlayAxisMotion( initial: state, target: target, spring: spec.spring, startTime: time, duration: spec.duration) animations.append(spring) } private static func fade(from: Float, to: Float, duration: Double) -> CABasicAnimation { let fade = CABasicAnimation(keyPath: "opacity") fade.fromValue = from fade.toValue = to fade.duration = duration fade.timingFunction = CAMediaTimingFunction(name: .easeOut) return fade } private func updateTicks() { let width = layer.bounds.width let height = layer.bounds.height let inset = min(layer.cornerRadius + 3, min(width, height) / 4) let length = min(8, min(width, height) / 8) let path = CGMutablePath() for cornerX in [inset, width - inset] { for cornerY in [inset, height - inset] { path.move(to: CGPoint(x: cornerX, y: cornerY)) path.addLine(to: CGPoint(x: cornerX + (cornerX < width / 2 ? length : -length), y: cornerY)) path.move(to: CGPoint(x: cornerX, y: cornerY)) path.addLine(to: CGPoint(x: cornerX, y: cornerY + (cornerY < height / 2 ? length : -length))) } } ticks.path = path } }