Branchwell

PulseCanvas / app · pulsecanvas.ai / mobile / MobileExport.swift

Raw 8.6 KB on 23ffa4e102ea595ec83f2b18683b75332fc815c3
1import SwiftUI
2import UIKit
3
4struct MobileExport: View {
5 @ObservedObject var editor: MobileEditor
6 @ObservedObject var exporter: SocialExportController
7 @ObservedObject var audio: AudioController
8 @ObservedObject var radio: RadioController
9 @State private var request: MobileVideoSaveRequest?
10 @State private var saved = false
11 @State private var renderStarted = false
12 @State private var error: String?
13 init(editor: MobileEditor) { self.editor = editor; exporter = editor.exporter; audio = editor.audio; radio = editor.radio }
14 private var hasCurrentResult: Bool { renderStarted && exporter.exportedURL != nil }
15 var body: some View {
16 ScrollView {
17 VStack(alignment: .leading, spacing: 24) {
18 if !exporter.isExporting {
19 Picker("Canvas", selection: $exporter.aspect) { ForEach(SocialAspect.allCases) { Text($0.title).tag($0) } }.accessibilityIdentifier("mobileExportCanvas")
20 Picker("Resolution", selection: $exporter.resolution) { Text("720p").tag(720); Text("1080p").tag(1080); Text("4K").tag(2160) }.pickerStyle(.segmented)
21 Picker("Frame rate", selection: $exporter.fps) { ForEach([24, 30, 60], id: \.self) { Text("\($0) fps").tag($0) } }.pickerStyle(.segmented)
22 Text(radio.isActive ? "Export the current Radio song with the visualizer you’re watching." : "Full soundtrack included. Higher resolutions take longer to render.").foregroundStyle(.secondary)
23 }
24 if exporter.isExporting || hasCurrentResult {
25 if let image = exporter.framePreview { Image(decorative: image, scale: 1).resizable().scaledToFit().frame(maxHeight: 250).clipShape(RoundedRectangle(cornerRadius: 14)) }
26 ProgressView(value: exporter.progress)
27 Text(saved ? String(localized: "Video saved") : hasCurrentResult ? String(localized: "Your video is ready") : exporter.status).font(.headline)
28 if let estimate = exporter.estimatedSecondsRemaining { Text("About \(MobileTransport.time(estimate)) remaining").foregroundStyle(.secondary) }
29 }
30 if let error { Text(error).foregroundStyle(.red) }
31 if exporter.didFail { Text(exporter.status).foregroundStyle(.red) }
32 }.padding(24)
33 }.safeAreaInset(edge: .bottom, spacing: 0) {
34 VStack(spacing: 10) {
35 if exporter.isExporting {
36 Button("Cancel export") { exporter.cancel() }.buttonStyle(MobileButton())
37 } else {
38 if let url = exporter.exportedURL, hasCurrentResult {
39 Button { request = MobileVideoSaveRequest(url: url) } label: {
40 Label(saved ? "Save another copy" : "Save video", systemImage: "tray.and.arrow.down").frame(maxWidth: .infinity, minHeight: 52)
41 }.buttonStyle(MobileButton(prominent: true)).accessibilityIdentifier("saveMobileVideo")
42 }
43 Button { startExport() } label: {
44 Label(hasCurrentResult ? "Render another video" : "Render video", systemImage: "film").frame(maxWidth: .infinity, minHeight: 52)
45 }.buttonStyle(MobileButton(prominent: !hasCurrentResult))
46 .accessibilityIdentifier("renderMobileVideo")
47 .disabled(audio.selectedURL == nil || radio.isActive && !radio.canSeek)
48 }
49 }.padding(20).frame(maxWidth: .infinity).background(MobileTheme.background)
50 }.interactiveDismissDisabled(exporter.isExporting)
51 .fullScreenCover(item: $request) { item in
52 MobileVideoSavePicker(url: item.url) { result in
53 request = nil
54 if let result {
55 switch result {
56 case .success: saved = true
57 case .failure(let failure): error = failure.localizedDescription
58 }
59 }
60 }
61 }
62 }
63 private func startExport() {
64 let radioExport = radio.isActive
65 if radioExport { radio.pause() } else { audio.pause(); editor.studio.save(editor.render) }
66 let audioURL = audio.selectedURL
67 let render = radioExport ? radio.visualizer : editor.render
68 let segments = !radioExport && editor.studio.isStudio ? editor.studio.segments : []
69 saved = false; error = nil
70 #if DEBUG
71 // Repeated UI runs keep earlier Files exports; isolate their names too.
72 let filename = ProcessInfo.processInfo.arguments.contains("-PCMobileQA")
73 ? "PulseCanvas-QA-Video-\(UUID().uuidString).mp4" : "PulseCanvas Video.mp4"
74 #else
75 let filename = "PulseCanvas Video.mp4"
76 #endif
77 let destination = FileManager.default.temporaryDirectory.appendingPathComponent("Mobile-video-\(UUID().uuidString)").appendingPathComponent(filename)
78 do { try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) }
79 catch { self.error = error.localizedDescription; return }
80 Task { renderStarted = true; await exporter.export(audioURL: audioURL, render: render, to: destination,
81 segments: segments, appearances: radioExport ? [:] : editor.studio.presets) }
82 }
83}
84
85private struct MobileVideoSaveRequest: Identifiable { let id = UUID(); let url: URL }
86private struct MobileVideoSavePicker: UIViewControllerRepresentable {
87 let url: URL
88 let completion: (Result<URL, Error>?) -> Void
89 func makeCoordinator() -> Coordinator { Coordinator(completion: completion) }
90 func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
91 let picker = UIDocumentPickerViewController(forExporting: [url], asCopy: true)
92 picker.delegate = context.coordinator; picker.shouldShowFileExtensions = true; return picker
93 }
94 func updateUIViewController(_ controller: UIDocumentPickerViewController, context: Context) {}
95 final class Coordinator: NSObject, UIDocumentPickerDelegate {
96 let completion: (Result<URL, Error>?) -> Void
97 init(completion: @escaping (Result<URL, Error>?) -> Void) { self.completion = completion }
98 func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
99 if let url = urls.first { completion(.success(url)) } else { completion(.failure(CocoaError(.fileWriteUnknown))) }
100 }
101 func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { completion(nil) }
102 }
103}
104
105struct MobileAbout: View {
106 @ObservedObject var editor: MobileEditor
107 var body: some View {
108 List {
109 Section {
110 Text("PulseCanvas Studio").font(.title2.bold())
111 Text("Music into moving visuals. Free to use, with no account or subscription.")
112 }
113 Section("Onboarding") {
114 Button("Welcome to PulseCanvas Studio", systemImage: "sparkles") {
115 NotificationCenter.default.post(name: .pulseCanvasOnboarding, object: nil)
116 }.accessibilityIdentifier("settingsWelcomePulseCanvas")
117 }
118 Section {
119 UserBackupView(currentProject: { try editor.projectData() }, prepare: {
120 editor.radio.leave(); editor.selectedTab = 0; editor.audio.pause(); editor.saveSession()
121 }, openProject: { data in Task { await editor.openProject(data) } })
122 .disabled(editor.loading || editor.exporter.isExporting)
123 }
124 Section("iCloud") {
125 CloudSyncView(prepare: { editor.radio.leave(); editor.audio.pause() }, openProject: { data in
126 Task { await editor.openProject(data) }
127 }).disabled(editor.loading || editor.exporter.isExporting)
128 }
129 Section("Legal & Credits") {
130 Text("First-party source is open source and public domain (Unlicense). Third-party assets keep their separate terms. Native Metal effects only; no projectM engine or external preset pack is included.")
131 Link("Source code on GitHub", destination: URL(string: "https://github.com/projectatomai/pulsecanvas")!)
132 Link("Privacy policy", destination: URL(string: "https://pulsecanvas.ai/privacy/")!)
133 if let url = Bundle.main.url(forResource: "PulseCanvas-LICENSE", withExtension: "txt", subdirectory: "Legal"), let license = try? String(contentsOf: url, encoding: .utf8) {
134 DisclosureGroup("Application license") { Text(license).font(.caption).textSelection(.enabled) }
135 }
136 }
137 }
138 }
139}