#if os(macOS) import AppKit import ObjectiveC import XCTest @testable import DocsKit /// Counts the characters whose attributes the text system fixes /// (`-[NSMutableAttributedString fixAttributesInRange:]`, which the text /// storage's lazy fixing calls), while installed. @MainActor enum AttributeFixing { nonisolated(unsafe) static var characters = 0 /// Installs the counter, or (called again) takes it out. static func exchange() { method_exchangeImplementations(class_getInstanceMethod(NSMutableAttributedString.self, #selector(NSMutableAttributedString.fixAttributes(in:)))!, class_getInstanceMethod(NSMutableAttributedString.self, #selector(NSMutableAttributedString.docsCountingFixAttributes(in:)))!) } } extension NSMutableAttributedString { @objc func docsCountingFixAttributes(in range: NSRange) { AttributeFixing.characters += range.length docsCountingFixAttributes(in: range) // the original, exchanged } } /// The Mac's large-document checks and the line-fragment gate (spec /// 2026-11-22 §7 "Incremental pagination" 10, "Measurement and targets"; /// §11 "Large documents", "Line-fragment requests"), on a 200-page /// document built here the way fixtures/generate-large-doc.mjs builds one: /// five paragraphs with bold and italic runs a page, a heading every second /// page and a list every fifth. @MainActor final class PaginationLargeDocumentTests: XCTestCase { static func pages(_ count: Int) -> [CRDTNode] { SurfaceFixture.pages(count) } /// The document in a window, as the app shows it: the desk in a scroll /// view at the default magnification, Pages on. @MainActor final class Window { let state = SurfaceState(width: DocsDeskLayout.paperWidth) let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled, .resizable], backing: .buffered, defer: false) let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 1000, height: 800)) var view: DocsTextView { state.text } init(_ nodes: [CRDTNode], paged: Bool = true) { window.isReleasedWhenClosed = false scroll.hasVerticalScroller = true scroll.allowsMagnification = true scroll.documentView = DocsDeskView(page: state.text) scroll.magnification = 4.0 / 3.0 window.contentView = scroll window.orderFront(nil) state.text.paged = paged state.markPendingOnEdit = false state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil) window.displayIfNeeded() } func close() { window.contentView = nil; window.close() } } private func until(_ what: String, seconds: Double = 30, _ condition: () -> Bool) async throws { let deadline = ContinuousClock.now + .seconds(seconds) while !condition() { guard ContinuousClock.now < deadline else { throw LoopFailure("timed out waiting for \(what)") } try await Task.sleep(for: .milliseconds(5)) } } /// The caret against its glyph, no line across a separator, and the /// page numbers the oracle gives. private func assertEndChecks(_ document: Window, _ message: String, caretShown: Bool = true, file: StaticString = #filePath, line: UInt = #line) { let view = document.view let manager = view.layoutManager! let storage = view.textStorage! document.window.displayIfNeeded() let caret = view.selectedRange().location let glyph = manager.glyphIndexForCharacter(at: min(caret, storage.length - 1)) let caretLine = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil) // As the smoke test checks it: where the text view puts the caret // (its insertion point rect) against the line its glyph is on. let caretRect = manager.boundingRect(forGlyphRange: NSRange(location: glyph, length: 1), in: view.textContainer!) XCTAssertEqual(caretRect.minY, caretLine.minY, accuracy: 1, "caret against glyph: \(message)", file: file, line: line) if caretShown { XCTAssertTrue(view.visibleRect.intersects(caretLine), "the caret's line is shown: \(message)", file: file, line: line) } // The lines laid out near the end: none across a separator. let separators = view.pagination.separators let shown = manager.glyphRange(forBoundingRect: view.visibleRect, in: view.textContainer!) manager.enumerateLineFragments(forGlyphRange: shown) { _, used, _, _, _ in for separator in separators where used.minY < separator + 18 && used.maxY > separator { XCTFail("a line (\(used)) straddles the separator at \(separator): \(message)", file: file, line: line) } } // Page numbers: the separators above the caret, against the oracle. let oracle = PaginationEquivalenceTests.oracle(storage) XCTAssertEqual(separators.count, oracle.separators.count, "pages: \(message)", file: file, line: line) XCTAssertEqual(separators.filter { $0 < caretLine.minY }.count, oracle.separators.filter { $0 < caretLine.minY }.count, "the caret's page: \(message)", file: file, line: line) var range = NSRange() _ = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: &range) if let oracleLine = oracle.lines[manager.characterIndexForGlyph(at: range.location)] { XCTAssertEqual(caretLine.minY, oracleLine.y, accuracy: 0.5, "the caret's line where a whole layout puts it: \(message)", file: file, line: line) } } /// §7 item 10: open, let the idle chunks finish (the live layout still /// holds nothing past the first screen), ⌘↓ to the end and type. func testLargeDocumentAfterMeasuringCompletes() async throws { DocsFonts.register() let document = Window(Self.pages(200)) defer { document.close() } let view = document.view let manager = view.layoutManager! XCTAssertFalse(view.pagination.isComplete, "the rest is measured in idle chunks") try await until("the idle chunks complete") { view.pagination.isComplete } let last = manager.numberOfGlyphs - 1 XCTAssertNil(manager.textContainer(forGlyphAt: last, effectiveRange: nil, withoutAdditionalLayout: true), "the live layout manager holds no layout at the end") view.moveToEndOfDocument(nil) view.insertText("Typed at the end", replacementRange: view.selectedRange()) assertEndChecks(document, "after the idle chunks") // Pages off and on (§7's bound on the toggle: ≤ 250 ms at p200h, // indicative; printed, not held). for paged in [false, true] { let start = ContinuousClock.now #if DOCS_PROBES let pagination = DocsProbes.paginationMs, lines = DocsProbes.lineRequests #endif view.paged = paged view.layoutSubtreeIfNeeded() let laidOut = start.duration(to: .now) document.window.displayIfNeeded() #if DOCS_PROBES print("PAGES TOGGLE p200 to paged=\(paged): \(start.duration(to: .now)) (layout \(laidOut), pagination \(DocsProbes.paginationMs - pagination) ms, \(DocsProbes.lineRequests - lines) line requests)") #endif } // Toggling keeps the scroll offset, not the caret, in view (as before). assertEndChecks(document, "after Pages off and on", caretShown: false) } /// The second variant: the jump comes at open, before the idle chunks /// complete; its contiguous measurement makes the same checks pass. func testLargeDocumentJumpBeforeMeasuringCompletes() async throws { DocsFonts.register() let document = Window(Self.pages(200)) defer { document.close() } let view = document.view XCTAssertFalse(view.pagination.isComplete, "the rest is measured in idle chunks") view.moveToEndOfDocument(nil) view.insertText("Typed at the end", replacementRange: view.selectedRange()) assertEndChecks(document, "jumped before the idle chunks") } /// The text view leaving its window while the rest is still being /// measured (Fable on #173, finding 1): the pending idle chunk must not /// then measure the whole rest in one turn (1.7 s at 400 pages). It /// waits, and measuring resumes once the view is in a window again. func testLeavingTheWindowMidMeasureMeasuresNothingMore() async throws { DocsFonts.register() let document = Window(Self.pages(400)) defer { document.close() } let view = document.view let frontier = view.pagination.frontier XCTAssertLessThan(frontier, view.pagination.units.count, "measuring is still going on") document.window.contentView = nil XCTAssertNil(view.window) try await Task.sleep(for: .milliseconds(300)) XCTAssertEqual(view.pagination.frontier, frontier, "nothing measured out of a window") document.window.contentView = document.scroll view.needsLayout = true document.window.displayIfNeeded() try await until("measuring resumes and completes") { view.pagination.isComplete } } /// Idle chunks are time-boxed, not a fixed count of blocks (Fable on /// #173, finding 2): with no time to spend, a chunk measures one block. func testAnIdleChunkMeasuresWithinItsTimeBudget() async throws { DocsFonts.register() let budget = DocsPagination.chunkBudget DocsPagination.chunkBudget = .zero defer { DocsPagination.chunkBudget = budget } let document = Window(Self.pages(200)) defer { document.close() } let pagination = document.view.pagination let frontier = pagination.frontier XCTAssertLessThan(frontier, pagination.units.count) pagination.update(visibleBottom: -.greatestFiniteMagnitude, idle: true) XCTAssertEqual(pagination.frontier, frontier + 1, "a chunk with no time left measures one block") } /// Typing at the start of a long document while the rest is still /// being measured, then after measuring is done: each later key fixes /// the attributes of its own paragraph, not the rest of the document /// (dd8c49a; Fable's delta review asked for a gate). Without the /// one-time fix when measuring completes, every key fixed everything /// from the first early key to the document's end again. func testKeysAfterMeasuringFixOnlyTheirOwnAttributes() async throws { DocsFonts.register() var nodes = Self.pages(200) let document = Window(nodes) defer { document.close() } let view = document.view let storage = view.textStorage! document.window.makeKeyAndOrderFront(nil) document.window.makeFirstResponder(view) XCTAssertFalse(view.pagination.isComplete) // Keys at the start of the first paragraph, each drawn by its // publication, as the app types them, while the chunks measure and // after. var typed = "" AttributeFixing.exchange() defer { AttributeFixing.exchange() } var fixed: [Int] = [], after: [Int] = [] do { for _ in 0..<40 { let complete = view.pagination.isComplete let block = (storage.string as NSString).range(of: "\n").location + 1 view.setSelectedRange(NSRange(location: block + typed.utf16.count, length: 0)) AttributeFixing.characters = 0 view.insertText("x", replacementRange: view.selectedRange()) typed += "x" var paragraph = nodes[1] var text = paragraph.children![0] text.runs![0].insert = typed + Self.pages(200)[1].children![0].runs![0].insert paragraph.children![0] = text nodes[1] = paragraph document.state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: [paragraph.id]) document.window.displayIfNeeded() fixed.append(AttributeFixing.characters) if complete { after.append(AttributeFixing.characters) } if after.count >= 8 { break } // Eight keys a second, as a person types, the chunks between. try await Task.sleep(for: .milliseconds(125)) } } print("ATTRIBUTE FIXING per key (\(fixed.count - after.count) while measuring, \(after.count) after): \(fixed) of \(storage.length)") XCTAssertEqual(after.count, 8, "keys after measuring") XCTAssertLessThan(after.max() ?? 0, 20_000, "characters fixed per key after measuring, of \(storage.length): \(fixed)") } #if DOCS_PROBES /// While the idle chunks measure what is below the screen, nothing on /// screen moves, so nothing is redrawn (Fable on #173, finding 2: every /// chunk redrew the visible rect, its estimated bottom having moved). func testIdleChunksBelowTheScreenRedrawNothing() async throws { DocsFonts.register() let document = Window(Self.pages(200)) defer { document.close() } let view = document.view XCTAssertFalse(view.pagination.isComplete) let redraws = DocsProbes.paginationRedraws try await until("the idle chunks complete") { view.pagination.isComplete } XCTAssertEqual(DocsProbes.paginationRedraws - redraws, 0, "redraws while measuring below the screen") } /// §7's line-fragment gate, per key at p20 and p200: TextKit's requests /// to the live container (counted inside `lineFragmentRect`, so its own /// re-layout counts) stay within the edited block's lines, the visible /// lines and 8, through the key's display. Pages on and off. func testLineFragmentRequestsPerKey() async throws { DocsFonts.register() for pages in [20, 200] { for paged in [true, false] { let document = Window(Self.pages(pages), paged: paged) defer { document.close() } let view = document.view try await until("measured") { view.pagination.isComplete } let manager = view.layoutManager! let storage = view.textStorage! // The end of a block in the middle of the document, on screen. var block = NSRange() _ = storage.attribute(.docsTopBlock, at: storage.length / 2, longestEffectiveRange: &block, in: NSRange(location: 0, length: storage.length)) view.setSelectedRange(NSRange(location: NSMaxRange(block) - 1, length: 0)) view.scrollRangeToVisible(view.selectedRange()) document.window.displayIfNeeded() try await Task.sleep(for: .milliseconds(50)) var worst: (requests: Int, bound: Int) = (-1, 0) var counts: [Int] = [] for index in 0..<40 { let before = DocsProbes.lineRequests view.insertText(index % 9 == 8 ? " " : "x", replacementRange: view.selectedRange()) document.window.displayIfNeeded() let requests = DocsProbes.lineRequests - before counts.append(requests) var unit = NSRange() _ = storage.attribute(.docsTopBlock, at: max(0, view.selectedRange().location - 1), longestEffectiveRange: &unit, in: NSRange(location: 0, length: storage.length)) var blockLines = 0, visibleLines = 0 manager.enumerateLineFragments(forGlyphRange: manager.glyphRange(forCharacterRange: unit, actualCharacterRange: nil)) { _, _, _, _, _ in blockLines += 1 } manager.enumerateLineFragments(forGlyphRange: manager.glyphRange(forBoundingRect: view.visibleRect, in: view.textContainer!)) { _, _, _, _, _ in visibleLines += 1 } let bound = blockLines + visibleLines + 8 if worst.requests < 0 || requests - bound > worst.requests - worst.bound { worst = (requests, bound) } XCTAssertLessThanOrEqual(requests, bound, "p\(pages) paged=\(paged) key \(index): \(requests) line requests, bound \(bound)") } print("LINE REQUESTS p\(pages) paged=\(paged) per key: \(counts.map(String.init).joined(separator: " ")); closest to the bound: \(worst.requests) against \(worst.bound)") } } } #endif } #endif