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

545 lines
21 KiB
Swift
Executable File

// VisualizerSettingsView — port of lib/screens/visualizer_settings_screen.dart,
// carrying the preset model + store from lib/models/visualizer_preset.dart.
//
// The Dart contract is kept exactly:
// - VisualizerPreset: the same ten fields, same defaults, same flat JSON
// (style serialized as the enum name, every field default-filled on read —
// forward/backward compat is default-fill, not versioned).
// - VisualizerStore: singleton, the four built-ins, active falls back to
// presets.first, delete() restores the built-ins when the list empties and
// re-points a dangling activeId, save() on every mutation with errors
// swallowed. Persisted under the SAME SharedPreferences key ("cs_visualizer",
// JSON {activeId, presets[]}) with the one-time flutter.* adoption move the
// other stores use, so a Flutter install's presets carry over.
// - The screen: New-preset action, intro copy, one expandable card per preset
// with radio-select / name / style / follow-theme / swatches / sensitivity /
// glow / density / mirror — every edit upserts (= persists) immediately.
// One Dart nuance made explicit: the Dart screen mutated the preset object
// in place and upsert was effectively save(); VisualizerPreset is a struct
// here, so edits flow through Bindings whose setter upserts the copy.
//
// What SwiftUI changes:
// - ExpansionTile → DisclosureGroup inside an RwCard; Radio<String> → a
// circle button (SwiftUI has no radio on iOS).
// - The Dart intro said "Open it from the ⣿ button on the player" — the
// native player bar has no visualizer button yet, so this screen carries
// an explicit "Open Visualizer" row (AppDestination.visualizer) instead
// and the copy points at it.
import CrossSoundKit
import Inject
import RedWhiteUI
import SwiftUI
// MARK: - Model (visualizer_preset.dart)
/// VizStyle — raw values are the Dart enum names, which is what the JSON
/// stores; an unknown string falls back to bars (_styleFrom's orElse).
public enum VizStyle: String, CaseIterable, Sendable {
case bars, waveform, circular, blob
/// vizStyleLabel(s), verbatim.
public var label: String {
switch self {
case .bars: "Frequency bars"
case .waveform: "Waveform"
case .circular: "Circular / orbit"
case .blob: "Blob / pulse"
}
}
}
/// A user-savable visualizer look. Colors either follow the app theme
/// (recolor live when the theme changes) or use fixed custom ARGB colors.
public struct VisualizerPreset: Identifiable, Sendable {
public var id: String
public var name: String
public var style: VizStyle
public var followTheme: Bool
/// ARGB, used only when !followTheme (Dart stored Flutter Color ints).
public var color1: UInt32
public var color2: UInt32
/// Multiplies energy in the painter; UI range 0.4..2.5.
public var sensitivity: Double
/// 0..1 → blur radius 2 + glow*6 while playing.
public var glow: Double
/// Bars/spokes count; UI range 16..160, painter clamps 8..180 (persisted
/// values can legally sit outside the UI range — the slider only clamps
/// its displayed value, like the Dart value.clamp(min, max)).
public var density: Int
/// Bars style only: mirror from the vertical center.
public var mirror: Bool
public init(
id: String,
name: String,
style: VizStyle = .bars,
followTheme: Bool = true,
color1: UInt32 = 0xFFEF_4444,
color2: UInt32 = 0xFFFF_8A5B,
sensitivity: Double = 1.0,
glow: Double = 0.55,
density: Int = 72,
mirror: Bool = true
) {
self.id = id
self.name = name
self.style = style
self.followTheme = followTheme
self.color1 = color1
self.color2 = color2
self.sensitivity = sensitivity
self.glow = glow
self.density = density
self.mirror = mirror
}
/// toJson — flat map, keys exactly the Dart field names.
public func toJSON() -> [String: Any] {
[
"id": id, "name": name, "style": style.rawValue, "followTheme": followTheme,
"color1": Int(color1), "color2": Int(color2), "sensitivity": sensitivity,
"glow": glow, "density": density, "mirror": mirror,
]
}
/// fromJson — every field default-filled when missing (id→'preset',
/// name→'Preset', the rest the constructor defaults), like the Dart factory.
public static func fromJSON(_ j: [String: Any]) -> VisualizerPreset {
VisualizerPreset(
id: j["id"] as? String ?? "preset",
name: j["name"] as? String ?? "Preset",
style: VizStyle(rawValue: j["style"] as? String ?? "bars") ?? .bars,
followTheme: j["followTheme"] as? Bool ?? true,
color1: (j["color1"] as? NSNumber).map { UInt32(truncatingIfNeeded: $0.int64Value) }
?? 0xFFEF_4444,
color2: (j["color2"] as? NSNumber).map { UInt32(truncatingIfNeeded: $0.int64Value) }
?? 0xFFFF_8A5B,
sensitivity: (j["sensitivity"] as? NSNumber)?.doubleValue ?? 1.0,
glow: (j["glow"] as? NSNumber)?.doubleValue ?? 0.55,
density: (j["density"] as? NSNumber)?.intValue ?? 72,
mirror: j["mirror"] as? Bool ?? true)
}
/// _defaults(), verbatim — ids included, so "preset-bars" stays the
/// initial activeId across both codebases.
public static var builtins: [VisualizerPreset] {
[
VisualizerPreset(id: "preset-bars", name: "Spectrum", style: .bars, mirror: true),
VisualizerPreset(
id: "preset-wave", name: "Waveform", style: .waveform, color2: 0xFFFF_FFFF,
sensitivity: 1.1),
VisualizerPreset(id: "preset-ring", name: "Orbit", style: .circular, glow: 0.6, density: 96),
VisualizerPreset(id: "preset-blob", name: "Pulse", style: .blob, color2: 0xFFFF_5500, glow: 0.7),
]
}
}
// MARK: - Store (visualizer_preset.dart VisualizerStore)
/// Singleton store — presets + active selection, persisted under the Flutter
/// key. Self-hydrating (load() in init, like EqualizerEngine) so the Dart
/// "load once at AppState init or presets silently stay defaults" trap can't
/// happen here: the first access hydrates.
@MainActor
@Observable
public final class VisualizerStore {
public static let shared = VisualizerStore()
/// The SAME SharedPreferences key the Flutter app used.
private static let prefKey = "cs_visualizer"
public private(set) var presets: [VisualizerPreset] = VisualizerPreset.builtins
public private(set) var activeId = "preset-bars"
/// Dart's `active` getter: a dangling activeId falls back to presets.first
/// (the list is never empty — delete() restores the built-ins).
public var active: VisualizerPreset {
presets.first { $0.id == activeId } ?? presets[0]
}
private init() { load() }
public func setActive(_ id: String) {
activeId = id
save()
}
/// Replace by id or append — every edit path funnels through here, so
/// upsert doubles as the save() trigger, same as Dart.
public func upsert(_ preset: VisualizerPreset) {
if let i = presets.firstIndex(where: { $0.id == preset.id }) {
presets[i] = preset
} else {
presets.append(preset)
}
save()
}
public func delete(_ id: String) {
presets.removeAll { $0.id == id }
if presets.isEmpty { presets = VisualizerPreset.builtins }
if !presets.contains(where: { $0.id == activeId }) { activeId = presets[0].id }
save()
}
/// 'preset-' + microsecondsSinceEpoch in base 36, like the Dart newId().
public func newId() -> String {
"preset-" + String(Int(Date().timeIntervalSince1970 * 1_000_000), radix: 36)
}
/// Load the cs_visualizer blob — parse errors keep defaults, exactly like
/// Dart. One-time adoption of the shared_preferences copy first — MOVE, not
/// copy: the flutter.* key is deleted even when nothing is adopted (the
/// AuthStore/EqualizerEngine convention).
public func load() {
let d = UserDefaults.standard
if d.object(forKey: Self.prefKey) == nil, let v = d.string(forKey: "flutter.\(Self.prefKey)") {
d.set(v, forKey: Self.prefKey)
}
d.removeObject(forKey: "flutter.\(Self.prefKey)")
guard
let raw = d.string(forKey: Self.prefKey),
let j = (try? JSONSerialization.jsonObject(with: Data(raw.utf8))) as? [String: Any]
else { return }
let list = ((j["presets"] as? [[String: Any]]) ?? []).map(VisualizerPreset.fromJSON)
if !list.isEmpty { presets = list }
activeId = j["activeId"] as? String ?? presets[0].id
if !presets.contains(where: { $0.id == activeId }) { activeId = presets[0].id }
CSLog.shared.log("visualizer", "loaded \(presets.count) presets active=\(activeId)")
}
/// Persist {activeId, presets[]} with the Dart field names so the blob
/// round-trips with the Flutter build. Errors swallowed, like Dart.
public func save() {
let blob: [String: Any] = [
"activeId": activeId,
"presets": presets.map { $0.toJSON() },
]
guard let data = try? JSONSerialization.data(withJSONObject: blob) else { return }
UserDefaults.standard.set(String(decoding: data, as: UTF8.self), forKey: Self.prefKey)
}
}
// MARK: - Screen (visualizer_settings_screen.dart)
/// Swatch palette, verbatim from the Dart _palette list. Preset DATA, not
/// theme colors: a swatch is the fixed ARGB a preset saves (and the Flutter
/// JSON shares), so these stay literals — "Follow app theme" is the themed
/// path.
private let kVizSwatches: [UInt32] = [
0xFFEF_4444, 0xFFFF_5500, 0xFFFF_8A5B, 0xFFEC_4899, 0xFFA8_55F7,
0xFF3B_82F6, 0xFF06_B6D4, 0xFF22_C55E, 0xFFEA_B308, 0xFFFF_FFFF,
]
@MainActor
public struct VisualizerSettingsView: View {
// The active RedWhiteUI palette (set once by AppRoot's .rwTheme()).
@Environment(\.rw) private var p
private let store = VisualizerStore.shared
/// Which preset cards are expanded (the Dart ExpansionTiles kept their own
/// state; DisclosureGroup wants it explicit).
@State private var expanded: Set<String> = []
public init() {}
@ObserveInjection var inject
public var body: some View {
ScrollView {
VStack(alignment: .leading, spacing: 0) {
header(p)
intro(p)
openRow(p)
ForEach(store.presets) { preset in
presetCard(preset, palette: p)
}
.padding(.horizontal, RwSizes.pagePadding)
}
.padding(.bottom, RwSizes.section)
}
// Settings column: cap the line length on wide macOS windows, same as
// EqualizerView/RadioTunerView — lists stay full-bleed, forms don't.
.frame(maxWidth: 640, alignment: .leading)
.frame(maxWidth: .infinity)
.background(p.bg)
.enableInjection()
}
// MARK: - Header (title + the Dart app bar's New-preset action)
private func header(_ p: RwPalette) -> some View {
HStack(alignment: .top, spacing: RwSizes.gap) {
VStack(alignment: .leading, spacing: 6) {
// headlineLarge is the library's page-title role (the old hand-set
// 28/heavy).
Text("Visualizer")
.rw(.headlineLarge)
AccentBar(width: 40)
}
Spacer(minLength: RwSizes.gap)
// Dart RwAction(Icons.add, 'New preset'): a defaults-filled preset,
// upserted and made active.
// rwText: the library's compact borderless button owns the label's
// font and red-at-rest color now.
Button {
let preset = VisualizerPreset(id: store.newId(), name: "My preset")
store.upsert(preset)
store.setActive(preset.id)
expanded.insert(preset.id)
} label: {
Label("New preset", systemImage: "plus")
}
.buttonStyle(.bareText)
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.top, RwSizes.pagePadding)
.padding(.bottom, RwSizes.gap)
}
/// The Dart intro copy, with the player-bar sentence swapped for the row
/// below (see the header note).
private func intro(_ p: RwPalette) -> some View {
Text(
"Save your own visualizer looks. \u{201C}Follow app theme\u{201D} recolors the "
+ "visualizer whenever you change the app theme. Open it from the row below. "
+ "It reacts to the track\u{2019}s waveform, so it works on Go+/DRM tracks too.")
.rw(.bodySmall)
.lineSpacing(3)
.padding(.horizontal, RwSizes.pagePadding)
.padding(.bottom, RwSizes.gap)
}
/// Native-only entry point: Flutter opened the fullscreen visualizer from
/// the player bar's graphic_eq button; until the native bar grows one, this
/// row is how AppDestination.visualizer is reached.
private func openRow(_ p: RwPalette) -> some View {
NavigationLink(value: AppDestination.visualizer) {
LitPalette { p in
RwCard(padding: EdgeInsets()) {
HStack(spacing: RwSizes.gap) {
Image(systemName: "waveform")
.font(.system(size: 17))
.foregroundStyle(p.red)
.frame(width: 28)
VStack(alignment: .leading, spacing: 2) {
// The role's primary red.
Text("Open Visualizer")
.rw(.bodyLarge)
Text("Fullscreen, driven by the current track")
.rw(.labelMedium)
}
Spacer(minLength: RwSizes.gap)
// iconInactive, not a text token: it's chrome, so a theme file's
// "icons" color reaches it.
Image(systemName: "chevron.right")
.font(.system(size: 12, weight: .semibold))
.foregroundStyle(p.iconInactive)
}
.padding(.horizontal, RwSizes.pagePadding)
.padding(.vertical, 10)
.contentShape(Rectangle())
}
}
}
.buttonStyle(.bareRow())
.padding(.horizontal, RwSizes.pagePadding)
.padding(.bottom, RwSizes.gap)
}
// MARK: - Preset cards (_presetCard)
/// Every setter upserts the edited copy — the struct-model equivalent of
/// the Dart mutate-in-place-then-upsert (_touch). The getter re-finds by id
/// so a delete mid-edit degrades to a throwaway copy instead of a crash.
private func binding(for id: String) -> Binding<VisualizerPreset> {
Binding(
get: { store.presets.first { $0.id == id } ?? VisualizerPreset(id: id, name: "Preset") },
set: { store.upsert($0) })
}
private func expandedBinding(_ id: String) -> Binding<Bool> {
Binding(
get: { expanded.contains(id) },
set: { if $0 { expanded.insert(id) } else { expanded.remove(id) } })
}
private func presetCard(_ preset: VisualizerPreset, palette p: RwPalette) -> some View {
RwCard(padding: EdgeInsets()) {
DisclosureGroup(isExpanded: expandedBinding(preset.id)) {
editor(binding(for: preset.id), style: preset.style, followTheme: preset.followTheme, palette: p)
.padding(.horizontal, RwSizes.pagePadding)
.padding(.bottom, RwSizes.gap)
} label: {
cardLabel(preset, palette: p)
}
// .color: the disclosure chevron only honors the Color tint. Chrome,
// so iconInactive (what a theme's "icons" color sets).
.tint(p.iconInactive.color)
.padding(.trailing, RwSizes.pagePadding)
}
// The Dart Card's vertical margin 5.
.padding(.vertical, 5)
}
/// leading Radio (select active) + name/style + trailing delete — the
/// delete is immediate with no confirm, matching Dart.
private func cardLabel(_ preset: VisualizerPreset, palette p: RwPalette) -> some View {
let active = store.activeId == preset.id
return HStack(spacing: RwSizes.gap) {
Button {
store.setActive(preset.id)
} label: {
LitPalette { p in
// Selected is the active state: the hover colour (BareButtons.swift).
Image(systemName: active ? "largecircle.fill.circle" : "circle")
.font(.system(size: 18))
.foregroundStyle(p.red)
}
}
.buttonStyle(.bareRow(active: active))
VStack(alignment: .leading, spacing: 2) {
Text(preset.name)
.rw(.bodyLarge, color: p.text.color)
.lineLimit(1)
Text(preset.style.label)
.rw(.labelMedium)
}
Spacer(minLength: RwSizes.gap)
Button {
expanded.remove(preset.id)
store.delete(preset.id)
} label: {
Image(systemName: "trash")
.font(.system(size: 14))
.foregroundStyle(p.iconInactive)
}
.buttonStyle(.plain)
.help("Delete")
}
.padding(.leading, RwSizes.pagePadding)
.padding(.vertical, 10)
}
// MARK: - Editor (the ExpansionTile children)
/// `style`/`followTheme` are passed alongside the binding so the visibility
/// branches (swatches, mirror) read the same values the label row rendered.
@ViewBuilder
private func editor(
_ b: Binding<VisualizerPreset>, style: VizStyle, followTheme: Bool, palette p: RwPalette
) -> some View {
VStack(alignment: .leading, spacing: RwSizes.gap) {
// Name — upserts per keystroke, like the Dart onChanged. The library
// field (square, Raleway), not the system .roundedBorder bezel.
TextField("Name", text: b.name)
.textFieldStyle(.bare)
HStack {
Text("Style")
.rw(.bodySmall)
Spacer()
// RwMenu, not Picker(.menu): a menu-style picker opens the same
// out-of-process glass panel the context menus did.
RwMenu(
VizStyle.allCases.map { style in
RwMenuItem(style.label, systemImage: b.style.wrappedValue == style ? "checkmark" : nil) {
b.style.wrappedValue = style
}
}
) {
// Bare Text, like every other RwMenu label: the menu's borderless
// button owns the font and color (red at rest, inverted while
// open). An .rw() color is baked in and would stay muted on the
// open state's solid red.
HStack(spacing: 4) {
Text(b.style.wrappedValue.label)
Image(systemName: "chevron.up.chevron.down")
.font(.system(size: 9, weight: .semibold))
}
}
}
toggleLine("Follow app theme colors", isOn: b.followTheme, palette: p)
if !followTheme {
swatchRow("Color 1", selected: b.color1, palette: p)
swatchRow("Color 2", selected: b.color2, palette: p)
}
sliderLine("Sensitivity", value: b.sensitivity, in: 0.4...2.5, palette: p)
sliderLine("Glow", value: b.glow, in: 0...1, palette: p)
// Density is an Int in the model; the slider drags a Double and rounds,
// clamping only the DISPLAYED value (Dart value.clamp) so an out-of-UI-
// range persisted density survives until the user actually drags.
sliderLine(
"Density (bars / orbit)",
value: Binding(
get: { Double(b.wrappedValue.density) },
set: { b.wrappedValue.density = Int($0.rounded()) }),
in: 16...160, palette: p)
if style == .bars {
toggleLine("Mirror bars from center", isOn: b.mirror, palette: p)
}
}
}
private func toggleLine(_ title: String, isOn: Binding<Bool>, palette p: RwPalette) -> some View {
// The library switch lays out label · spacer · track itself, and the
// title becomes the switch's VoiceOver label (it was an empty "").
Toggle(isOn: isOn) {
Text(title)
.rw(.bodySmall)
}
.toggleStyle(.rwSwitch)
}
private func sliderLine(
_ label: String, value: Binding<Double>, in range: ClosedRange<Double>, palette p: RwPalette
) -> some View {
HStack(spacing: RwSizes.gap) {
// Dart's SizedBox(width: 130) label column.
Text(label)
.rw(.bodySmall)
.frame(width: 130, alignment: .leading)
// The library slider commits continuously, so the visualizer reacts
// while dragging.
RwSlider(
value: Binding(
get: { min(max(value.wrappedValue, range.lowerBound), range.upperBound) },
set: { value.wrappedValue = $0 }),
in: range)
}
}
/// The 10 fixed 24px swatches; selected = 3px onSurface-equivalent border
/// vs 1px outlineVariant-equivalent. Square, unlike the Dart circles: the
/// house style is square everywhere (only knobs and radio glyphs stay
/// round), and a swatch is a control, not a knob.
private func swatchRow(
_ label: String, selected: Binding<UInt32>, palette p: RwPalette
) -> some View {
HStack(alignment: .center, spacing: RwSizes.gap) {
Text(label)
.rw(.bodySmall)
.frame(width: 62, alignment: .leading)
LazyVGrid(
columns: [GridItem(.adaptive(minimum: 24), spacing: 6)], alignment: .leading, spacing: 6
) {
ForEach(kVizSwatches, id: \.self) { c in
let sel = c == selected.wrappedValue
Button {
selected.wrappedValue = c
} label: {
Rectangle()
.fill(RwColor(c).color)
.frame(width: 24, height: 24)
.overlay(
Rectangle().stroke(sel ? p.text : p.hairStrong, lineWidth: sel ? 3 : 1))
}
.buttonStyle(.plain)
}
}
}
}
}