| 1 | import Foundation |
| 2 | import ImageIO |
| 3 | import RastrilloApple |
| 4 | import SwiftUI |
| 5 | import UniformTypeIdentifiers |
| 6 | import XCTest |
| 7 | @testable import DocsKit |
| 8 | #if os(macOS) |
| 9 | import AppKit |
| 10 | #else |
| 11 | import UIKit |
| 12 | #endif |
| 13 | |
| 14 | /// TestFlight 0.1.10 (12): on iPhone, opening a document with a list (or an |
| 15 | /// image, or a rule) never finished: 100% CPU and memory without bound. Each |
| 16 | /// `updateUIView` found the content unequal to what it had drawn (an |
| 17 | /// `NSTextList` or `NSTextAttachment` is equal only to itself, and every |
| 18 | /// render makes new ones), so it assigned the whole text again; that moved |
| 19 | /// the caret, the iOS selection callback wrote the selection binding in the |
| 20 | /// middle of the update, and the write asked for the next update. |
| 21 | /// |
| 22 | /// These open a document through the app's own wiring, `DocsWorkspace` with |
| 23 | /// a document ID in a window, on an in-memory server, and count the text |
| 24 | /// storage's edits: an editor that has settled makes none. The same file is |
| 25 | /// built for iOS as DocsPhoneTests (ios/project.yml; run it with |
| 26 | /// native/scripts/test-iphone.sh) and runs on the Mac in `swift test`, where |
| 27 | /// the coordinator already skipped the write while applying. On iOS the loop |
| 28 | /// held the main thread, so a looping build fails by the script's one-minute |
| 29 | /// time allowance rather than an assertion. |
| 30 | @MainActor final class EditorRenderLoopTests: XCTestCase { |
| 31 | private var harness: LoopHarness? |
| 32 | |
| 33 | override func tearDown() async throws { |
| 34 | await harness?.close() |
| 35 | harness = nil |
| 36 | } |
| 37 | |
| 38 | func testOpeningAListImageAndRuleSettles() async throws { |
| 39 | let harness = try await open(LoopFixture.everything) |
| 40 | try await harness.assertSettles("opening a list, an image and a rule") |
| 41 | // Moving the caret re-evaluates the editor (the tools read the |
| 42 | // selection) and must not draw the document again. |
| 43 | harness.moveCaret(to: 5) |
| 44 | try await harness.assertSettles("moving the caret", allowing: 0) |
| 45 | } |
| 46 | |
| 47 | func testAPeersInsertSettles() async throws { |
| 48 | let harness = try await open(LoopFixture.everything) |
| 49 | try await harness.assertSettles("opening") |
| 50 | let at = (harness.shown as NSString).range(of: LoopFixture.afterRule).location |
| 51 | XCTAssertNotEqual(at, NSNotFound) |
| 52 | try await harness.server.peerInsert("A peer’s note. ", at: at) |
| 53 | try await harness.until("the peer’s note is shown") { harness.shown.contains("A peer’s note. ") } |
| 54 | try await harness.assertSettles("a peer’s insert") |
| 55 | } |
| 56 | |
| 57 | func testTypingInTheMiddleSettles() async throws { |
| 58 | let harness = try await open(LoopFixture.everything) |
| 59 | try await harness.assertSettles("opening") |
| 60 | let line = (harness.shown as NSString).range(of: LoopFixture.middle) |
| 61 | XCTAssertNotEqual(line.location, NSNotFound) |
| 62 | harness.type(" typed", at: NSMaxRange(line)) |
| 63 | try await harness.until("the typing is shown and saved") { |
| 64 | harness.shown.contains(LoopFixture.middle + " typed") |
| 65 | } |
| 66 | try await harness.assertSettles("typing mid-document", allowing: 3 * " typed".count) |
| 67 | } |
| 68 | |
| 69 | private func open(_ blocks: [JSONValue]) async throws -> LoopHarness { |
| 70 | let harness = try await LoopHarness.open(blocks) |
| 71 | self.harness = harness |
| 72 | return harness |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | /// `DocsWorkspace` for one document in a window, and the text view it made. |
| 77 | @MainActor final class LoopHarness { |
| 78 | let server: LoopServer |
| 79 | #if os(macOS) |
| 80 | private let window: NSWindow |
| 81 | #else |
| 82 | private let window: UIWindow |
| 83 | #endif |
| 84 | private var observer: NSObjectProtocol? |
| 85 | private(set) var edits = 0 |
| 86 | |
| 87 | private init(server: LoopServer) { |
| 88 | self.server = server |
| 89 | let workspace = DocsWorkspace(client: NativeHTTP(origin: server.origin), transport: { server }, signOut: {}, documentID: "doc") |
| 90 | #if os(macOS) |
| 91 | window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1000, height: 800), styleMask: [.titled, .resizable], backing: .buffered, defer: false) |
| 92 | window.isReleasedWhenClosed = false |
| 93 | window.contentView = NSHostingView(rootView: workspace) |
| 94 | window.orderFront(nil) |
| 95 | #else |
| 96 | window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) |
| 97 | if let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene { window.windowScene = scene } |
| 98 | window.rootViewController = UIHostingController(rootView: workspace) |
| 99 | window.makeKeyAndVisible() |
| 100 | #endif |
| 101 | } |
| 102 | |
| 103 | static func open(_ blocks: [JSONValue]) async throws -> LoopHarness { |
| 104 | DocsFonts.register() |
| 105 | let server = LoopServer() |
| 106 | try await server.seed(blocks) |
| 107 | let harness = LoopHarness(server: server) |
| 108 | try await harness.until("the document is shown") { |
| 109 | guard let text = harness.textView else { return false } |
| 110 | return text.attributedString().length > 0 && harness.shown.contains(LoopFixture.middle) |
| 111 | } |
| 112 | guard let storage = harness.textView?.storage else { throw LoopFailure("no text storage") } |
| 113 | harness.observer = NotificationCenter.default.addObserver(forName: NSTextStorage.didProcessEditingNotification, object: storage, queue: nil) { [weak harness] _ in |
| 114 | MainActor.assumeIsolated { harness?.edits += 1 } |
| 115 | } |
| 116 | return harness |
| 117 | } |
| 118 | |
| 119 | func close() async { |
| 120 | if let observer { NotificationCenter.default.removeObserver(observer) } |
| 121 | #if os(macOS) |
| 122 | window.contentView = nil |
| 123 | window.close() |
| 124 | #else |
| 125 | window.rootViewController = nil |
| 126 | window.isHidden = true |
| 127 | #endif |
| 128 | // Let the workspace's onDisappear stop its model. |
| 129 | try? await Task.sleep(for: .milliseconds(50)) |
| 130 | } |
| 131 | |
| 132 | var textView: DocsTextView? { |
| 133 | #if os(macOS) |
| 134 | window.contentView.flatMap(Self.find) |
| 135 | #else |
| 136 | Self.find(in: window) |
| 137 | #endif |
| 138 | } |
| 139 | var shown: String { textView?.attributedString().string ?? "" } |
| 140 | |
| 141 | /// Settled: within five seconds the text view goes half a second |
| 142 | /// without its text being drawn, and it was drawn at most `allowing` |
| 143 | /// times before that (an image that loads is one; each typed character |
| 144 | /// is its own edit and render). A looping editor redraws without end. |
| 145 | func assertSettles(_ what: String, allowing: Int = 3, file: StaticString = #filePath, line: UInt = #line) async throws { |
| 146 | let start = edits |
| 147 | let deadline = ContinuousClock.now + .seconds(5) |
| 148 | var seen = edits, since = ContinuousClock.now, quiet = false |
| 149 | while ContinuousClock.now < deadline { |
| 150 | try await Task.sleep(for: .milliseconds(10)) |
| 151 | if edits != seen { seen = edits; since = .now } |
| 152 | else if ContinuousClock.now - since >= .milliseconds(500) { quiet = true; break } |
| 153 | } |
| 154 | XCTAssertTrue(quiet, "\(what): the text is still being drawn after five seconds (\(edits - start) times)", file: file, line: line) |
| 155 | XCTAssertLessThanOrEqual(seen - start, allowing, "\(what): the text was drawn \(seen - start) times before it settled", file: file, line: line) |
| 156 | } |
| 157 | |
| 158 | func until(_ what: String, _ condition: () -> Bool) async throws { |
| 159 | let deadline = ContinuousClock.now + .seconds(5) |
| 160 | while !condition() { |
| 161 | guard ContinuousClock.now < deadline else { throw LoopFailure("timed out waiting for \(what)") } |
| 162 | try await Task.sleep(for: .milliseconds(10)) |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | /// Where a tap would put the caret. |
| 167 | func moveCaret(to location: Int) { |
| 168 | guard let text = textView else { return } |
| 169 | #if os(macOS) |
| 170 | text.setSelectedRange(NSRange(location: location, length: 0)) |
| 171 | #else |
| 172 | text.selectedRange = NSRange(location: location, length: 0) |
| 173 | text.delegate?.textViewDidChangeSelection?(text) |
| 174 | #endif |
| 175 | } |
| 176 | |
| 177 | /// Typed one character at a time, as the keyboard sends it. |
| 178 | func type(_ characters: String, at start: Int) { |
| 179 | guard let text = textView else { return } |
| 180 | var at = start |
| 181 | for character in characters { |
| 182 | let piece = String(character) |
| 183 | #if os(macOS) |
| 184 | text.setSelectedRange(NSRange(location: at, length: 0)) |
| 185 | text.insertText(piece, replacementRange: text.selectedRange()) |
| 186 | #else |
| 187 | // UITextView.insertText from code skips the delegate, so the |
| 188 | // keyboard's path is taken by hand: ask the delegate, and only if |
| 189 | // it agrees, edit the storage and move the caret. |
| 190 | let range = NSRange(location: at, length: 0) |
| 191 | text.selectedRange = range |
| 192 | if text.delegate?.textView?(text, shouldChangeTextIn: range, replacementText: piece) ?? true { |
| 193 | text.textStorage.replaceCharacters(in: range, with: NSAttributedString(string: piece, attributes: text.typingAttributes)) |
| 194 | text.selectedRange = NSRange(location: at + piece.utf16.count, length: 0) |
| 195 | text.delegate?.textViewDidChange?(text) |
| 196 | } |
| 197 | #endif |
| 198 | at += piece.utf16.count |
| 199 | } |
| 200 | } |
| 201 | |
| 202 | #if os(macOS) |
| 203 | private static func find(_ view: NSView) -> DocsTextView? { |
| 204 | if let text = view as? DocsTextView { return text } |
| 205 | for child in view.subviews { if let text = find(child) { return text } } |
| 206 | return nil |
| 207 | } |
| 208 | #else |
| 209 | private static func find(in view: UIView) -> DocsTextView? { |
| 210 | if let text = view as? DocsTextView { return text } |
| 211 | for child in view.subviews { if let text = find(in: child) { return text } } |
| 212 | return nil |
| 213 | } |
| 214 | #endif |
| 215 | } |
| 216 | |
| 217 | private extension DocsTextView { |
| 218 | #if os(macOS) |
| 219 | var storage: NSTextStorage? { textStorage } |
| 220 | #else |
| 221 | var storage: NSTextStorage? { textStorage } |
| 222 | func attributedString() -> NSAttributedString { attributedText ?? NSAttributedString() } |
| 223 | #endif |
| 224 | } |
| 225 | |
| 226 | struct LoopFailure: Error, CustomStringConvertible { |
| 227 | let description: String |
| 228 | init(_ description: String) { self.description = description } |
| 229 | } |
| 230 | |
| 231 | /// One document, "doc", on the production replica: GET answers its detail |
| 232 | /// and state, POST commits an update and announces it on the stream, as |
| 233 | /// handlers.go does. Nothing leaves the process. |
| 234 | actor LoopServer: NativeTransport { |
| 235 | nonisolated let origin = URL(string: "https://docs.loop.invalid")! |
| 236 | private let replica = CRDTReplica(guid: "render-loop") |
| 237 | private var sequence: Int64 = 0 |
| 238 | private var rows: [Int64: Data] = [:] |
| 239 | private var listeners: [UUID: AsyncStream<Int64>.Continuation] = [:] |
| 240 | |
| 241 | func seed(_ blocks: [JSONValue]) async throws { |
| 242 | try await replica.open(update: Data()) |
| 243 | _ = try await replica.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| 244 | _ = try await replica.command(["op": .string("display_paste"), "at": .number(0), "length": .number(0), "blocks": .array(blocks)]) |
| 245 | } |
| 246 | |
| 247 | /// Another client's typing, committed as the next row. |
| 248 | func peerInsert(_ text: String, at position: Int) async throws { |
| 249 | let peer = CRDTReplica(guid: "render-loop") |
| 250 | try await peer.open(update: try await replica.persistentState().state) |
| 251 | let update = try await peer.command(["op": .string("display_edit"), "at": .number(Double(position)), "length": .number(0), "text": .string(text)]) |
| 252 | await peer.close() |
| 253 | try await replica.apply(update) |
| 254 | commit(update) |
| 255 | } |
| 256 | |
| 257 | @discardableResult private func commit(_ update: Data) -> Int64 { |
| 258 | sequence += 1; rows[sequence] = update |
| 259 | for listener in listeners.values { listener.yield(sequence) } |
| 260 | return sequence |
| 261 | } |
| 262 | |
| 263 | func responseDetails(_ path: String, method: String, body: Data?, contentType: String, maxBytes: Int) async throws -> NativeResponse { |
| 264 | let route = String(path.split(separator: "?")[0]) |
| 265 | guard route == "/d/doc" || route.hasPrefix("/d/doc/") else { return NativeResponse(data: Data(), status: 404, headers: [:]) } |
| 266 | if method == "POST", route == "/d/doc/updates", let body { |
| 267 | try await replica.apply(body) |
| 268 | return NativeResponse(data: Data(), status: 204, headers: ["Docs-Seq": String(commit(body))]) |
| 269 | } |
| 270 | if method == "POST" { return NativeResponse(data: Data(), status: 200, headers: [:]) } |
| 271 | if route == "/d/doc/updates" { |
| 272 | if let since = URLComponents(string: path)?.queryItems?.first(where: { $0.name == "since" })?.value.flatMap(Int64.init) { |
| 273 | let kept = rows.keys.sorted().filter { $0 > since } |
| 274 | let data = kept.isEmpty ? Data() : try await replica.mergeUpdates(kept.compactMap { rows[$0] }) |
| 275 | return NativeResponse(data: data, status: 200, headers: ["Docs-Seq": String(kept.last ?? since)]) |
| 276 | } |
| 277 | return NativeResponse(data: try await replica.persistentState().state, status: 200, headers: ["Docs-Seq": String(sequence)]) |
| 278 | } |
| 279 | let detail = DocumentDetail(sqid: "doc", title: "Render loop", guid: "render-loop", can_write: true, can_share: false) |
| 280 | return NativeResponse(data: try JSONEncoder().encode(detail), status: 200, headers: [:]) |
| 281 | } |
| 282 | |
| 283 | func stream(_ path: String, onOpen: @Sendable () async throws -> Void, onLine: @Sendable (String) async throws -> Void) async throws { |
| 284 | let id = UUID(), events = AsyncStream<Int64>.makeStream(bufferingPolicy: .bufferingNewest(1)) |
| 285 | listeners[id] = events.continuation |
| 286 | defer { listeners.removeValue(forKey: id) } |
| 287 | try await onOpen(); try await onLine("data: \(sequence)") |
| 288 | for await announced in events.stream { try Task.checkCancellation(); try await onLine("data: \(announced)") } |
| 289 | } |
| 290 | |
| 291 | func download(_ path: String, to destination: URL) async throws { throw NativeClientError.notFound } |
| 292 | } |
| 293 | |
| 294 | /// A document holding everything that made the iOS editor loop: bullet and |
| 295 | /// ordered lists, an image (a data URL, so nothing is fetched) and a rule. |
| 296 | enum LoopFixture { |
| 297 | static let middle = "The middle paragraph, typed into." |
| 298 | static let afterRule = "After the rule." |
| 299 | |
| 300 | static var everything: [JSONValue] { |
| 301 | [ |
| 302 | block("heading", [text("Lists, an image and a rule")], attrs: ["level": "1"]), |
| 303 | paragraph("Before the lists."), |
| 304 | list("bullet_list", ["Private wells", "Shared pumps", "Cisterns"]), |
| 305 | list("ordered_list", ["Survey the creek", "Build the dam"], order: "3"), |
| 306 | paragraph(middle), |
| 307 | block("paragraph", [.object(["type": .string("image"), "attrs": .object(["src": .string(picture), "alt": .string("A reservoir")])])]), |
| 308 | block("horizontal_rule", []), |
| 309 | paragraph(afterRule), |
| 310 | ] |
| 311 | } |
| 312 | |
| 313 | private static func text(_ insert: String) -> JSONValue { |
| 314 | .object(["type": .string("text"), "runs": .array([.object(["insert": .string(insert), "marks": .object([:])])])]) |
| 315 | } |
| 316 | private static func paragraph(_ insert: String) -> JSONValue { block("paragraph", [text(insert)]) } |
| 317 | private static func list(_ type: String, _ items: [String], order: String? = nil) -> JSONValue { |
| 318 | block(type, items.map { block("list_item", [paragraph($0)]) }, attrs: order.map { ["order": $0] } ?? [:]) |
| 319 | } |
| 320 | private static func block(_ type: String, _ children: [JSONValue], attrs: [String: String] = [:]) -> JSONValue { |
| 321 | var object: [String: JSONValue] = ["type": .string(type)] |
| 322 | if !children.isEmpty { object["children"] = .array(children) } |
| 323 | if !attrs.isEmpty { object["attrs"] = .object(attrs.mapValues { .string($0) }) } |
| 324 | return .object(object) |
| 325 | } |
| 326 | |
| 327 | /// A 64 × 36 picture in two colours. |
| 328 | static let picture: String = { |
| 329 | let context = CGContext(data: nil, width: 64, height: 36, bitsPerComponent: 8, bytesPerRow: 0, |
| 330 | space: CGColorSpace(name: CGColorSpace.sRGB)!, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)! |
| 331 | context.setFillColor(red: 0.62, green: 0.80, blue: 0.93, alpha: 1); context.fill(CGRect(x: 0, y: 0, width: 64, height: 36)) |
| 332 | context.setFillColor(red: 0.16, green: 0.42, blue: 0.62, alpha: 1); context.fill(CGRect(x: 0, y: 0, width: 64, height: 14)) |
| 333 | let data = NSMutableData() |
| 334 | let destination = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)! |
| 335 | CGImageDestinationAddImage(destination, context.makeImage()!, nil) |
| 336 | CGImageDestinationFinalize(destination) |
| 337 | return "data:image/png;base64," + (data as Data).base64EncodedString() |
| 338 | }() |
| 339 | } |
| 340 | |