// THE LIBRARY LAYER (assets/design/albums/RESEARCH.md §1): the phone's own photo library, and nothing else. PhotoKit// itself is in the app target, compiled only into Cotton Albums (`App/Cotton/AlbumsPhotos+Photos.swift`, installed at// launch as `AlbumsPhotos`): this shared package names no PhotoKit class, so no other app references PHPhotoLibrary// (ITMS-90683). Here: the shapes, the rules that need no PhotoKit, and `AlbumsLibrary`, which forwards. The bytes stay in Photos; Albums reads what the phone already holds and never downloads an original to look at// it. What it reads:// - access, full or limited, and asking for it;// - every asset's metadata (all local: date, kind, subtypes, pixel size, duration, favourite, burst, place), every// shot of a burst included;// - the size of each asset on disk: exact where the phone says (`PHAssetResource.dataSize`, iOS 27), else the// undocumented `fileSize` key, else "about" from pixels, duration and kind;// - the best LOCAL picture at a small size with the network off; an asset with none is said (only in iCloud), never// fetched here;// - changes, while running (`PHPhotoLibraryChangeObserver`) and across launches (`fetchPersistentChanges(since:)`// from a saved token; an expired token means a full pass);// - real albums: Photos' own albums and smart albums, made and filled here (Albums he makes also appear in Photos);// - deleting in batches behind the one system confirmation per batch, with a timeout and a re-read of the library// to learn what really went (iOS 18.5–27 can lose the confirmation's answer, RESEARCH.md §1).#if os(iOS)importCoreGraphicsimportFoundationimportImageIOimport UIKit/// Whether Albums may read the library.publicenumAlbumsAccess: String, Sendable, Equatable {case unasked, full, limited, denied, restrictedpublicvar reads: Bool { self == .full || self == .limited }}/// One asset's metadata, all of it local.publicstructLibraryAsset: Sendable, Equatable, Identifiable {publicenumKind: String, Sendable { case photo, video, audio, other }publicstructFlags: OptionSet, Sendable, Hashable {publiclet rawValue: UInt32publicinit(rawValue: UInt32) { self.rawValue = rawValue }publicstaticlet screenshot = Flags(rawValue: 1 << 0)publicstaticlet live = Flags(rawValue: 1 << 1)publicstaticlet hdr = Flags(rawValue: 1 << 2)publicstaticlet panorama = Flags(rawValue: 1 << 3)publicstaticlet screenRecording = Flags(rawValue: 1 << 4)publicstaticlet depth = Flags(rawValue: 1 << 5)publicstaticlet favourite = Flags(rawValue: 1 << 6)publicstaticlet hidden = Flags(rawValue: 1 << 7)publicstaticlet burstPick = Flags(rawValue: 1 << 8)publicstaticlet cinematic = Flags(rawValue: 1 << 9)publicstaticlet slowMo = Flags(rawValue: 1 << 10)publicstaticlet timelapse = Flags(rawValue: 1 << 11)/// Came from a shared or iTunes-synced source, not the camera roll.publicstaticlet notCameraRoll = Flags(rawValue: 1 << 12) }publiclet id: Stringpubliclet kind: Kindpubliclet flags: Flagspubliclet created: Date?publiclet modified: Date?publiclet width: Intpubliclet height: Intpubliclet duration: Doublepubliclet burst: String?publiclet latitude: Double?publiclet longitude: Double?publicinit(id: String, kind: Kind, flags: Flags, created: Date?, modified: Date?, width: Int, height: Int, duration: Double, burst: String?, latitude: Double?, longitude: Double?) {self.id = idself.kind = kindself.flags = flagsself.created = createdself.modified = modifiedself.width = widthself.height = heightself.duration = durationself.burst = burstself.latitude = latitudeself.longitude = longitude }var pixels: Int { width * height }var longEdge: Int { max(width, height) }}/// What an asset takes on disk.publicstructLibrarySize: Sendable, Equatable {/// One part of an item: RAW and JPEG, an edit and its original, a Live photo's picture and film are one item with/// parts (coordinator's rule D), as PhotoKit keeps them: one asset, several resources.publicstructPart: Sendable, Equatable {publiclet kind: Stringpubliclet bytes: Int64?publiclet filename: Stringpublicinit(kind: String, bytes: Int64?, filename: String) {self.kind = kindself.bytes = bytesself.filename = filename } }publiclet bytes: Int64/// The phone said it; otherwise it is "about", from pixels, duration and kind.publiclet exact: Bool/// The original's file name (IMG_1234.HEIC, or WhatsApp's own), when the phone says.publiclet filename: String?publicvar parts: [Part] = []publicinit(bytes: Int64, exact: Bool, filename: String?, parts: [Part] = []) {self.bytes = bytesself.exact = exactself.filename = filenameself.parts = parts }}/// The best picture the phone holds with the network off./// One of Photos' albums.publicstructLibraryAlbum: Sendable, Equatable, Identifiable {publicenumKind: String, Sendable { case mine, smart, shared }publiclet id: Stringpubliclet title: Stringpubliclet kind: Kindpubliclet count: Intpubliclet canAdd: Boolpublicinit(id: String, title: String, kind: Kind, count: Int, canAdd: Bool) {self.id = idself.title = titleself.kind = kindself.count = countself.canAdd = canAdd }}/// What a delete did, read back from the library, never assumed.publicstructLibraryDeleteOutcome: Sendable, Equatable {publiclet asked: Intpubliclet gone: Int/// The person said no at the phone's confirmation.publiclet refused: Bool/// The confirmation's answer never came (the ProRAW bug); `gone` is what the re-read found.publiclet timedOut: Boolpublicinit(asked: Int, gone: Int, refused: Bool, timedOut: Bool) {self.asked = askedself.gone = goneself.refused = refusedself.timedOut = timedOut }}/// Every change Albums can make to the photo library, implemented in the app target only/// (`App/Cotton/AlbumsWrites+Photos.swift`) and installed at launch, never in a look-only build (`AlbumsLibrary.writes`).publicprotocolAlbumsWrites: Sendable {func makeAlbum(_ title: String, with ids: [String]) asyncthrows -> Stringfunc add(_ ids: [String], to albumID: String) asyncthrowsfunc rename(_ albumID: String, to title: String) asyncthrowsfunc deleteAlbum(_ albumID: String) asyncthrowsfunc delete(_ ids: [String], batch: Int, timeout: TimeInterval) async -> LibraryDeleteOutcome}/// The app target's door to install `AlbumsWrites`.publicenumAlbumsWritesInstall {publicstaticfunc install(_ writes: any AlbumsWrites) { AlbumsLibrary.writes = writes }}extensionLibraryAsset {/// What it takes on disk, about, when the phone does not say (`AlbumsLibrary.about`).publicvar aboutBytes: Int64 { AlbumsLibrary.about(self) }}publicenumLibraryChange: Sendable, Equatable {/// Something changed: read again (inserted, removed and changed ids where the phone says).case changed(inserted: [String], removed: [String], updated: [String])/// Across launches the token had expired: a whole pass.case wholePass}/// Everything Albums reads of the photo library, implemented with PhotoKit in the app target only/// (`App/Cotton/AlbumsPhotos+Photos.swift`, compiled only into Cotton Albums) and installed at launch.publicprotocolAlbumsPhotos: AnyObject, Sendable {var access: AlbumsAccess { get }func ask() async -> AlbumsAccess @MainActor func chooseMore(from controller: UIViewController)func assets() -> [LibraryAsset]func count() -> Intfunc assets(_ ids: [String]) -> [LibraryAsset]func cloudIDs(_ ids: [String]) -> [String: String]func size(_ asset: LibraryAsset) -> LibrarySizefunc sizes(_ assets: [LibraryAsset]) -> [String: LibrarySize]func originalLongEdge(_ id: String) -> Int?func request(_ id: String, side: CGFloat, mode: AlbumsPictureMode, network: Bool) async -> LocalPicturefunc measureSizes(count: Int) asyncfunc thumbnail(_ id: String, side: CGFloat, deliver: @escaping @Sendable (UIImage?) -> Void) -> Int32?func cancel(_ request: Int32)/// Keep: writes the parts of one asset that Keep keeps into `dir`: the photo as he sees it now (its edit, else/// its original; a RAW photo's rendered picture, never its RAW file) and a Live photo's motion; a video as it is/// now. A part only in iCloud is fetched; `mayGo` is asked as each piece arrives, and the read is CANCELLED the/// moment it answers false (the network Keep may use went, Stop, the background time ended): `.stopped`, nothing/// left in `dir`. A hidden asset is never read: `.hidden`.func keepParts(_ id: String, into dir: URL, mayGo: @escaping @Sendable () -> Bool) async -> KeepParts/// What Keep would send for these assets, from PhotoKit's own file sizes.func keepBytes(_ ids: [String]) -> KeepSizefunc albums() -> [LibraryAlbum]func members(of albumID: String) -> [String]/// A kept album's members from a read that ran WHOLE (full access, the album found), hidden ones left out; `nil`/// when it could not, which changes nothing (review M1: never decide by absence).func keptMembers(of albumID: String) -> [String]?/// Watch kept albums and their photos: `seen` is told, as the library reports them, which photos LEFT which/// album and which were DELETED from the library (a change observer's removed objects), and when an album gained/// some. Called again with the current lists whenever they change.func watchKept(albums: [String], assets: [String], seen: @escaping @Sendable (KeptChange) -> Void)func observe(_ seen: @escaping @Sendable (LibraryChange) -> Void) -> UUIDfunc stopObserving(_ key: UUID)func changes() throws -> (LibraryChange, Data?)func saveToken(_ token: Data?)var hasToken: Bool { get }}/// One file Keep sends to Cotton: a part of one asset, written by PhotoKit to a scratch file.publicstructKeepPart: Sendable, Equatable {/// `picture` (the photo or video as he sees it), `motion` (a Live photo's film) or `raw`.publiclet role: Stringpubliclet isVideo: Boolpubliclet url: URLpubliclet mime: Stringpubliclet filename: Stringpubliclet bytes: Int64publicinit(role: String, isVideo: Bool, url: URL, mime: String, filename: String, bytes: Int64) {self.role = roleself.isVideo = isVideoself.url = urlself.mime = mimeself.filename = filenameself.bytes = bytes }}/// What asking for an asset's parts came to.publicenumKeepParts: Sendable, Equatable {case parts([KeepPart])/// A part is only in iCloud and iCloud did not answer.case needsNetwork/// The read was cancelled as `mayGo` said: nothing was written.case stopped/// The asset is not in the library (as far as this read could tell; never taken as a deletion).case gone/// The asset is hidden in Photos: Keep never reads it.case hiddencase failed(String)}/// What Keep would send, from PhotoKit's own file sizes.publicstructKeepSize: Sendable, Equatable {publicvar bytes: Int64/// False when a part had no size PhotoKit would say.publicvar exact: Bool/// Photos with a RAW original: kept as the picture he sees (the RAW file is not taken by Cotton yet).publicvar raw: Intpublicinit(bytes: Int64 = 0, exact: Bool = false, raw: Int = 0) {self.bytes = bytesself.exact = exactself.raw = raw }}/// What the library reported about kept photos.publicstructKeptChange: Sendable, Equatable {/// Album id → photos taken out of it.publicvar left: [String: [String]] = [:]/// Photos deleted from the library.publicvar deleted: [String] = []/// Albums that gained photos.publicvar grew: [String] = []publicinit(left: [String: [String]] = [:], deleted: [String] = [], grew: [String] = []) {self.left = leftself.deleted = deletedself.grew = grew }publicvar isEmpty: Bool { left.values.allSatisfy(\.isEmpty) && deleted.isEmpty && grew.isEmpty }}/// The app target's door to install `AlbumsPhotos`.publicenumAlbumsPhotosInstall {publicstaticfunc install(_ photos: any AlbumsPhotos) { AlbumsLibrary.photos = photos }}/// The phone's library as Albums uses it: forwards to the installed `AlbumsPhotos`. In an app that installs none (every/// app but Cotton Albums, and tests), it reads nothing: access is unasked and the library empty.finalclassAlbumsLibrary: @unchecked Sendable {staticlet shared = AlbumsLibrary() nonisolated(unsafe) staticvar photos: (any AlbumsPhotos)?// MARK: Accessstaticvar access: AlbumsAccess { photos?.access ?? .unasked }/// Asks once; the phone's own question. Answers what was chosen.staticfunc ask() async -> AlbumsAccess { await photos?.ask() ?? .unasked }/// With limited access, the phone's own picker of which photos Albums may see. @MainActor staticfunc chooseMore(from controller: UIViewController) { photos?.chooseMore(from: controller) }// MARK: Reading/// Every photo and video, oldest first, every shot of a burst included, and whether its absences may be read as/// deletions (coordinator's rule A, 27 Nov: absence never removes a choice): only with full access and an/// enumeration that ran to its end. With limited access a shorter list is only what he chose to show.func enumerate() -> (assets: [LibraryAsset], complete: Bool) {let full = Self.access == .fulllet found = assets()return (found, full && found.count == count()) }func assets() -> [LibraryAsset] { Self.photos?.assets() ?? [] }func count() -> Int { Self.photos?.count() ?? 0 }func assets(_ ids: [String]) -> [LibraryAsset] { Self.photos?.assets(ids) ?? [] }/// Apple's cloud identifiers for these assets, the same on every Apple device on one iCloud library.func cloudIDs(_ ids: [String]) -> [String: String] { Self.photos?.cloudIDs(ids) ?? [:] }// MARK: Sizesfunc size(_ asset: LibraryAsset) -> LibrarySize { Self.photos?.size(asset) ?? LibrarySize(bytes: Self.about(asset), exact: false, filename: nil) }func sizes(_ assets: [LibraryAsset]) -> [String: LibrarySize] { Self.photos?.sizes(assets) ?? [:] }/// About: HEIC is near 0.25 bytes a pixel for a camera photo, a screenshot's PNG near 1; video about 1 MB a/// second at 1080p and 3 at 4K.staticfunc about(_ asset: LibraryAsset) -> Int64 {switch asset.kind {case .video:let rate: Double = asset.longEdge >= 3000 ? 3_000_000 : asset.longEdge >= 1800 ? 1_000_000 : 400_000returnInt64(max(1, asset.duration) * rate)default:let perPixel = asset.flags.contains(.screenshot) ? 1.0 : 0.25returnInt64(Double(max(1, asset.pixels)) * perPixel) + (asset.flags.contains(.live) ? 2_500_000 : 0) } }// MARK: Pictures/// The picture for one look, near `side` pixels on its long edge, the network off: AlbumsPicture's rule (high/// quality first, the long edge checked, small when short of enough) over the phone's answers.func localPicture(_ id: String, side: CGFloat, network: Bool = false) async -> LocalPicture {guardlet photos = Self.photos, let longEdge = photos.originalLongEdge(id) else { return .failed("gone") }returnawaitAlbumsPicture.ask(originalLongEdge: longEdge) { mode inawait photos.request(id, side: side, mode: mode, network: network) } }func measureSizes(count: Int) async { awaitSelf.photos?.measureSizes(count: count) }/// A picture for a screen (a grid tile, a Set's shot), which may be degraded first and then sharpen. Never asks/// the network.func thumbnail(_ id: String, side: CGFloat, deliver: @escaping @Sendable (UIImage?) -> Void) -> Int32? {guardlet photos = Self.photos else { deliver(nil); returnnil }return photos.thumbnail(id, side: side, deliver: deliver) }func cancel(_ request: Int32) { Self.photos?.cancel(request) }// MARK: Albumsfunc albums() -> [LibraryAlbum] { Self.photos?.albums() ?? [] }func members(of albumID: String) -> [String] { Self.photos?.members(of: albumID) ?? [] }// MARK: Keepfunc keepParts(_ id: String, into dir: URL, mayGo: @escaping @Sendable () -> Bool) async -> KeepParts {guardlet photos = Self.photos else { return .gone }returnawait photos.keepParts(id, into: dir, mayGo: mayGo) }func keepBytes(_ ids: [String]) -> KeepSize { Self.photos?.keepBytes(ids) ?? KeepSize() }func keptMembers(of albumID: String) -> [String]? { Self.photos?.keptMembers(of: albumID) }func watchKept(albums: [String], assets: [String], seen: @escaping @Sendable (KeptChange) -> Void) {Self.photos?.watchKept(albums: albums, assets: assets, seen: seen) }// MARK: Writing (the app installs it; a look-only app has none)/// The ONLY code that changes the photo library (albums made, renamed, deleted; photos deleted) lives in the app/// target (`App/Cotton/AlbumsWrites+Photos.swift`), compiled only into an app that may write photos. Cotton/// Albums' first build is LOOK-ONLY (owner, 27 Nov): its flavour says `photoWrites: false`, so it is built with/// `COTTON_NO_PHOTO_WRITES`, the file is not compiled, `writes` stays nil, and no call to/// `PHPhotoLibrary.performChanges` exists anywhere in its binary. `scripts/__tests__/business-flavour.test.ts` ("albums: the look-only build") holds/// the rule: this package names no photo-changing API at all. nonisolated(unsafe) staticvar writes: (any AlbumsWrites)?/// Whether this build can change the photo library at all. Screens draw no act when it cannot.staticvar canWrite: Bool { writes != nil }func makeAlbum(_ title: String, with ids: [String]) asyncthrows -> String {guardlet w = Self.writes else { throwAlbumsLibraryError.lookOnly }returntryawait w.makeAlbum(title, with: ids) }func add(_ ids: [String], to albumID: String) asyncthrows {guardlet w = Self.writes else { throwAlbumsLibraryError.lookOnly }tryawait w.add(ids, to: albumID) }func rename(_ albumID: String, to title: String) asyncthrows {guardlet w = Self.writes else { throwAlbumsLibraryError.lookOnly }tryawait w.rename(albumID, to: title) }/// Deletes the album, never its photos.func deleteAlbum(_ albumID: String) asyncthrows {guardlet w = Self.writes else { throwAlbumsLibraryError.lookOnly }tryawait w.deleteAlbum(albumID) }/// Only ever called from his Delete tap on this phone, with exactly the ids the screen showed (rule C). In a/// look-only build nothing is asked of the system: every id stays, and the outcome says it was refused.func delete(_ ids: [String]) async -> LibraryDeleteOutcome {guardlet w = Self.writes else { returnLibraryDeleteOutcome(asked: ids.count, gone: 0, refused: true, timedOut: false) }returnawait w.delete(ids, batch: 10_000, timeout: 300) }// MARK: Changes/// Calls `seen` with each change while Albums runs. Answers a key to stop. @discardableResultfunc observe(_ seen: @escaping @Sendable (LibraryChange) -> Void) -> UUID { Self.photos?.observe(seen) ?? UUID() }func stopObserving(_ key: UUID) { Self.photos?.stopObserving(key) }/// What changed since the token saved last, by id; `.wholePass` when there is none or it expired.func changes() throws -> (LibraryChange, Data?) { trySelf.photos?.changes() ?? (.wholePass, nil) }func saveToken(_ token: Data?) { Self.photos?.saveToken(token) }var hasToken: Bool { Self.photos?.hasToken ?? false }}publicenumAlbumsLibraryError: Error { case notMade, cannotAdd, lookOnly }#endif