Files
ReactorcoremeltdownandClaude Opus 5.5 634dd05486 0.41.1 (77): iOS controls redraw when the song changes
The Mix record bar, the Sampler waveform page, the LFO target picker and the
audition keyboards read the session but had no changing inputs, so SwiftUI
skipped redrawing them until something else (rotation) forced it. They now
observe MixSongWatch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:30:06 +01:00

268 lines
11 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
import SwiftUI
#if canImport(UIKit)
import UIKit
#endif
/// The Toolbox tab's audition keyboard (Android's StackedKeyboard without punch-in):
/// CH / OCT / VEL steppers over two stacked octaves, upper on top. Keys play the
/// mix bus on the keyboard's MIDI channel; out-of-scale keys are dimmed, unless the
/// channel reaches a Sampler (every pad must stay playable).
struct ToolboxKeyboard: View {
/// Redraw when the song changes: these inputs alone never change, so SwiftUI
/// would otherwise keep showing the old state.
@ObservedObject private var watch = MixSongWatch.shared
let app: AppModel
let channel: Int
let octave: Int
let velocity: Int
var body: some View {
let session = SizzleSession.shared
let inKey = routesToSampler ? Set(0..<12) : Set(session.scalePitchClasses.map { $0.intValue })
VStack(spacing: 4) {
MixKit.HScroll {
HStack(spacing: 6) {
selector("CH", channel == 0 ? "--" : "\(channel)",
{ app.kbdChannel = max(0, app.kbdChannel - 1) }, { app.kbdChannel = min(16, app.kbdChannel + 1) })
selector("OCT", "\(octave)–\(octave + 1)",
{ app.kbdOctave = max(0, app.kbdOctave - 1) }, { app.kbdOctave = min(8, app.kbdOctave + 1) })
selector("VEL", String(format: "%02X", velocity),
{ app.kbdVelocity = max(0, app.kbdVelocity - 8) }, { app.kbdVelocity = min(127, app.kbdVelocity + 8) })
}
}
.frame(maxWidth: .infinity, alignment: .leading)
octaveView(start: (octave + 2) * 12, inKey: inKey)
octaveView(start: (octave + 1) * 12, inKey: inKey)
}
.padding(6)
.background(Theme.background)
}
private var routesToSampler: Bool {
let s = SizzleSession.shared
return (0..<4).contains { ch in
s.midiChannel(ofChannel: ch) == channel && s.type(ofSlot: s.instrumentSlot(ofChannel: ch)) == "SAMPLER"
}
}
private func octaveView(start: Int, inKey: Set<Int>) -> some View {
let session = SizzleSession.shared, held = HeldNotes.shared
let ch = channel, vel = velocity
return PianoOctave(start: start, enabled: inKey,
onOn: { n in held.on(n); session.note(on: n, velocity: vel, midiChannel: ch) },
onOff: { n in held.off(n); session.noteOff(n, midiChannel: ch) })
}
private func selector(_ label: String, _ value: String, _ dec: @escaping () -> Void, _ inc: @escaping () -> Void) -> some View {
HStack(spacing: 6) {
Text(label).font(Theme.mono(11)).foregroundColor(Theme.dim)
MixKit.RepeatButton(label: "-", onStep: dec)
Text(value).font(Theme.mono(13)).foregroundColor(Theme.accent).frame(width: 40)
MixKit.RepeatButton(label: "+", onStep: inc)
}
}
}
/// SlotAuditionKeyboard: an OCT stepper over two octaves that play one toolbox slot
/// directly (the instrument editors pin it under their controls).
struct SlotAuditionKeyboard: View {
/// Redraw when the song changes: these inputs alone never change, so SwiftUI
/// would otherwise keep showing the old state.
@ObservedObject private var watch = MixSongWatch.shared
let slot: Int
@State private var octave = 3
var body: some View {
let session = SizzleSession.shared
let inKey = Set(session.scalePitchClasses.map { $0.intValue })
VStack(spacing: 4) {
HStack(spacing: 6) {
Text("OCT").font(Theme.mono(11)).foregroundColor(Theme.dim)
MixKit.RepeatButton(label: "-") { octave = max(0, octave - 1) }
Text("\(octave)–\(octave + 1)").font(Theme.mono(13)).foregroundColor(Theme.accent)
MixKit.RepeatButton(label: "+") { octave = min(8, octave + 1) }
}
.frame(maxWidth: .infinity, alignment: .leading)
octaveView(start: (octave + 2) * 12, inKey: inKey)
octaveView(start: (octave + 1) * 12, inKey: inKey)
}
.padding(6)
.background(Theme.background)
}
private func octaveView(start: Int, inKey: Set<Int>) -> some View {
let session = SizzleSession.shared, held = HeldNotes.shared, s = slot
return PianoOctave(start: start, enabled: inKey,
onOn: { n in held.on(n); session.auditionSlot(s, note: n, on: true) },
onOff: { n in held.off(n); session.auditionSlot(s, note: n, on: false) })
}
}
/// Android's PianoOctave: seven white keys with five black keys over them. Fingers
/// are tracked at the octave level, so sliding across keys retriggers each one (a
/// glissando) and several fingers play chords. Out-of-scale keys are dimmed and
/// silent; held notes light up.
struct PianoOctave: View {
let start: Int
let enabled: Set<Int>
let onOn: (Int) -> Void
let onOff: (Int) -> Void
@ObservedObject private var held = HeldNotes.shared
@StateObject private var router = KeyTouchRouter()
static let whites = [0, 2, 4, 5, 7, 9, 11]
static let blacks: [(pc: Int, after: Int)] = [(1, 0), (3, 1), (6, 3), (8, 4), (10, 5)]
static let blackW: CGFloat = 0.62, blackH: CGFloat = 0.62
var body: some View {
GeometryReader { g in
let size = g.size
let ww = size.width / 7, bw = ww * Self.blackW
let _ = router.configure(start: start, enabled: enabled, size: size, onOn: onOn, onOff: onOff)
ZStack(alignment: .topLeading) {
HStack(spacing: 0) {
ForEach(Self.whites, id: \.self) { pc in key(pc, black: false).frame(width: ww, height: size.height) }
}
ForEach(Self.blacks, id: \.pc) { b in
key(b.pc, black: true).frame(width: bw, height: size.height * Self.blackH)
.offset(x: ww * CGFloat(b.after + 1) - bw / 2)
}
}
.overlay(touchLayer)
}
}
private func midi(_ pc: Int) -> Int { min(127, max(0, start + pc)) }
private func key(_ pc: Int, black: Bool) -> some View {
let on = enabled.contains(pc)
let lit = held.isHeld(midi(pc))
let bg: Color = lit ? Theme.accent
: black ? (on ? Color(red: 0x18 / 255, green: 0x18 / 255, blue: 0x20 / 255) : Color(red: 0x0C / 255, green: 0x0C / 255, blue: 0x10 / 255))
: (on ? Color(white: 0xE8 / 255) : Color(white: 0x5A / 255))
let fg: Color = lit ? Theme.background
: black ? (on ? Color(white: 0xDD / 255) : Color(white: 0x55 / 255))
: (on ? Color(white: 0x14 / 255) : Color(white: 0x6A / 255))
return ZStack(alignment: .bottom) {
bg
Text(MixKit.pitchName(midi(pc)).replacingOccurrences(of: "-", with: ""))
.font(Theme.mono(12)).foregroundColor(fg).lineLimit(1).minimumScaleFactor(0.5)
.padding(.bottom, 3)
}
.overlay(Rectangle().stroke(lit ? Theme.accent : Color.black, lineWidth: 1))
}
@ViewBuilder private var touchLayer: some View {
#if canImport(UIKit)
MultiTouchSurface(router: router)
#else
Color.clear.contentShape(Rectangle())
.gesture(DragGesture(minimumDistance: 0)
.onChanged { router.touch(id: 0, at: $0.location, ended: false) }
.onEnded { router.touch(id: 0, at: $0.location, ended: true) })
#endif
}
}
/// Per-finger key tracking for a PianoOctave (pcAt in Piano.kt).
@MainActor
final class KeyTouchRouter: ObservableObject {
private var active: [Int: Int] = [:] // touch id -> pitch class, -1 off any playable key
private var start = 60
private var enabled: Set<Int> = []
private var size: CGSize = .zero
private var onOn: (Int) -> Void = { _ in }
private var onOff: (Int) -> Void = { _ in }
func configure(start: Int, enabled: Set<Int>, size: CGSize, onOn: @escaping (Int) -> Void, onOff: @escaping (Int) -> Void) {
// An octave change while a key is held: release the old notes first.
// (Deferred: this runs while SwiftUI evaluates the body.)
if start != self.start, !active.isEmpty {
let notes = active.values.filter { $0 >= 0 }.map(midi), off = self.onOff
active.removeAll()
DispatchQueue.main.async { notes.forEach(off) }
}
self.start = start
self.enabled = enabled
self.size = size
self.onOn = onOn
self.onOff = onOff
}
private func midi(_ pc: Int) -> Int { min(127, max(0, start + pc)) }
func touch(id: Int, at p: CGPoint, ended: Bool) {
if ended {
if let prev = active.removeValue(forKey: id), prev >= 0 { onOff(midi(prev)) }
return
}
let raw = pitchClass(at: p)
let pc = raw >= 0 && enabled.contains(raw) ? raw : -1
guard let prev = active[id] else {
active[id] = pc
if pc >= 0 { onOn(midi(pc)) }
return
}
if pc != prev {
if prev >= 0 { onOff(midi(prev)) }
if pc >= 0 { onOn(midi(pc)) }
active[id] = pc
}
}
func releaseAll() {
for (_, pc) in active where pc >= 0 { onOff(midi(pc)) }
active.removeAll()
}
private func pitchClass(at p: CGPoint) -> 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 ww = w / 7
if p.y <= h * PianoOctave.blackH {
let bw = ww * PianoOctave.blackW
for b in PianoOctave.blacks {
let bx = ww * CGFloat(b.after + 1) - bw / 2
if p.x >= bx && p.x <= bx + bw { return b.pc }
}
}
return PianoOctave.whites[min(6, max(0, Int(p.x / ww)))]
}
}
#if canImport(UIKit)
/// A transparent view that reports every finger (SwiftUI gestures follow only one).
private struct MultiTouchSurface: UIViewRepresentable {
let router: KeyTouchRouter
func makeUIView(context: Context) -> TouchView {
let v = TouchView()
v.router = router
return v
}
func updateUIView(_ v: TouchView, context: Context) { v.router = router }
final class TouchView: UIView {
weak var router: KeyTouchRouter?
override init(frame: CGRect) {
super.init(frame: frame)
isMultipleTouchEnabled = true
backgroundColor = .clear
}
required init?(coder: NSCoder) { fatalError() }
private func send(_ touches: Set<UITouch>, ended: Bool) {
for t in touches { router?.touch(id: ObjectIdentifier(t).hashValue, at: t.location(in: self), ended: ended) }
}
override func touchesBegan(_ t: Set<UITouch>, with e: UIEvent?) { send(t, ended: false) }
override func touchesMoved(_ t: Set<UITouch>, with e: UIEvent?) { send(t, ended: false) }
override func touchesEnded(_ t: Set<UITouch>, with e: UIEvent?) { send(t, ended: true) }
override func touchesCancelled(_ t: Set<UITouch>, with e: UIEvent?) { send(t, ended: true) }
}
}
#endif