// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later import SwiftUI import UniformTypeIdentifiers #if canImport(UIKit) import UIKit #endif /// A toolbox slot's settings over the Toolbox tab (Android's ParamEditor): the slot's /// name and CLOSE, the preset bar, the device's own extras (Sampler pad tools, the /// SF2/XI loader, the LFO's target) and its card editor. Instruments pin a playable /// part, the audition keyboard or the Sampler's pads, below the controls (1.7 : 1) /// or, in landscape, beside them (1 : 1.3). struct SlotEditor: View { let slot: Int let type: String let landscape: Bool let onClose: () -> Void @StateObject private var model: DeviceModel @ObservedObject private var watch = MixSongWatch.shared @ObservedObject private var recorder = SampleRecorder.shared @State private var pad = 0 /// What the file picker is for; kept after it closes, because SwiftUI resets /// the presentation binding before calling the completion handler. @State private var importing: ImportKind? @State private var pickerShown = false @State private var deviceCallback: ((URL) -> Void)? @State private var importError: String? @State private var showMidiLearn = false enum ImportKind: Identifiable { case preset, padSample, soundFont, device // device: a bespoke view's own load (deviceFilePicker) var id: Self { self } } init(slot: Int, type: String, landscape: Bool, onClose: @escaping () -> Void) { self.slot = slot self.type = type self.landscape = landscape self.onClose = onClose _model = StateObject(wrappedValue: SlotEditor.makeModel(slot: slot)) } private static let keyboardTypes: Set = ["SOUNDFONT", "NES_SYNTH", "MORPH_PAD", "GRAIN_CLOUD", "WAVETABLE"] var body: some View { let pinned = Self.keyboardTypes.contains(type) || type == "SAMPLER" GeometryReader { geo in Group { if pinned && landscape { HStack(spacing: 0) { controls.frame(width: (geo.size.width - 2) / 2.3) Theme.accent.frame(width: 2) pinnedPart } } else if pinned { VStack(spacing: 0) { controls.frame(height: (geo.size.height - 2) * 1.7 / 2.7) Theme.accent.frame(height: 2) pinnedPart } } else { controls } } } .background(Theme.background.opacity(0.96)) .fileImporter(isPresented: $pickerShown, allowedContentTypes: importTypes, allowsMultipleSelection: false) { result in guard case .success(let urls) = result, let url = urls.first, let kind = importing else { return } if kind == .device { deviceCallback?(url) } else { load(url, kind) } } .alert("Import failed", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } }), actions: { Button("OK") { importError = nil } }, message: { Text(importError ?? "") }) .background(Color.clear.alert("Recording", isPresented: Binding(get: { recorder.error != nil }, set: { if !$0 { recorder.error = nil } }), actions: { Button("OK") { recorder.error = nil } }, message: { Text(recorder.error ?? "") })) .onDisappear { if recorder.isRecording { _ = recorder.stop() } } .onChange(of: watch.revision) { _ in model.refresh() } // MIDI CCs move parameters too .sheet(isPresented: $showMidiLearn) { MidiLearnSheet(slot: slot, type: type) } } @ViewBuilder private var pinnedPart: some View { if type == "SAMPLER" { SamplerPadBank(slot: slot, selected: pad) { pad = $0 } } else { SlotAuditionKeyboard(slot: slot) } } private var controls: some View { let session = SizzleSession.shared return VStack(alignment: .leading, spacing: 8) { HStack { Text(session.name(ofSlot: slot)).font(Theme.mono(15)).foregroundColor(Theme.accent).lineLimit(1) Spacer() Text("⇄ MIDI").font(Theme.mono(13)).foregroundColor(Theme.accent) .contentShape(Rectangle()).onTapGesture { showMidiLearn = true } .padding(.trailing, 14) Text("CLOSE ✕").font(Theme.mono(13)).foregroundColor(Theme.dim) .contentShape(Rectangle()).onTapGesture(perform: onClose) } PresetBar(slot: slot, type: type, model: model, onImport: { importing = .preset; pickerShown = true }) switch type { case "SAMPLER": SamplerDetail(slot: slot, pad: pad, onSelectPad: { pad = $0 }, onImport: { importing = .padSample; pickerShown = true }) case "SOUNDFONT": SoundFontDetail(slot: slot, onImport: { importing = .soundFont; pickerShown = true }) default: EmptyView() } // The card editor brings its own padding and header row; with no name and // no preset menu (the bar above has them) the row is empty, so pull it up. DeviceEditor(model: model, showsHeader: false).padding(.horizontal, -10) .environment(\.deviceFilePicker) { done in deviceCallback = done importing = .device pickerShown = true } .environment(\.deviceRecorder, DeviceRecordControl(isRecording: recorder.isRecording) { if recorder.isRecording { recorder.stopIntoGrain(slot: slot) } else { recorder.start() } }) .frame(minHeight: 0, maxHeight: .infinity, alignment: .top).clipped() if type == "LFO" { LfoTargetPicker(lfo: slot) } } .padding(12) .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) .clipped() } private var importTypes: [UTType] { switch importing { case .padSample: return [.audio, .wav] case .preset, .soundFont, .device, .none: return [.item] } } /// Read a picked file (security-scoped) and hand it to the slot. private func load(_ url: URL, _ kind: ImportKind) { let session = SizzleSession.shared let scoped = url.startAccessingSecurityScopedResource() defer { if scoped { url.stopAccessingSecurityScopedResource() } } let maxBytes = 64 * 1024 * 1024 let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0 guard size <= maxBytes, let data = try? Data(contentsOf: url), data.count <= maxBytes else { importError = kind == .preset ? "Couldn't read the selected file." : "Couldn't read the file, or it's larger than 64 MB." return } let name = url.deletingPathExtension().lastPathComponent switch kind { case .preset: // Preset text, or a bundle with its sounds (how Android shares Sampler presets). guard session.importPresetData(data, intoSlot: slot) else { let display = SizzleSession.deviceTypes.first { $0.type == type }?.displayName ?? type importError = "Couldn't import this preset. The file may be corrupt, or not a valid \(display) preset or bundle." return } ToolboxNav.shared.editorEpoch += 1 // the slot's values (maybe its type) changed: rebuild the cards case .padSample: if (try? session.loadSampleData(data, name: name, intoSlot: slot, pad: pad)) == nil { importError = "Couldn't load this sample. Only uncompressed WAV files (8/16/24-bit PCM or 32-bit float) are supported." return } session.setNumber(0, ofSlot: slot, key: "pad\(pad)S") session.setNumber(1, ofSlot: slot, key: "pad\(pad)E") case .soundFont: if (try? session.loadSampleData(data, name: name, intoSlot: slot, pad: 0)) == nil { importError = "Couldn't load this instrument. Supported formats are .sf2, .xi and uncompressed .wav." } case .device: break // handed to the bespoke view (deviceCallback) } } /// SlotDeviceModel's slot-backed model, without a title or preset menu (this /// editor's header and PresetBar carry them); presets load from the library. static func makeModel(slot: Int) -> DeviceModel { let session = SizzleSession.shared let type = session.type(ofSlot: slot) let specs = SizzleSession.paramSpecs(forType: type) let infos = specs.map { s in ParamInfo(key: s.key, label: s.label, min: s.minValue, max: s.maxValue, def: s.defaultValue, isInt: s.isInt, choices: s.choices) } func read() -> [String: Float] { var v: [String: Float] = [:] for s in specs { let text = session.value(ofSlot: slot, key: s.key) if s.choices.isEmpty { v[s.key] = Float(text) ?? s.defaultValue } else { v[s.key] = Float(s.choices.firstIndex(of: text) ?? Int(s.defaultValue)) } } return v } let byKey = Dictionary(specs.map { ($0.key, $0) }, uniquingKeysWith: { a, _ in a }) return DeviceModel(toolboxType: type, displayName: "", infos: infos, values: read(), presetNames: [], write: { key, v in guard let s = byKey[key] else { return } if s.choices.isEmpty { session.setNumber(v, ofSlot: slot, key: key) } else { session.setValue(s.choices[max(0, min(s.choices.count - 1, Int(v.rounded())))], ofSlot: slot, key: key) } }, applyPreset: { name in _ = session.loadPreset(name, intoSlot: slot) }, reread: read) .withData(SlotDataSource(session: session, slot: slot)) } } /// Android's PresetBar: the library's presets for this device type, then DELETE /// (kept apart on the left), SAVE, IMPORT and SHARE. private struct PresetBar: View { let slot: Int let type: String let model: DeviceModel let onImport: () -> Void @State private var names: [String] @State private var selected: String? @State private var saving = false @State private var saveName = "" @State private var confirmDelete: String? init(slot: Int, type: String, model: DeviceModel, onImport: @escaping () -> Void) { self.slot = slot self.type = type self.model = model self.onImport = onImport _names = State(initialValue: SizzleSession.shared.libraryPresets(forType: type)) } private var session: SizzleSession { SizzleSession.shared } private var displayName: String { SizzleSession.deviceTypes.first { $0.type == type }?.displayName ?? type } private var slotName: String { session.name(ofSlot: slot) } var body: some View { let current = selected.flatMap { names.contains($0) ? $0 : nil } ?? (names.contains(slotName) ? slotName : names.first) VStack(alignment: .leading, spacing: 4) { MixKit.HScroll { if let current = current { MixKit.Dropdown(label: "PRESET", options: names, selected: current, optionLabel: { $0 }, onSelect: { selected = $0; model.applyPreset(named: $0) }) } else { Text("no presets").font(Theme.mono(11)).foregroundColor(Theme.dim) } } MixKit.HScroll { HStack(spacing: 6) { if let current = current { MixKit.Button(label: "DELETE", danger: true) { confirmDelete = current } Spacer().frame(width: 20) } MixKit.Button(label: "SAVE") { saveName = slotName.trimmingCharacters(in: .whitespaces).isEmpty ? displayName : slotName saving = true } MixKit.Button(label: "IMPORT", action: onImport) MixKit.Button(label: "SHARE") { share() } } } } .sheet(isPresented: $saving) { saveSheet } // `presenting:`: the binding (and confirmDelete) is reset before the action runs. .alert("Delete preset", isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } }), presenting: confirmDelete, actions: { n in Button("Delete", role: .destructive) { _ = session.deletePreset(n, type: type) selected = nil names = session.libraryPresets(forType: type) } Button("Cancel", role: .cancel) {} }, message: { n in Text("Delete \"\(n)\"? This cannot be undone.") }) } private var saveSheet: some View { VStack(alignment: .leading, spacing: 16) { Text("Save preset").font(Theme.mono(16)).foregroundColor(Theme.accent) TextField("Name", text: $saveName) .font(Theme.mono(14)).foregroundColor(Theme.text) .padding(8).overlay(Rectangle().stroke(Theme.grid, lineWidth: 1)) HStack(spacing: 12) { Spacer() MixKit.Button(label: "CANCEL") { saving = false } MixKit.Button(label: "SAVE", active: true) { let n = saveName.trimmingCharacters(in: .whitespaces) if !n.isEmpty { _ = session.savePreset(ofSlot: slot, name: n); selected = n } names = session.libraryPresets(forType: type) saving = false } } Spacer() } .padding(20) .background(Theme.surface.ignoresSafeArea()) .preferredColorScheme(.dark) } /// Save under the slot's name (so there is a file), then the share sheet. private func share() { let name = slotName.trimmingCharacters(in: .whitespaces).isEmpty ? displayName : slotName _ = session.savePreset(ofSlot: slot, name: name) names = session.libraryPresets(forType: type) guard let url = session.presetShareURL(forType: type, name: name) else { return } #if canImport(UIKit) let vc = UIActivityViewController(activityItems: [url], applicationActivities: nil) let root = UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.keyWindow }.first?.rootViewController var top = root while let p = top?.presentedViewController { top = p } if let pop = vc.popoverPresentationController, let v = top?.view { pop.sourceView = v pop.sourceRect = CGRect(x: v.bounds.midX, y: v.bounds.midY, width: 1, height: 1) pop.permittedArrowDirections = [] } top?.present(vc, animated: true) #endif } } /// LfoTargetPicker: every numeric parameter of every other filled slot; choosing /// one makes the LFO drive it (the parameter's value now is the centre). private struct LfoTargetPicker: View { let lfo: Int private struct Target: Hashable { let slot: Int, key: String, label: String var encoded: String { slot < 0 ? "" : "\(slot):\(key)" } } var body: some View { let session = SizzleSession.shared let none = Target(slot: -1, key: "", label: "— none —") var targets = [none] for i in 0..<16 where i != lfo { let t = session.type(ofSlot: i) if t.isEmpty { continue } let name = session.name(ofSlot: i) for spec in SizzleSession.paramSpecs(forType: t) where spec.choices.isEmpty { targets.append(Target(slot: i, key: spec.key, label: "\(i + 1):\(name) · \(spec.label)")) } } let current = session.value(ofSlot: lfo, key: "target") let selected = targets.first { $0.encoded == current } ?? none return VStack(alignment: .leading, spacing: 4) { MixKit.Dropdown(label: "TARGET", options: targets, selected: selected, fill: true, optionLabel: { $0.label }, onSelect: { session.setLfoTargetOfSlot(lfo, target: $0.slot, key: $0.key) }) Text("The LFO takes over its target parameter while assigned.").font(Theme.mono(10)).foregroundColor(Theme.dim) } } }