Skip to main content

egui_pop_api/
group.rs

1//! One undo step for many writes: [`AppHandle::group`] (and
2//! [`Call::group`] in a command) opens a history group through the host
3//! ([`Host::begin_group`](crate::host::Host::begin_group)), runs a
4//! closure, and ends the group when the closure succeeds or cancels it
5//! (every write put back) when it fails or panics.
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! The group goes through the host, so a host keeping its own history
11//! sees it. While the host dispatches a command it is out of reach; a
12//! command's group then goes through the host's
13//! [`Host::groups`](crate::host::Host::groups), or the store's groups
14//! when the host gives none.
15//!
16//! ```
17//! use egui_pop_api::{App, Ctx, Plugin, PluginError};
18//! use egui_pop_model::commands::{CommandSpec, Origin};
19//! use egui_pop_model::ids::{CommandId, PluginId};
20//! use egui_pop_model::values::{Change, Descriptor, Value};
21//!
22//! const RESET: CommandId = CommandId::from_static("swatch.reset");
23//!
24//! struct Swatch;
25//! impl Plugin for Swatch {
26//!     fn id(&self) -> PluginId { PluginId::from_static("swatch") }
27//!     fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
28//!         ctx.value("swatch/hue", Descriptor::float("Hue", 0.0, 360.0, 200.0))?;
29//!         ctx.value("swatch/size", Descriptor::float("Size", 40.0, 300.0, 160.0))?;
30//!         ctx.command(CommandSpec::new(RESET, "Reset", "Swatch"), |call| {
31//!             call.group("Reset the swatch", |g| {
32//!                 g.set("swatch/hue", Change::Reset)?;
33//!                 g.set("swatch/size", Change::Reset)?;
34//!                 Ok(serde_json::Value::Null)
35//!             })
36//!         })?;
37//!         Ok(())
38//!     }
39//! }
40//!
41//! let mut app = App::builder().plugin(Swatch).build(&egui::Context::default()).unwrap();
42//! let h = app.handle().clone();
43//! h.group(&Origin::User, "Move", |g| {
44//!     g.set("swatch/hue", Change::To(Value::Float(30.0)))?;
45//!     g.set("swatch/size", Change::To(Value::Float(80.0)))
46//! }).unwrap();
47//! app.run(&RESET, serde_json::Value::Null, Origin::User);
48//! assert_eq!(h.value::<f64>("swatch/hue"), Some(200.0));
49//! let store = h.store();
50//! let steps = egui_pop_core::lock(&store).undo_steps().to_vec();
51//! assert_eq!(steps.iter().map(|s| s.label.as_str()).collect::<Vec<_>>(), ["Move", "Reset the swatch"]);
52//! ```
53
54use std::fmt;
55use std::rc::Rc;
56
57use egui_pop_core::lock;
58use egui_pop_model::commands::Origin;
59use egui_pop_model::values::{Applied, Change, GestureId, Refused, Set};
60
61use crate::app::{AppHandle, Call};
62use crate::host::Groups;
63
64/// What opened a group, so the same one closes it.
65enum Route {
66    Host,
67    Groups(Rc<dyn Groups>),
68    Store,
69}
70
71/// A history group being written: what is written through it until the
72/// closure returns is one undo step, labelled and with its origin.
73pub struct Group<'a> {
74    app: &'a AppHandle,
75    origin: Origin,
76    gesture: Option<GestureId>,
77}
78
79impl fmt::Debug for Group<'_> {
80    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
81        f.debug_struct("Group")
82            .field("origin", &self.origin)
83            .field("gesture", &self.gesture)
84            .finish_non_exhaustive()
85    }
86}
87
88impl Group<'_> {
89    /// The group's gesture, to carry on writes made elsewhere
90    /// (`Set::gesture`); `None` when the host groups nothing. With a host
91    /// keeping its own history, it is that history's: writes to the
92    /// host's own values carry it.
93    pub fn gesture(&self) -> Option<GestureId> {
94        self.gesture
95    }
96
97    /// Who the group writes as.
98    pub fn origin(&self) -> &Origin {
99        &self.origin
100    }
101
102    /// Writes `change` to `path` in the value store, in the group, as
103    /// its origin.
104    pub fn set(&self, path: &str, change: Change) -> Result<Applied, Refused> {
105        self.write(Set::new(path, change, self.origin.clone()))
106    }
107
108    /// Writes `set` to the value store, in the group (its gesture added).
109    pub fn write(&self, set: Set) -> Result<Applied, Refused> {
110        let set = match self.gesture {
111            Some(g) => set.gesture(g),
112            None => set,
113        };
114        lock(&self.app.store()).set(set)
115    }
116}
117
118/// Closes the group: kept when `done` was set, put back otherwise (an
119/// error or a panic in the closure).
120struct Open<'a> {
121    app: &'a AppHandle,
122    route: Option<Route>,
123    gesture: Option<GestureId>,
124    keep: bool,
125}
126
127impl Drop for Open<'_> {
128    fn drop(&mut self) {
129        if let (Some(route), Some(g)) = (self.route.take(), self.gesture) {
130            self.app.end_group_by(route, g, self.keep);
131        }
132    }
133}
134
135impl AppHandle {
136    /// Runs `f` in a history group labelled `label`: its writes are one
137    /// undo step, written as `origin`. The group is ended when `f`
138    /// returns `Ok`, cancelled (its writes put back) when it returns
139    /// `Err` or panics. It goes through the host
140    /// ([`Host::begin_group`](crate::host::Host::begin_group)), or, from
141    /// inside a command, through [`Host::groups`](crate::host::Host::groups).
142    pub fn group<R, E>(
143        &self,
144        origin: &Origin,
145        label: &str,
146        f: impl FnOnce(&Group<'_>) -> Result<R, E>,
147    ) -> Result<R, E> {
148        let (route, gesture) = self.begin_group_by(origin, label);
149        let mut open = Open {
150            app: self,
151            route: Some(route),
152            gesture,
153            keep: false,
154        };
155        let group = Group {
156            app: self,
157            origin: origin.clone(),
158            gesture,
159        };
160        let out = f(&group);
161        open.keep = out.is_ok();
162        drop(open);
163        out
164    }
165
166    fn begin_group_by(&self, origin: &Origin, label: &str) -> (Route, Option<GestureId>) {
167        if let Some(g) = self.with_host_mut(|h| h.begin_group(origin, label)) {
168            return (Route::Host, g);
169        }
170        // The host is dispatching (a command's handler runs).
171        if let Some(groups) = self.dispatch_groups() {
172            let g = groups.begin(origin, label);
173            return (Route::Groups(groups), g);
174        }
175        let g = lock(&self.store()).begin_group(origin.clone(), label);
176        (Route::Store, Some(g))
177    }
178
179    fn end_group_by(&self, route: Route, group: GestureId, keep: bool) {
180        let end_in_store = |app: &AppHandle| {
181            let store = app.store();
182            let mut s = lock(&store);
183            if keep {
184                s.end(group);
185            } else {
186                s.cancel(group);
187            }
188        };
189        match route {
190            Route::Host => {
191                if self.with_host_mut(|h| h.end_group(group, keep)).is_none() {
192                    // Opened through the host, closed while it dispatches:
193                    // the store's own group is the default's.
194                    end_in_store(self);
195                }
196            }
197            Route::Groups(groups) => groups.end(group, keep),
198            Route::Store => end_in_store(self),
199        }
200    }
201}
202
203impl Call<'_> {
204    /// Runs `f` in a history group labelled `label`, as the command's
205    /// caller: [`AppHandle::group`] with this call's origin.
206    pub fn group<R, E>(
207        &self,
208        label: &str,
209        f: impl FnOnce(&Group<'_>) -> Result<R, E>,
210    ) -> Result<R, E> {
211        self.app.group(self.origin, label, f)
212    }
213}