iOS 0.3.0: card editors like Android's for every plugin (knobs, switches, tabs, drawings)

Layouts exported from Android's DeviceLayouts (DeviceLayouts.json), iOS layouts
for the devices with hand-built Android editors, SwiftUI editor shared by the
extension and the app, Mac snapshot tool for the editors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-15 22:41:33 +01:00
co-authored by Claude Opus 5.5
parent 47588990ce
commit b6589ee792
22 changed files with 1052 additions and 161 deletions
+77
View File
@@ -0,0 +1,77 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
/// Card layouts for the devices whose Android editor is hand-built (Android's
/// DeviceLayouts only has a one-card fallback for them), grouped the way those
/// Android editors group their controls.
enum BespokeLayouts {
typealias P = LayoutPanel
typealias V = LayoutPanel.Viz
static let pages: [String: [LayoutPage]] = [
"NES_SYNTH": [
LayoutPage(title: "Osc", panels: (0..<3).map { i in
P(title: "Oscillator \(i + 1)", tone: .SOURCE,
keys: ["osc\(i)wave", "osc\(i)level", "osc\(i)oct", "osc\(i)semi", "osc\(i)fine"])
} + [P(title: "Noise", tone: .SOURCE, keys: ["noise"])]),
LayoutPage(title: "Filter", panels: [
P(title: "Filter", tone: .FILTER, keys: ["cutoff", "reso", "keytrack", "fenvamt"],
viz: V(kind: "filter", cutoff: "cutoff", reso: "reso"), labels: ["fenvamt": "Env Amt"]),
P(title: "Filter envelope", tone: .ENV, keys: ["fatk", "fdec", "fsus", "frel"],
viz: V(kind: "envelope", a: "fatk", d: "fdec", s: "fsus", r: "frel")),
]),
LayoutPage(title: "Amp", panels: [
P(title: "Amp envelope", tone: .ENV, keys: ["attack", "decay", "sustain", "release"],
viz: V(kind: "envelope", a: "attack", d: "decay", s: "sustain", r: "release")),
]),
LayoutPage(title: "LFO", panels: [
P(title: "LFO", tone: .MOD, keys: ["lfowave", "lfodiv", "lfophase"],
viz: V(kind: "lfo", wave: "lfowave"), labels: ["lfodiv": "Rate", "lfophase": "Phase"]),
]),
LayoutPage(title: "Mod", panels: (0..<4).map { i in
P(title: "Mod slot \(i + 1)", tone: .MOD, keys: ["m\(i)src", "m\(i)dst", "m\(i)amt"],
labels: ["m\(i)src": "Source", "m\(i)dst": "Target", "m\(i)amt": "Amount"])
}),
],
"DELAY": [
LayoutPage(title: "Delay", panels: [
P(title: "Tape heads", tone: .MOD,
keys: (0..<4).flatMap { ["head\($0)On", "head\($0)Div"] },
labels: Dictionary(uniqueKeysWithValues: (0..<4).flatMap {
[("head\($0)On", "Head \($0 + 1)"), ("head\($0)Div", "Head \($0 + 1)")]
})),
P(title: "Loop", tone: .OUT, keys: ["feedback", "drywet", "tape"],
labels: ["drywet": "Mix", "tape": "Tape"]),
]),
],
"TAPE_ENGINE": [
LayoutPage(title: "Tape", panels: [
P(title: "Transport", tone: .SOURCE, keys: ["speed", "division"], labels: ["division": "Wow Sync"]),
P(title: "Wear", tone: .MOD, keys: ["wow", "flutter", "hiss"]),
]),
],
"MIX_TIGHTENER": [
LayoutPage(title: "Tightener", panels: [
P(title: "Strength", tone: .OUT, keys: ["strength"]),
]),
],
"GRANULAR": [
LayoutPage(title: "Glitch", panels: [
P(title: "Glitch", tone: .MOD, keys: ["intensity"]),
]),
],
"SAMPLER": [
LayoutPage(title: "Sampler", panels: [
P(title: "Output", tone: .OUT, keys: ["volume"]),
]),
],
"SOUNDFONT": [
LayoutPage(title: "Loader", panels: [
P(title: "Sample", tone: .SOURCE, keys: ["program", "loop", "loopXfade", "volume"],
labels: ["loopXfade": "Loop Fade"]),
P(title: "Envelope", tone: .ENV, keys: ["attack", "decay", "sustain", "release"],
viz: V(kind: "envelope", a: "attack", d: "decay", s: "sustain", r: "release")),
]),
],
]
}
+208
View File
@@ -0,0 +1,208 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// Sizzle's dark retro palette (Android's default theme) and the card tones.
enum Theme {
static let background = Color(red: 0.07, green: 0.08, blue: 0.09)
static let surface = Color(red: 0.11, green: 0.12, blue: 0.14)
static let grid = Color(white: 0.24)
static let text = Color(white: 0.92)
static let dim = Color(white: 0.58)
static let accent = Color(red: 0.96, green: 0.76, blue: 0.29)
static func tone(_ t: LayoutPanel.Tone) -> Color {
switch t {
case .SOURCE: return accent
case .FILTER: return Color(red: 0.45, green: 0.85, blue: 0.55)
case .ENV: return Color(red: 0.96, green: 0.56, blue: 0.69)
case .MOD: return Color(red: 0.70, green: 0.62, blue: 1.0)
case .OUT: return text
}
}
static func mono(_ size: CGFloat) -> Font { .system(size: size, design: .monospaced) }
}
/// A rotary knob like Android's: slide up/down to turn (a full sweep takes 280 pt,
/// independent of the knob's size, so fine moves are easy), double-tap to reset.
/// Bipolar ranges fill from the centre.
struct KnobView: View {
let label: String
let valueText: String
let value: Float
let min: Float
let max: Float
let def: Float
let tone: Color
let onChange: (Float) -> Void
@State private var dragStart: Float?
private let travel: Float = 280
var body: some View {
let span = max > min ? max - min : 1
let frac = CGFloat(Swift.min(1, Swift.max(0, (value - min) / span)))
let zero = CGFloat(Swift.min(1, Swift.max(0, (0 - min) / span)))
let bipolar = min < 0 && max > 0
VStack(spacing: 3) {
Text(valueText).font(Theme.mono(10)).foregroundColor(Theme.text).lineLimit(1).minimumScaleFactor(0.7)
ZStack {
Arc(from: 0, to: 1).stroke(Theme.grid, style: StrokeStyle(lineWidth: 4, lineCap: .round))
Arc(from: bipolar ? Swift.min(zero, frac) : 0, to: bipolar ? Swift.max(zero, frac) : frac)
.stroke(tone, style: StrokeStyle(lineWidth: 4, lineCap: .round))
Pointer(frac: frac).stroke(Theme.text, style: StrokeStyle(lineWidth: 2, lineCap: .round))
}
.frame(width: 46, height: 46)
.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 1)
.onChanged { g in
if dragStart == nil { dragStart = value }
let v = (dragStart ?? value) - Float(g.translation.height) / travel * span
onChange(Swift.min(max, Swift.max(min, v)))
}
.onEnded { _ in dragStart = nil })
.onTapGesture(count: 2) { onChange(def) }
Text(label.uppercased()).font(Theme.mono(9)).foregroundColor(Theme.dim).lineLimit(1).minimumScaleFactor(0.7)
}
.frame(maxWidth: .infinity)
}
/// 270° arc from bottom-left (135°) clockwise, between fractions [from]..[to].
private struct Arc: Shape {
let from: CGFloat, to: CGFloat
func path(in r: CGRect) -> Path {
var p = Path()
let c = CGPoint(x: r.midX, y: r.midY), rad = Swift.min(r.width, r.height) / 2 - 2
p.addArc(center: c, radius: rad, startAngle: .degrees(135 + 270 * from),
endAngle: .degrees(135 + 270 * to), clockwise: false)
return p
}
}
private struct Pointer: Shape {
let frac: CGFloat
func path(in r: CGRect) -> Path {
let c = CGPoint(x: r.midX, y: r.midY), rad = Swift.min(r.width, r.height) / 2 * 0.8
let a = (135 + 270 * frac) * .pi / 180
var p = Path()
p.move(to: c)
p.addLine(to: CGPoint(x: c.x + rad * cos(a), y: c.y + rad * sin(a)))
return p
}
}
}
/// A short choice list as a row of buttons.
struct SegmentedView: View {
let label: String
let choices: [String]
let selected: Int
let tone: Color
let onSelect: (Int) -> Void
var body: some View {
VStack(alignment: .leading, spacing: 3) {
Text(label.uppercased()).font(Theme.mono(9)).foregroundColor(Theme.dim)
HStack(spacing: 0) {
ForEach(choices.indices, id: \.self) { i in
let on = i == selected
Text(choices[i]).font(Theme.mono(11)).lineLimit(1).minimumScaleFactor(0.6)
.foregroundColor(on ? tone : Theme.dim)
.frame(maxWidth: .infinity, minHeight: 30)
.background(on ? tone.opacity(0.22) : Color.clear)
.overlay(Rectangle().stroke(on ? tone : Theme.grid.opacity(0.6), lineWidth: 0.5))
.contentShape(Rectangle())
.onTapGesture { onSelect(i) }
}
}
.overlay(Rectangle().stroke(Theme.grid, lineWidth: 1))
}
}
}
/// A long choice list as a menu.
struct ChoiceMenu: View {
let label: String
let choices: [String]
let selected: Int
let tone: Color
let onSelect: (Int) -> Void
var body: some View {
Menu {
ForEach(choices.indices, id: \.self) { i in Button(choices[i]) { onSelect(i) } }
} label: {
HStack {
Text(label.uppercased() + ":").foregroundColor(Theme.dim)
Text(choices.indices.contains(selected) ? choices[selected] : "").foregroundColor(Theme.text)
Spacer(minLength: 4)
Text("▾").foregroundColor(tone)
}
.font(Theme.mono(11))
.padding(.horizontal, 8).frame(minHeight: 30)
.overlay(Rectangle().stroke(Theme.grid, lineWidth: 1))
}
}
}
/// An on/off switch (stored as 0 / 1).
struct ToggleChip: View {
let label: String
let on: Bool
let tone: Color
let onToggle: () -> Void
var body: some View {
Text(label.uppercased()).font(Theme.mono(10)).lineLimit(1)
.foregroundColor(on ? tone : Theme.dim)
.frame(maxWidth: .infinity, minHeight: 30)
.background(on ? tone.opacity(0.22) : Color.clear)
.overlay(Rectangle().stroke(on ? tone : Theme.grid, lineWidth: 1))
.contentShape(Rectangle())
.onTapGesture(perform: onToggle)
}
}
/// Vertical bipolar faders (the graphic EQ): drag or tap to set, double-tap to zero.
struct FaderBank: View {
let infos: [ParamInfo]
let captions: [String]
let scale: Float
let tone: Color
@ObservedObject var model: DeviceModel
var body: some View {
HStack(spacing: 3) {
ForEach(infos.indices, id: \.self) { i in
let p = infos[i]
let v = model.value(p.key)
VStack(spacing: 2) {
let shown = v * scale
Text((shown > 0.05 ? "+" : "") + String(format: "%.0f", shown)).font(Theme.mono(9)).foregroundColor(Theme.text)
GeometryReader { g in
let span = p.max - p.min
let zeroY = g.size.height * CGFloat(1 - (0 - p.min) / span)
let y = g.size.height * CGFloat(1 - (v - p.min) / span)
ZStack(alignment: .topLeading) {
Rectangle().fill(Theme.background)
Rectangle().fill(tone.opacity(0.45))
.frame(height: abs(zeroY - y)).offset(y: Swift.min(y, zeroY))
Rectangle().fill(tone).frame(height: 4).offset(y: y - 2)
}
.overlay(Rectangle().stroke(Theme.grid, lineWidth: 1))
.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 0).onChanged { d in
let f = Float(1 - Swift.min(1, Swift.max(0, d.location.y / g.size.height)))
model.set(p.key, p.min + f * span)
})
.onTapGesture(count: 2) { model.set(p.key, p.def) }
}
.frame(height: 140)
Text(i < captions.count ? captions[i] : "").font(Theme.mono(9)).foregroundColor(Theme.dim)
}
}
}
}
}
+148
View File
@@ -0,0 +1,148 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
#if canImport(UIKit)
import UIKit
#endif
/// A device's editor, like the Android app's: tabs of titled cards, each tinted by
/// its role, with knobs for numbers, switches for short choices, menus for long
/// ones, faders for the EQ and live drawings. Used by the plugin extension and by
/// the app for the devices it hosts.
struct DeviceEditor: View {
@StateObject var model: DeviceModel
@State var page = 0
/// Render without a ScrollView (the Mac snapshot tool; ImageRenderer can't draw one).
static var snapshot = false
var body: some View {
let pages = Layouts.pages(for: model.au.toolboxType, allKeys: model.order)
VStack(alignment: .leading, spacing: 8) {
HStack {
Text(model.au.displayName.uppercased()).font(Theme.mono(15)).foregroundColor(Theme.accent)
Spacer()
if let presets = model.au.factoryPresets, !presets.isEmpty {
Menu {
ForEach(presets, id: \.number) { p in Button(p.name) { model.applyPreset(p) } }
} label: {
Text("PRESET: \(model.presetName ?? "—") ▾").font(Theme.mono(12)).foregroundColor(Theme.accent)
}
}
}
if pages.count > 1 {
HStack(spacing: 4) {
ForEach(pages.indices, id: \.self) { i in
let on = i == page
let tone = Theme.tone(pages[i].panels.first?.tone ?? .SOURCE)
Text(pages[i].title.uppercased()).font(Theme.mono(pages.count > 5 ? 10 : 12))
.lineLimit(1).minimumScaleFactor(0.7)
.foregroundColor(on ? tone : Theme.dim)
.frame(maxWidth: .infinity, minHeight: 30)
.background(on ? tone.opacity(0.22) : Theme.surface)
.overlay(Rectangle().stroke(on ? tone : Theme.grid, lineWidth: 1))
.contentShape(Rectangle())
.onTapGesture { page = i }
}
}
}
let cards = VStack(spacing: 8) {
ForEach(pages[Swift.min(page, pages.count - 1)].panels) { panel in
CardView(panel: panel, model: model)
}
}
if DeviceEditor.snapshot { cards; Spacer(minLength: 0) } else { ScrollView { cards } }
}
.padding(10)
.background(Theme.background)
}
}
/// One card: header, optional drawing, then choices, switches and knobs (or faders).
struct CardView: View {
let panel: LayoutPanel
@ObservedObject var model: DeviceModel
var body: some View {
let tone = Theme.tone(panel.tone)
let infos = panel.keys.compactMap { model.params[$0] }
let enums = infos.filter { $0.isEnum }
let segmented = enums.filter { $0.choices.count <= 6 && $0.choices.joined().count <= 34 }
let menus = enums.filter { !($0.choices.count <= 6 && $0.choices.joined().count <= 34) }
let toggles = infos.filter { $0.isToggle }
let knobs = infos.filter { !$0.isEnum && !$0.isToggle }
VStack(alignment: .leading, spacing: 7) {
HStack(spacing: 6) {
Rectangle().fill(tone).frame(width: 8, height: 8)
Text(panel.title.uppercased()).font(Theme.mono(11)).foregroundColor(tone)
}
if let viz = panel.viz, viz.kind != "wavetable" {
VizView(viz: viz, tone: tone, model: model)
}
if let captions = panel.faders {
FaderBank(infos: infos, captions: captions, scale: panel.faderScale ?? 1, tone: tone, model: model)
} else {
ForEach(Array(stride(from: 0, to: menus.count, by: 2)), id: \.self) { i in
HStack(spacing: 8) {
ForEach(menus[i..<Swift.min(i + 2, menus.count)], id: \.key) { p in
ChoiceMenu(label: Format.shortLabel(p, labels: panel.labels), choices: p.choices,
selected: Int(model.value(p.key).rounded()), tone: tone) { model.set(p.key, Float($0)) }
}
}
}
ForEach(segmented, id: \.key) { p in
SegmentedView(label: Format.shortLabel(p, labels: panel.labels), choices: p.choices,
selected: Int(model.value(p.key).rounded()), tone: tone) { model.set(p.key, Float($0)) }
}
if !toggles.isEmpty {
HStack(spacing: 6) {
ForEach(toggles, id: \.key) { p in
ToggleChip(label: Format.shortLabel(p, labels: panel.labels), on: model.value(p.key) >= 0.5,
tone: tone) { model.set(p.key, model.value(p.key) >= 0.5 ? 0 : 1) }
}
}
}
knobRows(knobs, tone: tone)
}
}
.padding(.horizontal, 8).padding(.vertical, 7)
.background(Theme.surface)
.overlay(Rectangle().stroke(tone.opacity(0.35), lineWidth: 1))
}
/// Up to six knobs a row, rows evenly filled, centred (Android's PanelCard).
@ViewBuilder private func knobRows(_ knobs: [ParamInfo], tone: Color) -> some View {
let n = knobs.count
if n > 0 {
let perRow = n <= 6 ? n : Int(ceil(Double(n) / ceil(Double(n) / 6)))
let slots = Swift.max(perRow, 4)
ForEach(Array(stride(from: 0, to: n, by: perRow)), id: \.self) { start in
let row = Array(knobs[start..<Swift.min(start + perRow, n)])
HStack(spacing: 4) {
let pad = slots - row.count
ForEach(0..<(pad / 2), id: \.self) { _ in Color.clear.frame(maxWidth: .infinity, maxHeight: 1) }
ForEach(row, id: \.key) { p in
KnobView(label: Format.shortLabel(p, labels: panel.labels),
valueText: Format.value(p, model.value(p.key)),
value: model.value(p.key), min: p.min, max: p.max, def: p.def, tone: tone) { model.set(p.key, $0) }
}
ForEach(0..<(pad - pad / 2), id: \.self) { _ in Color.clear.frame(maxWidth: .infinity, maxHeight: 1) }
}
}
}
}
}
#if canImport(UIKit)
/// For the Objective-C view controller: the editor for [au] in a hosting controller.
@objc(SizzleEditorFactory)
@MainActor
public final class SizzleEditorFactory: NSObject {
@objc public static func makeEditor(for au: SizzleDeviceAU) -> UIViewController {
let vc = UIHostingController(rootView: DeviceEditor(model: DeviceModel(au: au)))
vc.view.backgroundColor = UIColor(red: 0.07, green: 0.08, blue: 0.09, alpha: 1)
return vc
}
}
#endif
+86
View File
@@ -0,0 +1,86 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import AudioToolbox
import Foundation
/// One parameter as the editor sees it: the AU parameter plus what Sizzle's spec
/// says about it (default, whole numbers, label).
struct ParamInfo {
let param: AUParameter
let key: String
let label: String
let min: Float
let max: Float
let def: Float
let isInt: Bool
let choices: [String]
var isEnum: Bool { !choices.isEmpty }
/// On/off switches stored as 0..1 numbers (the Tape Delay's "Head N On").
var isToggle: Bool { !isEnum && key.hasSuffix("On") && min == 0 && max == 1 }
}
/// The editor's view of a SizzleDeviceAU: every parameter's value, kept in step
/// with the AU (host automation, presets) through a parameter observer.
@MainActor
final class DeviceModel: ObservableObject {
let au: SizzleDeviceAU
let params: [String: ParamInfo]
let order: [String]
@Published private(set) var values: [String: Float] = [:]
@Published var presetName: String?
private var token: AUParameterObserverToken?
init(au: SizzleDeviceAU) {
self.au = au
var params: [String: ParamInfo] = [:]
var order: [String] = []
var values: [String: Float] = [:]
for p in au.parameterTree?.allParameters ?? [] {
let info = ParamInfo(param: p, key: p.identifier, label: au.specLabel(for: p),
min: p.minValue, max: p.maxValue, def: au.defaultValue(for: p),
isInt: au.isIntegerParameter(p), choices: p.valueStrings ?? [])
params[p.identifier] = info
order.append(p.identifier)
values[p.identifier] = p.value
}
self.params = params
self.order = order
self.values = values
presetName = au.currentPreset?.name
token = au.parameterTree?.token(byAddingParameterObserver: { [weak self] address, value in
DispatchQueue.main.async { self?.observed(address: address, value: value) }
})
}
deinit {
if let token = token { au.parameterTree?.removeParameterObserver(token) }
}
private func observed(address: AUParameterAddress, value: AUValue) {
guard let p = au.parameterTree?.parameter(withAddress: address) else { return }
values[p.identifier] = value
}
func value(_ key: String) -> Float { values[key] ?? params[key]?.def ?? 0 }
func set(_ key: String, _ v: Float) {
guard let info = params[key] else { return }
var x = Swift.min(Swift.max(v, info.min), info.max)
if info.isInt { x = x.rounded() }
values[key] = x
info.param.setValue(x, originator: token)
}
func choice(_ key: String) -> String {
guard let info = params[key], info.isEnum else { return "" }
let i = Int(value(key).rounded())
return info.choices[Swift.max(0, Swift.min(info.choices.count - 1, i))]
}
func applyPreset(_ preset: AUAudioUnitPreset) {
au.currentPreset = preset
presetName = preset.name
for (key, info) in params { values[key] = info.param.value }
}
}
+56
View File
@@ -0,0 +1,56 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
/// Captions and value text, as Android's Panels.kt shortLabel() / formatParam().
enum Format {
private static let prefix = try! NSRegularExpression(pattern: "^(Osc\\s?\\d|Mod\\d?|LFO|Duck|F\\.)\\s+")
private static let unit = try! NSRegularExpression(pattern: "\\s*\\((dB|ms|s)\\)|\\s+s$")
private static let arrow = try! NSRegularExpression(pattern: "^.*>\\s*")
private static let timeKeys: Set<String> = ["attack", "decay", "release", "mattack", "mdecay", "mrelease", "fatk", "fdec", "frel"]
private static let divisionKeys: Set<String> = ["division", "lfodiv"]
private static let keyUnits: [String: String] = [
"predelay": "ms", "modrate": "Hz", "mtime": "s", "loopXfade": "ms",
"pitch": "st", "pitch_rand": "st", "semitones": "st", "o1semi": "st", "o2semi": "st",
"o1fine": "ct", "o2fine": "ct", "roomsize": "×",
]
private static func replace(_ re: NSRegularExpression, _ s: String, _ with: String) -> String {
re.stringByReplacingMatches(in: s, range: NSRange(s.startIndex..., in: s), withTemplate: with)
}
/// A control's caption: the card's override, else the label without its section
/// prefix ("Osc1 Level" → "Level", "LFO > Pitch" → "→ Pitch") or unit.
static func shortLabel(_ p: ParamInfo, labels: [String: String]?) -> String {
if let l = labels?[p.key] { return l }
return replace(arrow, replace(prefix, replace(unit, p.label, ""), ""), "→ ")
}
private static func roundToInt(_ v: Float) -> Int { Int((Double(v) + 0.5).rounded(.down)) }
/// How a value reads under its knob: time in ms / s, 0..1 as %, divisions by name.
static func value(_ p: ParamInfo, _ v: Float) -> String {
if p.isEnum { let i = max(0, min(p.choices.count - 1, roundToInt(v))); return p.choices[i] }
if p.key.hasSuffix("Div"), let names = Layouts.file?.delayDivisions {
return names[max(0, min(names.count - 1, Int(v)))]
}
if divisionKeys.contains(p.key), let names = Layouts.file?.timeDivisions {
return names[max(0, min(names.count - 1, roundToInt(v)))]
}
let u = keyUnits[p.key] ?? (p.label.contains("(dB)") ? "dB" : p.label.contains("(ms)") ? "ms" : "")
func signed(_ s: String, _ x: Float) -> String { p.min < 0 && x > 0 ? "+" + s : s }
if p.isInt { return signed("\(roundToInt(v))", v) + u }
if timeKeys.contains(p.key) && p.max > 1 {
if v < 1 { return "\(roundToInt(v * 1000))ms" }
return String(format: v < 10 ? "%.2fs" : "%.1fs", v)
}
if !u.isEmpty {
let f = (u == "ms" || u == "ct" || abs(v) >= 100) ? "%.0f" : (u == "Hz" || u == "×") ? "%.2f" : "%.1f"
return signed(String(format: f, v), v) + u
}
if p.min == 0 && p.max == 1 { return "\(roundToInt(v * 100))%" }
if p.min == -1 && p.max == 1 { return signed("\(roundToInt(v * 100))", v) + "%" }
return signed(String(format: "%.2f", v), v)
}
}
+57
View File
@@ -0,0 +1,57 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import Foundation
/// A device editor's tabs and cards, as Android's DeviceLayouts describes them
/// (exported to DeviceLayouts.json by IosGoldenExport) or, for devices whose
/// Android editor is hand-built, as BespokeLayouts.swift lays them out.
struct LayoutPage: Decodable, Identifiable {
let title: String
let panels: [LayoutPanel]
var id: String { title }
}
struct LayoutPanel: Decodable, Identifiable {
enum Tone: String, Decodable { case SOURCE, FILTER, ENV, MOD, OUT }
struct Viz: Decodable {
let kind: String // envelope | filter | lfo | wavetable
var a: String? = nil, d: String? = nil, s: String? = nil, r: String? = nil
var type: String? = nil, cutoff: String? = nil, reso: String? = nil
var wave: String? = nil
var osc: Int? = nil
}
let title: String
let tone: Tone
let keys: [String]
var viz: Viz? = nil
var labels: [String: String]? = nil
var faders: [String]? = nil
var faderScale: Float? = nil
var action: String? = nil
var id: String { title }
}
struct DeviceLayoutsFile: Decodable {
let devices: [String: [LayoutPage]]
let timeDivisions: [String]
let delayDivisions: [String]
}
enum Layouts {
/// Bundled with both the extension and the app (each finds its own copy).
static let file: DeviceLayoutsFile? = {
let bundle = Bundle(for: SizzleDeviceAU.self)
guard let url = bundle.url(forResource: "DeviceLayouts", withExtension: "json"),
let data = try? Data(contentsOf: url) else { return nil }
return try? JSONDecoder().decode(DeviceLayoutsFile.self, from: data)
}()
static func pages(for type: String, allKeys: [String]) -> [LayoutPage] {
if let bespoke = BespokeLayouts.pages[type] { return bespoke }
if let pages = file?.devices[type], !pages.isEmpty { return pages }
return [LayoutPage(title: type, panels: [LayoutPanel(title: type, tone: .SOURCE, keys: allKeys)])]
}
}
+97
View File
@@ -0,0 +1,97 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// The live drawing at the top of a card (Android's VizCanvas): an envelope's
/// shape, a filter's response, or two cycles of an LFO wave.
struct VizView: View {
let viz: LayoutPanel.Viz
let tone: Color
@ObservedObject var model: DeviceModel
private func num(_ key: String?) -> Float? {
guard let k = key, let p = model.params[k] else { return nil }
return Swift.min(p.max, Swift.max(p.min, model.value(k)))
}
private func frac(_ key: String?) -> Float? {
guard let k = key, let p = model.params[k], let v = num(k) else { return nil }
return (v - p.min) / (p.max - p.min)
}
var body: some View {
Canvas { ctx, size in
let w = size.width, h = size.height
let top = h * 0.12, bottom = h * 0.92
var path = Path()
switch viz.kind {
case "envelope":
let a = CGFloat(sqrt(frac(viz.a) ?? 0)) + 0.02
let d = viz.d != nil ? CGFloat(sqrt(frac(viz.d) ?? 0)) + 0.02 : 0
let s = viz.s != nil ? CGFloat(num(viz.s) ?? 1) : 1
let r = CGFloat(sqrt(frac(viz.r) ?? 0)) + 0.02
let hold: CGFloat = 0.45
let k = w / (a + d + hold + r)
let sy = bottom - (bottom - top) * s
path.move(to: CGPoint(x: 0, y: bottom))
path.addLine(to: CGPoint(x: a * k, y: top))
path.addLine(to: CGPoint(x: (a + d) * k, y: sy))
path.addLine(to: CGPoint(x: (a + d + hold) * k, y: sy))
path.addLine(to: CGPoint(x: w, y: bottom))
line(ctx, CGPoint(x: (a + d + hold) * k, y: top), CGPoint(x: (a + d + hold) * k, y: bottom))
case "filter":
let fc = Double(frac(viz.cutoff) ?? 0.5)
let q = 0.6 + Double(frac(viz.reso) ?? 0) * 9
let kind = viz.type.map { model.choice($0).uppercased().first ?? "L" } ?? "L"
for i in 0...96 {
let x = Double(i) / 96
let r = pow(2.0, (x - fc) * 10)
let den = sqrt(pow(1 - r * r, 2) + pow(r / q, 2))
let mag = kind == "H" ? r * r / den : kind == "B" ? (r / q) / den : 1 / den
let db = Swift.min(20, Swift.max(-30, 20 * log10(Swift.max(mag, 1e-4))))
let y = top + CGFloat((20 - db) / 50) * (bottom - top)
if i == 0 { path.move(to: CGPoint(x: 0, y: y)) } else { path.addLine(to: CGPoint(x: CGFloat(x) * w, y: y)) }
}
let zeroY = top + 20 / 50 * (bottom - top)
line(ctx, CGPoint(x: 0, y: zeroY), CGPoint(x: w, y: zeroY))
line(ctx, CGPoint(x: CGFloat(fc) * w, y: top), CGPoint(x: CGFloat(fc) * w, y: bottom))
case "lfo":
let name = viz.wave.map { model.choice($0).lowercased() } ?? "sine"
let sh: [CGFloat] = [0.6, -0.3, 0.9, -0.8, 0.2, -0.5, 0.75, -0.1]
for i in 0...160 {
let x = CGFloat(i) / 160
let p = (x * 2).truncatingRemainder(dividingBy: 1)
let v: CGFloat
if name.hasPrefix("tri") { v = 1 - 4 * abs(p - 0.5) }
else if name.hasPrefix("saw") { v = 1 - 2 * p }
else if name.hasPrefix("sq") { v = p < 0.5 ? 1 : -1 }
else if name.hasPrefix("s&h") || name.hasPrefix("sample") { v = sh[Swift.min(7, Int(x * 8))] }
else { v = sin(2 * .pi * p) }
let y = (top + bottom) / 2 - v * (bottom - top) / 2
if i == 0 { path.move(to: CGPoint(x: 0, y: y)) } else { path.addLine(to: CGPoint(x: x * w, y: y)) }
}
line(ctx, CGPoint(x: 0, y: (top + bottom) / 2), CGPoint(x: w, y: (top + bottom) / 2))
default:
return
}
if viz.kind != "lfo" {
var fill = path
fill.addLine(to: CGPoint(x: w, y: h))
fill.addLine(to: CGPoint(x: 0, y: h))
fill.closeSubpath()
ctx.fill(fill, with: .color(tone.opacity(0.15)))
}
ctx.stroke(path, with: .color(tone), lineWidth: 2)
}
.frame(height: 56)
.background(Theme.background)
.overlay(Rectangle().stroke(Theme.grid, lineWidth: 1))
}
private func line(_ ctx: GraphicsContext, _ a: CGPoint, _ b: CGPoint) {
var p = Path()
p.move(to: a)
p.addLine(to: b)
ctx.stroke(p, with: .color(Theme.grid), lineWidth: 1)
}
}