Cotton code
219 lines · 9.9 KB · SwiftRaw
// WALKING CINEMAS ON A SIMULATOR, Dev builds only: `-cinemas-open <place>` opens one screen at launch so each can be// looked at (and screenshotted) without a finger. Places: `home`, `search:<words>`, `you`, `groups`, `on_phone`,// `row:<row id>`, `title:<film id>`, `episode:<episode id>`, `sheet:<film id>`, `subtitles:<film id>`, `new_group`, `tv:<id>` (it plays on the// invented TV) and `remote:<id>` (and the remote opens). Used with `-cinemas-invent` for the invented library;// `-cinemas-hide <id>` hides one of the invented categories first; places `hidden` and `hide:<id>` open Hidden and the// Hide sheet. `-cinemas-tv` adds an invented TV, already chosen, since a simulator has none. `-cinemas-add-file <name>` brings an// invented film (made with ffmpeg, put in the app's Documents) into the dev account through Add films' own intake,// for timing play against the dev server. Compiled out of every real build.#if COTTON_DEV && os(iOS)import AVKitimport Foundationimport UIKitenum CinemasDevOpen {    /// Once a launch: the root's task runs again when a full-screen player goes, and must not open the place again.    @MainActor private static var ran = false    @MainActor    static func run(_ model: CinemasModel, tv: CinemasTV) async {        guard !ran else { return }        ran = true        let arguments = ProcessInfo.processInfo.arguments        if arguments.contains("-cinemas-tv"), let invented = model.source as? CinemasInvented {            tv.invent(CinemasDevTV(invented: invented))        }        if let at = arguments.firstIndex(of: "-cinemas-add-file"), at + 1 < arguments.count,           let documents = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {            let file = documents.appendingPathComponent(arguments[at + 1])            if FileManager.default.fileExists(atPath: file.path) {                await model.shares?.films(inPlace: [file])                model.changed()            }        }        // `-cinemas-hide <category id>`: that category hidden before the first screen, on the invented library.        if let at = arguments.firstIndex(of: "-cinemas-hide"), at + 1 < arguments.count {            _ = await model.source.hide(arguments[at + 1], hidden: true)            model.changed()        }        guard let at = arguments.firstIndex(of: "-cinemas-open"), at + 1 < arguments.count else { return }        let place = arguments[at + 1]        let (kind, rest) = place.split(separator: ":", maxSplits: 1).map(String.init).splitFirst()        // Let Home's first answer land, so a page pushed over it opens as it would from a tap.        try? await Task.sleep(for: .milliseconds(900))        switch kind {        case "search":            model.searchAsk = rest            model.tab = .search        case "you": model.tab = .you        case "groups":            model.tab = .you            model.push(.groups)        case "on_phone":            model.tab = .you            model.push(.onPhone)        case "row":            model.push(.row(id: rest ?? "films", title: (await model.source.row(rest ?? "films", after: nil).answer?.title) ?? ""))        case "bin":            model.tab = .you            model.push(.bin)        case "add":            model.tab = .you            model.push(.add)        case "title", "episode", "sheet", "subtitles", "send":            let table = kind == "episode" ? "film_episode" : "film"            guard let id = rest, let item = await model.source.title(table: table, id: id).answer?.item else { return }            switch kind {            case "sheet": model.sheet = .item(item)            case "send": model.sheet = .send(item)            case "subtitles":                model.open(item, from: "dev")                try? await Task.sleep(for: .milliseconds(700))                model.sheet = .subtitles(item)            default: model.open(item, from: "dev")            }        case "new_group": model.sheet = .newGroup        case "hidden": await model.openHidden()        case "hide":            guard let id = rest else { return }            model.sheet = .hide(id: id, name: (await model.source.groups().answer?.groups.first { $0.id == id }?.name) ?? id)        case "tv", "remote":            guard let id = rest else { return }            let table = id.contains("-e") ? "film_episode" : "film"            guard let item = await model.source.title(table: table, id: id).answer?.item else { return }            tv.start(item, model: model)            if kind == "remote" {                try? await Task.sleep(for: .milliseconds(1200))                tv.remoteOpen = true            }        default: break        }    }}/// The walk's player, Dev builds on the invented library only: the system player on Apple's public test stream (an/// invented film has no file), and where it was closed carried back as the title's place, so Resume can be walked.@MainActorenum CinemasWalkPlayer {    static let stream = URL(string: "https://devstreaming-cdn.apple.com/videos/streaming/examples/bipbop_16x9/bipbop_16x9_variant.m3u8")!    static func play(_ item: CinemasItem, on invented: CinemasInvented, then done: @escaping @MainActor () -> Void) {        let player = AVPlayer(url: stream)        let shown = Closing()        shown.player = player        shown.closed = { seconds, whole in            let length = Double(item.minutes ?? 0) * 60            Task {                // The test stream is not the film's length: the same share of it is carried over.                await invented.played(item.id, at: whole > 0 ? seconds / whole * length : 0, of: length)                done()            }        }        let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }        guard var top = scenes.flatMap(\.windows).first(where: \.isKeyWindow)?.rootViewController else { return }        while let above = top.presentedViewController { top = above }        top.present(shown, animated: true) {            // A title with no place yet starts just short of half way, so a walk that plays a few seconds and closes            // has closed half way, and its Resume can be read.            let share = item.progress ?? 0.45            Task { @MainActor in                for _ in 0..<40 {                    if let whole = player.currentItem?.duration.seconds, whole.isFinite, whole > 0 {                        await player.seek(to: CMTime(seconds: share * whole, preferredTimescale: 600))                        break                    }                    try? await Task.sleep(for: .milliseconds(250))                }                player.play()            }        }    }    final class Closing: AVPlayerViewController {        var closed: ((Double, Double) -> Void)?        override func viewDidDisappear(_ animated: Bool) {            super.viewDidDisappear(animated)            guard isBeingDismissed || presentingViewController == nil, let player else { return }            player.pause()            let whole = player.currentItem?.duration.seconds ?? 0            closed?(player.currentTime().seconds, whole.isFinite ? whole : 0)            closed = nil        }    }}/// The invented TV, Dev builds only: "Living room TV", already chosen; what plays on it runs on a clock of its own,/// pauses, jumps and seeks like the real one, and offers made-up subtitle and sound tracks. Stop on TV and Watch on/// phone let it go.@MainActorfinal class CinemasDevTV: CinemasTVEngine {    let invented: CinemasInvented    private var item: CinemasItem?    private var shown: (title: String, caption: String?, cover: String?, length: Double)?    private var at: Double = 0    private var since: Date?    private var subtitle: Int? = 0    private var sound = 0    init(invented: CinemasInvented) { self.invented = invented }    var device: String? { "Living room TV" }    var onTV: FilmPlayback.OnTV? {        guard let item, let shown else { return nil }        return FilmPlayback.OnTV(table: item.table, id: item.id, title: shown.title, caption: shown.caption, cover: shown.cover,                                 at: now, length: shown.length, paused: since == nil)    }    private var now: Double {        let gone = since.map { Date().timeIntervalSince($0) } ?? 0        return min(at + gone, shown?.length ?? 0)    }    func start(_ item: CinemasItem) async -> Bool {        guard let found = await invented.onTV(item) else { return false }        self.item = found.id == item.id ? item : CinemasItem(table: "film_episode", id: found.id, title: found.title, kind: .episode)        shown = (found.title, found.caption, found.cover, found.length)        at = found.at        since = Date()        return true    }    func pauseOrPlay() {        if since == nil { since = Date() } else { at = now; since = nil }    }    func skip(by seconds: Double) { seek(to: now + seconds) }    func seek(to seconds: Double) {        at = min(max(0, seconds), shown?.length ?? 0)        if since != nil { since = Date() }    }    func leave(watchHere: Bool) {        guard let item, let shown else { return }        let place = now        self.item = nil        self.shown = nil        since = nil        Task { await invented.played(item.id, at: place, of: shown.length) }    }    func tracks(_ kind: AVMediaCharacteristic) async -> [FilmPlayback.TrackChoice] {        if kind == .legible {            return ["English", "Hindi"].enumerated().map { .init(id: $0.offset, name: $0.element, chosen: $0.offset == subtitle) }        }        return ["Original", "Commentary"].enumerated().map { .init(id: $0.offset, name: $0.element, chosen: $0.offset == sound) }    }    func choose(_ index: Int?, _ kind: AVMediaCharacteristic) async {        if kind == .legible { subtitle = index } else { sound = index ?? 0 }    }}private extension Array where Element == String {    func splitFirst() -> (String, String?) { (first ?? "", count > 1 ? self[1] : nil) }}#endif