Files

294 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.
// ParameterKnob.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if canImport(SwiftUI)
import SwiftUI
import LyrebirdSynth
/// A rotary knob control bound to a `UIParamNode`.
///
/// Drag vertically to change value: drag up increases, drag down decreases.
/// Equivalent in behaviour to `ParameterSlider` — choose whichever fits the layout.
///
/// ```swift
/// ParameterKnob("Resonance", node: synth.$resonance, range: 0...1)
/// ```
public struct ParameterKnob: View {
// MARK: - Properties
private let label: String
private let node: UIParamNode
private let range: ClosedRange<Double>
/// Pixels of vertical drag that span the full parameter range. Default 200.
public var dragSensitivity: Double = 200
/// Called once when a drag gesture ends, with the value at the start of the drag and the final
/// value. Set via ``onEditingEnded(_:)``. Lets a host record a single edit per gesture (e.g. for
/// undo) rather than one per intermediate `node.update(_:)`.
private var onEditingEndedAction: ((Double, Double) -> Void)?
// MARK: - Private drag state
@State private var dragStartPosition: CGFloat = 0
@State private var dragStartValue: Double = 0
@State private var dragInProgress: Bool = false
// MARK: - Init
/// Creates a knob bound to a `UIParamNode`.
///
/// - Parameters:
/// - label: Text displayed below the knob.
/// - node: The `UIParamNode` to bind to (pass `synth.$paramName`).
/// - range: The minimum and maximum parameter values.
public init(
_ label: String,
node: UIParamNode,
range: ClosedRange<Double>
) {
self.label = label
self.node = node
self.range = range
}
// MARK: - Body
public var body: some View {
VStack(spacing: 4) {
knobDial
.frame(width: 50, height: 50) // matches dialSize constant inside knobDial
.gesture(dragGesture)
Text(label)
.font(.caption)
Text(formattedValue)
.font(.caption)
.monospacedDigit()
}
}
// MARK: - Knob dial drawing
private var knobDial: some View {
let normalised: Double = normalise(node.value)
// Rotation: -135° (fully CCW) to +135° (fully CW)
let startAngle: Double = -135.0
let totalArc: Double = 270.0
let rotation: Double = startAngle + normalised * totalArc
// Layout constants
let dialSize: CGFloat = 50
let indicatorWidth: CGFloat = 2
let indicatorHeight: CGFloat = 14
// Centre the indicator tip near the dial edge: dial radius − indicator height/2 − small inset
let indicatorInset: CGFloat = 3
let indicatorOffset: CGFloat = -(dialSize / 2 - indicatorHeight / 2 - indicatorInset)
return ZStack {
Circle()
.fill(Color.lyrebirdControlBackground)
.overlay(Circle().stroke(Color.lyrebirdSeparator, lineWidth: 1))
// Indicator line
Rectangle()
.fill(Color.accentColor)
.frame(width: indicatorWidth, height: indicatorHeight)
.offset(y: indicatorOffset)
.rotationEffect(.degrees(rotation))
}
}
// MARK: - Drag gesture
private var dragGesture: some Gesture {
DragGesture(minimumDistance: 1)
.onChanged { gesture in
if !dragInProgress {
// Capture drag origin on the first event. Using an explicit
// flag avoids a sentinel collision when the bound value is
// genuinely zero.
dragInProgress = true
dragStartPosition = gesture.location.y
dragStartValue = node.value
}
let delta: CGFloat = dragStartPosition - gesture.location.y // up = positive
let span: Double = range.upperBound - range.lowerBound
let change: Double = (Double(delta) / dragSensitivity) * span
let clamped: Double = min(max(dragStartValue + change, range.lowerBound), range.upperBound)
node.update(clamped)
}
.onEnded { _ in
let previousValue: Double = dragStartValue
dragInProgress = false
dragStartPosition = 0
dragStartValue = 0
onEditingEndedAction?(previousValue, node.value)
}
}
// MARK: - Modifiers
/// Returns a copy of the knob that calls `action` each time a drag gesture ends — once per
/// gesture, not per intermediate update — with the value at the start of the drag and the final
/// value. Use it to record a single edit (for example an undo checkpoint) when the user finishes
/// turning the knob.
///
/// - Parameter action: Receives `(previousValue, newValue)` — the knob's value when the drag
/// began and when it ended.
/// - Returns: A knob that reports the end of each edit.
public func onEditingEnded(_ action: @escaping (Double, Double) -> Void) -> ParameterKnob {
var copy: ParameterKnob = self
copy.onEditingEndedAction = action
return copy
}
// MARK: - Helpers
private func normalise(_ value: Double) -> Double {
let lo: Double = range.lowerBound
let hi: Double = range.upperBound
guard hi > lo else { return 0 }
return min(max((value - lo) / (hi - lo), 0), 1)
}
private var formattedValue: String {
formattedParameterValue(node.value)
}
}
#else
// Experimental Linux GUI, built only under `LYREBIRD_ENABLE_LINUX_UI=1`
// (see Package.swift). This is the first control ported from `LyrebirdUI`'s
// SwiftUI `ParameterKnob` to SwiftOpenUI's GTK4 surface: a rotary knob drawn
// with the Cairo-backed `DrawingContext` (SwiftOpenUI's stand-in for SwiftUI's
// `GraphicsContext`) and a `.onDrag` vertical drag-to-set.
//
// It binds to the same core `UIParamNode` the macOS `ParameterKnob` binds to,
// so a synthesizer's `@UIParam` drives both platforms from one model. Because
// `UIParamNode` is `@Observable`, a drag-driven `node.update(_:)` takes the
// GTK4 backend's narrow mutation (redraw-in-place) path carried by the pinned
// SwiftOpenUI fork, so the in-flight drag gesture survives and the knob tracks
// continuously.
//
// SwiftOpenUI + BackendGTK4 are always present in this target (see Package.swift),
// so no `canImport` guard is needed; `BackendGTK4` carries the Cairo-backed
// `DrawingContext` drawing methods (setColor/arc/moveTo/…), which are extensions
// not present in SwiftOpenUI's core.
import SwiftOpenUI
import BackendGTK4
import LyrebirdSynth
import Foundation
/// A rotary knob for the Linux/GTK4 UI, drawn on a `Canvas` and set by a
/// vertical drag. Binds to a core ``UIParamNode`` (via a synthesizer's
/// `@UIParam` projected value, `synth.$paramName`) — the same model the macOS
/// `ParameterKnob` uses. Mirrors that control's behaviour: −135°…+135° sweep,
/// drag-up increases.
public struct ParameterKnob: View {
private let label: String
private let node: UIParamNode
private let range: ClosedRange<Double>
/// Pixels of vertical drag spanning the full parameter range. Matches the
/// macOS knob's default.
public var dragSensitivity: Double = 200
/// Called once when a drag ends, with the drag's start value and final value. Set via
/// ``onEditingEnded(_:)``; mirrors the macOS knob so a host can record one edit per gesture.
private var onEditingEndedAction: ((Double, Double) -> Void)?
// Drag origin, captured on the first `onChanged` of each gesture. An
// explicit flag avoids a sentinel collision when the value is genuinely at
// the range's lower bound.
@State private var dragStartValue: Double = 0
@State private var dragInProgress: Bool = false
/// Creates a knob bound to a `UIParamNode`.
///
/// - Parameters:
/// - label: Text displayed below the knob.
/// - node: The `UIParamNode` to bind to (pass `synth.$paramName`).
/// - range: The minimum and maximum parameter values.
public init(
_ label: String,
node: UIParamNode,
range: ClosedRange<Double>
) {
self.label = label
self.node = node
self.range = range
}
public var body: some View {
VStack {
Canvas(renderer: { (ctx: DrawingContext, size: CGSize) in
let cx: Double = Double(size.width) / 2
let cy: Double = Double(size.height) / 2
let radius: Double = min(cx, cy) - 4
// Dial face ring.
ctx.setColor(r: 0.20, g: 0.20, b: 0.20)
ctx.setLineWidth(3)
ctx.arc(centerX: cx, centerY: cy, radius: radius,
startAngle: 0, endAngle: 2 * Double.pi)
ctx.stroke()
// Indicator: −135°…+135° sweep (270° total), like the macOS knob.
let startAngleRadians: Double = 0.75 * Double.pi
let sweepRadians: Double = 1.5 * Double.pi
let angle: Double = startAngleRadians + normalise(node.value) * sweepRadians
ctx.setColor(r: 0.30, g: 0.80, b: 1.0)
ctx.setLineWidth(3)
ctx.moveTo(x: cx, y: cy)
ctx.lineTo(x: cx + radius * cos(angle), y: cy + radius * sin(angle))
ctx.stroke()
})
.frame(width: 50, height: 50)
.onDrag(
minimumDistance: 0,
onChanged: { (drag: DragGestureValue) in
if !dragInProgress {
dragInProgress = true
dragStartValue = node.value
}
// Up (negative height) increases, matching the macOS knob.
let span: Double = range.upperBound - range.lowerBound
let change: Double = (-drag.height / dragSensitivity) * span
let target: Double = min(range.upperBound,
max(range.lowerBound, dragStartValue + change))
node.update(target)
},
onEnded: { (_: DragGestureValue) in
let previousValue: Double = dragStartValue
dragInProgress = false
onEditingEndedAction?(previousValue, node.value)
}
)
Text(label)
}
.padding()
}
/// Returns a copy of the knob that calls `action` each time a drag ends — once per gesture —
/// with the drag's start value and final value. Mirrors the macOS knob's ``onEditingEnded(_:)``.
///
/// - Parameter action: Receives `(previousValue, newValue)`.
/// - Returns: A knob that reports the end of each edit.
public func onEditingEnded(_ action: @escaping (Double, Double) -> Void) -> ParameterKnob {
var copy: ParameterKnob = self
copy.onEditingEndedAction = action
return copy
}
private func normalise(_ value: Double) -> Double {
let lo: Double = range.lowerBound
let hi: Double = range.upperBound
guard hi > lo else { return 0 }
return min(max((value - lo) / (hi - lo), 0), 1)
}
}
#endif