Cotton code
395 lines · 14.6 KB · SwiftRaw
// ALBUMS' STATE: where the person stands (first run, the four places, the screens over them, a sheet, a short line at// the foot) and the two layers under it, the library (`AlbumsLibrary`) and the pass (`AlbumsPass`). Every count, size,// word, Set and pick on screen is the core's answer (`AlbumsBook`); the phone reads the library, runs the pass, asks// the system to act when an answer says so, and draws.#if os(iOS)import CottonKitimport Foundationimport Observationimport SwiftUIenum AlbumsTab: String, CaseIterable, Identifiable {    case albums, tidy, people, you    var id: String { rawValue }    var words: String { AlbumsWords.line("tabs.\(rawValue)") }}enum AlbumsScreen: Equatable, Identifiable {    case album(id: String)    case allPhotos    case photo(id: String, back: String)    case sets    case set(id: String)    case list(key: String)    case bin(back: String)    case looked    var id: String {        switch self {        case .album(let id): "album-\(id)"        case .allPhotos: "all"        case .photo(let id, _): "photo-\(id)"        case .sets: "sets"        case .set(let id): "set-\(id)"        case .list(let key): "list-\(key)"        case .bin: "bin"        case .looked: "looked"        }    }}/// A question asked once before an act, in the core's words.struct AlbumsAsk: Equatable {    let question: String    var line: String?    let yes: String    let no: String    let tag: String    let act: () -> Void    static func == (a: AlbumsAsk, b: AlbumsAsk) -> Bool { a.tag == b.tag && a.question == b.question }}enum AlbumsSheetKind: Equatable {    case ask(AlbumsAsk)    case makeAlbum    case rename(id: String, title: String)    case name(group: String)    /// "Keep this album in Cotton": the album's Photos id and title.    case keep(id: String, title: String)}struct AlbumsToastLine: Equatable {    let words: String    var undo: AlbumsDone.Undo?    let at = Date()    static func == (a: AlbumsToastLine, b: AlbumsToastLine) -> Bool { a.words == b.words && a.at == b.at }}@MainActor@Observablefinal class AlbumsModel {    let core: any CottonCalling    let book: AlbumsBook    let pass = AlbumsPass.shared    /// What `albums.start` answered last: the opening screen.    private(set) var opening: AlbumsStart?    private(set) var access: AlbumsAccess = AlbumsLibrary.access    var tab: AlbumsTab = .albums    private(set) var visited: Set<AlbumsTab> = [.albums]    var stack: [AlbumsScreen] = []    var sheet: AlbumsSheetKind?    var toast: AlbumsToastLine?    /// Photos' own albums, read on launch and on every change.    private(set) var photoAlbums: [LibraryAlbum] = []    /// Bumped by a tap on the place stood on, so it goes back to its top; and by any change the places should read again.    private(set) var placed = 0    private(set) var changed = 0    /// The pass's lines, read again after each checkpoint (never the lists under his finger).    private(set) var lines: AlbumsPassLines?    /// A failure said once, in the family's words.    var failed: String { AlbumsWords.line("failed") }    var home: Bool { opening?.screen == "home" }    init(core: any CottonCalling, book: AlbumsBook? = nil) {        self.core = core        self.book = book ?? AlbumsBook(core: core)        // The pass hands the core its facts (albums.library.take, look.take, pass.lines): never an act.        AlbumsPass.shared.use(core)        // Keep (KEEP slice 1): hands the photos of the albums he keeps to Cotton's media path.        AlbumsKeeper.shared.use(core)        #if COTTON_DEV        Self.freshOnce()        #endif    }    #if COTTON_DEV    /// `-albums-fresh` starts from nothing, once per launch (SwiftUI may make the root, and so a model, more than once).    private static var fresh = false    private static func freshOnce() {        guard !fresh, ProcessInfo.processInfo.arguments.contains("-albums-fresh") else { return }        fresh = true        UserDefaults.standard.removeObject(forKey: "albums.faces")        AlbumsStore.shared.forgetAll()        UserDefaults.standard.removeObject(forKey: "albums.library.token")    }    #endif    private var permission: String {        switch access {        case .unasked: "none"        case .full: "full"        case .limited: "limited"        case .denied, .restricted: "denied"        }    }    /// Every launch and after any permission change: the core says which screen opens.    func launched() async {        #if COTTON_DEV        if ProcessInfo.processInfo.arguments.contains("-albums-bench-faces") { Task.detached { await AlbumsFaces.bench() } }        #endif        await ask()        #if COTTON_DEV        // A measurement run starts by itself (the photo access granted beforehand with `simctl privacy`).        if opening?.screen == "first_run", ProcessInfo.processInfo.arguments.contains("-albums-start") { await start(); return }        #endif        guard home, access.reads else { return }        await pass.readLibrary()        readAlbums()        pass.run()        AlbumsKeeper.shared.members()        AlbumsKeeper.shared.resume()        changed += 1        #if COTTON_DEV        keepForWalk()        if ProcessInfo.processInfo.arguments.contains("-albums-looked") { open(.looked) }        await walkTo()        if ProcessInfo.processInfo.arguments.contains("-albums-export") {            Task.detached {                while await !AlbumsPass.shared.finished { try? await Task.sleep(for: .seconds(5)) }                AlbumsMeasure.export()                AlbumsMeasure.write(AlbumsMeasure.numbers())                Log.write("albums: exported")            }        }        #endif    }    #if COTTON_DEV    /// Dev `-albums-keep <album title>` (the measured walk on a simulator nobody taps): keeps that Photos album as the    /// sheet's Keep would, with `-albums-keep-cellular` for its switch; once only.    private func keepForWalk() {        // `-albums-keep-ask <title>`: the album and its Keep sheet open, nothing kept (the walk's picture of the ask).        if let title = UserDefaults.standard.string(forKey: "albums-keep-ask"), let album = photoAlbums.first(where: { $0.title == title }) {            open(.album(id: album.id))            sheet = .keep(id: album.id, title: album.title)            return        }        guard let title = UserDefaults.standard.string(forKey: "albums-keep"),              let album = photoAlbums.first(where: { $0.title == title }),              AlbumsKeeper.shared.kept(album.id) == nil else { return }        let args = ProcessInfo.processInfo.arguments        AlbumsKeeper.shared.keep(album.id, title: album.title, cellular: args.contains("-albums-keep-cellular"))        open(.album(id: album.id))    }    /// The walk's screen, for screenshots on a simulator nobody taps: `-albums-tab albums|tidy|people|you` and    /// `-albums-open sets|set|bin|all|looked|list:<key>|photo` (`set` and `photo` are the first Set and its first shot).    private func walkTo() async {        let defaults = UserDefaults.standard        if let raw = defaults.string(forKey: "albums-tab"), let to = AlbumsTab(rawValue: raw) { place(to) }        guard let screen = defaults.string(forKey: "albums-open") else { return }        switch screen {        case "sets": open(.sets)        case "bin": open(.bin(back: ""))        case "all": open(.allPhotos)        case "looked": open(.looked)        case "set", "photo":            for _ in 0..<120 {                if let first = try? await book.sets().rows.first {                    open(.set(id: first.set))                    if screen == "photo", let shot = first.strip.first { open(.photo(id: shot, back: "")) }                    return                }                try? await Task.sleep(for: .seconds(5))            }        default:            if screen.hasPrefix("list:") { open(.list(key: String(screen.dropFirst(5)))) }            // A Photos album by its title (Keep's walk).            if screen.hasPrefix("album:"), let album = photoAlbums.first(where: { $0.title == String(screen.dropFirst(6)) }) { open(.album(id: album.id)) }        }    }    #endif    private func ask() async {        access = AlbumsLibrary.access        let chosen = access == .limited ? AlbumsLibrary.shared.count() : nil        do { opening = try await book.start(permission: permission, chosen: chosen) } catch { tell(failed) }    }    /// Start on first run: the phone's question, then the pass begins.    func start() async {        if AlbumsLibrary.access == .unasked { _ = await AlbumsLibrary.ask() }        await ask()        guard home, access.reads else { return }        await pass.readLibrary()        readAlbums()        pass.start()        changed += 1    }    func readAlbums() {        guard access.reads else { photoAlbums = []; return }        photoAlbums = AlbumsLibrary.shared.albums()    }    /// The pass's lines, once read: null once the pass is done (and then nothing is drawn).    private(set) var linesRead = false    func readLines() async {        guard let answer = try? await book.passLines() else { return }        lines = answer.progress        linesRead = true    }    // MARK: Places    func place(_ to: AlbumsTab) {        if tab == to { stack.removeAll(); placed += 1; return }        tab = to        visited.insert(to)        stack.removeAll()    }    func open(_ screen: AlbumsScreen) { stack.append(screen) }    func back() { if !stack.isEmpty { stack.removeLast() } }    /// Replaces the screen on top (a set's Next).    func replace(_ screen: AlbumsScreen) {        if stack.isEmpty { stack.append(screen) } else { stack[stack.count - 1] = screen }    }    func tell(_ words: String?, undo: AlbumsDone.Undo? = nil) {        guard let words, !words.isEmpty else { return }        let line = AlbumsToastLine(words: words, undo: undo)        toast = line        Task {            try? await Task.sleep(for: .seconds(undo == nil ? 3 : 8))            if toast == line { toast = nil }        }    }    /// A method's error: `gone` goes back a screen quietly; anything else says the family's failure line.    func refused(_ error: Error) {        if (error as? AlbumsRefusal)?.gone == true { back(); return }        tell(failed)    }    func cameBack() {        let before = access        access = AlbumsLibrary.access        if before != access { Task { await launched() } }        guard home else { return }        pass.cameBack()        readAlbums()        AlbumsKeeper.shared.members()        AlbumsKeeper.shared.resume()    }    func wentAway() { pass.wentAway() }    // MARK: Acts    func undo(_ undo: AlbumsDone.Undo) async {        do {            let done = try await book.undo(undo.token)            toast = nil            tell(done.said)            changed += 1        } catch { refused(error) }    }    /// What an act answered: `changed` reads the screen again (nothing was done); otherwise its line, with Undo.    func answered(_ done: AlbumsDone) {        if done.changed != true { tell(done.said, undo: done.undo) }        changed += 1    }    func moveToBin(ids: [String], shown: [String]) async {        do { answered(try await book.binMove(ids: ids, shown: shown)) } catch { refused(error) }    }    func moveToBin(list: String, shown: [String]) async {        do { answered(try await book.binMove(list: list, shown: shown)) } catch { refused(error) }    }    func keep(ids: [String], shown: [String]) async {        do { answered(try await book.keep(ids: ids, shown: shown)) } catch { refused(error) }    }    func bringBack(_ ids: [String], shown: [String]) async {        do { answered(try await book.bringBack(ids, shown: shown)) } catch { refused(error) }    }    /// The Bin's Delete, at his tap: the core answers what the system must do; the iPhone is asked once per part, and    /// only for ids the Bin showed (anything else asks nothing and redraws); then the core is told what is still there.    /// Never assumes the iPhone's question was accepted.    func deleteBin(shown: [String]) async {        do {            let done = try await book.binDelete(shown: shown)            guard done.changed != true, let platform = done.platform, platform.act == "delete" else { answered(done); return }            let allowed = Set(shown)            let parts = platform.parts.filter { !$0.isEmpty }            guard parts.allSatisfy({ $0.allSatisfy(allowed.contains) }) else { changed += 1; return }            var asked: [String] = []            for part in parts {                asked += part                _ = await AlbumsLibrary.shared.delete(part)            }            let still = Set(AlbumsLibrary.shared.assets(asked).map(\.id))            let after = try await book.platformDone(act: platform.act, asked: asked, stillHere: asked.filter { still.contains($0) })            tell(after.said)            await pass.readLibrary()            changed += 1        } catch { refused(error) }    }    func setFaces(_ on: Bool) async {        do {            let said = try await book.faces(on: on).said            if on { pass.faces = true; pass.refresh() } else { pass.turnOffFaces() }            tell(said)            changed += 1        } catch { refused(error) }    }    func askFacesOff(_ ask: AlbumsYou.Ask) {        sheet = .ask(AlbumsAsk(question: ask.question, line: ask.line, yes: ask.yes, no: ask.no, tag: "faces-off") { [weak self] in            Task { await self?.setFaces(false) }        })    }    func name(_ group: String, _ name: String) async {        do {            _ = try await book.name(group, name)            changed += 1        } catch { refused(error) }    }    // MARK: Albums in Photos    func makeAlbum(_ title: String) async {        do {            _ = try await AlbumsLibrary.shared.makeAlbum(title, with: [])            readAlbums()            changed += 1        } catch { tell(failed) }    }    func rename(_ id: String, to title: String) async {        do {            try await AlbumsLibrary.shared.rename(id, to: title)            readAlbums()            changed += 1        } catch { tell(failed) }    }    func askDelete(_ id: String, _ menu: AlbumsAlbum.Menu) {        sheet = .ask(AlbumsAsk(question: menu.deleteAsk, line: menu.deleteLine, yes: menu.delete, no: AlbumsWords.line("album.cancel"), tag: "delete-album") { [weak self] in            Task { @MainActor in                do {                    try await AlbumsLibrary.shared.deleteAlbum(id)                    self?.back()                    self?.readAlbums()                    self?.changed += 1                } catch {                    self?.tell(self?.failed)                }            }        })    }}#endif