Cotton code
475 lines · 20.9 KB · SwiftRaw
// The PHOTO as a GLOSSY LAB PRINT (the owner's pick, 30 Oct 2026, 00:25 IST: "I// do really like the lab print photos"; the photo picture// `objects-2/photos-2/1-lab-print`): a 1980s machine print of the photograph// lying bare on the Photos darkroom bench (`FaceGround.darkroomBench`, 12 Nov 2026),// a hair askew, with no paper and no rule of the deck's. The photograph IS// the card: it is drawn FIRST, as large as the card allows at its own shape// (a landscape picture fills the card's width, a tall one its height, the// cloth showing at its sides), and the print is laid round and over it —////   its white border, a SHAPE drawn over the picture's edge (the same width//   on every print), never a painting that could cover a picture;//   its shadow on the cloth (`photo-print-shadow`, a nine-slice, so a print//   of any shape keeps its corners' shadow and the curled lower right//   corner's lift), under it;//   its sheen (`photo-print-sheen`), a smooth soft gradient over the whole//   print, the lamp's long highlight at the upper left and the curled//   corner's shade, laid with transparency over the picture;//   and the date the camera burned into the picture's lower right, in//   glowing orange seven-segment figures, DD MM YY, read off the card's//   date; a photograph with no date has none.//// Nothing else is on the print: no caption, no place, no people. Every word// it might say is the viewer's. Stepped by a tap, it cuts (`FaceStep.cut`).//// The face reads the card's own fields, the photo face's (`photo`, `date`);// the picture's shape is the one thing a card does not carry, asked of// whatever draws pictures (`facePictureAspect`): a picture whose shape is// not known is laid as a lab's standard landscape print, 3:2, and filled.import CottonPaperimport CottonValuesimport SwiftUIenum PhotoPrintFaceKnobs {    /// The print in the card's room: the most of its width and of its    /// height it takes, askew and with its shadow round it.    static let fillWidth: CGFloat = 0.95    static let fillHeight: CGFloat = 0.95    /// The white border's width, as a share of the card's width: the same    /// on every print, a tall one's as a wide one's.    static let border: CGFloat = 0.021    /// The print's corners, very slightly rounded, in points.    static let corner: CGFloat = 2    /// How far askew the print lies, in degrees.    static let turn: Double = -0.9    /// A lab's standard print, 6 by 4, where the picture's shape is not known.    static let standard: CGFloat = 1.5    /// THE SHADOW (`photo-print-shadow`), as cut: a nine-slice drawn round a    /// square of `shadowSide` points, reaching `shadowReach` past it on every    /// side, its caps `shadowCap` points.    static let shadowSide: CGFloat = 150    static let shadowReach: CGFloat = 30    static let shadowCap: CGFloat = 45    /// THE BURN: its figures' height as a share of the picture's shorter    /// side (never under `burnLeast` points), and its inset from the    /// picture's lower right corner, as a share of the same.    static let burnHeight: CGFloat = 0.052    static let burnLeast: CGFloat = 9    static let burnInset: CGFloat = 0.05}/// The date a camera burns into a picture: DD MM YY, read off the card's/// date words as the core says them for a photo (`weekday_date_year`: "Sun/// 26 Oct 2026", a time after it or not) — the day, the month by the/// dates set's own month words, and the year's last two figures.public enum PrintBurn {    /// The three figures of `words`, "26 10 26"; nil when they do not say    /// a day, a month and a year.    public static func figures(_ words: String?) -> String? {        guard let words else { return nil }        let tokens = words.split(whereSeparator: { !$0.isLetter && !$0.isNumber }).map(String.init)        for (at, token) in tokens.enumerated() {            guard let month = month(token), at > 0, at + 1 < tokens.count,                  let day = Int(tokens[at - 1]), (1...31).contains(day),                  tokens[at + 1].count == 4, let year = Int(tokens[at + 1])            else { continue }            return [day, month, year % 100].map { String(format: "%02d", $0) }.joined(separator: " ")        }        return nil    }    /// The month a word names, 1 to 12, as the dates set says months.    static func month(_ word: String) -> Int? {        months.firstIndex { $0.caseInsensitiveCompare(word) == .orderedSame }.map { $0 + 1 }    }    private static let months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"]        .map { ShellLines.line("dates", "months.\($0)") }}/// Where a print lies in a card's room: the picture's size and the print's/// round it, at the picture's own shape.public struct PrintLaying: Equatable, Sendable {    /// The picture, in points.    public var picture: CGSize    /// The white border's width round it.    public var border: CGFloat    /// The print: the picture and its border.    public var print: CGSize {        CGSize(width: picture.width + 2 * border, height: picture.height + 2 * border)    }    /// A picture of `aspect` (width over height; nil, a standard print's) in    /// a card `room`: as large as the room allows, the border round it.    public static func laid(aspect: CGFloat?, in room: CGSize) -> PrintLaying {        let knobs = PhotoPrintFaceKnobs.self        let shape = aspect.flatMap { $0.isFinite && $0 > 0 ? $0 : nil } ?? knobs.standard        let border = knobs.border * room.width        let width = max(0, room.width * knobs.fillWidth - 2 * border)        let height = max(0, room.height * knobs.fillHeight - 2 * border)        let picture = width / height > shape            ? CGSize(width: height * shape, height: height)            : CGSize(width: width, height: width / shape)        return PrintLaying(picture: picture, border: border)    }}public struct PhotoPrintFace: View {    @Environment(\.faceOpened) private var opened    @Environment(\.accessibilityReduceMotion) private var reduceMotion    @State private var front = false    let card: DeckCard    /// The photograph's key; nil, the print is drawn empty.    let key: String?    @Environment(\.facePictureAspect) private var aspect    public init(card: DeckCard, key: String?) {        self.card = card        self.key = key    }    public var body: some View {        GeometryReader { box in            let laying = PrintLaying.laid(aspect: key.flatMap { aspect($0) }, in: box.size)            Group {                if opened {                    TurningPrint(card: card, key: key, laying: laying, angle: front ? 0 : 180)                        .environment(\.facePartTaps, nil)                        .contentShape(Rectangle())                        .onTapGesture {                            withAnimation(reduceMotion ? nil : .easeInOut(duration: 0.3)) { front.toggle() }                        }                        .onChange(of: card.record) { front = false }                } else {                    LabPrint(key: key, burn: PrintBurn.figures(card.text("date")), laying: laying)                }            }                .rotationEffect(.degrees(PhotoPrintFaceKnobs.turn))                .frame(width: box.size.width, height: box.size.height)        }        .accessibilityElement(children: .contain)        .accessibilityLabel(card.text("title") ?? "")        .accessibilityIdentifier("photo-print")    }}/// A painted layer, by its catalogue name, at the scale it was painted/// for; nil where this build carries no pictures.private func painted(_ name: String) -> Image? {    CottonMedia.image(name, scale: 3)}/// The print lying on the cloth: its shadow, the picture, the border over/// the picture's edge, the sheen over both, and the date burned in.private struct LabPrint: View {    let key: String?    let burn: String?    let laying: PrintLaying    var body: some View {        let knobs = PhotoPrintFaceKnobs.self        let print = laying.print        let picture = laying.picture        let reach = knobs.shadowReach        ZStack(alignment: .topLeading) {            if let shadow = painted("photo-print-shadow") {                shadow                    .resizable(capInsets: EdgeInsets(top: knobs.shadowCap, leading: knobs.shadowCap, bottom: knobs.shadowCap, trailing: knobs.shadowCap))                    .frame(width: print.width + 2 * reach, height: print.height + 2 * reach)                    .offset(x: -reach, y: -reach)                    .accessibilityHidden(true)            }            ZStack(alignment: .topLeading) {                // The picture first, a hair larger than its window, so the                // border always meets it.                Group {                    if let key {                        FacePicture(key: key, edge: max(picture.width, picture.height))                    } else {                        PhotosMaterial.card.colour                    }                }                .frame(width: picture.width + 1, height: picture.height + 1)                .clipped()                .offset(x: laying.border - 0.5, y: laying.border - 0.5)                .accessibilityHidden(true)                PrintBorder(border: laying.border, corner: knobs.corner)                    .fill(PhotosMaterial.border.colour, style: FillStyle(eoFill: true))                    .accessibilityHidden(true)                if let sheen = painted("photo-print-sheen") {                    sheen.resizable()                        .frame(width: print.width, height: print.height)                        .accessibilityHidden(true)                }                if let burn {                    let side = min(picture.width, picture.height)                    let height = max(knobs.burnLeast, knobs.burnHeight * side)                    let inset = knobs.burnInset * side                    let figures = SevenSegments.room(burn, height: height)                    // Its own room, its lower right corner `inset` in from                    // the picture's: the date is all that is tagged there.                    SevenSegments(figures: burn, height: height)                        .accessibilityRepresentation { Text(burn) }                        .accessibilityIdentifier("photo-print-date")                        .facePart(.when)                        .offset(                            x: laying.border + picture.width - inset - figures.width,                            y: laying.border + picture.height - inset - figures.height)                }            }            .frame(width: print.width, height: print.height, alignment: .topLeading)            .clipShape(RoundedRectangle(cornerRadius: knobs.corner))            .facePart(.picture)        }        .frame(width: print.width, height: print.height, alignment: .topLeading)    }}/// A print's white border: its outline, less the picture's window inside it.struct PrintBorder: Shape {    let border: CGFloat    let corner: CGFloat    func path(in rect: CGRect) -> Path {        var path = Path(roundedRect: rect, cornerRadius: corner)        path.addRect(rect.insetBy(dx: border, dy: border))        return path    }}/// Figures burned in by a camera's date back: seven-segment, a little/// slanted, in glowing orange with a bloom round them, laid over the/// picture as light is (screened).struct SevenSegments: View {    let figures: String    /// A figure's height, in points.    let height: CGFloat    /// Each figure's lit segments, a to g: top, upper right, lower right,    /// bottom, lower left, upper left, middle.    static let lit: [Character: String] = [        "0": "abcdef", "1": "bc", "2": "abged", "3": "abgcd", "4": "fgbc",        "5": "afgcd", "6": "afgedc", "7": "abc", "8": "abcdefg", "9": "abcdfg",    ]    /// A figure's width, the gap between figures and between pairs, the    /// segment's thickness and the slant, as shares of its height.    static let width: CGFloat = 0.5    static let gap: CGFloat = 0.22    static let space: CGFloat = 0.7    static let thickness: CGFloat = 0.12    static let slant: CGFloat = 0.1    var body: some View {        let size = Self.size(figures, height: height)        let path = Self.path(figures, height: height)        Canvas { context, _ in            context.drawLayer { bloom in                bloom.addFilter(.blur(radius: height * 0.14))                bloom.fill(path, with: .color(PhotosMaterial.bloom.colour.opacity(0.85)))            }            context.fill(path, with: .color(PhotosMaterial.burn.colour))        }        .frame(width: size.width, height: size.height)        .padding(height * Self.bloom)        .blendMode(.screen)    }    /// The room round the figures their bloom takes, as a share of their height.    static let bloom: CGFloat = 0.3    /// The room `figures` and their bloom take at `height`.    static func room(_ figures: String, height: CGFloat) -> CGSize {        let size = size(figures, height: height)        return CGSize(width: size.width + 2 * bloom * height, height: size.height + 2 * bloom * height)    }    /// The room `figures` take at `height`.    static func size(_ figures: String, height: CGFloat) -> CGSize {        var x: CGFloat = 0        for (at, character) in figures.enumerated() {            if character == " " { x += space * height; continue }            if at > 0, figures[figures.index(figures.startIndex, offsetBy: at - 1)] != " " { x += gap * height }            x += width * height        }        return CGSize(width: x + slant * height, height: height)    }    /// Every lit segment of `figures` at `height`, as one path.    static func path(_ figures: String, height h: CGFloat) -> Path {        let w = width * h        let t = thickness * h        var path = Path()        var x: CGFloat = 0        var previous: Character = " "        for character in figures {            if character == " " { x += space * h; previous = " "; continue }            if previous != " " { x += gap * h }            for segment in lit[character] ?? "" {                path.addPath(Self.segment(segment, w: w, h: h, t: t), transform: CGAffineTransform(translationX: x, y: 0))            }            x += w            previous = character        }        // Slanted as a date back's figures are: the top leans right.        return path.applying(CGAffineTransform(a: 1, b: 0, c: -slant, d: 1, tx: slant * h, ty: 0))    }    /// One segment of a figure `w` by `h`, `t` thick: a bar with pointed ends.    static func segment(_ name: Character, w: CGFloat, h: CGFloat, t: CGFloat) -> Path {        let half = t / 2        let middle = h / 2        let gap = t * 0.18        func across(_ y: CGFloat) -> Path {            Path { p in                p.move(to: CGPoint(x: gap, y: y))                p.addLine(to: CGPoint(x: gap + half, y: y - half))                p.addLine(to: CGPoint(x: w - gap - half, y: y - half))                p.addLine(to: CGPoint(x: w - gap, y: y))                p.addLine(to: CGPoint(x: w - gap - half, y: y + half))                p.addLine(to: CGPoint(x: gap + half, y: y + half))                p.closeSubpath()            }        }        func down(_ x: CGFloat, from top: CGFloat, to bottom: CGFloat) -> Path {            Path { p in                p.move(to: CGPoint(x: x, y: top + gap))                p.addLine(to: CGPoint(x: x + half, y: top + gap + half))                p.addLine(to: CGPoint(x: x + half, y: bottom - gap - half))                p.addLine(to: CGPoint(x: x, y: bottom - gap))                p.addLine(to: CGPoint(x: x - half, y: bottom - gap - half))                p.addLine(to: CGPoint(x: x - half, y: top + gap + half))                p.closeSubpath()            }        }        switch name {        case "a": return across(half)        case "g": return across(middle)        case "d": return across(h - half)        case "f": return down(half, from: half, to: middle)        case "e": return down(half, from: middle, to: h - half)        case "b": return down(w - half, from: half, to: middle)        case "c": return down(w - half, from: middle, to: h - half)        default: return Path()        }    }}/// The lab print, by its id beside the photo's own face, and the/// photographs it is reviewed in: invented pictures only. The specimen/// world's today is Thursday 29 October 2026; a photo's date is the day it/// was taken, said as the core says it (`weekday_date_year`).public enum PhotoPrintFaceCatalogue {    public static let stock: FaceStock = .own    public static let ground: FaceGround = .darkroomBench    public static var opened: DeckCard {        var card = lake        card.fields["place"] = .text("West shore")        card.fields["city"] = .text("Hilltown")        card.fields["model"] = .text("Sample Camera · Model 35")        card.fields["people"] = .list([.object(["name": .text("Alex Sample")]), .object(["name": .text("Blair Sample")])])        return card    }    public static let face = Face(id: "photo.print", specimens: [        Specimen("opened", opened, opened: true),        Specimen("lake", lake, picture: "kelmoor-lake"), Specimen("portrait", portrait, picture: "verandah-wide"),        Specimen("square", square, picture: "kelmoor-jetty"), Specimen("no-date", noDate, picture: "waterfall"),    ], steps: .cut) { card, picture, _ in        PhotoPrintFace(card: card, key: picture?.key)    }    static func photo(_ fields: [String: RecordValue]) -> DeckCard {        DeckCard(face: "photo.print", corner: nil, pressing: false, pace: nil, plate: nil, fields: fields)    }    /// A landscape: the print the card's width.    public static let lake = photo([        "photo": .text("kelmoor-lake"),        "title": .text("The jetty at Kelmoor"),        "date": .text("Sun 26 Oct 2026" + EventWhen.join + "6:48 pm"),        "place": .text("Kelmoor"),    ])    /// A tall picture: the print the card's height, the cloth at its sides.    public static let portrait = photo([        "photo": .text("verandah-wide"),        "title": .text("The verandah in the mist"),        "date": .text("Sat 25 Oct 2026" + EventWhen.join + "7:05 am"),        "place": .text("Kelmoor"),    ])    /// A square picture.    public static let square = photo([        "photo": .text("kelmoor-jetty"),        "date": .text("Sun 26 Oct 2026" + EventWhen.join + "6:52 pm"),        "place": .text("Kelmoor"),    ])    /// A photograph that says no day: no date burned in.    public static let noDate = photo([        "photo": .text("waterfall"),        "title": .text("The falls above the village"),    ])}private struct PrintBack: View {    let card: DeckCard    let laying: PrintLaying    var body: some View {        let size = laying.print        ZStack(alignment: .topLeading) {            RoundedRectangle(cornerRadius: PhotoPrintFaceKnobs.corner)                .fill(PhotosMaterial.border.colour)                .overlay(PhotosMaterial.card.colour.opacity(0.18))                .shadow(color: .black.opacity(0.3), radius: 12, x: 4, y: 8)            ScrollView {                VStack(alignment: .leading, spacing: 12) {                    if let day = card.text("date") { Text(day).facePart(.when) }                    let place = [card.text("place"), card.text("city")].compactMap { $0 }.joined(separator: ", ")                    if !place.isEmpty { Text(place).facePart(.place) }                    ForEach(Array(card.entries("people").enumerated()), id: \.offset) { _, person in                        if let name = person["name"]?.text { Text(name) }                    }                    if let caption = card.text("title") { Text(caption).facePart(.title) }                }                .font(CottonFonts.hand(max(16, size.width * 0.055)))                .foregroundStyle(PeopleMaterial.graphite.colour)                .frame(maxWidth: .infinity, alignment: .leading)                .padding(size.width * 0.08)            }            .padding(.bottom, size.width * 0.1)        }        .overlay(alignment: .bottomTrailing) {            if let camera = card.text("model") {                Text(camera).font(CottonFonts.type(10)).foregroundStyle(PeopleMaterial.graphite.colour)                    .padding(size.width * 0.05)            }        }        .frame(width: size.width, height: size.height)        .accessibilityIdentifier("photo-print-back")    }}/// Switch sides at the edge, so handwriting and emulsion never mirror.private struct TurningPrint: View, Animatable {    let card: DeckCard    let key: String?    let laying: PrintLaying    nonisolated var angle: Double    nonisolated var animatableData: Double {        get { angle }        set { angle = newValue }    }    var body: some View {        Group {            if angle < 90 { LabPrint(key: key, burn: PrintBurn.figures(card.text("date")), laying: laying) }            else {                PrintBack(card: card, laying: laying)                    .rotation3DEffect(.degrees(180), axis: (x: 0, y: 1, z: 0))            }        }        .rotation3DEffect(.degrees(angle), axis: (x: 0, y: 1, z: 0), perspective: 0.4)    }}