Cotton code
767 lines · 36.3 KB · SwiftRaw
// The PODCAST as a late-fifties portrait TRANSISTOR RADIO (12 Nov 2026,// the podcasts' own object on their own ground): the show IS the radio and// the radio IS its player, a bare object standing on a kitchen windowsill's// mint formica (`FaceGround.formicaCounter`) with no paper and no rule of// the deck's. Its case is two-tone, cherry red over cream parted by a chrome// strip; behind the dial window's glass the show's artwork stands as the// tuning card on a cream dial card, the show's name printed on the glass// beside it, the episode beneath, and across the foot the scale the needle// runs along, the episode's length at its end and the time played and left// at the needle's foot; the chrome plate on top says how many episodes the// show has; VOL and TUNE are engraved under the two knobs either side of the// speaker grille; the two keys carry a curved arrow and the fifteen seconds// they jump.//// PAINTED (`Media.xcassets`, `scripts/paint-radio.py`): the case with its// grille, its shadow, the dial card lit and dim, the glass's sheen, the// plate, the knob and its pointer, the keys raised and pressed, the button// in and out, the lamp off and on, and the needle, each laid where// `RadioFaceKnobs` places it in a 1086 x 1448 cabinet box, scaled by the// drawn width over 1086. The face draws live only what the data decides:// the artwork, every word and figure, the scale's ticks, the needle's// place, the pointers' angles and which of each pair of states is laid.//// THE PLAYER (`faceTrackPlayer`: on the phone the app's one podcast player,// in Loom the specimen player) says whether it holds this show's episode, and// how far into it: at REST (it holds none) the card is dim, the lamp off, the// button out, the needle at nought and no programme line — the show's name// alone; PLAYING the card is lit, the lamp on, the button in and the needle// at the time played; PAUSED the card is dim again, the lamp off, the button// out, and the needle holds where it stopped. Nothing here keeps time.//// THE CONTROLS are the radio's own, inside its cabinet: the button plays or// pauses; the left key jumps back fifteen seconds and the right on fifteen,// pressed while touched; VOL turns the sound's volume, its pointer following// the finger round its pivot; TUNE seeks — a fine turn moves seconds, a// quick one minutes — the needle and the times following the turn, the// player moved there when the finger lifts. The glass is the card's own: its// tap opens the show's episodes, as the card's tap does (`facePart(.title)`).//// The episode is the card's `episode` (its title, its length in seconds),// which the deck reads for the show: the one started, else the newest. Every// word is the core's (`DeckCard`), the record's or a line.import CottonPaperimport CottonValuesimport SwiftUIenum RadioFaceKnobs {    // THE CABINET BOX every placement is in, in the paintings' pixels    // (`scripts/paint-radio.py`): the face draws it its own width, never    // wider than `widest`, and every place below is scaled by the drawn    // width over it.    static let box = CGSize(width: 1086, height: 1448)    static let widest: CGFloat = 362    static let shadow = CGRect(x: -80, y: -80, width: 1246, height: 1608)    static let window = CGRect(x: 130, y: 150, width: 826, height: 490)    static let plate = CGRect(x: 468, y: 50, width: 150, height: 62)    static let lamp = CGRect(x: 125, y: 25, width: 130, height: 130)    static let button = CGRect(x: 480, y: 766, width: 126, height: 126)    static let volume = CGRect(x: 90, y: 1040, width: 190, height: 190)    static let tune = CGRect(x: 806, y: 1040, width: 190, height: 190)    static let keyBack = CGRect(x: 170, y: 770, width: 160, height: 112)    static let keyOn = CGRect(x: 756, y: 770, width: 160, height: 112)    // THE DIAL: the tuning card (the show's artwork), the show's name beside    // it, the programme line under that (at rest the name alone over both),    // the scale with its ends' labels, the needle's run, and the line the    // times stand on at its foot. A show with no artwork has its name across    // the card's whole width.    static let artwork = CGRect(x: 160, y: 178, width: 290, height: 290)    static let artworkCorner: CGFloat = 6    static let showName = CGRect(x: 478, y: 186, width: 450, height: 124)    static let programme = CGRect(x: 478, y: 318, width: 450, height: 150)    static let showAlone = CGRect(x: 478, y: 186, width: 450, height: 282)    static let noArtworkInset: CGFloat = 318    static let scaleLeft: CGFloat = 160    static let scaleRight: CGFloat = 926    static let tickBaseline: CGFloat = 548    static let ends = CGRect(x: 160, y: 486, width: 766, height: 27)    static let needle = CGSize(width: 12, height: 96)    static let needleTop: CGFloat = 500    static let times = CGRect(x: 160, y: 568, width: 766, height: 27)    /// The room the times keep from the needle either side.    static let timesGap: CGFloat = 14    /// Nearer an end of the scale than this, both times stand on the other    /// side of the needle.    static let timesTurn: CGFloat = 170    /// The scale's ticks: how many spaces, every how many a long one, and    /// their heights and stroke.    static let ticks = 60    static let longEvery = 5    static let tick: CGFloat = 10    static let longTick: CGFloat = 18    static let tickStroke: CGFloat = 2.4    // THE INK: the plate's count, the engravings under the knobs and the    // keys' arrows and seconds.    static let plateCount = CGRect(x: 478, y: 62, width: 130, height: 38)    static let volumeLabel = CGRect(x: 110, y: 1236, width: 150, height: 30)    static let tuneLabel = CGRect(x: 826, y: 1236, width: 150, height: 30)    static let keyBackInk = CGRect(x: 196, y: 790, width: 108, height: 62)    static let keyOnInk = CGRect(x: 782, y: 790, width: 108, height: 62)    /// A pressed key's ink sinks this far with it.    static let pressedSink: CGFloat = 3    /// The type, in the paintings' pixels.    static let showSize: CGFloat = 50    static let programmeSize: CGFloat = 30    static let endsSize: CGFloat = 24    static let timesSize: CGFloat = 26    static let plateSize: CGFloat = 30    static let engravingSize: CGFloat = 28    static let engravingTracking: CGFloat = 2    static let keySize: CGFloat = 32    static let arrowStroke: CGFloat = 3.2    /// The tuning card in the unlit window: a little darker and greyer.    static let unlitBrightness: Double = -0.08    static let unlitSaturation: Double = 0.8    // THE KNOBS: a pointer's sweep either side of upright, in degrees.    static let sweep: Double = 135    /// TUNE: the seconds a slow turn of one degree moves, and how a quick    /// turn gears it up — at `quick` degrees a second the gearing doubles,    /// growing with the square of the speed to at most `mostGearing`.    static let secondsPerDegree: Double = 0.5    static let quick: Double = 240    static let mostGearing: Double = 40    /// The keys' jump, back and on, in seconds.    static let skip: TimeInterval = 15}/// The episode a show's radio plays, as its card holds it (`episode`).public struct RadioEpisode: Equatable, Sendable {    /// Its record, where the deck read one.    public var record: String?    public var title: String?    /// Its length, in seconds, as the feed gives it.    public var seconds: TimeInterval    public init(record: String? = nil, title: String?, seconds: TimeInterval) {        self.record = record        self.title = title        self.seconds = seconds    }}/// What the radio reads off its card and its player.public enum RadioDial {    /// How the radio stands.    public enum State: Equatable, Sendable {        /// The player holds none of this show: dim, lamp off, needle at nought.        case rest        /// It plays this show's episode: lit, lamp on, button in.        case playing        /// It holds this show's episode, paused: dim, lamp off, the needle held.        case paused    }    /// The card's episode (`episode`); nil for a show with none.    public static func episode(_ card: DeckCard) -> RadioEpisode? {        guard case .object(let entry)? = card.fields["episode"] else { return nil }        return RadioEpisode(            record: entry["record"]?.text, title: entry["title"]?.text, seconds: max(0, entry["duration"]?.number ?? 0))    }    public static func state(_ play: TrackPlay) -> State {        guard play.held else { return .rest }        return play.playing || play.loading ? .playing : .paused    }    /// The episode's length: the player's where it knows one, else the feed's.    public static func length(_ play: TrackPlay, _ episode: RadioEpisode?) -> TimeInterval {        play.held && play.duration > 0 ? play.duration : episode?.seconds ?? 0    }    /// The needle's share of the scale: the time played over the length;    /// nought at rest and for an episode of no known length.    public static func share(_ elapsed: TimeInterval, of length: TimeInterval) -> Double {        guard length > 0, elapsed.isFinite else { return 0 }        return min(1, max(0, elapsed / length))    }    /// The needle's place along the scale, in the paintings' pixels.    static func needleX(_ share: Double) -> CGFloat {        let knobs = RadioFaceKnobs.self        return knobs.scaleLeft + CGFloat(share) * (knobs.scaleRight - knobs.scaleLeft)    }    /// A pointer's angle, in degrees from upright, for a share of its sweep.    public static func pointer(_ share: Double) -> Double {        -RadioFaceKnobs.sweep + 2 * RadioFaceKnobs.sweep * min(1, max(0, share))    }    /// The angle of `point` round `pivot`, in degrees clockwise from upright.    static func angle(of point: CGPoint, round pivot: CGPoint) -> Double {        atan2(Double(point.x - pivot.x), Double(pivot.y - point.y)) * 180 / .pi    }    /// The turn from one angle to the next, the short way round.    static func turn(from: Double, to: Double) -> Double {        var by = (to - from).truncatingRemainder(dividingBy: 360)        if by > 180 { by -= 360 }        if by <= -180 { by += 360 }        return by    }    /// The seconds TUNE moves for a turn of `degrees` made at `speed`    /// degrees a second: a slow turn seconds, a quick one minutes.    public static func tuned(_ degrees: Double, speed: Double) -> TimeInterval {        let knobs = RadioFaceKnobs.self        let quickness = speed / knobs.quick        return degrees * knobs.secondsPerDegree * min(knobs.mostGearing, 1 + quickness * quickness)    }}/// Which of the radio's keys.enum RadioKey: Equatable {    case back, on}public struct RadioFace: View {    let card: DeckCard    /// The show's artwork, the tuning card behind the glass; nil, the show    /// has none and its name spans the card.    var photo: FacePicture?    var play: TrackPlay = .still    var toggle: (() -> Void)?    var seek: (TimeInterval) -> Void = { _ in }    var volume: Double?    var turnVolume: ((Double) -> Void)?    /// Where a TUNE turn has the needle, until the finger lifts.    @State private var tuning: TimeInterval?    /// Where a VOL turn has the volume, while the finger turns it.    @State private var turned: Double?    @State private var pressed: RadioKey?    public init(        card: DeckCard, photo: FacePicture? = nil, play: TrackPlay = .still, toggle: (() -> Void)? = nil,        seek: @escaping (TimeInterval) -> Void = { _ in }, volume: Double? = nil, turnVolume: ((Double) -> Void)? = nil    ) {        self.card = card        self.photo = photo        self.play = play        self.toggle = toggle        self.seek = seek        self.volume = volume        self.turnVolume = turnVolume    }    public var body: some View {        let knobs = RadioFaceKnobs.self        let episode = RadioDial.episode(card)        let state = RadioDial.state(play)        let length = RadioDial.length(play, episode)        let elapsed = state == .rest ? 0 : (tuning ?? play.elapsed)        let share = RadioDial.share(elapsed, of: length)        GeometryReader { room in            let width = min(room.size.width, knobs.widest, room.size.height * knobs.box.width / knobs.box.height)            let s = width / knobs.box.width            let lit = state == .playing            ZStack(alignment: .topLeading) {                RadioPainted(name: "radio-shadow").placed(knobs.shadow, s)                RadioPainted(name: lit ? "radio-glass-lit" : "radio-glass-dim").placed(knobs.window, s)                tuningCard(lit: lit, s: s)                dial(episode: episode, state: state, elapsed: elapsed, length: length, s: s)                RadioPainted(name: "radio-needle")                    .frame(width: knobs.needle.width * s, height: knobs.needle.height * s)                    .offset(x: (RadioDial.needleX(share) - knobs.needle.width / 2) * s, y: knobs.needleTop * s)                    .accessibilityHidden(true)                RadioPainted(name: "radio-glass-sheen").placed(knobs.window, s)                RadioPainted(name: "radio-cabinet").placed(CGRect(origin: .zero, size: knobs.box), s)                glassPart(episode: episode, state: state, elapsed: elapsed, length: length, s: s)                plate(s)                RadioPainted(name: lit ? "radio-lamp-on" : "radio-lamp-off").placed(knobs.lamp, s)                    .accessibilityHidden(true)                volumeKnob(s)                tuneKnob(elapsed: elapsed, length: length, s: s)                key(.back, s: s)                key(.on, s: s)                button(state: state, s: s)            }            .frame(width: width, height: knobs.box.height * s, alignment: .topLeading)            .frame(width: room.size.width, height: room.size.height, alignment: .top)            .accessibilityElement(children: .contain)        }    }    // MARK: The dial    /// What is printed on the glass under the rim: the show's name, the    /// programme line, the scale and its ends, and the times at the needle.    private func dial(episode: RadioEpisode?, state: RadioDial.State, elapsed: TimeInterval, length: TimeInterval, s: CGFloat) -> some View {        let knobs = RadioFaceKnobs.self        let ink = PodcastMaterial.dial.colour        return ZStack(alignment: .topLeading) {            if let title = card.text("title") {                Text(title)                    .font(CottonFonts.caslon(knobs.showSize * s))                    .italic()                    .lineLimit(state == .rest ? 2 : 1)                    .minimumScaleFactor(0.6)                    .multilineTextAlignment(.center)                    .foregroundStyle(ink)                    .placed(spanned(state == .rest ? knobs.showAlone : knobs.showName), s, alignment: .center)                    .accessibilityIdentifier("radio-show")            }            if state != .rest, let programme = episode?.title {                Text(programme)                    .font(CottonFonts.serif(knobs.programmeSize * s))                    .italic()                    .lineLimit(2)                    .minimumScaleFactor(0.75)                    .multilineTextAlignment(.center)                    .foregroundStyle(ink)                    .placed(spanned(knobs.programme), s, alignment: .center)                    .accessibilityIdentifier("radio-programme")            }            RadioScale().placed(CGRect(x: knobs.scaleLeft, y: knobs.tickBaseline - knobs.longTick, width: knobs.scaleRight - knobs.scaleLeft, height: knobs.longTick), s)            if length > 0 {                HStack(spacing: 0) {                    Text(TrackClock.said(0))                    Spacer(minLength: 0)                    Text(TrackClock.said(length))                        .accessibilityIdentifier("radio-length")                }                .font(CottonFonts.serif(knobs.endsSize * s))                .monospacedDigit()                .foregroundStyle(ink)                .placed(knobs.ends, s, alignment: .bottom)            }            if state != .rest, length > 0 {                times(elapsed: elapsed, length: length, s: s)            }        }        .accessibilityHidden(true)    }    /// A line's place on the card: beside the tuning card, or across the    /// card's whole width where the show has no artwork.    private func spanned(_ rect: CGRect) -> CGRect {        guard photo == nil else { return rect }        let inset = RadioFaceKnobs.noArtworkInset        return CGRect(x: rect.minX - inset, y: rect.minY, width: rect.width + inset, height: rect.height)    }    /// The show's artwork, the tuning card on the dial card behind the    /// glass: lit with it, a little darker and greyer while it is not.    @ViewBuilder    private func tuningCard(lit: Bool, s: CGFloat) -> some View {        let knobs = RadioFaceKnobs.self        if let photo {            photo                .frame(width: knobs.artwork.width * s, height: knobs.artwork.height * s)                .clipShape(RoundedRectangle(cornerRadius: knobs.artworkCorner * s))                .brightness(lit ? 0 : knobs.unlitBrightness)                .saturation(lit ? 1 : knobs.unlitSaturation)                .at(knobs.artwork, s)                .accessibilityHidden(true)        }    }    /// The time played and the time left, at the needle's foot: either side    /// of it, or both on the far side of it near an end of the scale.    private func times(elapsed: TimeInterval, length: TimeInterval, s: CGFloat) -> some View {        let knobs = RadioFaceKnobs.self        let x = RadioDial.needleX(RadioDial.share(elapsed, of: length))        let played = Text(TrackClock.said(elapsed)).accessibilityIdentifier("radio-elapsed")        let left = Text(TrackClock.left(elapsed, of: length)).accessibilityIdentifier("radio-remaining")        let gap = knobs.timesGap        return ZStack(alignment: .topLeading) {            if x - knobs.scaleLeft < knobs.timesTurn {                HStack(spacing: gap * s) { played; left }                    .frame(width: (knobs.scaleRight - x - gap) * s, alignment: .leading)                    .offset(x: (x + gap) * s)            } else if knobs.scaleRight - x < knobs.timesTurn {                HStack(spacing: gap * s) { played; left }                    .frame(width: (x - gap - knobs.scaleLeft) * s, alignment: .trailing)                    .offset(x: knobs.scaleLeft * s)            } else {                played                    .frame(width: (x - gap - knobs.scaleLeft) * s, alignment: .trailing)                    .offset(x: knobs.scaleLeft * s)                left                    .frame(width: (knobs.scaleRight - x - gap) * s, alignment: .leading)                    .offset(x: (x + gap) * s)            }        }        .font(CottonFonts.serif(knobs.timesSize * s))        .monospacedDigit()        .lineLimit(1)        .foregroundStyle(PodcastMaterial.dial.colour)        .frame(height: knobs.times.height * s)        .offset(y: knobs.times.minY * s)    }    /// The glass as the card's own part: its tap opens the show's episodes,    /// as the card's does. What it says is said once, here.    private func glassPart(episode: RadioEpisode?, state: RadioDial.State, elapsed: TimeInterval, length: TimeInterval, s: CGFloat) -> some View {        let knobs = RadioFaceKnobs.self        let said = [card.text("title"), state == .rest ? nil : episode?.title,                    state == .rest || length <= 0 ? nil : TrackClock.said(elapsed) + " " + TrackClock.left(elapsed, of: length)]            .compactMap { $0 }        return Color.clear            .contentShape(Rectangle())            .frame(width: knobs.window.width * s, height: knobs.window.height * s)            .accessibilityElement(children: .ignore)            .accessibilityLabel(said.joined(separator: ShellLines.line("cards", "join")))            .accessibilityAddTraits(.isButton)            .accessibilityIdentifier("radio-glass")            .facePart(.title)            // Moved into place after it is tagged, so the region the deck            // reads is where it stands.            .at(knobs.window, s)    }    /// The chrome plate and the show's count of episodes typed on it.    private func plate(_ s: CGFloat) -> some View {        let knobs = RadioFaceKnobs.self        return ZStack(alignment: .topLeading) {            RadioPainted(name: "radio-plate").placed(knobs.plate, s)            if let count = card.text("count") {                Text(count)                    .font(CottonFonts.serif(knobs.plateSize * s))                    .monospacedDigit()                    .lineLimit(1)                    .minimumScaleFactor(0.5)                    .foregroundStyle(PodcastMaterial.cut.colour)                    .placed(knobs.plateCount, s, alignment: .center)                    .accessibilityIdentifier("radio-count")            }        }    }    // MARK: The knobs    /// VOL: the pointer at the volume's share of its sweep, turned round its    /// pivot by the finger, the volume turned with it.    private func volumeKnob(_ s: CGFloat) -> some View {        let knobs = RadioFaceKnobs.self        let shown = turned ?? volume        return RadioKnob(            angle: shown.map(RadioDial.pointer) ?? 0, label: ShellLines.line("faces", "radio.vol"),            labelRect: knobs.volumeLabel.offsetBy(dx: -knobs.volume.minX, dy: -knobs.volume.minY), s: s,            turn: { degrees, _ in                guard let turnVolume, let from = turned ?? volume else { return }                let to = min(1, max(0, from + degrees / (2 * knobs.sweep)))                turned = to                turnVolume(to)            },            lifted: { turned = nil })            .sized(knobs.volume, s, labelled: knobs.volumeLabel)            .accessibilityElement(children: .ignore)            .accessibilityLabel(ShellLines.line("faces", "radio.volume"))            .accessibilityValue(shown.map { Double($0).formatted(.percent.precision(.fractionLength(0))) } ?? "")            .accessibilityAdjustableAction { direction in                guard let turnVolume, let from = volume else { return }                turnVolume(min(1, max(0, from + (direction == .increment ? 0.1 : -0.1))))            }            .accessibilityIdentifier("radio-volume")            .facePart(.play)            .at(knobs.volume.union(knobs.volumeLabel), s)    }    /// TUNE: the pointer at the share played, a turn seeking — the needle    /// and the times following it — the player moved when the finger lifts.    private func tuneKnob(elapsed: TimeInterval, length: TimeInterval, s: CGFloat) -> some View {        let knobs = RadioFaceKnobs.self        let tunes = play.held && length > 0        return RadioKnob(            angle: RadioDial.pointer(RadioDial.share(elapsed, of: length)), label: ShellLines.line("faces", "radio.tune_label"),            labelRect: knobs.tuneLabel.offsetBy(dx: -knobs.tune.minX, dy: -knobs.tune.minY), s: s,            turn: { degrees, speed in                guard tunes else { return }                let from = tuning ?? play.elapsed                tuning = min(length, max(0, from + RadioDial.tuned(degrees, speed: speed)))            },            lifted: {                if let tuning { seek(tuning) }                tuning = nil            })            .sized(knobs.tune, s, labelled: knobs.tuneLabel)            .accessibilityElement(children: .ignore)            .accessibilityLabel(ShellLines.line("faces", "radio.tune"))            .accessibilityValue(tunes ? TrackClock.said(elapsed) : "")            .accessibilityAdjustableAction { direction in                guard tunes else { return }                seek(min(length, max(0, play.elapsed + (direction == .increment ? knobs.skip : -knobs.skip))))            }            .accessibilityIdentifier("radio-tune")            .facePart(.play)            .at(knobs.tune.union(knobs.tuneLabel), s)    }    // MARK: The keys and the button    /// A key: raised, or pressed while touched; lifted on it, it jumps.    private func key(_ key: RadioKey, s: CGFloat) -> some View {        let knobs = RadioFaceKnobs.self        let frame = key == .back ? knobs.keyBack : knobs.keyOn        let ink = (key == .back ? knobs.keyBackInk : knobs.keyOnInk).offsetBy(dx: -frame.minX, dy: -frame.minY)        let down = pressed == key        let side = key == .back ? "left" : "right"        let jumps = play.held        return ZStack(alignment: .topLeading) {            RadioPainted(name: down ? "radio-key-pressed-\(side)" : "radio-key-\(side)")                .frame(width: frame.width * s, height: frame.height * s)            RadioKeyInk(back: key == .back, seconds: Int(knobs.skip), s: s)                .frame(width: ink.width * s, height: ink.height * s)                .offset(x: ink.minX * s, y: (ink.minY + (down ? knobs.pressedSink : 0)) * s)        }        .frame(width: frame.width * s, height: frame.height * s, alignment: .topLeading)        .contentShape(Rectangle())        .gesture(            DragGesture(minimumDistance: 0)                .onChanged { touch in                    let inside = CGRect(origin: .zero, size: CGSize(width: frame.width * s, height: frame.height * s)).contains(touch.location)                    pressed = inside ? key : nil                }                .onEnded { touch in                    let inside = CGRect(origin: .zero, size: CGSize(width: frame.width * s, height: frame.height * s)).contains(touch.location)                    pressed = nil                    if inside, jumps { jump(key) }                })        .accessibilityElement(children: .ignore)        .accessibilityLabel(ShellLines.line("faces", key == .back ? "radio.back" : "radio.forward", ["n": String(Int(knobs.skip))]))        .accessibilityAddTraits(.isButton)        .accessibilityAction { if jumps { jump(key) } }        .accessibilityIdentifier(key == .back ? "radio-back" : "radio-forward")        .facePart(.play)        .at(frame, s)    }    private func jump(_ key: RadioKey) {        let length = RadioDial.length(play, RadioDial.episode(card))        let by = key == .back ? -RadioFaceKnobs.skip : RadioFaceKnobs.skip        seek(min(length > 0 ? length : .infinity, max(0, play.elapsed + by)))    }    /// The round button: in while it plays, out at rest and paused; a tap    /// plays or pauses.    private func button(state: RadioDial.State, s: CGFloat) -> some View {        let knobs = RadioFaceKnobs.self        return RadioPainted(name: state == .playing ? "radio-button-in" : "radio-button-out")            .frame(width: knobs.button.width * s, height: knobs.button.height * s)            .contentShape(Circle())            .onTapGesture { toggle?() }            .accessibilityElement(children: .ignore)            .accessibilityLabel(ShellLines.line("faces", state == .playing ? "media.pause" : "media.play"))            .accessibilityValue(RadioDial.episode(card)?.title ?? card.text("title") ?? "")            .accessibilityAddTraits(.isButton)            .accessibilityAction { toggle?() }            .accessibilityIdentifier("radio-button")            .facePart(.play)            .at(knobs.button, s)    }}/// One knob: the painted knob, its pointer turned to `angle` round the/// shared pivot, the engraving under it; a finger turning round the pivot/// turns it by the angle swept and the speed it swept it at.private struct RadioKnob: View {    let angle: Double    let label: String    /// Where the engraving stands, from the knob's corner, in the paintings' pixels.    let labelRect: CGRect    let s: CGFloat    let turn: (_ degrees: Double, _ speed: Double) -> Void    let lifted: () -> Void    @State private var last: (angle: Double, at: Date)?    var body: some View {        let knobs = RadioFaceKnobs.self        let size = CGSize(width: knobs.volume.width * s, height: knobs.volume.height * s)        let pivot = CGPoint(x: size.width / 2, y: size.height / 2)        ZStack(alignment: .topLeading) {            RadioPainted(name: "radio-knob")                .frame(width: size.width, height: size.height)            RadioPainted(name: "radio-knob-pointer")                .frame(width: size.width, height: size.height)                .rotationEffect(.degrees(angle), anchor: .center)            Text(label)                .font(CottonFonts.serif(knobs.engravingSize * s))                .tracking(knobs.engravingTracking * s)                .lineLimit(1)                .minimumScaleFactor(0.6)                .foregroundStyle(PodcastMaterial.engraving.colour)                // Its line taller than the painting's rectangle, centred on                // it, so the engraving is never shrunk to the rectangle.                .frame(width: labelRect.width * s, height: labelRect.height * 2 * s)                .offset(x: labelRect.minX * s, y: (labelRect.minY - labelRect.height / 2) * s)        }        .frame(width: size.width, height: size.height, alignment: .topLeading)        .contentShape(Circle())        .gesture(            DragGesture(minimumDistance: 0)                .onChanged { touch in                    let now = RadioDial.angle(of: touch.location, round: pivot)                    if let last {                        let by = RadioDial.turn(from: last.angle, to: now)                        let seconds = max(1.0 / 120, touch.time.timeIntervalSince(last.at))                        turn(by, abs(by) / seconds)                    }                    last = (now, touch.time)                }                .onEnded { _ in                    last = nil                    lifted()                })    }}/// A key's ink: the curved arrow over the seconds it jumps, cut into the ivory.private struct RadioKeyInk: View {    let back: Bool    let seconds: Int    let s: CGFloat    var body: some View {        let knobs = RadioFaceKnobs.self        VStack(spacing: 0) {            RadioArrow(back: back)                .stroke(PodcastMaterial.cut.colour, style: StrokeStyle(lineWidth: knobs.arrowStroke * s, lineCap: .round, lineJoin: .round))                .frame(maxWidth: .infinity, maxHeight: .infinity)            Text(String(seconds))                .font(CottonFonts.serif(knobs.keySize * s))                .monospacedDigit()                .lineLimit(1)                .foregroundStyle(PodcastMaterial.cut.colour)                .frame(maxWidth: .infinity, maxHeight: .infinity)        }        .allowsHitTesting(false)    }}/// The curved arrow over a key's seconds: an arc over the top, its head at/// the left end going back, at the right end going on.struct RadioArrow: Shape {    let back: Bool    func path(in rect: CGRect) -> Path {        let width = rect.width * 0.5, rise = rect.height * 0.5        let left = CGPoint(x: rect.midX - width / 2, y: rect.maxY - rect.height * 0.12)        let right = CGPoint(x: rect.midX + width / 2, y: left.y)        let top = CGPoint(x: rect.midX, y: left.y - rise * 2)        var path = Path()        path.move(to: left)        path.addQuadCurve(to: right, control: top)        // The head at the end it points to, along the curve's last run.        let tip = back ? left : right        let toward = CGPoint(x: tip.x - top.x, y: tip.y - top.y)        let length = max(0.001, hypot(toward.x, toward.y))        let unit = CGPoint(x: toward.x / length, y: toward.y / length)        let head = rect.height * 0.32        for side in [-1.0, 1.0] {            let spread = 0.55 * side            let dx = -(unit.x * cos(spread) - unit.y * sin(spread)) * head            let dy = -(unit.x * sin(spread) + unit.y * cos(spread)) * head            path.move(to: tip)            path.addLine(to: CGPoint(x: tip.x + dx, y: tip.y + dy))        }        return path    }}/// The scale printed across the glass: its rule, a tick at every space and/// a long one at every fifth, rising from the rule.private struct RadioScale: View {    var body: some View {        Canvas { context, size in            let knobs = RadioFaceKnobs.self            let s = size.height / knobs.longTick            var path = Path()            path.move(to: CGPoint(x: 0, y: size.height))            path.addLine(to: CGPoint(x: size.width, y: size.height))            for at in 0...knobs.ticks {                let x = size.width * CGFloat(at) / CGFloat(knobs.ticks)                let tall = at % knobs.longEvery == 0 ? knobs.longTick : knobs.tick                path.move(to: CGPoint(x: x, y: size.height))                path.addLine(to: CGPoint(x: x, y: size.height - tall * s))            }            context.stroke(path, with: .color(PodcastMaterial.dial.colour), lineWidth: knobs.tickStroke * s)        }        .allowsHitTesting(false)        .accessibilityHidden(true)    }}/// One of the radio's paintings, stretched to its frame; nothing where the/// build carries no pictures.private struct RadioPainted: View {    let name: String    var body: some View {        if let image = CottonMedia.image(name) {            image.resizable().interpolation(.high).accessibilityHidden(true)        }    }}private extension View {    /// This view laid at `rect` of the cabinet box, in its pixels, scaled by `s`.    func placed(_ rect: CGRect, _ s: CGFloat, alignment: Alignment = .center) -> some View {        frame(width: rect.width * s, height: rect.height * s, alignment: alignment)            .offset(x: rect.minX * s, y: rect.minY * s)    }    /// This view moved to `rect`'s corner of the cabinet box: last, after a    /// control is tagged (`facePart`), so the region the deck reads for it    /// is where it is drawn.    func at(_ rect: CGRect, _ s: CGFloat) -> some View {        offset(x: rect.minX * s, y: rect.minY * s)    }    /// A knob sized to `rect`, its touch reaching down over its engraving    /// (`labelled`), so the whole of it is the control; laid with `at`.    func sized(_ rect: CGRect, _ s: CGFloat, labelled: CGRect) -> some View {        let whole = rect.union(labelled)        return frame(width: rect.width * s, height: rect.height * s, alignment: .topLeading)            .frame(width: whole.width * s, height: whole.height * s, alignment: .topLeading)    }}/// The radio face, beside the album a show wore before it, and the shows it/// is reviewed in: under the player the app installs (`faceTrackPlayer`),/// else at rest. Each specimen names the player's word it is reviewed under/// (`Specimen.play`): at rest, playing, paused.public enum PodcastRadioFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .formicaCounter    public static let face = Face(id: "podcast.radio", specimens: [        Specimen("rest", hour, picture: "podcast-history"),        Specimen("playing", hour, picture: "podcast-history", play: TrackPlay(held: true, playing: true, elapsed: 1120, duration: 3756)),        Specimen("paused", hour, picture: "podcast-history", play: TrackPlay(held: true, playing: false, elapsed: 2470, duration: 3756)),        Specimen("long name, near the end", gazette, picture: "podcast-gazette", play: TrackPlay(held: true, playing: true, elapsed: 5100, duration: 5340)),        Specimen("no artwork, no episodes", quiet),    ]) { card, photo, _ in        TrackPlaying(card: card) { player in            RadioFace(                card: card, photo: photo, play: player.play, toggle: player.toggle, seek: player.seek, volume: player.volume,                turnVolume: player.turnVolume)        }    }    static func episode(_ title: String, _ seconds: Double) -> RecordValue {        .object(["title": .text(title), "duration": .number(seconds)])    }    /// An invented history show, its newest episode an hour long.    public static let hour = DeckCard(face: "podcast.radio", corner: nil, pressing: false, pace: nil, plate: nil, fields: [        "title": .text("The History Hour"),        "subtitle": .text("Example Broadcasting"),        "count": .text("128"),        "episode": episode("128. The Distant Coast (Part 3)", 3756),    ])    /// A long show name and a long episode title, near the episode's end.    public static let gazette = DeckCard(face: "podcast.radio", corner: nil, pressing: false, pace: nil, plate: nil, fields: [        "title": .text("The Evening Gazette of Small Inventions and Forgotten Machines"),        "count": .text("1,204"),        "episode": episode("1204. The Clockmaker Who Built a Lighthouse Out of Spare Parts and Patience", 5340),    ])    /// A show the object has read no episodes of yet.    public static let quiet = DeckCard(face: "podcast.radio", corner: nil, pressing: false, pace: nil, plate: nil, fields: [        "title": .text("Letters from the Valley"),        "count": .text("0"),    ])}