import Foundation #if os(macOS) import AppKit typealias DocsStorageEditActions = NSTextStorageEditActions #else import UIKit typealias DocsStorageEditActions = NSTextStorage.EditActions #endif /// The open document's text, as the text view holds it (spec 2026-11-22 /// §7 Design 3–9). One per document model; deliberately not observed, so /// nothing SwiftUI draws depends on it. Publications go model → surface → /// storage by direct call: /// /// - `apply(_:)` keeps the newest publication, drops a stale one, and /// gathers what changed into `pendingDirty` (or `fullDiff`, when the /// replica could not say); /// - `flushIfDeferred()` draws it once the text view can take it, /// re-rendering only the blocks that changed and their neighbours, and /// reconciling only their characters, found through the block index; /// - the text view's delegate callbacks (typing, selection, input rules, /// composition) come here, and reach the model through `hooks`. @MainActor final class DocumentSurface: NSObject { struct Publication: Sendable { let generation: UInt64 let projection: CRDTProjection let revision: UInt64 let dirty: Set? } /// What the surface asks of its model. Every one is a call, never an /// observed read, so the text view's host observes nothing. struct Hooks { var edit: @MainActor ([String: JSONValue]) -> Bool = { _ in false } var canRender: @MainActor (UInt64) -> Bool = { _ in true } var currentSelection: @MainActor () -> NSRange = { NSRange(location: 0, length: 0) } var didRender: @MainActor (UInt64) -> Void = { _ in } var compositionChanged: @MainActor (Bool) -> Void = { _ in } /// The caret or selection moved (any reason but a render). var selectionChanged: @MainActor (NSRange) -> Void = { _ in } /// …and the move was the person's, not their typing's. var selectionMoved: @MainActor () -> Void = {} var action: @MainActor (String) -> Bool = { _ in false } var canAction: @MainActor (String) -> Bool = { _ in false } /// The image sources the drawn blocks hold, when that set changes. var imageSourcesChanged: @MainActor ([String]) -> Void = { _ in } } var hooks = Hooks() #if os(macOS) private(set) weak var textView: DocsTextView? #else private(set) weak var textView: DocsTextView? #endif /// The replica revision the storage reflects. private(set) var appliedRevision: UInt64 = 0 /// The generation the storage reflects: edits name it as their source. private(set) var generation: UInt64 = 0 /// The newest publication, drawn or waiting to be. private(set) var newest: Publication? /// Blocks changed since `appliedRevision` (or since they were drawn). private(set) var pendingDirty = Set() /// The replica could not say what changed: compare every block. private(set) var fullDiff = false private(set) var index = DocumentBlockIndex() /// Publications handed to `apply`, drawn or not (tests: "no later /// publication"). private(set) var publicationsReceived = 0 /// Moves on every reset: a report deferred to the next turn checks it. private var resets: UInt64 = 0 /// Tests only: runs as a publication arrives, before it is applied. var willApply: ((Publication) -> Void)? /// What each drawn block was drawn from. private struct Entry { var node: CRDTNode var context: DocumentBlockSpacing.Context /// Its first paragraph's top margin when not first of the document. var firstBefore: CGFloat? var sources: Set /// Its length as drawn. A block whose run in the storage is any /// other length has been edited there (or lost characters to an /// edit across blocks) and is never kept as it stands. var length: Int } private var entries: [String: Entry] = [:] private var order: [String] = [] private var sourceCounts: [String: Int] = [:] private var reportedSources: [String] = [] private var images: [String: DocsPlatformImage] = [:] /// True while the surface itself edits the storage or the selection: /// the text view's callbacks then change nothing in the model. private(set) var applying = false private var flushing = false private var expectedSelection: NSRange? var isEditable = false { didSet { guard oldValue != isEditable else { return } textView?.isEditable = isEditable #if os(iOS) // The keyboard bar is a writer's (spec §3). textView?.showsKeyboardBar = isEditable #endif } } /// Marks chosen at a collapsed caret (DocsModel.typingMarks), so marked /// text is drawn in the face it will commit in. var typingMarks: [String: JSONValue]? { didSet { if oldValue != typingMarks { applyTypingFont() } } } // MARK: - Content /// The live text, which commands, word counts and the toolbar read. var content: NSAttributedString { #if os(macOS) textView?.textStorage ?? NSAttributedString() #else textView?.textStorage ?? NSAttributedString() #endif } private var storage: NSTextStorage? { textView?.textStorage } var selectedRange: NSRange? { #if os(macOS) textView?.selectedRange() #else textView?.selectedRange #endif } /// Forget the document drawn: a new one (or a new replica) follows, /// whose revisions start again. The next publication is drawn whole. /// The text view stays attached: a new draft (iPhone) or a discard /// keeps the same host, which is not rebuilt to attach it again; a /// rebuilt host's new view is drawn whole by `attach`. func reset() { resets &+= 1 appliedRevision = 0; generation = 0; newest = nil pendingDirty = []; fullDiff = false entries = [:]; order = []; sourceCounts = [:]; images = [:] expectedSelection = nil report(sources: []) } // MARK: - The text view func attach(_ text: DocsTextView) { if textView !== text { // Another text view, without the model opening again (the host // rebuilt: an iPad split collapsing, a window restructured), or // the first. Let the old one go if it is still there (its host // may have released it already), and draw the new one whole: // what the surface remembers is the old storage's, not this one's. if let old = textView { Self.release(old) } entries = [:]; order = []; sourceCounts = [:] pendingDirty = []; fullDiff = newest != nil } textView = text text.delegate = self storage?.delegate = self text.isEditable = isEditable #if os(iOS) text.showsKeyboardBar = isEditable // The Format sheet's state, for a text view built while it is open. text.keyboardSuppressed = keyboardSuppressed text.bottomObstruction = sheetHeight #endif text.ruleCommand = { [weak self] command in self?.ruleEdit(command) ?? false } text.clipboardEdit = { [weak self] blocks, range, replacement in self?.clipboardEdit(blocks: blocks, range: range, replacement: replacement) ?? false } text.compositionChanged = { [weak self] active in self?.hooks.compositionChanged(active) } text.compositionCommitted = { [weak self] before, after in self?.commitComposition(before: before, after: after) ?? true } text.action = { [weak self, weak text] action in text?.lastInputRule = nil return self?.hooks.action(action) ?? false } text.canAction = { [weak self] action in self?.hooks.canAction(action) ?? false } if let storage { index.rebuild(from: storage) } // Inside SwiftUI's update: draw now, so the first frame is final, // but tell the model on the next turn, not during the update. flushIfDeferred(notifyLater: true) } private static func release(_ text: DocsTextView) { if text.delegate === nil { return } text.delegate = nil #if os(macOS) text.textStorage?.delegate = nil #else text.textStorage.delegate = nil #endif text.ruleCommand = nil; text.clipboardEdit = nil; text.compositionChanged = nil text.compositionCommitted = nil; text.action = nil; text.canAction = nil } #if os(iOS) /// Remembered for a text view attached while the sheet is open. private var keyboardSuppressed = false private var sheetHeight: CGFloat = 0 /// The Format sheet is open (iPhone, S3): the keyboard goes, the text /// view keeps first responder and the selection. func suppressKeyboard(_ suppressed: Bool) { keyboardSuppressed = suppressed textView?.keyboardSuppressed = suppressed } /// The sheet's height over the text: it scrolls clear of it, the /// selection kept in view above it. func sheetCovers(_ height: CGFloat) { sheetHeight = height guard let text = textView, abs(text.bottomObstruction - height) > 0.5 else { return } text.bottomObstruction = height if height > 0 { text.scrollRangeToVisible(text.selectedRange) } } #endif /// An explicit command (not typing) went to the model. func explicitCommand() { textView?.lastInputRule = nil } // MARK: - Publications /// A publication from the model (trigger (a)). Stale ones are dropped: /// the storage already reflects that revision or a later one. func apply(_ publication: Publication) { publicationsReceived += 1 willApply?(publication) if let newest, publication.revision <= newest.revision { return } guard publication.revision > appliedRevision else { return } if let dirty = publication.dirty { pendingDirty.formUnion(dirty) } else { fullDiff = true } newest = publication flushIfDeferred() } /// Images arrived (or went): only the blocks that hold them are drawn again. func imagesChanged(_ loaded: [String: DocsPlatformImage]) { let changed = Set(loaded.keys).symmetricDifference(images.keys) .union(loaded.keys.filter { key in images[key].map { $0 !== loaded[key] } ?? false }) images = loaded guard !changed.isEmpty else { return } for (id, entry) in entries where !entry.sources.isDisjoint(with: changed) { pendingDirty.insert(id) } flushIfDeferred() } /// Draws what is waiting, if the text view can take it now: no input /// pending, nothing composing, the newest generation current, and no /// marked text (spec §7 Design 6). Called on every event that can make /// that true: (a) a publication applied, (b) the edit queue draining, /// (c) composition ending, (d) the generation catching up. func flushIfDeferred(notifyLater: Bool = false) { guard !flushing, let newest, let text = textView, let storage = text.textStorage as NSTextStorage? else { return } let waiting = newest.revision > appliedRevision || !pendingDirty.isEmpty || fullDiff guard waiting, hooks.canRender(newest.generation), !Self.hasMarkedText(text) else { return } #if DOCS_PROBES let probeStart = DocsProbes.now() defer { DocsProbes.publications += 1; DocsProbes.publicationMs += DocsProbes.ms(since: probeStart) } #endif flushing = true defer { flushing = false } let advancing = newest.revision > appliedRevision let newGeneration = generation != newest.generation let selected = newGeneration ? hooks.currentSelection() : (selectedRange ?? NSRange(location: 0, length: 0)) applying = true if entries.isEmpty { drawWhole(newest.projection, into: text, storage: storage) } else { drawChanged(newest.projection, storage: storage, textOnly: !advancing) } let sources = sourceCounts.keys.sorted() let length = storage.length let range = NSRange(location: min(selected.location, length), length: min(selected.length, max(0, length - selected.location))) if selectedRange != range { Self.select(range, in: text) } applying = false appliedRevision = newest.revision generation = newest.generation if !Self.hasMarkedText(text) { applyTypingFont() } // The model hears of the draw (the generation drawn, the image // sources) now, or, inside SwiftUI's update (attach), on the next // turn: no observed state is assigned during a view update. let rendered = newest.generation if notifyLater { // Only if the surface still shows that draw on the next turn: // a reset in between (another document) makes it the old one's. let resets = self.resets Task { @MainActor [weak self] in guard let self, self.resets == resets, self.generation == rendered else { return } self.report(sources: sources); self.hooks.didRender(rendered) } } else { report(sources: sources); hooks.didRender(rendered) } } /// Open, or after `reset`: the one whole render, and on iOS the one /// `attributedText` assignment. private func drawWhole(_ projection: CRDTProjection, into text: DocsTextView, storage: NSTextStorage) { let content = NativeTextProjection.render(projection, images: images) #if os(macOS) DocumentRenderReconciliation.apply(content, to: storage) #else text.attributedText = content #if DOCS_PROBES DocsProbes.attributedTextAssignments += 1 #endif #endif index.rebuild(from: storage) rememberWhole(projection.children) } /// After a whole draw: every block as the storage now holds it. private func rememberWhole(_ nodes: [CRDTNode]) { entries = [:]; sourceCounts = [:] var lengths: [String: Int] = [:] for run in index.runs { if let id = run.id { lengths[id, default: 0] += run.length } } let contexts = DocumentBlockSpacing.contexts(nodes) for (node, context) in zip(nodes, contexts) { remember(node, context: context, length: lengths[node.id] ?? 0) } order = nodes.map(\.id) pendingDirty = []; fullDiff = false } /// Everything since: the blocks that changed (or whose neighbours /// changed their spacing), drawn on their own and reconciled into /// their own characters. `textOnly`: nothing new from the replica (an /// image arrived), so a block whose text no longer matches what is /// shown (typing the replica has not answered yet) waits. private func drawChanged(_ projection: CRDTProjection, storage: NSTextStorage, textOnly: Bool) { let nodes = projection.children let ids = nodes.map(\.id) guard Set(ids).count == ids.count else { // Two blocks under one id: no per-block identity to go by. DocumentRenderReconciliation.apply(NativeTextProjection.render(projection, images: images), to: storage) index.rebuild(from: storage) rememberWhole(nodes) return } // What changed, by id. var changed = pendingDirty for node in nodes where entries[node.id] == nil || (fullDiff && entries[node.id]?.node != node) { changed.insert(node.id) } // Each block's context; a block whose context moved is drawn again // (its neighbour changed its top margin, or it became first or last). var contexts = Array(repeating: DocumentBlockSpacing.Context(), count: nodes.count) var next: CGFloat? for index in nodes.indices.reversed() { contexts[index].first = index == 0 contexts[index].last = index == nodes.count - 1 contexts[index].nextBefore = next let node = nodes[index] let before: CGFloat? = index == 0 || changed.contains(node.id) || entries[node.id] == nil ? DocumentBlockSpacing.firstBefore(node, first: index == 0) : entries[node.id]!.firstBefore if let before { next = before } } for index in nodes.indices { contexts[index].leading = true let node = nodes[index] let empty = changed.contains(node.id) || entries[node.id] == nil ? DocumentBlockSpacing.firstBefore(node) == nil : entries[node.id]!.firstBefore == nil if !empty { break } } var draw = changed for (index, node) in nodes.enumerated() where entries[node.id]?.context != contexts[index] { draw.insert(node.id) } if draw.isEmpty && order == ids { pendingDirty = []; fullDiff = false; return } // Anchors: blocks kept as they are, each one contiguous run of the // index, in order. Everything between two anchors is one gap. let positions = index.positions() var anchors: [(block: Int, run: DocumentBlockIndex.Run)] = [] var lastEnd = 0 for (block, id) in ids.enumerated() where !draw.contains(id) { guard let runs = positions[id], runs.count == 1 else { draw.insert(id); continue } let run = index.runs[runs[0]] guard run.location >= lastEnd, run.length == entries[id]?.length else { draw.insert(id); continue } anchors.append((block, run)); lastEnd = run.end } // Gaps, last first, so earlier ranges stay where they are. var gaps: [(blocks: Range, range: NSRange)] = [] var previousBlock = -1, previousEnd = 0 for (block, run) in anchors + [(nodes.count, DocumentBlockIndex.Run(id: nil, location: storage.length, length: 0))] { let range = NSRange(location: previousEnd, length: run.location - previousEnd) if block > previousBlock + 1 || range.length > 0 { gaps.append(((previousBlock + 1)..() for gap in gaps.reversed() { let rendered = NSMutableAttributedString() var lengths: [Int] = [] for block in gap.blocks { let drawn = NativeTextProjection.renderBlock(nodes[block], context: contexts[block], images: images) lengths.append(drawn.length) rendered.append(drawn) } if textOnly, storage.mutableString.substring(with: gap.range) != rendered.string { for block in gap.blocks { waiting.insert(nodes[block].id) } continue } DocumentRenderReconciliation.apply(rendered, to: storage, in: gap.range) for (block, length) in zip(gap.blocks, lengths) { remember(nodes[block], context: contexts[block], length: length) } } for (block, _) in anchors { entries[nodes[block].id]?.context = contexts[block] } let kept = Set(ids) for id in order where !kept.contains(id) { forget(id) } order = ids pendingDirty = waiting; fullDiff = false } private func remember(_ node: CRDTNode, context: DocumentBlockSpacing.Context, length: Int) { forget(node.id) let sources = DocsImageStore.sources(in: node) for source in sources { sourceCounts[source, default: 0] += 1 } entries[node.id] = Entry(node: node, context: context, firstBefore: DocumentBlockSpacing.firstBefore(node), sources: sources, length: length) } private func forget(_ id: String) { guard let old = entries.removeValue(forKey: id) else { return } for source in old.sources { let count = (sourceCounts[source] ?? 1) - 1 sourceCounts[source] = count > 0 ? count : nil } } private func report(sources: [String]) { guard sources != reportedSources else { return } reportedSources = sources hooks.imageSourcesChanged(sources) } // MARK: - Typing and selection (the text view's delegate) /// The text view changed its own text (typing, a paste, a composition): /// those blocks are drawn again at the next publication, whatever the /// replica says changed. Usually the replica names them too; but an /// edit it refused (or one a dropped publication carried) would /// otherwise stay on screen until something else touched the block. private func typed(around edited: NSRange) { // From the character before the edit through the one after it: an // edit across blocks leaves the head of one and the tail of // another, and both must be drawn again even if the replica // changes neither (it refused the edit, or clamped it). let first = max(0, edited.location - 1) let last = NSMaxRange(edited) let touched = index.runs(holding: first, through: last) for run in touched { if let id = run.id { pendingDirty.insert(id) } } // Text typed with no block (UIKit's typing attributes may not carry // it) belongs to the block before it. if let start = touched.first, start.id == nil, touched.startIndex > 0, let id = index.runs[touched.startIndex - 1].id { pendingDirty.insert(id) } } private func applyTypingFont() { guard let text = textView, let marks = typingMarks, let selected = selectedRange, selected.length == 0, !Self.hasMarkedText(text), let font = NativeTextProjection.typingFont(in: content, at: selected.location, marks: marks) else { return } if text.typingAttributes[.font] as? DocsPlatformFont != font { text.typingAttributes[.font] = font } } func ruleEdit(_ command: [String: JSONValue]) -> Bool { var command = command; command["generation"] = .number(Double(generation)) let accepted = hooks.edit(command) if accepted, case .number(let at)? = command["at"] { let inserted: Int if command["op"] == .string("display_revert_rule"), case .string(let text)? = command["text"] { inserted = text.utf16.count } else { inserted = 0 } expectedSelection = NSRange(location: Int(at) + inserted, length: 0) } return accepted } func clipboardEdit(blocks: [JSONValue]?, range: NSRange, replacement: String) -> Bool { var command: [String: JSONValue] = ["op": .string(blocks == nil ? "display_edit" : "display_paste"), "at": .number(Double(range.location)), "length": .number(Double(range.length)), "generation": .number(Double(generation))] if let blocks { command["blocks"] = .array(blocks) } else { command["text"] = .string(replacement) } let accepted = hooks.edit(command) if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) } return accepted } func commitComposition(before: NSAttributedString, after: String) -> Bool { guard let (range, replacement) = DocumentComposition.replacement(before: before.string, after: after) else { return true } guard var command = TextEditMapping.displayCommand(in: before, range: range, replacement: replacement) else { return false } command["generation"] = .number(Double(generation)) let accepted = hooks.edit(command) if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) } return accepted } /// Typing: the command first, then (if the model took it) the text view /// shows it at once, before any publication. func shouldChange(_ text: DocsTextView, in range: NSRange, replacement: String) -> Bool { if text.isComposing { return true } if text.interceptInput(replacement, range: range) { return false } guard var command = TextEditMapping.displayCommand(in: content, range: range, replacement: replacement) else { return false } command["generation"] = .number(Double(generation)) let accepted = hooks.edit(command) if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) } return accepted } func selectionDidChange(_ text: DocsTextView) { // A render moves the caret (iOS: assigning the text moves it to the // end and back) and then puts it where the model has it. Telling // the model here would change it in the middle of that (the iOS // render loop, TestFlight 0.1.10 (12)). guard !applying else { return } // Not `content.string`: that copies the whole text on every caret move. let characters = storage?.mutableString let length = characters?.length ?? 0 let selected = selectedRange ?? NSRange(location: 0, length: 0) if selected.length == 0 && selected.location == length && length > 0 && characters?.character(at: length - 1) == 10 { Self.select(NSRange(location: max(0, selected.location - 1), length: 0), in: text); return } if !text.isComposing { if selected != expectedSelection && selected != hooks.currentSelection() { hooks.selectionMoved() text.lastInputRule = nil } expectedSelection = nil } hooks.selectionChanged(selected) } private static func hasMarkedText(_ text: DocsTextView) -> Bool { #if os(macOS) text.hasMarkedText() #else text.markedTextRange != nil #endif } private static func select(_ range: NSRange, in text: DocsTextView) { #if os(macOS) text.setSelectedRange(range) #else text.selectedRange = range #endif } } // MARK: - Delegates extension DocumentSurface: NSTextStorageDelegate { nonisolated func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: DocsStorageEditActions, range editedRange: NSRange, changeInLength delta: Int) { // TextKit edits the text view's storage on the main thread only. nonisolated(unsafe) let edited = textStorage MainActor.assumeIsolated { guard edited === storage else { return } index.processEditing(edited, edited: editedRange, delta: delta) #if os(iOS) // The iPhone's page breaks (TextKit 2, DocsPhonePages). if editedMask.contains(.editedCharacters) || editedMask.contains(.editedAttributes) { textView?.storageEdited(editedRange, delta: delta) } // The pages building paragraphs again: no text changed. if textView?.pages.regenerating == true { return } #endif if !applying, editedMask.contains(.editedCharacters) { typed(around: editedRange) } } } } #if os(macOS) extension DocumentSurface: NSTextViewDelegate { func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool { guard let text = textView as? DocsTextView else { return false } if text.isComposing { return true } guard let replacementString else { return false } return shouldChange(text, in: affectedCharRange, replacement: replacementString) } func textViewDidChangeSelection(_ notification: Notification) { guard let text = notification.object as? DocsTextView else { return } selectionDidChange(text) } } #else extension DocumentSurface: UITextViewDelegate { func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { guard let view = textView as? DocsTextView else { return false } return shouldChange(view, in: range, replacement: text) } func textViewDidChangeSelection(_ textView: UITextView) { guard let text = textView as? DocsTextView else { return } text.releaseHeldBreaks() selectionDidChange(text) } } #endif