Cotton code
371 lines · 16.3 KB · SwiftRaw
// A tool, as the object that did its job — Home's directory, four across.//// A cut-out photograph standing on the plaster with the tool's NAME PRINTED ON// IT. The picture is a PHOTOGRAPH, like a cap: it keeps its own colours and// wears the cap board's one shadow, so a clipboard and a telephone lie on the// same ground at the same height.//// THE NAME IS ON THE OBJECT (the owner's ruling of 2026-09-16). It used to be// typed UNDER the picture with a figure pencilled under that — "284 open",// "1700 people" — and the two lines read as an App Store listing: a caption// and a subtitle under a piece of art. So the word moved onto the thing// itself, printed on the clipboard's header and the ledger's cover, set live// and blended into the photograph the way a project's name is printed on an// enamel cap; the figures went from Home altogether (Find keeps// figure-or-silence, and `FindTool.figure` is untouched — Home just draws// none); and the objects with no printable face carry no word at all. WHERE// each name is printed is `Paper/ToolPrint.swift` and nowhere else.//// THE CELL IS FIXED, THE OBJECT FITS. Every object is drawn inside the same// square — scaled to fit `objectFraction` of it, centred. The pictures were// cut with the same padding, which is what makes one fraction right for all of// them, and it is what makes a print box in the SQUARE's unit coordinates land// on the same place of every object.//// THE NAME IS STILL THE LABEL. The print is a picture of a word, so it is// hidden from VoiceOver along with the photograph, and the cell states its// name once (`accessibilityLabel`) — an object whose word is drawn and an// object with none read exactly the same.//// AND THE DECK LEAVES THE NAME OFF (2026-09-16, `Paper/ToolCard.swift`). Home's// directory is cards now, and a card prints the tool's name UNDER the picture —// so the object on a card is drawn `printing: .contentOnly` and comes up bare,// except the calendar, whose date is content rather than a label. This view is// unchanged at its default and still draws the name on the face: it is what the// Mac's sidebar draws.//// ONE PICTURE, AND ITS SHADOW IS A SHADOW. The lift is a `.shadow` on the// photograph, under the prints — `Lift.board` on the plaster, and the card's// own softer drop when a `ToolCard` hands one down. The card used to draw a// SECOND copy of the whole object, blurred and multiplied, to stand in for// one; twenty-four cards made that forty-eight photographs and twenty-four// live blurs on the one screen everybody passes through.//// NO PICTURE, NO GAP. A tool with no object (`asset == nil`), or a Mac build// that carries no resource bundle, draws a typed name card in the same square:// the directory then reads as a tool without its picture, never as a hole.import CottonKitimport CottonValuesimport SwiftUI#if canImport(UIKit)import UIKit#endifpublic struct ToolObject: View {    @Environment(\.theme) private var theme    /// Which of an object's prints are set on it.    ///    /// The object on a `ToolCard` is the same picture with its own LABEL left    /// off: the card prints the tool's name under the picture, so printing it    /// on the picture too would be the word twice. What survives is every print    /// that is CONTENT rather than a label — which is exactly one, the    /// calendar's date, because `SEP 16` is what the pad says and "Calendar" is    /// what the pad is called.    public enum Printing: Sendable {        /// Everything the object carries: its name on its own face, and the        /// calendar's date on its pad. Home's directory before the deck, the        /// Mac's sidebar.        case own        /// Only the prints that are content. The deck (`ToolCard`).        case contentOnly    }    /// **How the object is lifted off what it stands on.**    ///    /// The board's one shadow is what a cap and a bare object wear, and it is    /// the default. A card lifts its object differently — softer, dropped    /// further, scaled to the card — and it is the CARD that owns those    /// numbers (`ToolCardMetrics`), so it hands them down rather than drawing    /// a second copy of the picture to blur.    ///    /// Either way the shadow is cast by the PHOTOGRAPH and not by what is    /// printed on it: it is applied to the picture, under the prints, so the    /// calendar's date is ink on the pad rather than something hanging above    /// it.    public enum Lift: Sendable, Equatable {        /// `CapBoard.shadow` — the one lift every object on the plaster wears.        case board        /// The card's own: a radius, a drop and an opacity, in POINTS at the        /// size the caller is drawing.        case drop(radius: CGFloat, y: CGFloat, opacity: Double)    }    private let name: String    private let picture: ToolPicture?    private let now: Date    private let printing: Printing    private let lift: Lift    /// The square's side, when the caller already knows it — a card does, and    /// twenty-four cards measuring their own object is twenty-four layout    /// containers for one number. `nil` measures, which is what the sidebar    /// wants.    private let side: CGFloat?    private let imageVariant: ToolImageVariant    /// How much of the cell's side the object may take. With the two text    /// lines gone the cut-out fills its square — the PNGs were cut with ~6 %    /// padding of their own, which is the breathing room.    private var objectFraction: CGFloat { ToolObjectKnobs.toolObjectFraction }    public init(        name: String,        picture: ToolPicture?,        now: Date = Date(),        printing: Printing = .own,        lift: Lift = .board,        side: CGFloat? = nil,        imageVariant: ToolImageVariant = .full    ) {        self.name = name        self.picture = picture        self.now = now        self.printing = printing        self.lift = lift        self.side = side        self.imageVariant = imageVariant    }    /// An object the app ships, by its imageset name.    public init(        name: String,        asset: String?,        now: Date = Date(),        printing: Printing = .own,        lift: Lift = .board,        side: CGFloat? = nil,        imageVariant: ToolImageVariant = .full    ) {        self.init(            name: name, picture: asset.map(ToolPicture.asset), now: now, printing: printing, lift: lift, side: side,            imageVariant: imageVariant        )    }    private var asset: String? {        if case .asset(let name) = picture { return name }        return nil    }    /// What a card draws for a picture: the photo record it names, the object    /// the app ships, or — with neither — the tool's name typed on the card.    enum Drawn: Equatable {        case photo(String)        case object(String)        case typed    }    static func drawn(_ picture: ToolPicture?, family: ThemeFamily, shipped: (String) -> Bool) -> Drawn {        guard family == .paper else { return .typed }        switch picture {        case .photo(let reference): return .photo(reference)        case .asset(let name) where shipped(name): return .object(name)        default: return .typed        }    }    /// The object's own name — the part after `tool-`, which is the key    /// `ToolPrint` is written in.    private var objectName: String? {        guard let asset, asset.hasPrefix("tool-") else { return nil }        return String(asset.dropFirst("tool-".count))    }    public var body: some View {        drawing            .aspectRatio(1, contentMode: .fit)            .compositingGroup()            .accessibilityElement(children: .ignore)            .accessibilityLabel(name)    }    @ViewBuilder private var drawing: some View {        // A flat family has no photographs: the object is the typed card.        let drawn = Self.drawn(picture, family: theme.family) { CottonMedia.image(imageVariant.asset($0)) != nil }        if case .object(let asset) = drawn, let image = CottonMedia.image(imageVariant.asset(asset)) {            // The picture wears its hide HERE, on its own chain where it is            // bound: the object's NAME is printed on            // it in `cell`, and the picture would otherwise fold its asset            // name into the combined label.            let photograph = image                .resizable()                .interpolation(.medium)                .scaledToFit()                .accessibilityHidden(true)            if let side {                cell(photograph, side: side)            } else {                GeometryReader { geo in                    cell(photograph, side: min(geo.size.width, geo.size.height))                        .frame(width: geo.size.width, height: geo.size.height)                }            }        } else if case .photo(let reference) = drawn {            // A photo record the database holds: the same cut-out, lifted the            // same way, with nothing printed on it — its prints are keyed by            // the shipped objects' names.            if let side {                cell(ToolPhotograph(reference: reference, edge: side), side: side)            } else {                GeometryReader { geo in                    let side = min(geo.size.width, geo.size.height)                    cell(ToolPhotograph(reference: reference, edge: side), side: side)                        .frame(width: geo.size.width, height: geo.size.height)                }            }        } else {            TypedCard(name: name, seed: "tool-\(name)")                .padding(ToolObjectKnobs.toolObjectTypedPadding)        }    }    /// The object in a square of a decided side: the photograph at its    /// fraction of it, lifted, with whatever is printed on it over the top.    private func cell(_ photograph: some View, side: CGFloat) -> some View {        let objectSide = side * objectFraction        return ZStack {            lifted(photograph)                .frame(width: objectSide, height: objectSide)            prints(objectSide: objectSide)        }        // The blend has to hit the PHOTOGRAPH and stop there — without the        // group it would multiply through to the plaster under it.        .compositingGroup()        .frame(width: side, height: side)    }    /// The picture's own lift, cast by the PHOTOGRAPH — one shadow, never a    /// second drawing of the object blurred behind the first.    @ViewBuilder private func lifted<V: View>(_ picture: V) -> some View {        switch lift {        case .board:            CapBoard.shadow(picture)        case .drop(let radius, let y, let opacity):            picture.shadow(color: theme.colors.shadow.color.opacity(opacity), radius: radius, x: 0, y: y)        }    }    /// What is printed on this object: the date on the calendar's pad, the    /// tool's name on anything with a face, and nothing at all on the    /// self-evident ones.    @ViewBuilder private func prints(objectSide: CGFloat) -> some View {        if let objectName {            if objectName == ToolPrint.calendarObject, let day = ToolPrint.table(in: theme.scale)[objectName] {                // The DATE, in both modes: it is what the pad says, not what                // the pad is called.                let date = ToolPrint.calendarLines(now)                printed(date.month, ToolPrint.calendarMonth(in: theme.scale), objectSide: objectSide)                printed(date.day, day, objectSide: objectSide)            } else if printing == .own, let print = ToolPrint.table(in: theme.scale)[objectName] {                printed(name, print, objectSide: objectSide)            }        }    }    private func printed(_ text: String, _ print: ToolPrint, objectSide: CGFloat) -> some View {        let box = print.size(objectSide: objectSide)        let shift = print.offset(objectSide: objectSide)        return Text(print.transform.apply(text))            .font(print.face.font(print.fontSize(objectSide: objectSide, scale: theme.scale), in: theme.type))            .multilineTextAlignment(.center)            .lineLimit(print.lines)            .frame(width: box.width, height: box.height)            .foregroundStyle(print.ink.color)            .blendMode(print.ink.blend)            .rotationEffect(.degrees(print.rotation))            .offset(x: shift.width, y: shift.height)            // A picture of a word: the cell says the name once, above.            .accessibilityHidden(true)    }}/// Tool photographs decoded, by reference: the largest cut-out drawn of each,/// kept for the app's life — a few dozen small pictures. What a card drawn/// in one synchronous render (a fan print) reads, since it runs no task.@MainActorenum ToolPhotographs {    private static var decoded: [String: UIImage] = [:]    private static var underway: Set<String> = []    static func image(_ reference: String) -> UIImage? { decoded[reference] }    /// A load of `reference` is out.    static func loading(_ reference: String) -> Bool { underway.contains(reference) }    /// A load of `reference` is out from now: the caller starts it in a task.    static func ask(_ reference: String) { underway.insert(reference) }    /// The cut-out at `maxPixel`, from the bytes this device holds or fetches;    /// a larger one already decoded answers at once.    static func load(_ reference: String, core: any CottonCalling, maxPixel: Int) async -> UIImage? {        underway.insert(reference)        defer { underway.remove(reference) }        if let held = decoded[reference], Int(max(held.size.width, held.size.height) * held.scale) >= maxPixel {            return held        }        let media = PhotosMediaSource(core: core)        var path = await media.answer(for: reference, tier: .original)?.path        if path == nil { path = try? await media.ensure(reference) }        guard let path, let image = await ToolPhotograph.cutOut(reference: reference, at: path, maxPixel: maxPixel)        else { return decoded[reference] }        if let held = decoded[reference], held.size.width * held.scale >= image.size.width * image.scale { return held }        decoded[reference] = image        return image    }}/// A tool's picture held as a photo record, drawn from the ORIGINAL bytes:/// a cut-out keeps its transparency only there. The grid tier the media/// worker makes for every photo is a JPEG, and a tool picture drawn from it/// sat on a black square (owner, build 237). A tool card is one of a few/// dozen small fixed pictures, so it asks for the original and fetches it once/// when this device does not hold it — nothing while it has not arrived: a/// card with its stock and name and no object yet.struct ToolPhotograph: View {    let reference: String    let edge: CGFloat    @Environment(\.cottonCore) private var core    @Environment(\.displayScale) private var scale    @State private var image: UIImage?    var body: some View {        ZStack {            // Decoded once for every card that draws it — and drawn at once, so            // a card printed for the fan (`FanPrints`, one synchronous render            // that runs no task) carries it (292, walker292: Disk and Quotas).            if let image = image ?? ToolPhotographs.image(reference) {                Image(uiImage: image)                    .resizable()                    .interpolation(.medium)                    .scaledToFit()            } else {                Color.clear            }        }        .accessibilityHidden(true)        .task(id: reference) { await draw() }        .onMediaArrival {            guard image == nil else { return }            await draw()        }    }    private func draw() async {        guard let core else { return }        image = await ToolPhotographs.load(reference, core: core, maxPixel: Int((edge * scale).rounded()))    }    /// The original decoded at draw size, its alpha intact.    static func cutOut(reference: String, at path: String, maxPixel: Int) async -> UIImage? {        await Task.detached(priority: .userInitiated) {            MediaImages.decode(key: reference, rung: .original, at: path, maxPixel: maxPixel)        }.value    }}/// The sizes, counts and timings ToolObject draws with: Swift's own, beside/// their reader — a theme sets only its tokens (`scale.tokens`).enum ToolObjectKnobs {    static let toolObjectFraction: CGFloat = 0.98    static let toolObjectTypedPadding: CGFloat = 10}