// THE TV, FIRST CLASS (CONTRACT-2 "The TV"; the one thing he uses today): choosing the TV is Apple's own AirPlay // list; Play on TV opens that list and starts the film once a TV is chosen (or at once when one already is); while a // film plays on the TV, a slim bar stands above the bottom bar on every place, and a tap on it grows into the remote // (frame 8). The remote's words are the core's (`cinemas.remote`): where it plays, the title and its place in a series, // the time gone and the time left, the next episode, and the note on volume. When the TV lets go, the player leaves the // film waiting on the phone, paused (owner, 18 Nov 2026); Stop on TV tells the core so through `shell.player`. #if os(iOS) import AVFoundation import AVKit import CottonKit import SwiftUI /// What plays on the TV and the few acts a remote takes: Apple's player on AirPlay, or (a Dev build asked for it) an /// invented TV so the bar and the remote can be walked on a simulator, which has no TV. @MainActor protocol CinemasTVEngine: AnyObject { var onTV: FilmPlayback.OnTV? { get } /// The chosen TV's name. var device: String? { get } func pauseOrPlay() func skip(by seconds: Double) func seek(to seconds: Double) func leave(watchHere: Bool) func tracks(_ kind: AVMediaCharacteristic) async -> [FilmPlayback.TrackChoice] func choose(_ index: Int?, _ kind: AVMediaCharacteristic) async /// Starts `item` on the TV itself when the engine can; false hands it to the player. func start(_ item: CinemasItem) async -> Bool } /// AirPlay through Apple's player. @MainActor final class CinemasAirPlay: CinemasTVEngine { var onTV: FilmPlayback.OnTV? { FilmPlayback.onTV } var device: String? { AVAudioSession.sharedInstance().currentRoute.outputs.first { $0.portType == .airPlay }?.portName } func pauseOrPlay() { FilmPlayback.pauseOrPlay() } func skip(by seconds: Double) { FilmPlayback.skip(by: seconds) } func seek(to seconds: Double) { FilmPlayback.seek(to: seconds) } func leave(watchHere: Bool) { FilmPlayback.leaveTV(watchHere: watchHere) } func tracks(_ kind: AVMediaCharacteristic) async -> [FilmPlayback.TrackChoice] { await FilmPlayback.tracks(kind) } func choose(_ index: Int?, _ kind: AVMediaCharacteristic) async { await FilmPlayback.choose(index, kind) } func start(_ item: CinemasItem) async -> Bool { false } } @MainActor @Observable final class CinemasTV { /// The film playing on a TV now, read once a second while the app is open. private(set) var playing: FilmPlayback.OnTV? /// The TV's name while one is chosen. private(set) var device: String? /// The core's words for what plays (`cinemas.remote`), asked when the title changes and every few seconds. private(set) var words: CinemasRemoteWords? /// The remote stands over the app. var remoteOpen = false @ObservationIgnored var engine: any CinemasTVEngine = CinemasAirPlay() /// Where the remote's words come from; set by the root. @ObservationIgnored var source: (any CinemasSource)? /// A title waiting for a TV to be chosen, from Play on TV. private var waiting: (item: CinemasItem, model: CinemasModel)? @ObservationIgnored private var watching: Task? @ObservationIgnored private var routes: NSObjectProtocol? @ObservationIgnored private var asked: (id: String, at: Double, when: Date)? /// The one route button the app keeps off screen, which Play on TV and You › The TV press. @ObservationIgnored let picker: AVRoutePickerView = { let picker = AVRoutePickerView() picker.prioritizesVideoDevices = true return picker }() /// How often the remote's words are asked again while the same title plays. static let askEvery: TimeInterval = 10 init() { routes = NotificationCenter.default.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.routeChanged() } } watching = Task { [weak self] in while !Task.isCancelled { self?.read() try? await Task.sleep(for: .seconds(1)) } } read() } func read() { let now = engine.onTV if now != playing { playing = now } if now == nil { if remoteOpen { remoteOpen = false } if words != nil { words = nil } asked = nil } let name = engine.device if name != device { device = name } if let now { ask(now) } } /// Asks the core for the remote's words when the title changed, the place jumped, or a while has passed. private func ask(_ now: FilmPlayback.OnTV) { if let asked, asked.id == now.id, abs(now.at - asked.at - Date().timeIntervalSince(asked.when) * (now.paused ? 0 : 1)) < 2, Date().timeIntervalSince(asked.when) < Self.askEvery { return } asked = (now.id, now.at, Date()) guard let source else { return } let device = device Task { if case .read(let answer) = await source.remote(table: now.table, id: now.id, at: now.at, length: now.length > 0 ? now.length : nil, device: device), playing?.id == now.id { words = answer } } } /// The time gone and the time left, kept here between the core's answers, in the core's form. func clock(_ playing: FilmPlayback.OnTV, at: Double? = nil) -> (at: String, left: String?) { let at = at ?? playing.at let left = playing.length > 0 ? ShellLines.line("cinemas", "home.remote_left", ["left": Self.clock(max(0, playing.length - at))]) : nil return (Self.clock(at), left ?? words?.left) } /// m:ss, or h:mm:ss from an hour, as the core writes a time. static func clock(_ seconds: Double) -> String { let s = Int(seconds.isFinite ? max(0, seconds).rounded() : 0) return s >= 3600 ? String(format: "%d:%02d:%02d", s / 3600, s / 60 % 60, s % 60) : String(format: "%d:%02d", s / 60, s % 60) } private func routeChanged() { read() guard device != nil, let waiting else { return } self.waiting = nil start(waiting.item, model: waiting.model) } /// Apple's AirPlay list. func choose() { // The list opens from the route button's own control: there is no other way in for an app. for case let button as UIButton in picker.subviews { button.sendActions(for: .touchUpInside) } } /// Play on TV: at once when a TV is chosen; else the list opens, and the film starts once a TV is picked. func playOnTV(_ item: CinemasItem, model: CinemasModel) { if device != nil { start(item, model: model) return } waiting = (item, model) model.say(CinemasWords.line("stream.tv_waiting")) choose() } /// Plays `item` where the TV is: the engine's own, or the player (which hands it on to the TV). func start(_ item: CinemasItem, model: CinemasModel) { let engine = engine Task { if await !engine.start(item) { model.play(item) } asked = nil read() } } #if COTTON_DEV /// A Dev build's invented TV, named, already chosen. func invent(_ engine: any CinemasTVEngine) { self.engine = engine read() } #endif } /// The route button drawn where a screen wants it (Home's bar, a title's bar): Apple's own, in white. struct CinemasRouteButton: UIViewRepresentable { func makeUIView(context: Context) -> AVRoutePickerView { let picker = AVRoutePickerView() picker.prioritizesVideoDevices = true picker.tintColor = .white picker.activeTintColor = UIColor(CinemasInk.accent) picker.accessibilityIdentifier = "cinemas-route" return picker } func updateUIView(_ picker: AVRoutePickerView, context: Context) {} } /// The off-screen route button Play on TV presses, kept in the window so its list has somewhere to open from. struct CinemasHiddenPicker: UIViewRepresentable { let tv: CinemasTV func makeUIView(context: Context) -> UIView { let holder = UIView(frame: CGRect(x: 0, y: 0, width: 1, height: 1)) tv.picker.frame = holder.bounds tv.picker.alpha = 0.011 holder.addSubview(tv.picker) holder.isAccessibilityElement = false holder.accessibilityElementsHidden = true return holder } func updateUIView(_ view: UIView, context: Context) {} } /// The TV bar: the cover, what plays and where, pause; a tap grows it into the remote. It slides up above the bottom bar. struct CinemasTVBar: View { static let height: CGFloat = 64 let tv: CinemasTV var grow: Namespace.ID var body: some View { if let playing = tv.playing { HStack(spacing: 12) { CinemasPicture(key: playing.cover, title: nil, seed: playing.id) .frame(width: 30, height: 45) .clipShape(RoundedRectangle(cornerRadius: 4, style: .continuous)) .accessibilityHidden(true) VStack(alignment: .leading, spacing: 2) { Text(tv.words?.title ?? playing.title).font(CinemasFonts.sans(14, 600)).foregroundStyle(CinemasInk.ink).lineLimit(1) // The core's words; until they come, the TV's name in the same line. Text(tv.words?.playing ?? CinemasWords.line("stream.tv_playing", ["device": tv.device ?? ""])) .font(CinemasType.small) .foregroundStyle(CinemasInk.accent) .lineLimit(1) } .accessibilityElement(children: .combine) .accessibilityAddTraits(.isButton) .accessibilityHint(Text(CinemasWords.line("stream.tv_open"))) Spacer(minLength: 8) Button { tv.engine.pauseOrPlay(); tv.read() } label: { Image(systemName: playing.paused ? "play.fill" : "pause.fill") .font(.system(size: 20, weight: .semibold)) .foregroundStyle(CinemasInk.ink) .frame(width: 44, height: 44) .contentTransition(.symbolEffect(.replace)) } .buttonStyle(CinemasPress()) .accessibilityLabel(Text(CinemasWords.line(playing.paused ? "stream.tv_play" : "stream.tv_pause"))) .accessibilityIdentifier("cinemas-tv-pause") } .padding(.horizontal, 10) .frame(minHeight: 56) .background { ZStack(alignment: .bottomLeading) { RoundedRectangle(cornerRadius: 12, style: .continuous).fill(CinemasInk.raisedHigh) GeometryReader { box in Rectangle().fill(CinemasInk.accent) .frame(width: (playing.length > 0 ? box.size.width * min(playing.at / playing.length, 1) : 0).drawableOrZero, height: 2) .frame(maxHeight: .infinity, alignment: .bottom) .animation(CinemasMotion.keeping, value: playing.at) } .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) } } .matchedTransitionSource(id: "cinemas-tv", in: grow) { $0.clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) } .padding(.horizontal, 8) .padding(.vertical, 4) .contentShape(Rectangle()) .onTapGesture { tv.remoteOpen = true } .accessibilityElement(children: .contain) .accessibilityAction(named: Text(CinemasWords.line("stream.tv_open"))) { tv.remoteOpen = true } .accessibilityIdentifier("cinemas-tv-bar") } } } /// The remote, while a film plays on the TV (cinemas-3.html frame 8): where it plays, the picture, the title and its /// place in a series, the scrubber with the time gone and the time left, ten-second jumps, pause in the amber circle, /// the row of Subtitles, Audio and Next episode, the note on volume, then Stop on TV (the film waits on the phone, /// paused) and Watch on phone (it carries on here from the same second). struct CinemasRemote: View { let tv: CinemasTV let model: CinemasModel @Environment(\.dismiss) private var dismiss @Environment(\.dynamicTypeSize) private var typeSize @State private var scrubbing: Double? @State private var subtitles: [FilmPlayback.TrackChoice] = [] @State private var sounds: [FilmPlayback.TrackChoice] = [] private let skip: Double = 10 var body: some View { ScrollView { VStack(spacing: 0) { header if let playing = tv.playing { CinemasPicture(key: playing.cover, title: nil, seed: playing.id) .aspectRatio(16 / 9, contentMode: .fit) .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous)) .shadow(color: .black, radius: 30, y: 20) .padding(.horizontal, 28) .padding(.top, 26) .accessibilityHidden(true) VStack(alignment: .leading, spacing: 4) { Text((tv.words?.title ?? playing.title).uppercased()) .font(CinemasType.title(30)).foregroundStyle(CinemasInk.ink).lineLimit(3) .accessibilityAddTraits(.isHeader) if let caption = tv.words?.caption ?? playing.caption { Text(caption).font(CinemasFonts.sans(14, 400)).foregroundStyle(CinemasInk.quiet) } } .frame(maxWidth: .infinity, alignment: .leading) .padding(.top, 22) .padding(.horizontal, 28) CinemasScrubber(tv: tv, playing: playing, scrubbing: $scrubbing) .padding(.horizontal, 28) .padding(.top, 22) jumps(playing) .padding(.top, 26) .padding(.horizontal, 34) row .padding(.top, 30) .padding(.horizontal, 16) if let volume = tv.words?.volume { Text(volume).font(CinemasType.small).foregroundStyle(CinemasInk.quiet).multilineTextAlignment(.center) .padding(.top, 16).padding(.horizontal, 28) } leave .padding(.top, 16) .padding(.horizontal, 28) .padding(.bottom, 24) } } } .scrollBounceBehavior(.basedOnSize) .background { LinearGradient(stops: [.init(color: CinemasInk.remoteTop, location: 0), .init(color: CinemasInk.ground, location: 0.6)], startPoint: .top, endPoint: .bottom) .ignoresSafeArea() } .preferredColorScheme(.dark) .task(id: tv.playing?.id) { subtitles = await tv.engine.tracks(.legible) sounds = await tv.engine.tracks(.audible) } .accessibilityIdentifier("cinemas-remote") } private var header: some View { HStack { Button { dismiss() } label: { Image(systemName: "chevron.down").font(.system(size: 18, weight: .semibold)).foregroundStyle(CinemasInk.quiet).frame(width: 44, height: 44) } .accessibilityLabel(Text(CinemasWords.line("stream.tv_close"))) .accessibilityIdentifier("cinemas-remote-close") Spacer(minLength: 8) Label { Text(tv.words?.playing ?? CinemasWords.line("stream.tv_playing", ["device": tv.device ?? ""])) } icon: { Image(systemName: "tv") } .font(CinemasFonts.sans(15, 700)).foregroundStyle(CinemasInk.ink) .labelStyle(CinemasAmberIcon()) .multilineTextAlignment(.center) .accessibilityIdentifier("cinemas-remote-playing") Spacer(minLength: 8) CinemasRouteButton().frame(width: 44, height: 44) .accessibilityLabel(Text(CinemasWords.line("stream.tv_choose"))) } .padding(.horizontal, 12) .padding(.top, 12) } private func jumps(_ playing: FilmPlayback.OnTV) -> some View { HStack { Button { tv.engine.skip(by: -skip); tv.read() } label: { Image(systemName: "gobackward.10").font(.system(size: 32)).foregroundStyle(CinemasInk.ink).frame(width: 56, height: 56) } .accessibilityLabel(Text(CinemasWords.line("stream.tv_back", ["seconds": "\(Int(skip))"]))) .accessibilityIdentifier("cinemas-remote-back") Spacer() Button { tv.engine.pauseOrPlay(); tv.read() } label: { Image(systemName: playing.paused ? "play.fill" : "pause.fill") .font(.system(size: 34, weight: .bold)) .foregroundStyle(CinemasInk.onAccent) .frame(width: 84, height: 84) .background(Circle().fill(CinemasInk.accent)) .shadow(color: CinemasInk.accent.opacity(0.45), radius: 15, y: 10) .contentTransition(.symbolEffect(.replace)) } .buttonStyle(CinemasPress()) .accessibilityLabel(Text(CinemasWords.line(playing.paused ? "stream.tv_play" : "stream.tv_pause"))) .accessibilityIdentifier("cinemas-remote-pause") Spacer() Button { tv.engine.skip(by: skip); tv.read() } label: { Image(systemName: "goforward.10").font(.system(size: 32)).foregroundStyle(CinemasInk.ink).frame(width: 56, height: 56) } .accessibilityLabel(Text(CinemasWords.line("stream.tv_forward", ["seconds": "\(Int(skip))"]))) .accessibilityIdentifier("cinemas-remote-forward") } } /// Subtitles, Audio and Next episode: each says what stands now under its mark. private var row: some View { let layout = typeSize.isAccessibilitySize ? AnyLayout(VStackLayout(alignment: .leading, spacing: 14)) : AnyLayout(HStackLayout(alignment: .top, spacing: 0)) return layout { trackMenu(.legible, icon: "captions.bubble", label: CinemasWords.line("home.act_subtitles"), choices: subtitles, none: CinemasWords.line("home.subtitles_none"), off: CinemasWords.line("home.subtitles_off")) .accessibilityIdentifier("cinemas-remote-subtitles") trackMenu(.audible, icon: "waveform", label: CinemasWords.line("stream.tv_audio"), choices: sounds, none: CinemasWords.line("stream.tv_audio"), off: nil) .accessibilityIdentifier("cinemas-remote-audio") if let next = tv.words?.next { Button { tv.start(CinemasItem(table: next.table, id: next.id, title: next.label, kind: .episode), model: model) } label: { act(icon: "forward.end", word: next.label, second: nil) } .buttonStyle(CinemasPress()) .accessibilityIdentifier("cinemas-remote-next") } } } private func trackMenu(_ kind: AVMediaCharacteristic, icon: String, label: String, choices: [FilmPlayback.TrackChoice], none: String, off: String?) -> some View { let chosen = choices.first(where: \.chosen)?.name ?? (choices.isEmpty ? none : off ?? none) return Menu { if let off, !choices.isEmpty { Button { pick(nil, kind) } label: { Label(off, systemImage: choices.contains(where: \.chosen) ? "" : "checkmark") } } ForEach(choices) { choice in Button { pick(choice.id, kind) } label: { if choice.chosen { Label(choice.name, systemImage: "checkmark") } else { Text(choice.name) } } } } label: { act(icon: icon, word: chosen, second: nil) } .disabled(choices.isEmpty) .accessibilityLabel(Text(label)) .accessibilityValue(Text(chosen)) } private func pick(_ index: Int?, _ kind: AVMediaCharacteristic) { Task { await tv.engine.choose(index, kind) if kind == .legible { subtitles = await tv.engine.tracks(.legible) } else { sounds = await tv.engine.tracks(.audible) } } } private func act(icon: String, word: String, second: String?) -> some View { let wide = typeSize.isAccessibilitySize let layout = wide ? AnyLayout(HStackLayout(spacing: 12)) : AnyLayout(VStackLayout(spacing: 6)) return layout { Image(systemName: icon).font(.system(size: 22)).foregroundStyle(CinemasInk.ink).frame(height: 26) Text(word).font(CinemasFonts.sans(11, 500)).foregroundStyle(CinemasInk.quiet) .multilineTextAlignment(wide ? .leading : .center).lineLimit(wide ? nil : 2) } .frame(maxWidth: wide ? .infinity : 96, alignment: wide ? .leading : .center) .frame(maxWidth: .infinity) .contentShape(Rectangle()) } private var leave: some View { let layout = typeSize.isAccessibilitySize ? AnyLayout(VStackLayout(spacing: 10)) : AnyLayout(HStackLayout(spacing: 10)) return layout { CinemasButton(label: CinemasWords.line("stream.tv_stop"), icon: "stop.fill", style: .plain, height: 42) { tv.engine.leave(watchHere: false) tv.read() dismiss() } .accessibilityIdentifier("cinemas-remote-stop") CinemasButton(label: CinemasWords.line("stream.watch_on_phone"), icon: "iphone", style: .plain, height: 42) { dismiss() tv.engine.leave(watchHere: true) tv.read() } .accessibilityIdentifier("cinemas-remote-phone") } } } /// The scrubber of frame 8: a 5 pt track, the part played in amber, a 17 pt white knob; the time gone and the time /// left under it. A drag moves the knob and the times; letting go sends the place to the TV. VoiceOver adjusts it ten /// seconds at a time. struct CinemasScrubber: View { let tv: CinemasTV let playing: FilmPlayback.OnTV @Binding var scrubbing: Double? private static let track: CGFloat = 5 private static let knob: CGFloat = 17 var body: some View { let at = scrubbing ?? playing.at let share = playing.length > 0 ? min(max(at / playing.length, 0), 1) : 0 let times = tv.clock(playing, at: at) VStack(spacing: 8) { GeometryReader { box in let width = box.size.width.drawableOrZero ZStack(alignment: .leading) { Capsule().fill(Color.white.opacity(0.18)).frame(height: Self.track) Capsule().fill(CinemasInk.accent).frame(width: (width * share).drawableOrZero, height: Self.track) Circle().fill(Color.white).frame(width: Self.knob, height: Self.knob) .scaleEffect(scrubbing == nil ? 1 : 1.25) .offset(x: (width * share - Self.knob / 2).drawableOrZero) .animation(CinemasMotion.pressUp, value: scrubbing == nil) } .frame(height: 28) .contentShape(Rectangle()) .gesture(DragGesture(minimumDistance: 0) .onChanged { drag in guard width > 0, playing.length > 0 else { return } scrubbing = min(max(drag.location.x / width, 0), 1) * playing.length } .onEnded { _ in if let to = scrubbing { tv.engine.seek(to: to) } scrubbing = nil tv.read() }) } .frame(height: 28) HStack { Text(times.at).monospacedDigit() Spacer() if let left = times.left { Text(left).monospacedDigit() } } .font(CinemasFonts.sans(12, 400)) .foregroundStyle(CinemasInk.quiet) } .accessibilityElement(children: .ignore) .accessibilityLabel(Text(CinemasWords.line("stream.tv_place"))) .accessibilityValue(Text([times.at, times.left].compactMap { $0 }.joined(separator: ", "))) .accessibilityAdjustableAction { direction in switch direction { case .increment: tv.engine.skip(by: 10) case .decrement: tv.engine.skip(by: -10) @unknown default: break } tv.read() } .accessibilityIdentifier("cinemas-remote-scrubber") } } /// A label whose icon stands in amber. struct CinemasAmberIcon: LabelStyle { func makeBody(configuration: Configuration) -> some View { HStack(spacing: 6) { configuration.icon.foregroundStyle(CinemasInk.accent) configuration.title } } } #endif