Cotton code
261 lines · 12.1 KB · SwiftRaw
// 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 CottonKitimport Foundationpublic struct VoiceRegion: Sendable, Equatable {    /// The person's change of `from..<to` in the session's text to `text`.    public struct Touch: Sendable, Equatable {        public var from: Int        public var to: Int        public var text: String        public init(from: Int, to: Int, text: String) {            self.from = from            self.to = to            self.text = text        }    }    /// The session's text as the core last answered it.    public private(set) var core = ""    /// How much of ``core`` is settled before the tentative words (UTF-16).    public private(set) var settledLength = 0    /// How long the tentative words are; after them is `later`, settled.    public private(set) var tentativeLength = 0    /// The person's changes the core has not yet answered.    public private(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.    public private(set) var corrected: [NSRange] = []    public init() {}    /// Everything the region shows: the core's text with the person's    /// pending changes.    public var display: String { Self.applyInOrder(pending, to: core) }    /// The tentative words, as the core said them.    public var tentative: String {        let units = Array(core.utf16)        let at = min(settledLength, units.count)        let end = min(at + tentativeLength, units.count)        return String(utf16CodeUnits: Array(units[at ..< end]), count: end - at)    }    /// Where the tentative words sit inside ``display``.    public var tentativeRange: NSRange {        let length = display.utf16.count        let 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.    public var settled: String {        let units = Array(display.utf16)        let range = tentativeRange        let kept = Array(units[..<range.location]) + Array(units[(range.location + range.length)...])        return String(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.    public mutating func take(settled: String, tentative: String, later: String = "", edits: [VoiceEdit]) {        let next = settled + tentative + later        let 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 = changes        var 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 in                let 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.    public mutating func 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.    @discardableResult    public mutating func typed(_ typed: String) -> 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<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 = 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) }    }}