Skip to main content

egui_pop_core/
param.rs

1//! A parameter widget: the editor a value descriptor calls for, in any
2//! of the three binding modes (ADR 0009). A float or an int is a
3//! [`Slider`], or a [`NumberInput`] when its range is too wide to slide
4//! ([`crate::number::is_wide`]), a bool a check box, a choice a
5//! drop-down, three or four floats in `[0, 1]` a colour swatch, a text a
6//! field; every editor is named by the descriptor's label.
7//!
8//! ```
9//! use egui_pop_core::param::{self, Mode};
10//! use egui_pop_model::values::{Descriptor, Value};
11//!
12//! fn gain(ui: &mut egui::Ui, store: &egui_pop_core::binding::SharedStore, local: &mut Value) {
13//!     let d = Descriptor::float("Gain", 0.0, 2.0, 1.0);
14//!     param::param(ui, &d, Mode::Plain(local));
15//!     param::param(ui, &d, Mode::Bound(store, "params/gain"));
16//!     param::param(ui, &d, Mode::Watch(store, "params/gain"));
17//!     // Bound, the descriptor the path was declared with.
18//!     param::bound(ui, store, "params/gain");
19//! }
20//! ```
21
22use egui::{Response, Ui};
23use egui_pop_model::values::{Descriptor, Type, Value};
24
25use crate::binding::{self, Bindable, Binding, Choice, SharedStore};
26use crate::number::NumberInput;
27use crate::slider::Slider;
28use crate::ui::UiPop as _;
29use crate::widgets;
30
31/// Where the value is.
32#[derive(Debug)]
33pub enum Mode<'a> {
34    /// The caller's value.
35    Plain(&'a mut Value),
36    /// A store's path, read and written as the user.
37    Bound(&'a SharedStore, &'a str),
38    /// A store's path, shown only.
39    Watch(&'a SharedStore, &'a str),
40}
41
42fn with<T: Bindable>(
43    ui: &mut Ui,
44    mode: Mode<'_>,
45    widget: impl FnOnce(&mut Ui, &mut T) -> Response,
46) -> Response {
47    match mode {
48        Mode::Plain(v) => {
49            let mut t = T::from_value(v).unwrap_or_default();
50            let before = t.clone();
51            let r = widget(ui, &mut t);
52            if t != before {
53                *v = t.to_value();
54            }
55            r
56        }
57        Mode::Bound(store, path) => binding::edit(ui, Binding::bound(store, path), widget),
58        Mode::Watch(store, path) => binding::edit(ui, Binding::watch(store, path), widget),
59    }
60}
61
62/// A label, then `add`'s widget named by it.
63fn labelled(ui: &mut Ui, label: &str, add: impl FnOnce(&mut Ui) -> Response) -> Response {
64    ui.horizontal(|ui| {
65        let l = ui.label(label);
66        add(ui).labelled_by(l.id)
67    })
68    .inner
69}
70
71/// Whether a descriptor is a colour: three or four floats in `[0, 1]`.
72pub fn is_colour(d: &Descriptor) -> bool {
73    d.ty == Type::Floats
74        && matches!(d.count, Some(3 | 4))
75        && d.hard.is_some_and(|(lo, hi)| lo >= 0.0 && hi <= 1.0)
76}
77
78/// Draws the editor `d` calls for.
79pub fn param(ui: &mut Ui, d: &Descriptor, mode: Mode<'_>) -> Response {
80    param_shown(ui, d, mode, &|c| c.to_string())
81}
82
83/// The editor for a store's path, bound to it ([`Mode::Bound`]), its
84/// descriptor read from the store: the one the path was declared with.
85/// A path nobody declared shows as a warning, named by the path.
86///
87/// ```no_run
88/// use egui_pop_core::param;
89/// use egui_pop_model::ids::OwnerId;
90/// use egui_pop_model::values::{Descriptor, Store};
91///
92/// let mut store = Store::new();
93/// let d = Descriptor::float("Gain", 0.0, 2.0, 1.0);
94/// store.declare(&OwnerId::from_static("demo"), "params/gain", d).unwrap();
95/// let store = std::sync::Arc::new(std::sync::Mutex::new(store));
96/// let ctx = egui::Context::default();
97/// let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
98///     param::bound(ui, &store, "params/gain");
99/// });
100/// ```
101pub fn bound(ui: &mut Ui, store: &SharedStore, path: &str) -> Response {
102    let descriptor = crate::lock(store).get(path).map(|e| e.descriptor.clone());
103    match descriptor {
104        Some(d) => param(ui, &d, Mode::Bound(store, path)),
105        None => ui.label(format!("{path}: not declared")),
106    }
107}
108
109/// As [`param`], a choice's values shown through `shown` (a translation:
110/// `strings::setting_choice`); the value kept is the raw one.
111pub fn param_shown(
112    ui: &mut Ui,
113    d: &Descriptor,
114    mode: Mode<'_>,
115    shown: &dyn Fn(&str) -> String,
116) -> Response {
117    match d.ty {
118        // A range too wide for a slider: typed, with arrows.
119        Type::Float if crate::number::is_wide(d) => labelled(ui, &d.label, |ui| {
120            with(ui, mode, |ui, v: &mut f64| {
121                NumberInput::from_descriptor(v, d).show(ui)
122            })
123        }),
124        Type::Int if crate::number::is_wide(d) => labelled(ui, &d.label, |ui| {
125            with(ui, mode, |ui, v: &mut i64| {
126                let mut f = *v as f64;
127                let r = NumberInput::from_descriptor(&mut f, d).show(ui);
128                *v = f.round() as i64;
129                r
130            })
131        }),
132        Type::Float => with(ui, mode, |ui, v: &mut f64| {
133            ui.add(Slider::from_descriptor(v, d))
134        }),
135        Type::Int => with(ui, mode, |ui, v: &mut i64| {
136            let mut f = *v as f64;
137            let r = ui.add(Slider::from_descriptor(&mut f, d).integer());
138            *v = f.round() as i64;
139            r
140        }),
141        Type::Bool => with(ui, mode, |ui, v: &mut bool| {
142            widgets::checkbox(ui, v, &d.label)
143        }),
144        Type::Choice => labelled(ui, &d.label, |ui| {
145            with(ui, mode, |ui, v: &mut Choice| {
146                let mut picked = v.0.clone();
147                let combo =
148                    widgets::combo_box(("egui_pop.param", &d.label)).selected_text(shown(&picked));
149                let r = ui
150                    .combo_box(combo, |ui| {
151                        for c in &d.choices {
152                            widgets::selectable_value(ui, &mut picked, c.clone(), shown(c));
153                        }
154                    })
155                    .response;
156                crate::a11y::input(ui.ctx(), r.id, &d.label);
157                if picked != v.0 {
158                    v.0 = picked;
159                }
160                r
161            })
162        }),
163        Type::Floats if is_colour(d) => labelled(ui, &d.label, |ui| {
164            with(ui, mode, |ui, v: &mut Vec<f64>| {
165                v.resize(d.count.unwrap_or(3) as usize, 1.0);
166                let before = [v[0] as f32, v[1] as f32, v[2] as f32];
167                let mut rgb = before;
168                let r = ui.color_edit_button_rgb(&mut rgb);
169                // Only an edit goes back: egui's colour round trip moves
170                // the last bits of an untouched value.
171                if r.changed() && rgb != before {
172                    for (i, c) in rgb.iter().enumerate() {
173                        v[i] = f64::from(*c);
174                    }
175                }
176                r
177            })
178        }),
179        Type::Text => labelled(ui, &d.label, |ui| {
180            with(ui, mode, |ui, v: &mut String| {
181                // A secret is typed masked, and its accessibility value
182                // is masked too: it never shows on screen or in the tree.
183                let r = ui.add(egui::TextEdit::singleline(v).password(d.sensitive));
184                crate::focus_mode::follow_pointer(&r);
185                r
186            })
187        }),
188        Type::Floats | Type::Ints => labelled(ui, &d.label, |ui| {
189            let shown = match mode {
190                Mode::Plain(v) => v.to_json().to_string(),
191                Mode::Bound(s, p) | Mode::Watch(s, p) => crate::lock(s)
192                    .get(p)
193                    .map(|e| e.value.to_json().to_string())
194                    .unwrap_or_default(),
195            };
196            ui.monospace(shown)
197        }),
198    }
199}
200
201/// The value a mode holds now (for display beside the editor).
202pub fn current(mode: &Mode<'_>) -> Option<Value> {
203    match mode {
204        Mode::Plain(v) => Some((**v).clone()),
205        Mode::Bound(s, p) | Mode::Watch(s, p) => crate::lock(s).get(p).map(|e| e.value.clone()),
206    }
207}