// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later import SwiftUI import UniformTypeIdentifiers /// The fourth tab, after Android's SettingsScreen: MIDI panic, the project /// browser (save / load / new / delete, project bundles and .sng), audio route, /// recording, interface, colour themes, MIDI sync, control bindings, backup and /// restore, help and about, and the device lab. struct SetupScreen: View { @EnvironmentObject var app: AppModel // SetupContent doesn't observe AppModel, so it isn't redrawn at the transport's rate. var body: some View { SetupContent(app: app) } } private struct SetupContent: View { let app: AppModel @StateObject private var model = SetupModel() @Environment(\.openURL) private var openURL @State private var dialog: SetupDialog? @State private var saveName = "" @FocusState private var saveFocused: Bool @State private var importing = false @State private var importFormat = SetupModel.Format.sng @State private var showDeviceLab = false @State private var showPluginCheck = false @State private var bindingSource: BindingKind? @State private var confirmTheme: String? var body: some View { GeometryReader { geo in let wide = geo.size.width >= 900 ZStack { SnapScroll { VStack(spacing: 14) { panicButton if wide { HStack(alignment: .top, spacing: 14) { VStack(spacing: 14) { projectCard; AudioDevicesCard(); RecordingCard(); backupCard; helpCard } VStack(spacing: 14) { midiCard; BindingsCard { bindingSource = BindingKind($0) }; InterfaceCard(); themeCard; diagnosticsCard } } } else { projectCard AudioDevicesCard() RecordingCard() midiCard BindingsCard { bindingSource = BindingKind($0) } InterfaceCard() themeCard backupCard helpCard diagnosticsCard } } .padding(16) .frame(maxWidth: wide ? .infinity : 760) .frame(maxWidth: .infinity) } if let d = dialog { dialogView(d).transition(.opacity) } } } .fileImporter(isPresented: $importing, allowedContentTypes: [.data]) { result in switch result { case .success(let url): runImport(url) case .failure(let e): show("Import failed", e.localizedDescription) } } .deviceLab(isPresented: $showDeviceLab) .pluginCheck(isPresented: $showPluginCheck) .sheet(item: $bindingSource) { BindingsSheet(source: $0.source) } } /// Identifiable wrapper for the bindings sheet. struct BindingKind: Identifiable { let source: InputSource init(_ s: InputSource) { source = s } var id: String { "\(source)" } } // MARK: Cards with dialogs /// The MIDI card isn't built in the Mac snapshots before MIDI starts; it lists nothing then. private var midiCard: some View { MidiSyncCard() } private var themeCard: some View { ThemeCard(onImport: { pick(.theme) }, onDelete: { present(.confirmDeleteTheme($0)) }, onError: { show("Export failed", $0) }) } private var backupCard: some View { BackupCard(onBackup: backup, onRestore: { present(.confirmRestore) }) } // MARK: Panic /// Always at the top: silences every sounding or stuck note. private var panicButton: some View { Button { model.panic() } label: { Text("MIDI PANIC — ALL NOTES OFF") .font(.system(size: 15, weight: .bold)).foregroundColor(.white) .frame(maxWidth: .infinity, minHeight: 46) .background(SetupStyle.danger, in: Capsule()) .contentShape(Capsule()) } .buttonStyle(.plain) } // MARK: Project private var projectCard: some View { SetupCard(title: "Project", subtitle: "Full projects saved on this device; share them with other devices") { HStack(spacing: 6) { Text("Open:").foregroundColor(Theme.dim) Text(model.defaultSaveName).foregroundColor(Theme.text).lineLimit(1) } .font(.system(size: 14)) songList HStack(spacing: 8) { SetupButton(title: "Save", icon: "square.and.arrow.down", kind: .filled) { openSave() } SetupButton(title: "New", icon: "doc.badge.plus") { present(.confirmNew) } } SetupNote("Full projects keep mixer, FX, instruments and sample assignments.") SetupDivider() HStack(spacing: 8) { SetupButton(title: "Export project", icon: "square.and.arrow.up") { exportBundle() } SetupButton(title: "Import project", icon: "square.and.arrow.down.on.square") { pick(.project) } } SetupNote("A bundle (.szgz) carries everything — patterns, mixer, FX, instruments and samples — so it opens " + "complete on another device, Android too. Import takes a bundle or a .szg and replaces the current project.") SetupDivider() HStack(spacing: 8) { SetupButton(title: "Export .sng", icon: "square.and.arrow.up") { export(.sng) } SetupButton(title: "Import .sng", icon: "square.and.arrow.down.on.square") { pick(.sng) } } SetupNote(".sng carries notes/blocks/arrangement only (desktop-compatible).") } } /// The saved projects: tap one to load it, the bin deletes it (after asking). private var songList: some View { VStack(spacing: 0) { if model.songs.isEmpty { Text("No saved projects").font(.system(size: 14)).foregroundColor(Theme.dim) .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading).padding(.horizontal, 12) } ForEach(Array(model.songs.enumerated()), id: \.element) { i, name in if i > 0 { SetupDivider().padding(.leading, 12) } songRow(name) } } .background(Theme.background.opacity(0.6), in: RoundedRectangle(cornerRadius: 8)) .overlay(RoundedRectangle(cornerRadius: 8).stroke(Theme.grid, lineWidth: 1)) } private func songRow(_ name: String) -> some View { let open = name == model.songName return HStack(spacing: 10) { Button { load(name) } label: { HStack(spacing: 10) { Image(systemName: open ? "music.note" : "doc") .font(.system(size: 14)).foregroundColor(open ? Theme.accent : Theme.dim).frame(width: 18) Text(name).font(.system(size: 15, weight: open ? .semibold : .regular)) .foregroundColor(open ? Theme.accent : Theme.text).lineLimit(1) Spacer(minLength: 4) } .frame(minHeight: 44).contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityLabel(open ? "\(name), open" : "Load \(name)") Button { present(.confirmDelete(name)) } label: { Image(systemName: "trash").font(.system(size: 15)).foregroundColor(SetupStyle.danger) .frame(width: 44, height: 44).contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityLabel("Delete \(name)") } .padding(.leading, 12) } // MARK: Help private var helpCard: some View { SetupCard(title: "Help", subtitle: "About, source, user guide & support") { Text(Self.versionLine).font(.system(size: 14)).foregroundColor(Theme.text) ForEach(Self.links, id: \.0) { link in SetupRow(title: link.0, detail: link.1) { if let u = URL(string: link.1) { openURL(u) } } } } } private static let links = [ ("Source code", "https://git.rcmd.space/tiredsysadmin/sizzletracker-android"), ("User guide", "https://git.rcmd.space/tiredsysadmin/sizzletracker-android/src/branch/main/docs/USER_GUIDE.md#sizzletracker--user-guide"), ("Support us", "https://rcmd.space/pages/support/"), ] /// "Sizzle v0.4.0 (12)" from the bundle; just "Sizzle" where there is none (the snapshot tool). private static var versionLine: String { let info = Bundle.main.infoDictionary ?? [:] let name = info["CFBundleDisplayName"] as? String ?? "Sizzle" guard let v = info["CFBundleShortVersionString"] as? String else { return name } let build = info["CFBundleVersion"] as? String return "\(name) v\(v)" + (build.map { " (\($0))" } ?? "") } // MARK: Diagnostics private var diagnosticsCard: some View { SetupCard(title: "Diagnostics", subtitle: "The device test screen from earlier builds") { SetupRow(title: "Device lab", detail: "Play, edit and benchmark each instrument and effect on its own", icon: "waveform.path.ecg") { app.session.stop() showDeviceLab = true } SetupDivider() SetupRow(title: "Check plugins", detail: "Load each Sizzle plugin as another app would and render through it", icon: "checkmark.seal") { showPluginCheck = true } } } // MARK: Dialogs @ViewBuilder private func dialogView(_ d: SetupDialog) -> some View { switch d { case .save: let name = saveName.trimmingCharacters(in: .whitespacesAndNewlines) SetupDialogView(title: "Save project", message: model.songs.contains(name) ? "Replaces the saved project \"\(name)\"." : nil, confirm: "Save", confirmEnabled: !name.isEmpty, field: { TextField("Name", text: $saveName) .textFieldStyle(.plain) .font(.system(size: 16)).foregroundColor(Theme.text) .padding(.horizontal, 12).frame(minHeight: 44) .background(Theme.background, in: RoundedRectangle(cornerRadius: 8)) .overlay(RoundedRectangle(cornerRadius: 8).stroke(Theme.accent, lineWidth: 1)) .focused($saveFocused) .disableAutocorrection(true) .submitLabel(.done) .onSubmit { if !name.isEmpty { save(name) } } }, onConfirm: { save(name) }, onCancel: dismiss) .onAppear { saveFocused = true } case .confirmNew: SetupDialogView(title: "New project", message: "Start a clean, empty project? Any unsaved changes to the current song will be lost.", confirm: "New project", field: { EmptyView() }, onConfirm: { dismiss(); model.newSong(); resetCursor() }, onCancel: dismiss) case .confirmDelete(let name): SetupDialogView(title: "Delete project", message: "Delete \"\(name)\"? This cannot be undone.", confirm: "Delete", destructive: true, field: { EmptyView() }, onConfirm: { dismiss(); attempt("Delete failed") { try model.delete(name) } }, onCancel: dismiss) case .confirmDeleteTheme(let name): SetupDialogView(title: "Delete theme", message: "Delete \"\(name)\"? This cannot be undone.", confirm: "Delete", destructive: true, field: { EmptyView() }, onConfirm: { dismiss(); ThemeLibrary.shared.delete(name) }, onCancel: dismiss) case .confirmRestore: SetupDialogView(title: "Restore backup", message: "Replace every saved song, preset, theme, sample, the open song and the settings with a backup's?", confirm: "Choose backup", destructive: true, field: { EmptyView() }, onConfirm: { dismiss(); pick(.backup) }, onCancel: dismiss) case .message(let title, let text): SetupDialogView(title: title, message: text, confirm: "OK", cancel: nil, field: { EmptyView() }, onConfirm: dismiss, onCancel: dismiss) } } private func present(_ d: SetupDialog) { withAnimation(.easeOut(duration: 0.15)) { dialog = d } } private func dismiss() { saveFocused = false; withAnimation(.easeOut(duration: 0.15)) { dialog = nil } } private func show(_ title: String, _ text: String) { present(.message(title: title, text: text)) } private func attempt(_ title: String, _ body: () throws -> Void) { do { try body() } catch { show(title, error.localizedDescription) } } // MARK: Actions private func openSave() { saveName = model.defaultSaveName present(.save) } private func save(_ name: String) { guard !name.isEmpty else { return } dismiss() attempt("Save failed") { try model.save(name) } } private func load(_ name: String) { attempt("Load failed") { try model.load(name) } resetCursor() } private func exportBundle() { attempt("Export failed") { let url = try model.exportBundle() ShareSheet.present(url) { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } } } private func backup() { attempt("Backup failed") { let url = try model.backupFile() ShareSheet.present(url) { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } } } private func export(_ format: SetupModel.Format) { attempt("Export failed") { let url = try model.exportFile(format) ShareSheet.present(url) { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) } } } private func pick(_ format: SetupModel.Format) { importFormat = format importing = true } private func runImport(_ url: URL) { do { switch importFormat { case .theme: guard ThemeLibrary.shared.importText(try SetupFiles.readText(url)) != nil else { show("Import failed", "Couldn't import this file. It doesn't look like a valid .szt theme.") return } return case .backup: try model.restoreBackup(url) show("Backup restored", "Songs, presets, themes, samples and settings are back.") default: try model.importFile(url, as: importFormat) } resetCursor() } catch let e as SetupFileError { show("Import failed", e.localizedDescription) } catch is CocoaError { show("Import failed", "Couldn't read the selected file.") } catch { switch importFormat { case .sng: show("Import failed", "Couldn't import this file. It doesn't look like a valid .sng song.") case .backup: show("Restore failed", error.localizedDescription) default: show("Import failed", (error as NSError).domain == "Sizzle" ? error.localizedDescription : "Couldn't import this file. It doesn't look like a Sizzle project (.szgz or .szg).") } } } /// Like Android after a load or import: the tracker cursor back to the top. private func resetCursor() { app.cursorLine = 0 app.cursorTrack = 0 } }