egui_pop_core/layers.rs
1//! Layer ranks: a fixed order between the foreground layers of a window
2//! (ADR 0026).
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! egui has no z-index: inside an [`Order`], the layer shown or clicked
8//! last goes on top. A panel lying over the centre and an application's
9//! card both live in [`Order::Foreground`], so a click on the panel would
10//! put it over the card. Ranks fix the order between kinds of layers,
11//! bottom to top, in each window:
12//!
13//! 1. the docked panels and the central panel (egui's background);
14//! 2. [`Rank::Over`]: the zones lying over their neighbour and flyouts;
15//! 3. [`Rank::Overlay`]: egui-pop's and the application's overlays
16//! (cards, popovers, toasts, the zen way out);
17//! 4. every foreground layer nobody ranked: menus, combo lists, context
18//! menus, dialogs;
19//! 5. tooltips ([`Order::Tooltip`]).
20//!
21//! Inside a rank, egui's rule still holds: the layer clicked last is on
22//! top.
23//!
24//! Each pinned rank has a base: an empty foreground layer egui-pop puts
25//! at the bottom of the foreground on a window's first pass and never
26//! raises. A ranked layer is made a sublayer of its rank's base each
27//! pass ([`egui::Context::set_sublayer`]), so egui moves it right above
28//! that base at the end of the pass, whatever was clicked.
29//!
30//! An application overlay calls [`area`] where it would show an
31//! [`egui::Area`] (instead of calling `ctx.move_to_top` on it):
32//!
33//! ```no_run
34//! # fn card(ctx: &egui::Context) {
35//! use egui_pop_core::layers::{self, Rank};
36//!
37//! layers::area(
38//! ctx,
39//! egui::Area::new(egui::Id::unique("my_app.card")).anchor(egui::Align2::LEFT_BOTTOM, [8.0, -8.0]),
40//! Rank::Overlay,
41//! |ui| ui.label("Did you know?"),
42//! );
43//! # }
44//! ```
45//!
46//! A layer drawn some other way (a [`egui::Context::layer_painter`])
47//! calls [`rank`] each pass it is shown. A layer left unranked stays
48//! above every ranked one; a layer to keep under the lying-over zones is
49//! made a sublayer of [`base`]`(ctx, Rank::Over)` by its owner.
50//!
51//! [`begin_pass`] and [`end_pass`] run at the start and the end of every
52//! pass of every window once [`install`] was called (the application
53//! does).
54
55use std::collections::HashMap;
56
57use egui::{Context, Id, InnerResponse, LayerId, Order, Ui};
58
59use crate::state::{lock, shared_in_window};
60
61/// Where a foreground layer sits among the others of its window, bottom
62/// to top (see [the module](self)). The ranks not listed here are
63/// egui's: the background below, the unranked foreground layers and
64/// tooltips above.
65#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
66pub enum Rank {
67 /// The zones lying over their neighbour and flyouts.
68 Over,
69 /// Overlays: cards, popovers, toasts, the zen way out, an
70 /// application's own.
71 Overlay,
72}
73
74impl Rank {
75 /// Every rank, bottom to top.
76 pub const ALL: [Rank; 2] = [Rank::Over, Rank::Overlay];
77
78 fn name(self) -> &'static str {
79 match self {
80 Rank::Over => "over",
81 Rank::Overlay => "overlay",
82 }
83 }
84}
85
86/// The base layer of `rank`: an empty foreground layer kept at the
87/// bottom of the foreground, the ranked layers right above it. A host
88/// drawing its own lying-over surface makes it a sublayer of
89/// `base(ctx, Rank::Over)` (egui_stack's `LayoutArea::sublayer_of`).
90///
91/// The same in every window: each window has its own egui order.
92pub fn base(_ctx: &Context, rank: Rank) -> LayerId {
93 LayerId::new(
94 Order::Foreground,
95 Id::unique(("egui_pop.layers.base", rank.name())),
96 )
97}
98
99/// An empty layer each base holds as its sublayer, so that the base is
100/// in egui's order from the first pass on.
101fn anchor(rank: Rank) -> LayerId {
102 LayerId::new(
103 Order::Foreground,
104 Id::unique(("egui_pop.layers.anchor", rank.name())),
105 )
106}
107
108/// The layers ranked in a window: this pass's and the previous one's.
109#[derive(Debug, Default)]
110struct Ranked {
111 pass: u64,
112 now: HashMap<LayerId, Rank>,
113 last: HashMap<LayerId, Rank>,
114}
115
116impl Ranked {
117 /// Moves on to `pass`: what was ranked in the pass before stays
118 /// readable for this one.
119 fn at(&mut self, pass: u64) -> &mut Self {
120 if self.pass != pass {
121 self.last = if self.pass + 1 == pass {
122 std::mem::take(&mut self.now)
123 } else {
124 HashMap::new()
125 };
126 self.now.clear();
127 self.pass = pass;
128 }
129 self
130 }
131}
132
133fn note(ctx: &Context, layer: LayerId, rank: Rank) {
134 let st = shared_in_window::<Ranked>(ctx, "core.layers.ranked");
135 lock(&st)
136 .at(ctx.cumulative_pass_nr())
137 .now
138 .insert(layer, rank);
139}
140
141/// The rank `layer` was given in this pass or the previous one, in the
142/// window being drawn; `None` for a layer nobody ranked.
143pub fn rank_of(ctx: &Context, layer: LayerId) -> Option<Rank> {
144 if let Some(r) = Rank::ALL.into_iter().find(|r| base(ctx, *r) == layer) {
145 return Some(r);
146 }
147 let st = shared_in_window::<Ranked>(ctx, "core.layers.ranked");
148 let mut s = lock(&st);
149 let s = s.at(ctx.cumulative_pass_nr());
150 s.now.get(&layer).or_else(|| s.last.get(&layer)).copied()
151}
152
153/// Puts `layer` at `rank` for this pass: call it each pass the layer is
154/// shown. Only a foreground layer can be ranked; another is left where
155/// it is.
156pub fn rank(ctx: &Context, layer: LayerId, rank: Rank) {
157 if layer.order != Order::Foreground {
158 log::debug!("layers: {layer:?} is not a foreground layer, left unranked");
159 return;
160 }
161 ctx.set_sublayer(base(ctx, rank), layer);
162 note(ctx, layer, rank);
163}
164
165/// Puts `layer` at `rank` when the layer it was opened from, `opener`,
166/// lies at that rank or below it (a panel, a window, a lying-over zone,
167/// another overlay); leaves it unranked, above its opener, when the
168/// opener is above that rank (a dialog, a menu). Returns whether it was
169/// ranked.
170///
171/// A hover card or a popover opened from a dialog thus stays above the
172/// dialog.
173pub fn rank_from(ctx: &Context, layer: LayerId, rank: Rank, opener: LayerId) -> bool {
174 let below = match opener.order {
175 Order::Background | Order::Middle => true,
176 Order::Foreground => rank_of(ctx, opener).is_some_and(|r| r <= rank),
177 Order::Tooltip | Order::Debug => false,
178 };
179 if below {
180 self::rank(ctx, layer, rank);
181 }
182 below
183}
184
185/// Shows `area` in the foreground at `rank`: what an application calls
186/// for its own overlay instead of `ctx.move_to_top`.
187pub fn area<R>(
188 ctx: &Context,
189 area: egui::Area,
190 rank: Rank,
191 add_contents: impl FnOnce(&mut Ui) -> R,
192) -> InnerResponse<R> {
193 let r = area.order(Order::Foreground).show(ctx, add_contents);
194 self::rank(ctx, r.response.layer_id, rank);
195 r
196}
197
198/// Starts a pass of the window being drawn: puts the bases into egui's
199/// order, `Over` under `Overlay`. On a window's first pass, before any
200/// other foreground layer is shown, this puts them at the bottom of the
201/// foreground, where they stay since nothing raises them. Calling it
202/// again in a pass does nothing more.
203pub fn begin_pass(ctx: &Context) {
204 for r in Rank::ALL {
205 ctx.set_sublayer(base(ctx, r), anchor(r));
206 }
207}
208
209/// Ends a pass of the window being drawn: a ranked layer's own
210/// sublayers (a scene, a canvas overlay inside a lying-over panel) are
211/// made sublayers of its base too, since egui nests one level only; and
212/// the layers someone else made sublayers of a base (egui_stack's
213/// lying-over zones) are noted at its rank.
214pub fn end_pass(ctx: &Context) {
215 for r in Rank::ALL {
216 let b = base(ctx, r);
217 let children: Vec<LayerId> = ctx.memory(|m| m.areas().child_layers(b).collect());
218 for child in children {
219 if child == anchor(r) {
220 continue;
221 }
222 note(ctx, child, r);
223 let nested: Vec<LayerId> = ctx.memory(|m| m.areas().child_layers(child).collect());
224 for n in nested {
225 if n.order == Order::Foreground {
226 ctx.set_sublayer(b, n);
227 note(ctx, n, r);
228 }
229 }
230 }
231 }
232}
233
234/// Runs [`begin_pass`] and [`end_pass`] in every pass of every window.
235#[derive(Debug)]
236struct LayersPlugin;
237
238impl egui::plugin::Plugin for LayersPlugin {
239 fn debug_name(&self) -> &'static str {
240 "egui_pop_core::layers"
241 }
242
243 fn on_begin_pass(&mut self, ui: &mut Ui) {
244 begin_pass(ui.ctx());
245 }
246
247 fn on_end_pass(&mut self, ui: &mut Ui) {
248 end_pass(ui.ctx());
249 }
250}
251
252#[derive(Debug, Default)]
253struct Installed(bool);
254
255/// Installs the ranks on a context (once; later calls do nothing), and
256/// starts the current pass: call it before the pass shows any
257/// foreground layer.
258pub fn install(ctx: &Context) {
259 let st = crate::state::shared::<Installed>(ctx, "core.layers.installed");
260 let mut s = lock(&st);
261 if !s.0 {
262 s.0 = true;
263 drop(s);
264 ctx.add_plugin(LayersPlugin);
265 }
266 begin_pass(ctx);
267}