Skip to main content

egui/
ui_stack.rs

1use alloc::sync::Arc;
2use core::{any::Any, iter::FusedIterator};
3
4use crate::class::{Classes, HasClasses as _};
5use epaint::Color32;
6
7use crate::{Direction, Frame, Id, Rect};
8
9/// What kind is this [`crate::Ui`]?
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum UiKind {
12    /// A [`crate::Window`].
13    Window,
14
15    /// A [`crate::CentralPanel`].
16    CentralPanel,
17
18    /// A left [`crate::Panel`].
19    LeftPanel,
20
21    /// A right [`crate::Panel`].
22    RightPanel,
23
24    /// A top [`crate::Panel`].
25    TopPanel,
26
27    /// A bottom [`crate::Panel`].
28    BottomPanel,
29
30    /// A modal [`crate::Modal`].
31    Modal,
32
33    /// A [`crate::Frame`].
34    Frame,
35
36    /// A [`crate::ScrollArea`].
37    ScrollArea,
38
39    /// A [`crate::Resize`].
40    Resize,
41
42    /// The content of a regular menu.
43    Menu,
44
45    /// The content of a popup menu.
46    Popup,
47
48    /// A tooltip, as shown by e.g. [`crate::Response::on_hover_ui`].
49    Tooltip,
50
51    /// A picker, such as color picker.
52    Picker,
53
54    /// A table cell (from the `egui_extras` crate).
55    TableCell,
56
57    /// An [`crate::Area`] that is not of any other kind.
58    GenericArea,
59
60    /// A collapsible container, e.g. a [`crate::CollapsingHeader`].
61    Collapsible,
62}
63
64impl UiKind {
65    /// The accessibility role of a [`crate::Ui`] of this kind.
66    ///
67    /// Kinds with no role of their own are plain [`accesskit::Role::GenericContainer`]s.
68    pub fn accesskit_role(self) -> accesskit::Role {
69        use accesskit::Role;
70        match self {
71            Self::LeftPanel
72            | Self::RightPanel
73            | Self::TopPanel
74            | Self::BottomPanel
75            | Self::CentralPanel => Role::Pane,
76            Self::Modal | Self::Popup => Role::Dialog,
77            Self::Menu => Role::Menu,
78            Self::Tooltip => Role::Tooltip,
79            Self::Window
80            | Self::Frame
81            | Self::ScrollArea
82            | Self::Resize
83            | Self::Picker
84            | Self::TableCell
85            | Self::GenericArea
86            | Self::Collapsible => Role::GenericContainer,
87        }
88    }
89
90    /// Is this any kind of panel?
91    #[inline]
92    pub fn is_panel(&self) -> bool {
93        matches!(
94            self,
95            Self::CentralPanel
96                | Self::LeftPanel
97                | Self::RightPanel
98                | Self::TopPanel
99                | Self::BottomPanel
100        )
101    }
102
103    /// Is this any kind of [`crate::Area`]?
104    #[inline]
105    pub fn is_area(&self) -> bool {
106        match self {
107            Self::CentralPanel
108            | Self::LeftPanel
109            | Self::RightPanel
110            | Self::TopPanel
111            | Self::BottomPanel
112            | Self::Frame
113            | Self::ScrollArea
114            | Self::Resize
115            | Self::Collapsible
116            | Self::TableCell => false,
117
118            Self::Window
119            | Self::Menu
120            | Self::Modal
121            | Self::Popup
122            | Self::Tooltip
123            | Self::Picker
124            | Self::GenericArea => true,
125        }
126    }
127}
128
129// ----------------------------------------------------------------------------
130
131/// Information about a [`crate::Ui`] to be included in the corresponding [`UiStack`].
132#[derive(Clone, Default, Debug)]
133pub struct UiStackInfo {
134    pub kind: Option<UiKind>,
135    pub frame: Frame,
136    pub tags: UiTags,
137}
138
139impl UiStackInfo {
140    /// Create a new [`UiStackInfo`] with the given kind and an empty frame.
141    #[inline]
142    pub fn new(kind: UiKind) -> Self {
143        Self {
144            kind: Some(kind),
145            ..Default::default()
146        }
147    }
148
149    #[inline]
150    pub fn with_frame(mut self, frame: Frame) -> Self {
151        self.frame = frame;
152        self
153    }
154
155    /// Insert a tag with no value.
156    #[inline]
157    pub fn with_tag(mut self, key: impl Into<String>) -> Self {
158        self.tags.insert(key, None);
159        self
160    }
161
162    /// Insert a tag with some value.
163    #[inline]
164    pub fn with_tag_value(
165        mut self,
166        key: impl Into<String>,
167        value: impl Any + Send + Sync + 'static,
168    ) -> Self {
169        self.tags.insert(key, Some(Arc::new(value)));
170        self
171    }
172}
173
174// ----------------------------------------------------------------------------
175
176/// User-chosen tags.
177///
178/// You can use this in any way you want,
179/// i.e. to set some tag on a [`crate::Ui`] and then in your own widget check
180/// for the existence of this tag up the [`UiStack`].
181///
182/// Note that egui never sets any tags itself, so this is purely for user code.
183///
184/// All tagging is transient, and will only live as long as the parent [`crate::Ui`], i.e. within a single render frame.
185#[derive(Clone, Default, Debug)]
186pub struct UiTags(pub ahash::HashMap<String, Option<Arc<dyn Any + Send + Sync + 'static>>>);
187
188impl UiTags {
189    #[inline]
190    pub fn insert(
191        &mut self,
192        key: impl Into<String>,
193        value: Option<Arc<dyn Any + Send + Sync + 'static>>,
194    ) {
195        self.0.insert(key.into(), value);
196    }
197
198    #[inline]
199    pub fn contains(&self, key: &str) -> bool {
200        self.0.contains_key(key)
201    }
202
203    /// Get the value of a tag.
204    ///
205    /// Note that `None` is returned both if the key is set to the value `None`,
206    /// and if the key is not set at all.
207    #[inline]
208    pub fn get_any(&self, key: &str) -> Option<&Arc<dyn Any + Send + Sync + 'static>> {
209        self.0.get(key)?.as_ref()
210    }
211
212    /// Get the value of a tag.
213    ///
214    /// Note that `None` is returned both if the key is set to the value `None`,
215    /// and if the key is not set at all.
216    pub fn get_downcast<T: Any + Send + Sync + 'static>(&self, key: &str) -> Option<&T> {
217        self.0.get(key)?.as_ref().and_then(|any| any.downcast_ref())
218    }
219}
220
221// ----------------------------------------------------------------------------
222
223/// Information about a [`crate::Ui`] and its parents.
224///
225/// [`UiStack`] serves to keep track of the current hierarchy of [`crate::Ui`]s, such
226/// that nested widgets or user code may adapt to the surrounding context or obtain layout information
227/// from a [`crate::Ui`] that might be several steps higher in the hierarchy.
228///
229/// Note: since [`UiStack`] contains a reference to its parent, it is both a stack, and a node within
230/// that stack. Most of its methods are about the specific node, but some methods walk up the
231/// hierarchy to provide information about the entire stack.
232#[derive(Debug)]
233pub struct UiStack {
234    // stuff that `Ui::child_ui` can deal with directly
235    /// The [`crate::Ui::unique_id`] of this [`crate::Ui`].
236    ///
237    /// Globally unique, but NOT stable over time.
238    /// For the stable id scope, see [`Self::scope_id`].
239    pub unique_id: Id,
240
241    /// The [`crate::Ui::scope_id`] of this [`crate::Ui`].
242    ///
243    /// Stable over time, but shared with sibling [`crate::Ui`]s
244    /// that were not given different id salts.
245    /// For a globally unique id, see [`Self::unique_id`].
246    pub scope_id: Id,
247    pub info: UiStackInfo,
248    pub layout_direction: Direction,
249    pub min_rect: Rect,
250    pub max_rect: Rect,
251    pub parent: Option<Arc<Self>>,
252    pub classes: Classes,
253}
254
255// these methods act on this specific node
256impl UiStack {
257    #[inline]
258    pub fn kind(&self) -> Option<UiKind> {
259        self.info.kind
260    }
261
262    #[inline]
263    pub fn frame(&self) -> &Frame {
264        &self.info.frame
265    }
266
267    /// User tags.
268    #[inline]
269    pub fn tags(&self) -> &UiTags {
270        &self.info.tags
271    }
272
273    /// Is this [`crate::Ui`] a panel?
274    #[inline]
275    pub fn is_panel_ui(&self) -> bool {
276        self.kind().is_some_and(|kind| kind.is_panel())
277    }
278
279    /// Is this [`crate::Ui`] an [`crate::Area`]?
280    #[inline]
281    pub fn is_area_ui(&self) -> bool {
282        self.kind().is_some_and(|kind| kind.is_area())
283    }
284
285    /// Is this a root [`crate::Ui`], i.e. created with [`crate::Ui::new()`]?
286    #[inline]
287    pub fn is_root_ui(&self) -> bool {
288        self.parent.is_none()
289    }
290
291    /// This this [`crate::Ui`] a [`crate::Frame`] with a visible stroke?
292    #[inline]
293    pub fn has_visible_frame(&self) -> bool {
294        !self.info.frame.stroke.is_empty()
295    }
296
297    /// The background color of this [`crate::Ui`].
298    ///
299    /// This blend together all [`Frame::fill`] colors
300    /// up to the root.
301    #[inline]
302    pub fn bg_color(&self) -> Color32 {
303        let mut total = Color32::TRANSPARENT;
304        for node in self.iter() {
305            let fill = node.frame().fill;
306            if fill != Color32::TRANSPARENT {
307                total = fill.blend(total);
308                if total.is_opaque() {
309                    break;
310                }
311            }
312        }
313        total
314    }
315}
316
317// these methods act on the entire stack
318impl UiStack {
319    /// Return an iterator that walks the stack from this node to the root.
320    #[expect(clippy::iter_without_into_iter)]
321    pub fn iter(&self) -> UiStackIterator<'_> {
322        UiStackIterator { next: Some(self) }
323    }
324
325    /// Check if this node is or is contained in a [`crate::Ui`] of a specific kind.
326    pub fn contained_in(&self, kind: UiKind) -> bool {
327        self.iter().any(|frame| frame.kind() == Some(kind))
328    }
329
330    /// Does this node, or any [`crate::Ui`] up the stack, carry this class?
331    pub fn has_class(&self, class: &str) -> bool {
332        self.iter().any(|node| node.classes.has_class(class))
333    }
334}
335
336// ----------------------------------------------------------------------------
337
338/// Iterator that walks up a stack of `StackFrame`s.
339///
340/// See [`UiStack::iter`].
341pub struct UiStackIterator<'a> {
342    next: Option<&'a UiStack>,
343}
344
345impl<'a> Iterator for UiStackIterator<'a> {
346    type Item = &'a UiStack;
347
348    #[inline]
349    fn next(&mut self) -> Option<Self::Item> {
350        let current = self.next;
351        self.next = current.and_then(|frame| frame.parent.as_deref());
352        current
353    }
354}
355
356impl FusedIterator for UiStackIterator<'_> {}