Skip to main content

egui_pop_api/workbench/
window_areas.rs

1//! Each application window's own workbench: a centre, start and end side
2//! areas and a bottom area around the window's content, each holding
3//! panels as tabs and splits, as the main window's areas do
4//! (`Layout::windows`, saved with the layout).
5//!
6//! <div class="warning">Experimental: may change in any release
7//! (docs/stability.md).</div>
8//!
9//! A window with no panel in its areas draws its content alone, as
10//! before. Once a panel is placed in one of its areas, the window draws
11//! its start and end sides and its bottom around its content, and the
12//! panels of its centre beside it.
13//! A window opened with `WindowSpec::centre_dock` has no content:
14//! its centre is the whole middle, drawn even empty (a target for a tab
15//! dropped there), as the main window's. Each area is a dock of the
16//! workbench's one `egui_stack` space, which the main window's areas and
17//! every window's share (`in-window:<window>:<area>`): its tabs reorder,
18//! split and move between the window's areas by drag and drop, and a tab
19//! dragged into another window's area lands there, its new place saved
20//! with the layout (the space's drag spans the windows,
21//! `DockSpace::dragging`). An area keeps out the panels the main window's
22//! area of that name keeps out. Each tab's menu is the panel menu, as in
23//! the main window.
24//!
25//! # Its chrome
26//!
27//! As in the main window: a side area folds to a strip (its grip
28//! unfolds it, an icon per panel opens that panel as a flyout over the
29//! window's content) and the bottom folds out of sight
30//! (`AppHandle::fold_window_area`, saved in `WindowAreas::folded`); zen
31//! mode on one of its panels draws that panel alone in the window; each
32//! area and the window's content are F6 regions.
33//!
34//! # Where a panel opens (rule A)
35//!
36//! `pop.panel.open` carries the window it was asked from (`origin`): a
37//! menu, a command or a key fills it in with the window it runs in. A
38//! closed panel opened again goes, in this order:
39//!
40//! 1. where the application sends it: `pop.panel.home` answers a window
41//!    (its topology's home window, say), where it goes back to its last
42//!    place when that was there, else docks in its own area;
43//! 2. back to its last place, when that window is shown;
44//! 3. in the window it was asked from, in its own area (its declared
45//!    `area`, unless the application answers `pop.panel.home_area`);
46//! 4. that window gone, in the main window while it shows the shell, else
47//!    in the first window shown.
48//!
49//! Never in a window closed, nor in the main window while another
50//! window's content holds it.
51
52use std::collections::{BTreeMap, HashMap};
53
54use egui::{Id, Rect, Ui};
55use egui_pop_model::ids::PanelId;
56use egui_pop_model::layout::{Node, WindowAreas};
57use egui_pop_model::panels::Area;
58use egui_stack::{DockArea, DockSpace, NodeIndex, TabViewer};
59use serde_json::Value as Json;
60
61use super::{area_name, area_rules, empty_dock, panel_menu, read, to_dock};
62use crate::app::AppHandle;
63use crate::windows::WindowId;
64
65/// Where a panel opening was asked from, and where the application sends
66/// it (`pop.panel.home`), by window id.
67#[derive(Clone, Debug, Default, PartialEq, Eq)]
68pub(crate) struct OpenFrom {
69    /// The window the ask came from.
70    pub origin: Option<String>,
71    /// The window the application chose.
72    pub home: Option<String>,
73    /// The area the application chose (`pop.panel.home_area`), over the
74    /// panel's declared one.
75    pub area: Option<Area>,
76}
77
78impl OpenFrom {
79    /// Read from a step's arguments (`origin`, `home`); without an
80    /// `origin`, the window the change runs in.
81    pub(crate) fn of(app: &AppHandle, args: &Json) -> OpenFrom {
82        let text = |key: &str| args.get(key).and_then(Json::as_str).map(str::to_string);
83        OpenFrom {
84            origin: text("origin").or_else(|| Some(current_window(app))),
85            home: text("home"),
86            area: text("home_area").as_deref().and_then(super::area_from),
87        }
88    }
89}
90
91/// The window a change runs in: the one its command was asked in, else
92/// the window worked in last (a detached panel's counts as the main
93/// window's).
94pub(crate) fn current_window(app: &AppHandle) -> String {
95    app.window_of_group(app.current_window_group()).to_string()
96}
97
98/// The areas a window draws, in drawing order.
99const DRAWN: [Area; 4] = [Area::StartSide, Area::EndSide, Area::Bottom, Area::Center];
100
101/// What a window area's dock name starts with: `in-window:<window>:<area>`.
102const DOCK_PREFIX: &str = "in-window:";
103
104/// The name of an application window's area's dock in the workbench's
105/// space.
106pub(crate) fn dock_name(window: &str, area: Area) -> String {
107    format!("{DOCK_PREFIX}{window}:{}", area_name(area))
108}
109
110/// The window and the area a dock of the space stands for, when it is an
111/// application window's area.
112pub(crate) fn dock_place(name: &str) -> Option<(&str, Area)> {
113    let (window, area) = name.strip_prefix(DOCK_PREFIX)?.rsplit_once(':')?;
114    Some((window, super::area_from(area)?))
115}
116
117/// Adds each application window's areas to the workbench's space, a dock
118/// per area (an empty one kept, a target for a tab dropped there): the
119/// windows' docks share the main window's drag, so a tab moves from one
120/// window's area to another's as between the main window's areas.
121pub(crate) fn add_docks(space: &mut DockSpace<PanelId>, windows: &[WindowAreas]) {
122    for w in windows {
123        for area in DRAWN {
124            let name = dock_name(&w.window, area);
125            if space.has_dock(&name) {
126                continue;
127            }
128            let node = w.areas.iter().find(|(a, _)| *a == area).map(|(_, n)| n);
129            add_dock(space, &name, node);
130        }
131    }
132}
133
134/// Adds a window area's dock to the space, holding `node`, empty without.
135fn add_dock(space: &mut DockSpace<PanelId>, name: &str, node: Option<&Node>) {
136    let mut state = node.map_or_else(empty_dock, to_dock);
137    let tree = std::mem::take(state.main_surface_mut());
138    space.add_dock_tree(name, area_rules(), tree);
139}
140
141/// Each application window's areas, read back from the space, by window
142/// id: a window whose docks are all empty has none.
143pub(crate) fn read_docks(space: &DockSpace<PanelId>) -> BTreeMap<String, Vec<(Area, Node)>> {
144    let mut out: BTreeMap<String, Vec<(Area, Node)>> = BTreeMap::new();
145    for name in space.dock_names() {
146        let Some((window, area)) = dock_place(name) else {
147            continue;
148        };
149        let areas = out.entry(window.to_owned()).or_default();
150        if let Some(tree) = space.dock(name)
151            && !tree.is_empty()
152            && let Some(node) = read(tree, NodeIndex::root())
153        {
154            areas.push((area, node));
155        }
156    }
157    for areas in out.values_mut() {
158        areas.sort_by_key(|(a, _)| *a);
159    }
160    out
161}
162
163/// Draws an application window's content inside its areas, when it has
164/// panels in them; its content alone otherwise. A window whose middle is
165/// its centre dock (`WindowSpec::centre_dock`) draws its areas always,
166/// its centre in the whole middle, and never its content.
167pub(crate) fn show(app: &AppHandle, ui: &mut Ui, window: &WindowId, content: impl FnOnce(&mut Ui)) {
168    let centre_dock = app.window_centre_dock(window);
169    // Zen mode on one of its panels: that panel alone, its areas and
170    // content not drawn (and not changed).
171    let alone = app.workbench_mut().zen_in_app_window(window.as_str());
172    if let Some(panel) = alone {
173        super::show_alone(app, ui, &panel);
174        return;
175    }
176    // The window's areas as the space holds them now (a tab dropped in
177    // since, from any window).
178    let areas = {
179        let mut wb = app.workbench_mut();
180        wb.read_back();
181        wb.layout
182            .window_areas(window.as_str())
183            .map(|w| w.areas.clone())
184    };
185    let areas = areas.unwrap_or_default();
186    if areas.is_empty() && !centre_dock {
187        content(ui);
188        return;
189    }
190    let folded = app
191        .workbench_mut()
192        .layout
193        .window_areas(window.as_str())
194        .map(|w| w.folded.clone())
195        .unwrap_or_default();
196    let has = |area: Area| areas.iter().any(|(a, _)| *a == area);
197    let open = |area: Area| has(area) && !folded.contains(&area);
198    let strip = |area: Area| {
199        matches!(area, Area::StartSide | Area::EndSide) && has(area) && folded.contains(&area)
200    };
201    let salt = |area: Area| Id::unique(("egui_pop.window_area", window.as_str(), area_name(area)));
202    let mut viewer = WindowViewer { app };
203    // The window's docks keep their drag state apart from the other
204    // windows' (egui's memory is shared by all viewports), as egui_stack's
205    // native floats do; the space's session carries the drag across.
206    let area_id = super::space_id().with(("egui_pop.app_window", window.as_str()));
207    // Each area is a dock of the workbench's space, which every window
208    // shares: one drag across them all (`DockSpace::dragging`).
209    let mut dock = |ui: &mut Ui, area: Area| {
210        let region = egui_pop_core::focus::Region::new(
211            format!("region.window.{}", area_name(area)),
212            super::rank_of(area),
213        )
214        // A panel of text alone holds the focus itself (`region_panel`).
215        .holding(true);
216        let Some(mut space) = app.workbench_mut().take_space() else {
217            return;
218        };
219        let name = dock_name(window.as_str(), area);
220        if centre_dock && area == Area::Center && !space.has_dock(&name) {
221            // Its centre, empty, kept a target for a tab dropped there
222            // (the space projected again has no dock for a window
223            // without panels).
224            add_dock(&mut space, &name, None);
225        }
226        if space.has_dock(&name) {
227            egui_pop_core::focus::region(ui, &region, |ui| {
228                DockArea::dock(&mut space, &name)
229                    .id(area_id)
230                    .show_close_buttons(false)
231                    .show_add_buttons(false)
232                    .show_leaf_close_all_buttons(false)
233                    .show_leaf_collapse_buttons(false)
234                    .show_inside(ui, &mut viewer);
235            });
236        }
237        app.workbench_mut().put_space(space);
238    };
239    let size = ui.available_size();
240    let kit = egui_pop_core::kit::Kit::of(ui.ctx());
241    let strip_width = strip_breadth(ui.ctx(), &kit);
242    // Every area's frame has the same margins (`dock-area`), the centre's
243    // as the sides' and the bottom's, so their tab strips start at the
244    // same height and the gaps between them match, as in the main window.
245    let side_frame =
246        egui::Frame::side_top_panel(ui.style()).inner_margin(kit.dock_area_margin(false));
247    let centre_frame =
248        egui::Frame::central_panel(ui.style()).inner_margin(kit.dock_area_margin(false));
249    let mut strips = Vec::new();
250    for area in [Area::StartSide, Area::EndSide] {
251        if !strip(area) {
252            continue;
253        }
254        let panel = if area == Area::StartSide {
255            egui::Panel::left(salt(area).with("strip"))
256        } else {
257            egui::Panel::right(salt(area).with("strip"))
258        };
259        let r = panel
260            .resizable(false)
261            .exact_size(strip_width)
262            // The strip's cells run to its edges.
263            .frame(egui::Frame::side_top_panel(ui.style()).inner_margin(0.0))
264            .show(ui, |ui| window_strip(app, ui, &kit, window.as_str(), area));
265        strips.push((area, r.response.rect));
266    }
267    for area in [Area::StartSide, Area::EndSide] {
268        if !open(area) {
269            continue;
270        }
271        let panel = if area == Area::StartSide {
272            egui::Panel::left(salt(area))
273        } else {
274            egui::Panel::right(salt(area))
275        };
276        side_panel(app, panel, &areas, area, size.x)
277            .frame(side_frame)
278            .show(ui, |ui| dock(ui, area));
279    }
280    if open(Area::Bottom) {
281        egui::Panel::bottom(salt(Area::Bottom))
282            .resizable(true)
283            .default_size((size.y * 0.3).max(120.0))
284            .frame(side_frame)
285            .show(ui, |ui| dock(ui, Area::Bottom));
286    }
287    let centre = if centre_dock {
288        // The centre dock is the whole middle, as in the main window; the
289        // window has no content of its own.
290        drop(content);
291        let empty = !has(Area::Center);
292        egui::CentralPanel::default()
293            .frame(centre_frame)
294            .show(ui, |ui| {
295                let rect = ui.max_rect();
296                dock(ui, Area::Center);
297                if empty {
298                    empty_centre(ui, rect);
299                }
300            })
301            .response
302            .rect
303    } else {
304        if has(Area::Center) {
305            // The window's content keeps the start of the middle, its
306            // centre's panels beside it.
307            egui::Panel::right(salt(Area::Center))
308                .resizable(true)
309                .default_size(ui.available_width() * 0.5)
310                .frame(side_frame)
311                .show(ui, |ui| dock(ui, Area::Center));
312        }
313        egui::CentralPanel::default()
314            .show(ui, |ui| {
315                let region = egui_pop_core::focus::Region::new(
316                    "region.window.content",
317                    super::rank_of(Area::Center),
318                );
319                egui_pop_core::focus::region(ui, &region, content);
320            })
321            .response
322            .rect
323    };
324    // A folded side's panel shown as a flyout, over the content next to
325    // its strip.
326    let flyout = app.workbench_mut().flyout.clone();
327    if let Some(panel) = flyout {
328        let place = app
329            .workbench_mut()
330            .layout
331            .window_place(&panel)
332            .map(|(w, a)| (w.to_string(), a));
333        if let Some((_, area)) = place.filter(|(w, _)| w == window.as_str())
334            && let Some((_, rect)) = strips.iter().find(|(a, _)| *a == area)
335        {
336            show_flyout(app, ui, &kit, &panel, area, *rect, centre);
337        }
338    }
339    // What the docks changed (a tab moved, split, reordered, dropped in
340    // from another window or taken out to one), into the layout, saved.
341    let mut wb = app.workbench_mut();
342    wb.read_back();
343    let now = wb.layout.window_areas(window.as_str()).map(|w| &w.areas);
344    let changed = now.map_or(!areas.is_empty(), |now| *now != areas);
345    drop(wb);
346    if changed {
347        app.note_layout("workbench.window_areas");
348    }
349    // A tab dropped in, out of or between the windows' areas: its step.
350    super::settle_area_moves(app);
351}
352
353/// A side area's egui panel sized as the main window's side areas are
354/// (`Workbench::area_sizes`): never narrower than the largest least size
355/// of its panels (`PanelSpec::min_size`, or the one the application set,
356/// `AppBuilder::shell_panel_min_size`, `AppHandle::set_shell_panel_min_size`),
357/// never wider than a largest size the application set, first as wide as
358/// the largest `PanelSpec::default_size` (else a share of the window).
359fn side_panel(
360    app: &AppHandle,
361    panel: egui::Panel,
362    areas: &[(Area, Node)],
363    area: Area,
364    across: f32,
365) -> egui::Panel {
366    let panels: Vec<PanelId> = areas
367        .iter()
368        .filter(|(a, _)| *a == area)
369        .flat_map(|(_, node)| node.panels().into_iter().cloned())
370        .collect();
371    let (min, default, max) = app
372        .workbench_mut()
373        .area_sizes(&panels, &app.shell_bounds(), across);
374    let default = if default > 0.0 {
375        default
376    } else {
377        (across * 0.22).max(160.0)
378    };
379    let max = max.max(min);
380    // The default first: egui lowers the least size to it.
381    let mut panel = panel.resizable(true).default_size(default.clamp(min, max));
382    if min > 0.0 {
383        panel = panel.min_size(min);
384    }
385    if max.is_finite() {
386        panel = panel.max_size(max);
387    }
388    panel
389}
390
391/// An empty centre dock says so, to the eye and to a screen reader, as the
392/// main window's empty centre does, over its dock (which keeps the whole
393/// middle, a target for a tab dropped there).
394fn empty_centre(ui: &mut Ui, rect: Rect) {
395    let text = egui_pop_core::strings::tr(ui.ctx(), &crate::strings::WORKBENCH_DROP_HERE);
396    let mut over = ui.new_child(egui::UiBuilder::new().max_rect(rect));
397    over.centered_and_justified(|ui| {
398        ui.add(egui::Label::new(egui::RichText::new(text).weak()).selectable(false));
399    });
400}
401
402/// A strip's breadth: the kit's grip, widened to an icon's cell.
403fn strip_breadth(ctx: &egui::Context, kit: &egui_pop_core::kit::Kit) -> f32 {
404    let grip = kit.area_strip.data.width.max(1.0);
405    let t = egui_pop_core::theme::Tokens::of(ctx);
406    grip.max(t.size.icon_inline + 2.0 * t.space.s)
407}
408
409/// A folded side area's strip in an application window: a grip that
410/// unfolds the area, then an icon per panel, a click opening the panel as
411/// a flyout over the window's content, as in the main window.
412fn window_strip(
413    app: &AppHandle,
414    ui: &mut Ui,
415    kit: &egui_pop_core::kit::Kit,
416    window: &str,
417    area: Area,
418) {
419    let ctx = ui.ctx().clone();
420    let t = egui_pop_core::theme::Tokens::of(&ctx);
421    let rect = ui.max_rect();
422    let cell = rect.width();
423    let name = egui_pop_core::strings::tr_args(
424        &ctx,
425        &crate::strings::WORKBENCH_UNFOLD,
426        &[("area", &super::area_text(&ctx, area))],
427    );
428    let grip = Rect::from_min_size(rect.min, egui::vec2(cell, cell));
429    let icon = if super::on_left(area, app.workbench_mut().flipped) {
430        egui_pop_core::icon::Icon::ChevronRight
431    } else {
432        egui_pop_core::icon::Icon::ChevronLeft
433    };
434    let id = Id::unique(("egui_pop.window_strip_grip", window, super::area_name(area)));
435    let unfold = ui.interact(grip, id, egui::Sense::click());
436    let label = name.clone();
437    unfold.widget_info(move || egui::WidgetInfo::labeled(egui::Role::Button, true, &label));
438    let state = egui_pop_core::kit::State::from_response(&unfold);
439    let color = kit.activity_bar_item.style(state).text;
440    let glyph = Rect::from_center_size(
441        grip.center(),
442        egui::vec2(t.size.icon_inline, t.size.icon_inline),
443    );
444    egui_pop_core::icon::Source::from(icon).paint(ui, glyph, color);
445    if unfold.has_focus() {
446        egui_pop_core::focus::own_ring(&unfold.ctx, unfold.id);
447    }
448    if unfold.on_hover_text(&name).clicked() {
449        app.fold_window_area(window, area, false);
450    }
451    let panels: Vec<PanelId> = {
452        let wb = app.workbench_mut();
453        let areas = wb.layout.window_areas(window);
454        let node = areas.and_then(|w| w.areas.iter().find(|(a, _)| *a == area));
455        node.map(|(_, n)| n.panels().into_iter().cloned().collect())
456            .unwrap_or_default()
457    };
458    let mut top = grip.bottom() + t.space.xs;
459    for p in panels.iter().filter(|p| super::drawable(app, p)) {
460        let at = Rect::from_min_size(egui::pos2(rect.left(), top), egui::vec2(cell, cell));
461        if at.bottom() > rect.bottom() {
462            break;
463        }
464        super::strip_icon(app, ui, kit, area, p, at, false, false);
465        top += cell + t.space.xs;
466    }
467}
468
469/// A folded side's panel shown alone over the window's content, next to
470/// its strip (`strip`), as the main window's flyout: closed by Escape or
471/// a press away (the overlay stack), its band's pin unfolding the area.
472fn show_flyout(
473    app: &AppHandle,
474    ui: &mut Ui,
475    kit: &egui_pop_core::kit::Kit,
476    panel: &PanelId,
477    area: Area,
478    strip: Rect,
479    centre: Rect,
480) {
481    let width = app
482        .workbench_mut()
483        .layout
484        .flyouts
485        .get(panel)
486        .copied()
487        .unwrap_or(240.0)
488        .clamp(48.0, centre.width().max(48.0));
489    let rect = if strip.center().x <= centre.center().x {
490        Rect::from_min_size(
491            egui::pos2(strip.right(), centre.top()),
492            egui::vec2(width, centre.height()),
493        )
494    } else {
495        Rect::from_min_size(
496            egui::pos2(strip.left() - width, centre.top()),
497            egui::vec2(width, centre.height()),
498        )
499    };
500    let layer = egui::LayerId::new(
501        egui::Order::Middle,
502        Id::unique(("egui_pop.window_flyout", panel.as_str())),
503    );
504    let mut over = ui.new_child(
505        egui::UiBuilder::new()
506            .layer_id(layer)
507            .id_salt(("egui_pop.window_flyout", panel.as_str()))
508            .max_rect(rect),
509    );
510    over.painter()
511        .rect_filled(rect, 0.0, over.visuals().window_fill);
512    over.painter().rect_stroke(
513        rect,
514        0.0,
515        over.visuals().window_stroke,
516        egui::StrokeKind::Inside,
517    );
518    if !super::flyout_body(app, &mut over, kit, (area, strip.width()), panel) {
519        app.change_workbench(super::Change::Flyout(panel.clone(), false));
520    }
521}
522
523/// The panels of a window's areas, as tabs: each drawn by its panel, its
524/// menu the panel menu.
525struct WindowViewer<'a> {
526    app: &'a AppHandle,
527}
528
529impl TabViewer for WindowViewer<'_> {
530    type Tab = PanelId;
531
532    fn id(&mut self, tab: &mut PanelId) -> Id {
533        Id::unique(("egui_pop.window_panel", tab.as_str()))
534    }
535
536    fn title(&mut self, tab: &mut PanelId) -> egui::WidgetText {
537        self.app.panel_title(&self.app.egui(), tab).into()
538    }
539
540    fn ui(&mut self, ui: &mut Ui, tab: &mut PanelId) {
541        self.app.show_panel(ui, tab);
542    }
543
544    fn on_tab_button(&mut self, tab: &mut PanelId, response: &egui::Response) {
545        let title = self.app.panel_title(&response.ctx, tab);
546        egui_pop_core::a11y::name(response, egui::Role::Tab, &title);
547    }
548
549    fn context_menu(&mut self, ui: &mut Ui, tab: &mut PanelId, _path: egui_stack::TabPath) {
550        panel_menu::show(ui, self.app, tab);
551    }
552
553    fn allowed_in_windows(&self, _tab: &mut PanelId) -> bool {
554        false
555    }
556}
557
558/// The panel F6 gives the keyboard to in an application window's area
559/// region (`region.window.<area>`) when nothing there takes the focus:
560/// the area's shown tab, in the window worked in.
561pub(crate) fn region_panel(app: &AppHandle, region: &str) -> Option<PanelId> {
562    let area = super::area_from(region.strip_prefix("region.window.")?)?;
563    let window = current_window(app);
564    let wb = app.workbench_mut();
565    let w = wb.layout.window_areas(&window)?;
566    let (_, node) = w.areas.iter().find(|(a, _)| *a == area)?;
567    first_shown(node).cloned()
568}
569
570/// The shown tab of a node's first tab group.
571fn first_shown(node: &Node) -> Option<&PanelId> {
572    match node {
573        Node::Tabs { panels, active } => panels.get(*active).or(panels.first()),
574        Node::Split { a, b, .. } => first_shown(a).or_else(|| first_shown(b)),
575        Node::Grid { children, .. } => children.iter().find_map(first_shown),
576    }
577}
578
579/// The panels each window's areas hold, by window id, as an agent reads
580/// them.
581pub fn panels_by_window(app: &AppHandle) -> HashMap<String, Vec<(Area, Vec<PanelId>)>> {
582    let wb = app.workbench_mut();
583    wb.layout
584        .windows
585        .iter()
586        .map(|w| {
587            let areas = (w.areas.iter())
588                .map(|(a, n)| (*a, n.panels().into_iter().cloned().collect()))
589                .collect();
590            (w.window.clone(), areas)
591        })
592        .collect()
593}