Cotton code
310 lines · 12.7 KB · SwiftRaw
// CINEMAS' MODEL: where Cinemas stands (the place, each place's pushed screens, the sheet risen over the app, the// toast) and its one way to its answers (`CinemasSource`). It decides nothing: every row, word and act is the core's.#if os(iOS)import CottonKitimport SwiftUIenum CinemasTab: String, CaseIterable, Sendable {    case home, search, you    var icon: String {        switch self {        case .home: "house"        case .search: "magnifyingglass"        case .you: "person.crop.circle"        }    }    /// The icon while the tab is open; the magnifying glass has no filled form.    var iconOn: String { self == .search ? icon : "\(icon).fill" }}/// A screen pushed over a place's first screen.enum CinemasRoute: Hashable, Sendable {    /// A title's page; `source` names the poster it grew from (its row and its key), for the shared-element grow.    case title(CinemasItem, source: String)    /// A row opened whole.    case row(id: String, title: String)    /// You › Groups.    case groups    /// You › On this phone.    case onPhone    /// You › Bin: what he moved there, each with Put back.    case bin    /// You › Add films: films or a folder from Files.    case add    /// You › Hidden: his hidden categories, behind the phone's lock (CinemasHidden.swift).    case hidden    /// You › Hidden › Bin: the hidden titles' own Bin (core 4), shut with Hidden.    case hiddenBin}/// A sheet risen over the whole app.enum CinemasSheet: Identifiable, Equatable, Sendable {    /// The one sheet for a title (cinemas-3.html 9b): what it is, and which of his groups it is in, each changed at    /// once (a long press, the page's Add, its kind and group acts).    case item(CinemasItem)    /// Make a group with nothing in it yet.    case newGroup    /// Rename a group.    case rename(id: String, name: String)    /// A title's subtitles (`cinemas.subtitles`).    case subtitles(CinemasItem)    /// Send to a friend (the Send step).    case send(CinemasItem)    /// "Hide Rainy Sundays?": the honest line, then Hide.    case hide(id: String, name: String)    /// Share one of his film lists with people from his Circle (the one Share sheet, app cinemas).    case share(id: String)    var id: String {        switch self {        case .item(let item): "item/\(item.key)"        case .newGroup: "new"        case .rename(let id, _): "rename/\(id)"        case .subtitles(let item): "subtitles/\(item.key)"        case .send(let item): "send/\(item.key)"        case .hide(let id, _): "hide/\(id)"        case .share(let id): "share/\(id)"        }    }}struct CinemasToast: Equatable, Identifiable, Sendable {    let id = UUID()    var line: String    /// The act Undo takes back, when there is one; the toast then holds 10 s, not 4.    var undo: (@Sendable () async -> Void)?    static func == (a: Self, b: Self) -> Bool { a.id == b.id }}@MainActor@Observablefinal class CinemasModel {    @ObservationIgnored let source: any CinemasSource    @ObservationIgnored let core: (any CottonCalling)?    @ObservationIgnored let pictures: CinemasPictures    /// The share sheet's intake, which Add films hands its files to.    @ObservationIgnored let shares: ShareIntake?    var tab: CinemasTab = .home    var paths: [CinemasTab: [CinemasRoute]] = [:]    var sheet: CinemasSheet?    var toast: CinemasToast?    /// The screen's width, read once at the root from the ground (never from a scroll view, whose content is sized    /// from it); every place lays its posters out from it.    var width: CGFloat = 390    /// Words Search opens with (a walk's launch argument); taken once.    var searchAsk: String?    /// Bumped when anything Cinemas shows may have changed (an act, a sync from another device): every screen reads again.    var generation = 0    /// Hidden: whether its lock has passed, and since when he has been away from it.    var hidden = CinemasHiddenState()    /// The title prepared for Play now, if any.    @ObservationIgnored var prepared: CinemasItem?    init(source: any CinemasSource, core: (any CottonCalling)?, shares: ShareIntake? = nil) {        self.source = source        self.core = core        self.shares = shares        pictures = CinemasPictures(core: core)    }    // ── where it stands ────────────────────────────────────────────────    func push(_ route: CinemasRoute) { paths[tab, default: []].append(route) }    func open(_ item: CinemasItem, from row: String) { push(.title(item, source: "\(row)/\(item.key)")) }    func changed() {        generation += 1        // A film playing whose category was just hidden: its veil follows, and picture-in-picture closes.        FilmPlayback.dataChanged()    }    func binding(_ tab: CinemasTab) -> Binding<[CinemasRoute]> {        Binding(get: { self.paths[tab] ?? [] }, set: { self.paths[tab] = $0 })    }    /// A title sent: the receipt's words, and its Undo taking the send back while it is not yet kept.    func sent(_ sent: CinemasSent) {        let source = self.source        var undo: (@Sendable () async -> Void)?        if sent.undo != nil {            let id = sent.id            let undone = sent.undone            undo = { @Sendable [weak self] in                if case .read = await source.unsend(id), let undone { await self?.say(undone) }            }        }        say(sent.words ?? CinemasWords.line("stream.done"), undo: undo)    }    func say(_ line: String, undo: (@Sendable () async -> Void)? = nil) {        toast = CinemasToast(line: line, undo: undo)    }    // ── playing ────────────────────────────────────────────────────────    /// The system player, from where the core says (`shell.player play`).    func play(_ item: CinemasItem) {        #if COTTON_DEV        if let invented = source as? CinemasInvented {            CinemasWalkPlayer.play(item, on: invented) { [weak self] in self?.changed() }            return        }        #endif        let cover = [item.backdrop, item.poster].compactMap { $0 }.lazy.compactMap { self.pictures.latest($0) }.first        let hidden = hiddenReads        Task { await FilmPlayback.ask(table: item.table, id: item.id, cover: cover, hidden: hidden) }    }    /// A title on screen that Play would start (a film's or an episode's page, a series' page, Home's Featured): the    /// core fetches the first window of what Play would play ahead of the tap. A series is the episode the core would    /// choose (its `deal`). On mobile data the core fetches nothing unless this phone's films may stream on it.    func prepare(_ item: CinemasItem) {        #if COTTON_DEV        // `-play-no-prepare`: the same walk timed without it, for a before beside the after.        if source is CinemasInvented || ProcessInfo.processInfo.arguments.contains("-play-no-prepare") { return }        #endif        guard !item.preparing else { return }        prepared = item        FilmPlayback.prepare(table: item.table, id: item.id, hidden: hiddenReads)    }    /// That title left the screen: let it go, unless another has been prepared since (a page pushed over Home, or    /// Home shown again as a page leaves, whichever comes first).    func unprepare(_ item: CinemasItem) {        #if COTTON_DEV        if source is CinemasInvented { return }        #endif        guard prepared?.id == item.id else { return }        prepared = nil        FilmPlayback.unprepare()    }    /// Back in front: what was prepared before the background let it go, again.    func prepareAgain() {        if let prepared { prepare(prepared) }    }    /// From the start: the same play, at 0.    func playFromStart(_ item: CinemasItem) {        let cover = [item.backdrop, item.poster].compactMap { $0 }.lazy.compactMap { self.pictures.latest($0) }.first        let hidden = hiddenReads        Task { await FilmPlayback.ask(table: item.table, id: item.id, at: 0, cover: cover, hidden: hidden) }    }    // ── groups ─────────────────────────────────────────────────────────    /// A title into a group or out of it, with Undo; Home's rows read again.    func group(_ group: CinemasGroups.Group, item: CinemasItem, in add: Bool) async -> Bool {        switch await source.group(group.id, item: item, in: add) {        case .read:            changed()            UINotificationFeedbackGenerator().notificationOccurred(.success)            let source = self.source            let line = CinemasWords.line(add ? "stream.group_added" : "stream.group_taken_out", ["group": group.name])            say(line) { [weak self] in                _ = await source.group(group.id, item: item, in: !add)                await self?.changed()            }            return true        case .refused(let line):            UINotificationFeedbackGenerator().notificationOccurred(.warning)            say(line)            return false        }    }    func makeGroup(_ name: String, with item: CinemasItem?) async -> Bool {        switch await source.makeGroup(name, with: item) {        case .read:            changed()            UINotificationFeedbackGenerator().notificationOccurred(.success)            say(CinemasWords.line("stream.group_made", ["group": name]))            return true        case .refused(let line):            UINotificationFeedbackGenerator().notificationOccurred(.warning)            say(line)            return false        }    }    /// What a title is, changed at once: `cinemas.kind`; it stays (the core records that he chose it).    func kind(_ item: CinemasItem, to kind: CinemasItem.Kind) async -> Bool {        switch await source.kind(item, to: kind) {        case .read(let said):            changed()            UINotificationFeedbackGenerator().notificationOccurred(.success)            say(said ?? CinemasWords.line("stream.kind_changed", ["title": item.title, "kind": CinemasWords.line("stream.kind_many_\(kind.rawValue)")]))            return true        case .refused(let line):            UINotificationFeedbackGenerator().notificationOccurred(.warning)            say(line)            return false        }    }    /// It is an episode: the film moves into its series as season `season`, episode `episode`; a page standing for the    /// film closes, and the sheet with it.    func toEpisode(_ item: CinemasItem, series: String?, newSeries: String?, season: Int, episode: Int) async -> Bool {        switch await source.toEpisode(item, series: series, newSeries: newSeries, season: season, episode: episode) {        case .read:            for tab in CinemasTab.allCases {                paths[tab]?.removeAll { if case .title(let shown, _) = $0 { return shown.id == item.id } else { return false } }            }            sheet = nil            changed()            UINotificationFeedbackGenerator().notificationOccurred(.success)            say(CinemasWords.line("stream.episode_moved", ["title": item.title, "season": "\(season)", "episode": "\(episode)"]))            return true        case .refused(let line):            UINotificationFeedbackGenerator().notificationOccurred(.warning)            say(line)            return false        }    }    /// To the Bin, with Undo; a page standing for it closes.    func bin(_ item: CinemasItem) async {        switch await source.bin(item) {        case .read(let change):            for tab in CinemasTab.allCases {                paths[tab]?.removeAll { if case .title(let shown, _) = $0 { return shown.id == item.id } else { return false } }            }            changed()            let source = self.source            let title = item.title            var undo: (@Sendable () async -> Void)?            if let change {                undo = { @Sendable [weak self] in                    _ = await source.undo(change)                    await self?.putBack(title)                }            }            say(ShellLines.line("receipts", "binned", ["name": title]), undo: undo)        case .refused(let line):            UINotificationFeedbackGenerator().notificationOccurred(.warning)            say(line)        }    }    /// After an Undo of the Bin: said, and every screen reads again.    func putBack(_ title: String) {        say(ShellLines.line("receipts", "put_back", ["name": title]))        changed()    }    func act(_ done: CinemasRead<Bool>) {        switch done {        case .read: changed()        case .refused(let line):            UINotificationFeedbackGenerator().notificationOccurred(.warning)            say(line)        }    }}#endif