|
| 1 | +use crate::{ |
| 2 | + midi, |
| 3 | + server::MidiChannelUdp, |
| 4 | + widget::{ByTitle, Widget}, |
| 5 | +}; |
| 6 | +use caw_core::{Buf, Sig, SigShared, SigT}; |
| 7 | +use caw_midi::{MidiController01, MidiMessagesT}; |
| 8 | +use lazy_static::lazy_static; |
| 9 | + |
| 10 | +pub struct Knob { |
| 11 | + sig: Sig<MidiController01<MidiChannelUdp>>, |
| 12 | +} |
| 13 | + |
| 14 | +lazy_static! { |
| 15 | + // Used to prevent multiple windows from opening at the same time with the same name. Note that |
| 16 | + // when using with evcxr this seems to get cleared when a cell is recomputed, but this is still |
| 17 | + // valuable in the context of stereo signals, where a function is evaluated once for the left |
| 18 | + // channel and once for the right channel. In such a case, this prevents each knob openned by |
| 19 | + // that function from being openned twice. |
| 20 | + static ref BY_TITLE: ByTitle<Knob> = Default::default(); |
| 21 | +} |
| 22 | + |
| 23 | +impl Knob { |
| 24 | + pub fn new( |
| 25 | + title: String, |
| 26 | + initial_value_01: f32, |
| 27 | + sensitivity: f32, |
| 28 | + ) -> Sig<SigShared<Self>> { |
| 29 | + BY_TITLE.get_or_insert(title.as_str(), || { |
| 30 | + let channel = midi::alloc_channel(); |
| 31 | + let controller = midi::alloc_controller(channel); |
| 32 | + let widget = Widget::new( |
| 33 | + title.clone(), |
| 34 | + channel, |
| 35 | + "knob", |
| 36 | + vec![ |
| 37 | + format!("--controller={}", controller), |
| 38 | + format!("--initial-value={}", initial_value_01), |
| 39 | + format!("--sensitivity={}", sensitivity), |
| 40 | + ], |
| 41 | + ) |
| 42 | + .unwrap(); |
| 43 | + let sig = widget |
| 44 | + .channel() |
| 45 | + .controllers() |
| 46 | + .get_with_initial_value_01(controller.into(), initial_value_01); |
| 47 | + Self { sig } |
| 48 | + }) |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +impl SigT for Knob { |
| 53 | + type Item = f32; |
| 54 | + |
| 55 | + fn sample(&mut self, ctx: &caw_core::SigCtx) -> impl Buf<Self::Item> { |
| 56 | + self.sig.sample(ctx) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +mod knob_builder { |
| 61 | + use super::Knob; |
| 62 | + use caw_builder_proc_macros::builder; |
| 63 | + use caw_core::{Sig, SigShared}; |
| 64 | + |
| 65 | + builder! { |
| 66 | + #[constructor = "knob_"] |
| 67 | + #[constructor_doc = "A visual knob in a new window"] |
| 68 | + #[generic_setter_type_name = "X"] |
| 69 | + #[build_fn = "Knob::new"] |
| 70 | + #[build_ty = "Sig<SigShared<Knob>>"] |
| 71 | + pub struct Props { |
| 72 | + title: String, |
| 73 | + #[default = 0.5] |
| 74 | + initial_value_01: f32, |
| 75 | + #[default = 0.2] |
| 76 | + sensitivity: f32, |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + pub fn knob(title: impl Into<String>) -> Props { |
| 81 | + knob_(title.into()) |
| 82 | + } |
| 83 | +} |
| 84 | + |
| 85 | +pub use knob_builder::knob; |
0 commit comments