Skip to main content

egui/memory/
mod.rs

1#![warn(missing_docs)] // Let's keep this file well-documented.` to memory.rs
2
3use alloc::sync::Arc;
4use core::num::NonZeroUsize;
5
6use ahash::{HashMap, HashSet};
7use epaint::emath::TSTransform;
8
9use crate::{
10    EventFilter, Id, IdMap, LayerId, Order, Pos2, Rangef, RawInput, Rect, Style, Vec2, ViewportId,
11    ViewportIdMap, ViewportIdSet, area, vec2,
12};
13
14mod theme;
15pub use theme::{Theme, ThemePreference};
16
17// ----------------------------------------------------------------------------
18
19/// The data that egui persists between frames.
20///
21/// This includes window positions and sizes,
22/// how far the user has scrolled in a [`ScrollArea`](crate::ScrollArea) etc.
23///
24/// If you want this to persist when closing your app, you should serialize [`Memory`] and store it.
25/// For this you need to enable the `persistence` feature.
26///
27/// If you want to store data for your widgets, you should look at [`Memory::data`]
28#[derive(Clone, Debug)]
29#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
30#[cfg_attr(feature = "persistence", serde(default))]
31pub struct Memory {
32    /// Global egui options.
33    pub options: Options,
34
35    /// This map stores some superficial state for all widgets with custom [`Id`]s.
36    ///
37    /// This includes storing whether a [`crate::CollapsingHeader`] is open, how far scrolled a
38    /// [`crate::ScrollArea`] is, where the cursor in a [`crate::TextEdit`] is, etc.
39    ///
40    /// This is NOT meant to store any important data. Store that in your own structures!
41    ///
42    /// Each read clones the data, so keep your values cheap to clone.
43    /// If you want to store a lot of data, you should wrap it in `Arc<Mutex<…>>` so it is cheap to clone.
44    ///
45    /// This will be saved between different program runs if you use the `persistence` feature.
46    ///
47    /// To store a state common for all your widgets (a singleton), use [`Id::NULL`] as the key.
48    pub data: crate::util::IdTypeMap,
49
50    // ------------------------------------------
51    /// Can be used to cache computations from one frame to another.
52    ///
53    /// This is for saving CPU time when you have something that may take 1-100ms to compute.
54    /// Very slow operations (>100ms) should instead be done async (i.e. in another thread)
55    /// so as not to lock the UI thread.
56    ///
57    /// ```
58    /// use egui::cache::{ComputerMut, FrameCache};
59    ///
60    /// #[derive(Default)]
61    /// struct CharCounter {}
62    /// impl ComputerMut<&str, usize> for CharCounter {
63    ///     fn compute(&mut self, s: &str) -> usize {
64    ///         s.chars().count() // you probably want to cache something more expensive than this
65    ///     }
66    /// }
67    /// type CharCountCache<'a> = FrameCache<usize, CharCounter>;
68    ///
69    /// # let mut ctx = egui::Context::default();
70    /// ctx.memory_mut(|mem| {
71    ///     let cache = mem.caches.cache::<CharCountCache<'_>>();
72    ///     assert_eq!(*cache.get("hello"), 5);
73    /// });
74    /// ```
75    #[cfg_attr(feature = "persistence", serde(skip))]
76    pub caches: crate::cache::CacheStorage,
77
78    // ------------------------------------------
79    /// new fonts that will be applied at the start of the next frame
80    #[cfg_attr(feature = "persistence", serde(skip))]
81    pub(crate) new_font_definitions: Option<epaint::text::FontDefinitions>,
82
83    /// add new font that will be applied at the start of the next frame
84    #[cfg_attr(feature = "persistence", serde(skip))]
85    pub(crate) add_fonts: Vec<epaint::text::FontInsert>,
86
87    // Current active viewport
88    #[cfg_attr(feature = "persistence", serde(skip))]
89    pub(crate) viewport_id: ViewportId,
90
91    #[cfg_attr(feature = "persistence", serde(skip))]
92    everything_is_visible: bool,
93
94    /// Transforms per layer.
95    ///
96    /// Instead of using this directly, use:
97    /// * [`crate::Context::set_transform_layer`]
98    /// * [`crate::Context::layer_transform_to_global`]
99    /// * [`crate::Context::layer_transform_from_global`]
100    pub to_global: HashMap<LayerId, TSTransform>,
101
102    // -------------------------------------------------
103    // Per-viewport:
104    areas: ViewportIdMap<Areas>,
105
106    #[cfg_attr(feature = "persistence", serde(skip))]
107    pub(crate) interactions: ViewportIdMap<InteractionState>,
108
109    #[cfg_attr(feature = "persistence", serde(skip))]
110    pub(crate) focus: ViewportIdMap<Focus>,
111
112    /// Which popup-window is open on a viewport (if any)?
113    /// Could be a combo box, color picker, menu, etc.
114    /// Optionally stores the position of the popup (usually this would be the position where
115    /// the user clicked).
116    /// If position is [`None`], the popup position will be calculated based on some configuration
117    /// (e.g. relative to some other widget).
118    #[cfg_attr(feature = "persistence", serde(skip))]
119    popups: ViewportIdMap<OpenPopup>,
120
121    /// Whether to inform the backend to interrupt any ongoing IME composition
122    /// this pass.
123    #[cfg_attr(feature = "persistence", serde(skip))]
124    requested_interrupt_ime: bool,
125}
126
127impl Default for Memory {
128    fn default() -> Self {
129        let mut slf = Self {
130            options: Default::default(),
131            data: Default::default(),
132            caches: Default::default(),
133            new_font_definitions: Default::default(),
134            interactions: Default::default(),
135            focus: Default::default(),
136            viewport_id: Default::default(),
137            areas: Default::default(),
138            to_global: Default::default(),
139            popups: Default::default(),
140            everything_is_visible: Default::default(),
141            add_fonts: Default::default(),
142            requested_interrupt_ime: Default::default(),
143        };
144        slf.interactions.entry(slf.viewport_id).or_default();
145        slf.areas.entry(slf.viewport_id).or_default();
146        slf
147    }
148}
149
150/// A direction in which to move the keyboard focus.
151#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
152pub enum FocusDirection {
153    /// Select the widget closest above the current focused widget.
154    Up,
155
156    /// Select the widget to the right of the current focused widget.
157    Right,
158
159    /// Select the widget below the current focused widget.
160    Down,
161
162    /// Select the widget to the left of the current focused widget.
163    Left,
164
165    /// Select the previous widget that had focus.
166    Previous,
167
168    /// Select the next widget that wants focus.
169    Next,
170
171    /// Don't change focus.
172    #[default]
173    None,
174}
175
176impl FocusDirection {
177    pub(crate) fn is_cardinal(&self) -> bool {
178        match self {
179            Self::Up | Self::Right | Self::Down | Self::Left => true,
180
181            Self::Previous | Self::Next | Self::None => false,
182        }
183    }
184}
185
186// ----------------------------------------------------------------------------
187
188/// Some global options that you can read and write.
189///
190/// See also [`crate::style::DebugOptions`].
191#[derive(Clone, Debug, PartialEq)]
192#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
193#[cfg_attr(feature = "serde", serde(default))]
194pub struct Options {
195    /// The default style for new [`Ui`](crate::Ui):s in dark mode.
196    #[cfg_attr(feature = "serde", serde(skip))]
197    pub dark_style: Arc<Style>,
198
199    /// The default style for new [`Ui`](crate::Ui):s in light mode.
200    #[cfg_attr(feature = "serde", serde(skip))]
201    pub light_style: Arc<Style>,
202
203    /// Preference for selection between dark and light [`crate::Context::global_style`]
204    /// as the active style used by all subsequent windows, panels, etc.
205    ///
206    /// Default: `ThemePreference::System`.
207    pub theme_preference: ThemePreference,
208
209    /// Which theme to use in case [`Self::theme_preference`] is [`ThemePreference::System`]
210    /// and egui fails to detect the system theme.
211    ///
212    /// Default: [`crate::Theme::Dark`].
213    pub fallback_theme: Theme,
214
215    /// The current system theme, used to choose between
216    /// dark and light style in case [`Self::theme_preference`] is [`ThemePreference::System`].
217    #[cfg_attr(feature = "serde", serde(skip))]
218    pub(crate) system_theme: Option<Theme>,
219
220    /// If `true`, egui will keep the native window theme in sync with
221    /// [`Self::theme_preference`] by sending a [`crate::ViewportCommand::SetTheme`]
222    /// to the root viewport whenever the preference changes.
223    ///
224    /// This makes the native window decorations (title bar, borders, …) match the
225    /// theme selected inside egui.
226    ///
227    /// Set this to `false` if you want to manage the native window theme yourself.
228    ///
229    /// This is `true` by default.
230    pub sync_window_theme: bool,
231
232    /// Global zoom factor of the UI.
233    ///
234    /// This is used to calculate the `pixels_per_point`
235    /// for the UI as `pixels_per_point = zoom_fator * native_pixels_per_point`.
236    ///
237    /// The default is 1.0. Increase it to make all UI elements larger.
238    ///
239    /// You should call [`crate::Context::set_zoom_factor`]
240    /// instead of modifying this directly!
241    pub zoom_factor: f32,
242
243    /// If `true`, egui will change the scale of the ui ([`crate::Context::zoom_factor`]) when the user
244    /// presses Cmd+Plus, Cmd+Minus or Cmd+0, just like in a browser.
245    ///
246    /// This is `true` by default.
247    ///
248    /// On the web-backend of `eframe` this is set to false by default,
249    /// so that the zoom shortcuts are handled exclusively by the browser,
250    /// which will change the `native_pixels_per_point` (`devicePixelRatio`).
251    /// You can still zoom egui independently by calling [`crate::Context::set_zoom_factor`],
252    /// which will be applied on top of the browsers global zoom.
253    #[cfg_attr(feature = "serde", serde(skip))]
254    pub zoom_with_keyboard: bool,
255
256    /// Keyboard shortcuts to close the application.
257    ///
258    /// Pressing any of these will send [`crate::ViewportCommand::Close`]
259    /// to the root viewport.
260    ///
261    /// Defaults to `Cmd-Q` (which is Ctrl-Q on Linux/Windows, Cmd-Q on Mac).
262    /// Set to empty to disable.
263    #[cfg_attr(feature = "serde", serde(skip))]
264    pub quit_shortcuts: Vec<crate::KeyboardShortcut>,
265
266    /// Controls the tessellator.
267    pub tessellation_options: epaint::TessellationOptions,
268
269    /// If any widget moves or changes id, repaint everything.
270    ///
271    /// It is recommended you keep this OFF, as it may
272    /// lead to endless repaints for an unknown reason. See
273    /// (<https://github.com/rerun-io/rerun/issues/5018>).
274    pub repaint_on_widget_change: bool,
275
276    /// Maximum number of passes to run in one frame.
277    ///
278    /// Set to `1` for pure single-pass immediate mode.
279    /// Set to something larger than `1` to allow multi-pass when needed.
280    ///
281    /// Default is `2`. This means sometimes a frame will cost twice as much,
282    /// but usually only rarely (e.g. when showing a new panel for the first time).
283    ///
284    /// egui will usually only ever run one pass, even if `max_passes` is large.
285    ///
286    /// If this is `1`, [`crate::Context::request_discard`] will be ignored.
287    ///
288    /// Multi-pass is supported by [`crate::Context::run_ui`].
289    ///
290    /// See [`crate::Context::request_discard`] for more.
291    pub max_passes: NonZeroUsize,
292
293    /// This is a signal to any backend that we want the [`crate::PlatformOutput::events`] read out loud.
294    ///
295    /// The only change to egui is that labels can be focused by pressing tab.
296    ///
297    /// Screen readers are an experimental feature of egui, and not supported on all platforms.
298    /// `eframe` only supports it on web.
299    ///
300    /// Consider using [AccessKit](https://github.com/AccessKit/accesskit) instead,
301    /// which is supported by `eframe`.
302    pub screen_reader: bool,
303
304    /// Check reusing of [`Id`]s, and show a visual warning on screen when one is found.
305    ///
306    /// By default this is `true` in debug builds.
307    pub warn_on_id_clash: bool,
308
309    /// Options related to input state handling.
310    pub input_options: crate::input_state::InputOptions,
311
312    /// If `true`, `egui` will discard the loaded image data after
313    /// the texture is loaded onto the GPU to reduce memory usage.
314    ///
315    /// In modern GPU rendering, the texture data is not required after the texture is loaded.
316    ///
317    /// This is beneficial when using a large number or resolution of images and there is no need to
318    /// retain the image data, potentially saving a significant amount of memory.
319    ///
320    /// The drawback is that it becomes impossible to serialize the loaded images or render in non-GPU systems.
321    ///
322    /// Default is `false`.
323    pub reduce_texture_memory: bool,
324}
325
326impl Default for Options {
327    fn default() -> Self {
328        Self {
329            dark_style: Arc::new(Theme::Dark.default_style()),
330            light_style: Arc::new(Theme::Light.default_style()),
331            theme_preference: Default::default(),
332            fallback_theme: Theme::Dark,
333            system_theme: None,
334            sync_window_theme: true,
335            zoom_factor: 1.0,
336            zoom_with_keyboard: true,
337            quit_shortcuts: vec![crate::KeyboardShortcut::new(
338                crate::Modifiers::COMMAND,
339                crate::Key::Q,
340            )],
341            tessellation_options: Default::default(),
342            repaint_on_widget_change: false,
343
344            #[expect(clippy::unwrap_used)]
345            max_passes: NonZeroUsize::new(2).unwrap(),
346            screen_reader: false,
347            warn_on_id_clash: cfg!(debug_assertions),
348
349            // Input:
350            input_options: Default::default(),
351            reduce_texture_memory: false,
352        }
353    }
354}
355
356impl Options {
357    // Needs to be pub because we need to set the system_theme early in the eframe glow renderer.
358    #[doc(hidden)]
359    pub fn begin_pass(&mut self, new_raw_input: &RawInput) {
360        self.system_theme = new_raw_input.system_theme;
361    }
362
363    /// The currently active theme (may depend on the system theme).
364    pub(crate) fn theme(&self) -> Theme {
365        match self.theme_preference {
366            ThemePreference::Dark => Theme::Dark,
367            ThemePreference::Light => Theme::Light,
368            ThemePreference::System => self.system_theme.unwrap_or(self.fallback_theme),
369        }
370    }
371
372    pub(crate) fn style(&self) -> &Arc<Style> {
373        match self.theme() {
374            Theme::Dark => &self.dark_style,
375            Theme::Light => &self.light_style,
376        }
377    }
378
379    pub(crate) fn style_mut(&mut self) -> &mut Arc<Style> {
380        match self.theme() {
381            Theme::Dark => &mut self.dark_style,
382            Theme::Light => &mut self.light_style,
383        }
384    }
385}
386
387impl Options {
388    /// Show the options in the ui.
389    pub fn ui(&mut self, ui: &mut crate::Ui) {
390        let theme = self.theme();
391
392        let Self {
393            dark_style, // covered above
394            light_style,
395            theme_preference,
396            fallback_theme: _,
397            system_theme: _,
398            sync_window_theme,
399            zoom_factor,
400            zoom_with_keyboard,
401            quit_shortcuts: _, // not shown in ui
402            tessellation_options,
403            repaint_on_widget_change,
404            max_passes,
405            screen_reader: _, // needs to come from the integration
406            warn_on_id_clash,
407            input_options,
408            reduce_texture_memory,
409        } = self;
410
411        use crate::Widget as _;
412        use crate::containers::CollapsingHeader;
413
414        CollapsingHeader::new("⚙️ Options")
415            .default_open(false)
416            .show(ui, |ui| {
417                ui.horizontal(|ui| {
418                    ui.label("Max passes:");
419                    ui.add(crate::DragValue::new(max_passes).range(0..=10));
420                });
421
422                ui.checkbox(
423                    repaint_on_widget_change,
424                    "Repaint if any widget moves or changes id",
425                );
426
427                ui.horizontal(|ui| {
428                    ui.label("Zoom factor:");
429                    ui.add(crate::DragValue::new(zoom_factor).range(0.10..=10.0));
430                });
431
432                ui.checkbox(
433                    zoom_with_keyboard,
434                    "Zoom with keyboard (Cmd +, Cmd -, Cmd 0)",
435                );
436
437                ui.checkbox(warn_on_id_clash, "Warn if two widgets have the same Id");
438
439                ui.checkbox(reduce_texture_memory, "Reduce texture memory");
440            });
441
442        CollapsingHeader::new("🎑 Style")
443            .default_open(true)
444            .show(ui, |ui| {
445                theme_preference.buttons(ui);
446
447                ui.checkbox(sync_window_theme, "Sync window theme with egui theme");
448
449                let style = Arc::make_mut(match theme {
450                    Theme::Dark => dark_style,
451                    Theme::Light => light_style,
452                });
453                style.ui(ui);
454            });
455
456        CollapsingHeader::new("✒️ Painting")
457            .default_open(false)
458            .show(ui, |ui| {
459                tessellation_options.ui(ui);
460                ui.vertical_centered(|ui| {
461                    crate::reset_button(ui, tessellation_options, "Reset paint settings");
462                });
463            });
464
465        CollapsingHeader::new("🖱️ Input")
466            .default_open(false)
467            .show(ui, |ui| {
468                input_options.ui(ui);
469            });
470
471        ui.vertical_centered(|ui| crate::reset_button(ui, self, "Reset all"));
472    }
473}
474
475// ----------------------------------------------------------------------------
476
477/// The state of the interaction in egui,
478/// i.e. what is being dragged.
479///
480/// Say there is a button in a scroll area.
481/// If the user clicks the button, the button should click.
482/// If the user drags the button we should scroll the scroll area.
483/// Therefore, when the mouse is pressed, we register both the button
484/// and the scroll area (as `click_id`/`drag_id`).
485/// If the user releases the button without moving the mouse, we register it as a click on `click_id`.
486/// If the cursor moves too much, we clear the `click_id` and start passing move events to `drag_id`.
487#[derive(Clone, Debug, Default)]
488pub(crate) struct InteractionState {
489    /// A widget interested in clicks that has a mouse press on it.
490    pub potential_click_id: Option<Id>,
491
492    /// A widget interested in drags that has a mouse press on it.
493    ///
494    /// Note that this is set as soon as the mouse is pressed,
495    /// so the widget may not yet be marked as "dragged"
496    /// as that can only happen after the mouse has moved a bit
497    /// (at least if the widget is interesated in both clicks and drags).
498    pub potential_drag_id: Option<Id>,
499}
500
501/// Keeps tracks of what widget has keyboard focus
502#[derive(Clone, Debug, Default)]
503pub(crate) struct Focus {
504    /// The widget with keyboard focus (i.e. a text input field).
505    focused_widget: Option<FocusWidget>,
506
507    /// The ID of a widget that had keyboard focus during the previous frame.
508    id_previous_frame: Option<Id>,
509
510    /// The ID of a widget that had keyboard focus *two* frames ago.
511    ///
512    /// Kept so `Response::lost_focus` can still fire after a mid-frame
513    /// focus transition (e.g. clicking a `TextEdit` that was added to
514    /// the UI later than the currently focused one).
515    id_two_frames_ago: Option<Id>,
516
517    /// The ID of a widget to give the focus to in the next frame.
518    id_next_frame: Option<Id>,
519
520    /// If set, the next widget that is interested in focus will automatically get it.
521    /// Probably because the user pressed Tab.
522    give_to_next: bool,
523
524    /// The last widget interested in focus.
525    last_interested: Option<Id>,
526
527    /// Set when looking for widget with navigational keys like arrows, tab, shift+tab.
528    focus_direction: FocusDirection,
529
530    /// The top-most modal layer from the previous frame.
531    top_modal_layer: Option<LayerId>,
532
533    /// The top-most modal layer from the current frame.
534    top_modal_layer_current_frame: Option<LayerId>,
535
536    /// A cache of widget IDs that are interested in focus with their corresponding rectangles.
537    focus_widgets_cache: IdMap<Rect>,
538}
539
540/// The widget with focus.
541#[derive(Clone, Copy, Debug)]
542struct FocusWidget {
543    pub id: Id,
544    pub filter: EventFilter,
545}
546
547impl FocusWidget {
548    pub fn new(id: Id) -> Self {
549        Self {
550            id,
551            filter: Default::default(),
552        }
553    }
554}
555
556impl InteractionState {
557    /// Are we currently clicking or dragging an egui widget?
558    pub fn is_using_pointer(&self) -> bool {
559        self.potential_click_id.is_some() || self.potential_drag_id.is_some()
560    }
561}
562
563impl Focus {
564    /// Which widget currently has keyboard focus?
565    pub fn focused(&self) -> Option<Id> {
566        self.focused_widget.as_ref().map(|w| w.id)
567    }
568
569    fn begin_pass(&mut self, new_input: &crate::data::input::RawInput) {
570        self.id_two_frames_ago = self.id_previous_frame;
571        self.id_previous_frame = self.focused();
572        if let Some(id) = self.id_next_frame.take() {
573            self.focused_widget = Some(FocusWidget::new(id));
574        }
575        let event_filter = self.focused_widget.map(|w| w.filter).unwrap_or_default();
576
577        self.focus_direction = FocusDirection::None;
578
579        let mut focus_requested_by_accesskit = None;
580
581        for event in &new_input.events {
582            if !event_filter.matches(event)
583                && let crate::Event::Key {
584                    key,
585                    pressed: true,
586                    modifiers,
587                    ..
588                } = event
589                && let Some(cardinality) = match key {
590                    crate::Key::ArrowUp if !modifiers.any() => Some(FocusDirection::Up),
591                    crate::Key::ArrowRight if !modifiers.any() => Some(FocusDirection::Right),
592                    crate::Key::ArrowDown if !modifiers.any() => Some(FocusDirection::Down),
593                    crate::Key::ArrowLeft if !modifiers.any() => Some(FocusDirection::Left),
594
595                    crate::Key::Tab if !modifiers.any() => Some(FocusDirection::Next),
596                    crate::Key::Tab if modifiers.shift_only() => Some(FocusDirection::Previous),
597
598                    crate::Key::Escape if !modifiers.any() => {
599                        self.focused_widget = None;
600                        Some(FocusDirection::None)
601                    }
602
603                    _ => None,
604                }
605            {
606                self.focus_direction = cardinality;
607            }
608
609            if let crate::Event::AccessKitActionRequest(accesskit::ActionRequest {
610                action: accesskit::Action::Focus,
611                target_node,
612                target_tree,
613                data: None,
614            }) = event
615                && *target_tree == accesskit::TreeId::ROOT
616            {
617                focus_requested_by_accesskit = Some(*target_node);
618            }
619        }
620
621        // Handle accesskit focus requests
622        let newly_focused = focus_requested_by_accesskit.and_then(|node_id| {
623            self.focus_widgets_cache
624                .keys()
625                .find(|id| id.accesskit_id() == node_id)
626                .copied()
627        });
628        if let Some(id) = newly_focused {
629            self.focused_widget = Some(FocusWidget::new(id));
630            self.give_to_next = false;
631            self.reset_focus();
632        }
633    }
634
635    pub(crate) fn end_pass(&mut self, used_ids: &IdMap<Rect>) {
636        if self.focus_direction.is_cardinal()
637            && let Some(found_widget) = self.find_widget_in_direction(used_ids)
638        {
639            self.focused_widget = Some(FocusWidget::new(found_widget));
640        }
641
642        if let Some(focused_widget) = self.focused_widget {
643            // Allow calling `request_focus` one frame and not using it until next frame
644            let recently_gained_focus = self.id_previous_frame != Some(focused_widget.id);
645
646            if !recently_gained_focus && !used_ids.contains_key(&focused_widget.id) {
647                // Dead-mans-switch: the widget with focus has disappeared!
648                self.focused_widget = None;
649            }
650        }
651
652        self.top_modal_layer = self.top_modal_layer_current_frame.take();
653    }
654
655    pub(crate) fn had_focus_last_frame(&self, id: Id) -> bool {
656        self.id_previous_frame == Some(id)
657    }
658
659    fn interested_in_focus(&mut self, id: Id) {
660        // The rect is updated at the end of the frame.
661        self.focus_widgets_cache
662            .entry(id)
663            .or_insert(Rect::EVERYTHING);
664
665        if self.give_to_next && !self.had_focus_last_frame(id) {
666            self.focused_widget = Some(FocusWidget::new(id));
667            self.give_to_next = false;
668        } else if self.focused() == Some(id) {
669            if self.focus_direction == FocusDirection::Next {
670                self.focused_widget = None;
671                self.give_to_next = true;
672                self.reset_focus();
673            } else if self.focus_direction == FocusDirection::Previous {
674                self.id_next_frame = self.last_interested; // frame-delay so gained_focus works
675                self.reset_focus();
676            }
677        } else if self.focus_direction == FocusDirection::Next
678            && self.focused_widget.is_none()
679            && !self.give_to_next
680        {
681            // nothing has focus and the user pressed tab - give focus to the first widgets that wants it:
682            self.focused_widget = Some(FocusWidget::new(id));
683            self.reset_focus();
684        } else if self.focus_direction == FocusDirection::Previous
685            && self.focused_widget.is_none()
686            && !self.give_to_next
687        {
688            // nothing has focus and the user pressed Shift+Tab - give focus to the last widgets that wants it:
689            self.focused_widget = self.last_interested.map(FocusWidget::new);
690            self.reset_focus();
691        }
692
693        self.last_interested = Some(id);
694    }
695
696    fn set_modal_layer(&mut self, layer_id: LayerId) {
697        self.top_modal_layer_current_frame = Some(layer_id);
698    }
699
700    pub(crate) fn top_modal_layer(&self) -> Option<LayerId> {
701        self.top_modal_layer
702    }
703
704    fn reset_focus(&mut self) {
705        self.focus_direction = FocusDirection::None;
706    }
707
708    fn find_widget_in_direction(&mut self, new_rects: &IdMap<Rect>) -> Option<Id> {
709        // NOTE: `new_rects` here include some widgets _not_ interested in focus.
710
711        /// * negative if `a` is left of `b`
712        /// * positive if `a` is right of `b`
713        /// * zero if the ranges overlap significantly
714        fn range_diff(a: Rangef, b: Rangef) -> f32 {
715            let has_significant_overlap = a.intersection(b).span() >= 0.5 * b.span().min(a.span());
716            if has_significant_overlap {
717                0.0
718            } else {
719                a.center() - b.center()
720            }
721        }
722
723        let current_focused = self.focused_widget?;
724
725        // In what direction we are looking for the next widget.
726        let search_direction = match self.focus_direction {
727            FocusDirection::Up => Vec2::UP,
728            FocusDirection::Right => Vec2::RIGHT,
729            FocusDirection::Down => Vec2::DOWN,
730            FocusDirection::Left => Vec2::LEFT,
731            _ => {
732                return None;
733            }
734        };
735
736        // Update cache with new rects
737        self.focus_widgets_cache.retain(|id, old_rect| {
738            if let Some(new_rect) = new_rects.get(id) {
739                *old_rect = *new_rect;
740                true // Keep the item
741            } else {
742                false // Remove the item
743            }
744        });
745
746        let current_rect = self.focus_widgets_cache.get(&current_focused.id)?;
747
748        let mut best_score = f32::INFINITY;
749        let mut best_id = None;
750
751        // iteration order should only matter in case of a tie, and that should be very rare
752        #[expect(clippy::iter_over_hash_type)]
753        for (candidate_id, candidate_rect) in &self.focus_widgets_cache {
754            if *candidate_id == current_focused.id {
755                continue;
756            }
757
758            // There is a lot of room for improvement here.
759            let to_candidate = vec2(
760                range_diff(candidate_rect.x_range(), current_rect.x_range()),
761                range_diff(candidate_rect.y_range(), current_rect.y_range()),
762            );
763
764            let acos_angle = to_candidate.normalized().dot(search_direction);
765
766            // Only interested in widgets that fall in a 90° cone (±45°)
767            // of the search direction.
768            let is_in_search_cone = 0.5_f32.sqrt() <= acos_angle;
769            if is_in_search_cone {
770                let distance = to_candidate.length();
771
772                // There is a lot of room for improvement here.
773                let score = distance / (acos_angle * acos_angle);
774
775                if score < best_score {
776                    best_score = score;
777                    best_id = Some(*candidate_id);
778                }
779            }
780        }
781
782        best_id
783    }
784}
785
786impl Memory {
787    pub(crate) fn begin_pass(&mut self, new_raw_input: &RawInput, viewports: &ViewportIdSet) {
788        profiling::function_scope!();
789
790        self.viewport_id = new_raw_input.viewport_id;
791
792        // Cleanup
793        self.interactions.retain(|id, _| viewports.contains(id));
794        self.areas.retain(|id, _| viewports.contains(id));
795        self.popups.retain(|id, _| viewports.contains(id));
796
797        self.areas.entry(self.viewport_id).or_default();
798
799        self.requested_interrupt_ime = false;
800
801        // self.interactions  is handled elsewhere
802
803        self.options.begin_pass(new_raw_input);
804
805        self.focus
806            .entry(self.viewport_id)
807            .or_default()
808            .begin_pass(new_raw_input);
809    }
810
811    pub(crate) fn end_pass(&mut self, used_ids: &IdMap<Rect>) {
812        self.caches.update();
813        self.areas_mut().end_pass();
814        self.focus_mut().end_pass(used_ids);
815
816        // Clean up abandoned popups.
817        if let Some(popup) = self.popups.get_mut(&self.viewport_id) {
818            if popup.open_this_frame {
819                popup.open_this_frame = false;
820            } else {
821                self.popups.remove(&self.viewport_id);
822            }
823        }
824    }
825
826    pub(crate) fn set_viewport_id(&mut self, viewport_id: ViewportId) {
827        self.viewport_id = viewport_id;
828    }
829
830    /// Access memory of the [`Area`](crate::containers::area::Area)s, such as `Window`s.
831    pub fn areas(&self) -> &Areas {
832        self.areas
833            .get(&self.viewport_id)
834            .expect("Memory broken: no area for the current viewport")
835    }
836
837    /// Access memory of the [`Area`](crate::containers::area::Area)s, such as `Window`s.
838    pub fn areas_mut(&mut self) -> &mut Areas {
839        self.areas.entry(self.viewport_id).or_default()
840    }
841
842    /// Top-most layer at the given position.
843    pub fn layer_id_at(&self, pos: Pos2) -> Option<LayerId> {
844        let layer_id = self.areas().layer_id_at(pos, &self.to_global)?;
845        if self.is_above_modal_layer(layer_id) {
846            Some(layer_id)
847        } else {
848            self.top_modal_layer()
849        }
850    }
851
852    /// An iterator over all layers. Back-to-front, top is last.
853    pub fn layer_ids(&self) -> impl ExactSizeIterator<Item = LayerId> + '_ {
854        self.areas().order().iter().copied()
855    }
856
857    /// Check if the layer had focus last frame.
858    /// returns `true` if the layer had focus last frame, but not this one.
859    pub fn had_focus_last_frame(&self, id: Id) -> bool {
860        self.focus().and_then(|f| f.id_previous_frame) == Some(id)
861    }
862
863    /// Check if the widget lost keyboard focus.
864    ///
865    /// Returns `true` when `id` was the focused widget at the start
866    /// of this frame *or* the start of the previous frame — but is
867    /// not focused now. The two-frame window matters when focus
868    /// transfers mid-frame: the previously-focused widget has
869    /// usually already been rendered by the time another widget
870    /// claims focus, so the loss signal can only reach it on its
871    /// next render pass.
872    pub(crate) fn lost_focus(&self, id: Id) -> bool {
873        let had_recent_focus = self
874            .focus()
875            .map(|f| f.id_previous_frame == Some(id) || f.id_two_frames_ago == Some(id))
876            .unwrap_or(false);
877        had_recent_focus && !self.has_focus(id)
878    }
879
880    /// Check if the layer gained focus this frame.
881    /// returns `true` if the layer gained focus this frame, but not last one.
882    pub(crate) fn gained_focus(&self, id: Id) -> bool {
883        !self.had_focus_last_frame(id) && self.has_focus(id)
884    }
885
886    /// Does this widget have keyboard focus?
887    ///
888    /// This function does not consider whether the UI as a whole (e.g. window)
889    /// has the keyboard focus. That makes this function suitable for deciding
890    /// widget state that should not be disrupted if the user moves away from
891    /// the window and back.
892    #[inline(always)]
893    pub fn has_focus(&self, id: Id) -> bool {
894        self.focused() == Some(id)
895    }
896
897    /// Which widget has keyboard focus?
898    pub fn focused(&self) -> Option<Id> {
899        self.focus()?.focused()
900    }
901
902    /// Set an event filter for a widget.
903    ///
904    /// This allows you to control whether the widget will loose focus
905    /// when the user presses tab, arrow keys, or escape.
906    ///
907    /// You must first give focus to the widget before calling this.
908    pub fn set_focus_lock_filter(&mut self, id: Id, event_filter: EventFilter) {
909        if self.had_focus_last_frame(id)
910            && self.has_focus(id)
911            && let Some(focused) = &mut self.focus_mut().focused_widget
912            && focused.id == id
913        {
914            focused.filter = event_filter;
915        }
916    }
917
918    /// Give keyboard focus to a specific widget.
919    /// See also [`crate::Response::request_focus`].
920    ///
921    /// Calling this will interrupt IME composition.
922    #[inline(always)]
923    pub fn request_focus(&mut self, id: Id) {
924        self.focus_mut().focused_widget = Some(FocusWidget::new(id));
925        self.interrupt_ime();
926    }
927
928    /// Defer focus until the next pass so an already rendered widget sees `gained_focus`.
929    pub(crate) fn request_focus_next_frame(&mut self, id: Id) {
930        self.focus_mut().id_next_frame = Some(id);
931        self.interrupt_ime();
932    }
933
934    /// Surrender keyboard focus for a specific widget.
935    /// See also [`crate::Response::surrender_focus`].
936    #[inline(always)]
937    pub fn surrender_focus(&mut self, id: Id) {
938        let focus = self.focus_mut();
939        if focus.focused() == Some(id) {
940            focus.focused_widget = None;
941        }
942    }
943
944    /// Stop offering keyboard focus for a specific widget.
945    #[inline(always)]
946    pub fn ignore_focus(&mut self, id: Id) {
947        let focus = self.focus_mut();
948        focus.focus_widgets_cache.remove(&id);
949        if focus.focused() == Some(id) {
950            focus.focused_widget = None;
951        }
952    }
953
954    /// Move keyboard focus in a specific direction.
955    pub fn move_focus(&mut self, direction: FocusDirection) {
956        self.focus_mut().focus_direction = direction;
957    }
958
959    /// Returns true if
960    /// - this layer is the top-most modal layer or above it
961    /// - there is no modal layer
962    pub fn is_above_modal_layer(&self, layer_id: LayerId) -> bool {
963        if let Some(modal_layer) = self.focus().and_then(|f| f.top_modal_layer) {
964            matches!(
965                self.areas().compare_order(layer_id, modal_layer),
966                core::cmp::Ordering::Equal | core::cmp::Ordering::Greater
967            )
968        } else {
969            true
970        }
971    }
972
973    /// Does this layer allow interaction?
974    /// Returns true if
975    ///  - the layer is not behind a modal layer
976    ///  - the [`Order`] allows interaction
977    pub fn allows_interaction(&self, layer_id: LayerId) -> bool {
978        let is_above_modal_layer = self.is_above_modal_layer(layer_id);
979        let ordering_allows_interaction = layer_id.order.allow_interaction();
980        is_above_modal_layer && ordering_allows_interaction
981    }
982
983    /// Register this widget as being interested in getting keyboard focus.
984    /// This will allow the user to select it with tab and shift-tab.
985    /// This is normally done automatically when handling interactions,
986    /// but it is sometimes useful to pre-register interest in focus,
987    /// e.g. before deciding which type of underlying widget to use,
988    /// as in the [`crate::DragValue`] widget, so a widget can be focused
989    /// and rendered correctly in a single frame.
990    ///
991    /// Pass in the `layer_id` of the layer that the widget is in.
992    #[inline(always)]
993    pub fn interested_in_focus(&mut self, id: Id, layer_id: LayerId) {
994        if !self.allows_interaction(layer_id) {
995            return;
996        }
997        self.focus_mut().interested_in_focus(id);
998    }
999
1000    /// The navigation request after applying the focused widget's event filter.
1001    pub(crate) fn focus_direction(&self) -> FocusDirection {
1002        self.focus()
1003            .map_or(FocusDirection::None, |focus| focus.focus_direction)
1004    }
1005
1006    /// Limit focus to widgets on the given layer and above.
1007    /// If this is called multiple times per frame, the top layer wins.
1008    pub fn set_modal_layer(&mut self, layer_id: LayerId) {
1009        if let Some(current) = self.focus().and_then(|f| f.top_modal_layer_current_frame)
1010            && matches!(
1011                self.areas().compare_order(layer_id, current),
1012                core::cmp::Ordering::Less
1013            )
1014        {
1015            return;
1016        }
1017
1018        self.focus_mut().set_modal_layer(layer_id);
1019    }
1020
1021    /// Get the top modal layer (from the previous frame).
1022    pub fn top_modal_layer(&self) -> Option<LayerId> {
1023        self.focus()?.top_modal_layer()
1024    }
1025
1026    /// Stop editing the active [`TextEdit`](crate::TextEdit) (if any).
1027    #[inline(always)]
1028    pub fn stop_text_input(&mut self) {
1029        self.focus_mut().focused_widget = None;
1030    }
1031
1032    /// Forget window positions, sizes etc.
1033    /// Can be used to auto-layout windows.
1034    pub fn reset_areas(&mut self) {
1035        #[expect(clippy::iter_over_hash_type)]
1036        for area in self.areas.values_mut() {
1037            *area = Default::default();
1038        }
1039    }
1040
1041    /// Obtain the previous rectangle of an area.
1042    pub fn area_rect(&self, id: Id) -> Option<Rect> {
1043        self.areas().get(id).map(|state| state.rect())
1044    }
1045
1046    pub(crate) fn interaction(&self) -> &InteractionState {
1047        self.interactions
1048            .get(&self.viewport_id)
1049            .expect("Failed to get interaction")
1050    }
1051
1052    pub(crate) fn interaction_mut(&mut self) -> &mut InteractionState {
1053        self.interactions.entry(self.viewport_id).or_default()
1054    }
1055
1056    pub(crate) fn focus(&self) -> Option<&Focus> {
1057        self.focus.get(&self.viewport_id)
1058    }
1059
1060    pub(crate) fn focus_mut(&mut self) -> &mut Focus {
1061        self.focus.entry(self.viewport_id).or_default()
1062    }
1063
1064    /// Check if the widget owns IME events.
1065    ///
1066    /// A widget should only consume IME events if this returns `true`. At most
1067    /// one widget can own IME events for each frame.
1068    #[inline(always)]
1069    pub fn owns_ime_events(&self, id: Id) -> bool {
1070        // Note: Even if the IME is being interrupted in the current frame, we
1071        // should not return `false` here, since we still need
1072        // `PlatformOutput::ime` to be set in such cases.
1073
1074        self.has_focus(id)
1075    }
1076
1077    /// Interrupt the current IME composition, if any.
1078    pub fn interrupt_ime(&mut self) {
1079        self.requested_interrupt_ime = true;
1080    }
1081
1082    pub(crate) fn should_interrupt_ime(&self) -> bool {
1083        self.requested_interrupt_ime
1084    }
1085}
1086
1087/// State of an open popup.
1088#[derive(Clone, Copy, Debug)]
1089struct OpenPopup {
1090    /// Id of the popup.
1091    id: Id,
1092
1093    /// Optional position of the popup.
1094    pos: Option<Pos2>,
1095
1096    /// Whether this popup was still open this frame. Otherwise it's considered abandoned and `Memory::popup` will be cleared.
1097    open_this_frame: bool,
1098}
1099
1100impl OpenPopup {
1101    /// Create a new `OpenPopup`.
1102    fn new(id: Id, pos: Option<Pos2>) -> Self {
1103        Self {
1104            id,
1105            pos,
1106            open_this_frame: true,
1107        }
1108    }
1109}
1110
1111/// ## Popup state (internal API)
1112///
1113/// Used by [`crate::Popup`].
1114impl Memory {
1115    pub(crate) fn is_popup_open(&self, popup_id: Id) -> bool {
1116        self.popups
1117            .get(&self.viewport_id)
1118            .is_some_and(|state| state.id == popup_id)
1119            || self.everything_is_visible()
1120    }
1121
1122    pub(crate) fn any_popup_open(&self) -> bool {
1123        self.popups.contains_key(&self.viewport_id) || self.everything_is_visible()
1124    }
1125
1126    pub(crate) fn open_popup(&mut self, popup_id: Id) {
1127        self.popups
1128            .insert(self.viewport_id, OpenPopup::new(popup_id, None));
1129    }
1130
1131    pub(crate) fn keep_popup_open(&mut self, popup_id: Id) {
1132        if let Some(state) = self.popups.get_mut(&self.viewport_id)
1133            && state.id == popup_id
1134        {
1135            state.open_this_frame = true;
1136        }
1137    }
1138
1139    pub(crate) fn open_popup_at(&mut self, popup_id: Id, pos: impl Into<Option<Pos2>>) {
1140        self.popups
1141            .insert(self.viewport_id, OpenPopup::new(popup_id, pos.into()));
1142    }
1143
1144    pub(crate) fn popup_position(&self, id: Id) -> Option<Pos2> {
1145        let state = self.popups.get(&self.viewport_id)?;
1146        if state.id == id { state.pos } else { None }
1147    }
1148
1149    pub(crate) fn close_all_popups(&mut self) {
1150        self.popups.clear();
1151    }
1152
1153    pub(crate) fn close_popup(&mut self, popup_id: Id) {
1154        if self.is_popup_open(popup_id) {
1155            self.popups.remove(&self.viewport_id);
1156        }
1157    }
1158
1159    pub(crate) fn toggle_popup(&mut self, popup_id: Id) {
1160        if self.is_popup_open(popup_id) {
1161            self.close_popup(popup_id);
1162        } else {
1163            self.open_popup(popup_id);
1164        }
1165    }
1166}
1167
1168impl Memory {
1169    /// If true, all windows, menus, tooltips, etc., will be visible at once.
1170    ///
1171    /// This is useful for testing, benchmarking, pre-caching, etc.
1172    ///
1173    /// Experimental feature!
1174    #[inline(always)]
1175    pub fn everything_is_visible(&self) -> bool {
1176        self.everything_is_visible
1177    }
1178
1179    /// If true, all windows, menus, tooltips etc are to be visible at once.
1180    ///
1181    /// This is useful for testing, benchmarking, pre-caching, etc.
1182    ///
1183    /// Experimental feature!
1184    pub fn set_everything_is_visible(&mut self, value: bool) {
1185        self.everything_is_visible = value;
1186    }
1187}
1188
1189// ----------------------------------------------------------------------------
1190
1191/// Map containing the index of each layer in the order list, for quick lookups.
1192type OrderMap = HashMap<LayerId, usize>;
1193
1194/// Keeps track of [`Area`](crate::containers::area::Area)s, which are free-floating [`Ui`](crate::Ui)s.
1195/// These [`Area`](crate::containers::area::Area)s can be in any [`Order`].
1196#[derive(Clone, Debug, Default)]
1197#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
1198#[cfg_attr(feature = "serde", serde(default))]
1199pub struct Areas {
1200    areas: IdMap<area::AreaState>,
1201
1202    visible_areas_last_frame: ahash::HashSet<LayerId>,
1203    visible_areas_current_frame: ahash::HashSet<LayerId>,
1204
1205    // ----------------------------
1206    // Everything below this is general to all layers, not just areas.
1207    // TODO(emilk): move this to a separate struct.
1208    /// Back-to-front,  top is last.
1209    order: Vec<LayerId>,
1210
1211    /// Inverse of [`Self::order`], calculated at the end of the frame.
1212    order_map: OrderMap,
1213
1214    /// When an area wants to be on top, it is assigned here.
1215    /// This is used to reorder the layers at the end of the frame.
1216    /// If several layers want to be on top, they will keep their relative order.
1217    /// This means closing three windows and then reopening them all in one frame
1218    /// results in them being sent to the top and keeping their previous internal order.
1219    wants_to_be_on_top: ahash::HashSet<LayerId>,
1220
1221    /// The sublayers that each layer has.
1222    ///
1223    /// The parent sublayer is moved directly above the child sublayers in the ordering.
1224    sublayers: ahash::HashMap<LayerId, HashSet<LayerId>>,
1225}
1226
1227impl Areas {
1228    pub(crate) fn count(&self) -> usize {
1229        self.areas.len()
1230    }
1231
1232    pub(crate) fn get(&self, id: Id) -> Option<&area::AreaState> {
1233        self.areas.get(&id)
1234    }
1235
1236    pub(crate) fn get_mut(&mut self, id: Id) -> Option<&mut area::AreaState> {
1237        self.areas.get_mut(&id)
1238    }
1239
1240    /// Can the user interact with this layer or it's widgets, or do clicks go straight through it?
1241    pub(crate) fn is_interactable(&self, layer_id: LayerId) -> bool {
1242        self.get(layer_id.id).is_none_or(|area| area.interactable)
1243    }
1244
1245    /// All layers back-to-front, top is last.
1246    pub(crate) fn order(&self) -> &[LayerId] {
1247        &self.order
1248    }
1249
1250    /// Compare the order of two layers, based on the order list from last frame.
1251    ///
1252    /// May return [`std::cmp::Ordering::Equal`] if the layers are not in the order list.
1253    pub(crate) fn compare_order(&self, a: LayerId, b: LayerId) -> core::cmp::Ordering {
1254        // Sort by layer `order` first and use `order_map` to resolve disputes.
1255        // If `order_map` only contains one layer ID, then the other one will be
1256        // lower because `None < Some(x)`.
1257        match a.order.cmp(&b.order) {
1258            core::cmp::Ordering::Equal => self.order_map.get(&a).cmp(&self.order_map.get(&b)),
1259            cmp => cmp,
1260        }
1261    }
1262
1263    /// Set the state of the area of the given layer for this pass.
1264    ///
1265    /// [`crate::Area`] does this for you. Call it yourself for a layer you show without an
1266    /// [`crate::Area`] (e.g. with [`crate::UiBuilder::layer_id`]) that should still be found by
1267    /// [`Self::layer_id_at`], so that it gets the hover and the scroll wheel over its rectangle
1268    /// instead of the layers behind it.
1269    ///
1270    /// The rectangle is [`crate::AreaState::rect`], in the coordinates of the layer
1271    /// (before any [`crate::Context::set_transform_layer`]).
1272    /// If [`crate::AreaState::interactable`] is `false`, the pointer goes through the layer.
1273    ///
1274    /// Call this every pass the layer is shown.
1275    /// Once you stop, the layer is still found for one more pass, like an [`crate::Area`] that is no longer shown.
1276    pub fn set_state(&mut self, layer_id: LayerId, state: area::AreaState) {
1277        self.visible_areas_current_frame.insert(layer_id);
1278        self.areas.insert(layer_id.id, state);
1279        if !self.order.contains(&layer_id) {
1280            self.order.push(layer_id);
1281        }
1282    }
1283
1284    /// Top-most layer at the given position.
1285    pub fn layer_id_at(
1286        &self,
1287        pos: Pos2,
1288        layer_to_global: &HashMap<LayerId, TSTransform>,
1289    ) -> Option<LayerId> {
1290        for layer in self.order.iter().rev() {
1291            if self.is_visible(layer)
1292                && let Some(state) = self.areas.get(&layer.id)
1293            {
1294                let mut rect = state.rect();
1295                if state.interactable {
1296                    if let Some(to_global) = layer_to_global.get(layer) {
1297                        rect = *to_global * rect;
1298                    }
1299
1300                    if rect.contains(pos) {
1301                        return Some(*layer);
1302                    }
1303                }
1304            }
1305        }
1306        None
1307    }
1308
1309    pub fn visible_last_frame(&self, layer_id: &LayerId) -> bool {
1310        self.visible_areas_last_frame.contains(layer_id)
1311    }
1312
1313    pub fn is_visible(&self, layer_id: &LayerId) -> bool {
1314        self.visible_areas_last_frame.contains(layer_id)
1315            || self.visible_areas_current_frame.contains(layer_id)
1316    }
1317
1318    pub fn visible_layer_ids(&self) -> ahash::HashSet<LayerId> {
1319        core::iter::chain(
1320            &self.visible_areas_last_frame,
1321            &self.visible_areas_current_frame,
1322        )
1323        .copied()
1324        .collect()
1325    }
1326
1327    pub(crate) fn visible_windows(&self) -> impl Iterator<Item = (LayerId, &area::AreaState)> {
1328        self.visible_layer_ids()
1329            .into_iter()
1330            .filter(|layer| layer.order == crate::Order::Middle)
1331            .filter(|&layer| !self.is_sublayer(&layer))
1332            .filter_map(|layer| Some((layer, self.get(layer.id)?)))
1333    }
1334
1335    pub fn move_to_top(&mut self, layer_id: LayerId) {
1336        self.visible_areas_current_frame.insert(layer_id);
1337        self.wants_to_be_on_top.insert(layer_id);
1338
1339        if !self.order.contains(&layer_id) {
1340            self.order.push(layer_id);
1341        }
1342    }
1343
1344    /// Mark the `child` layer as a sublayer of `parent`.
1345    ///
1346    /// Sublayers are moved directly above the parent layer at the end of the frame. This is mainly
1347    /// intended for adding a new [Area](crate::Area) inside a [Window](crate::Window).
1348    ///
1349    /// This currently only supports one level of nesting. If `parent` is a sublayer of another
1350    /// layer, the behavior is unspecified.
1351    ///
1352    /// The two layers must have the same [`LayerId::order`].
1353    pub fn set_sublayer(&mut self, parent: LayerId, child: LayerId) {
1354        debug_assert_eq!(
1355            parent.order, child.order,
1356            "DEBUG ASSERT: Trying to set sublayers across layers of different order ({:?}, {:?}), which is currently undefined behavior in egui",
1357            parent.order, child.order
1358        );
1359
1360        self.sublayers.entry(parent).or_default().insert(child);
1361
1362        // Make sure the layers are in the order list:
1363        if !self.order.contains(&parent) {
1364            self.order.push(parent);
1365        }
1366        if !self.order.contains(&child) {
1367            self.order.push(child);
1368        }
1369    }
1370
1371    pub fn top_layer_id(&self, order: Order) -> Option<LayerId> {
1372        self.order
1373            .iter()
1374            .rfind(|layer| layer.order == order && !self.is_sublayer(layer))
1375            .copied()
1376    }
1377
1378    /// If this layer is the sublayer of another layer, return the parent.
1379    pub fn parent_layer(&self, layer_id: LayerId) -> Option<LayerId> {
1380        self.sublayers.iter().find_map(|(parent, children)| {
1381            if children.contains(&layer_id) {
1382                Some(*parent)
1383            } else {
1384                None
1385            }
1386        })
1387    }
1388
1389    /// All the child layers of this layer.
1390    pub fn child_layers(&self, layer_id: LayerId) -> impl Iterator<Item = LayerId> + '_ {
1391        self.sublayers.get(&layer_id).into_iter().flatten().copied()
1392    }
1393
1394    pub(crate) fn is_sublayer(&self, layer: &LayerId) -> bool {
1395        self.parent_layer(*layer).is_some()
1396    }
1397
1398    pub(crate) fn end_pass(&mut self) {
1399        let Self {
1400            visible_areas_last_frame,
1401            visible_areas_current_frame,
1402            order,
1403            wants_to_be_on_top,
1404            sublayers,
1405            ..
1406        } = self;
1407
1408        core::mem::swap(visible_areas_last_frame, visible_areas_current_frame);
1409        visible_areas_current_frame.clear();
1410
1411        order.sort_by_key(|layer| (layer.order, wants_to_be_on_top.contains(layer)));
1412        wants_to_be_on_top.clear();
1413
1414        // For all layers with sublayers, put the sublayers directly after the parent layer:
1415        // (it doesn't matter in which order we replace parents with their children)
1416        #[expect(clippy::iter_over_hash_type)]
1417        for (parent, children) in core::mem::take(sublayers) {
1418            let mut moved_layers = vec![parent]; // parent first…
1419
1420            order.retain(|l| {
1421                if children.contains(l) {
1422                    moved_layers.push(*l); // …followed by children
1423                    false
1424                } else {
1425                    true
1426                }
1427            });
1428            let Some(parent_pos) = order.iter().position(|l| l == &parent) else {
1429                continue;
1430            };
1431            order.splice(parent_pos..=parent_pos, moved_layers); // replace the parent with itself and its children
1432        }
1433
1434        self.order_map = self
1435            .order
1436            .iter()
1437            .enumerate()
1438            .map(|(i, id)| (*id, i))
1439            .collect();
1440    }
1441}
1442
1443// ----------------------------------------------------------------------------
1444
1445// Compile-time check that `Memory` is `Send + Sync` on every target.
1446// Deliberately not a `#[test]`: tests never run on wasm, but `cargo check` does.
1447const _: () = {
1448    const fn assert_send_sync<T: Send + Sync>() {}
1449    assert_send_sync::<Memory>();
1450};
1451
1452// Regression test for https://github.com/emilk/egui/issues/2142.
1453#[test]
1454fn lost_focus_fires_after_mid_frame_focus_transfer() {
1455    use crate::data::input::RawInput;
1456    let a = Id::unique("A");
1457    let b = Id::unique("B");
1458    let mut focus = Focus::default();
1459    let raw = RawInput::default();
1460
1461    fn lost_focus_check(focus: &Focus, id: Id) -> bool {
1462        let was_focused =
1463            focus.id_previous_frame == Some(id) || focus.id_two_frames_ago == Some(id);
1464        was_focused && focus.focused() != Some(id)
1465    }
1466
1467    // Frame N-1
1468    {
1469        focus.begin_pass(&raw);
1470        focus.focused_widget = Some(FocusWidget::new(a));
1471    }
1472
1473    // Frame N: `A` is focused at start; user clicks `B` mid-frame
1474    {
1475        focus.begin_pass(&raw);
1476        assert_eq!(focus.id_previous_frame, Some(a));
1477        assert!(!lost_focus_check(&focus, a));
1478        focus.focused_widget = Some(FocusWidget::new(b));
1479    }
1480
1481    // Frame N+1: `A` deferred lost_focus signal must fire
1482    {
1483        focus.begin_pass(&raw);
1484        assert_eq!(focus.id_two_frames_ago, Some(a));
1485        assert_eq!(focus.id_previous_frame, Some(b));
1486        assert!(lost_focus_check(&focus, a), "`A` lost_focus must fire");
1487        assert!(!lost_focus_check(&focus, b));
1488    }
1489
1490    // Frame N+2
1491    {
1492        focus.begin_pass(&raw);
1493        assert!(
1494            !lost_focus_check(&focus, a),
1495            "A's lost_focus must stop firing once the two-frame window passes",
1496        );
1497    }
1498}
1499
1500#[test]
1501fn order_map_total_ordering() {
1502    let mut layers = [
1503        LayerId::new(Order::Tooltip, Id::unique("a")),
1504        LayerId::new(Order::Background, Id::unique("b")),
1505        LayerId::new(Order::Background, Id::unique("c")),
1506        LayerId::new(Order::Tooltip, Id::unique("d")),
1507        LayerId::new(Order::Background, Id::unique("e")),
1508        LayerId::new(Order::Background, Id::unique("f")),
1509        LayerId::new(Order::Tooltip, Id::unique("g")),
1510    ];
1511    let mut areas = Areas::default();
1512
1513    // skip some of the layers
1514    for &layer in &layers[3..] {
1515        areas.set_state(layer, crate::AreaState::default());
1516    }
1517    areas.end_pass(); // sort layers
1518
1519    // Sort layers
1520    layers.sort_by(|&a, &b| areas.compare_order(a, b));
1521
1522    // Assert that `areas.compare_order()` forms a total ordering
1523    let mut equivalence_classes = vec![0];
1524    let mut i = 0;
1525    for &[a, b] in layers.array_windows() {
1526        assert!(a.order <= b.order, "does not follow LayerId.order");
1527        if areas.compare_order(a, b) != core::cmp::Ordering::Equal {
1528            i += 1;
1529        }
1530        equivalence_classes.push(i);
1531    }
1532    assert_eq!(layers.len(), equivalence_classes.len());
1533    for (&l1, c1) in core::iter::zip(&layers, &equivalence_classes) {
1534        for (&l2, c2) in core::iter::zip(&layers, &equivalence_classes) {
1535            assert_eq!(
1536                c1.cmp(c2),
1537                areas.compare_order(l1, l2),
1538                "not a total ordering",
1539            );
1540        }
1541    }
1542}
1543
1544#[test]
1545fn set_state_makes_layer_hit_testable() {
1546    let ctx = crate::Context::default();
1547    let layer_id = LayerId::new(Order::Foreground, Id::unique("layer"));
1548    let rect = Rect::from_min_size(crate::pos2(10.0, 20.0), vec2(100.0, 50.0));
1549    let outside = crate::pos2(200.0, 200.0);
1550
1551    let run_pass = |register: bool| {
1552        let mut found = (None, None);
1553        let output = ctx.run_ui(Default::default(), |ui| {
1554            if register {
1555                ui.memory_mut(|mem| {
1556                    mem.areas_mut().set_state(
1557                        layer_id,
1558                        area::AreaState {
1559                            pivot_pos: Some(rect.min),
1560                            size: Some(rect.size()),
1561                            ..Default::default()
1562                        },
1563                    );
1564                });
1565            }
1566            found = (
1567                ui.ctx().layer_id_at(rect.center()),
1568                ui.ctx().layer_id_at(outside),
1569            );
1570        });
1571        output.drop_without_applying_deltas();
1572        found
1573    };
1574
1575    let (inside, outside) = run_pass(true);
1576    assert_eq!(inside, Some(layer_id), "found over its rect");
1577    assert_ne!(outside, Some(layer_id), "not found outside of its rect");
1578
1579    let (inside, _) = run_pass(false);
1580    assert_eq!(inside, Some(layer_id), "still found the pass after");
1581
1582    let (inside, _) = run_pass(false);
1583    assert_ne!(inside, Some(layer_id), "gone once no longer registered");
1584}