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,261 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
#if canImport(UIKit)
import UIKit
#endif
/// The Toolbox tab's audition keyboard (Android's StackedKeyboard without punch-in):
/// CH / OCT / VEL steppers over two stacked octaves, upper on top. Keys play the
/// mix bus on the keyboard's MIDI channel; out-of-scale keys are dimmed, unless the
/// channel reaches a Sampler (every pad must stay playable).
struct ToolboxKeyboard: View {
let app: AppModel
let channel: Int
let octave: Int
let velocity: Int
var body: some View {
let session = SizzleSession.shared
let inKey = routesToSampler ? Set(0..<12) : Set(session.scalePitchClasses.map { $0.intValue })
VStack(spacing: 4) {
MixKit.HScroll {
HStack(spacing: 6) {
selector("CH", channel == 0 ? "--" : "\(channel)",
{ app.kbdChannel = max(0, app.kbdChannel - 1) }, { app.kbdChannel = min(16, app.kbdChannel + 1) })
selector("OCT", "\(octave)–\(octave + 1)",
{ app.kbdOctave = max(0, app.kbdOctave - 1) }, { app.kbdOctave = min(8, app.kbdOctave + 1) })
selector("VEL", String(format: "%02X", velocity),
{ app.kbdVelocity = max(0, app.kbdVelocity - 8) }, { app.kbdVelocity = min(127, app.kbdVelocity + 8) })
}
}
.frame(maxWidth: .infinity, alignment: .leading)
octaveView(start: (octave + 2) * 12, inKey: inKey)
octaveView(start: (octave + 1) * 12, inKey: inKey)
}
.padding(6)
.background(Theme.background)
}
private var routesToSampler: Bool {
let s = SizzleSession.shared
return (0..<4).contains { ch in
s.midiChannel(ofChannel: ch) == channel && s.type(ofSlot: s.instrumentSlot(ofChannel: ch)) == "SAMPLER"
}
}
private func octaveView(start: Int, inKey: Set<Int>) -> some View {
let session = SizzleSession.shared, held = HeldNotes.shared
let ch = channel, vel = velocity
return PianoOctave(start: start, enabled: inKey,
onOn: { n in held.on(n); session.note(on: n, velocity: vel, midiChannel: ch) },
onOff: { n in held.off(n); session.noteOff(n, midiChannel: ch) })
}
private func selector(_ label: String, _ value: String, _ dec: @escaping () -> Void, _ inc: @escaping () -> Void) -> some View {
HStack(spacing: 6) {
Text(label).font(Theme.mono(11)).foregroundColor(Theme.dim)
MixKit.RepeatButton(label: "-", onStep: dec)
Text(value).font(Theme.mono(13)).foregroundColor(Theme.accent).frame(width: 40)
MixKit.RepeatButton(label: "+", onStep: inc)
}
}
}
/// SlotAuditionKeyboard: an OCT stepper over two octaves that play one toolbox slot
/// directly (the instrument editors pin it under their controls).
struct SlotAuditionKeyboard: View {
let slot: Int
@State private var octave = 3
var body: some View {
let session = SizzleSession.shared
let inKey = Set(session.scalePitchClasses.map { $0.intValue })
VStack(spacing: 4) {
HStack(spacing: 6) {
Text("OCT").font(Theme.mono(11)).foregroundColor(Theme.dim)
MixKit.RepeatButton(label: "-") { octave = max(0, octave - 1) }
Text("\(octave)–\(octave + 1)").font(Theme.mono(13)).foregroundColor(Theme.accent)
MixKit.RepeatButton(label: "+") { octave = min(8, octave + 1) }
}
.frame(maxWidth: .infinity, alignment: .leading)
octaveView(start: (octave + 2) * 12, inKey: inKey)
octaveView(start: (octave + 1) * 12, inKey: inKey)
}
.padding(6)
.background(Theme.background)
}
private func octaveView(start: Int, inKey: Set<Int>) -> some View {
let session = SizzleSession.shared, held = HeldNotes.shared, s = slot
return PianoOctave(start: start, enabled: inKey,
onOn: { n in held.on(n); session.auditionSlot(s, note: n, on: true) },
onOff: { n in held.off(n); session.auditionSlot(s, note: n, on: false) })
}
}
/// Android's PianoOctave: seven white keys with five black keys over them. Fingers
/// are tracked at the octave level, so sliding across keys retriggers each one (a
/// glissando) and several fingers play chords. Out-of-scale keys are dimmed and
/// silent; held notes light up.
struct PianoOctave: View {
let start: Int
let enabled: Set<Int>
let onOn: (Int) -> Void
let onOff: (Int) -> Void
@ObservedObject private var held = HeldNotes.shared
@StateObject private var router = KeyTouchRouter()
static let whites = [0, 2, 4, 5, 7, 9, 11]
static let blacks: [(pc: Int, after: Int)] = [(1, 0), (3, 1), (6, 3), (8, 4), (10, 5)]
static let blackW: CGFloat = 0.62, blackH: CGFloat = 0.62
var body: some View {
GeometryReader { g in
let size = g.size
let ww = size.width / 7, bw = ww * Self.blackW
let _ = router.configure(start: start, enabled: enabled, size: size, onOn: onOn, onOff: onOff)
ZStack(alignment: .topLeading) {
HStack(spacing: 0) {
ForEach(Self.whites, id: \.self) { pc in key(pc, black: false).frame(width: ww, height: size.height) }
}
ForEach(Self.blacks, id: \.pc) { b in
key(b.pc, black: true).frame(width: bw, height: size.height * Self.blackH)
.offset(x: ww * CGFloat(b.after + 1) - bw / 2)
}
}
.overlay(touchLayer)
}
}
private func midi(_ pc: Int) -> Int { min(127, max(0, start + pc)) }
private func key(_ pc: Int, black: Bool) -> some View {
let on = enabled.contains(pc)
let lit = held.isHeld(midi(pc))
let bg: Color = lit ? Theme.accent
: black ? (on ? Color(red: 0x18 / 255, green: 0x18 / 255, blue: 0x20 / 255) : Color(red: 0x0C / 255, green: 0x0C / 255, blue: 0x10 / 255))
: (on ? Color(white: 0xE8 / 255) : Color(white: 0x5A / 255))
let fg: Color = lit ? Theme.background
: black ? (on ? Color(white: 0xDD / 255) : Color(white: 0x55 / 255))
: (on ? Color(white: 0x14 / 255) : Color(white: 0x6A / 255))
return ZStack(alignment: .bottom) {
bg
Text(MixKit.pitchName(midi(pc)).replacingOccurrences(of: "-", with: ""))
.font(Theme.mono(12)).foregroundColor(fg).lineLimit(1).minimumScaleFactor(0.5)
.padding(.bottom, 3)
}
.overlay(Rectangle().stroke(lit ? Theme.accent : Color.black, lineWidth: 1))
}
@ViewBuilder private var touchLayer: some View {
#if canImport(UIKit)
MultiTouchSurface(router: router)
#else
Color.clear.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 0)
.onChanged { router.touch(id: 0, at: $0.location, ended: false) }
.onEnded { router.touch(id: 0, at: $0.location, ended: true) })
#endif
}
}
/// Per-finger key tracking for a PianoOctave (pcAt in Piano.kt).
@MainActor
final class KeyTouchRouter: ObservableObject {
private var active: [Int: Int] = [:] // touch id -> pitch class, -1 off any playable key
private var start = 60
private var enabled: Set<Int> = []
private var size: CGSize = .zero
private var onOn: (Int) -> Void = { _ in }
private var onOff: (Int) -> Void = { _ in }
func configure(start: Int, enabled: Set<Int>, size: CGSize, onOn: @escaping (Int) -> Void, onOff: @escaping (Int) -> Void) {
// An octave change while a key is held: release the old notes first.
// (Deferred: this runs while SwiftUI evaluates the body.)
if start != self.start, !active.isEmpty {
let notes = active.values.filter { $0 >= 0 }.map(midi), off = self.onOff
active.removeAll()
DispatchQueue.main.async { notes.forEach(off) }
}
self.start = start
self.enabled = enabled
self.size = size
self.onOn = onOn
self.onOff = onOff
}
private func midi(_ pc: Int) -> Int { min(127, max(0, start + pc)) }
func touch(id: Int, at p: CGPoint, ended: Bool) {
if ended {
if let prev = active.removeValue(forKey: id), prev >= 0 { onOff(midi(prev)) }
return
}
let raw = pitchClass(at: p)
let pc = raw >= 0 && enabled.contains(raw) ? raw : -1
guard let prev = active[id] else {
active[id] = pc
if pc >= 0 { onOn(midi(pc)) }
return
}
if pc != prev {
if prev >= 0 { onOff(midi(prev)) }
if pc >= 0 { onOn(midi(pc)) }
active[id] = pc
}
}
func releaseAll() {
for (_, pc) in active where pc >= 0 { onOff(midi(pc)) }
active.removeAll()
}
private func pitchClass(at p: CGPoint) -> Int {
let w = size.width, h = size.height
guard w > 0, h > 0, p.x >= 0, p.x < w, p.y >= 0, p.y < h else { return -1 }
let ww = w / 7
if p.y <= h * PianoOctave.blackH {
let bw = ww * PianoOctave.blackW
for b in PianoOctave.blacks {
let bx = ww * CGFloat(b.after + 1) - bw / 2
if p.x >= bx && p.x <= bx + bw { return b.pc }
}
}
return PianoOctave.whites[min(6, max(0, Int(p.x / ww)))]
}
}
#if canImport(UIKit)
/// A transparent view that reports every finger (SwiftUI gestures follow only one).
private struct MultiTouchSurface: UIViewRepresentable {
let router: KeyTouchRouter
func makeUIView(context: Context) -> TouchView {
let v = TouchView()
v.router = router
return v
}
func updateUIView(_ v: TouchView, context: Context) { v.router = router }
final class TouchView: UIView {
weak var router: KeyTouchRouter?
override init(frame: CGRect) {
super.init(frame: frame)
isMultipleTouchEnabled = true
backgroundColor = .clear
}
required init?(coder: NSCoder) { fatalError() }
private func send(_ touches: Set<UITouch>, ended: Bool) {
for t in touches { router?.touch(id: ObjectIdentifier(t).hashValue, at: t.location(in: self), ended: ended) }
}
override func touchesBegan(_ t: Set<UITouch>, with e: UIEvent?) { send(t, ended: false) }
override func touchesMoved(_ t: Set<UITouch>, with e: UIEvent?) { send(t, ended: false) }
override func touchesEnded(_ t: Set<UITouch>, with e: UIEvent?) { send(t, ended: true) }
override func touchesCancelled(_ t: Set<UITouch>, with e: UIEvent?) { send(t, ended: true) }
}
}
#endif
@@ -0,0 +1,246 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// Sampler pads: 16 pads from C2 (MIDI 36), keys "padN" (sample id), "padNS" /
/// "padNE" (slice 0..1), "padNV" (volume, 0.8 by default).
enum SamplerPads {
static let baseNote = 36
static let defaultVolume: Float = 0.8
static func note(_ pad: Int) -> Int { baseNote + pad }
}
/// SamplerEditor's detail area for the selected pad: its source buttons, then a
/// swipeable pair of pages (waveform with slice markers / the 16 pad volumes).
struct SamplerDetail: View {
let slot: Int
let pad: Int
let onSelectPad: (Int) -> Void
let onImport: () -> Void
@State private var page = 0
var body: some View {
let session = SizzleSession.shared
let assigned = !session.value(ofSlot: slot, key: "pad\(pad)").isEmpty
VStack(alignment: .leading, spacing: 8) {
Text("Pad \(pad + 1) · \(MixKit.pitchName(SamplerPads.note(pad)))").font(Theme.mono(13)).foregroundColor(Theme.accent)
MixKit.HScroll {
HStack(spacing: 8) {
MixKit.Button(label: "IMPORT WAV", action: onImport)
if assigned {
MixKit.Button(label: "✂ CLIP") { _ = session.trimPad(pad, ofSlot: slot) }
MixKit.Button(label: "NORMALIZE") { _ = session.normalizePad(pad, ofSlot: slot) }
MixKit.Button(label: "CLEAR", danger: true) { session.clearPad(pad, ofSlot: slot) }
}
}
}
Group {
if page == 0 {
WaveformPage(slot: slot, pad: pad)
} else {
VStack(alignment: .leading, spacing: 6) {
Text("Pad volumes (drag a slider; tap selects that pad):").font(Theme.mono(11)).foregroundColor(Theme.dim)
PadVolumeBank(slot: slot, selected: pad, onSelect: onSelectPad)
}
}
}
.frame(maxWidth: .infinity, minHeight: 200, maxHeight: 200, alignment: .top)
.contentShape(Rectangle())
.simultaneousGesture(DragGesture(minimumDistance: 30).onEnded { g in
// Swipe between the pages (the drags inside them are vertical or marker drags).
guard abs(g.translation.width) > abs(g.translation.height) * 2, abs(g.translation.width) > 80 else { return }
page = g.translation.width < 0 ? 1 : 0
})
HStack(spacing: 8) {
ForEach(0..<2, id: \.self) { i in
Circle().fill(i == page ? Theme.accent : Theme.grid)
.frame(width: i == page ? 10 : 7, height: i == page ? 10 : 7)
.frame(width: 14, height: 14)
.contentShape(Rectangle())
.onTapGesture { page = i }
}
}
.frame(maxWidth: .infinity)
}
}
}
/// The selected pad's waveform; drag near a marker to move the slice start / end.
private struct WaveformPage: View {
let slot: Int
let pad: Int
@State private var dragging = -1
var body: some View {
let session = SizzleSession.shared
let key = "pad\(pad)"
let peaks = PeakCache.peaks(slot: slot, key: key)
let start = CGFloat(Float(session.value(ofSlot: slot, key: key + "S")) ?? 0)
let end = CGFloat(Float(session.value(ofSlot: slot, key: key + "E")) ?? 1)
let frames = session.sampleFrames(ofSlot: slot, key: key)
VStack(alignment: .leading, spacing: 6) {
GeometryReader { g in
let w = g.size.width, h = g.size.height
ZStack(alignment: .topLeading) {
Theme.surface
if let p = peaks { WaveformShape(peaks: p).stroke(Theme.text, lineWidth: 1) }
Theme.accent.opacity(0.14).frame(width: max(0, (end - start) * w), height: h).offset(x: start * w)
Theme.accent.frame(width: 3, height: h).offset(x: start * w - 1.5)
MixKit.playhead.frame(width: 3, height: h).offset(x: end * w - 1.5)
}
.clipped()
.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 1)
.onChanged { d in
guard w > 0 else { return }
if dragging < 0 {
let f0 = min(max(d.startLocation.x / w, 0), 1)
dragging = abs(f0 - start) <= abs(f0 - end) ? 0 : 1
}
let f = Float(min(max(d.location.x / w, 0), 1))
session.setNumber(f, ofSlot: slot, key: key + (dragging == 0 ? "S" : "E"))
}
.onEnded { _ in dragging = -1 })
}
.frame(height: 150)
Text(frames == 0 ? "Pad empty — Import a WAV to assign it."
: "\(frames) frames @ \(session.sampleRate(ofSlot: slot, key: key)) Hz · drag the markers, then CLIP to trim")
.font(Theme.mono(10)).foregroundColor(Theme.dim)
}
}
}
/// 16 vertical pad-volume sliders, 8 wide and 2 tall like the pad grid.
private struct PadVolumeBank: View {
let slot: Int
let selected: Int
let onSelect: (Int) -> Void
var body: some View {
VStack(spacing: 6) {
ForEach(0..<2, id: \.self) { row in
HStack(spacing: 4) {
ForEach(0..<8, id: \.self) { col in
PadVolumeSlider(slot: slot, pad: row * 8 + col, isSelected: selected == row * 8 + col, onSelect: onSelect)
}
}
}
}
}
}
private struct PadVolumeSlider: View {
let slot: Int
let pad: Int
let isSelected: Bool
let onSelect: (Int) -> Void
var body: some View {
let session = SizzleSession.shared
let vol = CGFloat(Float(session.value(ofSlot: slot, key: "pad\(pad)V")) ?? SamplerPads.defaultVolume)
let assigned = !session.value(ofSlot: slot, key: "pad\(pad)").isEmpty
let border = isSelected ? MixKit.playhead : (assigned ? Theme.accent : Theme.grid)
VStack(spacing: 1) {
GeometryReader { g in
let h = g.size.height
ZStack(alignment: .bottom) {
Theme.surface
(assigned ? Theme.accent : Theme.grid).opacity(0.55).frame(height: min(max(vol, 0), 1) * h)
}
.overlay(Rectangle().stroke(border, lineWidth: isSelected ? 2 : 1))
.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 0).onChanged { d in
if !isSelected { onSelect(pad) }
guard h > 0 else { return }
let raw = Float(min(max(1 - d.location.y / h, 0), 1))
let v = abs(raw - SamplerPads.defaultVolume) < 0.03 ? SamplerPads.defaultVolume : raw
session.setNumber(v, ofSlot: slot, key: "pad\(pad)V")
})
}
.frame(height: 76)
Text(MixKit.pitchName(SamplerPads.note(pad))).font(Theme.mono(8)).foregroundColor(assigned ? Theme.text : Theme.dim)
}
.frame(maxWidth: .infinity)
}
}
/// SamplerPadBank: the playable 4x4 pads pinned under the editor (pad 0 = C2 top
/// left). A pad sounds the instant it's touched and becomes the selected one.
struct SamplerPadBank: View {
let slot: Int
let selected: Int
let onSelect: (Int) -> Void
var body: some View {
VStack(spacing: 4) {
ForEach(0..<4, id: \.self) { row in
HStack(spacing: 4) {
ForEach(0..<4, id: \.self) { col in
PadCell(slot: slot, pad: row * 4 + col, isSelected: selected == row * 4 + col, onSelect: onSelect)
}
}
}
}
.padding(6)
.background(Theme.background)
}
}
private struct PadCell: View {
let slot: Int
let pad: Int
let isSelected: Bool
let onSelect: (Int) -> Void
@State private var down = false
var body: some View {
let session = SizzleSession.shared
let assigned = !session.value(ofSlot: slot, key: "pad\(pad)").isEmpty
let note = SamplerPads.note(pad)
let border = isSelected ? MixKit.playhead : (assigned ? Theme.accent : Theme.grid)
let fill = isSelected ? Theme.accent.opacity(0.28) : (assigned ? Theme.accent.opacity(0.12) : Theme.surface)
ZStack {
fill
VStack(spacing: 1) {
Text(MixKit.pitchName(note)).font(Theme.mono(10)).foregroundColor(assigned ? Theme.text : Theme.dim)
Text(assigned ? "●" : "+").font(Theme.mono(10)).foregroundColor(assigned ? Theme.accent : Theme.dim)
}
}
.overlay(Rectangle().stroke(border, lineWidth: isSelected ? 2 : 1))
.frame(maxWidth: .infinity, maxHeight: .infinity)
.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 0)
.onChanged { _ in
// On touch-down, like a drum pad; a one-shot, so no note-off (as Android).
guard !down else { return }
down = true
onSelect(pad)
session.auditionSlot(slot, note: note, on: true)
}
.onEnded { _ in down = false })
}
}
/// SoundFontEditor's loader part: LOAD SF2 / XI, what's loaded, and its waveform.
/// (Loop, crossfade, volume and envelope are on the cards below.)
struct SoundFontDetail: View {
let slot: Int
let onImport: () -> Void
var body: some View {
let session = SizzleSession.shared
let frames = session.sampleFrames(ofSlot: slot, key: "sfSample")
let root = Int(Float(session.value(ofSlot: slot, key: "sfRoot")) ?? 60)
VStack(alignment: .leading, spacing: 8) {
MixKit.Button(label: "LOAD SF2 / XI", action: onImport)
Text(frames == 0 ? "No instrument loaded — load a .sf2 or .xi file."
: "Loaded: \(frames) frames @ \(session.sampleRate(ofSlot: slot, key: "sfSample")) Hz · root \(MixKit.pitchName(root))")
.font(Theme.mono(10)).foregroundColor(frames == 0 ? Theme.dim : Theme.text)
if frames > 0, let peaks = PeakCache.peaks(slot: slot, key: "sfSample") {
WaveformShape(peaks: peaks).stroke(Theme.text, lineWidth: 1)
.frame(height: 96).background(Theme.surface)
}
}
}
}
@@ -0,0 +1,320 @@
// 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
@State private var pad = 0
@State private var importing: ImportKind?
@State private var importError: String?
enum ImportKind: Identifiable {
case preset, padSample, soundFont
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<String> = ["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: Binding(get: { importing != nil }, set: { if !$0 { importing = nil } }),
allowedContentTypes: importTypes, allowsMultipleSelection: false) { result in
let kind = importing
importing = nil
if case .success(let urls) = result, let url = urls.first, let kind = kind { load(url, kind) }
}
.alert("Import failed", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } }),
actions: { Button("OK") { importError = nil } }, message: { Text(importError ?? "") })
}
@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("CLOSE ✕").font(Theme.mono(13)).foregroundColor(Theme.dim)
.contentShape(Rectangle()).onTapGesture(perform: onClose)
}
PresetBar(slot: slot, type: type, model: model, onImport: { importing = .preset })
switch type {
case "SAMPLER": SamplerDetail(slot: slot, pad: pad, onSelectPad: { pad = $0 }, onImport: { importing = .padSample })
case "SOUNDFONT": SoundFontDetail(slot: slot, onImport: { importing = .soundFont })
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)
.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, .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:
guard let text = String(data: data, encoding: .utf8), session.importPresetText(text, 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."
}
}
}
/// 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)
}
}
/// 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 }
.alert("Delete preset", isPresented: Binding(get: { confirmDelete != nil }, set: { if !$0 { confirmDelete = nil } }), actions: {
Button("Delete", role: .destructive) {
if let n = confirmDelete { _ = session.deletePreset(n, type: type) }
selected = nil
confirmDelete = nil
names = session.libraryPresets(forType: type)
}
Button("Cancel", role: .cancel) { confirmDelete = nil }
}, message: { Text("Delete \"\(confirmDelete ?? "")\"? 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.presetFile(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)
}
}
}
@@ -0,0 +1,179 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// The third tab (Android's ToolboxScreen): 16 slot tiles holding instruments or
/// effects over (portrait) or beside (landscape) an audition keyboard.
/// - tap: pick a device for an empty tile, or open a filled tile's settings;
/// - long press: clear a filled tile, after confirming.
/// The slot editor (AppModel.editingSlot) opens over the whole tab.
struct ToolboxScreen: View {
@EnvironmentObject var app: AppModel
var body: some View {
ToolboxBody(app: app, editing: app.editingSlot ?? Self.snapshotSlot,
channel: app.kbdChannel, octave: app.kbdOctave, velocity: app.kbdVelocity)
}
/// The Mac snapshot tool can open a slot's editor: SIZZLE_SNAP_EDIT_SLOT=n.
private static let snapshotSlot: Int? =
Snapshot.active ? ProcessInfo.processInfo.environment["SIZZLE_SNAP_EDIT_SLOT"].flatMap { Int($0) } : nil
}
private struct ToolboxBody: View {
let app: AppModel
let editing: Int?
let channel: Int
let octave: Int
let velocity: Int
@ObservedObject private var watch = MixSongWatch.shared
@ObservedObject private var nav = ToolboxNav.shared
@State private var picking: Int?
@State private var clearing: Int?
private var session: SizzleSession { app.session }
var body: some View {
GeometryReader { geo in
let landscape = geo.size.width > geo.size.height
ZStack {
if landscape {
// A fixed 4x4 grid squashed to the height, beside the keyboard (1 : 1.3).
HStack(spacing: 0) {
tileGrid(side: nil).frame(width: (geo.size.width - 2) / 2.3)
Theme.accent.frame(width: 2)
ToolboxKeyboard(app: app, channel: channel, octave: octave, velocity: velocity)
}
} else {
// A scrolling grid of square tiles above the keyboard (1.7 : 1).
VStack(spacing: 0) {
SnapScroll { tileGrid(side: (geo.size.width - 12 - 18) / 4) }
.frame(height: (geo.size.height - 2) * 1.7 / 2.7, alignment: .top)
.clipped()
Theme.accent.frame(height: 2)
ToolboxKeyboard(app: app, channel: channel, octave: octave, velocity: velocity)
}
}
if let index = picking {
DevicePicker(onDismiss: { picking = nil }, onPick: { type in
session.fillSlot(index, withType: type)
picking = nil
app.editingSlot = index
})
}
if let index = editing, !session.type(ofSlot: index).isEmpty {
let type = session.type(ofSlot: index)
SlotEditor(slot: index, type: type, landscape: landscape, onClose: { nav.close(app: app) })
.id("\(index)|\(type)|\(nav.editorEpoch)")
}
}
}
.background(Theme.background)
.alert("Clear tile", isPresented: Binding(get: { clearing != nil }, set: { if !$0 { clearing = nil } }), actions: {
Button("Clear", role: .destructive) {
if let i = clearing { session.clearSlot(i) }
clearing = nil
}
Button("Cancel", role: .cancel) { clearing = nil }
}, message: {
if let i = clearing {
Text("Remove \"\(tileLabel(i))\" from tile \(i + 1)? This clears the device and its settings and can't be undone.")
}
})
}
private func tileLabel(_ i: Int) -> String {
let name = session.name(ofSlot: i)
if !name.trimmingCharacters(in: .whitespaces).isEmpty { return name }
let t = session.type(ofSlot: i)
return SizzleSession.deviceTypes.first { $0.type == t }?.displayName ?? ""
}
/// Four rows of four tiles: square in portrait, filling the height in landscape.
/// [side]: square tiles of that size (portrait); nil fills the height (landscape).
private func tileGrid(side: CGFloat?) -> some View {
VStack(spacing: 6) {
ForEach(0..<4, id: \.self) { row in
HStack(spacing: 6) {
ForEach(0..<4, id: \.self) { col in
let i = row * 4 + col
SlotTile(index: i, type: session.type(ofSlot: i), name: session.name(ofSlot: i))
.frame(width: side, height: side).frame(maxWidth: .infinity, maxHeight: side == nil ? .infinity : nil)
.onTapGesture {
nav.returnTab = nil
if session.type(ofSlot: i).isEmpty { picking = i } else { app.editingSlot = i }
}
.onLongPressGesture { if !session.type(ofSlot: i).isEmpty { clearing = i } }
}
}
.frame(maxHeight: side == nil ? .infinity : nil)
}
}
.padding(6)
}
}
/// One slot: its number, its name (or +) and INS / EFF.
private struct SlotTile: View {
let index: Int
let type: String
let name: String
var body: some View {
let empty = type.isEmpty
let isInstrument = SizzleSession.deviceTypes.first { $0.type == type }?.isInstrument ?? false
ZStack {
(empty ? Theme.surface : Theme.accent.opacity(0.12))
VStack(spacing: 1) {
Text(String(format: "%02d", index + 1)).font(Theme.mono(10)).foregroundColor(Theme.dim)
Text(empty ? "+" : name).font(Theme.mono(11)).foregroundColor(empty ? Theme.dim : Theme.text)
.lineLimit(1).truncationMode(.tail).multilineTextAlignment(.center)
if !empty {
Text(isInstrument ? "INS" : "EFF").font(Theme.mono(9)).foregroundColor(Theme.dim)
}
}
.padding(.horizontal, 5).padding(.vertical, 3)
}
.overlay(Rectangle().stroke(empty ? Theme.grid : Theme.accent, lineWidth: 1))
.contentShape(Rectangle())
}
}
/// The device list: instruments, MIDI effects, audio effects. Tap outside to dismiss.
private struct DevicePicker: View {
let onDismiss: () -> Void
let onPick: (String) -> Void
var body: some View {
let all = SizzleSession.deviceTypes
let groups: [(String, [SizzleDeviceType])] = [
("INSTRUMENTS", all.filter { $0.isInstrument }),
("MIDI EFFECTS", all.filter { !$0.isInstrument && $0.isMidiEffect }),
("AUDIO EFFECTS", all.filter { !$0.isInstrument && !$0.isMidiEffect }),
]
GeometryReader { geo in
SnapScroll {
VStack(alignment: .leading, spacing: 0) {
Text("SELECT DEVICE").font(Theme.mono(16)).foregroundColor(Theme.accent)
ForEach(groups, id: \.0) { header, types in
Text(header).font(Theme.mono(11)).foregroundColor(Theme.dim).padding(.top, 16).padding(.bottom, 2)
ForEach(types, id: \.type) { t in
Text(t.displayName).font(Theme.mono(18)).foregroundColor(Theme.text)
.padding(.vertical, 8)
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
.onTapGesture { onPick(t.type) }
}
}
}
.fixedSize(horizontal: true, vertical: false)
.padding(16)
.frame(maxWidth: .infinity, minHeight: geo.size.height, alignment: .top)
.contentShape(Rectangle())
.onTapGesture(perform: onDismiss) // anywhere but a device
}
}
.background(Theme.background.opacity(0.92))
}
}
@@ -0,0 +1,81 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// Toolbox navigation that outlives the tab (ToolboxScreen is rebuilt on each
/// switch): the tab to go back to when a slot editor opened from elsewhere closes
/// (Android's SlotEditorRequest.returnTab), and a counter that rebuilds the open
/// editor after its slot changed underneath it (a preset import).
@MainActor
final class ToolboxNav: ObservableObject {
static let shared = ToolboxNav()
var returnTab: AppModel.Tab?
@Published var editorEpoch = 0
/// Android's openSlotEditor: show [slot]'s settings over the Toolbox tab;
/// closing them returns to [returnTab].
static func open(_ slot: Int, app: AppModel, returnTab: AppModel.Tab?) {
guard slot >= 0, !app.session.type(ofSlot: slot).isEmpty else { return }
shared.returnTab = returnTab
app.editingSlot = slot
app.tab = .toolbox
}
func close(app: AppModel) {
app.editingSlot = nil
if let t = returnTab { app.tab = t }
returnTab = nil
}
}
/// Notes held on any on-screen keyboard or pad, for lighting keys (Android's heldNotes).
@MainActor
final class HeldNotes: ObservableObject {
static let shared = HeldNotes()
@Published private(set) var counts: [Int: Int] = [:]
func isHeld(_ midi: Int) -> Bool { (counts[midi] ?? 0) > 0 }
func on(_ midi: Int) { counts[midi, default: 0] += 1 }
func off(_ midi: Int) {
let n = (counts[midi] ?? 0) - 1
if n <= 0 { counts.removeValue(forKey: midi) } else { counts[midi] = n }
}
}
/// Waveform peaks per sample id, so redraws (marker drags) don't rescan the sample.
@MainActor
enum PeakCache {
private static var cache: [String: [Float]] = [:]
/// (min, max) pairs, interleaved; nil when the key holds no loaded sample.
static func peaks(slot: Int, key: String, buckets: Int = 400) -> [Float]? {
let session = SizzleSession.shared
let id = session.value(ofSlot: slot, key: key)
guard !id.isEmpty else { return nil }
let cacheKey = "\(id)|\(buckets)"
if let p = cache[cacheKey] { return p }
guard let data = session.samplePeaks(ofSlot: slot, key: key, buckets: buckets) else { return nil }
let p = data.withUnsafeBytes { Array($0.bindMemory(to: Float.self)) }
if cache.count > 64 { cache.removeAll() }
cache[cacheKey] = p
return p
}
}
/// Min/max waveform lines (the Sampler and SF2/XI previews).
struct WaveformShape: Shape {
let peaks: [Float]
func path(in r: CGRect) -> Path {
var p = Path()
let n = peaks.count / 2
guard n > 0 else { return p }
let bw = r.width / CGFloat(n), mid = r.height / 2
for i in 0..<n {
let x = r.minX + CGFloat(i) * bw
p.move(to: CGPoint(x: x, y: r.minY + mid - CGFloat(peaks[2 * i + 1]) * mid))
p.addLine(to: CGPoint(x: x, y: r.minY + mid - CGFloat(peaks[2 * i]) * mid + 0.5))
}
return p
}
}