// 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..