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(iOS) && DOCS_PROBES
2import UIKit
3import XCTest
4@testable import DocsKit
5
6/// The iPhone's large-document check (spec 2026-11-22 §7 "iPhone layout",
7/// §11 "Large documents"; plan S3 acceptance, carried from S1b #173), as a
8/// probe: skipped unless DOCS_PHONE_LARGE is set (TEST_RUNNER_DOCS_PHONE_LARGE=1
9/// through xcodebuild). A 200-page document, paged, on the production text
10/// view (TextKit 2 from S3):
11/// - opening lays out no further than the first screen, in ≤ 250 ms of
12/// main thread;
13/// - 40 keys in its middle, some making a new line: main-thread time per key
14/// ≤ 8 ms median, and no key over 16.7 ms;
15/// - jump to the end before anything past the first screen is laid out:
16/// the caret is on its glyph's line, no line crosses a page gap, and the
17/// lines near the end are where a whole layout puts them.
18/// Then the same document on TextKit 1 (`TextKit1PagedView`, the view as it
19/// shipped before S3), for the 72.7 pt caret finding.
20@MainActor final class PhoneLargeDocumentTests: XCTestCase {
21 private static let pages = 200
22
23 func testALongPagedDocumentOnTextKit2() async throws {
24 guard ProcessInfo.processInfo.environment["DOCS_PHONE_LARGE"] != nil else { throw XCTSkip("Set DOCS_PHONE_LARGE") }
25 DocsFonts.register()
26 let projection = SurfaceFixture.projection(SurfaceFixture.pages(Self.pages))
27 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
28 window.makeKeyAndVisible()
29 defer { window.isHidden = true }
30 let text = DocsTextView(frame: window.bounds)
31 text.paged = true
32 window.addSubview(text)
33 defer { text.removeFromSuperview() }
34 let surface = DocumentSurface()
35 var hooks = DocumentSurface.Hooks()
36 hooks.edit = { _ in true }
37 surface.hooks = hooks
38 surface.isEditable = true
39 surface.attach(text)
40 let layout = try XCTUnwrap(text.textLayoutManager, "TextKit 2")
41 let storage = text.textStorage
42 // Open.
43 var fragments = DocsProbes.layoutFragments
44 let rendering = DocsProbes.wholeRenderMs, layouts = DocsProbes.textLayoutMs
45 var start = ContinuousClock.now
46 surface.apply(DocumentSurface.Publication(generation: 1, projection: projection, revision: 1, dirty: nil))
47 text.layoutIfNeeded()
48 let open = Self.ms(start)
49 let openFragments = DocsProbes.layoutFragments - fragments
50 let paragraphs = text.pages.paragraphs.count
51 print(String(format: "PHONE LARGE textkit2: open breakdown: whole render %.1f ms, text view layout %.1f ms", DocsProbes.wholeRenderMs - rendering, DocsProbes.textLayoutMs - layouts))
52 print(String(format: "PHONE LARGE textkit2: open %.1f ms, %d of %d paragraphs laid out", open, openFragments, paragraphs))
53 XCTAssertNil(text.layoutManager(peeking: true), "still TextKit 2")
54 XCTAssertLessThan(openFragments, 200, "opening lays out about the first screen, not \(paragraphs) paragraphs")
55 // §7: a timing target holds within 20% of its value (median of three runs).
56 XCTAssertLessThanOrEqual(open, 250 * 1.2, "first screen within 250 ms of main thread")
57
58 // Keys in the middle, some making a new line: scrolled there as a
59 // person would (TextKit 2's scrollRangeToVisible does not scroll to
60 // text it has not laid out), then typing in a paragraph on screen.
61 text.setContentOffset(CGPoint(x: 0, y: text.contentSize.height / 2), animated: false)
62 text.layoutIfNeeded()
63 let shown = try XCTUnwrap(layout.textViewportLayoutController.viewportRange)
64 let content = try XCTUnwrap(layout.textContentManager)
65 let middle = Self.lineStart(storage.string as NSString, near: content.offset(from: content.documentRange.location, to: shown.location) + 200)
66 text.selectedRange = NSRange(location: middle, length: 0)
67 text.layoutIfNeeded()
68 try await Task.sleep(for: .milliseconds(300))
69 let measuredBefore = text.pages.paragraphs.filter { $0.height != nil }.count
70 var keys: [Double] = [], newLineKeys: [Double] = [], perKeyFragments: [Int] = [], perKeyMeasured: [Int] = [], perKeyBreaks: [Int] = []
71 let wrap = String(repeating: "Words to wrap the line. ", count: 3)
72 for index in 0..<40 {
73 let typed = index % 8 == 4 ? wrap : "x"
74 let range = text.selectedRange
75 fragments = DocsProbes.layoutFragments
76 let measured = DocsProbes.measureFragments, breaks = DocsProbes.pageBreakChanges
77 start = .now
78 if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: typed) ?? true {
79 storage.replaceCharacters(in: range, with: NSAttributedString(string: typed, attributes: text.typingAttributes))
80 text.selectedRange = NSRange(location: range.location + typed.utf16.count, length: 0)
81 text.delegate?.textViewDidChange?(text)
82 }
83 text.layoutIfNeeded()
84 let elapsed = Self.ms(start)
85 keys.append(elapsed)
86 if typed == wrap { newLineKeys.append(elapsed) }
87 perKeyFragments.append(DocsProbes.layoutFragments - fragments)
88 perKeyMeasured.append(DocsProbes.measureFragments - measured)
89 perKeyBreaks.append(DocsProbes.pageBreakChanges - breaks)
90 try await Task.sleep(for: .milliseconds(5))
91 }
92 let sorted = keys.sorted()
93 print(String(format: "PHONE LARGE textkit2: per key median %.2f ms, max %.2f ms; keys making new lines max %.2f ms; fragments per key median %d max %d",
94 sorted[sorted.count / 2], sorted.last ?? 0, newLineKeys.max() ?? 0,
95 perKeyFragments.sorted()[perKeyFragments.count / 2], perKeyFragments.max() ?? 0))
96 let onScreen = try XCTUnwrap(layout.textViewportLayoutController.viewportRange)
97 let typedAt = text.selectedRange.location
98 XCTAssertTrue(content.offset(from: content.documentRange.location, to: onScreen.location) <= typedAt
99 && typedAt <= content.offset(from: content.documentRange.location, to: onScreen.endLocation), "typed on screen")
100 print("PHONE LARGE textkit2: typing at \(typedAt), \(measuredBefore) paragraphs measured when it began")
101 print("PHONE LARGE textkit2: per key, fragments measuring \(perKeyMeasured.max() ?? 0) at most, page breaks moved \(perKeyBreaks.reduce(0, +)) in all")
102 XCTAssertLessThanOrEqual(sorted[sorted.count / 2], 8, "per key ≤ 8 ms median")
103 XCTAssertLessThanOrEqual(newLineKeys.max() ?? 0, 16.7, "no stall over 16.7 ms on a key that changes a line count")
104
105 // A peer's keys on page 2 while the screen is at the middle (Fable on
106 // #180), through the surface's publication path as a peer's change
107 // arrives, every fourth adding a line: main-thread time from the
108 // publication to the screen laid out. Nothing on screen moves.
109 // As a session would be by then: the rest measured while idle.
110 let idleDeadline = Date().addingTimeInterval(20)
111 while (text.pages.firstUnmeasured != nil || text.pages.settleFrom != nil || text.pages.hasChanges) && Date() < idleDeadline {
112 try await Task.sleep(for: .milliseconds(20))
113 }
114 text.layoutIfNeeded()
115 var nodes = SurfaceFixture.pages(Self.pages)
116 let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p1-2" })
117 var peerKeys: [Double] = [], peerLineKeys: [Double] = [], cascades: [(ms: Double, breaks: Int)] = [], plain: [Double] = []
118 var publications: [Double] = []
119 let relaid = DocsProbes.relaidParagraphs
120 for index in 0..<20 {
121 let typed = index % 4 == 3 ? wrap : "x"
122 nodes[peer].children?[0].runs?[0].insert += typed
123 let next = SurfaceFixture.projection(nodes)
124 // What the editor keeps still (F4): the line at the screen's
125 // middle (the caret is not on screen here: no first responder).
126 let middle = text.contentOffset.y + text.adjustedContentInset.top
127 + (text.bounds.height - text.adjustedContentInset.top - text.adjustedContentInset.bottom) / 2 - text.textContainerInset.top
128 let anchor = layout.textLayoutFragment(for: CGPoint(x: 0, y: middle))
129 .map { content.offset(from: content.documentRange.location, to: $0.rangeInElement.location) } ?? 0
130 func screenY(_ at: Int) -> CGFloat {
131 (content.location(content.documentRange.location, offsetBy: at).flatMap { layout.textLayoutFragment(for: $0)?.layoutFragmentFrame.minY } ?? 0) - text.contentOffset.y
132 }
133 let anchorY = screenY(anchor), breaks = DocsProbes.pageBreakChanges, published = DocsProbes.publicationMs
134 start = .now
135 surface.apply(DocumentSurface.Publication(generation: 1, projection: next, revision: UInt64(2 + index), dirty: ["p1-2"]))
136 text.layoutIfNeeded()
137 let elapsed = Self.ms(start)
138 XCTAssertEqual(screenY(anchor + typed.utf16.count), anchorY, accuracy: 0.5, "peer key \(index): nothing on screen moved")
139 peerKeys.append(elapsed)
140 publications.append(DocsProbes.publicationMs - published)
141 if typed == wrap { peerLineKeys.append(elapsed) }
142 let moved = DocsProbes.pageBreakChanges - breaks
143 if moved > 1 { cascades.append((elapsed, moved)) } else { plain.append(elapsed) }
144 try await Task.sleep(for: .milliseconds(5))
145 }
146 let peerSorted = peerKeys.sorted()
147 print(String(format: "PHONE LARGE textkit2: a peer's keys on page 2, screen at the middle: median %.2f ms (publication median %.2f ms), max %.2f ms; adding a line max %.2f ms; %d paragraphs laid out again",
148 peerSorted[peerSorted.count / 2], publications.sorted()[publications.count / 2], peerSorted.last ?? 0, peerLineKeys.max() ?? 0, DocsProbes.relaidParagraphs - relaid))
149 print("PHONE LARGE textkit2: peer keys moving at most one break, max \(String(format: "%.2f", plain.max() ?? 0)) ms; cascading breaks above the screen: \(cascades.map { String(format: "%.2f ms (%d breaks)", $0.ms, $0.breaks) })")
150 XCTAssertTrue(surface.content.string.contains(nodes[peer].plainText), "the peer's keys arrived")
151 XCTAssertEqual(DocsProbes.relaidParagraphs - relaid, 0, "nothing laid out again from the top")
152 // §7: a timing target holds within 20% of its value (median of three runs).
153 XCTAssertLessThanOrEqual(peerSorted[peerSorted.count / 2], 16.7, "a peer's key ≤ 16.7 ms median")
154 XCTAssertLessThanOrEqual(plain.max() ?? 0, 16.7 * 1.2, "no peer key over 16.7 ms that moves at most one break")
155
156 // A fresh view for the jump, laid out no further than its first screen.
157 let jumper = DocsTextView(frame: window.bounds)
158 jumper.paged = true
159 window.addSubview(jumper)
160 defer { jumper.removeFromSuperview() }
161 jumper.attributedText = NativeTextProjection.render(projection)
162 jumper.layoutIfNeeded()
163 let end = jumper.textStorage.length - 8
164 fragments = DocsProbes.layoutFragments
165 start = .now
166 // As the scroll indicator dragged to the bottom does: TextKit 2's
167 // scrollRangeToVisible does not scroll to text it has not laid out.
168 jumper.setContentOffset(CGPoint(x: 0, y: max(0, jumper.contentSize.height - jumper.bounds.height)), animated: false)
169 jumper.layoutIfNeeded()
170 jumper.selectedRange = NSRange(location: end, length: 0)
171 jumper.scrollRangeToVisible(jumper.selectedRange)
172 jumper.layoutIfNeeded()
173 let jump = Self.ms(start), jumpFragments = DocsProbes.layoutFragments - fragments
174 // Breaks through the screen's end: those below it are built while
175 // idle, before the screen gets to them.
176 let screenEnd = jumper.textLayoutManager.flatMap { layout in
177 layout.textViewportLayoutController.viewportRange.flatMap { range in
178 layout.textContentManager.map { $0.offset(from: $0.documentRange.location, to: range.endLocation) } } } ?? jumper.textStorage.length
179 let lastShown = (jumper.pages.paragraph(at: screenEnd) ?? 0) + 1
180 let breaks = jumper.pages.paragraphs.indices.filter { jumper.pages.paragraphs[$0].extra > 0 && $0 <= lastShown }
181 // Every break laid out where it was placed.
182 if let layout = jumper.textLayoutManager, let content = layout.textContentManager {
183 var off = 0, worst: CGFloat = 0
184 for index in breaks {
185 guard let location = content.location(content.documentRange.location, offsetBy: jumper.pages.range(of: index).location),
186 let fragment = layout.textLayoutFragment(for: location), fragment.state == .layoutAvailable,
187 let placed = jumper.pages.paragraphs[index].bottom.map({ $0 - (jumper.pages.paragraphs[index].height ?? 0) }) else { continue }
188 let top = fragment.layoutFragmentFrame.minY + (fragment.textLineFragments.first?.typographicBounds.minY ?? 0)
189 if abs(top - placed) > 0.5 { off += 1; worst = max(worst, abs(top - placed)) }
190 }
191 print("PHONE LARGE textkit2: \(breaks.count) page breaks; \(off) laid out away from where they were placed (worst \(worst) pt)")
192 XCTAssertEqual(off, 0, "every break is laid out where it was placed")
193 }
194 print(String(format: "PHONE LARGE textkit2: jump to the end %.1f ms, %d fragments laid out (measured contiguously: spec §7 Fallback, once per jump)", jump, jumpFragments))
195 // Measuring placed the document exactly, so its height changed under
196 // the jump: bring the caret on screen, as the text view does when the
197 // person types there.
198 let landed = jumper.caretRect(for: try XCTUnwrap(jumper.selectedTextRange).start)
199 jumper.setContentOffset(CGPoint(x: 0, y: max(0, landed.midY - jumper.bounds.height / 2)), animated: false)
200 jumper.layoutIfNeeded()
201 let caret = jumper.caretRect(for: try XCTUnwrap(jumper.selectedTextRange).start)
202 let lines = Self.lines(in: jumper, near: jumper.contentOffset.y, height: jumper.bounds.height)
203 let caretLine = lines.first { $0.range.contains(end) || NSMaxRange($0.range) == end }
204 print("PHONE LARGE textkit2: caret \(caret), its line \(String(describing: caretLine?.rect))")
205 let line = try XCTUnwrap(caretLine, "the caret's line is laid out")
206 XCTAssertTrue(caret.midY > line.rect.minY && caret.midY < line.rect.maxY, "the caret (\(caret)) is on its glyph's line (\(line.rect))")
207 let geometry = jumper.geometry
208 for line in lines {
209 let y = line.rect.minY - jumper.headerHeight
210 let page = geometry.page(at: y)
211 let top = CGFloat(page) * geometry.stride + DocsPageGeometry.verticalMargin
212 XCTAssertGreaterThanOrEqual(y, top - 0.01, "a line (\(line.rect)) starts in a gap")
213 XCTAssertLessThanOrEqual(y + line.rect.height, top + geometry.bodyHeight + 0.01, "a line (\(line.rect)) straddles a page gap")
214 }
215 // The same lines on a whole layout.
216 let whole = DocsTextView(frame: window.bounds)
217 whole.paged = true
218 window.addSubview(whole)
219 defer { whole.removeFromSuperview() }
220 whole.attributedText = jumper.attributedText
221 whole.layoutIfNeeded()
222 whole.paginateEverything()
223 let wholeLayout = try XCTUnwrap(whole.textLayoutManager)
224 wholeLayout.ensureLayout(for: wholeLayout.documentRange)
225 let reference = Dictionary(Self.lines(in: whole, near: 0, height: .greatestFiniteMagnitude).map { ($0.range.location, $0.rect) }, uniquingKeysWith: { a, _ in a })
226 var mismatches = 0
227 // Lines of text: the empty line after the last newline has no glyphs,
228 // and its x follows the typing attributes, not the layout.
229 for line in lines where line.range.length > 0 {
230 guard let other = reference[line.range.location] else { mismatches += 1; continue }
231 if abs(other.minY - line.rect.minY) > 0.5 || abs(other.minX - line.rect.minX) > 0.5 { mismatches += 1 }
232 }
233 print("PHONE LARGE textkit2: \(lines.count) lines near the end compared with a whole layout, \(mismatches) differ")
234 XCTAssertGreaterThan(lines.count, 5)
235 XCTAssertEqual(mismatches, 0, "lines near the end where a whole layout puts them")
236 withExtendedLifetime(layout) {}
237 }
238
239 /// The 72.7 pt caret (S1b, #173): TextKit 1's caret against its line,
240 /// as shipped and once the view has laid itself out.
241 func testTheTextKit1CaretAtTheEnd() async throws {
242 guard ProcessInfo.processInfo.environment["DOCS_PHONE_LARGE"] != nil else { throw XCTSkip("Set DOCS_PHONE_LARGE") }
243 DocsFonts.register()
244 let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874))
245 window.makeKeyAndVisible()
246 defer { window.isHidden = true }
247 for paged in [true, false] {
248 let text = TextKit1PagedView(frame: window.bounds)
249 text.paged = paged
250 window.addSubview(text)
251 defer { text.removeFromSuperview() }
252 text.attributedText = NativeTextProjection.render(SurfaceFixture.projection(SurfaceFixture.pages(Self.pages)))
253 text.layoutIfNeeded()
254 let manager = text.layoutManager
255 for (name, location) in [("first line", 3), ("page 2", Self.lineStart(text.textStorage.string as NSString, near: 4000) + 5), ("end", text.textStorage.length - 8)] {
256 text.selectedRange = NSRange(location: location, length: 0)
257 text.scrollRangeToVisible(text.selectedRange)
258 let before = text.caretRect(for: text.selectedTextRange!.start)
259 text.layoutIfNeeded()
260 try await Task.sleep(for: .milliseconds(50))
261 let after = text.caretRect(for: text.selectedTextRange!.start)
262 let glyph = manager.glyphIndexForCharacter(at: location)
263 let line = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil)
264 let used = manager.lineFragmentUsedRect(forGlyphAt: glyph, effectiveRange: nil)
265 let point = manager.location(forGlyphAt: glyph)
266 let geometry = (text.textContainer as! DocsPageTextContainer).geometry
267 let first = text.firstRect(for: text.textRange(from: text.position(from: text.beginningOfDocument, offset: location)!, to: text.position(from: text.beginningOfDocument, offset: location + 1)!)!)
268 print("PHONE LARGE textkit1 paged=\(paged) \(name): firstRect \(first); caret before layout \(before), after \(after); line \(line), used \(used), glyph at \(point); page \(geometry.page(at: line.minY)), line's offset in its page \(line.minY - CGFloat(geometry.page(at: line.minY)) * geometry.stride); offset \(line.minY - after.minY)")
269 }
270 }
271 }
272
273 static func lineStart(_ string: NSString, near location: Int) -> Int {
274 var at = location
275 while at > 0, string.character(at: at - 1) != 10 { at -= 1 }
276 return at
277 }
278
279 /// The laid-out lines of a TextKit 2 view between two heights, in the
280 /// text view's coordinates, each with its character range.
281 static func lines(in text: UITextView, near top: CGFloat, height: CGFloat) -> [(range: NSRange, rect: CGRect)] {
282 guard let layout = text.textLayoutManager, let content = layout.textContentManager else { return [] }
283 let origin = text.textContainerInset
284 var found: [(NSRange, CGRect)] = []
285 let start = layout.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top - origin.top)))?.rangeInElement.location ?? layout.documentRange.location
286 layout.enumerateTextLayoutFragments(from: start, options: [.ensuresLayout]) { fragment in
287 let frame = fragment.layoutFragmentFrame
288 if frame.minY + origin.top > top + height { return false }
289 let base = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location)
290 for line in fragment.textLineFragments {
291 let bounds = line.typographicBounds
292 let rect = CGRect(x: frame.minX + bounds.minX + origin.left, y: frame.minY + bounds.minY + origin.top, width: bounds.width, height: bounds.height)
293 found.append((NSRange(location: base + line.characterRange.location, length: line.characterRange.length), rect))
294 }
295 return true
296 }
297 return found
298 }
299
300 static func ms(_ start: ContinuousClock.Instant) -> Double {
301 let d = start.duration(to: .now); return Double(d.components.seconds) * 1000 + Double(d.components.attoseconds) / 1e15
302 }
303}
304
305extension UITextView {
306 /// The TextKit 1 layout manager only if the view already has one: asking
307 /// `layoutManager` itself would switch a TextKit 2 view to TextKit 1.
308 func layoutManager(peeking: Bool) -> NSLayoutManager? { textLayoutManager == nil ? layoutManager : nil }
309}
310
311/// The iPhone text view as it shipped before S3 (TextKit 1, the whole
312/// document laid out in `layoutSubviews`), kept for the caret comparison.
313final class TextKit1PagedView: UITextView {
314 var paged = false
315 init(frame: CGRect) {
316 let storage = NSTextStorage()
317 let manager = NSLayoutManager()
318 manager.usesFontLeading = false
319 let pages = DocsPageTextContainer(size: CGSize(width: max(320, frame.width), height: 1_000_000))
320 pages.lineFragmentPadding = 0
321 storage.addLayoutManager(manager)
322 manager.addTextContainer(pages)
323 super.init(frame: frame, textContainer: pages)
324 textContainerInset = .zero
325 }
326 required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") }
327 override func layoutSubviews() {
328 super.layoutSubviews()
329 guard let pages = textContainer as? DocsPageTextContainer else { return }
330 let width = max(160, bounds.width)
331 let size = CGSize(width: width, height: 1_000_000)
332 if pages.size != size { pages.size = size }
333 pages.geometry = DocsPageGeometry(viewportWidth: width, paged: paged)
334 layoutManager.ensureLayout(for: pages)
335 let height = pages.geometry.documentHeight(usedHeight: layoutManager.usedRect(for: pages).maxY)
336 if abs(contentSize.height - height) > 0.5 || abs(contentSize.width - width) > 0.5 {
337 contentSize = CGSize(width: width, height: height)
338 }
339 }
340}
341#endif
342