// 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.importCottonKitimportImageIOimportSwiftUI#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.structPhotosMediaKeyRequest: 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 = keyself.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.publicenumPhotosMediaTier: 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.publicstaticfunc isDone(_ tier: PhotosMediaTier?, with rung: MediaRung) -> Bool {switch tier {casenil: returntruecase .largest, .original: return rung == .original } }}/// What `read.mediaPath` answered: where the file is, and which rung it is.publicstructPhotosMediaAnswer: Equatable, Sendable {publicvar path: Stringpublicvar 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.publicstructPhotosMediaSource: Sendable {privatelet core: any CottonCallingpublicinit(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.publicfunc 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.publicfunc answer(for key: String, tier: PhotosMediaTier? = nil) async -> PhotosMediaAnswer? {guard !key.isEmpty else { returnnil }let answer = try? await core.callJSON(CottonMethod.readMediaPath,PhotosMediaKeyRequest(key: key, tier: tier) )guardlet answer, answer.flag("present"), let path = answer.text("path"),let rung = MediaRung(answered: answer)else { returnnil }returnPhotosMediaAnswer(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.publicfunc ensure(_ key: String, tier: PhotosMediaTier? = nil) asyncthrows -> String {let answer = tryawait 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.publicfunc 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.publicenumPhotosImageFile {/// 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.publicstaticfunc 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.publicstaticfunc 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.publicenumPhotosBlur {/// 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.publicstaticfunc image(base64: String?) -> UIImage? {guardlet base64, !base64.isEmpty else { returnnil }iflet kept = MediaImageCache.shared.blur(base64: base64) { return kept }guardlet data = Data(base64Encoded: base64), let made = UIImage(data: data) else {returnnil }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.enumPhotosTileState: Equatable, Sendable {/// Asking the ledger.case resolvingcase 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.publicstructPhotosPicture: View { @Environment(\.theme) privatevar themeprivatelet media: PhotosMediaSource/// The OBJECT key — a picture's own, a film's POSTER. `nil` is a real/// state and draws the absence.privatelet key: String?privatelet 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.privatelet maxPixel: Int/// Which rung to ask for. `nil` — the tile's order — for every grid; a/// detail view's hero says `.largest`.privatelet tier: PhotosMediaTier?privatelet blankWhileLoading: Bool @State privatevar state: PhotosTileState = .resolving @State privatevar 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 privatevar 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 privatevar 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 privatevar 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.privatevar isDone: Bool {guardcase .ready = state, let rung else { returnfalse }returnPhotosMediaTier.isDone(tier, with: rung) }publicinit( media: PhotosMediaSource, key: String?, preview: String? = nil, maxPixel: Int, tier: PhotosMediaTier? = nil, blankWhileLoading: Bool = false ) {self.media = mediaself.key = keyself.preview = previewself.maxPixel = maxPixelself.tier = tierself.blankWhileLoading = blankWhileLoading }publicvar body: someView {// 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 privatevar content: someView {iflet image {Image(uiImage: image) .resizable() .scaledToFill() } elseif blankWhileLoading {Color.clear } elseiflet 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) } } }privatefunc resolve() async {if imageKey != key { image = nil imageKey = nil rung = nil }guardlet key, !key.isEmpty else { state = .absentreturn }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 }guardlet 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 = keyguard (try? await media.ensure(key, tier: tier)) != nilelse { 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 = maxPixellet decoded = awaitTask.detached(priority: .userInitiated) {PhotosImageFile.image(key: key, rung: answer.rung, atPath: answer.path, maxPixel: pixels) }.valueiflet 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 = keyguard (try? await media.ensure(key, tier: tier)) != nilelse { 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`).enumPhotosMediaKnobs {staticlet facePhotoBlurRadius: CGFloat = 8staticlet facePhotoCornerRadius: CGFloat = 10staticlet facePhotoEmptyIconSize: CGFloat = 44staticlet facePhotoGlyphFraction: CGFloat = 0.26staticlet facePhotoGlyphMinSize: CGFloat = 10staticlet facePhotoPlayFraction: CGFloat = 0.28staticlet facePhotoPlayMinSize: CGFloat = 8staticlet facePhotoViewerVerticalPadding: CGFloat = 16staticlet facePhotoZoomMaxScale: CGFloat = 6staticlet facePhotoZoomSettle: CGFloat = 1.05}