1#[cfg(any(feature = "inspector", debug_assertions))]
2use crate::Inspector;
3#[cfg(target_os = "macos")]
4use crate::PlatformPixelBuffer;
5use crate::{
6 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
7 AsyncWindowContext, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow, Capslock,
8 Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,
9 DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
10 EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
11 Hsla, InputHandler, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke,
12 KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite,
13 MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas,
14 PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite,
15 Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage,
16 RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
17 SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,
18 StrikethroughStyle, Style, SubpixelSprite, SubscriberSet, Subscription, SystemWindowTab,
19 SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextRenderingMode, TextStyle,
20 TextStyleRefinement, ThermalState, TransformationMatrix, Underline, UnderlineStyle,
21 WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations,
22 WindowOptions, WindowParams, WindowTextSystem, point, prelude::*, profiler, px, rems, size,
23 transparent_black,
24};
25use anyhow::{Context as _, Result, anyhow};
26use derive_more::{Deref, DerefMut};
27use futures::FutureExt;
28use futures::channel::oneshot;
29#[cfg(feature = "input-latency-histogram")]
30use hdrhistogram::Histogram;
31use itertools::FoldWhile::{Continue, Done};
32use itertools::Itertools;
33use open_gpui_collections::{FxHashMap, FxHashSet};
34use open_gpui_core_util::post_inc;
35use open_gpui_core_util::{ResultExt, measure};
36use open_gpui_refineable::Refineable;
37use open_gpui_scheduler::Instant;
38use parking_lot::RwLock;
39use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
40use slotmap::SlotMap;
41use smallvec::SmallVec;
42use std::{
43 any::{Any, TypeId},
44 borrow::Cow,
45 cell::{Cell, RefCell},
46 cmp,
47 fmt::{Debug, Display},
48 hash::{Hash, Hasher},
49 marker::PhantomData,
50 mem,
51 ops::{DerefMut, Range},
52 rc::Rc,
53 sync::{
54 Arc, Weak,
55 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
56 },
57 time::Duration,
58};
59use uuid::Uuid;
60
61pub(crate) mod a11y;
62mod prompts;
63
64use self::a11y::A11y;
65#[cfg(not(target_family = "wasm"))]
66use self::a11y::ROOT_NODE_ID;
67use crate::util::{
68 atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
69 round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
70};
71pub use prompts::*;
72
73pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
75
76pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
79 width: Pixels(900.),
80 height: Pixels(750.),
81};
82
83#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
85pub enum DispatchPhase {
86 #[default]
91 Bubble,
92 Capture,
98}
99
100impl DispatchPhase {
101 #[inline]
103 pub fn bubble(self) -> bool {
104 self == DispatchPhase::Bubble
105 }
106
107 #[inline]
109 pub fn capture(self) -> bool {
110 self == DispatchPhase::Capture
111 }
112}
113
114struct WindowInvalidatorInner {
115 pub dirty: bool,
116 pub draw_phase: DrawPhase,
117 pub dirty_views: FxHashSet<EntityId>,
118 pub update_count: usize,
119}
120
121#[derive(Clone)]
122pub(crate) struct WindowInvalidator {
123 inner: Rc<RefCell<WindowInvalidatorInner>>,
124}
125
126impl WindowInvalidator {
127 pub fn new() -> Self {
128 WindowInvalidator {
129 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
130 dirty: true,
131 draw_phase: DrawPhase::None,
132 dirty_views: FxHashSet::default(),
133 update_count: 0,
134 })),
135 }
136 }
137
138 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
139 let mut inner = self.inner.borrow_mut();
140 inner.update_count += 1;
141 inner.dirty_views.insert(entity);
142 if inner.draw_phase == DrawPhase::None {
143 inner.dirty = true;
144 cx.push_effect(Effect::Notify { emitter: entity });
145 true
146 } else {
147 false
148 }
149 }
150
151 pub fn is_dirty(&self) -> bool {
152 self.inner.borrow().dirty
153 }
154
155 pub fn set_dirty(&self, dirty: bool) {
156 let mut inner = self.inner.borrow_mut();
157 inner.dirty = dirty;
158 if dirty {
159 inner.update_count += 1;
160 }
161 }
162
163 pub fn set_phase(&self, phase: DrawPhase) {
164 self.inner.borrow_mut().draw_phase = phase
165 }
166
167 pub fn update_count(&self) -> usize {
168 self.inner.borrow().update_count
169 }
170
171 pub fn take_views(&self) -> FxHashSet<EntityId> {
172 mem::take(&mut self.inner.borrow_mut().dirty_views)
173 }
174
175 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
176 self.inner.borrow_mut().dirty_views = views;
177 }
178
179 pub fn not_drawing(&self) -> bool {
180 self.inner.borrow().draw_phase == DrawPhase::None
181 }
182
183 #[track_caller]
184 pub fn debug_assert_paint(&self) {
185 debug_assert!(
186 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
187 "this method can only be called during paint"
188 );
189 }
190
191 #[track_caller]
192 pub fn debug_assert_prepaint(&self) {
193 debug_assert!(
194 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
195 "this method can only be called during request_layout, or prepaint"
196 );
197 }
198
199 #[track_caller]
200 pub fn debug_assert_paint_or_prepaint(&self) {
201 debug_assert!(
202 matches!(
203 self.inner.borrow().draw_phase,
204 DrawPhase::Paint | DrawPhase::Prepaint
205 ),
206 "this method can only be called during request_layout, prepaint, or paint"
207 );
208 }
209}
210
211type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
212
213pub(crate) type AnyWindowFocusListener =
214 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
215
216pub(crate) struct WindowFocusEvent {
217 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
218 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
219}
220
221impl WindowFocusEvent {
222 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
223 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
224 }
225
226 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
227 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
228 }
229}
230
231pub struct FocusOutEvent {
233 pub blurred: WeakFocusHandle,
235}
236
237slotmap::new_key_type! {
238 pub struct FocusId;
240}
241
242thread_local! {
243 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
246
247 static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
251}
252
253pub(crate) fn with_element_arena<R>(f: impl FnOnce(&mut Arena) -> R) -> R {
256 CURRENT_ELEMENT_ARENA.with(|current| {
257 if let Some(arena_ptr) = current.get() {
258 let arena_cell = unsafe { &*arena_ptr };
261 f(&mut arena_cell.borrow_mut())
262 } else {
263 ELEMENT_ARENA.with_borrow_mut(f)
264 }
265 })
266}
267
268pub(crate) struct ElementArenaScope {
271 previous: Option<*const RefCell<Arena>>,
272}
273
274impl ElementArenaScope {
275 pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
277 let previous = CURRENT_ELEMENT_ARENA.with(|current| {
278 let prev = current.get();
279 current.set(Some(arena as *const RefCell<Arena>));
280 prev
281 });
282 Self { previous }
283 }
284}
285
286impl Drop for ElementArenaScope {
287 fn drop(&mut self) {
288 CURRENT_ELEMENT_ARENA.with(|current| {
289 current.set(self.previous);
290 });
291 }
292}
293
294#[must_use]
296pub struct ArenaClearNeeded {
297 arena: *const RefCell<Arena>,
298}
299
300impl ArenaClearNeeded {
301 pub(crate) fn new(arena: &RefCell<Arena>) -> Self {
303 Self {
304 arena: arena as *const RefCell<Arena>,
305 }
306 }
307
308 pub fn clear(self) {
310 let arena_cell = unsafe { &*self.arena };
313 arena_cell.borrow_mut().clear();
314 }
315}
316
317pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;
318pub(crate) struct FocusRef {
319 pub(crate) ref_count: AtomicUsize,
320 pub(crate) tab_index: isize,
321 pub(crate) tab_stop: bool,
322}
323
324impl FocusId {
325 pub fn is_focused(&self, window: &Window) -> bool {
327 window.focus == Some(*self)
328 }
329
330 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
333 window
334 .focused(cx)
335 .is_some_and(|focused| self.contains(focused.id, window))
336 }
337
338 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
341 let focused = window.focused(cx);
342 focused.is_some_and(|focused| focused.id.contains(*self, window))
343 }
344
345 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
347 window
348 .rendered_frame
349 .dispatch_tree
350 .focus_contains(*self, other)
351 }
352}
353
354pub struct FocusHandle {
356 pub(crate) id: FocusId,
357 handles: Arc<FocusMap>,
358 pub tab_index: isize,
360 pub tab_stop: bool,
362}
363
364impl std::fmt::Debug for FocusHandle {
365 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
366 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
367 }
368}
369
370impl FocusHandle {
371 pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
372 let id = handles.write().insert(FocusRef {
373 ref_count: AtomicUsize::new(1),
374 tab_index: 0,
375 tab_stop: false,
376 });
377
378 Self {
379 id,
380 tab_index: 0,
381 tab_stop: false,
382 handles: handles.clone(),
383 }
384 }
385
386 pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
387 let lock = handles.read();
388 let focus = lock.get(id)?;
389 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
390 return None;
391 }
392 Some(Self {
393 id,
394 tab_index: focus.tab_index,
395 tab_stop: focus.tab_stop,
396 handles: handles.clone(),
397 })
398 }
399
400 pub fn tab_index(mut self, index: isize) -> Self {
402 self.tab_index = index;
403 if let Some(focus) = self.handles.write().get_mut(self.id) {
404 focus.tab_index = index;
405 }
406 self
407 }
408
409 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
413 self.tab_stop = tab_stop;
414 if let Some(focus) = self.handles.write().get_mut(self.id) {
415 focus.tab_stop = tab_stop;
416 }
417 self
418 }
419
420 pub fn downgrade(&self) -> WeakFocusHandle {
422 WeakFocusHandle {
423 id: self.id,
424 handles: Arc::downgrade(&self.handles),
425 }
426 }
427
428 pub fn focus(&self, window: &mut Window, cx: &mut App) {
430 window.focus(self, cx)
431 }
432
433 pub fn is_focused(&self, window: &Window) -> bool {
435 self.id.is_focused(window)
436 }
437
438 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
441 self.id.contains_focused(window, cx)
442 }
443
444 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
447 self.id.within_focused(window, cx)
448 }
449
450 pub fn contains(&self, other: &Self, window: &Window) -> bool {
452 self.id.contains(other.id, window)
453 }
454
455 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
457 if let Some(node_id) = window
458 .rendered_frame
459 .dispatch_tree
460 .focusable_node_id(self.id)
461 {
462 window.dispatch_action_on_node(node_id, action, cx)
463 }
464 }
465}
466
467impl Clone for FocusHandle {
468 fn clone(&self) -> Self {
469 Self::for_id(self.id, &self.handles).unwrap()
470 }
471}
472
473impl PartialEq for FocusHandle {
474 fn eq(&self, other: &Self) -> bool {
475 self.id == other.id
476 }
477}
478
479impl Eq for FocusHandle {}
480
481impl Drop for FocusHandle {
482 fn drop(&mut self) {
483 self.handles
484 .read()
485 .get(self.id)
486 .unwrap()
487 .ref_count
488 .fetch_sub(1, SeqCst);
489 }
490}
491
492#[derive(Clone, Debug)]
494pub struct WeakFocusHandle {
495 pub(crate) id: FocusId,
496 pub(crate) handles: Weak<FocusMap>,
497}
498
499impl WeakFocusHandle {
500 pub fn upgrade(&self) -> Option<FocusHandle> {
502 let handles = self.handles.upgrade()?;
503 FocusHandle::for_id(self.id, &handles)
504 }
505}
506
507impl PartialEq for WeakFocusHandle {
508 fn eq(&self, other: &WeakFocusHandle) -> bool {
509 self.id == other.id
510 }
511}
512
513impl Eq for WeakFocusHandle {}
514
515impl PartialEq<FocusHandle> for WeakFocusHandle {
516 fn eq(&self, other: &FocusHandle) -> bool {
517 self.id == other.id
518 }
519}
520
521impl PartialEq<WeakFocusHandle> for FocusHandle {
522 fn eq(&self, other: &WeakFocusHandle) -> bool {
523 self.id == other.id
524 }
525}
526
527pub trait Focusable: 'static {
530 fn focus_handle(&self, cx: &App) -> FocusHandle;
532}
533
534impl<V: Focusable> Focusable for Entity<V> {
535 fn focus_handle(&self, cx: &App) -> FocusHandle {
536 self.read(cx).focus_handle(cx)
537 }
538}
539
540pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
543
544impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
545
546pub struct DismissEvent;
548
549type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
550
551pub(crate) type AnyMouseListener =
552 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
553
554#[derive(Clone)]
555pub(crate) struct CursorStyleRequest {
556 pub(crate) hitbox_id: Option<HitboxId>,
557 pub(crate) style: CursorStyle,
558}
559
560#[derive(Default, Eq, PartialEq)]
561pub(crate) struct HitTest {
562 pub(crate) ids: SmallVec<[HitboxId; 8]>,
563 pub(crate) hover_hitbox_count: usize,
564}
565
566#[derive(Clone, Copy, Debug, Eq, PartialEq)]
568pub enum WindowControlArea {
569 Drag,
571 Close,
573 Max,
575 Min,
577}
578
579#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
581pub struct HitboxId(u64);
582
583#[cfg(feature = "test-support")]
584impl HitboxId {
585 pub const fn placeholder() -> Self {
590 Self(0)
591 }
592}
593
594impl HitboxId {
595 pub fn is_hovered(self, window: &Window) -> bool {
602 if window.captured_hitbox == Some(self) {
604 return true;
605 }
606 if window.last_input_was_keyboard() {
607 return false;
608 }
609 self.hit_test(window)
610 }
611
612 pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
617 if window.captured_hitbox == Some(self) {
619 return true;
620 }
621 self.hit_test(window)
622 }
623
624 fn hit_test(self, window: &Window) -> bool {
625 let hit_test = &window.mouse_hit_test;
626 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
627 if self == *id {
628 return true;
629 }
630 }
631 false
632 }
633
634 pub fn should_handle_scroll(self, window: &Window) -> bool {
639 window.mouse_hit_test.ids.contains(&self)
640 }
641
642 fn next(mut self) -> HitboxId {
643 HitboxId(self.0.wrapping_add(1))
644 }
645}
646
647#[derive(Clone, Debug, Deref)]
650pub struct Hitbox {
651 pub id: HitboxId,
653 #[deref]
655 pub bounds: Bounds<Pixels>,
656 pub content_mask: ContentMask<Pixels>,
658 pub behavior: HitboxBehavior,
660}
661
662impl Hitbox {
663 pub fn is_hovered(&self, window: &Window) -> bool {
680 self.id.is_hovered(window)
681 }
682
683 pub fn should_handle_scroll(&self, window: &Window) -> bool {
690 self.id.should_handle_scroll(window)
691 }
692}
693
694#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
696pub enum HitboxBehavior {
697 #[default]
699 Normal,
700
701 BlockMouse,
723
724 BlockMouseExceptScroll,
751}
752
753#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
755pub struct TooltipId(usize);
756
757impl TooltipId {
758 pub fn is_hovered(&self, window: &Window) -> bool {
760 window
761 .tooltip_bounds
762 .as_ref()
763 .is_some_and(|tooltip_bounds| {
764 tooltip_bounds.id == *self
765 && tooltip_bounds.bounds.contains(&window.mouse_position())
766 })
767 }
768}
769
770pub(crate) struct TooltipBounds {
771 id: TooltipId,
772 bounds: Bounds<Pixels>,
773}
774
775#[derive(Clone)]
776pub(crate) struct TooltipRequest {
777 id: TooltipId,
778 tooltip: AnyTooltip,
779}
780
781pub(crate) struct DeferredDraw {
782 current_view: EntityId,
783 priority: usize,
784 parent_node: DispatchNodeId,
785 element_id_stack: SmallVec<[ElementId; 32]>,
786 text_style_stack: Vec<TextStyleRefinement>,
787 content_mask: Option<ContentMask<Pixels>>,
788 rem_size: Pixels,
789 element: Option<AnyElement>,
790 absolute_offset: Point<Pixels>,
791 prepaint_range: Range<PrepaintStateIndex>,
792 paint_range: Range<PaintIndex>,
793}
794
795pub(crate) struct Frame {
796 pub(crate) focus: Option<FocusId>,
797 pub(crate) window_active: bool,
798 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
799 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
800 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
801 pub(crate) dispatch_tree: DispatchTree,
802 pub(crate) scene: Scene,
803 pub(crate) hitboxes: Vec<Hitbox>,
804 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
805 pub(crate) deferred_draws: Vec<DeferredDraw>,
806 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
807 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
808 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
809 #[cfg(any(test, feature = "test-support"))]
810 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
811 #[cfg(any(test, feature = "test-support"))]
812 pub(crate) debug_focus_handles: FxHashMap<String, FocusId>,
813 #[cfg(any(feature = "inspector", debug_assertions))]
814 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
815 #[cfg(any(feature = "inspector", debug_assertions))]
816 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
817 pub(crate) tab_stops: TabStopMap,
818}
819
820#[derive(Clone, Default)]
821pub(crate) struct PrepaintStateIndex {
822 hitboxes_index: usize,
823 tooltips_index: usize,
824 deferred_draws_index: usize,
825 dispatch_tree_index: usize,
826 accessed_element_states_index: usize,
827 line_layout_index: LineLayoutIndex,
828}
829
830#[derive(Clone, Default)]
831pub(crate) struct PaintIndex {
832 scene_index: usize,
833 mouse_listeners_index: usize,
834 input_handlers_index: usize,
835 cursor_styles_index: usize,
836 accessed_element_states_index: usize,
837 tab_handle_index: usize,
838 line_layout_index: LineLayoutIndex,
839}
840
841impl Frame {
842 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
843 Frame {
844 focus: None,
845 window_active: false,
846 element_states: FxHashMap::default(),
847 accessed_element_states: Vec::new(),
848 mouse_listeners: Vec::new(),
849 dispatch_tree,
850 scene: Scene::default(),
851 hitboxes: Vec::new(),
852 window_control_hitboxes: Vec::new(),
853 deferred_draws: Vec::new(),
854 input_handlers: Vec::new(),
855 tooltip_requests: Vec::new(),
856 cursor_styles: Vec::new(),
857
858 #[cfg(any(test, feature = "test-support"))]
859 debug_bounds: FxHashMap::default(),
860 #[cfg(any(test, feature = "test-support"))]
861 debug_focus_handles: FxHashMap::default(),
862
863 #[cfg(any(feature = "inspector", debug_assertions))]
864 next_inspector_instance_ids: FxHashMap::default(),
865
866 #[cfg(any(feature = "inspector", debug_assertions))]
867 inspector_hitboxes: FxHashMap::default(),
868 tab_stops: TabStopMap::default(),
869 }
870 }
871
872 pub(crate) fn clear(&mut self) {
873 self.element_states.clear();
874 self.accessed_element_states.clear();
875 self.mouse_listeners.clear();
876 self.dispatch_tree.clear();
877 self.scene.clear();
878 self.input_handlers.clear();
879 self.tooltip_requests.clear();
880 self.cursor_styles.clear();
881 self.hitboxes.clear();
882 self.window_control_hitboxes.clear();
883 self.deferred_draws.clear();
884 self.tab_stops.clear();
885 self.focus = None;
886
887 #[cfg(any(test, feature = "test-support"))]
888 {
889 self.debug_bounds.clear();
890 self.debug_focus_handles.clear();
891 }
892
893 #[cfg(any(feature = "inspector", debug_assertions))]
894 {
895 self.next_inspector_instance_ids.clear();
896 self.inspector_hitboxes.clear();
897 }
898 }
899
900 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
901 if !window.mouse_in_window {
902 return None;
903 }
904
905 self.cursor_styles
906 .iter()
907 .rev()
908 .fold_while(None, |style, request| match request.hitbox_id {
909 None => Done(Some(request.style)),
910 Some(hitbox_id) => Continue(style.or_else(|| {
911 hitbox_id
912 .is_hovered_ignoring_last_input(window)
913 .then_some(request.style)
914 })),
915 })
916 .into_inner()
917 }
918
919 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
920 let mut set_hover_hitbox_count = false;
921 let mut hit_test = HitTest::default();
922 for hitbox in self.hitboxes.iter().rev() {
923 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
924 if bounds.contains(&position) {
925 hit_test.ids.push(hitbox.id);
926 if !set_hover_hitbox_count
927 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
928 {
929 hit_test.hover_hitbox_count = hit_test.ids.len();
930 set_hover_hitbox_count = true;
931 }
932 if hitbox.behavior == HitboxBehavior::BlockMouse {
933 break;
934 }
935 }
936 }
937 if !set_hover_hitbox_count {
938 hit_test.hover_hitbox_count = hit_test.ids.len();
939 }
940 hit_test
941 }
942
943 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
944 self.focus
945 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
946 .unwrap_or_default()
947 }
948
949 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
950 for element_state_key in &self.accessed_element_states {
951 if let Some((element_state_key, element_state)) =
952 prev_frame.element_states.remove_entry(element_state_key)
953 {
954 self.element_states.insert(element_state_key, element_state);
955 }
956 }
957
958 self.scene.finish();
959 }
960}
961
962#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
963enum InputModality {
964 Mouse,
965 Keyboard,
966}
967
968pub struct Window {
970 pub(crate) handle: AnyWindowHandle,
971 pub(crate) invalidator: WindowInvalidator,
972 pub(crate) removed: bool,
973 pub(crate) platform_window: Box<dyn PlatformWindow>,
974 display_id: Option<DisplayId>,
975 sprite_atlas: Arc<dyn PlatformAtlas>,
976 text_system: Arc<WindowTextSystem>,
977 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
978 rem_size: Pixels,
979 rem_size_override_stack: SmallVec<[Pixels; 8]>,
984 pub(crate) viewport_size: Size<Pixels>,
985 layout_engine: Option<TaffyLayoutEngine>,
986 pub(crate) root: Option<AnyView>,
987 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
988 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
989 pub(crate) rendered_entity_stack: Vec<EntityId>,
990 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
991 pub(crate) element_opacity: f32,
992 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
993 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
994 pub(crate) image_cache_stack: Vec<AnyImageCache>,
995 pub(crate) rendered_frame: Frame,
996 pub(crate) next_frame: Frame,
997 next_hitbox_id: HitboxId,
998 pub(crate) next_tooltip_id: TooltipId,
999 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1000 next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1001 pub(crate) dirty_views: FxHashSet<EntityId>,
1002 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
1003 pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
1004 default_prevented: bool,
1005 mouse_position: Point<Pixels>,
1006 mouse_in_window: bool,
1007 mouse_hit_test: HitTest,
1008 modifiers: Modifiers,
1009 capslock: Capslock,
1010 scale_factor: f32,
1011 pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
1012 appearance: WindowAppearance,
1013 pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
1014 pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>,
1015 active: Rc<Cell<bool>>,
1016 hovered: Rc<Cell<bool>>,
1017 pub(crate) needs_present: Rc<Cell<bool>>,
1018 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1021 #[cfg(feature = "input-latency-histogram")]
1022 input_latency_tracker: InputLatencyTracker,
1023 last_input_modality: InputModality,
1024 pub(crate) refreshing: bool,
1025 pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
1026 pub(crate) focus: Option<FocusId>,
1027 focus_enabled: bool,
1028 pending_input: Option<PendingInput>,
1029 pending_modifier: ModifierState,
1030 pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
1031 prompt: Option<RenderablePromptHandle>,
1032 pub(crate) client_inset: Option<Pixels>,
1033 captured_hitbox: Option<HitboxId>,
1036 #[cfg(any(feature = "inspector", debug_assertions))]
1037 inspector: Option<Entity<Inspector>>,
1038 pub(crate) a11y: A11y,
1039}
1040
1041#[derive(Clone, Debug, Default)]
1042struct ModifierState {
1043 modifiers: Modifiers,
1044 saw_keystroke: bool,
1045}
1046
1047#[derive(Clone, Debug)]
1050pub(crate) struct InputRateTracker {
1051 timestamps: Vec<Instant>,
1052 window: Duration,
1053 inputs_per_second: u32,
1054 sustain_until: Instant,
1055 sustain_duration: Duration,
1056}
1057
1058impl Default for InputRateTracker {
1059 fn default() -> Self {
1060 Self {
1061 timestamps: Vec::new(),
1062 window: Duration::from_millis(100),
1063 inputs_per_second: 60,
1064 sustain_until: Instant::now(),
1065 sustain_duration: Duration::from_secs(1),
1066 }
1067 }
1068}
1069
1070impl InputRateTracker {
1071 pub fn record_input(&mut self) {
1072 let now = Instant::now();
1073 self.timestamps.push(now);
1074 self.prune_old_timestamps(now);
1075
1076 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1077 if self.timestamps.len() as u128 >= min_events {
1078 self.sustain_until = now + self.sustain_duration;
1079 }
1080 }
1081
1082 pub fn is_high_rate(&self) -> bool {
1083 Instant::now() < self.sustain_until
1084 }
1085
1086 fn prune_old_timestamps(&mut self, now: Instant) {
1087 self.timestamps
1088 .retain(|&t| now.duration_since(t) <= self.window);
1089 }
1090}
1091
1092#[cfg(feature = "input-latency-histogram")]
1095pub struct InputLatencySnapshot {
1096 pub latency_histogram: Histogram<u64>,
1098 pub events_per_frame_histogram: Histogram<u64>,
1100 pub mid_draw_events_dropped: u64,
1103}
1104
1105#[cfg(feature = "input-latency-histogram")]
1109struct InputLatencyTracker {
1110 first_input_at: Option<Instant>,
1113 pending_input_count: u64,
1115 latency_histogram: Histogram<u64>,
1117 events_per_frame_histogram: Histogram<u64>,
1119 mid_draw_events_dropped: u64,
1122}
1123
1124#[cfg(feature = "input-latency-histogram")]
1125impl InputLatencyTracker {
1126 fn new() -> Result<Self> {
1127 Ok(Self {
1128 first_input_at: None,
1129 pending_input_count: 0,
1130 latency_histogram: Histogram::new(3)
1131 .map_err(|e| anyhow!("Failed to create input latency histogram: {e}"))?,
1132 events_per_frame_histogram: Histogram::new(3)
1133 .map_err(|e| anyhow!("Failed to create events per frame histogram: {e}"))?,
1134 mid_draw_events_dropped: 0,
1135 })
1136 }
1137
1138 fn record_input(&mut self, dispatch_time: Instant) {
1141 self.first_input_at.get_or_insert(dispatch_time);
1142 self.pending_input_count += 1;
1143 }
1144
1145 fn record_mid_draw_input(&mut self) {
1148 self.mid_draw_events_dropped += 1;
1149 }
1150
1151 fn record_frame_presented(&mut self) {
1153 if let Some(first_input_at) = self.first_input_at.take() {
1154 let latency_nanos = first_input_at.elapsed().as_nanos() as u64;
1155 self.latency_histogram.record(latency_nanos).ok();
1156 }
1157 if self.pending_input_count > 0 {
1158 self.events_per_frame_histogram
1159 .record(self.pending_input_count)
1160 .ok();
1161 self.pending_input_count = 0;
1162 }
1163 }
1164
1165 fn snapshot(&self) -> InputLatencySnapshot {
1166 InputLatencySnapshot {
1167 latency_histogram: self.latency_histogram.clone(),
1168 events_per_frame_histogram: self.events_per_frame_histogram.clone(),
1169 mid_draw_events_dropped: self.mid_draw_events_dropped,
1170 }
1171 }
1172}
1173
1174#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1175pub(crate) enum DrawPhase {
1176 None,
1177 Prepaint,
1178 Paint,
1179 Focus,
1180}
1181
1182#[derive(Default, Debug)]
1183struct PendingInput {
1184 keystrokes: SmallVec<[Keystroke; 1]>,
1185 focus: Option<FocusId>,
1186 timer: Option<Task<()>>,
1187 needs_timeout: bool,
1188}
1189
1190pub(crate) struct ElementStateBox {
1191 pub(crate) inner: Box<dyn Any>,
1192 #[cfg(debug_assertions)]
1193 pub(crate) type_name: &'static str,
1194}
1195
1196fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1197 let active_window_bounds = cx
1202 .active_window()
1203 .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1204
1205 const CASCADE_OFFSET: f32 = 25.0;
1206
1207 let display = display_id
1208 .map(|id| cx.find_display(id))
1209 .unwrap_or_else(|| cx.primary_display());
1210
1211 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1212
1213 let display_bounds = display
1215 .as_ref()
1216 .map(|d| d.visible_bounds())
1217 .unwrap_or_else(default_placement);
1218
1219 let (
1220 Bounds {
1221 origin: base_origin,
1222 size: base_size,
1223 },
1224 window_bounds_ctor,
1225 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1226 Some(bounds) => match bounds {
1227 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1228 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1229 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1230 },
1231 None => (
1232 display
1233 .as_ref()
1234 .map(|d| d.default_bounds())
1235 .unwrap_or_else(default_placement),
1236 WindowBounds::Windowed,
1237 ),
1238 };
1239
1240 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1241 let proposed_origin = base_origin + cascade_offset;
1242 let proposed_bounds = Bounds::new(proposed_origin, base_size);
1243
1244 let display_right = display_bounds.origin.x + display_bounds.size.width;
1245 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1246 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1247 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1248
1249 let fits_horizontally = window_right <= display_right;
1250 let fits_vertically = window_bottom <= display_bottom;
1251
1252 let final_origin = match (fits_horizontally, fits_vertically) {
1253 (true, true) => proposed_origin,
1254 (false, true) => point(display_bounds.origin.x, base_origin.y),
1255 (true, false) => point(base_origin.x, display_bounds.origin.y),
1256 (false, false) => display_bounds.origin,
1257 };
1258 window_bounds_ctor(Bounds::new(final_origin, base_size))
1259}
1260
1261impl Window {
1262 pub(crate) fn new(
1263 handle: AnyWindowHandle,
1264 options: WindowOptions,
1265 cx: &mut App,
1266 ) -> Result<Self> {
1267 let WindowOptions {
1268 window_bounds,
1269 titlebar,
1270 focus,
1271 show,
1272 kind,
1273 is_movable,
1274 is_resizable,
1275 is_minimizable,
1276 accepts_pointer_input,
1277 display_id,
1278 window_background,
1279 app_id,
1280 window_min_size,
1281 window_decorations,
1282 #[cfg_attr(
1283 not(any(target_os = "linux", target_os = "freebsd")),
1284 allow(unused_variables)
1285 )]
1286 icon,
1287 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1288 tabbing_identifier,
1289 } = options;
1290
1291 let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1292 let mut platform_window = cx.platform.open_window(
1293 handle,
1294 WindowParams {
1295 bounds: window_bounds.get_bounds(),
1296 titlebar,
1297 kind,
1298 is_movable,
1299 is_resizable,
1300 is_minimizable,
1301 accepts_pointer_input,
1302 focus,
1303 show,
1304 display_id,
1305 window_min_size,
1306 icon,
1307 #[cfg(target_os = "macos")]
1308 tabbing_identifier,
1309 },
1310 )?;
1311
1312 let tab_bar_visible = platform_window.tab_bar_visible();
1313 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1314 if let Some(tabs) = platform_window.tabbed_windows() {
1315 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1316 }
1317
1318 let display_id = platform_window.display().map(|display| display.id());
1319 let sprite_atlas = platform_window.sprite_atlas();
1320 let mouse_position = platform_window.mouse_position();
1321 let modifiers = platform_window.modifiers();
1322 let capslock = platform_window.capslock();
1323 let content_size = platform_window.content_size();
1324 let scale_factor = platform_window.scale_factor();
1325 let appearance = platform_window.appearance();
1326 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1327 let invalidator = WindowInvalidator::new();
1328 let active = Rc::new(Cell::new(platform_window.is_active()));
1329 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1330 let needs_present = Rc::new(Cell::new(false));
1331 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1332 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1333 let last_frame_time = Rc::new(Cell::new(None));
1334
1335 platform_window
1336 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1337 platform_window.set_background_appearance(window_background);
1338
1339 match window_bounds {
1340 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1341 WindowBounds::Maximized(_) => platform_window.zoom(),
1342 WindowBounds::Windowed(_) => {}
1343 }
1344
1345 let accessibility_force_disabled = cx.accessibility_force_disabled;
1346 let a11y_active_flag = Arc::new(AtomicBool::new(false));
1347
1348 #[cfg(not(target_family = "wasm"))]
1349 if !accessibility_force_disabled {
1350 let initial_tree = accesskit::TreeUpdate {
1351 nodes: vec![(ROOT_NODE_ID, accesskit::Node::new(accesskit::Role::Window))],
1352 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
1353 tree_id: accesskit::TreeId::ROOT,
1354 focus: ROOT_NODE_ID,
1355 };
1356 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
1357 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
1358 let (action_sender, action_receiver) =
1359 async_channel::unbounded::<accesskit::ActionRequest>();
1360
1361 platform_window.a11y_init(crate::A11yCallbacks {
1362 activation: {
1363 let active_flag = a11y_active_flag.clone();
1364 Box::new(move || {
1365 log::info!("Accessibility activated");
1366 active_flag.store(true, SeqCst);
1367 activation_sender.send_blocking(()).log_err();
1368 Some(initial_tree.clone())
1369 })
1370 },
1371 action: Box::new(move |request| {
1372 action_sender.send_blocking(request).log_err();
1373 }),
1374 deactivation: {
1375 let active_flag = a11y_active_flag.clone();
1376 Box::new(move || {
1377 log::info!("Accessibility deactivated");
1378 active_flag.store(false, SeqCst);
1379 deactivation_sender.send_blocking(()).log_err();
1380 })
1381 },
1382 });
1383
1384 let mut async_cx = cx.to_async();
1390 cx.foreground_executor()
1391 .spawn(async move {
1392 while activation_receiver.recv().await.is_ok() {
1393 handle
1394 .update(&mut async_cx, |_, window, _| window.refresh())
1395 .log_err();
1396 }
1397 })
1398 .detach();
1399
1400 let mut async_cx = cx.to_async();
1401 cx.foreground_executor()
1402 .spawn(async move {
1403 while deactivation_receiver.recv().await.is_ok() {
1404 handle
1405 .update(&mut async_cx, |_, window, _| window.refresh())
1406 .log_err();
1407 }
1408 })
1409 .detach();
1410
1411 let mut async_cx = cx.to_async();
1412 cx.foreground_executor()
1413 .spawn(async move {
1414 while let Ok(request) = action_receiver.recv().await {
1415 handle
1416 .update(&mut async_cx, |_, window, cx| {
1417 window.handle_a11y_action(request, cx);
1418 })
1419 .log_err();
1420 }
1421 })
1422 .detach();
1423 }
1424
1425 platform_window.on_close(Box::new({
1426 let window_id = handle.window_id();
1427 let mut cx = cx.to_async();
1428 move || {
1429 let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
1430 let _ = cx.update(|cx| {
1431 SystemWindowTabController::remove_tab(cx, window_id);
1432 });
1433 }
1434 }));
1435 platform_window.on_request_frame(Box::new({
1436 let mut cx = cx.to_async();
1437 let invalidator = invalidator.clone();
1438 let active = active.clone();
1439 let needs_present = needs_present.clone();
1440 let next_frame_callbacks = next_frame_callbacks.clone();
1441 let input_rate_tracker = input_rate_tracker.clone();
1442 move |request_frame_options| {
1443 let thermal_state = handle
1444 .update(&mut cx, |_, _, cx| cx.thermal_state())
1445 .log_err();
1446
1447 let min_frame_interval = if !request_frame_options.force_render
1451 && !request_frame_options.require_presentation
1452 && next_frame_callbacks.borrow().is_empty()
1453 {
1454 None
1455 } else if !active.get() {
1456 Some(Duration::from_micros(33333))
1457 } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
1458 Some(Duration::from_micros(16667))
1459 } else {
1460 None
1461 };
1462
1463 let now = Instant::now();
1464 if let Some(min_interval) = min_frame_interval {
1465 if let Some(last_frame) = last_frame_time.get()
1466 && now.duration_since(last_frame) < min_interval
1467 {
1468 handle
1473 .update(&mut cx, |_, window, _| window.complete_frame())
1474 .log_err();
1475 return;
1476 }
1477 }
1478 last_frame_time.set(Some(now));
1479
1480 let next_frame_callbacks = next_frame_callbacks.take();
1481 if !next_frame_callbacks.is_empty() {
1482 handle
1483 .update(&mut cx, |_, window, cx| {
1484 for callback in next_frame_callbacks {
1485 callback(window, cx);
1486 }
1487 })
1488 .log_err();
1489 }
1490
1491 let needs_present = request_frame_options.require_presentation
1495 || needs_present.get()
1496 || (active.get() && input_rate_tracker.borrow_mut().is_high_rate());
1497
1498 if invalidator.is_dirty() || request_frame_options.force_render {
1499 measure("frame duration", || {
1500 handle
1501 .update(&mut cx, |_, window, cx| {
1502 if request_frame_options.force_render {
1503 window.refresh();
1506 }
1507 let arena_clear_needed = window.draw(cx);
1508 window.present();
1509 arena_clear_needed.clear();
1510 })
1511 .log_err();
1512 })
1513 } else if needs_present {
1514 handle
1515 .update(&mut cx, |_, window, _| window.present())
1516 .log_err();
1517 }
1518
1519 handle
1520 .update(&mut cx, |_, window, _| {
1521 window.complete_frame();
1522 })
1523 .log_err();
1524 }
1525 }));
1526 platform_window.on_resize(Box::new({
1527 let mut cx = cx.to_async();
1528 move |_, _| {
1529 handle
1530 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1531 .log_err();
1532 }
1533 }));
1534 platform_window.on_moved(Box::new({
1535 let mut cx = cx.to_async();
1536 move || {
1537 handle
1538 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1539 .log_err();
1540 }
1541 }));
1542 platform_window.on_appearance_changed(Box::new({
1543 let mut cx = cx.to_async();
1544 move || {
1545 handle
1546 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1547 .log_err();
1548 }
1549 }));
1550 platform_window.on_button_layout_changed(Box::new({
1551 let mut cx = cx.to_async();
1552 move || {
1553 handle
1554 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
1555 .log_err();
1556 }
1557 }));
1558 platform_window.on_active_status_change(Box::new({
1559 let mut cx = cx.to_async();
1560 move |active| {
1561 handle
1562 .update(&mut cx, |_, window, cx| {
1563 window.active.set(active);
1564 window.modifiers = window.platform_window.modifiers();
1565 window.capslock = window.platform_window.capslock();
1566 window
1567 .activation_observers
1568 .clone()
1569 .retain(&(), |callback| callback(window, cx));
1570
1571 window.bounds_changed(cx);
1572 window.refresh();
1573
1574 SystemWindowTabController::update_last_active(cx, window.handle.id);
1575 })
1576 .log_err();
1577 }
1578 }));
1579 platform_window.on_hover_status_change(Box::new({
1580 let mut cx = cx.to_async();
1581 move |active| {
1582 handle
1583 .update(&mut cx, |_, window, cx| {
1584 window.hovered.set(active);
1585 window.mouse_in_window = active;
1586 if !active {
1587 window.reset_cursor_style(cx);
1588 }
1589 window.refresh();
1590 })
1591 .log_err();
1592 }
1593 }));
1594 platform_window.on_input({
1595 let mut cx = cx.to_async();
1596 Box::new(move |event| {
1597 handle
1598 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1599 .log_err()
1600 .unwrap_or(DispatchEventResult::default())
1601 })
1602 });
1603 platform_window.on_hit_test_window_control({
1604 let mut cx = cx.to_async();
1605 Box::new(move || {
1606 handle
1607 .update(&mut cx, |_, window, _cx| {
1608 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1609 if window.mouse_hit_test.ids.contains(&hitbox.id) {
1610 return Some(*area);
1611 }
1612 }
1613 None
1614 })
1615 .log_err()
1616 .unwrap_or(None)
1617 })
1618 });
1619 platform_window.on_move_tab_to_new_window({
1620 let mut cx = cx.to_async();
1621 Box::new(move || {
1622 handle
1623 .update(&mut cx, |_, _window, cx| {
1624 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1625 })
1626 .log_err();
1627 })
1628 });
1629 platform_window.on_merge_all_windows({
1630 let mut cx = cx.to_async();
1631 Box::new(move || {
1632 handle
1633 .update(&mut cx, |_, _window, cx| {
1634 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1635 })
1636 .log_err();
1637 })
1638 });
1639 platform_window.on_select_next_tab({
1640 let mut cx = cx.to_async();
1641 Box::new(move || {
1642 handle
1643 .update(&mut cx, |_, _window, cx| {
1644 SystemWindowTabController::select_next_tab(cx, handle.window_id());
1645 })
1646 .log_err();
1647 })
1648 });
1649 platform_window.on_select_previous_tab({
1650 let mut cx = cx.to_async();
1651 Box::new(move || {
1652 handle
1653 .update(&mut cx, |_, _window, cx| {
1654 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1655 })
1656 .log_err();
1657 })
1658 });
1659 platform_window.on_toggle_tab_bar({
1660 let mut cx = cx.to_async();
1661 Box::new(move || {
1662 handle
1663 .update(&mut cx, |_, window, cx| {
1664 let tab_bar_visible = window.platform_window.tab_bar_visible();
1665 SystemWindowTabController::set_visible(cx, tab_bar_visible);
1666 })
1667 .log_err();
1668 })
1669 });
1670
1671 if let Some(app_id) = app_id {
1672 platform_window.set_app_id(&app_id);
1673 }
1674
1675 platform_window.map_window().unwrap();
1676
1677 Ok(Window {
1678 handle,
1679 invalidator,
1680 removed: false,
1681 platform_window,
1682 display_id,
1683 sprite_atlas,
1684 text_system,
1685 text_rendering_mode: cx.text_rendering_mode.clone(),
1686 rem_size: px(16.),
1687 rem_size_override_stack: SmallVec::new(),
1688 viewport_size: content_size,
1689 layout_engine: Some(TaffyLayoutEngine::new()),
1690 root: None,
1691 element_id_stack: SmallVec::default(),
1692 text_style_stack: Vec::new(),
1693 rendered_entity_stack: Vec::new(),
1694 element_offset_stack: Vec::new(),
1695 content_mask_stack: Vec::new(),
1696 element_opacity: 1.0,
1697 requested_autoscroll: None,
1698 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1699 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1700 next_frame_callbacks,
1701 next_hitbox_id: HitboxId(0),
1702 next_tooltip_id: TooltipId::default(),
1703 tooltip_bounds: None,
1704 dirty_views: FxHashSet::default(),
1705 focus_listeners: SubscriberSet::new(),
1706 focus_lost_listeners: SubscriberSet::new(),
1707 default_prevented: true,
1708 mouse_position,
1709 mouse_in_window: hovered.get(),
1710 mouse_hit_test: HitTest::default(),
1711 modifiers,
1712 capslock,
1713 scale_factor,
1714 bounds_observers: SubscriberSet::new(),
1715 appearance,
1716 appearance_observers: SubscriberSet::new(),
1717 button_layout_observers: SubscriberSet::new(),
1718 active,
1719 hovered,
1720 needs_present,
1721 input_rate_tracker,
1722 #[cfg(feature = "input-latency-histogram")]
1723 input_latency_tracker: InputLatencyTracker::new()?,
1724 last_input_modality: InputModality::Mouse,
1725 refreshing: false,
1726 activation_observers: SubscriberSet::new(),
1727 focus: None,
1728 focus_enabled: true,
1729 pending_input: None,
1730 pending_modifier: ModifierState::default(),
1731 pending_input_observers: SubscriberSet::new(),
1732 prompt: None,
1733 client_inset: None,
1734 image_cache_stack: Vec::new(),
1735 captured_hitbox: None,
1736 #[cfg(any(feature = "inspector", debug_assertions))]
1737 inspector: None,
1738 a11y: A11y::new(a11y_active_flag, accessibility_force_disabled),
1739 })
1740 }
1741
1742 pub(crate) fn new_focus_listener(
1743 &self,
1744 value: AnyWindowFocusListener,
1745 ) -> (Subscription, impl FnOnce() + use<>) {
1746 self.focus_listeners.insert((), value)
1747 }
1748}
1749
1750#[derive(Clone, Debug, Default, PartialEq, Eq)]
1751#[expect(missing_docs)]
1752pub struct DispatchEventResult {
1753 pub propagate: bool,
1754 pub default_prevented: bool,
1755}
1756
1757#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1761#[repr(C)]
1762pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1763 pub bounds: Bounds<P>,
1765}
1766
1767impl ContentMask<Pixels> {
1768 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1770 ContentMask {
1771 bounds: self.bounds.scale(factor),
1772 }
1773 }
1774
1775 pub fn intersect(&self, other: &Self) -> Self {
1777 let bounds = self.bounds.intersect(&other.bounds);
1778 ContentMask { bounds }
1779 }
1780}
1781
1782impl Window {
1783 fn mark_view_dirty(&mut self, view_id: EntityId) {
1784 for view_id in self
1787 .rendered_frame
1788 .dispatch_tree
1789 .view_path_reversed(view_id)
1790 {
1791 if !self.dirty_views.insert(view_id) {
1792 break;
1793 }
1794 }
1795 }
1796
1797 pub fn observe_window_appearance(
1799 &self,
1800 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1801 ) -> Subscription {
1802 let (subscription, activate) = self.appearance_observers.insert(
1803 (),
1804 Box::new(move |window, cx| {
1805 callback(window, cx);
1806 true
1807 }),
1808 );
1809 activate();
1810 subscription
1811 }
1812
1813 pub fn observe_button_layout_changed(
1815 &self,
1816 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1817 ) -> Subscription {
1818 let (subscription, activate) = self.button_layout_observers.insert(
1819 (),
1820 Box::new(move |window, cx| {
1821 callback(window, cx);
1822 true
1823 }),
1824 );
1825 activate();
1826 subscription
1827 }
1828
1829 pub fn replace_root<E>(
1831 &mut self,
1832 cx: &mut App,
1833 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
1834 ) -> Entity<E>
1835 where
1836 E: 'static + Render,
1837 {
1838 let view = cx.new(|cx| build_view(self, cx));
1839 self.root = Some(view.clone().into());
1840 self.refresh();
1841 view
1842 }
1843
1844 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
1846 where
1847 E: 'static + Render,
1848 {
1849 self.root
1850 .as_ref()
1851 .map(|view| view.clone().downcast::<E>().ok())
1852 }
1853
1854 pub fn window_handle(&self) -> AnyWindowHandle {
1856 self.handle
1857 }
1858
1859 pub fn refresh(&mut self) {
1861 if self.invalidator.not_drawing() {
1862 self.refreshing = true;
1863 self.invalidator.set_dirty(true);
1864 }
1865 }
1866
1867 pub fn remove_window(&mut self) {
1869 self.removed = true;
1870 }
1871
1872 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
1874 self.focus
1875 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
1876 }
1877
1878 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
1880 if !self.focus_enabled || self.focus == Some(handle.id) {
1881 return;
1882 }
1883
1884 self.focus = Some(handle.id);
1885 self.clear_pending_keystrokes();
1886
1887 let window_handle = self.handle;
1890 cx.defer(move |cx| {
1891 window_handle
1892 .update(cx, |_, window, cx| {
1893 window.pending_input_changed(cx);
1894 })
1895 .ok();
1896 });
1897
1898 self.refresh();
1899 }
1900
1901 pub fn blur(&mut self) {
1903 if !self.focus_enabled {
1904 return;
1905 }
1906
1907 self.focus = None;
1908 self.refresh();
1909 }
1910
1911 pub fn disable_focus(&mut self) {
1913 self.blur();
1914 self.focus_enabled = false;
1915 }
1916
1917 pub fn focus_next(&mut self, cx: &mut App) {
1919 if !self.focus_enabled {
1920 return;
1921 }
1922
1923 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
1924 self.focus(&handle, cx)
1925 }
1926 }
1927
1928 pub fn focus_prev(&mut self, cx: &mut App) {
1930 if !self.focus_enabled {
1931 return;
1932 }
1933
1934 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
1935 self.focus(&handle, cx)
1936 }
1937 }
1938
1939 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
1941 &self.text_system
1942 }
1943
1944 pub fn text_style(&self) -> TextStyle {
1946 let mut style = TextStyle::default();
1947 for refinement in &self.text_style_stack {
1948 style.refine(refinement);
1949 }
1950 style
1951 }
1952
1953 pub fn is_maximized(&self) -> bool {
1957 self.platform_window.is_maximized()
1958 }
1959
1960 pub fn request_decorations(&self, decorations: WindowDecorations) {
1962 self.platform_window.request_decorations(decorations);
1963 }
1964
1965 pub fn start_window_resize(&self, edge: ResizeEdge) {
1967 self.platform_window.start_window_resize(edge);
1968 }
1969
1970 pub fn window_bounds(&self) -> WindowBounds {
1973 self.platform_window.window_bounds()
1974 }
1975
1976 pub fn inner_window_bounds(&self) -> WindowBounds {
1978 self.platform_window.inner_window_bounds()
1979 }
1980
1981 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
1983 let focus_id = self.focused(cx).map(|handle| handle.id);
1984
1985 let window = self.handle;
1986 cx.defer(move |cx| {
1987 window
1988 .update(cx, |_, window, cx| {
1989 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
1990 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
1991 })
1992 .log_err();
1993 })
1994 }
1995
1996 pub(crate) fn dispatch_keystroke_observers(
1997 &mut self,
1998 event: &dyn Any,
1999 action: Option<Box<dyn Action>>,
2000 context_stack: Vec<KeyContext>,
2001 cx: &mut App,
2002 ) {
2003 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2004 return;
2005 };
2006
2007 cx.keystroke_observers.clone().retain(&(), move |callback| {
2008 (callback)(
2009 &KeystrokeEvent {
2010 keystroke: key_down_event.keystroke.clone(),
2011 action: action.as_ref().map(|action| action.boxed_clone()),
2012 context_stack: context_stack.clone(),
2013 },
2014 self,
2015 cx,
2016 )
2017 });
2018 }
2019
2020 pub(crate) fn dispatch_keystroke_interceptors(
2021 &mut self,
2022 event: &dyn Any,
2023 context_stack: Vec<KeyContext>,
2024 cx: &mut App,
2025 ) {
2026 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2027 return;
2028 };
2029
2030 cx.keystroke_interceptors
2031 .clone()
2032 .retain(&(), move |callback| {
2033 (callback)(
2034 &KeystrokeEvent {
2035 keystroke: key_down_event.keystroke.clone(),
2036 action: None,
2037 context_stack: context_stack.clone(),
2038 },
2039 self,
2040 cx,
2041 )
2042 });
2043 }
2044
2045 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2048 let handle = self.handle;
2049 cx.defer(move |cx| {
2050 handle.update(cx, |_, window, cx| f(window, cx)).ok();
2051 });
2052 }
2053
2054 pub fn observe<T: 'static>(
2058 &mut self,
2059 observed: &Entity<T>,
2060 cx: &mut App,
2061 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2062 ) -> Subscription {
2063 let entity_id = observed.entity_id();
2064 let observed = observed.downgrade();
2065 let window_handle = self.handle;
2066 cx.new_observer(
2067 entity_id,
2068 Box::new(move |cx| {
2069 window_handle
2070 .update(cx, |_, window, cx| {
2071 if let Some(handle) = observed.upgrade() {
2072 on_notify(handle, window, cx);
2073 true
2074 } else {
2075 false
2076 }
2077 })
2078 .unwrap_or(false)
2079 }),
2080 )
2081 }
2082
2083 pub fn subscribe<Emitter, Evt>(
2087 &mut self,
2088 entity: &Entity<Emitter>,
2089 cx: &mut App,
2090 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
2091 ) -> Subscription
2092 where
2093 Emitter: EventEmitter<Evt>,
2094 Evt: 'static,
2095 {
2096 let entity_id = entity.entity_id();
2097 let handle = entity.downgrade();
2098 let window_handle = self.handle;
2099 cx.new_subscription(
2100 entity_id,
2101 (
2102 TypeId::of::<Evt>(),
2103 Box::new(move |event, cx| {
2104 window_handle
2105 .update(cx, |_, window, cx| {
2106 if let Some(entity) = handle.upgrade() {
2107 let event = event.downcast_ref().expect("invalid event type");
2108 on_event(entity, event, window, cx);
2109 true
2110 } else {
2111 false
2112 }
2113 })
2114 .unwrap_or(false)
2115 }),
2116 ),
2117 )
2118 }
2119
2120 pub fn observe_release<T>(
2122 &self,
2123 entity: &Entity<T>,
2124 cx: &mut App,
2125 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2126 ) -> Subscription
2127 where
2128 T: 'static,
2129 {
2130 let entity_id = entity.entity_id();
2131 let window_handle = self.handle;
2132 let (subscription, activate) = cx.release_listeners.insert(
2133 entity_id,
2134 Box::new(move |entity, cx| {
2135 let entity = entity.downcast_mut().expect("invalid entity type");
2136 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2137 }),
2138 );
2139 activate();
2140 subscription
2141 }
2142
2143 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2146 AsyncWindowContext::new_context(cx.to_async(), self.handle)
2147 }
2148
2149 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2151 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2152 }
2153
2154 pub fn request_animation_frame(&self) {
2161 let entity = self.current_view();
2162 self.on_next_frame(move |_, cx| cx.notify(entity));
2163 }
2164
2165 #[track_caller]
2169 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2170 where
2171 R: 'static,
2172 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2173 {
2174 let handle = self.handle;
2175 cx.spawn(async move |app| {
2176 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2177 f(&mut async_window_cx).await
2178 })
2179 }
2180
2181 #[track_caller]
2185 pub fn spawn_with_priority<AsyncFn, R>(
2186 &self,
2187 priority: Priority,
2188 cx: &App,
2189 f: AsyncFn,
2190 ) -> Task<R>
2191 where
2192 R: 'static,
2193 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2194 {
2195 let handle = self.handle;
2196 cx.spawn_with_priority(priority, async move |app| {
2197 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2198 f(&mut async_window_cx).await
2199 })
2200 }
2201
2202 pub fn bounds_changed(&mut self, cx: &mut App) {
2208 self.scale_factor = self.platform_window.scale_factor();
2209 self.viewport_size = self.platform_window.content_size();
2210 self.display_id = self.platform_window.display().map(|display| display.id());
2211
2212 self.refresh();
2213
2214 self.bounds_observers
2215 .clone()
2216 .retain(&(), |callback| callback(self, cx));
2217 }
2218
2219 pub fn bounds(&self) -> Bounds<Pixels> {
2221 self.platform_window.bounds()
2222 }
2223
2224 #[cfg(any(test, feature = "test-support"))]
2228 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
2229 self.platform_window
2230 .render_to_image(&self.rendered_frame.scene)
2231 }
2232
2233 pub fn resize(&mut self, size: Size<Pixels>) {
2235 self.platform_window.resize(size);
2236 }
2237
2238 pub fn is_fullscreen(&self) -> bool {
2240 self.platform_window.is_fullscreen()
2241 }
2242
2243 pub fn is_minimized(&self) -> bool {
2245 self.platform_window.is_minimized()
2246 }
2247
2248 pub fn accepts_pointer_input(&self) -> bool {
2250 self.platform_window.accepts_pointer_input()
2251 }
2252
2253 pub fn set_accepts_pointer_input(&mut self, accepts_pointer_input: bool) -> bool {
2255 self.platform_window
2256 .set_accepts_pointer_input(accepts_pointer_input)
2257 }
2258
2259 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
2260 self.appearance = self.platform_window.appearance();
2261
2262 self.appearance_observers
2263 .clone()
2264 .retain(&(), |callback| callback(self, cx));
2265 }
2266
2267 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2268 self.button_layout_observers
2269 .clone()
2270 .retain(&(), |callback| callback(self, cx));
2271 }
2272
2273 pub fn appearance(&self) -> WindowAppearance {
2275 self.appearance
2276 }
2277
2278 pub fn viewport_size(&self) -> Size<Pixels> {
2280 self.viewport_size
2281 }
2282
2283 pub fn is_window_active(&self) -> bool {
2285 self.active.get()
2286 }
2287
2288 pub fn is_window_hovered(&self) -> bool {
2292 if cfg!(any(
2293 target_os = "windows",
2294 target_os = "linux",
2295 target_os = "freebsd"
2296 )) {
2297 self.hovered.get()
2298 } else {
2299 self.is_window_active()
2300 }
2301 }
2302
2303 pub fn zoom_window(&self) {
2305 self.platform_window.zoom();
2306 }
2307
2308 pub fn show_window_menu(&self, position: Point<Pixels>) {
2310 self.platform_window.show_window_menu(position)
2311 }
2312
2313 pub fn start_window_move(&self) {
2318 self.platform_window.start_window_move()
2319 }
2320
2321 pub fn set_client_inset(&mut self, inset: Pixels) {
2323 self.client_inset = Some(inset);
2324 self.platform_window.set_client_inset(inset);
2325 }
2326
2327 pub fn client_inset(&self) -> Option<Pixels> {
2329 self.client_inset
2330 }
2331
2332 pub fn window_decorations(&self) -> Decorations {
2334 self.platform_window.window_decorations()
2335 }
2336
2337 pub fn window_controls(&self) -> WindowControls {
2339 self.platform_window.window_controls()
2340 }
2341
2342 pub fn set_window_title(&mut self, title: &str) {
2344 self.platform_window.set_title(title);
2345 }
2346
2347 #[cfg(target_os = "macos")]
2349 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
2350 self.platform_window.set_traffic_light_position(position);
2351 }
2352
2353 pub fn set_app_id(&mut self, app_id: &str) {
2355 self.platform_window.set_app_id(app_id);
2356 }
2357
2358 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2360 self.platform_window
2361 .set_background_appearance(background_appearance);
2362 }
2363
2364 pub fn set_window_edited(&mut self, edited: bool) {
2366 self.platform_window.set_edited(edited);
2367 }
2368
2369 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
2372 self.platform_window.set_document_path(path);
2373 }
2374
2375 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2377 cx.platform
2378 .displays()
2379 .into_iter()
2380 .find(|display| Some(display.id()) == self.display_id)
2381 }
2382
2383 pub fn show_character_palette(&self) {
2385 self.platform_window.show_character_palette();
2386 }
2387
2388 pub fn scale_factor(&self) -> f32 {
2392 self.scale_factor
2393 }
2394
2395 pub fn rem_size(&self) -> Pixels {
2398 self.rem_size_override_stack
2399 .last()
2400 .copied()
2401 .unwrap_or(self.rem_size)
2402 }
2403
2404 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2407 self.rem_size = rem_size.into();
2408 }
2409
2410 pub fn with_global_id<R>(
2413 &mut self,
2414 element_id: ElementId,
2415 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2416 ) -> R {
2417 self.with_id(element_id, |this| {
2418 let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2419
2420 f(&global_id, this)
2421 })
2422 }
2423
2424 #[inline]
2426 pub fn with_id<R>(
2427 &mut self,
2428 element_id: impl Into<ElementId>,
2429 f: impl FnOnce(&mut Self) -> R,
2430 ) -> R {
2431 self.element_id_stack.push(element_id.into());
2432 let result = f(self);
2433 self.element_id_stack.pop();
2434 result
2435 }
2436
2437 #[inline]
2443 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2444 where
2445 F: FnOnce(&mut Self) -> R,
2446 {
2447 self.invalidator.debug_assert_paint_or_prepaint();
2448
2449 if let Some(rem_size) = rem_size {
2450 self.rem_size_override_stack.push(rem_size.into());
2451 let result = f(self);
2452 self.rem_size_override_stack.pop();
2453 result
2454 } else {
2455 f(self)
2456 }
2457 }
2458
2459 pub fn line_height(&self) -> Pixels {
2461 self.text_style().line_height_in_pixels(self.rem_size())
2462 }
2463
2464 #[inline]
2466 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
2467 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
2468 }
2469
2470 #[inline]
2472 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
2473 let scale_factor = f64::from(self.scale_factor());
2474 round_half_toward_zero_f64(value * scale_factor) / scale_factor
2475 }
2476
2477 #[inline]
2479 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
2480 bounds.map(|c| self.pixel_snap(c))
2481 }
2482
2483 #[inline]
2485 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
2486 position.map(|c| self.pixel_snap(c))
2487 }
2488
2489 #[inline]
2490 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2491 let scale_factor = self.scale_factor();
2492 let left = round_to_device_pixel(bounds.left().0, scale_factor);
2493 let top = round_to_device_pixel(bounds.top().0, scale_factor);
2494 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
2495 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2496 Bounds::from_corners(
2497 point(ScaledPixels(left), ScaledPixels(top)),
2498 point(ScaledPixels(right), ScaledPixels(bottom)),
2499 )
2500 }
2501
2502 #[inline]
2504 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
2505 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
2506 }
2507
2508 #[inline]
2509 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
2510 edges.map(|e| self.snap_stroke(*e))
2511 }
2512
2513 #[inline]
2515 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2516 let scale_factor = self.scale_factor();
2517 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
2518 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
2519 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
2520 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2521 Bounds::from_corners(
2522 point(ScaledPixels(left), ScaledPixels(top)),
2523 point(ScaledPixels(right), ScaledPixels(bottom)),
2524 )
2525 }
2526
2527 #[inline]
2528 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
2529 ContentMask {
2530 bounds: self.cover_bounds(self.content_mask().bounds),
2531 }
2532 }
2533
2534 pub fn prevent_default(&mut self) {
2537 self.default_prevented = true;
2538 }
2539
2540 pub fn default_prevented(&self) -> bool {
2542 self.default_prevented
2543 }
2544
2545 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2547 let node_id =
2548 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2549 self.rendered_frame
2550 .dispatch_tree
2551 .is_action_available(action, node_id)
2552 }
2553
2554 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2556 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2557 self.rendered_frame
2558 .dispatch_tree
2559 .is_action_available(action, node_id)
2560 }
2561
2562 pub fn mouse_position(&self) -> Point<Pixels> {
2564 self.mouse_position
2565 }
2566
2567 pub fn is_mouse_in_window(&self) -> bool {
2569 self.mouse_in_window
2570 }
2571
2572 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
2579 self.captured_hitbox = Some(hitbox_id);
2580 }
2581
2582 pub fn release_pointer(&mut self) {
2584 self.captured_hitbox = None;
2585 }
2586
2587 pub fn captured_hitbox(&self) -> Option<HitboxId> {
2589 self.captured_hitbox
2590 }
2591
2592 pub fn modifiers(&self) -> Modifiers {
2594 self.modifiers
2595 }
2596
2597 pub fn last_input_was_keyboard(&self) -> bool {
2600 self.last_input_modality == InputModality::Keyboard
2601 }
2602
2603 pub fn capslock(&self) -> Capslock {
2605 self.capslock
2606 }
2607
2608 fn complete_frame(&self) {
2609 self.platform_window.completed_frame();
2610 }
2611
2612 #[profiling::function]
2615 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2616 let _arena_scope = ElementArenaScope::enter(&cx.element_arena);
2619
2620 self.invalidate_entities();
2621 cx.entities.clear_accessed();
2622 debug_assert!(self.rendered_entity_stack.is_empty());
2623 self.invalidator.set_dirty(false);
2624 self.requested_autoscroll = None;
2625
2626 if let Some(input_handler) = self.platform_window.take_input_handler() {
2631 if let Some(slot) = self
2632 .rendered_frame
2633 .input_handlers
2634 .iter_mut()
2635 .rev()
2636 .find(|h| h.is_none())
2637 {
2638 *slot = Some(input_handler);
2639 } else {
2640 self.rendered_frame.input_handlers.push(Some(input_handler));
2641 }
2642 }
2643 if !cx.mode.skip_drawing() {
2644 self.draw_roots(cx);
2645 }
2646 self.dirty_views.clear();
2647 self.next_frame.window_active = self.active.get();
2648
2649 if let Some(input_handler) = self
2655 .next_frame
2656 .input_handlers
2657 .iter_mut()
2658 .rev()
2659 .find_map(|h| h.take())
2660 {
2661 self.platform_window.set_input_handler(input_handler);
2662 }
2663
2664 self.layout_engine.as_mut().unwrap().clear();
2665 self.text_system().finish_frame();
2666 self.next_frame.finish(&mut self.rendered_frame);
2667
2668 self.invalidator.set_phase(DrawPhase::Focus);
2669 let previous_focus_path = self.rendered_frame.focus_path();
2670 let previous_window_active = self.rendered_frame.window_active;
2671 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2672 self.next_frame.clear();
2673 let current_focus_path = self.rendered_frame.focus_path();
2674 let current_window_active = self.rendered_frame.window_active;
2675
2676 if previous_focus_path != current_focus_path
2677 || previous_window_active != current_window_active
2678 {
2679 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2680 self.focus_lost_listeners
2681 .clone()
2682 .retain(&(), |listener| listener(self, cx));
2683 }
2684
2685 let event = WindowFocusEvent {
2686 previous_focus_path: if previous_window_active {
2687 previous_focus_path
2688 } else {
2689 Default::default()
2690 },
2691 current_focus_path: if current_window_active {
2692 current_focus_path
2693 } else {
2694 Default::default()
2695 },
2696 };
2697 self.focus_listeners
2698 .clone()
2699 .retain(&(), |listener| listener(&event, self, cx));
2700 }
2701
2702 debug_assert!(self.rendered_entity_stack.is_empty());
2703 self.record_entities_accessed(cx);
2704 self.reset_cursor_style(cx);
2705 self.refreshing = false;
2706 self.invalidator.set_phase(DrawPhase::None);
2707 self.needs_present.set(true);
2708
2709 ArenaClearNeeded::new(&cx.element_arena)
2710 }
2711
2712 fn record_entities_accessed(&mut self, cx: &mut App) {
2713 let mut entities_ref = cx.entities.accessed_entities.get_mut();
2714 let mut entities = mem::take(entities_ref.deref_mut());
2715 let handle = self.handle;
2716 cx.record_entities_accessed(
2717 handle,
2718 self.invalidator.clone(),
2720 &entities,
2721 );
2722 let mut entities_ref = cx.entities.accessed_entities.get_mut();
2723 mem::swap(&mut entities, entities_ref.deref_mut());
2724 }
2725
2726 fn invalidate_entities(&mut self) {
2727 let mut views = self.invalidator.take_views();
2728 for entity in views.drain() {
2729 self.mark_view_dirty(entity);
2730 }
2731 self.invalidator.replace_views(views);
2732 }
2733
2734 #[profiling::function]
2735 fn present(&mut self) {
2736 self.platform_window.draw(&self.rendered_frame.scene);
2737 #[cfg(feature = "input-latency-histogram")]
2738 self.input_latency_tracker.record_frame_presented();
2739 self.needs_present.set(false);
2740 profiling::finish_frame!();
2741 }
2742
2743 #[cfg(feature = "input-latency-histogram")]
2745 pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
2746 self.input_latency_tracker.snapshot()
2747 }
2748
2749 fn draw_roots(&mut self, cx: &mut App) {
2750 self.invalidator.set_phase(DrawPhase::Prepaint);
2751 self.tooltip_bounds.take();
2752
2753 self.a11y.sync_active_flag();
2754 if self.a11y.is_active() {
2755 self.a11y.begin_frame();
2756 }
2757
2758 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
2759 let root_size = {
2760 #[cfg(any(feature = "inspector", debug_assertions))]
2761 {
2762 if self.inspector.is_some() {
2763 let mut size = self.viewport_size;
2764 size.width = (size.width - _inspector_width).max(px(0.0));
2765 size
2766 } else {
2767 self.viewport_size
2768 }
2769 }
2770 #[cfg(not(any(feature = "inspector", debug_assertions)))]
2771 {
2772 self.viewport_size
2773 }
2774 };
2775
2776 let mut root_element = self.root.as_ref().unwrap().clone().into_any();
2778 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2779
2780 #[cfg(any(feature = "inspector", debug_assertions))]
2781 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
2782
2783 self.prepaint_deferred_draws(cx);
2784
2785 let mut prompt_element = None;
2786 let mut active_drag_element = None;
2787 let mut tooltip_element = None;
2788 if let Some(prompt) = self.prompt.take() {
2789 let mut element = prompt.view.any_view().into_any();
2790 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2791 prompt_element = Some(element);
2792 self.prompt = Some(prompt);
2793 } else if let Some(active_drag) = cx.active_drag.take() {
2794 let mut element = active_drag.view.clone().into_any();
2795 let offset = self.mouse_position() - active_drag.cursor_offset;
2796 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
2797 active_drag_element = Some(element);
2798 cx.active_drag = Some(active_drag);
2799 } else {
2800 tooltip_element = self.prepaint_tooltip(cx);
2801 }
2802
2803 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
2804
2805 self.invalidator.set_phase(DrawPhase::Paint);
2807 root_element.paint(self, cx);
2808
2809 #[cfg(any(feature = "inspector", debug_assertions))]
2810 self.paint_inspector(inspector_element, cx);
2811
2812 self.paint_deferred_draws(cx);
2813
2814 if let Some(mut prompt_element) = prompt_element {
2815 prompt_element.paint(self, cx);
2816 } else if let Some(mut drag_element) = active_drag_element {
2817 drag_element.paint(self, cx);
2818 } else if let Some(mut tooltip_element) = tooltip_element {
2819 tooltip_element.paint(self, cx);
2820 }
2821
2822 #[cfg(any(feature = "inspector", debug_assertions))]
2823 self.paint_inspector_hitbox(cx);
2824
2825 let a11y_active_start_of_frame = self.a11y.is_active();
2827 self.a11y.sync_active_flag();
2828 let a11y_active_end_of_frame = self.a11y.is_active();
2829
2830 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
2831
2832 if a11y_active_start_of_frame {
2833 let tree_update = self.a11y.end_frame();
2835
2836 if should_send_a11y_update {
2837 log::debug!(
2838 "Sending a11y tree update: {} nodes",
2839 tree_update.nodes.len()
2840 );
2841 self.platform_window.a11y_tree_update(tree_update);
2842 }
2843 }
2844 }
2845
2846 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
2847 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
2849 let Some(Some(tooltip_request)) = self
2850 .next_frame
2851 .tooltip_requests
2852 .get(tooltip_request_index)
2853 .cloned()
2854 else {
2855 log::error!("Unexpectedly absent TooltipRequest");
2856 continue;
2857 };
2858 let mut element = tooltip_request.tooltip.view.clone().into_any();
2859 let mouse_position = tooltip_request.tooltip.mouse_position;
2860 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
2861
2862 let mut tooltip_bounds =
2863 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
2864 let window_bounds = Bounds {
2865 origin: Point::default(),
2866 size: self.viewport_size(),
2867 };
2868
2869 if tooltip_bounds.right() > window_bounds.right() {
2870 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
2871 if new_x >= Pixels::ZERO {
2872 tooltip_bounds.origin.x = new_x;
2873 } else {
2874 tooltip_bounds.origin.x = cmp::max(
2875 Pixels::ZERO,
2876 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
2877 );
2878 }
2879 }
2880
2881 if tooltip_bounds.bottom() > window_bounds.bottom() {
2882 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
2883 if new_y >= Pixels::ZERO {
2884 tooltip_bounds.origin.y = new_y;
2885 } else {
2886 tooltip_bounds.origin.y = cmp::max(
2887 Pixels::ZERO,
2888 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
2889 );
2890 }
2891 }
2892
2893 let is_visible =
2897 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
2898 if !is_visible {
2899 continue;
2900 }
2901
2902 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
2903 element.prepaint(window, cx)
2904 });
2905
2906 self.tooltip_bounds = Some(TooltipBounds {
2907 id: tooltip_request.id,
2908 bounds: tooltip_bounds,
2909 });
2910 return Some(element);
2911 }
2912 None
2913 }
2914
2915 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
2916 assert_eq!(self.element_id_stack.len(), 0);
2917
2918 let mut completed_draws = Vec::new();
2919
2920 let mut depth = 0;
2923 loop {
2924 assert!(depth < 10, "Exceeded maximum (10) deferred depth");
2926 depth += 1;
2927 let deferred_count = self.next_frame.deferred_draws.len();
2928 if deferred_count == 0 {
2929 break;
2930 }
2931
2932 let traversal_order = self.deferred_draw_traversal_order();
2934 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2935
2936 for deferred_draw_ix in traversal_order {
2937 let deferred_draw = &mut deferred_draws[deferred_draw_ix];
2938 self.element_id_stack
2939 .clone_from(&deferred_draw.element_id_stack);
2940 self.text_style_stack
2941 .clone_from(&deferred_draw.text_style_stack);
2942 self.next_frame
2943 .dispatch_tree
2944 .set_active_node(deferred_draw.parent_node);
2945
2946 let prepaint_start = self.prepaint_index();
2947 if let Some(element) = deferred_draw.element.as_mut() {
2948 self.with_rendered_view(deferred_draw.current_view, |window| {
2949 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2950 window.with_absolute_element_offset(
2951 deferred_draw.absolute_offset,
2952 |window| {
2953 element.prepaint(window, cx);
2954 },
2955 );
2956 });
2957 })
2958 } else {
2959 self.reuse_prepaint(deferred_draw.prepaint_range.clone());
2960 }
2961 let prepaint_end = self.prepaint_index();
2962 deferred_draw.prepaint_range = prepaint_start..prepaint_end;
2963 }
2964
2965 completed_draws.append(&mut deferred_draws);
2967
2968 self.element_id_stack.clear();
2969 self.text_style_stack.clear();
2970 }
2971
2972 self.next_frame.deferred_draws = completed_draws;
2974 }
2975
2976 fn paint_deferred_draws(&mut self, cx: &mut App) {
2977 assert_eq!(self.element_id_stack.len(), 0);
2978
2979 if self.next_frame.deferred_draws.len() == 0 {
2982 return;
2983 }
2984
2985 let traversal_order = self.deferred_draw_traversal_order();
2986 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2987 for deferred_draw_ix in traversal_order {
2988 let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
2989 self.element_id_stack
2990 .clone_from(&deferred_draw.element_id_stack);
2991 self.next_frame
2992 .dispatch_tree
2993 .set_active_node(deferred_draw.parent_node);
2994
2995 let paint_start = self.paint_index();
2996 let content_mask = deferred_draw.content_mask;
2997 if let Some(element) = deferred_draw.element.as_mut() {
2998 self.with_rendered_view(deferred_draw.current_view, |window| {
2999 window.with_content_mask(content_mask, |window| {
3000 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
3001 element.paint(window, cx);
3002 });
3003 })
3004 })
3005 } else {
3006 self.reuse_paint(deferred_draw.paint_range.clone());
3007 }
3008 let paint_end = self.paint_index();
3009 deferred_draw.paint_range = paint_start..paint_end;
3010 }
3011 self.next_frame.deferred_draws = deferred_draws;
3012 self.element_id_stack.clear();
3013 }
3014
3015 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
3016 let deferred_count = self.next_frame.deferred_draws.len();
3017 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
3018 sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3019 sorted_indices
3020 }
3021
3022 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
3023 PrepaintStateIndex {
3024 hitboxes_index: self.next_frame.hitboxes.len(),
3025 tooltips_index: self.next_frame.tooltip_requests.len(),
3026 deferred_draws_index: self.next_frame.deferred_draws.len(),
3027 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
3028 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3029 line_layout_index: self.text_system.layout_index(),
3030 }
3031 }
3032
3033 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
3034 self.next_frame.hitboxes.extend(
3035 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
3036 .iter()
3037 .cloned(),
3038 );
3039 self.next_frame.tooltip_requests.extend(
3040 self.rendered_frame.tooltip_requests
3041 [range.start.tooltips_index..range.end.tooltips_index]
3042 .iter_mut()
3043 .map(|request| request.take()),
3044 );
3045 self.next_frame.accessed_element_states.extend(
3046 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3047 ..range.end.accessed_element_states_index]
3048 .iter()
3049 .map(|(id, type_id)| (id.clone(), *type_id)),
3050 );
3051 self.text_system
3052 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3053
3054 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
3055 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
3056 &mut self.rendered_frame.dispatch_tree,
3057 self.focus,
3058 );
3059
3060 if reused_subtree.contains_focus() {
3061 self.next_frame.focus = self.focus;
3062 }
3063
3064 self.next_frame.deferred_draws.extend(
3065 self.rendered_frame.deferred_draws
3066 [range.start.deferred_draws_index..range.end.deferred_draws_index]
3067 .iter()
3068 .map(|deferred_draw| DeferredDraw {
3069 current_view: deferred_draw.current_view,
3070 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
3071 element_id_stack: deferred_draw.element_id_stack.clone(),
3072 text_style_stack: deferred_draw.text_style_stack.clone(),
3073 content_mask: deferred_draw.content_mask,
3074 rem_size: deferred_draw.rem_size,
3075 priority: deferred_draw.priority,
3076 element: None,
3077 absolute_offset: deferred_draw.absolute_offset,
3078 prepaint_range: deferred_draw.prepaint_range.clone(),
3079 paint_range: deferred_draw.paint_range.clone(),
3080 }),
3081 );
3082 }
3083
3084 pub(crate) fn paint_index(&self) -> PaintIndex {
3085 PaintIndex {
3086 scene_index: self.next_frame.scene.len(),
3087 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
3088 input_handlers_index: self.next_frame.input_handlers.len(),
3089 cursor_styles_index: self.next_frame.cursor_styles.len(),
3090 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3091 tab_handle_index: self.next_frame.tab_stops.paint_index(),
3092 line_layout_index: self.text_system.layout_index(),
3093 }
3094 }
3095
3096 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
3097 self.next_frame.cursor_styles.extend(
3098 self.rendered_frame.cursor_styles
3099 [range.start.cursor_styles_index..range.end.cursor_styles_index]
3100 .iter()
3101 .cloned(),
3102 );
3103 self.next_frame.input_handlers.extend(
3104 self.rendered_frame.input_handlers
3105 [range.start.input_handlers_index..range.end.input_handlers_index]
3106 .iter_mut()
3107 .map(|handler| handler.take()),
3108 );
3109 self.next_frame.mouse_listeners.extend(
3110 self.rendered_frame.mouse_listeners
3111 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
3112 .iter_mut()
3113 .map(|listener| listener.take()),
3114 );
3115 self.next_frame.accessed_element_states.extend(
3116 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3117 ..range.end.accessed_element_states_index]
3118 .iter()
3119 .map(|(id, type_id)| (id.clone(), *type_id)),
3120 );
3121 self.next_frame.tab_stops.replay(
3122 &self.rendered_frame.tab_stops.insertion_history
3123 [range.start.tab_handle_index..range.end.tab_handle_index],
3124 );
3125
3126 self.text_system
3127 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3128 self.next_frame.scene.replay(
3129 range.start.scene_index..range.end.scene_index,
3130 &self.rendered_frame.scene,
3131 );
3132 }
3133
3134 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
3138 where
3139 F: FnOnce(&mut Self) -> R,
3140 {
3141 self.invalidator.debug_assert_paint_or_prepaint();
3142 if let Some(style) = style {
3143 self.text_style_stack.push(style);
3144 let result = f(self);
3145 self.text_style_stack.pop();
3146 result
3147 } else {
3148 f(self)
3149 }
3150 }
3151
3152 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
3155 self.invalidator.debug_assert_paint();
3156 self.next_frame.cursor_styles.push(CursorStyleRequest {
3157 hitbox_id: Some(hitbox.id),
3158 style,
3159 });
3160 }
3161
3162 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
3167 self.invalidator.debug_assert_paint();
3168 self.next_frame.cursor_styles.push(CursorStyleRequest {
3169 hitbox_id: None,
3170 style,
3171 })
3172 }
3173
3174 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
3177 self.invalidator.debug_assert_prepaint();
3178 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
3179 self.next_frame
3180 .tooltip_requests
3181 .push(Some(TooltipRequest { id, tooltip }));
3182 id
3183 }
3184
3185 #[inline]
3190 pub fn with_content_mask<R>(
3191 &mut self,
3192 mask: Option<ContentMask<Pixels>>,
3193 f: impl FnOnce(&mut Self) -> R,
3194 ) -> R {
3195 self.invalidator.debug_assert_paint_or_prepaint();
3196 if let Some(mask) = mask {
3197 let mask = mask.intersect(&self.content_mask());
3198 self.content_mask_stack.push(mask);
3199 let result = f(self);
3200 self.content_mask_stack.pop();
3201 result
3202 } else {
3203 f(self)
3204 }
3205 }
3206
3207 pub fn with_element_offset<R>(
3210 &mut self,
3211 offset: Point<Pixels>,
3212 f: impl FnOnce(&mut Self) -> R,
3213 ) -> R {
3214 self.invalidator.debug_assert_prepaint();
3215
3216 if offset.is_zero() {
3217 return f(self);
3218 };
3219
3220 let abs_offset = self.element_offset() + offset;
3221 self.with_absolute_element_offset(abs_offset, f)
3222 }
3223
3224 pub fn with_absolute_element_offset<R>(
3228 &mut self,
3229 offset: Point<Pixels>,
3230 f: impl FnOnce(&mut Self) -> R,
3231 ) -> R {
3232 self.invalidator.debug_assert_prepaint();
3233 self.element_offset_stack.push(offset);
3234 let result = f(self);
3235 self.element_offset_stack.pop();
3236 result
3237 }
3238
3239 pub(crate) fn with_element_opacity<R>(
3240 &mut self,
3241 opacity: Option<f32>,
3242 f: impl FnOnce(&mut Self) -> R,
3243 ) -> R {
3244 self.invalidator.debug_assert_paint_or_prepaint();
3245
3246 let Some(opacity) = opacity else {
3247 return f(self);
3248 };
3249
3250 let previous_opacity = self.element_opacity;
3251 self.element_opacity = previous_opacity * opacity;
3252 let result = f(self);
3253 self.element_opacity = previous_opacity;
3254 result
3255 }
3256
3257 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
3263 self.invalidator.debug_assert_prepaint();
3264 let index = self.prepaint_index();
3265 let result = f(self);
3266 if result.is_err() {
3267 self.next_frame.hitboxes.truncate(index.hitboxes_index);
3268 self.next_frame
3269 .tooltip_requests
3270 .truncate(index.tooltips_index);
3271 self.next_frame
3272 .deferred_draws
3273 .truncate(index.deferred_draws_index);
3274 self.next_frame
3275 .dispatch_tree
3276 .truncate(index.dispatch_tree_index);
3277 self.next_frame
3278 .accessed_element_states
3279 .truncate(index.accessed_element_states_index);
3280 self.text_system.truncate_layouts(index.line_layout_index);
3281 }
3282 result
3283 }
3284
3285 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
3291 self.invalidator.debug_assert_prepaint();
3292 self.requested_autoscroll = Some(bounds);
3293 }
3294
3295 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
3298 self.invalidator.debug_assert_prepaint();
3299 self.requested_autoscroll.take()
3300 }
3301
3302 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3308 let (task, is_first) = cx.fetch_asset::<A>(source);
3309 task.clone().now_or_never().or_else(|| {
3310 if is_first {
3311 let entity_id = self.current_view();
3312 self.spawn(cx, {
3313 let task = task.clone();
3314 async move |cx| {
3315 task.await;
3316
3317 cx.on_next_frame(move |_, cx| {
3318 cx.notify(entity_id);
3319 });
3320 }
3321 })
3322 .detach();
3323 }
3324
3325 None
3326 })
3327 }
3328
3329 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3335 let (task, _) = cx.fetch_asset::<A>(source);
3336 task.now_or_never()
3337 }
3338 pub fn element_offset(&self) -> Point<Pixels> {
3341 self.invalidator.debug_assert_prepaint();
3342 self.element_offset_stack
3343 .last()
3344 .copied()
3345 .unwrap_or_default()
3346 }
3347
3348 #[inline]
3351 pub(crate) fn element_opacity(&self) -> f32 {
3352 self.invalidator.debug_assert_paint_or_prepaint();
3353 self.element_opacity
3354 }
3355
3356 pub fn content_mask(&self) -> ContentMask<Pixels> {
3358 self.invalidator.debug_assert_paint_or_prepaint();
3359 self.content_mask_stack
3360 .last()
3361 .cloned()
3362 .unwrap_or_else(|| ContentMask {
3363 bounds: Bounds {
3364 origin: Point::default(),
3365 size: self.viewport_size,
3366 },
3367 })
3368 }
3369
3370 pub fn with_element_namespace<R>(
3373 &mut self,
3374 element_id: impl Into<ElementId>,
3375 f: impl FnOnce(&mut Self) -> R,
3376 ) -> R {
3377 self.element_id_stack.push(element_id.into());
3378 let result = f(self);
3379 self.element_id_stack.pop();
3380 result
3381 }
3382
3383 pub fn use_keyed_state<S: 'static>(
3385 &mut self,
3386 key: impl Into<ElementId>,
3387 cx: &mut App,
3388 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3389 ) -> Entity<S> {
3390 let current_view = self.current_view();
3391 self.with_global_id(key.into(), |global_id, window| {
3392 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
3393 if let Some(state) = state {
3394 (state.clone(), state)
3395 } else {
3396 let new_state = cx.new(|cx| init(window, cx));
3397 cx.observe(&new_state, move |_, cx| {
3398 cx.notify(current_view);
3399 })
3400 .detach();
3401 (new_state.clone(), new_state)
3402 }
3403 })
3404 })
3405 }
3406
3407 #[track_caller]
3413 pub fn use_state<S: 'static>(
3414 &mut self,
3415 cx: &mut App,
3416 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3417 ) -> Entity<S> {
3418 self.use_keyed_state(
3419 ElementId::CodeLocation(*core::panic::Location::caller()),
3420 cx,
3421 init,
3422 )
3423 }
3424
3425 pub fn with_element_state<S, R>(
3430 &mut self,
3431 global_id: &GlobalElementId,
3432 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
3433 ) -> R
3434 where
3435 S: 'static,
3436 {
3437 self.invalidator.debug_assert_paint_or_prepaint();
3438
3439 let key = (global_id.clone(), TypeId::of::<S>());
3440 self.next_frame.accessed_element_states.push(key.clone());
3441
3442 if let Some(any) = self
3443 .next_frame
3444 .element_states
3445 .remove(&key)
3446 .or_else(|| self.rendered_frame.element_states.remove(&key))
3447 {
3448 let ElementStateBox {
3449 inner,
3450 #[cfg(debug_assertions)]
3451 type_name,
3452 } = any;
3453 let mut state_box = inner
3455 .downcast::<Option<S>>()
3456 .map_err(|_| {
3457 #[cfg(debug_assertions)]
3458 {
3459 anyhow::anyhow!(
3460 "invalid element state type for id, requested {:?}, actual: {:?}",
3461 std::any::type_name::<S>(),
3462 type_name
3463 )
3464 }
3465
3466 #[cfg(not(debug_assertions))]
3467 {
3468 anyhow::anyhow!(
3469 "invalid element state type for id, requested {:?}",
3470 std::any::type_name::<S>(),
3471 )
3472 }
3473 })
3474 .unwrap();
3475
3476 let state = state_box.take().expect(
3477 "reentrant call to with_element_state for the same state type and element id",
3478 );
3479 let (result, state) = f(Some(state), self);
3480 state_box.replace(state);
3481 self.next_frame.element_states.insert(
3482 key,
3483 ElementStateBox {
3484 inner: state_box,
3485 #[cfg(debug_assertions)]
3486 type_name,
3487 },
3488 );
3489 result
3490 } else {
3491 let (result, state) = f(None, self);
3492 self.next_frame.element_states.insert(
3493 key,
3494 ElementStateBox {
3495 inner: Box::new(Some(state)),
3496 #[cfg(debug_assertions)]
3497 type_name: std::any::type_name::<S>(),
3498 },
3499 );
3500 result
3501 }
3502 }
3503
3504 pub fn with_optional_element_state<S, R>(
3511 &mut self,
3512 global_id: Option<&GlobalElementId>,
3513 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
3514 ) -> R
3515 where
3516 S: 'static,
3517 {
3518 self.invalidator.debug_assert_paint_or_prepaint();
3519
3520 if let Some(global_id) = global_id {
3521 self.with_element_state(global_id, |state, cx| {
3522 let (result, state) = f(Some(state), cx);
3523 let state =
3524 state.expect("you must return some state when you pass some element id");
3525 (result, state)
3526 })
3527 } else {
3528 let (result, state) = f(None, self);
3529 debug_assert!(
3530 state.is_none(),
3531 "you must not return an element state when passing None for the global id"
3532 );
3533 result
3534 }
3535 }
3536
3537 #[inline]
3539 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
3540 if let Some(index) = index {
3541 self.next_frame.tab_stops.begin_group(index);
3542 let result = f(self);
3543 self.next_frame.tab_stops.end_group();
3544 result
3545 } else {
3546 f(self)
3547 }
3548 }
3549
3550 pub fn defer_draw(
3559 &mut self,
3560 element: AnyElement,
3561 absolute_offset: Point<Pixels>,
3562 priority: usize,
3563 content_mask: Option<ContentMask<Pixels>>,
3564 ) {
3565 self.invalidator.debug_assert_prepaint();
3566 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3567 self.next_frame.deferred_draws.push(DeferredDraw {
3568 current_view: self.current_view(),
3569 parent_node,
3570 element_id_stack: self.element_id_stack.clone(),
3571 text_style_stack: self.text_style_stack.clone(),
3572 content_mask,
3573 rem_size: self.rem_size(),
3574 priority,
3575 element: Some(element),
3576 absolute_offset,
3577 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3578 paint_range: PaintIndex::default()..PaintIndex::default(),
3579 });
3580 }
3581
3582 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3588 self.invalidator.debug_assert_paint();
3589
3590 let content_mask = self.content_mask();
3591 let clipped_bounds = bounds.intersect(&content_mask.bounds);
3592 if !clipped_bounds.is_empty() {
3593 self.next_frame
3594 .scene
3595 .push_layer(self.cover_bounds(clipped_bounds));
3596 }
3597
3598 let result = f(self);
3599
3600 if !clipped_bounds.is_empty() {
3601 self.next_frame.scene.pop_layer();
3602 }
3603
3604 result
3605 }
3606
3607 pub fn paint_drop_shadows(
3613 &mut self,
3614 bounds: Bounds<Pixels>,
3615 corner_radii: Corners<Pixels>,
3616 shadows: &[BoxShadow],
3617 ) {
3618 self.invalidator.debug_assert_paint();
3619
3620 let scale_factor = self.scale_factor();
3621 let content_mask = self.snapped_content_mask();
3622 let opacity = self.element_opacity();
3623 let element_bounds = self.cover_bounds(bounds);
3624 let element_corner_radii = corner_radii.scale(scale_factor);
3625 for shadow in shadows {
3626 if shadow.inset {
3627 continue;
3628 }
3629 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3630 self.next_frame.scene.insert_primitive(Shadow {
3631 order: 0,
3632 blur_radius: shadow.blur_radius.scale(scale_factor),
3633 bounds: self.cover_bounds(shadow_bounds),
3634 content_mask,
3635 corner_radii: corner_radii.scale(scale_factor),
3636 color: shadow.color.opacity(opacity),
3637 element_bounds,
3638 element_corner_radii,
3639 inset: 0,
3640 pad: 0,
3641 });
3642 }
3643 }
3644
3645 pub fn paint_inset_shadows(
3649 &mut self,
3650 bounds: Bounds<Pixels>,
3651 corner_radii: Corners<Pixels>,
3652 shadows: &[BoxShadow],
3653 ) {
3654 self.invalidator.debug_assert_paint();
3655
3656 let scale_factor = self.scale_factor();
3657 let content_mask = self.snapped_content_mask();
3658 let opacity = self.element_opacity();
3659 let element_bounds = self.cover_bounds(bounds);
3660 let element_corner_radii = corner_radii.scale(scale_factor);
3661 for shadow in shadows {
3662 if !shadow.inset {
3663 continue;
3664 }
3665 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
3666 let zero = Pixels::ZERO;
3669 let hole_corner_radii = Corners {
3670 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
3671 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
3672 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
3673 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
3674 };
3675 self.next_frame.scene.insert_primitive(Shadow {
3676 order: 0,
3677 blur_radius: shadow.blur_radius.scale(scale_factor),
3678 bounds: self.cover_bounds(hole),
3679 content_mask,
3680 corner_radii: hole_corner_radii.scale(scale_factor),
3681 color: shadow.color.opacity(opacity),
3682 element_bounds,
3683 element_corner_radii,
3684 inset: 1,
3685 pad: 0,
3686 });
3687 }
3688 }
3689
3690 pub fn paint_quad(&mut self, quad: PaintQuad) {
3700 self.invalidator.debug_assert_paint();
3701
3702 let opacity = self.element_opacity();
3703 let snapped_bounds = self.snap_bounds(quad.bounds);
3704 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
3705 self.next_frame.scene.insert_primitive(Quad {
3706 order: 0,
3707 bounds: snapped_bounds,
3708 content_mask: self.snapped_content_mask(),
3709 background: quad.background.opacity(opacity),
3710 border_color: quad.border_color.opacity(opacity),
3711 corner_radii: quad.corner_radii.scale(self.scale_factor()),
3712 border_widths: snapped_border_widths,
3713 border_style: quad.border_style,
3714 });
3715 }
3716
3717 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
3721 self.invalidator.debug_assert_paint();
3722
3723 let scale_factor = self.scale_factor();
3724 let content_mask = self.content_mask();
3725 let opacity = self.element_opacity();
3726 path.content_mask = content_mask;
3727 let color: Background = color.into();
3728 path.color = color.opacity(opacity);
3729 self.next_frame
3730 .scene
3731 .insert_primitive(path.scale(scale_factor));
3732 }
3733
3734 pub fn paint_underline(
3738 &mut self,
3739 origin: Point<Pixels>,
3740 width: Pixels,
3741 style: &UnderlineStyle,
3742 ) {
3743 self.invalidator.debug_assert_paint();
3744
3745 let scale_factor = self.scale_factor();
3746 let thickness = self.snap_stroke(style.thickness);
3747 let height = if style.wavy {
3748 ScaledPixels(thickness.0 * 3.)
3749 } else {
3750 thickness
3751 };
3752 let bounds = Bounds {
3753 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3754 size: size(self.snap_stroke(width), height),
3755 };
3756 let element_opacity = self.element_opacity();
3757
3758 self.next_frame.scene.insert_primitive(Underline {
3759 order: 0,
3760 pad: 0,
3761 bounds,
3762 content_mask: self.snapped_content_mask(),
3763 color: style.color.unwrap_or_default().opacity(element_opacity),
3764 thickness,
3765 wavy: if style.wavy { 1 } else { 0 },
3766 });
3767 }
3768
3769 pub fn paint_strikethrough(
3773 &mut self,
3774 origin: Point<Pixels>,
3775 width: Pixels,
3776 style: &StrikethroughStyle,
3777 ) {
3778 self.invalidator.debug_assert_paint();
3779
3780 let scale_factor = self.scale_factor();
3781 let height = style.thickness;
3782 let bounds = Bounds {
3783 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3784 size: size(self.snap_stroke(width), self.snap_stroke(height)),
3785 };
3786 let opacity = self.element_opacity();
3787
3788 self.next_frame.scene.insert_primitive(Underline {
3789 order: 0,
3790 pad: 0,
3791 bounds,
3792 content_mask: self.snapped_content_mask(),
3793 thickness: self.snap_stroke(style.thickness),
3794 color: style.color.unwrap_or_default().opacity(opacity),
3795 wavy: 0,
3796 });
3797 }
3798
3799 pub fn paint_glyph(
3808 &mut self,
3809 origin: Point<Pixels>,
3810 font_id: FontId,
3811 glyph_id: GlyphId,
3812 font_size: Pixels,
3813 color: Hsla,
3814 ) -> Result<()> {
3815 self.invalidator.debug_assert_paint();
3816
3817 let element_opacity = self.element_opacity();
3818 let scale_factor = self.scale_factor();
3819 let glyph_origin = origin.scale(scale_factor);
3820
3821 let quantized_origin = Point::new(
3822 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
3823 / SUBPIXEL_VARIANTS_X as f32,
3824 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
3825 / SUBPIXEL_VARIANTS_Y as f32,
3826 );
3827 let subpixel_variant = Point::new(
3828 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
3829 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
3830 );
3831 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
3832 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
3833 let dilation = self.text_system().glyph_dilation_for_color(color);
3834 let params = RenderGlyphParams {
3835 font_id,
3836 glyph_id,
3837 font_size,
3838 subpixel_variant,
3839 scale_factor,
3840 is_emoji: false,
3841 subpixel_rendering,
3842 dilation,
3843 };
3844
3845 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
3846 if !raster_bounds.is_zero() {
3847 let tile = self
3848 .sprite_atlas
3849 .get_or_insert_with(¶ms.clone().into(), &mut || {
3850 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
3851 Ok(Some((size, Cow::Owned(bytes))))
3852 })?
3853 .expect("Callback above only errors or returns Some");
3854 let bounds = Bounds {
3855 origin: integer_origin + raster_bounds.origin.map(Into::into),
3856 size: tile.bounds.size.map(Into::into),
3857 };
3858 let content_mask = self.snapped_content_mask();
3859
3860 if subpixel_rendering {
3861 self.next_frame.scene.insert_primitive(SubpixelSprite {
3862 order: 0,
3863 pad: 0,
3864 bounds,
3865 content_mask,
3866 color: color.opacity(element_opacity),
3867 tile,
3868 transformation: TransformationMatrix::unit(),
3869 });
3870 } else {
3871 self.next_frame.scene.insert_primitive(MonochromeSprite {
3872 order: 0,
3873 pad: 0,
3874 bounds,
3875 content_mask,
3876 color: color.opacity(element_opacity),
3877 tile,
3878 transformation: TransformationMatrix::unit(),
3879 });
3880 }
3881 }
3882 Ok(())
3883 }
3884
3885 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
3886 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
3887 return false;
3888 }
3889
3890 if !self.platform_window.is_subpixel_rendering_supported() {
3891 return false;
3892 }
3893
3894 let mode = match self.text_rendering_mode.get() {
3895 TextRenderingMode::PlatformDefault => self
3896 .text_system()
3897 .recommended_rendering_mode(font_id, font_size),
3898 mode => mode,
3899 };
3900
3901 mode == TextRenderingMode::Subpixel
3902 }
3903
3904 pub fn paint_emoji(
3913 &mut self,
3914 origin: Point<Pixels>,
3915 font_id: FontId,
3916 glyph_id: GlyphId,
3917 font_size: Pixels,
3918 ) -> Result<()> {
3919 self.invalidator.debug_assert_paint();
3920
3921 let scale_factor = self.scale_factor();
3922 let glyph_origin = origin.scale(scale_factor);
3923 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
3924 let params = RenderGlyphParams {
3925 font_id,
3926 glyph_id,
3927 font_size,
3928 subpixel_variant: Default::default(),
3929 scale_factor,
3930 is_emoji: true,
3931 subpixel_rendering: false,
3932 dilation: 0,
3933 };
3934
3935 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
3936 if !raster_bounds.is_zero() {
3937 let tile = self
3938 .sprite_atlas
3939 .get_or_insert_with(¶ms.clone().into(), &mut || {
3940 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
3941 Ok(Some((size, Cow::Owned(bytes))))
3942 })?
3943 .expect("Callback above only errors or returns Some");
3944
3945 let bounds = Bounds {
3946 origin: integer_origin + raster_bounds.origin.map(Into::into),
3947 size: tile.bounds.size.map(Into::into),
3948 };
3949 let content_mask = self.snapped_content_mask();
3950 let opacity = self.element_opacity();
3951
3952 self.next_frame.scene.insert_primitive(PolychromeSprite {
3953 order: 0,
3954 pad: 0,
3955 grayscale: false,
3956 bounds,
3957 corner_radii: Default::default(),
3958 content_mask,
3959 tile,
3960 opacity,
3961 });
3962 }
3963 Ok(())
3964 }
3965
3966 pub fn paint_svg(
3970 &mut self,
3971 bounds: Bounds<Pixels>,
3972 path: SharedString,
3973 mut data: Option<&[u8]>,
3974 transformation: TransformationMatrix,
3975 color: Hsla,
3976 cx: &App,
3977 ) -> Result<()> {
3978 self.invalidator.debug_assert_paint();
3979
3980 let element_opacity = self.element_opacity();
3981 let bounds = self.snap_bounds(bounds);
3982
3983 let params = RenderSvgParams {
3984 path,
3985 size: bounds.size.map(|pixels| {
3986 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
3987 }),
3988 };
3989
3990 let Some(tile) =
3991 self.sprite_atlas
3992 .get_or_insert_with(¶ms.clone().into(), &mut || {
3993 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
3994 else {
3995 return Ok(None);
3996 };
3997 Ok(Some((size, Cow::Owned(bytes))))
3998 })?
3999 else {
4000 return Ok(());
4001 };
4002 let content_mask = self.snapped_content_mask();
4003 let svg_bounds = Bounds {
4004 origin: bounds.center()
4005 - Point::new(
4006 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4007 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4008 ),
4009 size: tile
4010 .bounds
4011 .size
4012 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
4013 };
4014 let final_bounds = svg_bounds
4015 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
4016 .map_size(|size| size.ceil());
4017
4018 self.next_frame.scene.insert_primitive(MonochromeSprite {
4019 order: 0,
4020 pad: 0,
4021 bounds: final_bounds,
4022 content_mask,
4023 color: color.opacity(element_opacity),
4024 tile,
4025 transformation,
4026 });
4027
4028 Ok(())
4029 }
4030
4031 pub fn paint_image(
4036 &mut self,
4037 bounds: Bounds<Pixels>,
4038 corner_radii: Corners<Pixels>,
4039 data: Arc<RenderImage>,
4040 frame_index: usize,
4041 grayscale: bool,
4042 ) -> Result<()> {
4043 self.invalidator.debug_assert_paint();
4044
4045 let bounds = self.snap_bounds(bounds);
4046 let params = RenderImageParams {
4047 image_id: data.id,
4048 frame_index,
4049 };
4050
4051 let tile = self
4052 .sprite_atlas
4053 .get_or_insert_with(¶ms.into(), &mut || {
4054 Ok(Some((
4055 data.size(frame_index),
4056 Cow::Borrowed(
4057 data.as_bytes(frame_index)
4058 .expect("It's the caller's job to pass a valid frame index"),
4059 ),
4060 )))
4061 })?
4062 .expect("Callback above only returns Some");
4063 let content_mask = self.snapped_content_mask();
4064 let corner_radii = corner_radii.scale(self.scale_factor());
4065 let opacity = self.element_opacity();
4066
4067 self.next_frame.scene.insert_primitive(PolychromeSprite {
4068 order: 0,
4069 pad: 0,
4070 grayscale,
4071 bounds,
4072 content_mask,
4073 corner_radii,
4074 tile,
4075 opacity,
4076 });
4077 Ok(())
4078 }
4079
4080 #[cfg(target_os = "macos")]
4084 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: PlatformPixelBuffer) {
4085 use crate::PaintSurface;
4086
4087 self.invalidator.debug_assert_paint();
4088
4089 let bounds = self.snap_bounds(bounds);
4090 let content_mask = self.snapped_content_mask();
4091 self.next_frame.scene.insert_primitive(PaintSurface {
4092 order: 0,
4093 bounds,
4094 content_mask,
4095 image_buffer,
4096 });
4097 }
4098
4099 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
4101 for frame_index in 0..data.frame_count() {
4102 let params = RenderImageParams {
4103 image_id: data.id,
4104 frame_index,
4105 };
4106
4107 self.sprite_atlas.remove(¶ms.clone().into());
4108 }
4109
4110 Ok(())
4111 }
4112
4113 #[must_use]
4119 pub fn request_layout(
4120 &mut self,
4121 style: Style,
4122 children: impl IntoIterator<Item = LayoutId>,
4123 cx: &mut App,
4124 ) -> LayoutId {
4125 self.invalidator.debug_assert_prepaint();
4126
4127 cx.layout_id_buffer.clear();
4128 cx.layout_id_buffer.extend(children);
4129 let rem_size = self.rem_size();
4130 let scale_factor = self.scale_factor();
4131
4132 self.layout_engine.as_mut().unwrap().request_layout(
4133 style,
4134 rem_size,
4135 scale_factor,
4136 &cx.layout_id_buffer,
4137 )
4138 }
4139
4140 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
4149 where
4150 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
4151 + 'static,
4152 {
4153 self.invalidator.debug_assert_prepaint();
4154
4155 let rem_size = self.rem_size();
4156 let scale_factor = self.scale_factor();
4157 self.layout_engine
4158 .as_mut()
4159 .unwrap()
4160 .request_measured_layout(style, rem_size, scale_factor, measure)
4161 }
4162
4163 pub fn compute_layout(
4169 &mut self,
4170 layout_id: LayoutId,
4171 available_space: Size<AvailableSpace>,
4172 cx: &mut App,
4173 ) {
4174 self.invalidator.debug_assert_prepaint();
4175
4176 let mut layout_engine = self.layout_engine.take().unwrap();
4177 layout_engine.compute_layout(layout_id, available_space, self, cx);
4178 self.layout_engine = Some(layout_engine);
4179 }
4180
4181 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
4186 self.invalidator.debug_assert_prepaint();
4187
4188 let scale_factor = self.scale_factor();
4189 let mut bounds = self
4190 .layout_engine
4191 .as_mut()
4192 .unwrap()
4193 .layout_bounds(layout_id, scale_factor)
4194 .map(Into::into);
4195 let snapped_offset = self.pixel_snap_point(self.element_offset());
4196 bounds.origin += snapped_offset;
4197 bounds
4198 }
4199
4200 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
4206 self.invalidator.debug_assert_prepaint();
4207
4208 let content_mask = self.content_mask();
4209 let mut id = self.next_hitbox_id;
4210 self.next_hitbox_id = self.next_hitbox_id.next();
4211 let hitbox = Hitbox {
4212 id,
4213 bounds,
4214 content_mask,
4215 behavior,
4216 };
4217 self.next_frame.hitboxes.push(hitbox.clone());
4218 hitbox
4219 }
4220
4221 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
4225 self.invalidator.debug_assert_paint();
4226 self.next_frame.window_control_hitboxes.push((area, hitbox));
4227 }
4228
4229 pub fn set_key_context(&mut self, context: KeyContext) {
4234 self.invalidator.debug_assert_paint();
4235 self.next_frame.dispatch_tree.set_key_context(context);
4236 }
4237
4238 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
4243 self.invalidator.debug_assert_prepaint();
4244 if focus_handle.is_focused(self) {
4245 self.next_frame.focus = Some(focus_handle.id);
4246 }
4247 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
4248 }
4249
4250 pub fn set_view_id(&mut self, view_id: EntityId) {
4256 self.invalidator.debug_assert_prepaint();
4257 self.next_frame.dispatch_tree.set_view_id(view_id);
4258 }
4259
4260 pub fn current_view(&self) -> EntityId {
4262 self.invalidator.debug_assert_paint_or_prepaint();
4263 self.rendered_entity_stack.last().copied().unwrap()
4264 }
4265
4266 #[inline]
4267 pub(crate) fn with_rendered_view<R>(
4268 &mut self,
4269 id: EntityId,
4270 f: impl FnOnce(&mut Self) -> R,
4271 ) -> R {
4272 self.rendered_entity_stack.push(id);
4273 let result = f(self);
4274 self.rendered_entity_stack.pop();
4275 result
4276 }
4277
4278 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
4280 where
4281 F: FnOnce(&mut Self) -> R,
4282 {
4283 if let Some(image_cache) = image_cache {
4284 self.image_cache_stack.push(image_cache);
4285 let result = f(self);
4286 self.image_cache_stack.pop();
4287 result
4288 } else {
4289 f(self)
4290 }
4291 }
4292
4293 pub fn handle_input(
4302 &mut self,
4303 focus_handle: &FocusHandle,
4304 input_handler: impl InputHandler,
4305 cx: &App,
4306 ) {
4307 self.invalidator.debug_assert_paint();
4308
4309 if focus_handle.is_focused(self) {
4310 let cx = self.to_async(cx);
4311 self.next_frame
4312 .input_handlers
4313 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
4314 }
4315 }
4316
4317 pub fn on_mouse_event<Event: MouseEvent>(
4323 &mut self,
4324 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4325 ) {
4326 self.invalidator.debug_assert_paint();
4327
4328 self.next_frame.mouse_listeners.push(Some(Box::new(
4329 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
4330 if let Some(event) = event.downcast_ref() {
4331 listener(event, phase, window, cx)
4332 }
4333 },
4334 )));
4335 }
4336
4337 pub fn on_key_event<Event: KeyEvent>(
4346 &mut self,
4347 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4348 ) {
4349 self.invalidator.debug_assert_paint();
4350
4351 self.next_frame.dispatch_tree.on_key_event(Rc::new(
4352 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
4353 if let Some(event) = event.downcast_ref::<Event>() {
4354 listener(event, phase, window, cx)
4355 }
4356 },
4357 ));
4358 }
4359
4360 pub fn on_modifiers_changed(
4367 &mut self,
4368 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
4369 ) {
4370 self.invalidator.debug_assert_paint();
4371
4372 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
4373 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
4374 listener(event, window, cx)
4375 },
4376 ));
4377 }
4378
4379 pub fn on_focus_in(
4383 &mut self,
4384 handle: &FocusHandle,
4385 cx: &mut App,
4386 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
4387 ) -> Subscription {
4388 let focus_id = handle.id;
4389 let (subscription, activate) =
4390 self.new_focus_listener(Box::new(move |event, window, cx| {
4391 if event.is_focus_in(focus_id) {
4392 listener(window, cx);
4393 }
4394 true
4395 }));
4396 cx.defer(move |_| activate());
4397 subscription
4398 }
4399
4400 pub fn on_focus_out(
4403 &mut self,
4404 handle: &FocusHandle,
4405 cx: &mut App,
4406 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
4407 ) -> Subscription {
4408 let focus_id = handle.id;
4409 let (subscription, activate) =
4410 self.new_focus_listener(Box::new(move |event, window, cx| {
4411 if let Some(blurred_id) = event.previous_focus_path.last().copied()
4412 && event.is_focus_out(focus_id)
4413 {
4414 let event = FocusOutEvent {
4415 blurred: WeakFocusHandle {
4416 id: blurred_id,
4417 handles: Arc::downgrade(&cx.focus_handles),
4418 },
4419 };
4420 listener(event, window, cx)
4421 }
4422 true
4423 }));
4424 cx.defer(move |_| activate());
4425 subscription
4426 }
4427
4428 fn reset_cursor_style(&self, _cx: &mut App) {
4429 let style = self
4430 .rendered_frame
4431 .cursor_style(self)
4432 .unwrap_or(CursorStyle::Arrow);
4433 self.platform_window.set_cursor_style(style);
4434 }
4435
4436 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
4439 let keystroke = keystroke.with_simulated_ime();
4440 let result = self.dispatch_event(
4441 PlatformInput::KeyDown(KeyDownEvent {
4442 keystroke: keystroke.clone(),
4443 is_held: false,
4444 prefer_character_input: false,
4445 }),
4446 cx,
4447 );
4448 if !result.propagate {
4449 return true;
4450 }
4451
4452 if let Some(input) = keystroke.key_char
4453 && let Some(mut input_handler) = self.platform_window.take_input_handler()
4454 {
4455 input_handler.dispatch_input(&input, self, cx);
4456 self.platform_window.set_input_handler(input_handler);
4457 return true;
4458 }
4459
4460 false
4461 }
4462
4463 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
4466 self.highest_precedence_binding_for_action(action)
4467 .map(|binding| {
4468 binding
4469 .keystrokes()
4470 .iter()
4471 .map(ToString::to_string)
4472 .collect::<Vec<_>>()
4473 .join(" ")
4474 })
4475 .unwrap_or_else(|| action.name().to_string())
4476 }
4477
4478 #[profiling::function]
4480 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
4481 #[cfg(feature = "input-latency-histogram")]
4482 let dispatch_time = Instant::now();
4483 let update_count_before = self.invalidator.update_count();
4484 let old_modality = self.last_input_modality;
4488 self.last_input_modality = match &event {
4489 PlatformInput::KeyDown(_) => InputModality::Keyboard,
4490 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
4491 _ => self.last_input_modality,
4492 };
4493 if self.last_input_modality != old_modality {
4494 self.refresh();
4495 }
4496
4497 cx.propagate_event = true;
4499 self.default_prevented = false;
4501
4502 let event = match event {
4503 PlatformInput::MouseMove(mouse_move) => {
4506 self.mouse_position = mouse_move.position;
4507 self.mouse_in_window = true;
4508 self.modifiers = mouse_move.modifiers;
4509 PlatformInput::MouseMove(mouse_move)
4510 }
4511 PlatformInput::MouseDown(mouse_down) => {
4512 self.mouse_position = mouse_down.position;
4513 self.mouse_in_window = true;
4514 self.modifiers = mouse_down.modifiers;
4515 PlatformInput::MouseDown(mouse_down)
4516 }
4517 PlatformInput::MouseUp(mouse_up) => {
4518 self.mouse_position = mouse_up.position;
4519 self.mouse_in_window = true;
4520 self.modifiers = mouse_up.modifiers;
4521 PlatformInput::MouseUp(mouse_up)
4522 }
4523 PlatformInput::MousePressure(mouse_pressure) => {
4524 PlatformInput::MousePressure(mouse_pressure)
4525 }
4526 PlatformInput::MouseExited(mouse_exited) => {
4527 self.mouse_position = mouse_exited.position;
4528 self.mouse_in_window = false;
4529 self.modifiers = mouse_exited.modifiers;
4530 PlatformInput::MouseExited(mouse_exited)
4531 }
4532 PlatformInput::ModifiersChanged(modifiers_changed) => {
4533 self.modifiers = modifiers_changed.modifiers;
4534 self.capslock = modifiers_changed.capslock;
4535 PlatformInput::ModifiersChanged(modifiers_changed)
4536 }
4537 PlatformInput::ScrollWheel(scroll_wheel) => {
4538 self.mouse_position = scroll_wheel.position;
4539 self.mouse_in_window = true;
4540 self.modifiers = scroll_wheel.modifiers;
4541 PlatformInput::ScrollWheel(scroll_wheel)
4542 }
4543 PlatformInput::Pinch(pinch) => {
4544 self.mouse_position = pinch.position;
4545 self.mouse_in_window = true;
4546 self.modifiers = pinch.modifiers;
4547 PlatformInput::Pinch(pinch)
4548 }
4549 PlatformInput::FileDrop(file_drop) => match file_drop {
4552 FileDropEvent::Entered { position, paths } => {
4553 self.mouse_position = position;
4554 self.mouse_in_window = true;
4555 if cx.active_drag.is_none() {
4556 cx.active_drag = Some(AnyDrag {
4557 value: Arc::new(paths.clone()),
4558 view: cx.new(|_| paths).into(),
4559 cursor_offset: position,
4560 cursor_style: None,
4561 });
4562 }
4563 PlatformInput::MouseMove(MouseMoveEvent {
4564 position,
4565 pressed_button: Some(MouseButton::Left),
4566 modifiers: Modifiers::default(),
4567 })
4568 }
4569 FileDropEvent::Pending { position } => {
4570 self.mouse_position = position;
4571 self.mouse_in_window = true;
4572 PlatformInput::MouseMove(MouseMoveEvent {
4573 position,
4574 pressed_button: Some(MouseButton::Left),
4575 modifiers: Modifiers::default(),
4576 })
4577 }
4578 FileDropEvent::Submit { position } => {
4579 cx.activate(true);
4580 self.mouse_position = position;
4581 self.mouse_in_window = true;
4582 PlatformInput::MouseUp(MouseUpEvent {
4583 button: MouseButton::Left,
4584 position,
4585 modifiers: Modifiers::default(),
4586 click_count: 1,
4587 })
4588 }
4589 FileDropEvent::Exited => {
4590 self.mouse_in_window = false;
4591 cx.active_drag.take();
4592 PlatformInput::FileDrop(FileDropEvent::Exited)
4593 }
4594 },
4595 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
4596 };
4597
4598 if let Some(any_mouse_event) = event.mouse_event() {
4599 self.dispatch_mouse_event(any_mouse_event, cx);
4600 } else if let Some(any_key_event) = event.keyboard_event() {
4601 self.dispatch_key_event(any_key_event, cx);
4602 }
4603
4604 if self.invalidator.update_count() > update_count_before {
4605 self.input_rate_tracker.borrow_mut().record_input();
4606 #[cfg(feature = "input-latency-histogram")]
4607 if self.invalidator.not_drawing() {
4608 self.input_latency_tracker.record_input(dispatch_time);
4609 } else {
4610 self.input_latency_tracker.record_mid_draw_input();
4611 }
4612 }
4613
4614 DispatchEventResult {
4615 propagate: cx.propagate_event,
4616 default_prevented: self.default_prevented,
4617 }
4618 }
4619
4620 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4621 let exited_window = event.is::<crate::MouseExitEvent>();
4622 let hit_test = if exited_window {
4623 HitTest::default()
4624 } else {
4625 self.rendered_frame.hit_test(self.mouse_position())
4626 };
4627 if exited_window || hit_test != self.mouse_hit_test {
4628 self.mouse_hit_test = hit_test;
4629 self.reset_cursor_style(cx);
4630 }
4631
4632 #[cfg(any(feature = "inspector", debug_assertions))]
4633 if self.is_inspector_picking(cx) {
4634 self.handle_inspector_mouse_event(event, cx);
4635 return;
4637 }
4638
4639 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
4640
4641 for listener in &mut mouse_listeners {
4644 let listener = listener.as_mut().unwrap();
4645 listener(event, DispatchPhase::Capture, self, cx);
4646 if !cx.propagate_event {
4647 break;
4648 }
4649 }
4650
4651 if cx.propagate_event {
4653 for listener in mouse_listeners.iter_mut().rev() {
4654 let listener = listener.as_mut().unwrap();
4655 listener(event, DispatchPhase::Bubble, self, cx);
4656 if !cx.propagate_event {
4657 break;
4658 }
4659 }
4660 }
4661
4662 self.rendered_frame.mouse_listeners = mouse_listeners;
4663
4664 if cx.has_active_drag() {
4665 if event.is::<MouseMoveEvent>() {
4666 self.refresh();
4669 } else if event.is::<MouseUpEvent>() {
4670 cx.active_drag = None;
4673 self.refresh();
4674 }
4675 }
4676
4677 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
4679 self.captured_hitbox = None;
4680 }
4681 }
4682
4683 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
4684 if self.invalidator.is_dirty() {
4685 self.draw(cx).clear();
4686 }
4687
4688 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4689 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4690
4691 let mut keystroke: Option<Keystroke> = None;
4692
4693 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
4694 if event.modifiers.number_of_modifiers() == 0
4695 && self.pending_modifier.modifiers.number_of_modifiers() == 1
4696 && !self.pending_modifier.saw_keystroke
4697 {
4698 let key = match self.pending_modifier.modifiers {
4699 modifiers if modifiers.shift => Some("shift"),
4700 modifiers if modifiers.control => Some("control"),
4701 modifiers if modifiers.alt => Some("alt"),
4702 modifiers if modifiers.platform => Some("platform"),
4703 modifiers if modifiers.function => Some("function"),
4704 _ => None,
4705 };
4706 if let Some(key) = key {
4707 keystroke = Some(Keystroke {
4708 key: key.to_string(),
4709 key_char: None,
4710 modifiers: Modifiers::default(),
4711 });
4712 }
4713 }
4714
4715 if self.pending_modifier.modifiers.number_of_modifiers() == 0
4716 && event.modifiers.number_of_modifiers() == 1
4717 {
4718 self.pending_modifier.saw_keystroke = false
4719 }
4720 self.pending_modifier.modifiers = event.modifiers
4721 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
4722 self.pending_modifier.saw_keystroke = true;
4723 keystroke = Some(key_down_event.keystroke.clone());
4724 if key_down_event.keystroke.key_char.is_some()
4725 && matches!(
4726 cx.cursor_hide_mode,
4727 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
4728 )
4729 {
4730 cx.platform.hide_cursor_until_mouse_moves();
4731 }
4732 }
4733
4734 let Some(keystroke) = keystroke else {
4735 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4736 return;
4737 };
4738
4739 cx.propagate_event = true;
4740 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
4741 if !cx.propagate_event {
4742 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4743 return;
4744 }
4745
4746 let mut currently_pending = self.pending_input.take().unwrap_or_default();
4747 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
4748 currently_pending = PendingInput::default();
4749 }
4750
4751 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
4752 currently_pending.keystrokes,
4753 keystroke,
4754 &dispatch_path,
4755 );
4756
4757 if !match_result.to_replay.is_empty() {
4758 self.replay_pending_input(match_result.to_replay, cx);
4759 cx.propagate_event = true;
4760 }
4761
4762 if !match_result.pending.is_empty() {
4763 currently_pending.timer.take();
4764 currently_pending.keystrokes = match_result.pending;
4765 currently_pending.focus = self.focus;
4766
4767 let text_input_requires_timeout = event
4768 .downcast_ref::<KeyDownEvent>()
4769 .filter(|key_down| key_down.keystroke.key_char.is_some())
4770 .and_then(|_| self.platform_window.take_input_handler())
4771 .map_or(false, |mut input_handler| {
4772 let accepts = input_handler.accepts_text_input(self, cx);
4773 self.platform_window.set_input_handler(input_handler);
4774 accepts
4775 });
4776
4777 currently_pending.needs_timeout |=
4778 match_result.pending_has_binding || text_input_requires_timeout;
4779
4780 if currently_pending.needs_timeout {
4781 currently_pending.timer = Some(self.spawn(cx, async move |cx| {
4782 cx.background_executor.timer(Duration::from_secs(1)).await;
4783 cx.update(move |window, cx| {
4784 let Some(currently_pending) = window
4785 .pending_input
4786 .take()
4787 .filter(|pending| pending.focus == window.focus)
4788 else {
4789 return;
4790 };
4791
4792 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
4793 let dispatch_path =
4794 window.rendered_frame.dispatch_tree.dispatch_path(node_id);
4795
4796 let to_replay = window
4797 .rendered_frame
4798 .dispatch_tree
4799 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
4800
4801 window.pending_input_changed(cx);
4802 window.replay_pending_input(to_replay, cx)
4803 })
4804 .log_err();
4805 }));
4806 } else {
4807 currently_pending.timer = None;
4808 }
4809 self.pending_input = Some(currently_pending);
4810 self.pending_input_changed(cx);
4811 cx.propagate_event = false;
4812 return;
4813 }
4814
4815 let skip_bindings = event
4816 .downcast_ref::<KeyDownEvent>()
4817 .filter(|key_down_event| key_down_event.prefer_character_input)
4818 .map(|_| {
4819 self.platform_window
4820 .take_input_handler()
4821 .map_or(false, |mut input_handler| {
4822 let accepts = input_handler.accepts_text_input(self, cx);
4823 self.platform_window.set_input_handler(input_handler);
4824 accepts
4827 })
4828 })
4829 .unwrap_or(false);
4830
4831 if !skip_bindings {
4832 for binding in match_result.bindings {
4833 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4834 if !cx.propagate_event {
4835 self.dispatch_keystroke_observers(
4836 event,
4837 Some(binding.action),
4838 match_result.context_stack,
4839 cx,
4840 );
4841 self.pending_input_changed(cx);
4842 return;
4843 }
4844 }
4845 }
4846
4847 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
4848 self.pending_input_changed(cx);
4849 }
4850
4851 fn finish_dispatch_key_event(
4852 &mut self,
4853 event: &dyn Any,
4854 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
4855 context_stack: Vec<KeyContext>,
4856 cx: &mut App,
4857 ) {
4858 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
4859 if !cx.propagate_event {
4860 return;
4861 }
4862
4863 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
4864 if !cx.propagate_event {
4865 return;
4866 }
4867
4868 self.dispatch_keystroke_observers(event, None, context_stack, cx);
4869 }
4870
4871 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
4872 self.pending_input_observers
4873 .clone()
4874 .retain(&(), |callback| callback(self, cx));
4875 }
4876
4877 fn dispatch_key_down_up_event(
4878 &mut self,
4879 event: &dyn Any,
4880 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4881 cx: &mut App,
4882 ) {
4883 for node_id in dispatch_path {
4885 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4886
4887 for key_listener in node.key_listeners.clone() {
4888 key_listener(event, DispatchPhase::Capture, self, cx);
4889 if !cx.propagate_event {
4890 return;
4891 }
4892 }
4893 }
4894
4895 for node_id in dispatch_path.iter().rev() {
4897 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4899 for key_listener in node.key_listeners.clone() {
4900 key_listener(event, DispatchPhase::Bubble, self, cx);
4901 if !cx.propagate_event {
4902 return;
4903 }
4904 }
4905 }
4906 }
4907
4908 fn dispatch_modifiers_changed_event(
4909 &mut self,
4910 event: &dyn Any,
4911 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4912 cx: &mut App,
4913 ) {
4914 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
4915 return;
4916 };
4917 for node_id in dispatch_path.iter().rev() {
4918 let node = self.rendered_frame.dispatch_tree.node(*node_id);
4919 for listener in node.modifiers_changed_listeners.clone() {
4920 listener(event, self, cx);
4921 if !cx.propagate_event {
4922 return;
4923 }
4924 }
4925 }
4926 }
4927
4928 pub fn has_pending_keystrokes(&self) -> bool {
4930 self.pending_input.is_some()
4931 }
4932
4933 pub(crate) fn clear_pending_keystrokes(&mut self) {
4934 self.pending_input.take();
4935 }
4936
4937 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
4939 self.pending_input
4940 .as_ref()
4941 .map(|pending_input| pending_input.keystrokes.as_slice())
4942 }
4943
4944 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
4945 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4946 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4947
4948 'replay: for replay in replays {
4949 let event = KeyDownEvent {
4950 keystroke: replay.keystroke.clone(),
4951 is_held: false,
4952 prefer_character_input: true,
4953 };
4954
4955 cx.propagate_event = true;
4956 for binding in replay.bindings {
4957 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4958 if !cx.propagate_event {
4959 self.dispatch_keystroke_observers(
4960 &event,
4961 Some(binding.action),
4962 Vec::default(),
4963 cx,
4964 );
4965 continue 'replay;
4966 }
4967 }
4968
4969 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
4970 if !cx.propagate_event {
4971 continue 'replay;
4972 }
4973 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
4974 && let Some(mut input_handler) = self.platform_window.take_input_handler()
4975 {
4976 input_handler.dispatch_input(&input, self, cx);
4977 self.platform_window.set_input_handler(input_handler)
4978 }
4979 }
4980 }
4981
4982 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
4983 focus_id
4984 .and_then(|focus_id| {
4985 self.rendered_frame
4986 .dispatch_tree
4987 .focusable_node_id(focus_id)
4988 })
4989 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
4990 }
4991
4992 fn dispatch_action_on_node(
4993 &mut self,
4994 node_id: DispatchNodeId,
4995 action: &dyn Action,
4996 cx: &mut App,
4997 ) {
4998 self.dispatch_action_on_node_inner(node_id, action, cx);
4999
5000 if !cx.propagate_event
5001 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
5002 && self.last_input_was_keyboard()
5003 {
5004 cx.platform.hide_cursor_until_mouse_moves();
5005 }
5006 }
5007
5008 fn dispatch_action_on_node_inner(
5009 &mut self,
5010 node_id: DispatchNodeId,
5011 action: &dyn Action,
5012 cx: &mut App,
5013 ) {
5014 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5015
5016 cx.propagate_event = true;
5018 if let Some(mut global_listeners) = cx
5019 .global_action_listeners
5020 .remove(&action.as_any().type_id())
5021 {
5022 for listener in &global_listeners {
5023 profiler::update_running_action(action, cx);
5024 listener(action.as_any(), DispatchPhase::Capture, cx);
5025 profiler::save_action_timing();
5026 if !cx.propagate_event {
5027 break;
5028 }
5029 }
5030
5031 global_listeners.extend(
5032 cx.global_action_listeners
5033 .remove(&action.as_any().type_id())
5034 .unwrap_or_default(),
5035 );
5036
5037 cx.global_action_listeners
5038 .insert(action.as_any().type_id(), global_listeners);
5039 }
5040
5041 if !cx.propagate_event {
5042 return;
5043 }
5044
5045 for node_id in &dispatch_path {
5047 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5048 for DispatchActionListener {
5049 action_type,
5050 listener,
5051 } in node.action_listeners.clone()
5052 {
5053 let any_action = action.as_any();
5054 if action_type == any_action.type_id() {
5055 profiler::update_running_action(action, cx);
5056 listener(any_action, DispatchPhase::Capture, self, cx);
5057 profiler::save_action_timing();
5058
5059 if !cx.propagate_event {
5060 return;
5061 }
5062 }
5063 }
5064 }
5065
5066 for node_id in dispatch_path.iter().rev() {
5068 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5069 for DispatchActionListener {
5070 action_type,
5071 listener,
5072 } in node.action_listeners.clone()
5073 {
5074 let any_action = action.as_any();
5075 if action_type == any_action.type_id() {
5076 cx.propagate_event = false; profiler::update_running_action(action, cx);
5078 listener(any_action, DispatchPhase::Bubble, self, cx);
5079 profiler::save_action_timing();
5080
5081 if !cx.propagate_event {
5082 return;
5083 }
5084 }
5085 }
5086 }
5087
5088 if let Some(mut global_listeners) = cx
5090 .global_action_listeners
5091 .remove(&action.as_any().type_id())
5092 {
5093 for listener in global_listeners.iter().rev() {
5094 cx.propagate_event = false; profiler::update_running_action(action, cx);
5097 listener(action.as_any(), DispatchPhase::Bubble, cx);
5098 profiler::save_action_timing();
5099 if !cx.propagate_event {
5100 break;
5101 }
5102 }
5103
5104 global_listeners.extend(
5105 cx.global_action_listeners
5106 .remove(&action.as_any().type_id())
5107 .unwrap_or_default(),
5108 );
5109
5110 cx.global_action_listeners
5111 .insert(action.as_any().type_id(), global_listeners);
5112 }
5113 }
5114
5115 pub fn observe_global<G: Global>(
5118 &mut self,
5119 cx: &mut App,
5120 f: impl Fn(&mut Window, &mut App) + 'static,
5121 ) -> Subscription {
5122 let window_handle = self.handle;
5123 let (subscription, activate) = cx.global_observers.insert(
5124 TypeId::of::<G>(),
5125 Box::new(move |cx| {
5126 window_handle
5127 .update(cx, |_, window, cx| f(window, cx))
5128 .is_ok()
5129 }),
5130 );
5131 cx.defer(move |_| activate());
5132 subscription
5133 }
5134
5135 pub fn activate_window(&self) {
5137 self.platform_window.activate();
5138 }
5139
5140 pub fn minimize_window(&self) {
5142 self.platform_window.minimize();
5143 }
5144
5145 pub fn toggle_fullscreen(&self) {
5147 self.platform_window.toggle_fullscreen();
5148 }
5149
5150 pub fn invalidate_character_coordinates(&self) {
5152 self.on_next_frame(|window, cx| {
5153 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
5154 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
5155 window.platform_window.update_ime_position(bounds);
5156 }
5157 window.platform_window.set_input_handler(input_handler);
5158 }
5159 });
5160 }
5161
5162 pub fn prompt<T>(
5166 &mut self,
5167 level: PromptLevel,
5168 message: &str,
5169 detail: Option<&str>,
5170 answers: &[T],
5171 cx: &mut App,
5172 ) -> oneshot::Receiver<usize>
5173 where
5174 T: Clone + Into<PromptButton>,
5175 {
5176 let prompt_builder = cx.prompt_builder.take();
5177 let Some(prompt_builder) = prompt_builder else {
5178 unreachable!("Re-entrant window prompting is not supported by GPUI");
5179 };
5180
5181 let answers = answers
5182 .iter()
5183 .map(|answer| answer.clone().into())
5184 .collect::<Vec<_>>();
5185
5186 let receiver = match &prompt_builder {
5187 PromptBuilder::Default => self
5188 .platform_window
5189 .prompt(level, message, detail, &answers)
5190 .unwrap_or_else(|| {
5191 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
5192 }),
5193 PromptBuilder::Custom(_) => {
5194 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
5195 }
5196 };
5197
5198 cx.prompt_builder = Some(prompt_builder);
5199
5200 receiver
5201 }
5202
5203 fn build_custom_prompt(
5204 &mut self,
5205 prompt_builder: &PromptBuilder,
5206 level: PromptLevel,
5207 message: &str,
5208 detail: Option<&str>,
5209 answers: &[PromptButton],
5210 cx: &mut App,
5211 ) -> oneshot::Receiver<usize> {
5212 let (sender, receiver) = oneshot::channel();
5213 let handle = PromptHandle::new(sender);
5214 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
5215 self.prompt = Some(handle);
5216 receiver
5217 }
5218
5219 pub fn context_stack(&self) -> Vec<KeyContext> {
5221 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5222 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5223 dispatch_tree
5224 .dispatch_path(node_id)
5225 .iter()
5226 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
5227 .collect()
5228 }
5229
5230 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
5232 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5233 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
5234 for action_type in cx.global_action_listeners.keys() {
5235 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
5236 let action = cx.actions.build_action_type(action_type).ok();
5237 if let Some(action) = action {
5238 actions.insert(ix, action);
5239 }
5240 }
5241 }
5242 actions
5243 }
5244
5245 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
5248 self.rendered_frame
5249 .dispatch_tree
5250 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
5251 }
5252
5253 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
5256 self.rendered_frame
5257 .dispatch_tree
5258 .highest_precedence_binding_for_action(
5259 action,
5260 &self.rendered_frame.dispatch_tree.context_stack,
5261 )
5262 }
5263
5264 pub fn bindings_for_action_in_context(
5266 &self,
5267 action: &dyn Action,
5268 context: KeyContext,
5269 ) -> Vec<KeyBinding> {
5270 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5271 dispatch_tree.bindings_for_action(action, &[context])
5272 }
5273
5274 pub fn highest_precedence_binding_for_action_in_context(
5277 &self,
5278 action: &dyn Action,
5279 context: KeyContext,
5280 ) -> Option<KeyBinding> {
5281 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5282 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
5283 }
5284
5285 pub fn bindings_for_action_in(
5289 &self,
5290 action: &dyn Action,
5291 focus_handle: &FocusHandle,
5292 ) -> Vec<KeyBinding> {
5293 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5294 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
5295 return vec![];
5296 };
5297 dispatch_tree.bindings_for_action(action, &context_stack)
5298 }
5299
5300 pub fn highest_precedence_binding_for_action_in(
5304 &self,
5305 action: &dyn Action,
5306 focus_handle: &FocusHandle,
5307 ) -> Option<KeyBinding> {
5308 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5309 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
5310 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
5311 }
5312
5313 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
5315 self.rendered_frame
5316 .dispatch_tree
5317 .possible_next_bindings_for_input(input, &self.context_stack())
5318 }
5319
5320 fn context_stack_for_focus_handle(
5321 &self,
5322 focus_handle: &FocusHandle,
5323 ) -> Option<Vec<KeyContext>> {
5324 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5325 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
5326 let context_stack: Vec<_> = dispatch_tree
5327 .dispatch_path(node_id)
5328 .into_iter()
5329 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
5330 .collect();
5331 Some(context_stack)
5332 }
5333
5334 pub fn listener_for<T: 'static, E>(
5336 &self,
5337 view: &Entity<T>,
5338 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
5339 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
5340 let view = view.downgrade();
5341 move |e: &E, window: &mut Window, cx: &mut App| {
5342 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
5343 }
5344 }
5345
5346 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
5348 &self,
5349 entity: &Entity<E>,
5350 f: Callback,
5351 ) -> impl Fn(&mut Window, &mut App) + 'static {
5352 let entity = entity.downgrade();
5353 move |window: &mut Window, cx: &mut App| {
5354 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
5355 }
5356 }
5357
5358 pub fn on_window_should_close(
5361 &self,
5362 cx: &App,
5363 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
5364 ) {
5365 let mut cx = self.to_async(cx);
5366 self.platform_window.on_should_close(Box::new(move || {
5367 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
5368 }))
5369 }
5370
5371 pub fn on_action(
5380 &mut self,
5381 action_type: TypeId,
5382 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5383 ) {
5384 self.invalidator.debug_assert_paint();
5385
5386 self.next_frame
5387 .dispatch_tree
5388 .on_action(action_type, Rc::new(listener));
5389 }
5390
5391 pub fn on_action_when(
5400 &mut self,
5401 condition: bool,
5402 action_type: TypeId,
5403 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5404 ) {
5405 self.invalidator.debug_assert_paint();
5406
5407 if condition {
5408 self.next_frame
5409 .dispatch_tree
5410 .on_action(action_type, Rc::new(listener));
5411 }
5412 }
5413
5414 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
5417 self.platform_window.gpu_specs()
5418 }
5419
5420 pub fn titlebar_double_click(&self) {
5423 self.platform_window.titlebar_double_click();
5424 }
5425
5426 pub fn window_title(&self) -> String {
5429 self.platform_window.get_title()
5430 }
5431
5432 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
5435 self.platform_window.tabbed_windows()
5436 }
5437
5438 pub fn tab_bar_visible(&self) -> bool {
5441 self.platform_window.tab_bar_visible()
5442 }
5443
5444 pub fn merge_all_windows(&self) {
5447 self.platform_window.merge_all_windows()
5448 }
5449
5450 pub fn move_tab_to_new_window(&self) {
5453 self.platform_window.move_tab_to_new_window()
5454 }
5455
5456 pub fn toggle_window_tab_overview(&self) {
5459 self.platform_window.toggle_window_tab_overview()
5460 }
5461
5462 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
5465 self.platform_window
5466 .set_tabbing_identifier(tabbing_identifier)
5467 }
5468
5469 pub fn play_system_bell(&self) {
5472 self.platform_window.play_system_bell()
5473 }
5474
5475 pub fn on_a11y_action(
5481 &mut self,
5482 node_id: accesskit::NodeId,
5483 action: accesskit::Action,
5484 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
5485 ) {
5486 self.a11y
5487 .action_listeners
5488 .entry(node_id)
5489 .or_default()
5490 .push((action, Box::new(listener)));
5491 }
5492
5493 #[cfg(not(target_family = "wasm"))]
5494 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
5495 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
5498 let extra_data = request.data.as_ref();
5499 let mut matched = false;
5500 for (action, listener) in &mut listeners {
5501 if *action == request.action {
5502 listener(extra_data, self, cx);
5503 matched = true;
5504 }
5505 }
5506 self.a11y
5507 .action_listeners
5508 .insert(request.target_node, listeners);
5509 if matched {
5510 return;
5511 }
5512 }
5513
5514 match request.action {
5516 accesskit::Action::Click => {
5517 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
5518 let center = bounds.center();
5519 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
5520 button: MouseButton::Left,
5521 position: center,
5522 modifiers: Modifiers::default(),
5523 click_count: 1,
5524 first_mouse: false,
5525 });
5526 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
5527 button: MouseButton::Left,
5528 position: center,
5529 modifiers: Modifiers::default(),
5530 click_count: 1,
5531 });
5532 self.dispatch_event(mouse_down, cx);
5533 self.dispatch_event(mouse_up, cx);
5534 }
5535 }
5536 accesskit::Action::Focus => {
5537 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
5538 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
5539 {
5540 self.focus(&handle, cx);
5541 }
5542 }
5543 accesskit::Action::Blur => {
5544 self.blur();
5545 }
5546 _ => {
5547 log::debug!(
5548 "Unhandled a11y action: {:?} on {:?}",
5549 request.action,
5550 request.target_node
5551 );
5552 }
5553 }
5554 }
5555
5556 #[cfg(any(feature = "inspector", debug_assertions))]
5558 pub fn toggle_inspector(&mut self, cx: &mut App) {
5559 self.inspector = match self.inspector {
5560 None => Some(cx.new(|_| Inspector::new())),
5561 Some(_) => None,
5562 };
5563 self.refresh();
5564 }
5565
5566 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
5568 #[cfg(any(feature = "inspector", debug_assertions))]
5569 {
5570 if let Some(inspector) = &self.inspector {
5571 return inspector.read(_cx).is_picking();
5572 }
5573 }
5574 false
5575 }
5576
5577 #[cfg(any(feature = "inspector", debug_assertions))]
5579 pub fn with_inspector_state<T: 'static, R>(
5580 &mut self,
5581 _inspector_id: Option<&crate::InspectorElementId>,
5582 cx: &mut App,
5583 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
5584 ) -> R {
5585 if let Some(inspector_id) = _inspector_id
5586 && let Some(inspector) = &self.inspector
5587 {
5588 let inspector = inspector.clone();
5589 let active_element_id = inspector.read(cx).active_element_id();
5590 if Some(inspector_id) == active_element_id {
5591 return inspector.update(cx, |inspector, _cx| {
5592 inspector.with_active_element_state(self, f)
5593 });
5594 }
5595 }
5596 f(&mut None, self)
5597 }
5598
5599 #[cfg(any(feature = "inspector", debug_assertions))]
5600 pub(crate) fn build_inspector_element_id(
5601 &mut self,
5602 path: crate::InspectorElementPath,
5603 ) -> crate::InspectorElementId {
5604 self.invalidator.debug_assert_paint_or_prepaint();
5605 let path = Rc::new(path);
5606 let next_instance_id = self
5607 .next_frame
5608 .next_inspector_instance_ids
5609 .entry(path.clone())
5610 .or_insert(0);
5611 let instance_id = *next_instance_id;
5612 *next_instance_id += 1;
5613 crate::InspectorElementId { path, instance_id }
5614 }
5615
5616 #[cfg(any(feature = "inspector", debug_assertions))]
5617 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
5618 if let Some(inspector) = self.inspector.take() {
5619 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
5620 inspector_element.prepaint_as_root(
5621 point(self.viewport_size.width - inspector_width, px(0.0)),
5622 size(inspector_width, self.viewport_size.height).into(),
5623 self,
5624 cx,
5625 );
5626 self.inspector = Some(inspector);
5627 Some(inspector_element)
5628 } else {
5629 None
5630 }
5631 }
5632
5633 #[cfg(any(feature = "inspector", debug_assertions))]
5634 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
5635 if let Some(mut inspector_element) = inspector_element {
5636 inspector_element.paint(self, cx);
5637 };
5638 }
5639
5640 #[cfg(any(feature = "inspector", debug_assertions))]
5643 pub fn insert_inspector_hitbox(
5644 &mut self,
5645 hitbox_id: HitboxId,
5646 inspector_id: Option<&crate::InspectorElementId>,
5647 cx: &App,
5648 ) {
5649 self.invalidator.debug_assert_paint_or_prepaint();
5650 if !self.is_inspector_picking(cx) {
5651 return;
5652 }
5653 if let Some(inspector_id) = inspector_id {
5654 self.next_frame
5655 .inspector_hitboxes
5656 .insert(hitbox_id, inspector_id.clone());
5657 }
5658 }
5659
5660 #[cfg(any(feature = "inspector", debug_assertions))]
5661 fn paint_inspector_hitbox(&mut self, cx: &App) {
5662 if let Some(inspector) = self.inspector.as_ref() {
5663 let inspector = inspector.read(cx);
5664 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
5665 && let Some(hitbox) = self
5666 .next_frame
5667 .hitboxes
5668 .iter()
5669 .find(|hitbox| hitbox.id == hitbox_id)
5670 {
5671 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
5672 }
5673 }
5674 }
5675
5676 #[cfg(any(feature = "inspector", debug_assertions))]
5677 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5678 let Some(inspector) = self.inspector.clone() else {
5679 return;
5680 };
5681 if event.downcast_ref::<MouseMoveEvent>().is_some() {
5682 inspector.update(cx, |inspector, _cx| {
5683 if let Some((_, inspector_id)) =
5684 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5685 {
5686 inspector.hover(inspector_id, self);
5687 }
5688 });
5689 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
5690 inspector.update(cx, |inspector, _cx| {
5691 if let Some((_, inspector_id)) =
5692 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5693 {
5694 inspector.select(inspector_id, self);
5695 }
5696 });
5697 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
5698 const SCROLL_LINES: f32 = 3.0;
5700 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
5701 let delta_y = event
5702 .delta
5703 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
5704 .y;
5705 if let Some(inspector) = self.inspector.clone() {
5706 inspector.update(cx, |inspector, _cx| {
5707 if let Some(depth) = inspector.pick_depth.as_mut() {
5708 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
5709 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
5710 if *depth < 0.0 {
5711 *depth = 0.0;
5712 } else if *depth > max_depth {
5713 *depth = max_depth;
5714 }
5715 if let Some((_, inspector_id)) =
5716 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5717 {
5718 inspector.set_active_element_id(inspector_id, self);
5719 }
5720 }
5721 });
5722 }
5723 }
5724 }
5725
5726 #[cfg(any(feature = "inspector", debug_assertions))]
5727 fn hovered_inspector_hitbox(
5728 &self,
5729 inspector: &Inspector,
5730 frame: &Frame,
5731 ) -> Option<(HitboxId, crate::InspectorElementId)> {
5732 if let Some(pick_depth) = inspector.pick_depth {
5733 let depth = (pick_depth as i64).try_into().unwrap_or(0);
5734 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
5735 let skip_count = (depth as usize).min(max_skipped);
5736 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
5737 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
5738 return Some((*hitbox_id, inspector_id.clone()));
5739 }
5740 }
5741 }
5742 None
5743 }
5744
5745 #[cfg(any(test, feature = "test-support"))]
5748 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
5749 self.modifiers = modifiers;
5750 }
5751
5752 #[cfg(any(test, feature = "test-support"))]
5756 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
5757 let event = PlatformInput::MouseMove(MouseMoveEvent {
5758 position,
5759 modifiers: self.modifiers,
5760 pressed_button: None,
5761 });
5762 let _ = self.dispatch_event(event, cx);
5763 }
5764}
5765
5766slotmap::new_key_type! {
5768 pub struct WindowId;
5770}
5771
5772impl WindowId {
5773 pub fn as_u64(&self) -> u64 {
5775 self.0.as_ffi()
5776 }
5777}
5778
5779impl From<u64> for WindowId {
5780 fn from(value: u64) -> Self {
5781 WindowId(slotmap::KeyData::from_ffi(value))
5782 }
5783}
5784
5785#[derive(Deref, DerefMut)]
5788pub struct WindowHandle<V> {
5789 #[deref]
5790 #[deref_mut]
5791 pub(crate) any_handle: AnyWindowHandle,
5792 state_type: PhantomData<fn(V) -> V>,
5793}
5794
5795impl<V> Debug for WindowHandle<V> {
5796 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5797 f.debug_struct("WindowHandle")
5798 .field("any_handle", &self.any_handle.id.as_u64())
5799 .finish()
5800 }
5801}
5802
5803impl<V: 'static + Render> WindowHandle<V> {
5804 pub fn new(id: WindowId) -> Self {
5807 WindowHandle {
5808 any_handle: AnyWindowHandle {
5809 id,
5810 state_type: TypeId::of::<V>(),
5811 },
5812 state_type: PhantomData,
5813 }
5814 }
5815
5816 #[cfg(any(test, feature = "test-support"))]
5820 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
5821 where
5822 C: AppContext,
5823 {
5824 cx.update_window(self.any_handle, |root_view, _, _| {
5825 root_view
5826 .downcast::<V>()
5827 .map_err(|_| anyhow!("the type of the window's root view has changed"))
5828 })?
5829 }
5830
5831 pub fn update<C, R>(
5835 &self,
5836 cx: &mut C,
5837 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
5838 ) -> Result<R>
5839 where
5840 C: AppContext,
5841 {
5842 cx.update_window(self.any_handle, |root_view, window, cx| {
5843 let view = root_view
5844 .downcast::<V>()
5845 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5846
5847 Ok(view.update(cx, |view, cx| update(view, window, cx)))
5848 })?
5849 }
5850
5851 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
5855 let x = cx
5856 .windows
5857 .get(self.id)
5858 .and_then(|window| {
5859 window
5860 .as_deref()
5861 .and_then(|window| window.root.clone())
5862 .map(|root_view| root_view.downcast::<V>())
5863 })
5864 .context("window not found")?
5865 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5866
5867 Ok(x.read(cx))
5868 }
5869
5870 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
5874 where
5875 C: AppContext,
5876 {
5877 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
5878 }
5879
5880 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
5884 where
5885 C: AppContext,
5886 {
5887 cx.read_window(self, |root_view, _cx| root_view)
5888 }
5889
5890 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
5895 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
5896 .ok()
5897 }
5898}
5899
5900impl<V> Copy for WindowHandle<V> {}
5901
5902impl<V> Clone for WindowHandle<V> {
5903 fn clone(&self) -> Self {
5904 *self
5905 }
5906}
5907
5908impl<V> PartialEq for WindowHandle<V> {
5909 fn eq(&self, other: &Self) -> bool {
5910 self.any_handle == other.any_handle
5911 }
5912}
5913
5914impl<V> Eq for WindowHandle<V> {}
5915
5916impl<V> Hash for WindowHandle<V> {
5917 fn hash<H: Hasher>(&self, state: &mut H) {
5918 self.any_handle.hash(state);
5919 }
5920}
5921
5922impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
5923 fn from(val: WindowHandle<V>) -> Self {
5924 val.any_handle
5925 }
5926}
5927
5928#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
5930pub struct AnyWindowHandle {
5931 pub(crate) id: WindowId,
5932 state_type: TypeId,
5933}
5934
5935impl AnyWindowHandle {
5936 pub fn window_id(&self) -> WindowId {
5938 self.id
5939 }
5940
5941 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
5944 if TypeId::of::<T>() == self.state_type {
5945 Some(WindowHandle {
5946 any_handle: *self,
5947 state_type: PhantomData,
5948 })
5949 } else {
5950 None
5951 }
5952 }
5953
5954 pub fn update<C, R>(
5958 self,
5959 cx: &mut C,
5960 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
5961 ) -> Result<R>
5962 where
5963 C: AppContext,
5964 {
5965 cx.update_window(self, update)
5966 }
5967
5968 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
5972 where
5973 C: AppContext,
5974 T: 'static,
5975 {
5976 let view = self
5977 .downcast::<T>()
5978 .context("the type of the window's root view has changed")?;
5979
5980 cx.read_window(&view, read)
5981 }
5982}
5983
5984impl HasWindowHandle for Window {
5985 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
5986 self.platform_window.window_handle()
5987 }
5988}
5989
5990impl HasDisplayHandle for Window {
5991 fn display_handle(
5992 &self,
5993 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
5994 self.platform_window.display_handle()
5995 }
5996}
5997
5998#[derive(Clone, Debug, Eq, PartialEq, Hash)]
6003pub enum ElementId {
6004 View(EntityId),
6006 Integer(u64),
6008 Name(SharedString),
6010 Uuid(Uuid),
6012 FocusHandle(FocusId),
6014 NamedInteger(SharedString, u64),
6016 Path(Arc<std::path::Path>),
6018 CodeLocation(core::panic::Location<'static>),
6020 NamedChild(Arc<ElementId>, SharedString),
6022 OpaqueId([u8; 20]),
6024}
6025
6026impl ElementId {
6027 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
6029 Self::NamedInteger(name.into(), integer as u64)
6030 }
6031}
6032
6033impl Display for ElementId {
6034 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6035 match self {
6036 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
6037 ElementId::Integer(ix) => write!(f, "{}", ix)?,
6038 ElementId::Name(name) => write!(f, "{}", name)?,
6039 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
6040 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
6041 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
6042 ElementId::Path(path) => write!(f, "{}", path.display())?,
6043 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
6044 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
6045 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
6046 }
6047
6048 Ok(())
6049 }
6050}
6051
6052impl TryInto<SharedString> for ElementId {
6053 type Error = anyhow::Error;
6054
6055 fn try_into(self) -> anyhow::Result<SharedString> {
6056 if let ElementId::Name(name) = self {
6057 Ok(name)
6058 } else {
6059 anyhow::bail!("element id is not string")
6060 }
6061 }
6062}
6063
6064impl From<usize> for ElementId {
6065 fn from(id: usize) -> Self {
6066 ElementId::Integer(id as u64)
6067 }
6068}
6069
6070impl From<i32> for ElementId {
6071 fn from(id: i32) -> Self {
6072 Self::Integer(id as u64)
6073 }
6074}
6075
6076impl From<SharedString> for ElementId {
6077 fn from(name: SharedString) -> Self {
6078 ElementId::Name(name)
6079 }
6080}
6081
6082impl From<String> for ElementId {
6083 fn from(name: String) -> Self {
6084 ElementId::Name(name.into())
6085 }
6086}
6087
6088impl From<Arc<str>> for ElementId {
6089 fn from(name: Arc<str>) -> Self {
6090 ElementId::Name(name.into())
6091 }
6092}
6093
6094impl From<Arc<std::path::Path>> for ElementId {
6095 fn from(path: Arc<std::path::Path>) -> Self {
6096 ElementId::Path(path)
6097 }
6098}
6099
6100impl From<&'static str> for ElementId {
6101 fn from(name: &'static str) -> Self {
6102 ElementId::Name(SharedString::new_static(name))
6103 }
6104}
6105
6106impl<'a> From<&'a FocusHandle> for ElementId {
6107 fn from(handle: &'a FocusHandle) -> Self {
6108 ElementId::FocusHandle(handle.id)
6109 }
6110}
6111
6112impl From<(&'static str, EntityId)> for ElementId {
6113 fn from((name, id): (&'static str, EntityId)) -> Self {
6114 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
6115 }
6116}
6117
6118impl From<(&'static str, usize)> for ElementId {
6119 fn from((name, id): (&'static str, usize)) -> Self {
6120 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
6121 }
6122}
6123
6124impl From<(SharedString, usize)> for ElementId {
6125 fn from((name, id): (SharedString, usize)) -> Self {
6126 ElementId::NamedInteger(name, id as u64)
6127 }
6128}
6129
6130impl From<(&'static str, u64)> for ElementId {
6131 fn from((name, id): (&'static str, u64)) -> Self {
6132 ElementId::NamedInteger(SharedString::new_static(name), id)
6133 }
6134}
6135
6136impl From<Uuid> for ElementId {
6137 fn from(value: Uuid) -> Self {
6138 Self::Uuid(value)
6139 }
6140}
6141
6142impl From<(&'static str, u32)> for ElementId {
6143 fn from((name, id): (&'static str, u32)) -> Self {
6144 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
6145 }
6146}
6147
6148impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
6149 fn from((id, name): (ElementId, T)) -> Self {
6150 ElementId::NamedChild(Arc::new(id), name.into())
6151 }
6152}
6153
6154impl From<&'static core::panic::Location<'static>> for ElementId {
6155 fn from(location: &'static core::panic::Location<'static>) -> Self {
6156 ElementId::CodeLocation(*location)
6157 }
6158}
6159
6160impl From<[u8; 20]> for ElementId {
6161 fn from(opaque_id: [u8; 20]) -> Self {
6162 ElementId::OpaqueId(opaque_id)
6163 }
6164}
6165
6166#[derive(Clone)]
6169pub struct PaintQuad {
6170 pub bounds: Bounds<Pixels>,
6172 pub corner_radii: Corners<Pixels>,
6174 pub background: Background,
6176 pub border_widths: Edges<Pixels>,
6178 pub border_color: Hsla,
6180 pub border_style: BorderStyle,
6182}
6183
6184impl PaintQuad {
6185 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
6187 PaintQuad {
6188 corner_radii: corner_radii.into(),
6189 ..self
6190 }
6191 }
6192
6193 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
6195 PaintQuad {
6196 border_widths: border_widths.into(),
6197 ..self
6198 }
6199 }
6200
6201 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
6203 PaintQuad {
6204 border_color: border_color.into(),
6205 ..self
6206 }
6207 }
6208
6209 pub fn background(self, background: impl Into<Background>) -> Self {
6211 PaintQuad {
6212 background: background.into(),
6213 ..self
6214 }
6215 }
6216}
6217
6218pub fn quad(
6220 bounds: Bounds<Pixels>,
6221 corner_radii: impl Into<Corners<Pixels>>,
6222 background: impl Into<Background>,
6223 border_widths: impl Into<Edges<Pixels>>,
6224 border_color: impl Into<Hsla>,
6225 border_style: BorderStyle,
6226) -> PaintQuad {
6227 PaintQuad {
6228 bounds,
6229 corner_radii: corner_radii.into(),
6230 background: background.into(),
6231 border_widths: border_widths.into(),
6232 border_color: border_color.into(),
6233 border_style,
6234 }
6235}
6236
6237pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
6239 PaintQuad {
6240 bounds: bounds.into(),
6241 corner_radii: (0.).into(),
6242 background: background.into(),
6243 border_widths: (0.).into(),
6244 border_color: transparent_black(),
6245 border_style: BorderStyle::default(),
6246 }
6247}
6248
6249pub fn outline(
6251 bounds: impl Into<Bounds<Pixels>>,
6252 border_color: impl Into<Hsla>,
6253 border_style: BorderStyle,
6254) -> PaintQuad {
6255 PaintQuad {
6256 bounds: bounds.into(),
6257 corner_radii: (0.).into(),
6258 background: transparent_black().into(),
6259 border_widths: (1.).into(),
6260 border_color: border_color.into(),
6261 border_style,
6262 }
6263}