oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1import AppKit
2import SwiftUI
3
4/// The S2a header spike (spec 2026-11-22 §1, "Spike checklist"), run on the
5/// real document window: Docs' own title area at the toolbar's leading edge,
6/// the system title hidden but still set. Each item prints PASS, FAIL or
7/// UNVERIFIED with what was measured; the run never stops on a FAIL, so the
8/// whole checklist is reported at once. `DOCS_SMOKE_SPIKE=1` runs it.
9@MainActor enum HeaderSpike {
10 static func run(_ window: NSWindow, title: String) async {
11 print("SPIKE: macOS \(ProcessInfo.processInfo.operatingSystemVersionString)")
12 // 0. One title: the window's is the document's, hidden, and no
13 // principal (centred) item draws it again.
14 report("window title is the document title", window.title == title, "title=\(window.title)")
15 report("system title hidden", window.titleVisibility == .hidden, "titleVisibility=\(window.titleVisibility.rawValue)")
16 let toolbar = window.toolbar
17 report("no centred (.principal) item", toolbar?.centeredItemIdentifiers.isEmpty ?? true,
18 "centred=\(toolbar?.centeredItemIdentifiers.map(\.rawValue) ?? [])")
19 let titles = staticTexts(in: window, matching: title)
20 // In process, SwiftUI builds the toolbar's accessibility tree only for
21 // a running assistive technology: zero found means "not measured".
22 if titles.isEmpty { print("SPIKE UNVERIFIED: exactly one visible title — no accessibility tree in process; see the window capture") }
23 else { report("exactly one visible title", titles.count == 1, "static texts reading the title: \(titles.count)") }
24
25 // 6. VoiceOver: the window's name is the title; the title area reads
26 // the title, then the subtitle.
27 report("VoiceOver window name", window.accessibilityTitle() == title, "accessibilityTitle=\(window.accessibilityTitle() ?? "nil")")
28 let order = toolbarTexts(window)
29 print("SPIKE: toolbar accessibility texts in order: \(order)")
30 if let at = order.firstIndex(of: title) {
31 report("VoiceOver reads title then subtitle", order.count > at + 1 && order[at + 1].contains("·") || (order.count > at + 1 && !order[at + 1].isEmpty),
32 "after the title: \(order.count > at + 1 ? order[at + 1] : "nothing")")
33 } else { print("SPIKE UNVERIFIED: VoiceOver reads title then subtitle — no accessibility tree in process (needs VoiceOver on a real Mac)") }
34
35 // 5. Window tabs: the tab shows the document title.
36 report("window tab title", window.tab.title == title, "tab.title=\(window.tab.title)")
37
38 // 3. Overflow at narrow widths: the title area stays; trailing
39 // controls go into the » menu.
40 let original = window.frame
41 for width in [1120.0, 760, 560, 420] {
42 window.setContentSize(NSSize(width: width, height: 700))
43 try? await Task.sleep(for: .milliseconds(400))
44 let all = toolbar?.items.map(\.itemIdentifier.rawValue) ?? []
45 let visible = toolbar?.visibleItems?.map(\.itemIdentifier.rawValue) ?? []
46 let titleShown = window.toolbar?.visibleItems?.first?.itemIdentifier == window.toolbar?.items.first?.itemIdentifier
47 print("SPIKE: width \(Int(width)): items=\(all) visible=\(visible) titleShown=\(titleShown)")
48 }
49 window.setFrame(original, display: true)
50 try? await Task.sleep(for: .milliseconds(400))
51
52 // 2. Double-click on the title area renames.
53 if let frame = titleFrame(window, title) {
54 let point = NSPoint(x: frame.midX, y: frame.midY)
55 click(window, at: point, count: 2)
56 try? await Task.sleep(for: .milliseconds(400))
57 let field = editableField(window.contentView?.superview)
58 let editing = (window.firstResponder as? NSTextView)?.isFieldEditor == true
59 report("the rename field has the keyboard focus", editing, "firstResponder=\(String(describing: window.firstResponder.map { type(of: $0) }))")
60 report("double-click on the title renames", field != nil, "editable field: \(field.map { String(describing: type(of: $0)) } ?? "none")")
61 // Leave the rename as it was: Esc.
62 // Esc leaves the rename as it was (onExitCommand).
63 if field != nil, let esc = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime,
64 windowNumber: window.windowNumber, context: nil, characters: "\u{1b}", charactersIgnoringModifiers: "\u{1b}", isARepeat: false, keyCode: 53) {
65 window.sendEvent(esc)
66 }
67 try? await Task.sleep(for: .milliseconds(400))
68 report("Esc leaves the rename", editableField(window.contentView?.superview) == nil, "field after Esc: \(editableField(window.contentView?.superview) == nil ? "gone" : "still there")")
69 dump(window.toolbar?.items.first?.view, depth: 0)
70 print("SPIKE: in-process NSAccessibility exposes SwiftUI toolbar text only while an assistive technology is running, so VoiceOver's reading order is not measured here")
71
72 // 1. Drag by the title area: a mouse-down there may move the window.
73 let hit = window.contentView?.superview?.hitTest(window.contentView!.superview!.convert(point, from: nil))
74 var chain: [String] = []
75 var view = hit
76 var movable = false
77 while let v = view { chain.append("\(type(of: v)):\(v.mouseDownCanMoveWindow)"); if v.mouseDownCanMoveWindow { movable = true }; view = v.superview }
78 print("SPIKE: hit chain at the title: \(chain.prefix(6))")
79 report("title area can drag the window (mouseDownCanMoveWindow on the hit view)", hit?.mouseDownCanMoveWindow == true, "hit=\(hit.map { String(describing: type(of: $0)) } ?? "nil")")
80 // A real drag, posted as events: AppKit may run the drag through the
81 // window server, which reads the real cursor, so a non-move here is
82 // UNVERIFIED rather than FAIL.
83 let start = window.frame.origin
84 let screenPoint = window.convertPoint(toScreen: point)
85 func post(_ type: NSEvent.EventType, _ dx: CGFloat) {
86 let p = window.convertPoint(fromScreen: NSPoint(x: screenPoint.x + dx, y: screenPoint.y))
87 if let event = NSEvent.mouseEvent(with: type, location: p, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime,
88 windowNumber: window.windowNumber, context: nil, eventNumber: 0, clickCount: 1, pressure: 1) {
89 NSApp.postEvent(event, atStart: false)
90 }
91 }
92 post(.leftMouseDown, 0); for dx in stride(from: 10.0, through: 80, by: 10) { post(.leftMouseDragged, dx) }; post(.leftMouseUp, 80)
93 try? await Task.sleep(for: .milliseconds(800))
94 print("SPIKE \(window.frame.origin != start ? "PASS" : "UNVERIFIED"): posted drag on the title moves the window — \(start) -> \(window.frame.origin)")
95 if window.frame.origin != start { window.setFrameOrigin(start) }
96 _ = movable
97 } else { report("title area found", false, "no accessibility frame for the title") }
98
99 // 2b. Double-click on empty toolbar space still zooms or minimises.
100 let action = UserDefaults.standard.string(forKey: "AppleActionOnDoubleClick") ?? "Maximize"
101 if let frame = titleFrame(window, title) {
102 let empty = NSPoint(x: (frame.maxX + window.frame.width * 0.55) / 2, y: frame.midY)
103 let before = window.frame
104 click(window, at: empty, count: 2)
105 try? await Task.sleep(for: .milliseconds(900))
106 let changed = window.frame != before || window.isMiniaturized
107 report("double-click on empty toolbar (\(action))", changed || action == "None", "frame \(before) -> \(window.frame), miniaturised=\(window.isMiniaturized)")
108 if window.isMiniaturized { window.deminiaturize(nil); try? await Task.sleep(for: .milliseconds(900)) }
109 if window.frame != before { window.setFrame(before, display: true) }
110 }
111
112 // 4. Full screen: the title area and controls stay in the toolbar.
113 window.toggleFullScreen(nil)
114 try? await Task.sleep(for: .seconds(2))
115 let full = window.styleMask.contains(.fullScreen)
116 let titleInFull = window.toolbar?.visibleItems?.first?.view?.window != nil
117 report("full screen keeps the title area", full && titleInFull && window.title == title, "fullScreen=\(full) titleShown=\(titleInFull)")
118 if full { window.toggleFullScreen(nil); try? await Task.sleep(for: .seconds(2)) }
119 }
120
121 static func dump(_ view: NSView?, depth: Int) {
122 guard let view, depth < 12 else { return }
123 let ax = AX(object: view)
124 print("SPIKE AX \(String(repeating: " ", count: depth))\(type(of: view)) role=\(ax.role?.rawValue ?? "-") text=\(ax.text) children=\(ax.children.count)")
125 for child in ax.children where !(child.object is NSView) {
126 print("SPIKE AX \(String(repeating: " ", count: depth + 1))[element] role=\(child.role?.rawValue ?? "-") text=\(child.text) children=\(child.children.map { ($0.role?.rawValue ?? "-") + ":" + $0.text })")
127 }
128 for sub in view.subviews { dump(sub, depth: depth + 1) }
129 }
130 static func report(_ item: String, _ passed: Bool, _ detail: String) {
131 print("SPIKE \(passed ? "PASS" : "FAIL"): \(item) — \(detail)")
132 }
133
134 struct AX {
135 let object: AnyObject
136 var role: NSAccessibility.Role? { object.accessibilityRole?() }
137 var text: String {
138 if let element = object as? NSObject & NSAccessibilityProtocol, let value = element.accessibilityValue() as? String, !value.isEmpty { return value }
139 return (object as? NSObject & NSAccessibilityProtocol)?.accessibilityLabel() ?? object.accessibilityLabel?() ?? ""
140 }
141 var frame: NSRect { object.accessibilityFrame?() ?? .zero }
142 var children: [AX] { (object.accessibilityChildren?() ?? []).map { AX(object: $0 as AnyObject) } }
143 var hidden: Bool { (object as? NSView)?.isHiddenOrHasHiddenAncestor ?? false }
144 }
145 static func all(_ window: NSWindow) -> [AX] {
146 var found: [AX] = []
147 func walk(_ element: AX, depth: Int) {
148 guard depth < 40 else { return }
149 found.append(element)
150 for child in element.children { walk(child, depth: depth + 1) }
151 }
152 walk(AX(object: window), depth: 0)
153 // SwiftUI's toolbar items are their own hosting views, outside the
154 // content view's tree: walk them too.
155 for item in window.toolbar?.items ?? [] { if let view = item.view { walk(AX(object: view), depth: 0) } }
156 return found
157 }
158
159 /// Every accessibility static text in the window that reads `text`.
160 static func staticTexts(in window: NSWindow, matching text: String) -> [AX] {
161 all(window).filter { $0.role == .staticText && $0.text == text && !$0.hidden }
162 }
163
164 /// The static texts in the toolbar's band, in accessibility order.
165 static func toolbarTexts(_ window: NSWindow) -> [String] {
166 let top = window.frame.maxY - 60
167 return all(window).filter { $0.role == .staticText && $0.frame.minY >= top && !$0.text.isEmpty }.map(\.text)
168 }
169
170 /// The title's frame in window coordinates: the accessibility element's,
171 /// or the upper half of the leading (navigation) toolbar item's view.
172 static func titleFrame(_ window: NSWindow, _ title: String) -> NSRect? {
173 if let element = staticTexts(in: window, matching: title).first, element.frame != .zero {
174 return window.convertFromScreen(element.frame)
175 }
176 guard let view = window.toolbar?.items.first?.view, view.window != nil else { return nil }
177 let frame = view.convert(view.bounds, to: nil)
178 return NSRect(x: frame.minX, y: frame.midY, width: min(frame.width, 160), height: frame.height / 2)
179 }
180
181 static func click(_ window: NSWindow, at point: NSPoint, count: Int) {
182 for n in 1...count {
183 for type in [NSEvent.EventType.leftMouseDown, .leftMouseUp] {
184 if let event = NSEvent.mouseEvent(with: type, location: point, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime,
185 windowNumber: window.windowNumber, context: nil, eventNumber: 0, clickCount: n, pressure: 1) {
186 window.sendEvent(event)
187 }
188 }
189 }
190 }
191
192 static func editableField(_ view: NSView?) -> NSTextField? {
193 guard let view else { return nil }
194 if let field = view as? NSTextField, field.isEditable, !field.isHiddenOrHasHiddenAncestor { return field }
195 return view.subviews.lazy.compactMap(editableField).first
196 }
197}
198