Skip to main content

egui_pop_api/
toolbars.rs

1//! Toolbars drawn from their declarations (`docs/toolbars.md`): a toolbar
2//! is a menu id (`demo.toolbar`) whose items are contributed as any
3//! menu's (`Ctx::menu_item`, `CommandSpec::menu`, an alter hook), and
4//! drawn as a row or a column of buttons instead of a list.
5//!
6//! <div class="warning">Experimental: may change in any release
7//! (docs/stability.md).</div>
8//!
9//! - A command item is a button showing the command's icon
10//!   ([`CommandSpec::icon`](egui_pop_model::commands::CommandSpec::icon),
11//!   its `icon_on` while checked), its title and first key binding in the
12//!   tooltip; a toolbar showing its titles ([`Labels`]) writes the title
13//!   beside the icon, and a command without an icon shows its title.
14//! - Its `checked` clause draws it on (`toolbar-button`'s `selected`
15//!   state, framed as a checked menu icon is; announced as toggled, a
16//!   radio item as a chosen radio button); where the command or the item
17//!   does not apply it is greyed, the reason in its tooltip; a run waiting
18//!   for its result shows the spinner in its icon's place.
19//! - Groups are separated by a line, as in a menu; a submenu is a button
20//!   with a drop-down mark opening that menu; a list item gives a button
21//!   per entry (with the entry's own icon), asked of its provider when
22//!   the toolbar is first drawn and again when the context changes.
23//! - The tools that do not fit go, from the end, into a "More tools"
24//!   button ([`Glyph::More`](egui_pop_core::kit::Glyph::More)) opening
25//!   them as a menu.
26//! - The toolbar is one Tab stop: the arrows along it go from tool to
27//!   tool, Home and End to the first and the last, and Tab coming back
28//!   lands on the tool focused last.
29//!
30//! egui_stack's [`ToolRow`] lays the tools
31//! out, takes their input and moves the focus; the kit paints them (its
32//! `DockPainter`). Sizes come from the theme: the icon is
33//! `size.icon.toolbar`, padded by `space.xs`, so the density moves them.
34//! What each toolbar drew last is [`layout`] (the `toolbars` debug
35//! collector), so an agent reads a toolbar's tools, their state and which
36//! went into "More tools" without pixels.
37//!
38//! ```
39//! use egui_pop_api::AppHandle;
40//! use egui_pop_api::toolbars::{Labels, Toolbar};
41//! use egui_pop_model::ids::MenuId;
42//!
43//! const TOOLBAR: MenuId = MenuId::from_static("demo.toolbar");
44//!
45//! fn bar(ui: &mut egui::Ui, app: &AppHandle) {
46//!     Toolbar::new(app, &TOOLBAR).show(ui);
47//!     Toolbar::new(app, &TOOLBAR).labels(Labels::Beside).vertical().show(ui);
48//! }
49//! ```
50
51use std::cell::RefCell;
52use std::collections::BTreeMap;
53
54use egui::{Align, Layout, Popup, Ui};
55use egui_pop_core::icon::{Icon, IconRef, Size};
56use egui_pop_core::kit::Kit;
57use egui_pop_core::state::Slot;
58use egui_pop_core::strings;
59use egui_pop_core::theme::Tokens;
60use egui_pop_model::ids::{CommandId, MenuId};
61use egui_pop_model::menus::{Item, Shown, show_items};
62use egui_pop_model::when::{When, WhenContext};
63use egui_stack::toolbar::{self as row, ToolDisplay, ToolRow};
64use serde::Serialize;
65use serde_json::Value as Json;
66
67use crate::app::AppHandle;
68use crate::menus::{self, ListItem, Mark, RowTrace};
69use crate::strings as txt;
70
71/// How a toolbar shows its tools.
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
73#[serde(rename_all = "snake_case")]
74pub enum Labels {
75    /// Icons alone, the title in the tooltip; a tool without an icon
76    /// shows its title.
77    #[default]
78    Icons,
79    /// Each icon with its title beside it.
80    Beside,
81    /// Titles alone.
82    Text,
83}
84
85/// Which way a toolbar runs.
86#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize)]
87#[serde(rename_all = "snake_case")]
88pub enum Orientation {
89    /// A row, from the start.
90    #[default]
91    Horizontal,
92    /// A column, from the top (a tool palette).
93    Vertical,
94}
95
96/// What a tool is.
97#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
98#[serde(rename_all = "snake_case")]
99pub enum ToolKind {
100    /// A button running a command.
101    Command,
102    /// A button opening a menu.
103    Submenu,
104    /// The line between two groups.
105    Separator,
106}
107
108/// A tool as a toolbar drew it last, for agents and tests.
109#[derive(Clone, Debug, PartialEq, Serialize)]
110pub struct ToolTrace {
111    pub kind: ToolKind,
112    /// The command it runs.
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub command: Option<CommandId>,
115    /// The arguments it runs the command with.
116    #[serde(skip_serializing_if = "Json::is_null")]
117    pub args: Json,
118    /// The menu it opens.
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub submenu: Option<MenuId>,
121    /// Its title (its name for screen readers); empty for a separator.
122    pub label: String,
123    /// The name of the icon it shows, if any.
124    #[serde(skip_serializing_if = "Option::is_none")]
125    pub icon: Option<String>,
126    /// The key binding its tooltip gives.
127    #[serde(skip_serializing_if = "Option::is_none")]
128    pub keys: Option<String>,
129    pub enabled: bool,
130    /// Why it is greyed.
131    #[serde(skip_serializing_if = "Option::is_none")]
132    pub why: Option<String>,
133    /// It has a `checked` clause: a toggle (or a radio choice), on or not.
134    #[serde(skip_serializing_if = "std::ops::Not::not")]
135    pub checkable: bool,
136    #[serde(skip_serializing_if = "std::ops::Not::not")]
137    pub checked: bool,
138    #[serde(skip_serializing_if = "std::ops::Not::not")]
139    pub radio: bool,
140    /// Its command runs, waiting for its result.
141    #[serde(skip_serializing_if = "std::ops::Not::not")]
142    pub busy: bool,
143    /// It did not fit: it is in the "More tools" menu.
144    #[serde(skip_serializing_if = "std::ops::Not::not")]
145    pub overflow: bool,
146}
147
148/// A toolbar as it was drawn last.
149#[derive(Clone, Debug, PartialEq, Serialize)]
150pub struct ToolbarLayout {
151    pub menu: MenuId,
152    pub orientation: Orientation,
153    pub labels: Labels,
154    /// Its name for screen readers ([`Toolbar::name`]).
155    #[serde(skip_serializing_if = "Option::is_none")]
156    pub name: Option<String>,
157    /// Every tool, in order, those in "More tools" marked `overflow`.
158    pub tools: Vec<ToolTrace>,
159    /// How many tools went into "More tools" (separators not counted).
160    pub overflow: usize,
161}
162
163/// A toolbar's list entries and the context they were asked in, per
164/// toolbar and list.
165const LISTS: Slot<(WhenContext, Vec<ListItem>)> = Slot::new("api.toolbars.lists");
166
167/// Where each toolbar drew its tools last, by menu id.
168#[derive(Default)]
169struct Layouts(RefCell<BTreeMap<String, ToolbarLayout>>);
170
171/// What a toolbar drew last, if it was drawn.
172pub fn layout(app: &AppHandle, menu: &MenuId) -> Option<ToolbarLayout> {
173    app.local::<Layouts>()
174        .0
175        .borrow()
176        .get(menu.as_str())
177        .cloned()
178}
179
180/// Every toolbar's last layout, by menu id (the `toolbars` collector).
181pub(crate) fn layouts(app: &AppHandle) -> BTreeMap<String, ToolbarLayout> {
182    app.local::<Layouts>().0.borrow().clone()
183}
184
185/// A toolbar drawn from a menu's items.
186#[derive(Debug)]
187#[must_use = "draw it with `show`"]
188pub struct Toolbar<'a> {
189    app: &'a AppHandle,
190    menu: MenuId,
191    orientation: Orientation,
192    labels: Labels,
193    args: Json,
194    name: Option<String>,
195}
196
197impl<'a> Toolbar<'a> {
198    /// The toolbar of a menu's items: a row of icons.
199    pub fn new(app: &'a AppHandle, menu: &MenuId) -> Self {
200        Self {
201            app,
202            menu: menu.clone(),
203            orientation: Orientation::Horizontal,
204            labels: Labels::Icons,
205            args: Json::Null,
206            name: None,
207        }
208    }
209
210    /// Its name for screen readers (`Formatting`, `Tools`): its "More
211    /// tools" button is then `More tools: <name>`, so two toolbars of a
212    /// window never have two controls of one name. Give it whenever more
213    /// than one toolbar shows at a time.
214    pub fn name(mut self, name: impl Into<String>) -> Self {
215        self.name = Some(name.into());
216        self
217    }
218
219    /// A column instead of a row (a tool palette).
220    pub fn vertical(mut self) -> Self {
221        self.orientation = Orientation::Vertical;
222        self
223    }
224
225    /// Which way it runs.
226    pub fn orientation(mut self, orientation: Orientation) -> Self {
227        self.orientation = orientation;
228        self
229    }
230
231    /// Icons alone (the default), icons with their titles, or titles.
232    pub fn labels(mut self, labels: Labels) -> Self {
233        self.labels = labels;
234        self
235    }
236
237    /// Arguments of this toolbar (the document it acts on): merged into
238    /// every command a tool runs, and seen by `when` clauses as
239    /// `args.<key>`, as a context menu's.
240    pub fn args(mut self, args: Json) -> Self {
241        self.args = args;
242        self
243    }
244
245    /// Draws it in the room the `Ui` has, the tools that do not fit in
246    /// "More tools"; returns what it drew. A column measures the height
247    /// its `Ui` offers: inside `ui.horizontal` that is one row's, so give
248    /// it room (`ui.allocate_ui`, a panel) rather than a row.
249    pub fn show(self, ui: &mut Ui) -> ToolbarLayout {
250        let app = self.app;
251        let ctx = ui.ctx().clone();
252        let cx = menus::with_args(&app.when_context(), &self.args);
253        let shown = show_items(&app.menu(&self.menu), &cx);
254        let tools = self.tools(ui, &shown, &cx);
255        let t = Tokens::of(&ctx);
256        let icon = Size::Toolbar.points(&t);
257        let pad = t.space.xs;
258        let kit = Kit::of(&ctx);
259        // The More button's names, from the strings.
260        let mut labels = egui_stack::Labels::ENGLISH;
261        labels.more_tools = strings::tr(&ctx, &txt::TOOLBAR_MORE).into();
262        if let Some(toolbar) = &self.name {
263            labels.more_tools_in =
264                strings::tr_args(&ctx, &txt::TOOLBAR_MORE_IN, &[("toolbar", toolbar)]).into();
265        }
266        // Unique in the application: the row's memory (its Tab stop) and
267        // `laid_out` go by it.
268        let name = format!("egui-pop.toolbar:{}:{:?}", self.menu, ui.scope_id());
269        let mut bar = ToolRow::new(name)
270            .display(match self.labels {
271                Labels::Icons => ToolDisplay::Icons,
272                Labels::Beside => ToolDisplay::Beside,
273                Labels::Text => ToolDisplay::Text,
274            })
275            .icon_size(icon)
276            .padding(pad)
277            .spacing(pad / 2.0)
278            .painter(&*kit)
279            .labels(labels);
280        if self.orientation == Orientation::Vertical {
281            bar = bar.vertical();
282        }
283        if let Some(title) = &self.name {
284            bar = bar.title(title.clone());
285        }
286        let vertical = self.orientation == Orientation::Vertical;
287        let row_tools = tools
288            .iter()
289            .enumerate()
290            .map(|(i, tool)| self.row_tool(&ctx, i, tool, &cx));
291        let layout = if vertical {
292            Layout::top_down(Align::Min)
293        } else {
294            Layout::left_to_right(Align::Center)
295        };
296        let response = ui
297            .with_layout(layout, |ui| {
298                // A separator's room along the row.
299                ui.spacing_mut().item_spacing.x = t.space.s;
300                if vertical {
301                    return bar.show(ui, row_tools);
302                }
303                // A row is centred across the line it is in and takes
304                // the line's height, as a widget of `ui.horizontal` does:
305                // ToolRow starts at the top of its room, so its room is
306                // its own height (the tallest of the icon and the button
307                // text, padded), centred in the line.
308                let line = ui.available_rect_before_wrap();
309                let text = ui.text_style_height(&egui::TextStyle::Button);
310                let height = (icon.max(text) + 2.0 * pad).round();
311                let room = egui::vec2(ui.available_width(), height);
312                let out = ui.allocate_ui(room, |ui| bar.show(ui, row_tools)).inner;
313                if line.height().is_finite() {
314                    ui.expand_to_include_y(line.top());
315                    ui.expand_to_include_y(line.bottom());
316                }
317                out
318            })
319            .inner;
320        if let Some(tool) = response
321            .clicked
322            .as_deref()
323            .and_then(|id| id.parse::<usize>().ok())
324            .and_then(|i| tools.get(i))
325            && let Some(id) = &tool.trace.command
326        {
327            app.request_run_in(
328                id.clone(),
329                menus::merge(&tool.trace.args, &self.args),
330                cx.clone(),
331            );
332        }
333        // The row's tools as drawn, a subsequence of ours, in order.
334        let mut traces = Vec::with_capacity(response.laid.tools.len());
335        let mut ours = tools.iter().enumerate();
336        for laid in &response.laid.tools {
337            let sep = laid.kind == row::ToolKind::Separator;
338            let found = ours.by_ref().find(|(i, t)| {
339                if sep {
340                    t.trace.kind == ToolKind::Separator
341                } else {
342                    laid.id == i.to_string()
343                }
344            });
345            if let Some((_, t)) = found {
346                let mut trace = t.trace.clone();
347                trace.overflow = laid.overflow;
348                traces.push(trace);
349            }
350        }
351        // The More menu open: its rows, for agents, as a menu's.
352        let more_open = response
353            .laid
354            .more
355            .is_some_and(|more| Popup::is_id_open(&ctx, more.with("popup")));
356        // On the bus (ADR 0029): the More menu opened, closed and how.
357        if let Some(more) = response.laid.more {
358            egui_pop_core::overlay::follow_popup(
359                &ctx,
360                more.with("popup"),
361                "toolbar overflow",
362                more_open,
363                None,
364            );
365        }
366        if more_open {
367            let gutter = icon + 2.0 * pad;
368            for tr in traces
369                .iter()
370                .filter(|t| t.overflow && t.kind != ToolKind::Separator)
371            {
372                let mark = match (tr.busy, tr.checked, tr.icon.is_some()) {
373                    (true, ..) => Mark::Busy,
374                    (false, true, true) => Mark::Framed,
375                    (false, true, false) if tr.radio => Mark::Radio,
376                    (false, true, false) => Mark::Check,
377                    (false, false, true) => Mark::Icon,
378                    (false, false, false) => Mark::None,
379                };
380                menus::record_row(
381                    &ctx,
382                    RowTrace {
383                        menu: self.menu.clone(),
384                        label: tr.label.clone(),
385                        icon: tr.icon.clone(),
386                        mark,
387                        label_x: gutter,
388                        gutter,
389                    },
390                );
391            }
392        }
393        let out = ToolbarLayout {
394            menu: self.menu.clone(),
395            orientation: self.orientation,
396            labels: self.labels,
397            name: self.name.clone(),
398            overflow: response.laid.overflow,
399            tools: traces,
400        };
401        app.local::<Layouts>()
402            .0
403            .borrow_mut()
404            .insert(self.menu.to_string(), out.clone());
405        out
406    }
407
408    /// One of our tools as the row's, named by its index: its tooltip
409    /// (title, key, why it is greyed, the last run's error), its icon
410    /// recorded where drawn, a submenu drawing the menu's rows.
411    fn row_tool<'t>(
412        &'t self,
413        ctx: &egui::Context,
414        i: usize,
415        tool: &'t Tool,
416        cx: &'t WhenContext,
417    ) -> row::Tool<'t> {
418        let tr = &tool.trace;
419        let id = i.to_string();
420        let label = tr.label.clone();
421        let mut out = match tr.kind {
422            ToolKind::Separator => return row::Tool::separator(),
423            ToolKind::Submenu => {
424                let (app, args) = (self.app, &self.args);
425                let sub = tr.submenu.clone();
426                row::Tool::menu(id, label, move |ui| {
427                    if let Some(sub) = sub {
428                        let shown = show_items(&app.menu(&sub), cx);
429                        menus::rows(ui, app, &sub, shown, cx, args, 1);
430                    }
431                })
432            }
433            ToolKind::Command => match (tr.checkable, tr.radio) {
434                (true, true) => row::Tool::radio(id, label, tr.checked),
435                (true, false) => row::Tool::toggle(id, label, tr.checked),
436                _ => row::Tool::button(id, label),
437            },
438        };
439        // The application's live tooltip (`pop.command.label`), else the
440        // title.
441        let action = tr
442            .command
443            .as_ref()
444            .and_then(|c| self.app.command_text(c).tooltip)
445            .unwrap_or_else(|| tr.label.clone());
446        let tip = match &tr.keys {
447            Some(keys) => strings::tr_args(
448                ctx,
449                &txt::TOOLBAR_WITH_KEY,
450                &[("action", &action), ("keys", keys)],
451            ),
452            None => action,
453        };
454        let tip = match (&tr.why, &tool.failed) {
455            (Some(why), _) => format!("{tip}\n{why}"),
456            (None, Some(e)) => format!(
457                "{tip}\n{}",
458                strings::tr_args(ctx, &txt::MENU_LAST_RUN_FAILED, &[("error", e)])
459            ),
460            (None, None) => tip,
461        };
462        out = out.tooltip(tip).enabled(tr.enabled).busy(tr.busy);
463        if let Some(keys) = &tr.keys {
464            out = out.shortcut(keys.clone());
465        }
466        if let Some(icon) = tool.icon {
467            let (label, name) = (tr.label.as_str(), tr.icon.as_deref());
468            out = out.icon_painter(move |painter, rect, color| {
469                icon.paint(painter, rect, color);
470                if let Some(name) = name {
471                    egui_pop_core::icon::registry::record(painter.ctx(), "toolbar", label, name);
472                }
473            });
474        }
475        out
476    }
477
478    /// The tools of the shown items: a list item gives one per entry.
479    fn tools(&self, ui: &Ui, shown: &[Shown], cx: &WhenContext) -> Vec<Tool> {
480        let app = self.app;
481        let mut out = Vec::new();
482        for s in shown {
483            match s {
484                Shown::Separator => out.push(Tool::separator()),
485                Shown::Item {
486                    item,
487                    enabled,
488                    checked,
489                    checkable,
490                    radio,
491                } => match item {
492                    Item::Command { id, args, label } => out.push(Tool::command(
493                        ui.ctx(),
494                        app,
495                        cx,
496                        CommandTool {
497                            id,
498                            args: args.clone(),
499                            label: label.clone(),
500                            own_icon: None,
501                            enabled: *enabled,
502                            checked: *checked,
503                            checkable: *checkable,
504                            radio: *radio,
505                        },
506                    )),
507                    Item::Submenu { menu, label } => {
508                        let label = strings::menu_label(ui.ctx(), menu.as_str(), label);
509                        out.push(Tool::submenu(menu.clone(), label, *enabled));
510                    }
511                    Item::List { name } => {
512                        for e in self.list_entries(ui, name, cx) {
513                            out.push(Tool::command(
514                                ui.ctx(),
515                                app,
516                                cx,
517                                CommandTool {
518                                    id: &e.command,
519                                    args: e.args.clone(),
520                                    label: Some(e.label.clone()),
521                                    own_icon: e.icon,
522                                    enabled: *enabled && e.enabled,
523                                    checked: e.checked,
524                                    checkable: e.checked,
525                                    radio: false,
526                                },
527                            ));
528                        }
529                    }
530                },
531            }
532        }
533        out
534    }
535
536    /// A list item's entries: asked of its provider when the toolbar is
537    /// first drawn and again whenever the context changes (a toolbar
538    /// stays open, unlike a menu).
539    fn list_entries(&self, ui: &Ui, name: &str, cx: &WhenContext) -> Vec<ListItem> {
540        let key = LISTS.keyed((self.menu.as_str(), name));
541        if let Some((at, entries)) = key.get(ui.ctx())
542            && at == *cx
543        {
544            return entries;
545        }
546        let entries = self.app.list_items(name, cx);
547        key.set(ui.ctx(), (cx.clone(), entries.clone()));
548        entries
549    }
550}
551
552/// A command item, as a tool is made of it.
553struct CommandTool<'i> {
554    id: &'i CommandId,
555    args: Json,
556    label: Option<String>,
557    /// A list entry's own icon: never its command's.
558    own_icon: Option<Icon>,
559    enabled: bool,
560    checked: bool,
561    checkable: bool,
562    radio: bool,
563}
564
565/// A tool, worked out for this pass.
566struct Tool {
567    trace: ToolTrace,
568    /// The icon drawn, resolved.
569    icon: Option<Icon>,
570    /// The last run's error.
571    failed: Option<String>,
572}
573
574impl Tool {
575    fn separator() -> Tool {
576        Tool {
577            trace: ToolTrace {
578                kind: ToolKind::Separator,
579                command: None,
580                args: Json::Null,
581                submenu: None,
582                label: String::new(),
583                icon: None,
584                keys: None,
585                enabled: true,
586                why: None,
587                checkable: false,
588                checked: false,
589                radio: false,
590                busy: false,
591                overflow: false,
592            },
593            icon: None,
594            failed: None,
595        }
596    }
597
598    fn submenu(menu: MenuId, label: String, enabled: bool) -> Tool {
599        let mut tool = Tool::separator();
600        tool.trace.kind = ToolKind::Submenu;
601        tool.trace.submenu = Some(menu);
602        tool.trace.label = label;
603        tool.trace.enabled = enabled;
604        tool
605    }
606
607    fn command(ctx: &egui::Context, app: &AppHandle, cx: &WhenContext, c: CommandTool<'_>) -> Tool {
608        let spec = app.command(c.id);
609        let (title, why) = match &spec {
610            Some(s) => {
611                let applies = s.when.is_empty() || When::parse(&s.when).is_ok_and(|w| w.eval(cx));
612                let why = (!applies)
613                    .then(|| strings::tr_args(ctx, &txt::MENU_DOES_NOT_APPLY, &[("when", &s.when)]))
614                    .or_else(|| (!c.enabled).then(|| strings::tr(ctx, &txt::MENU_NOT_AVAILABLE)));
615                (
616                    c.label.clone().unwrap_or_else(|| app.command_menu_title(s)),
617                    why,
618                )
619            }
620            None => (
621                c.label.clone().unwrap_or_else(|| c.id.to_string()),
622                Some(strings::tr_args(
623                    ctx,
624                    &txt::MENU_NO_COMMAND,
625                    &[("id", c.id.as_str())],
626                )),
627            ),
628        };
629        let running = app.running(c.id);
630        let why = why.or_else(|| running.then(|| strings::tr(ctx, &txt::MENU_RUNNING)));
631        let failed = app
632            .history()
633            .iter()
634            .rev()
635            .find(|r| r.id == *c.id)
636            .and_then(|r| r.result.clone().err());
637        let (icon, name) = match c.own_icon {
638            Some(i) => (Some(i), Some(i.name().to_string())),
639            None => match spec.as_ref().and_then(|s| s.icon_for(c.checked)) {
640                Some(n) => (
641                    Some(IconRef::from(n).or_placeholder("toolbar")),
642                    Some(n.to_string()),
643                ),
644                None => (None, None),
645            },
646        };
647        let busy = crate::busy::busy_shown(
648            app,
649            ctx,
650            egui::Id::unique(("egui_pop_toolbar_busy", c.id.as_str(), &title)),
651            c.id,
652        );
653        Tool {
654            trace: ToolTrace {
655                kind: ToolKind::Command,
656                command: Some(c.id.clone()),
657                args: c.args,
658                submenu: None,
659                label: title,
660                icon: name,
661                keys: app.keys_for(c.id).first().cloned(),
662                enabled: why.is_none(),
663                why,
664                checkable: c.checkable,
665                checked: c.checked,
666                radio: c.radio,
667                busy,
668                overflow: false,
669            },
670            icon,
671            failed,
672        }
673    }
674}