Cotton code
156 lines · 8.1 KB · SwiftRaw
// What became of a dictation — and, for every ending that carries no words,// the sentence the user is owed.//// The rule predates dictation (hold-to-record era): endings were silently// swallowed down four separate null paths, and a capture app that can drop a// thought in silence is not a capture app. So every ending is NAMED and the app// always speaks. The dictation amendment retired hold-to-record voice notes// (the mic streams text live), and this grammar moved with it.//// TWO DELIBERATE DIFFERENCES FROM THE TYPESCRIPT:////   • The outcome is an `enum`, so the compiler — not a test — is what makes//     `dictationMessage` total. A new ending cannot be added without deciding//     what it says.//   • `CaseIterable`, so the test can assert the SET of endings that owe a//     sentence rather than a hand-typed list. The TypeScript test exercises//     four of the five sentences — a hand-typed list is exactly how an ending//     goes quiet. (`DictationOutcome` below names all seven, `dictationOnCall`//     included, and being an enum is what stops one going unnamed.)import Foundation/// The seven endings a dictation has.public enum DictationOutcome: String, Sendable, Equatable, CaseIterable {    /// Words were heard — the only outcome that carries text into the field.    case dictated    /// The user tapped ✕ — a deliberate discard, owed no sentence.    case dictationCancelled    /// The session finished with nothing heard.    case dictationEmpty    /// Mic or speech permission is denied.    case dictationDenied    /// No recognizer on this device/locale (or the OS refused the service).    case dictationUnavailable    /// The mic belongs to a live Cotton call — dictation never starts over one    /// (grabbing the input mid-call is the zero-audio-samples class of bug).    case dictationOnCall    /// The session died mid-thought (a call, Siri, an audio-route change) and    /// could not be resurrected; whatever was heard stays in the field.    case dictationInterrupted}public enum VoiceTake {    /// What to tell the user about an ending. `nil` for the two endings that    /// need no sentence: a dictation that landed its words (they speak for    /// themselves) and a deliberate cancel.    public static func dictationMessage(_ outcome: DictationOutcome) -> String? {        switch outcome {        case .dictated, .dictationCancelled: return nil        case .dictationEmpty: return ShellLines.line("capture", "voice.empty")        case .dictationDenied: return ShellLines.line("capture", "voice.denied")        case .dictationUnavailable: return ShellLines.line("capture", "voice.unavailable")        case .dictationOnCall: return ShellLines.line("capture", "voice.on_call")        case .dictationInterrupted: return ShellLines.line("capture", "voice.interrupted")        }    }    /// What JavaScript's `.trim()` strips and Swift's does not.    ///    /// `.whitespacesAndNewlines` misses `U+FEFF`, the byte-order mark, which    /// both `.trim()` and `/\s/` treat as space. Unreachable from a speech    /// transcript, but these two functions also fold text a person PASTED, and    /// two sides of one rule that disagree on a character is how a seam grows a    /// stray space nobody can see.    static let foldable = CharacterSet.whitespacesAndNewlines.union(        CharacterSet(charactersIn: "\u{FEFF}"))    /// The same set, one character at a time — the seam checks in    /// ``spliceDictation(before:_:after:)`` ask about a single `Character`.    static func isFoldable(_ character: Character?) -> Bool {        guard let character else { return false }        return character.isWhitespace || character == "\u{FEFF}"    }    /// Join a committed transcript and a live segment into one string. Pure —    /// the live stitcher and the composer's merge both lean on it, so spacing    /// has exactly one rule: single space at the seam, no leading/trailing    /// whitespace, empty parts vanish.    public static func foldDictationSegment(_ committed: String, _ segment: String) -> String {        let left = committed.trimmingCharacters(in: foldable)        let right = segment.trimmingCharacters(in: foldable)        if left.isEmpty { return right }        if right.isEmpty { return left }        return "\(left) \(right)"    }    /// Fold a SETTLED span onto the committed transcript — the one place that    /// answers "did the recogniser restate everything, or only the stretch    /// since the last boundary?".    ///    /// `SFSpeechRecognizer` cuts a long dictation into utterances at pauses    /// (`SystemSpeechRecogniser`), and a result describes "the current    /// utterance" — Apple's own words — so the span settled at a boundary    /// covers that stretch ALONE and must be appended. What the session's FINAL    /// carries once utterances have closed is documented nowhere: on the    /// on-device path it is observed to be the last stretch or nothing at all,    /// while a session that never segmented restates the whole thing. This    /// decides, so both land the same words and neither prints them twice:    ///    ///   • A span that repeats the committed text AND is long enough to cover    ///     the stretch still in progress as well is the session RESTATED, and    ///     replaces what is held.    ///   • Anything else is new, and is appended.    ///    /// **Both halves of that test are load-bearing.** The length is what keeps    /// a short honest utterance from reading as a restatement — "No." committed    /// and "No thanks." spoken next repeats the first word, and a bare prefix    /// test would drop the "No." — and the prefix is what keeps a genuine    /// restatement from being printed twice.    ///    /// The comparison is on letters and digits, lowercased, because    /// `addsPunctuation` re-punctuates and re-capitalises a restated span; a    /// literal test would call "One two, three" a stranger to "one two." and    /// say the opening words twice. It is not perfect and cannot be: a    /// restatement that also CORRECTS a word it already committed ("one too" →    /// "one two") is a stranger by any test, and is appended. That is the safe    /// side of the trade — a repeated phrase is visible and editable, a lost    /// paragraph is not.    ///    /// **The join edits nothing.** A new utterance opens with a capital letter    /// the recogniser chose, and it stays: what the recogniser said is what    /// lands (`Dictation.swift`'s header), so the seam gets a space and nothing    /// else.    public static func foldSettledSpan(committed: String, live: String, settled: String) -> String    {        let left = committed.trimmingCharacters(in: foldable)        let right = settled.trimmingCharacters(in: foldable)        if left.isEmpty { return right }        if right.isEmpty { return left }        let held = spokenKey(left)        let restated = spokenKey(right)        if restated.hasPrefix(held) && restated.count >= held.count + spokenKey(live).count {            return right        }        return foldDictationSegment(left, right)    }    /// A span reduced to the letters and digits it SAYS — the comparison key    /// above, and never shown to anybody.    static func spokenKey(_ text: String) -> String {        text.lowercased().filter { $0.isLetter || $0.isNumber }    }    /// Insert a dictated span between two halves of an existing text — the note    /// editor's cursor case. Unlike ``foldDictationSegment(_:_:)`` this NEVER    /// trims the surroundings (a paragraph break before the cursor is the    /// writer's, not ours); it only guarantees a single space at a seam where    /// words would otherwise collide.    public static func spliceDictation(before: String, _ span: String, after: String) -> String {        let middle = span.trimmingCharacters(in: foldable)        if middle.isEmpty { return before + after }        let leftSeam = before.isEmpty || isFoldable(before.last) ? "" : " "        let rightSeam = after.isEmpty || isFoldable(after.first) ? "" : " "        return "\(before)\(leftSeam)\(middle)\(rightSeam)\(after)"    }}