#if os(iOS) && DOCS_PROBES import UIKit import XCTest @testable import DocsKit /// The iPhone's large-document check (spec 2026-11-22 §7 "iPhone layout", /// §11 "Large documents"; plan S3 acceptance, carried from S1b #173), as a /// probe: skipped unless DOCS_PHONE_LARGE is set (TEST_RUNNER_DOCS_PHONE_LARGE=1 /// through xcodebuild). A 200-page document, paged, on the production text /// view (TextKit 2 from S3): /// - opening lays out no further than the first screen, in ≤ 250 ms of /// main thread; /// - 40 keys in its middle, some making a new line: main-thread time per key /// ≤ 8 ms median, and no key over 16.7 ms; /// - jump to the end before anything past the first screen is laid out: /// the caret is on its glyph's line, no line crosses a page gap, and the /// lines near the end are where a whole layout puts them. /// Then the same document on TextKit 1 (`TextKit1PagedView`, the view as it /// shipped before S3), for the 72.7 pt caret finding. @MainActor final class PhoneLargeDocumentTests: XCTestCase { private static let pages = 200 func testALongPagedDocumentOnTextKit2() async throws { guard ProcessInfo.processInfo.environment["DOCS_PHONE_LARGE"] != nil else { throw XCTSkip("Set DOCS_PHONE_LARGE") } DocsFonts.register() let projection = SurfaceFixture.projection(SurfaceFixture.pages(Self.pages)) let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() defer { window.isHidden = true } let text = DocsTextView(frame: window.bounds) text.paged = true window.addSubview(text) defer { text.removeFromSuperview() } let surface = DocumentSurface() var hooks = DocumentSurface.Hooks() hooks.edit = { _ in true } surface.hooks = hooks surface.isEditable = true surface.attach(text) let layout = try XCTUnwrap(text.textLayoutManager, "TextKit 2") let storage = text.textStorage // Open. var fragments = DocsProbes.layoutFragments let rendering = DocsProbes.wholeRenderMs, layouts = DocsProbes.textLayoutMs var start = ContinuousClock.now surface.apply(DocumentSurface.Publication(generation: 1, projection: projection, revision: 1, dirty: nil)) text.layoutIfNeeded() let open = Self.ms(start) let openFragments = DocsProbes.layoutFragments - fragments let paragraphs = text.pages.paragraphs.count print(String(format: "PHONE LARGE textkit2: open breakdown: whole render %.1f ms, text view layout %.1f ms", DocsProbes.wholeRenderMs - rendering, DocsProbes.textLayoutMs - layouts)) print(String(format: "PHONE LARGE textkit2: open %.1f ms, %d of %d paragraphs laid out", open, openFragments, paragraphs)) XCTAssertNil(text.layoutManager(peeking: true), "still TextKit 2") XCTAssertLessThan(openFragments, 200, "opening lays out about the first screen, not \(paragraphs) paragraphs") // §7: a timing target holds within 20% of its value (median of three runs). XCTAssertLessThanOrEqual(open, 250 * 1.2, "first screen within 250 ms of main thread") // Keys in the middle, some making a new line: scrolled there as a // person would (TextKit 2's scrollRangeToVisible does not scroll to // text it has not laid out), then typing in a paragraph on screen. text.setContentOffset(CGPoint(x: 0, y: text.contentSize.height / 2), animated: false) text.layoutIfNeeded() let shown = try XCTUnwrap(layout.textViewportLayoutController.viewportRange) let content = try XCTUnwrap(layout.textContentManager) let middle = Self.lineStart(storage.string as NSString, near: content.offset(from: content.documentRange.location, to: shown.location) + 200) text.selectedRange = NSRange(location: middle, length: 0) text.layoutIfNeeded() try await Task.sleep(for: .milliseconds(300)) let measuredBefore = text.pages.paragraphs.filter { $0.height != nil }.count var keys: [Double] = [], newLineKeys: [Double] = [], perKeyFragments: [Int] = [], perKeyMeasured: [Int] = [], perKeyBreaks: [Int] = [] let wrap = String(repeating: "Words to wrap the line. ", count: 3) for index in 0..<40 { let typed = index % 8 == 4 ? wrap : "x" let range = text.selectedRange fragments = DocsProbes.layoutFragments let measured = DocsProbes.measureFragments, breaks = DocsProbes.pageBreakChanges start = .now if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: typed) ?? true { storage.replaceCharacters(in: range, with: NSAttributedString(string: typed, attributes: text.typingAttributes)) text.selectedRange = NSRange(location: range.location + typed.utf16.count, length: 0) text.delegate?.textViewDidChange?(text) } text.layoutIfNeeded() let elapsed = Self.ms(start) keys.append(elapsed) if typed == wrap { newLineKeys.append(elapsed) } perKeyFragments.append(DocsProbes.layoutFragments - fragments) perKeyMeasured.append(DocsProbes.measureFragments - measured) perKeyBreaks.append(DocsProbes.pageBreakChanges - breaks) try await Task.sleep(for: .milliseconds(5)) } let sorted = keys.sorted() 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", sorted[sorted.count / 2], sorted.last ?? 0, newLineKeys.max() ?? 0, perKeyFragments.sorted()[perKeyFragments.count / 2], perKeyFragments.max() ?? 0)) let onScreen = try XCTUnwrap(layout.textViewportLayoutController.viewportRange) let typedAt = text.selectedRange.location XCTAssertTrue(content.offset(from: content.documentRange.location, to: onScreen.location) <= typedAt && typedAt <= content.offset(from: content.documentRange.location, to: onScreen.endLocation), "typed on screen") print("PHONE LARGE textkit2: typing at \(typedAt), \(measuredBefore) paragraphs measured when it began") print("PHONE LARGE textkit2: per key, fragments measuring \(perKeyMeasured.max() ?? 0) at most, page breaks moved \(perKeyBreaks.reduce(0, +)) in all") XCTAssertLessThanOrEqual(sorted[sorted.count / 2], 8, "per key ≤ 8 ms median") XCTAssertLessThanOrEqual(newLineKeys.max() ?? 0, 16.7, "no stall over 16.7 ms on a key that changes a line count") // A peer's keys on page 2 while the screen is at the middle (Fable on // #180), through the surface's publication path as a peer's change // arrives, every fourth adding a line: main-thread time from the // publication to the screen laid out. Nothing on screen moves. // As a session would be by then: the rest measured while idle. let idleDeadline = Date().addingTimeInterval(20) while (text.pages.firstUnmeasured != nil || text.pages.settleFrom != nil || text.pages.hasChanges) && Date() < idleDeadline { try await Task.sleep(for: .milliseconds(20)) } text.layoutIfNeeded() var nodes = SurfaceFixture.pages(Self.pages) let peer = try XCTUnwrap(nodes.firstIndex { $0.id == "p1-2" }) var peerKeys: [Double] = [], peerLineKeys: [Double] = [], cascades: [(ms: Double, breaks: Int)] = [], plain: [Double] = [] var publications: [Double] = [] let relaid = DocsProbes.relaidParagraphs for index in 0..<20 { let typed = index % 4 == 3 ? wrap : "x" nodes[peer].children?[0].runs?[0].insert += typed let next = SurfaceFixture.projection(nodes) // What the editor keeps still (F4): the line at the screen's // middle (the caret is not on screen here: no first responder). let middle = text.contentOffset.y + text.adjustedContentInset.top + (text.bounds.height - text.adjustedContentInset.top - text.adjustedContentInset.bottom) / 2 - text.textContainerInset.top let anchor = layout.textLayoutFragment(for: CGPoint(x: 0, y: middle)) .map { content.offset(from: content.documentRange.location, to: $0.rangeInElement.location) } ?? 0 func screenY(_ at: Int) -> CGFloat { (content.location(content.documentRange.location, offsetBy: at).flatMap { layout.textLayoutFragment(for: $0)?.layoutFragmentFrame.minY } ?? 0) - text.contentOffset.y } let anchorY = screenY(anchor), breaks = DocsProbes.pageBreakChanges, published = DocsProbes.publicationMs start = .now surface.apply(DocumentSurface.Publication(generation: 1, projection: next, revision: UInt64(2 + index), dirty: ["p1-2"])) text.layoutIfNeeded() let elapsed = Self.ms(start) XCTAssertEqual(screenY(anchor + typed.utf16.count), anchorY, accuracy: 0.5, "peer key \(index): nothing on screen moved") peerKeys.append(elapsed) publications.append(DocsProbes.publicationMs - published) if typed == wrap { peerLineKeys.append(elapsed) } let moved = DocsProbes.pageBreakChanges - breaks if moved > 1 { cascades.append((elapsed, moved)) } else { plain.append(elapsed) } try await Task.sleep(for: .milliseconds(5)) } let peerSorted = peerKeys.sorted() 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", peerSorted[peerSorted.count / 2], publications.sorted()[publications.count / 2], peerSorted.last ?? 0, peerLineKeys.max() ?? 0, DocsProbes.relaidParagraphs - relaid)) 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) })") XCTAssertTrue(surface.content.string.contains(nodes[peer].plainText), "the peer's keys arrived") XCTAssertEqual(DocsProbes.relaidParagraphs - relaid, 0, "nothing laid out again from the top") // §7: a timing target holds within 20% of its value (median of three runs). XCTAssertLessThanOrEqual(peerSorted[peerSorted.count / 2], 16.7, "a peer's key ≤ 16.7 ms median") XCTAssertLessThanOrEqual(plain.max() ?? 0, 16.7 * 1.2, "no peer key over 16.7 ms that moves at most one break") // A fresh view for the jump, laid out no further than its first screen. let jumper = DocsTextView(frame: window.bounds) jumper.paged = true window.addSubview(jumper) defer { jumper.removeFromSuperview() } jumper.attributedText = NativeTextProjection.render(projection) jumper.layoutIfNeeded() let end = jumper.textStorage.length - 8 fragments = DocsProbes.layoutFragments start = .now // As the scroll indicator dragged to the bottom does: TextKit 2's // scrollRangeToVisible does not scroll to text it has not laid out. jumper.setContentOffset(CGPoint(x: 0, y: max(0, jumper.contentSize.height - jumper.bounds.height)), animated: false) jumper.layoutIfNeeded() jumper.selectedRange = NSRange(location: end, length: 0) jumper.scrollRangeToVisible(jumper.selectedRange) jumper.layoutIfNeeded() let jump = Self.ms(start), jumpFragments = DocsProbes.layoutFragments - fragments // Breaks through the screen's end: those below it are built while // idle, before the screen gets to them. let screenEnd = jumper.textLayoutManager.flatMap { layout in layout.textViewportLayoutController.viewportRange.flatMap { range in layout.textContentManager.map { $0.offset(from: $0.documentRange.location, to: range.endLocation) } } } ?? jumper.textStorage.length let lastShown = (jumper.pages.paragraph(at: screenEnd) ?? 0) + 1 let breaks = jumper.pages.paragraphs.indices.filter { jumper.pages.paragraphs[$0].extra > 0 && $0 <= lastShown } // Every break laid out where it was placed. if let layout = jumper.textLayoutManager, let content = layout.textContentManager { var off = 0, worst: CGFloat = 0 for index in breaks { guard let location = content.location(content.documentRange.location, offsetBy: jumper.pages.range(of: index).location), let fragment = layout.textLayoutFragment(for: location), fragment.state == .layoutAvailable, let placed = jumper.pages.paragraphs[index].bottom.map({ $0 - (jumper.pages.paragraphs[index].height ?? 0) }) else { continue } let top = fragment.layoutFragmentFrame.minY + (fragment.textLineFragments.first?.typographicBounds.minY ?? 0) if abs(top - placed) > 0.5 { off += 1; worst = max(worst, abs(top - placed)) } } print("PHONE LARGE textkit2: \(breaks.count) page breaks; \(off) laid out away from where they were placed (worst \(worst) pt)") XCTAssertEqual(off, 0, "every break is laid out where it was placed") } 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)) // Measuring placed the document exactly, so its height changed under // the jump: bring the caret on screen, as the text view does when the // person types there. let landed = jumper.caretRect(for: try XCTUnwrap(jumper.selectedTextRange).start) jumper.setContentOffset(CGPoint(x: 0, y: max(0, landed.midY - jumper.bounds.height / 2)), animated: false) jumper.layoutIfNeeded() let caret = jumper.caretRect(for: try XCTUnwrap(jumper.selectedTextRange).start) let lines = Self.lines(in: jumper, near: jumper.contentOffset.y, height: jumper.bounds.height) let caretLine = lines.first { $0.range.contains(end) || NSMaxRange($0.range) == end } print("PHONE LARGE textkit2: caret \(caret), its line \(String(describing: caretLine?.rect))") let line = try XCTUnwrap(caretLine, "the caret's line is laid out") XCTAssertTrue(caret.midY > line.rect.minY && caret.midY < line.rect.maxY, "the caret (\(caret)) is on its glyph's line (\(line.rect))") let geometry = jumper.geometry for line in lines { let y = line.rect.minY - jumper.headerHeight let page = geometry.page(at: y) let top = CGFloat(page) * geometry.stride + DocsPageGeometry.verticalMargin XCTAssertGreaterThanOrEqual(y, top - 0.01, "a line (\(line.rect)) starts in a gap") XCTAssertLessThanOrEqual(y + line.rect.height, top + geometry.bodyHeight + 0.01, "a line (\(line.rect)) straddles a page gap") } // The same lines on a whole layout. let whole = DocsTextView(frame: window.bounds) whole.paged = true window.addSubview(whole) defer { whole.removeFromSuperview() } whole.attributedText = jumper.attributedText whole.layoutIfNeeded() whole.paginateEverything() let wholeLayout = try XCTUnwrap(whole.textLayoutManager) wholeLayout.ensureLayout(for: wholeLayout.documentRange) let reference = Dictionary(Self.lines(in: whole, near: 0, height: .greatestFiniteMagnitude).map { ($0.range.location, $0.rect) }, uniquingKeysWith: { a, _ in a }) var mismatches = 0 // Lines of text: the empty line after the last newline has no glyphs, // and its x follows the typing attributes, not the layout. for line in lines where line.range.length > 0 { guard let other = reference[line.range.location] else { mismatches += 1; continue } if abs(other.minY - line.rect.minY) > 0.5 || abs(other.minX - line.rect.minX) > 0.5 { mismatches += 1 } } print("PHONE LARGE textkit2: \(lines.count) lines near the end compared with a whole layout, \(mismatches) differ") XCTAssertGreaterThan(lines.count, 5) XCTAssertEqual(mismatches, 0, "lines near the end where a whole layout puts them") withExtendedLifetime(layout) {} } /// The 72.7 pt caret (S1b, #173): TextKit 1's caret against its line, /// as shipped and once the view has laid itself out. func testTheTextKit1CaretAtTheEnd() async throws { guard ProcessInfo.processInfo.environment["DOCS_PHONE_LARGE"] != nil else { throw XCTSkip("Set DOCS_PHONE_LARGE") } DocsFonts.register() let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() defer { window.isHidden = true } for paged in [true, false] { let text = TextKit1PagedView(frame: window.bounds) text.paged = paged window.addSubview(text) defer { text.removeFromSuperview() } text.attributedText = NativeTextProjection.render(SurfaceFixture.projection(SurfaceFixture.pages(Self.pages))) text.layoutIfNeeded() let manager = text.layoutManager for (name, location) in [("first line", 3), ("page 2", Self.lineStart(text.textStorage.string as NSString, near: 4000) + 5), ("end", text.textStorage.length - 8)] { text.selectedRange = NSRange(location: location, length: 0) text.scrollRangeToVisible(text.selectedRange) let before = text.caretRect(for: text.selectedTextRange!.start) text.layoutIfNeeded() try await Task.sleep(for: .milliseconds(50)) let after = text.caretRect(for: text.selectedTextRange!.start) let glyph = manager.glyphIndexForCharacter(at: location) let line = manager.lineFragmentRect(forGlyphAt: glyph, effectiveRange: nil) let used = manager.lineFragmentUsedRect(forGlyphAt: glyph, effectiveRange: nil) let point = manager.location(forGlyphAt: glyph) let geometry = (text.textContainer as! DocsPageTextContainer).geometry let first = text.firstRect(for: text.textRange(from: text.position(from: text.beginningOfDocument, offset: location)!, to: text.position(from: text.beginningOfDocument, offset: location + 1)!)!) 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)") } } } static func lineStart(_ string: NSString, near location: Int) -> Int { var at = location while at > 0, string.character(at: at - 1) != 10 { at -= 1 } return at } /// The laid-out lines of a TextKit 2 view between two heights, in the /// text view's coordinates, each with its character range. static func lines(in text: UITextView, near top: CGFloat, height: CGFloat) -> [(range: NSRange, rect: CGRect)] { guard let layout = text.textLayoutManager, let content = layout.textContentManager else { return [] } let origin = text.textContainerInset var found: [(NSRange, CGRect)] = [] let start = layout.textLayoutFragment(for: CGPoint(x: 0, y: max(0, top - origin.top)))?.rangeInElement.location ?? layout.documentRange.location layout.enumerateTextLayoutFragments(from: start, options: [.ensuresLayout]) { fragment in let frame = fragment.layoutFragmentFrame if frame.minY + origin.top > top + height { return false } let base = content.offset(from: content.documentRange.location, to: fragment.rangeInElement.location) for line in fragment.textLineFragments { let bounds = line.typographicBounds let rect = CGRect(x: frame.minX + bounds.minX + origin.left, y: frame.minY + bounds.minY + origin.top, width: bounds.width, height: bounds.height) found.append((NSRange(location: base + line.characterRange.location, length: line.characterRange.length), rect)) } return true } return found } static func ms(_ start: ContinuousClock.Instant) -> Double { let d = start.duration(to: .now); return Double(d.components.seconds) * 1000 + Double(d.components.attoseconds) / 1e15 } } extension UITextView { /// The TextKit 1 layout manager only if the view already has one: asking /// `layoutManager` itself would switch a TextKit 2 view to TextKit 1. func layoutManager(peeking: Bool) -> NSLayoutManager? { textLayoutManager == nil ? layoutManager : nil } } /// The iPhone text view as it shipped before S3 (TextKit 1, the whole /// document laid out in `layoutSubviews`), kept for the caret comparison. final class TextKit1PagedView: UITextView { var paged = false init(frame: CGRect) { let storage = NSTextStorage() let manager = NSLayoutManager() manager.usesFontLeading = false let pages = DocsPageTextContainer(size: CGSize(width: max(320, frame.width), height: 1_000_000)) pages.lineFragmentPadding = 0 storage.addLayoutManager(manager) manager.addTextContainer(pages) super.init(frame: frame, textContainer: pages) textContainerInset = .zero } required init?(coder: NSCoder) { fatalError("init(coder:) is unavailable") } override func layoutSubviews() { super.layoutSubviews() guard let pages = textContainer as? DocsPageTextContainer else { return } let width = max(160, bounds.width) let size = CGSize(width: width, height: 1_000_000) if pages.size != size { pages.size = size } pages.geometry = DocsPageGeometry(viewportWidth: width, paged: paged) layoutManager.ensureLayout(for: pages) let height = pages.geometry.documentHeight(usedHeight: layoutManager.usedRect(for: pages).maxY) if abs(contentSize.height - height) > 0.5 || abs(contentSize.width - width) > 0.5 { contentSize = CGSize(width: width, height: height) } } } #endif