import AppKit import ParcelAnimation public import ParcelConfig public import ParcelCore public import ParcelPlatform import QuartzCore import UniformTypeIdentifiers /// Frames are in global, top-left screen coordinates, in points. public struct TabViewPanelDisplay: Sendable, Equatable { public let id: DisplayID public let frame: Rect public let cards: [TabViewPanelCard] public init(id: DisplayID, frame: Rect, cards: [TabViewPanelCard]) { precondition(TabViewGeometry.valid(frame), "Display frame must be finite and positive") self.id = id self.frame = frame self.cards = cards } } /// The caller supplies the card's actual frame and its one-based position within its group. public struct TabViewPanelCard: Sendable, Equatable { public enum Kind: Sendable, Equatable { case tile, floating, minimized } public let id: WindowID public let appName: String public let title: String public let pid: Int32 public let frame: Rect public let position: Int public let total: Int public let kind: Kind public init( id: WindowID, appName: String, title: String, pid: Int32, frame: Rect, position: Int, total: Int, kind: Kind = .tile ) { precondition(TabViewGeometry.valid(frame), "Card frame must be finite and positive") precondition(position > 0 && position <= total, "Card position must be within the total") self.id = id self.appName = appName self.title = title self.pid = pid self.frame = frame self.position = position self.total = total self.kind = kind } } @MainActor public final class TabViewPanelController { private let onSelect: @MainActor (WindowID) -> Void private let isVoiceOverEnabled: @MainActor () -> Bool private let keyboardFocusIsOwned: (@MainActor () -> Bool)? private var panels: [DisplayID: LearningPanel] = [:] private var canvases: [DisplayID: TabViewCanvas] = [:] private var selected: WindowID? private var configuration = MotionConfiguration() private var accessibilityObservation: (any NSObjectProtocol)? private var frameClock: OverlayFrameClock? private var frameClockScreen: NSScreen? private var presentation: TabViewPresentationTrace? private var presentationReady = false private var previousApplication: NSRunningApplication? private var idlePanels: [DisplayID: LearningPanel] = [:] private var displayIDs: Set = [] public convenience init(onSelect: @escaping @MainActor (WindowID) -> Void) { self.init(isVoiceOverEnabled: { VoiceOverStatus.isRunning }, onSelect: onSelect) } package init( isVoiceOverEnabled: @escaping @MainActor () -> Bool, keyboardFocusIsOwned: (@MainActor () -> Bool)? = nil, onSelect: @escaping @MainActor (WindowID) -> Void ) { self.isVoiceOverEnabled = isVoiceOverEnabled self.keyboardFocusIsOwned = keyboardFocusIsOwned self.onSelect = onSelect } public func show( displays: [TabViewPanelDisplay], selected: WindowID?, configuration: MotionConfiguration, presentation: TabViewPresentationTrace? = nil ) { frameClock?.pause() self.presentation?.cancel() self.presentation = presentation presentationReady = false precondition(Set(displays.map(\.id)).count == displays.count, "Display IDs must be unique") let ids = displays.flatMap { $0.cards.map(\.id) } precondition(Set(ids).count == ids.count, "Window IDs must be unique") self.configuration = configuration displayIDs = Set(displays.map(\.id)) for id in Set(idlePanels.keys).subtracting(displayIDs) { idlePanels.removeValue(forKey: id)?.close() } let removed = Set(panels.keys).subtracting(displays.map(\.id)) for id in removed { panels.removeValue(forKey: id)?.close() canvases.removeValue(forKey: id) } self.selected = selected guard !displays.isEmpty else { presentation?.cancel() self.presentation = nil stopObservingAccessibility() return } guard let primary = NSScreen.screens.first else { preconditionFailure("Tab View requires a primary screen") } // Arm before drawing so a committed panel does not wait an extra refresh. if presentation != nil { if frameClock == nil || frameClockScreen !== primary { frameClock?.stop() frameClockScreen = primary frameClock = OverlayFrameClock(screen: primary) { [weak self] _ in guard let self, self.presentation != nil else { return } guard self.presentationReady else { self.frameClock?.request() return } self.presentation?.presented() self.presentation = nil } } frameClock?.request() } observeAccessibility() let accessibility = OverlayAccessibility.system for display in displays { let panel: LearningPanel if let existing = panels[display.id] { panel = existing } else if let idle = reusablePanel(for: display.id) { panel = idle panels[display.id] = panel } else { panel = LearningPanel( title: TabViewText.text("Tab View"), interactive: true, activatesApplication: isVoiceOverEnabled()) panel.collectionBehavior.remove(.participatesInCycle) panel.collectionBehavior.insert(.ignoresCycle) panels[display.id] = panel } panel.alphaValue = 1 panel.ignoresMouseEvents = false panel.setAccessibilityElement(true) let canvas = TabViewCanvas(display: display, selected: selected, accessibility: accessibility) { [weak self] id in guard let self else { return } self.updateSelection(id) self.onSelect(id) } panel.contentView = canvas canvases[display.id] = canvas panel.setFrame(TabViewGeometry.panelFrame(display.frame, primaryHeight: primary.frame.maxY), display: false) panel.orderFrontRegardless() for button in canvas.buttons.values { TabViewMotion.show(button.layer, configuration: configuration, reduceMotion: accessibility.reduceMotion) } } presentation?.checkpoint("panels") focusAccessibilitySelection() announceSelection() if presentation != nil { for panel in panels.values { panel.displayIfNeeded() } CATransaction.flush() presentation?.checkpoint("committed") presentationReady = true } } public func updateSelection(_ id: WindowID?) { guard selected != id else { return } selected = id for canvas in canvases.values { canvas.updateSelection(id) } focusAccessibilitySelection() announceSelection() } public func close(immediately: Bool = false) { frameClock?.pause() presentation?.cancel() presentation = nil stopObservingAccessibility() if let previousApplication, !previousApplication.isTerminated { NSApp.yieldActivation(to: previousApplication) previousApplication.activate(from: NSRunningApplication.current, options: []) } previousApplication = nil // Only completed fades enter the pool; an old fade cannot hide a reopened panel. let retiring = panels let retiringCanvases = Array(canvases.values) panels.removeAll() canvases.removeAll() selected = nil guard !retiring.isEmpty else { return } for canvas in retiringCanvases { canvas.disableInteraction() } guard !immediately, let duration = TabViewMotion.closeDuration( configuration: configuration, reduceMotion: NSWorkspace.shared.accessibilityDisplayShouldReduceMotion ) else { retire(retiring) return } for panel in retiring.values { panel.ignoresMouseEvents = true if panel.isKeyWindow { panel.resignKey() } panel.setAccessibilityElement(false) } NSAnimationContext.runAnimationGroup { context in context.duration = duration context.timingFunction = CAMediaTimingFunction(name: .easeOut) for panel in retiring.values { panel.animator().alphaValue = 0 } } completionHandler: { [weak self] in MainActor.assumeIsolated { if let self { self.retire(retiring) } else { for panel in retiring.values { panel.close() } } } } } private func reusablePanel(for id: DisplayID) -> LearningPanel? { guard let panel = idlePanels.removeValue(forKey: id) else { return nil } guard panel.activatesApplication == isVoiceOverEnabled() else { panel.close(); return nil } return panel } private func retire(_ retiring: [DisplayID: LearningPanel]) { for (id, panel) in retiring { panel.orderOut(nil) panel.setAccessibilityElement(false) panel.ignoresMouseEvents = true guard displayIDs.contains(id) else { panel.close(); continue } idlePanels.removeValue(forKey: id)?.close() idlePanels[id] = panel } } isolated deinit { stopObservingAccessibility() for panel in panels.values { panel.close() } for panel in idlePanels.values { panel.close() } frameClock?.stop() } package func prepareVoiceOverInput() { guard isVoiceOverEnabled() else { return } if keyboardFocusIsOwned?() ?? (NSApp.isActive && panels.values.contains(where: \.isKeyWindow)) { return } focusAccessibilitySelection() } private func focusAccessibilitySelection() { guard isVoiceOverEnabled(), let selected else { return } for (id, canvas) in canvases { guard let button = canvas.buttons[selected], let panel = panels[id] else { continue } if previousApplication == nil { previousApplication = NSWorkspace.shared.frontmostApplication } let focusPanel: LearningPanel if panel.activatesApplication { focusPanel = panel } else { // Removing nonactivatingPanel does not reliably clear AppKit's native activation tag. let replacement = LearningPanel(title: panel.title, interactive: true, activatesApplication: true) replacement.collectionBehavior = panel.collectionBehavior replacement.setFrame(panel.frame, display: false) panel.contentView = nil replacement.contentView = canvas panels[id] = replacement panel.close() focusPanel = replacement } NSApp.activate(ignoringOtherApps: true) focusPanel.becomesKeyOnlyIfNeeded = false focusPanel.makeKeyAndOrderFront(nil) focusPanel.makeFirstResponder(button) NSAccessibility.post(element: button, notification: .focusedUIElementChanged) return } } private func announceSelection() { guard let selected else { return } for canvas in canvases.values { guard let button = canvas.buttons[selected], let panel = canvas.window else { continue } NSAccessibility.post( element: panel, notification: .announcementRequested, userInfo: [ .announcement: TabViewText.label(button.card), .priority: NSAccessibilityPriorityLevel.medium.rawValue, ]) return } } private func observeAccessibility() { guard accessibilityObservation == nil else { return } accessibilityObservation = NSWorkspace.shared.notificationCenter.addObserver( forName: NSWorkspace.accessibilityDisplayOptionsDidChangeNotification, object: nil, queue: .main ) { [weak self] _ in MainActor.assumeIsolated { guard let self else { return } let accessibility = OverlayAccessibility.system for canvas in self.canvases.values { canvas.updateAccessibility(accessibility) if accessibility.reduceMotion { for button in canvas.buttons.values { button.layer?.removeAllAnimations() } } } } } } private func stopObservingAccessibility() { if let accessibilityObservation { NSWorkspace.shared.notificationCenter.removeObserver(accessibilityObservation) self.accessibilityObservation = nil } } } enum TabViewGeometry { static func valid(_ rect: Rect) -> Bool { rect.minX.isFinite && rect.minY.isFinite && rect.size.width.isFinite && rect.size.height.isFinite && rect.size.width > 0 && rect.size.height > 0 && rect.maxX.isFinite && rect.maxY.isFinite } static func panelFrame(_ display: Rect, primaryHeight: CGFloat) -> CGRect { CGRect(x: display.minX, y: primaryHeight - display.maxY, width: display.size.width, height: display.size.height) } static func cardFrame(_ card: Rect, in display: Rect) -> CGRect { CGRect( x: card.minX - display.minX, y: card.minY - display.minY, width: card.size.width, height: card.size.height) } } enum TabViewText { static func text(_ key: String) -> String { Bundle.module.localizedString(forKey: key, value: nil, table: "TabView") } static func title(_ card: TabViewPanelCard) -> String { card.title.isEmpty ? text("Untitled window") : card.title } static func label(_ card: TabViewPanelCard) -> String { let key = switch card.kind { case .tile: "%@, %@, tile %lld of %lld" case .floating: "%@, %@, floating window %lld of %lld" case .minimized: "%@, %@, minimized window %lld of %lld" } return String( format: text(key), locale: .current, card.appName, title(card), Int64(card.position), Int64(card.total)) } } @MainActor enum TabViewMotion { static func closeDuration(configuration: MotionConfiguration, reduceMotion: Bool) -> Double? { guard configuration.enabled, !reduceMotion else { return nil } let motion = OverlayMotion(configuration: configuration, accessibility: .init()) return motion.spec(.fade).duration } static func show(_ layer: CALayer?, configuration: MotionConfiguration, reduceMotion: Bool) { guard let layer else { return } layer.removeAllAnimations() guard !reduceMotion else { return } LearningMotion.show(layer, token: .pop, configuration: configuration) } } @MainActor final class TabViewCanvas: NSView { private(set) var buttons: [WindowID: TabViewCardButton] = [:] let scrollView = NSScrollView() private let document = TabViewDocumentView() private let overflowHint = NSTextField(labelWithString: TabViewText.text("Scroll to see more windows")) override var isFlipped: Bool { true } init( display: TabViewPanelDisplay, selected: WindowID?, accessibility: OverlayAccessibility, onSelect: @escaping @MainActor (WindowID) -> Void ) { let geometry: TabViewCardGeometry do { geometry = try TabViewCardGeometry(frames: display.cards.map(\.frame), viewport: display.frame) } catch { preconditionFailure("Invalid Tab View card geometry: \(error)") } super.init(frame: CGRect(x: 0, y: 0, width: display.frame.size.width, height: display.frame.size.height)) wantsLayer = true layer?.masksToBounds = true setAccessibilityElement(false) let overflow = geometry.contentFrame.size.width > bounds.width || geometry.contentFrame.size.height > bounds.height let hintHeight: CGFloat = overflow && bounds.height >= 100 ? 28 : 0 scrollView.frame = CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height - hintHeight) scrollView.autoresizingMask = [.width, .height] scrollView.drawsBackground = false scrollView.scrollerStyle = .overlay scrollView.hasHorizontalScroller = geometry.contentFrame.size.width > scrollView.frame.width scrollView.hasVerticalScroller = geometry.contentFrame.size.height > scrollView.frame.height scrollView.horizontalScrollElasticity = .none scrollView.verticalScrollElasticity = .none scrollView.setAccessibilityLabel(TabViewText.text("Tab View")) scrollView.setAccessibilityHelp(overflow ? TabViewText.text("Scroll to see more windows") : nil) document.frame = CGRect( origin: .zero, size: CGSize( width: geometry.contentFrame.size.width, height: geometry.contentFrame.size.height)) document.setAccessibilityElement(false) scrollView.documentView = document addSubview(scrollView) if hintHeight > 0 { overflowHint.frame = CGRect(x: 0, y: bounds.height - hintHeight, width: bounds.width, height: hintHeight) overflowHint.autoresizingMask = [.width, .minYMargin] overflowHint.alignment = .center overflowHint.font = NSFont.systemFont(ofSize: NSFont.smallSystemFontSize) overflowHint.setAccessibilityElement(false) overflowHint.drawsBackground = true addSubview(overflowHint) } for (card, frame) in zip(display.cards, geometry.frames) { let button = TabViewCardButton( card: card, selected: card.id == selected, accessibility: accessibility, onSelect: onSelect) button.frame = TabViewGeometry.cardFrame(frame, in: display.frame) document.addSubview(button) buttons[card.id] = button } scrollView.tile() updateAccessibility(accessibility) revealSelection(selected) } required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") } func updateSelection(_ selected: WindowID?) { for (id, button) in buttons { button.setSelected(id == selected) } revealSelection(selected) } private func revealSelection(_ selected: WindowID?) { guard let selected, let button = buttons[selected] else { return } document.scrollToVisible( button.frame.insetBy(dx: -TabViewCardGeometry.spacing, dy: -TabViewCardGeometry.spacing)) } func updateAccessibility(_ accessibility: OverlayAccessibility) { for button in buttons.values { button.accessibility = accessibility } overflowHint.textColor = accessibility.increaseContrast ? .labelColor : .secondaryLabelColor overflowHint.backgroundColor = accessibility.reduceTransparency || accessibility.increaseContrast ? .windowBackgroundColor : NSColor.windowBackgroundColor.withAlphaComponent(0.92) } func disableInteraction() { for button in buttons.values { button.isEnabled = false button.setAccessibilityElement(false) } } } @MainActor private final class TabViewDocumentView: NSView { override var isFlipped: Bool { true } } @MainActor final class TabViewCardButton: NSButton { let card: TabViewPanelCard private(set) var selected: Bool var accessibility: OverlayAccessibility { didSet { needsDisplay = true } } private let onSelect: @MainActor (WindowID) -> Void let appIcon: NSImage private static let genericAppIcon = NSWorkspace.shared.icon(for: .applicationBundle) override var isFlipped: Bool { true } init( card: TabViewPanelCard, selected: Bool, accessibility: OverlayAccessibility, onSelect: @escaping @MainActor (WindowID) -> Void ) { self.card = card self.selected = selected self.accessibility = accessibility self.onSelect = onSelect appIcon = NSRunningApplication(processIdentifier: card.pid)?.icon ?? Self.genericAppIcon super.init(frame: .zero) wantsLayer = true isBordered = false title = "" target = self action = #selector(selectCard) setAccessibilityLabel(TabViewText.label(card)) setAccessibilitySelected(selected) toolTip = TabViewText.label(card) } required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") } override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } @objc private func selectCard() { onSelect(card.id) } func setSelected(_ selected: Bool) { guard self.selected != selected else { return } self.selected = selected setAccessibilitySelected(selected) needsDisplay = true } override func draw(_ dirtyRect: NSRect) { let inset = min(accessibility.increaseContrast ? 2 : 1, bounds.width / 2, bounds.height / 2) let shape = NSBezierPath(roundedRect: bounds.insetBy(dx: inset, dy: inset), xRadius: 10, yRadius: 10) let solid = accessibility.reduceTransparency || accessibility.increaseContrast let background = selected ? NSColor.controlAccentColor : NSColor.windowBackgroundColor (solid ? background : background.withAlphaComponent(0.92)).setFill() shape.fill() (selected ? NSColor.selectedControlTextColor : NSColor.separatorColor).setStroke() shape.lineWidth = accessibility.increaseContrast ? (selected ? 4 : 2) : (selected ? 3 : 1) shape.stroke() let layout = TabViewCardLayout(size: bounds.size, layoutDirection: userInterfaceLayoutDirection) appIcon.draw( in: layout.icon, from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil) let foreground = selected ? NSColor.selectedControlTextColor : NSColor.labelColor let paragraph = NSMutableParagraphStyle() paragraph.lineBreakMode = .byTruncatingTail paragraph.alignment = .natural (card.appName as NSString).draw( in: layout.app, withAttributes: [ .font: NSFont.systemFont(ofSize: NSFont.smallSystemFontSize, weight: .semibold), .foregroundColor: foreground, .paragraphStyle: paragraph, ]) (TabViewText.title(card) as NSString).draw( in: layout.title, withAttributes: [ .font: NSFont.systemFont(ofSize: NSFont.systemFontSize), .foregroundColor: foreground, .paragraphStyle: paragraph, ]) } } struct TabViewCardLayout { let icon: CGRect let app: CGRect let title: CGRect init(size: CGSize, layoutDirection: NSUserInterfaceLayoutDirection = .leftToRight) { precondition( size.width.isFinite && size.height.isFinite && size.width >= TabViewCardGeometry.minimumSize.width && size.height >= TabViewCardGeometry.minimumSize.height, "Tab View cards must retain their readable minimum size") let content = CGRect(origin: .zero, size: size).insetBy(dx: 12, dy: 12) let iconSize: CGFloat = 40 let rightToLeft = layoutDirection == .rightToLeft icon = CGRect( x: rightToLeft ? content.maxX - iconSize : content.minX, y: content.midY - iconSize / 2, width: iconSize, height: iconSize) let textX = rightToLeft ? content.minX : icon.maxX + 8 let textWidth = content.width - iconSize - 8 let lineHeight: CGFloat = 17 app = CGRect(x: textX, y: content.midY - lineHeight, width: textWidth, height: lineHeight) title = CGRect(x: textX, y: content.midY, width: textWidth, height: lineHeight) } }