// The session's text inside a field, kept honest against two writers: the// core, which settles and corrects it, and the person, who may type into it// while the microphone is still open (the contract: `phone/voice.rs`).//// THE SESSION'S TEXT is everything this session has written — settled, then// tentative, then (rarely) settled text a second pass wrote ahead of the live// engine (`later`) — from offset 0 where the dictation began; every `from`/`to` on// the wire is a UTF-16 offset into it. The core's answers move it by `edits`// (offsets in the text before the answer, sorted last first, never// overlapping); this applies them, checked against the settled and tentative// text the same answer carries, and falls back to the difference of the two// texts if they ever disagree.//// THE PERSON'S TYPING is applied at once, in the field, and sent as// `voice.touched`; until the core's answer to it arrives the change is held// here as a pending touch, carried through any answer still in flight, so an// answer the core wrote before it knew never takes the person's words away.// Touches are kept IN THE ORDER THEY WERE SENT, each in the coordinates of the// text with the touches before it applied — the text the core holds when it// reads that touch, since the calls reach it in order. Nothing is merged: the// touched answers come back in the same order, and each lets go of the first.importCottonKitimportFoundationpublicstructVoiceRegion: Sendable, Equatable {/// The person's change of `from..<to` in the session's text to `text`.publicstructTouch: Sendable, Equatable {publicvar from: Intpublicvar to: Intpublicvar text: Stringpublicinit(from: Int, to: Int, text: String) {self.from = fromself.to = toself.text = text } }/// The session's text as the core last answered it.publicprivate(set) var core = ""/// How much of ``core`` is settled before the tentative words (UTF-16).publicprivate(set) var settledLength = 0/// How long the tentative words are; after them is `later`, settled.publicprivate(set) var tentativeLength = 0/// The person's changes the core has not yet answered.publicprivate(set) var pending: [Touch] = []/// The display ranges the last answer changed in text already settled —/// a second pass's correction — for the field to mark for a moment.publicprivate(set) var corrected: [NSRange] = []publicinit() {}/// Everything the region shows: the core's text with the person's/// pending changes.publicvar display: String { Self.applyInOrder(pending, to: core) }/// The tentative words, as the core said them.publicvar tentative: String {let units = Array(core.utf16)let at = min(settledLength, units.count)let end = min(at + tentativeLength, units.count)returnString(utf16CodeUnits: Array(units[at ..< end]), count: end - at) }/// Where the tentative words sit inside ``display``.publicvar tentativeRange: NSRange {let length = display.utf16.countlet at = min(Self.displayOffset(settledLength, touches: pending), length)let end = min(max(Self.displayOffset(settledLength + tentativeLength, touches: pending), at), length)return NSRange(location: at, length: end - at) }/// Everything settled as shown, the tentative words left out: what a/// field that cannot draw them lighter holds.publicvar settled: String {let units = Array(display.utf16)let range = tentativeRangelet kept = Array(units[..<range.location]) + Array(units[(range.location + range.length)...])returnString(utf16CodeUnits: kept, count: kept.count) }// MARK: The core's answer/// Take an answer: the session's text becomes `settled + tentative`, by/// the core's edits; pending touches are carried through them.publicmutatingfunc take(settled: String, tentative: String, later: String = "", edits: [VoiceEdit]) {let next = settled + tentative + laterlet changes = Self.changes(from: core, to: next, edits: edits)let wasSettled = settledLength// Each touch carried through the core's changes, then the changes// carried past it for the touch after (whose text has it applied).var through = changesvar carried: [Touch] = []for touch in pending {let moved = Self.carry(touch, through: through) through = Self.past(through, touch: touch) carried.append(moved) } pending = carried core = next settledLength = settled.utf16.count tentativeLength = tentative.utf16.count corrected = changes .filter { $0.from < wasSettled && !$0.text.isEmpty } .map { change inlet start = change.from + Self.shiftBefore(change.from, in: changes)return NSRange(location: Self.displayOffset(start, touches: pending), length: change.text.utf16.count) } }/// The core is answering the person's change: it is in the core's text/// now, and the answer's edits start from the text with it applied./// The answers come back in the order the touches went, so this is the/// first pending one, wherever answers in flight have since moved it.publicmutatingfunc acknowledge(_ sent: Touch) {guard !pending.isEmpty else { return }let touch = pending.removeFirst()let tentativeEnd = Self.mapped(settledLength + tentativeLength, through: touch) settledLength = Self.mapped(settledLength, through: touch) tentativeLength = max(0, tentativeEnd - settledLength) core = Self.apply([touch], to: core) }// MARK: The person's typing/// The region in the field now reads `typed`. Answers the person's/// change in the session's text, for `voice.touched`, or nil when nothing/// changed. @discardableResultpublicmutatingfunc typed(_ typed: String) -> Touch? {let shown = displayguard typed != shown else { returnnil }let old = Array(shown.utf16)let new = Array(typed.utf16)var prefix = 0while prefix < min(old.count, new.count), old[prefix] == new[prefix] { prefix += 1 }var suffix = 0while suffix < min(old.count, new.count) - prefix, old[old.count - 1 - suffix] == new[new.count - 1 - suffix] { suffix += 1 }let text = String(utf16CodeUnits: Array(new[prefix ..< (new.count - suffix)]), count: new.count - suffix - prefix)// In the coordinates of what is shown: the core's text with every// touch before this one applied, which is what it will hold.let touch = Touch(from: prefix, to: old.count - suffix, text: text) pending.append(touch)return touch }// MARK: Pure/// The edits that take `old` to `new`, in `old`'s coordinates, last first./// The core's own when applying them reproduces `new`, else the difference.staticfunc changes(from old: String, to new: String, edits: [VoiceEdit]) -> [VoiceEdit] {if old == new { return [] }if !edits.isEmpty, let applied = try? apply(edits, to: old), applied == new {return edits.sorted { $0.from > $1.from } }return difference(old, new).sorted { $0.from > $1.from } }/// Apply edits given in `text`'s coordinates, from the end, so none moves another.staticfunc apply(_ edits: [VoiceEdit], to text: String) throws -> String {var units = Array(text.utf16)var floor = Int.maxfor edit in edits.sorted(by: { $0.from > $1.from }) {guard edit.from >= 0, edit.from <= edit.to, edit.to <= units.count, edit.to <= floor else {throwRegionError.badEdit } units.replaceSubrange(edit.from ..< edit.to, with: Array(edit.text.utf16)) floor = edit.from }returnString(utf16CodeUnits: units, count: units.count) }staticfunc apply(_ touches: [Touch], to text: String) -> String {let edits = touches.map { VoiceEdit(from: $0.from, to: $0.to, text: $0.text) }return (try? apply(edits, to: text)) ?? text }enumRegionError: Error { case badEdit }/// The changed runs between two texts, as edits in `old`'s coordinates.staticfunc difference(_ old: String, _ new: String) -> [VoiceEdit] {let a = Array(old.utf16)let b = Array(new.utf16)var removed = Set<Int>()var inserted: [Int: UInt16] = [:]for change in b.difference(from: a) {switch change {case .remove(let offset, _, _): removed.insert(offset)case .insert(let offset, let element, _): inserted[offset] = element } }var edits: [VoiceEdit] = []var i = 0, j = 0while i < a.count || j < b.count {let deleting = i < a.count && removed.contains(i)let adding = j < b.count && inserted[j] != nilif !deleting && !adding { i += 1; j += 1continue }let from = ivar text: [UInt16] = []while i < a.count, removed.contains(i) { i += 1 }while j < b.count, let unit = inserted[j] { text.append(unit); j += 1 }let piece = String(utf16CodeUnits: text, count: text.count)iflet last = edits.last, last.to == from { edits[edits.count - 1] = VoiceEdit(from: last.from, to: i, text: last.text + piece) } else { edits.append(VoiceEdit(from: from, to: i, text: piece)) } }return edits }/// A pending touch carried through the core's changes. A change inside/// a touched range cannot happen by the core's promise; if one does, the/// person's words win and the touch keeps its place.staticfunc carry(_ touch: Touch, through changes: [VoiceEdit]) -> Touch {var shift = 0for change in changes where change.to <= touch.from && !(change.from == change.to && change.from == touch.from && touch.from != touch.to) { shift += change.text.utf16.count - (change.to - change.from) }returnTouch(from: touch.from + shift, to: touch.to + shift, text: touch.text) }/// A core offset as a display offset: through each pending touch in turn/// (an offset inside a touched range lands at the end of the person's text).staticfunc displayOffset(_ offset: Int, touches: [Touch]) -> Int { touches.reduce(offset) { mapped($0, through: $1) } }/// An offset in a text, in the text with `touch` applied.staticfunc mapped(_ offset: Int, through touch: Touch) -> Int {if offset >= touch.to { return offset + touch.text.utf16.count - (touch.to - touch.from) }if offset > touch.from { return touch.from + touch.text.utf16.count }return offset }staticfunc applyInOrder(_ touches: [Touch], to text: String) -> String { touches.reduce(text) { apply([$1], to: $0) } }/// The core's changes, in the text before `touch`, as changes in the/// text with it applied (both in the same old coordinates); a change over/// the person's range is theirs, and dropped.staticfunc past(_ changes: [VoiceEdit], touch: Touch) -> [VoiceEdit] {let delta = touch.text.utf16.count - (touch.to - touch.from)return changes.compactMap { change inlet insertsAtReplacement = change.from == change.to && change.from == touch.from && touch.from != touch.toif change.to <= touch.from && !insertsAtReplacement { return change }if change.from >= touch.to { returnVoiceEdit(from: change.from + delta, to: change.to + delta, text: change.text) }returnnil } }/// How far the changes before `offset` (old coordinates) move it.staticfunc shiftBefore(_ offset: Int, in changes: [VoiceEdit]) -> Int { changes.filter { $0.to <= offset && !($0.from == offset && $0.to == offset) } .reduce(0) { $0 + $1.text.utf16.count - ($1.to - $1.from) } }}