| 1 | import AppKit |
| 2 | import DocsKit |
| 3 | import RastrilloApple |
| 4 | import SwiftUI |
| 5 | |
| 6 | @MainActor private enum SmokeRun { static var started = false } |
| 7 | |
| 8 | @main struct DocumentWindowSmoke: App { |
| 9 | @State private var windows = DocsWindows() |
| 10 | var body: some Scene { |
| 11 | Window("Smoke Home", id: "home") { Launcher(windows: windows) } |
| 12 | WindowGroup("Smoke Document", id: "document", for: String.self) { _ in |
| 13 | DocsWorkspace(client: NativeHTTP(origin: URL(string: ProcessInfo.processInfo.environment["DOCS_SMOKE_ORIGIN"]!)!), |
| 14 | signOut: {}, documentID: "fixture", newDocument: ProcessInfo.processInfo.environment["DOCS_SMOKE_DRAFT"] == "1") |
| 15 | }.defaultSize(width: 1120, height: 820) |
| 16 | .restorationBehavior(.disabled) |
| 17 | .commands { DocsEditorCommands(); DocsWindowCommands(windows: windows) } |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | private struct Launcher: View { |
| 22 | let windows: DocsWindows |
| 23 | @Environment(\.openWindow) private var openWindow |
| 24 | var body: some View { |
| 25 | Text("Synthetic document window smoke test").frame(width: 400, height: 200) |
| 26 | .task { |
| 27 | guard !SmokeRun.started else { return } |
| 28 | SmokeRun.started = true |
| 29 | setlinebuf(stdout) |
| 30 | // The Format inspector's app-wide state starts at its default. |
| 31 | UserDefaults.standard.removeObject(forKey: "docs.inspector.open") |
| 32 | NSApp.setActivationPolicy(.regular) |
| 33 | openWindow(id: "document", value: "fixture") |
| 34 | if ProcessInfo.processInfo.environment["DOCS_SMOKE_DRAFT"] == "1" { |
| 35 | let start = ContinuousClock.now |
| 36 | var draftEditor: NSTextView? |
| 37 | var draftWindow: NSWindow? |
| 38 | for _ in 0..<20 { |
| 39 | if let window = NSApp.windows.first(where: { $0.title == docsMacString("Untitled document") }), let editor = window.contentView.flatMap(findEditor) { |
| 40 | draftWindow = window; draftEditor = editor; break |
| 41 | } |
| 42 | try? await Task.sleep(for: .milliseconds(50)) |
| 43 | } |
| 44 | guard let window = draftWindow, let editor = draftEditor else { fatalError("Local editor waited for server creation") } |
| 45 | precondition(start.duration(to: .now) < .seconds(1)) |
| 46 | NSApp.activate(ignoringOtherApps: true) |
| 47 | window.makeKeyAndOrderFront(nil); window.makeFirstResponder(editor) |
| 48 | editor.insertText("Instant draft", replacementRange: NSRange(location: 0, length: 0)) |
| 49 | for _ in 0..<80 { |
| 50 | if window.title == "Window smoke fixture" { break } |
| 51 | try? await Task.sleep(for: .milliseconds(50)) |
| 52 | } |
| 53 | precondition(window.title == "Window smoke fixture") |
| 54 | precondition(window.contentView.flatMap(findEditor) === editor, "Server attachment replaced the editor") |
| 55 | precondition(editor.string.contains("Instant draft"), "Creation lost locally typed text") |
| 56 | print("PASS: draft editor appears before delayed creation and keeps its text view and typing") |
| 57 | await exercise(window, editor: editor) |
| 58 | return |
| 59 | } |
| 60 | for _ in 0..<100 { |
| 61 | if let window = NSApp.windows.first(where: { $0.title == "Window smoke fixture" }), |
| 62 | let editor = window.contentView.flatMap(findEditor), !editor.string.isEmpty { |
| 63 | await exercise(window, editor: editor) |
| 64 | return |
| 65 | } |
| 66 | try? await Task.sleep(for: .milliseconds(100)) |
| 67 | } |
| 68 | fatalError("Document editor did not load") |
| 69 | } |
| 70 | } |
| 71 | @MainActor private func findEditor(_ view: NSView) -> NSTextView? { |
| 72 | if let text = view as? NSTextView, text.accessibilityIdentifier() == "docs.editor" { return text } |
| 73 | return view.subviews.lazy.compactMap(findEditor).first |
| 74 | } |
| 75 | @MainActor private func menuItem(_ title: String, in menu: NSMenu) -> NSMenuItem? { |
| 76 | for item in menu.items { |
| 77 | if item.title == title { return item } |
| 78 | if let submenu = item.submenu, let match = menuItem(title, in: submenu) { return match } |
| 79 | } |
| 80 | return nil |
| 81 | } |
| 82 | @MainActor private func exercise(_ window: NSWindow, editor: NSTextView) async { |
| 83 | NSApp.activate(ignoringOtherApps: true) |
| 84 | window.makeKeyAndOrderFront(nil) |
| 85 | if ProcessInfo.processInfo.environment["DOCS_SMOKE_SPIKE"] == "1" { |
| 86 | try? await Task.sleep(for: .milliseconds(800)) |
| 87 | await HeaderSpike.run(window, title: window.title) |
| 88 | if let path = ProcessInfo.processInfo.environment["DOCS_SMOKE_WINDOW_SHOT"] { |
| 89 | if let frame = window.contentView?.superview, let bitmap = frame.bitmapImageRepForCachingDisplay(in: frame.bounds) { |
| 90 | frame.cacheDisplay(in: frame.bounds, to: bitmap) |
| 91 | try? bitmap.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: path)) |
| 92 | } |
| 93 | } |
| 94 | if ProcessInfo.processInfo.environment["DOCS_SMOKE_SPIKE_ONLY"] == "1" { NSApp.terminate(nil) } |
| 95 | NSApp.activate(ignoringOtherApps: true) |
| 96 | window.makeKeyAndOrderFront(nil) |
| 97 | window.makeFirstResponder(editor) |
| 98 | editor.setSelectedRange(NSRange(location: 1, length: 2)) |
| 99 | try? await Task.sleep(for: .milliseconds(500)) |
| 100 | print("after spike: key=\(NSApp.keyWindow === window) responder=\(String(describing: window.firstResponder)) inspector=\(String(describing: UserDefaults.standard.object(forKey: "docs.inspector.open")))") |
| 101 | } |
| 102 | window.makeFirstResponder(editor) |
| 103 | editor.setSelectedRange(NSRange(location: 1, length: 2)) |
| 104 | try? await Task.sleep(for: .milliseconds(500)) |
| 105 | let original = editor.string |
| 106 | for step in 0..<8 { |
| 107 | try? await Task.sleep(for: .milliseconds(200)) |
| 108 | guard let menu = NSApp.mainMenu else { fatalError("no main menu") } |
| 109 | let title = step.isMultiple(of: 2) ? "Hide Format" : "Show Format" |
| 110 | for top in menu.items { if let submenu = top.submenu { submenu.delegate?.menuNeedsUpdate?(submenu); submenu.update() } } |
| 111 | guard let item = menuItem(title, in: menu), item.isEnabled else { |
| 112 | let view = menu.items.first { $0.submenu?.items.contains { $0.title.hasSuffix("Format") } == true }?.submenu |
| 113 | print("View menu: \(view?.items.map { "\($0.title)[\($0.isEnabled)]" } ?? [])"); fflush(stdout) |
| 114 | fatalError("\(title) unavailable or disabled in a writer's document window (step \(step))") |
| 115 | } |
| 116 | let beforeWidth = editor.enclosingScrollView!.frame.width |
| 117 | let beforeX = editor.frame.minX |
| 118 | item.menu?.performActionForItem(at: item.menu!.index(of: item)) |
| 119 | try? await Task.sleep(for: .milliseconds(200)) |
| 120 | // The floating inspector covers the desk: the scroll view keeps |
| 121 | // its width and the page slides (spec §1, page centring). |
| 122 | precondition(abs(editor.enclosingScrollView!.frame.width - beforeWidth) < 0.5, "Format changed the editor's space") |
| 123 | precondition(abs(editor.frame.minX - beforeX) > 10, "Format did not move the page: \(beforeX) -> \(editor.frame.minX)") |
| 124 | window.setContentSize(NSSize(width: step.isMultiple(of: 2) ? 900 : 1200, height: 760)) |
| 125 | try? await Task.sleep(for: .milliseconds(200)) |
| 126 | window.contentView?.layoutSubtreeIfNeeded() |
| 127 | precondition(window.contentView.flatMap(findEditor) === editor, "Inspector recreated editor") |
| 128 | precondition(editor.string == original && editor.selectedRange() == NSRange(location: 1, length: 2), "Panel lost content or selection") |
| 129 | } |
| 130 | // Save while the title field is still active, without submitting Return. |
| 131 | if let menu = NSApp.mainMenu, let rename = menuItem("Rename document", in: menu) { |
| 132 | rename.menu?.delegate?.menuNeedsUpdate?(rename.menu!) |
| 133 | rename.menu?.update() |
| 134 | guard let currentRename = menuItem("Rename document", in: menu), currentRename.isEnabled else { fatalError("Rename disabled in writable document") } |
| 135 | currentRename.menu?.performActionForItem(at: currentRename.menu!.index(of: currentRename)) |
| 136 | try? await Task.sleep(for: .milliseconds(200)) |
| 137 | func findTitle(_ view: NSView) -> NSTextField? { |
| 138 | if let field = view as? NSTextField, field.isEditable { return field } |
| 139 | return view.subviews.lazy.compactMap(findTitle).first |
| 140 | } |
| 141 | guard let root = window.contentView?.superview, let field = findTitle(root) else { fatalError("Editable header title missing") } |
| 142 | field.selectText(nil) |
| 143 | guard let input = field.currentEditor() as? NSTextView else { fatalError("Title has no field editor") } |
| 144 | input.selectAll(nil); input.insertText("Renamed from header", replacementRange: input.selectedRange()) |
| 145 | try? await Task.sleep(for: .milliseconds(200)) |
| 146 | guard let save = menuItem(docsMacString("Save"), in: menu) else { fatalError("Save unavailable") } |
| 147 | save.menu?.performActionForItem(at: save.menu!.index(of: save)) |
| 148 | try? await Task.sleep(for: .milliseconds(300)) |
| 149 | precondition(window.title == "Renamed from header", "Save lost the active title input") |
| 150 | print("PASS: Save commits active header title without Return") |
| 151 | } else { fatalError("Rename command missing") } |
| 152 | window.makeFirstResponder(editor) |
| 153 | editor.setSelectedRange(NSRange(location: editor.string.utf16.count - 1, length: 0)) |
| 154 | NSApp.activate(ignoringOtherApps: true) |
| 155 | window.makeKeyAndOrderFront(nil) |
| 156 | window.makeFirstResponder(editor) |
| 157 | editor.scrollRangeToVisible(editor.selectedRange()) |
| 158 | try? await Task.sleep(for: .milliseconds(100)) |
| 159 | func indicators(_ view: NSView) -> [NSView] { |
| 160 | (view is NSTextInsertionIndicator ? [view] : []) + view.subviews.flatMap(indicators) |
| 161 | } |
| 162 | func record(_ phase: String) { |
| 163 | let manager = editor.layoutManager! |
| 164 | manager.ensureLayout(for: editor.textContainer!) |
| 165 | let glyph = manager.glyphIndexForCharacter(at: min(editor.selectedRange().location, editor.string.utf16.count - 1)) |
| 166 | let line = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil) |
| 167 | let rect = editor.firstRect(forCharacterRange: editor.selectedRange(), actualRange: nil) |
| 168 | precondition(editor.textContainerOrigin == .zero, "Native caret origin drifted") |
| 169 | precondition(rect.height > 0, "Caret clipped outside editor bounds") |
| 170 | precondition(editor.bounds.maxY >= line.maxY, "Editor shrank below current line") |
| 171 | let visible = indicators(window.contentView!).filter { !$0.isHidden } |
| 172 | precondition(visible.count == 1, "Expected exactly one visible native insertion indicator; count=\(visible.count), phase=\(phase), editable=\(editor.isEditable), attached=\(editor.window === window), key=\(window.isKeyWindow), responder=\(String(describing: window.firstResponder))") |
| 173 | for indicator in visible { |
| 174 | let actual = indicator.convert(indicator.bounds, to: editor) |
| 175 | precondition(abs(actual.minY - line.minY) < 1, "Native insertion indicator disagrees with glyphs") |
| 176 | } |
| 177 | |
| 178 | } |
| 179 | for character in "\nCaret stability after Enter.\nSecond line.\nThird line." { |
| 180 | window.makeKeyAndOrderFront(nil) |
| 181 | window.makeFirstResponder(editor) |
| 182 | let before = editor.selectedRange().location |
| 183 | let typed = character == "\n" ? "\r" : String(character) |
| 184 | let event = NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: typed, charactersIgnoringModifiers: typed, isARepeat: false, keyCode: character == "\n" ? 36 : 0)! |
| 185 | editor.keyDown(with: event) |
| 186 | record("immediate") |
| 187 | let immediate = editor.firstRect(forCharacterRange: editor.selectedRange(), actualRange: nil) |
| 188 | try? await Task.sleep(for: .milliseconds(100)) |
| 189 | precondition(editor.selectedRange().location == before + String(character).utf16.count, "Typing moved selection unexpectedly") |
| 190 | record("settled") |
| 191 | let settled = editor.firstRect(forCharacterRange: editor.selectedRange(), actualRange: nil) |
| 192 | precondition(abs(immediate.minY - settled.minY) < 1, "Caret jumped after publication") |
| 193 | } |
| 194 | #if DEBUG |
| 195 | // ⌘B typed straight behind a letter, through the app's own event |
| 196 | // dispatch (key window, then the menu): the text view's key |
| 197 | // equivalent takes it, and the bold applies to what follows (S1b, |
| 198 | // Fable's delta review 3). |
| 199 | do { |
| 200 | window.makeKeyAndOrderFront(nil) |
| 201 | window.makeFirstResponder(editor) |
| 202 | func key(_ character: String, _ flags: NSEvent.ModifierFlags = [], code: UInt16 = 0) -> NSEvent { |
| 203 | NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags, timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: window.windowNumber, context: nil, characters: character, charactersIgnoringModifiers: character, isARepeat: false, keyCode: code)! |
| 204 | } |
| 205 | let keys = DocsProbes.keyEquivalentCommands, menus = DocsProbes.menuCommands |
| 206 | editor.keyDown(with: key("z")) |
| 207 | NSApp.sendEvent(key("b", .command, code: 11)) |
| 208 | try? await Task.sleep(for: .milliseconds(300)) |
| 209 | editor.keyDown(with: key("w")) |
| 210 | try? await Task.sleep(for: .milliseconds(300)) |
| 211 | precondition(DocsProbes.keyEquivalentCommands == keys + 1, "⌘B did not reach the text view's key equivalent") |
| 212 | precondition(DocsProbes.menuCommands == menus, "⌘B went to the Format menu") |
| 213 | let at = editor.selectedRange().location - 1 |
| 214 | let marks = (editor.textStorage?.attribute(NSAttributedString.Key("OficinaDocsMarks"), at: at, effectiveRange: nil) as? Data) |
| 215 | .flatMap { try? JSONSerialization.jsonObject(with: $0) as? [String: Any] } ?? [:] |
| 216 | precondition(marks["strong"] != nil, "⌘B typed behind a letter did not apply: \(marks)") |
| 217 | print("PASS: ⌘B typed straight behind a letter goes through the text view's key equivalent and applies") |
| 218 | } |
| 219 | #endif |
| 220 | if let path = ProcessInfo.processInfo.environment["DOCS_SMOKE_SCREENSHOT"], let view = window.contentView, |
| 221 | let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) { |
| 222 | view.cacheDisplay(in: view.bounds, to: bitmap) |
| 223 | try? bitmap.representation(using: .png, properties: [:])?.write(to: URL(fileURLWithPath: path)) |
| 224 | } |
| 225 | print("PASS: document loads, Format inspector toggles, window resizes, editor and selection persist, Enter and typing keep caret geometry stable") |
| 226 | NSApp.windows.first(where: { $0.title == "Smoke Home" })?.close() |
| 227 | window.makeKeyAndOrderFront(nil) |
| 228 | guard let menu = NSApp.mainMenu, let appMenu = menu.items.first?.submenu else { fatalError("App menu missing") } |
| 229 | appMenu.delegate?.menuNeedsUpdate?(appMenu) |
| 230 | appMenu.update() |
| 231 | guard let accounts = menuItem(docsMacString("Accounts"), in: appMenu), accounts.isEnabled, |
| 232 | let signOut = menuItem(docsMacString("Sign out"), in: appMenu), !signOut.isEnabled else { |
| 233 | fatalError("Account commands missing or unsafe in document window") |
| 234 | } |
| 235 | accounts.menu!.performActionForItem(at: accounts.menu!.index(of: accounts)) |
| 236 | try? await Task.sleep(for: .milliseconds(300)) |
| 237 | precondition(windows.accountsRequested, "Accounts action did not reach launcher") |
| 238 | precondition(NSApp.windows.contains { $0.title == "Smoke Home" && $0.isVisible }, "Accounts did not reopen Home") |
| 239 | print("PASS: account commands live in app menu and Accounts reopens closed Home") |
| 240 | NSApp.terminate(nil) |
| 241 | } |
| 242 | } |
| 243 | |