| 1 | #if os(macOS) |
| 2 | import AppKit |
| 3 | import XCTest |
| 4 | @testable import DocsKit |
| 5 | |
| 6 | /// Pagination equivalence (spec 2026-11-22 §11; §7 "Incremental |
| 7 | /// pagination" 9): edits typed through the real text view, each checked |
| 8 | /// before its publication arrives and after. Production's break table, |
| 9 | /// every live line-fragment origin (within 0.5pt) and the frame height must |
| 10 | /// equal a fresh run of `DocumentPageLayoutOracle`, today's measurement |
| 11 | /// before S1b, over the same storage. |
| 12 | /// |
| 13 | /// The fixture puts a large heading and an image as the first line after a |
| 14 | /// break, and holds a list taller than a page. |
| 15 | @MainActor final class PaginationEquivalenceTests: XCTestCase { |
| 16 | static func ledger(_ line: Int) -> String { "Ledger, line \(line): water drawn and paid for, and the books kept." } |
| 17 | static let picture = "data:image/png;base64,picture" |
| 18 | |
| 19 | /// 38 one-line paragraphs fill the first page, so the large heading is |
| 20 | /// the first line of page 2; 30 more and an image make the image the |
| 21 | /// first line of page 3; then a list of 70 items (taller than a page) |
| 22 | /// and more paragraphs. |
| 23 | static func fixture() -> [CRDTNode] { |
| 24 | var nodes = (1...38).map { SurfaceFixture.paragraph("a\($0)", ledger($0)) } |
| 25 | nodes.append(SurfaceFixture.heading("h1", "Expansion through the early twentieth century", level: 1)) |
| 26 | nodes += (39...68).map { SurfaceFixture.paragraph("a\($0)", ledger($0)) } |
| 27 | nodes.append(CRDTNode(id: "img", type: "paragraph", children: [CRDTNode(id: "imgi", type: "image", attrs: ["src": picture, "alt": "The second reservoir"])])) |
| 28 | nodes += (69...84).map { SurfaceFixture.paragraph("a\($0)", ledger($0)) } |
| 29 | // Inline code starting lines (its padding narrows the line) and a |
| 30 | // code block. |
| 31 | nodes.append(CRDTNode(id: "code1", type: "paragraph", children: [CRDTNode(id: "code1t", type: "text", runs: [ |
| 32 | CRDTRun(insert: "reservoir.capacity", marks: ["code": .object([:])]), |
| 33 | CRDTRun(insert: " is what the engineer wrote, and the council read it twice before the vote that followed it."), |
| 34 | ])])) |
| 35 | nodes.append(CRDTNode(id: "code2", type: "code_block", children: [CRDTNode(id: "code2t", type: "text", runs: [ |
| 36 | CRDTRun(insert: "reservoir.capacity = 1_200_000 # gallons, measured at the spillway in the spring of 1887\nfilter = .slowSand"), |
| 37 | ])])) |
| 38 | nodes.append(SurfaceFixture.list("list", "bullet_list", (1...70).map { "Item \($0) of a list longer than a page" })) |
| 39 | nodes += (85...130).map { SurfaceFixture.paragraph("a\($0)", ledger($0) + ($0 % 3 == 0 ? " " + String(repeating: "More words that wrap the line. ", count: 3) : "")) } |
| 40 | return nodes |
| 41 | } |
| 42 | static var images: [String: DocsPlatformImage] { [picture: NSImage(size: NSSize(width: 320, height: 180))] } |
| 43 | |
| 44 | struct Plan { |
| 45 | var starts: [Int: CGFloat] |
| 46 | var separators: [CGFloat] |
| 47 | var lines: [Int: CGPoint] |
| 48 | var height: CGFloat |
| 49 | } |
| 50 | |
| 51 | /// Today's measurement (`DocumentPageLayoutOracle`, a copy and its own |
| 52 | /// stack, laid out whole), and the live layout it gave: a copy of the |
| 53 | /// storage laid out with its breaks, as the container read them. |
| 54 | static func oracle(_ storage: NSAttributedString) -> Plan { |
| 55 | let size = CGSize(width: DocsDeskLayout.paperWidth, height: 1_000_000) |
| 56 | let geometry = DocsPageGeometry(viewportWidth: DocsDeskLayout.paperWidth, paged: false) |
| 57 | func stack(_ text: NSAttributedString) -> (NSTextStorage, DocsLayoutManager, DocsPageTextContainer) { |
| 58 | let storage = NSTextStorage(attributedString: text) |
| 59 | let manager = DocsLayoutManager() |
| 60 | let container = DocsPageTextContainer(size: size) |
| 61 | container.lineFragmentPadding = 0 |
| 62 | container.geometry = geometry |
| 63 | container.isMeasurement = true |
| 64 | storage.addLayoutManager(manager) |
| 65 | manager.addTextContainer(container) |
| 66 | return (storage, manager, container) |
| 67 | } |
| 68 | let (measured, measurementManager, measurementContainer) = stack(DocumentPageLayoutOracle.measurementContent(storage)) |
| 69 | measurementManager.ensureLayout(for: measurementContainer) |
| 70 | let result = DocumentPageLayoutOracle.measure(storage: measured, manager: measurementManager, container: measurementContainer) |
| 71 | let (copy, manager, container) = stack(storage) |
| 72 | let tops = OracleTops(result.starts) |
| 73 | container.tops = tops |
| 74 | manager.ensureLayout(for: container) |
| 75 | let lines = Self.lines(manager) |
| 76 | let bottom = manager.numberOfGlyphs > 0 ? manager.lineFragmentRect(forGlyphAt: manager.numberOfGlyphs - 1, effectiveRange: nil).maxY : DocsPageGeometry.verticalMargin |
| 77 | withExtendedLifetime((tops, copy, measured)) {} |
| 78 | return Plan(starts: result.starts, separators: result.separators, lines: lines, height: geometry.documentHeight(usedHeight: bottom)) |
| 79 | } |
| 80 | |
| 81 | static func lines(_ manager: NSLayoutManager) -> [Int: CGPoint] { |
| 82 | var lines: [Int: CGPoint] = [:] |
| 83 | manager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: manager.numberOfGlyphs)) { rect, _, _, glyphs, _ in |
| 84 | lines[manager.characterIndexForGlyph(at: glyphs.location)] = rect.origin |
| 85 | } |
| 86 | return lines |
| 87 | } |
| 88 | |
| 89 | /// What the text view does: its own pass, then (as anything drawing or |
| 90 | /// asking would) the live layout, here all of it. |
| 91 | static func production(_ view: DocsPagedTextView) -> Plan { |
| 92 | view.needsLayout = true |
| 93 | view.layoutSubtreeIfNeeded() |
| 94 | view.pagination.update(visibleBottom: .greatestFiniteMagnitude) |
| 95 | view.layout() |
| 96 | let manager = view.layoutManager! |
| 97 | manager.ensureLayout(for: view.textContainer!) |
| 98 | return Plan(starts: view.pagination.breakStarts, separators: view.pagination.separators, lines: lines(manager), height: view.frame.height) |
| 99 | } |
| 100 | |
| 101 | func assertEquivalent(_ view: DocsPagedTextView, _ message: String, file: StaticString = #filePath, line: UInt = #line) { |
| 102 | let storage = view.textStorage! |
| 103 | // Lines TextKit lays out lazily, before anything forces the whole |
| 104 | // container: the caret's, as typing lays it out. |
| 105 | let caret = view.selectedRange().location |
| 106 | view.layout() |
| 107 | if storage.length > 0 { |
| 108 | let manager = view.layoutManager! |
| 109 | let glyph = manager.glyphIndexForCharacter(at: min(caret, storage.length - 1)) |
| 110 | let lazy = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil) |
| 111 | let expected = Self.oracle(storage) |
| 112 | var range = NSRange() |
| 113 | _ = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: &range) |
| 114 | let start = manager.characterIndexForGlyph(at: range.location) |
| 115 | if let oracleLine = expected.lines[start] { |
| 116 | XCTAssertEqual(lazy.minY, oracleLine.y, accuracy: 0.5, "the caret's line, laid out on its own: \(message)", file: file, line: line) |
| 117 | } |
| 118 | } |
| 119 | let expected = Self.oracle(storage) |
| 120 | let actual = Self.production(view) |
| 121 | XCTAssertEqual(Set(actual.starts.keys), Set(expected.starts.keys), "break blocks: \(message)", file: file, line: line) |
| 122 | for (location, top) in expected.starts { |
| 123 | if let mine = actual.starts[location] { XCTAssertEqual(mine, top, accuracy: 0.5, "break top at \(location): \(message)", file: file, line: line) } |
| 124 | } |
| 125 | XCTAssertEqual(actual.separators.count, expected.separators.count, "separators: \(message)", file: file, line: line) |
| 126 | for (mine, theirs) in zip(actual.separators, expected.separators) { |
| 127 | XCTAssertEqual(mine, theirs, accuracy: 0.5, "separator: \(message)", file: file, line: line) |
| 128 | } |
| 129 | XCTAssertEqual(Set(actual.lines.keys), Set(expected.lines.keys), "line starts: \(message)", file: file, line: line) |
| 130 | var worst: (Int, CGFloat) = (0, 0) |
| 131 | for (start, origin) in expected.lines { |
| 132 | guard let mine = actual.lines[start] else { continue } |
| 133 | let difference = max(abs(mine.y - origin.y), abs(mine.x - origin.x)) |
| 134 | if difference > worst.1 { worst = (start, difference) } |
| 135 | } |
| 136 | XCTAssertLessThanOrEqual(worst.1, 0.5, "line origin at character \(worst.0): \(message)", file: file, line: line) |
| 137 | XCTAssertEqual(actual.height, expected.height, accuracy: 0.5, "frame height: \(message)", file: file, line: line) |
| 138 | } |
| 139 | |
| 140 | // MARK: - The edits |
| 141 | |
| 142 | @MainActor final class Document { |
| 143 | let state: SurfaceState |
| 144 | var nodes: [CRDTNode] |
| 145 | var fresh = 0 |
| 146 | var view: DocsTextView { state.text } |
| 147 | init(_ nodes: [CRDTNode], window: Bool, magnification: CGFloat) { |
| 148 | state = SurfaceState(width: DocsDeskLayout.paperWidth) |
| 149 | self.nodes = nodes |
| 150 | state.text.paged = true |
| 151 | state.surface.imagesChanged(PaginationEquivalenceTests.images) |
| 152 | if window { |
| 153 | let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 1000, height: 800)) |
| 154 | scroll.hasVerticalScroller = true |
| 155 | scroll.allowsMagnification = true |
| 156 | scroll.documentView = DocsDeskView(page: state.text) |
| 157 | scroll.magnification = magnification |
| 158 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled], backing: .buffered, defer: false) |
| 159 | window.isReleasedWhenClosed = false |
| 160 | window.contentView = scroll |
| 161 | self.window = window |
| 162 | } |
| 163 | state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: nil) |
| 164 | } |
| 165 | var window: NSWindow? |
| 166 | func close() { window?.contentView = nil; window?.close() } |
| 167 | |
| 168 | func location(of id: String) -> NSRange { |
| 169 | var found = NSRange(location: NSNotFound, length: 0) |
| 170 | let storage = view.textStorage! |
| 171 | storage.enumerateAttribute(.docsTopBlock, in: NSRange(location: 0, length: storage.length)) { value, range, stop in |
| 172 | if value as? String == id { found = found.location == NSNotFound ? range : NSUnionRange(found, range) } |
| 173 | } |
| 174 | return found |
| 175 | } |
| 176 | func index(of id: String) -> Int { nodes.firstIndex { $0.id == id }! } |
| 177 | func text(of id: String) -> String { nodes[index(of: id)].plainText } |
| 178 | func setText(_ id: String, _ text: String) { |
| 179 | let node = nodes[index(of: id)] |
| 180 | nodes[index(of: id)] = node.type == "heading" |
| 181 | ? SurfaceFixture.heading(id, text, level: Int(node.attrs?["level"] ?? "1") ?? 1) |
| 182 | : SurfaceFixture.paragraph(id, text) |
| 183 | } |
| 184 | /// The caret at `offset` into block `id`'s text, then typed. |
| 185 | func type(_ characters: String, in id: String, at offset: Int? = nil) { |
| 186 | let block = location(of: id) |
| 187 | let at = block.location + (offset ?? (block.length - 1)) |
| 188 | view.setSelectedRange(NSRange(location: at, length: 0)) |
| 189 | for character in characters { |
| 190 | if character == "\n" { view.insertNewline(nil) } else { view.insertText(String(character), replacementRange: view.selectedRange()) } |
| 191 | } |
| 192 | } |
| 193 | func publish(_ dirty: Set<String>?) { |
| 194 | state.pending = false |
| 195 | state.publish(SurfaceFixture.projection(nodes), generation: 1, dirty: dirty) |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | func testProductionPaginationEqualsTheOracle() throws { |
| 200 | DocsFonts.register() |
| 201 | for (window, magnification) in [(false, 4.0 / 3.0), (true, 4.0 / 3.0), (true, 2.0)] { |
| 202 | let label = window ? "zoom \(Int(magnification * 75))%" : "no window" |
| 203 | let document = Document(Self.fixture(), window: window, magnification: magnification) |
| 204 | defer { document.close() } |
| 205 | let view = document.view |
| 206 | assertEquivalent(view, "\(label): open") |
| 207 | let starts = Self.production(view).starts |
| 208 | // The fixture's point: a heading and an image start pages. |
| 209 | XCTAssertNotNil(starts[document.location(of: "h1").location], "\(label): the large heading starts page 2") |
| 210 | XCTAssertNotNil(starts[document.location(of: "img").location], "\(label): the image starts page 3") |
| 211 | |
| 212 | // Typing before a break. |
| 213 | document.type(" Typed here", in: "a30") |
| 214 | assertEquivalent(view, "\(label): typed before a break") |
| 215 | document.setText("a30", Self.ledger(30) + " Typed here") |
| 216 | document.publish(["a30"]) |
| 217 | assertEquivalent(view, "\(label): typed, published") |
| 218 | |
| 219 | // An optimistic Return, then its publication. |
| 220 | let a31 = document.text(of: "a31") |
| 221 | document.type("\n", in: "a31", at: 10) |
| 222 | assertEquivalent(view, "\(label): Return, provisional block") |
| 223 | document.setText("a31", String(a31.prefix(10))) |
| 224 | document.nodes.insert(SurfaceFixture.paragraph("r1", String(a31.dropFirst(10))), at: document.index(of: "a31") + 1) |
| 225 | document.publish(["a31", "r1"]) |
| 226 | assertEquivalent(view, "\(label): Return, published") |
| 227 | |
| 228 | // Backspace at that block's start: one paragraph, two runs. |
| 229 | let r1 = document.location(of: "r1") |
| 230 | view.setSelectedRange(NSRange(location: r1.location, length: 0)) |
| 231 | view.deleteBackward(nil) |
| 232 | assertEquivalent(view, "\(label): Backspace at a block's start") |
| 233 | document.nodes.remove(at: document.index(of: "r1")) |
| 234 | document.setText("a31", a31) |
| 235 | document.publish(["a31", "r1"]) |
| 236 | assertEquivalent(view, "\(label): Backspace, published") |
| 237 | |
| 238 | // A block deleted whole. |
| 239 | let a35 = document.location(of: "a35") |
| 240 | view.setSelectedRange(a35) |
| 241 | view.deleteBackward(nil) |
| 242 | assertEquivalent(view, "\(label): a block deleted") |
| 243 | document.nodes.remove(at: document.index(of: "a35")) |
| 244 | document.publish(["a35", "a34", "a36"]) |
| 245 | assertEquivalent(view, "\(label): delete, published") |
| 246 | |
| 247 | // A paste of three blocks, as DocsTextView.paste puts them in. |
| 248 | let pasted = (1...3).map { SurfaceFixture.paragraph("p\($0)", "Pasted paragraph \($0), long enough to matter to a page.") } |
| 249 | let at = document.location(of: "a20").location |
| 250 | let rendered = NativeTextProjection.render(SurfaceFixture.projection(pasted)) |
| 251 | view.setSelectedRange(NSRange(location: at, length: 0)) |
| 252 | XCTAssertTrue(document.state.surface.clipboardEdit(blocks: [], range: NSRange(location: at, length: 0), replacement: rendered.string)) |
| 253 | view.textStorage!.replaceCharacters(in: NSRange(location: at, length: 0), with: rendered) |
| 254 | view.didChangeText() |
| 255 | assertEquivalent(view, "\(label): three blocks pasted") |
| 256 | document.nodes.insert(contentsOf: pasted, at: document.index(of: "a20")) |
| 257 | document.publish(["p1", "p2", "p3", "a19", "a20"]) |
| 258 | assertEquivalent(view, "\(label): paste, published") |
| 259 | |
| 260 | // Several blocks changed in one flush (a peer's). |
| 261 | for id in ["a5", "a50", "a100"] { document.setText(id, document.text(of: id) + " A peer's longer note that wraps the line onto another one.") } |
| 262 | document.publish(["a5", "a50", "a100"]) |
| 263 | assertEquivalent(view, "\(label): three blocks in one flush") |
| 264 | |
| 265 | // Typing inside a block taller than a page. |
| 266 | let list = document.location(of: "list") |
| 267 | view.setSelectedRange(NSRange(location: list.location + 200, length: 0)) |
| 268 | view.insertText(" typed in the long list", replacementRange: view.selectedRange()) |
| 269 | assertEquivalent(view, "\(label): typed inside a block taller than a page") |
| 270 | |
| 271 | // Typing that moves a break forward, then back. |
| 272 | let before = Self.production(view).starts |
| 273 | let lastOnPage = document.nodes[document.index(of: "h1") - 1].id |
| 274 | let longer = " and more, enough words to need a second line of the paragraph." |
| 275 | document.type(longer, in: lastOnPage) |
| 276 | assertEquivalent(view, "\(label): a break moved") |
| 277 | XCTAssertNotEqual(Self.production(view).starts, before, "\(label): the typing moved a break") |
| 278 | let block = document.location(of: lastOnPage) |
| 279 | view.setSelectedRange(NSRange(location: NSMaxRange(block) - 1 - longer.utf16.count, length: longer.utf16.count)) |
| 280 | view.deleteBackward(nil) |
| 281 | assertEquivalent(view, "\(label): the break moved back") |
| 282 | XCTAssertEqual(Set(Self.production(view).starts.keys), Set(before.keys), "\(label): the break is back") |
| 283 | } |
| 284 | } |
| 285 | |
| 286 | /// A break goes only where a block's run starts a paragraph (§7 |
| 287 | /// Design 4): after a Backspace at a block's start, the second run of |
| 288 | /// the merged paragraph is never a break, and no separator falls inside |
| 289 | /// a paragraph. (The oracle, measuring runs, could put one there.) |
| 290 | func testNoBreakInsideAMergedParagraph() throws { |
| 291 | DocsFonts.register() |
| 292 | var nodes = (1...37).map { SurfaceFixture.paragraph("a\($0)", Self.ledger($0)) } |
| 293 | nodes.append(SurfaceFixture.paragraph("x", "The paragraph a Backspace joins to the next.")) |
| 294 | nodes.append(SurfaceFixture.paragraph("y", String(repeating: "The next one, long enough to cross the page's end. ", count: 6))) |
| 295 | nodes += (40...60).map { SurfaceFixture.paragraph("a\($0)", Self.ledger($0)) } |
| 296 | let document = Document(nodes, window: false, magnification: 1) |
| 297 | let view = document.view |
| 298 | _ = Self.production(view) |
| 299 | let y = document.location(of: "y") |
| 300 | view.setSelectedRange(NSRange(location: y.location, length: 0)) |
| 301 | view.deleteBackward(nil) |
| 302 | let plan = Self.production(view) |
| 303 | let storage = view.textStorage! |
| 304 | // The case this is about: measuring runs, the oracle breaks before |
| 305 | // the second run, inside the paragraph. |
| 306 | let merged = document.location(of: "y").location |
| 307 | XCTAssertNotNil(Self.oracle(storage).starts[merged], "the fixture puts the oracle's break inside the merged paragraph") |
| 308 | XCTAssertNil(plan.starts[merged]) |
| 309 | for location in plan.starts.keys { |
| 310 | XCTAssertTrue(location == 0 || storage.mutableString.character(at: location - 1) == 10, "a break at \(location) is inside a paragraph") |
| 311 | } |
| 312 | let manager = view.layoutManager! |
| 313 | manager.enumerateLineFragments(forGlyphRange: NSRange(location: 0, length: manager.numberOfGlyphs)) { _, used, _, _, _ in |
| 314 | for separator in plan.separators { |
| 315 | XCTAssertFalse(used.minY < separator + 18 && used.maxY > separator, "a line straddles the separator at \(separator)") |
| 316 | } |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | #endif |
| 321 | |
| 322 | #if os(macOS) |
| 323 | /// A seeded fuzz gate against the oracle (Fable on #173, finding 3, after |
| 324 | /// the fuzz of that review): random storage edits on a bare paged text view, |
| 325 | /// with and without a window, compared with a fresh `DocumentPageLayoutOracle` |
| 326 | /// run (paged) or a whole plain layout (pageless) every few edits. It |
| 327 | /// covers what the scripted test does not: edits while measuring is still |
| 328 | /// incomplete, the path where more than 50 blocks changed at once, pageless |
| 329 | /// line origins, two edits in one editing group, Pages toggled, jumps, |
| 330 | /// single idle chunks, and long mixed sequences. Fixed seeds, a few seconds. |
| 331 | @MainActor final class PaginationFuzzTests: XCTestCase { |
| 332 | struct Generator { |
| 333 | var state: UInt64 |
| 334 | mutating func next() -> UInt64 { |
| 335 | state &+= 0x9E37_79B9_7F4A_7C15 |
| 336 | var z = state |
| 337 | z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 |
| 338 | z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB |
| 339 | return z ^ (z >> 31) |
| 340 | } |
| 341 | mutating func below(_ bound: Int) -> Int { bound <= 0 ? 0 : Int(next() % UInt64(bound)) } |
| 342 | } |
| 343 | |
| 344 | static func fixture() -> [CRDTNode] { |
| 345 | var nodes = (1...20).map { SurfaceFixture.paragraph("a\($0)", PaginationEquivalenceTests.ledger($0) + ($0 % 4 == 0 ? " And a longer sentence that wraps onto a second line of the page." : "")) } |
| 346 | nodes.append(SurfaceFixture.heading("h1", "A heading near a break", level: 1)) |
| 347 | nodes += (21...34).map { SurfaceFixture.paragraph("a\($0)", PaginationEquivalenceTests.ledger($0)) } |
| 348 | nodes.append(CRDTNode(id: "img", type: "paragraph", children: [CRDTNode(id: "imgi", type: "image", attrs: ["src": PaginationEquivalenceTests.picture, "alt": "A picture"])])) |
| 349 | nodes.append(SurfaceFixture.list("list", "bullet_list", (1...30).map { "Item \($0) of a long list" })) |
| 350 | nodes.append(CRDTNode(id: "code", type: "paragraph", children: [CRDTNode(id: "codet", type: "text", runs: [ |
| 351 | CRDTRun(insert: "inline.code", marks: ["code": .object([:])]), CRDTRun(insert: " starts this line, which goes on long enough to wrap at the edge."), |
| 352 | ])])) |
| 353 | nodes += (35...44).map { SurfaceFixture.paragraph("a\($0)", PaginationEquivalenceTests.ledger($0)) } |
| 354 | return nodes |
| 355 | } |
| 356 | |
| 357 | @MainActor final class Host { |
| 358 | let view = DocsTextView(frame: CGRect(x: 0, y: 0, width: DocsDeskLayout.paperWidth, height: 700)) |
| 359 | var window: NSWindow? |
| 360 | init(window inWindow: Bool, paged: Bool) { |
| 361 | view.paged = paged |
| 362 | if inWindow { |
| 363 | let scroll = NSScrollView(frame: NSRect(x: 0, y: 0, width: 1000, height: 800)) |
| 364 | scroll.hasVerticalScroller = true |
| 365 | scroll.allowsMagnification = true |
| 366 | scroll.documentView = DocsDeskView(page: view) |
| 367 | scroll.magnification = 4.0 / 3.0 |
| 368 | let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled], backing: .buffered, defer: false) |
| 369 | window.isReleasedWhenClosed = false |
| 370 | window.contentView = scroll |
| 371 | self.window = window |
| 372 | } |
| 373 | } |
| 374 | func close() { window?.contentView = nil; window?.close() } |
| 375 | } |
| 376 | |
| 377 | static func render(_ nodes: [CRDTNode]) -> NSAttributedString { |
| 378 | NativeTextProjection.render(SurfaceFixture.projection(nodes), images: PaginationEquivalenceTests.images) |
| 379 | } |
| 380 | |
| 381 | /// The whole layout pageless production must equal: the storage laid |
| 382 | /// out plainly in the live container's geometry, no breaks. |
| 383 | static func plain(_ storage: NSAttributedString) -> PaginationEquivalenceTests.Plan { |
| 384 | let copy = NSTextStorage(attributedString: storage) |
| 385 | let manager = DocsLayoutManager() |
| 386 | let container = DocsPageTextContainer(size: CGSize(width: DocsDeskLayout.paperWidth, height: 1_000_000)) |
| 387 | container.lineFragmentPadding = 0 |
| 388 | container.geometry = DocsPageGeometry(viewportWidth: DocsDeskLayout.paperWidth, paged: false) |
| 389 | container.isMeasurement = true |
| 390 | copy.addLayoutManager(manager) |
| 391 | manager.addTextContainer(container) |
| 392 | manager.ensureLayout(for: container) |
| 393 | let bottom = manager.numberOfGlyphs > 0 ? manager.lineFragmentRect(forGlyphAt: manager.numberOfGlyphs - 1, effectiveRange: nil).maxY : DocsPageGeometry.verticalMargin |
| 394 | let lines = PaginationEquivalenceTests.lines(manager) |
| 395 | withExtendedLifetime(copy) {} |
| 396 | return .init(starts: [:], separators: [], lines: lines, height: container.geometry.documentHeight(usedHeight: bottom)) |
| 397 | } |
| 398 | |
| 399 | /// After a Backspace at a block's start, until its publication, one |
| 400 | /// paragraph holds two runs; the oracle may break between them, and |
| 401 | /// production may not (§7 Design 4): no comparison then. |
| 402 | static func transient(_ storage: NSAttributedString) -> Bool { |
| 403 | let characters = storage.string as NSString |
| 404 | var found = false |
| 405 | storage.enumerateAttribute(.docsTopBlock, in: NSRange(location: 0, length: storage.length)) { _, range, stop in |
| 406 | if range.location > 0, characters.character(at: range.location - 1) != 10 { found = true; stop.pointee = true } |
| 407 | } |
| 408 | return found |
| 409 | } |
| 410 | |
| 411 | func testSeededEditsMatchTheOracle() throws { |
| 412 | DocsFonts.register() |
| 413 | var comparisons = 0, incomplete = 0, stalePath = 0 |
| 414 | let start = ContinuousClock.now |
| 415 | for seed in UInt64(1)...8 { |
| 416 | var random = Generator(state: seed &* 7919) |
| 417 | let host = Host(window: seed % 2 == 0, paged: seed % 4 != 3) |
| 418 | defer { host.close() } |
| 419 | let view = host.view |
| 420 | let storage = view.textStorage! |
| 421 | storage.setAttributedString(Self.render(Self.fixture())) |
| 422 | var fresh = 0 |
| 423 | func paragraphStarts() -> [Int] { |
| 424 | let characters = storage.string as NSString |
| 425 | var starts = [0] |
| 426 | for index in 0..<max(0, storage.length - 1) where characters.character(at: index) == 10 { starts.append(index + 1) } |
| 427 | return starts |
| 428 | } |
| 429 | func attributes(at location: Int) -> [NSAttributedString.Key: Any] { |
| 430 | storage.length == 0 ? [:] : storage.attributes(at: min(max(0, location - 1), storage.length - 1), effectiveRange: nil) |
| 431 | } |
| 432 | func block(at location: Int) -> NSRange { |
| 433 | var range = NSRange() |
| 434 | _ = storage.attribute(.docsTopBlock, at: min(location, storage.length - 1), longestEffectiveRange: &range, in: NSRange(location: 0, length: storage.length)) |
| 435 | return range |
| 436 | } |
| 437 | func newBlocks(_ count: Int) -> NSAttributedString { |
| 438 | let nodes: [CRDTNode] = (0..<count).map { _ in |
| 439 | fresh += 1 |
| 440 | return fresh % 3 == 0 ? SurfaceFixture.heading("n\(seed)-\(fresh)", "A pasted heading \(fresh)", level: 1 + fresh % 3) |
| 441 | : SurfaceFixture.paragraph("n\(seed)-\(fresh)", "A pasted paragraph \(fresh), with enough words in it to wrap the line once or twice.") |
| 442 | } |
| 443 | return Self.render(nodes) |
| 444 | } |
| 445 | func edit() { |
| 446 | let length = storage.length |
| 447 | let at = random.below(max(1, length - 1)) |
| 448 | switch random.below(13) { |
| 449 | case 0, 1: storage.replaceCharacters(in: NSRange(location: at, length: 0), with: NSAttributedString(string: "x", attributes: attributes(at: at))) |
| 450 | case 2: storage.replaceCharacters(in: NSRange(location: at, length: 0), with: NSAttributedString(string: " words enough to wrap this line onto the next one of the page", attributes: attributes(at: at))) |
| 451 | case 3: storage.replaceCharacters(in: NSRange(location: at, length: 0), with: NSAttributedString(string: "\n", attributes: attributes(at: at))) |
| 452 | case 4: |
| 453 | let range = block(at: at) |
| 454 | if range.length < length { storage.replaceCharacters(in: range, with: "") } |
| 455 | case 5: |
| 456 | let paragraph = (storage.string as NSString).paragraphRange(for: NSRange(location: at, length: 0)) |
| 457 | let cut = NSRange(location: paragraph.location + random.below(max(1, paragraph.length - 1)), length: min(5, max(0, paragraph.length - 2))) |
| 458 | if NSMaxRange(cut) < NSMaxRange(paragraph) { storage.replaceCharacters(in: cut, with: "") } |
| 459 | case 6: |
| 460 | let starts = paragraphStarts() |
| 461 | storage.replaceCharacters(in: NSRange(location: starts[random.below(starts.count)], length: 0), with: newBlocks(1 + random.below(4))) |
| 462 | case 7: |
| 463 | let range = block(at: at) |
| 464 | if range.length < length { storage.replaceCharacters(in: range, with: newBlocks(1)) } |
| 465 | case 8: |
| 466 | storage.beginEditing() |
| 467 | storage.replaceCharacters(in: NSRange(location: at / 2, length: 0), with: NSAttributedString(string: "early words that wrap the line ", attributes: attributes(at: at / 2))) |
| 468 | let later = min(storage.length - 1, at + storage.length / 2) |
| 469 | storage.replaceCharacters(in: NSRange(location: later, length: 0), with: NSAttributedString(string: "\n", attributes: attributes(at: later))) |
| 470 | storage.endEditing() |
| 471 | case 9: |
| 472 | // A Backspace at a block's start, then its publication: |
| 473 | // the merged paragraph drawn as one block. |
| 474 | let starts = paragraphStarts().filter { $0 > 0 } |
| 475 | guard let joint = starts.isEmpty ? nil : starts[random.below(starts.count)] else { return } |
| 476 | storage.replaceCharacters(in: NSRange(location: joint - 1, length: 1), with: "") |
| 477 | view.layout() |
| 478 | let merged = (storage.string as NSString).paragraphRange(for: NSRange(location: joint - 1, length: 0)) |
| 479 | let text = (storage.string as NSString).substring(with: merged).trimmingCharacters(in: .newlines) |
| 480 | fresh += 1 |
| 481 | storage.replaceCharacters(in: merged, with: Self.render([SurfaceFixture.paragraph("m\(seed)-\(fresh)", text.isEmpty ? "Merged." : text)])) |
| 482 | case 10: view.paged.toggle() |
| 483 | case 11: |
| 484 | view.scrollRangeToVisible(NSRange(location: at, length: 0)) |
| 485 | view.pagination.update(visibleBottom: -.greatestFiniteMagnitude, idle: true) |
| 486 | default: |
| 487 | // Every block's attributes at once: more than 50 stale |
| 488 | // blocks (in a window, the full path's visible-first order). |
| 489 | if view.pagination.units.filter({ !$0.measured }).isEmpty && view.pagination.units.count > DocsPagination.staleLimit { stalePath += 1 } |
| 490 | // Half the time something that moves every line (as a font |
| 491 | // every block uses arriving would), else metadata only. |
| 492 | if random.below(2) == 0 { |
| 493 | storage.addAttribute(.kern, value: CGFloat(random.below(4)) * 0.1, range: NSRange(location: 0, length: storage.length)) |
| 494 | } else { |
| 495 | storage.addAttribute(NSAttributedString.Key("FuzzMetadata"), value: random.below(1000), range: NSRange(location: 0, length: storage.length)) |
| 496 | } |
| 497 | } |
| 498 | } |
| 499 | func compare(_ label: String) { |
| 500 | guard !Self.transient(storage) else { return } |
| 501 | if !view.pagination.isComplete { incomplete += 1 } |
| 502 | comparisons += 1 |
| 503 | let expected = view.paged ? PaginationEquivalenceTests.oracle(storage) : Self.plain(storage) |
| 504 | let actual = PaginationEquivalenceTests.production(view) |
| 505 | XCTAssertEqual(Set(actual.starts.keys), Set(expected.starts.keys), "breaks: \(label)") |
| 506 | for (location, top) in expected.starts { if let mine = actual.starts[location] { XCTAssertEqual(mine, top, accuracy: 0.5, "break top: \(label)") } } |
| 507 | XCTAssertEqual(actual.separators.count, expected.separators.count, "separators: \(label)") |
| 508 | for (mine, theirs) in zip(actual.separators, expected.separators) { XCTAssertEqual(mine, theirs, accuracy: 0.5, "separator: \(label)") } |
| 509 | XCTAssertEqual(Set(actual.lines.keys), Set(expected.lines.keys), "line starts: \(label)") |
| 510 | let worst = expected.lines.map { start, origin in actual.lines[start].map { max(abs($0.y - origin.y), abs($0.x - origin.x)) } ?? 0 }.max() ?? 0 |
| 511 | XCTAssertLessThanOrEqual(worst, 0.5, "line origins: \(label)") |
| 512 | XCTAssertEqual(actual.height, expected.height, accuracy: 0.5, "frame height: \(label)") |
| 513 | } |
| 514 | view.layout() |
| 515 | for step in 0..<80 { |
| 516 | edit() |
| 517 | // Sometimes a turn passes (the text view lays out) before the next edit. |
| 518 | if random.below(2) == 0 { view.layout() } |
| 519 | if step % 4 == 3 { compare("seed \(seed) step \(step) (\(view.paged ? "paged" : "pageless"), \(host.window == nil ? "no window" : "window"))") } |
| 520 | // Lines laid out between edits stay laid out, so a missed |
| 521 | // invalidation shows as a stale origin later. |
| 522 | if step % 4 == 1, storage.length > 0 { |
| 523 | view.layoutManager!.ensureLayout(forCharacterRange: NSRange(location: random.below(storage.length), length: 1)) |
| 524 | } |
| 525 | } |
| 526 | } |
| 527 | print("PAGINATION FUZZ: \(comparisons) comparisons, \(incomplete) with measuring incomplete, \(stalePath) whole-document attribute edits, \(start.duration(to: .now))") |
| 528 | XCTAssertGreaterThan(incomplete, 0, "edits compared while measuring was incomplete") |
| 529 | XCTAssertGreaterThan(stalePath, 0, "the more-than-50-stale path ran") |
| 530 | } |
| 531 | } |
| 532 | #endif |
| 533 | |