// KEEP THIS ALBUM IN COTTON (KEEP slice 1, NEXT-ALBUM-KEEP.md; KEEP 1e, NEXT-KEEP-1E.md): a copy of each photo of an// album he chooses goes to his Cotton space, sealed on this phone, through the media path every app already uses// (`capture.media` → the `_media` ledger → the drain). What is kept is the photo as he sees it now (its edit, else its// original; a RAW photo's rendered picture) and a Live photo's film; a video as it is now (`AlbumsPhotos.keepParts`).//// The rules this file holds:// - "Kept" is the object's own answer, per file (`media.uploads`): a photo is kept when every original it put in the// queue is uploaded; one Cotton refused is "could not be kept", with the reason (review H1).// - A copy of a Photos original is not his for good on this phone: it is queued with `source: photos`, and once the// object holds it the local copy leaves (the core's release); the scratch read goes the moment it is handed over,// and any left by a kill is swept at launch (review H2).// - Never decided by absence: a read of the album that is not whole changes nothing; a photo is left or gone only// when the library REPORTS it so (a change observer), and only once it is in Cotton; one that never reached Cotton// and leaves the album is simply no longer queued (review M1).// - Wi-Fi only unless he turns on mobile data: the read from iCloud is cancelled the moment the path is not one Keep// may use, and every file is queued `network: wifi`, which the drain holds off Wi-Fi (review M4). At most ten// photos or 50 MB of Keep's own wait in the queue, counted from the store, so the bound holds from the first file// after a kill.// - Stop, Stop keeping and the end of the background time stop at once, cancel the read in flight, and nothing starts// again until the app is in front or a new background task is granted (review M3).// - Nothing is ever deleted from Photos or from Cotton.#if os(iOS)importBackgroundTasksimportCottonKitimportFoundationimportObservationimportSwiftUI@MainActor@ObservablefinalclassAlbumsKeeper {staticlet shared = AlbumsKeeper()privatelet store = AlbumsStore.shared @ObservationIgnored privatevar core: (any CottonCalling)?private(set) var running = false/// Kept albums, and their counts as last read (the screens draw these).private(set) var albums: [AlbumsStore.KeptAlbum] = []private(set) var counts: [String: AlbumsStore.KeptCounts] = [:]private(set) var refusals: [String: [(code: String, n: Int)]] = [:]/// Keep's own originals handed over and not yet in Cotton, and their bytes, as the object last said.private(set) var onTheirWay: (files: Int, bytes: Int64) = (0, 0)/// Waiting for Wi-Fi: something is to be kept, and the network it may use is not here.private(set) var waitingForWiFi = false/// Changes whenever the counts do.private(set) var revision = 0/// Stop, Stop keeping's run, or the end of the background time: cleared only by a deliberate start. @ObservationIgnored privatelet stopFlag = KeepStop() @ObservationIgnored privatevar continued: BGTask? @ObservationIgnored privatevar continuedProgress: Progress? @ObservationIgnored privatevar watching = false @ObservationIgnored privatevar uploadsUnanswered = false @ObservationIgnored privatevar saidNetwork: String?privatevar stopAsked: Bool { stopFlag.value }func use(_ core: any CottonCalling) {guardself.core == nilelse { return }self.core = core// The network path is read by a monitor that answers a moment after it starts: start it now, so the first// Keep does not wait for Wi-Fi it is on. _ = AlbumsPass.onWiFiSelf.sweepScratch() #if COTTON_DEVifProcessInfo.processInfo.arguments.contains("-albums-keep-fresh") { store.forgetKept() } #endif refresh() }func refresh() { albums = store.keptAlbums()var out: [String: AlbumsStore.KeptCounts] = [:]var said: [String: [(code: String, n: Int)]] = [:]for album in albums { out[album.album] = store.keptCounts(album.album) said[album.album] = store.keptRefusals(album.album) } counts = out refusals = said revision += 1 }func kept(_ album: String) -> AlbumsStore.KeptAlbum? { albums.first { $0.album == album } }// MARK: His acts/// THE ONE CONSTANT that shows Keep in the real app (the coordinator's, for the cut: owner, 28 Nov, "photo backup/// into Cotton is the real direction"). True since the owner's decision (28 Nov): Keep is in his real Albums build./// Keep only ever reads a photo (no photo-changing call exists in this package; the flavour test holds that).staticlet realFlavourKeeps = true/// Whether this build may keep at all: a Dev build always; the real app once `realFlavourKeeps` says so./// scripts/__tests__/business-flavour.test.ts holds every way in to it.staticvar allowed: Bool { #if COTTON_DEVreturntrue #elsereturn realFlavourKeeps #endif }/// Keep: from now on every photo in this album has a copy in Cotton, and photos added later too.func keep(_ album: String, title: String, cellular: Bool) {guardSelf.allowed else { return } store.keep(album, title: title, cellular: cellular) members() refresh() submitContinued() start() }/// Stop keeping: new photos are no longer kept, from this photo on (the loop asks before each one). Every copy/// already in Cotton stays, and the ones on their way go on.func stopKeeping(_ album: String) { store.stopKeeping(album) refresh() }// MARK: The album, as Photos has it now/// Every kept album's members, from a whole read only (`keptMembers` answers nil otherwise, which changes/// nothing), and the watch moved on to them.func members() {let library = AlbumsLibrary.sharedfor album in store.keptAlbums() {guardlet now = library.keptMembers(of: album.album) else { continue } store.setKeptMembers(album.album, now, keeping: album.keeping, whole: true) } watch() }/// The library's word on kept albums and photos: taken out, deleted, added to.privatefunc watch() {let kept = store.keptAlbums().map(\.album)guard !kept.isEmpty else { return }AlbumsLibrary.shared.watchKept(albums: kept, assets: store.keptAssets()) { change inTask { @MainActor inAlbumsKeeper.shared.reported(change) } } watching = true }func reported(_ change: KeptChange) {for (album, assets) in change.left { store.keptRemoved(album, assets) } store.keptDeleted(change.deleted)if !change.grew.isEmpty { members() } else { watch() } refresh() resume() }// MARK: Running/// A deliberate start (his Keep): clears a stop and runs.func start() {guardSelf.allowed else { return } stopFlag.set(false) run() }/// The app is in front again (a launch, coming back, a library change while open): a stop left by the end of/// the background time is cleared then, and only then.func resume() {guardSelf.allowed else { return }// At launch the app is still inactive: only the background is refused.guard UIApplication.shared.applicationState != .background else { return } start() }/// Runs while nothing has stopped it.func run() {guard !running, core != nil, !stopAsked else { return }Task { await loop() } }func stop() { stopFlag.set(true) }privatefunc loop() async {guard !running, let core, !stopAsked else { return } running = truedefer { running = false; refresh() }let started = ContinuousClock.nowvar handed = 0var handedBytes: Int64 = 0let capture = CoreMediaCapture(core: core)let stop = stopFlagwhiletrue {while !stopAsked {let next = store.toKeep(8)if next.isEmpty { break }var moved = falsefor one in next where !stopAsked {// Stop keeping stops at once: asked before every photo.guard store.keeping(one.album) else { continue }await keepPace()if stopAsked { break }let cellular = one.cellularguardSelf.network(cellular: cellular) else { waitingForWiFi = true; break } waitingForWiFi = false// Over Cotton's limit for one file: said once, never read (a video is at most 500 MB).let size = awaitTask.detached { AlbumsLibrary.shared.keepBytes([one.asset]) }.valueif size.exact, size.bytes > Self.mostBytes { store.keptRefused(one.asset, code: "too_big", why: "\(size.bytes) bytes") moved = truecontinue }let album = one.albumlet dir = Self.scratch()let parts = awaitAlbumsLibrary.shared.keepParts(one.asset, into: dir) {KeepRule.mayGo(stopped: stop.value, cellular: cellular, onWiFi: Self.onWiFi, keeping: AlbumsStore.shared.keeping(album)) }defer { try? FileManager.default.removeItem(at: dir) }switch parts {case .parts(let parts):var keys: [String] = []var records: [String] = []var bytes: Int64 = 0var refused: (code: String, why: String)?var failed: String?let upload = CaptureUpload(network: KeepRule.network(cellular: cellular), askedBy: "albums.keep", source: "photos")for part in parts where refused == nil && failed == nil {do {let captured = tryawait capture.capture(file: part.url, mime: part.mime, kind: part.isVideo ? .video : .photo, filename: part.filename, upload: upload) keys.append(captured.key) records.append(captured.recordId) bytes += part.bytes } catchlet error asCottonCallErrorwhere error.code == "too_large" { refused = ("too_big", error.message) } catchlet error asCottonCallErrorwhere error.code == "bad_request" { refused = ("refused", error.message) } catch { failed = String("\(error)".prefix(200)) }// The scratch copy goes the moment it is handed over: the store holds its own.try? FileManager.default.removeItem(at: part.url) }iflet refused { store.keptRefused(one.asset, code: refused.code, why: String(refused.why.prefix(200))) } elseiflet failed {// Tried again on the next run; what went over already is the same file again (one sha256). store.keptFailed(one.album, one.asset, why: failed) } else { store.keptSending(one.asset, keys: keys, records: records, bytes: bytes) handed += 1 handedBytes += bytes } moved = truecase .stopped:// Not a failure: the network went, Stop, Stop keeping or the end of the background time. It waits.if !Self.network(cellular: cellular) { waitingForWiFi = true }case .hidden:// Hidden in Photos: never read, no longer queued. store.keptRemoved(one.album, [one.asset]) moved = truecase .needsNetwork: store.keptFailed(one.album, one.asset, why: "needs network") moved = truecase .gone:// Not found by this read: tried again, never taken as a deletion (only the library's word is). store.keptFailed(one.album, one.asset, why: "not found") moved = truecase .failed(let why) where why == "no part": store.keptRefused(one.asset, code: "no_part", why: why) moved = truecase .failed(let why): store.keptFailed(one.album, one.asset, why: why) moved = true }if waitingForWiFi { break } } refresh() setProgress()if handed > 0, handed % 50 < 8 { say(handed, handedBytes, started) }await checkUploads()if waitingForWiFi {// The continued task is for work that is going, not for waiting.if continued != nil { break }await waitForNetwork() } elseif !moved {break } }// Handed over: wait for the object to confirm each (bounded: an hour, then the next run carries on).let deadline = ContinuousClock.now + .seconds(3600)var ticks = 0var more = falselet pending = Set(store.toKeep(100).map(\.asset))while !stopAsked, onTheirWay.files > 0, ContinuousClock.now < deadline {// New photos in a kept album meanwhile: copied now, not after the wait.if store.toKeep(100).contains(where: { !pending.contains($0.asset) }) { more = true; break }try? awaitTask.sleep(for: .seconds(5))await checkUploads() setProgress() ticks += 1if ticks % 6 == 0 { say(handed, handedBytes, started) } }if !more || stopAsked { break } } say(handed, handedBytes, started) }/// Asks the object, per file, which handed-over photos it holds (`media.uploads`): one whose every original is/// uploaded is kept; one with a refused original could not be kept, with the reason; one the queue no longer knows/// at all waits to be kept again./// Tells the core's drain the network (MEDIA DRAIN 1 item 2) when it changed: Wi-Fi-only files go up only while/// the core has heard `wifi`.privatefunc sayNetwork() async {guardlet core else { return }let path = Self.pathWordguard path != saidNetwork else { return }do { _ = tryawait core.call(CottonMethod.mediaNetwork, KeepNetworkSay(path: path), as: KeepNetworkSaid.self) saidNetwork = path } catch {Log.write("albums: keep: the core did not hear the network (\(error))") } } nonisolated staticvar pathWord: String { #if COTTON_DEVlet off = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("albums-keep-no-wifi")ifFileManager.default.fileExists(atPath: off.path) { return"mobile" } #endifreturnAlbumsPass.pathWord }privatefunc checkUploads() async {await sayNetwork()guardlet core else { return }let sending = store.keptSendingKeys()guard !sending.isEmpty else { onTheirWay = (0, 0); return }var files: [String: KeepUploads.File] = [:]let keys = sending.flatMap(\.keys)var at = 0while at < keys.count {let page = Array(keys[at..<min(at + 2_000, keys.count)]) at += page.countdo {let answer = tryawait core.call(CottonMethod.mediaUploads, KeepUploadsAsk(keys: page), as: KeepUploads.self)for file in answer.files { files[file.key] = file } } catch {// Not knowing is not kept: nothing changes, and Keep copies no more until the object answers.if !uploadsUnanswered { Log.write("albums: keep: the upload queue did not answer (\(error))") } uploadsUnanswered = true onTheirWay = (Self.ahead + 1, onTheirWay.bytes)return } } uploadsUnanswered = falselet verdict = KeepRule.verdict(sending, files.mapValues {KeepRule.File(key: $0.key, phase: $0.phase, sent: $0.sent, total: $0.total, code: $0.code, line: $0.line) })for refusal in verdict.refused { store.keptRefused(refusal.asset, code: refusal.code, why: refusal.why) }let confirmed = verdict.confirmed, lost = verdict.lostlet left = verdict.files, leftBytes = verdict.bytes store.keptConfirmed(confirmed) store.keptAgain(lost) onTheirWay = (left, leftBytes)if !confirmed.isEmpty || !lost.isEmpty || !verdict.refused.isEmpty { refresh() } }/// Keep's own originals that may wait in Cotton's queue before Keep copies more: about ten photos, enough to keep/// the drain's three uploads busy. nonisolated staticlet ahead = 10/// And bytes: ten long videos are ten files too (walk 2: 37 files were 299 MB). nonisolated staticlet aheadBytes: Int64 = 50_000_000/// The most one file may weigh in Cotton (a video; `cotton-rules` media limits). nonisolated staticlet mostBytes: Int64 = 524_288_000/// Waits while more than `ahead` of Keep's own originals, or `aheadBytes` of them, are on their way, however long/// a big file takes. Counted from the store and the object's answer, so it holds from the first file after a kill.privatefunc keepPace() async {await checkUploads()var ticks = 0while !stopAsked, onTheirWay.files > Self.ahead || onTheirWay.bytes > Self.aheadBytes {try? awaitTask.sleep(for: .seconds(2))await checkUploads() ticks += 1if ticks % 30 == 0 { Log.write("albums: keep: waiting for \(onTheirWay.files) files to upload") } } }privatefunc waitForNetwork() async {Log.write("albums: keep: waiting for Wi-Fi")defer { Log.write("albums: keep: \(waitingForWiFi ? "still waiting forWi-Fi" : "on Wi-Fi again")") }let deadline = ContinuousClock.now + .seconds(600)while !stopAsked, ContinuousClock.now < deadline {try? awaitTask.sleep(for: .seconds(2))await sayNetwork()ifSelf.onWiFi { waitingForWiFi = false; return } } }privatefunc say(_ handed: Int, _ bytes: Int64, _ started: ContinuousClock.Instant) {let all = store.keptCounts()let took = started.duration(to: .now)let seconds = Double(took.components.seconds) + Double(took.components.attoseconds) / 1e18Log.write("albums: keep \(all.kept) kept, \(all.sending) sending, \(all.waiting) waiting, \(all.failed) failed, \(all.refused) refused, \(all.left) left, \(all.gone) gone of \(all.total); this run \(handed) handed over, \(bytes) bytes, \(Int(seconds)) s, \(onTheirWay.files) files on their way\(waitingForWiFi ? ", waiting forWi-Fi" : "")") }/// The network keeping may use: Wi-Fi, or any when he turned on mobile data.staticfunc network(cellular: Bool) -> Bool { cellular || onWiFi } nonisolated staticvar onWiFi: Bool { #if COTTON_DEV// The walk's Wi-Fi off on a simulator, which shares the Mac's network: Documents/albums-keep-no-wifi.let off = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("albums-keep-no-wifi")ifFileManager.default.fileExists(atPath: off.path) { returnfalse } #endifreturnAlbumsPass.onWiFi } nonisolated staticfunc scratch() -> URL {let dir = FileManager.default.temporaryDirectory.appendingPathComponent("albums-keep-\(UUID().uuidString)", isDirectory: true)try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)return dir }/// Scratch reads a kill left behind: swept at launch, before any read begins. nonisolated staticfunc sweepScratch() {let tmp = FileManager.default.temporaryDirectoryfor name in (try? FileManager.default.contentsOfDirectory(atPath: tmp.path)) ?? [] where name.hasPrefix("albums-keep-") {try? FileManager.default.removeItem(at: tmp.appendingPathComponent(name)) } }// MARK: The background/// Started by his Keep tap: carries on when he leaves Albums, with the phone's own progress and Stop. The same/// wildcard the look pass is permitted under (`<bundle>.pass.*`). nonisolated staticvar continuedID: String { (Bundle.main.bundleIdentifier ?? "com.cottondb.albums") + ".pass.keep" } nonisolated staticfunc registerTask() {let permitted = Bundle.main.object(forInfoDictionaryKey: "BGTaskSchedulerPermittedIdentifiers") as? [String] ?? []guard permitted.contains(where: { $0.hasSuffix(".pass.*") }) else { return } BGTaskScheduler.shared.register(forTaskWithIdentifier: continuedID, using: nil) { task inlet held = KeepHeldTask(task)Task { @MainActor inawaitAlbumsKeeper.shared.runContinued(held.task) } } }privatefunc runContinued(_ task: BGTask) async { continued = task continuedProgress = (task as? BGContinuedProcessingTask)?.progress// The end of the background time: stops at once and cancels the read in flight; nothing starts again until// the app is in front or a new task is granted. task.expirationHandler = { [stopFlag] in stopFlag.set(true) }// A new grant is a deliberate start. stopFlag.set(false) setProgress()// A run already going in the foreground carries on, reporting to this task.while running && !stopAsked { try? awaitTask.sleep(for: .seconds(1)) }if !stopAsked { await loop() }let all = store.keptCounts() task.setTaskCompleted(success: !stopAsked && all.waiting == 0 && all.sending == 0) continued = nil continuedProgress = nil }privatefunc setProgress() {guardlet progress = continuedProgress else { return }let all = store.keptCounts()let active = all.waiting + all.sending + all.kept + all.failed + all.refused progress.totalUnitCount = Int64(max(1, active)) progress.completedUnitCount = Int64(all.kept + all.refused) }privatefunc submitContinued() {let permitted = Bundle.main.object(forInfoDictionaryKey: "BGTaskSchedulerPermittedIdentifiers") as? [String] ?? []guard permitted.contains(where: { $0.hasSuffix(".pass.*") }) else { return }let waiting = store.keptCounts().waitinglet request = BGContinuedProcessingTaskRequest(identifier: Self.continuedID, title: AlbumsWords.keeping(waiting), subtitle: AlbumsWords.keepingLine) request.strategy = .queuedo { try BGTaskScheduler.shared.submit(request) } catch { Log.write("albums: keep: continued task not taken (\(error.localizedDescription))") } }}/// A task the scheduler hands over on its own queue, carried to the main actor that alone touches it after.privatestructKeepHeldTask: @unchecked Sendable {let task: BGTaskinit(_ task: BGTask) { self.task = task }}/// `media.uploads`'s question.structKeepUploadsAsk: Encodable { let keys: [String] }structKeepNetworkSay: Encodable { let path: String }structKeepNetworkSaid: Decodable { let path: String }/// `media.uploads`'s answer, the part Keep reads.structKeepUploads: Decodable {structFile: Decodable {let key: Stringlet phase: Stringlet sent: Int64?let total: Int64?let code: String?let line: String? }let files: [File]}// MARK: - The screens/// On a Photos album of his: "Keep this album in Cotton", or, once kept, where its photos are.structAlbumsKeepBand: View {let model: AlbumsModellet id: Stringlet title: Stringprivatelet keeper = AlbumsKeeper.shared @State privatevar asking = falseprivatefunc say(_ path: String, _ fills: [String: String] = [:]) -> String { AlbumsWords.keep(path, fills) }var body: someView {let _ = keeper.revisionGroup {iflet kept = keeper.kept(id) { band(kept, keeper.counts[id] ?? AlbumsStore.KeptCounts()) } else {Button { model.sheet = .keep(id: id, title: title) } label: { HStack(alignment: .center, spacing: 14) {Image(systemName: "icloud.and.arrow.up").font(.system(size: 18, weight: .light)).foregroundStyle(Olive.ink).accessibilityHidden(true) VStack(alignment: .leading, spacing: 3) {Text(verbatim: say("row")).font(AlbumsType.name).foregroundStyle(Olive.ink)Text(verbatim: say("ask_line")).font(AlbumsType.line).foregroundStyle(Olive.quiet).fixedSize(horizontal: false, vertical: true) } .frame(maxWidth: .infinity, alignment: .leading)Image(systemName: "chevron.right").font(.system(size: 13, weight: .semibold)).foregroundStyle(Olive.quiet).accessibilityHidden(true) } .padding(.vertical, 12) .overlay(alignment: .top) { Rectangle().fill(Olive.ink).frame(height: 2) } .overlay(alignment: .bottom) { AlbumsRule() } .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityIdentifier("albums-keep-row") } } .padding(.horizontal, Olive.side).padding(.top, 12) }privatefunc band(_ kept: AlbumsStore.KeptAlbum, _ c: AlbumsStore.KeptCounts) -> someView {let active = c.waiting + c.sending + c.kept + c.failed + c.refusedlet size = AlbumsWords.size(c.bytes)// Going: something waits, is on its way, or will be tried again.let going = c.waiting + c.sending + c.retrying > 0let head: String = {if !kept.keeping { return say("stopped", ["n": c.kept.formatted()]) }if !going { return say("done", ["n": c.kept.formatted(), "size": size]) }return say("band_head", ["n": active.formatted()]) }()var lines: [String] = []if kept.keeping, going {// Kept: the object answered for every original of it. lines.append(say("band_progress", ["done": c.kept.formatted(), "n": active.formatted(), "size": size])) }if c.sending > 0, keeper.onTheirWay.files > 0 { lines.append(say(kept.keeping ? "sending_line" : "stopped_sending", ["n": keeper.onTheirWay.files.formatted()])) }if kept.keeping, going {if keeper.waitingForWiFi { lines.append(say("band_wifi")) } elseif c.waiting > 0 { lines.append(say("band_away")) } }if c.retrying > 0 { lines.append(say("failed", ["n": c.retrying.formatted()])) }if c.failed > c.retrying { lines.append(say("failed_stopped", ["n": (c.failed - c.retrying).formatted()])) }for refusal in keeper.refusals[id] ?? [] { lines.append(say("refused", ["n": refusal.n.formatted(), "why": say("why_\(refusal.code)")])) }if c.left + c.gone > 0 { lines.append(say("left_line", ["n": (c.left + c.gone).formatted()])) }returnAlbumsBand(head: head, lines: lines, end: {if kept.keeping {Button(say("stop")) { asking = true } .buttonStyle(AlbumsOutlineButtonStyle()) .accessibilityIdentifier("albums-keep-stop") } }, below: {if kept.keeping, going, active > 0 {AlbumsProgressBar(fraction: Double(c.kept + c.refused) / Double(active), paused: keeper.waitingForWiFi) } }) .accessibilityElement(children: .contain) .accessibilityIdentifier("albums-keep-band") .confirmationDialog(say("stop_ask"), isPresented: $asking, titleVisibility: .visible) {Button(say("stop")) { keeper.stopKeeping(id) }Button(say("cancel"), role: .cancel) {} } message: {Text(verbatim: say("stop_line", ["n": c.kept.formatted()])) } }}/// The ask before keeping: what it is, what it weighs, how RAW photos are kept, and the mobile data switch.structAlbumsKeepSheet: View {let id: Stringlet title: Stringlet close: () -> Void @State privatevar cellular = false @State privatevar count = 0 @State privatevar size = KeepSize() @State privatevar measured = falseprivatefunc say(_ path: String, _ fills: [String: String] = [:]) -> String { AlbumsWords.keep(path, fills) }var body: someView { VStack(alignment: .leading, spacing: 0) {Text(verbatim: say("ask_title", ["title": title])).font(AlbumsType.sans(25, .bold, .title2)).foregroundStyle(Olive.ink) .fixedSize(horizontal: false, vertical: true).accessibilityAddTraits(.isHeader)Text(verbatim: say("ask_size", ["n": count.formatted(), "size": AlbumsWords.size(size.bytes, exact: size.exact)])) .font(AlbumsType.name).foregroundStyle(Olive.ink).padding(.top, 10) .accessibilityIdentifier("albums-keep-size")Text(verbatim: say("row_line")) .font(AlbumsType.line).foregroundStyle(Olive.quiet).fixedSize(horizontal: false, vertical: true).padding(.top, 6)Text(verbatim: say("ask_line")).font(AlbumsType.line).foregroundStyle(Olive.quiet).fixedSize(horizontal: false, vertical: true).padding(.top, 6)if size.raw > 0 {Text(verbatim: say("raw_line", ["n": size.raw.formatted()])).font(AlbumsType.line).foregroundStyle(Olive.quiet) .fixedSize(horizontal: false, vertical: true).padding(.top, 6) .accessibilityIdentifier("albums-keep-raw-line") }Toggle(isOn: $cellular) { Text(verbatim: say("cellular")).font(AlbumsType.name).foregroundStyle(Olive.ink) } .tint(Olive.accent).padding(.vertical, 10) .overlay(alignment: .bottom) { AlbumsRule() } .padding(.top, 14) .accessibilityIdentifier("albums-keep-cellular")Button(say("keep")) { close()AlbumsKeeper.shared.keep(id, title: title, cellular: cellular) } .buttonStyle(AlbumsMainButtonStyle()) .disabled(count == 0) .padding(.top, 20) .accessibilityIdentifier("albums-keep-yes") } .task {guard !measured else { return } measured = truelet album = id// Exactly what Keep sends (no RAW file), from PhotoKit's own sizes, off the main thread. His space is said// only when the object has said it (from 80% full), never a number assumed.let read = awaitTask.detached { () -> (Int, KeepSize) inlet members = AlbumsLibrary.shared.keptMembers(of: album) ?? AlbumsLibrary.shared.members(of: album)return (members.count, AlbumsLibrary.shared.keepBytes(members)) }.value count = read.0 size = read.1 } }}#endif