Cotton code
248 lines · 10.7 KB · SwiftRaw
// Bytes on this device, turned into something SwiftUI can draw.//// ONE loader for every picture this lane renders — a product's photograph, a// note's attachment, a person's face, a conversation's picture — because all of// them ask the same question of the same seam.//// **A RENDERER ASKS `read.mediaPath`, AND NOTHING HERE FETCHES ON MOUNT.**// That split is the crate's own (`crates/cotton-ffi/src/phone/media.rs`): "a// grid drawing two hundred thumbnails asks this one, and a read that could// start two hundred downloads would be a screen that opens the radio." This// file used to call `media.ensure` from `load` — the one call that MAY go to// the network — so every shelf of prints and every list of faces opened the// radio as it scrolled. `load` is the read// now; `fetch` is the method, it is named so nobody reaches it by accident, and// only the DETAIL view of a single picture, on a deliberate tap, calls it.//// **A big body is a FILE, never bytes, and that rule reaches decoding too.**// `UIImage(contentsOfFile:)` reads the whole original into memory — a grid does// that once per tile, and a full-page screenshot is measured in megapixels// nobody can see at the size it is drawn. ImageIO maps the file and decodes a// thumbnail at the edge actually going on screen, which is both the safe read// and the right one.//// THREE STATES and the caller draws all three, because the third is the honest// one: a version published from a desktop minutes ago has rows here and bytes// that have not landed, and "not on this phone yet" is a fact that heals itself// rather than an error.//// **AND THE TIER IS THE CRATE'S CHOICE, NOT THIS FILE'S.** `read.mediaPath`// answers the 256 px thumbnail this device collected if there is one, else the// bytes the key names, else nothing; a picture key gets its thumbnail for free// and everything else — a document, a meeting's audio — falls straight through.// So `load` still asks with the key alone, `.ready` still means "there is a// file at this path", and the difference between the tiers is a path and a// decode that costs a tenth as much.//// **WHAT WAS DECODED IS KEPT** (`MediaImageCache`): a lazy view rebuilt on a// scroll finds its picture by key and size before it crosses the boundary at// all. **And an absence is told when to ask again**: `.mediaSlot` wears// `.onMediaArrival`, the one doorbell `SyncModel.mediaEpoch` rings when the// ledger moves, and only a slot that is `.absent` answers it — a drawn picture// never re-decodes.import CottonKitimport ImageIOimport SwiftUI#if canImport(UIKit)import UIKit#endif/// Where one picture stands.enum MediaImageState {    /// Being asked for — never a spinner, the caller draws the frame's shape.    case resolving    case ready(UIImage)    /// Not on this device.    case absent}/// One picture's state and the KEY it is about.////// **A new KEY drops the picture; a re-ask over the SAME key keeps it on/// screen.** The rule `PhotosPicture` already followed, hoisted here because/// the Work lane did not: every caller began its `.task` with `state =/// .resolving`, so a pop-back — which re-runs `.task(id:)` with the very same/// key — blanked a picture that was already decoded and drawn, and the person/// watched the screen they had just left flash empty and fill again.////// It also drops a LATE answer for a key the view has moved on from, which the/// bare `state =` assignment could not: a fast scroll re-uses the view, and the/// slower of two overlapping decodes used to win.struct MediaImageSlot {    private(set) var state: MediaImageState = .resolving    /// The key `state` is an answer about — `nil` before the first ask.    private(set) var key: String?    /// The decoded picture, when there is one.    var image: UIImage? {        if case .ready(let image) = state { return image }        return nil    }    /// Only the picture of the record currently being drawn. A view's key    /// can change before its keyed task gets a turn to drop the old image.    func image(for asked: String?) -> UIImage? {        guard let asked, !asked.isEmpty, asked == key else { return nil }        return image    }    var isAbsent: Bool {        if case .absent = state { return true }        return false    }    /// Drawn, and nothing more to ask for.    var isReady: Bool { image != nil }    /// The newest ask: an answer from an older one is stale. Bytes can land    /// while an ask is in flight — it read before they were there and answers    /// absent — so the doorbell asks again then too, and only the newest    /// answer is kept (a grey tile that never redrew, sharing2, 16 Oct 2026).    private(set) var ask = 0    /// Begin an ask. A DIFFERENT key drops what is drawn — it is a different    /// picture — and the same key leaves it alone. Answers the ask's number,    /// which its `finish` names.    @discardableResult    mutating func begin(_ asked: String?) -> Int {        ask += 1        if key != asked {            key = asked            state = .resolving        }        return ask    }    /// The answer, kept only if it is still the answer to what is on screen    /// and no later ask has begun.    mutating func finish(_ answer: MediaImageState, for asked: String?, ask number: Int) {        guard asked == key, number == ask else { return }        state = answer    }}enum MediaImages {    /// **THE RENDERER'S ASK: `read.mediaPath`, which never fetches.**    ///    /// Decoded at `edge` points (times the display scale, which the caller    /// applies). `absent` is the honest answer for every reason the bytes are    /// not on this phone — never uploaded, not synced yet, evicted — and the    /// surfaces that need to say more than that say it themselves.    ///    /// **THE DECODE IS NOT THE MAIN ACTOR'S.** ImageIO maps and decodes on the    /// thread that asks, so a thirty-picture shelf mounting at once would fire    /// thirty decodes on the thread that paints. It runs off the    /// actor and only the finished `UIImage` — which UIKit declares `Sendable`,    /// being immutable — comes back.    ///    /// The database is passed IN rather than held: the renderers that call this    /// are Views, and a View reads the open database from the environment    /// (`\.cottonCore`) rather than being handed one through an `init`.    @MainActor    static func load(from database: any CottonCalling, key: String, edge: CGFloat) async        -> MediaImageState    {        // ALREADY DECODED at this size: no boundary crossing, no decode. The        // Work lane asks with the tile's order, so ANY rung is the answer —        // a face, a print, a chat picture has no "largest" to wait for.        if let kept = MediaImageCache.shared.picture(key: key, maxPixel: Int(edge.rounded())) {            return .ready(kept.image)        }        guard            let answer = try? await database.callJSON(                CottonMethod.readMediaPath,                ReadRequest(args: .object(["key": .string(key)]))            ),            answer.flag("present"),            let path = answer.text("path"),            let rung = MediaRung(answered: answer)        else { return .absent }        return await decoded(key: key, rung: rung, at: path, edge: edge)    }    @MainActor    private static func decoded(key: String, rung: MediaRung, at path: String, edge: CGFloat) async        -> MediaImageState    {        let decoded = await Task.detached(priority: .userInitiated) {            MediaImages.decode(key: key, rung: rung, at: path, maxPixel: Int(edge.rounded()))        }.value        guard let decoded else { return .absent }        return .ready(decoded)    }    /// The ONE decode-and-keep both lanes use: the cache by key and size when    /// what it holds is at least this rung, else the file decoded at that size    /// and filed under key, size AND rung.    ///    /// Off the main actor by contract — the callers detach it — and `nil` is    /// a file ImageIO could not read, which is the same absence as no file.    static func decode(key: String, rung: MediaRung, at path: String, maxPixel: Int) -> UIImage? {        if let kept = MediaImageCache.shared.picture(key: key, maxPixel: maxPixel), kept.rung >= rung {            return kept.image        }        guard let made = thumbnail(at: path, edge: CGFloat(maxPixel)) else { return nil }        MediaImageCache.shared.keep(made, rung: rung, key: key, maxPixel: maxPixel)        return made    }    /// The file DECODED AT DRAW SIZE, and never read whole.    static func thumbnail(at path: String, edge: CGFloat) -> UIImage? {        guard            let source = CGImageSourceCreateWithURL(URL(fileURLWithPath: path) as CFURL, nil)        else { return nil }        let options: [CFString: Any] = [            kCGImageSourceCreateThumbnailFromImageAlways: true,            kCGImageSourceCreateThumbnailWithTransform: true,            kCGImageSourceThumbnailMaxPixelSize: max(Int(edge.rounded()), 1),        ]        guard let made = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary)        else { return nil }        return UIImage(cgImage: made)    }}// MARK: - The slot, wired/// The Work lane's picture, resolved and kept current, as ONE modifier.////// Five views carried the same six lines — begin the slot, guard the key and/// the database, `load`, finish — and none of them heard when bytes landed./// This is those lines once, plus the doorbell: `.task(id: key)` is the first/// ask, `.onMediaArrival` every later one — absent or still asking — and a/// slot that is `.ready` answers the bell with nothing.private struct MediaSlotResolving: ViewModifier {    @Binding var slot: MediaImageSlot    let key: String?    let edge: CGFloat    @Environment(\.cottonCore) private var database    @Environment(\.displayScale) private var scale    func body(content: Content) -> some View {        content            .task(id: key) { await ask() }            .onMediaArrival {                guard !slot.isReady else { return }                await ask()            }    }    private func ask() async {        let number = slot.begin(key)        guard let key, !key.isEmpty, let database else {            slot.finish(.absent, for: key, ask: number)            return        }        let answer = await MediaImages.load(from: database, key: key, edge: edge * scale)        slot.finish(answer, for: key, ask: number)    }}extension View {    /// Resolve `key` into `slot` at `edge` POINTS (the display scale is    /// applied here), and ask again when bytes arrive before it is drawn.    func mediaSlot(_ slot: Binding<MediaImageSlot>, key: String?, edge: CGFloat) -> some View {        modifier(MediaSlotResolving(slot: slot, key: key, edge: edge))    }}