import Foundation import ImageIO import RastrilloApple import SwiftUI import UniformTypeIdentifiers import XCTest @testable import DocsKit #if os(macOS) import AppKit #else import UIKit #endif /// TestFlight 0.1.10 (12): on iPhone, opening a document with a list (or an /// image, or a rule) never finished: 100% CPU and memory without bound. Each /// `updateUIView` found the content unequal to what it had drawn (an /// `NSTextList` or `NSTextAttachment` is equal only to itself, and every /// render makes new ones), so it assigned the whole text again; that moved /// the caret, the iOS selection callback wrote the selection binding in the /// middle of the update, and the write asked for the next update. /// /// These open a document through the app's own wiring, `DocsWorkspace` with /// a document ID in a window, on an in-memory server, and count the text /// storage's edits: an editor that has settled makes none. The same file is /// built for iOS as DocsPhoneTests (ios/project.yml; run it with /// native/scripts/test-iphone.sh) and runs on the Mac in `swift test`, where /// the coordinator already skipped the write while applying. On iOS the loop /// held the main thread, so a looping build fails by the script's one-minute /// time allowance rather than an assertion. @MainActor final class EditorRenderLoopTests: XCTestCase { private var harness: LoopHarness? override func tearDown() async throws { await harness?.close() harness = nil } func testOpeningAListImageAndRuleSettles() async throws { let harness = try await open(LoopFixture.everything) try await harness.assertSettles("opening a list, an image and a rule") // Moving the caret re-evaluates the editor (the tools read the // selection) and must not draw the document again. harness.moveCaret(to: 5) try await harness.assertSettles("moving the caret", allowing: 0) } func testAPeersInsertSettles() async throws { let harness = try await open(LoopFixture.everything) try await harness.assertSettles("opening") let at = (harness.shown as NSString).range(of: LoopFixture.afterRule).location XCTAssertNotEqual(at, NSNotFound) try await harness.server.peerInsert("A peer’s note. ", at: at) try await harness.until("the peer’s note is shown") { harness.shown.contains("A peer’s note. ") } try await harness.assertSettles("a peer’s insert") } func testTypingInTheMiddleSettles() async throws { let harness = try await open(LoopFixture.everything) try await harness.assertSettles("opening") let line = (harness.shown as NSString).range(of: LoopFixture.middle) XCTAssertNotEqual(line.location, NSNotFound) harness.type(" typed", at: NSMaxRange(line)) try await harness.until("the typing is shown and saved") { harness.shown.contains(LoopFixture.middle + " typed") } try await harness.assertSettles("typing mid-document", allowing: 3 * " typed".count) } private func open(_ blocks: [JSONValue]) async throws -> LoopHarness { let harness = try await LoopHarness.open(blocks) self.harness = harness return harness } } /// `DocsWorkspace` for one document in a window, and the text view it made. @MainActor final class LoopHarness { let server: LoopServer #if os(macOS) private let window: NSWindow #else private let window: UIWindow #endif private var observer: NSObjectProtocol? private(set) var edits = 0 private init(server: LoopServer) { self.server = server let workspace = DocsWorkspace(client: NativeHTTP(origin: server.origin), transport: { server }, signOut: {}, documentID: "doc") #if os(macOS) window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled, .resizable], backing: .buffered, defer: false) window.isReleasedWhenClosed = false window.contentView = NSHostingView(rootView: workspace) window.orderFront(nil) #else window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene { window.windowScene = scene } window.rootViewController = UIHostingController(rootView: workspace) window.makeKeyAndVisible() #endif } static func open(_ blocks: [JSONValue]) async throws -> LoopHarness { DocsFonts.register() let server = LoopServer() try await server.seed(blocks) let harness = LoopHarness(server: server) try await harness.until("the document is shown") { guard let text = harness.textView else { return false } return text.attributedString().length > 0 && harness.shown.contains(LoopFixture.middle) } guard let storage = harness.textView?.storage else { throw LoopFailure("no text storage") } harness.observer = NotificationCenter.default.addObserver(forName: NSTextStorage.didProcessEditingNotification, object: storage, queue: nil) { [weak harness] _ in MainActor.assumeIsolated { harness?.edits += 1 } } return harness } func close() async { if let observer { NotificationCenter.default.removeObserver(observer) } #if os(macOS) window.contentView = nil window.close() #else window.rootViewController = nil window.isHidden = true #endif // Let the workspace's onDisappear stop its model. try? await Task.sleep(for: .milliseconds(50)) } var textView: DocsTextView? { #if os(macOS) window.contentView.flatMap(Self.find) #else Self.find(in: window) #endif } var shown: String { textView?.attributedString().string ?? "" } /// Settled: within five seconds the text view goes half a second /// without its text being drawn, and it was drawn at most `allowing` /// times before that (an image that loads is one; each typed character /// is its own edit and render). A looping editor redraws without end. func assertSettles(_ what: String, allowing: Int = 3, file: StaticString = #filePath, line: UInt = #line) async throws { let start = edits let deadline = ContinuousClock.now + .seconds(5) var seen = edits, since = ContinuousClock.now, quiet = false while ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) if edits != seen { seen = edits; since = .now } else if ContinuousClock.now - since >= .milliseconds(500) { quiet = true; break } } XCTAssertTrue(quiet, "\(what): the text is still being drawn after five seconds (\(edits - start) times)", file: file, line: line) XCTAssertLessThanOrEqual(seen - start, allowing, "\(what): the text was drawn \(seen - start) times before it settled", file: file, line: line) } func until(_ what: String, _ condition: () -> Bool) async throws { let deadline = ContinuousClock.now + .seconds(5) while !condition() { guard ContinuousClock.now < deadline else { throw LoopFailure("timed out waiting for \(what)") } try await Task.sleep(for: .milliseconds(10)) } } /// Where a tap would put the caret. func moveCaret(to location: Int) { guard let text = textView else { return } #if os(macOS) text.setSelectedRange(NSRange(location: location, length: 0)) #else text.selectedRange = NSRange(location: location, length: 0) text.delegate?.textViewDidChangeSelection?(text) #endif } /// Typed one character at a time, as the keyboard sends it. func type(_ characters: String, at start: Int) { guard let text = textView else { return } var at = start for character in characters { let piece = String(character) #if os(macOS) text.setSelectedRange(NSRange(location: at, length: 0)) text.insertText(piece, replacementRange: text.selectedRange()) #else // UITextView.insertText from code skips the delegate, so the // keyboard's path is taken by hand: ask the delegate, and only if // it agrees, edit the storage and move the caret. let range = NSRange(location: at, length: 0) text.selectedRange = range if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: piece) ?? true { text.textStorage.replaceCharacters(in: range, with: NSAttributedString(string: piece, attributes: text.typingAttributes)) text.selectedRange = NSRange(location: at + piece.utf16.count, length: 0) text.delegate?.textViewDidChange?(text) } #endif at += piece.utf16.count } } #if os(macOS) private static func find(_ view: NSView) -> DocsTextView? { if let text = view as? DocsTextView { return text } for child in view.subviews { if let text = find(child) { return text } } return nil } #else private static func find(in view: UIView) -> DocsTextView? { if let text = view as? DocsTextView { return text } for child in view.subviews { if let text = find(in: child) { return text } } return nil } #endif } private extension DocsTextView { #if os(macOS) var storage: NSTextStorage? { textStorage } #else var storage: NSTextStorage? { textStorage } func attributedString() -> NSAttributedString { attributedText ?? NSAttributedString() } #endif } struct LoopFailure: Error, CustomStringConvertible { let description: String init(_ description: String) { self.description = description } } /// One document, "doc", on the production replica: GET answers its detail /// and state, POST commits an update and announces it on the stream, as /// handlers.go does. Nothing leaves the process. actor LoopServer: NativeTransport { nonisolated let origin = URL(string: "https://docs.loop.invalid")! private let replica = CRDTReplica(guid: "render-loop") private var sequence: Int64 = 0 private var rows: [Int64: Data] = [:] private var listeners: [UUID: AsyncStream.Continuation] = [:] func seed(_ blocks: [JSONValue]) async throws { try await replica.open(update: Data()) _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(blocks)]) } /// Another client's typing, committed as the next row. func peerInsert(_ text: String, at position: Int) async throws { let peer = CRDTReplica(guid: "render-loop") try await peer.open(update: try await replica.persistentState().state) let update = try await peer.command(["op": .string("display_edit"), "at": .number(Double(position)), "length": .number(0), "text": .string(text)]) await peer.close() try await replica.apply(update) commit(update) } @discardableResult private func commit(_ update: Data) -> Int64 { sequence += 1; rows[sequence] = update for listener in listeners.values { listener.yield(sequence) } return sequence } func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { let route = String(path.split(separator: "?")[0]) guard route == "/d/doc" || route.hasPrefix("/d/doc/") else { return NativeResponse(data: Data(), status: 404, headers: [:]) } if method == "POST", route == "/d/doc/updates", let body { try await replica.apply(body) return NativeResponse(data: Data(), status: 204, headers: ["Docs-Seq": String(commit(body))]) } if method == "POST" { return NativeResponse(data: Data(), status: 200, headers: [:]) } if route == "/d/doc/updates" { if let since = URLComponents(string: path)?.queryItems?.first(where: { $0.name == "since" })?.value.flatMap(Int64.init) { let kept = rows.keys.sorted().filter { $0 > since } let data = kept.isEmpty ? Data() : try await replica.mergeUpdates(kept.compactMap { rows[$0] }) return NativeResponse(data: data, status: 200, headers: ["Docs-Seq": String(kept.last ?? since)]) } return NativeResponse(data: try await replica.persistentState().state, status: 200, headers: ["Docs-Seq": String(sequence)]) } let detail = DocumentDetail(sqid: "doc", title: "Render loop", guid: "render-loop", can_write: true, can_share: false) return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:]) } func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { let id = UUID(), events = AsyncStream.makeStream(bufferingPolicy: .bufferingNewest(1)) listeners[id] = events.continuation defer { listeners.removeValue(forKey: id) } try await onOpen(); try await onLine("data: \(sequence)") for await announced in events.stream { try Task.checkCancellation(); try await onLine("data: \(announced)") } } func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } } /// A document holding everything that made the iOS editor loop: bullet and /// ordered lists, an image (a data URL, so nothing is fetched) and a rule. enum LoopFixture { static let middle = "The middle paragraph, typed into." static let afterRule = "After the rule." static var everything: [JSONValue] { [ block("heading", [text("Lists, an image and a rule")], attrs: ["level": "1"]), paragraph("Before the lists."), list("bullet_list", ["Private wells", "Shared pumps", "Cisterns"]), list("ordered_list", ["Survey the creek", "Build the dam"], order: "3"), paragraph(middle), block("paragraph", [.object(["type": .string("image"), "attrs": .object(["src": .string(picture), "alt": .string("A reservoir")])])]), block("horizontal_rule", []), paragraph(afterRule), ] } private static func text(_ insert: String) -> JSONValue { .object(["type": .string("text"), "runs": .array([.object(["insert": .string(insert), "marks": .object([:])])])]) } private static func paragraph(_ insert: String) -> JSONValue { block("paragraph", [text(insert)]) } private static func list(_ type: String, _ items: [String], order: String? = nil) -> JSONValue { block(type, items.map { block("list_item", [paragraph($0)]) }, attrs: order.map { ["order": $0] } ?? [:]) } private static func block(_ type: String, _ children: [JSONValue], attrs: [String: String] = [:]) -> JSONValue { var object: [String: JSONValue] = ["type": .string(type)] if !children.isEmpty { object["children"] = .array(children) } if !attrs.isEmpty { object["attrs"] = .object(attrs.mapValues { .string($0) }) } return .object(object) } /// A 64 × 36 picture in two colours. static let picture: String = { let context = CGContext(data: nil, width: 64, height: 36, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! context.setFillColor(red: 0.62, green: 0.80, blue: 0.93, alpha: 1); context.fill(CGRect(x: 0, y: 0, width: 64, height: 36)) context.setFillColor(red: 0.16, green: 0.42, blue: 0.62, alpha: 1); context.fill(CGRect(x: 0, y: 0, width: 64, height: 14)) let data = NSMutableData() let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)! CGImageDestinationAddImage(destination, context.makeImage()!, nil) CGImageDestinationFinalize(destination) return "data:image/png;base64," + (data as Data).base64EncodedString() }() }