oficina / docs Public

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

Plain git — no account needed to clone.

Download

Download this file

1#if os(macOS)
2import AppKit
3import ObjectiveC
4import XCTest
5@testable import DocsKit
6
7/// Counts the characters whose attributes the text system fixes
8/// (`-[NSMutableAttributedString fixAttributesInRange:]`, which the text
9/// storage's lazy fixing calls), while installed.
10@MainActor enum AttributeFixing {
11 nonisolated(unsafe) static var characters = 0
12 /// Installs the counter, or (called again) takes it out.
13 static func exchange() {
14 method_exchangeImplementations(class_getInstanceMethod(NSMutableAttributedString.self, #selector(NSMutableAttributedString.fixAttributes(in:)))!,
15 class_getInstanceMethod(NSMutableAttributedString.self, #selector(NSMutableAttributedString.docsCountingFixAttributes(in:)))!)
16 }
17}
18extension NSMutableAttributedString {
19 @objc func docsCountingFixAttributes(in range: NSRange) {
20 AttributeFixing.characters += range.length
21 docsCountingFixAttributes(in: range) // the original, exchanged
22 }
23}
24
25/// The Mac's large-document checks and the line-fragment gate (spec
26/// 2026-11-22 §7 "Incremental pagination" 10, "Measurement and targets";
27/// §11 "Large documents", "Line-fragment requests"), on a 200-page
28/// document built here the way fixtures/generate-large-doc.mjs builds one:
29/// five paragraphs with bold and italic runs a page, a heading every second
30/// page and a list every fifth.
31@MainActor final class PaginationLargeDocumentTests: XCTestCase {
32 static func pages(_ count: Int) -> [CRDTNode] { SurfaceFixture.pages(count) }
33
34 /// The document in a window, as the app shows it: the desk in a scroll
35 /// view at the default magnification, Pages on.
36 @MainActor final class Window {
37 let state = SurfaceState(width: DocsDeskLayout.paperWidth)
38 let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled, .resizable], backing: .buffered, defer: false)
39 let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 1000, height: 800))
40 var view: DocsTextView { state.text }
41 init(_ nodes: [CRDTNode], paged: Bool = true) {
42 window.isReleasedWhenClosed = false
43 scroll.hasVerticalScroller = true
44 scroll.allowsMagnification = true
45 scroll.documentView = DocsDeskView(page: state.text)
46 scroll.magnification = 4.0 / 3.0
47 window.contentView = scroll
48 window.orderFront(nil)
49 state.text.paged = paged
50 state.markPendingOnEdit = false
51 state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil)
52 window.displayIfNeeded()
53 }
54 func close() { window.contentView = nil; window.close() }
55 }
56
57 private func until(_ what: String, seconds: Double = 30, _ condition: () -> Bool) async throws {
58 let deadline = ContinuousClock.now + .seconds(seconds)
59 while !condition() {
60 guard ContinuousClock.now < deadline else { throw LoopFailure("timed out waiting for \(what)") }
61 try await Task.sleep(for: .milliseconds(5))
62 }
63 }
64
65 /// The caret against its glyph, no line across a separator, and the
66 /// page numbers the oracle gives.
67 private func assertEndChecks(_ document: Window, _ message: String, caretShown: Bool = true, file: StaticString = #filePath, line: UInt = #line) {
68 let view = document.view
69 let manager = view.layoutManager!
70 let storage = view.textStorage!
71 document.window.displayIfNeeded()
72 let caret = view.selectedRange().location
73 let glyph = manager.glyphIndexForCharacter(at: min(caret, storage.length - 1))
74 let caretLine = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
75 // As the smoke test checks it: where the text view puts the caret
76 // (its insertion point rect) against the line its glyph is on.
77 let caretRect = manager.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: view.textContainer!)
78 XCTAssertEqual(caretRect.minY, caretLine.minY, accuracy: 1, "caret against glyph: \(message)", file: file, line: line)
79 if caretShown { XCTAssertTrue(view.visibleRect.intersects(caretLine), "the caret's line is shown: \(message)", file: file, line: line) }
80 // The lines laid out near the end: none across a separator.
81 let separators = view.pagination.separators
82 let shown = manager.glyphRange(forBoundingRect: view.visibleRect, in: view.textContainer!)
83 manager.enumerateLineFragments(forGlyphRange: shown) { _, used, _, _, _ in
84 for separator in separators where used.minY < separator + 18 && used.maxY > separator {
85 XCTFail("a line (\(used)) straddles the separator at \(separator): \(message)", file: file, line: line)
86 }
87 }
88 // Page numbers: the separators above the caret, against the oracle.
89 let oracle = PaginationEquivalenceTests.oracle(storage)
90 XCTAssertEqual(separators.count, oracle.separators.count, "pages: \(message)", file: file, line: line)
91 XCTAssertEqual(separators.filter { $0 < caretLine.minY }.count, oracle.separators.filter { $0 < caretLine.minY }.count, "the caret's page: \(message)", file: file, line: line)
92 var range = NSRange()
93 _ = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: &range)
94 if let oracleLine = oracle.lines[manager.characterIndexForGlyph(at: range.location)] {
95 XCTAssertEqual(caretLine.minY, oracleLine.y, accuracy: 0.5, "the caret's line where a whole layout puts it: \(message)", file: file, line: line)
96 }
97 }
98
99 /// §7 item 10: open, let the idle chunks finish (the live layout still
100 /// holds nothing past the first screen), ⌘↓ to the end and type.
101 func testLargeDocumentAfterMeasuringCompletes() async throws {
102 DocsFonts.register()
103 let document = Window(Self.pages(200))
104 defer { document.close() }
105 let view = document.view
106 let manager = view.layoutManager!
107 XCTAssertFalse(view.pagination.isComplete, "the rest is measured in idle chunks")
108 try await until("the idle chunks complete") { view.pagination.isComplete }
109 let last = manager.numberOfGlyphs - 1
110 XCTAssertNil(manager.textContainer(forGlyphAt: last, effectiveRange: nil, withoutAdditionalLayout: true),
111 "the live layout manager holds no layout at the end")
112 view.moveToEndOfDocument(nil)
113 view.insertText("Typed at the end", replacementRange: view.selectedRange())
114 assertEndChecks(document, "after the idle chunks")
115 // Pages off and on (§7's bound on the toggle: ≤ 250 ms at p200h,
116 // indicative; printed, not held).
117 for paged in [false, true] {
118 let start = ContinuousClock.now
119 #if DOCS_PROBES
120 let pagination = DocsProbes.paginationMs, lines = DocsProbes.lineRequests
121 #endif
122 view.paged = paged
123 view.layoutSubtreeIfNeeded()
124 let laidOut = start.duration(to: .now)
125 document.window.displayIfNeeded()
126 #if DOCS_PROBES
127 print("PAGES TOGGLE p200 to paged=\(paged): \(start.duration(to: .now)) (layout \(laidOut), pagination \(DocsProbes.paginationMs - pagination) ms, \(DocsProbes.lineRequests - lines) line requests)")
128 #endif
129 }
130 // Toggling keeps the scroll offset, not the caret, in view (as before).
131 assertEndChecks(document, "after Pages off and on", caretShown: false)
132 }
133
134 /// The second variant: the jump comes at open, before the idle chunks
135 /// complete; its contiguous measurement makes the same checks pass.
136 func testLargeDocumentJumpBeforeMeasuringCompletes() async throws {
137 DocsFonts.register()
138 let document = Window(Self.pages(200))
139 defer { document.close() }
140 let view = document.view
141 XCTAssertFalse(view.pagination.isComplete, "the rest is measured in idle chunks")
142 view.moveToEndOfDocument(nil)
143 view.insertText("Typed at the end", replacementRange: view.selectedRange())
144 assertEndChecks(document, "jumped before the idle chunks")
145 }
146
147 /// The text view leaving its window while the rest is still being
148 /// measured (Fable on #173, finding 1): the pending idle chunk must not
149 /// then measure the whole rest in one turn (1.7 s at 400 pages). It
150 /// waits, and measuring resumes once the view is in a window again.
151 func testLeavingTheWindowMidMeasureMeasuresNothingMore() async throws {
152 DocsFonts.register()
153 let document = Window(Self.pages(400))
154 defer { document.close() }
155 let view = document.view
156 let frontier = view.pagination.frontier
157 XCTAssertLessThan(frontier, view.pagination.units.count, "measuring is still going on")
158 document.window.contentView = nil
159 XCTAssertNil(view.window)
160 try await Task.sleep(for: .milliseconds(300))
161 XCTAssertEqual(view.pagination.frontier, frontier, "nothing measured out of a window")
162 document.window.contentView = document.scroll
163 view.needsLayout = true
164 document.window.displayIfNeeded()
165 try await until("measuring resumes and completes") { view.pagination.isComplete }
166 }
167
168 /// Idle chunks are time-boxed, not a fixed count of blocks (Fable on
169 /// #173, finding 2): with no time to spend, a chunk measures one block.
170 func testAnIdleChunkMeasuresWithinItsTimeBudget() async throws {
171 DocsFonts.register()
172 let budget = DocsPagination.chunkBudget
173 DocsPagination.chunkBudget = .zero
174 defer { DocsPagination.chunkBudget = budget }
175 let document = Window(Self.pages(200))
176 defer { document.close() }
177 let pagination = document.view.pagination
178 let frontier = pagination.frontier
179 XCTAssertLessThan(frontier, pagination.units.count)
180 pagination.update(visibleBottom: -.greatestFiniteMagnitude, idle: true)
181 XCTAssertEqual(pagination.frontier, frontier + 1, "a chunk with no time left measures one block")
182 }
183
184 /// Typing at the start of a long document while the rest is still
185 /// being measured, then after measuring is done: each later key fixes
186 /// the attributes of its own paragraph, not the rest of the document
187 /// (dd8c49a; Fable's delta review asked for a gate). Without the
188 /// one-time fix when measuring completes, every key fixed everything
189 /// from the first early key to the document's end again.
190 func testKeysAfterMeasuringFixOnlyTheirOwnAttributes() async throws {
191 DocsFonts.register()
192 var nodes = Self.pages(200)
193 let document = Window(nodes)
194 defer { document.close() }
195 let view = document.view
196 let storage = view.textStorage!
197 document.window.makeKeyAndOrderFront(nil)
198 document.window.makeFirstResponder(view)
199 XCTAssertFalse(view.pagination.isComplete)
200 // Keys at the start of the first paragraph, each drawn by its
201 // publication, as the app types them, while the chunks measure and
202 // after.
203 var typed = ""
204 AttributeFixing.exchange()
205 defer { AttributeFixing.exchange() }
206 var fixed: [Int] = [], after: [Int] = []
207 do {
208 for _ in 0..<40 {
209 let complete = view.pagination.isComplete
210 let block = (storage.string as NSString).range(of: "\n").location + 1
211 view.setSelectedRange(NSRange(location: block + typed.utf16.count, length: 0))
212 AttributeFixing.characters = 0
213 view.insertText("x", replacementRange: view.selectedRange())
214 typed += "x"
215 var paragraph = nodes[1]
216 var text = paragraph.children![0]
217 text.runs![0].insert = typed + Self.pages(200)[1].children![0].runs![0].insert
218 paragraph.children![0] = text
219 nodes[1] = paragraph
220 document.state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: [paragraph.id])
221 document.window.displayIfNeeded()
222 fixed.append(AttributeFixing.characters)
223 if complete { after.append(AttributeFixing.characters) }
224 if after.count >= 8 { break }
225 // Eight keys a second, as a person types, the chunks between.
226 try await Task.sleep(for: .milliseconds(125))
227 }
228 }
229 print("ATTRIBUTE FIXING per key (\(fixed.count - after.count) while measuring, \(after.count) after): \(fixed) of \(storage.length)")
230 XCTAssertEqual(after.count, 8, "keys after measuring")
231 XCTAssertLessThan(after.max() ?? 0, 20_000, "characters fixed per key after measuring, of \(storage.length): \(fixed)")
232 }
233
234 #if DOCS_PROBES
235 /// While the idle chunks measure what is below the screen, nothing on
236 /// screen moves, so nothing is redrawn (Fable on #173, finding 2: every
237 /// chunk redrew the visible rect, its estimated bottom having moved).
238 func testIdleChunksBelowTheScreenRedrawNothing() async throws {
239 DocsFonts.register()
240 let document = Window(Self.pages(200))
241 defer { document.close() }
242 let view = document.view
243 XCTAssertFalse(view.pagination.isComplete)
244 let redraws = DocsProbes.paginationRedraws
245 try await until("the idle chunks complete") { view.pagination.isComplete }
246 XCTAssertEqual(DocsProbes.paginationRedraws - redraws, 0, "redraws while measuring below the screen")
247 }
248
249 /// §7's line-fragment gate, per key at p20 and p200: TextKit's requests
250 /// to the live container (counted inside `lineFragmentRect`, so its own
251 /// re-layout counts) stay within the edited block's lines, the visible
252 /// lines and 8, through the key's display. Pages on and off.
253 func testLineFragmentRequestsPerKey() async throws {
254 DocsFonts.register()
255 for pages in [20, 200] {
256 for paged in [true, false] {
257 let document = Window(Self.pages(pages), paged: paged)
258 defer { document.close() }
259 let view = document.view
260 try await until("measured") { view.pagination.isComplete }
261 let manager = view.layoutManager!
262 let storage = view.textStorage!
263 // The end of a block in the middle of the document, on screen.
264 var block = NSRange()
265 _ = storage.attribute(.docsTopBlock, at: storage.length / 2, longestEffectiveRange: &block, in: NSRange(location: 0, length: storage.length))
266 view.setSelectedRange(NSRange(location: NSMaxRange(block) - 1, length: 0))
267 view.scrollRangeToVisible(view.selectedRange())
268 document.window.displayIfNeeded()
269 try await Task.sleep(for: .milliseconds(50))
270 var worst: (requests: Int, bound: Int) = (-1, 0)
271 var counts: [Int] = []
272 for index in 0..<40 {
273 let before = DocsProbes.lineRequests
274 view.insertText(index % 9 == 8 ? " " : "x", replacementRange: view.selectedRange())
275 document.window.displayIfNeeded()
276 let requests = DocsProbes.lineRequests - before
277 counts.append(requests)
278 var unit = NSRange()
279 _ = storage.attribute(.docsTopBlock, at: max(0, view.selectedRange().location - 1), longestEffectiveRange: &unit, in: NSRange(location: 0, length: storage.length))
280 var blockLines = 0, visibleLines = 0
281 manager.enumerateLineFragments(forGlyphRange: manager.glyphRange(forCharacterRange: unit, actualCharacterRange: nil)) { _, _, _, _, _ in blockLines += 1 }
282 manager.enumerateLineFragments(forGlyphRange: manager.glyphRange(forBoundingRect: view.visibleRect, in: view.textContainer!)) { _, _, _, _, _ in visibleLines += 1 }
283 let bound = blockLines + visibleLines + 8
284 if worst.requests < 0 || requests - bound > worst.requests - worst.bound { worst = (requests, bound) }
285 XCTAssertLessThanOrEqual(requests, bound, "p\(pages) paged=\(paged) key \(index): \(requests) line requests, bound \(bound)")
286 }
287 print("LINE REQUESTS p\(pages) paged=\(paged) per key: \(counts.map(String.init).joined(separator: " ")); closest to the bound: \(worst.requests) against \(worst.bound)")
288 }
289 }
290 }
291 #endif
292}
293#endif
294