Files
RedLintu16andClaude Opus 5.5 64ec524ba0 CrossSound for Apple platforms
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
2026-10-14 13:28:34 -07:00

538 lines
21 KiB
Swift
Executable File

// VisualizerView — port of lib/screens/visualizer_screen.dart +
// lib/widgets/visualizer_painter.dart.
//
// Waveform-driven, DRM-safe: the render input is the track's waveform JSON
// (1800 ints 0..140 via WaveformStore), scrubbed by engine.positionMs /
// durationMs. No audio tap, no FFT — which is exactly why it works on Go+/
// FairPlay tracks where the protected audio path refuses taps (the same
// reason the equalizer can't bite there). It is loudness-reactive, not a true
// spectrum: every style except `waveform` renders ONE smoothed loudness
// scalar shaped by a deterministic sin() wobble; only the waveform style
// indexes real samples (a span window centered on the playhead).
//
// Frame loop: Flutter's Ticker + setState-per-tick becomes
// TimelineView(.animation) + Canvas. The screen-side energy pipeline (7-sample
// window around the playhead → EMA 0.8/0.2) runs once per frame before the
// renderer, exactly where the Dart _onTick ran it; sensitivity is applied
// inside the renderer (energy * sensitivity, clamped), preserving the Dart
// screen/painter split — reordering those two changes the feel. The Dart
// ticker also ran at display rate, so the per-tick EMA coefficients port
// unchanged (a 120Hz ProMotion display just smooths ~2x faster in wall time).
// The loop runs regardless of playing state — paused shows the idle pulse.
//
// Luminance-aware light/dark: the Flutter screen hard-coded a black Scaffold;
// the desktop app (src/ui/visualizer.js) is the themable-surface precedent —
// _vizIsLight(--bg) drops the additive compositing, shrinks the glow, and
// _vizApplyChrome darkens the title/artist/close controls on light themes so
// the canvas doesn't wash out to white. This view draws over the active
// palette's bg — pure black in the stock dark palette (the Flutter look
// verbatim), pure white in light, anything at all under an imported theme —
// so it runs _vizIsLight's own test on that bg rather than trusting the color
// scheme, which a theme's background can contradict: light → glow halved;
// dark → full glow. The chrome needs no branch: it is contentText, the
// palette's readable-on-bg color.
//
// Themes are not optional: no color here is fixed. followTheme presets take
// the palette accent (p.red), the chips are the library's .rw(selected:) chip
// and the chrome is contentText, so an imported theme file re-skins the whole
// screen. Only a preset's own color1/color2 (user data) stay fixed.
//
// Interaction, per the Dart screen: preset chips bottom-center switch the
// active look live (no reload), close button top-right, and NO other gestures
// (no tap-to-hide chrome, no swipe).
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
@MainActor
public struct VisualizerView: View {
// The active RedWhiteUI palette (set once by AppRoot's .rwTheme()), an
// imported theme's included. Its bg is also the light/dark check: the color
// scheme can't be, once a theme brings its own background.
@Environment(\.rw) private var p
@Environment(AppServices.self) private var services
@Environment(\.dismiss) private var dismiss
private let store = VisualizerStore.shared
/// Per-frame mutable state kept OUTSIDE SwiftUI's diffing on purpose: the
/// EMA and the loaded waveform change every frame / mid-flight, and neither
/// should invalidate the view — TimelineView already redraws each frame
/// (the Dart screen's always-repaint contract).
@State private var frame = VizFrameState()
/// Ticker zero — phase = seconds since the screen opened, monotonic like
/// the Dart Ticker's `elapsed`.
@State private var start = Date()
public init() {}
@ObserveInjection var inject
public var body: some View {
// _vizIsLight(--bg) on the ACTIVE palette's bg, not the color scheme,
// which an imported theme's background can contradict (header note).
let isLight = vizIsLight(p.bg)
// The ONE place that still uses contentText: this chrome sits over the
// visualization, which follows the accent, so it is picked for luminance
// contrast, not brand identity — red text over red bars would be
// unreadable. contentText is the palette's readable-on-bg color in every
// scheme and theme, so it also replaces the old hard-coded white on dark.
let chrome = p.contentText.color
ZStack {
// Flutter: backgroundColor: Colors.black — the stock dark palette bg IS
// pure black; a light (or themed) bg takes the _vizIsLight branch.
p.bg.color.ignoresSafeArea()
TimelineView(.animation) { timeline in
canvasLayer(phase: timeline.date.timeIntervalSince(start), isLight: isLight)
}
.ignoresSafeArea()
}
// Track meta (Dart: Positioned left/right 24, bottom 92).
.overlay(alignment: .bottomLeading) {
if let track = services.queue.currentTrack {
trackMeta(track, chrome: chrome)
.padding(.horizontal, 24)
.padding(.bottom, 92)
}
}
// Preset chips (Dart: bottom-center Wrap, bottom 28) — live switch.
.overlay(alignment: .bottom) {
ChipFlow(spacing: 8) {
ForEach(store.presets) { preset in
chip(preset)
}
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.bottom, 28)
}
// Close (Dart: top 8, right 8, inside SafeArea).
.overlay(alignment: .topTrailing) {
Button {
dismiss()
} label: {
Image(systemName: "xmark")
.font(.system(size: 16, weight: .semibold))
.foregroundStyle(chrome)
.padding(12)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.keyboardShortcut(.cancelAction)
.padding(8)
}
// Immersive like the Dart no-app-bar Scaffold; the close button is the
// way out (plus the edge-swipe back gesture the stack keeps). AppShell
// skips rwPushChrome for this one destination, so the library's helper
// hides the system push chrome here instead: the navigation bar on iOS,
// the glass back button on macOS (never the window toolbar, so the
// traffic lights stay).
.rwHideSystemPushChrome()
// Track change → reload waveform. task(id:) re-runs (and cancels the old
// load) whenever the id changes; the wf is nulled SYNCHRONOUSLY first so
// the old track's waveform never drives the new one, and the stale-async
// guard re-checks the current id before applying — both straight from the
// Dart _onTick.
.task(id: services.queue.currentTrack?.id) {
guard let track = services.queue.currentTrack, track.id != frame.loadedTrackId else { return }
frame.loadedTrackId = track.id
frame.wf = nil
let ws = await WaveformStore.load(track.waveformUrl)
if !Task.isCancelled, services.queue.currentTrack?.id == track.id {
frame.wf = ws
}
}
.enableInjection()
}
// MARK: - Canvas frame
/// One tick: read the transport, run the screen-side energy step, then hand
/// a value-typed renderer to the Canvas (so the draw closure touches no
/// MainActor state).
private func canvasLayer(phase: Double, isLight: Bool) -> some View {
let posMs = services.engine.positionMs
let durMs = services.engine.durationMs
let playing = services.engine.state == .playing
let preset = store.active
// Local loudness at the playhead → smoothed energy (_onTick verbatim):
// average a 7-sample window around pos/dur*len, each /ceiling, skipping
// out-of-range indices; ceiling <= 0 falls back to 140.
var level = 0.0
if let wf = frame.wf, !wf.samples.isEmpty, durMs > 0 {
let len = wf.samples.count
let center = Double(posMs) / Double(durMs) * Double(len)
let ceilV = Double(wf.ceiling <= 0 ? 140 : wf.ceiling)
var acc = 0.0
var cnt = 0
for k in -3...3 {
let i = Int(center.rounded(.down)) + k
if i >= 0, i < len {
acc += Double(wf.samples[i]) / ceilV
cnt += 1
}
}
level = cnt > 0 ? acc / Double(cnt) : 0
}
frame.energy = frame.energy * 0.8 + level * 0.2
let renderer = VizRenderer(
wf: frame.wf,
posRatio: durMs > 0 ? min(max(Double(posMs) / Double(durMs), 0), 1) : 0,
playing: playing,
energy: frame.energy,
phase: phase,
preset: preset,
colors: gradientColors(preset),
isLight: isLight)
return Canvas { ctx, size in
renderer.draw(in: &ctx, size: size)
}
}
/// followTheme → primary + primary lerped 35% to white (the Dart build-time
/// Color.lerp(cs.primary, Colors.white, 0.35)); otherwise the preset's
/// fixed ARGB pair. "Primary" is the ACTIVE palette's accent (p.red), so an
/// imported theme recolors the visualizer like the rest of the app — it was
/// a hard-coded copy of the stock red. RwColor.lerp is the same per-channel,
/// alpha-included lerp as Flutter's Color.lerp.
private func gradientColors(_ preset: VisualizerPreset) -> (Color, Color) {
if preset.followTheme {
return (p.red.color, p.red.lerp(to: .white, 0.35).color)
}
return (RwColor(preset.color1).color, RwColor(preset.color2).color)
}
// MARK: - Chrome
/// 72x72 square artwork (the Dart radius 10 went with every other corner;
/// skipped when empty, failure → empty box like the Dart errorBuilder),
/// title 20 bold, username 14 @70%.
private func trackMeta(_ track: SCTrack, chrome: Color) -> some View {
HStack(spacing: 14) {
if let art = track.artworkUrl, !art.isEmpty {
AsyncImage(url: URL(string: art)) { image in
image.resizable().scaledToFill()
} placeholder: {
Color.clear
}
.frame(width: 72, height: 72)
// Square clip — still needed: scaledToFill overflows the 72pt box.
.clipped()
.rwBorder(.accent, width: 2)
}
VStack(alignment: .leading, spacing: 2) {
// Color via .rw(color:): .rw bakes its color in, so a trailing
// .foregroundStyle would be ignored.
Text(track.title)
.rw(.titleLarge, color: chrome)
.lineLimit(1)
Text(track.user.username)
.rw(.bodyMedium, color: chrome.opacity(0.7))
.lineLimit(1)
}
Spacer(minLength: 0)
}
}
/// The Dart chip (radius 999, white/black alpha washes, primary when
/// active) is now the library's chip idiom, as on the EQ / Ambience /
/// Search chips: .rw(selected:) — inverted (solid accent, onRed label)
/// while active, page-colored with the accent hairline otherwise. Square,
/// Raleway, every color a palette token, so a theme recolors it. Only the
/// Dart 14x7 padding survives: at the stock 44pt control height the four
/// builtins wrap onto a second row, up into the track meta at bottom 92.
private func chip(_ preset: VisualizerPreset) -> some View {
var style: BareButtonStyle = .bare(selected: preset.id == store.activeId)
style.padding = EdgeInsets(top: 7, leading: 14, bottom: 7, trailing: 14)
style.minHeight = nil
return Button {
store.setActive(preset.id)
} label: {
Text(preset.name)
}
.buttonStyle(style)
}
}
// MARK: - Per-frame state
/// Reference type on purpose: mutated inside the frame loop without
/// invalidating the view (see the @State comment above).
@MainActor
private final class VizFrameState {
var energy: Double = 0
var wf: WaveformSamples?
var loadedTrackId: String?
}
// MARK: - Renderer (visualizer_painter.dart, verbatim math)
/// Value-typed snapshot of one frame's inputs + the four style painters.
/// Mirrors VisualizerPainter field-for-field; `isLight` replaces the desktop
/// _vizIsLight branch (glow halved on light themes — the Flutter painter had
/// no theme branch because its screen was always black).
private struct VizRenderer {
let wf: WaveformSamples?
let posRatio: Double // 0..1
let playing: Bool
let energy: Double // smoothed local loudness 0..1
let phase: Double // seconds, monotonic
let preset: VisualizerPreset
let colors: (Color, Color)
let isLight: Bool
func draw(in ctx: inout GraphicsContext, size: CGSize) {
let w = size.width, h = size.height
guard w > 0, h > 0 else { return }
let n = min(max(preset.density, 8), 180)
let lv = min(max(energy * preset.sensitivity, 0), 1)
let live = playing && (wf?.samples.isEmpty == false)
// Flutter: MaskFilter.blur(normal, 2 + glow*6) only while playing — the
// whole shape blurs into the glow, same as here. Light themes halve the
// radius (desktop's "smaller glow" branch).
var glowRadius: Double?
if playing, preset.glow > 0 {
let r = 2 + preset.glow * 6
glowRadius = isLight ? r * 0.5 : r
}
if !live {
drawIdle(in: &ctx, w: w, h: h)
return
}
// Pseudo-spectrum from ONE loudness value + animated per-bar shaping —
// deliberately fake (do not read per-bar samples here): shared lv, a
// deterministic wobble, and a 45% low-index bias toward the left.
var spectrum = [Double](repeating: 0, count: n)
for i in 0..<n {
let t = Double(i) / Double(n)
let wob = 0.5 + 0.5 * sin(Double(i) * 0.7 + phase * 4 + sin(Double(i) * 0.3 + phase * 1.3) * 1.6)
let shape = (1 - t * 0.45) * (0.4 + 0.6 * wob)
spectrum[i] = min(max(lv * (0.45 + 1.15 * shape), 0), 1)
}
switch preset.style {
case .bars: drawBars(in: &ctx, w: w, h: h, sp: spectrum, glow: glowRadius)
case .waveform: drawWave(in: &ctx, w: w, h: h, n: n, glow: glowRadius)
case .circular: drawRing(in: &ctx, w: w, h: h, sp: spectrum, glow: glowRadius)
case .blob: drawBlob(in: &ctx, w: w, h: h, sp: spectrum, lv: lv, glow: glowRadius)
}
}
/// _vGrad — one linear color1→color2 gradient in canvas coordinates,
/// shared by every shape a style draws (like the Dart shader).
private func grad(_ x0: Double, _ y0: Double, _ x1: Double, _ y1: Double)
-> GraphicsContext.Shading
{
.linearGradient(
Gradient(colors: [colors.0, colors.1]),
startPoint: CGPoint(x: x0, y: y0),
endPoint: CGPoint(x: x1, y: y1))
}
/// A copy of the context with the glow blur applied (GraphicsContext is a
/// value type — the copy's filter never leaks to the caller).
private func glowCtx(_ ctx: GraphicsContext, _ glow: Double?) -> GraphicsContext {
var g = ctx
if let glow { g.addFilter(.blur(radius: glow)) }
return g
}
private func drawBars(
in ctx: inout GraphicsContext, w: Double, h: Double, sp: [Double], glow: Double?
) {
let g = glowCtx(ctx, glow)
let shading = grad(0, h, 0, 0)
let n = sp.count
let gap = max(1.0, (w / Double(n)) * 0.25)
let bw = w / Double(n) - gap
let mid = h / 2
for i in 0..<n {
// Squared for visual punch, min height 2.
let bh = max(2.0, sp[i] * sp[i] * h * 0.92)
let x = Double(i) * (bw + gap) + gap / 2
let top = preset.mirror ? mid - bh / 2 : h - bh
// Square bars: the Dart radius 2 went with every other corner.
g.fill(Path(CGRect(x: x, y: top, width: bw, height: bh)), with: shading)
}
}
/// The one style that reads REAL samples: a span = max(n, 96) window
/// centered on the playhead, drawn as two mirrored animated strokes.
private func drawWave(
in ctx: inout GraphicsContext, w: Double, h: Double, n: Int, glow: Double?
) {
guard let wf, n > 1 else { return }
let g = glowCtx(ctx, glow)
let s = wf.samples
let ceilV = Double(wf.ceiling <= 0 ? 140 : wf.ceiling)
let mid = h / 2
let len = s.count
let center = min(max(posRatio, 0), 1) * Double(len)
let span = Double(max(n, 96))
let shading = grad(0, 0, w, 0)
let style = StrokeStyle(lineWidth: 2.5)
for dir in [1.0, -1.0] {
var path = Path()
for i in 0..<n {
let idx = min(max(Int((center - span / 2 + Double(i) / Double(n) * span).rounded(.down)), 0), len - 1)
let amp = Double(s[idx]) / ceilV
let x = Double(i) / Double(n - 1) * w
let y = mid + dir * (amp * h * 0.42) * (0.6 + 0.4 * sin(Double(i) * 0.3 + phase * 3))
if i == 0 {
path.move(to: CGPoint(x: x, y: y))
} else {
path.addLine(to: CGPoint(x: x, y: y))
}
}
g.stroke(path, with: shading, style: style)
}
}
private func drawRing(
in ctx: inout GraphicsContext, w: Double, h: Double, sp: [Double], glow: Double?
) {
let g = glowCtx(ctx, glow)
let cx = w / 2, cy = h / 2
let r = min(w, h) * 0.26
let n = sp.count
let shading = grad(0, cy - r, 0, cy + r)
// Square caps, not the Dart round ones (those made every spoke a
// capsule); .square keeps the same half-width overhang, so the spokes
// keep their length.
let style = StrokeStyle(
lineWidth: max(1.5, (Double.pi * 2 * r) / Double(n) * 0.55), lineCap: .square)
for i in 0..<n {
let v = sp[i]
let len = 8 + v * v * min(w, h) * 0.3
// phase*0.3 = the slow rotation.
let a = Double(i) / Double(n) * Double.pi * 2 + phase * 0.3
let cosA = cos(a), sinA = sin(a)
var path = Path()
path.move(to: CGPoint(x: cx + cosA * r, y: cy + sinA * r))
path.addLine(to: CGPoint(x: cx + cosA * (r + len), y: cy + sinA * (r + len)))
g.stroke(path, with: shading, style: style)
}
}
private func drawBlob(
in ctx: inout GraphicsContext, w: Double, h: Double, sp: [Double], lv: Double, glow: Double?
) {
let g = glowCtx(ctx, glow)
let cx = w / 2, cy = h / 2
let baseR = min(w, h) * 0.15 * (1 + lv * 1.7)
let pts = 90
var path = Path()
for i in 0...pts {
let t = Double(i) / Double(pts)
let v = sp[Int((t * Double(sp.count - 1)).rounded(.down))]
let wobble = sin(t * Double.pi * 6 + phase * 2) * 0.06
let r = baseR * (1 + v * 0.45 + wobble)
let a = t * Double.pi * 2
let point = CGPoint(x: cx + cos(a) * r, y: cy + sin(a) * r)
if i == 0 {
path.move(to: point)
} else {
path.addLine(to: point)
}
}
path.closeSubpath()
g.fill(path, with: grad(cx, cy - baseR, cx, cy + baseR))
}
/// Paused or no waveform: color1 @50%, stroke 2, no glow — a pulsing circle
/// for circular/blob, a drifting sine line for bars/waveform.
private func drawIdle(in ctx: inout GraphicsContext, w: Double, h: Double) {
let cx = w / 2, cy = h / 2
let pulse = 0.5 + 0.5 * sin(phase * 1.4)
let shading = GraphicsContext.Shading.color(colors.0.opacity(0.5))
if preset.style == .circular || preset.style == .blob {
let r = min(w, h) * (0.15 + pulse * 0.03)
ctx.stroke(
Path(ellipseIn: CGRect(x: cx - r, y: cy - r, width: r * 2, height: r * 2)),
with: shading, lineWidth: 2)
} else {
var path = Path()
var x = 0.0
while x <= w {
let y = cy + sin(x * 0.012 + phase * 2) * (10 + pulse * 14)
if x == 0 {
path.move(to: CGPoint(x: x, y: y))
} else {
path.addLine(to: CGPoint(x: x, y: y))
}
x += 6
}
ctx.stroke(path, with: shading, lineWidth: 2)
}
}
}
// MARK: - Chip flow
/// Flutter's Wrap for the preset chips: rows centered as a group, 8pt spacing
/// on both axes (spacing/runSpacing 8), wrapping when the row would overflow.
private struct ChipFlow: Layout {
var spacing: CGFloat = 8
private func rows(_ subviews: Subviews, maxWidth: CGFloat) -> [[Int]] {
var rows: [[Int]] = [[]]
var x: CGFloat = 0
for (i, s) in subviews.enumerated() {
let w = s.sizeThatFits(.unspecified).width
if !rows[rows.count - 1].isEmpty, x + w > maxWidth {
rows.append([])
x = 0
}
rows[rows.count - 1].append(i)
x += w + spacing
}
return rows
}
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
let maxW = proposal.width ?? .infinity
var height: CGFloat = 0
for (r, row) in rows(subviews, maxWidth: maxW).enumerated() {
let rowH = row.map { subviews[$0].sizeThatFits(.unspecified).height }.max() ?? 0
height += rowH + (r > 0 ? spacing : 0)
}
return CGSize(width: proposal.width ?? 0, height: height)
}
func placeSubviews(
in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()
) {
var y = bounds.minY
for row in rows(subviews, maxWidth: bounds.width) {
let sizes = row.map { subviews[$0].sizeThatFits(.unspecified) }
let rowW =
sizes.map(\.width).reduce(0, +) + spacing * CGFloat(max(0, row.count - 1))
let rowH = sizes.map(\.height).max() ?? 0
var x = bounds.minX + (bounds.width - rowW) / 2
for (j, i) in row.enumerated() {
subviews[i].place(
at: CGPoint(x: x, y: y + (rowH - sizes[j].height) / 2), proposal: .unspecified)
x += sizes[j].width + spacing
}
y += rowH + spacing
}
}
}
// MARK: - Background luminance
/// _vizIsLight, verbatim: Rec. 709 weights on the gamma-encoded sRGB
/// channels, light above 140/255. Fed the active palette's bg, so an imported
/// theme's background — not the system color scheme — picks the branch.
private func vizIsLight(_ bg: RwColor) -> Bool {
0.2126 * bg.red + 0.7152 * bg.green + 0.0722 * bg.blue > 140.0 / 255.0
}