Cotton code
488 lines · 21.4 KB · SwiftRaw
// A CALL IN PROGRESS at the DESK TELEPHONE (Cotton Calling, 13 Nov 2026):// the whole screen is the calling desk's oxblood leather under the desk lamp// (`FaceGround.leatherDesk`), and on it////   THE OTHER PERSON, large, as a photograph standing in its white border a//   hair askew: their picture, or, while they send video, their video in//   its place; with no picture, their initials typed on the print. While//   this phone's camera is on, its own picture is a small print tucked over//   the big one's corner.//   THEIR NAME tooled in gilt on the leather under it, and the call's state//   under that ("Ringing…", "02:14", "Call ended"), as the caller resolved//   them.//   THE TELEPHONE standing at the foot, seen nearly from the front: the//   handset LIFTED off the cradle while the call is live, its coiled cord//   running off the foot of the screen to the hand that holds it, and//   REPLACED on the cradle once it is over. Its four broad line keys are the//   call's controls: mute, speaker, camera, and the red key that ends the//   call. A key that is on glows, its lamp lit behind it.//// The telephone is painted (`telephone-front`, `telephone-lifted`, by// `scripts/paint-telephone.py`); each key's glyph and glow are drawn live on// the key's face, where the painting's knobs say it lies. This is no deck// card: it stands over the call's state (`CallTelephoneState`), and its acts// are the caller's (`CallTelephoneActs`). Each key says its own words// (`calling` `controls.*`).import CottonPaperimport CottonValuesimport SwiftUI/// What the in-call telephone shows, every word already resolved by the/// caller.public struct CallTelephoneState: Sendable, Equatable {    /// Who the call is with.    public var name: String    /// The call's state in words: "Ringing…", "Connecting…", "02:14", "Call ended".    public var status: String    /// The call is live: the handset is lifted.    public var live: Bool    public var muted: Bool    public var speaker: Bool    /// This phone's camera is on.    public var video: Bool    /// The other side is sending video: their video stands large.    public var remoteVideo: Bool    public init(name: String, status: String, live: Bool, muted: Bool, speaker: Bool, video: Bool, remoteVideo: Bool) {        self.name = name        self.status = status        self.live = live        self.muted = muted        self.speaker = speaker        self.video = video        self.remoteVideo = remoteVideo    }}/// What the telephone's keys do: the caller's acts.public struct CallTelephoneActs {    public var mute: () -> Void    public var speaker: () -> Void    public var video: () -> Void    public var end: () -> Void    public init(mute: @escaping () -> Void, speaker: @escaping () -> Void, video: @escaping () -> Void, end: @escaping () -> Void) {        self.mute = mute        self.speaker = speaker        self.video = video        self.end = end    }    /// Keys that do nothing: the face reviewed alone.    public static var none: CallTelephoneActs { CallTelephoneActs(mute: {}, speaker: {}, video: {}, end: {}) }}enum CallTelephoneKnobs {    // THE TELEPHONE, as painted (`telephone-front` and `telephone-lifted`,    // one frame): its width over its height, and each line key's face as    // its four corners clockwise from the upper left, as shares of the    // painting (y down): mute, speaker, camera, end.    static let aspect: CGFloat = 1.1825    static let keys: [[CGPoint]] = [        [CGPoint(x: 0.2967, y: 0.7298), CGPoint(x: 0.3808, y: 0.739), CGPoint(x: 0.3762, y: 0.7821), CGPoint(x: 0.2919, y: 0.7727)],        [CGPoint(x: 0.4124, y: 0.7425), CGPoint(x: 0.4971, y: 0.7518), CGPoint(x: 0.4929, y: 0.7951), CGPoint(x: 0.408, y: 0.7856)],        [CGPoint(x: 0.529, y: 0.7553), CGPoint(x: 0.6143, y: 0.7646), CGPoint(x: 0.6104, y: 0.8082), CGPoint(x: 0.5249, y: 0.7986)],        [CGPoint(x: 0.6464, y: 0.7682), CGPoint(x: 0.7322, y: 0.7776), CGPoint(x: 0.7288, y: 0.8213), CGPoint(x: 0.6426, y: 0.8117)],    ]    /// The telephone's width as a share of the screen's, and the most of    /// the screen's height it may take.    static let phoneWidth: CGFloat = 1.12    static let phoneHeight: CGFloat = 0.46    /// The share of the painting's height that is bare leather above the    /// telephone's horns (the replaced handset's top stands at 0.12).    static let phoneBare: CGFloat = 0.1    /// A key's glyph, as a share of its face's height.    static let glyph: CGFloat = 0.78    /// The least a key's tap reaches, in points.    static let reach: CGFloat = 46    // THE PHOTOGRAPH: its width over its height, its white border as a    // share of its width, how far askew it stands, the most of the screen's    // width it takes; the small print of this phone's own picture, as a    // share of the big one's width, and its turn.    static let printAspect: CGFloat = 0.8    static let border: CGFloat = 0.045    static let printTurn: Double = -1.8    static let printWidth: CGFloat = 0.8    static let ownPrint: CGFloat = 0.34    static let ownTurn: Double = 4    // THE WORDS on the leather, as shares of the screen's width: the name's    // size and the state's, and the gaps round them.    static let nameSize: CGFloat = 0.082    static let statusSize: CGFloat = 0.046    static let gap: CGFloat = 0.035}/// One of the telephone's line keys.public enum CallTelephoneKey: Int, CaseIterable, Sendable {    case mute, speaker, video, end    /// The glyph moulded into the key, by the call's state.    public func glyph(_ state: CallTelephoneState) -> String {        switch self {        case .mute: state.muted ? "mic.slash.fill" : "mic.fill"        case .speaker: "speaker.wave.2.fill"        case .video: state.video ? "video.fill" : "video.slash.fill"        case .end: "phone.down.fill"        }    }    /// The key is on: its lamp glows behind it. The red key is never on.    public func lit(_ state: CallTelephoneState) -> Bool {        switch self {        case .mute: state.muted        case .speaker: state.speaker        case .video: state.video        case .end: false        }    }    /// What the key says to VoiceOver, in the calling set's words: the mute    /// key says what a tap does (mute, or unmute while muted); the speaker    /// and camera keys say themselves, on or not (`isSelected`).    public func words(_ state: CallTelephoneState) -> String {        switch self {        case .mute: ShellLines.line("calling", state.muted ? "controls.unmute" : "controls.mute")        case .speaker: ShellLines.line("calling", "controls.speaker")        case .video: ShellLines.line("calling", "controls.video")        case .end: ShellLines.line("calling", "controls.end")        }    }    /// The key says it is on (`isSelected`): the speaker and the camera.    public func selected(_ state: CallTelephoneState) -> Bool {        self == .speaker || self == .video ? lit(state) : false    }    /// The key's face as painted.    public var painted: PaintedKey { PaintedKey(corners: CallTelephoneKnobs.keys[rawValue]) }    /// The key's face in a telephone drawn `size` points: its corners,    /// clockwise from the upper left.    public func face(in size: CGSize) -> [CGPoint] { painted.face(in: size) }    /// The map from a box `box` points onto the key's face.    public func onFace(_ box: CGSize, in size: CGSize) -> CGAffineTransform { painted.onFace(box, in: size) }    /// The box a key's glyph is drawn in before it is laid on its face.    public func box(in size: CGSize) -> CGSize { painted.box(in: size) }}/// A key's face on a painted telephone, its four corners clockwise from the/// upper left as shares of the painting (y down): where a glyph moulded/// into it is laid, and where its glow shines through.public struct PaintedKey: Equatable, Sendable {    public let corners: [CGPoint]    public init(corners: [CGPoint]) {        self.corners = corners    }    /// Its corners in a painting drawn `size` points.    public func face(in size: CGSize) -> [CGPoint] {        corners.map { CGPoint(x: $0.x * size.width, y: $0.y * size.height) }    }    /// Its outline in a painting drawn `size` points.    public func outline(in size: CGSize) -> Path {        Path { path in            path.addLines(face(in: size))            path.closeSubpath()        }    }    /// The map from a box `box` points (its upper left at the origin) onto    /// the face: the face's upper edge along the box's top, its left edge    /// down the box's left.    public func onFace(_ box: CGSize, in size: CGSize) -> CGAffineTransform {        let c = face(in: size)        let across = CGPoint(x: c[1].x - c[0].x, y: c[1].y - c[0].y)        let down = CGPoint(x: c[3].x - c[0].x, y: c[3].y - c[0].y)        return CGAffineTransform(a: across.x / box.width, b: across.y / box.width, c: down.x / box.height, d: down.y / box.height,                                 tx: c[0].x, ty: c[0].y)    }    /// The box a glyph is drawn in before it is laid on the face: the face's    /// own width and height.    public func box(in size: CGSize) -> CGSize {        let c = face(in: size)        return CGSize(width: hypot(c[1].x - c[0].x, c[1].y - c[0].y), height: hypot(c[3].x - c[0].x, c[3].y - c[0].y))    }}/// A glyph moulded into a painted key: drawn in the face's box and laid on/// it, under its ink.struct MouldedGlyph: View {    let symbol: String    let key: PaintedKey    let size: CGSize    let share: CGFloat    let ink: Color    let multiply: Bool    var body: some View {        let box = key.box(in: size)        Image(systemName: symbol)            .font(CottonFonts.symbol(box.height * share, weight: .semibold))            .foregroundStyle(ink)            .frame(width: box.width, height: box.height)            .transformEffect(key.onFace(box, in: size))            .blendMode(multiply ? .multiply : .normal)            .allowsHitTesting(false)            .accessibilityHidden(true)    }}public struct CallTelephoneFace: View {    let state: CallTelephoneState    let picture: Image?    let remote: AnyView?    let local: AnyView?    let acts: CallTelephoneActs    public init(state: CallTelephoneState, picture: Image?, remote: AnyView?, local: AnyView?, acts: CallTelephoneActs) {        self.state = state        self.picture = picture        self.remote = remote        self.local = local        self.acts = acts    }    public var body: some View {        let knobs = CallTelephoneKnobs.self        ZStack {            FaceGroundSurface(.leatherDesk)                .ignoresSafeArea()            GeometryReader { screen in                let w = screen.size.width                let phoneW = min(w * knobs.phoneWidth, screen.size.height * knobs.phoneHeight * knobs.aspect)                let phone = CGSize(width: phoneW, height: phoneW / knobs.aspect)                // The photograph and the words stand in the room above the                // telephone, whose painting is bare above its horns.                let above = screen.size.height - phone.height * (1 - knobs.phoneBare)                let words = (knobs.nameSize * 1.3 + knobs.statusSize * 1.4 + knobs.gap * 4) * w                let printW = max(60, min(w * knobs.printWidth, (above - words) * knobs.printAspect))                ZStack(alignment: .top) {                    VStack(spacing: 0) {                        Spacer(minLength: knobs.gap * w)                        CallPrint(state: state, picture: picture, remote: remote, local: local, width: printW)                            .frame(width: printW, height: printW / knobs.printAspect)                        VStack(spacing: knobs.gap * 0.3 * w) {                            Text(verbatim: state.name)                                .font(CottonFonts.caslon(knobs.nameSize * w))                                .foregroundStyle(CallingMaterial.gilt.colour)                                .lineLimit(1)                                .minimumScaleFactor(0.5)                                .accessibilityIdentifier("call-telephone-name")                            Text(verbatim: state.status)                                .font(CottonFonts.type(knobs.statusSize * w))                                .foregroundStyle(CallingMaterial.gilt.colour.opacity(0.82))                                .lineLimit(1)                                .monospacedDigit()                                .accessibilityIdentifier("call-telephone-status")                        }                        .shadow(color: .black.opacity(0.55), radius: 0.5, x: 0, y: -0.6)                        .padding(.horizontal, knobs.gap * w)                        .padding(.top, knobs.gap * 1.2 * w)                        Spacer(minLength: knobs.gap * w)                    }                    .frame(width: w, height: max(0, above))                    DeskTelephone(state: state, acts: acts, size: phone)                        .frame(width: phone.width, height: phone.height)                        .frame(width: w, height: screen.size.height, alignment: .bottom)                }                .frame(width: w, height: screen.size.height, alignment: .top)            }            .ignoresSafeArea(edges: .bottom)        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("call-telephone")    }}/// The other person's photograph in its white border, or their video in its/// place; this phone's own picture tucked over its corner while its camera/// is on.private struct CallPrint: View {    let state: CallTelephoneState    let picture: Image?    let remote: AnyView?    let local: AnyView?    let width: CGFloat    var body: some View {        let knobs = CallTelephoneKnobs.self        let border = knobs.border * width        ZStack(alignment: .bottomTrailing) {            ZStack {                CallingMaterial.border.colour                Group {                    if state.remoteVideo, let remote {                        remote                    } else if let picture {                        picture.resizable().scaledToFill()                    } else {                        ZStack {                            CallingMaterial.card.colour                            Text(verbatim: CallTelephoneSetting.initials(state.name))                                .font(CottonFonts.caslon(width * 0.3))                                .foregroundStyle(CallingMaterial.cardInk.colour.opacity(0.75))                                .accessibilityHidden(true)                        }                    }                }                .frame(width: width - border * 2, height: width / knobs.printAspect - border * 2)                .clipped()                .accessibilityIdentifier(state.remoteVideo && remote != nil ? "call-telephone-remote" : "call-telephone-picture")            }            .frame(width: width, height: width / knobs.printAspect)            .rotationEffect(.degrees(knobs.printTurn))            .shadow(color: .black.opacity(0.45), radius: 8, x: 2, y: 6)            if state.video, let local {                let small = width * knobs.ownPrint                ZStack {                    CallingMaterial.border.colour                    local                        .frame(width: small - border, height: small / 0.75 - border)                        .clipped()                        .accessibilityIdentifier("call-telephone-local")                }                .frame(width: small, height: small / 0.75)                .rotationEffect(.degrees(knobs.ownTurn))                .shadow(color: .black.opacity(0.4), radius: 5, x: 1, y: 4)                .offset(x: small * 0.18, y: small * 0.14)            }        }    }}/// How the in-call telephone says what it draws.public enum CallTelephoneSetting {    /// The telephone's painting: the handset lifted while the call is live,    /// replaced on the cradle once it is over.    public static func painting(_ state: CallTelephoneState) -> String {        state.live ? "telephone-lifted" : "telephone-front"    }    /// The initials typed on a print that has no picture: the first letter    /// of the name's first word and of its last.    public static func initials(_ name: String) -> String {        let words = name.split(whereSeparator: \.isWhitespace).filter { $0.first?.isLetter ?? false }        let letters = [words.first, words.count > 1 ? words.last : nil].compactMap { $0?.first }        return String(letters).uppercased()    }}/// The desk telephone and its four line keys.private struct DeskTelephone: View {    let state: CallTelephoneState    let acts: CallTelephoneActs    let size: CGSize    var body: some View {        ZStack(alignment: .topLeading) {            if let painted = CottonMedia.image(CallTelephoneSetting.painting(state), scale: 3) {                painted.resizable().interpolation(.high)                    .frame(width: size.width, height: size.height)                    .accessibilityHidden(true)            } else {                StandInTelephone(size: size)            }            ForEach(CallTelephoneKey.allCases, id: \.self) { key in                LineKey(key: key, state: state, size: size, act: act(key))            }        }        .frame(width: size.width, height: size.height, alignment: .topLeading)    }    private func act(_ key: CallTelephoneKey) -> () -> Void {        switch key {        case .mute: acts.mute        case .speaker: acts.speaker        case .video: acts.video        case .end: acts.end        }    }}/// One line key: its glow when on, its glyph on its face, and its tap.private struct LineKey: View {    let key: CallTelephoneKey    let state: CallTelephoneState    let size: CGSize    let act: () -> Void    var body: some View {        let knobs = CallTelephoneKnobs.self        let lit = key.lit(state)        let quad = key.painted.outline(in: size)        let bounds = quad.boundingRect        let reach = CGSize(width: max(bounds.width, knobs.reach), height: max(bounds.height, knobs.reach))        ZStack(alignment: .topLeading) {            // The lamp behind a key that is on, shining through it: the key            // tinted amber, and its light spilling round it.            if lit {                quad.fill(CallingMaterial.glow.colour)                    .blendMode(.multiply)                    .opacity(0.8)                    .allowsHitTesting(false)                quad.fill(CallingMaterial.glow.colour)                    .blur(radius: bounds.height * 0.35)                    .blendMode(.screen)                    .opacity(0.7)                    .allowsHitTesting(false)            }            MouldedGlyph(symbol: key.glyph(state), key: key.painted, size: size, share: knobs.glyph,                         ink: key == .end ? CallingMaterial.keyInkOnRed.colour : CallingMaterial.keyInk.colour,                         multiply: key != .end)            Button(action: act) {                Color.clear                    .frame(width: reach.width, height: reach.height)                    .contentShape(Rectangle())            }            .buttonStyle(.plain)            .accessibilityLabel(Text(verbatim: key.words(state)))            .accessibilityAddTraits(key.selected(state) ? .isSelected : [])            .accessibilityIdentifier("call-telephone-\(String(describing: key))")            .offset(x: bounds.midX - reach.width / 2, y: bounds.midY - reach.height / 2)        }        .frame(width: size.width, height: size.height, alignment: .topLeading)    }}/// The telephone where this build carries no pictures: its cream wedge and/// its keys, flat.private struct StandInTelephone: View {    let size: CGSize    var body: some View {        Canvas { context, room in            let body = CGRect(x: room.width * 0.22, y: room.height * 0.2, width: room.width * 0.56, height: room.height * 0.68)            context.fill(Path(roundedRect: body, cornerRadius: room.width * 0.03), with: .color(CallingMaterial.cream.colour))            for (i, corners) in CallTelephoneKnobs.keys.enumerated() {                let key = Path { path in                    path.addLines(corners.map { CGPoint(x: $0.x * room.width, y: $0.y * room.height) })                    path.closeSubpath()                }                context.fill(key, with: .color(i == 3 ? CallingMaterial.ribbonRed.colour : CallingMaterial.slip.colour))            }        }        .frame(width: size.width, height: size.height)        .accessibilityHidden(true)    }}/// The in-call telephone in the states it is reviewed in: invented people/// only.public enum CallTelephoneCatalogue {    /// Ringing out: the handset lifted, nothing on.    public static let ringing = CallTelephoneState(name: "Mira Kaul", status: "Ringing…", live: true, muted: false, speaker: false, video: false, remoteVideo: false)    /// Talking, muted and on the speaker.    public static let talking = CallTelephoneState(name: "Arjun Rao", status: "02:14", live: true, muted: true, speaker: true, video: false, remoteVideo: false)    /// A video call: both sides send video.    public static let video = CallTelephoneState(name: "Mira Kaul", status: "12:40", live: true, muted: false, speaker: true, video: true, remoteVideo: true)    /// Over: the handset back on the cradle.    public static let ended = CallTelephoneState(name: "Arundhati Venkatalakshmi Krishnamurthy", status: "Call ended", live: false, muted: false, speaker: false, video: false, remoteVideo: false)    public static let states = [("ringing", ringing), ("talking", talking), ("video", video), ("ended", ended)]}