PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / PulseCanvasApp.swift
| 1 | import AppKit |
| 2 | import AVFoundation |
| 3 | import Combine |
| 4 | import SwiftUI |
| 5 | import UniformTypeIdentifiers |
| 6 | |
| 7 | struct LegalCreditsView: View { |
| 8 | private var legalDirectory: URL? { |
| 9 | guard let resources = Bundle.main.resourceURL else { return nil } |
| 10 | let legal = resources.appendingPathComponent("Legal") |
| 11 | return FileManager.default.fileExists(atPath: legal.path) ? legal : resources |
| 12 | } |
| 13 | |
| 14 | var body: some View { |
| 15 | ScrollView { |
| 16 | VStack(alignment: .leading, spacing: 16) { |
| 17 | Text("Legal & Credits").font(.title2).accessibilityAddTraits(.isHeader) |
| 18 | Text("Application").font(.headline) |
| 19 | Text("PulseCanvas first-party code is open source and public domain (Unlicense). Third-party components and assets have separate terms.") |
| 20 | #if STORE_BUILD |
| 21 | Text("Metal edition").font(.headline) |
| 22 | Text("This App Store edition includes \(NativeEffects.activeIDs.count) Metal visualizers. The projectM engine, OpenGL presets, and texture pack are not included.") |
| 23 | #else |
| 24 | Text("projectM engine").font(.headline) |
| 25 | Text("projectM 4.2.0 is included under LGPL 2.1 or later. Engine source and rebuild instructions accompany the matching source package.") |
| 26 | Text("Preset provenance").font(.headline) |
| 27 | Text("Cream of the Crop pack curated by ISOSCELES") |
| 28 | Link("https://www.patreon.com/posts/pack-nestdrop-91682111", destination: URL(string: "https://www.patreon.com/posts/pack-nestdrop-91682111")!) |
| 29 | Text("\(ProjectMPresets.shared.entries.count.formatted()) presets are available from the curated library. Bundled originals retain their pinned Cream of the Crop provenance; user imports, if present, have separate origins. Display labels are separate from original filenames and creator metadata. Upstream assumes public domain where author licenses are missing; individual permissions remain unresolved. Attribution does not establish licensing clearance.") |
| 30 | Text("Texture provenance").font(.headline) |
| 31 | Text("67 images come from the Milkdrop texture pack. Its inclusion guidance does not document individual asset grants; those permissions remain unresolved separately from the presets.") |
| 32 | #if DIRECT_BUILD && canImport(Sparkle) && !LOCAL_BUILD |
| 33 | Text("Automatic updates").font(.headline) |
| 34 | Text("Sparkle provides signed updates for the direct-download edition. Update checks send only the information needed to deliver the app; system profiling is disabled.") |
| 35 | #endif |
| 36 | #endif |
| 37 | Button("Open licenses, notices & provenance") { |
| 38 | if let legalDirectory { NSWorkspace.shared.open(legalDirectory) } |
| 39 | } |
| 40 | }.padding(24).textSelection(.enabled) |
| 41 | }.frame(minWidth: 500, minHeight: 440) |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | @main |
| 46 | enum PulseCanvasLauncher { |
| 47 | @MainActor static func main() { |
| 48 | #if DIRECT_BUILD && !STORE_BUILD |
| 49 | if Array(CommandLine.arguments.dropFirst()) == [PulseMCP.argument] { |
| 50 | PulseMCP.run() |
| 51 | return |
| 52 | } |
| 53 | #endif |
| 54 | PulseCanvasApp.main() |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | struct PulseCanvasApp: App { |
| 59 | @NSApplicationDelegateAdaptor(AppLifecycle.self) private var lifecycle |
| 60 | @Environment(\.openWindow) private var openWindow |
| 61 | @StateObject private var render = { _ = UserBackup.startupError; return RenderState() }() |
| 62 | @StateObject private var audio = AudioController() |
| 63 | @StateObject private var radio = RadioController() |
| 64 | @StateObject private var studio = StudioStore() |
| 65 | @StateObject private var exporter = SocialExportController() |
| 66 | @StateObject private var presentation = StudioPresentationController() |
| 67 | #if DIRECT_BUILD && !STORE_BUILD |
| 68 | @StateObject private var agentAccess = PulseMCPAccess() |
| 69 | @StateObject private var agentService = PulseMCPService() |
| 70 | #endif |
| 71 | #if DIRECT_BUILD && canImport(Sparkle) && !LOCAL_BUILD |
| 72 | @StateObject private var updater = AppUpdater() |
| 73 | #endif |
| 74 | var body: some Scene { |
| 75 | WindowGroup("PulseCanvas Studio") { |
| 76 | CreatorView(render: render, audio: audio, radio: radio, studio: studio, exporter: exporter, presentation: presentation, lifecycle: lifecycle) |
| 77 | .preferredColorScheme(.dark) |
| 78 | .modifier(PulseCanvasOnboardingPresentation(onReplay: { audio.pause() })) |
| 79 | #if DIRECT_BUILD && canImport(Sparkle) && !LOCAL_BUILD |
| 80 | .environmentObject(updater) |
| 81 | #endif |
| 82 | .frame(minWidth: 1080, minHeight: 740) |
| 83 | .onReceive(audio.visualizationUpdated) { |
| 84 | let target = radio.isActive ? radio.visualizer : render |
| 85 | target.audioTrebleAttackTime = audio.trebleAttackTime |
| 86 | target.audioTreblePulse = audio.selectedURL == nil ? nil : audio.treblePulse |
| 87 | target.audioBeatMotionTime = audio.beatMotionTime |
| 88 | target.audioMomentum = audio.momentum |
| 89 | target.audioPulse = audio.beatPulse |
| 90 | target.audioBands = audio.spectrum |
| 91 | target.audioEnvelopes = audio.envelopes |
| 92 | target.audioSwell = audio.swell |
| 93 | target.playbackTime = audio.selectedURL == nil ? nil : audio.playbackSeconds |
| 94 | if radio.isActive { radio.follow(time: audio.playbackSeconds) } |
| 95 | else if !exporter.isExporting && presentation.followsStudioTimeline { studio.follow(time: audio.playbackSeconds, render: render) } |
| 96 | if target.scene >= RenderState.nativeSceneNames.count { target.audioPCM = audio.visualizationPCM(at: audio.playbackSeconds) } |
| 97 | } |
| 98 | .onAppear { |
| 99 | NSApplication.shared.setActivationPolicy(.regular) |
| 100 | studio.apply(to: render) |
| 101 | audio.loadDefaultSoundtrackIfNeeded() |
| 102 | radio.attach(audio: audio) |
| 103 | lifecycle.attach(audio: audio, radio: radio) |
| 104 | #if DIRECT_BUILD && !STORE_BUILD |
| 105 | agentAccess.host(agentService) |
| 106 | if agentAccess.hostRunning { |
| 107 | agentService.attach(access: agentAccess, audio: audio, studio: studio, radio: radio, |
| 108 | render: render, exporter: exporter) |
| 109 | } |
| 110 | #endif |
| 111 | CloudSyncService.shared.start() |
| 112 | } |
| 113 | .onReceive(NotificationCenter.default.publisher(for: .pulseCanvasCloudDataApplied)) { _ in |
| 114 | studio.reloadCloudPresets(); radio.reloadCloudFavorites() |
| 115 | if !audio.isPlaying { studio.apply(to: render) } |
| 116 | } |
| 117 | } |
| 118 | #if STORE_BUILD |
| 119 | .defaultSize(width: 1440, height: 900) |
| 120 | #else |
| 121 | .defaultSize(width: 1440, height: 940) |
| 122 | #endif |
| 123 | .commands { |
| 124 | CommandGroup(after: .appInfo) { |
| 125 | Button("Welcome to PulseCanvas Studio") { |
| 126 | audio.pause() |
| 127 | NotificationCenter.default.post(name: .pulseCanvasOnboarding, object: nil) |
| 128 | } |
| 129 | Button("Legal & Credits") { openWindow(id: "legal-credits") } |
| 130 | Button("Backup & Restore…") { openWindow(id: "user-backup") } |
| 131 | #if DIRECT_BUILD && canImport(Sparkle) && !LOCAL_BUILD |
| 132 | Button("Check for Updates…") { updater.checkForUpdates() }.disabled(!updater.canCheck) |
| 133 | #endif |
| 134 | } |
| 135 | CommandMenu("Preview") { |
| 136 | if presentation.isPresented { |
| 137 | Button("Exit presentation") { audio.pause(); presentation.dismiss() } |
| 138 | } else { |
| 139 | Button(audio.isPlaying ? "Pause soundtrack" : "Play soundtrack") { |
| 140 | if radio.isActive { radio.togglePlayback() } else { audio.playPause() } |
| 141 | }.keyboardShortcut(.space, modifiers: []) |
| 142 | if radio.isActive { |
| 143 | Button("Next radio song") { radio.next() }.keyboardShortcut(.rightArrow, modifiers: []) |
| 144 | Button("Randomize radio visualizer") { radio.randomizeCurrentVisualizer() }.keyboardShortcut("r", modifiers: [.command, .shift]) |
| 145 | } else { |
| 146 | Button("Next visualizer") { choose(1) }.keyboardShortcut(.rightArrow, modifiers: []) |
| 147 | Button("Previous visualizer") { choose(-1) }.keyboardShortcut(.leftArrow, modifiers: []) |
| 148 | Button("Random visualizer") { if !exporter.isExporting { studio.randomizeScene(render) } }.keyboardShortcut("r", modifiers: [.command, .shift]) |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | Settings { |
| 154 | Form { |
| 155 | #if DIRECT_BUILD && !STORE_BUILD |
| 156 | PulseMCPSettings(access: agentAccess) |
| 157 | #endif |
| 158 | Section("Onboarding") { |
| 159 | Button("Welcome to PulseCanvas Studio", systemImage: "sparkles") { |
| 160 | NSApp.keyWindow?.close() |
| 161 | audio.pause() |
| 162 | NotificationCenter.default.post(name: .pulseCanvasOnboarding, object: nil) |
| 163 | }.accessibilityIdentifier("settingsWelcomePulseCanvas") |
| 164 | Text("See the onboarding again, from the beginning.").font(.callout).foregroundStyle(.secondary) |
| 165 | } |
| 166 | Section("Your data") { |
| 167 | Button("Backup & Restore…", systemImage: "externaldrive") { openWindow(id: "user-backup") } |
| 168 | } |
| 169 | Section("iCloud") { |
| 170 | CloudSyncView(prepare: { radio.leave(); audio.pause() }, openProject: { data in |
| 171 | NotificationCenter.default.post(name: .pulseCanvasOpenBackupProject, object: data) |
| 172 | }) |
| 173 | } |
| 174 | #if DIRECT_BUILD && canImport(Sparkle) && !LOCAL_BUILD |
| 175 | Section("Updates") { |
| 176 | Toggle("Automatically check for updates", isOn: $updater.automaticChecks) |
| 177 | Text("The direct-download edition checks pulsecanvas.ai for signed updates. System profiling is disabled.").font(.callout).foregroundStyle(.secondary) |
| 178 | Button("Check for Updates…") { updater.checkForUpdates() }.disabled(!updater.canCheck) |
| 179 | } |
| 180 | #endif |
| 181 | }.formStyle(.grouped).padding(16).frame(width: 620, height: 650) |
| 182 | } |
| 183 | Window("Legal & Credits", id: "legal-credits") { |
| 184 | LegalCreditsView() |
| 185 | }.defaultSize(width: 560, height: 540) |
| 186 | Window("Backup & Restore", id: "user-backup") { |
| 187 | ScrollView { |
| 188 | UserBackupView(currentProject: { |
| 189 | studio.save(render) |
| 190 | return try studio.document(audio: audio, render: render, exporter: exporter).encoded() |
| 191 | }, prepare: { radio.leave(); audio.pause() }, openProject: { data in |
| 192 | NotificationCenter.default.post(name: .pulseCanvasOpenBackupProject, object: data) |
| 193 | }) |
| 194 | .padding(24).tint(Color(red: 0.95, green: 0.68, blue: 0.55)).controlSize(.large) |
| 195 | .disabled(exporter.isExporting) |
| 196 | }.frame(minWidth: 540, minHeight: 480).preferredColorScheme(.dark) |
| 197 | }.defaultSize(width: 620, height: 580) |
| 198 | } |
| 199 | private func choose(_ direction: Int) { |
| 200 | guard !exporter.isExporting else { return } |
| 201 | let choices = ProjectMPresets.shared.eligibleScenes |
| 202 | guard !choices.isEmpty else { return } |
| 203 | let position = choices.firstIndex(of: render.scene) ?? (direction > 0 ? -1 : 0) |
| 204 | studio.selectScene(choices[(position + direction + choices.count) % choices.count], render: render) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | @MainActor |
| 209 | struct CreatorView: View { |
| 210 | @Environment(\.openWindow) private var openWindow |
| 211 | #if DIRECT_BUILD && canImport(Sparkle) && !LOCAL_BUILD |
| 212 | @EnvironmentObject private var updater: AppUpdater |
| 213 | #endif |
| 214 | @ObservedObject var render: RenderState |
| 215 | @ObservedObject var audio: AudioController |
| 216 | @ObservedObject var radio: RadioController |
| 217 | @ObservedObject var studio: StudioStore |
| 218 | @ObservedObject var exporter: SocialExportController |
| 219 | @ObservedObject var presentation: StudioPresentationController |
| 220 | let lifecycle: AppLifecycle |
| 221 | @State private var message = "" |
| 222 | @ObservedObject private var presetLibrary = ProjectMPresets.shared |
| 223 | @State private var showVisualizerBrowser = false |
| 224 | @State private var showHelp = false |
| 225 | @State private var showProjectSettings = false |
| 226 | @State private var showRadio = false |
| 227 | @State private var showMusicPicker = false |
| 228 | private let accent = Color(red: 0.95, green: 0.68, blue: 0.55) |
| 229 | private let background = Color(red: 0.145, green: 0.12, blue: 0.16) |
| 230 | private let panel = Color(red: 0.20, green: 0.17, blue: 0.22) |
| 231 | |
| 232 | var body: some View { |
| 233 | ZStack { |
| 234 | if radio.isActive { |
| 235 | RadioPlayerView(radio: radio, audio: audio, render: radio.visualizer) |
| 236 | } else if presentation.isPresented { |
| 237 | StudioPresentationView(render: render, audio: audio, studio: studio, mode: presentation.mode, aspect: exporter.aspect) { |
| 238 | audio.pause(); presentation.dismiss() |
| 239 | } |
| 240 | } else { editor } |
| 241 | } |
| 242 | .background(StudioWindowReader(attach: { window in |
| 243 | presentation.attach(window); lifecycle.track(window) |
| 244 | }).frame(width: 0, height: 0)) |
| 245 | .onChange(of: presentation.isPresented) { _, active in if !active { audio.pause() } } |
| 246 | .onReceive(radio.soundtrackInstalled) { |
| 247 | if !radio.isActive { studio.timelineSoundtrack = audio.selectedURL } |
| 248 | message = "" |
| 249 | } |
| 250 | .onChange(of: audio.selectedURL) { _, url in |
| 251 | guard !radio.isActive else { return } |
| 252 | render.playbackTime = url == nil ? nil : audio.playbackSeconds |
| 253 | render.audioTreblePulse = url == nil ? nil : audio.treblePulse |
| 254 | if url != studio.timelineSoundtrack { |
| 255 | studio.timelineSoundtrack = url |
| 256 | studio.segments = []; studio.detectedBPM = nil; studio.generationSeed = nil |
| 257 | if studio.isStudio && url != nil { detectSegments() } |
| 258 | } |
| 259 | } |
| 260 | .onChange(of: exporter.isExporting) { _, exporting in if exporting { radio.pause() } } |
| 261 | .sheet(isPresented: $showRadio) { |
| 262 | RadioLibraryView(radio: radio) { showRadio = false } |
| 263 | .dismissOnOutsideClick { showRadio = false } |
| 264 | } |
| 265 | .sheet(isPresented: $showMusicPicker) { |
| 266 | StudioMusicPicker(source: radio.studioMusicSource, folderBookmark: radio.studioMusicFolderBookmark, |
| 267 | library: radio.studioMusicLibrary, favoriteIDs: Set(radio.favoriteSongs.map(\.id)), useSong: importLibrarySong, close: { showMusicPicker = false }) |
| 268 | .frame(width: 670, height: 620) |
| 269 | .dismissOnOutsideClick { showMusicPicker = false } |
| 270 | } |
| 271 | // Reconcile saved songs without opening Radio or starting playback. |
| 272 | .task { await radio.refreshFavoriteSongs() } |
| 273 | } |
| 274 | |
| 275 | private var editor: some View { |
| 276 | GeometryReader { space in |
| 277 | let compactness = min(1, max(0, (860 - space.size.height) / 120)) |
| 278 | VStack(spacing: 0) { |
| 279 | toolbar(compactness: compactness, narrow: space.size.width < 1250) |
| 280 | Divider() |
| 281 | visualizers(compactness: compactness) |
| 282 | Divider() |
| 283 | HStack(spacing: 0) { |
| 284 | VStack(spacing: 0) { |
| 285 | canvas |
| 286 | Divider() |
| 287 | if studio.isStudio { |
| 288 | StudioTimelineView(studio: studio, render: render, audio: audio, exporting: exporter.isExporting, present: presentStudio, compactness: compactness) |
| 289 | Divider() |
| 290 | } |
| 291 | SoundtrackControls(audio: audio, exporting: exporter.isExporting, |
| 292 | selectSoundtrack: selectSoundtrack, chooseMusic: { showMusicPicker = true }, compactness: compactness) |
| 293 | .padding(.horizontal, 20).padding(.vertical, 20 - 10 * compactness).background(panel) |
| 294 | } |
| 295 | Divider() |
| 296 | inspector.frame(width: 300) |
| 297 | } |
| 298 | Divider() |
| 299 | HStack { |
| 300 | Text(message.isEmpty ? (radio.isActive ? radio.status : audio.status) : message).lineLimit(1) |
| 301 | Spacer() |
| 302 | if !exporter.status.isEmpty { Text(exporter.status).lineLimit(1).foregroundStyle(exporter.didFail ? .red : .secondary) } |
| 303 | Text(presetLibrary.pool.enabled ? "\(presetLibrary.eligibleScenes.count) of \(presetLibrary.availableScenes.count) visualizers" : "\(presetLibrary.availableScenes.count) visualizers").foregroundStyle(.secondary) |
| 304 | }.font(.system(size: 11)).padding(.horizontal, 20).padding(.vertical, 9) |
| 305 | } |
| 306 | } |
| 307 | .background(background).tint(accent) |
| 308 | .onReceive(NotificationCenter.default.publisher(for: .pulseCanvasOpenBackupProject)) { notification in |
| 309 | if let data = notification.object as? Data { openProject(data) } |
| 310 | } |
| 311 | .onAppear { |
| 312 | if let id = UserDefaults.standard.string(forKey: UserBackup.activeKey), |
| 313 | UserDefaults.standard.string(forKey: "PulseCanvas.backup.openedSession.v1") != id, |
| 314 | let data = try? Data(contentsOf: UserBackup.documents.appendingPathComponent("Backup-current.pulsecanvas")) { |
| 315 | UserDefaults.standard.set(id, forKey: "PulseCanvas.backup.openedSession.v1") |
| 316 | openProject(data) |
| 317 | } |
| 318 | } |
| 319 | .overlay { ExportOverlayView(exporter: exporter) } |
| 320 | .sheet(isPresented: $showVisualizerBrowser) { |
| 321 | PulseCanvasLibraryView(radio: radio, selected: render.scene, |
| 322 | appearance: { $0 == render.scene ? studio.preset(render) : studio.presets[$0] ?? VisualPreset.defaults(for: $0) }, |
| 323 | choose: { scene in choose(scene); showVisualizerBrowser = false }, |
| 324 | dismiss: { showVisualizerBrowser = false }) |
| 325 | .dismissOnOutsideClick { showVisualizerBrowser = false } |
| 326 | } |
| 327 | .sheet(isPresented: $showProjectSettings) { projectSettings.dismissOnOutsideClick { showProjectSettings = false } } |
| 328 | .sheet(isPresented: $showHelp) { |
| 329 | VStack(alignment: .leading, spacing: 18) { |
| 330 | Text("Create a music visual").font(.title2) |
| 331 | Button("Welcome to PulseCanvas Studio") { |
| 332 | showHelp = false; audio.pause() |
| 333 | NotificationCenter.default.post(name: .pulseCanvasOnboarding, object: nil) |
| 334 | }.buttonStyle(StudioButtonStyle()) |
| 335 | Text("1. Choose a visualizer from the top row. Adjust its colors, motion, and camera on the right.") |
| 336 | Text("2. Add a soundtrack. Play or scrub it to preview how the visuals react to the music.") |
| 337 | Text("3. Open Project settings to choose your canvas shape and video quality. Save video lets you choose a folder and saves an MP4 with your full soundtrack and visuals.") |
| 338 | Text("Phone uses 9:16. Portrait uses 3:4.").foregroundStyle(.secondary) |
| 339 | DisclosureGroup("Privacy") { |
| 340 | Text("PulseCanvas processes music and videos locally on your Mac. Radio downloads its catalog and music from the library you choose; the hosting service receives ordinary network requests. Optional iCloud sync uploads your saved projects with their soundtracks, favorites and saved looks to your Apple Account. It is off until you enable it in Settings. Playback, volume, personal Radio albums and access bookmarks stay on this device. The app has no PulseCanvas account, usage analytics or advertising tracking and does not record your microphone. Ordinary project files reference audio; iCloud projects include a separate soundtrack copy.") |
| 341 | .font(.callout).foregroundStyle(.secondary) |
| 342 | } |
| 343 | Button("Legal & Credits") { openWindow(id: "legal-credits") } |
| 344 | .buttonStyle(StudioButtonStyle(compact: true)) |
| 345 | Button("Done") { showHelp = false }.buttonStyle(StudioButtonStyle(treatment: .primary)) |
| 346 | }.padding(30).frame(width: 500) |
| 347 | .dismissOnOutsideClick { showHelp = false } |
| 348 | } |
| 349 | } |
| 350 | |
| 351 | private func toolbar(compactness: CGFloat, narrow: Bool) -> some View { |
| 352 | HStack(spacing: 10) { |
| 353 | Button { studio.randomizeScene(render) } label: { |
| 354 | Label("Random visualizer", systemImage: "shuffle") |
| 355 | }.buttonStyle(StudioButtonStyle(treatment: .accent)) |
| 356 | .help("Pick a fresh visualizer look, or restore a saved favorite") |
| 357 | .disabled(!presetLibrary.eligibleScenes.contains { $0 != render.scene }) |
| 358 | VisualizerRandomizerPicker() |
| 359 | #if DIRECT_BUILD && canImport(Sparkle) && !LOCAL_BUILD |
| 360 | AppUpdateButton(updater: updater) |
| 361 | #endif |
| 362 | Spacer(minLength: 8) |
| 363 | Button { showVisualizerBrowser = true } label: { Label("Library", systemImage: "square.grid.2x2") } |
| 364 | .help("Browse categories and save favorites") |
| 365 | Button { showRadio = true } label: { Label("Radio", systemImage: "dot.radiowaves.left.and.right") } |
| 366 | .help("Listen with beat-aligned visuals from all, favorites, or a category") |
| 367 | Button { openProject() } label: { Label("Open project", systemImage: "folder") } |
| 368 | Button { saveProject() } label: { Label("Save project", systemImage: "square.and.arrow.down") } |
| 369 | Button { showProjectSettings = true } label: { Label("Project settings", systemImage: "gearshape") } |
| 370 | Button { startExport() } label: { Label("Save video", systemImage: "square.and.arrow.down") } |
| 371 | .buttonStyle(StudioButtonStyle(treatment: .primary)) |
| 372 | .help("Choose a destination and save your video as an MP4") |
| 373 | Button { showHelp = true } label: { |
| 374 | Image(systemName: "questionmark").font(.system(size: 17, weight: .semibold)) |
| 375 | } |
| 376 | .buttonStyle(StudioButtonStyle(circular: true)) |
| 377 | .help("How to create a video").accessibilityLabel("Help") |
| 378 | }.buttonStyle(StudioButtonStyle(compact: narrow)).lineLimit(1) |
| 379 | .padding(.horizontal, 22).padding(.vertical, 14 - 8 * compactness).disabled(exporter.isExporting) |
| 380 | } |
| 381 | |
| 382 | private func visualizers(compactness: CGFloat) -> some View { |
| 383 | HStack(spacing: 14) { |
| 384 | VStack(spacing: 1) { |
| 385 | Button("Visualizers") { radio.leave(); studio.isStudio = false } |
| 386 | .buttonStyle(StudioTabStyle(selected: !studio.isStudio)) |
| 387 | Button("Studio") { |
| 388 | studio.save(render); studio.isStudio = true |
| 389 | if studio.segments.isEmpty { detectSegments() } |
| 390 | studio.follow(time: audio.playbackSeconds, render: render) |
| 391 | }.buttonStyle(StudioTabStyle(selected: studio.isStudio)) |
| 392 | }.padding(2).frame(width: 100) |
| 393 | .background(.black.opacity(0.18), in: RoundedRectangle(cornerRadius: 8)) |
| 394 | .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(.white.opacity(0.12))) |
| 395 | .disabled(exporter.isExporting) |
| 396 | VisualizerPresetStrip(selected:render.scene, revealRequest: studio.visualizerRevealRequest, poolRevision: presetLibrary.poolRevision, accent:accent, background:background, choose:choose) |
| 397 | .equatable().frame(height: 90) |
| 398 | .overlay { |
| 399 | HStack(spacing: 0) { |
| 400 | Rectangle().frame(width: 1) |
| 401 | Spacer(minLength: 0) |
| 402 | Rectangle().frame(width: 1) |
| 403 | } |
| 404 | .frame(height: 62) |
| 405 | .offset(y: -8) |
| 406 | .foregroundStyle(.white.opacity(0.22)) |
| 407 | .allowsHitTesting(false) |
| 408 | .accessibilityHidden(true) |
| 409 | } |
| 410 | }.padding(.horizontal, 20).padding(.vertical, 8 - 4 * compactness).background(panel).disabled(exporter.isExporting) |
| 411 | } |
| 412 | |
| 413 | private var canvas: some View { |
| 414 | GeometryReader { space in |
| 415 | let layout = CanvasPreviewLayout(size: space.size, aspectRatio: exporter.aspect.aspectRatio) |
| 416 | ZStack { |
| 417 | ZStack { |
| 418 | Rectangle().fill(Color.black) |
| 419 | if !exporter.isExporting { |
| 420 | VisualizerView(state: render) |
| 421 | .modifier(VisualizerFavoriteGesture { |
| 422 | presetLibrary.favorite(render.scene, appearance: studio.preset(render)) |
| 423 | }) |
| 424 | } |
| 425 | }.frame(width: layout.preview.width, height: layout.preview.height) |
| 426 | .clipShape(RoundedRectangle(cornerRadius: 3)) |
| 427 | .overlay(RoundedRectangle(cornerRadius: 3).stroke(.white.opacity(0.12))) |
| 428 | .position(x: layout.preview.midX, y: layout.preview.midY) |
| 429 | VStack(spacing: 0) { |
| 430 | canvasHeader |
| 431 | .shadow(color: layout.overlaysChrome ? .black.opacity(0.8) : .clear, radius: 3, y: 1) |
| 432 | Spacer(minLength: 0) |
| 433 | canvasFooter |
| 434 | .shadow(color: layout.overlaysChrome ? .black.opacity(0.8) : .clear, radius: 3, y: 1) |
| 435 | }.padding(layout.padding) |
| 436 | }.frame(width: space.size.width, height: space.size.height).clipped() |
| 437 | }.frame(maxWidth: .infinity, maxHeight: .infinity) |
| 438 | } |
| 439 | |
| 440 | private var canvasHeader: some View { |
| 441 | HStack { |
| 442 | Button { presetLibrary.toggleFavorite(render.scene, appearance: studio.preset(render)) } label: { |
| 443 | Image(systemName: presetLibrary.isFavorite(render.scene) ? "heart.fill" : "heart") |
| 444 | }.buttonStyle(StudioButtonStyle(treatment: presetLibrary.isFavorite(render.scene) ? .accent : .quiet, compact: true, circular: true)) |
| 445 | .help(presetLibrary.isFavorite(render.scene) ? "Remove this visualizer from Favorites" : "Add this visualizer to Favorites") |
| 446 | .disabled(exporter.isExporting) |
| 447 | .accessibilityLabel(presetLibrary.isFavorite(render.scene) ? "Unfavorite visualizer" : "Favorite visualizer") |
| 448 | Text(RenderState.sceneNames[render.scene]).font(.system(size: 18, weight: .medium)).lineLimit(1) |
| 449 | Spacer() |
| 450 | if !studio.isStudio { |
| 451 | Button { useAtPlayhead() } label: { Label("Use at playhead", systemImage: "timeline.selection") } |
| 452 | .buttonStyle(StudioButtonStyle(compact: true)) |
| 453 | .help("Assign this visualizer to the Studio section at the current song position") |
| 454 | .disabled(audio.selectedURL == nil || exporter.isExporting) |
| 455 | Button { presentVisualizer() } label: { Label("Present", systemImage: "play.rectangle.fill") } |
| 456 | .buttonStyle(StudioButtonStyle(treatment: .primary, compact: true)) |
| 457 | .accessibilityLabel("Present visualizer full screen") |
| 458 | .help("Watch this visualizer full screen with the soundtrack. Escape returns to the editor.") |
| 459 | .disabled(exporter.isExporting) |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | private var canvasFooter: some View { |
| 465 | VStack(spacing: 4) { |
| 466 | HStack { |
| 467 | Text(exporter.aspect.title).foregroundStyle(.secondary) |
| 468 | Spacer() |
| 469 | let dimensions = exporter.aspect.dimensions(resolution: exporter.resolution) |
| 470 | Text("\(dimensions.width) × \(dimensions.height) / \(exporter.fps) fps").monospacedDigit().foregroundStyle(.secondary) |
| 471 | }.font(.system(size: 11)) |
| 472 | if let error = render.errorMessage { Text(error).font(.caption).foregroundStyle(.red) } |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | private var inspector: some View { |
| 477 | ScrollView { |
| 478 | VStack(alignment: .leading, spacing: 18) { |
| 479 | Group { |
| 480 | HStack { |
| 481 | Text("Visual style").font(.title3.weight(.semibold)) |
| 482 | Spacer() |
| 483 | Button("Reset") { studio.reset(render) } |
| 484 | .buttonStyle(StudioButtonStyle(compact: true)) |
| 485 | .help("Reset this visualizer to its default visual settings; all sections using it update") |
| 486 | .accessibilityLabel("Reset visualizer to defaults") |
| 487 | Button { studio.randomize(render) } label: { Image(systemName: "dice.fill").font(.system(size: 20, weight: .medium)).frame(width: 32, height: 32).contentShape(Rectangle()) } |
| 488 | .buttonStyle(StudioButtonStyle(compact: true)).help("Randomize visuals").accessibilityLabel("Randomize visuals") |
| 489 | } |
| 490 | if render.scene < RenderState.nativeSceneNames.count { |
| 491 | Text("Color palette").font(.system(size: 12, weight: .medium)) |
| 492 | VStack(spacing: 4) { |
| 493 | ForEach(VisualPalette.allCases, id: \.rawValue) { palette in |
| 494 | Button { render.palette = palette.rawValue; studio.save(render) } label: { |
| 495 | HStack(spacing: 10) { |
| 496 | HStack(spacing: 0) { |
| 497 | ForEach(0..<palette.stops.count, id: \.self) { index in |
| 498 | let rgb = palette.stops[index] |
| 499 | Rectangle().fill(Color(red: Double(rgb.x), green: Double(rgb.y), blue: Double(rgb.z))) |
| 500 | } |
| 501 | }.frame(width: 70, height: 18).clipShape(RoundedRectangle(cornerRadius: 4)) |
| 502 | Text(palette.title).font(.system(size: 12)) |
| 503 | Spacer() |
| 504 | if render.palette == palette.rawValue { Image(systemName: "checkmark").foregroundStyle(accent) } |
| 505 | }.padding(.horizontal, 10).frame(minHeight: 44) |
| 506 | .background(render.palette == palette.rawValue ? accent.opacity(0.12) : background.opacity(0.4), in: RoundedRectangle(cornerRadius: 6)) |
| 507 | .contentShape(Rectangle()) |
| 508 | }.buttonStyle(.plain).accessibilityLabel(palette.title).accessibilityAddTraits(render.palette == palette.rawValue ? .isSelected : []) |
| 509 | } |
| 510 | } |
| 511 | } else { |
| 512 | Text("This preset supplies its own colors, shapes, waves, and feedback. Adjust motion and audio response below.") |
| 513 | .font(.system(size: 12)).foregroundStyle(.secondary) |
| 514 | } |
| 515 | Divider() |
| 516 | Text("Motion & depth").font(.system(size: 12, weight: .medium)) |
| 517 | control("Motion speed", key: \.speed, range: 0.05...3) |
| 518 | control("Zoom speed", key: \.zoomSpeed, range: 0...3) |
| 519 | .help("Add continuous forward zoom. Zero keeps the framing flat while the visualization continues animating.") |
| 520 | control("Chaos", key: \.chaos, range: 0...1) |
| 521 | .help("Zero turns off music response while smooth visualization motion and zoom continue. Increase for beat-driven waves, local swelling, liquid deformation, and motion.") |
| 522 | control("Brightness", key: \.brightness, range: 0.1...3) |
| 523 | if let detail = NativeEffects.effect(render.scene)?.detailLabel { |
| 524 | control(LocalizedStringKey(detail), key: \.liquidDetail, range: 0...1) |
| 525 | .help(render.scene == 23 ? "Add flowing ripples, finer folds, and sharper liquid reflections." : "Add finer structure and surface detail.") |
| 526 | } |
| 527 | if render.scene == 28 { |
| 528 | VStack(alignment: .leading, spacing: 4) { |
| 529 | HStack { Text("Halo count"); Spacer(); Text("\(render.haloCount)").foregroundStyle(.secondary).monospacedDigit() } |
| 530 | Slider(value: Binding(get: { Float(render.haloCount) }, set: { render.haloCount = Int($0.rounded()); studio.save(render) }), in: 1...12, step: 1) |
| 531 | .accessibilityLabel("Halo count") |
| 532 | }.font(.system(size: 11)) |
| 533 | .help("Number of rings in each travelling group. Add more for a denser field of halos.") |
| 534 | } |
| 535 | if render.scene < RenderState.nativeSceneNames.count { |
| 536 | control(LocalizedStringKey(NativeEffects.effect(render.scene)?.sizeLabel ?? "Particle size"), key: \.particleSize, range: 0.3...6) |
| 537 | control("Depth / fog", key: \.fog, range: 0...1) |
| 538 | } |
| 539 | control("Camera zoom", key: \.zoom, range: 0.3...2) |
| 540 | control("Camera rotation", key: \.rotation, range: -3.14...3.14) |
| 541 | control("Blur", key: \.motionBlur, range: 0...0.9) |
| 542 | Toggle("Hi-hat strobe", isOn: Binding(get: { render.strobeEnabled }, set: { render.strobeEnabled = $0; studio.save(render) })).toggleStyle(StudioSwitchStyle()) |
| 543 | if render.strobeEnabled { |
| 544 | control("Strobe sensitivity", key: \.strobeSensitivity, range: 0.25...4) |
| 545 | control("Flash strength", key: \.strobeStrength, range: 0.1...1) |
| 546 | Text("White flashes follow rapid high-frequency attacks in the soundtrack.").font(.system(size: 10)).foregroundStyle(.secondary) |
| 547 | } |
| 548 | }.disabled(exporter.isExporting) |
| 549 | if let url = exporter.exportedURL { |
| 550 | Button { NSWorkspace.shared.activateFileViewerSelecting([url]) } label: { |
| 551 | Label("Show in Finder", systemImage: "folder").frame(maxWidth: .infinity) |
| 552 | }.buttonStyle(StudioButtonStyle(compact: true)) |
| 553 | } |
| 554 | }.padding(19) |
| 555 | }.background(panel) |
| 556 | } |
| 557 | |
| 558 | private var projectSettings: some View { |
| 559 | VStack(alignment: .leading, spacing: 22) { |
| 560 | Text("Project settings").font(.title2.weight(.semibold)) |
| 561 | Text("Canvas shape and export quality for this project.").font(.system(size: 13)).foregroundStyle(.secondary) |
| 562 | VStack(spacing: 18) { |
| 563 | Picker("Canvas", selection: $exporter.aspect) { |
| 564 | ForEach(SocialAspect.allCases) { aspect in Text(aspect.title).tag(aspect) } |
| 565 | } |
| 566 | Picker("Resolution", selection: $exporter.resolution) { Text("720p").tag(720); Text("1080p").tag(1080); Text("4K").tag(2160) } |
| 567 | Picker("Frame rate", selection: $exporter.fps) { |
| 568 | ForEach(SocialExportController.supportedFrameRates, id: \.self) { rate in |
| 569 | Text(rate == 120 ? "120 fps (Experimental)" : "\(rate) fps").tag(rate) |
| 570 | } |
| 571 | } |
| 572 | }.pickerStyle(.menu).controlSize(.large) |
| 573 | if exporter.fps == 120 { |
| 574 | HStack(alignment: .top, spacing: 10) { |
| 575 | Image(systemName: "flask").foregroundStyle(accent) |
| 576 | VStack(alignment: .leading, spacing: 6) { |
| 577 | Text("Experimental frame rate").font(.system(size: 13, weight: .semibold)) |
| 578 | Text("120 fps renders twice as many frames as 60 fps. Export times and playback support vary.") |
| 579 | .font(.system(size: 12)).foregroundStyle(.secondary) |
| 580 | #if !STORE_BUILD |
| 581 | Text("Some OpenGL presets may become darker or look different. Choose 60 fps if this happens.") |
| 582 | .font(.system(size: 12)).foregroundStyle(.secondary) |
| 583 | #endif |
| 584 | }.fixedSize(horizontal: false, vertical: true) |
| 585 | }.padding(14).frame(maxWidth: .infinity, alignment: .leading) |
| 586 | .background(accent.opacity(0.08), in: RoundedRectangle(cornerRadius: 12)) |
| 587 | } |
| 588 | Text("Resolution uses the shorter canvas edge. Export saves an MP4 with the soundtrack included.") |
| 589 | .font(.system(size: 12)).foregroundStyle(.secondary) |
| 590 | HStack { |
| 591 | Spacer() |
| 592 | Button("Done") { showProjectSettings = false }.buttonStyle(StudioButtonStyle(treatment: .primary)) |
| 593 | } |
| 594 | }.padding(30).frame(width: 460).tint(accent) |
| 595 | } |
| 596 | |
| 597 | private func control(_ name: LocalizedStringKey, key: ReferenceWritableKeyPath<RenderState, Float>, range: ClosedRange<Float>) -> some View { |
| 598 | VStack(spacing: 6) { |
| 599 | HStack { Text(name); Spacer(); Text(String(format: "%.2f", render[keyPath: key])).monospacedDigit().foregroundStyle(.secondary) }.font(.system(size: 11)) |
| 600 | Slider(value: Binding(get: { render[keyPath: key] }, set: { render[keyPath: key] = $0; studio.save(render) }), in: range) |
| 601 | .accessibilityLabel(name) |
| 602 | } |
| 603 | } |
| 604 | private func presentStudio() { |
| 605 | guard studio.isStudio, audio.selectedURL != nil, !studio.segments.isEmpty, !exporter.isExporting else { return } |
| 606 | studio.save(render) |
| 607 | if presentation.present(audio: audio) { audio.playFullSoundtrack() } |
| 608 | } |
| 609 | |
| 610 | private func presentVisualizer() { |
| 611 | guard !studio.isStudio, !exporter.isExporting else { return } |
| 612 | studio.save(render) |
| 613 | if presentation.present(audio: audio, mode: .visualizer) { audio.playFullSoundtrack() } |
| 614 | } |
| 615 | |
| 616 | private func choose(_ index: Int) { studio.selectScene(index, render: render); if index >= RenderState.nativeSceneNames.count { render.audioPCM = audio.visualizationPCM(at: audio.playbackSeconds) } } |
| 617 | private func useAtPlayhead() { |
| 618 | if studio.segments.isEmpty { detectSegments() } |
| 619 | if let index = studio.assignAtPlayhead(audio.playbackSeconds, render: render) { |
| 620 | message = String(localized: "\(RenderState.sceneNames[render.scene]) assigned to section \(index + 1) · \(format(studio.segments[index].start))") |
| 621 | } else { message = String(localized: "Add a soundtrack to create Studio sections") } |
| 622 | } |
| 623 | private func detectSegments() { |
| 624 | guard let plan = audio.segmentPlan(beatsPerSection: studio.beatsPerSection) else { return } |
| 625 | studio.makeTimeline(plan, render: render) |
| 626 | studio.follow(time: audio.playbackSeconds, render: render) |
| 627 | } |
| 628 | private func format(_ seconds: Double) -> String { guard seconds.isFinite else { return "0:00" }; return String(format: "%d:%02d", Int(max(0, seconds)) / 60, Int(max(0, seconds)) % 60) } |
| 629 | private func selectSoundtrack() { |
| 630 | let picker = NSOpenPanel(); picker.allowedContentTypes = [.audio]; picker.allowsMultipleSelection = false; picker.canChooseDirectories = false |
| 631 | picker.message = String(localized: "Choose the soundtrack for this video") |
| 632 | if picker.runModal() == .OK, let url = picker.url { |
| 633 | radio.leave() |
| 634 | if audio.load(url: url) { message = "" } |
| 635 | } |
| 636 | } |
| 637 | private func importLibrarySong(_ url: URL, title: String) async throws { |
| 638 | let directory = UserDataStorage.support.appendingPathComponent("StudioMusic", isDirectory: true) |
| 639 | let prepared = try await Task.detached(priority: .userInitiated) { |
| 640 | let copy = try StudioMusicStorage.copy(url, title: title, into: directory) |
| 641 | do { return try PreparedSoundtrack(url: copy) } |
| 642 | catch { try? FileManager.default.removeItem(at: copy.deletingLastPathComponent()); throw error } |
| 643 | }.value |
| 644 | do { try Task.checkCancellation() } |
| 645 | catch { try? FileManager.default.removeItem(at: prepared.url.deletingLastPathComponent()); throw error } |
| 646 | radio.leave(); studio.isStudio = true |
| 647 | guard audio.install(prepared, title: title) else { throw CocoaError(.fileReadCorruptFile) } |
| 648 | message = "" |
| 649 | } |
| 650 | private func startExport() { |
| 651 | guard !exporter.isExporting else { return } |
| 652 | let picker = NSSavePanel(); picker.allowedContentTypes = [.mpeg4Movie]; picker.nameFieldStringValue = "PulseCanvas-\(RenderState.sceneNames[render.scene].replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: " ", with: "-").prefix(120)).mp4" |
| 653 | picker.title = String(localized: "Save video") |
| 654 | picker.prompt = String(localized: "Save video") |
| 655 | picker.canCreateDirectories = true |
| 656 | picker.message = String(localized: "Choose where to save your finished video") |
| 657 | guard picker.runModal() == .OK, let url = picker.url else { return } |
| 658 | radio.pause(); audio.pause() |
| 659 | studio.save(render) |
| 660 | let segments = studio.isStudio ? studio.segments : [] |
| 661 | let appearances = studio.presets |
| 662 | Task { await exporter.export(audioURL: audio.selectedURL, render: render, to: url, segments: segments, appearances: appearances) } |
| 663 | } |
| 664 | private func saveProject() { |
| 665 | let picker = NSSavePanel(); picker.nameFieldStringValue = "Untitled.pulsecanvas"; picker.allowedContentTypes = [UTType(filenameExtension: "pulsecanvas") ?? .json]; picker.canSelectHiddenExtension = true |
| 666 | guard picker.runModal() == .OK, let url = picker.url else { return } |
| 667 | studio.save(render) |
| 668 | if studio.cloudProjectID == nil { studio.cloudProjectID = UUID().uuidString } |
| 669 | do { |
| 670 | let data = try studio.document(audio: audio, render: render, exporter: exporter).encoded() |
| 671 | try data.write(to: url, options: .atomic) |
| 672 | try UserBackup.rememberProject(data, name: url.path) |
| 673 | message = String(localized: "Project saved") |
| 674 | } |
| 675 | catch { message = String(localized: "Cannot save project: \(error.localizedDescription)") } |
| 676 | } |
| 677 | private func openProject() { |
| 678 | let picker = NSOpenPanel(); picker.allowsMultipleSelection = false; picker.canChooseDirectories = false; picker.message = String(localized: "Choose a PulseCanvas project") |
| 679 | guard picker.runModal() == .OK, let url = picker.url else { return } |
| 680 | do { |
| 681 | let data = try Data(contentsOf: url) |
| 682 | if openProject(data) { try UserBackup.rememberProject(data, name: url.path) } |
| 683 | } catch { message = String(localized: "Cannot open project: \(error.localizedDescription)") } |
| 684 | } |
| 685 | @discardableResult |
| 686 | private func openProject(_ data: Data) -> Bool { |
| 687 | radio.leave() |
| 688 | do { |
| 689 | var project = try JSONDecoder().decode(CreatorProject.self, from: data) |
| 690 | project = try project.remapped(using: presetLibrary) |
| 691 | let aspect = try project.checkedAspect() |
| 692 | let soundtrack = try BundledSoundtrack.resolve(identifier: project.bundledSoundtrack, externalURL: project.soundtrack) |
| 693 | let previousSoundtrack = studio.timelineSoundtrack |
| 694 | studio.timelineSoundtrack = soundtrack |
| 695 | if let soundtrack { |
| 696 | if !audio.load(url: soundtrack, bookmark: project.soundtrackBookmark) { |
| 697 | let locate = NSOpenPanel() |
| 698 | locate.allowedContentTypes = [.audio] |
| 699 | locate.allowsMultipleSelection = false; locate.canChooseDirectories = false |
| 700 | locate.message = String(localized: "Locate this project’s soundtrack: \(soundtrack.lastPathComponent). Saved projects reference audio files; they do not include the audio.") |
| 701 | guard locate.runModal() == .OK, let replacement = locate.url, audio.load(url: replacement) else { |
| 702 | studio.timelineSoundtrack = previousSoundtrack; message = String(localized: "Project was not opened. Its soundtrack is unavailable."); return false |
| 703 | } |
| 704 | } |
| 705 | studio.timelineSoundtrack = audio.selectedURL |
| 706 | } else { audio.clear() } |
| 707 | guard (project.timeline?.last?.end ?? 0) <= audio.duration + 0.05 else { throw CocoaError(.fileReadCorruptFile) } |
| 708 | studio.applyDocument(project, aspect: aspect, audio: audio, render: render, exporter: exporter) |
| 709 | message = String(localized: "Project opened") |
| 710 | return true |
| 711 | } catch { |
| 712 | message = String(localized: "Cannot open project: \(error.localizedDescription)") |
| 713 | return false |
| 714 | } |
| 715 | } |
| 716 | } |
| 717 | |
| 718 | private struct SpectrumMeter: View { |
| 719 | let bands: [Float] |
| 720 | var body: some View { |
| 721 | GeometryReader { size in |
| 722 | let gap: CGFloat = 2 |
| 723 | HStack(alignment: .bottom, spacing: gap) { |
| 724 | ForEach(0..<16, id: \.self) { index in |
| 725 | let band = bands.indices.contains(index) && bands[index].isFinite ? CGFloat(bands[index]) : 0 |
| 726 | let height = max(2, size.size.height * min(1, max(0, band))) |
| 727 | RoundedRectangle(cornerRadius: 0.5) |
| 728 | .fill(Color(red: 0.95, green: 0.68, blue: 0.55).opacity(0.7)) |
| 729 | .frame(width: 3, height: height) |
| 730 | .animation(.linear(duration: 0.065), value: height) |
| 731 | } |
| 732 | }.frame(width: size.size.width, height: size.size.height, alignment: .bottomLeading) |
| 733 | } |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | /// Keep frame-rate playback updates inside the small soundtrack panel. |
| 738 | @MainActor |
| 739 | private struct SoundtrackControls: View { |
| 740 | @ObservedObject var audio: AudioController |
| 741 | let exporting: Bool |
| 742 | let selectSoundtrack: () -> Void |
| 743 | let chooseMusic: () -> Void |
| 744 | var compactness: CGFloat = 0 |
| 745 | @State private var playbackRevision = 0 |
| 746 | private let accent = Color(red: 0.95, green: 0.68, blue: 0.55) |
| 747 | var body: some View { |
| 748 | let _ = playbackRevision |
| 749 | VStack(alignment: .leading, spacing: 14 - 6 * compactness) { |
| 750 | HStack(spacing: 12) { |
| 751 | Image(systemName: "waveform").font(.system(size: 18)).foregroundStyle(accent) |
| 752 | .frame(width: 44, height: 44).background(accent.opacity(0.1), in: RoundedRectangle(cornerRadius: 10)) |
| 753 | VStack(alignment: .leading, spacing: 4) { |
| 754 | Text(audio.title).font(.system(size: 14, weight: .semibold)).lineLimit(1) |
| 755 | Text(audio.selectedURL == nil ? "Add music to sync your visuals." : "\(format(audio.duration)) soundtrack") |
| 756 | .font(.system(size: 12)).foregroundStyle(.secondary) |
| 757 | } |
| 758 | Spacer() |
| 759 | Menu { |
| 760 | Button("Choose music", action: chooseMusic) |
| 761 | Button("Choose audio file…", action: selectSoundtrack) |
| 762 | } label: { |
| 763 | Label(audio.selectedURL == nil ? "Add soundtrack" : "Replace audio", systemImage: "waveform.badge.plus") |
| 764 | }.menuStyle(.borderlessButton).fixedSize() |
| 765 | if audio.selectedURL != nil { |
| 766 | Button { audio.clear() } label: { Image(systemName: "xmark").frame(width: 20) } |
| 767 | .buttonStyle(StudioButtonStyle(treatment: .quiet, compact: true)) |
| 768 | .help("Remove soundtrack").accessibilityLabel("Remove soundtrack") |
| 769 | } |
| 770 | }.buttonStyle(StudioButtonStyle()) |
| 771 | HStack(spacing: 14) { |
| 772 | Button { audio.playPause() } label: { |
| 773 | Image(systemName: audio.isPlaying ? "pause.fill" : "play.fill") |
| 774 | .font(.system(size: 17, weight: .semibold)).frame(width: 32, height: 4) |
| 775 | }.buttonStyle(StudioButtonStyle(treatment: .primary, compact: true)) |
| 776 | .accessibilityLabel(audio.isPlaying ? "Pause soundtrack" : "Play soundtrack") |
| 777 | .help("Play or pause soundtrack (Space)").disabled(audio.selectedURL == nil) |
| 778 | VStack(spacing: 4) { |
| 779 | HStack { |
| 780 | Text(format(audio.playbackSeconds)) |
| 781 | Spacer() |
| 782 | Text(format(audio.duration)).foregroundStyle(.secondary) |
| 783 | }.font(.system(size: 12, weight: .medium)).monospacedDigit() |
| 784 | Slider(value: Binding(get: { audio.progress }, set: { audio.seek(fraction: $0) }), in: 0...1) |
| 785 | .accessibilityLabel("Soundtrack position").disabled(audio.selectedURL == nil) |
| 786 | } |
| 787 | SpectrumMeter(bands: audio.spectrum).frame(width: 78, height: 28).accessibilityHidden(true) |
| 788 | Toggle("Loop", isOn: $audio.loopEnabled).toggleStyle(StudioSwitchStyle(icon: "repeat")) |
| 789 | .fixedSize(horizontal: true, vertical: false) |
| 790 | .help("Repeat the soundtrack when it ends").disabled(audio.selectedURL == nil) |
| 791 | HStack(spacing: 8) { |
| 792 | Image(systemName: "speaker.wave.2").font(.system(size: 13)).foregroundStyle(.secondary) |
| 793 | Slider(value: $audio.volume, in: 0...1).frame(width: 70).accessibilityLabel("Preview volume") |
| 794 | } |
| 795 | } |
| 796 | }.disabled(exporting) |
| 797 | .onReceive(audio.visualizationUpdated.throttle(for: .milliseconds(33), scheduler: RunLoop.main, latest: true)) { playbackRevision &+= 1 } |
| 798 | } |
| 799 | |
| 800 | private func format(_ seconds: Double) -> String { |
| 801 | let seconds = max(0, Int(seconds)); return "\(seconds / 60):\(String(format: "%02d", seconds % 60))" |
| 802 | } |
| 803 | } |