Cotton code
462 lines · 20.9 KB · SwiftRaw
// The EPISODE as a LOBBY CARD, pinned on the Picture House's curtain-red// velvet under its one warm house light (`FaceGround.velvet`; the// coordinator's look for Cotton Cinemas, 4 Nov 2026, after the pictures// `cinemas13-house/episode-a`, `episode-b`, `episode-c` and `continue-a`).// The landscape card with its still aperture, its brass corners and blank// cream caption, its shadow, and the progress strip and ticket stub it// shares with the film's one-sheet (`CinemaParts.swift`) are PAINTED// (`Media.xcassets`, imported by `scripts/import-cinemas-materials.py`),// each laid where the materials' `layout.json` (`cinemas14-materials`,// `lobby-card`) places it in the 1422 x 917 card's box, scaled by the drawn// width over 1422. The face draws live only what the card decides:////   the STILL is the episode's own picture, laid behind the card's//   aperture; an episode kept without one shows the velvet through a dark//   field, its number typed large on it in the cream.//   the CAPTION says the episode ("S2 E5 · The Long Night": the core's mark//   for its season and number, then its title) in the typewriter face, on//   one line taken down until it fits, then on two, past the least size cut.//   its LENGTH ("48 min", from its minutes) at the caption's foot, left.//   the PROGRESS STRIP across the caption's foot, between the length and//   the place, for an episode part way through, filled as far as the resume//   point is of its length, its place typed at the right ("24:00 of//   48:00"); a watched one's full, its place at the end (`episode-c`).//   the STUB at the card's upper right corner once watched: stamped//   WATCHED, the day typed on its rule.//// Tagged: the still (`picture`), the caption (`title`), the strip// (`state`), the stub (`done`). Stepped by a tap, it cuts. Print on an// object scales with the object, never with Dynamic Type.//// What the card holds (the slots the Cinemas kit fills): `photo` (the// still), `title`, `subtitle` (the season and number, said by the core's// `field.episode_mark`), `number` (the episode's number, the figure typed// on a stillless card), `limit` (the length, minutes), `used` (the resume// point, seconds), `state` (stored: `needs_mac` wears the stub stamped// CONVERTING; `watched` wears the stub and fills the// strip), `date` (watched on). Every word is the core's or a line: the face// only sets them.import CottonPaperimport CottonValuesimport CoreTextimport SwiftUIenum EpisodeLobbyFaceKnobs {    // THE CARD'S BOX every placement is in, in the paintings' pixels    // (`layout.json`'s `lobby-card`): the face draws the card at most    // `widest` points wide (the composite's `lobbyRect`, 900 of the proof's    // 1024, at three pixels a point), and every place below is scaled by the    // drawn width over the box's.    static let box = CGSize(width: 1422, height: 917)    static let widest: CGFloat = 300    /// The most of the card's room the card and its shadow take.    static let fillWidth: CGFloat = 0.96    static let fillHeight: CGFloat = 0.94    /// Its shadow, 64 pixels past it on every side (`shadowOffset`).    static let shadow = CGRect(x: -64, y: -64, width: 1550, height: 1045)    // THE STILL: the card's aperture and its rounding (`stillAperture`,    // `apertureRadius`), and a still laid a hair past it, under the border.    static let aperture = CGRect(x: 31, y: 36, width: 1360, height: 682)    static let apertureRadius: CGFloat = 30    static let stillBleed: CGFloat = 4    /// Where no still is kept: how strongly the dark is laid over the    /// velvet, and the episode's number typed on it, its size.    static let screenStrength: Double = 0.5    static let numeralSize: CGFloat = 340    // THE CAPTION (`captionLiveTypeRect`): its words' size (the composite's,    // measured: 22 letters across 384 of its pixels) and the least they are    // taken down to, the step, and the step from one baseline to the next    // where it takes two lines.    static let caption = CGRect(x: 90, y: 735, width: 1242, height: 80)    static let captionSize: CGFloat = 46    static let captionLeast: CGFloat = 34    static let captionShrink: CGFloat = 0.94    static let captionStep: CGFloat = 1.05    // THE FOOT: the length set from the left (`durationLiveTypeRect`, its    // words beginning 23 pixels in, as the composite sets "48 min"), the    // place set to the right (`timeLiveTypeRect`, ending at the composite's    // 1300), both at the composite's size; the strip (`progressRect`) laid    // between them, kept `stripGap` clear of each.    static let foot = CGRect(x: 70, y: 810, width: 1280, height: 65)    static let lengthFrom: CGFloat = 93    static let placeTo: CGFloat = 1300    static let footSize: CGFloat = 31    static let progress = CGRect(x: 300, y: 835, width: 640, height: 14)    static let stripGap: CGFloat = 40    // THE STUB, at the card's upper right corner beside its brass (measured    // off `episode-c`: its left 70 of the card's hundred across, its width    // 29 of a hundred, its top at the card's edge), in the card's box.    static let stub = CGRect(x: 993, y: 10, width: 412, height: 261.4)}/// How the episode's lobby card is set.public enum EpisodeLobbySetting {    /// The episode is watched: its status, the value stored under its state.    public static func watched(_ card: DeckCard) -> Bool {        card.stored["state"] == "watched"    }    /// The caption's words: the core's mark for the season and number, then    /// the title, joined as the cards join words.    public static func caption(_ card: DeckCard) -> String? {        let title = card.text("title")?.split(whereSeparator: \.isWhitespace).joined(separator: " ")        let words = [card.text("subtitle"), title].compactMap { $0 }        return words.isEmpty ? nil : words.joined(separator: ShellLines.line("cards", "join"))    }    /// The caption set: on one line at its own size, taken down a step at a    /// time to the least; then on two balanced lines at the size the    /// caption's height allows, taken down again; past the least size the    /// second cut with an ellipsis. In the card's pixels.    public static func captionLines(_ card: DeckCard) -> (lines: [String], size: CGFloat) {        let knobs = EpisodeLobbyFaceKnobs.self        guard let words = caption(card) else { return ([], knobs.captionSize) }        let width = knobs.caption.width        var size = knobs.captionSize        while HighlightPassageSetting.wide(words, type(size)) > width, size * knobs.captionShrink >= knobs.captionLeast {            size *= knobs.captionShrink        }        if HighlightPassageSetting.wide(words, type(size)) <= width { return ([words], size) }        size = min(knobs.captionSize, knobs.caption.height / (2 * knobs.captionStep))        while HighlightPassageSetting.lines(words, font: type(size), width: width, limit: .max).count > 2,              size * knobs.captionShrink >= knobs.captionLeast {            size *= knobs.captionShrink        }        return (BookHardbackSetting.balanced(words, font: type(size), width: width, limit: 2), size)    }    /// The episode's length said from its minutes ("48 min", "1 h 05"), as    /// a film's is; nil, none kept.    public static func length(_ card: DeckCard) -> String? {        FilmPosterSetting.length(card)    }    /// How far the strip is filled, nought to one: a watched episode's    /// whole; else the resume point of its length, for one part way    /// through; nil, no strip.    public static func share(_ card: DeckCard) -> Double? {        if watched(card) { return 1 }        guard let at = card.number("used"), at > 0, let minutes = card.number("limit"), minutes > 0 else { return nil }        return min(1, at / (minutes * 60))    }    /// The place typed at the strip's right ("24:00 of 48:00"): the resume    /// point of the length, a watched episode's at its end; nil where the    /// length or the point is not kept.    public static func place(_ card: DeckCard) -> String? {        guard let minutes = card.number("limit"), minutes > 0 else { return nil }        let whole = minutes * 60        let at: Double        if watched(card) {            at = whole        } else {            guard let used = card.number("used"), used > 0 else { return nil }            at = min(used, whole)        }        return ShellLines.line("cards", "film.position", ["at": clock(at), "of": clock(whole)])    }    /// Seconds on a player's clock: "24:00", "5:30", "1:52:00".    public static func clock(_ seconds: Double) -> String {        let whole = Int(seconds.rounded())        let (hours, minutes, rest) = (whole / 3600, whole / 60 % 60, whole % 60)        func two(_ n: Int) -> String { n < 10 ? "0\(n)" : "\(n)" }        return hours > 0 ? "\(hours):\(two(minutes)):\(two(rest))" : "\(whole / 60):\(two(rest))"    }    /// The stub's stamp and the day it is typed with: CONVERTING, no day,    /// while the Mac converts it (as a film's, `FilmPosterSetting`); once    /// watched, WATCHED and the day; nil otherwise.    public static func stub(_ card: DeckCard) -> (stamp: String, day: String?)? {        if FilmPosterSetting.converting(card) { return (ShellLines.line("cards", "film.stub_converting").uppercased(), nil) }        guard watched(card) else { return nil }        return (ShellLines.line("cards", "film.stub").uppercased(), card.dated.map(DayStamp.of))    }    /// The episode's number, the figure a stillless card is typed with; nil,    /// none kept.    public static func numeral(_ card: DeckCard) -> String? {        guard let number = card.number("number"), number > 0 else { return nil }        return "\(Int(number.rounded()))"    }    /// The typewriter face as CoreText measures it.    static func type(_ size: CGFloat) -> CTFont {        _ = CottonFonts.type(1)        return CTFontCreateWithName(CottonFonts.typeFace as CFString, max(1, size), nil)    }}public struct EpisodeLobbyFace<Still: View>: View {    let card: DeckCard    /// The still laid behind the aperture; nil shows the dark field.    var still: Still?    public init(card: DeckCard, still: Still? = nil) {        self.card = card        self.still = still    }    public var body: some View {        let knobs = EpisodeLobbyFaceKnobs.self        let reach = knobs.shadow.union(knobs.stub)        GeometryReader { room in            let s = min(knobs.widest / knobs.box.width, room.size.width * knobs.fillWidth / reach.width,                        room.size.height * knobs.fillHeight / reach.height)            LobbyCard(card: card, still: still, s: s)                .frame(width: knobs.box.width * s, height: knobs.box.height * s, alignment: .topLeading)                .offset(x: (room.size.width - knobs.box.width * s) / 2,                        y: (room.size.height - reach.height * s) / 2 - reach.minY * s)                .frame(width: room.size.width, height: room.size.height, alignment: .topLeading)        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("episode-lobby")    }}/// The card in its box, scaled by `s`: its shadow, the still or the dark/// field, the card, the caption, its foot, the stub.private struct LobbyCard<Still: View>: View {    let card: DeckCard    let still: Still?    let s: CGFloat    var body: some View {        let knobs = EpisodeLobbyFaceKnobs.self        ZStack(alignment: .topLeading) {            CinemaPainted(name: "lobby-card-shadow").cinemaLaid(knobs.shadow, s)            if let still {                let bled = knobs.aperture.insetBy(dx: -knobs.stillBleed, dy: -knobs.stillBleed)                still                    .frame(width: bled.width * s, height: bled.height * s)                    .clipped()                    .accessibilityHidden(true)                    .offset(x: bled.minX * s, y: bled.minY * s)            } else {                DarkField(card: card, s: s)            }            CinemaPainted(name: "lobby-card").cinemaLaid(CGRect(origin: .zero, size: knobs.box), s)            StillPart(card: card, s: s)            Caption(card: card, s: s)            Foot(card: card, s: s)            if let stub = EpisodeLobbySetting.stub(card) {                CinemaStub(rect: knobs.stub, stamp: stub.stamp, day: stub.day, identifier: "episode-lobby-stub", s: s)            }        }        .frame(width: knobs.box.width * s, height: knobs.box.height * s, alignment: .topLeading)    }}/// The aperture as the card's part: the still, or the dark field.private struct StillPart: View {    let card: DeckCard    let s: CGFloat    var body: some View {        let knobs = EpisodeLobbyFaceKnobs.self        Color.clear            .contentShape(Rectangle())            .frame(width: knobs.aperture.width * s, height: knobs.aperture.height * s)            .accessibilityElement()            .accessibilityLabel(EpisodeLobbySetting.caption(card) ?? "")            .accessibilityIdentifier("episode-lobby-still")            .facePart(.picture)            // Moved into place after it is tagged, so the region the deck            // reads is where it stands.            .offset(x: knobs.aperture.minX * s, y: knobs.aperture.minY * s)    }}/// An episode kept without a still: the velvet in the aperture, the dark/// laid thin over it, its number typed large in the cream.private struct DarkField: View {    let card: DeckCard    let s: CGFloat    var body: some View {        let knobs = EpisodeLobbyFaceKnobs.self        let field = RoundedRectangle(cornerRadius: knobs.apertureRadius * s, style: .continuous)        ZStack {            // The velvet behind the card, its tile as the ground lays it            // (the house light laid once, by the ground), so the card's            // shadow does not stand in the aperture.            CinemasMaterial.velvet.colour                .overlay { CottonMedia.image(FaceGround.velvet.tile ?? "", scale: 3)?.resizable(resizingMode: .tile) }                .clipShape(field)            field.fill(CinemasMaterial.screen.colour.opacity(knobs.screenStrength))            if let numeral = EpisodeLobbySetting.numeral(card) {                Text(numeral)                    .font(CottonFonts.type(knobs.numeralSize * s))                    .foregroundStyle(CinemasMaterial.cream.colour)                    .lineLimit(1)                    .minimumScaleFactor(0.3)                    .accessibilityHidden(true)            }        }        .cinemaLaid(knobs.aperture, s)    }}/// The caption's words, centred on the cream.private struct Caption: View {    let card: DeckCard    let s: CGFloat    var body: some View {        let knobs = EpisodeLobbyFaceKnobs.self        let (lines, size) = EpisodeLobbySetting.captionLines(card)        VStack(spacing: 0) {            ForEach(Array(lines.enumerated()), id: \.offset) { _, line in                Text(line)                    .font(CottonFonts.type(size * s))                    .lineLimit(1)                    .fixedSize()                    .frame(height: size * knobs.captionStep * s)            }        }        .foregroundStyle(CinemasMaterial.ink.colour)        .frame(width: knobs.caption.width * s, height: knobs.caption.height * s)        .contentShape(Rectangle())        .accessibilityElement()        .accessibilityLabel(lines.joined(separator: " "))        .accessibilityAddTraits(.isHeader)        .accessibilityIdentifier("deck-title")        .facePart(.title)        .offset(x: knobs.caption.minX * s, y: knobs.caption.minY * s)    }}/// The caption's foot: the length at the left, the place at the right, the/// strip between them.private struct Foot: View {    let card: DeckCard    let s: CGFloat    var body: some View {        let knobs = EpisodeLobbyFaceKnobs.self        let length = EpisodeLobbySetting.length(card)        let place = EpisodeLobbySetting.place(card)        let font = EpisodeLobbySetting.type(knobs.footSize)        let lengthEnd = length.map { knobs.lengthFrom + HighlightPassageSetting.wide($0, font) } ?? knobs.lengthFrom        let placeStart = place.map { knobs.placeTo - HighlightPassageSetting.wide($0, font) } ?? knobs.placeTo        let from = max(knobs.progress.minX, lengthEnd + knobs.stripGap)        let to = min(knobs.progress.maxX, placeStart - knobs.stripGap)        ZStack(alignment: .topLeading) {            if let length {                typed(length, alignment: .leading)                    .accessibilityIdentifier("episode-lobby-length")                    .offset(x: knobs.lengthFrom * s, y: knobs.foot.minY * s)            }            if let share = EpisodeLobbySetting.share(card), to > from {                CinemaStrip(rect: CGRect(x: from, y: knobs.progress.minY, width: to - from, height: knobs.progress.height),                            share: share, said: place ?? share.formatted(.percent.precision(.fractionLength(0))),                            identifier: "episode-lobby-progress", s: s)            }            if let place {                typed(place, alignment: .trailing)                    .accessibilityIdentifier("episode-lobby-place")                    .offset(x: (knobs.placeTo - knobs.foot.width / 2) * s, y: knobs.foot.minY * s)            }        }    }    /// `words` in the typewriter at the foot's size, half the foot wide, set    /// from its leading edge or to its trailing one.    private func typed(_ words: String, alignment: Alignment) -> some View {        let knobs = EpisodeLobbyFaceKnobs.self        return Text(words)            .font(CottonFonts.type(knobs.footSize * s))            .foregroundStyle(CinemasMaterial.ink.colour)            .lineLimit(1)            .fixedSize()            .frame(width: knobs.foot.width / 2 * s, height: knobs.foot.height * s, alignment: alignment)    }}/// The episode's lobby card, by its id beside the film's one-sheet, and the/// episodes it is reviewed in: invented titles, an invented still. A day is/// said as the core says it (`weekday_date`), the mark as the core's/// `field.episode_mark` says it.public enum EpisodeLobbyFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .velvet    public static let face = Face(id: "episode.lobby", specimens: [        Specimen("still", still, picture: "kelmoor-lake"), Specimen("no-still", noStill),        Specimen("half-watched", halfWatched, picture: "kelmoor-lake"), Specimen("watched", watched, picture: "kelmoor-lake"),        Specimen("longest-title", longestTitle), Specimen("largest", largest, picture: "kelmoor-lake"),    ], steps: .cut) { card, picture, _ in        EpisodeLobbyFace(card: card, still: picture)    }    static func episode(_ status: String, _ fields: [String: RecordValue]) -> DeckCard {        var card = DeckCard(face: "episode.lobby", corner: nil, pressing: false, pace: nil, plate: nil, fields: fields)        card.stored["state"] = status        return card    }    /// Still to watch, its still kept.    public static let still = episode("want_to_watch", [        "title": .text("The Long Night"),        "subtitle": .text("S2 E5"),        "number": .number(5),        "photo": .text("kelmoor-lake"),        "limit": .number(48),        "date": .text("Add date"),    ])    /// No still kept: the dark field and the episode's number on it.    public static let noStill = episode("want_to_watch", [        "title": .text("The Fog Bell"),        "subtitle": .text("S1 E3"),        "number": .number(3),        "limit": .number(52),        "date": .text("Add date"),    ])    /// Half way through: the strip filled to its middle, its place typed.    public static let halfWatched = episode("watching", [        "title": .text("The Long Night"),        "subtitle": .text("S2 E5"),        "number": .number(5),        "photo": .text("kelmoor-lake"),        "used": .number(1440),        "limit": .number(48),        "date": .text("Add date"),    ])    /// Watched: the stub at the corner, its day typed; the strip full.    public static let watched = episode("watched", [        "title": .text("The Long Night"),        "subtitle": .text("S2 E5"),        "number": .number(5),        "photo": .text("kelmoor-lake"),        "limit": .number(48),        "date": .text("Wed 4 Nov"),    ])    /// The longest title: the caption on two lines, cut; no still.    public static let longestTitle = episode("watching", [        "title": .text("The Lamp-Keeper's Daughter Rows Out Past the Breakwater on the Longest Night of the Year"),        "subtitle": .text("S12 E104"),        "number": .number(104),        "used": .number(2400),        "limit": .number(64),        "date": .text("Add date"),    ])    /// The fullest card, drawn at every text size Loom has, the largest    /// among them: watched, a long title, an episode over an hour.    public static let largest = episode("watched", [        "title": .text("The Lantern Coast and the Harbour Towns, Part Two"),        "subtitle": .text("S3 E10"),        "number": .number(10),        "photo": .text("kelmoor-lake"),        "limit": .number(72),        "date": .text("Sun 1 Nov"),    ])}