Files

340 lines
12 KiB
Swift

// ParameterSlider.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(SwiftUI)
import SwiftUI
import LyrebirdSynth
/// A labelled continuous slider bound to a `UIParamNode`.
///
/// Changes flow through the node's atomic update path — RT-safe with no special handling.
///
/// ```swift
/// ParameterSlider("Amplitude", node: synth.$amplitude, range: 0.0...1.0)
/// ParameterSlider("Cutoff", node: synth.$cutoff, range: 20.0...20000.0, taper: .exponential)
/// ```
public struct ParameterSlider: View {
// MARK: - Taper
/// Value mapping applied between the slider's linear position and the parameter value.
public enum Taper {
/// No mapping — slider position maps directly to parameter value.
case linear
/// Exponential mapping — equal visual steps produce equal ratios (good for frequency, time).
case exponential
}
// MARK: - Properties
private let label: String
private let node: UIParamNode
private let range: ClosedRange<Double>
private let taper: Taper
/// Called once when a drag ends, with the value when the drag began and the final value. Set via
/// ``onEditingEnded(_:)``; lets a host record one edit per gesture (e.g. for undo).
private var onEditingEndedAction: ((Double, Double) -> Void)?
/// Value captured when a drag begins, so ``onEditingEnded(_:)`` can report `(previous, new)`.
@State private var dragStartValue: Double = 0
// MARK: - Init
/// Creates a slider bound to a `UIParamNode`.
///
/// - Parameters:
/// - label: Text displayed beside the slider.
/// - node: The `UIParamNode` to bind to (pass `synth.$paramName`).
/// - range: The minimum and maximum parameter values.
/// - taper: Value mapping. Default `.linear`.
public init(
_ label: String,
node: UIParamNode,
range: ClosedRange<Double>,
taper: Taper = .linear
) {
self.label = label
self.node = node
self.range = range
self.taper = taper
}
// MARK: - Body
public var body: some View {
HStack {
Text(label)
.frame(minWidth: 80, alignment: .leading)
Slider(value: binding, in: linearRange) { editing in
if editing {
dragStartValue = node.value
} else {
onEditingEndedAction?(dragStartValue, node.value)
}
}
Text(formattedValue)
.frame(minWidth: 60, alignment: .trailing)
.monospacedDigit()
}
}
// MARK: - Modifiers
/// Returns a copy of the slider that calls `action` each time a drag ends — once per gesture —
/// with the value when the drag began and the final value. Use it to record a single edit (for
/// example an undo checkpoint). Matches ``ParameterKnob/onEditingEnded(_:)``.
///
/// - Parameter action: Receives `(previousValue, newValue)`.
/// - Returns: A slider that reports the end of each edit.
public func onEditingEnded(_ action: @escaping (Double, Double) -> Void) -> ParameterSlider {
var copy: ParameterSlider = self
copy.onEditingEndedAction = action
return copy
}
// MARK: - Private helpers
/// Linear range always 0...1; taper mapping happens inside the Binding.
private var linearRange: ClosedRange<Double> { 0.0...1.0 }
private var binding: Binding<Double> {
Binding(
get: { toLinear(node.value) },
set: { node.update(fromLinear($0)) }
)
}
private func toLinear(_ value: Double) -> Double {
let lo: Double = range.lowerBound
let hi: Double = range.upperBound
// Degenerate range: avoid a 0/0 NaN thumb position.
guard hi > lo else { return 0 }
switch taper {
case .linear:
return (value - lo) / (hi - lo)
case .exponential:
guard lo > 0, hi > lo else { return (value - lo) / (hi - lo) }
return log(value / lo) / log(hi / lo)
}
}
private func fromLinear(_ position: Double) -> Double {
let lo: Double = range.lowerBound
let hi: Double = range.upperBound
switch taper {
case .linear:
return lo + position * (hi - lo)
case .exponential:
guard lo > 0, hi > lo else { return lo + position * (hi - lo) }
return lo * pow(hi / lo, position)
}
}
private var formattedValue: String {
let v: Double = node.value
if abs(v) >= 1000 {
return String(format: "%.0f", v)
} else if abs(v) >= 10 {
return String(format: "%.1f", v)
} else {
return String(format: "%.3f", v)
}
}
}
#else
// Linux/GTK4 counterpart to `LyrebirdUI.ParameterSlider`. Drawn on a `Canvas`
// with a `.onDrag` gesture — the same custom-drawn approach as
// `ParameterKnob` — rather than a native `Slider` (GtkScale). This is what
// lets a slider drag update the parameter on every motion event (like the knob
// and the macOS slider), and, crucially, lets the slider **track live** when a
// paired control bound to the same node is dragged: a Canvas closure reads
// `node.value` at paint time, so the GTK4 backend's per-drag redraw of every
// linked control repaints it in step. A native GtkScale, whose thumb position is
// pushed on rebuild (deferred during a drag), could only reconcile on release.
//
// Binds to a core `UIParamNode` (via `synth.$paramName`) with the same linear /
// exponential taper mapping the macOS slider uses. `BackendGTK4` carries the
// Cairo-backed `DrawingContext` drawing methods.
import SwiftOpenUI
import BackendGTK4
import LyrebirdSynth
import Foundation // log/pow for the exponential taper
/// A labelled continuous slider for the Linux/GTK4 UI, bound to a core
/// ``UIParamNode``. Mirrors `LyrebirdUI.ParameterSlider`: a leading label, a
/// horizontal Canvas-drawn track with a draggable thumb, and a trailing value
/// readout, with an optional exponential taper for ratio-based parameters
/// (frequency, time).
public struct ParameterSlider: View {
// MARK: - Taper
/// Value mapping applied between the slider's linear position and the
/// parameter value.
public enum Taper {
/// No mapping — slider position maps directly to parameter value.
case linear
/// Exponential mapping — equal visual steps produce equal ratios
/// (good for frequency, time).
case exponential
}
// MARK: - Properties
private let label: String
private let node: UIParamNode
private let range: ClosedRange<Double>
private let taper: Taper
// Layout constants (points), matching the macOS slider's proportions.
private let labelMinWidth: Double = 80
private let valueMinWidth: Double = 60
/// Track dimensions. The drag maps pointer x over this fixed width, so it
/// matches the Canvas's own size (`.frame(width: trackWidth, …)`).
private let trackWidth: Double = 160
private let trackHeight: Double = 24
/// Thumb radius; the usable track is inset by this so the thumb stays fully
/// visible at both ends.
private let thumbRadius: Double = 7
/// Called once when a drag ends, with the drag's start value and final value. Set via
/// ``onEditingEnded(_:)``; mirrors the macOS slider.
private var onEditingEndedAction: ((Double, Double) -> Void)?
// Drag origin, captured on the first `onChanged`.
@State private var dragStartValue: Double = 0
@State private var dragInProgress: Bool = false
// MARK: - Init
/// Creates a slider bound to a `UIParamNode`.
///
/// - Parameters:
/// - label: Text displayed beside the slider.
/// - node: The `UIParamNode` to bind to (pass `synth.$paramName`).
/// - range: The minimum and maximum parameter values.
/// - taper: Value mapping. Default `.linear`.
public init(
_ label: String,
node: UIParamNode,
range: ClosedRange<Double>,
taper: Taper = .linear
) {
self.label = label
self.node = node
self.range = range
self.taper = taper
}
// MARK: - Body
public var body: some View {
HStack {
Text(label)
.frame(minWidth: labelMinWidth, alignment: .leading)
Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
let w: Double = Double(size.width)
let h: Double = Double(size.height)
let cy: Double = h / 2
let x0: Double = thumbRadius
let x1: Double = w - thumbRadius
let usable: Double = max(x1 - x0, 1)
let pos: Double = toLinear(node.value)
let thumbX: Double = x0 + pos * usable
// Track background (full width).
ctx.setColor(r: 0.20, g: 0.20, b: 0.20)
ctx.setLineWidth(4)
ctx.moveTo(x: x0, y: cy)
ctx.lineTo(x: x1, y: cy)
ctx.stroke()
// Filled portion up to the thumb.
ctx.setColor(r: 0.30, g: 0.80, b: 1.0)
ctx.setLineWidth(4)
ctx.moveTo(x: x0, y: cy)
ctx.lineTo(x: thumbX, y: cy)
ctx.stroke()
// Thumb.
ctx.setColor(r: 0.90, g: 0.90, b: 0.95)
ctx.arc(centerX: thumbX, centerY: cy, radius: thumbRadius,
startAngle: 0, endAngle: 2 * Double.pi)
ctx.fill()
})
.frame(width: trackWidth, height: trackHeight)
.onDrag(
minimumDistance: 0,
onChanged: { (drag: DragGestureValue) in
if !dragInProgress {
dragInProgress = true
dragStartValue = node.value
}
// Absolute: the thumb follows the pointer x within the track.
let x0: Double = thumbRadius
let usable: Double = max(trackWidth - 2 * thumbRadius, 1)
let pos: Double = min(1, max(0, (drag.location.x - x0) / usable))
node.update(fromLinear(pos))
},
onEnded: { (_: DragGestureValue) in
dragInProgress = false
onEditingEndedAction?(dragStartValue, node.value)
}
)
Text(formattedValue)
.frame(minWidth: valueMinWidth, alignment: .trailing)
.monospacedDigit()
}
}
/// Returns a copy of the slider that calls `action` each time a drag ends — once per gesture —
/// with the drag's start value and final value. Mirrors the macOS slider's ``onEditingEnded(_:)``.
///
/// - Parameter action: Receives `(previousValue, newValue)`.
/// - Returns: A slider that reports the end of each edit.
public func onEditingEnded(_ action: @escaping (Double, Double) -> Void) -> ParameterSlider {
var copy: ParameterSlider = self
copy.onEditingEndedAction = action
return copy
}
// MARK: - Private helpers
private func toLinear(_ value: Double) -> Double {
let lo: Double = range.lowerBound
let hi: Double = range.upperBound
// Degenerate range: avoid a 0/0 NaN thumb position.
guard hi > lo else { return 0 }
switch taper {
case .linear:
return (value - lo) / (hi - lo)
case .exponential:
guard lo > 0, hi > lo else { return (value - lo) / (hi - lo) }
return log(value / lo) / log(hi / lo)
}
}
private func fromLinear(_ position: Double) -> Double {
let lo: Double = range.lowerBound
let hi: Double = range.upperBound
switch taper {
case .linear:
return lo + position * (hi - lo)
case .exponential:
guard lo > 0, hi > lo else { return lo + position * (hi - lo) }
return lo * pow(hi / lo, position)
}
}
private var formattedValue: String {
formattedParameterValue(node.value)
}
}
#endif