PulseCanvas / app / visionOS / VisionSession.swift
| 1 | import Combine |
| 2 | import Foundation |
| 3 | |
| 4 | /// Radio has its own transport and timeline; listening never overwrites a Studio project. |
| 5 | @MainActor final class VisionSession: ObservableObject { |
| 6 | let editor: VisionStudio |
| 7 | let radio: VisionRadio |
| 8 | @Published private(set) var radioMode = false |
| 9 | @Published var immersiveActive = false |
| 10 | @Published var fullImmersion = true |
| 11 | @Published var studioWindowHidden = false |
| 12 | @Published var edgeSmoothing = true |
| 13 | var activeStudio: VisionStudio { radioMode ? radio.studio : editor } |
| 14 | |
| 15 | init(editor: VisionStudio? = nil, radio: VisionRadio? = nil) { |
| 16 | self.editor = editor ?? VisionStudio(); self.radio = radio ?? VisionRadio() |
| 17 | } |
| 18 | func setRadioMode(_ enabled: Bool) { |
| 19 | guard enabled != radioMode, !immersiveActive else { return } |
| 20 | if radioMode { radio.suspend() } else { editor.suspend() } |
| 21 | radioMode = enabled |
| 22 | } |
| 23 | func suspend() { editor.suspend(); radio.suspend() } |
| 24 | } |
| 25 | |
| 26 | @MainActor final class VisionRadio: ObservableObject { |
| 27 | let studio: VisionStudio |
| 28 | @Published private(set) var stations: [RadioStation] = [] |
| 29 | @Published private(set) var stationID = "all-music" |
| 30 | @Published private(set) var favoriteSongs: [FavoriteRadioSong] = [] |
| 31 | @Published private(set) var favoriteSongsOnly = false |
| 32 | @Published private(set) var loading = false |
| 33 | @Published private(set) var loadingStations = false |
| 34 | @Published var error: String? |
| 35 | @Published private(set) var isPersonalMusic = false |
| 36 | @Published private(set) var folderImportNotice: String? |
| 37 | @Published var shuffle = true { didSet { queue.reset() } } |
| 38 | var hasPersonalMusic: Bool { defaults.url(forKey: PersonalRadioMusic.catalogKey) != nil } |
| 39 | var personalMusicTitle: String { isPersonalMusic ? catalog?.title ?? "My music folder" : "My music folder" } |
| 40 | private var folderTask: Task<Void, Never>? |
| 41 | private let source: URL |
| 42 | var studioMusicSource: URL { source } |
| 43 | var studioMusicLibrary: RadioLibrary { library } |
| 44 | private let library: RadioLibrary |
| 45 | private let defaults: UserDefaults |
| 46 | private let favoriteSongsKey = "PulseCanvas.radio.favoriteSongs.v1" |
| 47 | var musicGroupID: String { isPersonalMusic ? "my-music" : favoriteSongsOnly ? "favorite-songs" : stationID } |
| 48 | var playingTrack: RadioTrack? { |
| 49 | currentTrack.flatMap { index in catalog?.tracks.indices.contains(index) == true ? catalog?.tracks[index] : nil } |
| 50 | } |
| 51 | private var eligibleTrackIndices: [Int] { |
| 52 | guard let catalog else { return [] } |
| 53 | let favorites = Set(favoriteSongs.map(\.id)) |
| 54 | return catalog.tracks.indices.filter { !favoriteSongsOnly || favorites.contains(catalog.tracks[$0].id) } |
| 55 | } |
| 56 | private var catalog: RadioCatalog? |
| 57 | private var catalogURL: URL? |
| 58 | private var currentTrack: Int? |
| 59 | private var queue = RadioQueue() |
| 60 | private var task: Task<Void, Never>? |
| 61 | private var wantsPlayback = false |
| 62 | |
| 63 | init(directory: URL? = nil, source: URL = URL(string: "https://radio.pulsecanvas.si/stations.json")!, |
| 64 | presets: ProjectMPresets? = nil, defaults: UserDefaults = .standard) { |
| 65 | let root = directory ?? FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] |
| 66 | .appendingPathComponent("PulseCanvas/VisionRadio", isDirectory: true) |
| 67 | self.source = source |
| 68 | self.defaults = defaults |
| 69 | let personal = defaults.bool(forKey: PersonalRadioMusic.activeKey) && defaults.url(forKey: PersonalRadioMusic.catalogKey) != nil |
| 70 | isPersonalMusic = personal |
| 71 | if let data = defaults.data(forKey: favoriteSongsKey), data.count <= 8_000_000, |
| 72 | let saved = try? JSONDecoder().decode([FavoriteRadioSong].self, from: data), saved.count <= 2_000 { |
| 73 | var seen = Set<String>() |
| 74 | favoriteSongs = saved.filter { $0.sourceURL == source && $0.isValid && seen.insert($0.id).inserted } |
| 75 | } |
| 76 | favoriteSongsOnly = !personal && defaults.bool(forKey: "PulseCanvas.radio.favoriteSongsOnly.v1") |
| 77 | library = RadioLibrary(directory: root.appendingPathComponent("Audio")) |
| 78 | studio = VisionStudio(directory: root.appendingPathComponent("Session"), library: presets) |
| 79 | studio.randomizesPlaybackLooks = true |
| 80 | studio.loopPlayback = false |
| 81 | studio.onPlaybackFinished = { [weak self] in |
| 82 | guard let self, self.wantsPlayback else { return } |
| 83 | self.nextSong() |
| 84 | } |
| 85 | } |
| 86 | private var stationsTask: Task<Void, Never>? |
| 87 | /// Loads the station list. A second caller while a load is in flight waits for that load instead of returning at |
| 88 | /// once: Play Radio pressed before the list arrived used to find no stations and report an invalid catalog. |
| 89 | func refreshStations() async { |
| 90 | if let stationsTask { await stationsTask.value; return } |
| 91 | let task = Task { await self.loadStations() } |
| 92 | stationsTask = task |
| 93 | await task.value |
| 94 | stationsTask = nil |
| 95 | } |
| 96 | private func loadStations() async { |
| 97 | loadingStations = !isPersonalMusic; error = nil |
| 98 | defer { loadingStations = false } |
| 99 | do { |
| 100 | stations = try await library.stations(at: source).stations |
| 101 | if !isPersonalMusic && !stations.contains(where: { $0.id == stationID }) { |
| 102 | stationID = stations.first?.id ?? "all-music" |
| 103 | catalog = nil; catalogURL = nil; queue.reset(); currentTrack = nil |
| 104 | } |
| 105 | } catch { if !isPersonalMusic { self.error = String(localized: "Stations couldn't load. Check your connection and try again.") } } |
| 106 | } |
| 107 | func importMusicFolder(_ folder: URL) { |
| 108 | guard !loading else { return } |
| 109 | loading = true; error = nil; folderImportNotice = nil |
| 110 | let previous = defaults.url(forKey: PersonalRadioMusic.catalogKey) |
| 111 | folderTask = Task { [weak self, library] in |
| 112 | do { |
| 113 | let result = try await library.importMusicFolder(folder) |
| 114 | guard let self, !Task.isCancelled else { |
| 115 | await library.removePersonalCopy(at: result.url); return |
| 116 | } |
| 117 | self.defaults.set(result.url, forKey: PersonalRadioMusic.catalogKey) |
| 118 | self.loading = false; self.folderTask = nil |
| 119 | self.selectStation("my-music") |
| 120 | if result.skipped > 0 { self.folderImportNotice = String(localized: "\(result.skipped) unsupported files skipped.") } |
| 121 | await library.removePersonalCopy(at: previous) |
| 122 | } catch { |
| 123 | if !Task.isCancelled { self?.loading = false; self?.error = error.localizedDescription } |
| 124 | } |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | func selectStation(_ id: String) { |
| 129 | guard !loading else { return } |
| 130 | if id == "my-music" { |
| 131 | guard hasPersonalMusic else { return } |
| 132 | isPersonalMusic = true; favoriteSongsOnly = false |
| 133 | defaults.set(true, forKey: PersonalRadioMusic.activeKey) |
| 134 | catalog = nil; catalogURL = nil; currentTrack = nil; queue.reset() |
| 135 | nextSong(); return |
| 136 | } |
| 137 | if stations.isEmpty { |
| 138 | Task { [weak self] in |
| 139 | guard let self else { return } |
| 140 | await self.refreshStations() |
| 141 | if self.stations.isEmpty { self.error = String(localized: "Stations couldn't load. Your local music remains available.") } |
| 142 | else { self.selectStation(id) } |
| 143 | } |
| 144 | return |
| 145 | } |
| 146 | if isPersonalMusic { |
| 147 | isPersonalMusic = false; catalog = nil; catalogURL = nil; currentTrack = nil; queue.reset() |
| 148 | defaults.set(false, forKey: PersonalRadioMusic.activeKey) |
| 149 | } |
| 150 | if id == "favorite-songs" { |
| 151 | guard !loading else { return } |
| 152 | favoriteSongsOnly = true |
| 153 | defaults.set(true, forKey: "PulseCanvas.radio.favoriteSongsOnly.v1") |
| 154 | if let all = stations.first(where: { $0.id == "all-music" }) ?? (stations.count == 1 ? stations.first : nil) { |
| 155 | selectLoadedStation(all.id) |
| 156 | } else { error = String(localized: "The full music library isn't available. Try refreshing stations.") } |
| 157 | return |
| 158 | } |
| 159 | guard !loading, stations.contains(where: { $0.id == id }) else { return } |
| 160 | favoriteSongsOnly = false |
| 161 | defaults.set(false, forKey: "PulseCanvas.radio.favoriteSongsOnly.v1") |
| 162 | selectLoadedStation(id) |
| 163 | } |
| 164 | private func selectLoadedStation(_ id: String) { |
| 165 | if id != stationID { stationID = id; catalog = nil; catalogURL = nil; queue.reset(); currentTrack = nil } |
| 166 | queue.reset() |
| 167 | nextSong() |
| 168 | } |
| 169 | func isFavoriteSong(_ track: RadioTrack) -> Bool { favoriteSongs.contains { $0.id == track.id } } |
| 170 | func toggleFavoriteSong(_ track: RadioTrack) { |
| 171 | guard !isPersonalMusic || isFavoriteSong(track) else { return } |
| 172 | if let index = favoriteSongs.firstIndex(where: { $0.id == track.id }) { |
| 173 | favoriteSongs.remove(at: index) |
| 174 | } else if let catalogURL, catalog?.tracks.contains(where: { $0.id == track.id }) == true, |
| 175 | favoriteSongs.count < 2_000 { |
| 176 | let song = FavoriteRadioSong(track: track, sourceURL: source, catalogURL: catalogURL, |
| 177 | stationID: stationID, folderBookmark: nil) |
| 178 | guard song.isValid else { return } |
| 179 | favoriteSongs.append(song) |
| 180 | } |
| 181 | persistFavorites() |
| 182 | if favoriteSongsOnly && favoriteSongs.isEmpty { suspend() } |
| 183 | } |
| 184 | private func persistFavorites() { |
| 185 | if let data = try? JSONEncoder().encode(favoriteSongs) { defaults.set(data, forKey: favoriteSongsKey) } |
| 186 | NotificationCenter.default.post(name: .pulseCanvasUserDataChanged, object: nil) |
| 187 | queue.reset() |
| 188 | } |
| 189 | func reloadCloudFavorites() { |
| 190 | guard let data = defaults.data(forKey: favoriteSongsKey), |
| 191 | let songs = try? JSONDecoder().decode([FavoriteRadioSong].self, from: data), songs.count <= 2_000 else { return } |
| 192 | favoriteSongs = songs.filter { $0.isValid && $0.sourceURL == source }; queue.reset() |
| 193 | } |
| 194 | private var refreshingFavorites = false |
| 195 | /// Only the full, successfully loaded catalog can establish that a saved song was removed. |
| 196 | private func reconcileFavorites(_ complete: RadioCatalog, url: URL, stationID: String) { |
| 197 | let tracks = Dictionary(uniqueKeysWithValues: complete.tracks.map { ($0.id, $0) }) |
| 198 | let retained = favoriteSongs.compactMap { song -> FavoriteRadioSong? in |
| 199 | guard let track = tracks[song.id] else { return nil } |
| 200 | return FavoriteRadioSong(track: track, sourceURL: source, catalogURL: url, |
| 201 | stationID: stationID, folderBookmark: nil) |
| 202 | } |
| 203 | if retained != favoriteSongs { favoriteSongs = retained; persistFavorites() } |
| 204 | } |
| 205 | func refreshFavoriteSongs() async { |
| 206 | guard !refreshingFavorites, !favoriteSongs.isEmpty else { return } |
| 207 | refreshingFavorites = true |
| 208 | defer { refreshingFavorites = false } |
| 209 | guard let complete = try? await library.completeCatalog(at: source), !Task.isCancelled else { return } |
| 210 | reconcileFavorites(complete.catalog, url: complete.url, stationID: complete.stationID) |
| 211 | if favoriteSongsOnly && favoriteSongs.isEmpty { suspend() } |
| 212 | } |
| 213 | func playFavoriteSong(_ song: FavoriteRadioSong) { |
| 214 | guard !loading, favoriteSongs.contains(where: { $0.id == song.id }) else { return } |
| 215 | isPersonalMusic = false; defaults.set(false, forKey: PersonalRadioMusic.activeKey) |
| 216 | favoriteSongsOnly = true |
| 217 | defaults.set(true, forKey: "PulseCanvas.radio.favoriteSongsOnly.v1") |
| 218 | // Refresh the full catalog before selecting the saved identity. |
| 219 | stationID = "all-music"; catalog = nil; catalogURL = nil; currentTrack = nil; queue.reset() |
| 220 | nextSong(preferredTrackID: song.id) |
| 221 | } |
| 222 | func nextSong(preferredTrackID: String? = nil) { |
| 223 | guard !loading else { return } |
| 224 | if favoriteSongsOnly && favoriteSongs.isEmpty { |
| 225 | suspend(); error = String(localized: "No favorite songs yet. Tap a song's heart in Radio to save it."); return |
| 226 | } |
| 227 | loading = true; wantsPlayback = true; error = nil |
| 228 | studio.suspend() |
| 229 | task = Task { [weak self] in |
| 230 | guard let self else { return } |
| 231 | defer { self.loading = false } |
| 232 | do { |
| 233 | if self.isPersonalMusic { |
| 234 | if self.catalog == nil { |
| 235 | guard let url = self.defaults.url(forKey: PersonalRadioMusic.catalogKey) else { throw RadioError.invalidCatalog } |
| 236 | self.catalog = try await self.library.catalog(at: url); self.catalogURL = url |
| 237 | self.queue.reset(); self.currentTrack = nil |
| 238 | } |
| 239 | } else { |
| 240 | if self.stations.isEmpty { await self.refreshStations() } |
| 241 | try Task.checkCancellation() |
| 242 | let selectedID = self.favoriteSongsOnly ? "all-music" : self.stationID |
| 243 | guard let station = self.stations.first(where: { $0.id == selectedID }) |
| 244 | ?? (self.stations.count == 1 ? self.stations.first : nil) else { throw RadioError.invalidCatalog } |
| 245 | self.stationID = station.id |
| 246 | if self.catalog == nil { |
| 247 | let url = try station.resolvedURL(relativeTo: self.source) |
| 248 | self.catalog = try await self.library.catalog(at: url); self.catalogURL = url |
| 249 | self.queue.reset(); self.currentTrack = nil |
| 250 | if station.id == "all-music" || self.stations.count == 1, let catalog = self.catalog { |
| 251 | self.reconcileFavorites(catalog, url: url, stationID: station.id) |
| 252 | } |
| 253 | } |
| 254 | } |
| 255 | let choices = self.eligibleTrackIndices |
| 256 | guard let catalog = self.catalog, let url = self.catalogURL else { throw RadioError.invalidCatalog } |
| 257 | let preferred = preferredTrackID.flatMap { id in choices.first(where: { catalog.tracks[$0].id == id }) } |
| 258 | if preferredTrackID != nil && preferred == nil { |
| 259 | self.error = String(localized: "This song is no longer available in Radio."); return |
| 260 | } |
| 261 | guard let first = preferred ?? self.queue.next(count: choices.count, |
| 262 | current: self.currentTrack.flatMap { choices.firstIndex(of: $0) }, shuffle: self.shuffle).map({ choices[$0] }) else { |
| 263 | throw RadioError.allUnavailable |
| 264 | } |
| 265 | let others = choices.filter { $0 != first } |
| 266 | let candidates = [first] + (self.shuffle ? others.shuffled() : others) |
| 267 | var loadedIndex: Int? |
| 268 | for next in candidates { |
| 269 | try Task.checkCancellation() |
| 270 | let track = catalog.tracks[next] |
| 271 | do { |
| 272 | let audio = try await self.library.localAudio(for: track, catalogURL: url) |
| 273 | try Task.checkCancellation() |
| 274 | if await self.studio.loadRadioAudio(audio, title: track.title) { loadedIndex = next; break } |
| 275 | } catch is CancellationError { throw CancellationError() } |
| 276 | catch { continue } |
| 277 | } |
| 278 | guard let loadedIndex else { throw RadioError.allUnavailable } |
| 279 | guard !Task.isCancelled, self.wantsPlayback else { self.studio.suspend(); return } |
| 280 | self.currentTrack = loadedIndex |
| 281 | self.studio.randomizeVisualizer() |
| 282 | #if os(visionOS) |
| 283 | VisionLaunchOptions.current.applyCaptureSequence(to: self.studio) |
| 284 | #endif |
| 285 | self.studio.togglePlayback() |
| 286 | } catch is CancellationError { } |
| 287 | catch { self.error = String(localized: "Radio couldn't play this track. \(error.localizedDescription)") } |
| 288 | } |
| 289 | } |
| 290 | func togglePlayback() { |
| 291 | guard !loading else { return } |
| 292 | if favoriteSongsOnly && (playingTrack.map { !isFavoriteSong($0) } ?? true) { nextSong(); return } |
| 293 | guard currentTrack != nil else { nextSong(); return } |
| 294 | wantsPlayback = !studio.transport.playing |
| 295 | studio.togglePlayback() |
| 296 | } |
| 297 | func suspend() { |
| 298 | wantsPlayback = false |
| 299 | if folderTask != nil { folderTask?.cancel(); folderTask = nil; loading = false } |
| 300 | task?.cancel(); studio.suspend() |
| 301 | } |
| 302 | /// Awaitable for local fixture checks; UI requests stay asynchronous and responsive. |
| 303 | func waitForTrack() async { await task?.value } |
| 304 | } |