diff --git a/ios/CHANGELOG.md b/ios/CHANGELOG.md index 3df6ea8..9f2fef2 100644 --- a/ios/CHANGELOG.md +++ b/ios/CHANGELOG.md @@ -3,6 +3,27 @@ Sizzle for iOS/iPadOS (`cc.tiredsysadmin.ios.sizzle`). One entry per version in `../versions.properties` (`ios.versionName` / `ios.versionCode`). +## 0.4.0 (build 8) + +- Sizzle itself on iOS: the Tracker, Mix, Toolbox and Setup tabs, ported from + the Android app, playing songs through the C++ engine. + - Tracker: transport (tap tempo on the BPM), block / length / signature / + scale / root, the pattern grid with cursor, playhead follow, selection, + cut / copy / paste / clear, note-offs, skip step, the punch-in keyboard, and + the arrangement roll with lane mutes, FILL / CLEAR / OFF, loop A/B repeats. + - Mix: four strips with instrument and FX routing, MIDI channel, volume, + limiter, mute / solo and level meters. + - Toolbox: 16 slots, device picker, the card editors with a preset library + (factory presets, save / delete / import / share), audition keyboard, + Sampler pads (import WAV, slice, trim, normalize, pad volumes), SF2/XI + loading, the MIDI LFO's target. + - Setup: song browser (load / save / new / delete), import and export of + projects (.szg) and .sng, MIDI panic, help, the device lab and plugin check. +- Songs open from and save to the Android project format, autosave when the app + goes to the background, and reopen at launch. +- Not yet: MIDI input and clock sync, hardware keyboard and gamepad, recording, + themes, backups and sample-carrying project bundles. + ## 0.3.1 (build 7) - Fix: a sample loaded into the Sampler or the SF2/XI loader stayed silent. Its diff --git a/ios/README.md b/ios/README.md index 8ac8d3d..6d93900 100644 --- a/ios/README.md +++ b/ios/README.md @@ -12,6 +12,8 @@ Makefile (`make -C ios help`). | `core/tests/golden_test.cpp` | Compares the core with audio the Kotlin code renders | | `app/components.txt` | The plugin list (AU type, subtype, device, name) | | `app/FX/` | The plugin extension: `SizzleDeviceAU` (shared: parameters, presets, state), `SizzleEffectAU` (aufx), `SizzleInstrumentAU` (aumu), `SizzleFXViewController` (factory + editor). The app compiles the same classes to host them itself | +| `app/Host/SizzleSession*` | The bridge to the C++ song + engine (audio output, song lock, live-note queue); one category per screen | +| `app/Host/Screens/` | Tracker, Mix, Toolbox, Setup (SwiftUI, ported from the Android tabs); `make screen-snapshots` renders them on the Mac | | `app/Host/` | The app: `SizzleHost` plays the devices in-process (instrument → effect → output, keyboard, MIDI in, samples, benchmark); `PluginCheck` checks the extension's plugins | | `app/tests/au_test.mm` | Mac-side test of the AUv3 wrapper | | `app/FX/Editor/` | The SwiftUI device editor (cards, knobs, drawings), from `DeviceLayouts.json` (exported from Android) and `BespokeLayouts.swift` | diff --git a/ios/app/FX/Editor/DeviceEditor.swift b/ios/app/FX/Editor/DeviceEditor.swift index c1b1f85..85274e4 100644 --- a/ios/app/FX/Editor/DeviceEditor.swift +++ b/ios/app/FX/Editor/DeviceEditor.swift @@ -13,18 +13,23 @@ import UIKit struct DeviceEditor: View { @StateObject var model: DeviceModel @State var page = 0 + /// The device name and preset menu row; off where the host draws its own + /// (the app's slot editor has a preset bar of its own). + var showsHeader = true var body: some View { let pages = Layouts.pages(for: model.toolboxType, allKeys: model.order) VStack(alignment: .leading, spacing: 8) { - HStack { - Text(model.displayName.uppercased()).font(Theme.mono(15)).foregroundColor(Theme.accent) - Spacer() - if !model.presetNames.isEmpty { - Menu { - ForEach(model.presetNames, id: \.self) { name in Button(name) { model.applyPreset(named: name) } } - } label: { - Text("PRESET: \(model.presetName ?? "—") ▾").font(Theme.mono(12)).foregroundColor(Theme.accent) + if showsHeader { + HStack { + Text(model.displayName.uppercased()).font(Theme.mono(15)).foregroundColor(Theme.accent) + Spacer() + if !model.presetNames.isEmpty { + Menu { + ForEach(model.presetNames, id: \.self) { name in Button(name) { model.applyPreset(named: name) } } + } label: { + Text("PRESET: \(model.presetName ?? "—") ▾").font(Theme.mono(12)).foregroundColor(Theme.accent) + } } } } diff --git a/ios/app/Host/AppModel.swift b/ios/app/Host/AppModel.swift index 7a0e928..991415d 100644 --- a/ios/app/Host/AppModel.swift +++ b/ios/app/Host/AppModel.swift @@ -33,8 +33,8 @@ final class AppModel: ObservableObject { // On-screen keyboard (Android: kbdChannel / kbdOctave / kbdVelocity). @Published var kbdChannel = 1 - @Published var kbdOctave = 4 - @Published var kbdVelocity = 100 + @Published var kbdOctave = 3 + @Published var kbdVelocity = 127 /// The toolbox slot whose editor is open, if any. @Published var editingSlot: Int? diff --git a/ios/app/Host/Screens/Mix/MixKit.swift b/ios/app/Host/Screens/Mix/MixKit.swift new file mode 100644 index 0000000..d538c41 --- /dev/null +++ b/ios/app/Host/Screens/Mix/MixKit.swift @@ -0,0 +1,208 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// The Mix and Toolbox screens' building blocks, ported from Android's +/// components/Widgets.kt (RetroButton, RepeatButton, RetroDropdown, SectionLabel). +/// Namespaced so they can't clash with the other screens' own. +enum MixKit { + /// Android palette colours the shared Theme doesn't carry. + static let playhead = Color(red: 0x7C / 255, green: 0xFC / 255, blue: 0x9A / 255) + static let danger = Color(red: 0xE0 / 255, green: 0x5A / 255, blue: 0x4B / 255) + + /// Pitch.name: 60 -> "C-4", 61 -> "C#4". + static func pitchName(_ midi: Int) -> String { + guard (0...127).contains(midi) else { return "..." } + let names = ["C-", "C#", "D-", "D#", "E-", "F-", "F#", "G-", "G#", "A-", "A#", "B-"] + return names[midi % 12] + String(midi / 12 - 1) + } + + /// RetroButtonSurface: square corners, 1 pt border, accent when active, red for danger. + struct Face: View { + let label: String + var active = false + var danger = false + var width: CGFloat? = nil + var fill = false + + var body: some View { + let hue: Color? = danger ? MixKit.danger : (active ? Theme.accent : nil) + Text(label).font(Theme.mono(12)).lineLimit(1).truncationMode(.tail) + .foregroundColor(hue ?? Theme.text) + .padding(.horizontal, 10).padding(.vertical, 6) + .frame(width: width) + .frame(maxWidth: fill ? .infinity : nil) + .background(hue?.opacity(0.18) ?? Theme.surface) + .overlay(Rectangle().stroke(hue ?? Theme.grid, lineWidth: 1)) + .contentShape(Rectangle()) + } + } + + /// RetroButton: tap to act. + struct Button: View { + let label: String + var active = false + var danger = false + var width: CGFloat? = nil + var fill = false + let action: () -> Void + + var body: some View { + Face(label: label, active: active, danger: danger, width: width, fill: fill) + .onTapGesture(perform: action) + } + } + + /// RepeatButton: steps once on press, then repeats while held, faster and faster + /// (320 ms, ×0.8 each time, down to 24 ms). Dragging off stops it. + struct RepeatButton: View { + let label: String + var width: CGFloat? = nil + let onStep: () -> Void + @StateObject private var repeater = Repeater() + + var body: some View { + Face(label: label, width: width) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { g in + if abs(g.translation.width) > 24 || abs(g.translation.height) > 24 { repeater.stop() } + else if !repeater.pressed { repeater.start(onStep) } + } + .onEnded { _ in repeater.stop(); repeater.pressed = false }) + } + } + + @MainActor final class Repeater: ObservableObject { + var pressed = false + private var timer: Timer? + private var delay = 0.32 + private var step: (() -> Void)? + + func start(_ step: @escaping () -> Void) { + pressed = true + self.step = step + delay = 0.32 + step() + schedule() + } + + private func schedule() { + timer = Timer.scheduledTimer(withTimeInterval: delay, repeats: false) { [weak self] _ in + Task { @MainActor in self?.fire() } + } + } + + private func fire() { + guard timer != nil, let step = step else { return } + step() + delay = max(0.024, delay * 0.8) + schedule() + } + + func stop() { + timer?.invalidate() + timer = nil + step = nil + } + } + + /// SectionLabel: a dim upper-case header. + struct SectionLabel: View { + let text: String + var body: some View { + Text(text.uppercased()).font(Theme.mono(11)).foregroundColor(Theme.dim).padding(.vertical, 4) + } + } + + /// RetroDropdown: `LABEL:value ▾`, as wide as its longest option so it never + /// jumps. Tap opens the list (in balanced columns past 12 rows, like Android's); + /// an optional long press does something else (the mixer opens the device). + struct Dropdown: View { + let label: String + let options: [T] + let selected: T + var fill = false + let optionLabel: (T) -> String + var onLongPress: (() -> Void)? = nil + let onSelect: (T) -> Void + @State private var open = false + + var body: some View { + let prefix = label.isEmpty ? "" : label + ":" + let longest = options.map(optionLabel).max { $0.count < $1.count } ?? "" + ZStack(alignment: .leading) { + Text(prefix + longest + " ▾").foregroundColor(.clear) + Text(prefix + optionLabel(selected) + " ▾").foregroundColor(Theme.text).truncationMode(.tail) + } + .font(Theme.mono(12)).lineLimit(1) + .padding(.horizontal, 8).padding(.vertical, 6) + .frame(maxWidth: fill ? .infinity : nil, alignment: .leading) + .background(Theme.surface) + .overlay(Rectangle().stroke(Theme.grid, lineWidth: 1)) + .contentShape(Rectangle()) + .onTapGesture { open = true } + .onLongPressGesture { onLongPress?() } + .popover(isPresented: $open) { menu } + } + + private static var maxRows: Int { 12 } + + @ViewBuilder private var menu: some View { + let n = options.count + let cols = n <= Self.maxRows ? 1 : (n + Self.maxRows - 1) / Self.maxRows + if cols <= 4 { + let perCol = (n + cols - 1) / Swift.max(cols, 1) + HStack(alignment: .top, spacing: 0) { + ForEach(0.. some View { + Text(optionLabel(opt)).font(Theme.mono(13)).lineLimit(1) + .foregroundColor(opt == selected ? Theme.accent : Theme.text) + .padding(.horizontal, 12).padding(.vertical, 8) + .frame(maxWidth: .infinity, alignment: .leading) + .contentShape(Rectangle()) + .onTapGesture { onSelect(opt); open = false } + } + } + + /// A horizontal ScrollView, or a plain row while snapshotting. + struct HScroll: View { + @ViewBuilder let content: () -> Content + var body: some View { + if Snapshot.active { content() } + else { ScrollView(.horizontal, showsIndicators: false) { content() } } + } + } +} + +/// Re-renders the Mix and Toolbox screens when the song changes, without the +/// AppModel's transport polling (which would redraw them on every tracker line). +@MainActor +final class MixSongWatch: ObservableObject { + static let shared = MixSongWatch() + @Published private(set) var revision = 0 + private var observer: NSObjectProtocol? + + private init() { + observer = NotificationCenter.default.addObserver(forName: .SizzleSessionDidChange, object: nil, queue: .main) { [weak self] _ in + Task { @MainActor in self?.revision += 1 } + } + } +} diff --git a/ios/app/Host/Screens/Mix/MixScreen.swift b/ios/app/Host/Screens/Mix/MixScreen.swift new file mode 100644 index 0000000..ebca0b8 --- /dev/null +++ b/ios/app/Host/Screens/Mix/MixScreen.swift @@ -0,0 +1,185 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// The second tab (Android's MixerScreen): four channel strips, one per tracker +/// track. Each picks an instrument and up to four effects from the toolbox, sets a +/// MIDI channel, and has a volume fader with a live meter, a limiter and mute/solo. +/// Long-pressing an instrument or effect opens its settings in the Toolbox. +struct MixScreen: View { + @EnvironmentObject var app: AppModel + var body: some View { MixBody(app: app) } +} + +/// Watches the song only (not the transport), so playback doesn't redraw the strips; +/// the meters redraw themselves at display rate. +private struct MixBody: View { + let app: AppModel + @ObservedObject private var watch = MixSongWatch.shared + + var body: some View { + let session = app.session + let kinds = Dictionary(SizzleSession.deviceTypes.map { ($0.type, $0.isInstrument) }, uniquingKeysWith: { a, _ in a }) + var instruments: [Int] = [], effects: [Int] = [] + for i in 0..<16 { + let t = session.type(ofSlot: i) + guard !t.isEmpty, let inst = kinds[t] else { continue } + if inst { instruments.append(i) } else { effects.append(i) } + } + let names = (0..<16).map { session.name(ofSlot: $0) } + return GeometryReader { geo in + let landscape = geo.size.width > geo.size.height + HStack(spacing: 6) { + ForEach(0..<4, id: \.self) { ch in + ChannelStrip(ch: ch, landscape: landscape, instruments: instruments, effects: effects, names: names, + open: { ToolboxNav.open($0, app: app, returnTab: .mix) }) + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } + .padding(6) + } + .background(Theme.background) + } +} + +private struct ChannelStrip: View { + let ch: Int + let landscape: Bool + let instruments: [Int] + let effects: [Int] + let names: [String] + let open: (Int) -> Void + private var session: SizzleSession { SizzleSession.shared } + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Text("CH \(ch + 1)").font(Theme.mono(13)).foregroundColor(Theme.accent) + if landscape { + // Routing left (scrolls if short), levels right: the fader and + // LIM / M / S stay visible in the short height. + HStack(spacing: 6) { + SnapScroll { VStack(alignment: .leading, spacing: 4) { routing } } + .frame(maxWidth: .infinity, maxHeight: .infinity) + VStack(alignment: .leading, spacing: 4) { levels } + .frame(maxWidth: .infinity, maxHeight: .infinity) + } + } else { + routing + levels + } + } + .padding(6) + .background(Theme.surface) + } + + private func label(_ i: Int) -> String { i < 0 ? "—" : "\(i + 1):\(names[i])" } + + @ViewBuilder private var routing: some View { + let inst = session.instrumentSlot(ofChannel: ch) + MixKit.SectionLabel(text: "Instrument") + MixKit.Dropdown(label: "", options: [-1] + instruments, selected: inst, fill: true, optionLabel: label, + onLongPress: { if inst >= 0 { open(inst) } }, + onSelect: { session.setInstrumentSlot($0, ofChannel: ch) }) + MixKit.SectionLabel(text: "FX 1-4") + ForEach(0..<4, id: \.self) { i in + let fx = session.fxSlot(i, ofChannel: ch) + MixKit.Dropdown(label: "", options: [-1] + effects, selected: fx, fill: true, optionLabel: label, + onLongPress: { if fx >= 0 { open(fx) } }, + onSelect: { session.setFxSlot(i, to: $0, ofChannel: ch) }) + } + MixKit.SectionLabel(text: "MIDI Ch") + HStack(spacing: 0) { + MixKit.RepeatButton(label: "-") { + session.setMidiChannel(max(0, session.midiChannel(ofChannel: ch) - 1), ofChannel: ch) + } + Text("\(session.midiChannel(ofChannel: ch))").font(Theme.mono(12)).foregroundColor(Theme.text) + .lineLimit(1).frame(width: 28) + MixKit.RepeatButton(label: "+") { + session.setMidiChannel(min(16, session.midiChannel(ofChannel: ch) + 1), ofChannel: ch) + } + } + } + + @ViewBuilder private var levels: some View { + MixKit.SectionLabel(text: "Volume") + VolumeFader(ch: ch, value: session.volume(ofChannel: ch)) { session.setVolume($0, ofChannel: ch) } + .frame(maxWidth: .infinity, maxHeight: .infinity) + MixKit.Button(label: "LIM", active: session.hasLimiter(ch), fill: true) { + session.setChannel(ch, limiter: !session.hasLimiter(ch)) + } + HStack(spacing: 4) { + MixKit.Button(label: "M", active: session.isMuted(ch), fill: true) { session.setChannel(ch, muted: !session.isMuted(ch)) } + MixKit.Button(label: "S", active: session.isSolo(ch), fill: true) { session.setChannel(ch, solo: !session.isSolo(ch)) } + } + } +} + +/// Android's VerticalFader: the set level fills from the bottom with a thumb line; +/// tap or drag to set, snapping to the default (0.8) within ±0.03. The bus meter +/// rises inside the fill, green to amber to red over the track's height, all red +/// while the bus clips. Only the meter layer redraws each frame. +private struct VolumeFader: View { + let ch: Int + let value: Float + let onChange: (Float) -> Void + private let defaultVolume: Float = 0.8 + + var body: some View { + GeometryReader { g in + let h = g.size.height + let vol = CGFloat(min(max(value, 0), 1)) + let top = h - vol * h + ZStack(alignment: .top) { + Theme.background + Rectangle().fill(Theme.accent.opacity(0.30)).frame(height: vol * h).offset(y: top) + MeterLayer(ch: ch, volume: vol) + Rectangle().fill(Theme.accent).frame(height: 3).offset(y: min(max(top - 1.5, 0), max(h - 3, 0))) + } + .frame(width: g.size.width, height: h, alignment: .top) + .clipped() + .overlay(Rectangle().stroke(Theme.grid, lineWidth: 1)) + .contentShape(Rectangle()) + .gesture(DragGesture(minimumDistance: 0).onChanged { d in + guard h > 0 else { return } + let raw = min(max(Float(1 - d.location.y / h), 0), 1) + onChange(abs(raw - defaultVolume) < 0.03 ? defaultVolume : raw) + }) + } + } +} + +/// The live meter: a Canvas in a display-rate TimelineView, reading the engine's +/// peak and clip flag directly (no state, nothing else redraws). +private struct MeterLayer: View { + let ch: Int + let volume: CGFloat + + var body: some View { + if Snapshot.active { + Color.clear + } else { + TimelineView(.animation) { _ in + let session = SizzleSession.shared + let level = CGFloat(min(max(session.meter(ofChannel: ch), 0), 1)) + let clipped = session.clippedChannel(ch) + let vol = volume + Canvas { ctx, size in + let frac = min(level, vol) + guard frac > 0.001 else { return } + let h = size.height, mh = frac * h + let rect = Path(CGRect(x: 0, y: h - mh, width: size.width, height: mh)) + if clipped { + ctx.fill(rect, with: .color(MixKit.danger)) + } else { + let g = Gradient(stops: [ + .init(color: MixKit.playhead, location: 0), .init(color: MixKit.playhead, location: 0.65), + .init(color: Theme.accent, location: 0.85), .init(color: MixKit.danger, location: 1), + ]) + ctx.fill(rect, with: .linearGradient(g, startPoint: CGPoint(x: 0, y: h), endPoint: .zero)) + } + } + } + } + } +} diff --git a/ios/app/Host/Screens/MixScreen.swift b/ios/app/Host/Screens/MixScreen.swift deleted file mode 100644 index fe892fa..0000000 --- a/ios/app/Host/Screens/MixScreen.swift +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown -// SPDX-License-Identifier: GPL-3.0-or-later - -import SwiftUI - -/// Placeholder: being ported from the Android app. -struct MixScreen: View { - @EnvironmentObject var app: AppModel - var body: some View { - Text("Mix").font(Theme.mono(18)).foregroundColor(Theme.dim) - } -} diff --git a/ios/app/Host/Screens/Setup/SetupComponents.swift b/ios/app/Host/Screens/Setup/SetupComponents.swift new file mode 100644 index 0000000..5341e9e --- /dev/null +++ b/ios/app/Host/Screens/Setup/SetupComponents.swift @@ -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: 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: 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) + } + } +} diff --git a/ios/app/Host/Screens/Setup/SetupFiles.swift b/ios/app/Host/Screens/Setup/SetupFiles.swift new file mode 100644 index 0000000..4438e73 --- /dev/null +++ b/ios/app/Host/Screens/Setup/SetupFiles.swift @@ -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 "." (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." + } + } +} diff --git a/ios/app/Host/Screens/Setup/SetupModel.swift b/ios/app/Host/Screens/Setup/SetupModel.swift new file mode 100644 index 0000000..93ab525 --- /dev/null +++ b/ios/app/Host/Screens/Setup/SetupModel.swift @@ -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 ".sng" / ".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() + } +} diff --git a/ios/app/Host/Screens/Setup/SetupPlatform.swift b/ios/app/Host/Screens/Setup/SetupPlatform.swift new file mode 100644 index 0000000..392ff67 --- /dev/null +++ b/ios/app/Host/Screens/Setup/SetupPlatform.swift @@ -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) -> 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) -> 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) -> some View { self } + func pluginCheck(isPresented: Binding) -> some View { self } +} + +#endif diff --git a/ios/app/Host/Screens/Setup/SetupScreen.swift b/ios/app/Host/Screens/Setup/SetupScreen.swift new file mode 100644 index 0000000..80d7d5e --- /dev/null +++ b/ios/app/Host/Screens/Setup/SetupScreen.swift @@ -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 + } +} diff --git a/ios/app/Host/Screens/SetupScreen.swift b/ios/app/Host/Screens/SetupScreen.swift deleted file mode 100644 index ca76382..0000000 --- a/ios/app/Host/Screens/SetupScreen.swift +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown -// SPDX-License-Identifier: GPL-3.0-or-later - -import SwiftUI - -/// Placeholder: being ported from the Android app. -struct SetupScreen: View { - @EnvironmentObject var app: AppModel - var body: some View { - Text("Setup").font(Theme.mono(18)).foregroundColor(Theme.dim) - } -} diff --git a/ios/app/Host/Screens/Toolbox/AuditionKeyboards.swift b/ios/app/Host/Screens/Toolbox/AuditionKeyboards.swift new file mode 100644 index 0000000..462de11 --- /dev/null +++ b/ios/app/Host/Screens/Toolbox/AuditionKeyboards.swift @@ -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) -> 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) -> 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 + 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 = [] + private var size: CGSize = .zero + private var onOn: (Int) -> Void = { _ in } + private var onOff: (Int) -> Void = { _ in } + + func configure(start: Int, enabled: Set, 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, ended: Bool) { + for t in touches { router?.touch(id: ObjectIdentifier(t).hashValue, at: t.location(in: self), ended: ended) } + } + override func touchesBegan(_ t: Set, with e: UIEvent?) { send(t, ended: false) } + override func touchesMoved(_ t: Set, with e: UIEvent?) { send(t, ended: false) } + override func touchesEnded(_ t: Set, with e: UIEvent?) { send(t, ended: true) } + override func touchesCancelled(_ t: Set, with e: UIEvent?) { send(t, ended: true) } + } +} +#endif diff --git a/ios/app/Host/Screens/Toolbox/SamplerPanels.swift b/ios/app/Host/Screens/Toolbox/SamplerPanels.swift new file mode 100644 index 0000000..c40153d --- /dev/null +++ b/ios/app/Host/Screens/Toolbox/SamplerPanels.swift @@ -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) + } + } + } +} diff --git a/ios/app/Host/Screens/Toolbox/SlotEditor.swift b/ios/app/Host/Screens/Toolbox/SlotEditor.swift new file mode 100644 index 0000000..da7cec9 --- /dev/null +++ b/ios/app/Host/Screens/Toolbox/SlotEditor.swift @@ -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 = ["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) + } + } +} diff --git a/ios/app/Host/Screens/Toolbox/ToolboxScreen.swift b/ios/app/Host/Screens/Toolbox/ToolboxScreen.swift new file mode 100644 index 0000000..04475fa --- /dev/null +++ b/ios/app/Host/Screens/Toolbox/ToolboxScreen.swift @@ -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)) + } +} diff --git a/ios/app/Host/Screens/Toolbox/ToolboxState.swift b/ios/app/Host/Screens/Toolbox/ToolboxState.swift new file mode 100644 index 0000000..60e47d2 --- /dev/null +++ b/ios/app/Host/Screens/Toolbox/ToolboxState.swift @@ -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.. Int32 { beat >= 0 && beat < beats ? slots[lane * beats + beat] : -1 } +} + +/// The lower half of the tracker (Android's ArrangementRoll.kt): a fixed column of +/// lane mutes and block numbers, a bar ruler with the A/B loop regions, and the +/// 8-lane roll (lane i plays block i), drawn as one Canvas, over the loop toolbar. +/// +/// Cells aren't toggled by tapping: tap selects one cell, long-press then drag +/// sweeps a rectangle (dragging into a viewport edge scrolls the roll under the +/// finger), and the FILL/CLEAR, OFF and A/B buttons act on the selection. Tap a +/// block number to edit that block above; M mutes the lane. +struct ArrangementRollView: View { + let app: AppModel + @ObservedObject var state: TrackerState + @ObservedObject var mirror: TrackerMirror + @StateObject private var scroller = TrackerScroller() + + var body: some View { + let _ = mirror.revision + VStack(spacing: 0) { + HStack(spacing: 0) { + laneColumn.frame(width: 102) + RollCanvas(app: app, state: state, scroller: scroller) + } + .frame(maxHeight: .infinity) + loopToolbar + } + .background(TK.background) + } + + // MARK: lane column + + private var laneColumn: some View { + let s = SizzleSession.shared + return VStack(spacing: 0) { + Text("BLK").font(Theme.mono(8)).foregroundColor(TK.dim) + .frame(maxWidth: .infinity).frame(height: RollCanvas.rulerH).background(TK.surface) + ForEach(0..<8, id: \.self) { lane in + let active = s.activePattern == lane + let muted = s.isLaneMuted(lane) + HStack(spacing: 0) { + Text("M").font(Theme.mono(9)).foregroundColor(muted ? TK.danger : TK.dim) + .frame(width: 51).frame(maxHeight: .infinity) + .background(muted ? TK.danger.opacity(0.30) : TK.surface) + .contentShape(Rectangle()) + .onTapGesture { s.setLane(lane, muted: !muted) } + Text("\(lane + 1)").font(Theme.mono(11)).foregroundColor(active ? TK.accent : TK.dim) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .background(active ? TK.accent.opacity(0.25) : TK.surface) + .contentShape(Rectangle()) + .onTapGesture { state.setActiveBlock(app, lane) } + } + .frame(maxHeight: .infinity) + } + } + } + + // MARK: loop toolbar + + private var loopToolbar: some View { + let s = SizzleSession.shared + let has = state.hasArrSelection + return TKHScroll { + HStack(spacing: 6) { + TKButton(label: "LOOP", active: s.arrangementLoop) { s.arrangementLoop.toggle() } + TKButton(label: state.selectionAll({ $0 != -1 }) ? "CLEAR" : "FILL", active: has, width: 72) { + state.toggleSelectedCells() + } + // OFF keeps its label when it would clear (a marker is "filled" too, + // so FILL would also read CLEAR). + TKButton(label: "OFF", active: has, width: 72) { state.toggleSelectedOff() } + region(0, "A") + region(1, "B") + } + .padding(6) + } + .background(TK.surface) + } + + private func region(_ r: Int, _ name: String) -> some View { + HStack(spacing: 0) { + TKButton(label: name, active: state.regionValid(r)) { state.tapRegion(r) } + TKRepeatButton(label: "-") { state.changeRegionRepeats(r, -1) } + Text(" x\(SizzleSession.shared.regionRepeats(r)) ").font(Theme.mono(11)).foregroundColor(TK.text) + TKRepeatButton(label: "+") { state.changeRegionRepeats(r, +1) } + } + } +} + +/// The ruler and roll. Observes AppModel for the playhead beat; scrolls itself +/// (drag / fling), follows the playhead while playing and handles selection. +private struct RollCanvas: View { + @ObservedObject var app: AppModel + @ObservedObject var state: TrackerState + @ObservedObject var scroller: TrackerScroller + @State private var cache = TrackerArrangementCache() + @State private var touch = Touch() + + static let rulerH: CGFloat = 18 + static let beatW: CGFloat = 20 + /// Edge-scroll zone and full speed (pt/s) while sweeping a selection. + private static let edgeZone: CGFloat = 56 + private static let edgeSpeed: CGFloat = 1200 + private static let longPress: TimeInterval = 0.5 + + /// One touch: undecided (tap), scrolling, or sweeping a selection. + final class Touch { + enum Mode { case idle, pending, scrolling, selecting } + var mode = Mode.idle + var haltsFling = false + var start: CGPoint = .zero + var startOffset: CGFloat = 0 + var slopShift: CGFloat = 0 + var lane0 = 0, beat0 = 0 + var fingerVx: CGFloat = 0, fingerLane = 0 + var longTimer: Timer? + var edgeTimer: Timer? + var lastTick: TimeInterval = 0 + func cancelTimers() { longTimer?.invalidate(); longTimer = nil; edgeTimer?.invalidate(); edgeTimer = nil } + } + + var body: some View { + GeometryReader { geo in + let size = geo.size + let _ = cache.refresh() + let maxScroll = max(0, CGFloat(cache.beats) * Self.beatW - size.width) + canvas(size: size, scroll: min(max(scroller.offset, 0), maxScroll)) + .contentShape(Rectangle()) + .gesture(gesture(size: size, maxScroll: maxScroll)) + .onChange(of: app.currentBeat) { beat in follow(beat, width: size.width, maxScroll: maxScroll) } + } + .clipped() + } + + /// Keep the playhead mid-view once it reaches the middle. + private func follow(_ beat: Int, width: CGFloat, maxScroll: CGFloat) { + guard app.isPlaying, touch.mode == .idle || touch.mode == .pending else { return } + scroller.stop() + scroller.offset = min(max(CGFloat(beat) * Self.beatW - width / 2, 0), maxScroll) + } + + private func laneAt(_ y: CGFloat, height: CGFloat) -> Int { + let laneH = (height - Self.rulerH) / 8 + return min(max(Int((y - Self.rulerH) / laneH), 0), 7) + } + + private func beatAt(viewportX vx: CGFloat) -> Int { + min(max(Int((scroller.offset + vx) / Self.beatW), 0), cache.beats - 1) + } + + private func applySelection() { + state.setArrangementSelection(touch.lane0, touch.beat0, touch.fingerLane, beatAt(viewportX: touch.fingerVx)) + } + + private func gesture(size: CGSize, maxScroll: CGFloat) -> some Gesture { + DragGesture(minimumDistance: 0) + .onChanged { g in + let t = touch + if t.mode == .idle { + t.mode = .pending + t.haltsFling = scroller.isFlinging + scroller.stop() + t.start = g.startLocation + t.fingerVx = g.location.x; t.fingerLane = laneAt(g.location.y, height: size.height) + let timer = Timer(timeInterval: Self.longPress, repeats: false) { _ in + Task { @MainActor in beginSelection(size: size, maxScroll: maxScroll) } + } + RunLoop.main.add(timer, forMode: .common) + t.longTimer = timer + } + t.fingerVx = g.location.x + t.fingerLane = laneAt(g.location.y, height: size.height) + switch t.mode { + case .pending: + if abs(g.translation.width) > 8 || abs(g.translation.height) > 8 { + t.cancelTimers() + t.mode = .scrolling + t.startOffset = scroller.offset + t.slopShift = g.translation.width + } + case .scrolling: + scroller.offset = min(max(t.startOffset - (g.translation.width - t.slopShift), 0), maxScroll) + case .selecting: + applySelection() + case .idle: break + } + } + .onEnded { g in + let t = touch + t.cancelTimers() + switch t.mode { + case .pending: + if !t.haltsFling && g.location.y >= Self.rulerH { + let lane = laneAt(g.location.y, height: size.height), beat = beatAt(viewportX: g.location.x) + state.setArrangementSelection(lane, beat, lane, beat) + } + case .scrolling: + scroller.fling(distance: -(g.predictedEndTranslation.width - g.translation.width), max: maxScroll) + default: break + } + t.mode = .idle + } + } + + /// Long press held still: start sweeping a selection, with edge scrolling. + private func beginSelection(size: CGSize, maxScroll: CGFloat) { + let t = touch + guard t.mode == .pending else { return } + t.mode = .selecting + t.lane0 = laneAt(t.start.y, height: size.height) + t.beat0 = beatAt(viewportX: t.start.x) + applySelection() + t.lastTick = Date().timeIntervalSinceReferenceDate + let timer = Timer(timeInterval: 1.0 / 60, repeats: true) { _ in + Task { @MainActor in edgeTick(width: size.width, maxScroll: maxScroll) } + } + RunLoop.main.add(timer, forMode: .common) + t.edgeTimer = timer + } + + private func edgeTick(width w: CGFloat, maxScroll: CGFloat) { + let t = touch + guard t.mode == .selecting else { return } + let now = Date().timeIntervalSinceReferenceDate + let dt = CGFloat(now - t.lastTick) + t.lastTick = now + let z = Self.edgeZone + var push: CGFloat = 0 + if t.fingerVx > w - z { push = (t.fingerVx - (w - z)) / z } + else if t.fingerVx < z { push = -(z - t.fingerVx) / z } + push = min(max(push, -1), 1) + if push == 0 || dt <= 0 { return } + let next = min(max(scroller.offset + push * Self.edgeSpeed * dt, 0), maxScroll) + if next != scroller.offset { scroller.offset = next; applySelection() } + } + + // MARK: drawing + + private func canvas(size: CGSize, scroll: CGFloat) -> some View { + let s = SizzleSession.shared + let bpb = max(1, s.beatsPerBar) + let playing = app.isPlaying, playBeat = app.currentBeat + let hasSel = state.hasArrSelection + let laneR = hasSel ? state.arrLaneRange : 0...0 + let beatR = hasSel ? state.arrBeatRange : 0...0 + let regions = (0..<2).map { r in (valid: state.regionValid(r), start: s.regionStart(r), end: s.regionEnd(r)) } + let cache = self.cache + let beatW = Self.beatW, rulerH = Self.rulerH + return Canvas { ctx, size in + let w = size.width, h = size.height + let laneH = (h - rulerH) / 8 + let first = min(max(Int(scroll / beatW), 0), max(cache.beats - 1, 0)) + let last = min(max(Int((scroll + w) / beatW) + 2, 1), cache.beats) + func x(_ beat: Int) -> CGFloat { CGFloat(beat) * beatW - scroll } + func label(_ str: String, _ color: Color) -> GraphicsContext.ResolvedText { + ctx.resolve(Text(str).font(Theme.mono(9)).foregroundColor(color)) + } + + // Ruler + bar ticks/numbers. + ctx.fill(Path(CGRect(x: 0, y: 0, width: w, height: rulerH)), with: .color(TK.surface)) + for beat in first.. SizzleCell { cells[track * length + line] } +} + +/// The demoscene pattern grid (Android's PatternGrid.kt): 4 tracks × the pattern's +/// lines, each cell NOTE / VEL / CH, drawn as one Canvas. Beat and bar rows are +/// tinted, odd tracks shaded, the cursor cell and playhead row highlighted. +/// +/// Touch: tap moves the cursor to the cell and column; a drag or flick scrolls and +/// never selects; a touch that lands on a still-coasting grid only stops it. While +/// playing the view centres on the playhead until a scroll detaches it; switching +/// block re-attaches. A cursor that moves off screen is scrolled back into view. +struct PatternGridView: View { + @ObservedObject var app: AppModel + @ObservedObject var state: TrackerState + @StateObject private var scroller = TrackerScroller() + @State private var cache = TrackerPatternCache() + @State private var drag = DragTrack() + @State private var following = true + @State private var followPattern = -1 + + private let rowH: CGFloat = 20 + private let gutter: CGFloat = 30 + + final class DragTrack { + var active = false + var isTap = true + var haltsFling = false + var startOffset: CGFloat = 0 + var slopShift: CGFloat = 0 + } + + var body: some View { + GeometryReader { geo in + let size = geo.size + let _ = cache.refresh() + let maxScroll = max(0, CGFloat(cache.length) * rowH - size.height) + let scroll = effectiveScroll(height: size.height, maxScroll: maxScroll) + canvas(size: size, scroll: scroll) + .contentShape(Rectangle()) + .gesture(gesture(size: size, maxScroll: maxScroll)) + .onChange(of: app.cursorLine) { line in revealCursor(line, height: size.height, maxScroll: maxScroll) } + .onChange(of: cache.pattern) { _ in following = true; scroller.stop(); scroller.offset = 0 } + } + .background(TK.background) + .clipped() + } + + // MARK: scrolling + + private func playheadScroll(_ line: Int, height: CGFloat, maxScroll: CGFloat) -> CGFloat { + min(max(CGFloat(line) * rowH + rowH / 2 - height / 2, 0), maxScroll) + } + + private func effectiveScroll(height: CGFloat, maxScroll: CGFloat) -> CGFloat { + if app.isPlaying && following { return playheadScroll(app.currentLine, height: height, maxScroll: maxScroll) } + return min(max(scroller.offset, 0), maxScroll) + } + + /// Minimal scroll that brings the cursor row into view (never re-centres, so a + /// tapped row stays under the finger). + private func revealCursor(_ line: Int, height: CGFloat, maxScroll: CGFloat) { + let top = CGFloat(line) * rowH + let lo = min(max(top + rowH - height, 0), maxScroll) + let hi = min(max(top, lo), maxScroll) + let eff = effectiveScroll(height: height, maxScroll: maxScroll) + let next = min(max(eff, lo), hi) + if next != scroller.offset { scroller.offset = next } + } + + private func gesture(size: CGSize, maxScroll: CGFloat) -> some Gesture { + DragGesture(minimumDistance: 0) + .onChanged { g in + if !drag.active { + drag.active = true + drag.isTap = true + drag.haltsFling = scroller.isFlinging + scroller.stop() + } + let dy = g.translation.height + if drag.isTap && (abs(dy) > 8 || abs(g.translation.width) > 8) { + drag.isTap = false + drag.startOffset = effectiveScroll(height: size.height, maxScroll: maxScroll) + drag.slopShift = dy + following = false + } + if !drag.isTap { + scroller.offset = min(max(drag.startOffset - (dy - drag.slopShift), 0), maxScroll) + } + } + .onEnded { g in + defer { drag.active = false } + if drag.isTap { + if !drag.haltsFling { tap(g.location, size: size, maxScroll: maxScroll) } + } else { + scroller.fling(distance: -(g.predictedEndTranslation.height - g.translation.height), max: maxScroll) + } + } + } + + private func tap(_ p: CGPoint, size: CGSize, maxScroll: CGFloat) { + guard p.x >= gutter, cache.length > 0 else { return } + let scroll = effectiveScroll(height: size.height, maxScroll: maxScroll) + let line = min(max(Int((scroll + p.y) / rowH), 0), cache.length - 1) + let trackW = (size.width - gutter) / 4 + let tx = p.x - gutter + let track = min(max(Int(tx / trackW), 0), 3) + let within = tx - CGFloat(track) * trackW + let col: AppModel.Column = within < trackW * 0.5 ? .note : (within < trackW * 0.75 ? .velocity : .channel) + state.focusCell(app, track: track, line: line, column: col) + } + + // MARK: drawing + + private func canvas(size: CGSize, scroll: CGFloat) -> some View { + let s = SizzleSession.shared + let lpb = max(1, s.linesPerBeat), lpBar = max(1, s.linesPerBeat * s.beatsPerBar) + let playing = app.isPlaying, playLine = app.currentLine + let cTrack = app.cursorTrack, cLine = app.cursorLine, cCol = app.cursorColumn + let sel = state.hasSelection(app) + let selT = state.selTrackRange(app), selL = state.selLineRange(app) + let cache = self.cache + let rowH = self.rowH, gutter = self.gutter + return Canvas { ctx, size in + let w = size.width, h = size.height + let trackW = (w - gutter) / 4 + let noteW = trackW * 0.5, velW = trackW * 0.25 + var texts: [String: GraphicsContext.ResolvedText] = [:] + func draw(_ str: String, _ color: Color, _ fs: CGFloat, x: CGFloat, y: CGFloat) { + let key = "\(fs)|\(color == TK.text ? 0 : color == TK.accent ? 1 : 2)|" + str + let r: GraphicsContext.ResolvedText + if let c = texts[key] { r = c } else { + r = ctx.resolve(Text(str).font(Theme.mono(fs)).foregroundColor(color)); texts[key] = r + } + ctx.draw(r, at: CGPoint(x: x, y: y + rowH / 2), anchor: .leading) + } + + // 1) Alternating track tints + separators. + for t in 0..<4 { + let x0 = gutter + CGFloat(t) * trackW + if t % 2 == 1 { ctx.fill(Path(CGRect(x: x0, y: 0, width: trackW, height: h)), with: .color(TK.grid.opacity(0.35))) } + ctx.fill(Path(CGRect(x: x0, y: 0, width: 1, height: h)), with: .color(TK.grid)) + } + + // 2) Rows. + let first = Int(scroll / rowH) + let yShift = -(scroll - CGFloat(first) * rowH) + let visible = Int(h / rowH) + 1 + for screen in 0...visible { + let line = first + screen + if line >= cache.length { break } + if line < 0 { continue } + let y = yShift + CGFloat(screen) * rowH + let rowColor: Color? = playing && line == playLine ? TK.playhead.opacity(0.22) + : line % lpBar == 0 ? TK.bar.opacity(0.7) + : line % lpb == 0 ? TK.beat.opacity(0.7) : nil + if let rc = rowColor { ctx.fill(Path(CGRect(x: 0, y: y, width: w, height: rowH)), with: .color(rc)) } + + draw(line < 256 ? TK.hex2[line] : String(format: "%02X", line), TK.dim, 11, x: 2, y: y) + + for t in 0..<4 { + let cell = cache.cell(t, line) + let bx = gutter + CGFloat(t) * trackW + if sel && selT.contains(t) && selL.contains(line) { + ctx.fill(Path(CGRect(x: bx, y: y, width: trackW, height: rowH)), with: .color(TK.accent.opacity(0.18))) + } + if cTrack == t && cLine == line { + let r: CGRect + switch cCol { + case .note: r = CGRect(x: bx, y: y, width: noteW, height: rowH) + case .velocity: r = CGRect(x: bx + noteW, y: y, width: velW, height: rowH) + case .channel: r = CGRect(x: bx + noteW + velW, y: y, width: velW, height: rowH) + } + ctx.fill(Path(r), with: .color(TK.accent.opacity(0.30))) + } + let note = Int(cell.note) + let empty = note == -1, off = note == -2 + draw(empty ? "···" : off ? "===" : TK.noteName(note), TK.text, 12, x: bx + 2, y: y) + let vel = Int(cell.velocity), ch = Int(cell.channel) + draw(empty || off ? ".." : (vel < 256 ? TK.hex2[vel] : "\(vel)"), empty ? TK.dim : TK.accent, 12, + x: bx + noteW + 2, y: y) + draw(empty || off ? ".." : (ch < 100 ? TK.chan2[ch] : "\(ch)"), TK.dim, 12, + x: bx + noteW + velW + 2, y: y) + } + } + } + .frame(width: size.width, height: size.height) + } +} diff --git a/ios/app/Host/Screens/Tracker/PunchKeyboard.swift b/ios/app/Host/Screens/Tracker/PunchKeyboard.swift new file mode 100644 index 0000000..c12ff86 --- /dev/null +++ b/ios/app/Host/Screens/Tracker/PunchKeyboard.swift @@ -0,0 +1,185 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// The tracker's punch-in keyboard (Android's StackedKeyboard with punchIn = true): +/// a CH / OCT / VEL row over two stacked octaves (the upper one on top). A key +/// sounds on the keyboard's channel; its initial press also writes the note into +/// the cursor cell and advances the cursor by the skip step. Sliding across keys +/// glides (each key sounds, none is recorded). Out-of-scale keys are dimmed and +/// silent, unless the channel plays a Sampler (every pad must stay reachable). +struct PunchKeyboard: View { + @ObservedObject var app: AppModel + let state: TrackerState + @ObservedObject var mirror: TrackerMirror + @ObservedObject private var held = TrackerHeldNotes.shared + + private static let velStep = 8 + + var body: some View { + let _ = mirror.revision + let inKey = inKeyPitchClasses() + VStack(spacing: 4) { + TKHScroll { + HStack(spacing: 6) { + selector("CH", app.kbdChannel == 0 ? "--" : "\(app.kbdChannel)", + { app.kbdChannel = max(0, app.kbdChannel - 1) }, { app.kbdChannel = min(16, app.kbdChannel + 1) }) + selector("OCT", "\(app.kbdOctave)–\(app.kbdOctave + 1)", + { app.kbdOctave = max(0, app.kbdOctave - 1) }, { app.kbdOctave = min(8, app.kbdOctave + 1) }) + selector("VEL", String(format: "%02X", app.kbdVelocity), + { app.kbdVelocity = max(0, app.kbdVelocity - Self.velStep) }, + { app.kbdVelocity = min(127, app.kbdVelocity + Self.velStep) }) + } + } + .fixedSize(horizontal: false, vertical: true) + octave(start: (app.kbdOctave + 2) * 12, inKey: inKey) + octave(start: (app.kbdOctave + 1) * 12, inKey: inKey) + } + .padding(6) + .background(TK.background) + .onDisappear { held.releaseAll() } + } + + @ViewBuilder + private func selector(_ label: String, _ value: String, _ dec: @escaping () -> Void, _ inc: @escaping () -> Void) -> some View { + Text(label).font(Theme.mono(11)).foregroundColor(TK.dim) + TKRepeatButton(label: "-", onStep: dec) + Text(value).font(Theme.mono(13)).foregroundColor(TK.accent).frame(width: 40) + TKRepeatButton(label: "+", onStep: inc) + } + + private func inKeyPitchClasses() -> Set { + let s = SizzleSession.shared + for ch in 0..<4 where s.midiChannel(ofChannel: ch) == app.kbdChannel { + let slot = s.instrumentSlot(ofChannel: ch) + if slot >= 0 && s.type(ofSlot: slot) == "SAMPLER" { return Set(0..<12) } + } + return Set(s.scalePitchClasses.map { $0.intValue }) + } + + private func octave(start: Int, inKey: Set) -> some View { + let app = self.app, state = self.state, held = self.held + func midi(_ pc: Int) -> Int { min(max(start + pc, 0), 127) } + return TrackerPianoOctave( + label: { pc in TK.noteName(midi(pc)).replacingOccurrences(of: "-", with: "") }, + enabled: { inKey.contains($0) }, + pressed: { held.isHeld(midi($0)) }, + onNoteOn: { pc, slid in + let n = midi(pc) + if !slid { state.punchNote(app, n) } + held.on(n, app: app) + }, + onNoteOff: { pc in held.off(midi(pc), app: app) }) + } +} + +/// One octave as a piano (Android's PianoOctave): seven white keys with the five +/// black keys over them. Each finger is tracked by the key it went down on and +/// hit-tested against the whole octave as it moves, so a slide retriggers on each +/// key it crosses and several fingers play chords. +struct TrackerPianoOctave: View { + let label: (Int) -> String + let enabled: (Int) -> Bool + let pressed: (Int) -> Bool + let onNoteOn: (Int, Bool) -> Void + let onNoteOff: (Int) -> Void + + private static let whites = [0, 2, 4, 5, 7, 9, 11] + private static let blacks: [(pc: Int, after: Int)] = [(1, 0), (3, 1), (6, 3), (8, 4), (10, 5)] + private static let blackW: CGFloat = 0.62, blackH: CGFloat = 0.62 + + var body: some View { + GeometryReader { geo in + let size = geo.size + let whiteW = size.width / 7 + ZStack(alignment: .topLeading) { + HStack(spacing: 0) { + ForEach(Self.whites, id: \.self) { pc in key(pc, black: false, size: size).frame(width: whiteW, height: size.height) } + } + ForEach(Self.blacks, id: \.pc) { b in + key(b.pc, black: true, size: size) + .frame(width: whiteW * Self.blackW, height: size.height * Self.blackH) + .padding(.leading, whiteW * CGFloat(b.after + 1) - whiteW * Self.blackW / 2) + } + } + .coordinateSpace(name: "tk-octave") + } + } + + private func key(_ pc: Int, black: Bool, size: CGSize) -> some View { + PianoKeyView(label: label(pc), black: black, enabled: enabled(pc), lit: pressed(pc), + hit: { p in hit(p, size: size) }, onNoteOn: onNoteOn, onNoteOff: onNoteOff) + } + + /// Pitch class under a point in octave coordinates, or -1 (off the keyboard or + /// on a disabled key). Black keys win in their upper region. + private func hit(_ p: CGPoint, size: CGSize) -> 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 whiteW = w / 7 + var pc = Self.whites[min(max(Int(p.x / whiteW), 0), 6)] + if p.y <= h * Self.blackH { + let bw = whiteW * Self.blackW + for b in Self.blacks { + let bx = whiteW * CGFloat(b.after + 1) - bw / 2 + if p.x >= bx && p.x <= bx + bw { pc = b.pc; break } + } + } + return enabled(pc) ? pc : -1 + } +} + +/// A key face (Android's PianoKey) that owns the gesture of the finger that went +/// down on it; [hit] maps the finger's position in the octave to a pitch class. +private struct PianoKeyView: View { + let label: String + let black: Bool + let enabled: Bool + let lit: Bool + let hit: (CGPoint) -> Int + let onNoteOn: (Int, Bool) -> Void + let onNoteOff: (Int) -> Void + + @State private var finger = Finger() + final class Finger { var current: Int? } + + private static let white = Color(white: 0xE8 / 255), whiteOff = Color(white: 0x5A / 255) + private static let blackOn = Color(red: 0x18 / 255, green: 0x18 / 255, blue: 0x20 / 255) + private static let blackOff = Color(red: 0x0C / 255, green: 0x0C / 255, blue: 0x10 / 255) + + var body: some View { + face + .contentShape(Rectangle()) + .gesture(DragGesture(minimumDistance: 0, coordinateSpace: .named("tk-octave")) + .onChanged { g in + let pc = hit(g.location) + if let prev = finger.current { + if pc != prev { + if prev >= 0 { onNoteOff(prev) } + if pc >= 0 { onNoteOn(pc, true) } + finger.current = pc + } + } else { + finger.current = pc + if pc >= 0 { onNoteOn(pc, false) } + } + } + .onEnded { _ in + if let prev = finger.current, prev >= 0 { onNoteOff(prev) } + finger.current = nil + }) + } + + private var face: some View { + let bg: Color = lit ? TK.accent : black ? (enabled ? Self.blackOn : Self.blackOff) : (enabled ? Self.white : Self.whiteOff) + let fg: Color = lit ? TK.background + : black ? (enabled ? Color(white: 0xDD / 255) : Color(white: 0x55 / 255)) + : (enabled ? Color(white: 0x14 / 255) : Color(white: 0x6A / 255)) + return ZStack(alignment: .bottom) { + bg + Text(label).font(Theme.mono(12)).foregroundColor(fg).lineLimit(1).fixedSize().padding(.bottom, 3) + } + .overlay(Rectangle().stroke(lit ? TK.accent : Color.black, lineWidth: 1)) + } +} diff --git a/ios/app/Host/Screens/Tracker/TrackerScreen.swift b/ios/app/Host/Screens/Tracker/TrackerScreen.swift new file mode 100644 index 0000000..3fd8742 --- /dev/null +++ b/ios/app/Host/Screens/Tracker/TrackerScreen.swift @@ -0,0 +1,148 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// The first tab (Android's TrackerScreen.kt): the transport toolbar and pattern +/// grid over the arrangement roll (or the punch-in keyboard) in portrait, 1.7 : 1; +/// in landscape the toolbar runs across the top and the grid sits beside the +/// lower half (1.4 : 1, or 1 : 1.3 with the keyboard, which needs the width). +struct TrackerScreen: View { + @EnvironmentObject var app: AppModel + // TrackerBody only stores references, so the playhead lines AppModel publishes + // re-run this body but not TrackerBody's: only the grid and roll redraw. + var body: some View { TrackerBody(app: app, state: TrackerState.shared) } +} + +private struct TrackerBody: View { + let app: AppModel + @ObservedObject var state: TrackerState + @StateObject private var mirror: TrackerMirror + + init(app: AppModel, state: TrackerState) { + self.app = app + self.state = state + _mirror = StateObject(wrappedValue: TrackerMirror(app)) + } + + var body: some View { + GeometryReader { geo in + let landscape = geo.size.width > geo.size.height + if landscape { self.landscape(geo.size) } else { portrait(geo.size) } + } + .background(TK.background) + } + + private func portrait(_ size: CGSize) -> some View { + let upper = (size.height - 2) * 1.7 / 2.7 + return VStack(spacing: 0) { + VStack(spacing: 0) { + TransportToolbar(app: app, state: state, mirror: mirror, landscape: false) + PatternGridView(app: app, state: state) + } + .frame(height: upper) + TK.accent.frame(height: 2) + lower.frame(maxHeight: .infinity) + } + } + + private func landscape(_ size: CGSize) -> some View { + let gridWeight: CGFloat = state.punchInMode ? 1 : 1.4 + let lowerWeight: CGFloat = state.punchInMode ? 1.3 : 1 + let gridW = (size.width - 2) * gridWeight / (gridWeight + lowerWeight) + return VStack(spacing: 0) { + TransportToolbar(app: app, state: state, mirror: mirror, landscape: true) + TK.accent.frame(height: 2) + HStack(spacing: 0) { + PatternGridView(app: app, state: state).frame(width: gridW) + TK.accent.frame(width: 2) + lower.frame(maxWidth: .infinity) + } + .frame(maxHeight: .infinity) + } + } + + @ViewBuilder private var lower: some View { + if state.punchInMode { + PunchKeyboard(app: app, state: state, mirror: mirror) + } else { + ArrangementRollView(app: app, state: state, mirror: mirror) + } + } +} + +/// Transport, pattern and edit controls: three justified rows in portrait, two in +/// landscape (pattern and edit groups share a row). +private struct TransportToolbar: View { + let app: AppModel + @ObservedObject var state: TrackerState + @ObservedObject var mirror: TrackerMirror + let landscape: Bool + + var body: some View { + let _ = mirror.revision + VStack(spacing: 6) { + TKJustifiedRow(items: transportItems) + if landscape { + TKJustifiedRow(items: patternItems + editItems) + } else { + TKJustifiedRow(items: patternItems) + TKJustifiedRow(items: editItems) + } + } + .padding(6) + .background(TK.surface) + } + + /// STOP, PLAY/PAUSE, tempo (-, readout = tap tempo, +), signature. + private var transportItems: [AnyView] { + let s = SizzleSession.shared + let playing = mirror.isPlaying + return [ + AnyView(TKButton(label: "⧉ STOP") { state.stop() }), + AnyView(TKButton(label: playing ? "❚❚ PAUSE" : "▶ PLAY", active: playing, width: 112) { state.playPause() }), + AnyView(HStack(spacing: 0) { + TKRepeatButton(label: "-") { state.setTempo(SizzleSession.shared.tempo - 1) } + Text("\(Int(s.tempo)) BPM").font(Theme.mono(12)).foregroundColor(TK.text).lineLimit(1) + .frame(width: 72).padding(.vertical, 6) + .contentShape(Rectangle()) + .onTapGesture { state.tapTempo() } + TKRepeatButton(label: "+") { state.setTempo(SizzleSession.shared.tempo + 1) } + }), + AnyView(TKDropdown("SIG", options: Array(SizzleSession.signatureLabels.indices), selected: s.signature, + optionLabel: { SizzleSession.signatureLabels[$0] }) { state.setSignature(app, $0) }), + ] + } + + /// Active block, pattern length, scale, root. + private var patternItems: [AnyView] { + let s = SizzleSession.shared + let length = s.length(ofPattern: s.activePattern) + let lengths = s.lengthOptions.map { $0.intValue } + let names = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"] + return [ + AnyView(TKDropdown("BLK", options: Array(0..<8), selected: s.activePattern, + optionLabel: { "\($0 + 1)" }) { state.setActiveBlock(app, $0) }), + AnyView(TKDropdown("LEN", options: lengths.contains(length) ? lengths : lengths + [length], + selected: length) { state.setPatternLength(app, $0) }), + AnyView(TKDropdown("SCALE", options: Array(SizzleSession.scaleLabels.indices), selected: s.scale, + optionLabel: { SizzleSession.scaleLabels[$0] }) { SizzleSession.shared.scale = $0 }), + AnyView(TKDropdown("ROOT", options: Array(0..<12), selected: s.rootNote, + optionLabel: { names[$0] }) { SizzleSession.shared.rootNote = $0 }), + ] + } + + /// SEL, cut ✂, copy ⧉, paste ▤, delete ✕, note-off, skip step, KBD. + private var editItems: [AnyView] { + [ + AnyView(TKButton(label: "SEL", active: state.selectMode) { state.toggleSelectMode(app) }), + AnyView(TKButton(label: "✂") { state.cutSelection(app) }), + AnyView(TKButton(label: "⧉") { state.copySelection(app) }), + AnyView(TKButton(label: "▤", active: state.canPaste) { state.pasteClipboard(app) }), + AnyView(TKButton(label: "✕") { state.deleteAndAdvance(app) }), + AnyView(TKButton(label: "OFF ===") { state.noteOffFocused(app) }), + AnyView(TKDropdown("SKIP", options: [0, 1, 2, 4, 8], selected: state.skipStep) { state.skipStep = $0 }), + AnyView(TKButton(label: "⌨ KBD", active: state.punchInMode) { state.punchInMode.toggle() }), + ] + } +} diff --git a/ios/app/Host/Screens/Tracker/TrackerState.swift b/ios/app/Host/Screens/Tracker/TrackerState.swift new file mode 100644 index 0000000..86f0b13 --- /dev/null +++ b/ios/app/Host/Screens/Tracker/TrackerState.swift @@ -0,0 +1,303 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import Combine +import SwiftUI + +/// The Tracker tab's own UI state and edit operations: the parts of Android's +/// AppViewModel the tab uses beyond what AppModel holds (cursor, keyboard +/// channel/octave/velocity). One instance for the app's life, so selection, skip +/// step, KBD mode and the clipboard survive tab switches as they do on Android. +@MainActor +final class TrackerState: ObservableObject { + static let shared = TrackerState() + + // Selection & clipboard (Android: selectMode / selAnchor* / clipboard). + @Published private(set) var selectMode = false + @Published private(set) var selAnchorTrack = -1 + @Published private(set) var selAnchorLine = -1 + /// Copied cells, [trackOffset][lineOffset]. + @Published private(set) var clipboard: [[SizzleCell]]? + var canPaste: Bool { clipboard != nil } + + /// Rows the cursor jumps after a punch-in / note-off / delete (0, 1, 2, 4, 8). + @Published var skipStep = 1 + /// The lower half shows the punch-in keyboard instead of the arrangement. + @Published var punchInMode = false + + // Arrangement selection: anchor (…0) and live corner (…1); beat < 0 = none. + @Published private(set) var arrSelLane0 = -1 + @Published private(set) var arrSelBeat0 = -1 + @Published private(set) var arrSelLane1 = -1 + @Published private(set) var arrSelBeat1 = -1 + + /// Tap-tempo timestamps. + private var tapTimes: [TimeInterval] = [] + + private var session: SizzleSession { SizzleSession.shared } + private var length: Int { max(1, session.length(ofPattern: session.activePattern)) } + + // MARK: selection ranges + + func hasSelection(_ app: AppModel) -> Bool { selectMode && selAnchorTrack >= 0 } + func selTrackRange(_ app: AppModel) -> ClosedRange { + hasSelection(app) ? min(selAnchorTrack, app.cursorTrack)...max(selAnchorTrack, app.cursorTrack) : app.cursorTrack...app.cursorTrack + } + func selLineRange(_ app: AppModel) -> ClosedRange { + hasSelection(app) ? min(selAnchorLine, app.cursorLine)...max(selAnchorLine, app.cursorLine) : app.cursorLine...app.cursorLine + } + + // MARK: cursor + + func focusCell(_ app: AppModel, track: Int, line: Int, column: AppModel.Column) { + app.cursorTrack = min(max(track, 0), 3) + app.cursorLine = min(max(line, 0), length - 1) + app.cursorColumn = column + } + + /// Move the cursor by [d] rows, wrapping at the pattern ends. + func moveCursorWrap(_ app: AppModel, _ d: Int) { + let len = length + app.cursorLine = ((app.cursorLine + d) % len + len) % len + } + + // MARK: edits (Android: punchNote / noteOffFocused / deleteAndAdvance / …) + + func punchNote(_ app: AppModel, _ midi: Int) { + let cell = SizzleCell(note: Int32(min(max(midi, 0), 127)), velocity: Int32(min(max(app.kbdVelocity, 0), 127)), + channel: Int32(app.kbdChannel)) + session.setCell(cell, inPattern: session.activePattern, track: app.cursorTrack, line: app.cursorLine) + moveCursorWrap(app, skipStep) + } + + /// Insert a note-off ("===") at the cursor and advance by the skip step. + func noteOffFocused(_ app: AppModel) { + session.setCell(SizzleCell(note: -2, velocity: 127, channel: 1), inPattern: session.activePattern, + track: app.cursorTrack, line: app.cursorLine) + moveCursorWrap(app, skipStep) + } + + /// DEL: clear the selection (or the focused cell) and advance by the skip step. + func deleteAndAdvance(_ app: AppModel) { + deleteSelection(app) + moveCursorWrap(app, skipStep) + } + + func toggleSelectMode(_ app: AppModel) { + selectMode.toggle() + if selectMode { selAnchorTrack = app.cursorTrack; selAnchorLine = app.cursorLine } + else { selAnchorTrack = -1; selAnchorLine = -1 } + } + + func copySelection(_ app: AppModel) { + let p = session.activePattern + let tr = selTrackRange(app), lr = selLineRange(app) + clipboard = tr.map { t in lr.map { l in session.cell(inPattern: p, track: t, line: l) } } + } + + func deleteSelection(_ app: AppModel) { + let tr = selTrackRange(app), lr = selLineRange(app) + session.clearCells(inPattern: session.activePattern, fromTrack: tr.lowerBound, toTrack: tr.upperBound, + fromLine: lr.lowerBound, toLine: lr.upperBound) + } + + func cutSelection(_ app: AppModel) { copySelection(app); deleteSelection(app) } + + /// Paste with the clipboard's top-left at the cursor, clipped to the grid. + func pasteClipboard(_ app: AppModel) { + guard let cb = clipboard, let h = cb.first?.count, h > 0 else { return } + let flat = cb.flatMap { $0 } + flat.withUnsafeBufferPointer { buf in + session.writeCells(buf.baseAddress!, width: cb.count, height: h, inPattern: session.activePattern, + track: app.cursorTrack, line: app.cursorLine) + } + } + + // MARK: song settings + + func setActiveBlock(_ app: AppModel, _ i: Int) { + session.activePattern = min(max(i, 0), 7) + app.cursorLine = min(max(app.cursorLine, 0), length - 1) + } + + func setPatternLength(_ app: AppModel, _ len: Int) { + session.setLength(len, ofPattern: session.activePattern) + app.cursorLine = min(max(app.cursorLine, 0), len - 1) + } + + func setSignature(_ app: AppModel, _ sig: Int) { + session.setSignatureSnappingActivePattern(sig) + app.cursorLine = min(max(app.cursorLine, 0), length - 1) + } + + func setTempo(_ bpm: Float) { session.tempo = min(max(bpm, 20), 300) } + + /// Tap tempo: two or more taps in time set the tempo from the average interval; + /// a pause over 2 s starts a fresh count; at most 8 taps are averaged. + func tapTempo() { + let now = Date().timeIntervalSinceReferenceDate + if let last = tapTimes.last, now - last > 2 { tapTimes.removeAll() } + tapTimes.append(now) + while tapTimes.count > 8 { tapTimes.removeFirst() } + if tapTimes.count >= 2, let first = tapTimes.first, let last = tapTimes.last, last > first { + setTempo(Float(Double(tapTimes.count - 1) * 60 / (last - first))) + } + } + + // MARK: transport + + /// Play starts from the arrangement selection's first beat when there is one. + func playPause() { + if session.isPlaying { session.pause() } + else if arrSelBeat0 >= 0 { session.play(fromBeat: min(arrSelBeat0, arrSelBeat1)) } + else { session.play() } + } + + /// Stop also clears the arrangement selection, so the next Play starts at the top. + func stop() { + clearArrangementSelection() + session.stop() + } + + // MARK: arrangement + + var hasArrSelection: Bool { arrSelBeat0 >= 0 } + var arrLaneRange: ClosedRange { min(arrSelLane0, arrSelLane1)...max(arrSelLane0, arrSelLane1) } + var arrBeatRange: ClosedRange { min(arrSelBeat0, arrSelBeat1)...max(arrSelBeat0, arrSelBeat1) } + + func setArrangementSelection(_ lane0: Int, _ beat0: Int, _ lane1: Int, _ beat1: Int) { + if arrSelLane0 == lane0 && arrSelBeat0 == beat0 && arrSelLane1 == lane1 && arrSelBeat1 == beat1 { return } + arrSelLane0 = lane0; arrSelBeat0 = beat0; arrSelLane1 = lane1; arrSelBeat1 = beat1 + } + + func clearArrangementSelection() { setArrangementSelection(-1, -1, -1, -1) } + + /// Whether every selected slot passes [test] (FILL/CLEAR and OFF labels). + func selectionAll(_ test: (Int32) -> Bool) -> Bool { + guard hasArrSelection else { return false } + for lane in arrLaneRange { for beat in arrBeatRange where !test(Int32(session.arrangementLane(lane, beat: beat))) { return false } } + return true + } + + /// FILL / CLEAR: a fully filled selection clears, anything else fills with each + /// lane's own block. + func toggleSelectedCells() { + guard hasArrSelection else { return } + let clear = selectionAll { $0 != -1 } + session.fillArrangement(fromLane: arrLaneRange.lowerBound, toLane: arrLaneRange.upperBound, + fromBeat: arrBeatRange.lowerBound, toBeat: arrBeatRange.upperBound, + pattern: clear ? -1 : SizzleArrangementOwnLane) + } + + /// OFF: a selection of only off markers clears, anything else becomes markers. + func toggleSelectedOff() { + guard hasArrSelection else { return } + let clear = selectionAll { $0 == -2 } + session.fillArrangement(fromLane: arrLaneRange.lowerBound, toLane: arrLaneRange.upperBound, + fromBeat: arrBeatRange.lowerBound, toBeat: arrBeatRange.upperBound, + pattern: clear ? -1 : -2) + } + + func regionValid(_ r: Int) -> Bool { session.regionEnabled(r) && session.regionEnd(r) > session.regionStart(r) } + + /// A / B: a set region is removed; otherwise the selection's beats become it. + func tapRegion(_ r: Int) { + let reps = session.regionRepeats(r) + if regionValid(r) { + session.setRegion(r, enabled: false, start: 0, end: 0, repeats: reps) + } else if hasArrSelection { + session.setRegion(r, enabled: true, start: arrBeatRange.lowerBound, end: arrBeatRange.upperBound + 1, repeats: reps) + } + } + + func changeRegionRepeats(_ r: Int, _ delta: Int) { + session.setRegion(r, enabled: session.regionEnabled(r), start: session.regionStart(r), end: session.regionEnd(r), + repeats: max(1, session.regionRepeats(r) + delta)) + } +} + +/// The song revision and play state, deduplicated, so toolbars refresh on edits +/// and play/stop but not on every playhead line (AppModel publishes those too). +@MainActor +final class TrackerMirror: ObservableObject { + @Published private(set) var revision = 0 + @Published private(set) var isPlaying = false + private var subs: Set = [] + + init(_ app: AppModel) { + revision = app.revision + isPlaying = app.isPlaying + app.$revision.removeDuplicates().sink { [weak self] in self?.revision = $0 }.store(in: &subs) + app.$isPlaying.removeDuplicates().sink { [weak self] in self?.isPlaying = $0 }.store(in: &subs) + } +} + +/// Notes held on the punch-in keyboard (Android: heldNotes), lighting the keys. +@MainActor +final class TrackerHeldNotes: ObservableObject { + static let shared = TrackerHeldNotes() + @Published private(set) var counts: [Int: Int] = [:] + /// Channel each sounding note went out on, so note-off matches it. + private var channels: [Int: Int] = [:] + + func isHeld(_ midi: Int) -> Bool { (counts[midi] ?? 0) > 0 } + + func on(_ midi: Int, app: AppModel) { + counts[midi, default: 0] += 1 + channels[midi] = app.kbdChannel + SizzleSession.shared.note(on: midi, velocity: min(max(app.kbdVelocity, 0), 127), midiChannel: app.kbdChannel) + } + + func off(_ midi: Int, app: AppModel) { + let n = (counts[midi] ?? 0) - 1 + if n <= 0 { counts[midi] = nil } else { counts[midi] = n } + SizzleSession.shared.noteOff(midi, midiChannel: channels[midi] ?? app.kbdChannel) + } + + /// Release everything (the keyboard went away mid-press). + func releaseAll() { + for (midi, ch) in channels where (counts[midi] ?? 0) > 0 { SizzleSession.shared.noteOff(midi, midiChannel: ch) } + counts.removeAll() + } +} + +/// A one-axis scroll position with drag and fling (exponential decay), shared by +/// the pattern grid (vertical) and the arrangement roll (horizontal). Plain +/// SwiftUI: a 60 Hz timer stands in for a display link. +@MainActor +final class TrackerScroller: ObservableObject { + @Published var offset: CGFloat = 0 + private var timer: Timer? + private var velocity: CGFloat = 0 + private var maxOffset: CGFloat = 0 + private var lastTick: TimeInterval = 0 + private let tau: CGFloat = 0.325 + + var isFlinging: Bool { timer != nil } + + func stop() { timer?.invalidate(); timer = nil } + + /// Coast [distance] points (the gesture's predicted overshoot) in the scroll direction. + func fling(distance: CGFloat, max: CGFloat) { + stop() + guard abs(distance) > 4 else { return } + maxOffset = max + velocity = distance / tau + lastTick = Date().timeIntervalSinceReferenceDate + let t = Timer(timeInterval: 1.0 / 60, repeats: true) { [weak self] _ in + Task { @MainActor in self?.tick() } + } + RunLoop.main.add(t, forMode: .common) + timer = t + } + + private func tick() { + let now = Date().timeIntervalSinceReferenceDate + let dt = CGFloat(now - lastTick) + lastTick = now + let next = min(max(offset + velocity * dt, 0), maxOffset) + velocity *= exp(-dt / tau) + if next != offset { offset = next } + if abs(velocity) < 12 || next <= 0 || next >= maxOffset { stop() } + } +} diff --git a/ios/app/Host/Screens/Tracker/TrackerWidgets.swift b/ios/app/Host/Screens/Tracker/TrackerWidgets.swift new file mode 100644 index 0000000..1e363c1 --- /dev/null +++ b/ios/app/Host/Screens/Tracker/TrackerWidgets.swift @@ -0,0 +1,186 @@ +// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown +// SPDX-License-Identifier: GPL-3.0-or-later + +import SwiftUI + +/// The Android "Amber CRT" palette slots the shared Theme doesn't have (beat/bar +/// row tints, the playhead green, the danger red), plus Theme's own for brevity. +enum TK { + static let background = Theme.background + static let surface = Theme.surface + static let grid = Theme.grid + static let text = Theme.text + static let dim = Theme.dim + static let accent = Theme.accent + static let beat = Color(red: 0x14 / 255, green: 0x1C / 255, blue: 0x1A / 255) + static let bar = Color(red: 0x1E / 255, green: 0x2A / 255, blue: 0x20 / 255) + static let playhead = Color(red: 0x7C / 255, green: 0xFC / 255, blue: 0x9A / 255) + static let danger = Color(red: 0xE0 / 255, green: 0x5A / 255, blue: 0x4B / 255) + + /// Pitch.name: 60 → "C-4", 61 → "C#4" (MIDI 12 == C0). + static let noteNames: [String] = (0..<128).map { m in + let names = ["C-", "C#", "D-", "D#", "E-", "F-", "F#", "G-", "G#", "A-", "A#", "B-"] + return names[m % 12] + String(m / 12 - 1) + } + static func noteName(_ midi: Int) -> String { (0..<128).contains(midi) ? noteNames[midi] : "..." } + static let hex2: [String] = (0..<256).map { String(format: "%02X", $0) } + static let chan2: [String] = (0..<100).map { String(format: "%02d", $0) } +} + +/// Android's RetroButton: flat, square, 1 pt border, monospace label. [active] +/// paints it in the accent colour, [danger] in red; [width] pins the width. +struct TKButton: View { + let label: String + var active = false + var width: CGFloat? = nil + var danger = false + let action: () -> Void + + var body: some View { + TKButtonFace(label: label, active: active, width: width, danger: danger) + .contentShape(Rectangle()) + .onTapGesture(perform: action) + } +} + +struct TKButtonFace: View { + let label: String + var active = false + var width: CGFloat? = nil + var danger = false + + var body: some View { + let hue: Color? = danger ? TK.danger : (active ? TK.accent : nil) + Text(label) + .font(Theme.mono(12)).lineLimit(1).truncationMode(.tail) + .foregroundColor(hue ?? TK.text) + .padding(.horizontal, 10).padding(.vertical, 6) + .frame(width: width) + .background(hue.map { $0.opacity(0.18) } ?? TK.surface) + .overlay(Rectangle().stroke(hue ?? TK.grid, lineWidth: 1)) + .fixedSize(horizontal: width == nil, vertical: true) + } +} + +/// Android's RepeatButton: steps once on press, then repeats while held with the +/// interval shrinking (320 ms × 0.8 per step, down to 24 ms). Lifting the finger +/// or sliding off (more than a few points) stops it. +struct TKRepeatButton: View { + let label: String + var active = false + var width: CGFloat? = nil + let onStep: () -> Void + + @State private var repeater = Repeater() + + var body: some View { + TKButtonFace(label: label, active: active, width: width) + .contentShape(Rectangle()) + .gesture(DragGesture(minimumDistance: 0) + .onChanged { g in + if !repeater.pressed { + repeater.start(onStep) + } else if abs(g.translation.width) > 12 || abs(g.translation.height) > 12 { + repeater.stop() + } + } + .onEnded { _ in repeater.stop(); repeater.pressed = false }) + .onDisappear { repeater.stop() } + } + + final class Repeater { + var pressed = false + private var timer: Timer? + private var delay: TimeInterval = 0.32 + + func start(_ step: @escaping () -> Void) { + pressed = true + step() + delay = 0.32 + schedule(step) + } + + private func schedule(_ step: @escaping () -> Void) { + let t = Timer(timeInterval: delay, repeats: false) { [weak self] _ in + guard let self = self, self.timer != nil else { return } + step() + self.delay = max(0.024, self.delay * 0.8) + self.schedule(step) + } + RunLoop.main.add(t, forMode: .common) + timer = t + } + + func stop() { timer?.invalidate(); timer = nil } + } +} + +/// Android's RetroDropdown, `LABEL:value ▾`, sized to its longest option so it +/// never resizes. Tap opens a menu of the options. +struct TKDropdown: View { + let label: String + let options: [T] + let selected: T + let optionLabel: (T) -> String + let onSelect: (T) -> Void + + init(_ label: String, options: [T], selected: T, optionLabel: @escaping (T) -> String = { "\($0)" }, + onSelect: @escaping (T) -> Void) { + self.label = label; self.options = options; self.selected = selected + self.optionLabel = optionLabel; self.onSelect = onSelect + } + + var body: some View { + if Snapshot.active { face } else { + Menu { + ForEach(options, id: \.self) { o in + Button { onSelect(o) } label: { + if o == selected { Label(optionLabel(o), systemImage: "checkmark") } else { Text(optionLabel(o)) } + } + } + } label: { face } + } + } + + private var face: some View { + let prefix = label.isEmpty ? "" : label + ":" + let longest = options.map(optionLabel).max { $0.count < $1.count } ?? "" + return ZStack(alignment: .leading) { + Text(prefix + longest + " ▾").hidden() + Text(prefix + optionLabel(selected) + " ▾").foregroundColor(TK.text) + } + .font(Theme.mono(12)).lineLimit(1) + .padding(.horizontal, 8).padding(.vertical, 6) + .background(TK.surface) + .overlay(Rectangle().stroke(TK.grid, lineWidth: 1)) + .fixedSize() + } +} + +/// A horizontally scrolling row (a plain row in snapshot mode: ImageRenderer +/// can't draw scroll views). +struct TKHScroll: View { + @ViewBuilder let content: () -> Content + var body: some View { + if Snapshot.active { + content().fixedSize(horizontal: true, vertical: false) + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading).clipped() + } else { + ScrollView(.horizontal, showsIndicators: false) { content() } + } + } +} + +/// Android's Row(horizontalArrangement = SpaceBetween): items spread edge to edge. +struct TKJustifiedRow: View { + let items: [AnyView] + var body: some View { + HStack(spacing: 0) { + ForEach(items.indices, id: \.self) { i in + if i > 0 { Spacer(minLength: 4) } + items[i] + } + } + .frame(maxWidth: .infinity) + } +} diff --git a/ios/app/Host/Screens/TrackerScreen.swift b/ios/app/Host/Screens/TrackerScreen.swift deleted file mode 100644 index 8e5cea0..0000000 --- a/ios/app/Host/Screens/TrackerScreen.swift +++ /dev/null @@ -1,12 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown -// SPDX-License-Identifier: GPL-3.0-or-later - -import SwiftUI - -/// Placeholder: being ported from the Android app. -struct TrackerScreen: View { - @EnvironmentObject var app: AppModel - var body: some View { - Text("Tracker").font(Theme.mono(18)).foregroundColor(Theme.dim) - } -} diff --git a/ios/app/Host/SizzleSession+Internal.h b/ios/app/Host/SizzleSession+Internal.h index fde1d38..9c51765 100644 --- a/ios/app/Host/SizzleSession+Internal.h +++ b/ios/app/Host/SizzleSession+Internal.h @@ -16,6 +16,8 @@ - (void)edit:(void (^)(sizzle::model::Project &p, sizzle::engine::Engine &e))body; /// Read the song consistently: [body] runs under the lock, nothing is posted. - (void)read:(void (^)(const sizzle::model::Project &p, const sizzle::engine::Engine &e))body; +/// Put back into the store every sample the song refers to (Documents/samples). +- (void)rehydrateSamples; /// The sample store (thread-safe on its own). - (sizzle::sampler::SampleStore &)sampleStore; @end diff --git a/ios/app/Host/SizzleSession+Mix.h b/ios/app/Host/SizzleSession+Mix.h index 54fa2fd..4035dbd 100644 --- a/ios/app/Host/SizzleSession+Mix.h +++ b/ios/app/Host/SizzleSession+Mix.h @@ -5,8 +5,43 @@ NS_ASSUME_NONNULL_BEGIN -/// API the Mix screen needs beyond SizzleSession.h. +/// API the Mix and Toolbox screens need beyond SizzleSession.h. @interface SizzleSession (Mix) + +#pragma mark - Slot samples (Sampler pads "padN", the SF2/XI loader's "sfSample") +/// Frames / sample rate of the sample a slot key refers to (0 when none is loaded). +- (NSInteger)sampleFramesOfSlot:(NSInteger)slot key:(NSString *)key; +- (NSInteger)sampleRateOfSlot:(NSInteger)slot key:(NSString *)key; +/// The sample as [buckets] (min, max) float pairs for drawing (Android's computePeaks), +/// or nil when none is loaded. +- (nullable NSData *)samplePeaksOfSlot:(NSInteger)slot key:(NSString *)key buckets:(NSInteger)buckets; +/// SamplerEditor's CLIP: replace the pad's sample with its slice; markers reset. NO if nothing to trim. +- (BOOL)trimPad:(NSInteger)pad ofSlot:(NSInteger)slot; +/// NORMALIZE: peak-normalise the pad's sample to full scale. NO if empty, silent or already full. +- (BOOL)normalizePad:(NSInteger)pad ofSlot:(NSInteger)slot; +/// CLEAR: forget the pad's sample and slice markers. +- (void)clearPad:(NSInteger)pad ofSlot:(NSInteger)slot; + +#pragma mark - MIDI LFO +/// Point LFO [slot] at [target]'s parameter [key] ("slot:key"), capturing that +/// parameter's current value as the modulation centre; target < 0 clears it. +- (void)setLfoTargetOfSlot:(NSInteger)slot target:(NSInteger)target key:(NSString *)key; + +#pragma mark - Preset library (Documents/presets//.szp, PresetIo text) +/// Saved presets for a device type, alphabetically. The type's factory presets are +/// written into the library the first time (Android's seedFactoryPresets), so a +/// deleted one stays deleted. +- (NSArray *)libraryPresetsForType:(NSString *)type; +/// Save [slot] under [name] (the slot takes that name). +- (BOOL)savePresetOfSlot:(NSInteger)slot name:(NSString *)name; +/// Load a saved preset into [slot] (renamed to the preset). +- (BOOL)loadPreset:(NSString *)name intoSlot:(NSInteger)slot; +- (BOOL)deletePreset:(NSString *)name type:(NSString *)type; +/// Import preset text into [slot] (it takes the preset's device type) and save it to the library. +- (BOOL)importPresetText:(NSString *)text intoSlot:(NSInteger)slot; +/// The preset's file, for sharing (nil when missing). +- (nullable NSURL *)presetFileForType:(NSString *)type name:(NSString *)name; + @end NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleSession+Mix.mm b/ios/app/Host/SizzleSession+Mix.mm index ed1e00c..112e8a7 100644 --- a/ios/app/Host/SizzleSession+Mix.mm +++ b/ios/app/Host/SizzleSession+Mix.mm @@ -4,7 +4,273 @@ #import "SizzleSession+Mix.h" #import "SizzleSession+Internal.h" +#include +#include +#include +#include +#include +#include "io/PresetIo.hpp" +#include "sizzle/DeviceSpecs.gen.hpp" + using namespace sizzle; -@implementation SizzleSession (Mix) +/// SizzleSession.mm's own: put back into the store the samples the song refers to. +@interface SizzleSession (MixPrivate) +- (void)rehydrateSamples; +@end + +namespace { + +std::string padKey(NSInteger pad) { return "pad" + std::to_string(pad); } + +/// PresetLibrary.sanitize: [A-Za-z0-9._ -] kept, anything else "_", blank "preset". +NSString *sanitize(NSString *name) { + NSString *t = [name stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceAndNewlineCharacterSet]; + NSMutableString *out = [NSMutableString string]; + for (NSUInteger i = 0; i < t.length; ++i) { + unichar c = [t characterAtIndex:i]; + BOOL ok = (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '.' || c == '_' || c == ' ' || c == '-'; + [out appendString:ok ? [NSString stringWithCharacters:&c length:1] : @"_"]; + } + return out.length ? out : @"preset"; +} + +} // namespace + +@implementation SizzleSession (Mix) + +#pragma mark - samples + +/// The sample id a slot key holds ("" when none). +- (std::string)mixSampleId:(NSInteger)slot key:(NSString *)key { + __block std::string id; + std::string k = key.UTF8String; + [self read:^(const model::Project &p, const engine::Engine &) { + if (slot >= 0 && slot < model::Project::TOOLBOX_SLOTS) id = p.toolbox[(size_t)slot].s(k.c_str(), ""); + }]; + return id; +} + +- (const Sample *)mixSample:(NSInteger)slot key:(NSString *)key { + std::string id = [self mixSampleId:slot key:key]; + return id.empty() ? nullptr : [self sampleStore].get(id.c_str()); +} + +- (NSInteger)sampleFramesOfSlot:(NSInteger)slot key:(NSString *)key { + const Sample *s = [self mixSample:slot key:key]; + return s ? (NSInteger)s->data.size() : 0; +} + +- (NSInteger)sampleRateOfSlot:(NSInteger)slot key:(NSString *)key { + const Sample *s = [self mixSample:slot key:key]; + return s ? s->sampleRate : 0; +} + +- (NSData *)samplePeaksOfSlot:(NSInteger)slot key:(NSString *)key buckets:(NSInteger)buckets { + const Sample *s = [self mixSample:slot key:key]; + if (!s || buckets <= 0) return nil; + const std::vector &data = s->data; + std::vector out((size_t)buckets * 2, 0.f); + if (!data.empty()) { + size_t step = std::max(1, data.size() / (size_t)buckets); + for (size_t b = 0; b < (size_t)buckets; ++b) { + size_t start = b * step; + if (start >= data.size()) break; + size_t end = std::min(start + step, data.size()); + float mn = 1.f, mx = -1.f; + for (size_t i = start; i < end; ++i) { mn = std::min(mn, data[i]); mx = std::max(mx, data[i]); } + out[2 * b] = std::clamp(mn, -1.f, 1.f); + out[2 * b + 1] = std::clamp(mx, -1.f, 1.f); + } + } + return [NSData dataWithBytes:out.data() length:out.size() * sizeof(float)]; +} + +/// Store [sample] as a new sample for the pad (a fresh id, so pads sharing the old one keep it). +- (BOOL)mixReplacePad:(NSInteger)pad ofSlot:(NSInteger)slot with:(const Sample &)sample name:(NSString *)name { + std::vector wav = sampler::SampleStore::encodeWav(sample); + return [self loadSampleData:[NSData dataWithBytes:wav.data() length:wav.size()] name:name intoSlot:slot pad:pad error:nil]; +} + +- (BOOL)trimPad:(NSInteger)pad ofSlot:(NSInteger)slot { + NSString *key = @(padKey(pad).c_str()); + const Sample *s = [self mixSample:slot key:key]; + if (!s) return NO; + size_t len = s->data.size(); + if (len <= 1) return NO; + std::string sk = padKey(pad) + "S", ek = padKey(pad) + "E"; + __block float a = 0, b = 1; + [self read:^(const model::Project &p, const engine::Engine &) { + a = std::clamp(p.toolbox[(size_t)slot].f(sk.c_str(), 0.f), 0.f, 1.f); + b = std::clamp(p.toolbox[(size_t)slot].f(ek.c_str(), 1.f), 0.f, 1.f); + }]; + size_t start = std::min((size_t)(std::min(a, b) * (float)len), len - 1); + size_t end = std::clamp((size_t)(std::max(a, b) * (float)len), start + 1, len); + if (start == 0 && end == len) return NO; // the slice already spans the whole sample + Sample cut; + cut.data.assign(s->data.begin() + (long)start, s->data.begin() + (long)end); + cut.sampleRate = s->sampleRate; + if (![self mixReplacePad:pad ofSlot:slot with:cut name:@"trim"]) return NO; + [self edit:^(model::Project &p, engine::Engine &) { + p.toolbox[(size_t)slot].set(sk.c_str(), 0.f); + p.toolbox[(size_t)slot].set(ek.c_str(), 1.f); + }]; + return YES; +} + +- (BOOL)normalizePad:(NSInteger)pad ofSlot:(NSInteger)slot { + const Sample *s = [self mixSample:slot key:@(padKey(pad).c_str())]; + if (!s || s->data.empty()) return NO; + float peak = 0; + for (float v : s->data) peak = std::max(peak, std::fabs(v)); + if (peak <= 0) return NO; // silent: nothing to normalise + float gain = 1.f / peak; + if (gain >= 0.999f && gain <= 1.001f) return NO; // already at full scale + Sample out; + out.data.resize(s->data.size()); + for (size_t i = 0; i < s->data.size(); ++i) out.data[i] = std::clamp(s->data[i] * gain, -1.f, 1.f); + out.sampleRate = s->sampleRate; + return [self mixReplacePad:pad ofSlot:slot with:out name:@"norm"]; +} + +- (void)clearPad:(NSInteger)pad ofSlot:(NSInteger)slot { + std::string k = padKey(pad), sk = k + "S", ek = k + "E"; + [self edit:^(model::Project &p, engine::Engine &) { + if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return; + model::ToolboxSlot &s = p.toolbox[(size_t)slot]; + Params kept; // Params has no remove: copy everything else + for (int i = 0; i < s.values.size(); ++i) { + const char *key = s.values.keyAt(i); + if (k == key || sk == key || ek == key) continue; + kept.set(key, s.values.valueAt(i)); + } + s.values = kept; + ++s.version; + }]; +} + +#pragma mark - LFO + +- (void)setLfoTargetOfSlot:(NSInteger)slot target:(NSInteger)target key:(NSString *)key { + std::string k = key.UTF8String; + [self edit:^(model::Project &p, engine::Engine &) { + if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return; + model::ToolboxSlot &lfo = p.toolbox[(size_t)slot]; + if (target < 0 || target >= model::Project::TOOLBOX_SLOTS) { lfo.set("target", ""); return; } + const model::ToolboxSlot &t = p.toolbox[(size_t)target]; + float def = 0; + if (const DeviceSpec *d = findDevice(t.type.c_str())) + for (int i = 0; i < d->paramCount; ++i) if (k == d->params[i].key) def = d->params[i].def; + lfo.set("target", (std::to_string(target) + ":" + k).c_str()); + lfo.set("center", t.f(k.c_str(), def)); + }]; +} + +#pragma mark - preset library + +- (NSURL *)mixPresetDir:(NSString *)type { + NSURL *docs = [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject; + NSURL *dir = [[docs URLByAppendingPathComponent:@"presets"] URLByAppendingPathComponent:type]; + [NSFileManager.defaultManager createDirectoryAtURL:dir withIntermediateDirectories:YES attributes:nil error:nil]; + return dir; +} + +- (NSURL *)mixPresetURL:(NSString *)type name:(NSString *)name { + return [[self mixPresetDir:type] URLByAppendingPathComponent:[sanitize(name) stringByAppendingString:@".szp"]]; +} + +/// PresetLibrary.seedType: write the type's factory presets once; the marker lists +/// the names already written so a preset the user deletes isn't brought back. +- (void)mixSeedType:(NSString *)type { + NSURL *marker = [[self mixPresetDir:type] URLByAppendingPathComponent:@".seeded"]; + NSString *text = [NSString stringWithContentsOfURL:marker encoding:NSUTF8StringEncoding error:nil]; + NSMutableSet *seeded = [NSMutableSet set]; + for (NSString *line in [text componentsSeparatedByString:@"\n"]) { + NSString *t = [line stringByTrimmingCharactersInSet:NSCharacterSet.whitespaceCharacterSet]; + if (t.length && ![t isEqualToString:@"1"]) [seeded addObject:t]; + } + BOOL changed = NO; + std::string ty = type.UTF8String; + for (int i = 0; i < gen::factoryPresetCount; ++i) { + const auto &f = gen::factoryPresets[i]; + if (ty != f.type) continue; + NSString *name = @(f.name); + if ([seeded containsObject:name]) continue; + NSURL *url = [self mixPresetURL:type name:name]; + if (![NSFileManager.defaultManager fileExistsAtPath:url.path]) { + model::ToolboxSlot s; + s.fill(ty); + for (int k = 0; f.values[k] && f.values[k + 1]; k += 2) s.set(f.values[k], f.values[k + 1]); + s.name = f.name; + [@(io::PresetIo::exportText(s).c_str()) writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:nil]; + } + [seeded addObject:name]; + changed = YES; + } + if (changed || !text) + [[seeded.allObjects componentsJoinedByString:@"\n"] writeToURL:marker atomically:YES encoding:NSUTF8StringEncoding error:nil]; +} + +- (NSArray *)libraryPresetsForType:(NSString *)type { + if (!type.length) return @[]; + [self mixSeedType:type]; + NSArray *files = [NSFileManager.defaultManager contentsOfDirectoryAtURL:[self mixPresetDir:type] + includingPropertiesForKeys:nil options:0 error:nil]; + NSMutableArray *names = [NSMutableArray array]; + for (NSURL *u in files) if ([u.pathExtension isEqualToString:@"szp"]) [names addObject:u.URLByDeletingPathExtension.lastPathComponent]; + return [names sortedArrayUsingSelector:@selector(compare:)]; +} + +- (BOOL)savePresetOfSlot:(NSInteger)slot name:(NSString *)name { + NSString *type = [self typeOfSlot:slot]; + if (!type.length) return NO; + std::string n = name.UTF8String; + __block std::string text; + [self edit:^(model::Project &p, engine::Engine &) { + model::ToolboxSlot &s = p.toolbox[(size_t)slot]; + s.name = n; + text = io::PresetIo::exportText(s); + }]; + return [@(text.c_str()) writeToURL:[self mixPresetURL:type name:name] atomically:YES encoding:NSUTF8StringEncoding error:nil]; +} + +- (BOOL)loadPreset:(NSString *)name intoSlot:(NSInteger)slot { + NSString *type = [self typeOfSlot:slot]; + if (!type.length) return NO; + NSString *text = [NSString stringWithContentsOfURL:[self mixPresetURL:type name:name] encoding:NSUTF8StringEncoding error:nil]; + if (!text) return NO; + std::string t = text.UTF8String ?: "", n = name.UTF8String; + __block BOOL ok = NO; + [self edit:^(model::Project &p, engine::Engine &e) { + model::ToolboxSlot &s = p.toolbox[(size_t)slot]; + ok = io::PresetIo::importText(s, t); + if (ok) { s.name = n; e.rebuildFxChains(); } + }]; + if (ok) [self rehydrateSamples]; + return ok; +} + +- (BOOL)deletePreset:(NSString *)name type:(NSString *)type { + return [NSFileManager.defaultManager removeItemAtURL:[self mixPresetURL:type name:name] error:nil]; +} + +- (BOOL)importPresetText:(NSString *)text intoSlot:(NSInteger)slot { + if (slot < 0 || slot >= model::Project::TOOLBOX_SLOTS) return NO; + std::string t = text.UTF8String ?: ""; + __block BOOL ok = NO; + [self edit:^(model::Project &p, engine::Engine &e) { + ok = io::PresetIo::importText(p.toolbox[(size_t)slot], t); + if (ok) e.rebuildFxChains(); + }]; + if (!ok) return NO; + [self rehydrateSamples]; + NSString *name = [self nameOfSlot:slot]; + return [self savePresetOfSlot:slot name:name.length ? name : [self typeOfSlot:slot]]; +} + +- (NSURL *)presetFileForType:(NSString *)type name:(NSString *)name { + NSURL *u = [self mixPresetURL:type name:name]; + return [NSFileManager.defaultManager fileExistsAtPath:u.path] ? u : nil; +} + @end diff --git a/ios/app/Host/SizzleSession+Setup.h b/ios/app/Host/SizzleSession+Setup.h index 5ea6061..c1c3c0a 100644 --- a/ios/app/Host/SizzleSession+Setup.h +++ b/ios/app/Host/SizzleSession+Setup.h @@ -7,6 +7,13 @@ NS_ASSUME_NONNULL_BEGIN /// API the Setup screen needs beyond SizzleSession.h. @interface SizzleSession (Setup) +/// Whether [text] is a Sizzle project (.szg): its first non-blank line is the +/// "SIZZLETRACKER-SNG 1" header ProjectIo writes. ProjectIo itself skips bad lines +/// one by one, so any text would "load" as an empty song without this check. ++ (BOOL)looksLikeProjectText:(NSString *)text; +/// Replace the open song with a project file's contents (Import project), after +/// checking it looks like one; the song keeps the name stored in the file. +- (BOOL)importProjectText:(NSString *)text error:(NSError **)error; @end NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleSession+Setup.mm b/ios/app/Host/SizzleSession+Setup.mm index 78433cb..44752d6 100644 --- a/ios/app/Host/SizzleSession+Setup.mm +++ b/ios/app/Host/SizzleSession+Setup.mm @@ -4,7 +4,32 @@ #import "SizzleSession+Setup.h" #import "SizzleSession+Internal.h" +#include "io/KotlinText.hpp" + using namespace sizzle; +static NSError *setupError(NSString *msg) { + return [NSError errorWithDomain:@"Sizzle" code:1 userInfo:@{NSLocalizedDescriptionKey: msg}]; +} + @implementation SizzleSession (Setup) + ++ (BOOL)looksLikeProjectText:(NSString *)text { + std::string t = text.UTF8String ?: ""; + for (const std::string &raw : io::kt::lines(t)) { + const std::string line = io::kt::trim(raw); + if (line.empty()) continue; + return line == "SIZZLETRACKER-SNG 1"; + } + return NO; +} + +- (BOOL)importProjectText:(NSString *)text error:(NSError **)error { + if (![SizzleSession looksLikeProjectText:text]) { + if (error) *error = setupError(@"This doesn't look like a Sizzle project (.szg)."); + return NO; + } + return [self loadProjectText:text error:error]; +} + @end diff --git a/ios/app/Host/SizzleSession+Tracker.h b/ios/app/Host/SizzleSession+Tracker.h index f5a12a5..1fbd06b 100644 --- a/ios/app/Host/SizzleSession+Tracker.h +++ b/ios/app/Host/SizzleSession+Tracker.h @@ -5,8 +5,45 @@ NS_ASSUME_NONNULL_BEGIN -/// API the Tracker screen needs beyond SizzleSession.h. +/// For -fillArrangementFromLane:…: write each lane's own block id (lane i ⟷ block i). +static const NSInteger SizzleArrangementOwnLane = -3; + +/// API the Tracker screen needs beyond SizzleSession.h. Bulk reads and writes, so +/// the grid and the roll cache the song once per revision instead of taking the +/// lock per cell. @interface SizzleSession (Tracker) + +/// Copies the pattern's cells track-major (cells[track * length + line]); returns +/// the pattern's length (0 for no such pattern). Copies nothing when [capacity] is +/// smaller than 4 × length. +- (NSInteger)copyCellsOfPattern:(NSInteger)pattern into:(SizzleCell *)cells capacity:(NSInteger)capacity; + +/// Writes a block of cells (track-major, [width] tracks × [height] lines) with its +/// top-left at track/line, clipped to the pattern (Android's paste, Cell.setFrom). +- (void)writeCells:(const SizzleCell *)cells width:(NSInteger)width height:(NSInteger)height + inPattern:(NSInteger)pattern track:(NSInteger)track line:(NSInteger)line; + +/// Cell.clear() on tracks t0...t1 × lines l0...l1 (inclusive, clipped): empty note, +/// full velocity, channel kept. +- (void)clearCellsInPattern:(NSInteger)pattern fromTrack:(NSInteger)t0 toTrack:(NSInteger)t1 + fromLine:(NSInteger)l0 toLine:(NSInteger)l1; + +/// Android's setTimeSignature: sets the signature and, when the active pattern's +/// length isn't one the new signature allows, snaps it to the shortest option. +- (void)setSignatureSnappingActivePattern:(NSInteger)signature; + +/// The roll's width in beats for the current signature (Arrangement.canvasBeats). +@property (nonatomic, readonly) NSInteger arrangementCanvasBeats; + +/// Copies the arrangement lane-major (slots[lane * beats + beat], 8 lanes): a +/// pattern id, -1 empty or -2 note-off. +- (void)copyArrangementSlots:(int *)slots beats:(NSInteger)beats; + +/// Sets lanes lane0...lane1 × beats beat0...beat1 (inclusive) to [pattern] (-1 empty, +/// -2 note-off, SizzleArrangementOwnLane for each lane's own block) in one edit. +- (void)fillArrangementFromLane:(NSInteger)lane0 toLane:(NSInteger)lane1 + fromBeat:(NSInteger)beat0 toBeat:(NSInteger)beat1 pattern:(NSInteger)pattern; + @end NS_ASSUME_NONNULL_END diff --git a/ios/app/Host/SizzleSession+Tracker.mm b/ios/app/Host/SizzleSession+Tracker.mm index 333be87..5ff7acc 100644 --- a/ios/app/Host/SizzleSession+Tracker.mm +++ b/ios/app/Host/SizzleSession+Tracker.mm @@ -4,7 +4,91 @@ #import "SizzleSession+Tracker.h" #import "SizzleSession+Internal.h" +#include + using namespace sizzle; @implementation SizzleSession (Tracker) + +- (NSInteger)copyCellsOfPattern:(NSInteger)pattern into:(SizzleCell *)cells capacity:(NSInteger)capacity { + __block NSInteger length = 0; + [self read:^(const model::Project &p, const engine::Engine &) { + const model::Pattern *pt = p.pattern((int)pattern); + if (!pt) return; + length = pt->length; + if (capacity < (NSInteger)model::Pattern::TRACK_COUNT * length) return; + for (int t = 0; t < model::Pattern::TRACK_COUNT; ++t) + for (int l = 0; l < pt->length; ++l) { + const model::Cell &c = pt->cell(t, l); + cells[t * length + l] = {c.note, c.velocity, c.channel}; + } + }]; + return length; +} + +- (void)writeCells:(const SizzleCell *)cells width:(NSInteger)width height:(NSInteger)height + inPattern:(NSInteger)pattern track:(NSInteger)track line:(NSInteger)line { + if (width <= 0 || height <= 0) return; + [self edit:^(model::Project &p, engine::Engine &) { + model::Pattern *pt = p.pattern((int)pattern); + if (!pt) return; + for (NSInteger ti = 0; ti < width; ++ti) + for (NSInteger li = 0; li < height; ++li) { + NSInteger t = track + ti, l = line + li; + if (t < 0 || l < 0 || t >= model::Pattern::TRACK_COUNT || l >= pt->length) continue; + const SizzleCell &s = cells[ti * height + li]; + model::Cell &c = pt->cell((int)t, (int)l); + c.note = std::clamp(s.note, -2, 127); + c.velocity = std::clamp(s.velocity, 0, 127); + c.channel = std::clamp(s.channel, 0, 16); + } + }]; +} + +- (void)clearCellsInPattern:(NSInteger)pattern fromTrack:(NSInteger)t0 toTrack:(NSInteger)t1 + fromLine:(NSInteger)l0 toLine:(NSInteger)l1 { + [self edit:^(model::Project &p, engine::Engine &) { + model::Pattern *pt = p.pattern((int)pattern); + if (!pt) return; + for (NSInteger t = std::max(t0, 0); t <= std::min(t1, model::Pattern::TRACK_COUNT - 1); ++t) + for (NSInteger l = std::max(l0, 0); l <= std::min(l1, pt->length - 1); ++l) + pt->cell((int)t, (int)l).clear(); + }]; +} + +- (void)setSignatureSnappingActivePattern:(NSInteger)sig { + if (sig < 0 || sig >= model::TIME_SIGNATURE_COUNT) return; + [self edit:^(model::Project &p, engine::Engine &e) { + p.timeSignature = (model::TimeSignature)sig; + const model::TimeSignatureInfo &ti = model::info(p.timeSignature); + model::Pattern &pt = p.activePattern(); + const int *opts = ti.lengthOptions; + if (std::find(opts, opts + 3, pt.length) == opts + 3) pt.resize(opts[0]); + e.rebuildArrangement(); + }]; +} + +- (NSInteger)arrangementCanvasBeats { + __block NSInteger beats = 1; + [self read:^(const model::Project &p, const engine::Engine &) { beats = p.arrangement.canvasBeats(p.timeSignature); }]; + return beats; +} + +- (void)copyArrangementSlots:(int *)slots beats:(NSInteger)beats { + [self read:^(const model::Project &p, const engine::Engine &) { + for (int lane = 0; lane < model::Arrangement::LANE_COUNT; ++lane) + for (NSInteger b = 0; b < beats; ++b) slots[lane * beats + b] = p.arrangement.patternAt(lane, (int)b); + }]; +} + +- (void)fillArrangementFromLane:(NSInteger)lane0 toLane:(NSInteger)lane1 + fromBeat:(NSInteger)beat0 toBeat:(NSInteger)beat1 pattern:(NSInteger)pattern { + [self edit:^(model::Project &p, engine::Engine &e) { + for (NSInteger lane = std::max(lane0, 0); lane <= std::min(lane1, model::Arrangement::LANE_COUNT - 1); ++lane) + for (NSInteger b = std::max(beat0, 0); b <= std::min(beat1, model::Arrangement::MAX_BEATS - 1); ++b) + p.arrangement.set((int)lane, (int)b, pattern == SizzleArrangementOwnLane ? (int)lane : (int)pattern); + e.rebuildArrangement(); + }]; +} + @end diff --git a/ios/app/Host/SizzleSession.mm b/ios/app/Host/SizzleSession.mm index e020835..a844520 100644 --- a/ios/app/Host/SizzleSession.mm +++ b/ios/app/Host/SizzleSession.mm @@ -439,7 +439,7 @@ bool isSampleKey(const char *key) { } - (void)applyFactoryPreset:(NSString *)name toSlot:(NSInteger)slot { std::string n = name.UTF8String; - [self edit:^(model::Project &p, engine::Engine &) { + [self edit:^(model::Project &p, engine::Engine &e) { if (slot < 0 || slot >= 16) return; model::ToolboxSlot &s = p.toolbox[(size_t)slot]; for (int i = 0; i < gen::factoryPresetCount; ++i) { @@ -448,6 +448,7 @@ bool isSampleKey(const char *key) { for (int k = 0; kv[k] && kv[k + 1]; k += 2) s.set(kv[k], kv[k + 1]); s.name = n; } + e.rebuildFxChains(); }]; } @@ -490,11 +491,15 @@ bool isSampleKey(const char *key) { - (BOOL)loadSongNamed:(NSString *)name error:(NSError **)error { NSString *text = [NSString stringWithContentsOfURL:[self songURL:name] encoding:NSUTF8StringEncoding error:error]; - return text && [self loadProjectText:text error:error]; + if (!text || ![self loadProjectText:text error:error]) return NO; + self.songName = name; // as Android's loadSong: the file's name wins + return YES; } - (BOOL)deleteSongNamed:(NSString *)name error:(NSError **)error { - return [NSFileManager.defaultManager removeItemAtURL:[self songURL:name] error:error]; + BOOL ok = [NSFileManager.defaultManager removeItemAtURL:[self songURL:name] error:error]; + if (ok) [self changed]; + return ok; } - (void)newSong { diff --git a/versions.properties b/versions.properties index 294a448..28f7be8 100644 --- a/versions.properties +++ b/versions.properties @@ -17,8 +17,8 @@ android.versionCode = 70 # iOS/iPadOS (cc.tiredsysadmin.ios.sizzle): the AUv3 plugin app in ios/app; the # Makefile there passes these to Xcode and names the .ipa by versionCode. (The # TrollStore spike in ios/spike keeps its own version in its project.yml.) -ios.versionName = 0.3.1 -ios.versionCode = 7 +ios.versionName = 0.4.0 +ios.versionCode = 8 macos.versionName = - linux.versionName = - bsd.versionName = -