#if os(iOS) import Foundation import UIKit import XCTest @testable import DocsKit /// ยง7's iPhone row: main-thread time per one-block publication, before S1a /// (the whole `attributedText` assigned, as `applyRender` did) and after /// (`DocumentSurface`: the one block rendered and reconciled), each with /// the layout that follows. A probe, not a gate: skipped unless /// DOCS_RT_AUDIT_DOCS names a directory of generate-large-doc.mjs /// documents (TEST_RUNNER_DOCS_RT_AUDIT_DOCS through xcodebuild). @MainActor final class SurfaceTimingTests: XCTestCase { func testOneBlockPublication() async throws { guard let dir = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_DOCS"] else { throw XCTSkip("Set DOCS_RT_AUDIT_DOCS") } let names = (ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_ONLY"] ?? "p20,p200h").split(separator: ",").map(String.init) DocsFonts.register() for name in names { let replica = CRDTReplica(guid: "timing-" + name) try await replica.open(update: try Data(contentsOf: URL(fileURLWithPath: "\(dir)/\(name).bin"))) var projection = try await replica.projection() await replica.close() let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() let block = projection.children.count / 2 for paged in [true, false] { // Before: the whole text assigned per publication. let before = DocsTextView(frame: window.bounds) before.paged = paged window.addSubview(before) before.attributedText = NativeTextProjection.render(projection) before.layoutIfNeeded() var whole: [Double] = [] var current = projection for _ in 0..<8 { current.children[block] = Self.appending("x", to: current.children[block]) let start = ContinuousClock.now before.attributedText = NativeTextProjection.render(current) before.layoutIfNeeded() whole.append(Self.ms(start)) } before.removeFromSuperview() // After: the surface. let after = DocsTextView(frame: window.bounds) after.paged = paged window.addSubview(after) let surface = DocumentSurface() surface.attach(after) current = projection var revision: UInt64 = 1 surface.apply(DocumentSurface.Publication(generation: 1, projection: current, revision: revision, dirty: nil)) after.layoutIfNeeded() var perBlock: [Double] = [] for _ in 0..<8 { current.children[block] = Self.appending("x", to: current.children[block]) revision += 1 let start = ContinuousClock.now surface.apply(DocumentSurface.Publication(generation: 1, projection: current, revision: revision, dirty: [current.children[block].id])) after.layoutIfNeeded() perBlock.append(Self.ms(start)) } after.removeFromSuperview() print(String(format: "SURFACE TIMING %@ paged=%d: attributedText+layout median %.2f ms; surface+layout median %.2f ms (n=8; %@ / %@)", name, paged ? 1 : 0, Self.median(whole), Self.median(perBlock), whole.map { String(format: "%.1f", $0) }.joined(separator: " "), perBlock.map { String(format: "%.1f", $0) }.joined(separator: " "))) } projection = CRDTProjection(children: [], canUndo: false, canRedo: false) window.isHidden = true } } /// The keystroke on the iPhone (S1b step 0): the keyboard's path into /// the text view (the delegate asked, the storage edited, the caret /// moved), then the layout UIKit runs before it draws, per key; and the /// line-fragment requests our container gets for it. func testKeystroke() async throws { guard let dir = ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_DOCS"] else { throw XCTSkip("Set DOCS_RT_AUDIT_DOCS") } let names = (ProcessInfo.processInfo.environment["DOCS_RT_AUDIT_ONLY"] ?? "p1,p5,p20,p50,p200h").split(separator: ",").map(String.init) DocsFonts.register() for name in names { let replica = CRDTReplica(guid: "keys-" + name) try await replica.open(update: try Data(contentsOf: URL(fileURLWithPath: "\(dir)/\(name).bin"))) let projection = try await replica.projection() await replica.close() for paged in [true, false] { let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) window.makeKeyAndVisible() let text = DocsTextView(frame: window.bounds) text.paged = paged window.addSubview(text) let surface = DocumentSurface() var hooks = DocumentSurface.Hooks() hooks.edit = { _ in true } surface.hooks = hooks surface.isEditable = true surface.attach(text) var start = ContinuousClock.now surface.apply(DocumentSurface.Publication(generation: 1, projection: projection, revision: 1, dirty: nil)) text.layoutIfNeeded() let open = Self.ms(start) let content = text.textStorage.string as NSString var at = content.length / 3 while at < content.length, content.character(at: at) == 10 { at += 1 } text.selectedRange = NSRange(location: at, length: 0) text.scrollRangeToVisible(text.selectedRange) text.layoutIfNeeded() try await Task.sleep(for: .milliseconds(200)) var keys: [Double] = [], lines: [Int] = [] for _ in 0..<40 { #if DOCS_PROBES let lines0 = DocsProbes.lineRequests #endif start = .now let range = text.selectedRange if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: "x") ?? true { text.textStorage.replaceCharacters(in: range, with: NSAttributedString(string: "x", attributes: text.typingAttributes)) text.selectedRange = NSRange(location: range.location + 1, length: 0) text.delegate?.textViewDidChange?(text) } text.layoutIfNeeded() keys.append(Self.ms(start)) #if DOCS_PROBES lines.append(DocsProbes.lineRequests - lines0) #endif try await Task.sleep(for: .milliseconds(10)) } let sorted = keys.sorted() print(String(format: "KEYSTROKE TIMING %@ paged=%d: open %.1f ms; key + layout median %.2f ms p95 %.2f ms max %.2f ms; line requests per key median %d max %d", name, paged ? 1 : 0, open, Self.median(keys), sorted[Int(Double(sorted.count - 1) * 0.95)], sorted.last ?? 0, lines.sorted()[lines.count / 2], lines.max() ?? 0)) text.removeFromSuperview() window.isHidden = true } } } static func ms(_ start: ContinuousClock.Instant) -> Double { let d = start.duration(to: .now); return Double(d.components.seconds) * 1000 + Double(d.components.attoseconds) / 1e15 } static func median(_ values: [Double]) -> Double { let s = values.sorted(); return s.isEmpty ? .nan : s[s.count / 2] } static func appending(_ text: String, to node: CRDTNode) -> CRDTNode { var node = node if var runs = node.runs, !runs.isEmpty { runs[0].insert += text; node.runs = runs; return node } if var children = node.children { for index in children.indices { let changed = appending(text, to: children[index]) if changed != children[index] { children[index] = changed; node.children = children; return node } } } return node } } #endif