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:
Reactorcoremeltdown
2026-11-16 14:26:01 +01:00
co-authored by Claude Opus 5.5
parent 435305e42a
commit 64e21e0bcc
54 changed files with 3303 additions and 97 deletions
+179
View File
@@ -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
+108
View File
@@ -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
}
}
+212
View File
@@ -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)
}
}
+210
View File
@@ -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)
}
}
}
}
}