iOS 0.6.0: milestone 5 (recording, MIDI, input bindings, themes, bundles, backups)
- Master recording (MasterSink ring + writer thread) and the sample recorder - CoreMIDI in/out: sound module, clock send/follow, virtual "Sizzle" ports; platform-free parser/module/clock in core (midi_test) - Hardware keyboard and gamepads via GameController; rebindable keyboard, gamepad and MIDI CC actions; per-parameter MIDI learn - Colour themes (.szt), project bundles (.szgz), backup & restore; ZIP in core with zlib (zip_test against jar and unzip) - Persistent app settings; audio pauses in the background unless sound module Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
435305e42a
commit
64e21e0bcc
@@ -50,6 +50,22 @@ extension EnvironmentValues {
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's microphone recorder for editors that take a recording (the Grain
|
||||
/// Cloud's RECORD); nil in the plugin, which shows no RECORD button.
|
||||
struct DeviceRecordControl {
|
||||
let isRecording: Bool
|
||||
let toggle: () -> Void
|
||||
}
|
||||
private struct DeviceRecorderKey: EnvironmentKey {
|
||||
static let defaultValue: DeviceRecordControl? = nil
|
||||
}
|
||||
extension EnvironmentValues {
|
||||
var deviceRecorder: DeviceRecordControl? {
|
||||
get { self[DeviceRecorderKey.self] }
|
||||
set { self[DeviceRecorderKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand-built pieces of device editors (the Android app's bespoke editors), by
|
||||
/// device. DeviceEditor asks here first and falls back to the card layout. Each
|
||||
/// device's views live in their own file in this folder.
|
||||
|
||||
@@ -18,7 +18,7 @@ enum DelayBespoke {
|
||||
"1/4T", "1/8", "1/16.", "1/8T", "1/16", "1/16T"]
|
||||
static var divisions: [String] { Layouts.file?.delayDivisions ?? fallbackDivisions }
|
||||
/// Android's default theme's playhead green (the selected-step band).
|
||||
static let band = Color(red: 0x7C / 255.0, green: 0xFC / 255.0, blue: 0x9A / 255.0)
|
||||
static var band: Color { Theme.playhead }
|
||||
}
|
||||
|
||||
private struct DelayEditorView: View {
|
||||
|
||||
@@ -14,7 +14,8 @@ protocol SampleLengthSource: AnyObject {
|
||||
|
||||
/// The Grain Cloud's source strip (Android's GrainCloudEditor.kt): load a WAV (or
|
||||
/// SF2/XI) as the cloud's own source, and see the source with its START..END region
|
||||
/// lit. The settings themselves are the card pages below it. (RECORD isn't ported.)
|
||||
/// lit. The settings themselves are the card pages below it. RECORD (the app only)
|
||||
/// makes a microphone take the source.
|
||||
@MainActor
|
||||
enum GrainCloudBespoke {
|
||||
static func header(_ model: DeviceModel) -> AnyView? { AnyView(GrainSourceStrip(model: model)) }
|
||||
@@ -39,6 +40,7 @@ struct GrainSourceStrip: View {
|
||||
@ObservedObject var model: DeviceModel
|
||||
@State private var pickerShown = false
|
||||
@Environment(\.deviceFilePicker) private var hostPicker
|
||||
@Environment(\.deviceRecorder) private var recorder
|
||||
@State private var importError: String?
|
||||
/// Bumped while a built-in source is still being rendered, to look again.
|
||||
@State private var retry = 0
|
||||
@@ -63,6 +65,15 @@ struct GrainSourceStrip: View {
|
||||
.overlay(Rectangle().stroke(Theme.accent.opacity(0.6), lineWidth: 1))
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture { if let pick = hostPicker { pick { url in load(url) } } else { pickerShown = true } }
|
||||
if let rec = recorder {
|
||||
Text(rec.isRecording ? "■ STOP REC" : "● RECORD").font(Theme.mono(12))
|
||||
.foregroundColor(rec.isRecording ? Theme.background : Theme.accent)
|
||||
.padding(.horizontal, 10).padding(.vertical, 6)
|
||||
.background(rec.isRecording ? Theme.accent : Theme.surface)
|
||||
.overlay(Rectangle().stroke(Theme.accent.opacity(0.6), lineWidth: 1))
|
||||
.contentShape(Rectangle())
|
||||
.onTapGesture(perform: rec.toggle)
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
Text(caption).font(Theme.mono(10)).foregroundColor(Theme.dim)
|
||||
|
||||
@@ -18,14 +18,38 @@ struct SnapScroll<Content: View>: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sizzle's dark retro palette (Android's default theme) and the card tones.
|
||||
/// A colour theme (Android's RetroPalette), colours as 0xRRGGBB.
|
||||
struct Palette: Equatable {
|
||||
var name: String
|
||||
var background, surface, grid, text, textDim, accent, beat, bar, playhead, danger: UInt32
|
||||
|
||||
static let amber = Palette(name: "Amber CRT", background: 0x0B0D0E, surface: 0x15181A, grid: 0x23282B,
|
||||
text: 0xCFE8D8, textDim: 0x6E7C74, accent: 0xF2C14E, beat: 0x141C1A, bar: 0x1E2A20,
|
||||
playhead: 0x7CFC9A, danger: 0xE05A4B)
|
||||
static let ice = Palette(name: "Ice Terminal", background: 0x07090F, surface: 0x10151F, grid: 0x1E2633,
|
||||
text: 0xCFE0FF, textDim: 0x63708A, accent: 0x62B6FF, beat: 0x121A26, bar: 0x1B2740,
|
||||
playhead: 0x8AF0FF, danger: 0xE05A7A)
|
||||
static let stock = [amber, ice]
|
||||
|
||||
static func color(_ rgb: UInt32) -> Color {
|
||||
Color(red: Double((rgb >> 16) & 0xFF) / 255, green: Double((rgb >> 8) & 0xFF) / 255, blue: Double(rgb & 0xFF) / 255)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sizzle's retro palette (the current theme; the plugins always use the default)
|
||||
/// and the card tones. The app redraws everything when the theme changes.
|
||||
enum Theme {
|
||||
static let background = Color(red: 0.07, green: 0.08, blue: 0.09)
|
||||
static let surface = Color(red: 0.11, green: 0.12, blue: 0.14)
|
||||
static let grid = Color(white: 0.24)
|
||||
static let text = Color(white: 0.92)
|
||||
static let dim = Color(white: 0.58)
|
||||
static let accent = Color(red: 0.96, green: 0.76, blue: 0.29)
|
||||
static var current = Palette.amber
|
||||
static var background: Color { Palette.color(current.background) }
|
||||
static var surface: Color { Palette.color(current.surface) }
|
||||
static var grid: Color { Palette.color(current.grid) }
|
||||
static var text: Color { Palette.color(current.text) }
|
||||
static var dim: Color { Palette.color(current.textDim) }
|
||||
static var accent: Color { Palette.color(current.accent) }
|
||||
static var beat: Color { Palette.color(current.beat) }
|
||||
static var bar: Color { Palette.color(current.bar) }
|
||||
static var playhead: Color { Palette.color(current.playhead) }
|
||||
static var danger: Color { Palette.color(current.danger) }
|
||||
|
||||
static func tone(_ t: LayoutPanel.Tone) -> Color {
|
||||
switch t {
|
||||
|
||||
@@ -152,7 +152,7 @@ struct CardView: View {
|
||||
public final class SizzleEditorFactory: NSObject {
|
||||
@objc public static func makeEditor(for au: SizzleDeviceAU) -> UIViewController {
|
||||
let vc = UIHostingController(rootView: DeviceEditor(model: DeviceModel(au: au)))
|
||||
vc.view.backgroundColor = UIColor(red: 0.07, green: 0.08, blue: 0.09, alpha: 1)
|
||||
vc.view.backgroundColor = UIColor(Theme.background)
|
||||
return vc
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,6 +101,12 @@ final class DeviceModel: ObservableObject {
|
||||
return info.choices[Swift.max(0, Swift.min(info.choices.count - 1, i))]
|
||||
}
|
||||
|
||||
/// Read the values again (changed elsewhere: a MIDI CC bound to a parameter).
|
||||
func refresh() {
|
||||
let v = reread()
|
||||
if v != values { values = v }
|
||||
}
|
||||
|
||||
func applyPreset(named name: String) {
|
||||
applyPresetNamed(name)
|
||||
presetName = name
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// Everything that runs once at launch, before any screen (Android's SizzleApp):
|
||||
/// settings that live outside the song, MIDI, and the hardware input sources.
|
||||
@MainActor
|
||||
enum AppBoot {
|
||||
static func start() {
|
||||
let settings = AppSettings.shared
|
||||
let session = SizzleSession.shared
|
||||
session.recordTailBars = settings.recordTailBars
|
||||
ThemeLibrary.shared.select(settings.paletteName)
|
||||
|
||||
let input = InputController.shared
|
||||
input.app = AppModel.main
|
||||
input.start()
|
||||
HardwareInput.shared.start()
|
||||
|
||||
let midi = SizzleMidi.shared
|
||||
midi.sendClock = settings.sendMidiClock
|
||||
midi.receiveClock = settings.receiveMidiClock
|
||||
midi.soundModule = settings.soundModule
|
||||
midi.onNote = { on, ch, note, vel in input.midiNote(on: on, channel: ch, note: note, velocity: vel) }
|
||||
midi.onControl = { cc, value in input.midiControl(cc, value) }
|
||||
midi.start(withDisabledKeys: settings.midiSourcesOff)
|
||||
}
|
||||
|
||||
/// Leaving the foreground: save, and unless Sizzle stays on as a sound module
|
||||
/// (or is playing / recording), pause the audio so iOS can suspend the app.
|
||||
static func background() {
|
||||
let session = SizzleSession.shared
|
||||
session.autosave()
|
||||
let busy = session.isPlaying || session.masterRecording || SampleRecorder.shared.isRecording
|
||||
if !AppSettings.shared.soundModule && !busy { session.audioSuspended = true }
|
||||
}
|
||||
|
||||
static func foreground() { SizzleSession.shared.audioSuspended = false }
|
||||
}
|
||||
@@ -32,8 +32,9 @@ final class AppModel: ObservableObject {
|
||||
@Published var cursorColumn: Column = .note
|
||||
|
||||
// On-screen keyboard (Android: kbdChannel / kbdOctave / kbdVelocity).
|
||||
@Published var kbdChannel = 1
|
||||
@Published var kbdOctave = 3
|
||||
// Channel and octave persist (AppSettings), like Android's.
|
||||
@Published var kbdChannel = AppSettings.shared.kbdChannel { didSet { AppSettings.shared.kbdChannel = kbdChannel } }
|
||||
@Published var kbdOctave = AppSettings.shared.kbdOctave { didSet { AppSettings.shared.kbdOctave = kbdOctave } }
|
||||
@Published var kbdVelocity = 127
|
||||
|
||||
/// The toolbox slot whose editor is open, if any.
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
|
||||
/// App-level settings that persist across launches (Android's SettingsStore and
|
||||
/// BindingStore). Song, mixer and toolbox settings live in the project instead.
|
||||
/// Stored in UserDefaults; a backup carries them as a text file (`settings.txt`,
|
||||
/// one `key=value` line each, see `exportText` / `importText`).
|
||||
@MainActor
|
||||
final class AppSettings: ObservableObject {
|
||||
static let shared = AppSettings()
|
||||
private let d = UserDefaults.standard
|
||||
|
||||
/// The colour theme's name (a built-in one or a user theme).
|
||||
@Published var paletteName: String { didSet { d.set(paletteName, forKey: "palette") } }
|
||||
/// FX tail captured after the sequencer stops (bars, 0..4).
|
||||
@Published var recordTailBars: Int { didSet { d.set(recordTailBars, forKey: "recordTailBars") } }
|
||||
/// The on-screen keyboards' MIDI channel (0 = none) and base octave.
|
||||
@Published var kbdChannel: Int { didSet { d.set(kbdChannel, forKey: "kbdChannel") } }
|
||||
@Published var kbdOctave: Int { didSet { d.set(kbdOctave, forKey: "kbdOctave") } }
|
||||
/// The live meters inside the mixer's volume faders.
|
||||
@Published var vuMeters: Bool { didSet { d.set(vuMeters, forKey: "vuMeters") } }
|
||||
/// Send MIDI clock, Start/Stop and the sequenced notes to MIDI destinations.
|
||||
@Published var sendMidiClock: Bool { didSet { d.set(sendMidiClock, forKey: "midiClockSend") } }
|
||||
/// Follow an external MIDI clock's tempo and Start/Stop.
|
||||
@Published var receiveMidiClock: Bool { didSet { d.set(receiveMidiClock, forKey: "midiClockRecv") } }
|
||||
/// Keep the audio running in the background so incoming MIDI plays (sound module).
|
||||
@Published var soundModule: Bool { didSet { d.set(soundModule, forKey: "soundModule") } }
|
||||
/// MIDI sources the user switched off (MidiSourceKey).
|
||||
@Published var midiSourcesOff: Set<String> { didSet { d.set(Array(midiSourcesOff).sorted(), forKey: "midiSourcesOff") } }
|
||||
/// Input bindings, one `code=actionId` line each (gamepad: `modifier:code=actionId`);
|
||||
/// nil until the user changes them (the defaults apply).
|
||||
@Published var keyboardBindings: String? { didSet { d.set(keyboardBindings, forKey: "bindKeyboard") } }
|
||||
@Published var gamepadBindings: String? { didSet { d.set(gamepadBindings, forKey: "bindGamepad") } }
|
||||
@Published var midiBindings: String? { didSet { d.set(midiBindings, forKey: "bindMidi") } }
|
||||
|
||||
private init() {
|
||||
paletteName = d.string(forKey: "palette") ?? "Amber CRT"
|
||||
recordTailBars = d.object(forKey: "recordTailBars") as? Int ?? 2
|
||||
kbdChannel = d.object(forKey: "kbdChannel") as? Int ?? 1
|
||||
kbdOctave = d.object(forKey: "kbdOctave") as? Int ?? 3
|
||||
vuMeters = d.object(forKey: "vuMeters") as? Bool ?? true
|
||||
sendMidiClock = d.bool(forKey: "midiClockSend")
|
||||
receiveMidiClock = d.bool(forKey: "midiClockRecv")
|
||||
soundModule = d.bool(forKey: "soundModule")
|
||||
midiSourcesOff = Set(d.stringArray(forKey: "midiSourcesOff") ?? [])
|
||||
keyboardBindings = d.string(forKey: "bindKeyboard")
|
||||
gamepadBindings = d.string(forKey: "bindGamepad")
|
||||
midiBindings = d.string(forKey: "bindMidi")
|
||||
}
|
||||
|
||||
// MARK: Backup text
|
||||
|
||||
private static let keys = ["palette", "recordTailBars", "kbdChannel", "kbdOctave", "vuMeters", "midiClockSend",
|
||||
"midiClockRecv", "soundModule", "midiSourcesOff", "bindKeyboard", "bindGamepad", "bindMidi"]
|
||||
|
||||
/// Every setting as `key=value` lines; multi-line values (bindings, the source
|
||||
/// list) are escaped (`\n` → `\\n`).
|
||||
func exportText() -> String {
|
||||
var lines = ["SIZZLE-SETTINGS 1"]
|
||||
for k in Self.keys {
|
||||
guard let v = d.object(forKey: k) else { continue }
|
||||
let text: String
|
||||
switch v {
|
||||
case let a as [String]: text = a.joined(separator: "\n")
|
||||
case let n as NSNumber where k == "vuMeters" || k.hasPrefix("midiClock") || k == "soundModule": text = n.boolValue ? "true" : "false"
|
||||
default: text = "\(v)"
|
||||
}
|
||||
lines.append(k + "=" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\n", with: "\\n"))
|
||||
}
|
||||
return lines.joined(separator: "\n") + "\n"
|
||||
}
|
||||
|
||||
/// Restore settings written by exportText (unknown keys are ignored).
|
||||
func importText(_ text: String) {
|
||||
var map: [String: String] = [:]
|
||||
for line in text.split(separator: "\n") {
|
||||
guard let eq = line.firstIndex(of: "=") else { continue }
|
||||
var v = "", esc = false
|
||||
for c in line[line.index(after: eq)...] {
|
||||
if esc { v.append(c == "n" ? "\n" : c); esc = false } else if c == "\\" { esc = true } else { v.append(c) }
|
||||
}
|
||||
map[String(line[..<eq])] = v
|
||||
}
|
||||
if let v = map["palette"] { paletteName = v }
|
||||
if let v = map["recordTailBars"].flatMap(Int.init) { recordTailBars = max(0, min(4, v)) }
|
||||
if let v = map["kbdChannel"].flatMap(Int.init) { kbdChannel = max(0, min(16, v)) }
|
||||
if let v = map["kbdOctave"].flatMap(Int.init) { kbdOctave = max(0, min(8, v)) }
|
||||
if let v = map["vuMeters"] { vuMeters = v == "true" }
|
||||
if let v = map["midiClockSend"] { sendMidiClock = v == "true" }
|
||||
if let v = map["midiClockRecv"] { receiveMidiClock = v == "true" }
|
||||
if let v = map["soundModule"] { soundModule = v == "true" }
|
||||
if let v = map["midiSourcesOff"] { midiSourcesOff = Set(v.split(separator: "\n").map(String.init)) }
|
||||
if let v = map["bindKeyboard"] { keyboardBindings = v }
|
||||
if let v = map["bindGamepad"] { gamepadBindings = v }
|
||||
if let v = map["bindMidi"] { midiBindings = v }
|
||||
}
|
||||
}
|
||||
@@ -8,3 +8,6 @@
|
||||
#import "SizzleSession+Setup.h"
|
||||
#import "SizzleSession+Sources.h"
|
||||
#import "SizzleSession+Viz.h"
|
||||
#import "SizzleSession+Record.h"
|
||||
#import "SizzleMidi.h"
|
||||
#import "SizzleSession+Files.h"
|
||||
|
||||
@@ -18,9 +18,15 @@
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>LSSupportsOpeningDocumentsInPlace</key>
|
||||
<true/>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>Sizzle records the microphone or an audio interface's input into samples.</string>
|
||||
<key>UIBackgroundModes</key>
|
||||
<array>
|
||||
<string>audio</string>
|
||||
</array>
|
||||
<key>UIFileSharingEnabled</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
import GameController
|
||||
#if canImport(UIKit)
|
||||
import UIKit
|
||||
#endif
|
||||
|
||||
/// Hardware keyboards and gamepads through the GameController framework (Android's
|
||||
/// KeyboardInput and GamepadInput). Both feed InputRouter; their maps are
|
||||
/// InputBindings'. Keys are ignored while a text field is being typed into.
|
||||
///
|
||||
/// Keyboard: bound hotkeys first ("octaveUp"/"octaveDown" move the piano's octave,
|
||||
/// Shift+the next-column key goes back a column), then the fixed two-octave piano.
|
||||
/// Gamepad: buttons, the D-pad and both sticks (edge-detected with hysteresis) go
|
||||
/// through one press/release path, so any of them can be bound or chorded.
|
||||
@MainActor
|
||||
final class HardwareInput {
|
||||
static let shared = HardwareInput()
|
||||
|
||||
/// The keyboard piano's octave (Android's KeyboardInput.baseOctave).
|
||||
private(set) var baseOctave = 4
|
||||
private var pianoHeld: [Int: Int] = [:] // key code -> pitch it started
|
||||
private var heldPad: [Int] = [] // gamepad controls held, in press order
|
||||
private var learnSeq: [Int] = []
|
||||
private var axes: [Int: Int] = [:] // axis id -> sign (-1, 0, 1)
|
||||
private var started = false
|
||||
|
||||
private var router: InputRouter { InputRouter.shared }
|
||||
private var bindings: InputBindings { InputBindings.shared }
|
||||
|
||||
func start() {
|
||||
guard !started else { return }
|
||||
started = true
|
||||
let nc = NotificationCenter.default
|
||||
nc.addObserver(forName: .GCKeyboardDidConnect, object: nil, queue: .main) { n in
|
||||
Task { @MainActor in (n.object as? GCKeyboard).map(HardwareInput.shared.attach) }
|
||||
}
|
||||
nc.addObserver(forName: .GCControllerDidConnect, object: nil, queue: .main) { n in
|
||||
Task { @MainActor in (n.object as? GCController).map(HardwareInput.shared.attach) }
|
||||
}
|
||||
if let kb = GCKeyboard.coalesced { attach(kb) }
|
||||
GCController.controllers().forEach(attach)
|
||||
}
|
||||
|
||||
// MARK: Keyboard
|
||||
|
||||
private func attach(_ kb: GCKeyboard) {
|
||||
kb.keyboardInput?.keyChangedHandler = { _, _, code, pressed in
|
||||
Task { @MainActor in HardwareInput.shared.key(code.rawValue, pressed) }
|
||||
}
|
||||
}
|
||||
|
||||
private func shiftHeld() -> Bool {
|
||||
guard let k = GCKeyboard.coalesced?.keyboardInput else { return false }
|
||||
return (k.button(forKeyCode: .leftShift)?.isPressed ?? false) || (k.button(forKeyCode: .rightShift)?.isPressed ?? false)
|
||||
}
|
||||
|
||||
private func key(_ code: Int, _ pressed: Bool) {
|
||||
if !pressed {
|
||||
router.releaseRepeat(AnyHashable("k\(code)"))
|
||||
if let pitch = pianoHeld.removeValue(forKey: code) {
|
||||
router.dispatch(.noteOff(pitch: pitch, channel: -1, sounded: false))
|
||||
}
|
||||
return
|
||||
}
|
||||
if Self.typingInTextField() { return }
|
||||
if router.learnSource == .keyboard {
|
||||
router.dispatch(.raw(source: .keyboard, code: code, value: 1, modifier: 0))
|
||||
return
|
||||
}
|
||||
if let id = bindings.keyboard[code] {
|
||||
switch id {
|
||||
case "octaveDown": baseOctave = max(0, baseOctave - 1)
|
||||
case "octaveUp": baseOctave = min(8, baseOctave + 1)
|
||||
case "nextColumn": router.pressRepeat(AnyHashable("k\(code)"), shiftHeld() ? .prevColumn : .nextColumn)
|
||||
default: if let a = InputActions.action(id) { router.pressRepeat(AnyHashable("k\(code)"), a) }
|
||||
}
|
||||
return
|
||||
}
|
||||
if let offset = InputBindings.piano[code] {
|
||||
let pitch = min(max(60 + (baseOctave - 4) * 12 + offset, 0), 127)
|
||||
pianoHeld[code] = pitch
|
||||
router.dispatch(.noteOn(pitch: pitch, velocity: 100, channel: -1, sounded: false))
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(UIKit)
|
||||
fileprivate static var found: UIResponder?
|
||||
private static func typingInTextField() -> Bool {
|
||||
found = nil
|
||||
UIApplication.shared.sendAction(#selector(UIResponder.sizzleFindFirstResponder(_:)), to: nil, from: nil, for: nil)
|
||||
defer { found = nil }
|
||||
return found is UITextField || found is UITextView
|
||||
}
|
||||
#else
|
||||
private static func typingInTextField() -> Bool { false }
|
||||
#endif
|
||||
|
||||
// MARK: Gamepad
|
||||
|
||||
private func attach(_ c: GCController) {
|
||||
guard let g = c.extendedGamepad else { return }
|
||||
typealias P = InputBindings.Pad
|
||||
let buttons: [(GCControllerButtonInput?, Int)] = [
|
||||
(g.buttonA, P.a), (g.buttonB, P.b), (g.buttonX, P.x), (g.buttonY, P.y),
|
||||
(g.leftShoulder, P.l1), (g.rightShoulder, P.r1), (g.leftTrigger, P.l2), (g.rightTrigger, P.r2),
|
||||
(g.buttonMenu, P.menu), (g.buttonOptions, P.options),
|
||||
(g.leftThumbstickButton, P.l3), (g.rightThumbstickButton, P.r3),
|
||||
(g.dpad.up, P.up), (g.dpad.down, P.down), (g.dpad.left, P.left), (g.dpad.right, P.right),
|
||||
]
|
||||
for (button, code) in buttons {
|
||||
button?.pressedChangedHandler = { _, _, pressed in
|
||||
Task { @MainActor in pressed ? HardwareInput.shared.padDown(code) : HardwareInput.shared.padUp(code) }
|
||||
}
|
||||
}
|
||||
// Up is negative, as on Android (GameController's y points up).
|
||||
g.leftThumbstick.valueChangedHandler = { _, x, y in
|
||||
Task { @MainActor in
|
||||
HardwareInput.shared.axis(0, x, P.lsLeft, P.lsRight)
|
||||
HardwareInput.shared.axis(1, -y, P.lsUp, P.lsDown)
|
||||
}
|
||||
}
|
||||
g.rightThumbstick.valueChangedHandler = { _, x, y in
|
||||
Task { @MainActor in
|
||||
HardwareInput.shared.axis(2, x, P.rsLeft, P.rsRight)
|
||||
HardwareInput.shared.axis(3, -y, P.rsUp, P.rsDown)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Push past 0.6 = press, back inside 0.4 = release; in between, hold.
|
||||
private func axis(_ id: Int, _ value: Float, _ neg: Int, _ pos: Int) {
|
||||
let last = axes[id] ?? 0
|
||||
let sign = value <= -0.6 ? -1 : value >= 0.6 ? 1 : (value > -0.4 && value < 0.4) ? 0 : last
|
||||
guard sign != last else { return }
|
||||
axes[id] = sign
|
||||
if last == -1 { padUp(neg) } else if last == 1 { padUp(pos) }
|
||||
if sign == -1 { padDown(neg) } else if sign == 1 { padDown(pos) }
|
||||
}
|
||||
|
||||
private func padDown(_ code: Int) {
|
||||
if router.learnSource == .gamepad {
|
||||
if !learnSeq.contains(code) { learnSeq.append(code) }
|
||||
if !heldPad.contains(code) { heldPad.append(code) }
|
||||
return
|
||||
}
|
||||
// A chord first: any control already held may be the modifier.
|
||||
for mod in heldPad {
|
||||
if let id = bindings.gamepad[GamepadChord(modifier: mod, code: code)] {
|
||||
heldPad.append(code)
|
||||
if let a = InputActions.action(id) { router.pressRepeat(AnyHashable("g\(code)"), a) }
|
||||
return
|
||||
}
|
||||
}
|
||||
if !heldPad.contains(code) { heldPad.append(code) }
|
||||
if let id = bindings.gamepad[GamepadChord(modifier: 0, code: code)], let a = InputActions.action(id) {
|
||||
router.pressRepeat(AnyHashable("g\(code)"), a)
|
||||
}
|
||||
}
|
||||
|
||||
private func padUp(_ code: Int) {
|
||||
heldPad.removeAll { $0 == code }
|
||||
router.releaseRepeat(AnyHashable("g\(code)"))
|
||||
// A learn capture ends once every control of the combo is released.
|
||||
if router.learnSource == .gamepad, !learnSeq.isEmpty, !heldPad.contains(where: learnSeq.contains) {
|
||||
let main = learnSeq.last!, mod = learnSeq.count >= 2 ? learnSeq.first! : 0
|
||||
learnSeq.removeAll()
|
||||
router.dispatch(.raw(source: .gamepad, code: main, value: 1, modifier: mod))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if canImport(UIKit)
|
||||
extension UIResponder {
|
||||
@objc fileprivate func sizzleFindFirstResponder(_ sender: Any?) { HardwareInput.found = self }
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,108 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Android's InputAction: every hardware source (keyboard, gamepad, MIDI) becomes
|
||||
/// one of these, so a feature is written once (AppModel+Input) and works from all.
|
||||
enum InputAction: Equatable {
|
||||
case navUp, navDown, navLeft, navRight
|
||||
case nextColumn, prevColumn
|
||||
case increment(Int), decrement(Int)
|
||||
case clearCell, noteOffCell
|
||||
/// [channel] 1..16 for MIDI, -1 for a source without one (the keyboard's piano);
|
||||
/// [sounded]: the MIDI sound module already played it (only show / punch it in).
|
||||
case noteOn(pitch: Int, velocity: Int, channel: Int, sounded: Bool)
|
||||
case noteOff(pitch: Int, channel: Int, sounded: Bool)
|
||||
case playPause, stop, toggleLoop
|
||||
case selectTab(Int), nextTab, prevTab
|
||||
/// An unbound control (a MIDI CC, a key or a gamepad chord during learn).
|
||||
/// [modifier]: the held gamepad control of a chord, 0 for none.
|
||||
case raw(source: InputSource, code: Int, value: Float, modifier: Int)
|
||||
|
||||
/// Cursor and value steps repeat while their control is held.
|
||||
var isRepeatable: Bool {
|
||||
switch self {
|
||||
case .navUp, .navDown, .navLeft, .navRight, .nextColumn, .prevColumn, .increment, .decrement: return true
|
||||
default: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum InputSource { case touch, keyboard, gamepad, midi }
|
||||
|
||||
/// Android's InputActions: the stable action ids the binding maps store, and what
|
||||
/// each one does. Settings lists them in this order.
|
||||
enum InputActions {
|
||||
static let all: [(id: String, label: String)] = [
|
||||
("playPause", "Play / Pause"), ("stop", "Stop"), ("loop", "Loop on/off"),
|
||||
("up", "Cursor up"), ("down", "Cursor down"), ("left", "Cursor left"), ("right", "Cursor right"),
|
||||
("nextColumn", "Next column"), ("prevColumn", "Previous column"),
|
||||
("increment", "Value +1"), ("decrement", "Value −1"), ("clear", "Clear cell"), ("noteOff", "Note-off"),
|
||||
("nextTab", "Next tab"), ("prevTab", "Previous tab"),
|
||||
]
|
||||
|
||||
static func action(_ id: String) -> InputAction? {
|
||||
switch id {
|
||||
case "playPause": return .playPause
|
||||
case "stop": return .stop
|
||||
case "loop": return .toggleLoop
|
||||
case "up": return .navUp
|
||||
case "down": return .navDown
|
||||
case "left": return .navLeft
|
||||
case "right": return .navRight
|
||||
case "increment": return .increment(1)
|
||||
case "decrement": return .decrement(1)
|
||||
case "clear": return .clearCell
|
||||
case "noteOff": return .noteOffCell
|
||||
case "nextColumn": return .nextColumn
|
||||
case "prevColumn": return .prevColumn
|
||||
case "nextTab": return .nextTab
|
||||
case "prevTab": return .prevTab
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Android's InputRouter: one dispatch point, the shared accelerating
|
||||
/// hold-to-repeat (320 ms, ×0.8 per step, down to 45 ms) and the learn state.
|
||||
@MainActor
|
||||
final class InputRouter: ObservableObject {
|
||||
static let shared = InputRouter()
|
||||
|
||||
/// Set by AppModel: what happens with each action.
|
||||
var handler: ((InputAction) -> Void)?
|
||||
/// While set, the next control of this source is captured as a binding.
|
||||
@Published var learnSource: InputSource?
|
||||
|
||||
private var repeatKey: AnyHashable?
|
||||
private var repeatTimer: Timer?
|
||||
|
||||
func dispatch(_ a: InputAction) { handler?(a) }
|
||||
|
||||
/// Fire [action] for a press and, if it repeats, keep firing while [key] is held.
|
||||
func pressRepeat(_ key: AnyHashable, _ action: InputAction) {
|
||||
dispatch(action)
|
||||
guard action.isRepeatable else { return }
|
||||
repeatTimer?.invalidate()
|
||||
repeatKey = key
|
||||
schedule(action, after: 0.32)
|
||||
}
|
||||
|
||||
private func schedule(_ action: InputAction, after interval: TimeInterval) {
|
||||
repeatTimer = Timer.scheduledTimer(withTimeInterval: interval, repeats: false) { [weak self] _ in
|
||||
Task { @MainActor in
|
||||
guard let self = self, self.repeatKey != nil else { return }
|
||||
self.dispatch(action)
|
||||
self.schedule(action, after: max(0.045, interval * 0.8))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func releaseRepeat(_ key: AnyHashable) {
|
||||
guard repeatKey == key else { return }
|
||||
repeatTimer?.invalidate()
|
||||
repeatTimer = nil
|
||||
repeatKey = nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A gamepad binding: a control, optionally while another is held (Android's
|
||||
/// GamepadChord). modifier 0 = none.
|
||||
struct GamepadChord: Hashable {
|
||||
let modifier: Int
|
||||
let code: Int
|
||||
}
|
||||
|
||||
/// The three rebindable maps (Android's KeyboardInput / GamepadInput / MidiInput
|
||||
/// bindings, persisted like BindingStore: one `code=actionId` line each, gamepad
|
||||
/// `modifier:code=actionId`). Keyboard codes are USB HID usages (GCKeyCode).
|
||||
@MainActor
|
||||
final class InputBindings: ObservableObject {
|
||||
static let shared = InputBindings()
|
||||
|
||||
@Published private(set) var keyboard: [Int: String]
|
||||
@Published private(set) var gamepad: [GamepadChord: String]
|
||||
@Published private(set) var midi: [Int: String]
|
||||
|
||||
private init() {
|
||||
let s = AppSettings.shared
|
||||
keyboard = s.keyboardBindings.map(Self.decodeInt) ?? Self.defaultKeyboard
|
||||
gamepad = s.gamepadBindings.map(Self.decodeChord) ?? Self.defaultGamepad
|
||||
midi = s.midiBindings.map(Self.decodeInt) ?? [:]
|
||||
}
|
||||
|
||||
/// After a backup restore: read the maps from the settings again.
|
||||
func reload() {
|
||||
let s = AppSettings.shared
|
||||
keyboard = s.keyboardBindings.map(Self.decodeInt) ?? Self.defaultKeyboard
|
||||
gamepad = s.gamepadBindings.map(Self.decodeChord) ?? Self.defaultGamepad
|
||||
midi = s.midiBindings.map(Self.decodeInt) ?? [:]
|
||||
}
|
||||
|
||||
// Each action keeps at most one binding per device kind (Android's learn).
|
||||
func bindKey(_ code: Int, to id: String) { keyboard = keyboard.filter { $0.value != id }; keyboard[code] = id; save() }
|
||||
func bindGamepad(_ chord: GamepadChord, to id: String) { gamepad = gamepad.filter { $0.value != id }; gamepad[chord] = id; save() }
|
||||
func bindMidi(_ cc: Int, to id: String) { midi = midi.filter { $0.value != id }; midi[cc] = id; save() }
|
||||
|
||||
func clear(_ id: String, source: InputSource) {
|
||||
switch source {
|
||||
case .keyboard: keyboard = keyboard.filter { $0.value != id }
|
||||
case .gamepad: gamepad = gamepad.filter { $0.value != id }
|
||||
case .midi: midi = midi.filter { $0.value != id }
|
||||
case .touch: return
|
||||
}
|
||||
save()
|
||||
}
|
||||
|
||||
func resetDefaults(_ source: InputSource) {
|
||||
switch source {
|
||||
case .keyboard: keyboard = Self.defaultKeyboard
|
||||
case .gamepad: gamepad = Self.defaultGamepad
|
||||
case .midi: midi = [:]
|
||||
case .touch: return
|
||||
}
|
||||
save()
|
||||
}
|
||||
|
||||
func keyFor(_ id: String) -> Int? { keyboard.first { $0.value == id }?.key }
|
||||
func chordFor(_ id: String) -> GamepadChord? { gamepad.first { $0.value == id }?.key }
|
||||
func ccFor(_ id: String) -> Int? { midi.first { $0.value == id }?.key }
|
||||
|
||||
private func save() {
|
||||
let s = AppSettings.shared
|
||||
s.keyboardBindings = keyboard.map { "\($0.key)=\($0.value)" }.sorted().joined(separator: "\n")
|
||||
s.gamepadBindings = gamepad.map { "\($0.key.modifier):\($0.key.code)=\($0.value)" }.sorted().joined(separator: "\n")
|
||||
s.midiBindings = midi.map { "\($0.key)=\($0.value)" }.sorted().joined(separator: "\n")
|
||||
}
|
||||
|
||||
private static func decodeInt(_ s: String) -> [Int: String] {
|
||||
var out: [Int: String] = [:]
|
||||
for line in s.split(separator: "\n") {
|
||||
guard let eq = line.firstIndex(of: "="), eq > line.startIndex, let code = Int(line[..<eq]) else { continue }
|
||||
out[code] = String(line[line.index(after: eq)...])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private static func decodeChord(_ s: String) -> [GamepadChord: String] {
|
||||
var out: [GamepadChord: String] = [:]
|
||||
for line in s.split(separator: "\n") {
|
||||
guard let eq = line.firstIndex(of: "=") else { continue }
|
||||
let parts = line[..<eq].split(separator: ":")
|
||||
guard parts.count == 2, let m = Int(parts[0]), let c = Int(parts[1]) else { continue }
|
||||
out[GamepadChord(modifier: m, code: c)] = String(line[line.index(after: eq)...])
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// MARK: Keyboard (HID usages)
|
||||
|
||||
enum Key {
|
||||
static let a = 4, l = 15, enter = 40, backspace = 42, tab = 43, space = 44, minus = 45, equals = 46, grave = 53
|
||||
static let pageUp = 75, pageDown = 78, right = 79, left = 80, down = 81, up = 82
|
||||
static let leftShift = 225, rightShift = 229
|
||||
}
|
||||
|
||||
/// Android's default hotkeys, kept off the piano letters.
|
||||
static let defaultKeyboard: [Int: String] = [
|
||||
Key.up: "up", Key.down: "down", Key.left: "left", Key.right: "right", Key.tab: "nextColumn",
|
||||
Key.space: "playPause", Key.enter: "stop", Key.l: "loop", Key.pageUp: "increment", Key.pageDown: "decrement",
|
||||
Key.backspace: "clear", Key.grave: "noteOff", Key.minus: "octaveDown", Key.equals: "octaveUp",
|
||||
]
|
||||
|
||||
/// The fixed two-octave tracker piano: Z S X D C V G B H N J M, then Q 2 W 3 E R 5 T 6 Y 7 U.
|
||||
static let piano: [Int: Int] = {
|
||||
let lower = "zsxdcvgbhnjm", upper = "q2w3er5t6y7u"
|
||||
var m: [Int: Int] = [:]
|
||||
for (i, c) in lower.enumerated() { m[hid(c)] = i }
|
||||
for (i, c) in upper.enumerated() { m[hid(c)] = 12 + i }
|
||||
return m
|
||||
}()
|
||||
|
||||
private static func hid(_ c: Character) -> Int {
|
||||
if let v = c.asciiValue, v >= 97, v <= 122 { return Int(v) - 97 + 4 } // a..z
|
||||
if c == "0" { return 39 }
|
||||
return Int(c.asciiValue! - 49) + 30 // 1..9
|
||||
}
|
||||
|
||||
static func keyLabel(_ code: Int) -> String {
|
||||
switch code {
|
||||
case 4...29: return String(UnicodeScalar(UInt8(code - 4 + 65)))
|
||||
case 30...38: return String(code - 29)
|
||||
case 39: return "0"
|
||||
case Key.enter: return "Return"
|
||||
case 41: return "Esc"
|
||||
case Key.backspace: return "Delete"
|
||||
case Key.tab: return "Tab"
|
||||
case Key.space: return "Space"
|
||||
case Key.minus: return "-"
|
||||
case Key.equals: return "="
|
||||
case 47: return "["
|
||||
case 48: return "]"
|
||||
case 49: return "\\"
|
||||
case 51: return ";"
|
||||
case 52: return "'"
|
||||
case Key.grave: return "`"
|
||||
case 54: return ","
|
||||
case 55: return "."
|
||||
case 56: return "/"
|
||||
case 58...69: return "F\(code - 57)"
|
||||
case 74: return "Home"
|
||||
case Key.pageUp: return "Page Up"
|
||||
case 76: return "Fwd Delete"
|
||||
case 77: return "End"
|
||||
case Key.pageDown: return "Page Down"
|
||||
case Key.right: return "→"
|
||||
case Key.left: return "←"
|
||||
case Key.down: return "↓"
|
||||
case Key.up: return "↑"
|
||||
default: return "Key \(code)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Gamepad controls
|
||||
|
||||
enum Pad {
|
||||
static let a = 1, b = 2, x = 3, y = 4, l1 = 5, r1 = 6, l2 = 7, r2 = 8, menu = 9, options = 10, l3 = 11, r3 = 12
|
||||
static let up = 20, down = 21, left = 22, right = 23
|
||||
static let lsLeft = 0x20001, lsRight = 0x20002, lsUp = 0x20003, lsDown = 0x20004
|
||||
static let rsLeft = 0x20005, rsRight = 0x20006, rsUp = 0x20007, rsDown = 0x20008
|
||||
}
|
||||
|
||||
static let defaultGamepad: [GamepadChord: String] = {
|
||||
let plain: [(Int, String)] = [
|
||||
(Pad.a, "playPause"), (Pad.b, "stop"), (Pad.x, "clear"), (Pad.y, "loop"), (Pad.l1, "prevTab"), (Pad.r1, "nextTab"),
|
||||
(Pad.up, "up"), (Pad.down, "down"), (Pad.left, "left"), (Pad.right, "right"),
|
||||
(Pad.lsUp, "up"), (Pad.lsDown, "down"), (Pad.lsLeft, "left"), (Pad.lsRight, "right"),
|
||||
(Pad.rsUp, "increment"), (Pad.rsDown, "decrement"),
|
||||
]
|
||||
return Dictionary(uniqueKeysWithValues: plain.map { (GamepadChord(modifier: 0, code: $0.0), $0.1) })
|
||||
}()
|
||||
|
||||
static func padLabel(_ code: Int) -> String {
|
||||
switch code {
|
||||
case Pad.a: return "A"
|
||||
case Pad.b: return "B"
|
||||
case Pad.x: return "X"
|
||||
case Pad.y: return "Y"
|
||||
case Pad.l1: return "L1"
|
||||
case Pad.r1: return "R1"
|
||||
case Pad.l2: return "L2"
|
||||
case Pad.r2: return "R2"
|
||||
case Pad.menu: return "Menu"
|
||||
case Pad.options: return "Options"
|
||||
case Pad.l3: return "L3"
|
||||
case Pad.r3: return "R3"
|
||||
case Pad.up: return "UP"
|
||||
case Pad.down: return "DOWN"
|
||||
case Pad.left: return "LEFT"
|
||||
case Pad.right: return "RIGHT"
|
||||
case Pad.lsLeft: return "LS←"
|
||||
case Pad.lsRight: return "LS→"
|
||||
case Pad.lsUp: return "LS↑"
|
||||
case Pad.lsDown: return "LS↓"
|
||||
case Pad.rsLeft: return "RS←"
|
||||
case Pad.rsRight: return "RS→"
|
||||
case Pad.rsUp: return "RS↑"
|
||||
case Pad.rsDown: return "RS↓"
|
||||
default: return "#\(code)"
|
||||
}
|
||||
}
|
||||
|
||||
static func chordLabel(_ c: GamepadChord) -> String {
|
||||
c.modifier == 0 ? padLabel(c.code) : padLabel(c.modifier) + " + " + padLabel(c.code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
|
||||
/// What the app does with input actions (Android's AppViewModel.onAction and its
|
||||
/// learn / parameter-CC code), and the MIDI controller side of MidiInput
|
||||
/// (CC bindings, momentary navigation pads).
|
||||
@MainActor
|
||||
final class InputController: ObservableObject {
|
||||
static let shared = InputController()
|
||||
|
||||
/// The app model actions apply to (set at launch).
|
||||
weak var app: AppModel?
|
||||
|
||||
/// Settings' learn: the action whose binding the next control of [learnSource] sets.
|
||||
@Published private(set) var learnTarget: String?
|
||||
/// Toolbox parameter MIDI learn: the next CC moved binds to this slot's parameter.
|
||||
@Published private(set) var paramLearnSlot = -1
|
||||
@Published private(set) var paramLearnKey: String?
|
||||
|
||||
/// Android's lastNote / lastChannel: seeds for stepping an empty cell.
|
||||
private var lastNote = 60
|
||||
private var lastChannel = 0
|
||||
|
||||
private var router: InputRouter { InputRouter.shared }
|
||||
private var session: SizzleSession { SizzleSession.shared }
|
||||
static let ccPrefix = "midicc@"
|
||||
|
||||
func start() {
|
||||
router.handler = { [weak self] in self?.handle($0) }
|
||||
}
|
||||
|
||||
// MARK: Actions
|
||||
|
||||
func handle(_ action: InputAction) {
|
||||
guard let app = app else { return }
|
||||
let tracker = TrackerState.shared
|
||||
switch action {
|
||||
case .navUp: tracker.moveCursorWrap(app, -tracker.skipStep)
|
||||
case .navDown: tracker.moveCursorWrap(app, tracker.skipStep)
|
||||
case .navLeft: moveColumnFlat(app, -1)
|
||||
case .navRight: moveColumnFlat(app, 1)
|
||||
case .nextColumn: app.cursorColumn = AppModel.Column(rawValue: (app.cursorColumn.rawValue + 1) % 3)!
|
||||
case .prevColumn: app.cursorColumn = AppModel.Column(rawValue: (app.cursorColumn.rawValue + 2) % 3)!
|
||||
case .increment(let n): editFocused(app, n)
|
||||
case .decrement(let n): editFocused(app, -n)
|
||||
case .clearCell:
|
||||
session.clearCells(inPattern: session.activePattern, fromTrack: app.cursorTrack, toTrack: app.cursorTrack,
|
||||
fromLine: app.cursorLine, toLine: app.cursorLine)
|
||||
case .noteOffCell: tracker.noteOffFocused(app)
|
||||
case let .noteOn(pitch, velocity, channel, sounded):
|
||||
TrackerHeldNotes.shared.mark(pitch, on: true)
|
||||
let ch = channel >= 1 ? channel : app.kbdChannel
|
||||
if !sounded { session.note(on: pitch, velocity: velocity, midiChannel: ch) }
|
||||
if app.tab == .tracker && tracker.punchInMode {
|
||||
tracker.punchNote(app, pitch, velocity: velocity, channel: ch)
|
||||
lastNote = pitch; lastChannel = ch
|
||||
}
|
||||
case let .noteOff(pitch, channel, sounded):
|
||||
TrackerHeldNotes.shared.mark(pitch, on: false)
|
||||
if !sounded { session.noteOff(pitch, midiChannel: channel >= 1 ? channel : app.kbdChannel) }
|
||||
case .playPause: tracker.playPause()
|
||||
case .stop: tracker.stop()
|
||||
case .toggleLoop: session.arrangementLoop = !session.arrangementLoop
|
||||
case .selectTab(let i): app.tab = AppModel.Tab(rawValue: min(max(i, 0), 3))!
|
||||
case .nextTab: app.tab = AppModel.Tab(rawValue: min(app.tab.rawValue + 1, 3))!
|
||||
case .prevTab: app.tab = AppModel.Tab(rawValue: max(app.tab.rawValue - 1, 0))!
|
||||
case let .raw(source, code, value, modifier): onRaw(source, code, value, modifier)
|
||||
}
|
||||
}
|
||||
|
||||
/// The three columns of every track laid end to end (Android's moveColumnFlat).
|
||||
private func moveColumnFlat(_ app: AppModel, _ dir: Int) {
|
||||
let flat = min(max(app.cursorTrack * 3 + app.cursorColumn.rawValue + dir, 0), 11)
|
||||
app.cursorTrack = flat / 3
|
||||
app.cursorColumn = AppModel.Column(rawValue: flat % 3)!
|
||||
}
|
||||
|
||||
/// Android's editFocused: the note steps within the scale (an empty cell starts
|
||||
/// from the last note entered), velocity and channel step by one.
|
||||
private func editFocused(_ app: AppModel, _ dir: Int) {
|
||||
let p = session.activePattern
|
||||
var c = session.cell(inPattern: p, track: app.cursorTrack, line: app.cursorLine)
|
||||
if c.note == -2 && app.cursorColumn != .note { return } // a note-off has only its note
|
||||
switch app.cursorColumn {
|
||||
case .note:
|
||||
let seed = c.note >= 0 ? Int(c.note) : lastNote
|
||||
let inKey = Set(session.scalePitchClasses.map { $0.intValue })
|
||||
var n = seed
|
||||
repeat {
|
||||
n += dir
|
||||
if n < 0 || n > 127 { n = seed; break }
|
||||
} while !inKey.contains(n % 12)
|
||||
c.note = Int32(n)
|
||||
lastNote = n
|
||||
if c.channel == 0 { c.channel = Int32(max(lastChannel, 1)) }
|
||||
case .velocity:
|
||||
c.velocity = Int32(min(max(Int(c.velocity) + dir, 0), 127))
|
||||
case .channel:
|
||||
let seed = c.note == -1 ? lastChannel : Int(c.channel)
|
||||
c.channel = Int32(min(max(seed + dir, 1), 16))
|
||||
lastChannel = Int(c.channel)
|
||||
}
|
||||
session.setCell(c, inPattern: p, track: app.cursorTrack, line: app.cursorLine)
|
||||
}
|
||||
|
||||
// MARK: MIDI controllers (MidiInput.handleCc)
|
||||
|
||||
func midiControl(_ cc: Int, _ value: Int) {
|
||||
guard let id = InputBindings.shared.midi[cc], router.learnSource != .midi else {
|
||||
router.dispatch(.raw(source: .midi, code: cc, value: Float(value) / 127, modifier: 0))
|
||||
return
|
||||
}
|
||||
// Navigation pads are momentary: press (>= 64) starts the hold-to-repeat,
|
||||
// release ends it.
|
||||
let key = AnyHashable("m\(cc)")
|
||||
switch id {
|
||||
case "up", "down", "left", "right":
|
||||
if value >= 64, let a = InputActions.action(id) { router.pressRepeat(key, a) } else { router.releaseRepeat(key) }
|
||||
case "increment", "decrement":
|
||||
if let a = InputActions.action(id) { router.dispatch(a) }
|
||||
default:
|
||||
if value >= 64, let a = InputActions.action(id) { router.dispatch(a) }
|
||||
}
|
||||
}
|
||||
|
||||
func midiNote(on: Bool, channel: Int, note: Int, velocity: Int) {
|
||||
router.dispatch(on ? .noteOn(pitch: note, velocity: velocity, channel: channel, sounded: true)
|
||||
: .noteOff(pitch: note, channel: channel, sounded: true))
|
||||
}
|
||||
|
||||
// MARK: Learn
|
||||
|
||||
func beginLearn(_ id: String, source: InputSource) {
|
||||
cancelParamLearn()
|
||||
learnTarget = id
|
||||
router.learnSource = source
|
||||
}
|
||||
|
||||
func cancelLearn() {
|
||||
learnTarget = nil
|
||||
router.learnSource = nil
|
||||
}
|
||||
|
||||
func beginParamLearn(slot: Int, key: String) {
|
||||
cancelLearn()
|
||||
paramLearnSlot = slot
|
||||
paramLearnKey = key
|
||||
router.learnSource = .midi
|
||||
}
|
||||
|
||||
func cancelParamLearn() {
|
||||
paramLearnSlot = -1
|
||||
paramLearnKey = nil
|
||||
if learnTarget == nil { router.learnSource = nil }
|
||||
}
|
||||
|
||||
func paramCc(slot: Int, key: String) -> Int? { Int(session.value(ofSlot: slot, key: Self.ccPrefix + key)) }
|
||||
|
||||
func clearParamCc(slot: Int, key: String) { session.setValue("", ofSlot: slot, key: Self.ccPrefix + key) }
|
||||
|
||||
private func onRaw(_ source: InputSource, _ code: Int, _ value: Float, _ modifier: Int) {
|
||||
if let key = paramLearnKey {
|
||||
if source == .midi { bindParamCc(slot: paramLearnSlot, key: key, cc: code); cancelParamLearn() }
|
||||
return
|
||||
}
|
||||
guard let target = learnTarget else {
|
||||
if source == .midi { applyParamCc(code, value) } // a CC bound to toolbox parameters drives them
|
||||
return
|
||||
}
|
||||
guard source == router.learnSource else { return }
|
||||
let b = InputBindings.shared
|
||||
switch source {
|
||||
case .midi: b.bindMidi(code, to: target)
|
||||
case .gamepad: b.bindGamepad(GamepadChord(modifier: modifier, code: code), to: target)
|
||||
case .keyboard: b.bindKey(code, to: target)
|
||||
case .touch: break
|
||||
}
|
||||
cancelLearn()
|
||||
}
|
||||
|
||||
/// One physical control drives one parameter: the CC leaves any other first.
|
||||
private func bindParamCc(slot: Int, key: String, cc: Int) {
|
||||
for s in 0..<16 where !session.type(ofSlot: s).isEmpty {
|
||||
for spec in SizzleSession.paramSpecs(forType: session.type(ofSlot: s)) where paramCc(slot: s, key: spec.key) == cc {
|
||||
clearParamCc(slot: s, key: spec.key)
|
||||
}
|
||||
}
|
||||
session.setValue(String(cc), ofSlot: slot, key: Self.ccPrefix + key)
|
||||
}
|
||||
|
||||
private func applyParamCc(_ cc: Int, _ norm: Float) {
|
||||
let n = min(max(norm, 0), 1)
|
||||
for s in 0..<16 {
|
||||
let type = session.type(ofSlot: s)
|
||||
if type.isEmpty { continue }
|
||||
for spec in SizzleSession.paramSpecs(forType: type) where paramCc(slot: s, key: spec.key) == cc {
|
||||
if !spec.choices.isEmpty {
|
||||
let i = min(max(Int((n * Float(spec.choices.count - 1)).rounded()), 0), spec.choices.count - 1)
|
||||
session.setValue(spec.choices[i], ofSlot: s, key: spec.key)
|
||||
} else {
|
||||
var v = spec.minValue + n * (spec.maxValue - spec.minValue)
|
||||
if spec.isInt { v = v.rounded() }
|
||||
session.setNumber(v, ofSlot: s, key: spec.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ import SwiftUI
|
||||
/// portrait and a side rail in landscape, as the Android app's App.kt lays them out.
|
||||
struct RootView: View {
|
||||
@ObservedObject private var app: AppModel
|
||||
/// The whole tree is rebuilt when the theme changes (Theme is read, not observed).
|
||||
@ObservedObject private var settings = AppSettings.shared
|
||||
init(model: AppModel? = nil) { app = model ?? AppModel.main }
|
||||
@Environment(\.scenePhase) private var phase
|
||||
@Environment(\.verticalSizeClass) private var vClass
|
||||
@@ -24,8 +26,15 @@ struct RootView: View {
|
||||
.background(Theme.background.ignoresSafeArea())
|
||||
}
|
||||
.environmentObject(app)
|
||||
.id(settings.paletteName)
|
||||
.preferredColorScheme(.dark)
|
||||
.onChange(of: phase) { p in if p != .active { app.session.autosave() } }
|
||||
.onChange(of: phase) { p in
|
||||
switch p {
|
||||
case .background: AppBoot.background()
|
||||
case .active: AppBoot.foreground()
|
||||
default: app.session.autosave()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ViewBuilder private var screen: some View {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import AVFoundation
|
||||
import SwiftUI
|
||||
|
||||
/// Android's SampleRecorder: records the microphone (or a connected audio
|
||||
/// interface's input) into a sample, at most 30 seconds. The audio session switches
|
||||
/// to play-and-record only while recording, so playback keeps its normal routing
|
||||
/// otherwise. Main thread.
|
||||
@MainActor
|
||||
final class SampleRecorder: ObservableObject {
|
||||
static let shared = SampleRecorder()
|
||||
|
||||
@Published private(set) var isRecording = false
|
||||
@Published var error: String?
|
||||
|
||||
private var recorder: AVAudioRecorder?
|
||||
private let file = FileManager.default.temporaryDirectory.appendingPathComponent("sample-rec.wav")
|
||||
|
||||
func start() {
|
||||
guard !isRecording else { return }
|
||||
#if os(iOS)
|
||||
AVAudioSession.sharedInstance().requestRecordPermission { granted in
|
||||
Task { @MainActor in
|
||||
if granted { self.begin() } else { self.error = "Sizzle has no microphone access. Allow it in Settings › Privacy › Microphone." }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
private func begin() {
|
||||
let s = AVAudioSession.sharedInstance()
|
||||
do {
|
||||
try s.setCategory(.playAndRecord, options: [.defaultToSpeaker, .allowBluetoothA2DP, .mixWithOthers])
|
||||
try s.setActive(true)
|
||||
let r = try AVAudioRecorder(url: file, settings: [
|
||||
AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: 44_100, AVNumberOfChannelsKey: 1,
|
||||
AVLinearPCMBitDepthKey: 16, AVLinearPCMIsFloatKey: false, AVLinearPCMIsBigEndianKey: false,
|
||||
])
|
||||
guard r.record(forDuration: 30) else { throw CocoaError(.fileWriteUnknown) }
|
||||
recorder = r
|
||||
isRecording = true
|
||||
} catch {
|
||||
restoreSession()
|
||||
self.error = "Couldn't start recording: \(error.localizedDescription)"
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Stop and return the take as WAV data (nil if nothing was captured).
|
||||
func stop() -> Data? {
|
||||
guard let r = recorder else { return nil }
|
||||
r.stop()
|
||||
recorder = nil
|
||||
isRecording = false
|
||||
restoreSession()
|
||||
defer { try? FileManager.default.removeItem(at: file) }
|
||||
guard let data = try? Data(contentsOf: file), data.count > 44 else { return nil }
|
||||
return data
|
||||
}
|
||||
|
||||
private func restoreSession() {
|
||||
#if os(iOS)
|
||||
try? AVAudioSession.sharedInstance().setCategory(.playback)
|
||||
#endif
|
||||
}
|
||||
|
||||
private static var stamp: String { "rec-\(Int(Date().timeIntervalSince1970 * 1000))" }
|
||||
|
||||
/// Stop and put the take on Sampler [slot]'s [pad] (Android: stopRecordingInto).
|
||||
func stopInto(slot: Int, pad: Int) {
|
||||
guard let data = stop() else { return }
|
||||
do { try SizzleSession.shared.loadSampleData(data, name: Self.stamp, intoSlot: slot, pad: pad) }
|
||||
catch { self.error = error.localizedDescription }
|
||||
}
|
||||
|
||||
/// Stop and make the take Grain Cloud [slot]'s source (Android: stopRecordingIntoGrain).
|
||||
func stopIntoGrain(slot: Int) {
|
||||
guard let data = stop() else { return }
|
||||
do { try SizzleSession.shared.loadGrainSourceData(data, name: Self.stamp, intoSlot: slot) }
|
||||
catch { self.error = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,9 @@ import SwiftUI
|
||||
/// 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)
|
||||
/// The theme's playhead and danger colours.
|
||||
static var playhead: Color { Theme.playhead }
|
||||
static var danger: Color { Theme.danger }
|
||||
|
||||
/// Pitch.name: 60 -> "C-4", 61 -> "C#4".
|
||||
static func pitchName(_ midi: Int) -> String {
|
||||
|
||||
@@ -28,18 +28,53 @@ private struct MixBody: View {
|
||||
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)
|
||||
return VStack(spacing: 0) {
|
||||
RecordToolbar(session: session)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/// Android's RecordToolbar: arm the master recording (it starts on Play or an
|
||||
/// external MIDI clock Start), the FX tail after the stop, and the last take. Takes
|
||||
/// are saved in Sizzle's Recordings folder (Files app); SHARE sends the last one.
|
||||
private struct RecordToolbar: View {
|
||||
let session: SizzleSession
|
||||
|
||||
var body: some View {
|
||||
let recording = session.masterRecording
|
||||
let last = session.lastRecordingURL
|
||||
let status: String = recording ? "recording…"
|
||||
: session.recordArmed ? "armed — starts on play or MIDI clock start"
|
||||
: last.map { "saved \($0.lastPathComponent)" } ?? "master → WAV (Files › Sizzle › Recordings)"
|
||||
MixKit.HScroll {
|
||||
HStack(spacing: 6) {
|
||||
MixKit.Button(label: recording ? "● REC" : "● ARM", active: session.recordArmed && !recording, danger: recording) {
|
||||
session.recordArmed = !session.recordArmed
|
||||
}
|
||||
MixKit.Dropdown(label: "TAIL", options: [0, 1, 2, 3, 4], selected: session.recordTailBars,
|
||||
optionLabel: { "\($0) bar" + ($0 == 1 ? "" : "s") },
|
||||
onSelect: { session.recordTailBars = $0; AppSettings.shared.recordTailBars = $0 })
|
||||
if let url = last, !recording {
|
||||
MixKit.Button(label: "SHARE") { ShareSheet.present(url) }
|
||||
}
|
||||
Text(status).font(Theme.mono(11)).foregroundColor(Theme.dim).lineLimit(1)
|
||||
}
|
||||
.padding(6)
|
||||
}
|
||||
.background(Theme.background)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
.background(Theme.surface)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -133,7 +168,7 @@ private struct VolumeFader: View {
|
||||
ZStack(alignment: .top) {
|
||||
Theme.background
|
||||
Rectangle().fill(Theme.accent.opacity(0.30)).frame(height: vol * h).offset(y: top)
|
||||
MeterLayer(ch: ch, volume: vol)
|
||||
if AppSettings.shared.vuMeters { 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)
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// One device kind's bindings (Android's binding sections and BindingRow): each
|
||||
/// action with its current control, LEARN (then press the key / combo or move the
|
||||
/// MIDI control) and ✕ to unbind.
|
||||
struct BindingsSheet: View {
|
||||
let source: InputSource
|
||||
@ObservedObject private var bindings = InputBindings.shared
|
||||
@ObservedObject private var input = InputController.shared
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
|
||||
private struct Group { let title: String; let actions: [(id: String, label: String)] }
|
||||
|
||||
private var groups: [Group] {
|
||||
var g = [
|
||||
Group(title: "Transport", actions: [("playPause", "Play / Pause"), ("stop", "Stop"), ("loop", "Toggle Loop")]),
|
||||
Group(title: "Navigation", actions: [("up", "Cursor Up"), ("down", "Cursor Down"), ("left", "Cursor Left"), ("right", "Cursor Right")]),
|
||||
Group(title: "Editing", actions: [("increment", "Value +"), ("decrement", "Value -"), ("clear", "Clear Cell")]
|
||||
+ (source == .keyboard ? [("noteOff", "Note Off")] : [])),
|
||||
]
|
||||
if source == .keyboard {
|
||||
g.append(Group(title: "Columns", actions: [("nextColumn", "Next Column"), ("prevColumn", "Prev Column")]))
|
||||
g.append(Group(title: "Octave", actions: [("octaveDown", "Octave Down"), ("octaveUp", "Octave Up")]))
|
||||
}
|
||||
g.append(Group(title: "Tabs", actions: [("nextTab", "Next Tab"), ("prevTab", "Prev Tab")]))
|
||||
return g
|
||||
}
|
||||
|
||||
private var title: String {
|
||||
switch source {
|
||||
case .gamepad: return "Gamepad Bindings"
|
||||
case .keyboard: return "Keyboard Hotkeys"
|
||||
default: return "MIDI Bindings"
|
||||
}
|
||||
}
|
||||
|
||||
private var hint: String {
|
||||
switch source {
|
||||
case .gamepad: return "LEARN, then press a button, D-pad direction or stick direction — or hold one and press another for a combo."
|
||||
case .keyboard: return "LEARN, then press a key. Unbound letter keys play the tracker piano (Z…M, Q…U)."
|
||||
default: return "LEARN, then press a pad or move a control on your MIDI controller (CC)."
|
||||
}
|
||||
}
|
||||
|
||||
private func label(_ id: String) -> String? {
|
||||
switch source {
|
||||
case .gamepad: return bindings.chordFor(id).map(InputBindings.chordLabel)
|
||||
case .keyboard: return bindings.keyFor(id).map(InputBindings.keyLabel)
|
||||
default: return bindings.ccFor(id).map { "CC \($0)" }
|
||||
}
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 10) {
|
||||
HStack {
|
||||
Text(title).font(.system(size: 19, weight: .semibold)).foregroundColor(Theme.accent)
|
||||
Spacer()
|
||||
SetupButton(title: "Defaults") { bindings.resetDefaults(source) }
|
||||
SetupButton(title: "Done", kind: .filled) { dismiss() }
|
||||
}
|
||||
Text(hint).font(.system(size: 12)).foregroundColor(Theme.dim)
|
||||
ScrollView {
|
||||
VStack(alignment: .leading, spacing: 12) {
|
||||
ForEach(groups, id: \.title) { group in
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
Text(group.title.uppercased()).font(.system(size: 11, weight: .semibold)).foregroundColor(Theme.dim)
|
||||
ForEach(group.actions, id: \.id) { a in row(a.id, a.label) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(20)
|
||||
.background(Theme.surface.ignoresSafeArea())
|
||||
.preferredColorScheme(.dark)
|
||||
.onDisappear { input.cancelLearn() }
|
||||
}
|
||||
|
||||
private func row(_ id: String, _ text: String) -> some View {
|
||||
let listening = input.learnTarget == id
|
||||
let bound = label(id)
|
||||
return HStack(spacing: 10) {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(text).font(.system(size: 15)).foregroundColor(Theme.text)
|
||||
Text(bound ?? "unbound").font(.system(size: 12, design: .monospaced)).foregroundColor(bound == nil ? Theme.dim : Theme.accent)
|
||||
}
|
||||
Spacer()
|
||||
SetupButton(title: listening ? "Listening…" : "Learn", kind: listening ? .filled : .outlined) {
|
||||
if listening { input.cancelLearn() } else { input.beginLearn(id, source: source) }
|
||||
}
|
||||
if bound != nil {
|
||||
Button { bindings.clear(id, source: source) } label: {
|
||||
Image(systemName: "xmark").foregroundColor(Theme.dim).frame(width: 36, height: 36)
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
}
|
||||
}
|
||||
.padding(.vertical, 2)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// A labelled switch (Android's ToggleRow).
|
||||
struct SetupToggle: View {
|
||||
let title: String
|
||||
let detail: String
|
||||
let isOn: Bool
|
||||
let onChange: (Bool) -> Void
|
||||
|
||||
var body: some View {
|
||||
Toggle(isOn: Binding(get: { isOn }, set: onChange)) {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text(title).font(.system(size: 15, weight: .medium)).foregroundColor(Theme.text)
|
||||
Text(detail).font(.system(size: 12)).foregroundColor(Theme.dim).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
}
|
||||
.tint(Theme.accent)
|
||||
}
|
||||
}
|
||||
|
||||
/// Audio Devices: iOS picks the route; this shows it and offers the system picker.
|
||||
struct AudioDevicesCard: View {
|
||||
var body: some View {
|
||||
SetupCard(title: "Audio Devices", subtitle: "Playback and recording go where iOS routes audio") {
|
||||
AudioRouteView()
|
||||
SetupNote("Plug in an audio interface or headphones, or pick AirPlay / Bluetooth with the route button. " +
|
||||
"The sample recorder records from the current input.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Recording: where master takes go and the FX tail (the ARM button is on Mix).
|
||||
struct RecordingCard: View {
|
||||
@ObservedObject var settings = AppSettings.shared
|
||||
|
||||
var body: some View {
|
||||
SetupCard(title: "Recording", subtitle: "Record the master bus to WAV files") {
|
||||
HStack(spacing: 8) {
|
||||
Text("FX tail after stop").font(.system(size: 15)).foregroundColor(Theme.text)
|
||||
Spacer()
|
||||
ForEach(0..<5, id: \.self) { n in
|
||||
SetupButton(title: "\(n)", kind: settings.recordTailBars == n ? .filled : .outlined) {
|
||||
settings.recordTailBars = n
|
||||
SizzleSession.shared.recordTailBars = n
|
||||
}
|
||||
}
|
||||
}
|
||||
SetupNote("Arm with ● ARM on the Mix tab; the take starts on Play (or an external MIDI clock Start) and " +
|
||||
"ends this many bars after the stop. Takes are in Files › On My iPad › Sizzle › Recordings.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Interface: the mixer meters (Android's InterfaceCard).
|
||||
struct InterfaceCard: View {
|
||||
@ObservedObject var settings = AppSettings.shared
|
||||
|
||||
var body: some View {
|
||||
SetupCard(title: "Interface", subtitle: "On-screen display options") {
|
||||
SetupToggle(title: "Mixer VU meters", detail: "Show live level meters inside the mixer volume faders.",
|
||||
isOn: settings.vuMeters) { settings.vuMeters = $0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Color Theme: pick, import, export or delete (Android's ThemeCard).
|
||||
struct ThemeCard: View {
|
||||
@ObservedObject var library = ThemeLibrary.shared
|
||||
let onImport: () -> Void
|
||||
let onDelete: (String) -> Void
|
||||
let onError: (String) -> Void
|
||||
|
||||
var body: some View {
|
||||
let current = Theme.current.name
|
||||
SetupCard(title: "Color Theme", subtitle: "Pick, import, export or delete a palette") {
|
||||
HStack(spacing: 8) {
|
||||
Menu {
|
||||
ForEach(library.names, id: \.self) { name in
|
||||
Button(name + (library.isStock(name) ? " (stock)" : "")) { library.select(name) }
|
||||
}
|
||||
} label: {
|
||||
HStack(spacing: 6) {
|
||||
Text(current).font(.system(size: 15, weight: .medium)).lineLimit(1)
|
||||
Image(systemName: "chevron.down").font(.system(size: 12))
|
||||
}
|
||||
.foregroundColor(Theme.text)
|
||||
.padding(.horizontal, 14).frame(minHeight: 38)
|
||||
.overlay(Capsule().stroke(Theme.grid, lineWidth: 1))
|
||||
}
|
||||
if !library.isStock(current) {
|
||||
SetupButton(title: "Delete", kind: .danger) { onDelete(current) }
|
||||
}
|
||||
}
|
||||
SetupDivider()
|
||||
HStack(spacing: 8) {
|
||||
SetupButton(title: "Export .szt", icon: "square.and.arrow.up") {
|
||||
do { ShareSheet.present(try library.exportFile()) } catch { onError(error.localizedDescription) }
|
||||
}
|
||||
SetupButton(title: "Import .szt", icon: "square.and.arrow.down.on.square", action: onImport)
|
||||
}
|
||||
SetupNote("Stock themes can't be deleted; imported .szt themes appear in the list.")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// MIDI Sync: clock out / in, sound-module mode and the MIDI sources (Android's
|
||||
/// MidiSyncCard + MidiInputsList).
|
||||
struct MidiSyncCard: View {
|
||||
@ObservedObject var settings = AppSettings.shared
|
||||
@ObservedObject var midi = MidiSources.shared
|
||||
|
||||
var body: some View {
|
||||
SetupCard(title: "MIDI Sync", subtitle: "MIDI clock and notes over USB, Bluetooth, network and other apps") {
|
||||
SetupToggle(title: "Send MIDI clock",
|
||||
detail: "Send clock, start/stop and the tracks' notes to MIDI devices and apps, so Sizzle drives them.",
|
||||
isOn: settings.sendMidiClock) { settings.sendMidiClock = $0; SizzleMidi.shared.sendClock = $0 }
|
||||
SetupDivider()
|
||||
SetupToggle(title: "Receive MIDI clock",
|
||||
detail: "Follow an external clock's tempo, and start/stop Sizzle's own song with it " +
|
||||
"(tempo only while Sizzle runs as a MIDI sound module).",
|
||||
isOn: settings.receiveMidiClock) { settings.receiveMidiClock = $0; SizzleMidi.shared.receiveClock = $0 }
|
||||
SetupDivider()
|
||||
SetupToggle(title: "Keep running as MIDI sound module",
|
||||
detail: "Keep playing incoming MIDI with Sizzle in the background (another app can use it as its synth). " +
|
||||
"Sizzle's own song doesn't start from the other app's clock meanwhile.",
|
||||
isOn: settings.soundModule) { settings.soundModule = $0; SizzleMidi.shared.soundModule = $0 }
|
||||
SetupDivider()
|
||||
HStack {
|
||||
VStack(alignment: .leading, spacing: 2) {
|
||||
Text("MIDI inputs").font(.system(size: 15, weight: .medium)).foregroundColor(Theme.text)
|
||||
Text("Sources Sizzle listens to. Each mixer track plays the notes on its MIDI channel. " +
|
||||
"Other apps can also send to the \"Sizzle\" MIDI destination.")
|
||||
.font(.system(size: 12)).foregroundColor(Theme.dim).fixedSize(horizontal: false, vertical: true)
|
||||
}
|
||||
Spacer()
|
||||
SetupButton(title: "Reconnect") { SizzleMidi.shared.reconnect() }
|
||||
}
|
||||
if midi.sources.isEmpty {
|
||||
SetupNote("No MIDI sources found.")
|
||||
}
|
||||
ForEach(midi.sources, id: \.key) { src in
|
||||
SetupToggle(title: src.name, detail: !src.enabled ? "Off" : src.connected ? "Listening" : "Not connected (tap Reconnect)",
|
||||
isOn: src.enabled) { on in
|
||||
if on { settings.midiSourcesOff.remove(src.key) } else { settings.midiSourcesOff.insert(src.key) }
|
||||
SizzleMidi.shared.setSourceKey(src.key, enabled: on)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// SizzleMidi's source list as an observable (refreshed on its change callback).
|
||||
@MainActor
|
||||
final class MidiSources: ObservableObject {
|
||||
static let shared = MidiSources()
|
||||
@Published private(set) var sources: [SizzleMidiSource] = []
|
||||
|
||||
private init() {
|
||||
sources = SizzleMidi.shared.sources
|
||||
SizzleMidi.shared.onSourcesChanged = { [weak self] in self?.sources = SizzleMidi.shared.sources }
|
||||
}
|
||||
}
|
||||
|
||||
/// The three binding editors (Android's Gamepad Bindings / Keyboard Hotkeys / MIDI Bindings).
|
||||
struct BindingsCard: View {
|
||||
let open: (InputSource) -> Void
|
||||
|
||||
var body: some View {
|
||||
SetupCard(title: "Controls", subtitle: "Hardware keyboard, gamepad and MIDI controller bindings") {
|
||||
SetupRow(title: "Gamepad Bindings", detail: "Rebind buttons, sticks and combos", icon: "gamecontroller") { open(.gamepad) }
|
||||
SetupDivider()
|
||||
SetupRow(title: "Keyboard Hotkeys", detail: "Rebind keys; Z…M and Q…U play notes", icon: "keyboard") { open(.keyboard) }
|
||||
SetupDivider()
|
||||
SetupRow(title: "MIDI Bindings", detail: "MIDI-learn controls for transport and editing", icon: "pianokeys") { open(.midi) }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Backup & Restore (Android's BackupCard).
|
||||
struct BackupCard: View {
|
||||
let onBackup: () -> Void
|
||||
let onRestore: () -> Void
|
||||
|
||||
var body: some View {
|
||||
SetupCard(title: "Backup & Restore", subtitle: "Save or restore all songs, presets, themes & settings") {
|
||||
HStack(spacing: 8) {
|
||||
SetupButton(title: "Back up", icon: "externaldrive", kind: .filled, action: onBackup)
|
||||
SetupButton(title: "Restore", icon: "arrow.counterclockwise", action: onRestore)
|
||||
}
|
||||
SetupNote("A backup is one .zip with every saved song, preset, theme, sample, the open song and the settings. " +
|
||||
"Restoring replaces all of them.")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import SwiftUI
|
||||
/// 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 var danger: Color { Theme.danger }
|
||||
static let corner: CGFloat = 10
|
||||
}
|
||||
|
||||
@@ -145,6 +145,8 @@ enum SetupDialog: Identifiable {
|
||||
case save
|
||||
case confirmNew
|
||||
case confirmDelete(String)
|
||||
case confirmDeleteTheme(String)
|
||||
case confirmRestore
|
||||
case message(title: String, text: String)
|
||||
|
||||
var id: String {
|
||||
@@ -152,6 +154,8 @@ enum SetupDialog: Identifiable {
|
||||
case .save: return "save"
|
||||
case .confirmNew: return "new"
|
||||
case .confirmDelete(let n): return "delete:" + n
|
||||
case .confirmDeleteTheme(let n): return "theme:" + n
|
||||
case .confirmRestore: return "restore"
|
||||
case .message(let t, let m): return "msg:" + t + m
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,6 +17,28 @@ enum SetupFiles {
|
||||
return url
|
||||
}
|
||||
|
||||
/// Writes [data] to a fresh temporary folder as "<name>.<ext>".
|
||||
static func export(_ data: Data, name: 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(name).appendingPathExtension(ext)
|
||||
try data.write(to: url)
|
||||
return url
|
||||
}
|
||||
|
||||
/// Reads a picked file (security-scoped), refusing anything over [limit] bytes.
|
||||
static func readData(_ url: URL, limit: Int) throws -> Data {
|
||||
let scoped = url.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||
let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0
|
||||
guard size <= limit else { throw SetupFileError.tooLarge }
|
||||
let data = try Data(contentsOf: url)
|
||||
guard data.count <= limit else { throw SetupFileError.tooLarge }
|
||||
return data
|
||||
}
|
||||
|
||||
/// The song name as a file name: path separators replaced, blank → "untitled".
|
||||
static func fileStem(_ name: String) -> String {
|
||||
let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
@@ -42,7 +64,7 @@ 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 .tooLarge: return "The file is too large for Sizzle."
|
||||
case .notText: return "Couldn't read the selected file."
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,8 +63,9 @@ final class SetupModel: ObservableObject {
|
||||
|
||||
// MARK: Export / import
|
||||
|
||||
/// What a picked file is for.
|
||||
enum Format {
|
||||
case sng, project
|
||||
case sng, project, theme, backup
|
||||
var ext: String { self == .sng ? "sng" : "szg" }
|
||||
}
|
||||
|
||||
@@ -77,11 +78,47 @@ final class SetupModel: ObservableObject {
|
||||
/// 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 {
|
||||
if format == .project {
|
||||
// A bundle (.szgz, a ZIP) or a plain project (.szg).
|
||||
let data = try SetupFiles.readData(url, limit: 64 << 20)
|
||||
if SizzleSession.isZip(data) { try session.importProjectBundleData(data) }
|
||||
else if let text = String(data: data, encoding: .utf8) { try session.importProjectText(text) }
|
||||
else { throw SetupFileError.notText }
|
||||
refresh()
|
||||
return
|
||||
}
|
||||
let text = try SetupFiles.readText(url)
|
||||
switch format {
|
||||
case .sng: try session.importSngText(text)
|
||||
case .project: try session.importProjectText(text)
|
||||
default: try session.importProjectText(text)
|
||||
}
|
||||
refresh()
|
||||
}
|
||||
|
||||
/// The open song as a bundle, "<song>.szgz" in a temporary folder.
|
||||
func exportBundle() throws -> URL {
|
||||
guard let data = session.projectBundleData() else { throw SetupFileError.notText }
|
||||
return try SetupFiles.export(data, name: SetupFiles.fileStem(songName), ext: "szgz")
|
||||
}
|
||||
|
||||
/// Everything as "sizzle-backup-yyyyMMdd-HHmm.zip" (Android names it the same way).
|
||||
func backupFile() throws -> URL {
|
||||
guard let data = session.backupData(withSettings: AppSettings.shared.exportText()) else { throw SetupFileError.notText }
|
||||
let f = DateFormatter()
|
||||
f.locale = Locale(identifier: "en_US_POSIX")
|
||||
f.dateFormat = "yyyyMMdd-HHmm"
|
||||
return try SetupFiles.export(data, name: "sizzle-backup-" + f.string(from: Date()), ext: "zip")
|
||||
}
|
||||
|
||||
/// Restore a backup, then apply its settings, bindings and theme.
|
||||
func restoreBackup(_ url: URL) throws {
|
||||
let data = try SetupFiles.readData(url, limit: 1 << 30)
|
||||
let settings = try session.restoreBackupData(data)
|
||||
if !settings.isEmpty { AppSettings.shared.importText(settings) }
|
||||
InputBindings.shared.reload()
|
||||
ThemeLibrary.shared.refresh()
|
||||
ThemeLibrary.shared.select(AppSettings.shared.paletteName)
|
||||
session.recordTailBars = AppSettings.shared.recordTailBars
|
||||
refresh()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import SwiftUI
|
||||
// DeviceLabView / PluginCheck), so there they are no-ops.
|
||||
|
||||
#if canImport(UIKit)
|
||||
import AVKit
|
||||
import UIKit
|
||||
|
||||
enum ShareSheet {
|
||||
@@ -79,8 +80,53 @@ private struct PluginCheckSheet: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// The system's audio route picker (AirPlay, Bluetooth, an interface) and the
|
||||
/// current route's names (Android's audio device rows; iOS chooses the route).
|
||||
struct AudioRouteView: View {
|
||||
@State private var output = AudioRouteView.names(\.outputs)
|
||||
@State private var input = AudioRouteView.names(\.inputs)
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
HStack(spacing: 10) {
|
||||
VStack(alignment: .leading, spacing: 3) {
|
||||
Text("Output: " + output).font(.system(size: 14)).foregroundColor(Theme.text)
|
||||
Text("Input: " + input).font(.system(size: 14)).foregroundColor(Theme.text)
|
||||
}
|
||||
Spacer()
|
||||
RoutePicker().frame(width: 44, height: 44)
|
||||
}
|
||||
}
|
||||
.onReceive(NotificationCenter.default.publisher(for: AVAudioSession.routeChangeNotification).receive(on: RunLoop.main)) { _ in
|
||||
output = Self.names(\.outputs)
|
||||
input = Self.names(\.inputs)
|
||||
}
|
||||
}
|
||||
|
||||
static func names(_ kp: KeyPath<AVAudioSessionRouteDescription, [AVAudioSessionPortDescription]>) -> String {
|
||||
let ports = AVAudioSession.sharedInstance().currentRoute[keyPath: kp].map(\.portName)
|
||||
return ports.isEmpty ? "—" : ports.joined(separator: ", ")
|
||||
}
|
||||
|
||||
private struct RoutePicker: UIViewRepresentable {
|
||||
func makeUIView(context: Context) -> AVRoutePickerView {
|
||||
let v = AVRoutePickerView()
|
||||
v.tintColor = UIColor(Theme.accent)
|
||||
v.activeTintColor = UIColor(Theme.accent)
|
||||
return v
|
||||
}
|
||||
func updateUIView(_ v: AVRoutePickerView, context: Context) {}
|
||||
}
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
struct AudioRouteView: View {
|
||||
var body: some View {
|
||||
Text("Output: Speaker\nInput: Microphone").font(.system(size: 14)).foregroundColor(Theme.text)
|
||||
}
|
||||
}
|
||||
|
||||
enum ShareSheet {
|
||||
@MainActor static func present(_ url: URL, done: @escaping () -> Void = {}) { done() }
|
||||
}
|
||||
|
||||
@@ -5,10 +5,9 @@ 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.
|
||||
/// browser (save / load / new / delete, project bundles and .sng), audio route,
|
||||
/// recording, interface, colour themes, MIDI sync, control bindings, backup and
|
||||
/// restore, help and about, and the device lab.
|
||||
struct SetupScreen: View {
|
||||
@EnvironmentObject var app: AppModel
|
||||
// SetupContent doesn't observe AppModel, so it isn't redrawn at the transport's rate.
|
||||
@@ -27,6 +26,8 @@ private struct SetupContent: View {
|
||||
@State private var importFormat = SetupModel.Format.sng
|
||||
@State private var showDeviceLab = false
|
||||
@State private var showPluginCheck = false
|
||||
@State private var bindingSource: BindingKind?
|
||||
@State private var confirmTheme: String?
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { geo in
|
||||
@@ -37,13 +38,19 @@ private struct SetupContent: View {
|
||||
panicButton
|
||||
if wide {
|
||||
HStack(alignment: .top, spacing: 14) {
|
||||
VStack(spacing: 14) { projectCard; helpCard }
|
||||
VStack(spacing: 14) { comingLater; diagnosticsCard }
|
||||
VStack(spacing: 14) { projectCard; AudioDevicesCard(); RecordingCard(); backupCard; helpCard }
|
||||
VStack(spacing: 14) { midiCard; BindingsCard { bindingSource = BindingKind($0) }; InterfaceCard(); themeCard; diagnosticsCard }
|
||||
}
|
||||
} else {
|
||||
projectCard
|
||||
AudioDevicesCard()
|
||||
RecordingCard()
|
||||
midiCard
|
||||
BindingsCard { bindingSource = BindingKind($0) }
|
||||
InterfaceCard()
|
||||
themeCard
|
||||
backupCard
|
||||
helpCard
|
||||
comingLater
|
||||
diagnosticsCard
|
||||
}
|
||||
}
|
||||
@@ -62,6 +69,28 @@ private struct SetupContent: View {
|
||||
}
|
||||
.deviceLab(isPresented: $showDeviceLab)
|
||||
.pluginCheck(isPresented: $showPluginCheck)
|
||||
.sheet(item: $bindingSource) { BindingsSheet(source: $0.source) }
|
||||
}
|
||||
|
||||
/// Identifiable wrapper for the bindings sheet.
|
||||
struct BindingKind: Identifiable {
|
||||
let source: InputSource
|
||||
init(_ s: InputSource) { source = s }
|
||||
var id: String { "\(source)" }
|
||||
}
|
||||
|
||||
// MARK: Cards with dialogs
|
||||
|
||||
/// The MIDI card isn't built in the Mac snapshots before MIDI starts; it lists nothing then.
|
||||
private var midiCard: some View { MidiSyncCard() }
|
||||
|
||||
private var themeCard: some View {
|
||||
ThemeCard(onImport: { pick(.theme) }, onDelete: { present(.confirmDeleteTheme($0)) },
|
||||
onError: { show("Export failed", $0) })
|
||||
}
|
||||
|
||||
private var backupCard: some View {
|
||||
BackupCard(onBackup: backup, onRestore: { present(.confirmRestore) })
|
||||
}
|
||||
|
||||
// MARK: Panic
|
||||
@@ -96,11 +125,11 @@ private struct SetupContent: View {
|
||||
|
||||
SetupDivider()
|
||||
HStack(spacing: 8) {
|
||||
SetupButton(title: "Export project", icon: "square.and.arrow.up") { export(.project) }
|
||||
SetupButton(title: "Export project", icon: "square.and.arrow.up") { exportBundle() }
|
||||
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.")
|
||||
SetupNote("A bundle (.szgz) carries everything — patterns, mixer, FX, instruments and samples — so it opens " +
|
||||
"complete on another device, Android too. Import takes a bundle or a .szg and replaces the current project.")
|
||||
|
||||
SetupDivider()
|
||||
HStack(spacing: 8) {
|
||||
@@ -178,29 +207,6 @@ private struct SetupContent: View {
|
||||
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 {
|
||||
@@ -247,6 +253,15 @@ private struct SetupContent: View {
|
||||
confirm: "Delete", destructive: true, field: { EmptyView() },
|
||||
onConfirm: { dismiss(); attempt("Delete failed") { try model.delete(name) } },
|
||||
onCancel: dismiss)
|
||||
case .confirmDeleteTheme(let name):
|
||||
SetupDialogView(title: "Delete theme", message: "Delete \"\(name)\"? This cannot be undone.",
|
||||
confirm: "Delete", destructive: true, field: { EmptyView() },
|
||||
onConfirm: { dismiss(); ThemeLibrary.shared.delete(name) }, onCancel: dismiss)
|
||||
case .confirmRestore:
|
||||
SetupDialogView(title: "Restore backup",
|
||||
message: "Replace every saved song, preset, theme, sample, the open song and the settings with a backup's?",
|
||||
confirm: "Choose backup", destructive: true, field: { EmptyView() },
|
||||
onConfirm: { dismiss(); pick(.backup) }, onCancel: dismiss)
|
||||
case .message(let title, let text):
|
||||
SetupDialogView(title: title, message: text, confirm: "OK", cancel: nil, field: { EmptyView() },
|
||||
onConfirm: dismiss, onCancel: dismiss)
|
||||
@@ -279,6 +294,20 @@ private struct SetupContent: View {
|
||||
resetCursor()
|
||||
}
|
||||
|
||||
private func exportBundle() {
|
||||
attempt("Export failed") {
|
||||
let url = try model.exportBundle()
|
||||
ShareSheet.present(url) { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
|
||||
}
|
||||
}
|
||||
|
||||
private func backup() {
|
||||
attempt("Backup failed") {
|
||||
let url = try model.backupFile()
|
||||
ShareSheet.present(url) { try? FileManager.default.removeItem(at: url.deletingLastPathComponent()) }
|
||||
}
|
||||
}
|
||||
|
||||
private func export(_ format: SetupModel.Format) {
|
||||
attempt("Export failed") {
|
||||
let url = try model.exportFile(format)
|
||||
@@ -293,16 +322,31 @@ private struct SetupContent: View {
|
||||
|
||||
private func runImport(_ url: URL) {
|
||||
do {
|
||||
try model.importFile(url, as: importFormat)
|
||||
switch importFormat {
|
||||
case .theme:
|
||||
guard ThemeLibrary.shared.importText(try SetupFiles.readText(url)) != nil else {
|
||||
show("Import failed", "Couldn't import this file. It doesn't look like a valid .szt theme.")
|
||||
return
|
||||
}
|
||||
return
|
||||
case .backup:
|
||||
try model.restoreBackup(url)
|
||||
show("Backup restored", "Songs, presets, themes, samples and settings are back.")
|
||||
default:
|
||||
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).")
|
||||
switch importFormat {
|
||||
case .sng: show("Import failed", "Couldn't import this file. It doesn't look like a valid .sng song.")
|
||||
case .backup: show("Restore failed", error.localizedDescription)
|
||||
default: show("Import failed", (error as NSError).domain == "Sizzle" ? error.localizedDescription
|
||||
: "Couldn't import this file. It doesn't look like a Sizzle project (.szgz or .szg).")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// Android's MidiLearnPopup: every parameter of the slot with its MIDI CC. LEARN,
|
||||
/// then move a knob or fader on a MIDI controller; ✕ removes the binding. The
|
||||
/// bindings are saved in the song (`midicc@<key>` slot values), as on Android.
|
||||
struct MidiLearnSheet: View {
|
||||
let slot: Int
|
||||
let type: String
|
||||
@ObservedObject private var input = InputController.shared
|
||||
@ObservedObject private var watch = MixSongWatch.shared
|
||||
@Environment(\.dismiss) private var dismiss
|
||||
|
||||
var body: some View {
|
||||
let session = SizzleSession.shared
|
||||
VStack(alignment: .leading, spacing: 8) {
|
||||
HStack {
|
||||
Text("MIDI LEARN — \(session.name(ofSlot: slot))").font(Theme.mono(14)).foregroundColor(Theme.accent)
|
||||
Spacer()
|
||||
Text("DONE").font(Theme.mono(13)).foregroundColor(Theme.dim)
|
||||
.contentShape(Rectangle()).onTapGesture { dismiss() }
|
||||
}
|
||||
Text("Tap LEARN, then move a knob/fader on your MIDI controller.").font(Theme.mono(10)).foregroundColor(Theme.dim)
|
||||
SnapScroll {
|
||||
VStack(spacing: 6) {
|
||||
ForEach(SizzleSession.paramSpecs(forType: type), id: \.key) { spec in
|
||||
let arming = input.paramLearnSlot == slot && input.paramLearnKey == spec.key
|
||||
let cc = input.paramCc(slot: slot, key: spec.key)
|
||||
HStack(spacing: 8) {
|
||||
Text(spec.label).font(Theme.mono(12)).foregroundColor(Theme.text)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
Text(arming ? "waiting…" : cc.map { "CC \($0)" } ?? "—").font(Theme.mono(11))
|
||||
.foregroundColor(arming ? Theme.accent : Theme.dim).frame(width: 72, alignment: .leading)
|
||||
MixKit.Button(label: arming ? "ARMING" : "LEARN", active: arming, width: 78) {
|
||||
if arming { input.cancelParamLearn() } else { input.beginParamLearn(slot: slot, key: spec.key) }
|
||||
}
|
||||
MixKit.Button(label: "✕") { input.clearParamCc(slot: slot, key: spec.key) }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(16)
|
||||
.background(Theme.surface.ignoresSafeArea())
|
||||
.preferredColorScheme(.dark)
|
||||
.onDisappear { input.cancelParamLearn() }
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ struct SamplerDetail: View {
|
||||
let onSelectPad: (Int) -> Void
|
||||
let onImport: () -> Void
|
||||
@State private var page = 0
|
||||
@ObservedObject private var recorder = SampleRecorder.shared
|
||||
|
||||
var body: some View {
|
||||
let session = SizzleSession.shared
|
||||
@@ -28,6 +29,15 @@ struct SamplerDetail: View {
|
||||
MixKit.HScroll {
|
||||
HStack(spacing: 8) {
|
||||
MixKit.Button(label: "IMPORT WAV", action: onImport)
|
||||
if recorder.isRecording {
|
||||
MixKit.Button(label: "■ STOP REC", active: true) {
|
||||
recorder.stopInto(slot: slot, pad: pad)
|
||||
session.setNumber(0, ofSlot: slot, key: "pad\(pad)S")
|
||||
session.setNumber(1, ofSlot: slot, key: "pad\(pad)E")
|
||||
}
|
||||
} else {
|
||||
MixKit.Button(label: "● RECORD") { recorder.start() }
|
||||
}
|
||||
if assigned {
|
||||
MixKit.Button(label: "✂ CLIP") { _ = session.trimPad(pad, ofSlot: slot) }
|
||||
MixKit.Button(label: "NORMALIZE") { _ = session.normalizePad(pad, ofSlot: slot) }
|
||||
|
||||
@@ -20,6 +20,7 @@ struct SlotEditor: View {
|
||||
|
||||
@StateObject private var model: DeviceModel
|
||||
@ObservedObject private var watch = MixSongWatch.shared
|
||||
@ObservedObject private var recorder = SampleRecorder.shared
|
||||
@State private var pad = 0
|
||||
/// What the file picker is for; kept after it closes, because SwiftUI resets
|
||||
/// the presentation binding before calling the completion handler.
|
||||
@@ -27,6 +28,7 @@ struct SlotEditor: View {
|
||||
@State private var pickerShown = false
|
||||
@State private var deviceCallback: ((URL) -> Void)?
|
||||
@State private var importError: String?
|
||||
@State private var showMidiLearn = false
|
||||
|
||||
enum ImportKind: Identifiable {
|
||||
case preset, padSample, soundFont, device // device: a bespoke view's own load (deviceFilePicker)
|
||||
@@ -71,6 +73,11 @@ struct SlotEditor: View {
|
||||
}
|
||||
.alert("Import failed", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } }),
|
||||
actions: { Button("OK") { importError = nil } }, message: { Text(importError ?? "") })
|
||||
.background(Color.clear.alert("Recording", isPresented: Binding(get: { recorder.error != nil }, set: { if !$0 { recorder.error = nil } }),
|
||||
actions: { Button("OK") { recorder.error = nil } }, message: { Text(recorder.error ?? "") }))
|
||||
.onDisappear { if recorder.isRecording { _ = recorder.stop() } }
|
||||
.onChange(of: watch.revision) { _ in model.refresh() } // MIDI CCs move parameters too
|
||||
.sheet(isPresented: $showMidiLearn) { MidiLearnSheet(slot: slot, type: type) }
|
||||
}
|
||||
|
||||
@ViewBuilder private var pinnedPart: some View {
|
||||
@@ -87,6 +94,9 @@ struct SlotEditor: View {
|
||||
HStack {
|
||||
Text(session.name(ofSlot: slot)).font(Theme.mono(15)).foregroundColor(Theme.accent).lineLimit(1)
|
||||
Spacer()
|
||||
Text("⇄ MIDI").font(Theme.mono(13)).foregroundColor(Theme.accent)
|
||||
.contentShape(Rectangle()).onTapGesture { showMidiLearn = true }
|
||||
.padding(.trailing, 14)
|
||||
Text("CLOSE ✕").font(Theme.mono(13)).foregroundColor(Theme.dim)
|
||||
.contentShape(Rectangle()).onTapGesture(perform: onClose)
|
||||
}
|
||||
@@ -104,6 +114,9 @@ struct SlotEditor: View {
|
||||
importing = .device
|
||||
pickerShown = true
|
||||
}
|
||||
.environment(\.deviceRecorder, DeviceRecordControl(isRecording: recorder.isRecording) {
|
||||
if recorder.isRecording { recorder.stopIntoGrain(slot: slot) } else { recorder.start() }
|
||||
})
|
||||
.frame(minHeight: 0, maxHeight: .infinity, alignment: .top).clipped()
|
||||
if type == "LFO" { LfoTargetPicker(lfo: slot) }
|
||||
}
|
||||
|
||||
@@ -63,9 +63,11 @@ final class TrackerState: ObservableObject {
|
||||
|
||||
// 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))
|
||||
/// Velocity and channel default to the on-screen keyboard's; MIDI punch-in
|
||||
/// passes the incoming note's own, so the cell plays back as it was played.
|
||||
func punchNote(_ app: AppModel, _ midi: Int, velocity: Int? = nil, channel: Int? = nil) {
|
||||
let cell = SizzleCell(note: Int32(min(max(midi, 0), 127)), velocity: Int32(min(max(velocity ?? app.kbdVelocity, 0), 127)),
|
||||
channel: Int32(channel ?? app.kbdChannel))
|
||||
session.setCell(cell, inPattern: session.activePattern, track: app.cursorTrack, line: app.cursorLine)
|
||||
moveCursorWrap(app, skipStep)
|
||||
}
|
||||
@@ -254,6 +256,14 @@ final class TrackerHeldNotes: ObservableObject {
|
||||
SizzleSession.shared.noteOff(midi, midiChannel: channels[midi] ?? app.kbdChannel)
|
||||
}
|
||||
|
||||
/// Light or unlight a key without sounding it (hardware keys, MIDI in: the
|
||||
/// input layer plays those itself).
|
||||
func mark(_ midi: Int, on: Bool) {
|
||||
if on { counts[midi, default: 0] += 1; return }
|
||||
let n = (counts[midi] ?? 0) - 1
|
||||
if n <= 0 { counts[midi] = nil } else { counts[midi] = n }
|
||||
}
|
||||
|
||||
/// 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) }
|
||||
|
||||
@@ -6,16 +6,16 @@ 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)
|
||||
static var background: Color { Theme.background }
|
||||
static var surface: Color { Theme.surface }
|
||||
static var grid: Color { Theme.grid }
|
||||
static var text: Color { Theme.text }
|
||||
static var dim: Color { Theme.dim }
|
||||
static var accent: Color { Theme.accent }
|
||||
static var beat: Color { Theme.beat }
|
||||
static var bar: Color { Theme.bar }
|
||||
static var playhead: Color { Theme.playhead }
|
||||
static var danger: Color { Theme.danger }
|
||||
|
||||
/// Pitch.name: 60 → "C-4", 61 → "C#4" (MIDI 12 == C0).
|
||||
static let noteNames: [String] = (0..<128).map { m in
|
||||
|
||||
@@ -5,5 +5,6 @@ import SwiftUI
|
||||
|
||||
@main
|
||||
struct SizzleApp: App {
|
||||
init() { AppBoot.start() }
|
||||
var body: some Scene { WindowGroup { RootView() } }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#import <Foundation/Foundation.h>
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/// One MIDI source as Setup lists it. [key] is stable across launches (what the
|
||||
/// device says about itself), so the on/off choice can be saved.
|
||||
@interface SizzleMidiSource : NSObject
|
||||
@property (nonatomic, readonly) NSString *key;
|
||||
@property (nonatomic, readonly) NSString *name;
|
||||
@property (nonatomic, readonly) BOOL enabled;
|
||||
@property (nonatomic, readonly) BOOL connected;
|
||||
@end
|
||||
|
||||
/**
|
||||
* CoreMIDI for Sizzle (Android's MidiInput + MidiSoundModule + MidiClock):
|
||||
*
|
||||
* IN: every MIDI source (USB, Bluetooth, network, other apps) is listened to unless
|
||||
* switched off, plus Sizzle's own virtual destination ("Sizzle") that other apps
|
||||
* can send to. Each source has its own byte parser. Notes play the mixer tracks
|
||||
* listening on their channel straight from the MIDI thread (queued to the audio
|
||||
* thread, no UI in the path); CC 123/120 release a channel. Real-time bytes follow
|
||||
* an external clock (tempo, Start/Stop) while [receiveClock] is on.
|
||||
*
|
||||
* OUT: while [sendClock] is on and the song plays, a thread sends the clock (24
|
||||
* PPQN), Start/Stop, and the sequenced notes to every destination and through
|
||||
* Sizzle's virtual source.
|
||||
*
|
||||
* The blocks are called on the main thread.
|
||||
*/
|
||||
NS_SWIFT_UI_ACTOR
|
||||
@interface SizzleMidi : NSObject
|
||||
|
||||
@property (class, nonatomic, readonly) SizzleMidi *shared;
|
||||
|
||||
/// Create the client and ports and connect the enabled sources. Idempotent.
|
||||
- (void)startWithDisabledKeys:(NSSet<NSString *> *)disabled;
|
||||
@property (nonatomic, readonly) NSArray<SizzleMidiSource *> *sources;
|
||||
- (void)setSourceKey:(NSString *)key enabled:(BOOL)enabled;
|
||||
/// Disconnect and connect every enabled source again.
|
||||
- (void)reconnect;
|
||||
/// Release every note the sources hold (panic).
|
||||
- (void)releaseAll;
|
||||
|
||||
@property (nonatomic) BOOL sendClock;
|
||||
@property (nonatomic) BOOL receiveClock;
|
||||
/// Sound-module mode: an external clock's Start/Stop no longer start or stop the song.
|
||||
@property (nonatomic) BOOL soundModule;
|
||||
|
||||
/// A note the module played or released (channel 1..16), for held keys and punch-in.
|
||||
@property (nonatomic, copy, nullable) void (^onNote)(BOOL on, NSInteger channel, NSInteger note, NSInteger velocity);
|
||||
/// A Control Change the module didn't consume (bindings, MIDI learn): value 0..127.
|
||||
@property (nonatomic, copy, nullable) void (^onControl)(NSInteger cc, NSInteger value);
|
||||
/// The source list changed.
|
||||
@property (nonatomic, copy, nullable) void (^onSourcesChanged)(void);
|
||||
/// A tempo taken from an external clock was applied.
|
||||
@property (nonatomic, copy, nullable) void (^onTempoFollowed)(float bpm);
|
||||
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,337 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#import "SizzleMidi.h"
|
||||
#import "SizzleSession+Internal.h"
|
||||
|
||||
#import <CoreMIDI/CoreMIDI.h>
|
||||
#include <mach/mach_time.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
#include "sizzle/Midi.hpp"
|
||||
|
||||
// The MIDIPacketList API: deprecated since iOS 14 but available, and the only one
|
||||
// on both sides of the deployment target (15) that every source speaks.
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
@interface SizzleMidiSource ()
|
||||
- (instancetype)initWithKey:(NSString *)key name:(NSString *)name enabled:(BOOL)enabled connected:(BOOL)connected;
|
||||
@end
|
||||
|
||||
@implementation SizzleMidiSource
|
||||
- (instancetype)initWithKey:(NSString *)key name:(NSString *)name enabled:(BOOL)enabled connected:(BOOL)connected {
|
||||
if ((self = [super init])) { _key = key; _name = name; _enabled = enabled; _connected = connected; }
|
||||
return self;
|
||||
}
|
||||
@end
|
||||
|
||||
namespace {
|
||||
|
||||
int64_t nowNs() {
|
||||
static mach_timebase_info_data_t tb = [] { mach_timebase_info_data_t t; mach_timebase_info(&t); return t; }();
|
||||
return (int64_t)(mach_absolute_time() * tb.numer / tb.denom);
|
||||
}
|
||||
|
||||
/// Notes go straight to the audio thread's MIDI queue (the module's lock
|
||||
/// serialises the pushes from different MIDI threads).
|
||||
struct SessionSink : midi::NoteSink {
|
||||
__unsafe_unretained SizzleSession *session = nil;
|
||||
void busNoteOn(int ch, int note, int vel) override { [session midiNoteOn:note velocity:vel channel:ch]; }
|
||||
void busNoteOff(int ch, int note) override { [session midiNoteOff:note channel:ch]; }
|
||||
};
|
||||
|
||||
/// One source we may listen to. Never freed: CoreMIDI may still be delivering on
|
||||
/// its thread right after a disconnect, so the connection's refCon stays valid.
|
||||
struct Conn {
|
||||
intptr_t id = 0;
|
||||
MIDIUniqueID uid = 0;
|
||||
MIDIEndpointRef ep = 0;
|
||||
bool connected = false;
|
||||
NSString *key = @"", *name = @"";
|
||||
std::unique_ptr<midi::MidiByteParser> parser;
|
||||
};
|
||||
|
||||
struct State {
|
||||
SessionSink sink;
|
||||
midi::MidiSoundModule module{sink};
|
||||
midi::ClockFollower follower;
|
||||
std::mutex followerLock;
|
||||
std::atomic<bool> sendEnabled{false}, receiveEnabled{false}, soundModule{false}, running{false};
|
||||
engine::Engine *engine = nullptr;
|
||||
const model::Project *project = nullptr;
|
||||
|
||||
MIDIClientRef client = 0;
|
||||
MIDIPortRef inPort = 0, outPort = 0;
|
||||
MIDIEndpointRef virtualIn = 0, virtualOut = 0;
|
||||
std::vector<std::unique_ptr<Conn>> conns; // main thread
|
||||
Conn virtualConn;
|
||||
std::mutex destLock;
|
||||
std::vector<MIDIEndpointRef> dests;
|
||||
std::thread sender;
|
||||
|
||||
void feed(Conn *c, const MIDIPacketList *pl) {
|
||||
const MIDIPacket *p = &pl->packet[0];
|
||||
for (UInt32 i = 0; i < pl->numPackets; ++i) {
|
||||
c->parser->feed(p->data, p->length);
|
||||
p = MIDIPacketNext(p);
|
||||
}
|
||||
}
|
||||
|
||||
void send(const uint8_t *bytes, int n) {
|
||||
Byte buf[64];
|
||||
MIDIPacketList *pl = (MIDIPacketList *)buf;
|
||||
MIDIPacket *pk = MIDIPacketListInit(pl);
|
||||
pk = MIDIPacketListAdd(pl, sizeof buf, pk, 0, n, bytes);
|
||||
if (!pk) return;
|
||||
{
|
||||
std::lock_guard<std::mutex> g(destLock);
|
||||
for (MIDIEndpointRef d : dests) MIDISend(outPort, d, pl);
|
||||
}
|
||||
if (virtualOut) MIDIReceived(virtualOut, pl);
|
||||
}
|
||||
|
||||
/// MidiClock.sendLoop: clock at 24 PPQN while playing, Start/Stop on the edges,
|
||||
/// and the engine's sequenced notes. Polls every 0.5 ms while sending.
|
||||
void sendLoop() {
|
||||
bool lastPlaying = false;
|
||||
int64_t next = 0;
|
||||
const uint8_t clock = 0xF8, start = 0xFA, stop = 0xFC;
|
||||
while (running.load()) {
|
||||
if (sendEnabled.load()) {
|
||||
const bool playing = engine->isPlaying();
|
||||
const int64_t now = nowNs();
|
||||
if (playing && !lastPlaying) { send(&start, 1); next = now; lastPlaying = true; }
|
||||
else if (!playing && lastPlaying) { send(&stop, 1); lastPlaying = false; }
|
||||
if (playing && now >= next) {
|
||||
send(&clock, 1);
|
||||
const float bpm = std::clamp(project->tempoBpm, 20.f, 300.f);
|
||||
const int64_t interval = (int64_t)(60'000'000'000.0 / (bpm * 24.0));
|
||||
next += interval;
|
||||
if (next < now) next = now + interval;
|
||||
}
|
||||
for (int guard = 0, m; guard < 256 && (m = engine->pollMidiOut()) >= 0; ++guard) {
|
||||
const uint8_t msg[3] = {(uint8_t)((m >> 16) & 0xFF), (uint8_t)((m >> 8) & 0x7F), (uint8_t)(m & 0x7F)};
|
||||
send(msg, 3);
|
||||
}
|
||||
} else if (lastPlaying) {
|
||||
send(&stop, 1);
|
||||
lastPlaying = false;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(sendEnabled.load() ? 500 : 10'000));
|
||||
}
|
||||
if (lastPlaying) send(&stop, 1);
|
||||
}
|
||||
};
|
||||
|
||||
State *gState = nullptr;
|
||||
|
||||
NSString *stringProp(MIDIObjectRef o, CFStringRef prop) {
|
||||
CFStringRef s = nullptr;
|
||||
if (MIDIObjectGetStringProperty(o, prop, &s) != noErr || !s) return @"";
|
||||
return (__bridge_transfer NSString *)s;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
@implementation SizzleMidi {
|
||||
NSMutableSet<NSString *> *_disabled;
|
||||
NSArray<SizzleMidiSource *> *_sources;
|
||||
}
|
||||
|
||||
+ (SizzleMidi *)shared {
|
||||
static SizzleMidi *m;
|
||||
static dispatch_once_t once;
|
||||
dispatch_once(&once, ^{ m = [SizzleMidi new]; });
|
||||
return m;
|
||||
}
|
||||
|
||||
- (instancetype)init {
|
||||
if ((self = [super init])) { _disabled = [NSMutableSet set]; _sources = @[]; }
|
||||
return self;
|
||||
}
|
||||
|
||||
- (NSArray<SizzleMidiSource *> *)sources { return _sources; }
|
||||
|
||||
/// A parser for [conn] whose messages go to the module, the CC handler and the clock.
|
||||
static std::unique_ptr<midi::MidiByteParser> makeParser(State *st, intptr_t id) {
|
||||
return std::make_unique<midi::MidiByteParser>(
|
||||
[st, id](int status, int d1, int d2) {
|
||||
if (st->module.onChannelMessage(id, status, d1, d2) || (status & 0xF0) != 0xB0) return;
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (auto cb = SizzleMidi.shared.onControl) cb(d1, d2);
|
||||
});
|
||||
},
|
||||
[st](int status) {
|
||||
std::lock_guard<std::mutex> g(st->followerLock);
|
||||
st->follower.realtime(status, nowNs());
|
||||
});
|
||||
}
|
||||
|
||||
- (void)startWithDisabledKeys:(NSSet<NSString *> *)disabled {
|
||||
if (gState) return;
|
||||
[_disabled setSet:disabled];
|
||||
SizzleSession *session = SizzleSession.shared;
|
||||
State *st = new State();
|
||||
gState = st;
|
||||
st->sink.session = session;
|
||||
st->engine = [session enginePointer];
|
||||
st->project = [session projectPointer];
|
||||
st->engine->setMidiOutEnabled(_sendClock);
|
||||
st->sendEnabled = _sendClock;
|
||||
st->receiveEnabled = _receiveClock;
|
||||
st->soundModule = _soundModule;
|
||||
|
||||
st->module.listener = [](bool on, int ch, int note, int vel) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (auto cb = SizzleMidi.shared.onNote) cb(on, ch, note, vel);
|
||||
});
|
||||
};
|
||||
// Start/Stop always reach the engine (an armed recording follows another app's
|
||||
// transport); the song itself follows only with "receive clock" on and outside
|
||||
// sound-module mode. Tempo follows whenever receiving.
|
||||
st->follower.onTransport = [st](bool start) {
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (start) st->engine->externalClockStart(); else st->engine->externalClockStop();
|
||||
if (!st->receiveEnabled.load() || st->soundModule.load()) return;
|
||||
SizzleSession *s = SizzleSession.shared;
|
||||
if (start) { if (!s.isPlaying) [s play]; } else [s pause];
|
||||
});
|
||||
};
|
||||
st->follower.onTempo = [st](float bpm) {
|
||||
if (!st->receiveEnabled.load()) return;
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
SizzleSession.shared.tempo = bpm;
|
||||
if (auto cb = SizzleMidi.shared.onTempoFollowed) cb(bpm);
|
||||
});
|
||||
};
|
||||
|
||||
__weak SizzleMidi *weakSelf = self;
|
||||
OSStatus err = MIDIClientCreateWithBlock(CFSTR("Sizzle"), &st->client, ^(const MIDINotification *n) {
|
||||
if (n->messageID != kMIDIMsgSetupChanged) return;
|
||||
dispatch_async(dispatch_get_main_queue(), ^{ [weakSelf rescan]; });
|
||||
});
|
||||
if (err != noErr) { NSLog(@"Sizzle MIDI: no client (%d)", (int)err); return; }
|
||||
MIDIInputPortCreateWithBlock(st->client, CFSTR("Sizzle In"), &st->inPort, ^(const MIDIPacketList *pl, void *ref) {
|
||||
st->feed((Conn *)ref, pl);
|
||||
});
|
||||
MIDIOutputPortCreate(st->client, CFSTR("Sizzle Out"), &st->outPort);
|
||||
// Sizzle as a destination other apps can pick, and as a source of its clock/notes.
|
||||
st->virtualConn.id = -1;
|
||||
st->virtualConn.parser = makeParser(st, -1);
|
||||
Conn *vc = &st->virtualConn;
|
||||
if (MIDIDestinationCreateWithBlock(st->client, CFSTR("Sizzle"), &st->virtualIn, ^(const MIDIPacketList *pl, void *) {
|
||||
st->feed(vc, pl);
|
||||
}) != noErr) st->virtualIn = 0;
|
||||
else st->module.sourceConnected(-1);
|
||||
if (MIDISourceCreate(st->client, CFSTR("Sizzle"), &st->virtualOut) != noErr) st->virtualOut = 0;
|
||||
|
||||
st->running = true;
|
||||
st->sender = std::thread([st] { st->sendLoop(); });
|
||||
[self rescan];
|
||||
}
|
||||
|
||||
/// Match CoreMIDI's endpoints with our connections: connect enabled new sources,
|
||||
/// drop vanished ones (releasing their notes), refresh the destination list.
|
||||
- (void)rescan {
|
||||
State *st = gState;
|
||||
if (!st) return;
|
||||
std::vector<MIDIEndpointRef> dests;
|
||||
for (ItemCount i = 0, n = MIDIGetNumberOfDestinations(); i < n; ++i) {
|
||||
MIDIEndpointRef d = MIDIGetDestination(i);
|
||||
if (d && d != st->virtualIn) dests.push_back(d);
|
||||
}
|
||||
{ std::lock_guard<std::mutex> g(st->destLock); st->dests = dests; }
|
||||
|
||||
std::vector<bool> seen(st->conns.size(), false);
|
||||
for (ItemCount i = 0, n = MIDIGetNumberOfSources(); i < n; ++i) {
|
||||
MIDIEndpointRef ep = MIDIGetSource(i);
|
||||
if (!ep || ep == st->virtualOut) continue;
|
||||
SInt32 uid = 0;
|
||||
MIDIObjectGetIntegerProperty(ep, kMIDIPropertyUniqueID, &uid);
|
||||
Conn *c = nullptr;
|
||||
for (size_t k = 0; k < st->conns.size(); ++k)
|
||||
if (st->conns[k]->uid == uid) { c = st->conns[k].get(); seen[k] = true; break; }
|
||||
if (!c) {
|
||||
auto made = std::make_unique<Conn>();
|
||||
made->id = (intptr_t)st->conns.size() + 1;
|
||||
made->uid = uid;
|
||||
made->parser = makeParser(st, made->id);
|
||||
c = made.get();
|
||||
st->conns.push_back(std::move(made));
|
||||
seen.push_back(true);
|
||||
}
|
||||
NSString *name = stringProp(ep, kMIDIPropertyDisplayName);
|
||||
if (!name.length) name = stringProp(ep, kMIDIPropertyName);
|
||||
c->name = name.length ? name : @"MIDI device";
|
||||
c->key = [@[stringProp(ep, kMIDIPropertyManufacturer), stringProp(ep, kMIDIPropertyModel), c->name]
|
||||
componentsJoinedByString:@"|"];
|
||||
if (c->connected && c->ep != ep) { MIDIPortDisconnectSource(st->inPort, c->ep); c->connected = false; st->module.sourceDisconnected(c->id); }
|
||||
c->ep = ep;
|
||||
const bool want = ![_disabled containsObject:c->key];
|
||||
if (want && !c->connected && MIDIPortConnectSource(st->inPort, ep, c) == noErr) {
|
||||
c->connected = true;
|
||||
st->module.sourceConnected(c->id);
|
||||
} else if (!want && c->connected) {
|
||||
MIDIPortDisconnectSource(st->inPort, ep);
|
||||
c->connected = false;
|
||||
st->module.sourceDisconnected(c->id);
|
||||
}
|
||||
}
|
||||
for (size_t k = 0; k < st->conns.size(); ++k) {
|
||||
Conn *c = st->conns[k].get();
|
||||
if (!seen[k]) {
|
||||
if (c->connected) { c->connected = false; st->module.sourceDisconnected(c->id); }
|
||||
c->ep = 0;
|
||||
}
|
||||
}
|
||||
[self publish];
|
||||
}
|
||||
|
||||
- (void)publish {
|
||||
NSMutableArray *list = [NSMutableArray array];
|
||||
NSMutableSet *keys = [NSMutableSet set];
|
||||
if (gState) for (auto &c : gState->conns) {
|
||||
if (!c->ep || [keys containsObject:c->key]) continue;
|
||||
[keys addObject:c->key];
|
||||
[list addObject:[[SizzleMidiSource alloc] initWithKey:c->key name:c->name
|
||||
enabled:![_disabled containsObject:c->key] connected:c->connected]];
|
||||
}
|
||||
_sources = list;
|
||||
if (_onSourcesChanged) _onSourcesChanged();
|
||||
}
|
||||
|
||||
- (void)setSourceKey:(NSString *)key enabled:(BOOL)enabled {
|
||||
if (enabled) [_disabled removeObject:key]; else [_disabled addObject:key];
|
||||
[self rescan];
|
||||
}
|
||||
|
||||
- (void)reconnect {
|
||||
State *st = gState;
|
||||
if (!st) return;
|
||||
for (auto &c : st->conns) {
|
||||
if (!c->connected) continue;
|
||||
MIDIPortDisconnectSource(st->inPort, c->ep);
|
||||
c->connected = false;
|
||||
st->module.sourceDisconnected(c->id);
|
||||
}
|
||||
[self rescan];
|
||||
}
|
||||
|
||||
- (void)releaseAll { if (gState) gState->module.releaseAll(); }
|
||||
|
||||
- (void)setSendClock:(BOOL)on {
|
||||
_sendClock = on;
|
||||
if (gState) { gState->sendEnabled = on; gState->engine->setMidiOutEnabled(on); }
|
||||
}
|
||||
- (void)setReceiveClock:(BOOL)on { _receiveClock = on; if (gState) gState->receiveEnabled = on; }
|
||||
- (void)setSoundModule:(BOOL)on { _soundModule = on; if (gState) gState->soundModule = on; }
|
||||
|
||||
@end
|
||||
@@ -0,0 +1,31 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#import "SizzleSession.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/// Project bundles and whole-app backups (Android's ProjectBundleIo and BackupIo),
|
||||
/// both ZIP archives in Android's layouts.
|
||||
@interface SizzleSession (Files)
|
||||
|
||||
/// The open song as a bundle (.szgz): project.szg, every sample its Sampler,
|
||||
/// SF2/XI, Grain Cloud and Wavetable slots use (samples/<n>.wav) and
|
||||
/// samples/manifest.txt (`<n>\t<sample id>` per line).
|
||||
- (nullable NSData *)projectBundleData;
|
||||
/// Replace the open song with a bundle's: its samples are stored under their ids
|
||||
/// first, so the song finds them. Leaves the song alone if it isn't a bundle.
|
||||
- (BOOL)importProjectBundleData:(NSData *)data error:(NSError **)error;
|
||||
/// True for a ZIP archive (bundle or backup) rather than text.
|
||||
+ (BOOL)isZipData:(NSData *)data;
|
||||
|
||||
/// Everything Sizzle keeps: Documents/songs, themes, presets and samples, the
|
||||
/// autosaved song, and [settings] as settings.txt. The open song is autosaved first.
|
||||
- (nullable NSData *)backupDataWithSettings:(NSString *)settings;
|
||||
/// Restore a backup: it is unpacked aside first and only swapped in once it looks
|
||||
/// like one, so a wrong file can't destroy anything. The restored autosave becomes
|
||||
/// the open song. Returns the backup's settings text ("" if it has none), or nil.
|
||||
- (nullable NSString *)restoreBackupData:(NSData *)data error:(NSError **)error;
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,225 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#import "SizzleSession+Files.h"
|
||||
#import "SizzleSession+Internal.h"
|
||||
#import "SizzleSession+Setup.h"
|
||||
|
||||
#include <map>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "io/Zip.hpp"
|
||||
|
||||
using namespace sizzle;
|
||||
namespace zip = sizzle::io::zip;
|
||||
|
||||
// Defined in SizzleSession.mm (Documents/samples/<id>.wav).
|
||||
@interface SizzleSession (FilesPrivate)
|
||||
- (NSURL *)sampleURL:(const std::string &)id;
|
||||
@end
|
||||
|
||||
namespace {
|
||||
|
||||
NSError *filesError(NSString *msg) {
|
||||
return [NSError errorWithDomain:@"Sizzle" code:3 userInfo:@{NSLocalizedDescriptionKey: msg}];
|
||||
}
|
||||
|
||||
NSURL *documents() {
|
||||
return [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> bytesOf(NSData *d) {
|
||||
const uint8_t *b = (const uint8_t *)d.bytes;
|
||||
return std::vector<uint8_t>(b, b + d.length);
|
||||
}
|
||||
|
||||
NSData *dataOf(const std::vector<uint8_t> &v) { return [NSData dataWithBytes:v.data() length:v.size()]; }
|
||||
|
||||
// Backup areas under Documents (Android: songs, themes, presets, datastore; the
|
||||
// iOS app keeps its samples as files too, and settings as settings.txt).
|
||||
NSArray<NSString *> *const kAreas = @[@"songs", @"themes", @"presets", @"samples"];
|
||||
NSString *const kAutosave = @"autosave.szg";
|
||||
NSString *const kSettings = @"settings.txt";
|
||||
|
||||
} // namespace
|
||||
|
||||
@implementation SizzleSession (Files)
|
||||
|
||||
+ (BOOL)isZipData:(NSData *)data {
|
||||
return data.length >= 4 && !memcmp(data.bytes, "PK\x03\x04", 4);
|
||||
}
|
||||
|
||||
#pragma mark - bundles
|
||||
|
||||
/// ProjectBundleIo.collectSampleIds: per slot, a Sampler's pads, else the
|
||||
/// SF2/XI, Grain Cloud or Wavetable sample; each id once, in that order.
|
||||
- (std::vector<std::string>)files_sampleIds {
|
||||
std::vector<std::string> ids;
|
||||
auto add = [&](NSString *v) {
|
||||
if (!v.length) return;
|
||||
std::string id = v.UTF8String;
|
||||
for (auto &x : ids) if (x == id) return;
|
||||
ids.push_back(id);
|
||||
};
|
||||
for (NSInteger s = 0; s < 16; ++s) {
|
||||
NSString *type = [self typeOfSlot:s];
|
||||
if ([type isEqualToString:@"SAMPLER"]) {
|
||||
for (int p = 0; p < 16; ++p) add([self valueOfSlot:s key:[NSString stringWithFormat:@"pad%d", p]]);
|
||||
} else if ([@[@"SOUNDFONT", @"GRAIN_CLOUD", @"WAVETABLE"] containsObject:type]) {
|
||||
add([self valueOfSlot:s key:@"sfSample"]);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
- (nullable NSData *)projectBundleData {
|
||||
std::vector<zip::Entry> entries;
|
||||
NSData *text = [[self projectText] dataUsingEncoding:NSUTF8StringEncoding];
|
||||
entries.push_back({"project.szg", bytesOf(text)});
|
||||
std::string manifest;
|
||||
int i = 0;
|
||||
for (const std::string &id : [self files_sampleIds]) {
|
||||
NSData *wav = [NSData dataWithContentsOfURL:[self sampleURL:id]];
|
||||
std::vector<uint8_t> bytes;
|
||||
if (wav) bytes = bytesOf(wav);
|
||||
else if (auto s = [self sampleStore].get(id.c_str())) bytes = sampler::SampleStore::encodeWav(*s);
|
||||
if (!bytes.empty()) {
|
||||
entries.push_back({"samples/" + std::to_string(i) + ".wav", std::move(bytes)});
|
||||
manifest += std::to_string(i) + "\t" + id + "\n";
|
||||
}
|
||||
++i;
|
||||
}
|
||||
entries.push_back({"samples/manifest.txt", std::vector<uint8_t>(manifest.begin(), manifest.end())});
|
||||
return dataOf(zip::write(entries));
|
||||
}
|
||||
|
||||
- (BOOL)importProjectBundleData:(NSData *)data error:(NSError **)error {
|
||||
std::vector<zip::Entry> entries;
|
||||
// ZipLimits.forBundle: 64 MB.
|
||||
if (!zip::read((const uint8_t *)data.bytes, data.length, entries, 64ull << 20)) {
|
||||
if (error) *error = filesError(@"Couldn't read this bundle: it isn't a ZIP, is damaged, or is larger than 64 MB.");
|
||||
return NO;
|
||||
}
|
||||
NSString *text = nil;
|
||||
std::map<std::string, std::string> manifest; // index -> original id
|
||||
std::map<std::string, const std::vector<uint8_t> *> wavs;
|
||||
for (const auto &e : entries) {
|
||||
if (!zip::safeName(e.name)) continue;
|
||||
if (e.name == "project.szg") text = [[NSString alloc] initWithBytes:e.data.data() length:e.data.size() encoding:NSUTF8StringEncoding];
|
||||
else if (e.name == "samples/manifest.txt") {
|
||||
std::string m(e.data.begin(), e.data.end());
|
||||
size_t start = 0;
|
||||
while (start < m.size()) {
|
||||
size_t end = m.find('\n', start);
|
||||
if (end == std::string::npos) end = m.size();
|
||||
std::string line = m.substr(start, end - start);
|
||||
if (!line.empty() && line.back() == '\r') line.pop_back();
|
||||
const size_t tab = line.find('\t');
|
||||
if (tab != std::string::npos && tab > 0) manifest[line.substr(0, tab)] = line.substr(tab + 1);
|
||||
start = end + 1;
|
||||
}
|
||||
} else if (e.name.rfind("samples/", 0) == 0 && e.name.size() > 12 && e.name.compare(e.name.size() - 4, 4, ".wav") == 0) {
|
||||
wavs[e.name.substr(8, e.name.size() - 12)] = &e.data;
|
||||
}
|
||||
}
|
||||
if (!text || ![SizzleSession looksLikeProjectText:text]) {
|
||||
if (error) *error = filesError(@"This archive holds no Sizzle project.");
|
||||
return NO;
|
||||
}
|
||||
// Store each sample under its original id, where the song looks for it.
|
||||
for (const auto &[idx, id] : manifest) {
|
||||
auto w = wavs.find(idx);
|
||||
if (w == wavs.end() || id.empty()) continue;
|
||||
[self sampleStore].remove(id.c_str()); // a stale copy under the same id must not win
|
||||
[dataOf(*w->second) writeToURL:[self sampleURL:id] atomically:YES];
|
||||
}
|
||||
[self stop];
|
||||
return [self importProjectText:text error:error];
|
||||
}
|
||||
|
||||
#pragma mark - backups
|
||||
|
||||
- (nullable NSData *)backupDataWithSettings:(NSString *)settings {
|
||||
[self autosave];
|
||||
NSFileManager *fm = NSFileManager.defaultManager;
|
||||
NSURL *docs = documents();
|
||||
std::vector<zip::Entry> entries;
|
||||
for (NSString *area in kAreas) {
|
||||
NSURL *dir = [docs URLByAppendingPathComponent:area];
|
||||
NSDirectoryEnumerator *walk = [fm enumeratorAtURL:dir includingPropertiesForKeys:@[NSURLIsRegularFileKey] options:0 errorHandler:nil];
|
||||
for (NSURL *f in walk) {
|
||||
NSNumber *regular = nil;
|
||||
[f getResourceValue:®ular forKey:NSURLIsRegularFileKey error:nil];
|
||||
if (!regular.boolValue) continue;
|
||||
NSString *rel = [f.path substringFromIndex:dir.path.length];
|
||||
if ([rel hasPrefix:@"/"]) rel = [rel substringFromIndex:1];
|
||||
if ([rel hasPrefix:@"."] || [rel containsString:@"/."]) continue; // export scratch
|
||||
NSData *d = [NSData dataWithContentsOfURL:f];
|
||||
if (d) entries.push_back({std::string(area.UTF8String) + "/" + rel.UTF8String, bytesOf(d)});
|
||||
}
|
||||
}
|
||||
if (NSData *a = [NSData dataWithContentsOfURL:[docs URLByAppendingPathComponent:kAutosave]]) entries.push_back({kAutosave.UTF8String, bytesOf(a)});
|
||||
NSData *s = [settings dataUsingEncoding:NSUTF8StringEncoding];
|
||||
entries.push_back({kSettings.UTF8String, bytesOf(s)});
|
||||
return dataOf(zip::write(entries));
|
||||
}
|
||||
|
||||
- (nullable NSString *)restoreBackupData:(NSData *)data error:(NSError **)error {
|
||||
std::vector<zip::Entry> entries;
|
||||
// ZipLimits.forBackup: 512 MB.
|
||||
if (!zip::read((const uint8_t *)data.bytes, data.length, entries, 512ull << 20)) {
|
||||
if (error) *error = filesError(@"Couldn't read this backup: it isn't a ZIP, is damaged, or is too large.");
|
||||
return nil;
|
||||
}
|
||||
NSFileManager *fm = NSFileManager.defaultManager;
|
||||
NSURL *docs = documents();
|
||||
NSURL *staging = [docs URLByAppendingPathComponent:@".restore_tmp"];
|
||||
[fm removeItemAtURL:staging error:nil];
|
||||
[fm createDirectoryAtURL:staging withIntermediateDirectories:YES attributes:nil error:nil];
|
||||
BOOL looksValid = NO;
|
||||
NSString *settings = @"";
|
||||
for (const auto &e : entries) {
|
||||
if (!zip::safeName(e.name)) continue;
|
||||
NSString *name = @(e.name.c_str());
|
||||
if ([name isEqualToString:kSettings]) {
|
||||
settings = [[NSString alloc] initWithBytes:e.data.data() length:e.data.size() encoding:NSUTF8StringEncoding] ?: @"";
|
||||
continue;
|
||||
}
|
||||
NSString *top = name.pathComponents.firstObject;
|
||||
const BOOL area = [kAreas containsObject:top] && name.pathComponents.count > 1;
|
||||
if (!area && ![name isEqualToString:kAutosave]) continue; // not ours (Android's datastore, …)
|
||||
NSURL *target = [staging URLByAppendingPathComponent:name];
|
||||
[fm createDirectoryAtURL:target.URLByDeletingLastPathComponent withIntermediateDirectories:YES attributes:nil error:nil];
|
||||
if ([dataOf(e.data) writeToURL:target atomically:NO]) looksValid = YES;
|
||||
}
|
||||
if (!looksValid) {
|
||||
[fm removeItemAtURL:staging error:nil];
|
||||
if (error) *error = filesError(@"This file doesn't look like a Sizzle backup.");
|
||||
return nil;
|
||||
}
|
||||
[self stop];
|
||||
for (NSString *area in kAreas) {
|
||||
NSURL *src = [staging URLByAppendingPathComponent:area];
|
||||
if (![fm fileExistsAtPath:src.path]) continue;
|
||||
NSURL *dst = [docs URLByAppendingPathComponent:area];
|
||||
[fm removeItemAtURL:dst error:nil];
|
||||
[fm moveItemAtURL:src toURL:dst error:nil];
|
||||
}
|
||||
NSURL *autoSrc = [staging URLByAppendingPathComponent:kAutosave];
|
||||
if ([fm fileExistsAtPath:autoSrc.path]) {
|
||||
NSURL *dst = [docs URLByAppendingPathComponent:kAutosave];
|
||||
[fm removeItemAtURL:dst error:nil];
|
||||
[fm moveItemAtURL:autoSrc toURL:dst error:nil];
|
||||
NSString *text = [NSString stringWithContentsOfURL:dst encoding:NSUTF8StringEncoding error:nil];
|
||||
if (text) [self loadProjectText:text error:nil];
|
||||
}
|
||||
[fm removeItemAtURL:staging error:nil];
|
||||
[fm createDirectoryAtURL:[docs URLByAppendingPathComponent:@"songs"] withIntermediateDirectories:YES attributes:nil error:nil];
|
||||
[fm createDirectoryAtURL:[docs URLByAppendingPathComponent:@"samples"] withIntermediateDirectories:YES attributes:nil error:nil];
|
||||
[self rehydrateSamples];
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SizzleSessionDidChange object:nil];
|
||||
return settings;
|
||||
}
|
||||
|
||||
@end
|
||||
@@ -20,4 +20,14 @@
|
||||
- (void)rehydrateSamples;
|
||||
/// The sample store (thread-safe on its own).
|
||||
- (sizzle::sampler::SampleStore &)sampleStore;
|
||||
|
||||
// For the MIDI threads (SizzleMidi): no lock taken.
|
||||
/// Queue a note for the audio thread. Callers must not push concurrently (the
|
||||
/// sound module's lock serialises them).
|
||||
- (void)midiNoteOn:(int)note velocity:(int)velocity channel:(int)channel;
|
||||
- (void)midiNoteOff:(int)note channel:(int)channel;
|
||||
/// The engine and song, for lock-free reads (isPlaying, pollMidiOut, the tempo)
|
||||
/// and the engine's atomic setters. Both live as long as the session.
|
||||
- (sizzle::engine::Engine *)enginePointer;
|
||||
- (const sizzle::model::Project *)projectPointer;
|
||||
@end
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#import "SizzleSession.h"
|
||||
|
||||
NS_ASSUME_NONNULL_BEGIN
|
||||
|
||||
/// Master-bus recording (Android's MasterRecorder + the mixer's record toolbar).
|
||||
/// Arm it, and the next Play (or an external MIDI clock Start) captures the final
|
||||
/// stereo mix to a 16-bit WAV, until a tail of [recordTailBars] bars after the
|
||||
/// sequencer stops. Takes go to Documents/Recordings/sizzle-yyyyMMdd-HHmmss.wav
|
||||
/// (visible in the Files app). The audio thread only writes into a ring buffer; a
|
||||
/// writer thread does the file I/O.
|
||||
@interface SizzleSession (Record)
|
||||
@property (nonatomic) BOOL recordArmed;
|
||||
/// FX tail captured after the sequencer stops, in bars (0..4).
|
||||
@property (nonatomic) NSInteger recordTailBars;
|
||||
/// True while a take is capturing (from its start until the file is finished).
|
||||
@property (nonatomic, readonly) BOOL masterRecording;
|
||||
/// The last finished take, if any (this run of the app).
|
||||
@property (nonatomic, readonly, nullable) NSURL *lastRecordingURL;
|
||||
@property (nonatomic, readonly) NSURL *recordingsDirectory;
|
||||
@end
|
||||
|
||||
NS_ASSUME_NONNULL_END
|
||||
@@ -0,0 +1,166 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
#import "SizzleSession+Record.h"
|
||||
#import "SizzleSession+Internal.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
using namespace sizzle;
|
||||
|
||||
namespace {
|
||||
|
||||
/// MasterRecorder.kt: a single-producer / single-consumer ring of interleaved
|
||||
/// stereo floats (about two seconds), drained by a writer thread into a 16-bit
|
||||
/// stereo WAV whose header sizes are patched at the end.
|
||||
class MasterRecorder final : public engine::MasterSink {
|
||||
public:
|
||||
MasterRecorder(int sampleRate, NSURL *dir) : sr(sampleRate), ring((size_t)std::max(2, sampleRate * 4)), dir(dir) {}
|
||||
~MasterRecorder() override { capturing.store(false); if (writer.joinable()) writer.join(); }
|
||||
|
||||
bool isActive() const override { return active.load(); }
|
||||
|
||||
/// Main thread (Play) or the MIDI thread (an external clock Start).
|
||||
bool begin() override {
|
||||
if (active.load()) return false;
|
||||
if (writer.joinable()) writer.join(); // the previous take's thread has finished (active is false)
|
||||
writePos.store(0); readPos.store(0);
|
||||
active.store(true);
|
||||
capturing.store(true);
|
||||
NSDate *start = [NSDate date];
|
||||
NSURL *temp = [dir URLByAppendingPathComponent:@".take.wav"];
|
||||
writer = std::thread([this, temp, start] {
|
||||
const bool ok = writeLoop(temp.fileSystemRepresentation);
|
||||
NSURL *done = ok ? finish(temp, start) : nil;
|
||||
active.store(false);
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
if (done) lastTake = done;
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SizzleSessionDidChange object:nil];
|
||||
});
|
||||
});
|
||||
dispatch_async(dispatch_get_main_queue(), ^{
|
||||
[[NSNotificationCenter defaultCenter] postNotificationName:SizzleSessionDidChange object:nil];
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Audio thread: no allocation, no locks; drops the frame if the writer starved.
|
||||
void write(float left, float right) override {
|
||||
if (!capturing.load(std::memory_order_relaxed)) return;
|
||||
const uint64_t w = writePos.load(std::memory_order_relaxed);
|
||||
if (w - readPos.load(std::memory_order_acquire) > ring.size() - 2) return;
|
||||
ring[w % ring.size()] = left;
|
||||
ring[(w + 1) % ring.size()] = right;
|
||||
writePos.store(w + 2, std::memory_order_release);
|
||||
}
|
||||
|
||||
void endCapture() override { capturing.store(false); }
|
||||
|
||||
NSURL *lastTake = nil; // main thread
|
||||
|
||||
private:
|
||||
bool writeLoop(const char *path) {
|
||||
FILE *f = std::fopen(path, "wb");
|
||||
if (!f) { capturing.store(false); return false; }
|
||||
writeHeader(f, 0);
|
||||
uint64_t samples = 0;
|
||||
constexpr size_t chunk = 4096;
|
||||
int16_t out[chunk];
|
||||
bool ok = true;
|
||||
for (;;) {
|
||||
const uint64_t w = writePos.load(std::memory_order_acquire);
|
||||
const uint64_t r = readPos.load(std::memory_order_relaxed);
|
||||
if (r < w) {
|
||||
const size_t n = (size_t)std::min<uint64_t>(w - r, chunk);
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const float s = std::clamp(ring[(r + i) % ring.size()], -1.f, 1.f);
|
||||
out[i] = (int16_t)(int)(s * 32767.f); // little-endian host
|
||||
}
|
||||
if (std::fwrite(out, 2, n, f) != n) ok = false;
|
||||
samples += n;
|
||||
readPos.store(r + n, std::memory_order_release);
|
||||
} else if (!capturing.load()) {
|
||||
break;
|
||||
} else {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
}
|
||||
}
|
||||
writeHeader(f, samples);
|
||||
ok = std::fclose(f) == 0 && ok;
|
||||
return ok;
|
||||
}
|
||||
|
||||
void writeHeader(FILE *f, uint64_t sampleCount) {
|
||||
const uint32_t data = (uint32_t)(sampleCount * 2);
|
||||
auto u32 = [f](uint32_t v) { uint8_t b[4] = {(uint8_t)v, (uint8_t)(v >> 8), (uint8_t)(v >> 16), (uint8_t)(v >> 24)}; std::fwrite(b, 1, 4, f); };
|
||||
auto u16 = [f](uint16_t v) { uint8_t b[2] = {(uint8_t)v, (uint8_t)(v >> 8)}; std::fwrite(b, 1, 2, f); };
|
||||
std::fseek(f, 0, SEEK_SET);
|
||||
std::fwrite("RIFF", 1, 4, f); u32(36 + data); std::fwrite("WAVE", 1, 4, f);
|
||||
std::fwrite("fmt ", 1, 4, f); u32(16); u16(1); u16(2); u32((uint32_t)sr); u32((uint32_t)sr * 4); u16(4); u16(16);
|
||||
std::fwrite("data", 1, 4, f); u32(data);
|
||||
std::fseek(f, 0, SEEK_END);
|
||||
}
|
||||
|
||||
/// Give the finished take its date-time name (Android: sizzle-yyyyMMdd-HHmmss.wav).
|
||||
NSURL *finish(NSURL *temp, NSDate *start) {
|
||||
NSDateFormatter *df = [NSDateFormatter new];
|
||||
df.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
|
||||
df.dateFormat = @"yyyyMMdd-HHmmss";
|
||||
NSString *base = [@"sizzle-" stringByAppendingString:[df stringFromDate:start]];
|
||||
NSURL *dst = [dir URLByAppendingPathComponent:[base stringByAppendingPathExtension:@"wav"]];
|
||||
for (int i = 2; [NSFileManager.defaultManager fileExistsAtPath:dst.path]; ++i)
|
||||
dst = [dir URLByAppendingPathComponent:[NSString stringWithFormat:@"%@-%d.wav", base, i]];
|
||||
return [NSFileManager.defaultManager moveItemAtURL:temp toURL:dst error:nil] ? dst : nil;
|
||||
}
|
||||
|
||||
const int sr;
|
||||
std::vector<float> ring;
|
||||
NSURL *dir;
|
||||
std::atomic<uint64_t> writePos{0}, readPos{0};
|
||||
std::atomic<bool> capturing{false}, active{false};
|
||||
std::thread writer;
|
||||
};
|
||||
|
||||
MasterRecorder *gRecorder = nullptr; // lives as long as the app (the session never goes away)
|
||||
bool gArmed = false;
|
||||
NSInteger gTail = 2;
|
||||
|
||||
} // namespace
|
||||
|
||||
@implementation SizzleSession (Record)
|
||||
|
||||
- (NSURL *)recordingsDirectory {
|
||||
NSURL *docs = [NSFileManager.defaultManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask].firstObject;
|
||||
NSURL *dir = [docs URLByAppendingPathComponent:@"Recordings"];
|
||||
[NSFileManager.defaultManager createDirectoryAtURL:dir withIntermediateDirectories:YES attributes:nil error:nil];
|
||||
return dir;
|
||||
}
|
||||
|
||||
- (void)rec_apply {
|
||||
NSURL *dir = self.recordingsDirectory;
|
||||
const bool armed = gArmed;
|
||||
const int tail = (int)gTail;
|
||||
[self edit:^(model::Project &, engine::Engine &e) {
|
||||
if (!gRecorder) {
|
||||
gRecorder = new MasterRecorder(e.sampleRate(), dir);
|
||||
e.setMasterSink(gRecorder);
|
||||
}
|
||||
e.setRecordingArm(armed, tail);
|
||||
}];
|
||||
}
|
||||
|
||||
- (BOOL)recordArmed { return gArmed; }
|
||||
- (void)setRecordArmed:(BOOL)armed { gArmed = armed; [self rec_apply]; }
|
||||
|
||||
- (NSInteger)recordTailBars { return gTail; }
|
||||
- (void)setRecordTailBars:(NSInteger)bars { gTail = std::clamp<NSInteger>(bars, 0, 4); [self rec_apply]; }
|
||||
|
||||
- (BOOL)masterRecording { return gRecorder && gRecorder->isActive(); }
|
||||
- (nullable NSURL *)lastRecordingURL { return gRecorder ? gRecorder->lastTake : nil; }
|
||||
|
||||
@end
|
||||
@@ -156,6 +156,10 @@ NS_SWIFT_UI_ACTOR
|
||||
/// Saved on backgrounding and restored at launch (Documents/autosave.szg).
|
||||
- (void)autosave;
|
||||
|
||||
#pragma mark - Audio output
|
||||
/// Pause the audio output (in the background with nothing to play) or start it again.
|
||||
@property (nonatomic) BOOL audioSuspended;
|
||||
|
||||
#pragma mark - Samples
|
||||
/// A WAV into a Sampler pad / an SF2, XI or WAV into the SF2/XI loader.
|
||||
- (BOOL)loadSampleData:(NSData *)data name:(NSString *)name intoSlot:(NSInteger)slot pad:(NSInteger)pad error:(NSError **)error;
|
||||
|
||||
@@ -47,6 +47,9 @@ struct NoteQueue {
|
||||
}
|
||||
};
|
||||
|
||||
/// The app paused the output on purpose (background, idle): don't restart it on a route change.
|
||||
bool gAudioSuspended = false;
|
||||
|
||||
constexpr int kChunk = 192; // Android's block size: keeps the MIDI LFO's rate (see PORTING.md)
|
||||
|
||||
NSError *sessionError(NSString *msg) {
|
||||
@@ -100,6 +103,7 @@ bool isSampleKey(const char *key) {
|
||||
std::unique_ptr<sampler::SampleStore> _store;
|
||||
std::unique_ptr<engine::Engine> _engine;
|
||||
NoteQueue _notes;
|
||||
NoteQueue _midiNotes; // pushed by the MIDI threads (serialised by the sound module's lock)
|
||||
std::vector<float> _scratch;
|
||||
AVAudioEngine *_audio;
|
||||
AVAudioSourceNode *_source;
|
||||
@@ -158,6 +162,26 @@ bool isSampleKey(const char *key) {
|
||||
if (getenv("SIZZLE_NO_AUDIO")) return; // the Mac snapshot tool: no sound
|
||||
NSError *err = nil;
|
||||
if (![_audio startAndReturnError:&err]) NSLog(@"Sizzle audio: %@", err);
|
||||
// A route or category change (the sample recorder switches to play-and-record,
|
||||
// headphones, an audio interface) stops the engine; an interruption (a call)
|
||||
// ends with it stopped. Start it again either way.
|
||||
AVAudioEngine *audio = _audio;
|
||||
void (^restart)(NSNotification *) = ^(NSNotification *) {
|
||||
if (audio.isRunning || gAudioSuspended) return;
|
||||
#if TARGET_OS_IPHONE
|
||||
[[AVAudioSession sharedInstance] setActive:YES error:nil];
|
||||
#endif
|
||||
NSError *e = nil;
|
||||
if (![audio startAndReturnError:&e]) NSLog(@"Sizzle audio restart: %@", e);
|
||||
};
|
||||
NSNotificationCenter *nc = NSNotificationCenter.defaultCenter;
|
||||
[nc addObserverForName:AVAudioEngineConfigurationChangeNotification object:_audio queue:NSOperationQueue.mainQueue usingBlock:restart];
|
||||
#if TARGET_OS_IPHONE
|
||||
[nc addObserverForName:AVAudioSessionInterruptionNotification object:nil queue:NSOperationQueue.mainQueue
|
||||
usingBlock:^(NSNotification *n) {
|
||||
if ([n.userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue] == AVAudioSessionInterruptionTypeEnded) restart(n);
|
||||
}];
|
||||
#endif
|
||||
}
|
||||
|
||||
/// The audio thread. Never blocks: if the song is being edited, this block is silent.
|
||||
@@ -180,6 +204,9 @@ bool isSampleKey(const char *key) {
|
||||
case 3: e->auditionSlotOff(n.b); break;
|
||||
}
|
||||
});
|
||||
_midiNotes.drain([e](const NoteEvent &n) {
|
||||
if (n.kind == 0) e->busNoteOn(n.a, n.b, n.c); else e->busNoteOff(n.a, n.b);
|
||||
});
|
||||
float *buf = _scratch.data();
|
||||
for (AVAudioFrameCount done = 0; done < frames;) {
|
||||
int n = (int)std::min<AVAudioFrameCount>(kChunk, frames - done);
|
||||
@@ -335,6 +362,25 @@ bool isSampleKey(const char *key) {
|
||||
- (void)stop { [self edit:^(model::Project &, engine::Engine &e) { e.stop(); }]; }
|
||||
- (void)panic { [self edit:^(model::Project &, engine::Engine &e) { e.panic(); }]; }
|
||||
- (BOOL)isPlaying { return _engine->isPlaying(); }
|
||||
|
||||
- (BOOL)audioSuspended { return !_audio.isRunning; }
|
||||
- (void)setAudioSuspended:(BOOL)suspended {
|
||||
if (getenv("SIZZLE_NO_AUDIO")) return;
|
||||
gAudioSuspended = suspended;
|
||||
if (suspended) { [_audio pause]; return; }
|
||||
if (_audio.isRunning) return;
|
||||
#if TARGET_OS_IPHONE
|
||||
[[AVAudioSession sharedInstance] setActive:YES error:nil];
|
||||
#endif
|
||||
NSError *e = nil;
|
||||
if (![_audio startAndReturnError:&e]) NSLog(@"Sizzle audio resume: %@", e);
|
||||
}
|
||||
|
||||
#pragma mark - MIDI threads (SizzleSession+Internal.h)
|
||||
- (void)midiNoteOn:(int)note velocity:(int)velocity channel:(int)channel { _midiNotes.push({0, channel, note, velocity}); }
|
||||
- (void)midiNoteOff:(int)note channel:(int)channel { _midiNotes.push({1, channel, note, 0}); }
|
||||
- (engine::Engine *)enginePointer { return _engine.get(); }
|
||||
- (const model::Project *)projectPointer { return _project.get(); }
|
||||
- (NSInteger)currentLine { return _engine->transport().currentLine; }
|
||||
- (NSInteger)currentBeat { return _engine->transport().currentBeat; }
|
||||
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Colour themes (Android's ThemeIo + ThemeLibrary): the two stock palettes in
|
||||
/// code, user themes as `SIZZLE-THEME 1` text in Documents/themes/<name>.szt, the
|
||||
/// same files the Android app imports and exports.
|
||||
@MainActor
|
||||
final class ThemeLibrary: ObservableObject {
|
||||
static let shared = ThemeLibrary()
|
||||
static let header = "SIZZLE-THEME 1"
|
||||
|
||||
@Published private(set) var names: [String] = []
|
||||
|
||||
private var dir: URL {
|
||||
let d = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("themes")
|
||||
try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)
|
||||
return d
|
||||
}
|
||||
|
||||
private init() { refresh() }
|
||||
|
||||
/// Stock themes first, then the stored ones alphabetically.
|
||||
func refresh() {
|
||||
let files = (try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? []
|
||||
let user = files.filter { $0.hasSuffix(".szt") }.map { String($0.dropLast(4)) }.sorted()
|
||||
names = Palette.stock.map(\.name) + user.filter { u in !Palette.stock.contains { $0.name == u } }
|
||||
}
|
||||
|
||||
func isStock(_ name: String) -> Bool { Palette.stock.contains { $0.name == name } }
|
||||
|
||||
func palette(named name: String) -> Palette? {
|
||||
if let p = Palette.stock.first(where: { $0.name == name }) { return p }
|
||||
guard let text = try? String(contentsOf: file(name), encoding: .utf8) else { return nil }
|
||||
return Self.parse(text)
|
||||
}
|
||||
|
||||
/// Apply a theme by name (unknown names fall back to the default) and remember it.
|
||||
func select(_ name: String) {
|
||||
let p = palette(named: name) ?? .amber
|
||||
Theme.current = p
|
||||
if AppSettings.shared.paletteName != p.name { AppSettings.shared.paletteName = p.name }
|
||||
}
|
||||
|
||||
/// Store and apply theme [text]; nil if it isn't a theme.
|
||||
func importText(_ text: String) -> Palette? {
|
||||
guard let p = Self.parse(text) else { return nil }
|
||||
try? Self.export(p).write(to: file(p.name), atomically: true, encoding: .utf8)
|
||||
refresh()
|
||||
select(p.name)
|
||||
return p
|
||||
}
|
||||
|
||||
func delete(_ name: String) {
|
||||
guard !isStock(name) else { return }
|
||||
try? FileManager.default.removeItem(at: file(name))
|
||||
refresh()
|
||||
if Theme.current.name == name { select(Palette.amber.name) }
|
||||
}
|
||||
|
||||
/// The current theme as a .szt in a temporary folder, for sharing.
|
||||
func exportFile() throws -> URL {
|
||||
let p = Theme.current
|
||||
let d = FileManager.default.temporaryDirectory.appendingPathComponent("ThemeExport", isDirectory: true)
|
||||
try? FileManager.default.removeItem(at: d)
|
||||
try FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)
|
||||
let url = d.appendingPathComponent(Self.sanitize(p.name) + ".szt")
|
||||
try Self.export(p).write(to: url, atomically: true, encoding: .utf8)
|
||||
return url
|
||||
}
|
||||
|
||||
private func file(_ name: String) -> URL { dir.appendingPathComponent(Self.sanitize(name) + ".szt") }
|
||||
|
||||
/// Android's sanitize: anything but letters, digits, `._ -` becomes `_`.
|
||||
static func sanitize(_ name: String) -> String {
|
||||
let ok = Set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._ -")
|
||||
let s = String(name.trimmingCharacters(in: .whitespaces).map { ok.contains($0) ? $0 : "_" })
|
||||
return s.isEmpty ? "theme" : s
|
||||
}
|
||||
|
||||
// MARK: ThemeIo
|
||||
|
||||
static func export(_ p: Palette) -> String {
|
||||
func hex(_ c: UInt32) -> String { String(format: "#%06X", c & 0xFFFFFF) }
|
||||
return [header, "NAME=\(p.name)", "background=\(hex(p.background))", "surface=\(hex(p.surface))",
|
||||
"grid=\(hex(p.grid))", "text=\(hex(p.text))", "textDim=\(hex(p.textDim))", "accent=\(hex(p.accent))",
|
||||
"beat=\(hex(p.beat))", "bar=\(hex(p.bar))", "playhead=\(hex(p.playhead))", "danger=\(hex(p.danger))"]
|
||||
.joined(separator: "\n") + "\n"
|
||||
}
|
||||
|
||||
/// Lenient about single colours (a bad one falls back to the default theme's),
|
||||
/// strict about the header and a name.
|
||||
static func parse(_ text: String) -> Palette? {
|
||||
var map: [String: String] = [:]
|
||||
var sawHeader = false
|
||||
for raw in text.components(separatedBy: .newlines) {
|
||||
let line = raw.trimmingCharacters(in: .whitespaces)
|
||||
if line.isEmpty { continue }
|
||||
if line == header { sawHeader = true; continue }
|
||||
if let eq = line.firstIndex(of: "="), eq > line.startIndex {
|
||||
map[line[..<eq].trimmingCharacters(in: .whitespaces)] = line[line.index(after: eq)...].trimmingCharacters(in: .whitespaces)
|
||||
}
|
||||
}
|
||||
guard sawHeader, let name = map["NAME"], !name.isEmpty else { return nil }
|
||||
let d = Palette.amber
|
||||
func c(_ k: String, _ fb: UInt32) -> UInt32 {
|
||||
guard var h = map[k] else { return fb }
|
||||
if h.hasPrefix("#") { h.removeFirst() }
|
||||
guard h.count == 6, let v = UInt32(h, radix: 16) else { return fb }
|
||||
return v
|
||||
}
|
||||
return Palette(name: name, background: c("background", d.background), surface: c("surface", d.surface),
|
||||
grid: c("grid", d.grid), text: c("text", d.text), textDim: c("textDim", d.textDim),
|
||||
accent: c("accent", d.accent), beat: c("beat", d.beat), bar: c("bar", d.bar),
|
||||
playhead: c("playhead", d.playhead), danger: c("danger", d.danger))
|
||||
}
|
||||
}
|
||||
+7
-2
@@ -44,7 +44,7 @@ targets:
|
||||
SWIFT_OBJC_BRIDGING_HEADER: FX/Bridging.h
|
||||
# force_load: the effects are found through weak placeholder makers (Registry.cpp),
|
||||
# so without it the linker keeps the placeholders and skips the real ports.
|
||||
OTHER_LDFLAGS: ["-lc++", "-force_load", "$(BUILT_PRODUCTS_DIR)/libSizzleCore.a"]
|
||||
OTHER_LDFLAGS: ["-lc++", "-lz", "-force_load", "$(BUILT_PRODUCTS_DIR)/libSizzleCore.a"]
|
||||
Sizzle:
|
||||
type: application
|
||||
platform: iOS
|
||||
@@ -52,6 +52,10 @@ targets:
|
||||
path: Host/Info.plist
|
||||
properties:
|
||||
UIBackgroundModes: [audio]
|
||||
NSMicrophoneUsageDescription: Sizzle records the microphone or an audio interface's input into samples.
|
||||
# Documents (songs, samples, recordings, backups) shows in the Files app.
|
||||
UIFileSharingEnabled: true
|
||||
LSSupportsOpeningDocumentsInPlace: true
|
||||
# The app hosts the devices itself (in-process), so it compiles the plugin
|
||||
# classes and the editor too, and links the whole core.
|
||||
sources:
|
||||
@@ -72,6 +76,7 @@ targets:
|
||||
- sdk: AVFoundation.framework
|
||||
- sdk: CoreAudioKit.framework
|
||||
- sdk: CoreMIDI.framework
|
||||
- sdk: GameController.framework
|
||||
settings:
|
||||
base:
|
||||
PRODUCT_BUNDLE_IDENTIFIER: cc.tiredsysadmin.ios.sizzle
|
||||
@@ -85,5 +90,5 @@ targets:
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon
|
||||
SWIFT_OBJC_BRIDGING_HEADER: Host/Bridging.h
|
||||
USER_HEADER_SEARCH_PATHS: ["$(SRCROOT)/FX"]
|
||||
OTHER_LDFLAGS: ["-lc++", "-force_load", "$(BUILT_PRODUCTS_DIR)/libSizzleCore.a"]
|
||||
OTHER_LDFLAGS: ["-lc++", "-lz", "-force_load", "$(BUILT_PRODUCTS_DIR)/libSizzleCore.a"]
|
||||
|
||||
|
||||
@@ -7,3 +7,6 @@
|
||||
#import "SizzleSession+Setup.h"
|
||||
#import "SizzleSession+Sources.h"
|
||||
#import "SizzleSession+Viz.h"
|
||||
#import "SizzleSession+Record.h"
|
||||
#import "SizzleMidi.h"
|
||||
#import "SizzleSession+Files.h"
|
||||
|
||||
Reference in New Issue
Block a user