Skip to main content

egui_pop_core/
binding.rs

1//! Three ways to bind a widget's value (ADR 0009): plain `&mut T` as in
2//! egui, bound to a value store (writes with an origin, a drag is one
3//! gesture, listeners told), or watch-only.
4//!
5//! ```
6//! use std::sync::{Arc, Mutex};
7//! use egui_pop_core::binding::{self, Binding};
8//! use egui_pop_model::ids::OwnerId;
9//! use egui_pop_model::values::{Descriptor, Store};
10//!
11//! let store = Arc::new(Mutex::new(Store::new()));
12//! store.lock().unwrap()
13//!     .declare(&OwnerId::FRAMEWORK, "settings/volume", Descriptor::float("Volume", 0.0, 1.0, 0.5))
14//!     .unwrap();
15//!
16//! fn draw(ui: &mut egui::Ui, store: &binding::SharedStore, local: &mut f64) {
17//!     // As in egui:
18//!     binding::edit(ui, Binding::plain(local), |ui, v| ui.add(egui::Slider::new(v, 0.0..=1.0)));
19//!     // Bound to the store:
20//!     binding::edit(ui, Binding::bound(store, "settings/volume"), |ui, v: &mut f64| {
21//!         ui.add(egui::Slider::new(v, 0.0..=1.0))
22//!     });
23//!     // Shown, never written:
24//!     binding::edit(ui, Binding::watch(store, "settings/volume"), |ui, v: &mut f64| {
25//!         ui.add(egui::Slider::new(v, 0.0..=1.0))
26//!     });
27//! }
28//! ```
29
30use std::sync::{Arc, Mutex};
31
32use egui::{Id, Response, Ui};
33use egui_pop_model::commands::Origin;
34use egui_pop_model::ids::OwnerId;
35use egui_pop_model::values::{Change, GestureId, Set, Store, Value};
36
37use crate::state::{Slot, lock, shared};
38use crate::strings::{self, HELD_BY, NO_VALUE, READ_ONLY};
39
40/// A store shared between the application, its widgets and its commands.
41pub type SharedStore = Arc<Mutex<Store>>;
42
43/// A type a widget edits that the store can hold.
44pub trait Bindable: Clone + PartialEq + Default {
45    fn from_value(value: &Value) -> Option<Self>;
46    fn to_value(&self) -> Value;
47}
48
49impl Bindable for f64 {
50    fn from_value(v: &Value) -> Option<Self> {
51        v.as_f64()
52    }
53    fn to_value(&self) -> Value {
54        Value::Float(*self)
55    }
56}
57
58impl Bindable for f32 {
59    fn from_value(v: &Value) -> Option<Self> {
60        v.as_f64().map(|v| v as f32)
61    }
62    fn to_value(&self) -> Value {
63        Value::Float(*self as f64)
64    }
65}
66
67impl Bindable for i64 {
68    fn from_value(v: &Value) -> Option<Self> {
69        v.as_i64().or_else(|| v.as_f64().map(|f| f.round() as i64))
70    }
71    fn to_value(&self) -> Value {
72        Value::Int(*self)
73    }
74}
75
76impl Bindable for i32 {
77    fn from_value(v: &Value) -> Option<Self> {
78        i64::from_value(v).map(|v| v as i32)
79    }
80    fn to_value(&self) -> Value {
81        Value::Int(*self as i64)
82    }
83}
84
85impl Bindable for bool {
86    fn from_value(v: &Value) -> Option<Self> {
87        v.as_bool()
88    }
89    fn to_value(&self) -> Value {
90        Value::Bool(*self)
91    }
92}
93
94impl Bindable for String {
95    fn from_value(v: &Value) -> Option<Self> {
96        v.as_text().map(str::to_string)
97    }
98    fn to_value(&self) -> Value {
99        Value::Text(self.clone())
100    }
101}
102
103/// How a widget's value is held.
104#[derive(Debug)]
105pub enum Binding<'a, T> {
106    /// The caller's value, as in egui.
107    Plain(&'a mut T),
108    /// A path of a store, read and written.
109    Bound {
110        store: &'a SharedStore,
111        path: &'a str,
112    },
113    /// A path of a store, read only.
114    Watch {
115        store: &'a SharedStore,
116        path: &'a str,
117    },
118}
119
120impl<'a, T> Binding<'a, T> {
121    pub fn plain(value: &'a mut T) -> Self {
122        Binding::Plain(value)
123    }
124
125    pub fn bound(store: &'a SharedStore, path: &'a str) -> Self {
126        Binding::Bound { store, path }
127    }
128
129    pub fn watch(store: &'a SharedStore, path: &'a str) -> Self {
130        Binding::Watch { store, path }
131    }
132}
133
134/// A bound widget's gesture in the store, per widget.
135const GESTURE: Slot<u64> = Slot::new("core.binding.gesture");
136/// The widget gave its gesture up, per widget.
137const CANCELLED: Slot<bool> = Slot::new("core.binding.cancelled");
138/// Why the store refused the widget's last write, per widget.
139const REFUSED: Slot<String> = Slot::new("core.binding.refused");
140
141/// Tells the binding around a widget that its gesture is given up (the
142/// widget has put its value back): bound to a store, the gesture's
143/// writes are undone and leave no undo step.
144pub fn cancel_gesture(ctx: &egui::Context, response_id: Id) {
145    CANCELLED.keyed(response_id).set(ctx, true);
146}
147
148/// A bound widget's gesture still open: its window, its widget, its
149/// store and the gesture in it.
150struct OpenGesture {
151    window: egui::ViewportId,
152    widget: Id,
153    store: SharedStore,
154    gesture: GestureId,
155}
156
157impl std::fmt::Debug for OpenGesture {
158    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
159        f.debug_struct("OpenGesture")
160            .field("window", &self.window)
161            .field("widget", &self.widget)
162            .field("gesture", &self.gesture)
163            .finish_non_exhaustive()
164    }
165}
166
167/// The bound widgets' gestures still open, and whether the end of pass
168/// that cancels the orphans is registered.
169#[derive(Debug, Default)]
170struct Open {
171    gestures: Vec<OpenGesture>,
172    registered: bool,
173}
174
175fn open_gestures(ctx: &egui::Context) -> Arc<Mutex<Open>> {
176    shared::<Open>(ctx, "core.binding.open")
177}
178
179/// Notes a gesture opened by a bound widget, so that it is cancelled if
180/// the widget goes away with it open.
181fn opened(ctx: &egui::Context, widget: Id, store: &SharedStore, gesture: GestureId) {
182    let st = open_gestures(ctx);
183    let mut open = lock(&st);
184    open.gestures.retain(|g| g.widget != widget);
185    open.gestures.push(OpenGesture {
186        window: ctx.viewport_id(),
187        widget,
188        store: Arc::clone(store),
189        gesture,
190    });
191    if !open.registered {
192        open.registered = true;
193        ctx.on_end_pass(
194            "egui_pop_core::binding",
195            Arc::new(|ui: &mut Ui| cancel_orphans(ui.ctx())),
196        );
197    }
198}
199
200/// The widget's gesture is over (ended or cancelled).
201fn closed(ctx: &egui::Context, widget: Id) {
202    lock(&open_gestures(ctx))
203        .gestures
204        .retain(|g| g.widget != widget);
205}
206
207/// At the end of a window's pass: a gesture whose widget was not drawn
208/// in it (its host closed, by its close button or a command, with the
209/// gesture open) is cancelled: the store puts its values back and no
210/// undo step is left, and egui's drag of the gone widget is stopped.
211fn cancel_orphans(ctx: &egui::Context) {
212    let window = ctx.viewport_id();
213    let orphans: Vec<OpenGesture> = {
214        let st = open_gestures(ctx);
215        let mut open = lock(&st);
216        let (gone, kept) = std::mem::take(&mut open.gestures)
217            .into_iter()
218            .partition(|g| {
219                g.window == window && !ctx.viewport(|v| v.this_pass.widgets.contains(g.widget))
220            });
221        open.gestures = kept;
222        gone
223    };
224    for g in orphans {
225        lock(&g.store).cancel(g.gesture);
226        GESTURE.keyed(g.widget).remove(ctx);
227        if ctx.dragged_id() == Some(g.widget) {
228            ctx.stop_dragging();
229        }
230        log::debug!(target: "egui_pop", "binding: the widget {:?} went away mid-gesture; gesture cancelled", g.widget);
231    }
232}
233
234/// Draws a widget over a binding. `widget` edits a local copy; what
235/// changed goes back as the binding says.
236///
237/// Bound to a store, a drag is one gesture. It is cancelled (the store
238/// puts the values back, no undo step is left) when the widget gives it
239/// up ([`cancel_gesture`]), when Escape ends the drag (see
240/// [`focus`](crate::focus#escape-in-order)), and when the widget is not
241/// drawn in a pass while it is open (its host closed mid-drag).
242pub fn edit<T: Bindable>(
243    ui: &mut Ui,
244    binding: Binding<'_, T>,
245    widget: impl FnOnce(&mut Ui, &mut T) -> Response,
246) -> Response {
247    match binding {
248        Binding::Plain(v) => widget(ui, v),
249        Binding::Watch { store, path } => {
250            let mut v = read(store, path).unwrap_or_default();
251            let r = ui.add_enabled_ui(false, |ui| widget(ui, &mut v)).inner;
252            r.on_disabled_hover_text(strings::tr(ui.ctx(), &READ_ONLY))
253        }
254        Binding::Bound { store, path } => {
255            let (current, held) = {
256                let s = lock(store);
257                match s.get(path) {
258                    Some(e) => (
259                        T::from_value(&e.value),
260                        s.held_by(path).filter(|o| **o != Origin::User).cloned(),
261                    ),
262                    None => (None, None),
263                }
264            };
265            let Some(mut v) = current else {
266                let mut dummy = T::default();
267                let r = ui.add_enabled_ui(false, |ui| widget(ui, &mut dummy)).inner;
268                log::warn!(target: "egui_pop", "binding to `{path}`: no such value (or not this type); the widget is disabled");
269                return r.on_disabled_hover_text(strings::tr_args(
270                    ui.ctx(),
271                    &NO_VALUE,
272                    &[("path", path)],
273                ));
274            };
275            let before = v.clone();
276            let mut r = widget(ui, &mut v);
277            let gid = GESTURE.keyed(r.id);
278            if r.drag_started() {
279                let g = lock(store).begin_gesture(Origin::User, &format!("drag {path}"));
280                gid.set(ui.ctx(), g.0);
281                opened(ui.ctx(), r.id, store, g);
282            }
283            let gesture = gid.get(ui.ctx()).map(GestureId);
284            let cancelled = CANCELLED.keyed(r.id).remove(ui.ctx()).unwrap_or(false)
285                || (r.drag_stopped() && crate::focus::escape_cancelled(ui.ctx()).is_some());
286            if cancelled {
287                // The widget gave the gesture up, or Escape ended the drag
288                // (an egui widget does not put its value back itself):
289                // the store puts the values back, no undo step is left.
290                if let Some(g) = gesture {
291                    lock(store).cancel(g);
292                    gid.remove(ui.ctx());
293                    closed(ui.ctx(), r.id);
294                }
295                return r;
296            }
297            if v != before {
298                // A person's edit: the framework writes it, whoever drew
299                // the widget.
300                let mut set =
301                    Set::new(path, Change::To(v.to_value()), Origin::User).by(&OwnerId::FRAMEWORK);
302                set.gesture = gesture;
303                let outcome = lock(store).set(set);
304                match outcome {
305                    Ok(_) => {
306                        REFUSED.keyed(r.id).remove(ui.ctx());
307                    }
308                    Err(refused) => {
309                        log::warn!(target: "egui_pop", "write to `{path}` refused: {refused}");
310                        REFUSED.keyed(r.id).set(ui.ctx(), refused.to_string());
311                    }
312                }
313            }
314            if r.drag_stopped()
315                && let Some(g) = gesture
316            {
317                lock(store).end(g);
318                gid.remove(ui.ctx());
319                closed(ui.ctx(), r.id);
320            }
321            if let Some(by) = held {
322                r = r.on_hover_text(strings::tr_args(
323                    ui.ctx(),
324                    &HELD_BY,
325                    &[("origin", &format!("{by:?}"))],
326                ));
327            }
328            if let Some(e) = REFUSED.keyed(r.id).get(ui.ctx()) {
329                r = r.on_hover_text(e);
330            }
331            r
332        }
333    }
334}
335
336/// Reads a path as a type.
337pub fn read<T: Bindable>(store: &SharedStore, path: &str) -> Option<T> {
338    lock(store).get(path).and_then(|e| T::from_value(&e.value))
339}
340
341/// One of a descriptor's choices, as a widget edits it (a `String` would
342/// be written as free text).
343#[derive(Clone, Debug, Default, PartialEq, Eq)]
344pub struct Choice(pub String);
345
346impl Bindable for Choice {
347    fn from_value(v: &Value) -> Option<Self> {
348        v.as_choice().map(|c| Choice(c.to_string()))
349    }
350    fn to_value(&self) -> Value {
351        Value::Choice(self.0.clone())
352    }
353}
354
355impl Bindable for Vec<f64> {
356    fn from_value(v: &Value) -> Option<Self> {
357        match v {
358            Value::Floats(f) => Some(f.clone()),
359            _ => None,
360        }
361    }
362    fn to_value(&self) -> Value {
363        Value::Floats(self.clone())
364    }
365}