Cotton code
335 lines · 13.8 KB · SwiftRaw
// The microphone in the input surface the shell owns — the same place in// every app: the trailing end of the bar that sits on the keyboard (Story's// element bar, the note editor's bar, the one-line input's capsule). Tap to// start, tap to stop; no hold.//// Three states: idle (the mic), listening (the mic filled, breathing with the// level), settling (the last words and second passes landing). The strip over// the bar shows the words as they stand, the tentative ones lighter, and any// model the plan wants that this phone lacks, offered with its size in the// core's own words. Every word here is the core's (`voice.plan`'s lines) or a// kit line.import CottonKitimport CottonPaperimport CottonVoiceimport osimport SwiftUI/// Makes the sessions of this process: the microphone, or in Cotton Dev a/// recording named by the walk (`VOICE_AUDIO` in the launch environment, or/// `-voice-audio <path>`), played as if spoken.@MainActorpublic enum VoiceSessions {    public static func make(core: any CottonCalling) -> VoiceSession {        let session = VoiceSession(core: core, store: .current, source: source)        #if COTTON_DEV            let languages = debugLanguages            let held = debugModels            if languages != nil || held != nil {                session.prelude = {                    // A walk's languages, set as the person would in Voice                    // settings, before the plan is asked for.                    if let languages {                        let set = ["set": ["languages": languages.map { ["code": $0] }]]                        if let data = try? JSONSerialization.data(withJSONObject: set) {                            _ = try? await core.callRaw(CottonMethod.voiceSettings, requestJSON: String(decoding: data, as: UTF8.self))                        }                    }                    if let held { adoptOnce(held) }                }            }        #endif        return session    }    public static var source: VoiceAudioSource {        #if COTTON_DEV            if let path = debugAudioPath { return .recording(URL(fileURLWithPath: path)) }        #endif        return .microphone    }    #if COTTON_DEV        /// Cotton Dev only: the recording the next session plays. A walk sets        /// it at launch; the debug URL `cottondev://voice-audio?path=` sets it        /// between sessions.        public static var debugAudioPath: String? = {            let environment = ProcessInfo.processInfo.environment            if let path = environment["VOICE_AUDIO"], !path.isEmpty { return path }            let arguments = ProcessInfo.processInfo.arguments            if let at = arguments.firstIndex(of: "-voice-audio"), at + 1 < arguments.count { return arguments[at + 1] }            return nil        }()        /// Cotton Dev only: `-voice-languages te,en` sets the person's        /// dictation languages before each session (the walks' Telugu and        /// Japanese).        /// Cotton Dev only: `-voice-models <folder>` names a folder of        /// models already on this machine, one folder each holding its files        /// and a `voice-model.json` (model, family, kind, role, languages,        /// `files: { part: name }`, options?): the simulator's proof models,        /// adopted as if downloaded. A model the catalogue names takes its        /// parts and options from the catalogue.        static let debugModels: URL? = {            let arguments = ProcessInfo.processInfo.arguments            guard let at = arguments.firstIndex(of: "-voice-models"), at + 1 < arguments.count else { return nil }            return URL(fileURLWithPath: arguments[at + 1], isDirectory: true)        }()        private static var adopted = false        @MainActor        static func adoptOnce(_ folder: URL) {            guard !adopted else { return }            adopted = true            struct Described: Decodable {                let model: String                let family: String                let kind: String                let role: String                let languages: [String]                let files: [String: String]?                let options: [String: String]?            }            let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []            for name in names {                let at = folder.appendingPathComponent(name, isDirectory: true)                guard let handle = try? FileHandle(forReadingFrom: at.appendingPathComponent("voice-model.json")),                      let data = try? handle.read(upToCount: 64 * 1024),                      let described = try? JSONDecoder().decode(Described.self, from: data) else { continue }                try? handle.close()                let parts = Dictionary((described.files ?? [:]).map { ($1, $0) }, uniquingKeysWith: { first, _ in first })                let files = ((try? FileManager.default.contentsOfDirectory(atPath: at.path)) ?? [])                    .filter { $0 != "voice-model.json" && !$0.hasPrefix(".") }                    .map { VoiceModelFile(name: $0, url: "", bytes: 0, sha256: "", part: parts[$0] ?? "") }                var entry = VoiceModelEntry(model: described.model, family: described.family, kind: described.kind, files: files,                                            options: described.options ?? [:])                entry.role = described.role                entry.languages = described.languages                VoiceModelStore.current.adopt(entry, from: at)            }            log.notice("voice-models adopted from \(folder.path, privacy: .public): \(names.joined(separator: ","), privacy: .public)")        }        static let debugLanguages: [String]? = {            let arguments = ProcessInfo.processInfo.arguments            guard let at = arguments.firstIndex(of: "-voice-languages"), at + 1 < arguments.count else { return nil }            return arguments[at + 1].split(separator: ",").map(String.init)        }()    #endif    static let log = Logger(subsystem: "com.cottondb.voice", category: "control")}/// The mic: one tap to start, one to stop.struct VoiceMicButton: View {    let session: VoiceSession    let identifier: String    let tap: () -> Void    @Environment(\.theme) private var theme    public init(session: VoiceSession, identifier: String, tap: @escaping () -> Void) {        self.session = session        self.identifier = identifier        self.tap = tap    }    public var body: some View {        Button(action: tap) {            ZStack {                Circle()                    .fill(listening ? theme.print(.red) : Color.clear)                    .scaleEffect(listening ? 1 + session.level * 0.25 : 1)                    .animation(.easeOut(duration: 0.12), value: session.level)                if session.phase == .settling || session.phase == .preparing {                    ProgressView().controlSize(.small)                } else {                    Image(systemName: failed ? "mic.slash" : (listening ? "mic.fill" : "mic"))                        .font(.system(size: 17, weight: .medium))                        .foregroundStyle(listening ? theme.sheet(.cream) : theme.print(.ink))                }            }            .frame(width: 36, height: 36)            .frame(width: 44, height: 44)            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityLabel(Text(verbatim: label))        .accessibilityIdentifier(identifier)        .accessibilityValue(Text(verbatim: stateWord))    }    private var listening: Bool { session.phase == .listening }    private var failed: Bool { if case .failed = session.phase { true } else { false } }    private var label: String {        listening ? session.line("listening") : session.line("idle")    }    /// The state as a walk reads it.    private var stateWord: String {        switch session.phase {        case .idle: "idle"        case .preparing: "preparing"        case .listening: "listening"        case .settling: "settling"        case .failed: "failed"        }    }}/// The words as they stand, the tentative ones lighter, over the bar; and/// the models the plan offers.public struct VoiceStrip: View {    let session: VoiceSession    /// Draw the words (a field that cannot draw lighter words inline).    let showsWords: Bool    @Environment(\.theme) private var theme    @State private var store = VoiceModelStore.current    public init(session: VoiceSession, showsWords: Bool) {        self.session = session        self.showsWords = showsWords    }    public var body: some View {        VStack(alignment: .leading, spacing: 6) {            if case .failed(let failure) = session.phase {                Text(verbatim: session.line(failure.lineKey))                    .font(CottonFonts.type(13))                    .foregroundStyle(theme.print(.ink))                    .accessibilityIdentifier("voice-failure")                    .onTapGesture { session.dismiss() }            }            if showsWords, session.isActive, !session.region.display.isEmpty {                words                    .font(CottonFonts.type(15))                    .lineLimit(3)                    .accessibilityIdentifier("voice-words")            } else if session.phase == .listening, session.region.display.isEmpty {                Text(verbatim: session.line("listening"))                    .font(CottonFonts.type(13))                    .foregroundStyle(CottonColors.inkTertiary)                    .accessibilityIdentifier("voice-listening")            }            ForEach(session.offers) { offer in                offerRow(offer)            }        }        .frame(maxWidth: .infinity, alignment: .leading)        .padding(.horizontal, 12)    }    private var words: Text {        let settled = Text(verbatim: session.region.settled).foregroundStyle(theme.print(.ink))        let tentative = Text(verbatim: session.region.tentative).foregroundStyle(CottonColors.inkTertiary)        return Text("\(settled)\(tentative)")    }    @ViewBuilder    private func offerRow(_ offer: VoiceDownload) -> some View {        let state = store.states[offer.model] ?? .absent        HStack(spacing: 8) {            Text(verbatim: offer.why)                .font(CottonFonts.type(13))                .foregroundStyle(theme.print(.ink))            Spacer(minLength: 4)            switch state {            case .downloading:                let done = Double(store.bytesDone[offer.model] ?? 0)                ProgressView(value: offer.bytes > 0 ? min(1, done / Double(offer.bytes)) : nil)                    .frame(width: 60)            case .ready:                Image(systemName: "checkmark")                    .foregroundStyle(theme.print(.ink))            case .absent, .failed:                Button {                    Task { await session.download(offer) }                } label: {                    Text(verbatim: session.line(state == .failed ? "failed" : "download"))                        .font(CottonFonts.type(13).bold())                        .foregroundStyle(theme.print(.red))                }                .buttonStyle(.plain)                .accessibilityIdentifier("voice-download-\(offer.model)")            }        }        .accessibilityElement(children: .combine)        .accessibilityIdentifier("voice-offer")    }}/// The bar's voice half for a field of plain text: the strip and the mic,/// the mic at the trailing end. The host keeps its text; this reads it at the/// tap and writes back what the session shows.public struct VoiceFieldBar: View {    let field: VoiceField    let identifier: String    let request: () -> VoicePlanRequest    let text: () -> String    let selection: () -> NSRange?    let write: (String) -> Void    /// The strip beside the mic; a host that draws the strip elsewhere says no.    var showsStrip = true    public init(        field: VoiceField, identifier: String, showsStrip: Bool = true, request: @escaping () -> VoicePlanRequest,        text: @escaping () -> String, selection: @escaping () -> NSRange?, write: @escaping (String) -> Void    ) {        self.showsStrip = showsStrip        self.field = field        self.identifier = identifier        self.request = request        self.text = text        self.selection = selection        self.write = write    }    public var body: some View {        HStack(alignment: .center, spacing: 4) {            if showsStrip { VoiceStrip(session: field.session, showsWords: !field.inlineTentative) }            VoiceMicButton(session: field.session, identifier: identifier) { tap() }        }        .onChange(of: field.text) { _, shown in            if let shown { field.didWrite(shown); write(shown) }        }    }    private func tap() {        let session = field.session        if session.phase == .listening || session.phase == .preparing {            Task {                let written = await field.stop()                write(written)            }        } else if session.phase == .idle || session.isFailed {            session.dismiss()            Task { await field.start(text: text(), selection: selection(), request: request()) }        }    }}extension VoiceSession {    var isFailed: Bool { if case .failed = phase { true } else { false } }}extension String {    /// A SwiftUI text selection as UTF-16 offsets in this text.    func utf16Range(_ selection: TextSelection?) -> NSRange? {        guard let selection else { return nil }        switch selection.indices {        case .selection(let range):            guard range.lowerBound <= endIndex, range.upperBound <= endIndex else { return nil }            return NSRange(range, in: self)        case .multiSelection(let set):            guard let first = set.ranges.first, first.upperBound <= endIndex else { return nil }            return NSRange(first, in: self)        @unknown default:            return nil        }    }}