Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Components/AppKitBridges.swift3// Description: The AppKit pieces under the SwiftUI interface: the Quick Look panel (QLPreviewPanel) with its zoom from the item, on-screen anchors of items, a per-window key-down catcher (Space, Return, arrows, type-select), an inline rename field, and access to the window's search field.4import AppKit5import ApplicationServices6import Quartz7import SwiftUI89// MARK: Anchors (where an item is on screen)10/// Views register here under the identifier of the item they show; Quick Look asks for the frame to zoom from.11@MainActor final class AnchorRegistry {12 static let shared = AnchorRegistry()13 private final class Weak { weak var view: NSView?; init(_ v: NSView) { view = v } }14 private var views: [String: Weak] = [:]15 func register(_ view: NSView, for id: String) { views[id] = Weak(view); if views.count > 4000 { views = views.filter { $0.value.view != nil } } }16 func unregister(_ view: NSView, for id: String) { if views[id]?.view === view { views[id] = nil } }17 /// Frame of the item's picture in screen coordinates, when it is visible in a window.18 func screenFrame(_ id: String) -> NSRect? {19 guard let v = views[id]?.view, let w = v.window, !v.isHiddenOrHasHiddenAncestor else { return nil }20 let r = w.convertToScreen(v.convert(v.bounds, to: nil))21 return w.frame.intersects(r) ? r : nil22 }23 func snapshot(_ id: String) -> NSImage? {24 guard let v = views[id]?.view?.superview, let rep = v.bitmapImageRepForCachingDisplay(in: v.bounds) else { return nil }25 v.cacheDisplay(in: v.bounds, to: rep)26 let img = NSImage(size: v.bounds.size); img.addRepresentation(rep); return img27 }28}29struct FrameAnchor: NSViewRepresentable {30 let id: String31 final class V: NSView { var id = "" }32 func makeNSView(context: Context) -> V { let v = V(); v.id = id; AnchorRegistry.shared.register(v, for: id); return v }33 func updateNSView(_ v: V, context: Context) {34 if v.id != id { AnchorRegistry.shared.unregister(v, for: v.id); v.id = id }35 AnchorRegistry.shared.register(v, for: id)36 }37 static func dismantleNSView(_ v: V, coordinator: ()) { AnchorRegistry.shared.unregister(v, for: v.id) }38}3940// MARK: Quick Look41/// Drives the system Quick Look panel for one item at a time; the browser moves the selection and hands over the next item.42@MainActor final class QuickLookCoordinator: NSObject, @preconcurrency QLPreviewPanelDataSource, @preconcurrency QLPreviewPanelDelegate {43 static let shared = QuickLookCoordinator()44 private var url: URL?45 private(set) var itemID: String?46 /// Key presses the panel does not use itself (arrows) go back to the browser that opened it.47 var onKey: ((NSEvent) -> Bool)?48 private(set) var presentations = 04950 var isVisible: Bool { QLPreviewPanel.sharedPreviewPanelExists() && QLPreviewPanel.shared().isVisible }51 func show(url: URL, itemID: String) {52 self.url = url; self.itemID = itemID; presentations += 153 guard let panel = QLPreviewPanel.shared() else { return }54 if panel.isVisible { adopt(panel); panel.reloadData() }55 else { panel.makeKeyAndOrderFront(nil); if panel.dataSource == nil { adopt(panel); panel.reloadData() } }56 }57 func close() { if isVisible { QLPreviewPanel.shared().orderOut(nil) } }58 func adopt(_ panel: QLPreviewPanel) { panel.dataSource = self; panel.delegate = self }59 func release(_ panel: QLPreviewPanel) { panel.dataSource = nil; panel.delegate = nil }6061 func numberOfPreviewItems(in panel: QLPreviewPanel!) -> Int { url == nil ? 0 : 1 }62 func previewPanel(_ panel: QLPreviewPanel!, previewItemAt index: Int) -> QLPreviewItem! { url as NSURL? }63 func previewPanel(_ panel: QLPreviewPanel!, handle event: NSEvent!) -> Bool {64 guard let event, event.type == .keyDown else { return false }65 return onKey?(event) ?? false66 }67 /// The panel grows out of the item's picture and shrinks back into it.68 func previewPanel(_ panel: QLPreviewPanel!, sourceFrameOnScreenFor item: QLPreviewItem!) -> NSRect {69 guard !NSWorkspace.shared.accessibilityDisplayShouldReduceMotion, let id = itemID, let r = AnchorRegistry.shared.screenFrame(id) else { return .zero }70 return r71 }72 func previewPanel(_ panel: QLPreviewPanel!, transitionImageFor item: QLPreviewItem!, contentRect: UnsafeMutablePointer<NSRect>!) -> Any! {73 itemID.flatMap { AnchorRegistry.shared.snapshot($0) }74 }75}7677// MARK: Keys78/// Catches key-down events of the window it lives in before the focused control sees them. The handler returns true when it used the key.79struct KeyCatcher: NSViewRepresentable {80 let handler: (NSEvent) -> Bool81 @MainActor final class V: NSView {82 var handler: ((NSEvent) -> Bool)?83 private var monitor: Any?84 override func viewDidMoveToWindow() {85 super.viewDidMoveToWindow()86 if let monitor { NSEvent.removeMonitor(monitor); self.monitor = nil }87 guard window != nil else { return }88 monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in89 guard let self, let w = self.window, event.window === w, w.attachedSheet == nil else { return event }90 return self.handler?(event) == true ? nil : event91 }92 }93 func stop() { if let monitor { NSEvent.removeMonitor(monitor) }; monitor = nil }94 }95 func makeNSView(context: Context) -> V { let v = V(); v.handler = handler; return v }96 func updateNSView(_ v: V, context: Context) { v.handler = handler }97 static func dismantleNSView(_ v: V, coordinator: ()) { v.stop() }98}99extension NSEvent {100 /// True while the person is typing in a text field or a text view of this window.101 @MainActor var isInTextInput: Bool { window?.firstResponder is NSText }102 @MainActor var firstResponderIsTable: Bool { window?.firstResponder is NSTableView }103 var plainModifiers: NSEvent.ModifierFlags { modifierFlags.intersection([.command, .control, .option, .shift]) }104}105enum Key { static let space: UInt16 = 49, `return`: UInt16 = 36, enter: UInt16 = 76, escape: UInt16 = 53, left: UInt16 = 123, right: UInt16 = 124, down: UInt16 = 125, up: UInt16 = 126, tab: UInt16 = 48, delete: UInt16 = 51 }106107// MARK: Window helpers108@MainActor enum WindowTools {109 /// Puts the insertion point in the window's toolbar search field (⌘F).110 static func focusSearch(in window: NSWindow?) {111 guard let window else { return }112 if let item = window.toolbar?.items.compactMap({ $0 as? NSSearchToolbarItem }).first { item.beginSearchInteraction(); return }113 if let field = find(NSSearchField.self, in: window.contentView?.superview) { window.makeFirstResponder(field) }114 }115 private static func find<T: NSView>(_ type: T.Type, in view: NSView?) -> T? {116 guard let view else { return nil }117 if let hit = view as? T { return hit }118 for sub in view.subviews { if let hit = find(type, in: sub) { return hit } }119 return nil120 }121 static var keyBrowserWindow: NSWindow? { NSApp.keyWindow ?? NSApp.mainWindow ?? NSApp.windows.first { $0.isVisible && $0.canBecomeMain } }122}123/// Gives SwiftUI code the NSWindow it is in.124struct WindowReader: NSViewRepresentable {125 let onWindow: (NSWindow?) -> Void126 final class V: NSView { var onWindow: ((NSWindow?) -> Void)?; override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); onWindow?(window) } }127 func makeNSView(context: Context) -> V { let v = V(); v.onWindow = onWindow; return v }128 func updateNSView(_ v: V, context: Context) { v.onWindow = onWindow }129}130131// MARK: Inline rename132/// A text field that takes the focus as soon as it appears, with the name selected up to its extension — the Finder's rename.133struct RenameField: NSViewRepresentable {134 let initial: String135 let isFolder: Bool136 var alignment: NSTextAlignment = .left137 let commit: (String) -> Void138 let cancel: () -> Void139 func makeCoordinator() -> C { C(self) }140 func makeNSView(context: Context) -> NSTextField {141 let f = NSTextField(string: initial)142 f.delegate = context.coordinator; f.isBordered = true; f.bezelStyle = .roundedBezel; f.font = .systemFont(ofSize: NSFont.systemFontSize); f.alignment = alignment143 f.lineBreakMode = .byTruncatingMiddle; f.usesSingleLineMode = true; f.focusRingType = .default144 f.setAccessibilityIdentifier("inline-rename")145 DispatchQueue.main.async { [weak f] in146 guard let f, let w = f.window else { return }147 w.makeFirstResponder(f)148 let stem = isFolder ? (initial as NSString).length : ((initial as NSString).deletingPathExtension as NSString).length149 f.currentEditor()?.selectedRange = NSRange(location: 0, length: stem > 0 ? stem : (initial as NSString).length)150 }151 return f152 }153 func updateNSView(_ f: NSTextField, context: Context) { context.coordinator.parent = self }154 @MainActor final class C: NSObject, NSTextFieldDelegate {155 var parent: RenameField156 private var finished = false157 init(_ p: RenameField) { parent = p }158 func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {159 if selector == #selector(NSResponder.cancelOperation(_:)) { finished = true; parent.cancel(); return true }160 if selector == #selector(NSResponder.insertNewline(_:)) { finished = true; parent.commit(control.stringValue); return true }161 return false162 }163 func controlTextDidEndEditing(_ note: Notification) {164 guard !finished, let f = note.object as? NSTextField else { return }165 finished = true; parent.commit(f.stringValue) // clicking elsewhere keeps what was typed, as in the Finder166 }167 }168}169170#if SPD_DEV171// MARK: Driving the interface from inside the app (development checks)172/// Finds controls of this app's own windows through the system accessibility API addressed to its own process, and173/// presses them — what a person's click does, without a pointer and without touching any other app. (SwiftUI only174/// builds its accessibility tree for a client of that API; asking the views directly returns nothing.)175@MainActor enum AX {176 private static let app = AXUIElementCreateApplication(getpid())177 private static func attr(_ e: AXUIElement, _ name: String) -> AnyObject? { var v: AnyObject?; return AXUIElementCopyAttributeValue(e, name as CFString, &v) == .success ? v : nil }178 private static func children(_ e: AXUIElement) -> [AXUIElement] { (attr(e, kAXChildrenAttribute) as? [AXUIElement]) ?? [] }179 static func identifier(_ e: AXUIElement) -> String { (attr(e, kAXIdentifierAttribute) as? String) ?? "" }180 static func label(_ e: AXUIElement) -> String { (attr(e, kAXDescriptionAttribute) as? String) ?? (attr(e, kAXTitleAttribute) as? String) ?? "" }181 /// Windows of the app, the small ones first (sheets, settings, panels): what a check presses is usually there, and the182 /// main window can hold thousands of cells.183 private static var windows: [AXUIElement] {184 let all = (attr(app, kAXWindowsAttribute) as? [AXUIElement]) ?? []185 return all.sorted { (attr($0, kAXMainAttribute) as? Bool ?? false ? 1 : 0) < (attr($1, kAXMainAttribute) as? Bool ?? false ? 1 : 0) }186 }187 /// Breadth-first, each element once, and never more than `budget` elements: an accessibility tree may contain188 /// cross-references, and a walk without these limits was seen spinning for minutes.189 private static func walk(_ root: AXUIElement, budget: Int = 6000, _ visit: (AXUIElement) -> Bool) -> Bool {190 var queue = [root], seen: Set<AXUIElement> = [root], index = 0191 while index < queue.count, index < budget {192 let e = queue[index]; index += 1193 if visit(e) { return true }194 for c in children(e) where seen.insert(c).inserted { queue.append(c) }195 }196 return false197 }198 static func find(where match: (AXUIElement) -> Bool) -> AXUIElement? {199 var hit: AXUIElement?200 for w in windows { if walk(w, { if match($0) { hit = $0; return true }; return false }) { break } }201 return hit202 }203 static func element(id: String) -> AXUIElement? { find { identifier($0) == id } }204 static func element(labelPrefix: String) -> AXUIElement? { find { label($0).hasPrefix(labelPrefix) } }205 static func count(id: String) -> Int { var n = 0; for w in windows { _ = walk(w, { if identifier($0) == id { n += 1 }; return false }) }; return n }206 /// True when the API answers for this process at all (it needs no permission for one's own process, but a sandbox could refuse it).207 static var available: Bool { !windows.isEmpty }208 @discardableResult static func press(_ e: AXUIElement?) -> Bool { guard let e else { return false }; return AXUIElementPerformAction(e, kAXPressAction as CFString) == .success }209}210#endif211