// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown // SPDX-License-Identifier: GPL-3.0-or-later import Combine import SwiftUI /// The Tracker tab's own UI state and edit operations: the parts of Android's /// AppViewModel the tab uses beyond what AppModel holds (cursor, keyboard /// channel/octave/velocity). One instance for the app's life, so selection, skip /// step, KBD mode and the clipboard survive tab switches as they do on Android. @MainActor final class TrackerState: ObservableObject { static let shared = TrackerState() // Selection & clipboard (Android: selectMode / selAnchor* / clipboard). @Published private(set) var selectMode = false @Published private(set) var selAnchorTrack = -1 @Published private(set) var selAnchorLine = -1 /// Copied cells, [trackOffset][lineOffset]. @Published private(set) var clipboard: [[SizzleCell]]? var canPaste: Bool { clipboard != nil } /// Rows the cursor jumps after a punch-in / note-off / delete (0, 1, 2, 4, 8). @Published var skipStep = 1 /// The lower half shows the punch-in keyboard instead of the arrangement. @Published var punchInMode = false // Arrangement selection: anchor (…0) and live corner (…1); beat < 0 = none. @Published private(set) var arrSelLane0 = -1 @Published private(set) var arrSelBeat0 = -1 @Published private(set) var arrSelLane1 = -1 @Published private(set) var arrSelBeat1 = -1 /// Tap-tempo timestamps. private var tapTimes: [TimeInterval] = [] private var session: SizzleSession { SizzleSession.shared } private var length: Int { max(1, session.length(ofPattern: session.activePattern)) } // MARK: selection ranges func hasSelection(_ app: AppModel) -> Bool { selectMode && selAnchorTrack >= 0 } func selTrackRange(_ app: AppModel) -> ClosedRange { hasSelection(app) ? min(selAnchorTrack, app.cursorTrack)...max(selAnchorTrack, app.cursorTrack) : app.cursorTrack...app.cursorTrack } func selLineRange(_ app: AppModel) -> ClosedRange { hasSelection(app) ? min(selAnchorLine, app.cursorLine)...max(selAnchorLine, app.cursorLine) : app.cursorLine...app.cursorLine } // MARK: cursor func focusCell(_ app: AppModel, track: Int, line: Int, column: AppModel.Column) { app.cursorTrack = min(max(track, 0), 3) app.cursorLine = min(max(line, 0), length - 1) app.cursorColumn = column } /// Move the cursor by [d] rows, wrapping at the pattern ends. func moveCursorWrap(_ app: AppModel, _ d: Int) { let len = length app.cursorLine = ((app.cursorLine + d) % len + len) % len } // MARK: edits (Android: punchNote / noteOffFocused / deleteAndAdvance / …) /// 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) } /// Insert a note-off ("===") at the cursor and advance by the skip step. func noteOffFocused(_ app: AppModel) { session.setCell(SizzleCell(note: -2, velocity: 127, channel: 1), inPattern: session.activePattern, track: app.cursorTrack, line: app.cursorLine) moveCursorWrap(app, skipStep) } /// DEL: clear the selection (or the focused cell) and advance by the skip step. func deleteAndAdvance(_ app: AppModel) { deleteSelection(app) moveCursorWrap(app, skipStep) } func toggleSelectMode(_ app: AppModel) { selectMode.toggle() if selectMode { selAnchorTrack = app.cursorTrack; selAnchorLine = app.cursorLine } else { selAnchorTrack = -1; selAnchorLine = -1 } } func copySelection(_ app: AppModel) { let p = session.activePattern let tr = selTrackRange(app), lr = selLineRange(app) clipboard = tr.map { t in lr.map { l in session.cell(inPattern: p, track: t, line: l) } } } func deleteSelection(_ app: AppModel) { let tr = selTrackRange(app), lr = selLineRange(app) session.clearCells(inPattern: session.activePattern, fromTrack: tr.lowerBound, toTrack: tr.upperBound, fromLine: lr.lowerBound, toLine: lr.upperBound) } func cutSelection(_ app: AppModel) { copySelection(app); deleteSelection(app) } /// Paste with the clipboard's top-left at the cursor, clipped to the grid. func pasteClipboard(_ app: AppModel) { guard let cb = clipboard, let h = cb.first?.count, h > 0 else { return } let flat = cb.flatMap { $0 } flat.withUnsafeBufferPointer { buf in session.writeCells(buf.baseAddress!, width: cb.count, height: h, inPattern: session.activePattern, track: app.cursorTrack, line: app.cursorLine) } } // MARK: song settings func setActiveBlock(_ app: AppModel, _ i: Int) { session.activePattern = min(max(i, 0), 7) app.cursorLine = min(max(app.cursorLine, 0), length - 1) } func setPatternLength(_ app: AppModel, _ len: Int) { session.setLength(len, ofPattern: session.activePattern) app.cursorLine = min(max(app.cursorLine, 0), len - 1) } func setSignature(_ app: AppModel, _ sig: Int) { session.setSignatureSnappingActivePattern(sig) app.cursorLine = min(max(app.cursorLine, 0), length - 1) } func setTempo(_ bpm: Float) { session.tempo = min(max(bpm, 20), 300) } /// Tap tempo: two or more taps in time set the tempo from the average interval; /// a pause over 2 s starts a fresh count; at most 8 taps are averaged. func tapTempo() { let now = Date().timeIntervalSinceReferenceDate if let last = tapTimes.last, now - last > 2 { tapTimes.removeAll() } tapTimes.append(now) while tapTimes.count > 8 { tapTimes.removeFirst() } if tapTimes.count >= 2, let first = tapTimes.first, let last = tapTimes.last, last > first { setTempo(Float(Double(tapTimes.count - 1) * 60 / (last - first))) } } // MARK: transport /// Play starts from the arrangement selection's first beat when there is one. func playPause() { if session.isPlaying { session.pause() } else if arrSelBeat0 >= 0 { session.play(fromBeat: min(arrSelBeat0, arrSelBeat1)) } else { session.play() } } /// Stop also clears the arrangement selection, so the next Play starts at the top. func stop() { clearArrangementSelection() session.stop() } // MARK: arrangement var hasArrSelection: Bool { arrSelBeat0 >= 0 } var arrLaneRange: ClosedRange { min(arrSelLane0, arrSelLane1)...max(arrSelLane0, arrSelLane1) } var arrBeatRange: ClosedRange { min(arrSelBeat0, arrSelBeat1)...max(arrSelBeat0, arrSelBeat1) } func setArrangementSelection(_ lane0: Int, _ beat0: Int, _ lane1: Int, _ beat1: Int) { if arrSelLane0 == lane0 && arrSelBeat0 == beat0 && arrSelLane1 == lane1 && arrSelBeat1 == beat1 { return } arrSelLane0 = lane0; arrSelBeat0 = beat0; arrSelLane1 = lane1; arrSelBeat1 = beat1 } func clearArrangementSelection() { setArrangementSelection(-1, -1, -1, -1) } /// Whether every selected slot passes [test] (FILL/CLEAR and OFF labels). func selectionAll(_ test: (Int32) -> Bool) -> Bool { guard hasArrSelection else { return false } for lane in arrLaneRange { for beat in arrBeatRange where !test(Int32(session.arrangementLane(lane, beat: beat))) { return false } } return true } /// FILL / CLEAR: a fully filled selection clears, anything else fills with each /// lane's own block. func toggleSelectedCells() { guard hasArrSelection else { return } let clear = selectionAll { $0 != -1 } session.fillArrangement(fromLane: arrLaneRange.lowerBound, toLane: arrLaneRange.upperBound, fromBeat: arrBeatRange.lowerBound, toBeat: arrBeatRange.upperBound, pattern: clear ? -1 : SizzleArrangementOwnLane) } /// OFF: a selection of only off markers clears, anything else becomes markers. func toggleSelectedOff() { guard hasArrSelection else { return } let clear = selectionAll { $0 == -2 } session.fillArrangement(fromLane: arrLaneRange.lowerBound, toLane: arrLaneRange.upperBound, fromBeat: arrBeatRange.lowerBound, toBeat: arrBeatRange.upperBound, pattern: clear ? -1 : -2) } func regionValid(_ r: Int) -> Bool { session.regionEnabled(r) && session.regionEnd(r) > session.regionStart(r) } /// A / B: a set region is removed; otherwise the selection's beats become it. func tapRegion(_ r: Int) { let reps = session.regionRepeats(r) if regionValid(r) { session.setRegion(r, enabled: false, start: 0, end: 0, repeats: reps) } else if hasArrSelection { session.setRegion(r, enabled: true, start: arrBeatRange.lowerBound, end: arrBeatRange.upperBound + 1, repeats: reps) } } func changeRegionRepeats(_ r: Int, _ delta: Int) { session.setRegion(r, enabled: session.regionEnabled(r), start: session.regionStart(r), end: session.regionEnd(r), repeats: max(1, session.regionRepeats(r) + delta)) } } /// The song revision and play state, deduplicated, so toolbars refresh on edits /// and play/stop but not on every playhead line (AppModel publishes those too). @MainActor final class TrackerMirror: ObservableObject { @Published private(set) var revision = 0 @Published private(set) var isPlaying = false private var subs: Set = [] init(_ app: AppModel) { revision = app.revision isPlaying = app.isPlaying app.$revision.removeDuplicates().sink { [weak self] in self?.revision = $0 }.store(in: &subs) app.$isPlaying.removeDuplicates().sink { [weak self] in self?.isPlaying = $0 }.store(in: &subs) } } /// Notes held on the punch-in keyboard (Android: heldNotes), lighting the keys. @MainActor final class TrackerHeldNotes: ObservableObject { static let shared = TrackerHeldNotes() @Published private(set) var counts: [Int: Int] = [:] /// Channel each sounding note went out on, so note-off matches it. private var channels: [Int: Int] = [:] func isHeld(_ midi: Int) -> Bool { (counts[midi] ?? 0) > 0 } func on(_ midi: Int, app: AppModel) { counts[midi, default: 0] += 1 channels[midi] = app.kbdChannel SizzleSession.shared.note(on: midi, velocity: min(max(app.kbdVelocity, 0), 127), midiChannel: app.kbdChannel) } func off(_ midi: Int, app: AppModel) { let n = (counts[midi] ?? 0) - 1 if n <= 0 { counts[midi] = nil } else { counts[midi] = n } SizzleSession.shared.noteOff(midi, midiChannel: channels[midi] ?? app.kbdChannel) } /// 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) } counts.removeAll() } } /// A one-axis scroll position with drag and fling (exponential decay), shared by /// the pattern grid (vertical) and the arrangement roll (horizontal). Plain /// SwiftUI: a 60 Hz timer stands in for a display link. @MainActor final class TrackerScroller: ObservableObject { @Published var offset: CGFloat = 0 private var timer: Timer? private var velocity: CGFloat = 0 private var maxOffset: CGFloat = 0 private var lastTick: TimeInterval = 0 private let tau: CGFloat = 0.325 var isFlinging: Bool { timer != nil } func stop() { timer?.invalidate(); timer = nil } /// Coast [distance] points (the gesture's predicted overshoot) in the scroll direction. func fling(distance: CGFloat, max: CGFloat) { stop() guard abs(distance) > 4 else { return } maxOffset = max velocity = distance / tau lastTick = Date().timeIntervalSinceReferenceDate let t = Timer(timeInterval: 1.0 / 60, repeats: true) { [weak self] _ in Task { @MainActor in self?.tick() } } RunLoop.main.add(t, forMode: .common) timer = t } private func tick() { let now = Date().timeIntervalSinceReferenceDate let dt = CGFloat(now - lastTick) lastTick = now let next = min(max(offset + velocity * dt, 0), maxOffset) velocity *= exp(-dt / tau) if next != offset { offset = next } if abs(velocity) < 12 || next <= 0 || next >= maxOffset { stop() } } }