| 1 | import Foundation |
| 2 | import Observation |
| 3 | import RastrilloApple |
| 4 | import RastrilloNative |
| 5 | |
| 6 | @MainActor @Observable final class DocsModel { |
| 7 | enum ListState { case loading, loaded, failed } |
| 8 | var listState = ListState.loading |
| 9 | private var listRequest = UUID() |
| 10 | var documents: [DocumentSummary] = [] |
| 11 | var canCreate = false |
| 12 | // Observed state is assigned only when it differs (spec 2026-11-22 §7 |
| 13 | // Design 11): an equal assignment still invalidates every view that |
| 14 | // reads it. These are written from many places, so the guard is in |
| 15 | // their setters. |
| 16 | @ObservationIgnored private var _errorKey: String? |
| 17 | var errorKey: String? { |
| 18 | get { access(keyPath: \.errorKey); return _errorKey } |
| 19 | set { guard newValue != _errorKey else { return }; withMutation(keyPath: \.errorKey) { _errorKey = newValue } } |
| 20 | } |
| 21 | @ObservationIgnored private var _detail: DocumentDetail? |
| 22 | var detail: DocumentDetail? { |
| 23 | get { access(keyPath: \.detail); return _detail } |
| 24 | set { |
| 25 | guard newValue != _detail else { return } |
| 26 | withMutation(keyPath: \.detail) { _detail = newValue } |
| 27 | pushEditability() |
| 28 | refreshToolbarSelection() |
| 29 | } |
| 30 | } |
| 31 | /// The newest projection published. Not observed: the editor draws it |
| 32 | /// through `surface`, never through SwiftUI (spec §7 Design 2). What |
| 33 | /// the chrome needs of it is `history`, observed on its own. |
| 34 | @ObservationIgnored var projection: CRDTProjection? { |
| 35 | didSet { |
| 36 | let next = DocumentHistoryState(projection) |
| 37 | if next != history { history = next } |
| 38 | } |
| 39 | } |
| 40 | /// The open document's text, as its text view holds it. |
| 41 | @ObservationIgnored let surface = DocumentSurface() |
| 42 | /// Undo, redo and whether a document is shown, observed on their own: |
| 43 | /// the header's pill, the toolbar's undo and redo, and Tools ▸ Word |
| 44 | /// count read these, never the projection. Set with each projection the |
| 45 | /// model publishes (publishCurrent), whatever the access and whether or |
| 46 | /// not input is pending; assigned only when they differ. |
| 47 | private(set) var history = DocumentHistoryState() |
| 48 | /// Moves after each draw that changed the text view's storage (the |
| 49 | /// surface's flush; S1a): what a live count (the word-count sheet) |
| 50 | /// watches to recompute. Never moves inside a view update. |
| 51 | private(set) var contentRevision: UInt64 = 0 |
| 52 | /// Whether a document has been published to the editor: what the |
| 53 | /// workspace shows instead of the projection itself. |
| 54 | var showsDocument: Bool { history.loaded } |
| 55 | /// The formatting at the selection, for the toolbar: one value, |
| 56 | /// assigned only when it differs (spec §7 Design 10). |
| 57 | private(set) var toolbarSelection = DocumentToolbarSelection() |
| 58 | /// Commands have been held back (input pending, a generation catching |
| 59 | /// up, a pause) for longer than a glance: the toolbar, inspector and |
| 60 | /// Format menu show disabled until they can run, and anything queued |
| 61 | /// meanwhile is dropped (grey means the click did not take). Not for the |
| 62 | /// few milliseconds every key holds them, which would make the panel |
| 63 | /// blink and SwiftUI evaluate it on every key (S1b step 0), and never for |
| 64 | /// an IME composition, however long (CJK writers compose constantly): |
| 65 | /// commands chosen then are queued and run after the commit. |
| 66 | @ObservationIgnored private var _commandsHeld = false |
| 67 | private(set) var commandsHeld: Bool { |
| 68 | get { access(keyPath: \.commandsHeld); return _commandsHeld } |
| 69 | set { guard newValue != _commandsHeld else { return }; withMutation(keyPath: \.commandsHeld) { _commandsHeld = newValue } } |
| 70 | } |
| 71 | /// How long commands may be held before they show disabled: the |
| 72 | /// busy-button rule's 650 ms. |
| 73 | static var commandsHeldAfter: Duration = .milliseconds(650) |
| 74 | @ObservationIgnored private var holdTask: Task<Void, Never>? |
| 75 | /// Commands asked for while held, in order (`whenCommandsReady`). |
| 76 | @ObservationIgnored private var readyQueue: [@MainActor (DocumentCommands) -> Void] = [] |
| 77 | /// The image sources of the document drawn, for the image loader. |
| 78 | private(set) var imageSources: [String] = [] |
| 79 | /// Moves when the editor asks for Open a document… (⌘K): the window |
| 80 | /// shows its jump sheet (spec §1, menus). |
| 81 | private(set) var jumpRequests = 0 |
| 82 | var projectionGeneration: UInt64 = 0 { |
| 83 | // Trigger (d): the generation caught up. |
| 84 | didSet { if oldValue != projectionGeneration { surface.flushIfDeferred() } } |
| 85 | } |
| 86 | var renderedGeneration: UInt64 = 0 |
| 87 | var composing = false |
| 88 | @ObservationIgnored private var _inputPaused = false |
| 89 | var inputPaused: Bool { |
| 90 | get { access(keyPath: \.inputPaused); return _inputPaused } |
| 91 | set { |
| 92 | guard newValue != _inputPaused else { return } |
| 93 | withMutation(keyPath: \.inputPaused) { _inputPaused = newValue } |
| 94 | pushEditability() |
| 95 | refreshToolbarSelection() |
| 96 | // Not a flush trigger (spec §7 Design 6, "Two events are not |
| 97 | // triggers"): canRender does not read inputPaused, and must not, |
| 98 | // since a reader is paused for good and still sees peers' |
| 99 | // changes; a writer paused by a refused command still holds it |
| 100 | // as pending input, so the queue draining draws. The call costs |
| 101 | // nothing. |
| 102 | if !newValue { surface.flushIfDeferred() } |
| 103 | } |
| 104 | } |
| 105 | /// Spec §6 row 1: a 403 or 404 said the document was deleted or is no |
| 106 | /// longer shared. Left again on a later 200. |
| 107 | var unavailable = false |
| 108 | /// Input paused by a 401 while the session is re-minted (§6 notes): a |
| 109 | /// reason of its own, beside `inputPaused`, so the re-minted session's |
| 110 | /// 200 clears only this one and never a pause something else set. |
| 111 | @ObservationIgnored private var _sessionPaused = false |
| 112 | private(set) var sessionPaused: Bool { |
| 113 | get { access(keyPath: \.sessionPaused); return _sessionPaused } |
| 114 | set { |
| 115 | guard newValue != _sessionPaused else { return } |
| 116 | withMutation(keyPath: \.sessionPaused) { _sessionPaused = newValue } |
| 117 | pushEditability() |
| 118 | refreshToolbarSelection() |
| 119 | } |
| 120 | } |
| 121 | /// The pause came from a read-only answer to `refreshAccess`: a later |
| 122 | /// writable answer lifts it. |
| 123 | @ObservationIgnored private var pausedAsReader = false |
| 124 | /// A Delete… of the document opened at this epoch is waiting for the |
| 125 | /// server: its typing and commands wait too, so nothing new reaches the |
| 126 | /// outbox of a document about to be gone. Another document opened |
| 127 | /// meanwhile is not held by it. |
| 128 | @ObservationIgnored private var deletingEpoch: UUID? { |
| 129 | didSet { if oldValue != deletingEpoch { pushEditability(); refreshToolbarSelection() } } |
| 130 | } |
| 131 | private var deleting: Bool { deletingEpoch != nil && deletingEpoch == documentEpoch } |
| 132 | /// Typing and commands are refused: paused for any reason. |
| 133 | var inputBlocked: Bool { inputPaused || sessionPaused || deleting } |
| 134 | /// What the window may do with the document (§6 rows 1 and 10). |
| 135 | var documentAccess: DocsAccess { unavailable ? .unavailable : detail?.can_write == true ? .writable : .readOnly } |
| 136 | var explicitCommandRevision: UInt64 = 0 |
| 137 | var loading = false |
| 138 | var creatingDocument = false |
| 139 | private var lifetime = UUID() |
| 140 | @ObservationIgnored private var _draftToken: String? |
| 141 | private(set) var draftToken: String? { |
| 142 | get { access(keyPath: \.draftToken); return _draftToken } |
| 143 | set { guard newValue != _draftToken else { return }; withMutation(keyPath: \.draftToken) { _draftToken = newValue } } |
| 144 | } |
| 145 | private var creationTask: Task<Void, Never>? |
| 146 | @ObservationIgnored private var _pendingTitle: String? |
| 147 | private var pendingTitle: String? { |
| 148 | get { access(keyPath: \.pendingTitle); return _pendingTitle } |
| 149 | set { guard newValue != _pendingTitle else { return }; withMutation(keyPath: \.pendingTitle) { _pendingTitle = newValue } } |
| 150 | } |
| 151 | private var metadataDirty = false |
| 152 | var renameInput: String? |
| 153 | private var titleRevision: UInt64 = 0 |
| 154 | var isDraft: Bool { draftToken != nil } |
| 155 | var editorIdentity = UUID() |
| 156 | |
| 157 | /// Where the text view's selection is. The text view tells the model |
| 158 | /// by callback; nothing observes it (spec §7 Design 10). |
| 159 | @ObservationIgnored var selection = NSRange(location: 0, length: 0) |
| 160 | var typingMarks: [String: JSONValue]? { |
| 161 | didSet { if oldValue != typingMarks { surface.typingMarks = typingMarks; refreshToolbarSelection() } } |
| 162 | } |
| 163 | private var replica: CRDTReplica? |
| 164 | private var sequence: Int64 = 0 |
| 165 | let offlineAccount: DocsOfflineAccount |
| 166 | private var persistence: DocsPersistence? |
| 167 | private var documentKey: String? |
| 168 | private var failedUpdate: Data? |
| 169 | private var localFailure: SyncFailure? |
| 170 | private var writerTask: Task<Void, Never>? |
| 171 | private let writer = CoalescedRunner() |
| 172 | private var laneSummary = OutboxSummary() |
| 173 | private var summaryTask: Task<Void, Never>? |
| 174 | @ObservationIgnored private var sendObserver: UUID? |
| 175 | /// A stream event that may be only this client's own POST, held until |
| 176 | /// that POST's answer says (see `refresh`). |
| 177 | @ObservationIgnored private var heldRemoteSequence: Int64? |
| 178 | @ObservationIgnored private var heldRemoteTask: Task<Void, Never>? |
| 179 | /// The metadata revision `reloadMetadata` last read for this document. |
| 180 | @ObservationIgnored private var loadedMetadataRevision: Int? |
| 181 | /// Remote rows that would not apply (a corrupt or over-budget update): |
| 182 | /// the cursor they were fetched from, how often, and when to try again. |
| 183 | /// Fetching the same bytes on every announcement would spend the |
| 184 | /// interpreter's whole budget each time and stall the editor behind it. |
| 185 | @ObservationIgnored private var refusedRemote: (since: Int64, attempts: Int, notBefore: ContinuousClock.Instant)? |
| 186 | @ObservationIgnored private var refusedRetryTask: Task<Void, Never>? |
| 187 | @ObservationIgnored private var latestAnnounced: Int64 = 0 |
| 188 | /// The replica parks something it has not accepted (#145, #147): catch up, |
| 189 | /// and from the start if that does not settle it. See `settleParking`. |
| 190 | @ObservationIgnored private(set) var unsettledParking = false |
| 191 | /// The iPhone app is in the background: no stream may start. |
| 192 | @ObservationIgnored private var liveUpdatesSuspended = false |
| 193 | var syncStatus: SyncStatus { offlineAccount.drainer.status(lane: documentKey.map { "doc:" + $0 }, localFailure: localFailure) } |
| 194 | var lostChangesNotice: String? { outboxSummary.lostUnsent ? NativeSyncStrings.kit.unsentLost : nil } |
| 195 | func dismissLostChangesNotice() async { await offlineAccount.outbox.acknowledgeLoss() } |
| 196 | var outboxSummary: OutboxSummary { offlineAccount.drainer.summary } |
| 197 | |
| 198 | private var editing: [[String: JSONValue]] = [] |
| 199 | private var editingTask: Task<Void, Never>? |
| 200 | private var streamTask: Task<Void, Never>? |
| 201 | private var saving = false |
| 202 | private var documentEpoch = UUID() |
| 203 | private let publications = DocumentPublication() |
| 204 | /// Resolved on every request, never captured: this model can hold unsent |
| 205 | /// edits for longer than one session, and signing in again replaces the |
| 206 | /// transport under it. A captured client would keep sending with the ended |
| 207 | /// session. nil means no session; requests then fail as `.unauthorized`. |
| 208 | private let transport: @MainActor () -> NativeTransport? |
| 209 | /// The stream loop waits on this between attempts, so a restored network |
| 210 | /// reconnects at once and an offline device makes no timed attempts. |
| 211 | let connectivity: NativeConnectivity |
| 212 | /// Monotonic seconds for the stream loop's pacing; tests substitute a fake. |
| 213 | var reconnectClock: @MainActor () -> TimeInterval = { ProcessInfo.processInfo.systemUptime } |
| 214 | init(transport: @escaping @MainActor () -> NativeTransport?, connectivity: NativeConnectivity? = nil, draft: Bool = false, offlineAccount: DocsOfflineAccount? = nil) { |
| 215 | self.transport = transport |
| 216 | self.connectivity = connectivity ?? .shared |
| 217 | self.offlineAccount = offlineAccount ?? DocsOfflineAccount(store: EphemeralDocsStore(), accountID: UUID().uuidString, connectivity: connectivity ?? .shared, transport: transport) |
| 218 | if draft { draftToken = UUID().uuidString } |
| 219 | configureSurface() |
| 220 | } |
| 221 | convenience init(client: NativeTransport, connectivity: NativeConnectivity? = nil, draft: Bool = false) { |
| 222 | self.init(transport: { client }, connectivity: connectivity, draft: draft) |
| 223 | } |
| 224 | private func client() throws -> NativeTransport { |
| 225 | guard let current = transport() else { throw NativeClientError.unauthorized } |
| 226 | return current |
| 227 | } |
| 228 | var hasPendingInput: Bool { !editing.isEmpty || editingTask != nil } |
| 229 | var hasUnpersistedInput: Bool { metadataDirty || (renameInput != nil && renameInput != detail?.title) || composing || !editing.isEmpty || editingTask != nil || failedUpdate != nil || localFailure == .cannotSaveOnDevice } |
| 230 | var hasUnsentChanges: Bool { !laneSummary.isEmpty || pendingTitle != nil || isDraft } |
| 231 | // K6 relaxes the close guard; K3 exposes the split without bypassing it. |
| 232 | var hasUnsavedChanges: Bool { hasUnpersistedInput || hasUnsentChanges } |
| 233 | private func configurePersistence(key: String, replica: CRDTReplica) { |
| 234 | documentKey = key |
| 235 | persistence = DocsPersistence(store: offlineAccount.store, outbox: offlineAccount.outbox, key: key, replica: replica, cache: offlineAccount.replicaCache) |
| 236 | loadedMetadataRevision = nil |
| 237 | if let sendObserver { offlineAccount.stopObservingSends(sendObserver) } |
| 238 | sendObserver = offlineAccount.observeSends { [weak self] result in self?.sent(result) } |
| 239 | summaryTask?.cancel() |
| 240 | summaryTask = Task { [weak self, outbox = offlineAccount.outbox] in |
| 241 | for await summary in await outbox.changes { |
| 242 | guard let self, self.documentKey == key else { return } |
| 243 | self.updateLaneSummary(summary.only("doc:" + key)) |
| 244 | self.reloadMetadata() |
| 245 | } |
| 246 | } |
| 247 | } |
| 248 | private func updateLaneSummary(_ summary: OutboxSummary) { |
| 249 | laneSummary = summary |
| 250 | let tooLarge = summary.lanes.values.contains { $0.bytes > 32 * 1024 * 1024 } |
| 251 | if tooLarge, localFailure == nil || localFailure == .tooManyUnsent { |
| 252 | localFailure = .tooManyUnsent; inputPaused = true |
| 253 | } else if !tooLarge, localFailure == .tooManyUnsent { |
| 254 | localFailure = nil; inputPaused = detail?.can_write != true || summary.held > 0 |
| 255 | } |
| 256 | } |
| 257 | /// Every outbox change calls this (several per keystroke), so it reads |
| 258 | /// and decrypts the file only when this account has written it since, |
| 259 | /// and assigns observed state only when it differs. |
| 260 | private func reloadMetadata() { |
| 261 | guard !metadataDirty, let key = documentKey else { return } |
| 262 | let revision = offlineAccount.metadataRevisions[key, default: 0] |
| 263 | guard revision != loadedMetadataRevision, let stored = try? offlineAccount.metadata(key) else { return } |
| 264 | loadedMetadataRevision = revision |
| 265 | let attached = draftToken != nil && stored.draftToken == nil |
| 266 | if detail != stored.detail { detail = stored.detail } |
| 267 | if pendingTitle != stored.pendingTitle { pendingTitle = stored.pendingTitle } |
| 268 | if draftToken != stored.draftToken { draftToken = stored.draftToken } |
| 269 | if attached, streamTask == nil, !liveUpdatesSuspended { |
| 270 | streamTask = Task { [weak self] in await self?.listen(stored.detail.sqid) } |
| 271 | } |
| 272 | } |
| 273 | private func saveMetadata() throws { |
| 274 | guard let documentKey, let detail else { return } |
| 275 | metadataDirty = true |
| 276 | try offlineAccount.saveMetadata(DocsOfflineMetadata(detail: detail, pendingTitle: pendingTitle, draftToken: draftToken), key: documentKey) |
| 277 | metadataDirty = false |
| 278 | } |
| 279 | private func schedulePersistence() { |
| 280 | writerTask?.cancel() |
| 281 | writerTask = Task { [weak self] in |
| 282 | do { try await Task.sleep(for: .seconds(2)) } catch { return } |
| 283 | await self?.persistReplica() |
| 284 | } |
| 285 | } |
| 286 | func persistReplica() async { |
| 287 | await writer.run { [weak self] in |
| 288 | guard let self, let persistence = self.persistence else { return } |
| 289 | do { |
| 290 | if try await !persistence.persist() { self.schedulePersistence() } |
| 291 | else if self.localFailure == .cannotSaveOnDevice, self.failedUpdate == nil, !self.metadataDirty { |
| 292 | self.localFailure = nil |
| 293 | if self.detail?.can_write == true { self.inputPaused = false } |
| 294 | } |
| 295 | } catch { self.localFailure = .cannotSaveOnDevice; self.inputPaused = true } |
| 296 | } |
| 297 | } |
| 298 | private func durable(_ update: Data) async throws { |
| 299 | guard let persistence else { throw BlobStoreError.unavailable } |
| 300 | failedUpdate = update |
| 301 | try await persistence.enqueue(update) |
| 302 | failedUpdate = nil |
| 303 | updateLaneSummary(await offlineAccount.outbox.summary.only(persistence.lane)) |
| 304 | try await persistence.compact() |
| 305 | } |
| 306 | func load(query: String = "") async { |
| 307 | do { try await offlineAccount.activate() } catch { localFailure = .cannotSaveOnDevice } |
| 308 | let request = UUID(); listRequest = request |
| 309 | listState = .loading |
| 310 | do { |
| 311 | var components = URLComponents(); components.queryItems = [URLQueryItem(name: "q", value: query)] |
| 312 | let q = (components.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B") |
| 313 | let response: DocumentList = try await client().request("/?\(q)") |
| 314 | guard listRequest == request, !Task.isCancelled else { return } |
| 315 | documents = response.documents; canCreate = response.can_create |
| 316 | listState = .loaded; errorKey = nil |
| 317 | } catch { |
| 318 | guard listRequest == request else { return } |
| 319 | listState = .failed; errorKey = "docs.error.generic" |
| 320 | } |
| 321 | } |
| 322 | /// The editor and its initial paragraph are local. Server acknowledgement |
| 323 | /// only attaches an identity; it never reconstructs the editor or selection. |
| 324 | func newDraft() async { |
| 325 | guard detail == nil, replica == nil else { return } |
| 326 | if draftToken == nil { draftToken = UUID().uuidString } |
| 327 | let epoch = documentEpoch |
| 328 | let guid = UUID().uuidString |
| 329 | let local = CRDTReplica(guid: guid) |
| 330 | loading = true |
| 331 | defer { if documentEpoch == epoch { loading = false } } |
| 332 | do { |
| 333 | try await offlineAccount.outbox.load() |
| 334 | _ = try await local.open(update: Data()) |
| 335 | let update = try await local.command(["op": .string("insert_element"), "at": .number(0), "type": .string("paragraph")]) |
| 336 | guard documentEpoch == epoch else { await local.close(); return } |
| 337 | // A model is reused across documents: never compare a draft's |
| 338 | // rows with the cursor of the document open before it, nor its |
| 339 | // presentations with that document's generations (after `stop` |
| 340 | // they would all be refused as older). |
| 341 | sequence = 0; resetRemoteState() |
| 342 | projectionGeneration = 0; renderedGeneration = 0; resetSurface() |
| 343 | replica = local |
| 344 | configurePersistence(key: "draft-" + draftToken!, replica: local) |
| 345 | detail = DocumentDetail(sqid: "draft-" + draftToken!, title: String(localized: "docs.document.untitled", bundle: DocsResources.bundle), guid: guid, can_write: true, can_share: false) |
| 346 | failedUpdate = update |
| 347 | try saveMetadata() |
| 348 | try await durable(update) |
| 349 | await publish() |
| 350 | guard documentEpoch == epoch else { return } |
| 351 | offlineAccount.drainer.start() |
| 352 | startCreation() |
| 353 | } catch { if documentEpoch == epoch { errorKey = "native.pending"; localFailure = .cannotSaveOnDevice; inputPaused = true } } |
| 354 | } |
| 355 | private func startCreation() { |
| 356 | guard creationTask == nil, draftToken != nil else { return } |
| 357 | creatingDocument = true |
| 358 | let epoch = documentEpoch |
| 359 | creationTask = Task { |
| 360 | await attachDraft(epoch: epoch) |
| 361 | if documentEpoch == epoch { creationTask = nil; creatingDocument = false } |
| 362 | } |
| 363 | } |
| 364 | private func attachDraft(epoch: UUID) async { |
| 365 | guard let key = documentKey else { return } |
| 366 | do { |
| 367 | try await offlineAccount.ensureMetadataEntry(key) |
| 368 | await offlineAccount.drainer.drain() |
| 369 | guard documentEpoch == epoch else { return } |
| 370 | reloadMetadata() |
| 371 | if isDraft { errorKey = "native.pending" } |
| 372 | else { await persistReplica(); await flush() } |
| 373 | } catch { if documentEpoch == epoch { errorKey = "native.pending" } } |
| 374 | } |
| 375 | @discardableResult func commitRename() -> Bool { |
| 376 | guard let value = renameInput else { return true } |
| 377 | guard rename(value) else { return false } |
| 378 | renameInput = nil |
| 379 | return true |
| 380 | } |
| 381 | @discardableResult func rename(_ value: String) -> Bool { |
| 382 | guard let detail, detail.can_write else { return false } |
| 383 | let trimmed = value.trimmingCharacters(in: .whitespacesAndNewlines) |
| 384 | let title = trimmed.isEmpty ? String(localized: "docs.document.untitled", bundle: DocsResources.bundle) : trimmed |
| 385 | guard title.utf8.count <= 1024 else { errorKey = "docs.error.generic"; return false } |
| 386 | if title == detail.title { |
| 387 | guard metadataDirty else { return true } |
| 388 | do { try saveMetadata() } catch { localFailure = .cannotSaveOnDevice; inputPaused = true; return false } |
| 389 | } |
| 390 | self.detail = DocumentDetail(sqid: detail.sqid, title: title, guid: detail.guid, can_write: detail.can_write, can_share: detail.can_share) |
| 391 | pendingTitle = title; titleRevision &+= 1 |
| 392 | do { try saveMetadata() } catch { localFailure = .cannotSaveOnDevice; inputPaused = true; return false } |
| 393 | Task { |
| 394 | do { if let documentKey { try await offlineAccount.ensureMetadataEntry(documentKey) } } |
| 395 | catch { localFailure = .cannotSaveOnDevice; inputPaused = true } |
| 396 | await flush() |
| 397 | } |
| 398 | return true |
| 399 | } |
| 400 | func open(_ sqid: String) async { |
| 401 | guard !hasUnsavedChanges else { errorKey = "native.pending"; return } |
| 402 | let epoch = UUID(); documentEpoch = epoch; editorIdentity = UUID() |
| 403 | streamTask?.cancel(); streamTask = nil |
| 404 | let previous = replica; replica = nil; detail = nil; projection = nil |
| 405 | if unavailable { unavailable = false } |
| 406 | if sessionPaused { sessionPaused = false } |
| 407 | loading = true; errorKey = nil |
| 408 | if let previous { await previous.close() } |
| 409 | guard documentEpoch == epoch else { return } |
| 410 | defer { if documentEpoch == epoch { loading = false } } |
| 411 | do { |
| 412 | try await offlineAccount.outbox.load() |
| 413 | let key = try offlineAccount.key(for: sqid) |
| 414 | let cached = try offlineAccount.metadata(key) |
| 415 | pendingTitle = cached?.pendingTitle; draftToken = cached?.draftToken |
| 416 | let detail: DocumentDetail |
| 417 | let initial: Data |
| 418 | let seq: Int64 |
| 419 | if let cached, try offlineAccount.replicaCache.hasBase(key) { |
| 420 | detail = cached.detail; pendingTitle = cached.pendingTitle; initial = Data(); seq = 0 |
| 421 | } else { |
| 422 | let remote: DocumentDetail = try await client().request("/d/\(sqid)") |
| 423 | detail = DocumentDetail(sqid: remote.sqid, title: cached?.pendingTitle ?? remote.title, guid: remote.guid, can_write: remote.can_write, can_share: remote.can_share) |
| 424 | let reply = try await client().responseDetails("/d/\(sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| 425 | try reply.requireSuccess() |
| 426 | guard let cursor = Int64(reply.header("Docs-Seq") ?? "") else { throw CRDTReplica.Failure.rejected } |
| 427 | initial = reply.data; seq = cursor |
| 428 | } |
| 429 | guard documentEpoch == epoch else { return } |
| 430 | let replica = CRDTReplica(guid: detail.guid) |
| 431 | configurePersistence(key: key, replica: replica) |
| 432 | try await persistence!.reopen(fallback: initial, sequence: seq) |
| 433 | let projection = try await replica.projection() |
| 434 | let persisted = await replica.currentSequence() |
| 435 | guard documentEpoch == epoch else { await replica.close(); return } |
| 436 | // The cursor is this document's before the replica is published: |
| 437 | // a POST answer (`sent`) is compared with it as soon as it is. |
| 438 | sequence = persisted; resetRemoteState() |
| 439 | self.replica = replica; self.detail = detail |
| 440 | reloadMetadata() |
| 441 | laneSummary = await offlineAccount.outbox.summary.only("doc:" + key) |
| 442 | if cached == nil { try saveMetadata() } |
| 443 | try await offlineAccount.ensureMetadataEntry(key) |
| 444 | projectionGeneration = 0; renderedGeneration = 0; resetSurface() |
| 445 | selection = NSRange(location: 0, length: 0); typingMarks = nil |
| 446 | composing = false; inputPaused = false; pausedAsReader = false |
| 447 | updateLaneSummary(laneSummary) |
| 448 | await publish() |
| 449 | guard documentEpoch == epoch else { return } |
| 450 | unsettledParking = persistence?.unsettled == true |
| 451 | // Not while unsettled: such a replica may show nothing of a |
| 452 | // document that has content. |
| 453 | if projection.children.isEmpty && detail.can_write && !unsettledParking { |
| 454 | enqueue(["op":.string("insert_element"), "at":.number(0), "type":.string("paragraph")]) |
| 455 | } |
| 456 | await persistReplica() |
| 457 | offlineAccount.drainer.start() |
| 458 | if !liveUpdatesSuspended { streamTask = Task { [weak self] in await self?.listen(sqid) } } |
| 459 | } catch { if documentEpoch == epoch { errorKey = "docs.error.generic"; detail = nil; projection = nil } } |
| 460 | } |
| 461 | @discardableResult func enqueue(_ command: [String: JSONValue]) -> Bool { |
| 462 | #if DOCS_PROBES |
| 463 | let probeStart = DocsProbes.now() |
| 464 | defer { DocsProbes.commands += 1; DocsProbes.commandMs += DocsProbes.ms(since: probeStart) } |
| 465 | #endif |
| 466 | guard !inputBlocked, detail?.can_write == true else { return false } |
| 467 | let buffered = editing.reduce(0) { $0 + ((try? JSONEncoder().encode($1).count) ?? 0) } |
| 468 | guard let incoming = try? JSONEncoder().encode(command).count, incoming <= 2 * 1024 * 1024 - buffered else { errorKey = "native.pending"; return false } |
| 469 | var command = command |
| 470 | if case .number(let generation) = command["generation"], let value = UInt64(exactly: generation) { didRender(value) } |
| 471 | if command["generation"] == nil, renderedGeneration != 0 { command["generation"] = .number(Double(renderedGeneration)) } |
| 472 | if [JSONValue.string("replace_text"), .string("display_edit")].contains(command["op"] ?? .null), let typingMarks { command["marks"] = .object(typingMarks) } |
| 473 | if ![JSONValue.string("display_edit"), .string("display_autoformat"), .string("display_revert_rule"), .string("display_exit_list"), .string("insert_element")].contains(command["op"] ?? .null) { |
| 474 | explicitCommandRevision &+= 1; surface.explicitCommand() |
| 475 | } |
| 476 | editing.append(command) |
| 477 | if editingTask == nil { editingTask = Task { await drainEdits() } } |
| 478 | if !composing { holdCommands() } |
| 479 | return true |
| 480 | } |
| 481 | private func drainEdits() async { |
| 482 | let epoch = documentEpoch |
| 483 | defer { |
| 484 | if documentEpoch == epoch { |
| 485 | editingTask = nil |
| 486 | // Trigger (b): the queue drained. |
| 487 | surface.flushIfDeferred() |
| 488 | refreshToolbarSelection() |
| 489 | } |
| 490 | } |
| 491 | while documentEpoch == epoch, !editing.isEmpty, let replica { |
| 492 | let command = editing.removeFirst() |
| 493 | do { |
| 494 | let update = try await replica.command(command) |
| 495 | guard documentEpoch == epoch else { return } |
| 496 | do { try await durable(update) } |
| 497 | catch { localFailure = .cannotSaveOnDevice; inputPaused = true; break } |
| 498 | if editing.isEmpty { await publish() } |
| 499 | } catch { |
| 500 | guard documentEpoch == epoch else { return } |
| 501 | errorKey = "native.recovered"; editing.insert(command, at: 0); inputPaused = true; break |
| 502 | } |
| 503 | } |
| 504 | Task { await flush() } |
| 505 | } |
| 506 | func compositionChanged(_ active: Bool) { |
| 507 | composing = active |
| 508 | if !active { |
| 509 | // Trigger (c): composition ended. |
| 510 | surface.flushIfDeferred() |
| 511 | refreshToolbarSelection() |
| 512 | // Still held after the commit (its input pending): from now the |
| 513 | // usual hold, which may grey out. |
| 514 | if !DocumentCommands(model: self, content: surface.content).isEnabled { holdCommands() } |
| 515 | if editingTask == nil { Task { await publish() } } |
| 516 | } |
| 517 | } |
| 518 | func canRender(_ generation: UInt64) -> Bool { !hasPendingInput && !composing && generation == projectionGeneration } |
| 519 | func currentSelection() -> NSRange { selection } |
| 520 | func selectionMovedExplicitly() { |
| 521 | typingMarks = nil |
| 522 | // A queued command applies only to the selection it was chosen with. |
| 523 | readyQueue = [] |
| 524 | } |
| 525 | func didRender(_ generation: UInt64) { |
| 526 | // Every draw, also of a generation already rendered (plain typing |
| 527 | // reuses its source): the toolbar may show the selection now. |
| 528 | defer { refreshToolbarSelection() } |
| 529 | // A delayed acknowledgement cannot retire the currently displayed source. |
| 530 | guard generation > renderedGeneration else { return } |
| 531 | renderedGeneration = generation |
| 532 | // Not a flush trigger (spec §7 Design 6): canRender reads |
| 533 | // projectionGeneration, not renderedGeneration, so trigger (d) is |
| 534 | // projectionGeneration's didSet. The call costs nothing. |
| 535 | surface.flushIfDeferred() |
| 536 | } |
| 537 | private func publish() async { await publications.run { await self.publishCurrent() } } |
| 538 | private func publishCurrent() async { |
| 539 | let epoch = documentEpoch |
| 540 | guard !composing, editing.isEmpty, let replica else { return } |
| 541 | await replica.retainGenerations(Set([renderedGeneration, projectionGeneration])) |
| 542 | guard documentEpoch == epoch, editing.isEmpty else { return } |
| 543 | do { |
| 544 | let source = renderedGeneration; let selected = selection |
| 545 | // What the text view has drawn: the replica answers with what |
| 546 | // changed since then, in the same call (spec §7 Design 2). |
| 547 | let since = surface.appliedRevision |
| 548 | if let presented = try await replica.presentation(source: source, selection: selected, allowReuse: source == projectionGeneration, since: since), editing.isEmpty, source == renderedGeneration, selected == selection, !composing, documentEpoch == epoch, presented.generation >= projectionGeneration { |
| 549 | selection = presented.selection; projectionGeneration = presented.generation; projection = presented.projection |
| 550 | // Trigger (a), and (d): the generation caught up. |
| 551 | surface.apply(DocumentSurface.Publication(generation: presented.generation, projection: presented.projection, |
| 552 | revision: presented.revision, dirty: presented.dirty)) |
| 553 | refreshToolbarSelection() |
| 554 | schedulePersistence() |
| 555 | } |
| 556 | } catch { if documentEpoch == epoch { errorKey = "native.recovered" } } |
| 557 | } |
| 558 | func retry() async { |
| 559 | let epoch = documentEpoch |
| 560 | if localFailure == .cannotSaveOnDevice || failedUpdate != nil { |
| 561 | do { |
| 562 | try await offlineAccount.outbox.load() |
| 563 | if metadataDirty { try saveMetadata() } |
| 564 | if let failedUpdate { try await durable(failedUpdate) } |
| 565 | guard documentEpoch == epoch else { return } |
| 566 | localFailure = nil; inputPaused = false |
| 567 | await persistReplica() |
| 568 | guard localFailure == nil else { return } |
| 569 | await publish() |
| 570 | } catch { return } |
| 571 | } |
| 572 | if let persistence { updateLaneSummary(await offlineAccount.outbox.summary.only(persistence.lane)) } |
| 573 | if localFailure == .tooManyUnsent { return } |
| 574 | offlineAccount.drainer.start() |
| 575 | if editingTask == nil, !editing.isEmpty, !inputPaused { |
| 576 | editingTask = Task { await drainEdits() } |
| 577 | } |
| 578 | if isDraft { |
| 579 | if replica == nil { await newDraft() } else { startCreation() } |
| 580 | await creationTask?.value |
| 581 | return |
| 582 | } |
| 583 | if transport() != nil { offlineAccount.drainer.sessionRestored() } |
| 584 | offlineAccount.drainer.retryNow() |
| 585 | if inputPaused || sessionPaused { |
| 586 | if let detail { await refreshAccess(detail.sqid, epoch: epoch) } |
| 587 | // Not while the document is gone (§6 row 1) or the session is |
| 588 | // being re-minted after a 401: its 200 resumes input itself. |
| 589 | guard documentEpoch == epoch, detail?.can_write == true, !unavailable, !sessionPaused else { return } |
| 590 | inputPaused = false; errorKey = nil |
| 591 | if editingTask == nil { editingTask = Task { await drainEdits() } } |
| 592 | } else { await flush() } |
| 593 | } |
| 594 | func stop() async { |
| 595 | lifetime = UUID() |
| 596 | offlineAccount.sendNow() |
| 597 | await persistReplica() |
| 598 | guard !hasUnsavedChanges else { return } |
| 599 | documentEpoch = UUID(); streamTask?.cancel(); streamTask = nil |
| 600 | writerTask?.cancel(); summaryTask?.cancel(); stopObservingSends() |
| 601 | let previous = replica; replica = nil; detail = nil; projection = nil |
| 602 | if let previous { await previous.close() } |
| 603 | } |
| 604 | /// Discard only unsent local draft state. An already acknowledged network |
| 605 | /// update remains part of the shared document, as in the web editor. |
| 606 | func discardAll() async { |
| 607 | documentEpoch = UUID() |
| 608 | writerTask?.cancel(); editingTask?.cancel(); streamTask?.cancel() |
| 609 | do { |
| 610 | try await persistence?.discard() |
| 611 | if let documentKey { try offlineAccount.removeMetadata(documentKey) } |
| 612 | } catch { localFailure = .cannotSaveOnDevice; return } |
| 613 | writerTask?.cancel(); summaryTask?.cancel(); stopObservingSends(); persistence = nil; documentKey = nil |
| 614 | laneSummary = OutboxSummary(); failedUpdate = nil; localFailure = nil |
| 615 | documentEpoch = UUID() |
| 616 | creationTask?.cancel(); creationTask = nil; creatingDocument = false |
| 617 | draftToken = nil; pendingTitle = nil; metadataDirty = false; renameInput = nil |
| 618 | streamTask?.cancel(); streamTask = nil |
| 619 | editingTask?.cancel(); editingTask = nil |
| 620 | editing.removeAll(); saving = false |
| 621 | composing = false; inputPaused = false; pausedAsReader = false; typingMarks = nil |
| 622 | selection = NSRange(location: 0, length: 0) |
| 623 | let previous = replica; replica = nil; detail = nil; projection = nil |
| 624 | sequence = 0; resetRemoteState() |
| 625 | projectionGeneration = 0; renderedGeneration = 0; resetSurface(); errorKey = nil |
| 626 | if let previous { await previous.close() } |
| 627 | } |
| 628 | func saveAll() async -> Bool { |
| 629 | guard commitRename() else { return false } |
| 630 | if isDraft { startCreation(); await creationTask?.value } |
| 631 | if let editingTask { await editingTask.value } |
| 632 | offlineAccount.sendNow() |
| 633 | while saving { try? await Task.sleep(for: .milliseconds(20)) } |
| 634 | await flush() |
| 635 | await persistReplica() |
| 636 | return !hasUnsavedChanges |
| 637 | } |
| 638 | func flush() async { |
| 639 | guard !saving, detail != nil, let persistence else { return }; saving = true |
| 640 | let epoch = documentEpoch |
| 641 | defer { if documentEpoch == epoch { saving = false } } |
| 642 | do { try await offlineAccount.ensureMetadataEntry(persistence.key) } |
| 643 | catch { localFailure = .cannotSaveOnDevice; inputPaused = true; return } |
| 644 | await offlineAccount.drainer.drain() |
| 645 | guard documentEpoch == epoch else { return } |
| 646 | laneSummary = await offlineAccount.outbox.summary.only(persistence.lane) |
| 647 | reloadMetadata() |
| 648 | // SyncStatus presents a durable pending lane; it does not require |
| 649 | // keeping this document open. Preserve unrelated actionable errors. |
| 650 | if errorKey == "native.pending" || errorKey == "docs.editor.status.retrying" { errorKey = nil } |
| 651 | } |
| 652 | private func listen(_ sqid: String) async { |
| 653 | let epoch = documentEpoch |
| 654 | // Paces reconnects: a server's Retry-After is a deadline no wake |
| 655 | // crosses; otherwise back off, cut short by a connectivity change, |
| 656 | // with no timer while the path is down. The backoff resets only after |
| 657 | // a stream that stayed open for 5 s, timed from onOpen. |
| 658 | let reconnect = NativeReconnect(connectivity: connectivity, now: reconnectClock) |
| 659 | while !Task.isCancelled, documentEpoch == epoch, detail?.sqid == sqid { |
| 660 | await flush() |
| 661 | do { |
| 662 | try await client().stream("/d/\(sqid)/stream", onOpen: { [weak self] in |
| 663 | await reconnect.opened() |
| 664 | // A stream opening again after a 401 is the re-minted session. |
| 665 | await self?.sessionReopened(sqid, epoch: epoch) |
| 666 | }) { [weak self] line in |
| 667 | if line.hasPrefix("data:"), let seq = Int64(line.dropFirst(5).trimmingCharacters(in: .whitespaces)) { |
| 668 | await self?.refresh(sqid, remoteSequence: seq) |
| 669 | } |
| 670 | } |
| 671 | } catch { |
| 672 | reconnect.failed(error) |
| 673 | if !Task.isCancelled, documentEpoch == epoch { |
| 674 | errorKey = "docs.editor.status.retrying" |
| 675 | await refreshAccess(sqid, epoch: epoch) |
| 676 | } |
| 677 | } |
| 678 | await reconnect.pause() |
| 679 | } |
| 680 | } |
| 681 | /// `holding` false: fetch even while this document's POST is on the |
| 682 | /// wire (the hold's own timeout). |
| 683 | private func refresh(_ sqid: String, remoteSequence: Int64, holding: Bool = true) async { |
| 684 | let epoch = documentEpoch |
| 685 | guard detail?.sqid == sqid else { return } |
| 686 | latestAnnounced = max(latestAnnounced, remoteSequence) |
| 687 | guard remoteSequence > sequence || unsettledParking, let replica else { return } |
| 688 | // Unsettled with nothing newer to fetch: only a catch-up from the |
| 689 | // start can supply what the replica's parked structs wait for. |
| 690 | if unsettledParking && remoteSequence <= sequence { sequence = 0 } |
| 691 | // Rows that would not apply are fetched again only after a backoff, |
| 692 | // and the editor keeps saying it is retrying meanwhile. |
| 693 | if let refused = refusedRemote, refused.since == sequence, refused.notBefore > .now { |
| 694 | errorKey = "docs.editor.status.retrying" |
| 695 | scheduleRefusedRetry(sqid, at: refused.notBefore) |
| 696 | return |
| 697 | } |
| 698 | // The server announces a POST before answering it, so the next row |
| 699 | // may be this client's own update, already in the replica. Hold the |
| 700 | // event until that POST's answer says (`sent`); a POST that does not |
| 701 | // answer within a second no longer holds it. |
| 702 | if holding, remoteSequence == sequence + 1, let documentKey, offlineAccount.postingUpdates.contains(documentKey) { |
| 703 | heldRemoteSequence = max(heldRemoteSequence ?? 0, remoteSequence) |
| 704 | if heldRemoteTask == nil { |
| 705 | heldRemoteTask = Task { [weak self] in |
| 706 | try? await Task.sleep(for: .seconds(1)) |
| 707 | guard let self, !Task.isCancelled else { return } |
| 708 | self.heldRemoteTask = nil |
| 709 | await self.releaseHeldRemote(sqid, holding: false) |
| 710 | } |
| 711 | } |
| 712 | return |
| 713 | } |
| 714 | do { |
| 715 | // The cursor this request fetches from, read before it suspends: |
| 716 | // settleParking takes 0 to mean the reply is the whole state. |
| 717 | let since = sequence |
| 718 | let reply: NativeResponse, seq: Int64 |
| 719 | do { |
| 720 | reply = try await client().responseDetails("/d/\(sqid)/updates?since=\(since)", maxBytes: 8 * 1024 * 1024) |
| 721 | guard reply.status == 200, let cursor = Int64(reply.header("Docs-Seq") ?? "") else { throw CRDTReplica.Failure.rejected } |
| 722 | seq = cursor |
| 723 | } catch { |
| 724 | // A catch-up from the start is a whole download: a failed one |
| 725 | // waits out the same backoff as rows that would not apply. |
| 726 | if since == 0, unsettledParking, self.detail?.sqid == sqid, self.replica === replica { backOff(sqid, since: since) } |
| 727 | throw error |
| 728 | } |
| 729 | guard self.detail?.sqid == sqid, self.replica === replica else { return } |
| 730 | do { try await replica.apply(reply.data) } |
| 731 | catch { |
| 732 | guard self.detail?.sqid == sqid, self.replica === replica else { return } |
| 733 | backOff(sqid, since: since) |
| 734 | throw error |
| 735 | } |
| 736 | guard self.detail?.sqid == sqid, self.replica === replica else { return } |
| 737 | if refusedRemote != nil { |
| 738 | refusedRemote = nil; refusedRetryTask?.cancel(); refusedRetryTask = nil |
| 739 | if errorKey == "docs.editor.status.retrying" { errorKey = nil } |
| 740 | } |
| 741 | sequence = max(sequence, seq) |
| 742 | await replica.setSequence(sequence) |
| 743 | try await settleParking(sqid, caughtUpFrom: since) |
| 744 | // Show the change first: storing it is not what makes it durable |
| 745 | // (the server has it, and `sequence` is stored with the state). |
| 746 | if editing.isEmpty && editingTask == nil { await publish() } |
| 747 | await persistReplica() |
| 748 | await flush() |
| 749 | } catch { if documentEpoch == epoch, !Task.isCancelled { errorKey = "docs.editor.status.retrying" } } |
| 750 | } |
| 751 | /// Fetch from `since` again only after a backoff: 2 s, 4 s, 8 s … at |
| 752 | /// most a minute between attempts. |
| 753 | private func backOff(_ sqid: String, since: Int64) { |
| 754 | let attempts = (refusedRemote?.since == since ? refusedRemote!.attempts : 0) + 1 |
| 755 | let delay = Duration.seconds(min(60, 1 << min(attempts, 6))) |
| 756 | refusedRemote = (since, attempts, ContinuousClock.now.advanced(by: delay)) |
| 757 | scheduleRefusedRetry(sqid, at: refusedRemote!.notBefore) |
| 758 | } |
| 759 | /// After a catch-up: if the replica parks something it has not accepted, |
| 760 | /// a catch-up from `since` > 0 did not supply it, so catch up from the |
| 761 | /// start once. After a catch-up from the start the replica holds the |
| 762 | /// server's whole state: rebuilt from its own snapshot it drops a damaged |
| 763 | /// duplicate (#145), and what still parks is the server's own, accepted |
| 764 | /// and stored with it so no later open downloads it again (#147). |
| 765 | private func settleParking(_ sqid: String, caughtUpFrom since: Int64) async throws { |
| 766 | guard let replica else { return } |
| 767 | guard try await replica.hasUnacceptedParking() else { |
| 768 | // A catch-up healed it: the stored base still holds the damage, |
| 769 | // which segments cannot remove, so the next persist replaces it. |
| 770 | if unsettledParking { await replica.markSettled() } |
| 771 | unsettledParking = false; return |
| 772 | } |
| 773 | if since > 0 { |
| 774 | unsettledParking = true |
| 775 | Task { [weak self] in await self?.refresh(sqid, remoteSequence: self?.latestAnnounced ?? 0, holding: false) } |
| 776 | } else { |
| 777 | try await replica.settleAfterCatchingUpFromStart() |
| 778 | unsettledParking = false |
| 779 | } |
| 780 | } |
| 781 | /// An update POST came back. The web's rule (live-updates.mjs |
| 782 | /// `noteOwnSeq`): adopt the server's sequence for it only when it is |
| 783 | /// exactly the next row, so nothing anyone else wrote can be skipped, and |
| 784 | /// only when this replica holds every entry the POST carried (another |
| 785 | /// window of the document may have written some). Then the stream's |
| 786 | /// event for it is not fetched back and applied a second time. |
| 787 | private func sent(_ result: DocsSentUpdates) { |
| 788 | guard result.key == documentKey, let persistence, let replica, let sqid = detail?.sqid else { return } |
| 789 | if let assigned = result.sequence, assigned == sequence + 1, !result.entries.isEmpty, result.entries.isSubset(of: persistence.held) { |
| 790 | sequence = assigned |
| 791 | Task { await replica.setSequence(assigned) } |
| 792 | } |
| 793 | if result.sequence != nil { persistence.forget(result.entries) } |
| 794 | if heldRemoteSequence != nil { Task { await releaseHeldRemote(sqid) } } |
| 795 | } |
| 796 | private func releaseHeldRemote(_ sqid: String, holding: Bool = true) async { |
| 797 | guard let held = heldRemoteSequence else { return } |
| 798 | heldRemoteSequence = nil |
| 799 | heldRemoteTask?.cancel(); heldRemoteTask = nil |
| 800 | if held > sequence { await refresh(sqid, remoteSequence: held, holding: holding) } |
| 801 | } |
| 802 | private func scheduleRefusedRetry(_ sqid: String, at deadline: ContinuousClock.Instant) { |
| 803 | guard refusedRetryTask == nil else { return } |
| 804 | refusedRetryTask = Task { [weak self] in |
| 805 | try? await Task.sleep(until: deadline) |
| 806 | guard let self, !Task.isCancelled else { return } |
| 807 | self.refusedRetryTask = nil |
| 808 | await self.refresh(sqid, remoteSequence: self.latestAnnounced) |
| 809 | } |
| 810 | } |
| 811 | /// Per-document bookkeeping of the live channel, cleared with the cursor. |
| 812 | private func resetRemoteState() { |
| 813 | heldRemoteTask?.cancel(); heldRemoteTask = nil; heldRemoteSequence = nil |
| 814 | refusedRetryTask?.cancel(); refusedRetryTask = nil; refusedRemote = nil |
| 815 | latestAnnounced = 0 |
| 816 | unsettledParking = false |
| 817 | } |
| 818 | private func stopObservingSends() { |
| 819 | if let sendObserver { offlineAccount.stopObservingSends(sendObserver) } |
| 820 | sendObserver = nil |
| 821 | heldRemoteTask?.cancel(); heldRemoteTask = nil; heldRemoteSequence = nil |
| 822 | } |
| 823 | /// The iPhone app going to the background: close the live stream rather |
| 824 | /// than keep the radio up for its heartbeat, and send what is waiting. |
| 825 | /// A suspended app's connection would only come back as an error anyway. |
| 826 | func suspendLiveUpdates() { |
| 827 | liveUpdatesSuspended = true |
| 828 | offlineAccount.sendNow() |
| 829 | streamTask?.cancel(); streamTask = nil |
| 830 | } |
| 831 | /// Back in the foreground: reopen the stream. Its connect-time event |
| 832 | /// fetches whatever arrived meanwhile. |
| 833 | func resumeLiveUpdates() { |
| 834 | liveUpdatesSuspended = false |
| 835 | guard streamTask == nil, replica != nil, !isDraft, let sqid = detail?.sqid else { return } |
| 836 | streamTask = Task { [weak self] in await self?.listen(sqid) } |
| 837 | } |
| 838 | /// Asks for the document's access again now (the stream's reopening after |
| 839 | /// a 401 does; tests call it directly). |
| 840 | func revalidateAccess() async { |
| 841 | if let sqid = detail?.sqid { await refreshAccess(sqid, epoch: documentEpoch) } |
| 842 | } |
| 843 | private func sessionReopened(_ sqid: String, epoch: UUID) async { |
| 844 | if sessionPaused { await refreshAccess(sqid, epoch: epoch) } |
| 845 | } |
| 846 | |
| 847 | // MARK: - The editor's surface |
| 848 | |
| 849 | private func configureSurface() { |
| 850 | var hooks = DocumentSurface.Hooks() |
| 851 | hooks.edit = { [weak self] command in self?.enqueue(command) ?? false } |
| 852 | hooks.canRender = { [weak self] generation in self?.canRender(generation) ?? false } |
| 853 | hooks.currentSelection = { [weak self] in self?.selection ?? NSRange(location: 0, length: 0) } |
| 854 | // Each draw: the generation drawn, and the content revision (a live |
| 855 | // word count recomputes). The surface calls this after a flush, on |
| 856 | // the next turn when the flush ran inside SwiftUI's update. |
| 857 | hooks.didRender = { [weak self] generation in |
| 858 | self?.didRender(generation) |
| 859 | self?.contentRevision &+= 1 |
| 860 | } |
| 861 | hooks.compositionChanged = { [weak self] active in self?.compositionChanged(active) } |
| 862 | hooks.selectionChanged = { [weak self] range in self?.selectionChanged(range) } |
| 863 | hooks.selectionMoved = { [weak self] in self?.selectionMovedExplicitly() } |
| 864 | hooks.action = { [weak self] action in self?.perform(action) ?? false } |
| 865 | hooks.canAction = { [weak self] action in self?.canPerform(action) ?? false } |
| 866 | hooks.imageSourcesChanged = { [weak self] sources in |
| 867 | guard let self, self.imageSources != sources else { return } |
| 868 | self.imageSources = sources |
| 869 | } |
| 870 | surface.hooks = hooks |
| 871 | pushEditability() |
| 872 | } |
| 873 | private func resetSurface() { |
| 874 | surface.reset() |
| 875 | if toolbarSelection != DocumentToolbarSelection() { toolbarSelection = DocumentToolbarSelection() } |
| 876 | } |
| 877 | private func pushEditability() { surface.isEditable = detail?.can_write == true && !inputBlocked } |
| 878 | /// The text view's selection moved. |
| 879 | func selectionChanged(_ range: NSRange) { |
| 880 | selection = range |
| 881 | refreshToolbarSelection() |
| 882 | } |
| 883 | /// The toolbar's state, from the live text at the selection; kept while |
| 884 | /// input is pending, as before. Called wherever `DocumentCommands.isEnabled` |
| 885 | /// can turn true (the queue draining, a draw, composition ending, input |
| 886 | /// or the session unpaused, the access changing) and when the selection |
| 887 | /// moves, so the kept state never outlives the input that held it. |
| 888 | func refreshToolbarSelection() { |
| 889 | #if DOCS_PROBES |
| 890 | let probeStart = DocsProbes.now() |
| 891 | defer { DocsProbes.toolbarRefreshes += 1; DocsProbes.toolbarRefreshMs += DocsProbes.ms(since: probeStart) } |
| 892 | #endif |
| 893 | let commands = DocumentCommands(model: self, content: surface.content) |
| 894 | if commands.isEnabled || !commands.isAvailable { releaseCommands(run: commands.isEnabled) } |
| 895 | guard let value = DocumentToolbarSelection(commands: DocumentCommands(model: self, content: surface.content)), |
| 896 | value != toolbarSelection else { return } |
| 897 | toolbarSelection = value |
| 898 | } |
| 899 | /// A toolbar, inspector, menu or key command: now if commands can run, |
| 900 | /// else queued, in order, until they can: the input pending when it was |
| 901 | /// chosen has been drawn, or the composition committed. Dropped if the |
| 902 | /// selection then moves explicitly (it applies only to the selection it |
| 903 | /// was chosen with), if editing becomes unavailable, or if the hold |
| 904 | /// greys the controls out; and not queued while they are grey. |
| 905 | func whenCommandsReady(_ command: @escaping @MainActor (DocumentCommands) -> Void) { |
| 906 | let commands = DocumentCommands(model: self, content: surface.content) |
| 907 | if commands.isEnabled { command(commands); return } |
| 908 | guard commands.isAvailable, !commandsHeld else { return } |
| 909 | readyQueue.append(command) |
| 910 | if !composing { holdCommands() } |
| 911 | } |
| 912 | /// Commands are held from now: after `commandsHeldAfter`, if they still |
| 913 | /// are and no composition holds them, they show disabled and the queue |
| 914 | /// is dropped. |
| 915 | private func holdCommands() { |
| 916 | guard holdTask == nil, !commandsHeld else { return } |
| 917 | holdTask = Task { @MainActor [weak self] in |
| 918 | try? await Task.sleep(for: Self.commandsHeldAfter) |
| 919 | guard let self, !Task.isCancelled else { return } |
| 920 | self.holdTask = nil |
| 921 | let commands = DocumentCommands(model: self, content: self.surface.content) |
| 922 | guard !commands.isEnabled, commands.isAvailable, !self.composing else { return } |
| 923 | self.readyQueue = [] |
| 924 | self.commandsHeld = true |
| 925 | } |
| 926 | } |
| 927 | /// Commands can run (or never will, for now): stop holding, and run |
| 928 | /// what was queued meanwhile, in order, while they can (each may leave |
| 929 | /// input pending again, and the rest then waits for it). |
| 930 | private func releaseCommands(run: Bool) { |
| 931 | holdTask?.cancel(); holdTask = nil |
| 932 | commandsHeld = false |
| 933 | guard run else { readyQueue = []; return } |
| 934 | while !readyQueue.isEmpty { |
| 935 | let commands = DocumentCommands(model: self, content: surface.content) |
| 936 | guard commands.isEnabled else { if !composing { holdCommands() }; return } |
| 937 | readyQueue.removeFirst()(commands) |
| 938 | } |
| 939 | } |
| 940 | /// A command from the text view's keys. Formatting typed straight after |
| 941 | /// a letter (⌘B while the letter is pending) is queued like a click. |
| 942 | func perform(_ action: String) -> Bool { |
| 943 | if action == "jump" { jumpRequests &+= 1; return true } |
| 944 | let commands = DocumentCommands(model: self, content: surface.content) |
| 945 | guard ["bold", "italic", "code", "indent", "outdent", "clear-format"].contains(action), !commands.isEnabled else { |
| 946 | return commands.perform(action) |
| 947 | } |
| 948 | guard commands.isAvailable, !commandsHeld else { return false } |
| 949 | whenCommandsReady { $0.perform(action) } |
| 950 | return true |
| 951 | } |
| 952 | func canPerform(_ action: String) -> Bool { |
| 953 | detail?.can_write == true && !hasPendingInput && !composing && !inputBlocked |
| 954 | && (action == "undo" ? history.canUndo : history.canRedo) |
| 955 | } |
| 956 | |
| 957 | // MARK: - Delete… |
| 958 | |
| 959 | /// Why Delete… is not offered now, or nil when it is (spec §1, Delete…): |
| 960 | /// owners only (`can_share`), never a draft, not once the document is |
| 961 | /// gone; refused while changes are unsent, and while the origin is offline. |
| 962 | enum DeleteBlock: Equatable { case notOwner, unsent, offline } |
| 963 | func deleteBlock(offline: Bool) -> DeleteBlock? { |
| 964 | guard detail?.can_share == true, !isDraft, documentAccess != .unavailable else { return .notOwner } |
| 965 | if hasUnsavedChanges { return .unsent } |
| 966 | if offline { return .offline } |
| 967 | return nil |
| 968 | } |
| 969 | |
| 970 | /// What a Delete… came to, and whether the deleted document was still |
| 971 | /// the open one when the answer came (the window closes, or the iPhone |
| 972 | /// goes back to the library, only then). |
| 973 | struct DeleteResult: Equatable { |
| 974 | let outcome: DocsDeletion.Outcome |
| 975 | let wasOpen: Bool |
| 976 | } |
| 977 | |
| 978 | /// Deletes the open document (`DocsDeletion`'s rule). Sends what is |
| 979 | /// waiting first and refuses if anything is still unsent; only a |
| 980 | /// `.deleted` answer drops the document's outbox lane and replica. |
| 981 | /// |
| 982 | /// The document, its key and its persistence are taken before the |
| 983 | /// request: another document may be open by the time the answer comes |
| 984 | /// (back to the library, open B, on a slow link). Then only the deleted |
| 985 | /// document's lane, replica and metadata go, by its key, and the model |
| 986 | /// and the open document are left alone (Fable on #178, finding 1). |
| 987 | func deleteDocument() async -> DeleteResult? { |
| 988 | await flush() |
| 989 | guard deleteBlock(offline: false) == nil, let sqid = detail?.sqid, let client = transport(), |
| 990 | let key = documentKey, let deleted = persistence else { return nil } |
| 991 | let epoch = documentEpoch |
| 992 | deletingEpoch = epoch |
| 993 | let outcome = await DocsDeletion.run(sqid: sqid, transport: client) |
| 994 | if deletingEpoch == epoch { deletingEpoch = nil } |
| 995 | guard outcome == .deleted else { return DeleteResult(outcome: outcome, wasOpen: detail?.sqid == sqid) } |
| 996 | documents.removeAll { $0.sqid == sqid } |
| 997 | if detail?.sqid == sqid { |
| 998 | await discardAll() |
| 999 | return DeleteResult(outcome: outcome, wasOpen: true) |
| 1000 | } |
| 1001 | do { |
| 1002 | try await deleted.discard() |
| 1003 | try offlineAccount.removeMetadata(key) |
| 1004 | } catch { /* The document is gone on the server; what is left here is refused there and never shown. */ } |
| 1005 | return DeleteResult(outcome: outcome, wasOpen: false) |
| 1006 | } |
| 1007 | |
| 1008 | /// Another window deleted `sqid`: it leaves the list now, before the reload. |
| 1009 | func forgetListed(_ sqid: String) { documents.removeAll { $0.sqid == sqid } } |
| 1010 | |
| 1011 | /// Revalidate capability after stream/write rejection while retaining the draft. |
| 1012 | private func refreshAccess(_ sqid: String, epoch: UUID) async { |
| 1013 | let revision = titleRevision |
| 1014 | let hadPendingTitle = pendingTitle != nil |
| 1015 | do { |
| 1016 | let reply = try await client().responseDetails("/d/\(sqid)", maxBytes: 1024 * 1024) |
| 1017 | guard documentEpoch == epoch else { return } |
| 1018 | if reply.status == 200 { |
| 1019 | let current = try JSONDecoder().decode(DocumentDetail.self, from: reply.data) |
| 1020 | // The GET may have read its title before a rename acknowledged. |
| 1021 | // Clearing pendingTitle must not let that old reply win afterward. |
| 1022 | let title = pendingTitle ?? ((hadPendingTitle || titleRevision != revision) ? (detail?.title ?? current.title) : current.title) |
| 1023 | detail = DocumentDetail(sqid: current.sqid, title: title, guid: current.guid, can_write: current.can_write, can_share: current.can_share) |
| 1024 | if !current.can_write { inputPaused = true; pausedAsReader = true } |
| 1025 | else if pausedAsReader { |
| 1026 | // Given write access again: lift the pause the read-only |
| 1027 | // answer set, and only that one (a refused command, a |
| 1028 | // failed save or a full outbox keep theirs). |
| 1029 | pausedAsReader = false |
| 1030 | if localFailure == nil, failedUpdate == nil, editing.isEmpty, !unavailable { inputPaused = false } |
| 1031 | } |
| 1032 | // Spec §6: a 200 after row 1 (re-shared or restored) leaves it, |
| 1033 | // and releases the entries held meanwhile; after a 401, the |
| 1034 | // re-minted session's 200 resumes input with the access as is. |
| 1035 | if unavailable { |
| 1036 | unavailable = false |
| 1037 | if current.can_write { Task { [weak self] in await self?.retry() } } |
| 1038 | } |
| 1039 | // Only the 401's own reason: a pause something else set |
| 1040 | // (native.recovered, a full outbox, a held entry) stays. |
| 1041 | if sessionPaused { sessionPaused = false } |
| 1042 | } else if reply.status == 401 { |
| 1043 | // The session ended, not the access: pause input and leave |
| 1044 | // can_write and the chrome alone while the session is re-minted. |
| 1045 | if !sessionPaused { sessionPaused = true } |
| 1046 | } else if [403, 404].contains(reply.status) { |
| 1047 | // Deleted, or no longer shared: row 1, "No longer available". |
| 1048 | if !unavailable { unavailable = true } |
| 1049 | inputPaused = true |
| 1050 | if let current = detail, current.can_write || current.can_share { |
| 1051 | detail = DocumentDetail(sqid: current.sqid, title: current.title, guid: current.guid, can_write: false, can_share: false) |
| 1052 | } |
| 1053 | } |
| 1054 | } catch { /* A connection failure cannot establish a capability change. */ } |
| 1055 | } |
| 1056 | |
| 1057 | } |
| 1058 | |
| 1059 | /// What the undo/redo pill and the word-count command show (S2a), derived |
| 1060 | /// from each projection the model holds. |
| 1061 | struct DocumentHistoryState: Equatable, Sendable { |
| 1062 | var loaded = false |
| 1063 | var canUndo = false |
| 1064 | var canRedo = false |
| 1065 | init() {} |
| 1066 | init(_ projection: CRDTProjection?) { |
| 1067 | loaded = projection != nil |
| 1068 | canUndo = projection?.canUndo == true |
| 1069 | canRedo = projection?.canRedo == true |
| 1070 | } |
| 1071 | } |
| 1072 | |