iOS 0.4.0: Sizzle's Tracker, Mix, Toolbox and Setup tabs on the C++ engine

Ported from the Android tabs by parallel agents (each screen with its own
SizzleSession category); slot editors use the card editor with a preset
library; songs load/save in the Android project format.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-16 09:32:30 +01:00
co-authored by Claude Opus 5.5
parent 29650b88d7
commit 962cfd1e2b
35 changed files with 4088 additions and 66 deletions
@@ -0,0 +1,194 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// Building blocks of the Setup tab, after Android's SettingsScreen: titled cards,
/// buttons, link rows, rows for sections still to come, and the modal dialog.
/// SwiftUI only (the Mac snapshot tool renders them).
enum SetupStyle {
static let danger = Color(red: 0.86, green: 0.27, blue: 0.27)
static let corner: CGFloat = 10
}
/// A titled card for one settings group (Android's SettingsCard).
struct SetupCard<Content: View>: View {
let title: String
var subtitle: String?
var enabled = true
@ViewBuilder let content: () -> Content
var body: some View {
VStack(alignment: .leading, spacing: 10) {
VStack(alignment: .leading, spacing: 3) {
Text(title).font(.system(size: 17, weight: .semibold)).foregroundColor(enabled ? Theme.accent : Theme.dim)
if let s = subtitle { Text(s).font(.system(size: 13)).foregroundColor(Theme.dim) }
}
content()
}
.padding(16)
.frame(maxWidth: .infinity, alignment: .leading)
.background(Theme.surface, in: RoundedRectangle(cornerRadius: SetupStyle.corner))
}
}
/// Filled (primary), outlined or destructive button.
struct SetupButton: View {
enum Kind { case filled, outlined, danger }
let title: String
var icon: String?
var kind: Kind = .outlined
var enabled = true
let action: () -> Void
var body: some View {
Button(action: action) {
HStack(spacing: 6) {
if let icon = icon { Image(systemName: icon).font(.system(size: 13)) }
Text(title).font(.system(size: 15, weight: .medium)).lineLimit(1)
}
.padding(.horizontal, 14).frame(minHeight: 38)
.foregroundColor(foreground)
.background(background, in: Capsule())
.overlay(Capsule().stroke(kind == .outlined ? Theme.grid : Color.clear, lineWidth: 1))
.contentShape(Capsule())
}
.buttonStyle(.plain)
.disabled(!enabled)
.opacity(enabled ? 1 : 0.4)
}
private var foreground: Color {
switch kind {
case .filled: return Theme.background
case .outlined: return Theme.text
case .danger: return .white
}
}
private var background: Color {
switch kind {
case .filled: return Theme.accent
case .outlined: return .clear
case .danger: return SetupStyle.danger
}
}
}
/// Small grey explanatory text under a group of buttons.
struct SetupNote: View {
let text: String
init(_ text: String) { self.text = text }
var body: some View {
Text(text).font(.system(size: 12)).foregroundColor(Theme.dim).fixedSize(horizontal: false, vertical: true)
}
}
struct SetupDivider: View {
var body: some View { Rectangle().fill(Theme.grid.opacity(0.7)).frame(height: 1) }
}
/// A tappable row with a label, a detail line and a chevron (Android's LinkRow and NavCard).
struct SetupRow: View {
let title: String
let detail: String
var icon: String?
var tint: Color = Theme.accent
let action: () -> Void
var body: some View {
Button(action: action) {
HStack(spacing: 12) {
if let icon = icon { Image(systemName: icon).font(.system(size: 17)).foregroundColor(tint).frame(width: 24) }
VStack(alignment: .leading, spacing: 2) {
Text(title).font(.system(size: 16, weight: .medium)).foregroundColor(tint)
Text(detail).font(.system(size: 12)).foregroundColor(Theme.dim).lineLimit(2)
}
Spacer(minLength: 8)
Image(systemName: "chevron.right").font(.system(size: 13, weight: .semibold)).foregroundColor(tint)
}
.padding(.vertical, 8)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
}
}
/// An Android settings section not ported yet: its place in the layout, greyed
/// out and marked as coming later.
struct ComingLaterRow: View {
let title: String
let subtitle: String
let icon: String
var body: some View {
HStack(spacing: 12) {
Image(systemName: icon).font(.system(size: 16)).foregroundColor(Theme.dim).frame(width: 24)
VStack(alignment: .leading, spacing: 2) {
Text(title).font(.system(size: 15, weight: .medium)).foregroundColor(Theme.dim)
Text(subtitle).font(.system(size: 12)).foregroundColor(Theme.dim.opacity(0.75)).lineLimit(2)
}
Spacer(minLength: 8)
Text("Later").font(.system(size: 11)).foregroundColor(Theme.dim)
.padding(.horizontal, 8).padding(.vertical, 3)
.overlay(Capsule().stroke(Theme.grid, lineWidth: 1))
.fixedSize()
}
.padding(.vertical, 4)
.accessibilityElement(children: .combine)
.accessibilityHint("Coming in a later version")
}
}
/// The Setup tab's modal dialogs. iOS 15 alerts can't hold a text field, so the
/// save prompt (and with it every dialog here, for one look) is drawn in SwiftUI.
enum SetupDialog: Identifiable {
case save
case confirmNew
case confirmDelete(String)
case message(title: String, text: String)
var id: String {
switch self {
case .save: return "save"
case .confirmNew: return "new"
case .confirmDelete(let n): return "delete:" + n
case .message(let t, let m): return "msg:" + t + m
}
}
}
/// A dimmed backdrop with a centred card: title, message, optional text field, buttons.
struct SetupDialogView<Field: View>: View {
let title: String
let message: String?
let confirm: String
var destructive = false
var cancel: String? = "Cancel"
var confirmEnabled = true
@ViewBuilder let field: () -> Field
let onConfirm: () -> Void
let onCancel: () -> Void
var body: some View {
ZStack {
Color.black.opacity(0.55).ignoresSafeArea().onTapGesture(perform: onCancel)
VStack(alignment: .leading, spacing: 14) {
Text(title).font(.system(size: 19, weight: .semibold)).foregroundColor(Theme.text)
if let m = message {
Text(m).font(.system(size: 14)).foregroundColor(Theme.dim).fixedSize(horizontal: false, vertical: true)
}
field()
HStack(spacing: 10) {
Spacer()
if let c = cancel { SetupButton(title: c, kind: .outlined, action: onCancel) }
SetupButton(title: confirm, kind: destructive ? .danger : .filled, enabled: confirmEnabled, action: onConfirm)
}
}
.padding(20)
.frame(maxWidth: 420)
.background(Theme.surface, in: RoundedRectangle(cornerRadius: 14))
.overlay(RoundedRectangle(cornerRadius: 14).stroke(Theme.grid, lineWidth: 1))
.padding(24)
}
}
}
@@ -0,0 +1,49 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
/// Export and import files for the Setup tab (Foundation only).
enum SetupFiles {
/// Writes [text] to a fresh temporary folder as "<song name>.<ext>" (the name
/// the share sheet and Files show), clearing earlier exports first.
static func export(_ text: String, songName: String, ext: String) throws -> URL {
let root = FileManager.default.temporaryDirectory.appendingPathComponent("Exports", isDirectory: true)
try? FileManager.default.removeItem(at: root)
let dir = root.appendingPathComponent(UUID().uuidString, isDirectory: true)
try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let url = dir.appendingPathComponent(fileStem(songName)).appendingPathExtension(ext)
try text.write(to: url, atomically: true, encoding: .utf8)
return url
}
/// The song name as a file name: path separators replaced, blank → "untitled".
static func fileStem(_ name: String) -> String {
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
let safe = trimmed.components(separatedBy: CharacterSet(charactersIn: "/\\:")).joined(separator: "_")
return safe.isEmpty || safe.hasPrefix(".") ? "untitled" + safe : safe
}
/// Reads a picked file as text (security-scoped, as .fileImporter hands it over).
static func readText(_ url: URL) throws -> String {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
let data = try Data(contentsOf: url)
// Song files are small text; refuse anything huge before decoding.
guard data.count <= 32 << 20 else { throw SetupFileError.tooLarge }
guard let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else {
throw SetupFileError.notText
}
return text
}
}
enum SetupFileError: LocalizedError {
case tooLarge, notText
var errorDescription: String? {
switch self {
case .tooLarge: return "The file is too large to be a Sizzle song."
case .notText: return "Couldn't read the selected file."
}
}
}
@@ -0,0 +1,87 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import Combine
import Foundation
/// The Setup tab's state: the saved songs (Documents/songs) and the open song's
/// name, refreshed when the song changes or a file is saved or deleted, plus the
/// project actions (Android's AppViewModel songNames / saveSong / loadSong /
/// newProject / deleteSong / importSng / writeSngExport).
///
/// Kept apart from AppModel so the screen doesn't re-render (and re-list the
/// songs folder) at the transport's 30 Hz while playing.
@MainActor
final class SetupModel: ObservableObject {
let session = SizzleSession.shared
@Published private(set) var songs: [String] = []
@Published private(set) var songName = ""
private var observer: NSObjectProtocol?
init() {
refresh()
observer = NotificationCenter.default.addObserver(forName: .SizzleSessionDidChange, object: nil, queue: .main) { [weak self] _ in
Task { @MainActor in self?.refresh() }
}
}
deinit { if let o = observer { NotificationCenter.default.removeObserver(o) } }
func refresh() {
let list = session.songNames, name = session.songName
if list != songs { songs = list }
if name != songName { songName = name }
}
/// The save prompt's default: the open song's name, else "untitled".
var defaultSaveName: String {
let n = songName.trimmingCharacters(in: .whitespacesAndNewlines)
return n.isEmpty ? "untitled" : n
}
func save(_ name: String) throws {
try session.saveSongNamed(name.trimmingCharacters(in: .whitespacesAndNewlines))
refresh()
}
func load(_ name: String) throws {
try session.loadSongNamed(name)
refresh()
}
func delete(_ name: String) throws {
try session.deleteSongNamed(name)
refresh()
}
func newSong() {
session.newSong()
refresh()
}
func panic() { session.panic() }
// MARK: Export / import
enum Format {
case sng, project
var ext: String { self == .sng ? "sng" : "szg" }
}
/// The open song written to a temporary "<song>.sng" / "<song>.szg" for sharing.
func exportFile(_ format: Format) throws -> URL {
let text = format == .sng ? session.sngText() : session.projectText()
return try SetupFiles.export(text, songName: songName, ext: format.ext)
}
/// Imports a picked file: a .sng into the open song (notes, blocks,
/// arrangement), or a project replacing it.
func importFile(_ url: URL, as format: Format) throws {
let text = try SetupFiles.readText(url)
switch format {
case .sng: try session.importSngText(text)
case .project: try session.importProjectText(text)
}
refresh()
}
}
@@ -0,0 +1,93 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
// The Setup tab's UIKit-backed pieces: the share sheet, the device lab and the
// plugin check. The Mac snapshot tool has no UIKit (and doesn't compile
// DeviceLabView / PluginCheck), so there they are no-ops.
#if canImport(UIKit)
import UIKit
enum ShareSheet {
/// Presents the system share sheet for [url] over the frontmost view controller
/// (a centred popover on iPad); [done] runs when it closes.
@MainActor static func present(_ url: URL, done: @escaping () -> Void = {}) {
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
guard var top = (scene?.windows.first { $0.isKeyWindow } ?? scene?.windows.first)?.rootViewController else { return }
while let next = top.presentedViewController { top = next }
let vc = UIActivityViewController(activityItems: [url], applicationActivities: nil)
vc.completionWithItemsHandler = { _, _, _, _ in done() }
if let pop = vc.popoverPresentationController {
pop.sourceView = top.view
pop.sourceRect = CGRect(x: top.view.bounds.midX, y: top.view.bounds.midY, width: 0, height: 0)
pop.permittedArrowDirections = []
}
top.present(vc, animated: true)
}
}
extension View {
/// The old device test screen (instruments, effects, benchmark), full screen.
func deviceLab(isPresented: Binding<Bool>) -> some View {
fullScreenCover(isPresented: isPresented) {
VStack(spacing: 0) {
HStack {
Text("Device lab").font(.headline)
Spacer()
Button("Done") { isPresented.wrappedValue = false }.font(.body.weight(.semibold))
}
.padding(.horizontal).padding(.top, 12)
DeviceLabView()
}
.background(Theme.background.ignoresSafeArea())
.preferredColorScheme(.dark)
}
}
/// Loads every registered Sizzle plugin out of process and renders through it.
func pluginCheck(isPresented: Binding<Bool>) -> some View {
sheet(isPresented: isPresented) { PluginCheckSheet { isPresented.wrappedValue = false } }
}
}
private struct PluginCheckSheet: View {
let close: () -> Void
@StateObject private var check = PluginCheck()
var body: some View {
VStack(alignment: .leading, spacing: 10) {
HStack {
Text("Plugin check").font(.headline)
if check.running { ProgressView().padding(.leading, 6) }
Spacer()
Button("Run again") { Task { await check.run() } }.disabled(check.running)
Button("Done", action: close).font(.body.weight(.semibold)).padding(.leading, 12)
}
ScrollView {
Text(check.lines.joined(separator: "\n"))
.font(.system(.footnote, design: .monospaced))
.frame(maxWidth: .infinity, alignment: .leading)
.textSelection(.enabled)
}
}
.padding()
.preferredColorScheme(.dark)
.task { await check.run() }
}
}
#else
enum ShareSheet {
@MainActor static func present(_ url: URL, done: @escaping () -> Void = {}) { done() }
}
extension View {
func deviceLab(isPresented: Binding<Bool>) -> some View { self }
func pluginCheck(isPresented: Binding<Bool>) -> some View { self }
}
#endif
@@ -0,0 +1,314 @@
// 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, export and import of projects and .sng),
/// help and about, and the device lab. Android's other sections (audio devices,
/// recording, interface, themes, MIDI sync, bindings, backup) keep their places
/// as greyed-out cards until they're ported.
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
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; helpCard }
VStack(spacing: 14) { comingLater; diagnosticsCard }
}
} else {
projectCard
helpCard
comingLater
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)
}
// 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") { export(.project) }
SetupButton(title: "Import project", icon: "square.and.arrow.down.on.square") { pick(.project) }
}
SetupNote("A project file (.szg) carries patterns, mixer, FX and instruments, so it opens " +
"complete on another device (samples aren't included yet). Import 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: Sections still to come
private static let later: [(String, String, String)] = [
("Audio Devices", "Route playback / recording to USB or built-in", "hifispeaker"),
("Recording", "Record the master bus to WAV files", "record.circle"),
("Interface", "On-screen display options", "rectangle.on.rectangle"),
("Color Theme", "Pick, import, export or delete a palette", "paintpalette"),
("MIDI Sync", "MIDI clock in and out, sources, sound module", "metronome"),
("Gamepad Bindings", "Rebind buttons & combos", "gamecontroller"),
("Keyboard Hotkeys", "Rebind keyboard keys", "keyboard"),
("MIDI Bindings", "MIDI-learn controls", "pianokeys"),
("Backup & Restore", "Save or restore all songs, presets, themes & settings", "externaldrive"),
]
private var comingLater: some View {
SetupCard(title: "More settings", subtitle: "Coming in a later version", enabled: false) {
ForEach(Array(Self.later.enumerated()), id: \.offset) { i, s in
if i > 0 { SetupDivider() }
ComingLaterRow(title: s.0, subtitle: s.1, icon: s.2)
}
}
}
// 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 .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 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 {
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 {
show("Import failed", importFormat == .sng
? "Couldn't import this file. It doesn't look like a valid .sng song."
: "Couldn't import this file. It doesn't look like a Sizzle project (.szg).")
}
}
/// Like Android after a load or import: the tracker cursor back to the top.
private func resetCursor() {
app.cursorLine = 0
app.cursorTrack = 0
}
}