// A picture's bytes, on this phone. // // **Nothing here fetches anything over HTTP**, and there is no seam by which it // could: the two questions this file asks are `read.mediaPath` ("where are // these bytes on this device") and `media.ensure` ("go and get them"), both // answered by the crate, both answering a PATH. `SourceGuardTests` refuses // `URLSession` in every source and this file gives it nothing to refuse. // // **The grid asks the read; a tap asks the method.** That split is the crate's // own (`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." A tile that fetched from every thumbnail would be the // other arrangement, and the crate wins. // // **THE RESOLVE ORDER IS THE CRATE'S, NOT THIS FILE'S.** `read.mediaPath` // answers, in order: the 256 px THUMBNAIL this device collected (the eager // sweep, `cotton-client/src/media/thumbs.rs`, is its only fetcher and it takes // them five hundred to a pack), then the ORIGINAL if the bytes are here, then // `present: false`. So `PhotosPicture` draws thumbnail → original → the row's // own BLUR → a glyph, and it asks once: the decision lives in one place because // four renderers would eventually disagree, and asking twice would be two // boundary crossings per tile on a scrolling grid. **None of the four is a // spinner** (`ThumbFetchSweepTests`). // // **A DETAIL VIEW asks for the LARGEST copy.** The same read, walked from the // top — original → display → thumbnail — under `tier: "largest"`, because a // hero drawn at the width of the screen asked with the tile's order and was // handed the 256 px thumbnail enlarged while the original sat on disk. The // film page says `tier: "original"` for the film, because a film's key resolves // under the tile's order to its thumbnail JPEG. **Two words, two call sites** // (`PagePicture`'s hero, `MediaStage`'s film), and // `ThumbFetchSweepTests` holds every grid to asking with the key alone. // // **What was decoded is KEPT, and an absence is TOLD.** `MediaImageCache` is // the one decoded-picture cache both lanes share, so a tile scrolled back into // view draws without crossing the boundary; and `PhotosPicture` wears // `.onMediaArrival` — `SyncModel.mediaEpoch`'s doorbell — so a tile that // honestly said "not on this phone" asks again the moment the bytes are, and // only then: a drawn picture never re-decodes. // // **A file is read as a file, never as a body.** Swift's whole-file reads — the `Data` and `UIImage` // initialisers that take a path — are all banned by `WholeBodySweepTests`, and the // ban is right: a 40 MB HEIC held whole in memory to draw a 120pt square is the // jetsam kill build 106 already paid for. `ImageIO` opens the file at a URL and // decodes a thumbnail at the size actually being drawn, so what lands in memory // is the square, not the picture. // // Everything in this file is `Photos`-prefixed. The `/videos` and // `/settings#storage` screens are another agent's in the same sub-step and want // the same three pieces; the orchestrator decides later whether to hoist them. // The two METHOD names are already shared — ``CottonMethod/readMediaPath`` and // ``CottonMethod/mediaEnsure`` are each declared once, beside the other read // names rather than beside a screen, and this file uses those rather than a // second pair over the same two wire strings. import CottonKit import ImageIO import SwiftUI #if canImport(UIKit) import UIKit #endif // MARK: - Asking the core where the bytes are /// What `read.mediaPath` asks and `media.ensure` asks. /// /// The one request this file sends, and it lives beside the caller now that the /// boundary's shapes are JSON. struct PhotosMediaKeyRequest: Encodable, Sendable { var key: String /// Which rung `read.mediaPath` walks from. `nil` is the crate's default — /// the tile's order — and is what every grid sends. The two words are /// `PhotosMediaTier`'s, and the encoder leaves the field out when nil so /// the wire is unchanged for every caller that has no opinion. var tier: String? init(key: String, tier: PhotosMediaTier? = nil) { self.key = key self.tier = tier?.rawValue } } /// The two tiers a caller may NAME. The default (the tile's order) is the /// absence of one. /// /// The words are the crate's (`phone/media.rs`, `Tier`), and this is the one /// place Swift spells them: a renderer with an opinion about which rung it /// wants says it here, and `ThumbFetchSweepTests` lists who may. public enum PhotosMediaTier: String, Sendable { /// Original → display → thumbnail. A detail view's word. case largest /// The bytes the key names and nothing that stands in for them. The /// film page's word. case original /// Is a picture decoded from `rung` the END of this ask, or a stand-in /// worth asking again over when bytes arrive? /// /// The tile's order (`nil`) is done with anything: the thumbnail IS its /// preferred answer. `largest` and `original` are done only with the /// original — a hero drawn from the thumbnail on a second phone is /// `.ready` and still not done, and this is the one rule that stops it /// keeping that thumbnail for the rest of the process after the viewer's /// fetch has put the original beside it. public static func isDone(_ tier: PhotosMediaTier?, with rung: MediaRung) -> Bool { switch tier { case nil: return true case .largest, .original: return rung == .original } } } /// What `read.mediaPath` answered: where the file is, and which rung it is. public struct PhotosMediaAnswer: Equatable, Sendable { public var path: String public var rung: MediaRung } /// The two media questions, over the same core a screen's model holds. /// /// A small value rather than a second model: a tile is a `View`, it needs one /// answer, and giving every tile an `@Observable` of its own would be a /// thousand of them on a full library. public struct PhotosMediaSource: Sendable { private let core: any CottonCalling public init(core: any CottonCalling) { self.core = core } /// Where these bytes are, if they are here. Never a fetch, never a /// refusal a caller has to handle: an absence is an answer. /// /// **The THUMBNAIL first, then the original.** The key handed in is the /// picture's own (or, for a film, its poster's); the crate derives the /// thumbnail's key from it and answers whichever tier this device holds. /// Nothing here names a tier, and `ThumbFetchSweepTests` holds this file to /// that. /// /// **`present: false` is a real answer, not an error.** The bytes are simply /// not on this device yet, which is the state a person on a train is in, and /// a renderer that drew a spinner over it would be promising something no /// read is going to bring. public func path(for key: String) async -> String? { await answer(for: key)?.path } /// The path AND the rung, for a caller that has to know which file it was /// handed — the tile, which decides from the rung whether its ask is done. public func answer(for key: String, tier: PhotosMediaTier? = nil) async -> PhotosMediaAnswer? { guard !key.isEmpty else { return nil } let answer = try? await core.callJSON( CottonMethod.readMediaPath, PhotosMediaKeyRequest(key: key, tier: tier) ) guard let answer, answer.flag("present"), let path = answer.text("path"), let rung = MediaRung(answered: answer) else { return nil } return PhotosMediaAnswer(path: path, rung: rung) } /// The path, fetching the bytes first if they are not here. /// /// Throws the crate's own refusal, message and all — `no_media_fetch` until /// something fills its `MediaFetch` seam, and that sentence says the record /// is intact and the bytes come down as soon as one is wired up. It is /// shown, never swallowed and never turned into a code. /// /// The answer is `{path, fetched}`; `fetched` says whether it had to go and /// get them, and nothing on a screen draws that today. public func ensure(_ key: String, tier: PhotosMediaTier? = nil) async throws -> String { let answer = try await core.callJSON( CottonMethod.mediaEnsure, PhotosMediaKeyRequest(key: key, tier: tier) ) return answer.text("path") ?? "" } /// Say that a DETAIL view opened these bytes. /// /// The stamp the budgeted cache orders by, and it is called from the two /// surfaces that show an original — the full-screen viewer on a tap, and /// the film page, which opening is the asking. **Never from a grid**: a /// least-recently-viewed rule fed by a scrolling finger would drop exactly /// the pictures somebody keeps opening. /// /// Best effort and deliberately not `throws`: the person asked for a /// picture and the picture is there. A stamp that did not land changes /// which file leaves this phone first in three weeks' time, and turning /// that into an error would put a refusal over a photograph that opened. public func viewed(_ key: String) async { _ = try? await core.callJSON( CottonMethod.mediaViewed, PhotosMediaKeyRequest(key: key) ) } } // MARK: - Reading a picture off disk /// One picture, decoded at the size it is drawn. public enum PhotosImageFile { /// Decode the file at `path` down to `maxPixel` on its longest side. /// /// `CGImageSource` reads the file at a URL and hands back a thumbnail /// without ever holding the whole picture: it is the one decode on iOS that /// is honest about a 40 MB HEIC. **ONE decoder for both lanes** — /// `MediaImages.thumbnail` is it, and this name is the photos lane's door /// to the same call. public static func image(atPath path: String, maxPixel: Int) -> UIImage? { MediaImages.thumbnail(at: path, edge: CGFloat(max(1, maxPixel))) } /// The decode, KEPT: `MediaImageCache` by key and size first (when what /// it holds is at least `rung`), else the file decoded and filed under /// key, size and rung. What a tile and a viewer call. public static func image(key: String, rung: MediaRung, atPath path: String, maxPixel: Int) -> UIImage? { MediaImages.decode(key: key, rung: rung, at: path, maxPixel: max(1, maxPixel)) } } /// The inline blur a row carries. /// /// `preview` is a 32px JPEG in base64 — bounded by construction, which is why /// it is decoded in memory and the picture itself is not. It is something of /// the picture to look at while the bytes resolve, rather than a grey square, /// and it matters most on the screen a person scrolls the moment their database /// arrives on a second phone. public enum PhotosBlur { /// The blur, decoded ONCE per string: this was called on every body /// evaluation of every tile, base64-decoding and re-inflating a JPEG each /// time the grid laid out. public static func image(base64: String?) -> UIImage? { guard let base64, !base64.isEmpty else { return nil } if let kept = MediaImageCache.shared.blur(base64: base64) { return kept } guard let data = Data(base64Encoded: base64), let made = UIImage(data: data) else { return nil } MediaImageCache.shared.keepBlur(made, base64: base64) return made } } // MARK: - The tile /// What a tile is drawing. /// /// Three, and never a fourth: the crate resolves the TIER behind `.ready`, so /// "drawing the thumbnail" and "drawing the original" are the same state here /// and the difference is a path. enum PhotosTileState: Equatable, Sendable { /// Asking the ledger. case resolving case ready(path: String) /// **Named, not silent**: these bytes are not on this phone. The honest /// answer is a glyph that SAYS so, not a spinner that never resolves. case absent } /// A picture off this phone's disk, filling whatever frame it is given — the /// one resolve-and-decode every photo surface draws with: the square tile, a /// print's window, a contact sheet's cell. /// /// Three states, and the third is the point (the offline-first media rule): the /// bytes may simply not be on this phone, and the honest answer is the row's own /// blur — or, failing even that, a glyph that SAYS so, never a spinner that /// never resolves. It asks `read.mediaPath` and nothing else: a grid that could /// start two hundred downloads would be a screen that opens the radio. public struct PhotosPicture: View { @Environment(\.theme) private var theme private let media: PhotosMediaSource /// The OBJECT key — a picture's own, a film's POSTER. `nil` is a real /// state and draws the absence. private let key: String? private let preview: String? /// The longest side to decode at, in pixels: the size it is drawn, so what /// lands in memory is the square and not the picture. private let maxPixel: Int /// Which rung to ask for. `nil` — the tile's order — for every grid; a /// detail view's hero says `.largest`. private let tier: PhotosMediaTier? private let blankWhileLoading: Bool @State private var state: PhotosTileState = .resolving @State private var image: UIImage? /// The key `image` was decoded from. A new key drops the old picture at /// once; a re-ask over the same key keeps it on screen while asking. @State private var imageKey: String? /// The rung `image` was decoded from. With `tier`, it decides whether /// this tile is DONE or is drawing a stand-in it should ask again over. @State private var rung: MediaRung? /// The key this view went and got once: a picture drawn LARGE on its own /// (a card in hand, a detail view) is the one tile that may fetch, and it /// asks the object once per key, never per redraw. @State private var fetchedFor: String? /// Nothing more to ask for: absent tiles ask again on arrival, and so do /// drawn ones whose rung is below what their tier wants. private var isDone: Bool { guard case .ready = state, let rung else { return false } return PhotosMediaTier.isDone(tier, with: rung) } public init( media: PhotosMediaSource, key: String?, preview: String? = nil, maxPixel: Int, tier: PhotosMediaTier? = nil, blankWhileLoading: Bool = false ) { self.media = media self.key = key self.preview = preview self.maxPixel = maxPixel self.tier = tier self.blankWhileLoading = blankWhileLoading } public var body: some View { // A clear box the picture overlays, so a filled image takes the frame // it was given rather than its own size. Color.clear .overlay { content } .preference(key: FanPageReadingPreference.self, value: FanPageReading(filled: state != .resolving)) .clipped() .task(id: key) { await resolve() } // THE DOORBELL: bytes moved on this phone. An absence asks again, // and so does a hero drawing the thumbnail while it waits for the // original; a tile that is DONE does nothing, and a re-ask that // answers the same rung is a cache hit, never a re-decode. .onMediaArrival { guard !isDone else { return } await resolve() } } @ViewBuilder private var content: some View { if let image { Image(uiImage: image) .resizable() .scaledToFill() } else if blankWhileLoading { Color.clear } else if let blur = PhotosBlur.image(base64: preview) { Image(uiImage: blur) .resizable() .scaledToFill() .blur(radius: PhotosMediaKnobs.facePhotoBlurRadius) .accessibilityIdentifier("photos-tile-preview") } else { GeometryReader { geo in // The kind's own picture, the same while it is looked for and // when it is not here: `icloud.slash` read "Not Uploaded To // iCloud", which is not what it meant, and fought a film's // play disc drawn over it (walker 604bcce6). A page that says // so in words draws `AbsentSlip`. Image(systemName: AbsentKind.photo.symbol) .font(theme.type.interface(max(PhotosMediaKnobs.facePhotoGlyphMinSize, min(geo.size.width, geo.size.height) * PhotosMediaKnobs.facePhotoGlyphFraction))) .foregroundStyle(theme.colors.inkTertiary.color) .frame(width: geo.size.width, height: geo.size.height) .accessibilityHidden(true) } } } private func resolve() async { if imageKey != key { image = nil imageKey = nil rung = nil } guard let key, !key.isEmpty else { state = .absent return } if image == nil { state = .resolving } // ALREADY DECODED at this size AND at a rung this ask is done with: // drawn at once, no boundary crossing. A hero finding the thumbnail it // cached on a second phone is NOT done, and asks the ledger — which is // how it learns the viewer has since fetched the original. if image == nil, let kept = MediaImageCache.shared.picture(key: key, maxPixel: maxPixel), PhotosMediaTier.isDone(tier, with: kept.rung) { image = kept.image imageKey = key rung = kept.rung state = .ready(path: "") return } guard let answer = await media.answer(for: key, tier: tier) else { // Keep what is drawn: a stand-in beats a blur while the bytes are // elsewhere, and `absent` is only ever said about nothing. if image == nil { state = .absent } // A grid never fetches (the sweep fills it); ONE picture drawn // large goes and gets its display copy from the object, once. guard tier == .largest, fetchedFor != key else { return } fetchedFor = key guard (try? await media.ensure(key, tier: tier)) != nil else { return } await resolve() return } // The decode is off the main actor: a grid scrolling past forty tiles // decodes forty squares, and doing that on the main thread is the // stutter this whole file exists to avoid. let pixels = maxPixel let decoded = await Task.detached(priority: .userInitiated) { PhotosImageFile.image(key: key, rung: answer.rung, atPath: answer.path, maxPixel: pixels) }.value if let decoded { image = decoded imageKey = key rung = answer.rung } // Readiness includes the decode, not just finding the file. state = .ready(path: answer.path) // The thumbnail the pictures sweep fetched is a stand-in for a // picture drawn large: drawn now, and its display copy fetched once, // as it would be had nothing been here. guard tier == .largest, answer.rung == .thumb, fetchedFor != key else { return } fetchedFor = key guard (try? await media.ensure(key, tier: tier)) != nil else { return } await resolve() } } // MARK: - The confirm // THE PHOTOS LANE HAS NO DIALOG OF ITS OWN. `PhotosConfirmDialog` — a // `groundElevated` card with the retired slab corner — folded into // `.confirmDecision` in phase 20 (`dress-d`): a delete in the photo library, // on an open photo and on an open video is asked the way every other screen // asks, on the paper slip. **The confirm itself is the product rule, not a // formality**: nothing in Cotton ever deletes a person's pictures on their // behalf, so the only path from a review note to an empty tile runs through a // person choosing rows and reading a sentence that says what goes and where // else it will be missing. `ConfirmSweepTests` holds the one way to ask. /// The sizes, counts and timings PhotosMedia draws with: Swift's own, beside /// their reader — a theme sets only its tokens (`scale.tokens`). enum PhotosMediaKnobs { static let facePhotoBlurRadius: CGFloat = 8 static let facePhotoCornerRadius: CGFloat = 10 static let facePhotoEmptyIconSize: CGFloat = 44 static let facePhotoGlyphFraction: CGFloat = 0.26 static let facePhotoGlyphMinSize: CGFloat = 10 static let facePhotoPlayFraction: CGFloat = 0.28 static let facePhotoPlayMinSize: CGFloat = 8 static let facePhotoViewerVerticalPadding: CGFloat = 16 static let facePhotoZoomMaxScale: CGFloat = 6 static let facePhotoZoomSettle: CGFloat = 1.05 }