Skip to main content

egui_pop_api/
zones.rs

1//! Zones and blocks (ADR 0005). A zone is a named place; blocks are drawn
2//! in it, lightest first. Four operations: add, replace, extend (before
3//! or after a block) and wrap (around a block, receiving it as a
4//! closure). They are resolved when the application is built or a plugin
5//! comes or goes, never per frame; what cannot apply is reported with
6//! what happens instead.
7
8use std::collections::BTreeMap;
9use std::fmt;
10
11use egui::Ui;
12use egui_pop_model::diagnostics::Diagnostics;
13use egui_pop_model::ids::{BlockId, OwnerId, ZoneId};
14use serde::Serialize;
15
16use crate::app::AppHandle;
17
18/// Above the menu bar, the whole window's width: a window's own title
19/// bar (`frame::FramePlugin`), or anything an application puts there.
20pub const TITLE: ZoneId = ZoneId::from_static("app.title");
21/// Items in the window's own title bar, before its buttons (declared by
22/// `frame::FramePlugin`).
23pub const CAPTION: ZoneId = ZoneId::from_static("app.caption");
24/// The start of the window's own title bar (declared by
25/// `frame::FramePlugin`): by default the `egui_pop.frame.menu` block (the
26/// system menu button and the application's name); an application puts
27/// its logo there by replacing that block.
28pub const CAPTION_START: ZoneId = ZoneId::from_static("app.caption-start");
29/// A strip along the start edge, beside the side bar (the activity bar
30/// of `strips::StripsPlugin`).
31pub const ACTIVITY_BAR: ZoneId = ZoneId::from_static("app.activity-bar");
32/// The top bar, after the main menu.
33pub const TOP_BAR: ZoneId = ZoneId::from_static("app.top-bar");
34/// The top bar's end: blocks drawn there, left to right, sit at the
35/// bar's end before the commands of `app::MENU_BAR_END` (a document's
36/// name, a readout, a widget of the application's). They keep the width
37/// they took the pass before, as the top bar's do; the menus overflow
38/// first. Declared by the framework beside the shell's zones.
39///
40/// <div class="warning">Experimental: may change in any release
41/// (docs/stability.md).</div>
42pub const TOP_BAR_END: ZoneId = ZoneId::from_static("app.top-bar-end");
43/// The side bar at the start (left in left-to-right).
44pub const SIDE_BAR: ZoneId = ZoneId::from_static("app.side-bar");
45/// The main area.
46pub const MAIN: ZoneId = ZoneId::from_static("app.main");
47/// The side bar at the end.
48pub const INSPECTOR: ZoneId = ZoneId::from_static("app.inspector");
49/// The status bar at the bottom.
50pub const STATUS_BAR: ZoneId = ZoneId::from_static("app.status-bar");
51
52/// Drawn after the shell, every frame, in the main window only: blocks
53/// there show what stays in the main window (the settings window, the
54/// frame's edges) or follow a setting. Overlays that open
55/// in the window the user works in go in [`WINDOW_OVERLAYS`].
56pub const OVERLAYS: ZoneId = ZoneId::from_static("app.overlays");
57
58/// Drawn after each window's content, in the main window and in every
59/// detached panel's window: blocks there show overlays that belong to a
60/// window (the dialogs and the command palette, over the window they
61/// were opened from; the toasts, in the active window), each drawing
62/// only in its own (`AppHandle::active_window`, egui's
63/// `Context::viewport_id`). Declared by the framework beside the shell's
64/// zones.
65pub const WINDOW_OVERLAYS: ZoneId = ZoneId::from_static("app.window-overlays");
66
67/// The shell's zones, declared by the framework.
68pub const SHELL: [ZoneId; 8] = [
69    TITLE,
70    TOP_BAR,
71    ACTIVITY_BAR,
72    SIDE_BAR,
73    MAIN,
74    INSPECTOR,
75    STATUS_BAR,
76    OVERLAYS,
77];
78
79/// Draws a block.
80pub type DrawFn = Box<dyn FnMut(&mut Ui, &AppHandle)>;
81/// Draws around a block; calls `inner` (or not) where it likes.
82pub type WrapFn = Box<dyn FnMut(&mut Ui, &AppHandle, &mut dyn FnMut(&mut Ui))>;
83
84/// Where an extending block goes.
85#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
86pub enum Place {
87    Before(BlockId),
88    After(BlockId),
89}
90
91/// A block operation, as a plugin declares it.
92pub enum Block {
93    Add {
94        id: BlockId,
95        weight: i32,
96        draw: DrawFn,
97    },
98    Replace {
99        target: BlockId,
100        id: BlockId,
101        draw: DrawFn,
102    },
103    Extend {
104        place: Place,
105        id: BlockId,
106        draw: DrawFn,
107    },
108    Wrap {
109        target: BlockId,
110        id: BlockId,
111        wrap: WrapFn,
112    },
113}
114
115impl fmt::Debug for Block {
116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
117        match self {
118            Block::Add { id, weight, .. } => write!(f, "Add({id}, {weight})"),
119            Block::Replace { target, id, .. } => write!(f, "Replace({target} with {id})"),
120            Block::Extend { place, id, .. } => write!(f, "Extend({id} {place:?})"),
121            Block::Wrap { target, id, .. } => write!(f, "Wrap({target} in {id})"),
122        }
123    }
124}
125
126impl Block {
127    /// A new block, drawn by weight (lighter first).
128    pub fn add(id: BlockId, weight: i32, draw: impl FnMut(&mut Ui, &AppHandle) + 'static) -> Block {
129        Block::Add {
130            id,
131            weight,
132            draw: Box::new(draw),
133        }
134    }
135
136    /// Takes the place (and weight) of `target`.
137    pub fn replace(
138        target: BlockId,
139        id: BlockId,
140        draw: impl FnMut(&mut Ui, &AppHandle) + 'static,
141    ) -> Block {
142        Block::Replace {
143            target,
144            id,
145            draw: Box::new(draw),
146        }
147    }
148
149    /// A new block right before or after another.
150    pub fn extend(
151        place: Place,
152        id: BlockId,
153        draw: impl FnMut(&mut Ui, &AppHandle) + 'static,
154    ) -> Block {
155        Block::Extend {
156            place,
157            id,
158            draw: Box::new(draw),
159        }
160    }
161
162    /// Draws around `target`.
163    pub fn wrap(
164        target: BlockId,
165        id: BlockId,
166        wrap: impl FnMut(&mut Ui, &AppHandle, &mut dyn FnMut(&mut Ui)) + 'static,
167    ) -> Block {
168        Block::Wrap {
169            target,
170            id,
171            wrap: Box::new(wrap),
172        }
173    }
174
175    pub fn id(&self) -> &BlockId {
176        match self {
177            Block::Add { id, .. }
178            | Block::Replace { id, .. }
179            | Block::Extend { id, .. }
180            | Block::Wrap { id, .. } => id,
181        }
182    }
183
184    fn op(&self) -> &'static str {
185        match self {
186            Block::Add { .. } => "add",
187            Block::Replace { .. } => "replace",
188            Block::Extend { .. } => "extend",
189            Block::Wrap { .. } => "wrap",
190        }
191    }
192}
193
194/// A block as contributed.
195#[derive(Debug)]
196pub(crate) struct Contribution {
197    pub zone: ZoneId,
198    pub owner: OwnerId,
199    /// The plugin's rank in connection order (later plugins apply later).
200    pub rank: usize,
201    pub seq: u64,
202    /// Taken out while it is drawn.
203    pub block: Option<Block>,
204}
205
206/// One block of a resolved zone: what draws it, what wraps it.
207#[derive(Clone, Debug, PartialEq, Serialize)]
208pub struct Resolved {
209    pub id: BlockId,
210    pub owner: OwnerId,
211    pub weight: i32,
212    /// The contribution drawing it.
213    #[serde(skip)]
214    pub(crate) draw: usize,
215    /// Wrappers, innermost first: (contribution, id, owner).
216    #[serde(skip)]
217    pub(crate) wraps: Vec<usize>,
218    /// What was applied: `replaced by x`, `wrapped by y`.
219    pub notes: Vec<String>,
220}
221
222/// A declared zone.
223#[derive(Clone, Debug, PartialEq, Serialize)]
224pub struct ZoneInfo {
225    pub id: ZoneId,
226    pub owner: OwnerId,
227    pub title: String,
228    pub blocks: Vec<Resolved>,
229}
230
231/// Zones, contributions and their resolution.
232#[derive(Debug, Default)]
233pub(crate) struct ZoneTable {
234    pub zones: BTreeMap<ZoneId, (OwnerId, String)>,
235    pub contributions: Vec<Contribution>,
236    pub resolved: BTreeMap<ZoneId, Vec<Resolved>>,
237    next: u64,
238}
239
240impl ZoneTable {
241    pub fn declare(&mut self, owner: &OwnerId, zone: ZoneId, title: &str) -> Result<(), OwnerId> {
242        if let Some((by, _)) = self.zones.get(&zone) {
243            return Err(by.clone());
244        }
245        self.zones.insert(zone, (owner.clone(), title.into()));
246        Ok(())
247    }
248
249    pub fn contribute(&mut self, owner: &OwnerId, rank: usize, zone: ZoneId, block: Block) {
250        self.next += 1;
251        self.contributions.push(Contribution {
252            zone,
253            owner: owner.clone(),
254            rank,
255            seq: self.next,
256            block: Some(block),
257        });
258    }
259
260    pub fn remove_owner(&mut self, owner: &OwnerId) {
261        self.contributions.retain(|c| c.owner != *owner);
262        self.zones.retain(|_, (o, _)| o != owner);
263    }
264
265    /// Sets the plugin ranks (connection order) for the resolution.
266    pub fn set_rank(&mut self, owner: &OwnerId, rank: usize) {
267        for c in &mut self.contributions {
268            if c.owner == *owner {
269                c.rank = rank;
270            }
271        }
272    }
273
274    /// Resolves every zone; diagnostics for what could not apply.
275    pub fn resolve(&mut self, d: &mut Diagnostics) {
276        self.resolved.clear();
277        let mut by_zone: BTreeMap<ZoneId, Vec<usize>> = BTreeMap::new();
278        for (i, c) in self.contributions.iter().enumerate() {
279            if !self.zones.contains_key(&c.zone) {
280                let op = c.block.as_ref().map_or("block", Block::op);
281                let id = c
282                    .block
283                    .as_ref()
284                    .map(|b| b.id().to_string())
285                    .unwrap_or_default();
286                d.error(
287                    "unknown-zone",
288                    Some(&c.owner),
289                    &id,
290                    format!(
291                        "{op} `{id}` targets zone `{}`, which nobody declared: it is not shown",
292                        c.zone
293                    ),
294                );
295                continue;
296            }
297            by_zone.entry(c.zone.clone()).or_default().push(i);
298        }
299        for (zone, mut list) in by_zone {
300            // Plugin order, then registration order.
301            list.sort_by_key(|&i| (self.contributions[i].rank, self.contributions[i].seq));
302            let out = self.resolve_zone(&zone, &list, d);
303            self.resolved.insert(zone, out);
304        }
305        for zone in self.zones.keys() {
306            self.resolved.entry(zone.clone()).or_default();
307        }
308    }
309
310    fn resolve_zone(&self, zone: &ZoneId, list: &[usize], d: &mut Diagnostics) -> Vec<Resolved> {
311        let c = &self.contributions;
312        let mut out: Vec<Resolved> = Vec::new();
313        let taken = |out: &Vec<Resolved>, id: &BlockId| out.iter().any(|r| r.id == *id);
314        let dup = |d: &mut Diagnostics, i: usize, id: &BlockId| {
315            d.error(
316                "duplicate-block",
317                Some(&c[i].owner),
318                id.as_str(),
319                format!("zone `{zone}` already has a block `{id}`: this one is not shown"),
320            );
321        };
322        // Adds, by weight then order.
323        let mut adds: Vec<(i32, usize)> = list
324            .iter()
325            .filter_map(|&i| match &c[i].block {
326                Some(Block::Add { weight, .. }) => Some((*weight, i)),
327                _ => None,
328            })
329            .collect();
330        adds.sort_by_key(|(w, i)| (*w, c[*i].rank, c[*i].seq));
331        for (weight, i) in adds {
332            let id = c[i].block.as_ref().expect("a block").id().clone();
333            if taken(&out, &id) {
334                dup(d, i, &id);
335                continue;
336            }
337            out.push(Resolved {
338                id,
339                owner: c[i].owner.clone(),
340                weight,
341                draw: i,
342                wraps: Vec::new(),
343                notes: Vec::new(),
344            });
345        }
346        let last_weight = |out: &Vec<Resolved>| out.last().map_or(0, |r| r.weight);
347        // Replaces.
348        for &i in list {
349            if let Some(Block::Replace { target, id, .. }) = &c[i].block {
350                match out.iter().position(|r| r.id == *target) {
351                    Some(p) => {
352                        let old = out[p].owner.clone();
353                        out[p].id = id.clone();
354                        out[p].owner = c[i].owner.clone();
355                        out[p].draw = i;
356                        out[p].notes.push(format!("replaced `{target}` ({old})"));
357                    }
358                    None if taken(&out, id) => dup(d, i, id),
359                    None => {
360                        let weight = last_weight(&out);
361                        d.warn(
362                            "dangling-replace",
363                            Some(&c[i].owner),
364                            id.as_str(),
365                            format!(
366                                "`{id}` replaces `{target}` in zone `{zone}`, which has no such block: it is added as a new block at the end"
367                            ),
368                        );
369                        out.push(Resolved {
370                            id: id.clone(),
371                            owner: c[i].owner.clone(),
372                            weight,
373                            draw: i,
374                            wraps: Vec::new(),
375                            notes: vec![format!("meant to replace missing `{target}`")],
376                        });
377                    }
378                }
379            }
380        }
381        // Extends.
382        for &i in list {
383            if let Some(Block::Extend { place, id, .. }) = &c[i].block {
384                if taken(&out, id) {
385                    dup(d, i, id);
386                    continue;
387                }
388                let (target, after) = match place {
389                    Place::Before(t) => (t, false),
390                    Place::After(t) => (t, true),
391                };
392                let at = out.iter().position(|r| r.id == *target);
393                let (pos, weight, note) = match at {
394                    Some(p) => (
395                        if after { p + 1 } else { p },
396                        out[p].weight,
397                        format!("{} `{target}`", if after { "after" } else { "before" }),
398                    ),
399                    None => {
400                        d.warn(
401                            "dangling-extend",
402                            Some(&c[i].owner),
403                            id.as_str(),
404                            format!(
405                                "`{id}` goes {} `{target}` in zone `{zone}`, which has no such block: it is added at the end",
406                                if after { "after" } else { "before" }
407                            ),
408                        );
409                        (
410                            out.len(),
411                            last_weight(&out),
412                            format!("meant to go next to missing `{target}`"),
413                        )
414                    }
415                };
416                out.insert(
417                    pos,
418                    Resolved {
419                        id: id.clone(),
420                        owner: c[i].owner.clone(),
421                        weight,
422                        draw: i,
423                        wraps: Vec::new(),
424                        notes: vec![note],
425                    },
426                );
427            }
428        }
429        // Wraps, in plugin order: the last applied is the outermost.
430        for &i in list {
431            if let Some(Block::Wrap { target, id, .. }) = &c[i].block {
432                match out.iter_mut().find(|r| r.id == *target) {
433                    Some(r) => {
434                        r.wraps.push(i);
435                        r.notes.push(format!("wrapped by `{id}` ({})", c[i].owner));
436                    }
437                    None => d.warn(
438                        "dangling-wrap",
439                        Some(&c[i].owner),
440                        id.as_str(),
441                        format!("`{id}` wraps `{target}` in zone `{zone}`, which has no such block: the wrap is skipped"),
442                    ),
443                }
444            }
445        }
446        out
447    }
448
449    /// The zones with their resolved blocks.
450    pub fn infos(&self) -> Vec<ZoneInfo> {
451        self.zones
452            .iter()
453            .map(|(id, (owner, title))| ZoneInfo {
454                id: id.clone(),
455                owner: owner.clone(),
456                title: title.clone(),
457                blocks: self.resolved.get(id).cloned().unwrap_or_default(),
458            })
459            .collect()
460    }
461}
462
463/// Draws a resolved block through its wrappers.
464pub(crate) fn draw_chain(ui: &mut Ui, app: &AppHandle, draw: &mut DrawFn, wraps: &mut [WrapFn]) {
465    match wraps.split_last_mut() {
466        None => draw(ui, app),
467        Some((outer, inner)) => {
468            outer(ui, app, &mut |ui: &mut Ui| draw_chain(ui, app, draw, inner));
469        }
470    }
471}