1#![warn(missing_docs)] use 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#[derive(Clone, Debug)]
29#[cfg_attr(feature = "persistence", derive(serde::Deserialize, serde::Serialize))]
30#[cfg_attr(feature = "persistence", serde(default))]
31pub struct Memory {
32 pub options: Options,
34
35 pub data: crate::util::IdTypeMap,
49
50 #[cfg_attr(feature = "persistence", serde(skip))]
76 pub caches: crate::cache::CacheStorage,
77
78 #[cfg_attr(feature = "persistence", serde(skip))]
81 pub(crate) new_font_definitions: Option<epaint::text::FontDefinitions>,
82
83 #[cfg_attr(feature = "persistence", serde(skip))]
85 pub(crate) add_fonts: Vec<epaint::text::FontInsert>,
86
87 #[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 pub to_global: HashMap<LayerId, TSTransform>,
101
102 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 #[cfg_attr(feature = "persistence", serde(skip))]
119 popups: ViewportIdMap<OpenPopup>,
120
121 #[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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
152pub enum FocusDirection {
153 Up,
155
156 Right,
158
159 Down,
161
162 Left,
164
165 Previous,
167
168 Next,
170
171 #[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#[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 #[cfg_attr(feature = "serde", serde(skip))]
197 pub dark_style: Arc<Style>,
198
199 #[cfg_attr(feature = "serde", serde(skip))]
201 pub light_style: Arc<Style>,
202
203 pub theme_preference: ThemePreference,
208
209 pub fallback_theme: Theme,
214
215 #[cfg_attr(feature = "serde", serde(skip))]
218 pub(crate) system_theme: Option<Theme>,
219
220 pub sync_window_theme: bool,
231
232 pub zoom_factor: f32,
242
243 #[cfg_attr(feature = "serde", serde(skip))]
254 pub zoom_with_keyboard: bool,
255
256 #[cfg_attr(feature = "serde", serde(skip))]
264 pub quit_shortcuts: Vec<crate::KeyboardShortcut>,
265
266 pub tessellation_options: epaint::TessellationOptions,
268
269 pub repaint_on_widget_change: bool,
275
276 pub max_passes: NonZeroUsize,
292
293 pub screen_reader: bool,
303
304 pub warn_on_id_clash: bool,
308
309 pub input_options: crate::input_state::InputOptions,
311
312 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_options: Default::default(),
351 reduce_texture_memory: false,
352 }
353 }
354}
355
356impl Options {
357 #[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 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 pub fn ui(&mut self, ui: &mut crate::Ui) {
390 let theme = self.theme();
391
392 let Self {
393 dark_style, 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: _, tessellation_options,
403 repaint_on_widget_change,
404 max_passes,
405 screen_reader: _, 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#[derive(Clone, Debug, Default)]
488pub(crate) struct InteractionState {
489 pub potential_click_id: Option<Id>,
491
492 pub potential_drag_id: Option<Id>,
499}
500
501#[derive(Clone, Debug, Default)]
503pub(crate) struct Focus {
504 focused_widget: Option<FocusWidget>,
506
507 id_previous_frame: Option<Id>,
509
510 id_two_frames_ago: Option<Id>,
516
517 id_next_frame: Option<Id>,
519
520 give_to_next: bool,
523
524 last_interested: Option<Id>,
526
527 focus_direction: FocusDirection,
529
530 top_modal_layer: Option<LayerId>,
532
533 top_modal_layer_current_frame: Option<LayerId>,
535
536 focus_widgets_cache: IdMap<Rect>,
538}
539
540#[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 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 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 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 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 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 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; 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 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 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 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 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 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 } else {
742 false }
744 });
745
746 let current_rect = self.focus_widgets_cache.get(¤t_focused.id)?;
747
748 let mut best_score = f32::INFINITY;
749 let mut best_id = None;
750
751 #[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 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 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 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 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.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 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 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 pub fn areas_mut(&mut self) -> &mut Areas {
839 self.areas.entry(self.viewport_id).or_default()
840 }
841
842 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 pub fn layer_ids(&self) -> impl ExactSizeIterator<Item = LayerId> + '_ {
854 self.areas().order().iter().copied()
855 }
856
857 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 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 pub(crate) fn gained_focus(&self, id: Id) -> bool {
883 !self.had_focus_last_frame(id) && self.has_focus(id)
884 }
885
886 #[inline(always)]
893 pub fn has_focus(&self, id: Id) -> bool {
894 self.focused() == Some(id)
895 }
896
897 pub fn focused(&self) -> Option<Id> {
899 self.focus()?.focused()
900 }
901
902 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 #[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 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 #[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 #[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 pub fn move_focus(&mut self, direction: FocusDirection) {
956 self.focus_mut().focus_direction = direction;
957 }
958
959 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 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 #[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 pub(crate) fn focus_direction(&self) -> FocusDirection {
1002 self.focus()
1003 .map_or(FocusDirection::None, |focus| focus.focus_direction)
1004 }
1005
1006 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 pub fn top_modal_layer(&self) -> Option<LayerId> {
1023 self.focus()?.top_modal_layer()
1024 }
1025
1026 #[inline(always)]
1028 pub fn stop_text_input(&mut self) {
1029 self.focus_mut().focused_widget = None;
1030 }
1031
1032 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 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 #[inline(always)]
1069 pub fn owns_ime_events(&self, id: Id) -> bool {
1070 self.has_focus(id)
1075 }
1076
1077 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#[derive(Clone, Copy, Debug)]
1089struct OpenPopup {
1090 id: Id,
1092
1093 pos: Option<Pos2>,
1095
1096 open_this_frame: bool,
1098}
1099
1100impl OpenPopup {
1101 fn new(id: Id, pos: Option<Pos2>) -> Self {
1103 Self {
1104 id,
1105 pos,
1106 open_this_frame: true,
1107 }
1108 }
1109}
1110
1111impl 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 #[inline(always)]
1175 pub fn everything_is_visible(&self) -> bool {
1176 self.everything_is_visible
1177 }
1178
1179 pub fn set_everything_is_visible(&mut self, value: bool) {
1185 self.everything_is_visible = value;
1186 }
1187}
1188
1189type OrderMap = HashMap<LayerId, usize>;
1193
1194#[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 order: Vec<LayerId>,
1210
1211 order_map: OrderMap,
1213
1214 wants_to_be_on_top: ahash::HashSet<LayerId>,
1220
1221 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 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 pub(crate) fn order(&self) -> &[LayerId] {
1247 &self.order
1248 }
1249
1250 pub(crate) fn compare_order(&self, a: LayerId, b: LayerId) -> core::cmp::Ordering {
1254 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 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 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 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 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 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 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 #[expect(clippy::iter_over_hash_type)]
1417 for (parent, children) in core::mem::take(sublayers) {
1418 let mut moved_layers = vec![parent]; order.retain(|l| {
1421 if children.contains(l) {
1422 moved_layers.push(*l); 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); }
1433
1434 self.order_map = self
1435 .order
1436 .iter()
1437 .enumerate()
1438 .map(|(i, id)| (*id, i))
1439 .collect();
1440 }
1441}
1442
1443const _: () = {
1448 const fn assert_send_sync<T: Send + Sync>() {}
1449 assert_send_sync::<Memory>();
1450};
1451
1452#[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 {
1469 focus.begin_pass(&raw);
1470 focus.focused_widget = Some(FocusWidget::new(a));
1471 }
1472
1473 {
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 {
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 {
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 for &layer in &layers[3..] {
1515 areas.set_state(layer, crate::AreaState::default());
1516 }
1517 areas.end_pass(); layers.sort_by(|&a, &b| areas.compare_order(a, b));
1521
1522 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}