| 1 | import Foundation |
| 2 | #if os(macOS) |
| 3 | import AppKit |
| 4 | typealias DocsStorageEditActions = NSTextStorageEditActions |
| 5 | #else |
| 6 | import UIKit |
| 7 | typealias DocsStorageEditActions = NSTextStorage.EditActions |
| 8 | #endif |
| 9 | |
| 10 | /// The open document's text, as the text view holds it (spec 2026-11-22 |
| 11 | /// §7 Design 3–9). One per document model; deliberately not observed, so |
| 12 | /// nothing SwiftUI draws depends on it. Publications go model → surface → |
| 13 | /// storage by direct call: |
| 14 | /// |
| 15 | /// - `apply(_:)` keeps the newest publication, drops a stale one, and |
| 16 | /// gathers what changed into `pendingDirty` (or `fullDiff`, when the |
| 17 | /// replica could not say); |
| 18 | /// - `flushIfDeferred()` draws it once the text view can take it, |
| 19 | /// re-rendering only the blocks that changed and their neighbours, and |
| 20 | /// reconciling only their characters, found through the block index; |
| 21 | /// - the text view's delegate callbacks (typing, selection, input rules, |
| 22 | /// composition) come here, and reach the model through `hooks`. |
| 23 | @MainActor final class DocumentSurface: NSObject { |
| 24 | struct Publication: Sendable { |
| 25 | let generation: UInt64 |
| 26 | let projection: CRDTProjection |
| 27 | let revision: UInt64 |
| 28 | let dirty: Set<String>? |
| 29 | } |
| 30 | |
| 31 | /// What the surface asks of its model. Every one is a call, never an |
| 32 | /// observed read, so the text view's host observes nothing. |
| 33 | struct Hooks { |
| 34 | var edit: @MainActor ([String: JSONValue]) -> Bool = { _ in false } |
| 35 | var canRender: @MainActor (UInt64) -> Bool = { _ in true } |
| 36 | var currentSelection: @MainActor () -> NSRange = { NSRange(location: 0, length: 0) } |
| 37 | var didRender: @MainActor (UInt64) -> Void = { _ in } |
| 38 | var compositionChanged: @MainActor (Bool) -> Void = { _ in } |
| 39 | /// The caret or selection moved (any reason but a render). |
| 40 | var selectionChanged: @MainActor (NSRange) -> Void = { _ in } |
| 41 | /// …and the move was the person's, not their typing's. |
| 42 | var selectionMoved: @MainActor () -> Void = {} |
| 43 | var action: @MainActor (String) -> Bool = { _ in false } |
| 44 | var canAction: @MainActor (String) -> Bool = { _ in false } |
| 45 | /// The image sources the drawn blocks hold, when that set changes. |
| 46 | var imageSourcesChanged: @MainActor ([String]) -> Void = { _ in } |
| 47 | } |
| 48 | var hooks = Hooks() |
| 49 | |
| 50 | #if os(macOS) |
| 51 | private(set) weak var textView: DocsTextView? |
| 52 | #else |
| 53 | private(set) weak var textView: DocsTextView? |
| 54 | #endif |
| 55 | |
| 56 | /// The replica revision the storage reflects. |
| 57 | private(set) var appliedRevision: UInt64 = 0 |
| 58 | /// The generation the storage reflects: edits name it as their source. |
| 59 | private(set) var generation: UInt64 = 0 |
| 60 | /// The newest publication, drawn or waiting to be. |
| 61 | private(set) var newest: Publication? |
| 62 | /// Blocks changed since `appliedRevision` (or since they were drawn). |
| 63 | private(set) var pendingDirty = Set<String>() |
| 64 | /// The replica could not say what changed: compare every block. |
| 65 | private(set) var fullDiff = false |
| 66 | private(set) var index = DocumentBlockIndex() |
| 67 | /// Publications handed to `apply`, drawn or not (tests: "no later |
| 68 | /// publication"). |
| 69 | private(set) var publicationsReceived = 0 |
| 70 | /// Moves on every reset: a report deferred to the next turn checks it. |
| 71 | private var resets: UInt64 = 0 |
| 72 | /// Tests only: runs as a publication arrives, before it is applied. |
| 73 | var willApply: ((Publication) -> Void)? |
| 74 | |
| 75 | /// What each drawn block was drawn from. |
| 76 | private struct Entry { |
| 77 | var node: CRDTNode |
| 78 | var context: DocumentBlockSpacing.Context |
| 79 | /// Its first paragraph's top margin when not first of the document. |
| 80 | var firstBefore: CGFloat? |
| 81 | var sources: Set<String> |
| 82 | /// Its length as drawn. A block whose run in the storage is any |
| 83 | /// other length has been edited there (or lost characters to an |
| 84 | /// edit across blocks) and is never kept as it stands. |
| 85 | var length: Int |
| 86 | } |
| 87 | private var entries: [String: Entry] = [:] |
| 88 | private var order: [String] = [] |
| 89 | private var sourceCounts: [String: Int] = [:] |
| 90 | private var reportedSources: [String] = [] |
| 91 | private var images: [String: DocsPlatformImage] = [:] |
| 92 | |
| 93 | /// True while the surface itself edits the storage or the selection: |
| 94 | /// the text view's callbacks then change nothing in the model. |
| 95 | private(set) var applying = false |
| 96 | private var flushing = false |
| 97 | private var expectedSelection: NSRange? |
| 98 | |
| 99 | var isEditable = false { |
| 100 | didSet { |
| 101 | guard oldValue != isEditable else { return } |
| 102 | textView?.isEditable = isEditable |
| 103 | #if os(iOS) |
| 104 | // The keyboard bar is a writer's (spec §3). |
| 105 | textView?.showsKeyboardBar = isEditable |
| 106 | #endif |
| 107 | } |
| 108 | } |
| 109 | /// Marks chosen at a collapsed caret (DocsModel.typingMarks), so marked |
| 110 | /// text is drawn in the face it will commit in. |
| 111 | var typingMarks: [String: JSONValue]? { didSet { if oldValue != typingMarks { applyTypingFont() } } } |
| 112 | |
| 113 | // MARK: - Content |
| 114 | |
| 115 | /// The live text, which commands, word counts and the toolbar read. |
| 116 | var content: NSAttributedString { |
| 117 | #if os(macOS) |
| 118 | textView?.textStorage ?? NSAttributedString() |
| 119 | #else |
| 120 | textView?.textStorage ?? NSAttributedString() |
| 121 | #endif |
| 122 | } |
| 123 | private var storage: NSTextStorage? { textView?.textStorage } |
| 124 | var selectedRange: NSRange? { |
| 125 | #if os(macOS) |
| 126 | textView?.selectedRange() |
| 127 | #else |
| 128 | textView?.selectedRange |
| 129 | #endif |
| 130 | } |
| 131 | |
| 132 | /// Forget the document drawn: a new one (or a new replica) follows, |
| 133 | /// whose revisions start again. The next publication is drawn whole. |
| 134 | /// The text view stays attached: a new draft (iPhone) or a discard |
| 135 | /// keeps the same host, which is not rebuilt to attach it again; a |
| 136 | /// rebuilt host's new view is drawn whole by `attach`. |
| 137 | func reset() { |
| 138 | resets &+= 1 |
| 139 | appliedRevision = 0; generation = 0; newest = nil |
| 140 | pendingDirty = []; fullDiff = false |
| 141 | entries = [:]; order = []; sourceCounts = [:]; images = [:] |
| 142 | expectedSelection = nil |
| 143 | report(sources: []) |
| 144 | } |
| 145 | |
| 146 | // MARK: - The text view |
| 147 | |
| 148 | func attach(_ text: DocsTextView) { |
| 149 | if textView !== text { |
| 150 | // Another text view, without the model opening again (the host |
| 151 | // rebuilt: an iPad split collapsing, a window restructured), or |
| 152 | // the first. Let the old one go if it is still there (its host |
| 153 | // may have released it already), and draw the new one whole: |
| 154 | // what the surface remembers is the old storage's, not this one's. |
| 155 | if let old = textView { Self.release(old) } |
| 156 | entries = [:]; order = []; sourceCounts = [:] |
| 157 | pendingDirty = []; fullDiff = newest != nil |
| 158 | } |
| 159 | textView = text |
| 160 | text.delegate = self |
| 161 | storage?.delegate = self |
| 162 | text.isEditable = isEditable |
| 163 | #if os(iOS) |
| 164 | text.showsKeyboardBar = isEditable |
| 165 | // The Format sheet's state, for a text view built while it is open. |
| 166 | text.keyboardSuppressed = keyboardSuppressed |
| 167 | text.bottomObstruction = sheetHeight |
| 168 | #endif |
| 169 | text.ruleCommand = { [weak self] command in self?.ruleEdit(command) ?? false } |
| 170 | text.clipboardEdit = { [weak self] blocks, range, replacement in self?.clipboardEdit(blocks: blocks, range: range, replacement: replacement) ?? false } |
| 171 | text.compositionChanged = { [weak self] active in self?.hooks.compositionChanged(active) } |
| 172 | text.compositionCommitted = { [weak self] before, after in self?.commitComposition(before: before, after: after) ?? true } |
| 173 | text.action = { [weak self, weak text] action in |
| 174 | text?.lastInputRule = nil |
| 175 | return self?.hooks.action(action) ?? false |
| 176 | } |
| 177 | text.canAction = { [weak self] action in self?.hooks.canAction(action) ?? false } |
| 178 | if let storage { index.rebuild(from: storage) } |
| 179 | // Inside SwiftUI's update: draw now, so the first frame is final, |
| 180 | // but tell the model on the next turn, not during the update. |
| 181 | flushIfDeferred(notifyLater: true) |
| 182 | } |
| 183 | |
| 184 | private static func release(_ text: DocsTextView) { |
| 185 | if text.delegate === nil { return } |
| 186 | text.delegate = nil |
| 187 | #if os(macOS) |
| 188 | text.textStorage?.delegate = nil |
| 189 | #else |
| 190 | text.textStorage.delegate = nil |
| 191 | #endif |
| 192 | text.ruleCommand = nil; text.clipboardEdit = nil; text.compositionChanged = nil |
| 193 | text.compositionCommitted = nil; text.action = nil; text.canAction = nil |
| 194 | } |
| 195 | |
| 196 | #if os(iOS) |
| 197 | /// Remembered for a text view attached while the sheet is open. |
| 198 | private var keyboardSuppressed = false |
| 199 | private var sheetHeight: CGFloat = 0 |
| 200 | /// The Format sheet is open (iPhone, S3): the keyboard goes, the text |
| 201 | /// view keeps first responder and the selection. |
| 202 | func suppressKeyboard(_ suppressed: Bool) { |
| 203 | keyboardSuppressed = suppressed |
| 204 | textView?.keyboardSuppressed = suppressed |
| 205 | } |
| 206 | /// The sheet's height over the text: it scrolls clear of it, the |
| 207 | /// selection kept in view above it. |
| 208 | func sheetCovers(_ height: CGFloat) { |
| 209 | sheetHeight = height |
| 210 | guard let text = textView, abs(text.bottomObstruction - height) > 0.5 else { return } |
| 211 | text.bottomObstruction = height |
| 212 | if height > 0 { text.scrollRangeToVisible(text.selectedRange) } |
| 213 | } |
| 214 | #endif |
| 215 | |
| 216 | /// An explicit command (not typing) went to the model. |
| 217 | func explicitCommand() { textView?.lastInputRule = nil } |
| 218 | |
| 219 | // MARK: - Publications |
| 220 | |
| 221 | /// A publication from the model (trigger (a)). Stale ones are dropped: |
| 222 | /// the storage already reflects that revision or a later one. |
| 223 | func apply(_ publication: Publication) { |
| 224 | publicationsReceived += 1 |
| 225 | willApply?(publication) |
| 226 | if let newest, publication.revision <= newest.revision { return } |
| 227 | guard publication.revision > appliedRevision else { return } |
| 228 | if let dirty = publication.dirty { pendingDirty.formUnion(dirty) } else { fullDiff = true } |
| 229 | newest = publication |
| 230 | flushIfDeferred() |
| 231 | } |
| 232 | |
| 233 | /// Images arrived (or went): only the blocks that hold them are drawn again. |
| 234 | func imagesChanged(_ loaded: [String: DocsPlatformImage]) { |
| 235 | let changed = Set(loaded.keys).symmetricDifference(images.keys) |
| 236 | .union(loaded.keys.filter { key in images[key].map { $0 !== loaded[key] } ?? false }) |
| 237 | images = loaded |
| 238 | guard !changed.isEmpty else { return } |
| 239 | for (id, entry) in entries where !entry.sources.isDisjoint(with: changed) { pendingDirty.insert(id) } |
| 240 | flushIfDeferred() |
| 241 | } |
| 242 | |
| 243 | /// Draws what is waiting, if the text view can take it now: no input |
| 244 | /// pending, nothing composing, the newest generation current, and no |
| 245 | /// marked text (spec §7 Design 6). Called on every event that can make |
| 246 | /// that true: (a) a publication applied, (b) the edit queue draining, |
| 247 | /// (c) composition ending, (d) the generation catching up. |
| 248 | func flushIfDeferred(notifyLater: Bool = false) { |
| 249 | guard !flushing, let newest, let text = textView, let storage = text.textStorage as NSTextStorage? else { return } |
| 250 | let waiting = newest.revision > appliedRevision || !pendingDirty.isEmpty || fullDiff |
| 251 | guard waiting, hooks.canRender(newest.generation), !Self.hasMarkedText(text) else { return } |
| 252 | #if DOCS_PROBES |
| 253 | let probeStart = DocsProbes.now() |
| 254 | defer { DocsProbes.publications += 1; DocsProbes.publicationMs += DocsProbes.ms(since: probeStart) } |
| 255 | #endif |
| 256 | flushing = true |
| 257 | defer { flushing = false } |
| 258 | let advancing = newest.revision > appliedRevision |
| 259 | let newGeneration = generation != newest.generation |
| 260 | let selected = newGeneration ? hooks.currentSelection() : (selectedRange ?? NSRange(location: 0, length: 0)) |
| 261 | applying = true |
| 262 | if entries.isEmpty { drawWhole(newest.projection, into: text, storage: storage) } |
| 263 | else { drawChanged(newest.projection, storage: storage, textOnly: !advancing) } |
| 264 | let sources = sourceCounts.keys.sorted() |
| 265 | let length = storage.length |
| 266 | let range = NSRange(location: min(selected.location, length), length: min(selected.length, max(0, length - selected.location))) |
| 267 | if selectedRange != range { Self.select(range, in: text) } |
| 268 | applying = false |
| 269 | appliedRevision = newest.revision |
| 270 | generation = newest.generation |
| 271 | if !Self.hasMarkedText(text) { applyTypingFont() } |
| 272 | // The model hears of the draw (the generation drawn, the image |
| 273 | // sources) now, or, inside SwiftUI's update (attach), on the next |
| 274 | // turn: no observed state is assigned during a view update. |
| 275 | let rendered = newest.generation |
| 276 | if notifyLater { |
| 277 | // Only if the surface still shows that draw on the next turn: |
| 278 | // a reset in between (another document) makes it the old one's. |
| 279 | let resets = self.resets |
| 280 | Task { @MainActor [weak self] in |
| 281 | guard let self, self.resets == resets, self.generation == rendered else { return } |
| 282 | self.report(sources: sources); self.hooks.didRender(rendered) |
| 283 | } |
| 284 | } else { report(sources: sources); hooks.didRender(rendered) } |
| 285 | } |
| 286 | |
| 287 | /// Open, or after `reset`: the one whole render, and on iOS the one |
| 288 | /// `attributedText` assignment. |
| 289 | private func drawWhole(_ projection: CRDTProjection, into text: DocsTextView, storage: NSTextStorage) { |
| 290 | let content = NativeTextProjection.render(projection, images: images) |
| 291 | #if os(macOS) |
| 292 | DocumentRenderReconciliation.apply(content, to: storage) |
| 293 | #else |
| 294 | text.attributedText = content |
| 295 | #if DOCS_PROBES |
| 296 | DocsProbes.attributedTextAssignments += 1 |
| 297 | #endif |
| 298 | #endif |
| 299 | index.rebuild(from: storage) |
| 300 | rememberWhole(projection.children) |
| 301 | } |
| 302 | /// After a whole draw: every block as the storage now holds it. |
| 303 | private func rememberWhole(_ nodes: [CRDTNode]) { |
| 304 | entries = [:]; sourceCounts = [:] |
| 305 | var lengths: [String: Int] = [:] |
| 306 | for run in index.runs { if let id = run.id { lengths[id, default: 0] += run.length } } |
| 307 | let contexts = DocumentBlockSpacing.contexts(nodes) |
| 308 | for (node, context) in zip(nodes, contexts) { remember(node, context: context, length: lengths[node.id] ?? 0) } |
| 309 | order = nodes.map(\.id) |
| 310 | pendingDirty = []; fullDiff = false |
| 311 | } |
| 312 | |
| 313 | /// Everything since: the blocks that changed (or whose neighbours |
| 314 | /// changed their spacing), drawn on their own and reconciled into |
| 315 | /// their own characters. `textOnly`: nothing new from the replica (an |
| 316 | /// image arrived), so a block whose text no longer matches what is |
| 317 | /// shown (typing the replica has not answered yet) waits. |
| 318 | private func drawChanged(_ projection: CRDTProjection, storage: NSTextStorage, textOnly: Bool) { |
| 319 | let nodes = projection.children |
| 320 | let ids = nodes.map(\.id) |
| 321 | guard Set(ids).count == ids.count else { |
| 322 | // Two blocks under one id: no per-block identity to go by. |
| 323 | DocumentRenderReconciliation.apply(NativeTextProjection.render(projection, images: images), to: storage) |
| 324 | index.rebuild(from: storage) |
| 325 | rememberWhole(nodes) |
| 326 | return |
| 327 | } |
| 328 | // What changed, by id. |
| 329 | var changed = pendingDirty |
| 330 | for node in nodes where entries[node.id] == nil || (fullDiff && entries[node.id]?.node != node) { changed.insert(node.id) } |
| 331 | // Each block's context; a block whose context moved is drawn again |
| 332 | // (its neighbour changed its top margin, or it became first or last). |
| 333 | var contexts = Array(repeating: DocumentBlockSpacing.Context(), count: nodes.count) |
| 334 | var next: CGFloat? |
| 335 | for index in nodes.indices.reversed() { |
| 336 | contexts[index].first = index == 0 |
| 337 | contexts[index].last = index == nodes.count - 1 |
| 338 | contexts[index].nextBefore = next |
| 339 | let node = nodes[index] |
| 340 | let before: CGFloat? = index == 0 || changed.contains(node.id) || entries[node.id] == nil |
| 341 | ? DocumentBlockSpacing.firstBefore(node, first: index == 0) : entries[node.id]!.firstBefore |
| 342 | if let before { next = before } |
| 343 | } |
| 344 | for index in nodes.indices { |
| 345 | contexts[index].leading = true |
| 346 | let node = nodes[index] |
| 347 | let empty = changed.contains(node.id) || entries[node.id] == nil |
| 348 | ? DocumentBlockSpacing.firstBefore(node) == nil : entries[node.id]!.firstBefore == nil |
| 349 | if !empty { break } |
| 350 | } |
| 351 | var draw = changed |
| 352 | for (index, node) in nodes.enumerated() where entries[node.id]?.context != contexts[index] { draw.insert(node.id) } |
| 353 | if draw.isEmpty && order == ids { pendingDirty = []; fullDiff = false; return } |
| 354 | |
| 355 | // Anchors: blocks kept as they are, each one contiguous run of the |
| 356 | // index, in order. Everything between two anchors is one gap. |
| 357 | let positions = index.positions() |
| 358 | var anchors: [(block: Int, run: DocumentBlockIndex.Run)] = [] |
| 359 | var lastEnd = 0 |
| 360 | for (block, id) in ids.enumerated() where !draw.contains(id) { |
| 361 | guard let runs = positions[id], runs.count == 1 else { draw.insert(id); continue } |
| 362 | let run = index.runs[runs[0]] |
| 363 | guard run.location >= lastEnd, run.length == entries[id]?.length else { draw.insert(id); continue } |
| 364 | anchors.append((block, run)); lastEnd = run.end |
| 365 | } |
| 366 | // Gaps, last first, so earlier ranges stay where they are. |
| 367 | var gaps: [(blocks: Range<Int>, range: NSRange)] = [] |
| 368 | var previousBlock = -1, previousEnd = 0 |
| 369 | for (block, run) in anchors + [(nodes.count, DocumentBlockIndex.Run(id: nil, location: storage.length, length: 0))] { |
| 370 | let range = NSRange(location: previousEnd, length: run.location - previousEnd) |
| 371 | if block > previousBlock + 1 || range.length > 0 { gaps.append(((previousBlock + 1)..<block, range)) } |
| 372 | previousBlock = block; previousEnd = run.end |
| 373 | } |
| 374 | var waiting = Set<String>() |
| 375 | for gap in gaps.reversed() { |
| 376 | let rendered = NSMutableAttributedString() |
| 377 | var lengths: [Int] = [] |
| 378 | for block in gap.blocks { |
| 379 | let drawn = NativeTextProjection.renderBlock(nodes[block], context: contexts[block], images: images) |
| 380 | lengths.append(drawn.length) |
| 381 | rendered.append(drawn) |
| 382 | } |
| 383 | if textOnly, storage.mutableString.substring(with: gap.range) != rendered.string { |
| 384 | for block in gap.blocks { waiting.insert(nodes[block].id) } |
| 385 | continue |
| 386 | } |
| 387 | DocumentRenderReconciliation.apply(rendered, to: storage, in: gap.range) |
| 388 | for (block, length) in zip(gap.blocks, lengths) { remember(nodes[block], context: contexts[block], length: length) } |
| 389 | } |
| 390 | for (block, _) in anchors { entries[nodes[block].id]?.context = contexts[block] } |
| 391 | let kept = Set(ids) |
| 392 | for id in order where !kept.contains(id) { forget(id) } |
| 393 | order = ids |
| 394 | pendingDirty = waiting; fullDiff = false |
| 395 | } |
| 396 | |
| 397 | private func remember(_ node: CRDTNode, context: DocumentBlockSpacing.Context, length: Int) { |
| 398 | forget(node.id) |
| 399 | let sources = DocsImageStore.sources(in: node) |
| 400 | for source in sources { sourceCounts[source, default: 0] += 1 } |
| 401 | entries[node.id] = Entry(node: node, context: context, firstBefore: DocumentBlockSpacing.firstBefore(node), sources: sources, length: length) |
| 402 | } |
| 403 | private func forget(_ id: String) { |
| 404 | guard let old = entries.removeValue(forKey: id) else { return } |
| 405 | for source in old.sources { |
| 406 | let count = (sourceCounts[source] ?? 1) - 1 |
| 407 | sourceCounts[source] = count > 0 ? count : nil |
| 408 | } |
| 409 | } |
| 410 | private func report(sources: [String]) { |
| 411 | guard sources != reportedSources else { return } |
| 412 | reportedSources = sources |
| 413 | hooks.imageSourcesChanged(sources) |
| 414 | } |
| 415 | |
| 416 | // MARK: - Typing and selection (the text view's delegate) |
| 417 | |
| 418 | /// The text view changed its own text (typing, a paste, a composition): |
| 419 | /// those blocks are drawn again at the next publication, whatever the |
| 420 | /// replica says changed. Usually the replica names them too; but an |
| 421 | /// edit it refused (or one a dropped publication carried) would |
| 422 | /// otherwise stay on screen until something else touched the block. |
| 423 | private func typed(around edited: NSRange) { |
| 424 | // From the character before the edit through the one after it: an |
| 425 | // edit across blocks leaves the head of one and the tail of |
| 426 | // another, and both must be drawn again even if the replica |
| 427 | // changes neither (it refused the edit, or clamped it). |
| 428 | let first = max(0, edited.location - 1) |
| 429 | let last = NSMaxRange(edited) |
| 430 | let touched = index.runs(holding: first, through: last) |
| 431 | for run in touched { if let id = run.id { pendingDirty.insert(id) } } |
| 432 | // Text typed with no block (UIKit's typing attributes may not carry |
| 433 | // it) belongs to the block before it. |
| 434 | if let start = touched.first, start.id == nil, touched.startIndex > 0, let id = index.runs[touched.startIndex - 1].id { |
| 435 | pendingDirty.insert(id) |
| 436 | } |
| 437 | } |
| 438 | |
| 439 | private func applyTypingFont() { |
| 440 | guard let text = textView, let marks = typingMarks, let selected = selectedRange, selected.length == 0, !Self.hasMarkedText(text), |
| 441 | let font = NativeTextProjection.typingFont(in: content, at: selected.location, marks: marks) else { return } |
| 442 | if text.typingAttributes[.font] as? DocsPlatformFont != font { text.typingAttributes[.font] = font } |
| 443 | } |
| 444 | |
| 445 | func ruleEdit(_ command: [String: JSONValue]) -> Bool { |
| 446 | var command = command; command["generation"] = .number(Double(generation)) |
| 447 | let accepted = hooks.edit(command) |
| 448 | if accepted, case .number(let at)? = command["at"] { |
| 449 | let inserted: Int |
| 450 | if command["op"] == .string("display_revert_rule"), case .string(let text)? = command["text"] { inserted = text.utf16.count } else { inserted = 0 } |
| 451 | expectedSelection = NSRange(location: Int(at) + inserted, length: 0) |
| 452 | } |
| 453 | return accepted |
| 454 | } |
| 455 | func clipboardEdit(blocks: [JSONValue]?, range: NSRange, replacement: String) -> Bool { |
| 456 | 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))] |
| 457 | if let blocks { command["blocks"] = .array(blocks) } else { command["text"] = .string(replacement) } |
| 458 | let accepted = hooks.edit(command) |
| 459 | if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) } |
| 460 | return accepted |
| 461 | } |
| 462 | func commitComposition(before: NSAttributedString, after: String) -> Bool { |
| 463 | guard let (range, replacement) = DocumentComposition.replacement(before: before.string, after: after) else { return true } |
| 464 | guard var command = TextEditMapping.displayCommand(in: before, range: range, replacement: replacement) else { return false } |
| 465 | command["generation"] = .number(Double(generation)) |
| 466 | let accepted = hooks.edit(command) |
| 467 | if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) } |
| 468 | return accepted |
| 469 | } |
| 470 | /// Typing: the command first, then (if the model took it) the text view |
| 471 | /// shows it at once, before any publication. |
| 472 | func shouldChange(_ text: DocsTextView, in range: NSRange, replacement: String) -> Bool { |
| 473 | if text.isComposing { return true } |
| 474 | if text.interceptInput(replacement, range: range) { return false } |
| 475 | guard var command = TextEditMapping.displayCommand(in: content, range: range, replacement: replacement) else { return false } |
| 476 | command["generation"] = .number(Double(generation)) |
| 477 | let accepted = hooks.edit(command) |
| 478 | if accepted { expectedSelection = NSRange(location: range.location + replacement.utf16.count, length: 0) } |
| 479 | return accepted |
| 480 | } |
| 481 | func selectionDidChange(_ text: DocsTextView) { |
| 482 | // A render moves the caret (iOS: assigning the text moves it to the |
| 483 | // end and back) and then puts it where the model has it. Telling |
| 484 | // the model here would change it in the middle of that (the iOS |
| 485 | // render loop, TestFlight 0.1.10 (12)). |
| 486 | guard !applying else { return } |
| 487 | // Not `content.string`: that copies the whole text on every caret move. |
| 488 | let characters = storage?.mutableString |
| 489 | let length = characters?.length ?? 0 |
| 490 | let selected = selectedRange ?? NSRange(location: 0, length: 0) |
| 491 | if selected.length == 0 && selected.location == length && length > 0 && characters?.character(at: length - 1) == 10 { |
| 492 | Self.select(NSRange(location: max(0, selected.location - 1), length: 0), in: text); return |
| 493 | } |
| 494 | if !text.isComposing { |
| 495 | if selected != expectedSelection && selected != hooks.currentSelection() { |
| 496 | hooks.selectionMoved() |
| 497 | text.lastInputRule = nil |
| 498 | } |
| 499 | expectedSelection = nil |
| 500 | } |
| 501 | hooks.selectionChanged(selected) |
| 502 | } |
| 503 | |
| 504 | private static func hasMarkedText(_ text: DocsTextView) -> Bool { |
| 505 | #if os(macOS) |
| 506 | text.hasMarkedText() |
| 507 | #else |
| 508 | text.markedTextRange != nil |
| 509 | #endif |
| 510 | } |
| 511 | private static func select(_ range: NSRange, in text: DocsTextView) { |
| 512 | #if os(macOS) |
| 513 | text.setSelectedRange(range) |
| 514 | #else |
| 515 | text.selectedRange = range |
| 516 | #endif |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | // MARK: - Delegates |
| 521 | |
| 522 | extension DocumentSurface: NSTextStorageDelegate { |
| 523 | nonisolated func textStorage(_ textStorage: NSTextStorage, didProcessEditing editedMask: DocsStorageEditActions, range editedRange: NSRange, changeInLength delta: Int) { |
| 524 | // TextKit edits the text view's storage on the main thread only. |
| 525 | nonisolated(unsafe) let edited = textStorage |
| 526 | MainActor.assumeIsolated { |
| 527 | guard edited === storage else { return } |
| 528 | index.processEditing(edited, edited: editedRange, delta: delta) |
| 529 | #if os(iOS) |
| 530 | // The iPhone's page breaks (TextKit 2, DocsPhonePages). |
| 531 | if editedMask.contains(.editedCharacters) || editedMask.contains(.editedAttributes) { textView?.storageEdited(editedRange, delta: delta) } |
| 532 | // The pages building paragraphs again: no text changed. |
| 533 | if textView?.pages.regenerating == true { return } |
| 534 | #endif |
| 535 | if !applying, editedMask.contains(.editedCharacters) { typed(around: editedRange) } |
| 536 | } |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | #if os(macOS) |
| 541 | extension DocumentSurface: NSTextViewDelegate { |
| 542 | func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool { |
| 543 | guard let text = textView as? DocsTextView else { return false } |
| 544 | if text.isComposing { return true } |
| 545 | guard let replacementString else { return false } |
| 546 | return shouldChange(text, in: affectedCharRange, replacement: replacementString) |
| 547 | } |
| 548 | func textViewDidChangeSelection(_ notification: Notification) { |
| 549 | guard let text = notification.object as? DocsTextView else { return } |
| 550 | selectionDidChange(text) |
| 551 | } |
| 552 | } |
| 553 | #else |
| 554 | extension DocumentSurface: UITextViewDelegate { |
| 555 | func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { |
| 556 | guard let view = textView as? DocsTextView else { return false } |
| 557 | return shouldChange(view, in: range, replacement: text) |
| 558 | } |
| 559 | func textViewDidChangeSelection(_ textView: UITextView) { |
| 560 | guard let text = textView as? DocsTextView else { return } |
| 561 | text.releaseHeldBreaks() |
| 562 | selectionDidChange(text) |
| 563 | } |
| 564 | } |
| 565 | #endif |
| 566 | |