Cotton code
768 lines · 35.0 KB · SwiftRaw
// A voice message in Comms: its player in the bubble, drawn from// assets/design/chat/voice-player.html (the owner's feedback, Comms build 23,// item 2: voice notes played but the player looked unfinished). Play and// pause in Comms' own glyphs, the core's 36 bars filling from the player's// real position, the length counting down what is left, one speed for every// note (1×, 1.5×, 2×: `chat.settings` voiceSpeed, the person's, synced), a// note of theirs not played until it has played a second (`chat.act played`,// never told to the sender), loading with nothing blank, and the core's words// when the file can't be fetched (Try again) or has gone. One note plays at a// time; each keeps its place for the sitting when another starts.//// Under the player, the words its sender's phone heard in it, so nobody has to// listen. The words are heard on the sending phone only, after the message// has gone (`chat.act transcript`), by the same on-device engine dictation// uses (`DictationModel.live(audio: .file)`: Apple's DictationTranscriber,// iOS 26). A phone with no on-device model for the language hears nothing,// and the voice message goes without words; audio is never sent anywhere to// be heard.#if os(iOS)import AVFoundationimport CottonKitimport SwiftUI/// The words in a recorded voice message, heard on this phone and nowhere else.@MainActorenum ChatVoiceWords {    /// The words heard in `file`, or nil: none heard, or this phone has no    /// on-device model for the language. The recording plays into the engine    /// at the pace it was spoken.    static func heard(in file: URL) async -> String? {        #if COTTON_DEV        // Chat Dev's invented recording says known words; `-chat-warm-voice-hear YES` hears it with the real engine.        if ChatWarmSeed.asked, ChatWarmSeed.voice, !ChatWarmSeed.voiceHear { return ChatWarmSeed.voiceWords }        #endif        guard let audio = try? AVAudioFile(forReading: file) else { return nil }        let seconds = Double(audio.length) / audio.processingFormat.sampleRate        let dictation = DictationModel.live(audio: .file(file))        defer { dictation.release() }        if await dictation.start(prefix: "", hints: DictationHints()) != nil { return nil }        // The language's model is fetched on first use.        let deadline = ContinuousClock.now + .seconds(60)        while dictation.phase == .starting, ContinuousClock.now < deadline {            try? await Task.sleep(for: .milliseconds(100))        }        guard dictation.phase == .listening else { return nil }        try? await Task.sleep(for: .seconds(seconds + 0.8))        let words = await dictation.finish().text.trimmingCharacters(in: .whitespacesAndNewlines)        return words.isEmpty ? nil : words    }}/// A voice file's loudness as a waveform: the highest sample in each of/// `count` slices, 0…1. For a voice message that came with none (sent by an/// older phone, or imported): the core keeps it (`chat.waveform`) and works/// out the bars from it, as it does for every other.enum ChatVoicePeaks {    static func of(_ url: URL, count: Int = 64) -> [Double]? {        guard let file = try? AVAudioFile(forReading: url), file.length >= AVAudioFramePosition(count) else { return nil }        let format = file.processingFormat        let total = Int(file.length), share = total / count, chunk: AVAudioFrameCount = 16_384        guard share > 0, let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: chunk) else { return nil }        var peaks = [Double](repeating: 0, count: count)        var at = 0        // Read a piece at a time, so a long note never sits whole in memory.        while at < total {            guard (try? file.read(into: buffer, frameCount: chunk)) != nil, buffer.frameLength > 0, let channel = buffer.floatChannelData?[0] else { break }            for i in stride(from: 0, to: Int(buffer.frameLength), by: 4) {                let slice = min(count - 1, (at + i) / share)                peaks[slice] = max(peaks[slice], Double(min(1, abs(channel[i]))))            }            at += Int(buffer.frameLength)        }        return peaks    }}/// The player's own word that a note has played to its end, passed to the one player.final class ChatVoiceEnding: NSObject, AVAudioPlayerDelegate {    private let done: @MainActor (AVAudioPlayer) -> Void    init(_ done: @escaping @MainActor (AVAudioPlayer) -> Void) { self.done = done }    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {        let done = self.done        nonisolated(unsafe) let player = player        Task { @MainActor in done(player) }    }}/// Where one voice message stands.enum ChatVoicePhase: Equatable {    /// Not started: its length whole, no speed.    case rest    /// Tapped, its file not on the phone yet: the arc turns in the round.    case loading    case playing    /// Paused part-way: its place kept for the sitting.    case paused    /// The file can't be fetched now: Try again, in the core's words.    case offline(String)    /// The file has gone, or won't play: nothing to tap, in the core's words.    case gone(String)}/// The one voice message playing, from its file on this phone (`chat.file`),/// and every note's place for the sitting.@MainActor@Observablefinal class ChatVoicePlayer {    static let shared = ChatVoicePlayer()    /// The message the player holds (playing, or paused part-way), and where in it, in seconds of the note's own time.    private(set) var message: String?    private(set) var playing = false    private(set) var position: TimeInterval = 0    /// The note being fetched to play.    private(set) var loading: String?    /// One speed for every voice message (`chat.settings` voiceSpeed).    private(set) var speed: Double = 1    /// The other notes' places, kept for the sitting when another started.    private(set) var places: [String: TimeInterval] = [:]    /// Notes whose file can't be fetched now, or has gone / won't play, with the core's words.    private(set) var offline: [String: String] = [:]    private(set) var broken: [String: String] = [:]    /// Notes of theirs played here this sitting: drawn played at once.    private(set) var playedHere: Set<String> = []    /// Each note's length as its file says, once opened.    private(set) var lengths: [String: TimeInterval] = [:]    static let speeds: [Double] = [1, 1.5, 2]    /// A note becomes played once it has played this long (or to its end, when shorter).    static let playedAfter: TimeInterval = 1    @ObservationIgnored private var player: AVAudioPlayer?    @ObservationIgnored private var ticker: Task<Void, Never>?    @ObservationIgnored private var fetch: Task<Void, Never>?    @ObservationIgnored private var book: (any ChatBook)?    @ObservationIgnored private var unplayed = false    @ObservationIgnored private var onPlayed: (String) -> Void = { _ in }    @ObservationIgnored private var observers: [any NSObjectProtocol] = []    /// Told by the player itself when a note has played to its end: the only word that it has.    @ObservationIgnored private lazy var ending = ChatVoiceEnding { [weak self] player in self?.ended(player) }    private init() {        let center = NotificationCenter.default        // A call (an interruption) or the headphones coming out pauses, keeping the place.        observers.append(center.addObserver(forName: AVAudioSession.interruptionNotification, object: nil, queue: .main) { [weak self] note in            let began = (note.userInfo?[AVAudioSessionInterruptionTypeKey] as? UInt).flatMap(AVAudioSession.InterruptionType.init) == .began            if began { MainActor.assumeIsolated { self?.pause() } }        })        observers.append(center.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: .main) { [weak self] note in            let gone = (note.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt).flatMap(AVAudioSession.RouteChangeReason.init) == .oldDeviceUnavailable            if gone { MainActor.assumeIsolated { self?.pause() } }        })    }    /// The chat opened: the speed as the core keeps it.    func open(_ book: any ChatBook) async {        self.book = book        speed = await book.voiceSpeed()    }    /// Where `message` stands now.    func phase(_ message: String, part: ChatMediaPart?) -> ChatVoicePhase {        if let words = broken[message] { return .gone(words) }        if part?.gone == true { return .gone(ShellLines.line("chat", "app.notice.file_gone")) }        if let words = offline[message] { return .offline(words) }        if loading == message { return .loading }        if self.message == message { return playing ? .playing : .paused }        if places[message] != nil { return .paused }        return .rest    }    /// Where in `message` the place stands, in seconds.    func place(_ message: String) -> TimeInterval {        self.message == message ? position : places[message] ?? 0    }    /// The note's whole length, in seconds: the core's, else its file's.    func length(_ message: String, part: ChatMediaPart?) -> TimeInterval {        if let ms = part?.durationMs, ms > 0 { return Double(ms) / 1_000 }        return lengths[message] ?? 0    }    /// The round tapped: play from its place or the start, pause keeping it, stop a loading, or try again.    func tap(_ bubble: ChatBubble, part: ChatMediaPart, book: (any ChatBook)?, played: @escaping (String) -> Void) {        let id = bubble.message        switch phase(id, part: part) {        case .gone: return        case .loading:            fetch?.cancel()            fetch = nil            loading = nil        case .playing:            pause()        case .paused where message == id:            if let player { resume(player) }        case .rest, .paused, .offline:            start(bubble, part: part, book: book ?? self.book, played: played)        }    }    private func start(_ bubble: ChatBubble, part: ChatMediaPart, book: (any ChatBook)?, played: @escaping (String) -> Void) {        let id = bubble.message        let from = places[id] ?? 0        // Another note playing pauses where it stands, its place kept.        hold()        offline[id] = nil        guard let book else { return }        loading = id        fetch?.cancel()        fetch = Task { [weak self] in            do {                let file = try await book.file(message: id, index: part.index)                guard !Task.isCancelled, let self, self.loading == id else { return }                self.loading = nil                let url = URL(fileURLWithPath: file.path)                guard let player = try? AVAudioPlayer(contentsOf: url) else {                    self.broken[id] = ShellLines.line("chat", "app.voice.unplayable")                    return                }                // A note that came with no waveform gets one from this phone, kept by the core for every phone.                if part.bars == nil, part.waveform?.isEmpty ?? true { Task.detached(priority: .utility) { await ChatVoicePlayer.waveform(of: url, message: id, index: part.index, book: book) } }                player.enableRate = true                player.delegate = self.ending                player.prepareToPlay()                self.lengths[id] = player.duration                try? AVAudioSession.sharedInstance().setCategory(.playback, mode: .spokenAudio)                try? AVAudioSession.sharedInstance().setActive(true)                self.player = player                self.message = id                self.unplayed = !bubble.mine && part.played == false && !self.playedHere.contains(id)                self.onPlayed = played                player.currentTime = min(from, max(0, player.duration - 0.05))                self.position = player.currentTime                self.places[id] = nil                self.resume(player)            } catch let refusal as CottonCallError {                guard let self, self.loading == id else { return }                self.loading = nil                if refusal.code == "file_gone" { self.broken[id] = refusal.message } else { self.offline[id] = refusal.message }            } catch {                guard let self, self.loading == id, !Task.isCancelled else { return }                self.loading = nil                self.offline[id] = ShellLines.line("chat", "app.notice.file_offline")            }        }    }    private func resume(_ player: AVAudioPlayer) {        player.rate = Float(speed)        try? AVAudioSession.sharedInstance().setActive(true)        guard player.play() || (player.prepareToPlay() && player.play()) else {            // No silent failure: a note that will not play says so, in the core's words.            if let message { broken[message] = ShellLines.line("chat", "app.voice.unplayable") }            return release()        }        playing = true        ticker?.cancel()        ticker = Task { [weak self] in            var stalled = 0            while !Task.isCancelled {                try? await Task.sleep(for: .milliseconds(50))                guard let self, let player = self.player else { return }                // Not playing for a moment is not its end (Comms 26, B5: a seek dropped the note back to its start). A                // player sets `isPlaying` false for a moment as its place is moved; only the player's own word that it                // finished ends the note (`ended`). One that stays still part-way while it should play is asked again.                if !player.isPlaying, self.playing, player.currentTime < player.duration - 0.1 {                    stalled += 1                    if stalled >= 6 { stalled = 0; player.play() }                } else {                    stalled = 0                }                self.position = player.currentTime                if self.unplayed, player.currentTime >= Self.playedAfter { self.markPlayed() }            }        }    }    /// The player says its note played to its end: back to the start, the length whole again.    private func ended(_ finished: AVAudioPlayer) {        guard finished === player, playing else { return }        if unplayed { markPlayed() }        finish()    }    private func markPlayed() {        guard unplayed, let message else { return }        unplayed = false        playedHere.insert(message)        onPlayed(message)    }    /// Paused where it stands.    func pause() {        guard let player, playing else { return }        player.pause()        position = player.currentTime        playing = false        ticker?.cancel()    }    /// The note playing paused and set down, its place kept for the sitting.    private func hold() {        guard let player, let message else { return }        player.pause()        let at = player.currentTime        if at > 0, at < player.duration { places[message] = at }        release()    }    /// Played to its end: at its start again.    private func finish() {        if let message { places[message] = nil }        release()    }    private func release() {        ticker?.cancel()        ticker = nil        player?.stop()        player = nil        message = nil        playing = false        position = 0        try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)    }    /// The chat left: the note stops, and the places kept for the sitting go.    func stop() {        fetch?.cancel()        fetch = nil        loading = nil        release()        places = [:]        offline = [:]    }    /// The place moved, by a drag or a tap on the bars, or VoiceOver's swipe: playing or paused.    func seek(_ message: String, to at: TimeInterval, length: TimeInterval) {        let at = max(0, min(at, max(0, length - 0.05)))        if self.message == message, let player {            player.currentTime = at            position = at            #if COTTON_DEV            // `-chat-voice-seek-stalls YES`: the player stands still a moment after each move of its place, as a            // phone's does, so a test can see that a seek never ends the note.            if playing, UserDefaults.standard.bool(forKey: "chat-voice-seek-stalls") {                player.pause()                Task { [weak self] in                    try? await Task.sleep(for: .milliseconds(400))                    if let self, self.playing, self.player === player { player.play() }                }            }            #endif        } else if places[message] != nil {            places[message] = at        }    }    /// The pill tapped: the next speed, round again; the note keeps playing from where it was.    func nextSpeed() {        let at = Self.speeds.firstIndex(of: speed) ?? 0        speed = Self.speeds[(at + 1) % Self.speeds.count]        player?.rate = Float(speed)        let chosen = speed        if let book { Task { await book.setVoiceSpeed(chosen) } }    }    nonisolated static func waveform(of url: URL, message: String, index: Int, book: any ChatBook) async {        guard let peaks = ChatVoicePeaks.of(url) else { return }        await book.setWaveforms([ChatWaveformMade(message: message, index: index, waveform: peaks)])    }}// MARK: words/// The player's words, every one a kit line (`app.voice.*`).enum ChatVoiceSaid {    static func line(_ key: String, _ fills: [String: String] = [:]) -> String { ShellLines.line("chat", "app.voice.\(key)", fills) }    /// `m:ss`, minutes not padded, as the core writes a length; rounded up, so 0:00 only at the end.    static func time(_ seconds: TimeInterval) -> String {        let whole = max(0, Int(seconds.rounded(.up)))        let tens = (whole % 60) / 10, ones = whole % 10        return "\(whole / 60):\(tens)\(ones)"    }    static func speed(_ n: Double) -> String {        n == n.rounded() ? String(Int(n)) : String(n)    }}// MARK: the glyphs, in Comms' own line (no borrowed icon set)private struct VoicePlayGlyph: Shape {    func path(in rect: CGRect) -> Path {        let s = rect.width / 24        var p = Path()        p.move(to: CGPoint(x: 9 * s, y: 6.6 * s))        p.addLine(to: CGPoint(x: 9 * s, y: 17.4 * s))        p.addQuadCurve(to: CGPoint(x: 10.6 * s, y: 18.25 * s), control: CGPoint(x: 9 * s, y: 18.9 * s))        p.addLine(to: CGPoint(x: 18.9 * s, y: 12.85 * s))        p.addQuadCurve(to: CGPoint(x: 18.9 * s, y: 11.15 * s), control: CGPoint(x: 19.7 * s, y: 12 * s))        p.addLine(to: CGPoint(x: 10.6 * s, y: 5.75 * s))        p.addQuadCurve(to: CGPoint(x: 9 * s, y: 6.6 * s), control: CGPoint(x: 9 * s, y: 5.1 * s))        p.closeSubpath()        return p    }}private struct VoicePauseGlyph: Shape {    func path(in rect: CGRect) -> Path {        let s = rect.width / 24        var p = Path()        p.addRoundedRect(in: CGRect(x: 6.6 * s, y: 5.8 * s, width: 3.8 * s, height: 12.4 * s), cornerSize: CGSize(width: 1.5 * s, height: 1.5 * s))        p.addRoundedRect(in: CGRect(x: 13.6 * s, y: 5.8 * s, width: 3.8 * s, height: 12.4 * s), cornerSize: CGSize(width: 1.5 * s, height: 1.5 * s))        return p    }}private struct VoiceRetryGlyph: Shape {    func path(in rect: CGRect) -> Path {        let s = rect.width / 24        var p = Path()        p.addArc(center: CGPoint(x: 11.95 * s, y: 12.3 * s), radius: 6.5 * s, startAngle: .degrees(3), endAngle: .degrees(-38), clockwise: false)        p.move(to: CGPoint(x: 17.2 * s, y: 4.4 * s))        p.addLine(to: CGPoint(x: 17.2 * s, y: 7.9 * s))        p.addLine(to: CGPoint(x: 13.7 * s, y: 7.9 * s))        return p.strokedPath(StrokeStyle(lineWidth: 2 * s, lineCap: .round, lineJoin: .round))    }}/// The loading arc: one turn a second, still under Reduce Motion.private struct VoiceLoadingArc: View {    let colour: Color    @Environment(\.accessibilityReduceMotion) private var still    @State private var turned = false    var body: some View {        Circle()            .trim(from: 0, to: 0.25)            .stroke(colour, style: StrokeStyle(lineWidth: 2.2, lineCap: .round))            .frame(width: 22, height: 22)            .rotationEffect(.degrees(turned ? 360 : 0))            .frame(width: 26, height: 26)            .onAppear {                guard !still else { return }                withAnimation(.linear(duration: 1).repeatForever(autoreverses: false)) { turned = true }            }    }}// MARK: the player/// A voice message: the round, the 36 bars (or the thin track), the length/// and, while it has started, the speed; under it the words its sender's/// phone heard in it, or the core's words when its file can't be had.struct ChatVoiceView: View {    let bubble: ChatBubble    let ink: Color    let dim: Color    /// A note of theirs has played a second: the thread asks `chat.act played` and draws the bubble answered.    var played: (String) -> Void = { _ in }    @Environment(\.chatLook) private var look    @Environment(\.chatBook) private var book    @Environment(\.dynamicTypeSize) private var typeSize    @Environment(\.colorScheme) private var scheme    private var player: ChatVoicePlayer { .shared }    /// Posted with the message's id when the player's height changes in place: the thread measures its row again.    static let resized = Notification.Name("chat.voice.resized")    static let round: CGFloat = 40    static let gap: CGFloat = 10    static let bars = 36    static let row: CGFloat = 28    /// The drawn player's width at the default sizes: 40 + 10 + 178.    static let width: CGFloat = 228    private var part: ChatMediaPart? { bubble.media.first { $0.kind == .voice || $0.kind == .audio } ?? bubble.media.first }    private var big: Bool { typeSize.isAccessibilitySize }    private var mine: Bool { bubble.mine }    private var c: ChatColours { look.colours }    private var mineInk: Color { c.bubbleOutText }    private var unplayed: Bool { !mine && part?.played == false && !player.playedHere.contains(bubble.message) }    var body: some View {        let id = bubble.message        let phase = player.phase(id, part: part)        let length = player.length(id, part: part)        let at = player.place(id)        let started = phase == .playing || phase == .paused        VStack(alignment: .leading, spacing: 4) {            HStack(alignment: .top, spacing: Self.gap) {                roundButton(phase: phase, length: length, at: at)                VStack(alignment: .leading, spacing: 1) {                    BarsView(part: part, progress: started && length > 0 ? at / length : 0, started: started, mine: mine, gone: isGone(phase), big: big,                             heard: mine ? mineInk : c.text, unheard: mine ? mineInk.opacity(scheme == .dark ? 0.30 : 0.28) : c.faint) { fraction in                        guard started, length > 0 else { return }                        player.seek(id, to: fraction * length, length: length)                    }                    .padding(.top, 6)                    .accessibilityElement()                    .accessibilityLabel(Text(verbatim: ChatVoiceSaid.line("position")))                    .accessibilityValue(Text(verbatim: ChatVoiceSaid.line("position_value", ["at": ChatVoiceSaid.time(at), "length": ChatVoiceSaid.time(length)])))                    .accessibilityAdjustableAction { direction in                        let step: TimeInterval = direction == .increment ? 5 : -5                        player.seek(id, to: at + step, length: length)                    }                    .accessibilityIdentifier("chat-voice-position-\(id)")                    // Read only once the note has started: at rest the bars are not read.                    .accessibilityHidden(!started)                    foot(phase: phase, length: length, at: at, started: started)                }                .frame(maxWidth: big ? .infinity : 178, alignment: .leading)            }            under(phase: phase)        }        .frame(maxWidth: big ? .infinity : Self.width, alignment: .leading)        .onChange(of: Self.shape(phase, started: started, big: big)) {            NotificationCenter.default.post(name: Self.resized, object: id)        }    }    /// What decides the player's height: the words under it, and at the largest text the speed's own line.    private static func shape(_ phase: ChatVoicePhase, started: Bool, big: Bool) -> Int {        let under: Int        switch phase {        case .offline: under = 1        case .gone: under = 2        default: under = 0        }        return under * 2 + (big && started ? 1 : 0)    }    private func isGone(_ phase: ChatVoicePhase) -> Bool {        if case .gone = phase { return true }        return false    }    // The round: play, pause, loading, try again, or faint when gone. Drawn at 40, met at 44.    @ViewBuilder private func roundButton(phase: ChatVoicePhase, length: TimeInterval, at: TimeInterval) -> some View {        let id = bubble.message        let (fill, glyph) = roundColours(phase)        Button {            guard let part else { return }            player.tap(bubble, part: part, book: book, played: played)        } label: {            ZStack {                Circle().fill(fill)                switch phase {                case .playing:                    VoicePauseGlyph().fill(glyph).frame(width: 18, height: 18)                case .loading:                    VoiceLoadingArc(colour: glyph)                case .offline:                    VoiceRetryGlyph().fill(glyph).frame(width: 18, height: 18)                default:                    VoicePlayGlyph().fill(glyph).overlay(VoicePlayGlyph().stroke(glyph, style: StrokeStyle(lineWidth: 1.2, lineJoin: .round))).frame(width: 18, height: 18)                }            }            .frame(width: Self.round, height: Self.round)            .padding(2)            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .padding(-2)        .disabled(isGone(phase))        .accessibilityLabel(Text(verbatim: roundSaid(phase)))        .accessibilityValue(Text(verbatim: roundValue(phase, length: length, at: at)))        .accessibilityIdentifier("chat-voice-play-\(id)")    }    private func roundColours(_ phase: ChatVoicePhase) -> (Color, Color) {        switch phase {        case .gone: return (c.bar, c.faint)        case .offline: return mine ? (mineInk.opacity(0.10), mineInk) : (c.bar, c.text)        default:            if mine { return (mineInk, c.bubbleOut) }            return unplayed ? (c.accent, c.onAccent) : (c.text, c.ground)        }    }    private func roundSaid(_ phase: ChatVoicePhase) -> String {        switch phase {        case .playing: ChatVoiceSaid.line("pause")        case .loading: ChatVoiceSaid.line("loading")        case .offline: ChatWords.line("thread.retry")        case .gone: ChatVoiceSaid.line("gone")        case .rest, .paused: ChatVoiceSaid.line("play")        }    }    private func roundValue(_ phase: ChatVoicePhase, length: TimeInterval, at: TimeInterval) -> String {        switch phase {        case .playing, .paused: return ChatVoiceSaid.line("left", ["time": ChatVoiceSaid.time(length - at)])        case .offline(let words): return words        case .gone, .loading: return ""        case .rest:            let whole = part?.length ?? ChatVoiceSaid.time(length)            return unplayed ? [whole, ChatVoiceSaid.line("not_played")].joined(separator: ", ") : whole        }    }    // The foot line: the length (counting down once started), the not-played dot, the speed at the right.    @ViewBuilder private func foot(phase: ChatVoicePhase, length: TimeInterval, at: TimeInterval, started: Bool) -> some View {        let id = bubble.message        let shown = started ? ChatVoiceSaid.time(length - at) : (part?.length ?? ChatVoiceSaid.time(length))        let lengthText = HStack(spacing: 6) {            Text(verbatim: shown)                .font(look.font(12.5))                .monospacedDigit()                .foregroundStyle(mine ? mineInk.opacity(0.72) : c.dim)                .fixedSize()            if unplayed, !started, !isGone(phase) {                Circle().fill(c.accent).frame(width: big ? 12 : 7, height: big ? 12 : 7)            }        }        .accessibilityIdentifier("chat-voice-length-\(id)")        .accessibilityHidden(true)        let pill = Button { player.nextSpeed() } label: {            Text(verbatim: ChatVoiceSaid.line("speed_short", ["n": ChatVoiceSaid.speed(player.speed)]))                .font(look.font(13, .semibold))                .monospacedDigit()                .foregroundStyle(mine ? mineInk : c.text)                .padding(.vertical, 5)                .padding(.horizontal, 8)                .background(Capsule().fill(mine ? mineInk.opacity(0.10) : c.bar))                .frame(minWidth: 44, minHeight: 44)                .contentShape(Rectangle())        }        .buttonStyle(.plain)        .padding(.vertical, -10)        .accessibilityLabel(Text(verbatim: ChatVoiceSaid.line("speed")))        .accessibilityValue(Text(verbatim: ChatVoiceSaid.line("speed_value", ["n": ChatVoiceSaid.speed(player.speed)])))        .accessibilityIdentifier("chat-voice-speed-\(id)")        if big {            // At the largest text the length and the speed wrap onto their own lines rather than squeeze.            VStack(alignment: .leading, spacing: 6) {                lengthText                if started { pill.padding(.vertical, 10) }            }            .frame(minHeight: 44, alignment: .leading)        } else {            HStack(spacing: 0) {                lengthText                Spacer(minLength: 6)                if started { pill }            }            .frame(minHeight: 24)        }    }    // Under the player: the core's words when its file can't be had, else the words heard in it.    @ViewBuilder private func under(phase: ChatVoicePhase) -> some View {        let id = bubble.message        let wide: CGFloat? = big ? nil : Self.width        switch phase {        case .offline(let words):            Button {                guard let part else { return }                player.tap(bubble, part: part, book: book, played: played)            } label: {                (Text(verbatim: words).foregroundStyle(mine ? mineInk : c.danger)                 + Text(verbatim: " ") + Text(verbatim: ChatWords.line("thread.retry")).fontWeight(.semibold).foregroundStyle(mine ? mineInk : c.text))                    .font(look.font(14.5))                    .multilineTextAlignment(.leading)                    .fixedSize(horizontal: false, vertical: true)                    .frame(maxWidth: wide, alignment: .leading)                    .frame(minHeight: 44, alignment: .topLeading)                    .contentShape(Rectangle())            }            .buttonStyle(.plain)            .accessibilityLabel(Text(verbatim: ChatWords.line("thread.retry")))            .accessibilityValue(Text(verbatim: words))            .accessibilityIdentifier("chat-voice-retry-\(id)")        case .gone(let words):            Text(verbatim: words)                .font(look.font(14.5))                .foregroundStyle(mine ? mineInk.opacity(0.75) : c.dim)                .fixedSize(horizontal: false, vertical: true)                .frame(maxWidth: wide, alignment: .leading)                .accessibilityIdentifier("chat-voice-gone-\(id)")        default:            if let words = part?.transcript, !words.isEmpty {                Text(verbatim: words)                    .font(look.font(14.5))                    .foregroundStyle(mine ? mineInk.opacity(0.75) : c.dim)                    .fixedSize(horizontal: false, vertical: true)                    .frame(maxWidth: wide, alignment: .leading)                    // The words land in a bubble already drawn: they stand at once, never faded in.                    .transition(.identity)                    // Said with the bubble (WarmSpoken), as they stand under the player.                    .accessibilityIdentifier("chat-voice-transcript-\(id)")                    .accessibilityHidden(true)            }        }    }}/// The 36 bars the core answered, filling from the place; a note with none draws the thin track./// A drag along them (or a tap) moves the place; their target is 44 tall.private struct BarsView: View {    let part: ChatMediaPart?    let progress: Double    let started: Bool    let mine: Bool    let gone: Bool    let big: Bool    let heard: Color    let unheard: Color    let moved: (Double) -> Void    /// This touch, once it has gone a few points: along the bars (it moves the place) or up the chat (it scrolls, and    /// the place stays where it was).    @State private var sideways: Bool?    var body: some View {        GeometryReader { box in            let width = box.size.width            Group {                if let bars = part?.bars, !bars.isEmpty {                    let gap: CGFloat = big ? 1.5 : 2                    let bar: CGFloat = big ? max(2, (width - gap * CGFloat(bars.count - 1)) / CGFloat(bars.count)) : 3                    HStack(alignment: .center, spacing: gap) {                        ForEach(Array(bars.enumerated()), id: \.offset) { i, h in                            Capsule()                                .fill(progress > 0 && Double(i) / Double(bars.count) < progress ? heard : unheard)                                .frame(width: big ? min(bar, 2) : bar, height: 3 + 21 * max(0, min(1, h)))                        }                    }                    .opacity(gone ? 0.55 : 1)                    .frame(width: width, height: ChatVoiceView.row, alignment: .leading)                } else {                    ZStack(alignment: .leading) {                        Capsule().fill(unheard).frame(height: 4)                        Capsule().fill(heard).frame(width: width * progress, height: 4)                        if started {                            Circle().fill(heard).frame(width: 10, height: 10).offset(x: max(0, width * progress - 5))                        }                    }                    .frame(width: width, height: ChatVoiceView.row)                }            }            .overlay {                Color.clear                    .frame(width: width, height: 44)                    .contentShape(Rectangle())                    // A tap sets the place; a drag along the bars moves it. A drag that starts up or down is the                    // chat scrolling past, and leaves the place alone.                    .onTapGesture(coordinateSpace: .local) { point in                        guard started, width > 0 else { return }                        moved(max(0, min(1, point.x / width)))                    }                    .simultaneousGesture(DragGesture(minimumDistance: 6).onChanged { drag in                        guard started, width > 0 else { return }                        if sideways == nil { sideways = abs(drag.translation.width) > abs(drag.translation.height) }                        guard sideways == true else { return }                        moved(max(0, min(1, drag.location.x / width)))                    }.onEnded { _ in sideways = nil })                    .allowsHitTesting(started)            }        }        .frame(width: big ? nil : 178, height: ChatVoiceView.row)        .frame(maxWidth: big ? .infinity : 178, alignment: .leading)    }}#endif