// 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. import CottonKit import Foundation public struct VoiceRegion: Sendable, Equatable { /// The person's change of `from.. Touch? { let shown = display guard typed != shown else { return nil } let old = Array(shown.utf16) let new = Array(typed.utf16) var prefix = 0 while prefix < min(old.count, new.count), old[prefix] == new[prefix] { prefix += 1 } var suffix = 0 while 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. static func 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. static func apply(_ edits: [VoiceEdit], to text: String) throws -> String { var units = Array(text.utf16) var floor = Int.max for 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 { throw RegionError.badEdit } units.replaceSubrange(edit.from ..< edit.to, with: Array(edit.text.utf16)) floor = edit.from } return String(utf16CodeUnits: units, count: units.count) } static func 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 } enum RegionError: Error { case badEdit } /// The changed runs between two texts, as edits in `old`'s coordinates. static func difference(_ old: String, _ new: String) -> [VoiceEdit] { let a = Array(old.utf16) let b = Array(new.utf16) var removed = Set() 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 = 0 while i < a.count || j < b.count { let deleting = i < a.count && removed.contains(i) let adding = j < b.count && inserted[j] != nil if !deleting && !adding { i += 1; j += 1 continue } let from = i var 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) if let 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. static func carry(_ touch: Touch, through changes: [VoiceEdit]) -> Touch { var shift = 0 for 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) } return Touch(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). static func displayOffset(_ offset: Int, touches: [Touch]) -> Int { touches.reduce(offset) { mapped($0, through: $1) } } /// An offset in a text, in the text with `touch` applied. static func 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 } static func 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. static func past(_ changes: [VoiceEdit], touch: Touch) -> [VoiceEdit] { let delta = touch.text.utf16.count - (touch.to - touch.from) return changes.compactMap { change in let insertsAtReplacement = change.from == change.to && change.from == touch.from && touch.from != touch.to if change.to <= touch.from && !insertsAtReplacement { return change } if change.from >= touch.to { return VoiceEdit(from: change.from + delta, to: change.to + delta, text: change.text) } return nil } } /// How far the changes before `offset` (old coordinates) move it. static func 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) } } }