// 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) } } } } }