Branchwell

PulseCanvas / app / visionOS / VisionStudioView.swift

1import SwiftUI
2import UniformTypeIdentifiers
3
4struct VisionStudioView: View {
5 @ObservedObject var studio: VisionStudio
6 @ObservedObject var session: VisionSession
7 @Environment(\.openImmersiveSpace) private var openSpace
8 @Environment(\.dismissImmersiveSpace) private var dismissSpace
9 @Environment(\.dismissWindow) private var dismissWindow
10 @Environment(\.scenePhase) private var phase
11 @Environment(\.pulseCanvasOnboardingActive) private var onboardingActive
12 @State private var importAudio = false
13 @State private var chooseMusic = false
14 @State private var importProject = false
15 @State private var exportProject = false
16 @State private var projectData = Data()
17 @State private var locateAudio = false
18 @State private var exportVideo = false
19 @State private var changingSpace = false
20 @State private var showLibrary = false
21 @State private var showStyle = false
22 @State private var legal = false
23 @State private var replayOnboardingAfterSupport = false
24 @State private var launchApplied = false
25
26 var body: some View {
27 VStack(spacing: 16) {
28 workspaceHeader
29 if session.radioMode {
30 radioSurface
31 } else {
32 VStack(alignment: .leading, spacing: 12) {
33 preview.aspectRatio(16.0 / 9, contentMode: .fit)
34 .accessibilityIdentifier("visionVisualizerPreview")
35 .frame(maxWidth: .infinity, maxHeight: .infinity)
36 VisionTransportView(studio: studio, transport: studio.transport)
37 if studio.needsSoundtrack {
38 Button("Locate soundtrack", systemImage: "waveform.badge.plus") { locateAudio = true }
39 .buttonStyle(.borderedProminent)
40 }
41 }
42 }
43 if !session.radioMode { VisionTimelineView(studio: studio) }
44 }.padding(.vertical, 20).padding(.leading, 12).padding(.trailing, 20)
45 .frame(minWidth: 1100, minHeight: 780)
46 .ornament(visibility: onboardingActive ? .hidden : .visible,
47 attachmentAnchor: .scene(.bottom), contentAlignment: .top) {
48 editorControls.padding(12).glassBackgroundEffect().padding(.top, 12)
49 }
50 .sheet(isPresented: $showStyle) {
51 VStack(alignment: .leading, spacing: 20) {
52 HStack {
53 Text("Visual style").font(.title2.bold())
54 Spacer()
55 Button("Done") { showStyle = false }
56 .accessibilityIdentifier("closeVisionStyleButton")
57 }
58 VisionStyleControls(studio: studio)
59 }.padding(32).frame(width: 1000, height: 720)
60 .accessibilityElement(children: .contain)
61 .accessibilityIdentifier("visionStylePanel")
62 }
63 .sheet(isPresented: $showLibrary) {
64 VisionLibrary(studio: studio) { showLibrary = false }
65 .padding(24).frame(width: 760, height: 730)
66 }
67 .sheet(isPresented: $chooseMusic) {
68 VisionStudioMusicPicker(studio: session.editor, radio: session.radio) { chooseMusic = false }
69 .frame(width: 680, height: 640)
70 }
71 .sheet(isPresented: $legal, onDismiss: {
72 guard replayOnboardingAfterSupport else { return }
73 replayOnboardingAfterSupport = false
74 // Finish removing the support sheet before replacing its root view.
75 NotificationCenter.default.post(name: .pulseCanvasOnboarding, object: nil)
76 }) {
77 VisionInfoView(session: session, close: { legal = false }, replayOnboarding: {
78 replayOnboardingAfterSupport = true
79 legal = false
80 })
81 }
82 .sheet(isPresented: $exportVideo) { VisionVideoExportView(studio: studio) { exportVideo = false } }
83 .task { await session.editor.start(); await applyLaunchOptions() }
84 // Reconcile saved songs even when the listener stays in Studio.
85 .task { await session.radio.refreshFavoriteSongs() }
86 .task(id: session.radioMode) { if session.radioMode { await session.radio.refreshStations() } }
87 .onChange(of: phase) { _, phase in if phase == .background && !session.immersiveActive { session.suspend() } }
88 .fileImporter(isPresented: $importAudio, allowedContentTypes: [.audio]) { result in
89 switch result {
90 case .success(let url): Task { await studio.importAudio(url) }
91 case .failure(let error): studio.message = error.localizedDescription
92 }
93 }
94 .onOpenURL { openProject($0) }
95 .fileImporter(isPresented: $locateAudio, allowedContentTypes: [.audio]) { result in
96 switch result {
97 case .success(let url): Task { await studio.importAudio(url, generateTimeline: false) }
98 case .failure(let error): studio.message = error.localizedDescription
99 }
100 }
101 .fileImporter(isPresented: $importProject, allowedContentTypes: [.pulseCanvas, .pulseVision, .json]) { result in
102 switch result {
103 case .success(let url): openProject(url)
104 case .failure(let error): studio.message = error.localizedDescription
105 }
106 }
107 .fileExporter(isPresented: $exportProject, document: VisionProjectDocument(data: projectData),
108 contentType: .pulseCanvas, defaultFilename: "PulseCanvas Studio") { result in
109 if case .failure(let error) = result { studio.message = error.localizedDescription }
110 if case .success(let url) = result {
111 do { try UserBackup.rememberProject(projectData, name: url.path) }
112 catch { studio.message = String(localized: "Project saved, but its backup copy wasn't updated: \(error.localizedDescription)") }
113 }
114 }
115 .alert("PulseCanvas Studio", isPresented: Binding(get: { studio.message != nil }, set: { if !$0 { studio.message = nil } })) {
116 Button("OK") { studio.message = nil }
117 } message: { Text(studio.message ?? "") }
118 }
119
120 // A separate, neutral ornament leaves the window for the canvas and timeline.
121 private var editorControls: some View {
122 HStack(spacing: 12) {
123 if !session.radioMode {
124 Button("Choose music", systemImage: "music.note.list") { chooseMusic = true }.disabled(studio.loading)
125 .accessibilityIdentifier("chooseStudioMusicButton")
126 .help("Choose music")
127 Button("Import audio", systemImage: "tray.and.arrow.down") { importAudio = true }.disabled(studio.loading || session.radioMode)
128 .accessibilityIdentifier("importAudioButton")
129 .help("Import audio")
130 Button("Open project", systemImage: "folder") { importProject = true }.disabled(studio.loading || session.radioMode)
131 .help("Open project")
132 Button("Save project", systemImage: "internaldrive") {
133 do {
134 studio.prepareProjectIdentity()
135 projectData = try studio.project.portableData(duration: studio.transport.duration, scene: studio.selectedScene)
136 exportProject = true
137 } catch { studio.message = String(localized: "Couldn't save project: \(error.localizedDescription)") }
138 }.disabled(session.radioMode || studio.loading || studio.needsSoundtrack)
139 .accessibilityIdentifier("saveProjectButton")
140 .help("Save project")
141 Button("Export MP4", systemImage: "film") { exportVideo = true }
142 .disabled(studio.loading || session.radioMode)
143 .accessibilityIdentifier("exportMP4Button")
144 .help("Export MP4")
145 Divider().frame(height: 28)
146 }
147 Button("Settings", systemImage: "gearshape") { legal = true }
148 .accessibilityIdentifier("visionInfoButton")
149 .help("Settings")
150 if studio.loading { ProgressView("Analyzing music…") }
151 HStack(spacing: 8) {
152 Text("Hide room").font(.callout)
153 Toggle("Hide room", isOn: $session.fullImmersion).labelsHidden()
154 .toggleStyle(.switch).disabled(session.immersiveActive)
155 .accessibilityIdentifier("hideRoomToggle")
156 .tint(Color(red: 0.95, green: 0.68, blue: 0.55))
157 }.fixedSize()
158 immersiveButton
159 }.labelStyle(.iconOnly).buttonStyle(.borderless).tint(.white)
160 }
161
162 private var preview: some View {
163 Group {
164 if session.immersiveActive {
165 VStack(spacing: 16) {
166 Image(systemName: "visionpro").font(.largeTitle)
167 Text("Immersive viewing is active").font(.title3)
168 }.frame(maxWidth: .infinity, maxHeight: .infinity)
169 } else if exportVideo {
170 Color.clear.frame(maxWidth: .infinity, maxHeight: .infinity)
171 } else { VisualizerView(state: studio.render).frame(maxWidth: .infinity, maxHeight: .infinity) }
172 }.clipShape(RoundedRectangle(cornerRadius: 22))
173 .overlay {
174 if let error = studio.render.errorMessage { Text(error).padding().background(.regularMaterial) }
175 }
176 }
177
178 // One header owns the workspace switch in both modes, so its position never changes.
179 private var workspaceHeader: some View {
180 HStack(spacing: 20) {
181 Picker("Workspace", selection: Binding(get: { session.radioMode }, set: { session.setRadioMode($0) })) {
182 Label("Studio", systemImage: "rectangle.split.3x1").tag(false)
183 Label("Radio", systemImage: "radio").tag(true)
184 }.pickerStyle(.segmented).frame(width: 340, height: 52).disabled(session.immersiveActive)
185 .accessibilityIdentifier("workspacePicker")
186 if session.radioMode {
187 VisionRadioVisualizerControls(studio: studio)
188 } else {
189 Text(NativeEffects.names[studio.selectedScene]).font(.title2.bold()).lineLimit(1)
190 .accessibilityIdentifier("selectedVisualizerName")
191 }
192 Spacer(minLength: 0)
193 if !session.radioMode {
194 Button { studio.randomizeVisualizer() } label: { Image(systemName: "shuffle") }
195 .accessibilityLabel("Random visualizer").accessibilityIdentifier("randomVisualizerButton")
196 Button { studio.randomizeLook() } label: { Image(systemName: "dice.fill") }
197 .accessibilityLabel("Randomize current visual style").accessibilityIdentifier("randomizeStyleButton")
198 Button { showStyle = true } label: { Image(systemName: "slider.horizontal.3") }
199 .accessibilityLabel("Visual style").accessibilityIdentifier("visionStyleButton")
200 .help("Visual style")
201 }
202 Button("Library", systemImage: "square.grid.2x2") { showLibrary = true }
203 .accessibilityIdentifier("visionLibraryButton")
204 }
205 }
206
207 private var radioSurface: some View {
208 VStack(spacing: 12) {
209 preview.frame(maxWidth: .infinity, maxHeight: .infinity)
210 VStack(spacing: 12) {
211 VisionRadioControls(radio: session.radio)
212 VisionTransportView(studio: studio, transport: studio.transport, radio: session.radio)
213 }.padding(16).background(.white.opacity(0.05), in: RoundedRectangle(cornerRadius: 20))
214 }
215 }
216
217 private var immersiveButton: some View {
218 Button {
219 Task { await toggleImmersive() }
220 } label: {
221 Image(systemName: "visionpro").font(.title3)
222 .frame(minWidth: 44, minHeight: 44)
223 }.disabled(changingSpace)
224 .accessibilityIdentifier("immersiveButton")
225 .accessibilityLabel(session.immersiveActive ? "Leave full screen" : "Enter full screen")
226 .help(session.immersiveActive ? "Leave full screen" : "Enter full screen")
227 }
228
229 private func toggleImmersive() async {
230 changingSpace = true
231 defer { changingSpace = false }
232 if session.immersiveActive { await dismissSpace() }
233 else {
234 switch await openSpace(id: "visualizer-stage") {
235 case .opened:
236 session.immersiveActive = true
237 session.studioWindowHidden = true
238 dismissWindow(id: "studio")
239 case .userCancelled: break
240 case .error: studio.message = String(localized: "Immersive viewing couldn't open. Your Studio remains available.")
241 @unknown default: break
242 }
243 }
244 }
245
246 /// Launch hooks for UI tests and recorded demos (see `VisionLaunchOptions`); applied once, after the soundtrack loads.
247 private func applyLaunchOptions() async {
248 let launch = VisionLaunchOptions.current
249 guard !launchApplied, launch != VisionLaunchOptions(arguments: []) else { return }
250 launchApplied = true
251 let editor = session.editor
252 if let hide = launch.hideRoom { session.fullImmersion = hide }
253 if launch.visualizer != nil, let first = editor.project.clips.first {
254 if let index = launch.visualizerIndex(in: NativeEffects.names) {
255 editor.assign(index, to: first.id); editor.select(first)
256 }
257 if editor.project.clips.first?.scene != launch.visualizerIndex(in: NativeEffects.names) {
258 NSLog("PulseCanvas launch hook: -PCVisualizer %@ is not an available visualizer in this build", launch.visualizer ?? "")
259 }
260 }
261 #if DEBUG
262 if launch.uiTesting, let audio = launch.captureAudio { await editor.importAudio(audio) }
263 #endif
264 launch.applyCaptureSequence(to: editor)
265 if let seconds = launch.seek { editor.seek(seconds) }
266 if launch.radio {
267 session.setRadioMode(true)
268 if launch.autoplay { session.radio.nextSong(); await session.radio.waitForTrack() }
269 } else if launch.autoplay, !editor.transport.playing, editor.transport.duration > 0 {
270 editor.togglePlayback()
271 }
272 if launch.openImmersive { await toggleImmersive() }
273 }
274
275 private func openProject(_ url: URL) {
276 let access = url.startAccessingSecurityScopedResource()
277 defer { if access { url.stopAccessingSecurityScopedResource() } }
278 do {
279 guard (try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? Int.max) < 4_000_000 else { throw CocoaError(.fileReadCorruptFile) }
280 let data = try Data(contentsOf: url)
281 let project = try VisionProject.openPortable(data)
282 Task {
283 await studio.replaceProject(project)
284 do { try UserBackup.rememberProject(data, name: url.path) }
285 catch { studio.message = String(localized: "Project opened, but its backup copy wasn't updated: \(error.localizedDescription)") }
286 }
287 } catch { studio.message = error.localizedDescription }
288 }
289}
290
291private struct VisionRadioVisualizerControls: View {
292 @ObservedObject var studio: VisionStudio
293 @ObservedObject private var library = ProjectMPresets.shared
294 var body: some View {
295 VStack(alignment: .leading, spacing: 6) {
296 HStack(spacing: 12) {
297 HStack(spacing: 8) {
298 Button {
299 library.toggleFavorite(studio.selectedScene, appearance: studio.look.preset)
300 } label: {
301 Image(systemName: library.isFavorite(studio.selectedScene) ? "heart.fill" : "heart")
302 .frame(width: 24, height: 24)
303 }.buttonStyle(.bordered).buttonBorderShape(.circle)
304 .accessibilityLabel(library.isFavorite(studio.selectedScene) ? "Unfavorite visualizer" : "Favorite visualizer")
305 .accessibilityIdentifier("favoriteRadioVisualizerButton")
306 VStack(alignment: .leading, spacing: 2) {
307 Text("Visualizer").font(.caption).foregroundStyle(.secondary)
308 Text(NativeEffects.names[studio.selectedScene]).font(.headline).lineLimit(1)
309 .accessibilityIdentifier("selectedVisualizerName")
310 }.layoutPriority(1)
311
312 }
313 Button("Random visualizer", systemImage: "shuffle") { studio.randomizeVisualizer() }
314 .buttonStyle(.borderedProminent).disabled(library.eligibleScenes.isEmpty)
315 .accessibilityIdentifier("randomVisualizerButton")
316 VisualizerRandomizerPicker(compact: true)
317 }
318 if let message = library.favoritesFallbackMessage {
319 Text(message).font(.caption).foregroundStyle(.secondary)
320 }
321 }
322 }
323}
324
325private struct VisionRadioControls: View {
326 @ObservedObject var radio: VisionRadio
327 @State private var showFavorites = false
328 @State private var musicFolder = false
329 var body: some View {
330 HStack(spacing: 16) {
331 VisionRadioSongTitle(radio: radio)
332 if radio.loadingStations {
333 ProgressView("Loading stations…")
334 } else {
335 Menu {
336 Button("All music") { radio.selectStation("all-music") }
337 ForEach(radio.stations.filter { $0.id != "all-music" }) { station in
338 Button(station.title) { radio.selectStation(station.id) }
339 }
340 Button("Favorite songs") { radio.selectStation("favorite-songs") }
341 Divider()
342 if radio.hasPersonalMusic { Button("My music folder") { radio.selectStation("my-music") } }
343 Button("Choose music folder…", systemImage: "folder.badge.plus") { musicFolder = true }
344 Toggle("Shuffle songs", isOn: $radio.shuffle)
345 } label: {
346 Label(radio.isPersonalMusic ? radio.personalMusicTitle : radio.favoriteSongsOnly ? "Favorite songs" : radio.stations.first { $0.id == radio.stationID }?.title ?? "All music",
347 systemImage: "antenna.radiowaves.left.and.right").lineLimit(1)
348 }.frame(maxWidth: 260).disabled(radio.loading)
349 .accessibilityIdentifier("radioStationPicker")
350 Button("Next song", systemImage: "forward.end.fill") { radio.nextSong() }
351 .accessibilityIdentifier("nextRadioSongButton")
352 .disabled(radio.loading || radio.stations.isEmpty && !radio.isPersonalMusic)
353 if !radio.isPersonalMusic {
354 Button("Favorite songs", systemImage: "heart.fill") { showFavorites = true }
355 .accessibilityIdentifier("favoriteSongsLibraryButton")
356 }
357 }
358 Spacer(minLength: 0)
359 if radio.loading { ProgressView("Preparing music…") }
360 if radio.isPersonalMusic, let notice = radio.folderImportNotice { Text(notice).font(.caption).foregroundStyle(.secondary) }
361 if let error = radio.error {
362 Text(error).font(.caption).foregroundStyle(.secondary).lineLimit(1)
363 Button("Retry stations") { Task { await radio.refreshStations() } }
364 }
365 }.sheet(isPresented: $showFavorites) { VisionFavoriteSongsView(radio: radio) }
366 .fileImporter(isPresented: $musicFolder, allowedContentTypes: [.folder]) { result in
367 switch result {
368 case .success(let url): radio.importMusicFolder(url)
369 case .failure(let error): radio.error = error.localizedDescription
370 }
371 }
372 }
373}
374
375private struct VisionFavoriteSongsView: View {
376 @ObservedObject var radio: VisionRadio
377 @Environment(\.dismiss) private var dismiss
378 var body: some View {
379 VStack(alignment: .leading, spacing: 20) {
380 HStack {
381 Label("Favorite songs", systemImage: "heart.fill").font(.title2.bold())
382 Spacer()
383 Button("Done") { dismiss() }
384 }
385 Button("Play favorite songs", systemImage: "shuffle") {
386 radio.selectStation("favorite-songs"); dismiss()
387 }.buttonStyle(.borderedProminent)
388 .disabled(radio.favoriteSongs.isEmpty || radio.loading || radio.stations.isEmpty)
389 .accessibilityIdentifier("playFavoriteSongsButton")
390 if radio.favoriteSongs.isEmpty {
391 ContentUnavailableView("No favorite songs yet", systemImage: "heart",
392 description: Text("Tap the heart beside a song's title in Radio to save it here."))
393 } else {
394 ScrollView {
395 LazyVStack(spacing: 8) {
396 ForEach(radio.favoriteSongs.sorted { $0.track.title.localizedStandardCompare($1.track.title) == .orderedAscending }) { song in
397 HStack {
398 Button {
399 radio.playFavoriteSong(song); dismiss()
400 } label: {
401 HStack(spacing: 12) {
402 Image(systemName: "play.circle.fill").font(.title2)
403 VStack(alignment: .leading, spacing: 4) {
404 Text(song.track.title).font(.headline).lineLimit(1)
405 Text(song.track.genre).font(.caption).foregroundStyle(.secondary)
406 }
407 Spacer()
408 }.frame(maxWidth: .infinity, minHeight: 44).contentShape(Rectangle())
409 }.buttonStyle(.plain).disabled(radio.loading)
410 .accessibilityLabel("Play \(song.track.title)")
411 Button { radio.toggleFavoriteSong(song.track) } label: {
412 Image(systemName: "heart.fill").frame(width: 44, height: 44)
413 }.accessibilityLabel("Unfavorite song \(song.track.title)")
414 }.padding(12).background(.white.opacity(0.05), in: RoundedRectangle(cornerRadius: 16))
415 }
416 }
417 }
418 }
419 }.padding(28).frame(width: 620, height: 540)
420 .task { await radio.refreshFavoriteSongs() }
421 }
422}
423
424/// Observe song favorites directly so the heart updates in both the window and immersive controls.
425struct VisionRadioSongTitle: View {
426 @ObservedObject var radio: VisionRadio
427 var body: some View {
428 HStack(spacing: 8) {
429 if let track = radio.playingTrack, !radio.isPersonalMusic {
430 Button { radio.toggleFavoriteSong(track) } label: {
431 Image(systemName: radio.isFavoriteSong(track) ? "heart.fill" : "heart")
432 .frame(width: 24, height: 24)
433 }.buttonStyle(.bordered).buttonBorderShape(.circle).disabled(radio.loading)
434 .accessibilityLabel(radio.isFavoriteSong(track) ? "Unfavorite song" : "Favorite song")
435 .accessibilityIdentifier("favoriteRadioSongButton")
436 }
437 Text(radio.playingTrack?.title ?? "Radio").font(.headline).lineLimit(1)
438 .accessibilityIdentifier("radioSongName")
439 }.frame(maxWidth: .infinity, alignment: .leading)
440 }
441}
442
443private struct VisionLibrary: View {
444 @ObservedObject var studio: VisionStudio
445 let close: () -> Void
446 @ObservedObject private var library = ProjectMPresets.shared
447 @State private var query = ""
448 @FocusState private var searchFocused: Bool
449 private var scenes: [Int] { library.filteredScenes(query: query) }
450 var body: some View {
451 VStack(alignment: .leading, spacing: 12) {
452 HStack {
453 Text("Visualizers").font(.title2.bold())
454 Spacer()
455 Button("Done") { searchFocused = false; close() }.accessibilityIdentifier("closeVisionLibraryButton")
456 }
457 VisualizerRandomizerPicker(compact: true, fillsWidth: true)
458 TextField("Search visualizers", text: $query).textFieldStyle(.roundedBorder)
459 .focused($searchFocused).submitLabel(.search).onSubmit { searchFocused = false }
460 .accessibilityIdentifier("visualizerSearchField")
461 ScrollView {
462 LazyVStack(spacing: 6) {
463 ForEach(scenes, id: \.self) { scene in
464 HStack(spacing: 0) {
465 Button { searchFocused = false; studio.assign(scene); close() } label: {
466 HStack(spacing: 10) {
467 Image(systemName: library.icon(for: scene))
468 .frame(width: 24).foregroundStyle(.tint)
469 Text(NativeEffects.names[scene])
470 .font(.body.weight(.medium))
471 .multilineTextAlignment(.leading)
472 .fixedSize(horizontal: false, vertical: true)
473 Spacer(minLength: 0)
474 }.padding(.leading, 8).padding(.vertical, 10)
475 .frame(maxWidth: .infinity, minHeight: 52, alignment: .leading)
476 .contentShape(Rectangle())
477 }.buttonStyle(.plain).hoverEffect(.highlight)
478 .accessibilityIdentifier("libraryVisualizer-\(scene)")
479 Button { library.toggleFavorite(scene, appearance: studio.project.looks[scene]?.preset ?? VisualPreset.defaults(for: scene)) } label: {
480 Image(systemName: library.isFavorite(scene) ? "heart.fill" : "heart")
481 .frame(width: 44, height: 52).contentShape(Rectangle())
482 }.buttonStyle(.plain).hoverEffect(.highlight)
483 .accessibilityLabel(library.isFavorite(scene) ? "Unfavorite \(NativeEffects.names[scene])" : "Favorite \(NativeEffects.names[scene])")
484 }.background(scene == studio.selectedScene ? Color.orange.opacity(0.18) : Color.white.opacity(0.04),
485 in: RoundedRectangle(cornerRadius: 12))
486 }
487 if scenes.isEmpty {
488 VStack(spacing: 8) {
489 Image(systemName: "line.3.horizontal.decrease.circle").font(.title)
490 Text("No matching visualizers").font(.headline)
491 }.multilineTextAlignment(.center).padding(.vertical, 28).padding(.horizontal, 8)
492 }
493 }.padding(.trailing, 6)
494 }.scrollIndicators(.visible)
495 .accessibilityIdentifier("visionVisualizerList")
496 Text("\(scenes.count) of \(NativeEffects.activeCount) effects")
497 .font(.caption).foregroundStyle(.secondary).padding(.leading, 8)
498 }
499 }
500}
501
502private struct VisionTransportView: View {
503 @ObservedObject var studio: VisionStudio
504 @ObservedObject var transport: VisionTransport
505 var radio: VisionRadio?
506 var body: some View {
507 VStack(spacing: 8) {
508 if radio == nil { Text(studio.project.audioTitle).font(.headline).lineLimit(1)
509 .frame(maxWidth: .infinity, alignment: .leading)
510 }
511 HStack(spacing: 16) {
512 if let radio {
513 VisionRadioPlaybackButton(radio: radio, transport: transport)
514 .buttonStyle(.borderedProminent)
515 .accessibilityIdentifier("playPauseButton")
516 .accessibilityLabel(radio.loading ? "Preparing Radio" : transport.playing ? "Pause Radio" : "Play Radio")
517 } else {
518 Button { studio.togglePlayback() } label: {
519 Image(systemName: transport.playing ? "pause.fill" : "play.fill").frame(width: 44, height: 32)
520 }.buttonStyle(.borderedProminent).disabled(studio.loading || transport.duration <= 0)
521 .accessibilityLabel(transport.playing ? "Pause" : "Play")
522 .accessibilityIdentifier("playPauseButton")
523 }
524 Text(Duration.seconds(transport.seconds).formatted(.time(pattern: .minuteSecond)))
525 .monospacedDigit().frame(width: 60)
526 .accessibilityIdentifier("elapsedTime")
527 Slider(value: Binding(get: { transport.seconds }, set: { studio.seek($0) }),
528 in: 0...max(1, transport.duration)).accessibilityLabel("Soundtrack position")
529 .disabled(studio.loading || studio.needsSoundtrack || transport.duration <= 0)
530 Text(Duration.seconds(transport.duration).formatted(.time(pattern: .minuteSecond)))
531 .monospacedDigit().frame(width: 60)
532 Image(systemName: studio.volume == 0 ? "speaker.slash.fill" : "speaker.wave.2.fill")
533 Slider(value: $studio.volume, in: 0...1).frame(width: 110).accessibilityLabel("Volume")
534 }
535 if radio == nil { Toggle(isOn: Binding(get: { studio.loopPlayback }, set: { studio.loopPlayback = $0 })) {
536 Label("Loop soundtrack", systemImage: "repeat")
537 }.toggleStyle(.button)
538 .accessibilityIdentifier("loopSoundtrackToggle")
539 .help("Repeat the soundtrack and Studio timeline from the beginning")
540 .frame(maxWidth: .infinity, alignment: .leading)
541 }
542 }
543 }
544}
545
546/// Radio can start before audio exists; only an in-progress song request blocks another tap.
547struct VisionRadioPlaybackButton: View {
548 @ObservedObject var radio: VisionRadio
549 @ObservedObject var transport: VisionTransport
550 var body: some View {
551 Button { radio.togglePlayback() } label: {
552 ZStack {
553 if radio.loading { ProgressView().controlSize(.small) }
554 else { Image(systemName: transport.playing ? "pause.fill" : "play.fill") }
555 }.frame(width: 44, height: 32)
556 }.disabled(radio.loading)
557 .accessibilityLabel(radio.loading ? "Preparing Radio" : transport.playing ? "Pause Radio" : "Play Radio")
558 }
559}
560
561private struct VisionStyleControls: View {
562 @ObservedObject var studio: VisionStudio
563 var clipID: UUID? = nil
564 private var look: VisionLook {
565 clipID.flatMap { studio.look(for: $0) } ?? studio.look
566 }
567 private var scene: Int {
568 clipID.flatMap { id in studio.project.clips.first { $0.id == id }?.scene } ?? studio.selectedScene
569 }
570 private let columns = Array(repeating: GridItem(.flexible(), spacing: 24, alignment: .top), count: 3)
571 private func value(_ key: WritableKeyPath<VisionLook, Float>) -> Binding<Float> {
572 Binding(get: { look[keyPath: key] }, set: { value in studio.updateLook(for: clipID) { $0[keyPath: key] = value } })
573 }
574 var body: some View {
575 VStack(spacing: 14) {
576 HStack {
577 Picker("Palette", selection: Binding(get: { look.palette }, set: { value in studio.updateLook(for: clipID) { $0.palette = value } })) {
578 ForEach(VisualPalette.allCases, id: \.rawValue) { Text($0.title).tag($0.rawValue) }
579 }
580 Button("Reset") { studio.resetLook(for: clipID) }
581 }
582 ScrollView {
583 VStack(alignment: .leading, spacing: 16) {
584 LazyVGrid(columns: columns, alignment: .leading, spacing: 16) {
585 control("Chaos", binding: value(\.chaos), range: 0...1)
586 control("Zoom speed", binding: value(\.zoomSpeed), range: 0...3)
587 control("Motion speed", binding: value(\.speed), range: 0...3)
588 control("Brightness", binding: value(\.brightness), range: 0.1...3)
589 control(LocalizedStringKey(NativeEffects.effect(scene)?.sizeLabel ?? "Particle size"), binding: value(\.size), range: 0.3...6)
590 control("Depth / fog", binding: value(\.fog), range: 0...1)
591 control("Camera zoom", binding: value(\.zoom), range: 0.3...2)
592 control("Camera rotation", binding: value(\.rotation), range: -3.14...3.14)
593 control("Blur", binding: value(\.motionBlur), range: 0...0.9)
594 if let detail = NativeEffects.effect(scene)?.detailLabel {
595 control(LocalizedStringKey(detail), binding: value(\.detail), range: 0...1)
596 }
597 if scene == 28 {
598 control("Halo count", binding: Binding(get: { Float(look.haloCount) }, set: { count in
599 studio.updateLook(for: clipID) { $0.haloCount = Int(count.rounded()) }
600 }), range: 1...12, step: 1, digits: 0)
601 }
602 }
603 VStack(alignment: .leading, spacing: 12) {
604 HStack(spacing: 12) {
605 Label("Hi-hat strobe", systemImage: "bolt.fill")
606 Toggle("Hi-hat strobe", isOn: Binding(get: { look.strobeEnabled }, set: { enabled in
607 studio.updateLook(for: clipID) { $0.strobeEnabled = enabled }
608 })).labelsHidden().toggleStyle(.switch).fixedSize()
609 .accessibilityLabel("Hi-hat strobe")
610 .accessibilityIdentifier("visionStrobeToggle")
611 }.frame(maxWidth: .infinity, alignment: .leading)
612 if look.strobeEnabled {
613 LazyVGrid(columns: columns, alignment: .leading, spacing: 16) {
614 control("Sensitivity", binding: value(\.strobeSensitivity), range: 0.25...4)
615 control("Strength", binding: value(\.strobeStrength), range: 0.1...1)
616 }
617 }
618 }
619 if studio.immersiveActive && clipID == nil {
620 LazyVGrid(columns: columns, alignment: .leading, spacing: 16) {
621 control("Screen distance", binding: $studio.screenDistance, range: 2...5)
622 control("Screen height", binding: $studio.screenHeight, range: 0.8...2)
623 }
624 }
625 }.padding(.trailing, 10).padding(.bottom, 12)
626 }.scrollIndicators(.visible).frame(maxHeight: .infinity)
627 }
628 }
629 private func control(_ title: LocalizedStringKey, binding: Binding<Float>, range: ClosedRange<Float>, step: Float? = nil, digits: Int = 2) -> some View {
630 VStack(alignment: .leading, spacing: 8) {
631 HStack { Text(title); Spacer(); Text(binding.wrappedValue, format: .number.precision(.fractionLength(digits))).monospacedDigit() }
632 .font(.caption)
633 Group {
634 if let step { Slider(value: binding, in: range, step: step) }
635 else { Slider(value: binding, in: range) }
636 }.accessibilityLabel(title)
637 }
638 }
639}
640
641private struct VisionTimelineView: View {
642 @ObservedObject var studio: VisionStudio
643 @State private var applying = false
644 @State private var randomizing = false
645 var body: some View {
646 VStack(alignment: .leading, spacing: 12) {
647 HStack {
648
649 Text("\(studio.project.clips.count) sections · \(Int(studio.project.bpm)) BPM").foregroundStyle(.secondary)
650 Spacer()
651 Button("Randomize timeline", systemImage: "shuffle") { randomizing = true }
652 .buttonStyle(.borderedProminent)
653 .accessibilityIdentifier("randomizeTimelineButton")
654 .disabled(studio.loading || studio.needsSoundtrack || studio.transport.duration <= 0)
655 Button("Apply to all", systemImage: "slider.horizontal.3") { applying = true }
656 .disabled(studio.loading || studio.needsSoundtrack || studio.transport.duration <= 0)
657 }
658 ScrollViewReader { proxy in
659 ScrollView(.horizontal) {
660 LazyHStack(spacing: 12) {
661 ForEach(studio.project.clips) { clip in
662 VisionTimelineCard(studio: studio, clip: clip).id(clip.id)
663 }
664 }
665 }.frame(height: 160)
666 .onChange(of: studio.selected) { _, selected in
667 guard studio.transport.playing, let selected else { return }
668 withAnimation(.easeInOut(duration: 0.25)) { proxy.scrollTo(selected, anchor: .center) }
669 }
670 }
671 }.sheet(isPresented: $applying) { VisionApplySettings(studio: studio) { applying = false } }
672 .sheet(isPresented: $randomizing) { VisionRandomizeTimeline(studio: studio) { randomizing = false } }
673 }
674}
675
676private struct VisionRandomizeTimeline: View {
677 @ObservedObject var studio: VisionStudio
678 @ObservedObject private var library = ProjectMPresets.shared
679 let close: () -> Void
680 @State private var visualizers = true
681 @State private var barLengths = false
682 @State private var error: String?
683 var body: some View {
684 VStack(alignment: .leading, spacing: 22) {
685 Label("Randomize timeline", systemImage: "shuffle").font(.title2.bold())
686 Text("Choose what to replace across all \(studio.project.clips.count) Studio sections.")
687 .foregroundStyle(.secondary)
688 VStack(alignment: .leading, spacing: 16) {
689 Toggle("Visualizers", isOn: $visualizers).toggleStyle(.switch)
690 .accessibilityIdentifier("randomizeTimelineVisualizers")
691 Text("Current group: \(library.poolSummary)").font(.callout).foregroundStyle(.secondary)
692 Toggle("Bar lengths", isOn: $barLengths).toggleStyle(.switch)
693 .accessibilityIdentifier("randomizeTimelineBars")
694 Text("Choose 1–8 bars per section on the song’s beat grid. Tail sections may be trimmed or repeated to fit the song.")
695 .font(.callout).foregroundStyle(.secondary)
696 }.padding(20).background(.white.opacity(0.05), in: RoundedRectangle(cornerRadius: 18))
697 Text(visualizers ? "Fresh looks replace visual settings; saved favorites keep their look. Your soundtrack stays." : "Visualizer order, soundtrack and saved styles stay unchanged.")
698 .font(.callout).foregroundStyle(.secondary)
699 if let error { Text(error).font(.callout).foregroundStyle(.orange) }
700 HStack {
701 Button("Cancel", role: .cancel, action: close)
702 Spacer()
703 Button("Randomize timeline", systemImage: "shuffle") {
704 if studio.randomizeTimeline(visualizers: visualizers, barLengths: barLengths) { close() }
705 else { error = String(localized: "No changes were made. Choose a larger visualizer group or fewer sections, then try again.") }
706 }.buttonStyle(.borderedProminent)
707 .accessibilityIdentifier("confirmRandomizeTimelineButton")
708 .disabled(studio.loading || (!visualizers && !barLengths) || (visualizers && library.eligibleScenes.isEmpty))
709 }
710 }.padding(28).frame(width: 640)
711 .accessibilityElement(children: .contain)
712 .accessibilityIdentifier("randomizeTimelineSheet")
713 }
714}
715
716private struct VisionApplySettings: View {
717 @ObservedObject var studio: VisionStudio
718 let close: () -> Void
719 @State private var includeBars = false
720 @State private var bars = 4
721 @State private var includeChaos = false
722 @State private var chaos: Float = 0.5
723 @State private var includeZoom = false
724 @State private var zoom: Float = 1.5
725 @State private var includeSpeed = false
726 @State private var speed: Float = 1
727 @State private var strobe = 0
728 @State private var sensitivity: Float = 1
729 @State private var strength: Float = 1
730 var body: some View {
731 VStack(alignment: .leading, spacing: 20) {
732 Label("Apply settings to all", systemImage: "slider.horizontal.3").font(.title2.bold())
733 Text("Apply selected settings to every visualizer and Studio section. Other settings stay unchanged.")
734 .foregroundStyle(.secondary)
735 ScrollView {
736 VStack(alignment: .leading, spacing: 22) {
737 Toggle("Bars per section", isOn: $includeBars)
738 Stepper("\(bars) bars", value: $bars, in: 1...64).disabled(!includeBars)
739 Divider()
740 setting("Chaos", included: $includeChaos, value: $chaos, range: 0...1)
741 setting("Zoom speed", included: $includeZoom, value: $zoom, range: 0...3)
742 setting("Motion speed", included: $includeSpeed, value: $speed, range: 0.05...3)
743 Divider()
744 Text("Hi-hat strobe").font(.headline)
745 Picker("Hi-hat strobe", selection: $strobe) {
746 Text("Keep unchanged").tag(0); Text("Add to all").tag(1); Text("Remove from all").tag(2)
747 }.pickerStyle(.segmented)
748 VStack(alignment: .leading) {
749 Text("Sensitivity · \(sensitivity, specifier: "%.2f")")
750 Slider(value: $sensitivity, in: 0.25...4).accessibilityLabel("Strobe sensitivity")
751 Text("Strength · \(strength, specifier: "%.2f")")
752 Slider(value: $strength, in: 0.1...1).accessibilityLabel("Strobe strength")
753 }.disabled(strobe != 1)
754 }.padding(.trailing, 12)
755 }.scrollIndicators(.visible)
756 HStack {
757 Button("Cancel", action: close)
758 Spacer()
759 Button("Apply selected settings") {
760 studio.applyCommonSettings(VisionCommonSettings(bars: includeBars ? bars : nil,
761 chaos: includeChaos ? chaos : nil, zoomSpeed: includeZoom ? zoom : nil,
762 motionSpeed: includeSpeed ? speed : nil,
763 strobeEnabled: strobe == 0 ? nil : strobe == 1,
764 strobeSensitivity: strobe == 1 ? sensitivity : nil,
765 strobeStrength: strobe == 1 ? strength : nil))
766 close()
767 }.buttonStyle(.borderedProminent)
768 .disabled(!includeBars && !includeChaos && !includeZoom && !includeSpeed && strobe == 0)
769 }
770 }.padding(28).frame(width: 660, height: 720)
771 .onAppear {
772 bars = studio.project.clips[studio.selectedIndex].bars
773 chaos = studio.look.chaos; zoom = studio.look.zoomSpeed; speed = studio.look.speed
774 sensitivity = studio.look.strobeSensitivity; strength = studio.look.strobeStrength
775 }
776 }
777 private func setting(_ title: LocalizedStringKey, included: Binding<Bool>, value: Binding<Float>, range: ClosedRange<Float>) -> some View {
778 VStack(alignment: .leading, spacing: 10) {
779 Toggle(title, isOn: included)
780 HStack {
781 Slider(value: value, in: range).accessibilityLabel(title)
782 Text(value.wrappedValue, format: .number.precision(.fractionLength(2))).monospacedDigit().frame(width: 50)
783 }.disabled(!included.wrappedValue)
784 }
785 }
786}
787
788private struct VisionTimelineCard: View {
789 @ObservedObject var studio: VisionStudio
790 let clip: VisionClip
791 @State private var choosing = false
792 var body: some View {
793 VStack(alignment: .leading, spacing: 12) {
794 Button { studio.select(clip); choosing = true } label: {
795 HStack(spacing: 10) {
796 Image(systemName: NativeEffects.all[clip.scene].icon).foregroundStyle(.tint)
797 Text(NativeEffects.names[clip.scene]).font(.headline).lineLimit(2)
798 .multilineTextAlignment(.leading)
799 Spacer(minLength: 0)
800 Image(systemName: "chevron.down").font(.caption.weight(.semibold))
801 }.frame(maxWidth: .infinity, minHeight: 52, alignment: .leading).contentShape(Rectangle())
802 }.buttonStyle(.plain).hoverEffect(.highlight)
803 .accessibilityLabel("Choose visualizer for \(NativeEffects.names[clip.scene]) section")
804 .accessibilityIdentifier("chooseVisualizer-\(clip.id)")
805 .popover(isPresented: $choosing, arrowEdge: .bottom) {
806 VisionClipPicker(studio: studio, clipID: clip.id) { choosing = false }
807 .presentationCompactAdaptation(.popover)
808 }
809 Stepper("\(clip.bars) bars",
810 value: Binding(get: { clip.bars }, set: { studio.bars($0, clip: clip.id) }), in: 1...64)
811 .accessibilityLabel("Bars for \(NativeEffects.names[clip.scene])")
812 }.padding(16).frame(width: 300)
813 .background(studio.selected == clip.id ? Color.orange.opacity(0.2) : Color.white.opacity(0.06),
814 in: RoundedRectangle(cornerRadius: 20))
815 }
816}
817
818private struct VisionClipPicker: View {
819 @ObservedObject var studio: VisionStudio
820 @ObservedObject private var library = ProjectMPresets.shared
821 let clipID: UUID
822 let close: () -> Void
823 @State private var query = ""
824 @State private var favoritesOnly = false
825 private var clip: VisionClip? { studio.project.clips.first { $0.id == clipID } }
826 private var scenes: [Int] { library.filteredScenes(query: query, favoritesOnly: favoritesOnly) }
827
828 var body: some View {
829 VStack(alignment: .leading, spacing: 16) {
830 HStack {
831 Text("Choose visualizer").font(.title2.bold())
832 Spacer()
833 Button("Done", action: close).buttonStyle(.borderedProminent)
834 }
835 if let clip {
836 HStack(spacing: 12) {
837 TextField("Search visualizers", text: $query).textFieldStyle(.roundedBorder)
838 Toggle(isOn: $favoritesOnly) { Label("Favorites", systemImage: "heart.fill") }
839 .toggleStyle(.button)
840 }
841 VisualizerRandomizerPicker(compact: true, fillsWidth: true)
842 ScrollView {
843 LazyVStack(spacing: 6) {
844 ForEach(scenes, id: \.self) { scene in
845 HStack(spacing: 8) {
846 Button {
847 studio.assign(scene, to: clipID)
848 close()
849 } label: {
850 HStack(spacing: 12) {
851 Image(systemName: library.icon(for: scene)).frame(width: 28).foregroundStyle(.tint)
852 Text(NativeEffects.names[scene]).multilineTextAlignment(.leading)
853 Spacer(minLength: 0)
854 if scene == clip.scene { Image(systemName: "checkmark").foregroundStyle(.tint) }
855 }.frame(maxWidth: .infinity, minHeight: 48, alignment: .leading)
856 .contentShape(Rectangle())
857 }.buttonStyle(.plain).hoverEffect(.highlight)
858 Button { library.toggleFavorite(scene, appearance: studio.project.looks[scene]?.preset ?? VisualPreset.defaults(for: scene)) } label: {
859 Image(systemName: library.isFavorite(scene) ? "heart.fill" : "heart")
860 .frame(width: 44, height: 48)
861 }.buttonStyle(.plain).hoverEffect(.highlight)
862 .accessibilityLabel(library.isFavorite(scene) ? "Unfavorite \(NativeEffects.names[scene])" : "Favorite \(NativeEffects.names[scene])")
863 }.padding(.horizontal, 10)
864 .background(scene == clip.scene ? Color.orange.opacity(0.15) : Color.white.opacity(0.04),
865 in: RoundedRectangle(cornerRadius: 12))
866 }
867 if scenes.isEmpty { Text("No matching visualizers").foregroundStyle(.secondary).padding(24) }
868 }.padding(.trailing, 6)
869 }.frame(maxHeight: .infinity).scrollIndicators(.visible)
870 Button("Surprise me", systemImage: "shuffle") {
871 let candidates = scenes.filter { $0 != clip.scene }
872 if let next = (candidates.isEmpty ? scenes : candidates).randomElement() {
873 studio.assign(next, to: clipID)
874 close()
875 }
876 }.buttonStyle(.borderedProminent).disabled(scenes.isEmpty)
877 .accessibilityLabel("Surprise me")
878 .accessibilityIdentifier("surpriseClipVisualizerButton")
879 .frame(maxWidth: .infinity, alignment: .trailing)
880 } else { Text("Section unavailable"); Spacer() }
881 }.padding(24).frame(width: 680, height: 680)
882 .accessibilityElement(children: .contain)
883 .accessibilityIdentifier("clipVisualizerPicker")
884 }
885}
886
887private struct VisionStudioMusicPicker: View {
888 @ObservedObject var studio: VisionStudio
889 @ObservedObject var radio: VisionRadio
890 let close: () -> Void
891 var body: some View {
892 StudioMusicPicker(source: radio.studioMusicSource, library: radio.studioMusicLibrary, favoriteIDs: Set(radio.favoriteSongs.map(\.id)), useSong: { url, title in
893 guard await studio.importAudio(url, title: title) else {
894 throw CocoaError(.fileReadCorruptFile, userInfo: [NSLocalizedDescriptionKey: studio.message ?? "This song could not be loaded."])
895 }
896 }, close: close)
897 .task { await radio.refreshFavoriteSongs() }
898 }
899}