Skip to main content

egui_pop_model/
panels.rs

1//! Panels are declared, never hard-coded: a plugin or the shell says what
2//! a panel is and where it goes by default; the shell places it, saves
3//! where the user moved it, and offers its commands.
4
5use serde::{Deserialize, Serialize};
6
7use crate::ids::{CommandId, OwnerId, PanelId};
8use crate::mount::{self, HostOffer, Mountable};
9use crate::registry::Registry;
10
11/// The shell's areas. Start and end, not left and right: ready for
12/// right-to-left layouts.
13#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum Area {
16    /// The centre: editors, tabbed and splittable.
17    Center,
18    /// The side bar at the start (left in left-to-right).
19    StartSide,
20    /// The side bar at the end.
21    EndSide,
22    Bottom,
23}
24
25impl Area {
26    pub const ALL: [Area; 4] = [Area::Center, Area::StartSide, Area::EndSide, Area::Bottom];
27
28    /// As people call it.
29    pub fn name(self) -> &'static str {
30        match self {
31            Area::Center => "the centre",
32            Area::StartSide => "the start side bar",
33            Area::EndSide => "the end side bar",
34            Area::Bottom => "the bottom panel",
35        }
36    }
37}
38
39/// What a panel does to what the application edits (a document, a
40/// photo): shows it, edits it, or shows it with parts that edit it. The
41/// application declares it ([`PanelSpec::kind`]); the panel's chrome
42/// shows an "edits" mark for a control or mixed panel, never the panel.
43#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
44#[serde(rename_all = "snake_case")]
45pub enum PanelKind {
46    /// It only shows, or moves what is shown (pan, zoom, selection):
47    /// nothing it does is an edit.
48    #[default]
49    View,
50    /// Its purpose is editing (parameters, a node graph, masks).
51    Control,
52    /// A view with parts that edit (a histogram dragged to change the
53    /// exposure).
54    Mixed,
55}
56
57impl PanelKind {
58    pub const ALL: [PanelKind; 3] = [PanelKind::View, PanelKind::Control, PanelKind::Mixed];
59
60    /// As the bus and agents write it (`control`).
61    pub fn as_str(self) -> &'static str {
62        match self {
63            PanelKind::View => "view",
64            PanelKind::Control => "control",
65            PanelKind::Mixed => "mixed",
66        }
67    }
68
69    /// Whether it edits, wholly or in part: its chrome shows the mark.
70    pub fn edits(self) -> bool {
71        self != PanelKind::View
72    }
73}
74
75/// How many of a panel may be open at once ([`PanelSpec::instances`]).
76#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
77#[serde(rename_all = "snake_case")]
78pub enum Instances {
79    /// One: the panel declared (Settings, an import window).
80    #[default]
81    Single,
82    /// As many as asked: the panel declared is instance 1, each new one
83    /// `<id>#<n>` (a second gallery, another quick collection), drawn by
84    /// the panel's one draw function, with a payload of its own kept in
85    /// the layout (`Layout::instances`).
86    Multiple,
87}
88
89/// A panel as declared: its id, title, areas, sizes, and whether it opens
90/// once or as many times as asked ([`PanelSpec::instances`]).
91///
92/// Need (layout): a panel opened several times at once, each instance with its own state.
93#[derive(Clone, Debug, PartialEq, Serialize)]
94pub struct PanelSpec {
95    pub id: PanelId,
96    pub title: String,
97    /// Its default area.
98    pub area: Area,
99    /// The areas it may be moved to besides `area`; empty: any area.
100    pub areas: Vec<Area>,
101    /// Command ids the panel contributes (its toggle and focus commands
102    /// are added by the shell).
103    pub commands: Vec<CommandId>,
104    /// The smallest size it may be given across its area (a side bar's
105    /// width, the bottom panel's height), in points.
106    pub min_size: f32,
107    /// The size it asks for across its area when it opens there.
108    pub default_size: Option<f32>,
109    /// Whether it may be detached into a window of its own.
110    pub detachable: bool,
111    /// The icon naming it in strips (an `egui_pop_core::icon::Icon`
112    /// name); empty: its title's first letter.
113    pub icon: String,
114    /// Drawn without a tab bar when it is alone in its area (the shell's
115    /// zones shown as panels).
116    pub bare: bool,
117    /// Placed in its area at first; `false`: closed until asked for.
118    pub open: bool,
119    /// A palette: it floats over the interface when it opens (a
120    /// toolbox, a navigator); it may still be docked in its areas.
121    pub palette: bool,
122    /// Whether it may float over the interface: every panel may unless
123    /// it opts out ([`PanelSpec::floatable`]); a palette always may.
124    pub floatable: bool,
125    /// What its content needs (ADR 0013): checked against each host it
126    /// is put in. `None`: a plain widget, any host of a panel.
127    pub content: Option<Mountable>,
128    /// What it does to what the application edits ([`PanelKind`]):
129    /// a view unless declared.
130    pub kind: PanelKind,
131    /// Whether it opens once or as many times as asked ([`Instances`]).
132    pub instances: Instances,
133}
134
135/// Where a panel is put: one of the shell's areas, floating over the
136/// interface as a palette, or detached into a window of its own.
137#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
138#[serde(rename_all = "snake_case")]
139pub enum Place {
140    Area(Area),
141    Floating,
142    Window,
143}
144
145/// A host a panel may be put in: the place, and what the host offers
146/// there (ADR 0013).
147#[derive(Clone, Debug, PartialEq, Serialize)]
148pub struct PanelHost {
149    pub place: Place,
150    pub offer: HostOffer,
151}
152
153impl PanelSpec {
154    pub fn new(id: PanelId, title: &str, area: Area) -> Self {
155        Self {
156            id,
157            title: title.into(),
158            area,
159            areas: Vec::new(),
160            commands: Vec::new(),
161            min_size: 120.0,
162            default_size: None,
163            detachable: true,
164            icon: String::new(),
165            bare: false,
166            open: true,
167            palette: false,
168            floatable: true,
169            content: None,
170            kind: PanelKind::View,
171            instances: Instances::Single,
172        }
173    }
174
175    /// Whether it opens once (the default) or as many times as asked: a
176    /// new instance is `<id>#<n>`, made by `pop.panel.open` with
177    /// `instance: "new"`.
178    pub fn instances(mut self, instances: Instances) -> Self {
179        self.instances = instances;
180        self
181    }
182
183    /// The spec of its instance `id` (`<id>#<n>`): the same panel, under
184    /// that id, titled `title` (else its own title and `n`: "Gallery 2"),
185    /// open where it is placed.
186    pub fn instance_spec(&self, id: &PanelId, title: Option<&str>) -> PanelSpec {
187        let mut spec = self.clone();
188        spec.title = match title {
189            Some(t) => t.to_string(),
190            None => format!("{} {}", self.title, id.instance_number()),
191        };
192        spec.id = id.clone();
193        spec.open = true;
194        spec
195    }
196
197    /// What it does to what the application edits: a control or mixed
198    /// panel's chrome shows an "edits" mark on its tab and its palette
199    /// band.
200    pub fn kind(mut self, kind: PanelKind) -> Self {
201        self.kind = kind;
202        self
203    }
204
205    /// What its content needs: a host refusing it refuses the panel.
206    pub fn content(mut self, needs: Mountable) -> Self {
207        self.content = Some(needs);
208        self
209    }
210
211    /// The smallest size across its area, in points.
212    pub fn min_size(mut self, points: f32) -> Self {
213        self.min_size = points.max(0.0);
214        self
215    }
216
217    /// The size it asks for across its area, in points.
218    pub fn default_size(mut self, points: f32) -> Self {
219        self.default_size = Some(points.max(self.min_size));
220        self
221    }
222
223    /// Whether it may be detached into a window of its own.
224    pub fn detachable(mut self, on: bool) -> Self {
225        self.detachable = on;
226        self
227    }
228
229    /// Its icon in strips, by name (`search`, `settings`...).
230    pub fn icon(mut self, name: &str) -> Self {
231        self.icon = name.into();
232        self
233    }
234
235    /// Closed until asked for (its command, a step): a new layout and a
236    /// repaired one keep it closed.
237    pub fn closed(mut self) -> Self {
238        self.open = false;
239        self
240    }
241
242    /// A palette: floats over the interface when it opens, never modal;
243    /// its area is where it docks.
244    pub fn palette(mut self) -> Self {
245        self.palette = true;
246        self.floatable = true;
247        self
248    }
249
250    /// Whether it may float over the interface: on unless turned off
251    /// here (a view that would leave its area empty, the centre's
252    /// document); a palette always may.
253    pub fn floatable(mut self, on: bool) -> Self {
254        self.floatable = on || self.palette;
255        self
256    }
257
258    /// Drawn without a tab bar when alone in its area.
259    pub fn bare(mut self) -> Self {
260        self.bare = true;
261        self
262    }
263
264    /// Why it may not be put in a host, if it may not: an area it stays
265    /// out of, floating or a window it is not allowed, or a host its
266    /// content does not fit (with the rule, ADR 0013).
267    pub fn refuses(&self, host: &PanelHost) -> Option<String> {
268        let place = match host.place {
269            Place::Area(area) => {
270                (!self.allows(area)).then(|| format!("{} stays out of {}", self.title, area.name()))
271            }
272            Place::Floating => (!self.floatable).then(|| format!("{} cannot float", self.title)),
273            Place::Window => {
274                (!self.detachable).then(|| format!("{} cannot be detached", self.title))
275            }
276        };
277        place.or_else(|| {
278            let needs = self.content.as_ref()?;
279            let fit = mount::check(needs, &host.offer);
280            let refusal = fit.refusal()?;
281            Some(format!(
282                "{} cannot go in {}: {}",
283                self.title,
284                host.offer.name.to_lowercase(),
285                refusal.reason()
286            ))
287        })
288    }
289
290    /// Restricts where it may go (its default area always allowed).
291    pub fn only_in(mut self, areas: &[Area]) -> Self {
292        self.areas = areas.to_vec();
293        self
294    }
295
296    /// Whether the panel may live in an area.
297    pub fn allows(&self, area: Area) -> bool {
298        self.areas.is_empty() || area == self.area || self.areas.contains(&area)
299    }
300}
301
302/// The declared panels, each owned.
303#[derive(Debug, Default)]
304pub struct Panels {
305    specs: Registry<PanelId, PanelSpec>,
306}
307
308impl Panels {
309    pub fn new() -> Self {
310        Self::default()
311    }
312
313    pub fn declare(&mut self, owner: &OwnerId, spec: PanelSpec) -> Result<(), String> {
314        let id = spec.id.clone();
315        self.specs
316            .insert(owner, id, spec)
317            .map_err(|t| format!("panel `{}` is already declared by `{}`", t.id, t.by))
318    }
319
320    pub fn get(&self, id: &str) -> Option<&PanelSpec> {
321        PanelId::new(id).ok().and_then(|id| self.specs.get(&id))
322    }
323
324    /// Every panel, in declaration order.
325    pub fn all(&self) -> Vec<&PanelSpec> {
326        self.specs
327            .in_order()
328            .into_iter()
329            .map(|(_, s)| &s.item)
330            .collect()
331    }
332
333    /// Who declared a panel: the application's own plugin, or a plugin
334    /// of a library (egui-pop's jobs centre).
335    pub fn owner(&self, id: &PanelId) -> Option<&OwnerId> {
336        self.specs.owner(id)
337    }
338
339    /// Every panel with its owner, in declaration order.
340    pub fn owned(&self) -> Vec<(&PanelSpec, &OwnerId)> {
341        self.specs
342            .in_order()
343            .into_iter()
344            .map(|(_, s)| (&s.item, &s.owner))
345            .collect()
346    }
347
348    pub fn remove_owner(&mut self, owner: &OwnerId) -> Vec<PanelId> {
349        self.specs
350            .remove_owner(owner)
351            .into_iter()
352            .map(|(id, _)| id)
353            .collect()
354    }
355
356    /// The commands the shell adds for each panel: focus and toggle, with
357    /// their titles.
358    pub fn shell_commands(&self) -> Vec<(CommandId, String)> {
359        self.all()
360            .into_iter()
361            .flat_map(|p| {
362                let focus = p.id.as_str().to_string() + ".focus";
363                let toggle = p.id.as_str().to_string() + ".toggle";
364                [
365                    (CommandId::new(focus), format!("Focus {}", p.title)),
366                    (CommandId::new(toggle), format!("Show or hide {}", p.title)),
367                ]
368            })
369            .filter_map(|(id, t)| id.ok().map(|id| (id, t)))
370            .collect()
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::*;
377    use crate::mount::{HostSize, Mountable};
378
379    fn host(place: Place) -> PanelHost {
380        PanelHost {
381            place,
382            offer: HostOffer::new("panel", "P", "Docked panel"),
383        }
384    }
385
386    #[test]
387    fn a_panel_is_a_view_unless_declared() {
388        let id = PanelId::new("demo.params").unwrap();
389        let spec = PanelSpec::new(id.clone(), "Parameters", Area::EndSide);
390        assert_eq!(spec.kind, PanelKind::View);
391        assert!(!spec.kind.edits());
392        let spec = spec.kind(PanelKind::Mixed);
393        assert!(spec.kind.edits());
394        assert_eq!(serde_json::to_value(spec.kind).unwrap(), "mixed");
395        for k in PanelKind::ALL {
396            assert_eq!(serde_json::to_value(k).unwrap(), k.as_str());
397        }
398    }
399
400    #[test]
401    fn a_panel_refuses_areas_floating_and_windows_it_is_not_allowed() {
402        let id = PanelId::new("demo.log").unwrap();
403        let spec = PanelSpec::new(id, "Log", Area::Bottom)
404            .only_in(&[Area::Center])
405            .floatable(false)
406            .detachable(false);
407        assert_eq!(spec.refuses(&host(Place::Area(Area::Bottom))), None);
408        assert_eq!(
409            spec.refuses(&host(Place::Area(Area::StartSide))).as_deref(),
410            Some("Log stays out of the start side bar")
411        );
412        assert_eq!(
413            spec.refuses(&host(Place::Floating)).as_deref(),
414            Some("Log cannot float")
415        );
416        assert_eq!(
417            spec.refuses(&host(Place::Window)).as_deref(),
418            Some("Log cannot be detached")
419        );
420    }
421
422    #[test]
423    fn a_panel_floats_unless_it_opts_out() {
424        let id = PanelId::new("demo.log").unwrap();
425        let spec = PanelSpec::new(id, "Log", Area::Bottom);
426        assert_eq!(spec.refuses(&host(Place::Floating)), None);
427        let spec = spec.floatable(false);
428        assert_eq!(
429            spec.refuses(&host(Place::Floating)).as_deref(),
430            Some("Log cannot float")
431        );
432        // A palette always may.
433        assert!(spec.palette().floatable(false).floatable);
434    }
435
436    #[test]
437    fn a_panel_refuses_a_host_its_content_does_not_fit() {
438        let id = PanelId::new("demo.view").unwrap();
439        let spec = PanelSpec::new(id, "View", Area::Center)
440            .floatable(true)
441            .content(Mountable::new("viewport", "Viewport").fills());
442        let row = PanelHost {
443            place: Place::Floating,
444            offer: HostOffer::new("line", "L", "Line zone").size(HostSize::Row),
445        };
446        let why = spec.refuses(&row).unwrap();
447        assert!(why.starts_with("View cannot go in line zone: "), "{why}");
448        assert!(why.contains("R1, D1"), "{why}");
449        assert_eq!(spec.refuses(&host(Place::Floating)), None);
450    }
451}