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