Cotton code
435 lines · 20.2 KB · SwiftRaw
// 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)import CoreGraphicsimport Foundationimport ImageIOimport UIKit/// Whether Albums may read the library.public enum AlbumsAccess: String, Sendable, Equatable {    case unasked, full, limited, denied, restricted    public var reads: Bool { self == .full || self == .limited }}/// One asset's metadata, all of it local.public struct LibraryAsset: Sendable, Equatable, Identifiable {    public enum Kind: String, Sendable { case photo, video, audio, other }    public struct Flags: OptionSet, Sendable, Hashable {        public let rawValue: UInt32        public init(rawValue: UInt32) { self.rawValue = rawValue }        public static let screenshot = Flags(rawValue: 1 << 0)        public static let live = Flags(rawValue: 1 << 1)        public static let hdr = Flags(rawValue: 1 << 2)        public static let panorama = Flags(rawValue: 1 << 3)        public static let screenRecording = Flags(rawValue: 1 << 4)        public static let depth = Flags(rawValue: 1 << 5)        public static let favourite = Flags(rawValue: 1 << 6)        public static let hidden = Flags(rawValue: 1 << 7)        public static let burstPick = Flags(rawValue: 1 << 8)        public static let cinematic = Flags(rawValue: 1 << 9)        public static let slowMo = Flags(rawValue: 1 << 10)        public static let timelapse = Flags(rawValue: 1 << 11)        /// Came from a shared or iTunes-synced source, not the camera roll.        public static let notCameraRoll = Flags(rawValue: 1 << 12)    }    public let id: String    public let kind: Kind    public let flags: Flags    public let created: Date?    public let modified: Date?    public let width: Int    public let height: Int    public let duration: Double    public let burst: String?    public let latitude: Double?    public let longitude: Double?    public init(id: String, kind: Kind, flags: Flags, created: Date?, modified: Date?, width: Int, height: Int, duration: Double,                burst: String?, latitude: Double?, longitude: Double?) {        self.id = id        self.kind = kind        self.flags = flags        self.created = created        self.modified = modified        self.width = width        self.height = height        self.duration = duration        self.burst = burst        self.latitude = latitude        self.longitude = longitude    }    var pixels: Int { width * height }    var longEdge: Int { max(width, height) }}/// What an asset takes on disk.public struct LibrarySize: 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.    public struct Part: Sendable, Equatable {        public let kind: String        public let bytes: Int64?        public let filename: String        public init(kind: String, bytes: Int64?, filename: String) {            self.kind = kind            self.bytes = bytes            self.filename = filename        }    }    public let bytes: Int64    /// The phone said it; otherwise it is "about", from pixels, duration and kind.    public let exact: Bool    /// The original's file name (IMG_1234.HEIC, or WhatsApp's own), when the phone says.    public let filename: String?    public var parts: [Part] = []    public init(bytes: Int64, exact: Bool, filename: String?, parts: [Part] = []) {        self.bytes = bytes        self.exact = exact        self.filename = filename        self.parts = parts    }}/// The best picture the phone holds with the network off./// One of Photos' albums.public struct LibraryAlbum: Sendable, Equatable, Identifiable {    public enum Kind: String, Sendable { case mine, smart, shared }    public let id: String    public let title: String    public let kind: Kind    public let count: Int    public let canAdd: Bool    public init(id: String, title: String, kind: Kind, count: Int, canAdd: Bool) {        self.id = id        self.title = title        self.kind = kind        self.count = count        self.canAdd = canAdd    }}/// What a delete did, read back from the library, never assumed.public struct LibraryDeleteOutcome: Sendable, Equatable {    public let asked: Int    public let gone: Int    /// The person said no at the phone's confirmation.    public let refused: Bool    /// The confirmation's answer never came (the ProRAW bug); `gone` is what the re-read found.    public let timedOut: Bool    public init(asked: Int, gone: Int, refused: Bool, timedOut: Bool) {        self.asked = asked        self.gone = gone        self.refused = refused        self.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`).public protocol AlbumsWrites: Sendable {    func makeAlbum(_ title: String, with ids: [String]) async throws -> String    func add(_ ids: [String], to albumID: String) async throws    func rename(_ albumID: String, to title: String) async throws    func deleteAlbum(_ albumID: String) async throws    func delete(_ ids: [String], batch: Int, timeout: TimeInterval) async -> LibraryDeleteOutcome}/// The app target's door to install `AlbumsWrites`.public enum AlbumsWritesInstall {    public static func install(_ writes: any AlbumsWrites) { AlbumsLibrary.writes = writes }}extension LibraryAsset {    /// What it takes on disk, about, when the phone does not say (`AlbumsLibrary.about`).    public var aboutBytes: Int64 { AlbumsLibrary.about(self) }}public enum LibraryChange: 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.public protocol AlbumsPhotos: AnyObject, Sendable {    var access: AlbumsAccess { get }    func ask() async -> AlbumsAccess    @MainActor func chooseMore(from controller: UIViewController)    func assets() -> [LibraryAsset]    func count() -> Int    func assets(_ ids: [String]) -> [LibraryAsset]    func cloudIDs(_ ids: [String]) -> [String: String]    func size(_ asset: LibraryAsset) -> LibrarySize    func sizes(_ assets: [LibraryAsset]) -> [String: LibrarySize]    func originalLongEdge(_ id: String) -> Int?    func request(_ id: String, side: CGFloat, mode: AlbumsPictureMode, network: Bool) async -> LocalPicture    func measureSizes(count: Int) async    func 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]) -> KeepSize    func 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) -> UUID    func 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.public struct KeepPart: Sendable, Equatable {    /// `picture` (the photo or video as he sees it), `motion` (a Live photo's film) or `raw`.    public let role: String    public let isVideo: Bool    public let url: URL    public let mime: String    public let filename: String    public let bytes: Int64    public init(role: String, isVideo: Bool, url: URL, mime: String, filename: String, bytes: Int64) {        self.role = role        self.isVideo = isVideo        self.url = url        self.mime = mime        self.filename = filename        self.bytes = bytes    }}/// What asking for an asset's parts came to.public enum KeepParts: 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 hidden    case failed(String)}/// What Keep would send, from PhotoKit's own file sizes.public struct KeepSize: Sendable, Equatable {    public var bytes: Int64    /// False when a part had no size PhotoKit would say.    public var exact: Bool    /// Photos with a RAW original: kept as the picture he sees (the RAW file is not taken by Cotton yet).    public var raw: Int    public init(bytes: Int64 = 0, exact: Bool = false, raw: Int = 0) {        self.bytes = bytes        self.exact = exact        self.raw = raw    }}/// What the library reported about kept photos.public struct KeptChange: Sendable, Equatable {    /// Album id → photos taken out of it.    public var left: [String: [String]] = [:]    /// Photos deleted from the library.    public var deleted: [String] = []    /// Albums that gained photos.    public var grew: [String] = []    public init(left: [String: [String]] = [:], deleted: [String] = [], grew: [String] = []) {        self.left = left        self.deleted = deleted        self.grew = grew    }    public var isEmpty: Bool { left.values.allSatisfy(\.isEmpty) && deleted.isEmpty && grew.isEmpty }}/// The app target's door to install `AlbumsPhotos`.public enum AlbumsPhotosInstall {    public static func 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.final class AlbumsLibrary: @unchecked Sendable {    static let shared = AlbumsLibrary()    nonisolated(unsafe) static var photos: (any AlbumsPhotos)?    // MARK: Access    static var access: AlbumsAccess { photos?.access ?? .unasked }    /// Asks once; the phone's own question. Answers what was chosen.    static func ask() async -> AlbumsAccess { await photos?.ask() ?? .unasked }    /// With limited access, the phone's own picker of which photos Albums may see.    @MainActor static func 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 == .full        let 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: Sizes    func 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.    static func 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_000            return Int64(max(1, asset.duration) * rate)        default:            let perPixel = asset.flags.contains(.screenshot) ? 1.0 : 0.25            return Int64(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 {        guard let photos = Self.photos, let longEdge = photos.originalLongEdge(id) else { return .failed("gone") }        return await AlbumsPicture.ask(originalLongEdge: longEdge) { mode in            await photos.request(id, side: side, mode: mode, network: network)        }    }    func measureSizes(count: Int) async { await Self.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? {        guard let photos = Self.photos else { deliver(nil); return nil }        return photos.thumbnail(id, side: side, deliver: deliver)    }    func cancel(_ request: Int32) { Self.photos?.cancel(request) }    // MARK: Albums    func albums() -> [LibraryAlbum] { Self.photos?.albums() ?? [] }    func members(of albumID: String) -> [String] { Self.photos?.members(of: albumID) ?? [] }    // MARK: Keep    func keepParts(_ id: String, into dir: URL, mayGo: @escaping @Sendable () -> Bool) async -> KeepParts {        guard let photos = Self.photos else { return .gone }        return await 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) static var writes: (any AlbumsWrites)?    /// Whether this build can change the photo library at all. Screens draw no act when it cannot.    static var canWrite: Bool { writes != nil }    func makeAlbum(_ title: String, with ids: [String]) async throws -> String {        guard let w = Self.writes else { throw AlbumsLibraryError.lookOnly }        return try await w.makeAlbum(title, with: ids)    }    func add(_ ids: [String], to albumID: String) async throws {        guard let w = Self.writes else { throw AlbumsLibraryError.lookOnly }        try await w.add(ids, to: albumID)    }    func rename(_ albumID: String, to title: String) async throws {        guard let w = Self.writes else { throw AlbumsLibraryError.lookOnly }        try await w.rename(albumID, to: title)    }    /// Deletes the album, never its photos.    func deleteAlbum(_ albumID: String) async throws {        guard let w = Self.writes else { throw AlbumsLibraryError.lookOnly }        try await 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 {        guard let w = Self.writes else { return LibraryDeleteOutcome(asked: ids.count, gone: 0, refused: true, timedOut: false) }        return await w.delete(ids, batch: 10_000, timeout: 300)    }    // MARK: Changes    /// Calls `seen` with each change while Albums runs. Answers a key to stop.    @discardableResult    func 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?) { try Self.photos?.changes() ?? (.wholePass, nil) }    func saveToken(_ token: Data?) { Self.photos?.saveToken(token) }    var hasToken: Bool { Self.photos?.hasToken ?? false }}public enum AlbumsLibraryError: Error { case notMade, cannotAdd, lookOnly }#endif