iOS 0.4.0: Sizzle's Tracker, Mix, Toolbox and Setup tabs on the C++ engine

Ported from the Android tabs by parallel agents (each screen with its own
SizzleSession category); slot editors use the card editor with a preset
library; songs load/save in the Android project format.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-16 09:32:30 +01:00
co-authored by Claude Opus 5.5
parent 29650b88d7
commit 962cfd1e2b
35 changed files with 4088 additions and 66 deletions
@@ -0,0 +1,331 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// The arrangement's slots, copied once per song revision for drawing.
final class TrackerArrangementCache {
private(set) var beats = 1
private(set) var slots: [Int32] = []
private var revision: UInt = .max
func refresh() {
let s = SizzleSession.shared
if s.revision == revision { return }
revision = s.revision
beats = max(1, s.arrangementCanvasBeats)
if slots.count != 8 * beats { slots = Array(repeating: -1, count: 8 * beats) }
slots.withUnsafeMutableBufferPointer { $0.baseAddress!.withMemoryRebound(to: Int32.self, capacity: $0.count) { p in
s.copyArrangementSlots(p, beats: beats)
} }
}
func slot(_ lane: Int, _ beat: Int) -> Int32 { beat >= 0 && beat < beats ? slots[lane * beats + beat] : -1 }
}
/// The lower half of the tracker (Android's ArrangementRoll.kt): a fixed column of
/// lane mutes and block numbers, a bar ruler with the A/B loop regions, and the
/// 8-lane roll (lane i plays block i), drawn as one Canvas, over the loop toolbar.
///
/// Cells aren't toggled by tapping: tap selects one cell, long-press then drag
/// sweeps a rectangle (dragging into a viewport edge scrolls the roll under the
/// finger), and the FILL/CLEAR, OFF and A/B buttons act on the selection. Tap a
/// block number to edit that block above; M mutes the lane.
struct ArrangementRollView: View {
let app: AppModel
@ObservedObject var state: TrackerState
@ObservedObject var mirror: TrackerMirror
@StateObject private var scroller = TrackerScroller()
var body: some View {
let _ = mirror.revision
VStack(spacing: 0) {
HStack(spacing: 0) {
laneColumn.frame(width: 102)
RollCanvas(app: app, state: state, scroller: scroller)
}
.frame(maxHeight: .infinity)
loopToolbar
}
.background(TK.background)
}
// MARK: lane column
private var laneColumn: some View {
let s = SizzleSession.shared
return VStack(spacing: 0) {
Text("BLK").font(Theme.mono(8)).foregroundColor(TK.dim)
.frame(maxWidth: .infinity).frame(height: RollCanvas.rulerH).background(TK.surface)
ForEach(0..<8, id: \.self) { lane in
let active = s.activePattern == lane
let muted = s.isLaneMuted(lane)
HStack(spacing: 0) {
Text("M").font(Theme.mono(9)).foregroundColor(muted ? TK.danger : TK.dim)
.frame(width: 51).frame(maxHeight: .infinity)
.background(muted ? TK.danger.opacity(0.30) : TK.surface)
.contentShape(Rectangle())
.onTapGesture { s.setLane(lane, muted: !muted) }
Text("\(lane + 1)").font(Theme.mono(11)).foregroundColor(active ? TK.accent : TK.dim)
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(active ? TK.accent.opacity(0.25) : TK.surface)
.contentShape(Rectangle())
.onTapGesture { state.setActiveBlock(app, lane) }
}
.frame(maxHeight: .infinity)
}
}
}
// MARK: loop toolbar
private var loopToolbar: some View {
let s = SizzleSession.shared
let has = state.hasArrSelection
return TKHScroll {
HStack(spacing: 6) {
TKButton(label: "LOOP", active: s.arrangementLoop) { s.arrangementLoop.toggle() }
TKButton(label: state.selectionAll({ $0 != -1 }) ? "CLEAR" : "FILL", active: has, width: 72) {
state.toggleSelectedCells()
}
// OFF keeps its label when it would clear (a marker is "filled" too,
// so FILL would also read CLEAR).
TKButton(label: "OFF", active: has, width: 72) { state.toggleSelectedOff() }
region(0, "A")
region(1, "B")
}
.padding(6)
}
.background(TK.surface)
}
private func region(_ r: Int, _ name: String) -> some View {
HStack(spacing: 0) {
TKButton(label: name, active: state.regionValid(r)) { state.tapRegion(r) }
TKRepeatButton(label: "-") { state.changeRegionRepeats(r, -1) }
Text(" x\(SizzleSession.shared.regionRepeats(r)) ").font(Theme.mono(11)).foregroundColor(TK.text)
TKRepeatButton(label: "+") { state.changeRegionRepeats(r, +1) }
}
}
}
/// The ruler and roll. Observes AppModel for the playhead beat; scrolls itself
/// (drag / fling), follows the playhead while playing and handles selection.
private struct RollCanvas: View {
@ObservedObject var app: AppModel
@ObservedObject var state: TrackerState
@ObservedObject var scroller: TrackerScroller
@State private var cache = TrackerArrangementCache()
@State private var touch = Touch()
static let rulerH: CGFloat = 18
static let beatW: CGFloat = 20
/// Edge-scroll zone and full speed (pt/s) while sweeping a selection.
private static let edgeZone: CGFloat = 56
private static let edgeSpeed: CGFloat = 1200
private static let longPress: TimeInterval = 0.5
/// One touch: undecided (tap), scrolling, or sweeping a selection.
final class Touch {
enum Mode { case idle, pending, scrolling, selecting }
var mode = Mode.idle
var haltsFling = false
var start: CGPoint = .zero
var startOffset: CGFloat = 0
var slopShift: CGFloat = 0
var lane0 = 0, beat0 = 0
var fingerVx: CGFloat = 0, fingerLane = 0
var longTimer: Timer?
var edgeTimer: Timer?
var lastTick: TimeInterval = 0
func cancelTimers() { longTimer?.invalidate(); longTimer = nil; edgeTimer?.invalidate(); edgeTimer = nil }
}
var body: some View {
GeometryReader { geo in
let size = geo.size
let _ = cache.refresh()
let maxScroll = max(0, CGFloat(cache.beats) * Self.beatW - size.width)
canvas(size: size, scroll: min(max(scroller.offset, 0), maxScroll))
.contentShape(Rectangle())
.gesture(gesture(size: size, maxScroll: maxScroll))
.onChange(of: app.currentBeat) { beat in follow(beat, width: size.width, maxScroll: maxScroll) }
}
.clipped()
}
/// Keep the playhead mid-view once it reaches the middle.
private func follow(_ beat: Int, width: CGFloat, maxScroll: CGFloat) {
guard app.isPlaying, touch.mode == .idle || touch.mode == .pending else { return }
scroller.stop()
scroller.offset = min(max(CGFloat(beat) * Self.beatW - width / 2, 0), maxScroll)
}
private func laneAt(_ y: CGFloat, height: CGFloat) -> Int {
let laneH = (height - Self.rulerH) / 8
return min(max(Int((y - Self.rulerH) / laneH), 0), 7)
}
private func beatAt(viewportX vx: CGFloat) -> Int {
min(max(Int((scroller.offset + vx) / Self.beatW), 0), cache.beats - 1)
}
private func applySelection() {
state.setArrangementSelection(touch.lane0, touch.beat0, touch.fingerLane, beatAt(viewportX: touch.fingerVx))
}
private func gesture(size: CGSize, maxScroll: CGFloat) -> some Gesture {
DragGesture(minimumDistance: 0)
.onChanged { g in
let t = touch
if t.mode == .idle {
t.mode = .pending
t.haltsFling = scroller.isFlinging
scroller.stop()
t.start = g.startLocation
t.fingerVx = g.location.x; t.fingerLane = laneAt(g.location.y, height: size.height)
let timer = Timer(timeInterval: Self.longPress, repeats: false) { _ in
Task { @MainActor in beginSelection(size: size, maxScroll: maxScroll) }
}
RunLoop.main.add(timer, forMode: .common)
t.longTimer = timer
}
t.fingerVx = g.location.x
t.fingerLane = laneAt(g.location.y, height: size.height)
switch t.mode {
case .pending:
if abs(g.translation.width) > 8 || abs(g.translation.height) > 8 {
t.cancelTimers()
t.mode = .scrolling
t.startOffset = scroller.offset
t.slopShift = g.translation.width
}
case .scrolling:
scroller.offset = min(max(t.startOffset - (g.translation.width - t.slopShift), 0), maxScroll)
case .selecting:
applySelection()
case .idle: break
}
}
.onEnded { g in
let t = touch
t.cancelTimers()
switch t.mode {
case .pending:
if !t.haltsFling && g.location.y >= Self.rulerH {
let lane = laneAt(g.location.y, height: size.height), beat = beatAt(viewportX: g.location.x)
state.setArrangementSelection(lane, beat, lane, beat)
}
case .scrolling:
scroller.fling(distance: -(g.predictedEndTranslation.width - g.translation.width), max: maxScroll)
default: break
}
t.mode = .idle
}
}
/// Long press held still: start sweeping a selection, with edge scrolling.
private func beginSelection(size: CGSize, maxScroll: CGFloat) {
let t = touch
guard t.mode == .pending else { return }
t.mode = .selecting
t.lane0 = laneAt(t.start.y, height: size.height)
t.beat0 = beatAt(viewportX: t.start.x)
applySelection()
t.lastTick = Date().timeIntervalSinceReferenceDate
let timer = Timer(timeInterval: 1.0 / 60, repeats: true) { _ in
Task { @MainActor in edgeTick(width: size.width, maxScroll: maxScroll) }
}
RunLoop.main.add(timer, forMode: .common)
t.edgeTimer = timer
}
private func edgeTick(width w: CGFloat, maxScroll: CGFloat) {
let t = touch
guard t.mode == .selecting else { return }
let now = Date().timeIntervalSinceReferenceDate
let dt = CGFloat(now - t.lastTick)
t.lastTick = now
let z = Self.edgeZone
var push: CGFloat = 0
if t.fingerVx > w - z { push = (t.fingerVx - (w - z)) / z }
else if t.fingerVx < z { push = -(z - t.fingerVx) / z }
push = min(max(push, -1), 1)
if push == 0 || dt <= 0 { return }
let next = min(max(scroller.offset + push * Self.edgeSpeed * dt, 0), maxScroll)
if next != scroller.offset { scroller.offset = next; applySelection() }
}
// MARK: drawing
private func canvas(size: CGSize, scroll: CGFloat) -> some View {
let s = SizzleSession.shared
let bpb = max(1, s.beatsPerBar)
let playing = app.isPlaying, playBeat = app.currentBeat
let hasSel = state.hasArrSelection
let laneR = hasSel ? state.arrLaneRange : 0...0
let beatR = hasSel ? state.arrBeatRange : 0...0
let regions = (0..<2).map { r in (valid: state.regionValid(r), start: s.regionStart(r), end: s.regionEnd(r)) }
let cache = self.cache
let beatW = Self.beatW, rulerH = Self.rulerH
return Canvas { ctx, size in
let w = size.width, h = size.height
let laneH = (h - rulerH) / 8
let first = min(max(Int(scroll / beatW), 0), max(cache.beats - 1, 0))
let last = min(max(Int((scroll + w) / beatW) + 2, 1), cache.beats)
func x(_ beat: Int) -> CGFloat { CGFloat(beat) * beatW - scroll }
func label(_ str: String, _ color: Color) -> GraphicsContext.ResolvedText {
ctx.resolve(Text(str).font(Theme.mono(9)).foregroundColor(color))
}
// Ruler + bar ticks/numbers.
ctx.fill(Path(CGRect(x: 0, y: 0, width: w, height: rulerH)), with: .color(TK.surface))
for beat in first..<last where beat % bpb == 0 {
ctx.fill(Path(CGRect(x: x(beat), y: 0, width: 1, height: h)), with: .color(TK.grid))
ctx.draw(label("\(beat / bpb + 1)", TK.dim), at: CGPoint(x: x(beat) + 2, y: rulerH / 2), anchor: .leading)
}
// A / B loop-region bands.
for (r, color, letter) in [(0, TK.accent, "A"), (1, TK.playhead, "B")] {
let g = regions[r]
guard g.valid else { continue }
let x0 = x(g.start), x1 = x(g.end)
ctx.fill(Path(CGRect(x: x0, y: 0, width: x1 - x0, height: rulerH)), with: .color(color.opacity(0.25)))
ctx.fill(Path(CGRect(x: x0, y: 0, width: x1 - x0, height: 2)), with: .color(color))
var lx = x0 + 2
if g.start % bpb == 0 { lx += label("\(g.start / bpb + 1)", TK.dim).measure(in: size).width + 3 }
ctx.draw(label(letter, color), at: CGPoint(x: lx, y: rulerH / 2), anchor: .leading)
}
// Lane cells.
for lane in 0..<8 {
let ly = rulerH + CGFloat(lane) * laneH
for beat in first..<last {
let slot = cache.slot(lane, beat)
let fill: Color
if slot == -2 { fill = TK.danger.opacity(0.85) }
else if slot != -1 { fill = TK.accent.opacity(0.85) }
else if playing && beat == playBeat { fill = TK.playhead.opacity(0.3) }
else if hasSel && laneR.contains(lane) && beatR.contains(beat) { fill = TK.bar }
else if beat % bpb == 0 { fill = TK.surface }
else { fill = TK.grid.opacity(0.35) }
ctx.fill(Path(CGRect(x: x(beat) + 0.5, y: ly + 0.5, width: beatW - 1, height: laneH - 1)), with: .color(fill))
}
ctx.fill(Path(CGRect(x: 0, y: ly, width: w, height: 1)), with: .color(TK.background))
}
// Selection outline.
if hasSel {
let r = CGRect(x: x(beatR.lowerBound), y: rulerH + CGFloat(laneR.lowerBound) * laneH,
width: CGFloat(beatR.count) * beatW, height: CGFloat(laneR.count) * laneH)
ctx.stroke(Path(r), with: .color(TK.accent), lineWidth: 2)
}
// Playhead.
if playing {
ctx.fill(Path(CGRect(x: x(playBeat) - 1, y: 0, width: 2, height: h)), with: .color(TK.playhead))
}
}
.frame(width: size.width, height: size.height)
}
}
@@ -0,0 +1,211 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// The active pattern's cells, copied from the song once per song revision so the
/// grid draws from memory instead of taking the song lock per cell.
final class TrackerPatternCache {
private(set) var pattern = -1
private(set) var length = 0
private(set) var cells: [SizzleCell] = []
private var revision: UInt = .max
func refresh() {
let s = SizzleSession.shared
let rev = s.revision, p = s.activePattern
if rev == revision && p == pattern { return }
revision = rev; pattern = p
let len = s.length(ofPattern: p)
if cells.count < 4 * len { cells = Array(repeating: SizzleCell(note: -1, velocity: 127, channel: 0), count: 4 * len) }
length = cells.withUnsafeMutableBufferPointer { s.copyCells(ofPattern: p, into: $0.baseAddress!, capacity: $0.count) }
}
func cell(_ track: Int, _ line: Int) -> SizzleCell { cells[track * length + line] }
}
/// The demoscene pattern grid (Android's PatternGrid.kt): 4 tracks × the pattern's
/// lines, each cell NOTE / VEL / CH, drawn as one Canvas. Beat and bar rows are
/// tinted, odd tracks shaded, the cursor cell and playhead row highlighted.
///
/// Touch: tap moves the cursor to the cell and column; a drag or flick scrolls and
/// never selects; a touch that lands on a still-coasting grid only stops it. While
/// playing the view centres on the playhead until a scroll detaches it; switching
/// block re-attaches. A cursor that moves off screen is scrolled back into view.
struct PatternGridView: View {
@ObservedObject var app: AppModel
@ObservedObject var state: TrackerState
@StateObject private var scroller = TrackerScroller()
@State private var cache = TrackerPatternCache()
@State private var drag = DragTrack()
@State private var following = true
@State private var followPattern = -1
private let rowH: CGFloat = 20
private let gutter: CGFloat = 30
final class DragTrack {
var active = false
var isTap = true
var haltsFling = false
var startOffset: CGFloat = 0
var slopShift: CGFloat = 0
}
var body: some View {
GeometryReader { geo in
let size = geo.size
let _ = cache.refresh()
let maxScroll = max(0, CGFloat(cache.length) * rowH - size.height)
let scroll = effectiveScroll(height: size.height, maxScroll: maxScroll)
canvas(size: size, scroll: scroll)
.contentShape(Rectangle())
.gesture(gesture(size: size, maxScroll: maxScroll))
.onChange(of: app.cursorLine) { line in revealCursor(line, height: size.height, maxScroll: maxScroll) }
.onChange(of: cache.pattern) { _ in following = true; scroller.stop(); scroller.offset = 0 }
}
.background(TK.background)
.clipped()
}
// MARK: scrolling
private func playheadScroll(_ line: Int, height: CGFloat, maxScroll: CGFloat) -> CGFloat {
min(max(CGFloat(line) * rowH + rowH / 2 - height / 2, 0), maxScroll)
}
private func effectiveScroll(height: CGFloat, maxScroll: CGFloat) -> CGFloat {
if app.isPlaying && following { return playheadScroll(app.currentLine, height: height, maxScroll: maxScroll) }
return min(max(scroller.offset, 0), maxScroll)
}
/// Minimal scroll that brings the cursor row into view (never re-centres, so a
/// tapped row stays under the finger).
private func revealCursor(_ line: Int, height: CGFloat, maxScroll: CGFloat) {
let top = CGFloat(line) * rowH
let lo = min(max(top + rowH - height, 0), maxScroll)
let hi = min(max(top, lo), maxScroll)
let eff = effectiveScroll(height: height, maxScroll: maxScroll)
let next = min(max(eff, lo), hi)
if next != scroller.offset { scroller.offset = next }
}
private func gesture(size: CGSize, maxScroll: CGFloat) -> some Gesture {
DragGesture(minimumDistance: 0)
.onChanged { g in
if !drag.active {
drag.active = true
drag.isTap = true
drag.haltsFling = scroller.isFlinging
scroller.stop()
}
let dy = g.translation.height
if drag.isTap && (abs(dy) > 8 || abs(g.translation.width) > 8) {
drag.isTap = false
drag.startOffset = effectiveScroll(height: size.height, maxScroll: maxScroll)
drag.slopShift = dy
following = false
}
if !drag.isTap {
scroller.offset = min(max(drag.startOffset - (dy - drag.slopShift), 0), maxScroll)
}
}
.onEnded { g in
defer { drag.active = false }
if drag.isTap {
if !drag.haltsFling { tap(g.location, size: size, maxScroll: maxScroll) }
} else {
scroller.fling(distance: -(g.predictedEndTranslation.height - g.translation.height), max: maxScroll)
}
}
}
private func tap(_ p: CGPoint, size: CGSize, maxScroll: CGFloat) {
guard p.x >= gutter, cache.length > 0 else { return }
let scroll = effectiveScroll(height: size.height, maxScroll: maxScroll)
let line = min(max(Int((scroll + p.y) / rowH), 0), cache.length - 1)
let trackW = (size.width - gutter) / 4
let tx = p.x - gutter
let track = min(max(Int(tx / trackW), 0), 3)
let within = tx - CGFloat(track) * trackW
let col: AppModel.Column = within < trackW * 0.5 ? .note : (within < trackW * 0.75 ? .velocity : .channel)
state.focusCell(app, track: track, line: line, column: col)
}
// MARK: drawing
private func canvas(size: CGSize, scroll: CGFloat) -> some View {
let s = SizzleSession.shared
let lpb = max(1, s.linesPerBeat), lpBar = max(1, s.linesPerBeat * s.beatsPerBar)
let playing = app.isPlaying, playLine = app.currentLine
let cTrack = app.cursorTrack, cLine = app.cursorLine, cCol = app.cursorColumn
let sel = state.hasSelection(app)
let selT = state.selTrackRange(app), selL = state.selLineRange(app)
let cache = self.cache
let rowH = self.rowH, gutter = self.gutter
return Canvas { ctx, size in
let w = size.width, h = size.height
let trackW = (w - gutter) / 4
let noteW = trackW * 0.5, velW = trackW * 0.25
var texts: [String: GraphicsContext.ResolvedText] = [:]
func draw(_ str: String, _ color: Color, _ fs: CGFloat, x: CGFloat, y: CGFloat) {
let key = "\(fs)|\(color == TK.text ? 0 : color == TK.accent ? 1 : 2)|" + str
let r: GraphicsContext.ResolvedText
if let c = texts[key] { r = c } else {
r = ctx.resolve(Text(str).font(Theme.mono(fs)).foregroundColor(color)); texts[key] = r
}
ctx.draw(r, at: CGPoint(x: x, y: y + rowH / 2), anchor: .leading)
}
// 1) Alternating track tints + separators.
for t in 0..<4 {
let x0 = gutter + CGFloat(t) * trackW
if t % 2 == 1 { ctx.fill(Path(CGRect(x: x0, y: 0, width: trackW, height: h)), with: .color(TK.grid.opacity(0.35))) }
ctx.fill(Path(CGRect(x: x0, y: 0, width: 1, height: h)), with: .color(TK.grid))
}
// 2) Rows.
let first = Int(scroll / rowH)
let yShift = -(scroll - CGFloat(first) * rowH)
let visible = Int(h / rowH) + 1
for screen in 0...visible {
let line = first + screen
if line >= cache.length { break }
if line < 0 { continue }
let y = yShift + CGFloat(screen) * rowH
let rowColor: Color? = playing && line == playLine ? TK.playhead.opacity(0.22)
: line % lpBar == 0 ? TK.bar.opacity(0.7)
: line % lpb == 0 ? TK.beat.opacity(0.7) : nil
if let rc = rowColor { ctx.fill(Path(CGRect(x: 0, y: y, width: w, height: rowH)), with: .color(rc)) }
draw(line < 256 ? TK.hex2[line] : String(format: "%02X", line), TK.dim, 11, x: 2, y: y)
for t in 0..<4 {
let cell = cache.cell(t, line)
let bx = gutter + CGFloat(t) * trackW
if sel && selT.contains(t) && selL.contains(line) {
ctx.fill(Path(CGRect(x: bx, y: y, width: trackW, height: rowH)), with: .color(TK.accent.opacity(0.18)))
}
if cTrack == t && cLine == line {
let r: CGRect
switch cCol {
case .note: r = CGRect(x: bx, y: y, width: noteW, height: rowH)
case .velocity: r = CGRect(x: bx + noteW, y: y, width: velW, height: rowH)
case .channel: r = CGRect(x: bx + noteW + velW, y: y, width: velW, height: rowH)
}
ctx.fill(Path(r), with: .color(TK.accent.opacity(0.30)))
}
let note = Int(cell.note)
let empty = note == -1, off = note == -2
draw(empty ? "···" : off ? "===" : TK.noteName(note), TK.text, 12, x: bx + 2, y: y)
let vel = Int(cell.velocity), ch = Int(cell.channel)
draw(empty || off ? ".." : (vel < 256 ? TK.hex2[vel] : "\(vel)"), empty ? TK.dim : TK.accent, 12,
x: bx + noteW + 2, y: y)
draw(empty || off ? ".." : (ch < 100 ? TK.chan2[ch] : "\(ch)"), TK.dim, 12,
x: bx + noteW + velW + 2, y: y)
}
}
}
.frame(width: size.width, height: size.height)
}
}
@@ -0,0 +1,185 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// The tracker's punch-in keyboard (Android's StackedKeyboard with punchIn = true):
/// a CH / OCT / VEL row over two stacked octaves (the upper one on top). A key
/// sounds on the keyboard's channel; its initial press also writes the note into
/// the cursor cell and advances the cursor by the skip step. Sliding across keys
/// glides (each key sounds, none is recorded). Out-of-scale keys are dimmed and
/// silent, unless the channel plays a Sampler (every pad must stay reachable).
struct PunchKeyboard: View {
@ObservedObject var app: AppModel
let state: TrackerState
@ObservedObject var mirror: TrackerMirror
@ObservedObject private var held = TrackerHeldNotes.shared
private static let velStep = 8
var body: some View {
let _ = mirror.revision
let inKey = inKeyPitchClasses()
VStack(spacing: 4) {
TKHScroll {
HStack(spacing: 6) {
selector("CH", app.kbdChannel == 0 ? "--" : "\(app.kbdChannel)",
{ app.kbdChannel = max(0, app.kbdChannel - 1) }, { app.kbdChannel = min(16, app.kbdChannel + 1) })
selector("OCT", "\(app.kbdOctave)–\(app.kbdOctave + 1)",
{ app.kbdOctave = max(0, app.kbdOctave - 1) }, { app.kbdOctave = min(8, app.kbdOctave + 1) })
selector("VEL", String(format: "%02X", app.kbdVelocity),
{ app.kbdVelocity = max(0, app.kbdVelocity - Self.velStep) },
{ app.kbdVelocity = min(127, app.kbdVelocity + Self.velStep) })
}
}
.fixedSize(horizontal: false, vertical: true)
octave(start: (app.kbdOctave + 2) * 12, inKey: inKey)
octave(start: (app.kbdOctave + 1) * 12, inKey: inKey)
}
.padding(6)
.background(TK.background)
.onDisappear { held.releaseAll() }
}
@ViewBuilder
private func selector(_ label: String, _ value: String, _ dec: @escaping () -> Void, _ inc: @escaping () -> Void) -> some View {
Text(label).font(Theme.mono(11)).foregroundColor(TK.dim)
TKRepeatButton(label: "-", onStep: dec)
Text(value).font(Theme.mono(13)).foregroundColor(TK.accent).frame(width: 40)
TKRepeatButton(label: "+", onStep: inc)
}
private func inKeyPitchClasses() -> Set<Int> {
let s = SizzleSession.shared
for ch in 0..<4 where s.midiChannel(ofChannel: ch) == app.kbdChannel {
let slot = s.instrumentSlot(ofChannel: ch)
if slot >= 0 && s.type(ofSlot: slot) == "SAMPLER" { return Set(0..<12) }
}
return Set(s.scalePitchClasses.map { $0.intValue })
}
private func octave(start: Int, inKey: Set<Int>) -> some View {
let app = self.app, state = self.state, held = self.held
func midi(_ pc: Int) -> Int { min(max(start + pc, 0), 127) }
return TrackerPianoOctave(
label: { pc in TK.noteName(midi(pc)).replacingOccurrences(of: "-", with: "") },
enabled: { inKey.contains($0) },
pressed: { held.isHeld(midi($0)) },
onNoteOn: { pc, slid in
let n = midi(pc)
if !slid { state.punchNote(app, n) }
held.on(n, app: app)
},
onNoteOff: { pc in held.off(midi(pc), app: app) })
}
}
/// One octave as a piano (Android's PianoOctave): seven white keys with the five
/// black keys over them. Each finger is tracked by the key it went down on and
/// hit-tested against the whole octave as it moves, so a slide retriggers on each
/// key it crosses and several fingers play chords.
struct TrackerPianoOctave: View {
let label: (Int) -> String
let enabled: (Int) -> Bool
let pressed: (Int) -> Bool
let onNoteOn: (Int, Bool) -> Void
let onNoteOff: (Int) -> Void
private static let whites = [0, 2, 4, 5, 7, 9, 11]
private static let blacks: [(pc: Int, after: Int)] = [(1, 0), (3, 1), (6, 3), (8, 4), (10, 5)]
private static let blackW: CGFloat = 0.62, blackH: CGFloat = 0.62
var body: some View {
GeometryReader { geo in
let size = geo.size
let whiteW = size.width / 7
ZStack(alignment: .topLeading) {
HStack(spacing: 0) {
ForEach(Self.whites, id: \.self) { pc in key(pc, black: false, size: size).frame(width: whiteW, height: size.height) }
}
ForEach(Self.blacks, id: \.pc) { b in
key(b.pc, black: true, size: size)
.frame(width: whiteW * Self.blackW, height: size.height * Self.blackH)
.padding(.leading, whiteW * CGFloat(b.after + 1) - whiteW * Self.blackW / 2)
}
}
.coordinateSpace(name: "tk-octave")
}
}
private func key(_ pc: Int, black: Bool, size: CGSize) -> some View {
PianoKeyView(label: label(pc), black: black, enabled: enabled(pc), lit: pressed(pc),
hit: { p in hit(p, size: size) }, onNoteOn: onNoteOn, onNoteOff: onNoteOff)
}
/// Pitch class under a point in octave coordinates, or -1 (off the keyboard or
/// on a disabled key). Black keys win in their upper region.
private func hit(_ p: CGPoint, size: CGSize) -> Int {
let w = size.width, h = size.height
guard w > 0, h > 0, p.x >= 0, p.x < w, p.y >= 0, p.y < h else { return -1 }
let whiteW = w / 7
var pc = Self.whites[min(max(Int(p.x / whiteW), 0), 6)]
if p.y <= h * Self.blackH {
let bw = whiteW * Self.blackW
for b in Self.blacks {
let bx = whiteW * CGFloat(b.after + 1) - bw / 2
if p.x >= bx && p.x <= bx + bw { pc = b.pc; break }
}
}
return enabled(pc) ? pc : -1
}
}
/// A key face (Android's PianoKey) that owns the gesture of the finger that went
/// down on it; [hit] maps the finger's position in the octave to a pitch class.
private struct PianoKeyView: View {
let label: String
let black: Bool
let enabled: Bool
let lit: Bool
let hit: (CGPoint) -> Int
let onNoteOn: (Int, Bool) -> Void
let onNoteOff: (Int) -> Void
@State private var finger = Finger()
final class Finger { var current: Int? }
private static let white = Color(white: 0xE8 / 255), whiteOff = Color(white: 0x5A / 255)
private static let blackOn = Color(red: 0x18 / 255, green: 0x18 / 255, blue: 0x20 / 255)
private static let blackOff = Color(red: 0x0C / 255, green: 0x0C / 255, blue: 0x10 / 255)
var body: some View {
face
.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 0, coordinateSpace: .named("tk-octave"))
.onChanged { g in
let pc = hit(g.location)
if let prev = finger.current {
if pc != prev {
if prev >= 0 { onNoteOff(prev) }
if pc >= 0 { onNoteOn(pc, true) }
finger.current = pc
}
} else {
finger.current = pc
if pc >= 0 { onNoteOn(pc, false) }
}
}
.onEnded { _ in
if let prev = finger.current, prev >= 0 { onNoteOff(prev) }
finger.current = nil
})
}
private var face: some View {
let bg: Color = lit ? TK.accent : black ? (enabled ? Self.blackOn : Self.blackOff) : (enabled ? Self.white : Self.whiteOff)
let fg: Color = lit ? TK.background
: black ? (enabled ? Color(white: 0xDD / 255) : Color(white: 0x55 / 255))
: (enabled ? Color(white: 0x14 / 255) : Color(white: 0x6A / 255))
return ZStack(alignment: .bottom) {
bg
Text(label).font(Theme.mono(12)).foregroundColor(fg).lineLimit(1).fixedSize().padding(.bottom, 3)
}
.overlay(Rectangle().stroke(lit ? TK.accent : Color.black, lineWidth: 1))
}
}
@@ -0,0 +1,148 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// The first tab (Android's TrackerScreen.kt): the transport toolbar and pattern
/// grid over the arrangement roll (or the punch-in keyboard) in portrait, 1.7 : 1;
/// in landscape the toolbar runs across the top and the grid sits beside the
/// lower half (1.4 : 1, or 1 : 1.3 with the keyboard, which needs the width).
struct TrackerScreen: View {
@EnvironmentObject var app: AppModel
// TrackerBody only stores references, so the playhead lines AppModel publishes
// re-run this body but not TrackerBody's: only the grid and roll redraw.
var body: some View { TrackerBody(app: app, state: TrackerState.shared) }
}
private struct TrackerBody: View {
let app: AppModel
@ObservedObject var state: TrackerState
@StateObject private var mirror: TrackerMirror
init(app: AppModel, state: TrackerState) {
self.app = app
self.state = state
_mirror = StateObject(wrappedValue: TrackerMirror(app))
}
var body: some View {
GeometryReader { geo in
let landscape = geo.size.width > geo.size.height
if landscape { self.landscape(geo.size) } else { portrait(geo.size) }
}
.background(TK.background)
}
private func portrait(_ size: CGSize) -> some View {
let upper = (size.height - 2) * 1.7 / 2.7
return VStack(spacing: 0) {
VStack(spacing: 0) {
TransportToolbar(app: app, state: state, mirror: mirror, landscape: false)
PatternGridView(app: app, state: state)
}
.frame(height: upper)
TK.accent.frame(height: 2)
lower.frame(maxHeight: .infinity)
}
}
private func landscape(_ size: CGSize) -> some View {
let gridWeight: CGFloat = state.punchInMode ? 1 : 1.4
let lowerWeight: CGFloat = state.punchInMode ? 1.3 : 1
let gridW = (size.width - 2) * gridWeight / (gridWeight + lowerWeight)
return VStack(spacing: 0) {
TransportToolbar(app: app, state: state, mirror: mirror, landscape: true)
TK.accent.frame(height: 2)
HStack(spacing: 0) {
PatternGridView(app: app, state: state).frame(width: gridW)
TK.accent.frame(width: 2)
lower.frame(maxWidth: .infinity)
}
.frame(maxHeight: .infinity)
}
}
@ViewBuilder private var lower: some View {
if state.punchInMode {
PunchKeyboard(app: app, state: state, mirror: mirror)
} else {
ArrangementRollView(app: app, state: state, mirror: mirror)
}
}
}
/// Transport, pattern and edit controls: three justified rows in portrait, two in
/// landscape (pattern and edit groups share a row).
private struct TransportToolbar: View {
let app: AppModel
@ObservedObject var state: TrackerState
@ObservedObject var mirror: TrackerMirror
let landscape: Bool
var body: some View {
let _ = mirror.revision
VStack(spacing: 6) {
TKJustifiedRow(items: transportItems)
if landscape {
TKJustifiedRow(items: patternItems + editItems)
} else {
TKJustifiedRow(items: patternItems)
TKJustifiedRow(items: editItems)
}
}
.padding(6)
.background(TK.surface)
}
/// STOP, PLAY/PAUSE, tempo (-, readout = tap tempo, +), signature.
private var transportItems: [AnyView] {
let s = SizzleSession.shared
let playing = mirror.isPlaying
return [
AnyView(TKButton(label: "⧉ STOP") { state.stop() }),
AnyView(TKButton(label: playing ? "❚❚ PAUSE" : "▶ PLAY", active: playing, width: 112) { state.playPause() }),
AnyView(HStack(spacing: 0) {
TKRepeatButton(label: "-") { state.setTempo(SizzleSession.shared.tempo - 1) }
Text("\(Int(s.tempo)) BPM").font(Theme.mono(12)).foregroundColor(TK.text).lineLimit(1)
.frame(width: 72).padding(.vertical, 6)
.contentShape(Rectangle())
.onTapGesture { state.tapTempo() }
TKRepeatButton(label: "+") { state.setTempo(SizzleSession.shared.tempo + 1) }
}),
AnyView(TKDropdown("SIG", options: Array(SizzleSession.signatureLabels.indices), selected: s.signature,
optionLabel: { SizzleSession.signatureLabels[$0] }) { state.setSignature(app, $0) }),
]
}
/// Active block, pattern length, scale, root.
private var patternItems: [AnyView] {
let s = SizzleSession.shared
let length = s.length(ofPattern: s.activePattern)
let lengths = s.lengthOptions.map { $0.intValue }
let names = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
return [
AnyView(TKDropdown("BLK", options: Array(0..<8), selected: s.activePattern,
optionLabel: { "\($0 + 1)" }) { state.setActiveBlock(app, $0) }),
AnyView(TKDropdown("LEN", options: lengths.contains(length) ? lengths : lengths + [length],
selected: length) { state.setPatternLength(app, $0) }),
AnyView(TKDropdown("SCALE", options: Array(SizzleSession.scaleLabels.indices), selected: s.scale,
optionLabel: { SizzleSession.scaleLabels[$0] }) { SizzleSession.shared.scale = $0 }),
AnyView(TKDropdown("ROOT", options: Array(0..<12), selected: s.rootNote,
optionLabel: { names[$0] }) { SizzleSession.shared.rootNote = $0 }),
]
}
/// SEL, cut ✂, copy ⧉, paste ▤, delete ✕, note-off, skip step, KBD.
private var editItems: [AnyView] {
[
AnyView(TKButton(label: "SEL", active: state.selectMode) { state.toggleSelectMode(app) }),
AnyView(TKButton(label: "✂") { state.cutSelection(app) }),
AnyView(TKButton(label: "⧉") { state.copySelection(app) }),
AnyView(TKButton(label: "▤", active: state.canPaste) { state.pasteClipboard(app) }),
AnyView(TKButton(label: "✕") { state.deleteAndAdvance(app) }),
AnyView(TKButton(label: "OFF ===") { state.noteOffFocused(app) }),
AnyView(TKDropdown("SKIP", options: [0, 1, 2, 4, 8], selected: state.skipStep) { state.skipStep = $0 }),
AnyView(TKButton(label: "⌨ KBD", active: state.punchInMode) { state.punchInMode.toggle() }),
]
}
}
@@ -0,0 +1,303 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import Combine
import SwiftUI
/// The Tracker tab's own UI state and edit operations: the parts of Android's
/// AppViewModel the tab uses beyond what AppModel holds (cursor, keyboard
/// channel/octave/velocity). One instance for the app's life, so selection, skip
/// step, KBD mode and the clipboard survive tab switches as they do on Android.
@MainActor
final class TrackerState: ObservableObject {
static let shared = TrackerState()
// Selection & clipboard (Android: selectMode / selAnchor* / clipboard).
@Published private(set) var selectMode = false
@Published private(set) var selAnchorTrack = -1
@Published private(set) var selAnchorLine = -1
/// Copied cells, [trackOffset][lineOffset].
@Published private(set) var clipboard: [[SizzleCell]]?
var canPaste: Bool { clipboard != nil }
/// Rows the cursor jumps after a punch-in / note-off / delete (0, 1, 2, 4, 8).
@Published var skipStep = 1
/// The lower half shows the punch-in keyboard instead of the arrangement.
@Published var punchInMode = false
// Arrangement selection: anchor (…0) and live corner (…1); beat < 0 = none.
@Published private(set) var arrSelLane0 = -1
@Published private(set) var arrSelBeat0 = -1
@Published private(set) var arrSelLane1 = -1
@Published private(set) var arrSelBeat1 = -1
/// Tap-tempo timestamps.
private var tapTimes: [TimeInterval] = []
private var session: SizzleSession { SizzleSession.shared }
private var length: Int { max(1, session.length(ofPattern: session.activePattern)) }
// MARK: selection ranges
func hasSelection(_ app: AppModel) -> Bool { selectMode && selAnchorTrack >= 0 }
func selTrackRange(_ app: AppModel) -> ClosedRange<Int> {
hasSelection(app) ? min(selAnchorTrack, app.cursorTrack)...max(selAnchorTrack, app.cursorTrack) : app.cursorTrack...app.cursorTrack
}
func selLineRange(_ app: AppModel) -> ClosedRange<Int> {
hasSelection(app) ? min(selAnchorLine, app.cursorLine)...max(selAnchorLine, app.cursorLine) : app.cursorLine...app.cursorLine
}
// MARK: cursor
func focusCell(_ app: AppModel, track: Int, line: Int, column: AppModel.Column) {
app.cursorTrack = min(max(track, 0), 3)
app.cursorLine = min(max(line, 0), length - 1)
app.cursorColumn = column
}
/// Move the cursor by [d] rows, wrapping at the pattern ends.
func moveCursorWrap(_ app: AppModel, _ d: Int) {
let len = length
app.cursorLine = ((app.cursorLine + d) % len + len) % len
}
// MARK: edits (Android: punchNote / noteOffFocused / deleteAndAdvance / …)
func punchNote(_ app: AppModel, _ midi: Int) {
let cell = SizzleCell(note: Int32(min(max(midi, 0), 127)), velocity: Int32(min(max(app.kbdVelocity, 0), 127)),
channel: Int32(app.kbdChannel))
session.setCell(cell, inPattern: session.activePattern, track: app.cursorTrack, line: app.cursorLine)
moveCursorWrap(app, skipStep)
}
/// Insert a note-off ("===") at the cursor and advance by the skip step.
func noteOffFocused(_ app: AppModel) {
session.setCell(SizzleCell(note: -2, velocity: 127, channel: 1), inPattern: session.activePattern,
track: app.cursorTrack, line: app.cursorLine)
moveCursorWrap(app, skipStep)
}
/// DEL: clear the selection (or the focused cell) and advance by the skip step.
func deleteAndAdvance(_ app: AppModel) {
deleteSelection(app)
moveCursorWrap(app, skipStep)
}
func toggleSelectMode(_ app: AppModel) {
selectMode.toggle()
if selectMode { selAnchorTrack = app.cursorTrack; selAnchorLine = app.cursorLine }
else { selAnchorTrack = -1; selAnchorLine = -1 }
}
func copySelection(_ app: AppModel) {
let p = session.activePattern
let tr = selTrackRange(app), lr = selLineRange(app)
clipboard = tr.map { t in lr.map { l in session.cell(inPattern: p, track: t, line: l) } }
}
func deleteSelection(_ app: AppModel) {
let tr = selTrackRange(app), lr = selLineRange(app)
session.clearCells(inPattern: session.activePattern, fromTrack: tr.lowerBound, toTrack: tr.upperBound,
fromLine: lr.lowerBound, toLine: lr.upperBound)
}
func cutSelection(_ app: AppModel) { copySelection(app); deleteSelection(app) }
/// Paste with the clipboard's top-left at the cursor, clipped to the grid.
func pasteClipboard(_ app: AppModel) {
guard let cb = clipboard, let h = cb.first?.count, h > 0 else { return }
let flat = cb.flatMap { $0 }
flat.withUnsafeBufferPointer { buf in
session.writeCells(buf.baseAddress!, width: cb.count, height: h, inPattern: session.activePattern,
track: app.cursorTrack, line: app.cursorLine)
}
}
// MARK: song settings
func setActiveBlock(_ app: AppModel, _ i: Int) {
session.activePattern = min(max(i, 0), 7)
app.cursorLine = min(max(app.cursorLine, 0), length - 1)
}
func setPatternLength(_ app: AppModel, _ len: Int) {
session.setLength(len, ofPattern: session.activePattern)
app.cursorLine = min(max(app.cursorLine, 0), len - 1)
}
func setSignature(_ app: AppModel, _ sig: Int) {
session.setSignatureSnappingActivePattern(sig)
app.cursorLine = min(max(app.cursorLine, 0), length - 1)
}
func setTempo(_ bpm: Float) { session.tempo = min(max(bpm, 20), 300) }
/// Tap tempo: two or more taps in time set the tempo from the average interval;
/// a pause over 2 s starts a fresh count; at most 8 taps are averaged.
func tapTempo() {
let now = Date().timeIntervalSinceReferenceDate
if let last = tapTimes.last, now - last > 2 { tapTimes.removeAll() }
tapTimes.append(now)
while tapTimes.count > 8 { tapTimes.removeFirst() }
if tapTimes.count >= 2, let first = tapTimes.first, let last = tapTimes.last, last > first {
setTempo(Float(Double(tapTimes.count - 1) * 60 / (last - first)))
}
}
// MARK: transport
/// Play starts from the arrangement selection's first beat when there is one.
func playPause() {
if session.isPlaying { session.pause() }
else if arrSelBeat0 >= 0 { session.play(fromBeat: min(arrSelBeat0, arrSelBeat1)) }
else { session.play() }
}
/// Stop also clears the arrangement selection, so the next Play starts at the top.
func stop() {
clearArrangementSelection()
session.stop()
}
// MARK: arrangement
var hasArrSelection: Bool { arrSelBeat0 >= 0 }
var arrLaneRange: ClosedRange<Int> { min(arrSelLane0, arrSelLane1)...max(arrSelLane0, arrSelLane1) }
var arrBeatRange: ClosedRange<Int> { 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<AnyCancellable> = []
init(_ app: AppModel) {
revision = app.revision
isPlaying = app.isPlaying
app.$revision.removeDuplicates().sink { [weak self] in self?.revision = $0 }.store(in: &subs)
app.$isPlaying.removeDuplicates().sink { [weak self] in self?.isPlaying = $0 }.store(in: &subs)
}
}
/// Notes held on the punch-in keyboard (Android: heldNotes), lighting the keys.
@MainActor
final class TrackerHeldNotes: ObservableObject {
static let shared = TrackerHeldNotes()
@Published private(set) var counts: [Int: Int] = [:]
/// Channel each sounding note went out on, so note-off matches it.
private var channels: [Int: Int] = [:]
func isHeld(_ midi: Int) -> Bool { (counts[midi] ?? 0) > 0 }
func on(_ midi: Int, app: AppModel) {
counts[midi, default: 0] += 1
channels[midi] = app.kbdChannel
SizzleSession.shared.note(on: midi, velocity: min(max(app.kbdVelocity, 0), 127), midiChannel: app.kbdChannel)
}
func off(_ midi: Int, app: AppModel) {
let n = (counts[midi] ?? 0) - 1
if n <= 0 { counts[midi] = nil } else { counts[midi] = n }
SizzleSession.shared.noteOff(midi, midiChannel: channels[midi] ?? app.kbdChannel)
}
/// Release everything (the keyboard went away mid-press).
func releaseAll() {
for (midi, ch) in channels where (counts[midi] ?? 0) > 0 { SizzleSession.shared.noteOff(midi, midiChannel: ch) }
counts.removeAll()
}
}
/// A one-axis scroll position with drag and fling (exponential decay), shared by
/// the pattern grid (vertical) and the arrangement roll (horizontal). Plain
/// SwiftUI: a 60 Hz timer stands in for a display link.
@MainActor
final class TrackerScroller: ObservableObject {
@Published var offset: CGFloat = 0
private var timer: Timer?
private var velocity: CGFloat = 0
private var maxOffset: CGFloat = 0
private var lastTick: TimeInterval = 0
private let tau: CGFloat = 0.325
var isFlinging: Bool { timer != nil }
func stop() { timer?.invalidate(); timer = nil }
/// Coast [distance] points (the gesture's predicted overshoot) in the scroll direction.
func fling(distance: CGFloat, max: CGFloat) {
stop()
guard abs(distance) > 4 else { return }
maxOffset = max
velocity = distance / tau
lastTick = Date().timeIntervalSinceReferenceDate
let t = Timer(timeInterval: 1.0 / 60, repeats: true) { [weak self] _ in
Task { @MainActor in self?.tick() }
}
RunLoop.main.add(t, forMode: .common)
timer = t
}
private func tick() {
let now = Date().timeIntervalSinceReferenceDate
let dt = CGFloat(now - lastTick)
lastTick = now
let next = min(max(offset + velocity * dt, 0), maxOffset)
velocity *= exp(-dt / tau)
if next != offset { offset = next }
if abs(velocity) < 12 || next <= 0 || next >= maxOffset { stop() }
}
}
@@ -0,0 +1,186 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
/// The Android "Amber CRT" palette slots the shared Theme doesn't have (beat/bar
/// row tints, the playhead green, the danger red), plus Theme's own for brevity.
enum TK {
static let background = Theme.background
static let surface = Theme.surface
static let grid = Theme.grid
static let text = Theme.text
static let dim = Theme.dim
static let accent = Theme.accent
static let beat = Color(red: 0x14 / 255, green: 0x1C / 255, blue: 0x1A / 255)
static let bar = Color(red: 0x1E / 255, green: 0x2A / 255, blue: 0x20 / 255)
static let playhead = Color(red: 0x7C / 255, green: 0xFC / 255, blue: 0x9A / 255)
static let danger = Color(red: 0xE0 / 255, green: 0x5A / 255, blue: 0x4B / 255)
/// Pitch.name: 60 → "C-4", 61 → "C#4" (MIDI 12 == C0).
static let noteNames: [String] = (0..<128).map { m in
let names = ["C-", "C#", "D-", "D#", "E-", "F-", "F#", "G-", "G#", "A-", "A#", "B-"]
return names[m % 12] + String(m / 12 - 1)
}
static func noteName(_ midi: Int) -> String { (0..<128).contains(midi) ? noteNames[midi] : "..." }
static let hex2: [String] = (0..<256).map { String(format: "%02X", $0) }
static let chan2: [String] = (0..<100).map { String(format: "%02d", $0) }
}
/// Android's RetroButton: flat, square, 1 pt border, monospace label. [active]
/// paints it in the accent colour, [danger] in red; [width] pins the width.
struct TKButton: View {
let label: String
var active = false
var width: CGFloat? = nil
var danger = false
let action: () -> Void
var body: some View {
TKButtonFace(label: label, active: active, width: width, danger: danger)
.contentShape(Rectangle())
.onTapGesture(perform: action)
}
}
struct TKButtonFace: View {
let label: String
var active = false
var width: CGFloat? = nil
var danger = false
var body: some View {
let hue: Color? = danger ? TK.danger : (active ? TK.accent : nil)
Text(label)
.font(Theme.mono(12)).lineLimit(1).truncationMode(.tail)
.foregroundColor(hue ?? TK.text)
.padding(.horizontal, 10).padding(.vertical, 6)
.frame(width: width)
.background(hue.map { $0.opacity(0.18) } ?? TK.surface)
.overlay(Rectangle().stroke(hue ?? TK.grid, lineWidth: 1))
.fixedSize(horizontal: width == nil, vertical: true)
}
}
/// Android's RepeatButton: steps once on press, then repeats while held with the
/// interval shrinking (320 ms × 0.8 per step, down to 24 ms). Lifting the finger
/// or sliding off (more than a few points) stops it.
struct TKRepeatButton: View {
let label: String
var active = false
var width: CGFloat? = nil
let onStep: () -> Void
@State private var repeater = Repeater()
var body: some View {
TKButtonFace(label: label, active: active, width: width)
.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 0)
.onChanged { g in
if !repeater.pressed {
repeater.start(onStep)
} else if abs(g.translation.width) > 12 || abs(g.translation.height) > 12 {
repeater.stop()
}
}
.onEnded { _ in repeater.stop(); repeater.pressed = false })
.onDisappear { repeater.stop() }
}
final class Repeater {
var pressed = false
private var timer: Timer?
private var delay: TimeInterval = 0.32
func start(_ step: @escaping () -> Void) {
pressed = true
step()
delay = 0.32
schedule(step)
}
private func schedule(_ step: @escaping () -> Void) {
let t = Timer(timeInterval: delay, repeats: false) { [weak self] _ in
guard let self = self, self.timer != nil else { return }
step()
self.delay = max(0.024, self.delay * 0.8)
self.schedule(step)
}
RunLoop.main.add(t, forMode: .common)
timer = t
}
func stop() { timer?.invalidate(); timer = nil }
}
}
/// Android's RetroDropdown, `LABEL:value ▾`, sized to its longest option so it
/// never resizes. Tap opens a menu of the options.
struct TKDropdown<T: Hashable>: View {
let label: String
let options: [T]
let selected: T
let optionLabel: (T) -> String
let onSelect: (T) -> Void
init(_ label: String, options: [T], selected: T, optionLabel: @escaping (T) -> String = { "\($0)" },
onSelect: @escaping (T) -> Void) {
self.label = label; self.options = options; self.selected = selected
self.optionLabel = optionLabel; self.onSelect = onSelect
}
var body: some View {
if Snapshot.active { face } else {
Menu {
ForEach(options, id: \.self) { o in
Button { onSelect(o) } label: {
if o == selected { Label(optionLabel(o), systemImage: "checkmark") } else { Text(optionLabel(o)) }
}
}
} label: { face }
}
}
private var face: some View {
let prefix = label.isEmpty ? "" : label + ":"
let longest = options.map(optionLabel).max { $0.count < $1.count } ?? ""
return ZStack(alignment: .leading) {
Text(prefix + longest + " ▾").hidden()
Text(prefix + optionLabel(selected) + " ▾").foregroundColor(TK.text)
}
.font(Theme.mono(12)).lineLimit(1)
.padding(.horizontal, 8).padding(.vertical, 6)
.background(TK.surface)
.overlay(Rectangle().stroke(TK.grid, lineWidth: 1))
.fixedSize()
}
}
/// A horizontally scrolling row (a plain row in snapshot mode: ImageRenderer
/// can't draw scroll views).
struct TKHScroll<Content: View>: View {
@ViewBuilder let content: () -> Content
var body: some View {
if Snapshot.active {
content().fixedSize(horizontal: true, vertical: false)
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading).clipped()
} else {
ScrollView(.horizontal, showsIndicators: false) { content() }
}
}
}
/// Android's Row(horizontalArrangement = SpaceBetween): items spread edge to edge.
struct TKJustifiedRow: View {
let items: [AnyView]
var body: some View {
HStack(spacing: 0) {
ForEach(items.indices, id: \.self) { i in
if i > 0 { Spacer(minLength: 4) }
items[i]
}
}
.frame(maxWidth: .infinity)
}
}