1#[cfg(any(feature = "inspector", debug_assertions))]
2use crate::Inspector;
3use crate::{
4 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
5 AsyncWindowContext, AtlasTile, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow,
6 Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,
7 DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
8 EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
9 Hsla, InputHandler, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke,
10 KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite,
11 MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas,
12 PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite,
13 Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage,
14 RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
15 SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,
16 StrikethroughStyle, Style, SubpixelSprite, SubscriberSet, Subscription, SystemWindowTab,
17 SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextRenderingMode, TextStyle,
18 TextStyleRefinement, ThermalState, TransformationMatrix, Underline, UnderlineStyle,
19 WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations,
20 WindowOptions, WindowParams, WindowTextSystem, point, prelude::*, profiler, px, rems, size,
21 transparent_black,
22};
23
24use anyhow::{Context as _, Result, anyhow};
25use collections::{FxHashMap, FxHashSet};
26#[cfg(target_os = "macos")]
27use core_video::pixel_buffer::CVPixelBuffer;
28use derive_more::{Deref, DerefMut};
29use futures::FutureExt;
30use futures::channel::oneshot;
31use gpui_util::post_inc;
32use gpui_util::{ResultExt, measure};
33#[cfg(feature = "input-latency-histogram")]
34use hdrhistogram::Histogram;
35use itertools::FoldWhile::{Continue, Done};
36use itertools::Itertools;
37use parking_lot::RwLock;
38use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
39use refineable::Refineable;
40use scheduler::Instant;
41use slotmap::SlotMap;
42use smallvec::SmallVec;
43use std::{
44 any::{Any, TypeId},
45 borrow::Cow,
46 cell::{Cell, RefCell},
47 cmp,
48 fmt::{Debug, Display},
49 hash::{Hash, Hasher},
50 marker::PhantomData,
51 mem,
52 ops::{DerefMut, Range},
53 rc::Rc,
54 sync::{
55 Arc, Weak,
56 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
57 },
58 time::Duration,
59};
60use uuid::Uuid;
61
62pub(crate) mod a11y;
63mod prompts;
64
65pub use a11y::A11ySubtreeBuilder;
66
67use self::a11y::A11y;
68#[cfg(not(target_family = "wasm"))]
69use self::a11y::ROOT_NODE_ID;
70use crate::util::{
71 atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
72 round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
73};
74pub use prompts::*;
75
76pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
78
79pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
82 width: Pixels(900.),
83 height: Pixels(750.),
84};
85
86#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
88pub enum DispatchPhase {
89 #[default]
94 Bubble,
95 Capture,
101}
102
103impl DispatchPhase {
104 #[inline]
106 pub fn bubble(self) -> bool {
107 self == DispatchPhase::Bubble
108 }
109
110 #[inline]
112 pub fn capture(self) -> bool {
113 self == DispatchPhase::Capture
114 }
115}
116
117struct WindowInvalidatorInner {
118 pub dirty: bool,
119 pub draw_phase: DrawPhase,
120 pub dirty_views: FxHashSet<EntityId>,
121 pub update_count: usize,
122 pub frame_dirty: FrameDirtyAccumulator,
123}
124
125#[derive(Default)]
130struct FrameDirtyAccumulator {
131 dirty_at: Option<Instant>,
132 invalidations: u64,
133}
134
135#[derive(Clone)]
136pub(crate) struct WindowInvalidator {
137 inner: Rc<RefCell<WindowInvalidatorInner>>,
138}
139
140impl WindowInvalidator {
141 pub fn new() -> Self {
142 WindowInvalidator {
143 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
144 dirty: true,
145 draw_phase: DrawPhase::None,
146 dirty_views: FxHashSet::default(),
147 update_count: 0,
148 frame_dirty: FrameDirtyAccumulator::default(),
149 })),
150 }
151 }
152
153 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
154 let mut inner = self.inner.borrow_mut();
155 inner.update_count += 1;
156 inner.dirty_views.insert(entity);
157 if inner.draw_phase == DrawPhase::None {
158 Self::record_frame_dirty(&mut inner);
159 inner.dirty = true;
160 cx.push_effect(Effect::Notify { emitter: entity });
161 true
162 } else {
163 false
164 }
165 }
166
167 pub fn is_dirty(&self) -> bool {
168 self.inner.borrow().dirty
169 }
170
171 pub fn set_dirty(&self, dirty: bool) {
172 let mut inner = self.inner.borrow_mut();
173 inner.dirty = dirty;
174 if dirty {
175 inner.update_count += 1;
176 Self::record_frame_dirty(&mut inner);
177 }
178 }
179
180 pub fn set_phase(&self, phase: DrawPhase) {
181 self.inner.borrow_mut().draw_phase = phase
182 }
183
184 pub fn update_count(&self) -> usize {
185 self.inner.borrow().update_count
186 }
187
188 fn record_frame_dirty(inner: &mut WindowInvalidatorInner) {
189 if profiler::frame_trace_enabled() {
190 inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
191 inner.frame_dirty.invalidations += 1;
192 }
193 }
194
195 fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
196 mem::take(&mut self.inner.borrow_mut().frame_dirty)
197 }
198
199 pub fn take_views(&self) -> FxHashSet<EntityId> {
200 mem::take(&mut self.inner.borrow_mut().dirty_views)
201 }
202
203 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
204 self.inner.borrow_mut().dirty_views = views;
205 }
206
207 pub fn not_drawing(&self) -> bool {
208 self.inner.borrow().draw_phase == DrawPhase::None
209 }
210
211 #[track_caller]
212 pub fn debug_assert_paint(&self) {
213 debug_assert!(
214 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
215 "this method can only be called during paint"
216 );
217 }
218
219 #[track_caller]
220 pub fn debug_assert_prepaint(&self) {
221 debug_assert!(
222 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
223 "this method can only be called during request_layout, or prepaint"
224 );
225 }
226
227 #[track_caller]
228 pub fn debug_assert_paint_or_prepaint(&self) {
229 debug_assert!(
230 matches!(
231 self.inner.borrow().draw_phase,
232 DrawPhase::Paint | DrawPhase::Prepaint
233 ),
234 "this method can only be called during request_layout, prepaint, or paint"
235 );
236 }
237}
238
239type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
240
241pub(crate) type AnyWindowFocusListener =
242 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
243
244pub(crate) struct WindowFocusEvent {
245 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
246 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
247}
248
249impl WindowFocusEvent {
250 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
251 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
252 }
253
254 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
255 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
256 }
257}
258
259pub struct FocusOutEvent {
261 pub blurred: WeakFocusHandle,
263}
264
265slotmap::new_key_type! {
266 pub struct FocusId;
268}
269
270thread_local! {
271 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
274
275 static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
279}
280
281fn draw_in_progress() -> bool {
292 CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some())
293}
294
295pub(crate) fn with_element_arena<R>(f: impl FnOnce(&mut Arena) -> R) -> R {
298 CURRENT_ELEMENT_ARENA.with(|current| {
299 if let Some(arena_ptr) = current.get() {
300 let arena_cell = unsafe { &*arena_ptr };
303 f(&mut arena_cell.borrow_mut())
304 } else {
305 ELEMENT_ARENA.with_borrow_mut(f)
306 }
307 })
308}
309
310pub(crate) struct ElementArenaScope {
325 entered: *const RefCell<Arena>,
328 previous: Option<*const RefCell<Arena>>,
329 exited: bool,
330}
331
332impl ElementArenaScope {
333 pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
335 arena.borrow_mut().begin_scope();
336 let previous = CURRENT_ELEMENT_ARENA.with(|current| {
337 let prev = current.get();
338 current.set(Some(arena as *const RefCell<Arena>));
339 prev
340 });
341 Self {
342 entered: arena as *const RefCell<Arena>,
343 previous,
344 exited: false,
345 }
346 }
347
348 pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
357 assert!(
358 std::ptr::eq(self.entered, arena),
359 "ElementArenaScope::exit called with a different arena than was entered"
360 );
361 self.exited = true;
362 ArenaClearNeeded::new(arena)
367 }
368}
369
370impl Drop for ElementArenaScope {
371 fn drop(&mut self) {
372 CURRENT_ELEMENT_ARENA.with(|current| {
379 current.set(self.previous);
380 });
381 unsafe { &*self.entered }.borrow_mut().end_scope();
385 if !self.exited && !std::thread::panicking() {
386 debug_assert!(false, "ElementArenaScope dropped without calling exit()");
387 log::error!(
388 "ElementArenaScope dropped without calling exit(); \
389 the arena clear for this draw was never requested"
390 );
391 }
392 }
393}
394
395#[must_use]
397pub struct ArenaClearNeeded {
398 arena: *const RefCell<Arena>,
401}
402
403impl ArenaClearNeeded {
404 fn new(arena: &RefCell<Arena>) -> Self {
407 Self {
408 arena: arena as *const RefCell<Arena>,
409 }
410 }
411
412 pub fn clear(self, cx: &mut App) {
421 assert!(
422 std::ptr::eq(self.arena, &*cx.element_arena),
423 "ArenaClearNeeded::clear called with a different App than the draw ran against"
424 );
425 RefCell::borrow_mut(&cx.element_arena).clear();
426 }
427}
428
429pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;
430pub(crate) struct FocusRef {
431 pub(crate) ref_count: AtomicUsize,
432 pub(crate) tab_index: isize,
433 pub(crate) tab_stop: bool,
434}
435
436impl FocusId {
437 pub fn is_focused(&self, window: &Window) -> bool {
439 window.focus == Some(*self)
440 }
441
442 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
445 window
446 .focused(cx)
447 .is_some_and(|focused| self.contains(focused.id, window))
448 }
449
450 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
453 let focused = window.focused(cx);
454 focused.is_some_and(|focused| focused.id.contains(*self, window))
455 }
456
457 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
459 window
460 .rendered_frame
461 .dispatch_tree
462 .focus_contains(*self, other)
463 }
464}
465
466pub struct FocusHandle {
468 pub(crate) id: FocusId,
469 handles: Arc<FocusMap>,
470 pub tab_index: isize,
472 pub tab_stop: bool,
474}
475
476impl std::fmt::Debug for FocusHandle {
477 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
478 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
479 }
480}
481
482impl FocusHandle {
483 pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
484 let id = handles.write().insert(FocusRef {
485 ref_count: AtomicUsize::new(1),
486 tab_index: 0,
487 tab_stop: false,
488 });
489
490 Self {
491 id,
492 tab_index: 0,
493 tab_stop: false,
494 handles: handles.clone(),
495 }
496 }
497
498 pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
499 let lock = handles.read();
500 let focus = lock.get(id)?;
501 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
502 return None;
503 }
504 Some(Self {
505 id,
506 tab_index: focus.tab_index,
507 tab_stop: focus.tab_stop,
508 handles: handles.clone(),
509 })
510 }
511
512 pub fn tab_index(mut self, index: isize) -> Self {
514 self.tab_index = index;
515 if let Some(focus) = self.handles.write().get_mut(self.id) {
516 focus.tab_index = index;
517 }
518 self
519 }
520
521 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
525 self.tab_stop = tab_stop;
526 if let Some(focus) = self.handles.write().get_mut(self.id) {
527 focus.tab_stop = tab_stop;
528 }
529 self
530 }
531
532 pub fn downgrade(&self) -> WeakFocusHandle {
534 WeakFocusHandle {
535 id: self.id,
536 handles: Arc::downgrade(&self.handles),
537 }
538 }
539
540 pub fn focus(&self, window: &mut Window, cx: &mut App) {
542 window.focus(self, cx)
543 }
544
545 pub fn is_focused(&self, window: &Window) -> bool {
547 self.id.is_focused(window)
548 }
549
550 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
553 self.id.contains_focused(window, cx)
554 }
555
556 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
559 self.id.within_focused(window, cx)
560 }
561
562 pub fn contains(&self, other: &Self, window: &Window) -> bool {
564 self.id.contains(other.id, window)
565 }
566
567 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
569 if let Some(node_id) = window
570 .rendered_frame
571 .dispatch_tree
572 .focusable_node_id(self.id)
573 {
574 window.dispatch_action_on_node(node_id, action, cx)
575 }
576 }
577}
578
579impl Clone for FocusHandle {
580 fn clone(&self) -> Self {
581 Self::for_id(self.id, &self.handles).unwrap()
582 }
583}
584
585impl PartialEq for FocusHandle {
586 fn eq(&self, other: &Self) -> bool {
587 self.id == other.id
588 }
589}
590
591impl Eq for FocusHandle {}
592
593impl Drop for FocusHandle {
594 fn drop(&mut self) {
595 self.handles
596 .read()
597 .get(self.id)
598 .unwrap()
599 .ref_count
600 .fetch_sub(1, SeqCst);
601 }
602}
603
604#[derive(Clone, Debug)]
606pub struct WeakFocusHandle {
607 pub(crate) id: FocusId,
608 pub(crate) handles: Weak<FocusMap>,
609}
610
611impl WeakFocusHandle {
612 pub fn upgrade(&self) -> Option<FocusHandle> {
614 let handles = self.handles.upgrade()?;
615 FocusHandle::for_id(self.id, &handles)
616 }
617}
618
619impl PartialEq for WeakFocusHandle {
620 fn eq(&self, other: &WeakFocusHandle) -> bool {
621 self.id == other.id
622 }
623}
624
625impl Eq for WeakFocusHandle {}
626
627impl PartialEq<FocusHandle> for WeakFocusHandle {
628 fn eq(&self, other: &FocusHandle) -> bool {
629 self.id == other.id
630 }
631}
632
633impl PartialEq<WeakFocusHandle> for FocusHandle {
634 fn eq(&self, other: &WeakFocusHandle) -> bool {
635 self.id == other.id
636 }
637}
638
639pub trait Focusable: 'static {
642 fn focus_handle(&self, cx: &App) -> FocusHandle;
644}
645
646impl<V: Focusable> Focusable for Entity<V> {
647 fn focus_handle(&self, cx: &App) -> FocusHandle {
648 self.read(cx).focus_handle(cx)
649 }
650}
651
652pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
655
656impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
657
658pub struct DismissEvent;
660
661type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
662
663pub(crate) type AnyMouseListener =
664 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
665
666#[derive(Clone)]
667pub(crate) struct CursorStyleRequest {
668 pub(crate) hitbox_id: Option<HitboxId>,
669 pub(crate) style: CursorStyle,
670}
671
672#[derive(Default, Eq, PartialEq)]
673pub(crate) struct HitTest {
674 pub(crate) ids: SmallVec<[HitboxId; 8]>,
675 pub(crate) hover_hitbox_count: usize,
676}
677
678#[derive(Clone, Copy, Debug, Eq, PartialEq)]
680pub enum WindowControlArea {
681 Drag,
683 Close,
685 Max,
687 Min,
689}
690
691#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
693pub struct HitboxId(u64);
694
695#[cfg(feature = "test-support")]
696impl HitboxId {
697 pub const fn placeholder() -> Self {
702 Self(0)
703 }
704}
705
706impl HitboxId {
707 pub fn is_hovered(self, window: &Window) -> bool {
714 if window.captured_hitbox == Some(self) {
716 return true;
717 }
718 if window.last_input_was_keyboard() {
719 return false;
720 }
721 self.hit_test(window)
722 }
723
724 pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
729 if window.captured_hitbox == Some(self) {
731 return true;
732 }
733 self.hit_test(window)
734 }
735
736 fn hit_test(self, window: &Window) -> bool {
737 let hit_test = &window.mouse_hit_test;
738 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
739 if self == *id {
740 return true;
741 }
742 }
743 false
744 }
745
746 pub fn should_handle_scroll(self, window: &Window) -> bool {
751 window.mouse_hit_test.ids.contains(&self)
752 }
753
754 fn next(mut self) -> HitboxId {
755 HitboxId(self.0.wrapping_add(1))
756 }
757}
758
759#[derive(Clone, Debug, Deref)]
762pub struct Hitbox {
763 pub id: HitboxId,
765 #[deref]
767 pub bounds: Bounds<Pixels>,
768 pub content_mask: ContentMask<Pixels>,
770 pub behavior: HitboxBehavior,
772}
773
774impl Hitbox {
775 pub fn is_hovered(&self, window: &Window) -> bool {
792 self.id.is_hovered(window)
793 }
794
795 pub fn should_handle_scroll(&self, window: &Window) -> bool {
802 self.id.should_handle_scroll(window)
803 }
804}
805
806#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
808pub enum HitboxBehavior {
809 #[default]
811 Normal,
812
813 BlockMouse,
835
836 BlockMouseExceptScroll,
863}
864
865#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
867pub struct TooltipId(usize);
868
869impl TooltipId {
870 pub fn is_hovered(&self, window: &Window) -> bool {
872 window
873 .tooltip_bounds
874 .as_ref()
875 .is_some_and(|tooltip_bounds| {
876 tooltip_bounds.id == *self
877 && tooltip_bounds.bounds.contains(&window.mouse_position())
878 })
879 }
880}
881
882pub(crate) struct TooltipBounds {
883 id: TooltipId,
884 bounds: Bounds<Pixels>,
885}
886
887#[derive(Clone)]
888pub(crate) struct TooltipRequest {
889 id: TooltipId,
890 tooltip: AnyTooltip,
891}
892
893pub(crate) struct DeferredDraw {
894 current_view: EntityId,
895 priority: usize,
896 parent_node: DispatchNodeId,
897 element_id_stack: SmallVec<[ElementId; 32]>,
898 text_style_stack: Vec<TextStyleRefinement>,
899 content_mask: Option<ContentMask<Pixels>>,
900 rem_size: Pixels,
901 element: Option<AnyElement>,
902 absolute_offset: Point<Pixels>,
903 prepaint_range: Range<PrepaintStateIndex>,
904 paint_range: Range<PaintIndex>,
905}
906
907pub(crate) struct Frame {
908 pub(crate) focus: Option<FocusId>,
909 pub(crate) window_active: bool,
910 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
911 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
912 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
913 pub(crate) dispatch_tree: DispatchTree,
914 pub(crate) scene: Scene,
915 pub(crate) hitboxes: Vec<Hitbox>,
916 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
917 pub(crate) deferred_draws: Vec<DeferredDraw>,
918 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
919 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
920 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
921 #[cfg(any(test, feature = "test-support"))]
922 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
923 #[cfg(any(test, feature = "test-support"))]
924 debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
925 #[cfg(any(feature = "inspector", debug_assertions))]
926 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
927 #[cfg(any(feature = "inspector", debug_assertions))]
928 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
929 pub(crate) tab_stops: TabStopMap,
930}
931
932#[derive(Clone, Default)]
933pub(crate) struct PrepaintStateIndex {
934 hitboxes_index: usize,
935 tooltips_index: usize,
936 deferred_draws_index: usize,
937 dispatch_tree_index: usize,
938 accessed_element_states_index: usize,
939 line_layout_index: LineLayoutIndex,
940}
941
942#[derive(Clone, Default)]
943pub(crate) struct PaintIndex {
944 scene_index: usize,
945 #[cfg(any(test, feature = "test-support"))]
946 debug_bounds_index: usize,
947 mouse_listeners_index: usize,
948 input_handlers_index: usize,
949 cursor_styles_index: usize,
950 accessed_element_states_index: usize,
951 tab_handle_index: usize,
952 line_layout_index: LineLayoutIndex,
953}
954
955impl Frame {
956 #[cfg(any(test, feature = "test-support"))]
957 pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) {
958 self.debug_bounds.insert(selector.clone(), bounds);
959 self.debug_bounds_records.push((selector, bounds));
960 }
961
962 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
963 Frame {
964 focus: None,
965 window_active: false,
966 element_states: FxHashMap::default(),
967 accessed_element_states: Vec::new(),
968 mouse_listeners: Vec::new(),
969 dispatch_tree,
970 scene: Scene::default(),
971 hitboxes: Vec::new(),
972 window_control_hitboxes: Vec::new(),
973 deferred_draws: Vec::new(),
974 input_handlers: Vec::new(),
975 tooltip_requests: Vec::new(),
976 cursor_styles: Vec::new(),
977
978 #[cfg(any(test, feature = "test-support"))]
979 debug_bounds: FxHashMap::default(),
980 #[cfg(any(test, feature = "test-support"))]
981 debug_bounds_records: Vec::new(),
982
983 #[cfg(any(feature = "inspector", debug_assertions))]
984 next_inspector_instance_ids: FxHashMap::default(),
985
986 #[cfg(any(feature = "inspector", debug_assertions))]
987 inspector_hitboxes: FxHashMap::default(),
988 tab_stops: TabStopMap::default(),
989 }
990 }
991
992 pub(crate) fn clear(&mut self) {
993 self.element_states.clear();
994 self.accessed_element_states.clear();
995 self.mouse_listeners.clear();
996 self.dispatch_tree.clear();
997 self.scene.clear();
998 self.input_handlers.clear();
999 self.tooltip_requests.clear();
1000 self.cursor_styles.clear();
1001 self.hitboxes.clear();
1002 self.window_control_hitboxes.clear();
1003 self.deferred_draws.clear();
1004 self.tab_stops.clear();
1005 self.focus = None;
1006
1007 #[cfg(any(test, feature = "test-support"))]
1008 {
1009 self.debug_bounds.clear();
1010 self.debug_bounds_records.clear();
1011 }
1012
1013 #[cfg(any(feature = "inspector", debug_assertions))]
1014 {
1015 self.next_inspector_instance_ids.clear();
1016 self.inspector_hitboxes.clear();
1017 }
1018 }
1019
1020 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1021 self.cursor_styles
1022 .iter()
1023 .rev()
1024 .fold_while(None, |style, request| match request.hitbox_id {
1025 None => Done(Some(request.style)),
1026 Some(hitbox_id) => Continue(style.or_else(|| {
1027 hitbox_id
1028 .is_hovered_ignoring_last_input(window)
1029 .then_some(request.style)
1030 })),
1031 })
1032 .into_inner()
1033 }
1034
1035 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
1036 let mut set_hover_hitbox_count = false;
1037 let mut hit_test = HitTest::default();
1038 for hitbox in self.hitboxes.iter().rev() {
1039 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
1040 if bounds.contains(&position) {
1041 hit_test.ids.push(hitbox.id);
1042 if !set_hover_hitbox_count
1043 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1044 {
1045 hit_test.hover_hitbox_count = hit_test.ids.len();
1046 set_hover_hitbox_count = true;
1047 }
1048 if hitbox.behavior == HitboxBehavior::BlockMouse {
1049 break;
1050 }
1051 }
1052 }
1053 if !set_hover_hitbox_count {
1054 hit_test.hover_hitbox_count = hit_test.ids.len();
1055 }
1056 hit_test
1057 }
1058
1059 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1060 self.focus
1061 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1062 .unwrap_or_default()
1063 }
1064
1065 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1066 for element_state_key in &self.accessed_element_states {
1067 if let Some((element_state_key, element_state)) =
1068 prev_frame.element_states.remove_entry(element_state_key)
1069 {
1070 self.element_states.insert(element_state_key, element_state);
1071 }
1072 }
1073
1074 self.scene.finish();
1075 }
1076}
1077
1078#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1079enum InputModality {
1080 Mouse,
1081 Keyboard,
1082 Touch,
1083}
1084
1085pub struct Window {
1087 pub(crate) handle: AnyWindowHandle,
1088 pub(crate) invalidator: WindowInvalidator,
1089 pub(crate) removed: bool,
1090 pub(crate) platform_window: Box<dyn PlatformWindow>,
1091 display_id: Option<DisplayId>,
1092 is_resizable: bool,
1093 is_minimizable: bool,
1094 sprite_atlas: Arc<dyn PlatformAtlas>,
1095 text_system: Arc<WindowTextSystem>,
1096 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1097 rem_size: Pixels,
1098 rem_size_override_stack: SmallVec<[Pixels; 8]>,
1103 pub(crate) viewport_size: Size<Pixels>,
1104 layout_engine: Option<TaffyLayoutEngine>,
1105 pub(crate) root: Option<AnyView>,
1106 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
1107 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1108 pub(crate) rendered_entity_stack: Vec<EntityId>,
1109 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1110 pub(crate) element_opacity: f32,
1111 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1112 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1113 pub(crate) image_cache_stack: Vec<AnyImageCache>,
1114 pub(crate) rendered_frame: Frame,
1115 pub(crate) next_frame: Frame,
1116 next_hitbox_id: HitboxId,
1117 pub(crate) next_tooltip_id: TooltipId,
1118 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1119 next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1120 pub(crate) dirty_views: FxHashSet<EntityId>,
1121 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
1122 pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
1123 default_prevented: bool,
1124 mouse_position: Point<Pixels>,
1125 mouse_hit_test: HitTest,
1126 modifiers: Modifiers,
1127 capslock: Capslock,
1128 scale_factor: f32,
1129 pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
1130 appearance: WindowAppearance,
1131 pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
1132 pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>,
1133 active: Rc<Cell<bool>>,
1134 hovered: Rc<Cell<bool>>,
1135 pub(crate) needs_present: Rc<Cell<bool>>,
1136 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1139 #[cfg(feature = "input-latency-histogram")]
1140 input_latency_tracker: InputLatencyTracker,
1141 last_input_modality: InputModality,
1142 pub(crate) refreshing: bool,
1143 pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
1144 pub(crate) focus: Option<FocusId>,
1145 focus_enabled: bool,
1146 pub(crate) focus_generation: u64,
1149 pending_input: Option<PendingInput>,
1150 pending_modifier: ModifierState,
1151 pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
1152 prompt: Option<RenderablePromptHandle>,
1153 pub(crate) client_inset: Option<Pixels>,
1154 captured_hitbox: Option<HitboxId>,
1157 #[cfg(any(feature = "inspector", debug_assertions))]
1158 inspector: Option<Entity<Inspector>>,
1159 pub(crate) a11y: A11y,
1160}
1161
1162#[derive(Clone, Debug, Default)]
1163struct ModifierState {
1164 modifiers: Modifiers,
1165 saw_other_input: bool,
1166}
1167
1168#[derive(Clone, Debug)]
1171pub(crate) struct InputRateTracker {
1172 timestamps: Vec<Instant>,
1173 window: Duration,
1174 inputs_per_second: u32,
1175 sustain_until: Instant,
1176 sustain_duration: Duration,
1177}
1178
1179impl Default for InputRateTracker {
1180 fn default() -> Self {
1181 Self {
1182 timestamps: Vec::new(),
1183 window: Duration::from_millis(100),
1184 inputs_per_second: 60,
1185 sustain_until: Instant::now(),
1186 sustain_duration: Duration::from_secs(1),
1187 }
1188 }
1189}
1190
1191impl InputRateTracker {
1192 pub fn record_input(&mut self) {
1193 let now = Instant::now();
1194 self.timestamps.push(now);
1195 self.prune_old_timestamps(now);
1196
1197 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1198 if self.timestamps.len() as u128 >= min_events {
1199 self.sustain_until = now + self.sustain_duration;
1200 }
1201 }
1202
1203 pub fn is_high_rate(&self) -> bool {
1204 Instant::now() < self.sustain_until
1205 }
1206
1207 fn prune_old_timestamps(&mut self, now: Instant) {
1208 self.timestamps
1209 .retain(|&t| now.duration_since(t) <= self.window);
1210 }
1211}
1212
1213#[cfg(feature = "input-latency-histogram")]
1216#[derive(Clone)]
1217pub struct InputLatencySnapshot {
1218 pub latency_histogram: Histogram<u64>,
1220 pub events_per_frame_histogram: Histogram<u64>,
1222 pub mid_draw_events_dropped: u64,
1225}
1226
1227#[cfg(feature = "input-latency-histogram")]
1231struct InputLatencyTracker {
1232 first_input_at: Option<Instant>,
1235 pending_input_count: u64,
1237 latency_histogram: Histogram<u64>,
1239 events_per_frame_histogram: Histogram<u64>,
1241 mid_draw_events_dropped: u64,
1244}
1245
1246#[cfg(feature = "input-latency-histogram")]
1247impl InputLatencyTracker {
1248 fn new() -> Result<Self> {
1249 Ok(Self {
1250 first_input_at: None,
1251 pending_input_count: 0,
1252 latency_histogram: Histogram::new(3)
1253 .map_err(|e| anyhow!("Failed to create input latency histogram: {e}"))?,
1254 events_per_frame_histogram: Histogram::new(3)
1255 .map_err(|e| anyhow!("Failed to create events per frame histogram: {e}"))?,
1256 mid_draw_events_dropped: 0,
1257 })
1258 }
1259
1260 fn record_input(&mut self, dispatch_time: Instant) {
1263 self.first_input_at.get_or_insert(dispatch_time);
1264 self.pending_input_count += 1;
1265 }
1266
1267 fn record_mid_draw_input(&mut self) {
1270 self.mid_draw_events_dropped += 1;
1271 }
1272
1273 fn record_frame_presented(&mut self) {
1275 if let Some(first_input_at) = self.first_input_at.take() {
1276 let latency_nanos = first_input_at.elapsed().as_nanos() as u64;
1277 self.latency_histogram.record(latency_nanos).ok();
1278 }
1279 if self.pending_input_count > 0 {
1280 self.events_per_frame_histogram
1281 .record(self.pending_input_count)
1282 .ok();
1283 self.pending_input_count = 0;
1284 }
1285 }
1286
1287 fn snapshot(&self) -> InputLatencySnapshot {
1288 InputLatencySnapshot {
1289 latency_histogram: self.latency_histogram.clone(),
1290 events_per_frame_histogram: self.events_per_frame_histogram.clone(),
1291 mid_draw_events_dropped: self.mid_draw_events_dropped,
1292 }
1293 }
1294}
1295
1296#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1297pub(crate) enum DrawPhase {
1298 None,
1299 Prepaint,
1300 Paint,
1301 Focus,
1302}
1303
1304#[derive(Default, Debug)]
1305struct PendingInput {
1306 keystrokes: SmallVec<[Keystroke; 1]>,
1307 focus: Option<FocusId>,
1308 timer: Option<Task<()>>,
1309 needs_timeout: bool,
1310 generation: Rc<()>,
1311}
1312
1313pub(crate) struct ElementStateBox {
1314 pub(crate) inner: Box<dyn Any>,
1315 #[cfg(debug_assertions)]
1316 pub(crate) type_name: &'static str,
1317}
1318
1319fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1320 let active_window_bounds = cx
1325 .active_window()
1326 .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1327
1328 const CASCADE_OFFSET: f32 = 25.0;
1329
1330 let display = display_id
1331 .map(|id| cx.find_display(id))
1332 .unwrap_or_else(|| cx.primary_display());
1333
1334 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1335
1336 let display_bounds = display
1338 .as_ref()
1339 .map(|d| d.visible_bounds())
1340 .unwrap_or_else(default_placement);
1341
1342 let (
1343 Bounds {
1344 origin: base_origin,
1345 size: base_size,
1346 },
1347 window_bounds_ctor,
1348 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1349 Some(bounds) => match bounds {
1350 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1351 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1352 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1353 },
1354 None => (
1355 display
1356 .as_ref()
1357 .map(|d| d.default_bounds())
1358 .unwrap_or_else(default_placement),
1359 WindowBounds::Windowed,
1360 ),
1361 };
1362
1363 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1364 let proposed_origin = base_origin + cascade_offset;
1365 let proposed_bounds = Bounds::new(proposed_origin, base_size);
1366
1367 let display_right = display_bounds.origin.x + display_bounds.size.width;
1368 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1369 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1370 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1371
1372 let fits_horizontally = window_right <= display_right;
1373 let fits_vertically = window_bottom <= display_bottom;
1374
1375 let final_origin = match (fits_horizontally, fits_vertically) {
1376 (true, true) => proposed_origin,
1377 (false, true) => point(display_bounds.origin.x, base_origin.y),
1378 (true, false) => point(base_origin.x, display_bounds.origin.y),
1379 (false, false) => display_bounds.origin,
1380 };
1381 window_bounds_ctor(Bounds::new(final_origin, base_size))
1382}
1383
1384impl Window {
1385 pub(crate) fn new(
1386 handle: AnyWindowHandle,
1387 options: WindowOptions,
1388 cx: &mut App,
1389 ) -> Result<Self> {
1390 let WindowOptions {
1391 window_bounds,
1392 titlebar,
1393 focus,
1394 show,
1395 kind,
1396 is_movable,
1397 app_owns_titlebar_drag,
1398 is_resizable,
1399 is_minimizable,
1400 display_id,
1401 window_background,
1402 app_id,
1403 window_min_size,
1404 window_decorations,
1405 #[cfg_attr(
1406 not(any(target_os = "linux", target_os = "freebsd")),
1407 allow(unused_variables)
1408 )]
1409 icon,
1410 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1411 tabbing_identifier,
1412 } = options;
1413
1414 let initial_window_title = titlebar
1415 .as_ref()
1416 .and_then(|titlebar| titlebar.title.clone());
1417
1418 let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1419 let mut platform_window = cx.platform.open_window(
1420 handle,
1421 WindowParams {
1422 bounds: window_bounds.get_bounds(),
1423 titlebar,
1424 kind,
1425 is_movable,
1426 app_owns_titlebar_drag,
1427 is_resizable,
1428 is_minimizable,
1429 focus,
1430 show,
1431 display_id,
1432 window_min_size,
1433 app_id: app_id.clone(),
1434 icon,
1435 #[cfg(target_os = "macos")]
1436 tabbing_identifier,
1437 },
1438 )?;
1439
1440 let tab_bar_visible = platform_window.tab_bar_visible();
1441 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1442 if let Some(tabs) = platform_window.tabbed_windows() {
1443 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1444 }
1445
1446 let display_id = platform_window.display().map(|display| display.id());
1447 let sprite_atlas = platform_window.sprite_atlas();
1448 let mouse_position = platform_window.mouse_position();
1449 let modifiers = platform_window.modifiers();
1450 let capslock = platform_window.capslock();
1451 let content_size = platform_window.content_size();
1452 let scale_factor = platform_window.scale_factor();
1453 let appearance = platform_window.appearance();
1454 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1455 let invalidator = WindowInvalidator::new();
1456 let active = Rc::new(Cell::new(platform_window.is_active()));
1457 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1458 let needs_present = Rc::new(Cell::new(false));
1459 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1460 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1461 let last_frame_time = Rc::new(Cell::new(None));
1462
1463 platform_window
1464 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1465 platform_window.set_background_appearance(window_background);
1466
1467 match window_bounds {
1468 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1469 WindowBounds::Maximized(_) => platform_window.zoom(),
1470 WindowBounds::Windowed(_) => {}
1471 }
1472
1473 let accessibility_force_disabled = cx.accessibility_force_disabled;
1474 let a11y_active_flag = Arc::new(AtomicBool::new(false));
1475
1476 #[cfg(not(target_family = "wasm"))]
1477 if !accessibility_force_disabled {
1478 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
1479 if let Some(title) = &initial_window_title {
1480 initial_root_node.set_label(title.to_string());
1481 }
1482 let initial_tree = accesskit::TreeUpdate {
1483 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
1484 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
1485 tree_id: accesskit::TreeId::ROOT,
1486 focus: ROOT_NODE_ID,
1487 };
1488 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
1489 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
1490 let (action_sender, action_receiver) =
1491 async_channel::unbounded::<accesskit::ActionRequest>();
1492
1493 platform_window.a11y_init(crate::A11yCallbacks {
1494 activation: {
1495 let active_flag = a11y_active_flag.clone();
1496 Box::new(move || {
1497 log::info!("Accessibility activated");
1498 active_flag.store(true, SeqCst);
1499 activation_sender.send_blocking(()).log_err();
1500 Some(initial_tree.clone())
1501 })
1502 },
1503 action: Box::new(move |request| {
1504 action_sender.send_blocking(request).log_err();
1505 }),
1506 deactivation: {
1507 let active_flag = a11y_active_flag.clone();
1508 Box::new(move || {
1509 log::info!("Accessibility deactivated");
1510 active_flag.store(false, SeqCst);
1511 deactivation_sender.send_blocking(()).log_err();
1512 })
1513 },
1514 });
1515
1516 let mut async_cx = cx.to_async();
1522 cx.foreground_executor()
1523 .spawn(async move {
1524 while activation_receiver.recv().await.is_ok() {
1525 handle
1526 .update(&mut async_cx, |_, window, _| window.refresh())
1527 .log_err();
1528 }
1529 })
1530 .detach();
1531
1532 let mut async_cx = cx.to_async();
1533 cx.foreground_executor()
1534 .spawn(async move {
1535 while deactivation_receiver.recv().await.is_ok() {
1536 handle
1537 .update(&mut async_cx, |_, window, _| window.refresh())
1538 .log_err();
1539 }
1540 })
1541 .detach();
1542
1543 let mut async_cx = cx.to_async();
1544 cx.foreground_executor()
1545 .spawn(async move {
1546 while let Ok(request) = action_receiver.recv().await {
1547 handle
1548 .update(&mut async_cx, |_, window, cx| {
1549 window.handle_a11y_action(request, cx);
1550 })
1551 .log_err();
1552 }
1553 })
1554 .detach();
1555 }
1556
1557 platform_window.on_close(Box::new({
1558 let window_id = handle.window_id();
1559 let cx = cx.to_async();
1560 move || {
1561 cx.spawn(async move |cx| {
1564 cx.update(|cx| {
1565 if cx.windows.contains_key(window_id) {
1567 handle
1568 .update(cx, |_, window, _| window.remove_window())
1569 .log_err();
1570 }
1571 SystemWindowTabController::remove_tab(cx, window_id);
1572 });
1573 })
1574 .detach();
1575 }
1576 }));
1577 platform_window.on_request_frame(Box::new({
1578 let mut cx = cx.to_async();
1579 let invalidator = invalidator.clone();
1580 let active = active.clone();
1581 let needs_present = needs_present.clone();
1582 let next_frame_callbacks = next_frame_callbacks.clone();
1583 let input_rate_tracker = input_rate_tracker.clone();
1584 let mut deferred_force_render = false;
1585 move |request_frame_options| {
1586 if draw_in_progress() {
1602 log::debug!("deferring re-entrant window draw request");
1603 deferred_force_render |= request_frame_options.force_render;
1604 return;
1605 }
1606 let force_render =
1610 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
1611
1612 let thermal_state = handle
1613 .update(&mut cx, |_, _, cx| cx.thermal_state())
1614 .log_err();
1615
1616 let min_frame_interval = if request_frame_options.require_presentation
1620 || (!request_frame_options.force_render
1621 && next_frame_callbacks.borrow().is_empty())
1622 {
1623 None
1624 } else if !active.get() && !input_rate_tracker.borrow_mut().is_high_rate() {
1625 Some(Duration::from_micros(33333))
1626 } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
1627 Some(Duration::from_micros(16667))
1628 } else {
1629 None
1630 };
1631
1632 let now = Instant::now();
1633 if let Some(min_interval) = min_frame_interval {
1634 if let Some(last_frame) = last_frame_time.get()
1635 && now.duration_since(last_frame) < min_interval
1636 {
1637 deferred_force_render |= force_render;
1639 handle
1644 .update(&mut cx, |_, window, _| window.complete_frame())
1645 .log_err();
1646 return;
1647 }
1648 }
1649 last_frame_time.set(Some(now));
1650
1651 let next_frame_callbacks = next_frame_callbacks.take();
1652 if !next_frame_callbacks.is_empty() {
1653 handle
1654 .update(&mut cx, |_, window, cx| {
1655 for callback in next_frame_callbacks {
1656 callback(window, cx);
1657 }
1658 })
1659 .log_err();
1660 }
1661
1662 let needs_present = request_frame_options.require_presentation
1666 || needs_present.get()
1667 || input_rate_tracker.borrow_mut().is_high_rate();
1668
1669 if invalidator.is_dirty() || force_render {
1670 measure("frame duration", || {
1671 handle
1672 .update(&mut cx, |_, window, cx| {
1673 if force_render {
1674 window.refresh();
1677 }
1678 let arena_clear_needed = window.draw(cx);
1679 window.present();
1680 arena_clear_needed.clear(cx);
1681 })
1682 .log_err();
1683 })
1684 } else if needs_present {
1685 handle
1686 .update(&mut cx, |_, window, _| window.present())
1687 .log_err();
1688 }
1689
1690 handle
1691 .update(&mut cx, |_, window, _| {
1692 window.complete_frame();
1693 })
1694 .log_err();
1695 }
1696 }));
1697 platform_window.on_resize(Box::new({
1698 let mut cx = cx.to_async();
1699 move |_, _| {
1700 handle
1701 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1702 .log_err();
1703 }
1704 }));
1705 platform_window.on_moved(Box::new({
1706 let mut cx = cx.to_async();
1707 move || {
1708 handle
1709 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1710 .log_err();
1711 }
1712 }));
1713 platform_window.on_appearance_changed(Box::new({
1714 let cx = cx.to_async();
1715 let foreground_executor = cx.foreground_executor().clone();
1716 move || {
1717 let mut cx = cx.clone();
1718 foreground_executor
1721 .spawn(async move {
1722 handle
1723 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1724 .log_err();
1725 })
1726 .detach();
1727 }
1728 }));
1729 platform_window.on_button_layout_changed(Box::new({
1730 let mut cx = cx.to_async();
1731 move || {
1732 handle
1733 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
1734 .log_err();
1735 }
1736 }));
1737 platform_window.on_active_status_change(Box::new({
1738 let mut cx = cx.to_async();
1739 move |active| {
1740 handle
1741 .update(&mut cx, |_, window, cx| {
1742 window.active.set(active);
1743 window.modifiers = window.platform_window.modifiers();
1744 window.capslock = window.platform_window.capslock();
1745 window
1746 .activation_observers
1747 .clone()
1748 .retain(&(), |callback| callback(window, cx));
1749
1750 window.bounds_changed(cx);
1751 window.refresh();
1752
1753 SystemWindowTabController::update_last_active(cx, window.handle.id);
1754 })
1755 .log_err();
1756 }
1757 }));
1758 platform_window.on_hover_status_change(Box::new({
1759 let mut cx = cx.to_async();
1760 move |active| {
1761 handle
1762 .update(&mut cx, |_, window, _| {
1763 window.hovered.set(active);
1764 window.refresh();
1765 })
1766 .log_err();
1767 }
1768 }));
1769 platform_window.on_input({
1770 let mut cx = cx.to_async();
1771 Box::new(move |event| {
1772 handle
1773 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1774 .log_err()
1775 .unwrap_or(DispatchEventResult::default())
1776 })
1777 });
1778 platform_window.on_hit_test_window_control({
1779 let mut cx = cx.to_async();
1780 Box::new(move || {
1781 handle
1782 .update(&mut cx, |_, window, _cx| {
1783 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1784 if window.mouse_hit_test.ids.contains(&hitbox.id) {
1785 return Some(*area);
1786 }
1787 }
1788 None
1789 })
1790 .log_err()
1791 .unwrap_or(None)
1792 })
1793 });
1794 platform_window.on_move_tab_to_new_window({
1795 let mut cx = cx.to_async();
1796 Box::new(move || {
1797 handle
1798 .update(&mut cx, |_, _window, cx| {
1799 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1800 })
1801 .log_err();
1802 })
1803 });
1804 platform_window.on_merge_all_windows({
1805 let mut cx = cx.to_async();
1806 Box::new(move || {
1807 handle
1808 .update(&mut cx, |_, _window, cx| {
1809 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1810 })
1811 .log_err();
1812 })
1813 });
1814 platform_window.on_select_next_tab({
1815 let mut cx = cx.to_async();
1816 Box::new(move || {
1817 handle
1818 .update(&mut cx, |_, _window, cx| {
1819 SystemWindowTabController::select_next_tab(cx, handle.window_id());
1820 })
1821 .log_err();
1822 })
1823 });
1824 platform_window.on_select_previous_tab({
1825 let mut cx = cx.to_async();
1826 Box::new(move || {
1827 handle
1828 .update(&mut cx, |_, _window, cx| {
1829 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1830 })
1831 .log_err();
1832 })
1833 });
1834 platform_window.on_toggle_tab_bar({
1835 let mut cx = cx.to_async();
1836 Box::new(move || {
1837 handle
1838 .update(&mut cx, |_, window, cx| {
1839 let tab_bar_visible = window.platform_window.tab_bar_visible();
1840 SystemWindowTabController::set_visible(cx, tab_bar_visible);
1841 })
1842 .log_err();
1843 })
1844 });
1845
1846 if let Some(app_id) = app_id {
1847 platform_window.set_app_id(&app_id);
1848 }
1849
1850 platform_window.map_window().unwrap();
1851
1852 Ok(Window {
1853 handle,
1854 invalidator,
1855 removed: false,
1856 platform_window,
1857 display_id,
1858 is_resizable,
1859 is_minimizable,
1860 sprite_atlas,
1861 text_system,
1862 text_rendering_mode: cx.text_rendering_mode.clone(),
1863 rem_size: px(16.),
1864 rem_size_override_stack: SmallVec::new(),
1865 viewport_size: content_size,
1866 layout_engine: Some(TaffyLayoutEngine::new()),
1867 root: None,
1868 element_id_stack: SmallVec::default(),
1869 text_style_stack: Vec::new(),
1870 rendered_entity_stack: Vec::new(),
1871 element_offset_stack: Vec::new(),
1872 content_mask_stack: Vec::new(),
1873 element_opacity: 1.0,
1874 requested_autoscroll: None,
1875 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1876 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1877 next_frame_callbacks,
1878 next_hitbox_id: HitboxId(0),
1879 next_tooltip_id: TooltipId::default(),
1880 tooltip_bounds: None,
1881 dirty_views: FxHashSet::default(),
1882 focus_listeners: SubscriberSet::new(),
1883 focus_lost_listeners: SubscriberSet::new(),
1884 default_prevented: true,
1885 mouse_position,
1886 mouse_hit_test: HitTest::default(),
1887 modifiers,
1888 capslock,
1889 scale_factor,
1890 bounds_observers: SubscriberSet::new(),
1891 appearance,
1892 appearance_observers: SubscriberSet::new(),
1893 button_layout_observers: SubscriberSet::new(),
1894 active,
1895 hovered,
1896 needs_present,
1897 input_rate_tracker,
1898 #[cfg(feature = "input-latency-histogram")]
1899 input_latency_tracker: InputLatencyTracker::new()?,
1900 last_input_modality: InputModality::Mouse,
1901 refreshing: false,
1902 activation_observers: SubscriberSet::new(),
1903 focus: None,
1904 focus_enabled: true,
1905 focus_generation: 0,
1906 pending_input: None,
1907 pending_modifier: ModifierState::default(),
1908 pending_input_observers: SubscriberSet::new(),
1909 prompt: None,
1910 client_inset: None,
1911 image_cache_stack: Vec::new(),
1912 captured_hitbox: None,
1913 #[cfg(any(feature = "inspector", debug_assertions))]
1914 inspector: None,
1915 a11y: A11y::new(
1916 a11y_active_flag,
1917 accessibility_force_disabled,
1918 initial_window_title,
1919 ),
1920 })
1921 }
1922
1923 pub(crate) fn new_focus_listener(
1924 &self,
1925 value: AnyWindowFocusListener,
1926 ) -> (Subscription, impl FnOnce() + use<>) {
1927 self.focus_listeners.insert((), value)
1928 }
1929}
1930
1931#[derive(Clone, Debug, Default, PartialEq, Eq)]
1932#[expect(missing_docs)]
1933pub struct DispatchEventResult {
1934 pub propagate: bool,
1935 pub default_prevented: bool,
1936}
1937
1938#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1942#[repr(C)]
1943pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1944 pub bounds: Bounds<P>,
1946}
1947
1948impl ContentMask<Pixels> {
1949 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1951 ContentMask {
1952 bounds: self.bounds.scale(factor),
1953 }
1954 }
1955
1956 pub fn intersect(&self, other: &Self) -> Self {
1958 let bounds = self.bounds.intersect(&other.bounds);
1959 ContentMask { bounds }
1960 }
1961}
1962
1963impl Window {
1964 fn mark_view_dirty(&mut self, view_id: EntityId) {
1965 for view_id in self
1968 .rendered_frame
1969 .dispatch_tree
1970 .view_path_reversed(view_id)
1971 {
1972 if !self.dirty_views.insert(view_id) {
1973 break;
1974 }
1975 }
1976 }
1977
1978 pub fn observe_window_appearance(
1980 &self,
1981 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1982 ) -> Subscription {
1983 let (subscription, activate) = self.appearance_observers.insert(
1984 (),
1985 Box::new(move |window, cx| {
1986 callback(window, cx);
1987 true
1988 }),
1989 );
1990 activate();
1991 subscription
1992 }
1993
1994 pub fn observe_button_layout_changed(
1996 &self,
1997 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1998 ) -> Subscription {
1999 let (subscription, activate) = self.button_layout_observers.insert(
2000 (),
2001 Box::new(move |window, cx| {
2002 callback(window, cx);
2003 true
2004 }),
2005 );
2006 activate();
2007 subscription
2008 }
2009
2010 pub fn replace_root<E>(
2012 &mut self,
2013 cx: &mut App,
2014 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
2015 ) -> Entity<E>
2016 where
2017 E: 'static + Render,
2018 {
2019 let view = cx.new(|cx| build_view(self, cx));
2020 self.root = Some(view.clone().into());
2021 self.refresh();
2022 view
2023 }
2024
2025 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
2027 where
2028 E: 'static + Render,
2029 {
2030 self.root
2031 .as_ref()
2032 .map(|view| view.clone().downcast::<E>().ok())
2033 }
2034
2035 pub fn window_handle(&self) -> AnyWindowHandle {
2037 self.handle
2038 }
2039
2040 pub fn refresh(&mut self) {
2042 if self.invalidator.not_drawing() {
2043 self.refreshing = true;
2044 self.invalidator.set_dirty(true);
2045 }
2046 }
2047
2048 pub fn remove_window(&mut self) {
2050 self.clear_pending_keystrokes();
2051 self.removed = true;
2052 }
2053
2054 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
2056 self.focus
2057 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
2058 }
2059
2060 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
2062 if !self.focus_enabled || self.focus == Some(handle.id) {
2063 return;
2064 }
2065
2066 self.focus = Some(handle.id);
2067 self.focus_generation = self.focus_generation.wrapping_add(1);
2068 self.clear_pending_keystrokes();
2069
2070 let window_handle = self.handle;
2073 cx.defer(move |cx| {
2074 window_handle
2075 .update(cx, |_, window, cx| {
2076 window.pending_input_changed(cx);
2077 })
2078 .ok();
2079 });
2080
2081 self.refresh();
2082 }
2083
2084 pub fn blur(&mut self) {
2086 if !self.focus_enabled {
2087 return;
2088 }
2089
2090 if self.focus.is_some() {
2091 self.focus_generation = self.focus_generation.wrapping_add(1);
2092 }
2093 self.focus = None;
2094 self.refresh();
2095 }
2096
2097 pub fn disable_focus(&mut self) {
2099 self.blur();
2100 self.focus_enabled = false;
2101 }
2102
2103 pub fn focus_next(&mut self, cx: &mut App) {
2105 if !self.focus_enabled {
2106 return;
2107 }
2108
2109 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
2110 self.focus(&handle, cx)
2111 }
2112 }
2113
2114 pub fn focus_prev(&mut self, cx: &mut App) {
2116 if !self.focus_enabled {
2117 return;
2118 }
2119
2120 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
2121 self.focus(&handle, cx)
2122 }
2123 }
2124
2125 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
2127 &self.text_system
2128 }
2129
2130 pub fn text_style(&self) -> TextStyle {
2132 let mut style = TextStyle::default();
2133 for refinement in &self.text_style_stack {
2134 style.refine(refinement);
2135 }
2136 style
2137 }
2138
2139 pub fn is_maximized(&self) -> bool {
2143 self.platform_window.is_maximized()
2144 }
2145
2146 pub fn request_decorations(&self, decorations: WindowDecorations) {
2148 self.platform_window.request_decorations(decorations);
2149 }
2150
2151 pub fn set_exclusive_zone(&self, zone: Pixels) {
2157 self.platform_window.set_exclusive_zone(zone);
2158 }
2159
2160 #[cfg(all(target_os = "linux", feature = "wayland"))]
2165 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
2166 self.platform_window.set_exclusive_edge(edge);
2167 }
2168
2169 pub fn start_window_resize(&self, edge: ResizeEdge) {
2171 if self.is_resizable {
2172 self.platform_window.start_window_resize(edge);
2173 }
2174 }
2175
2176 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
2183 self.platform_window.set_input_region(region);
2184 }
2185
2186 pub fn window_bounds(&self) -> WindowBounds {
2189 self.platform_window.window_bounds()
2190 }
2191
2192 pub fn inner_window_bounds(&self) -> WindowBounds {
2194 self.platform_window.inner_window_bounds()
2195 }
2196
2197 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
2199 let focus_id = self.focused(cx).map(|handle| handle.id);
2200
2201 let window = self.handle;
2202 cx.defer(move |cx| {
2203 window
2204 .update(cx, |_, window, cx| {
2205 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
2206 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
2207 })
2208 .log_err();
2209 })
2210 }
2211
2212 pub(crate) fn dispatch_keystroke_observers(
2213 &mut self,
2214 event: &dyn Any,
2215 action: Option<Box<dyn Action>>,
2216 context_stack: Vec<KeyContext>,
2217 cx: &mut App,
2218 ) {
2219 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2220 return;
2221 };
2222
2223 cx.keystroke_observers.clone().retain(&(), move |callback| {
2224 (callback)(
2225 &KeystrokeEvent {
2226 keystroke: key_down_event.keystroke.clone(),
2227 action: action.as_ref().map(|action| action.boxed_clone()),
2228 context_stack: context_stack.clone(),
2229 },
2230 self,
2231 cx,
2232 )
2233 });
2234 }
2235
2236 pub(crate) fn dispatch_keystroke_interceptors(
2237 &mut self,
2238 event: &dyn Any,
2239 context_stack: Vec<KeyContext>,
2240 cx: &mut App,
2241 ) {
2242 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2243 return;
2244 };
2245
2246 cx.keystroke_interceptors
2247 .clone()
2248 .retain(&(), move |callback| {
2249 (callback)(
2250 &KeystrokeEvent {
2251 keystroke: key_down_event.keystroke.clone(),
2252 action: None,
2253 context_stack: context_stack.clone(),
2254 },
2255 self,
2256 cx,
2257 )
2258 });
2259 }
2260
2261 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2264 let handle = self.handle;
2265 cx.defer(move |cx| {
2266 handle.update(cx, |_, window, cx| f(window, cx)).ok();
2267 });
2268 }
2269
2270 pub fn observe<T: 'static>(
2274 &mut self,
2275 observed: &Entity<T>,
2276 cx: &mut App,
2277 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2278 ) -> Subscription {
2279 let entity_id = observed.entity_id();
2280 let observed = observed.downgrade();
2281 let window_handle = self.handle;
2282 cx.new_observer(
2283 entity_id,
2284 Box::new(move |cx| {
2285 window_handle
2286 .update(cx, |_, window, cx| {
2287 if let Some(handle) = observed.upgrade() {
2288 on_notify(handle, window, cx);
2289 true
2290 } else {
2291 false
2292 }
2293 })
2294 .unwrap_or(false)
2295 }),
2296 )
2297 }
2298
2299 pub fn subscribe<Emitter, Evt>(
2303 &mut self,
2304 entity: &Entity<Emitter>,
2305 cx: &mut App,
2306 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
2307 ) -> Subscription
2308 where
2309 Emitter: EventEmitter<Evt>,
2310 Evt: 'static,
2311 {
2312 let entity_id = entity.entity_id();
2313 let handle = entity.downgrade();
2314 let window_handle = self.handle;
2315 cx.new_subscription(
2316 entity_id,
2317 (
2318 TypeId::of::<Evt>(),
2319 Box::new(move |event, cx| {
2320 window_handle
2321 .update(cx, |_, window, cx| {
2322 if let Some(entity) = handle.upgrade() {
2323 let event = event.downcast_ref().expect("invalid event type");
2324 on_event(entity, event, window, cx);
2325 true
2326 } else {
2327 false
2328 }
2329 })
2330 .unwrap_or(false)
2331 }),
2332 ),
2333 )
2334 }
2335
2336 pub fn observe_release<T>(
2338 &self,
2339 entity: &Entity<T>,
2340 cx: &mut App,
2341 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2342 ) -> Subscription
2343 where
2344 T: 'static,
2345 {
2346 let entity_id = entity.entity_id();
2347 let window_handle = self.handle;
2348 let (subscription, activate) = cx.release_listeners.insert(
2349 entity_id,
2350 Box::new(move |entity, cx| {
2351 let entity = entity.downcast_mut().expect("invalid entity type");
2352 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2353 }),
2354 );
2355 activate();
2356 subscription
2357 }
2358
2359 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2362 AsyncWindowContext::new_context(cx.to_async(), self.handle)
2363 }
2364
2365 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2367 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2368 }
2369
2370 pub fn request_animation_frame(&self) {
2383 let entity = self.current_view();
2384 self.on_next_frame(move |_, cx| cx.notify(entity));
2385 }
2386
2387 #[cfg(any(test, feature = "test-support"))]
2392 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
2393 let callbacks = self.next_frame_callbacks.take();
2394 let count = callbacks.len();
2395 for callback in callbacks {
2396 callback(self, cx);
2397 }
2398 count
2399 }
2400
2401 #[track_caller]
2405 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2406 where
2407 R: 'static,
2408 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2409 {
2410 let handle = self.handle;
2411 cx.spawn(async move |app| {
2412 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2413 f(&mut async_window_cx).await
2414 })
2415 }
2416
2417 #[track_caller]
2421 pub fn spawn_with_priority<AsyncFn, R>(
2422 &self,
2423 priority: Priority,
2424 cx: &App,
2425 f: AsyncFn,
2426 ) -> Task<R>
2427 where
2428 R: 'static,
2429 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2430 {
2431 let handle = self.handle;
2432 cx.spawn_with_priority(priority, async move |app| {
2433 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2434 f(&mut async_window_cx).await
2435 })
2436 }
2437
2438 pub fn bounds_changed(&mut self, cx: &mut App) {
2444 self.scale_factor = self.platform_window.scale_factor();
2445 self.viewport_size = self.platform_window.content_size();
2446 self.display_id = self.platform_window.display().map(|display| display.id());
2447 self.mouse_position = self.platform_window.mouse_position();
2448
2449 self.refresh();
2450
2451 self.bounds_observers
2452 .clone()
2453 .retain(&(), |callback| callback(self, cx));
2454 }
2455
2456 pub fn bounds(&self) -> Bounds<Pixels> {
2458 self.platform_window.bounds()
2459 }
2460
2461 #[cfg(any(test, feature = "test-support"))]
2465 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
2466 self.platform_window
2467 .render_to_image(&self.rendered_frame.scene)
2468 }
2469
2470 pub fn resize(&mut self, size: Size<Pixels>) {
2472 self.platform_window.resize(size);
2473 }
2474
2475 pub fn is_fullscreen(&self) -> bool {
2477 self.platform_window.is_fullscreen()
2478 }
2479
2480 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
2481 self.appearance = self.platform_window.appearance();
2482
2483 self.appearance_observers
2484 .clone()
2485 .retain(&(), |callback| callback(self, cx));
2486 }
2487
2488 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2489 self.button_layout_observers
2490 .clone()
2491 .retain(&(), |callback| callback(self, cx));
2492 }
2493
2494 pub fn appearance(&self) -> WindowAppearance {
2496 self.appearance
2497 }
2498
2499 pub fn viewport_size(&self) -> Size<Pixels> {
2501 self.viewport_size
2502 }
2503
2504 pub fn is_window_active(&self) -> bool {
2506 self.active.get()
2507 }
2508
2509 pub fn is_window_hovered(&self) -> bool {
2513 if cfg!(any(
2514 target_os = "windows",
2515 target_os = "linux",
2516 target_os = "freebsd"
2517 )) {
2518 self.hovered.get()
2519 } else {
2520 self.is_window_active()
2521 }
2522 }
2523
2524 pub fn zoom_window(&self) {
2526 self.platform_window.zoom();
2527 }
2528
2529 pub fn show_window_menu(&self, position: Point<Pixels>) {
2531 self.platform_window.show_window_menu(position)
2532 }
2533
2534 pub fn start_window_move(&self) {
2539 self.platform_window.start_window_move()
2540 }
2541
2542 pub fn set_client_inset(&mut self, inset: Pixels) {
2544 self.client_inset = Some(inset);
2545 self.platform_window.set_client_inset(inset);
2546 }
2547
2548 pub fn client_inset(&self) -> Option<Pixels> {
2550 self.client_inset
2551 }
2552
2553 pub fn window_decorations(&self) -> Decorations {
2555 self.platform_window.window_decorations()
2556 }
2557
2558 pub fn is_resizable(&self) -> bool {
2560 self.is_resizable
2561 }
2562
2563 pub fn is_minimizable(&self) -> bool {
2565 self.is_minimizable
2566 }
2567
2568 pub fn window_controls(&self) -> WindowControls {
2570 self.platform_window.window_controls()
2571 }
2572
2573 pub fn set_window_title(&mut self, title: &str) {
2575 self.platform_window.set_title(title);
2576 self.a11y.set_window_title(title.to_string());
2577 }
2578
2579 #[cfg(target_os = "macos")]
2581 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
2582 self.platform_window.set_traffic_light_position(position);
2583 }
2584
2585 pub fn set_app_id(&mut self, app_id: &str) {
2587 self.platform_window.set_app_id(app_id);
2588 }
2589
2590 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2592 self.platform_window
2593 .set_background_appearance(background_appearance);
2594 }
2595
2596 pub fn set_window_edited(&mut self, edited: bool) {
2598 self.platform_window.set_edited(edited);
2599 }
2600
2601 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
2604 self.platform_window.set_document_path(path);
2605 }
2606
2607 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2609 cx.platform
2610 .displays()
2611 .into_iter()
2612 .find(|display| Some(display.id()) == self.display_id)
2613 }
2614
2615 pub fn show_character_palette(&self) {
2617 self.platform_window.show_character_palette();
2618 }
2619
2620 pub fn scale_factor(&self) -> f32 {
2624 self.scale_factor
2625 }
2626
2627 #[cfg(any(test, feature = "test-support"))]
2629 pub fn set_scale_factor(&mut self, scale_factor: f32) {
2630 self.scale_factor = scale_factor;
2631 self.refresh();
2632 }
2633
2634 pub fn rem_size(&self) -> Pixels {
2637 self.rem_size_override_stack
2638 .last()
2639 .copied()
2640 .unwrap_or(self.rem_size)
2641 }
2642
2643 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2646 self.rem_size = rem_size.into();
2647 }
2648
2649 pub fn with_global_id<R>(
2652 &mut self,
2653 element_id: ElementId,
2654 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2655 ) -> R {
2656 self.with_id(element_id, |this| {
2657 let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2658
2659 f(&global_id, this)
2660 })
2661 }
2662
2663 #[inline]
2665 pub fn with_id<R>(
2666 &mut self,
2667 element_id: impl Into<ElementId>,
2668 f: impl FnOnce(&mut Self) -> R,
2669 ) -> R {
2670 self.element_id_stack.push(element_id.into());
2671 let result = f(self);
2672 self.element_id_stack.pop();
2673 result
2674 }
2675
2676 #[inline]
2682 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2683 where
2684 F: FnOnce(&mut Self) -> R,
2685 {
2686 self.invalidator.debug_assert_paint_or_prepaint();
2687
2688 if let Some(rem_size) = rem_size {
2689 self.rem_size_override_stack.push(rem_size.into());
2690 let result = f(self);
2691 self.rem_size_override_stack.pop();
2692 result
2693 } else {
2694 f(self)
2695 }
2696 }
2697
2698 pub fn line_height(&self) -> Pixels {
2700 self.text_style().line_height_in_pixels(self.rem_size())
2701 }
2702
2703 #[inline]
2705 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
2706 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
2707 }
2708
2709 #[inline]
2711 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
2712 let scale_factor = f64::from(self.scale_factor());
2713 round_half_toward_zero_f64(value * scale_factor) / scale_factor
2714 }
2715
2716 #[inline]
2718 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
2719 bounds.map(|c| self.pixel_snap(c))
2720 }
2721
2722 #[inline]
2724 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
2725 position.map(|c| self.pixel_snap(c))
2726 }
2727
2728 #[inline]
2729 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2730 let scale_factor = self.scale_factor();
2731 let left = round_to_device_pixel(bounds.left().0, scale_factor);
2732 let top = round_to_device_pixel(bounds.top().0, scale_factor);
2733 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
2734 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2735 Bounds::from_corners(
2736 point(ScaledPixels(left), ScaledPixels(top)),
2737 point(ScaledPixels(right), ScaledPixels(bottom)),
2738 )
2739 }
2740
2741 #[inline]
2743 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
2744 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
2745 }
2746
2747 #[inline]
2748 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
2749 edges.map(|e| self.snap_stroke(*e))
2750 }
2751
2752 #[inline]
2754 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2755 let scale_factor = self.scale_factor();
2756 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
2757 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
2758 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
2759 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2760 Bounds::from_corners(
2761 point(ScaledPixels(left), ScaledPixels(top)),
2762 point(ScaledPixels(right), ScaledPixels(bottom)),
2763 )
2764 }
2765
2766 #[inline]
2767 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
2768 ContentMask {
2769 bounds: self.cover_bounds(self.content_mask().bounds),
2770 }
2771 }
2772
2773 pub fn prevent_default(&mut self) {
2776 self.default_prevented = true;
2777 }
2778
2779 pub fn default_prevented(&self) -> bool {
2781 self.default_prevented
2782 }
2783
2784 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2786 let node_id =
2787 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2788 self.rendered_frame
2789 .dispatch_tree
2790 .is_action_available(action, node_id)
2791 }
2792
2793 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2795 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2796 self.rendered_frame
2797 .dispatch_tree
2798 .is_action_available(action, node_id)
2799 }
2800
2801 pub fn mouse_position(&self) -> Point<Pixels> {
2803 self.mouse_position
2804 }
2805
2806 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
2813 self.captured_hitbox = Some(hitbox_id);
2814 }
2815
2816 pub fn release_pointer(&mut self) {
2818 self.captured_hitbox = None;
2819 }
2820
2821 pub fn captured_hitbox(&self) -> Option<HitboxId> {
2823 self.captured_hitbox
2824 }
2825
2826 pub fn modifiers(&self) -> Modifiers {
2828 self.modifiers
2829 }
2830
2831 pub fn last_input_was_keyboard(&self) -> bool {
2834 self.last_input_modality == InputModality::Keyboard
2835 }
2836
2837 pub fn capslock(&self) -> Capslock {
2839 self.capslock
2840 }
2841
2842 fn complete_frame(&self) {
2843 self.platform_window.completed_frame();
2844 }
2845
2846 #[profiling::function]
2849 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2850 let frame_dirty = self.invalidator.take_frame_dirty();
2853 let draw_started_at = profiler::frame_trace_enabled().then(Instant::now);
2854
2855 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
2858
2859 self.invalidate_entities();
2860 cx.entities.clear_accessed();
2861 debug_assert!(self.rendered_entity_stack.is_empty());
2862 self.invalidator.set_dirty(false);
2863 self.requested_autoscroll = None;
2864
2865 if let Some(input_handler) = self.platform_window.take_input_handler() {
2870 if let Some(slot) = self
2871 .rendered_frame
2872 .input_handlers
2873 .iter_mut()
2874 .rev()
2875 .find(|h| h.is_none())
2876 {
2877 *slot = Some(input_handler);
2878 } else {
2879 self.rendered_frame.input_handlers.push(Some(input_handler));
2880 }
2881 }
2882 if !cx.mode.skip_drawing() {
2883 self.draw_roots(cx);
2884 }
2885 self.dirty_views.clear();
2886 self.next_frame.window_active = self.active.get();
2887
2888 if let Some(input_handler) = self
2894 .next_frame
2895 .input_handlers
2896 .iter_mut()
2897 .rev()
2898 .find_map(|h| h.take())
2899 {
2900 self.platform_window.set_input_handler(input_handler);
2901 }
2902
2903 self.layout_engine.as_mut().unwrap().clear();
2904 self.text_system().finish_frame();
2905 self.next_frame.finish(&mut self.rendered_frame);
2906
2907 self.invalidator.set_phase(DrawPhase::Focus);
2908 let previous_focus_path = self.rendered_frame.focus_path();
2909 let previous_window_active = self.rendered_frame.window_active;
2910 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2911 self.next_frame.clear();
2912 let current_focus_path = self.rendered_frame.focus_path();
2913 let current_window_active = self.rendered_frame.window_active;
2914 let mut focus_before_listeners = self.focus;
2915
2916 if previous_focus_path != current_focus_path
2917 || previous_window_active != current_window_active
2918 {
2919 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2920 self.focus_lost_listeners
2921 .clone()
2922 .retain(&(), |listener| listener(self, cx));
2923 focus_before_listeners = self.focus;
2928 }
2929
2930 let event = WindowFocusEvent {
2931 previous_focus_path: if previous_window_active {
2932 previous_focus_path
2933 } else {
2934 Default::default()
2935 },
2936 current_focus_path: if current_window_active {
2937 current_focus_path
2938 } else {
2939 Default::default()
2940 },
2941 };
2942 self.focus_listeners
2943 .clone()
2944 .retain(&(), |listener| listener(&event, self, cx));
2945 }
2946
2947 debug_assert!(self.rendered_entity_stack.is_empty());
2948 self.record_entities_accessed(cx);
2949 self.reset_cursor_style(cx);
2950 self.refreshing = false;
2951 self.invalidator.set_phase(DrawPhase::None);
2952 if self.focus != focus_before_listeners {
2957 self.refresh();
2958 }
2959 self.needs_present.set(true);
2960
2961 if let Some(draw_start) = draw_started_at {
2962 profiler::record_frame_timing(profiler::FrameTiming {
2963 window_id: self.handle.window_id(),
2964 dirty_at: frame_dirty.dirty_at,
2965 invalidations: frame_dirty.invalidations,
2966 draw_start,
2967 draw_end: Instant::now(),
2968 });
2969 }
2970
2971 arena_scope.exit(&cx.element_arena)
2974 }
2975
2976 fn record_entities_accessed(&mut self, cx: &mut App) {
2977 let mut entities_ref = cx.entities.accessed_entities.get_mut();
2978 let mut entities = mem::take(entities_ref.deref_mut());
2979 let handle = self.handle;
2980 cx.record_entities_accessed(
2981 handle,
2982 self.invalidator.clone(),
2984 &entities,
2985 );
2986 let mut entities_ref = cx.entities.accessed_entities.get_mut();
2987 mem::swap(&mut entities, entities_ref.deref_mut());
2988 }
2989
2990 fn invalidate_entities(&mut self) {
2991 let mut views = self.invalidator.take_views();
2992 for entity in views.drain() {
2993 self.mark_view_dirty(entity);
2994 }
2995 self.invalidator.replace_views(views);
2996 }
2997
2998 #[profiling::function]
2999 fn present(&mut self) {
3000 self.platform_window.draw(&self.rendered_frame.scene);
3001 #[cfg(feature = "input-latency-histogram")]
3002 self.input_latency_tracker.record_frame_presented();
3003 self.needs_present.set(false);
3004 profiling::finish_frame!();
3005 }
3006
3007 #[cfg(feature = "bench")]
3013 pub fn present_if_needed(&mut self) {
3014 if self.needs_present.get() {
3015 self.present();
3016 }
3017 }
3018
3019 #[cfg(feature = "input-latency-histogram")]
3021 pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
3022 self.input_latency_tracker.snapshot()
3023 }
3024
3025 fn draw_roots(&mut self, cx: &mut App) {
3026 self.invalidator.set_phase(DrawPhase::Prepaint);
3027 self.tooltip_bounds.take();
3028
3029 self.a11y.sync_active_flag();
3030 if self.a11y.is_active() {
3031 self.a11y.begin_frame();
3032 }
3033
3034 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
3035 let root_size = {
3036 #[cfg(any(feature = "inspector", debug_assertions))]
3037 {
3038 if self.inspector.is_some() {
3039 let mut size = self.viewport_size;
3040 size.width = (size.width - _inspector_width).max(px(0.0));
3041 size
3042 } else {
3043 self.viewport_size
3044 }
3045 }
3046 #[cfg(not(any(feature = "inspector", debug_assertions)))]
3047 {
3048 self.viewport_size
3049 }
3050 };
3051
3052 let scale_factor = self.scale_factor();
3056 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
3057 let root_layout_id = root_element.request_layout(self, cx);
3058 self.layout_engine
3059 .as_mut()
3060 .unwrap()
3061 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
3062 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3063
3064 #[cfg(any(feature = "inspector", debug_assertions))]
3065 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
3066
3067 self.prepaint_deferred_draws(cx);
3068
3069 let mut prompt_element = None;
3070 let mut active_drag_element = None;
3071 let mut tooltip_element = None;
3072 if let Some(prompt) = self.prompt.take() {
3073 let mut element = prompt.view.any_view().into_any_element();
3074 let prompt_layout_id = element.request_layout(self, cx);
3075 self.layout_engine
3076 .as_mut()
3077 .unwrap()
3078 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
3079 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3080 prompt_element = Some(element);
3081 self.prompt = Some(prompt);
3082 } else if let Some(active_drag) = cx.active_drag.take() {
3083 let mut element = active_drag.view.clone().into_any_element();
3084 let offset = self.mouse_position() - active_drag.cursor_offset;
3085 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
3086 active_drag_element = Some(element);
3087 cx.active_drag = Some(active_drag);
3088 } else {
3089 tooltip_element = self.prepaint_tooltip(cx);
3090 }
3091
3092 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
3093
3094 self.invalidator.set_phase(DrawPhase::Paint);
3096 root_element.paint(self, cx);
3097
3098 #[cfg(any(feature = "inspector", debug_assertions))]
3099 self.paint_inspector(inspector_element, cx);
3100
3101 self.paint_deferred_draws(cx);
3102
3103 if let Some(mut prompt_element) = prompt_element {
3104 prompt_element.paint(self, cx);
3105 } else if let Some(mut drag_element) = active_drag_element {
3106 drag_element.paint(self, cx);
3107 } else if let Some(mut tooltip_element) = tooltip_element {
3108 tooltip_element.paint(self, cx);
3109 }
3110
3111 #[cfg(any(feature = "inspector", debug_assertions))]
3112 self.paint_inspector_hitbox(cx);
3113
3114 let a11y_active_start_of_frame = self.a11y.is_active();
3116 self.a11y.sync_active_flag();
3117 let a11y_active_end_of_frame = self.a11y.is_active();
3118
3119 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
3120
3121 if a11y_active_start_of_frame {
3122 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
3125 viewport_size: self.viewport_size,
3126 scale_factor: self.scale_factor,
3127 tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
3128 };
3129 let tree_update = self.a11y.end_frame(frame_info);
3131
3132 if should_send_a11y_update {
3133 log::debug!(
3134 "Sending a11y tree update: {} nodes",
3135 tree_update.nodes.len()
3136 );
3137 self.platform_window.a11y_tree_update(tree_update);
3138 }
3139 }
3140 }
3141
3142 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
3143 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
3145 let Some(Some(tooltip_request)) = self
3146 .next_frame
3147 .tooltip_requests
3148 .get(tooltip_request_index)
3149 .cloned()
3150 else {
3151 log::error!("Unexpectedly absent TooltipRequest");
3152 continue;
3153 };
3154 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
3155 let mouse_position = tooltip_request.tooltip.mouse_position;
3156 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
3157
3158 let mut tooltip_bounds =
3159 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
3160 let window_bounds = Bounds {
3161 origin: Point::default(),
3162 size: self.viewport_size(),
3163 };
3164
3165 if tooltip_bounds.right() > window_bounds.right() {
3166 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
3167 if new_x >= Pixels::ZERO {
3168 tooltip_bounds.origin.x = new_x;
3169 } else {
3170 tooltip_bounds.origin.x = cmp::max(
3171 Pixels::ZERO,
3172 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
3173 );
3174 }
3175 }
3176
3177 if tooltip_bounds.bottom() > window_bounds.bottom() {
3178 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
3179 if new_y >= Pixels::ZERO {
3180 tooltip_bounds.origin.y = new_y;
3181 } else {
3182 tooltip_bounds.origin.y = cmp::max(
3183 Pixels::ZERO,
3184 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
3185 );
3186 }
3187 }
3188
3189 let is_visible =
3193 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
3194 if !is_visible {
3195 continue;
3196 }
3197
3198 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
3199 element.prepaint(window, cx)
3200 });
3201
3202 self.tooltip_bounds = Some(TooltipBounds {
3203 id: tooltip_request.id,
3204 bounds: tooltip_bounds,
3205 });
3206 return Some(element);
3207 }
3208 None
3209 }
3210
3211 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
3212 assert_eq!(self.element_id_stack.len(), 0);
3213
3214 let mut round_start = 0;
3225 let mut depth = 0;
3226 loop {
3227 let round_end = self.next_frame.deferred_draws.len();
3228 if round_start == round_end {
3229 break;
3230 }
3231 assert!(depth < 10, "Exceeded maximum (10) deferred depth");
3233 depth += 1;
3234
3235 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
3237 traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3238
3239 for deferred_draw_ix in traversal_order {
3240 let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
3241 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
3242 self.element_id_stack
3243 .clone_from(&deferred_draw.element_id_stack);
3244 self.text_style_stack
3245 .clone_from(&deferred_draw.text_style_stack);
3246 (
3247 deferred_draw.element.take(),
3248 deferred_draw.parent_node,
3249 deferred_draw.current_view,
3250 deferred_draw.rem_size,
3251 deferred_draw.absolute_offset,
3252 deferred_draw.prepaint_range.clone(),
3253 )
3254 };
3255 self.next_frame.dispatch_tree.set_active_node(parent_node);
3256
3257 let prepaint_start = self.prepaint_index();
3258 if let Some(mut element) = element {
3259 self.with_rendered_view(current_view, |window| {
3260 window.with_rem_size(Some(rem_size), |window| {
3261 window.with_absolute_element_offset(absolute_offset, |window| {
3262 element.prepaint(window, cx);
3263 });
3264 });
3265 });
3266 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
3267 } else {
3268 self.reuse_prepaint(prepaint_range);
3269 }
3270 let prepaint_end = self.prepaint_index();
3271 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
3272 prepaint_start..prepaint_end;
3273 }
3274
3275 self.element_id_stack.clear();
3276 self.text_style_stack.clear();
3277 round_start = round_end;
3278 }
3279 }
3280
3281 fn paint_deferred_draws(&mut self, cx: &mut App) {
3282 assert_eq!(self.element_id_stack.len(), 0);
3283
3284 if self.next_frame.deferred_draws.len() == 0 {
3287 return;
3288 }
3289
3290 let traversal_order = self.deferred_draw_traversal_order();
3291 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
3292 for deferred_draw_ix in traversal_order {
3293 let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
3294 self.element_id_stack
3295 .clone_from(&deferred_draw.element_id_stack);
3296 self.next_frame
3297 .dispatch_tree
3298 .set_active_node(deferred_draw.parent_node);
3299
3300 let paint_start = self.paint_index();
3301 let content_mask = deferred_draw.content_mask;
3302 if let Some(element) = deferred_draw.element.as_mut() {
3303 self.with_rendered_view(deferred_draw.current_view, |window| {
3304 window.with_content_mask(content_mask, |window| {
3305 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
3306 element.paint(window, cx);
3307 });
3308 })
3309 })
3310 } else {
3311 self.reuse_paint(deferred_draw.paint_range.clone());
3312 }
3313 let paint_end = self.paint_index();
3314 deferred_draw.paint_range = paint_start..paint_end;
3315 }
3316 self.next_frame.deferred_draws = deferred_draws;
3317 self.element_id_stack.clear();
3318 }
3319
3320 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
3321 let deferred_count = self.next_frame.deferred_draws.len();
3322 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
3323 sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3324 sorted_indices
3325 }
3326
3327 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
3328 PrepaintStateIndex {
3329 hitboxes_index: self.next_frame.hitboxes.len(),
3330 tooltips_index: self.next_frame.tooltip_requests.len(),
3331 deferred_draws_index: self.next_frame.deferred_draws.len(),
3332 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
3333 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3334 line_layout_index: self.text_system.layout_index(),
3335 }
3336 }
3337
3338 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
3339 self.next_frame.hitboxes.extend(
3340 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
3341 .iter()
3342 .cloned(),
3343 );
3344 self.next_frame.tooltip_requests.extend(
3345 self.rendered_frame.tooltip_requests
3346 [range.start.tooltips_index..range.end.tooltips_index]
3347 .iter_mut()
3348 .map(|request| request.take()),
3349 );
3350 self.next_frame.accessed_element_states.extend(
3351 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3352 ..range.end.accessed_element_states_index]
3353 .iter()
3354 .map(|(id, type_id)| (id.clone(), *type_id)),
3355 );
3356 self.text_system
3357 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3358
3359 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
3360 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
3361 &mut self.rendered_frame.dispatch_tree,
3362 self.focus,
3363 );
3364
3365 if reused_subtree.contains_focus() {
3366 self.next_frame.focus = self.focus;
3367 }
3368
3369 self.next_frame.deferred_draws.extend(
3370 self.rendered_frame.deferred_draws
3371 [range.start.deferred_draws_index..range.end.deferred_draws_index]
3372 .iter()
3373 .map(|deferred_draw| DeferredDraw {
3374 current_view: deferred_draw.current_view,
3375 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
3376 element_id_stack: deferred_draw.element_id_stack.clone(),
3377 text_style_stack: deferred_draw.text_style_stack.clone(),
3378 content_mask: deferred_draw.content_mask,
3379 rem_size: deferred_draw.rem_size,
3380 priority: deferred_draw.priority,
3381 element: None,
3382 absolute_offset: deferred_draw.absolute_offset,
3383 prepaint_range: deferred_draw.prepaint_range.clone(),
3384 paint_range: deferred_draw.paint_range.clone(),
3385 }),
3386 );
3387 }
3388
3389 pub(crate) fn paint_index(&self) -> PaintIndex {
3390 PaintIndex {
3391 scene_index: self.next_frame.scene.len(),
3392 #[cfg(any(test, feature = "test-support"))]
3393 debug_bounds_index: self.next_frame.debug_bounds_records.len(),
3394 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
3395 input_handlers_index: self.next_frame.input_handlers.len(),
3396 cursor_styles_index: self.next_frame.cursor_styles.len(),
3397 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3398 tab_handle_index: self.next_frame.tab_stops.paint_index(),
3399 line_layout_index: self.text_system.layout_index(),
3400 }
3401 }
3402
3403 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
3404 #[cfg(any(test, feature = "test-support"))]
3406 for (selector, bounds) in &self.rendered_frame.debug_bounds_records
3407 [range.start.debug_bounds_index..range.end.debug_bounds_index]
3408 {
3409 self.next_frame
3410 .record_debug_bounds(selector.clone(), *bounds);
3411 }
3412 self.next_frame.cursor_styles.extend(
3413 self.rendered_frame.cursor_styles
3414 [range.start.cursor_styles_index..range.end.cursor_styles_index]
3415 .iter()
3416 .cloned(),
3417 );
3418 self.next_frame.input_handlers.extend(
3419 self.rendered_frame.input_handlers
3420 [range.start.input_handlers_index..range.end.input_handlers_index]
3421 .iter_mut()
3422 .map(|handler| handler.take()),
3423 );
3424 self.next_frame.mouse_listeners.extend(
3425 self.rendered_frame.mouse_listeners
3426 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
3427 .iter_mut()
3428 .map(|listener| listener.take()),
3429 );
3430 self.next_frame.accessed_element_states.extend(
3431 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3432 ..range.end.accessed_element_states_index]
3433 .iter()
3434 .map(|(id, type_id)| (id.clone(), *type_id)),
3435 );
3436 self.next_frame.tab_stops.replay(
3437 &self.rendered_frame.tab_stops.insertion_history
3438 [range.start.tab_handle_index..range.end.tab_handle_index],
3439 );
3440
3441 self.text_system
3442 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3443 self.next_frame.scene.replay(
3444 range.start.scene_index..range.end.scene_index,
3445 &self.rendered_frame.scene,
3446 );
3447 }
3448
3449 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
3453 where
3454 F: FnOnce(&mut Self) -> R,
3455 {
3456 self.invalidator.debug_assert_paint_or_prepaint();
3457 if let Some(style) = style {
3458 self.text_style_stack.push(style);
3459 let result = f(self);
3460 self.text_style_stack.pop();
3461 result
3462 } else {
3463 f(self)
3464 }
3465 }
3466
3467 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
3470 self.invalidator.debug_assert_paint();
3471 self.next_frame.cursor_styles.push(CursorStyleRequest {
3472 hitbox_id: Some(hitbox.id),
3473 style,
3474 });
3475 }
3476
3477 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
3482 self.invalidator.debug_assert_paint();
3483 self.next_frame.cursor_styles.push(CursorStyleRequest {
3484 hitbox_id: None,
3485 style,
3486 })
3487 }
3488
3489 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
3492 self.invalidator.debug_assert_prepaint();
3493 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
3494 self.next_frame
3495 .tooltip_requests
3496 .push(Some(TooltipRequest { id, tooltip }));
3497 id
3498 }
3499
3500 #[inline]
3505 pub fn with_content_mask<R>(
3506 &mut self,
3507 mask: Option<ContentMask<Pixels>>,
3508 f: impl FnOnce(&mut Self) -> R,
3509 ) -> R {
3510 self.invalidator.debug_assert_paint_or_prepaint();
3511 if let Some(mask) = mask {
3512 let mask = mask.intersect(&self.content_mask());
3513 self.content_mask_stack.push(mask);
3514 let result = f(self);
3515 self.content_mask_stack.pop();
3516 result
3517 } else {
3518 f(self)
3519 }
3520 }
3521
3522 pub fn with_element_offset<R>(
3525 &mut self,
3526 offset: Point<Pixels>,
3527 f: impl FnOnce(&mut Self) -> R,
3528 ) -> R {
3529 self.invalidator.debug_assert_prepaint();
3530
3531 if offset.is_zero() {
3532 return f(self);
3533 };
3534
3535 let abs_offset = self.element_offset() + offset;
3536 self.with_absolute_element_offset(abs_offset, f)
3537 }
3538
3539 pub fn with_absolute_element_offset<R>(
3543 &mut self,
3544 offset: Point<Pixels>,
3545 f: impl FnOnce(&mut Self) -> R,
3546 ) -> R {
3547 self.invalidator.debug_assert_prepaint();
3548 self.element_offset_stack.push(offset);
3549 let result = f(self);
3550 self.element_offset_stack.pop();
3551 result
3552 }
3553
3554 pub(crate) fn with_element_opacity<R>(
3555 &mut self,
3556 opacity: Option<f32>,
3557 f: impl FnOnce(&mut Self) -> R,
3558 ) -> R {
3559 self.invalidator.debug_assert_paint_or_prepaint();
3560
3561 let Some(opacity) = opacity else {
3562 return f(self);
3563 };
3564
3565 let previous_opacity = self.element_opacity;
3566 self.element_opacity = previous_opacity * opacity;
3567 let result = f(self);
3568 self.element_opacity = previous_opacity;
3569 result
3570 }
3571
3572 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
3578 self.invalidator.debug_assert_prepaint();
3579 let index = self.prepaint_index();
3580 let result = f(self);
3581 if result.is_err() {
3582 self.next_frame.hitboxes.truncate(index.hitboxes_index);
3583 self.next_frame
3584 .tooltip_requests
3585 .truncate(index.tooltips_index);
3586 self.next_frame
3587 .deferred_draws
3588 .truncate(index.deferred_draws_index);
3589 self.next_frame
3590 .dispatch_tree
3591 .truncate(index.dispatch_tree_index);
3592 self.next_frame
3593 .accessed_element_states
3594 .truncate(index.accessed_element_states_index);
3595 self.text_system.truncate_layouts(index.line_layout_index);
3596 }
3597 result
3598 }
3599
3600 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
3606 self.invalidator.debug_assert_prepaint();
3607 self.requested_autoscroll = Some(bounds);
3608 }
3609
3610 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
3613 self.invalidator.debug_assert_prepaint();
3614 self.requested_autoscroll.take()
3615 }
3616
3617 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3623 let (task, is_first) = cx.fetch_asset::<A>(source);
3624 task.clone().now_or_never().or_else(|| {
3625 if is_first {
3626 let entity_id = self.current_view();
3627 self.spawn(cx, {
3628 let task = task.clone();
3629 async move |cx| {
3630 task.await;
3631
3632 cx.on_next_frame(move |_, cx| {
3633 cx.notify(entity_id);
3634 });
3635 }
3636 })
3637 .detach();
3638 }
3639
3640 None
3641 })
3642 }
3643
3644 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3650 let (task, _) = cx.fetch_asset::<A>(source);
3651 task.now_or_never()
3652 }
3653 pub fn element_offset(&self) -> Point<Pixels> {
3656 self.invalidator.debug_assert_prepaint();
3657 self.element_offset_stack
3658 .last()
3659 .copied()
3660 .unwrap_or_default()
3661 }
3662
3663 #[inline]
3666 pub(crate) fn element_opacity(&self) -> f32 {
3667 self.invalidator.debug_assert_paint_or_prepaint();
3668 self.element_opacity
3669 }
3670
3671 pub fn content_mask(&self) -> ContentMask<Pixels> {
3673 self.invalidator.debug_assert_paint_or_prepaint();
3674 self.content_mask_stack
3675 .last()
3676 .cloned()
3677 .unwrap_or_else(|| ContentMask {
3678 bounds: Bounds {
3679 origin: Point::default(),
3680 size: self.viewport_size,
3681 },
3682 })
3683 }
3684
3685 pub fn with_element_namespace<R>(
3688 &mut self,
3689 element_id: impl Into<ElementId>,
3690 f: impl FnOnce(&mut Self) -> R,
3691 ) -> R {
3692 self.element_id_stack.push(element_id.into());
3693 let result = f(self);
3694 self.element_id_stack.pop();
3695 result
3696 }
3697
3698 pub fn use_keyed_state<S: 'static>(
3700 &mut self,
3701 key: impl Into<ElementId>,
3702 cx: &mut App,
3703 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3704 ) -> Entity<S> {
3705 let current_view = self.current_view();
3706 self.with_global_id(key.into(), |global_id, window| {
3707 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
3708 if let Some(state) = state {
3709 (state.clone(), state)
3710 } else {
3711 let new_state = cx.new(|cx| init(window, cx));
3712 cx.observe(&new_state, move |_, cx| {
3713 cx.notify(current_view);
3714 })
3715 .detach();
3716 (new_state.clone(), new_state)
3717 }
3718 })
3719 })
3720 }
3721
3722 #[track_caller]
3728 pub fn use_state<S: 'static>(
3729 &mut self,
3730 cx: &mut App,
3731 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3732 ) -> Entity<S> {
3733 self.use_keyed_state(
3734 ElementId::CodeLocation(*core::panic::Location::caller()),
3735 cx,
3736 init,
3737 )
3738 }
3739
3740 pub fn with_element_state<S, R>(
3745 &mut self,
3746 global_id: &GlobalElementId,
3747 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
3748 ) -> R
3749 where
3750 S: 'static,
3751 {
3752 self.invalidator.debug_assert_paint_or_prepaint();
3753
3754 let key = (global_id.clone(), TypeId::of::<S>());
3755 self.next_frame.accessed_element_states.push(key.clone());
3756
3757 if let Some(any) = self
3758 .next_frame
3759 .element_states
3760 .remove(&key)
3761 .or_else(|| self.rendered_frame.element_states.remove(&key))
3762 {
3763 let ElementStateBox {
3764 inner,
3765 #[cfg(debug_assertions)]
3766 type_name,
3767 } = any;
3768 let mut state_box = inner
3770 .downcast::<Option<S>>()
3771 .map_err(|_| {
3772 #[cfg(debug_assertions)]
3773 {
3774 anyhow::anyhow!(
3775 "invalid element state type for id, requested {:?}, actual: {:?}",
3776 std::any::type_name::<S>(),
3777 type_name
3778 )
3779 }
3780
3781 #[cfg(not(debug_assertions))]
3782 {
3783 anyhow::anyhow!(
3784 "invalid element state type for id, requested {:?}",
3785 std::any::type_name::<S>(),
3786 )
3787 }
3788 })
3789 .unwrap();
3790
3791 let state = state_box.take().expect(
3792 "reentrant call to with_element_state for the same state type and element id",
3793 );
3794 let (result, state) = f(Some(state), self);
3795 state_box.replace(state);
3796 self.next_frame.element_states.insert(
3797 key,
3798 ElementStateBox {
3799 inner: state_box,
3800 #[cfg(debug_assertions)]
3801 type_name,
3802 },
3803 );
3804 result
3805 } else {
3806 let (result, state) = f(None, self);
3807 self.next_frame.element_states.insert(
3808 key,
3809 ElementStateBox {
3810 inner: Box::new(Some(state)),
3811 #[cfg(debug_assertions)]
3812 type_name: std::any::type_name::<S>(),
3813 },
3814 );
3815 result
3816 }
3817 }
3818
3819 pub fn with_optional_element_state<S, R>(
3826 &mut self,
3827 global_id: Option<&GlobalElementId>,
3828 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
3829 ) -> R
3830 where
3831 S: 'static,
3832 {
3833 self.invalidator.debug_assert_paint_or_prepaint();
3834
3835 if let Some(global_id) = global_id {
3836 self.with_element_state(global_id, |state, cx| {
3837 let (result, state) = f(Some(state), cx);
3838 let state =
3839 state.expect("you must return some state when you pass some element id");
3840 (result, state)
3841 })
3842 } else {
3843 let (result, state) = f(None, self);
3844 debug_assert!(
3845 state.is_none(),
3846 "you must not return an element state when passing None for the global id"
3847 );
3848 result
3849 }
3850 }
3851
3852 #[inline]
3854 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
3855 if let Some(index) = index {
3856 self.next_frame.tab_stops.begin_group(index);
3857 let result = f(self);
3858 self.next_frame.tab_stops.end_group();
3859 result
3860 } else {
3861 f(self)
3862 }
3863 }
3864
3865 pub fn defer_draw(
3874 &mut self,
3875 element: AnyElement,
3876 absolute_offset: Point<Pixels>,
3877 priority: usize,
3878 content_mask: Option<ContentMask<Pixels>>,
3879 ) {
3880 self.invalidator.debug_assert_prepaint();
3881 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3882 self.next_frame.deferred_draws.push(DeferredDraw {
3883 current_view: self.current_view(),
3884 parent_node,
3885 element_id_stack: self.element_id_stack.clone(),
3886 text_style_stack: self.text_style_stack.clone(),
3887 content_mask,
3888 rem_size: self.rem_size(),
3889 priority,
3890 element: Some(element),
3891 absolute_offset,
3892 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3893 paint_range: PaintIndex::default()..PaintIndex::default(),
3894 });
3895 }
3896
3897 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3903 self.invalidator.debug_assert_paint();
3904
3905 let content_mask = self.content_mask();
3906 let clipped_bounds = bounds.intersect(&content_mask.bounds);
3907 if !clipped_bounds.is_empty() {
3908 self.next_frame
3909 .scene
3910 .push_layer(self.cover_bounds(clipped_bounds));
3911 }
3912
3913 let result = f(self);
3914
3915 if !clipped_bounds.is_empty() {
3916 self.next_frame.scene.pop_layer();
3917 }
3918
3919 result
3920 }
3921
3922 pub fn paint_drop_shadows(
3928 &mut self,
3929 bounds: Bounds<Pixels>,
3930 corner_radii: Corners<Pixels>,
3931 shadows: &[BoxShadow],
3932 ) {
3933 self.invalidator.debug_assert_paint();
3934
3935 let scale_factor = self.scale_factor();
3936 let content_mask = self.snapped_content_mask();
3937 let opacity = self.element_opacity();
3938 let element_bounds = self.cover_bounds(bounds);
3939 let element_corner_radii = corner_radii.scale(scale_factor);
3940 for shadow in shadows {
3941 if shadow.inset {
3942 continue;
3943 }
3944 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3945 self.next_frame.scene.insert_primitive(Shadow {
3946 order: 0,
3947 blur_radius: shadow.blur_radius.scale(scale_factor),
3948 bounds: self.cover_bounds(shadow_bounds),
3949 content_mask,
3950 corner_radii: corner_radii.scale(scale_factor),
3951 color: shadow.color.opacity(opacity),
3952 element_bounds,
3953 element_corner_radii,
3954 inset: 0,
3955 pad: 0,
3956 });
3957 }
3958 }
3959
3960 pub fn paint_inset_shadows(
3964 &mut self,
3965 bounds: Bounds<Pixels>,
3966 corner_radii: Corners<Pixels>,
3967 shadows: &[BoxShadow],
3968 ) {
3969 self.invalidator.debug_assert_paint();
3970
3971 let scale_factor = self.scale_factor();
3972 let content_mask = self.snapped_content_mask();
3973 let opacity = self.element_opacity();
3974 let element_bounds = self.cover_bounds(bounds);
3975 let element_corner_radii = corner_radii.scale(scale_factor);
3976 for shadow in shadows {
3977 if !shadow.inset {
3978 continue;
3979 }
3980 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
3981 let zero = Pixels::ZERO;
3984 let hole_corner_radii = Corners {
3985 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
3986 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
3987 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
3988 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
3989 };
3990 self.next_frame.scene.insert_primitive(Shadow {
3991 order: 0,
3992 blur_radius: shadow.blur_radius.scale(scale_factor),
3993 bounds: self.cover_bounds(hole),
3994 content_mask,
3995 corner_radii: hole_corner_radii.scale(scale_factor),
3996 color: shadow.color.opacity(opacity),
3997 element_bounds,
3998 element_corner_radii,
3999 inset: 1,
4000 pad: 0,
4001 });
4002 }
4003 }
4004
4005 pub fn paint_quad(&mut self, quad: PaintQuad) {
4015 self.invalidator.debug_assert_paint();
4016
4017 let opacity = self.element_opacity();
4018 let snapped_bounds = self.snap_bounds(quad.bounds);
4019 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
4020 let quad = Quad {
4021 order: 0,
4022 bounds: snapped_bounds,
4023 content_mask: self.snapped_content_mask(),
4024 background: quad.background.opacity(opacity),
4025 border_color: quad.border_color.opacity(opacity),
4026 corner_radii: quad.corner_radii.scale(self.scale_factor()),
4027 border_widths: snapped_border_widths,
4028 border_style: quad.border_style,
4029 };
4030
4031 if !quad.background.is_transparent() {
4032 self.next_frame.scene.insert_primitive(quad);
4033 return;
4034 }
4035
4036 let radii = &quad.corner_radii;
4042 let widths = &quad.border_widths;
4043
4044 let antialias_slack = point(ScaledPixels(1.0), ScaledPixels(1.0));
4045 let top_left_inset = point(
4046 widths.left,
4047 widths.top.max(radii.top_left).max(radii.top_right),
4048 ) + antialias_slack;
4049 let bottom_right_inset = point(
4050 widths.right,
4051 widths.bottom.max(radii.bottom_left).max(radii.bottom_right),
4052 ) + antialias_slack;
4053
4054 let outer_bounds = quad.bounds;
4055 let inner_bounds = Bounds::from_corners(
4056 outer_bounds.origin + top_left_inset,
4057 outer_bounds.bottom_right() - bottom_right_inset,
4058 );
4059
4060 if inner_bounds.is_empty() {
4061 self.next_frame.scene.insert_primitive(quad);
4062 return;
4063 }
4064
4065 let strips = [
4066 Bounds::from_corners(
4068 outer_bounds.origin,
4069 point(outer_bounds.right(), inner_bounds.top()),
4070 ),
4071 Bounds::from_corners(
4073 point(outer_bounds.left(), inner_bounds.bottom()),
4074 outer_bounds.bottom_right(),
4075 ),
4076 Bounds::from_corners(
4078 point(outer_bounds.left(), inner_bounds.top()),
4079 inner_bounds.bottom_left(),
4080 ),
4081 Bounds::from_corners(
4083 inner_bounds.top_right(),
4084 point(outer_bounds.right(), inner_bounds.bottom()),
4085 ),
4086 ];
4087
4088 for strip in strips {
4089 let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
4090 if !content_mask_bounds.is_empty() {
4091 self.next_frame.scene.insert_primitive(Quad {
4092 content_mask: ContentMask {
4093 bounds: content_mask_bounds,
4094 },
4095 ..quad
4096 });
4097 }
4098 }
4099 }
4100
4101 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
4105 self.invalidator.debug_assert_paint();
4106
4107 let scale_factor = self.scale_factor();
4108 let content_mask = self.content_mask();
4109 let opacity = self.element_opacity();
4110 path.content_mask = content_mask;
4111 let color: Background = color.into();
4112 path.color = color.opacity(opacity);
4113 self.next_frame
4114 .scene
4115 .insert_primitive(path.scale(scale_factor));
4116 }
4117
4118 pub fn paint_underline(
4122 &mut self,
4123 origin: Point<Pixels>,
4124 width: Pixels,
4125 style: &UnderlineStyle,
4126 ) {
4127 self.invalidator.debug_assert_paint();
4128
4129 let scale_factor = self.scale_factor();
4130 let thickness = self.snap_stroke(style.thickness);
4131 let height = if style.wavy {
4132 ScaledPixels(thickness.0 * 3.)
4133 } else {
4134 thickness
4135 };
4136 let bounds = Bounds {
4137 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4138 size: size(self.snap_stroke(width), height),
4139 };
4140 let element_opacity = self.element_opacity();
4141
4142 self.next_frame.scene.insert_primitive(Underline {
4143 order: 0,
4144 pad: 0,
4145 bounds,
4146 content_mask: self.snapped_content_mask(),
4147 color: style.color.unwrap_or_default().opacity(element_opacity),
4148 thickness,
4149 wavy: style.wavy.into(),
4150 });
4151 }
4152
4153 pub fn paint_strikethrough(
4157 &mut self,
4158 origin: Point<Pixels>,
4159 width: Pixels,
4160 style: &StrikethroughStyle,
4161 ) {
4162 self.invalidator.debug_assert_paint();
4163
4164 let scale_factor = self.scale_factor();
4165 let height = style.thickness;
4166 let bounds = Bounds {
4167 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4168 size: size(self.snap_stroke(width), self.snap_stroke(height)),
4169 };
4170 let opacity = self.element_opacity();
4171
4172 self.next_frame.scene.insert_primitive(Underline {
4173 order: 0,
4174 pad: 0,
4175 bounds,
4176 content_mask: self.snapped_content_mask(),
4177 thickness: self.snap_stroke(style.thickness),
4178 color: style.color.unwrap_or_default().opacity(opacity),
4179 wavy: false.into(),
4180 });
4181 }
4182
4183 pub fn paint_glyph(
4192 &mut self,
4193 origin: Point<Pixels>,
4194 font_id: FontId,
4195 glyph_id: GlyphId,
4196 font_size: Pixels,
4197 color: Hsla,
4198 ) -> Result<()> {
4199 self.invalidator.debug_assert_paint();
4200
4201 let element_opacity = self.element_opacity();
4202 let scale_factor = self.scale_factor();
4203 let glyph_origin = origin.scale(scale_factor);
4204
4205 let quantized_origin = Point::new(
4206 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
4207 / SUBPIXEL_VARIANTS_X as f32,
4208 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
4209 / SUBPIXEL_VARIANTS_Y as f32,
4210 );
4211 let subpixel_variant = Point::new(
4212 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
4213 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
4214 );
4215 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
4216 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
4217 let dilation = self.text_system().glyph_dilation_for_color(color);
4218 let params = RenderGlyphParams {
4219 font_id,
4220 glyph_id,
4221 font_size,
4222 subpixel_variant,
4223 scale_factor,
4224 is_emoji: false,
4225 subpixel_rendering,
4226 dilation,
4227 };
4228
4229 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4230 if !raster_bounds.is_zero() {
4231 let tile = self
4232 .sprite_atlas
4233 .get_or_insert_with(¶ms.clone().into(), &mut || {
4234 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4235 Ok(Some((size, Cow::Owned(bytes))))
4236 })?
4237 .expect("Callback above only errors or returns Some");
4238 let bounds = Bounds {
4239 origin: integer_origin + raster_bounds.origin.map(Into::into),
4240 size: tile.bounds.size.map(Into::into),
4241 };
4242 let content_mask = self.snapped_content_mask();
4243
4244 if subpixel_rendering {
4245 self.next_frame.scene.insert_primitive(SubpixelSprite {
4246 order: 0,
4247 pad: 0,
4248 bounds,
4249 content_mask,
4250 color: color.opacity(element_opacity),
4251 tile,
4252 transformation: TransformationMatrix::unit(),
4253 });
4254 } else {
4255 self.next_frame.scene.insert_primitive(MonochromeSprite {
4256 order: 0,
4257 pad: 0,
4258 bounds,
4259 content_mask,
4260 color: color.opacity(element_opacity),
4261 tile,
4262 transformation: TransformationMatrix::unit(),
4263 });
4264 }
4265 }
4266 Ok(())
4267 }
4268
4269 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
4270 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
4271 return false;
4272 }
4273
4274 if !self.platform_window.is_subpixel_rendering_supported() {
4275 return false;
4276 }
4277
4278 let mode = match self.text_rendering_mode.get() {
4279 TextRenderingMode::PlatformDefault => self
4280 .text_system()
4281 .recommended_rendering_mode(font_id, font_size),
4282 mode => mode,
4283 };
4284
4285 mode == TextRenderingMode::Subpixel
4286 }
4287
4288 pub fn paint_emoji(
4297 &mut self,
4298 origin: Point<Pixels>,
4299 font_id: FontId,
4300 glyph_id: GlyphId,
4301 font_size: Pixels,
4302 ) -> Result<()> {
4303 self.invalidator.debug_assert_paint();
4304
4305 let scale_factor = self.scale_factor();
4306 let glyph_origin = origin.scale(scale_factor);
4307 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
4308 let params = RenderGlyphParams {
4309 font_id,
4310 glyph_id,
4311 font_size,
4312 subpixel_variant: Default::default(),
4313 scale_factor,
4314 is_emoji: true,
4315 subpixel_rendering: false,
4316 dilation: 0,
4317 };
4318
4319 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4320 if !raster_bounds.is_zero() {
4321 let tile = self
4322 .sprite_atlas
4323 .get_or_insert_with(¶ms.clone().into(), &mut || {
4324 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4325 Ok(Some((size, Cow::Owned(bytes))))
4326 })?
4327 .expect("Callback above only errors or returns Some");
4328
4329 let bounds = Bounds {
4330 origin: integer_origin + raster_bounds.origin.map(Into::into),
4331 size: tile.bounds.size.map(Into::into),
4332 };
4333 let content_mask = self.snapped_content_mask();
4334 let opacity = self.element_opacity();
4335
4336 self.next_frame.scene.insert_primitive(PolychromeSprite {
4337 order: 0,
4338 pad: 0,
4339 grayscale: false.into(),
4340 bounds,
4341 corner_radii: Default::default(),
4342 content_mask,
4343 tile,
4344 opacity,
4345 });
4346 }
4347 Ok(())
4348 }
4349
4350 pub fn paint_svg(
4354 &mut self,
4355 bounds: Bounds<Pixels>,
4356 path: SharedString,
4357 mut data: Option<&[u8]>,
4358 transformation: TransformationMatrix,
4359 color: Hsla,
4360 cx: &App,
4361 ) -> Result<()> {
4362 self.invalidator.debug_assert_paint();
4363
4364 let element_opacity = self.element_opacity();
4365 let bounds = self.snap_bounds(bounds);
4366
4367 let params = RenderSvgParams {
4368 path,
4369 size: bounds.size.map(|pixels| {
4370 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
4371 }),
4372 };
4373
4374 let Some(tile) =
4375 self.sprite_atlas
4376 .get_or_insert_with(¶ms.clone().into(), &mut || {
4377 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
4378 else {
4379 return Ok(None);
4380 };
4381 Ok(Some((size, Cow::Owned(bytes))))
4382 })?
4383 else {
4384 return Ok(());
4385 };
4386 let content_mask = self.snapped_content_mask();
4387 let svg_bounds = Bounds {
4388 origin: bounds.center()
4389 - Point::new(
4390 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4391 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4392 ),
4393 size: tile
4394 .bounds
4395 .size
4396 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
4397 };
4398 let final_bounds = svg_bounds
4399 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
4400 .map_size(|size| size.ceil());
4401
4402 self.next_frame.scene.insert_primitive(MonochromeSprite {
4403 order: 0,
4404 pad: 0,
4405 bounds: final_bounds,
4406 content_mask,
4407 color: color.opacity(element_opacity),
4408 tile,
4409 transformation,
4410 });
4411
4412 Ok(())
4413 }
4414
4415 pub fn paint_image(
4424 &mut self,
4425 bounds: Bounds<Pixels>,
4426 image_bounds: Bounds<Pixels>,
4427 corner_radii: Corners<Pixels>,
4428 data: Arc<RenderImage>,
4429 frame_index: usize,
4430 grayscale: bool,
4431 ) -> Result<()> {
4432 self.invalidator.debug_assert_paint();
4433
4434 let visible_bounds = bounds.intersect(&image_bounds);
4435 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
4436 return Ok(());
4437 }
4438 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
4439 return Ok(());
4440 }
4441
4442 let params = RenderImageParams {
4443 image_id: data.id,
4444 frame_index,
4445 };
4446
4447 let tile = self
4448 .sprite_atlas
4449 .get_or_insert_with(¶ms.into(), &mut || {
4450 Ok(Some((
4451 data.size(frame_index),
4452 Cow::Borrowed(
4453 data.as_bytes(frame_index)
4454 .expect("It's the caller's job to pass a valid frame index"),
4455 ),
4456 )))
4457 })?
4458 .expect("Callback above only returns Some");
4459
4460 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
4461
4462 let sub_tile = if visible_bounds == image_bounds {
4463 tile
4464 } else {
4465 let x_offset_ratio =
4466 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
4467 let y_offset_ratio =
4468 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
4469 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
4470 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
4471
4472 let tile_origin_x = tile.bounds.origin.x.0;
4473 let tile_origin_y = tile.bounds.origin.y.0;
4474 let tile_width = tile.bounds.size.width.0;
4475 let tile_height = tile.bounds.size.height.0;
4476
4477 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
4478 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
4479 let sub_width = (width_ratio * tile_width as f32).round() as i32;
4480 let sub_height = (height_ratio * tile_height as f32).round() as i32;
4481
4482 let max_x = tile_origin_x + tile_width;
4483 let max_y = tile_origin_y + tile_height;
4484
4485 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
4486 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
4487 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
4488 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
4489
4490 AtlasTile {
4491 bounds: Bounds {
4492 origin: point(
4493 DevicePixels(clamped_origin_x),
4494 DevicePixels(clamped_origin_y),
4495 ),
4496 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
4497 },
4498 ..tile
4499 }
4500 };
4501
4502 let content_mask = self.snapped_content_mask();
4503 let corner_radii = corner_radii
4504 .clamp_radii_for_quad_size(visible_bounds.size)
4505 .scale(self.scale_factor());
4506 let opacity = self.element_opacity();
4507
4508 self.next_frame.scene.insert_primitive(PolychromeSprite {
4509 order: 0,
4510 pad: 0,
4511 grayscale: grayscale.into(),
4512 bounds: visible_bounds_snapped,
4513 content_mask,
4514 corner_radii,
4515 tile: sub_tile,
4516 opacity,
4517 });
4518 Ok(())
4519 }
4520
4521 #[cfg(target_os = "macos")]
4525 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
4526 use crate::PaintSurface;
4527
4528 self.invalidator.debug_assert_paint();
4529
4530 let bounds = self.snap_bounds(bounds);
4531 let content_mask = self.snapped_content_mask();
4532 self.next_frame.scene.insert_primitive(PaintSurface {
4533 order: 0,
4534 bounds,
4535 content_mask,
4536 image_buffer,
4537 });
4538 }
4539
4540 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
4542 for frame_index in 0..data.frame_count() {
4543 let params = RenderImageParams {
4544 image_id: data.id,
4545 frame_index,
4546 };
4547
4548 self.sprite_atlas.remove(¶ms.clone().into());
4549 }
4550
4551 Ok(())
4552 }
4553
4554 #[cfg(any(test, feature = "test-support"))]
4556 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
4557 data.frame_count() > 0
4558 && (0..data.frame_count()).all(|frame_index| {
4559 self.sprite_atlas.contains(
4560 &RenderImageParams {
4561 image_id: data.id,
4562 frame_index,
4563 }
4564 .into(),
4565 )
4566 })
4567 }
4568
4569 #[must_use]
4575 pub fn request_layout(
4576 &mut self,
4577 style: Style,
4578 children: impl IntoIterator<Item = LayoutId>,
4579 cx: &mut App,
4580 ) -> LayoutId {
4581 self.invalidator.debug_assert_prepaint();
4582
4583 cx.layout_id_buffer.clear();
4584 cx.layout_id_buffer.extend(children);
4585 let rem_size = self.rem_size();
4586 let scale_factor = self.scale_factor();
4587
4588 self.layout_engine.as_mut().unwrap().request_layout(
4589 style,
4590 rem_size,
4591 scale_factor,
4592 &cx.layout_id_buffer,
4593 )
4594 }
4595
4596 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
4605 where
4606 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
4607 + 'static,
4608 {
4609 self.invalidator.debug_assert_prepaint();
4610
4611 let rem_size = self.rem_size();
4612 let scale_factor = self.scale_factor();
4613 self.layout_engine
4614 .as_mut()
4615 .unwrap()
4616 .request_measured_layout(style, rem_size, scale_factor, measure)
4617 }
4618
4619 pub fn compute_layout(
4625 &mut self,
4626 layout_id: LayoutId,
4627 available_space: Size<AvailableSpace>,
4628 cx: &mut App,
4629 ) {
4630 self.invalidator.debug_assert_prepaint();
4631
4632 let mut layout_engine = self.layout_engine.take().unwrap();
4633 layout_engine.compute_layout(layout_id, available_space, self, cx);
4634 self.layout_engine = Some(layout_engine);
4635 }
4636
4637 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
4642 self.invalidator.debug_assert_prepaint();
4643
4644 let scale_factor = self.scale_factor();
4645 let mut bounds = self
4646 .layout_engine
4647 .as_mut()
4648 .unwrap()
4649 .layout_bounds(layout_id, scale_factor)
4650 .map(Into::into);
4651 let snapped_offset = self.pixel_snap_point(self.element_offset());
4652 bounds.origin += snapped_offset;
4653 bounds
4654 }
4655
4656 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
4662 self.invalidator.debug_assert_prepaint();
4663
4664 let content_mask = self.content_mask();
4665 let mut id = self.next_hitbox_id;
4666 self.next_hitbox_id = self.next_hitbox_id.next();
4667 let hitbox = Hitbox {
4668 id,
4669 bounds,
4670 content_mask,
4671 behavior,
4672 };
4673 self.next_frame.hitboxes.push(hitbox.clone());
4674 hitbox
4675 }
4676
4677 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
4681 self.invalidator.debug_assert_paint();
4682 self.next_frame.window_control_hitboxes.push((area, hitbox));
4683 }
4684
4685 pub fn set_key_context(&mut self, context: KeyContext) {
4690 self.invalidator.debug_assert_paint();
4691 self.next_frame.dispatch_tree.set_key_context(context);
4692 }
4693
4694 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
4699 self.invalidator.debug_assert_prepaint();
4700 if focus_handle.is_focused(self) {
4701 self.next_frame.focus = Some(focus_handle.id);
4702 }
4703 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
4704 }
4705
4706 pub fn set_view_id(&mut self, view_id: EntityId) {
4712 self.invalidator.debug_assert_prepaint();
4713 self.next_frame.dispatch_tree.set_view_id(view_id);
4714 }
4715
4716 pub fn current_view(&self) -> EntityId {
4718 self.invalidator.debug_assert_paint_or_prepaint();
4719 self.rendered_entity_stack.last().copied().unwrap()
4720 }
4721
4722 #[inline]
4723 pub(crate) fn with_rendered_view<R>(
4724 &mut self,
4725 id: EntityId,
4726 f: impl FnOnce(&mut Self) -> R,
4727 ) -> R {
4728 self.rendered_entity_stack.push(id);
4729 let result = f(self);
4730 self.rendered_entity_stack.pop();
4731 result
4732 }
4733
4734 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
4736 where
4737 F: FnOnce(&mut Self) -> R,
4738 {
4739 if let Some(image_cache) = image_cache {
4740 self.image_cache_stack.push(image_cache);
4741 let result = f(self);
4742 self.image_cache_stack.pop();
4743 result
4744 } else {
4745 f(self)
4746 }
4747 }
4748
4749 pub fn handle_input(
4758 &mut self,
4759 focus_handle: &FocusHandle,
4760 input_handler: impl InputHandler,
4761 cx: &App,
4762 ) {
4763 self.invalidator.debug_assert_paint();
4764
4765 if focus_handle.is_focused(self) {
4766 let cx = self.to_async(cx);
4767 self.next_frame
4768 .input_handlers
4769 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
4770 }
4771 }
4772
4773 pub fn on_mouse_event<Event: MouseEvent>(
4779 &mut self,
4780 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4781 ) {
4782 self.invalidator.debug_assert_paint();
4783
4784 self.next_frame.mouse_listeners.push(Some(Box::new(
4785 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
4786 if let Some(event) = event.downcast_ref() {
4787 listener(event, phase, window, cx)
4788 }
4789 },
4790 )));
4791 }
4792
4793 pub fn on_key_event<Event: KeyEvent>(
4802 &mut self,
4803 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4804 ) {
4805 self.invalidator.debug_assert_paint();
4806
4807 self.next_frame.dispatch_tree.on_key_event(Rc::new(
4808 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
4809 if let Some(event) = event.downcast_ref::<Event>() {
4810 listener(event, phase, window, cx)
4811 }
4812 },
4813 ));
4814 }
4815
4816 pub fn on_modifiers_changed(
4823 &mut self,
4824 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
4825 ) {
4826 self.invalidator.debug_assert_paint();
4827
4828 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
4829 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
4830 listener(event, window, cx)
4831 },
4832 ));
4833 }
4834
4835 pub fn on_focus_in(
4839 &mut self,
4840 handle: &FocusHandle,
4841 cx: &mut App,
4842 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
4843 ) -> Subscription {
4844 let focus_id = handle.id;
4845 let (subscription, activate) =
4846 self.new_focus_listener(Box::new(move |event, window, cx| {
4847 if event.is_focus_in(focus_id) {
4848 listener(window, cx);
4849 }
4850 true
4851 }));
4852 cx.defer(move |_| activate());
4853 subscription
4854 }
4855
4856 pub fn on_focus_out(
4859 &mut self,
4860 handle: &FocusHandle,
4861 cx: &mut App,
4862 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
4863 ) -> Subscription {
4864 let focus_id = handle.id;
4865 let (subscription, activate) =
4866 self.new_focus_listener(Box::new(move |event, window, cx| {
4867 if let Some(blurred_id) = event.previous_focus_path.last().copied()
4868 && event.is_focus_out(focus_id)
4869 {
4870 let event = FocusOutEvent {
4871 blurred: WeakFocusHandle {
4872 id: blurred_id,
4873 handles: Arc::downgrade(&cx.focus_handles),
4874 },
4875 };
4876 listener(event, window, cx)
4877 }
4878 true
4879 }));
4880 cx.defer(move |_| activate());
4881 subscription
4882 }
4883
4884 fn reset_cursor_style(&self, cx: &mut App) {
4885 if self.is_window_hovered() {
4887 let style = self
4888 .rendered_frame
4889 .cursor_style(self)
4890 .unwrap_or(CursorStyle::Arrow);
4891 cx.platform.set_cursor_style(style);
4892 }
4893 }
4894
4895 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
4898 let keystroke = keystroke.with_simulated_ime();
4899 let result = self.dispatch_event(
4900 PlatformInput::KeyDown(KeyDownEvent {
4901 keystroke: keystroke.clone(),
4902 is_held: false,
4903 prefer_character_input: false,
4904 }),
4905 cx,
4906 );
4907 if !result.propagate {
4908 return true;
4909 }
4910
4911 if let Some(input) = keystroke.key_char
4912 && let Some(mut input_handler) = self.platform_window.take_input_handler()
4913 {
4914 input_handler.dispatch_input(&input, self, cx);
4915 self.platform_window.set_input_handler(input_handler);
4916 return true;
4917 }
4918
4919 false
4920 }
4921
4922 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
4925 self.highest_precedence_binding_for_action(action)
4926 .map(|binding| {
4927 binding
4928 .keystrokes()
4929 .iter()
4930 .map(ToString::to_string)
4931 .collect::<Vec<_>>()
4932 .join(" ")
4933 })
4934 .unwrap_or_else(|| action.name().to_string())
4935 }
4936
4937 #[profiling::function]
4939 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
4940 #[cfg(feature = "input-latency-histogram")]
4941 let dispatch_time = Instant::now();
4942 let update_count_before = self.invalidator.update_count();
4943 let old_modality = self.last_input_modality;
4947 self.last_input_modality = match &event {
4948 PlatformInput::KeyDown(_) => InputModality::Keyboard,
4949 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
4950 PlatformInput::Touch(_) => InputModality::Touch,
4951 _ => self.last_input_modality,
4952 };
4953 if self.last_input_modality != old_modality {
4954 self.refresh();
4955 }
4956
4957 cx.propagate_event = true;
4959 self.default_prevented = false;
4961
4962 let event = match event {
4963 PlatformInput::MouseMove(mouse_move) => {
4966 self.mouse_position = mouse_move.position;
4967 self.modifiers = mouse_move.modifiers;
4968 PlatformInput::MouseMove(mouse_move)
4969 }
4970 PlatformInput::MouseDown(mouse_down) => {
4971 self.mouse_position = mouse_down.position;
4972 self.modifiers = mouse_down.modifiers;
4973 PlatformInput::MouseDown(mouse_down)
4974 }
4975 PlatformInput::MouseUp(mouse_up) => {
4976 self.mouse_position = mouse_up.position;
4977 self.modifiers = mouse_up.modifiers;
4978 PlatformInput::MouseUp(mouse_up)
4979 }
4980 PlatformInput::MousePressure(mouse_pressure) => {
4981 PlatformInput::MousePressure(mouse_pressure)
4982 }
4983 PlatformInput::MouseExited(mouse_exited) => {
4984 self.modifiers = mouse_exited.modifiers;
4985 PlatformInput::MouseExited(mouse_exited)
4986 }
4987 PlatformInput::ModifiersChanged(modifiers_changed) => {
4988 self.modifiers = modifiers_changed.modifiers;
4989 self.capslock = modifiers_changed.capslock;
4990 PlatformInput::ModifiersChanged(modifiers_changed)
4991 }
4992 PlatformInput::ScrollWheel(scroll_wheel) => {
4993 self.mouse_position = scroll_wheel.position;
4994 self.modifiers = scroll_wheel.modifiers;
4995 PlatformInput::ScrollWheel(scroll_wheel)
4996 }
4997 PlatformInput::Pinch(pinch) => {
4998 self.mouse_position = pinch.position;
4999 self.modifiers = pinch.modifiers;
5000 PlatformInput::Pinch(pinch)
5001 }
5002 PlatformInput::FileDrop(file_drop) => match file_drop {
5005 FileDropEvent::Entered { position, paths } => {
5006 self.mouse_position = position;
5007 let source_window = self.handle.window_id();
5008 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
5009 cx.active_drag = Some(AnyDrag {
5010 value: Arc::new(paths.clone()),
5011 view: cx.new(|_| paths).into(),
5012 cursor_offset: position,
5013 cursor_style: None,
5014 external_payload_source: None,
5015 });
5016 }
5017 PlatformInput::MouseMove(MouseMoveEvent {
5018 position,
5019 pressed_button: Some(MouseButton::Left),
5020 modifiers: Modifiers::default(),
5021 })
5022 }
5023 FileDropEvent::Pending { position } => {
5024 self.mouse_position = position;
5025 PlatformInput::MouseMove(MouseMoveEvent {
5026 position,
5027 pressed_button: Some(MouseButton::Left),
5028 modifiers: Modifiers::default(),
5029 })
5030 }
5031 FileDropEvent::Submit { position } => {
5032 cx.activate(true);
5033 self.mouse_position = position;
5034 PlatformInput::MouseUp(MouseUpEvent {
5035 button: MouseButton::Left,
5036 position,
5037 modifiers: Modifiers::default(),
5038 click_count: 1,
5039 })
5040 }
5041 FileDropEvent::Exited => {
5042 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
5043 cx.active_drag.take();
5044 }
5045 self.refresh();
5046 PlatformInput::FileDrop(FileDropEvent::Exited)
5047 }
5048 FileDropEvent::Ended => {
5049 cx.end_platform_drag(self.handle.window_id());
5050 self.refresh();
5051 PlatformInput::FileDrop(FileDropEvent::Ended)
5052 }
5053 },
5054 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
5055 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
5056 };
5057
5058 if let Some(any_mouse_event) = event.mouse_event() {
5059 self.dispatch_mouse_event(any_mouse_event, cx);
5060 } else if let Some(any_key_event) = event.keyboard_event() {
5061 self.dispatch_key_event(any_key_event, cx);
5062 }
5063
5064 self.promote_external_drag_to_platform(&event, cx);
5067
5068 if self.invalidator.update_count() > update_count_before {
5069 self.input_rate_tracker.borrow_mut().record_input();
5070 #[cfg(feature = "input-latency-histogram")]
5071 if self.invalidator.not_drawing() {
5072 self.input_latency_tracker.record_input(dispatch_time);
5073 } else {
5074 self.input_latency_tracker.record_mid_draw_input();
5075 }
5076 }
5077
5078 DispatchEventResult {
5079 propagate: cx.propagate_event,
5080 default_prevented: self.default_prevented,
5081 }
5082 }
5083
5084 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
5085 let PlatformInput::MouseMove(mouse_move) = event else {
5086 return;
5087 };
5088 if mouse_move.pressed_button != Some(MouseButton::Left) {
5089 return;
5090 }
5091 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
5092 return;
5093 }
5094 if !self.platform_window.can_start_external_drag() {
5095 return;
5096 }
5097 let Some(payload_source) = cx
5098 .active_drag
5099 .as_mut()
5100 .and_then(|drag| drag.external_payload_source.take())
5101 else {
5102 return;
5103 };
5104 let Some(payload) = payload_source(self, cx) else {
5105 return;
5106 };
5107 if self.platform_window.start_external_drag(&payload)
5108 && cx.hand_active_drag_to_platform(self.handle.window_id())
5109 {
5110 self.refresh();
5111 }
5112 }
5113
5114 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5115 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
5116 if hit_test != self.mouse_hit_test {
5117 self.mouse_hit_test = hit_test;
5118 self.reset_cursor_style(cx);
5119 }
5120
5121 #[cfg(any(feature = "inspector", debug_assertions))]
5122 if self.is_inspector_picking(cx) {
5123 self.handle_inspector_mouse_event(event, cx);
5124 return;
5126 }
5127
5128 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
5129
5130 for listener in &mut mouse_listeners {
5133 let listener = listener.as_mut().unwrap();
5134 listener(event, DispatchPhase::Capture, self, cx);
5135 if !cx.propagate_event {
5136 break;
5137 }
5138 }
5139
5140 if cx.propagate_event {
5142 for listener in mouse_listeners.iter_mut().rev() {
5143 let listener = listener.as_mut().unwrap();
5144 listener(event, DispatchPhase::Bubble, self, cx);
5145 if !cx.propagate_event {
5146 break;
5147 }
5148 }
5149 }
5150
5151 self.rendered_frame.mouse_listeners = mouse_listeners;
5152
5153 if cx.has_active_drag() {
5154 if event.is::<MouseMoveEvent>() {
5155 self.refresh();
5158 } else if event.is::<MouseUpEvent>() {
5159 cx.active_drag = None;
5162 self.refresh();
5163 }
5164 }
5165
5166 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
5168 self.captured_hitbox = None;
5169 }
5170 }
5171
5172 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
5173 if self.invalidator.is_dirty() {
5174 self.draw(cx).clear(cx);
5175 }
5176
5177 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5178 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5179
5180 let mut keystroke: Option<Keystroke> = None;
5181
5182 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
5183 if event.modifiers.number_of_modifiers() == 0
5184 && self.pending_modifier.modifiers.number_of_modifiers() == 1
5185 && !self.pending_modifier.saw_other_input
5186 {
5187 let key = match self.pending_modifier.modifiers {
5188 modifiers if modifiers.shift => Some("shift"),
5189 modifiers if modifiers.control => Some("control"),
5190 modifiers if modifiers.alt => Some("alt"),
5191 modifiers if modifiers.platform => Some("platform"),
5192 modifiers if modifiers.function => Some("function"),
5193 _ => None,
5194 };
5195 if let Some(key) = key {
5196 keystroke = Some(Keystroke {
5197 key: key.to_string(),
5198 key_char: None,
5199 modifiers: Modifiers::default(),
5200 });
5201 }
5202 }
5203
5204 if self.pending_modifier.modifiers.number_of_modifiers() == 0
5205 && event.modifiers.number_of_modifiers() == 1
5206 {
5207 self.pending_modifier.saw_other_input = false
5208 } else if event.modifiers.number_of_modifiers() > 1 {
5209 self.pending_modifier.saw_other_input = true
5210 }
5211 self.pending_modifier.modifiers = event.modifiers
5212 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
5213 self.pending_modifier.saw_other_input = true;
5214 keystroke = Some(key_down_event.keystroke.clone());
5215 if key_down_event.keystroke.key_char.is_some()
5216 && matches!(
5217 cx.cursor_hide_mode,
5218 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
5219 )
5220 {
5221 cx.platform.hide_cursor_until_mouse_moves();
5222 }
5223 }
5224
5225 let Some(keystroke) = keystroke else {
5226 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5227 return;
5228 };
5229
5230 cx.propagate_event = true;
5231 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
5232 if !cx.propagate_event {
5233 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5234 return;
5235 }
5236
5237 let mut currently_pending = self.pending_input.take().unwrap_or_default();
5238 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
5239 currently_pending = PendingInput::default();
5240 }
5241
5242 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
5243 currently_pending.keystrokes,
5244 keystroke,
5245 &dispatch_path,
5246 );
5247
5248 if !match_result.to_replay.is_empty() {
5249 self.replay_pending_input(match_result.to_replay, cx);
5250 cx.propagate_event = true;
5251 }
5252
5253 if !match_result.pending.is_empty() {
5254 currently_pending.timer.take();
5255 currently_pending.keystrokes = match_result.pending;
5256 currently_pending.focus = self.focus;
5257
5258 let text_input_requires_timeout = event
5259 .downcast_ref::<KeyDownEvent>()
5260 .filter(|key_down| key_down.keystroke.key_char.is_some())
5261 .and_then(|_| self.platform_window.take_input_handler())
5262 .map_or(false, |mut input_handler| {
5263 let accepts = input_handler.accepts_text_input(self, cx);
5264 self.platform_window.set_input_handler(input_handler);
5265 accepts
5266 });
5267
5268 currently_pending.needs_timeout |=
5269 match_result.pending_has_binding || text_input_requires_timeout;
5270
5271 if currently_pending.needs_timeout {
5272 let generation = Rc::new(());
5273 currently_pending.generation = generation.clone();
5274 currently_pending.timer = Some(self.spawn(cx, async move |cx| {
5275 cx.background_executor.timer(Duration::from_secs(1)).await;
5276 cx.update_if_present(move |window, cx| {
5277 if !window
5278 .pending_input
5279 .as_ref()
5280 .is_some_and(|pending| Rc::ptr_eq(&pending.generation, &generation))
5281 {
5282 return;
5283 }
5284 let Some(currently_pending) = window
5285 .pending_input
5286 .take()
5287 .filter(|pending| pending.focus == window.focus)
5288 else {
5289 return;
5290 };
5291
5292 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
5293 let dispatch_path =
5294 window.rendered_frame.dispatch_tree.dispatch_path(node_id);
5295
5296 let to_replay = window
5297 .rendered_frame
5298 .dispatch_tree
5299 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
5300
5301 window.pending_input_changed(cx);
5302 window.replay_pending_input(to_replay, cx)
5303 })
5304 .log_err();
5305 }));
5306 } else {
5307 currently_pending.timer = None;
5308 }
5309 self.pending_input = Some(currently_pending);
5310 self.pending_input_changed(cx);
5311 cx.propagate_event = false;
5312 return;
5313 }
5314
5315 let skip_bindings = event
5316 .downcast_ref::<KeyDownEvent>()
5317 .filter(|key_down_event| key_down_event.prefer_character_input)
5318 .map(|_| {
5319 self.platform_window
5320 .take_input_handler()
5321 .map_or(false, |mut input_handler| {
5322 let accepts = input_handler.accepts_text_input(self, cx);
5323 self.platform_window.set_input_handler(input_handler);
5324 accepts
5327 })
5328 })
5329 .unwrap_or(false);
5330
5331 if !skip_bindings {
5332 for binding in match_result.bindings {
5333 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5334 if !cx.propagate_event {
5335 self.dispatch_keystroke_observers(
5336 event,
5337 Some(binding.action),
5338 match_result.context_stack,
5339 cx,
5340 );
5341 self.pending_input_changed(cx);
5342 return;
5343 }
5344 }
5345 }
5346
5347 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
5348 self.pending_input_changed(cx);
5349 }
5350
5351 fn finish_dispatch_key_event(
5352 &mut self,
5353 event: &dyn Any,
5354 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
5355 context_stack: Vec<KeyContext>,
5356 cx: &mut App,
5357 ) {
5358 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
5359 if !cx.propagate_event {
5360 return;
5361 }
5362
5363 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
5364 if !cx.propagate_event {
5365 return;
5366 }
5367
5368 self.dispatch_keystroke_observers(event, None, context_stack, cx);
5369 }
5370
5371 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
5372 self.pending_input_observers
5373 .clone()
5374 .retain(&(), |callback| callback(self, cx));
5375 }
5376
5377 fn dispatch_key_down_up_event(
5378 &mut self,
5379 event: &dyn Any,
5380 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5381 cx: &mut App,
5382 ) {
5383 for node_id in dispatch_path {
5385 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5386
5387 for key_listener in node.key_listeners.clone() {
5388 key_listener(event, DispatchPhase::Capture, self, cx);
5389 if !cx.propagate_event {
5390 return;
5391 }
5392 }
5393 }
5394
5395 for node_id in dispatch_path.iter().rev() {
5397 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5399 for key_listener in node.key_listeners.clone() {
5400 key_listener(event, DispatchPhase::Bubble, self, cx);
5401 if !cx.propagate_event {
5402 return;
5403 }
5404 }
5405 }
5406 }
5407
5408 fn dispatch_modifiers_changed_event(
5409 &mut self,
5410 event: &dyn Any,
5411 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5412 cx: &mut App,
5413 ) {
5414 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
5415 return;
5416 };
5417 for node_id in dispatch_path.iter().rev() {
5418 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5419 for listener in node.modifiers_changed_listeners.clone() {
5420 listener(event, self, cx);
5421 if !cx.propagate_event {
5422 return;
5423 }
5424 }
5425 }
5426 }
5427
5428 fn active_pending_input(&self) -> Option<&PendingInput> {
5431 self.pending_input
5432 .as_ref()
5433 .filter(|pending_input| pending_input.focus == self.focus)
5434 }
5435
5436 pub fn has_pending_keystrokes(&self) -> bool {
5438 self.active_pending_input().is_some()
5439 }
5440
5441 pub(crate) fn clear_pending_keystrokes(&mut self) {
5442 self.pending_input.take();
5443 }
5444
5445 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
5447 self.active_pending_input()
5448 .map(|pending_input| pending_input.keystrokes.as_slice())
5449 }
5450
5451 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
5452 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5453 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5454
5455 'replay: for replay in replays {
5456 let event = KeyDownEvent {
5457 keystroke: replay.keystroke.clone(),
5458 is_held: false,
5459 prefer_character_input: true,
5460 };
5461
5462 cx.propagate_event = true;
5463 for binding in replay.bindings {
5464 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5465 if !cx.propagate_event {
5466 self.dispatch_keystroke_observers(
5467 &event,
5468 Some(binding.action),
5469 Vec::default(),
5470 cx,
5471 );
5472 continue 'replay;
5473 }
5474 }
5475
5476 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
5477 if !cx.propagate_event {
5478 continue 'replay;
5479 }
5480 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
5481 && let Some(mut input_handler) = self.platform_window.take_input_handler()
5482 {
5483 input_handler.dispatch_input(&input, self, cx);
5484 self.platform_window.set_input_handler(input_handler)
5485 }
5486 }
5487 }
5488
5489 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
5490 focus_id
5491 .and_then(|focus_id| {
5492 self.rendered_frame
5493 .dispatch_tree
5494 .focusable_node_id(focus_id)
5495 })
5496 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
5497 }
5498
5499 fn dispatch_action_on_node(
5500 &mut self,
5501 node_id: DispatchNodeId,
5502 action: &dyn Action,
5503 cx: &mut App,
5504 ) {
5505 self.dispatch_action_on_node_inner(node_id, action, cx);
5506
5507 if !cx.propagate_event
5508 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
5509 && self.last_input_was_keyboard()
5510 {
5511 cx.platform.hide_cursor_until_mouse_moves();
5512 }
5513 }
5514
5515 fn dispatch_action_on_node_inner(
5516 &mut self,
5517 node_id: DispatchNodeId,
5518 action: &dyn Action,
5519 cx: &mut App,
5520 ) {
5521 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5522
5523 cx.propagate_event = true;
5525 if let Some(mut global_listeners) = cx
5526 .global_action_listeners
5527 .remove(&action.as_any().type_id())
5528 {
5529 for listener in &global_listeners {
5530 profiler::update_running_action(action, cx);
5531 listener(action.as_any(), DispatchPhase::Capture, cx);
5532 profiler::save_action_timing();
5533 if !cx.propagate_event {
5534 break;
5535 }
5536 }
5537
5538 global_listeners.extend(
5539 cx.global_action_listeners
5540 .remove(&action.as_any().type_id())
5541 .unwrap_or_default(),
5542 );
5543
5544 cx.global_action_listeners
5545 .insert(action.as_any().type_id(), global_listeners);
5546 }
5547
5548 if !cx.propagate_event {
5549 return;
5550 }
5551
5552 for node_id in &dispatch_path {
5554 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5555 for DispatchActionListener {
5556 action_type,
5557 listener,
5558 } in node.action_listeners.clone()
5559 {
5560 let any_action = action.as_any();
5561 if action_type == any_action.type_id() {
5562 profiler::update_running_action(action, cx);
5563 listener(any_action, DispatchPhase::Capture, self, cx);
5564 profiler::save_action_timing();
5565
5566 if !cx.propagate_event {
5567 return;
5568 }
5569 }
5570 }
5571 }
5572
5573 for node_id in dispatch_path.iter().rev() {
5575 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5576 for DispatchActionListener {
5577 action_type,
5578 listener,
5579 } in node.action_listeners.clone()
5580 {
5581 let any_action = action.as_any();
5582 if action_type == any_action.type_id() {
5583 cx.propagate_event = false; profiler::update_running_action(action, cx);
5585 listener(any_action, DispatchPhase::Bubble, self, cx);
5586 profiler::save_action_timing();
5587
5588 if !cx.propagate_event {
5589 return;
5590 }
5591 }
5592 }
5593 }
5594
5595 if let Some(mut global_listeners) = cx
5597 .global_action_listeners
5598 .remove(&action.as_any().type_id())
5599 {
5600 for listener in global_listeners.iter().rev() {
5601 cx.propagate_event = false; profiler::update_running_action(action, cx);
5604 listener(action.as_any(), DispatchPhase::Bubble, cx);
5605 profiler::save_action_timing();
5606 if !cx.propagate_event {
5607 break;
5608 }
5609 }
5610
5611 global_listeners.extend(
5612 cx.global_action_listeners
5613 .remove(&action.as_any().type_id())
5614 .unwrap_or_default(),
5615 );
5616
5617 cx.global_action_listeners
5618 .insert(action.as_any().type_id(), global_listeners);
5619 }
5620 }
5621
5622 pub fn observe_global<G: Global>(
5625 &mut self,
5626 cx: &mut App,
5627 f: impl Fn(&mut Window, &mut App) + 'static,
5628 ) -> Subscription {
5629 let window_handle = self.handle;
5630 let (subscription, activate) = cx.global_observers.insert(
5631 TypeId::of::<G>(),
5632 Box::new(move |cx| {
5633 window_handle
5634 .update(cx, |_, window, cx| f(window, cx))
5635 .is_ok()
5636 }),
5637 );
5638 cx.defer(move |_| activate());
5639 subscription
5640 }
5641
5642 pub fn activate_window(&self) {
5644 self.platform_window.activate();
5645 }
5646
5647 pub fn request_attention(&self) {
5649 self.platform_window.request_attention();
5650 }
5651
5652 pub fn minimize_window(&self) {
5654 self.platform_window.minimize();
5655 }
5656
5657 pub fn toggle_fullscreen(&self) {
5659 self.platform_window.toggle_fullscreen();
5660 }
5661
5662 pub fn invalidate_character_coordinates(&self) {
5664 self.on_next_frame(|window, cx| {
5665 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
5666 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
5667 window.platform_window.update_ime_position(bounds);
5668 }
5669 window.platform_window.set_input_handler(input_handler);
5670 }
5671 });
5672 }
5673
5674 pub fn prompt<T>(
5678 &mut self,
5679 level: PromptLevel,
5680 message: &str,
5681 detail: Option<&str>,
5682 answers: &[T],
5683 cx: &mut App,
5684 ) -> oneshot::Receiver<usize>
5685 where
5686 T: Clone + Into<PromptButton>,
5687 {
5688 let prompt_builder = cx.prompt_builder.take();
5689 let Some(prompt_builder) = prompt_builder else {
5690 unreachable!("Re-entrant window prompting is not supported by GPUI");
5691 };
5692
5693 let answers = answers
5694 .iter()
5695 .map(|answer| answer.clone().into())
5696 .collect::<Vec<_>>();
5697
5698 let receiver = match &prompt_builder {
5699 PromptBuilder::Default => self
5700 .platform_window
5701 .prompt(level, message, detail, &answers)
5702 .unwrap_or_else(|| {
5703 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
5704 }),
5705 PromptBuilder::Custom(_) => {
5706 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
5707 }
5708 };
5709
5710 cx.prompt_builder = Some(prompt_builder);
5711
5712 receiver
5713 }
5714
5715 fn build_custom_prompt(
5716 &mut self,
5717 prompt_builder: &PromptBuilder,
5718 level: PromptLevel,
5719 message: &str,
5720 detail: Option<&str>,
5721 answers: &[PromptButton],
5722 cx: &mut App,
5723 ) -> oneshot::Receiver<usize> {
5724 let (sender, receiver) = oneshot::channel();
5725 let handle = PromptHandle::new(sender);
5726 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
5727 self.prompt = Some(handle);
5728 receiver
5729 }
5730
5731 pub fn has_active_prompt(&self) -> bool {
5736 self.prompt.is_some()
5737 }
5738
5739 pub fn context_stack(&self) -> Vec<KeyContext> {
5741 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5742 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5743 dispatch_tree
5744 .dispatch_path(node_id)
5745 .iter()
5746 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
5747 .collect()
5748 }
5749
5750 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
5752 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5753 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
5754 for action_type in cx.global_action_listeners.keys() {
5755 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
5756 let action = cx.actions.build_action_type(action_type).ok();
5757 if let Some(action) = action {
5758 actions.insert(ix, action);
5759 }
5760 }
5761 }
5762 actions
5763 }
5764
5765 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
5768 self.rendered_frame
5769 .dispatch_tree
5770 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
5771 }
5772
5773 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
5776 self.rendered_frame
5777 .dispatch_tree
5778 .highest_precedence_binding_for_action(
5779 action,
5780 &self.rendered_frame.dispatch_tree.context_stack,
5781 )
5782 }
5783
5784 pub fn bindings_for_action_in_context(
5786 &self,
5787 action: &dyn Action,
5788 context: KeyContext,
5789 ) -> Vec<KeyBinding> {
5790 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5791 dispatch_tree.bindings_for_action(action, &[context])
5792 }
5793
5794 pub fn highest_precedence_binding_for_action_in_context(
5797 &self,
5798 action: &dyn Action,
5799 context: KeyContext,
5800 ) -> Option<KeyBinding> {
5801 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5802 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
5803 }
5804
5805 pub fn bindings_for_action_in(
5809 &self,
5810 action: &dyn Action,
5811 focus_handle: &FocusHandle,
5812 ) -> Vec<KeyBinding> {
5813 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5814 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
5815 return vec![];
5816 };
5817 dispatch_tree.bindings_for_action(action, &context_stack)
5818 }
5819
5820 pub fn highest_precedence_binding_for_action_in(
5824 &self,
5825 action: &dyn Action,
5826 focus_handle: &FocusHandle,
5827 ) -> Option<KeyBinding> {
5828 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5829 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
5830 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
5831 }
5832
5833 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
5835 self.rendered_frame
5836 .dispatch_tree
5837 .possible_next_bindings_for_input(input, &self.context_stack())
5838 }
5839
5840 fn context_stack_for_focus_handle(
5841 &self,
5842 focus_handle: &FocusHandle,
5843 ) -> Option<Vec<KeyContext>> {
5844 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5845 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
5846 let context_stack: Vec<_> = dispatch_tree
5847 .dispatch_path(node_id)
5848 .into_iter()
5849 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
5850 .collect();
5851 Some(context_stack)
5852 }
5853
5854 pub fn listener_for<T: 'static, E>(
5856 &self,
5857 view: &Entity<T>,
5858 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
5859 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
5860 let view = view.downgrade();
5861 move |e: &E, window: &mut Window, cx: &mut App| {
5862 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
5863 }
5864 }
5865
5866 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
5868 &self,
5869 entity: &Entity<E>,
5870 f: Callback,
5871 ) -> impl Fn(&mut Window, &mut App) + 'static {
5872 let entity = entity.downgrade();
5873 move |window: &mut Window, cx: &mut App| {
5874 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
5875 }
5876 }
5877
5878 pub fn on_window_should_close(
5881 &self,
5882 cx: &App,
5883 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
5884 ) {
5885 let mut cx = self.to_async(cx);
5886 self.platform_window.on_should_close(Box::new(move || {
5887 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
5888 }))
5889 }
5890
5891 pub fn on_action(
5900 &mut self,
5901 action_type: TypeId,
5902 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5903 ) {
5904 self.invalidator.debug_assert_paint();
5905
5906 self.next_frame
5907 .dispatch_tree
5908 .on_action(action_type, Rc::new(listener));
5909 }
5910
5911 pub fn on_action_when(
5920 &mut self,
5921 condition: bool,
5922 action_type: TypeId,
5923 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5924 ) {
5925 self.invalidator.debug_assert_paint();
5926
5927 if condition {
5928 self.next_frame
5929 .dispatch_tree
5930 .on_action(action_type, Rc::new(listener));
5931 }
5932 }
5933
5934 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
5937 self.platform_window.gpu_specs()
5938 }
5939
5940 pub fn titlebar_double_click(&self) {
5943 self.platform_window
5944 .titlebar_double_click(self.is_resizable, self.is_minimizable);
5945 }
5946
5947 pub fn window_title(&self) -> String {
5950 self.platform_window.get_title()
5951 }
5952
5953 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
5956 self.platform_window.tabbed_windows()
5957 }
5958
5959 pub fn tab_bar_visible(&self) -> bool {
5962 self.platform_window.tab_bar_visible()
5963 }
5964
5965 pub fn merge_all_windows(&self) {
5968 self.platform_window.merge_all_windows()
5969 }
5970
5971 pub fn move_tab_to_new_window(&self) {
5974 self.platform_window.move_tab_to_new_window()
5975 }
5976
5977 pub fn toggle_window_tab_overview(&self) {
5980 self.platform_window.toggle_window_tab_overview()
5981 }
5982
5983 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
5986 self.platform_window
5987 .set_tabbing_identifier(tabbing_identifier)
5988 }
5989
5990 pub fn play_system_bell(&self) {
5993 self.platform_window.play_system_bell()
5994 }
5995
5996 pub fn is_a11y_active(&self) -> bool {
6007 self.a11y.is_active()
6008 }
6009
6010 #[cfg(any(test, feature = "test-support"))]
6017 pub fn enable_a11y_for_testing(&mut self) {
6018 self.a11y.enable_for_test();
6019 self.refresh();
6020 }
6021
6022 pub fn debug_a11y_tree_json(&self) -> Option<String> {
6024 self.a11y.debug_tree_json()
6025 }
6026
6027 pub fn on_a11y_action(
6033 &mut self,
6034 node_id: accesskit::NodeId,
6035 action: accesskit::Action,
6036 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
6037 ) {
6038 self.a11y
6039 .action_listeners
6040 .entry(node_id)
6041 .or_default()
6042 .push((action, Box::new(listener)));
6043 }
6044
6045 #[cfg(not(target_family = "wasm"))]
6046 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
6047 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
6050 let extra_data = request.data.as_ref();
6051 let mut matched = false;
6052 for (action, listener) in &mut listeners {
6053 if *action == request.action {
6054 listener(extra_data, self, cx);
6055 matched = true;
6056 }
6057 }
6058 self.a11y
6059 .action_listeners
6060 .insert(request.target_node, listeners);
6061 if matched {
6062 return;
6063 }
6064 }
6065
6066 match request.action {
6068 accesskit::Action::Click => {
6069 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
6070 let center = bounds.center();
6071 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
6072 button: MouseButton::Left,
6073 position: center,
6074 modifiers: Modifiers::default(),
6075 click_count: 1,
6076 first_mouse: false,
6077 });
6078 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
6079 button: MouseButton::Left,
6080 position: center,
6081 modifiers: Modifiers::default(),
6082 click_count: 1,
6083 });
6084 self.dispatch_event(mouse_down, cx);
6085 self.dispatch_event(mouse_up, cx);
6086 }
6087 }
6088 accesskit::Action::Focus => {
6089 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
6090 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
6091 {
6092 self.focus(&handle, cx);
6093 }
6094 }
6095 accesskit::Action::Blur => {
6096 self.blur();
6097 }
6098 _ => {
6099 log::debug!(
6100 "Unhandled a11y action: {:?} on {:?}",
6101 request.action,
6102 request.target_node
6103 );
6104 }
6105 }
6106 }
6107
6108 #[cfg(any(feature = "inspector", debug_assertions))]
6110 pub fn toggle_inspector(&mut self, cx: &mut App) {
6111 self.inspector = match self.inspector {
6112 None => Some(cx.new(|_| Inspector::new())),
6113 Some(_) => None,
6114 };
6115 self.refresh();
6116 }
6117
6118 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
6120 #[cfg(any(feature = "inspector", debug_assertions))]
6121 {
6122 if let Some(inspector) = &self.inspector {
6123 return inspector.read(_cx).is_picking();
6124 }
6125 }
6126 false
6127 }
6128
6129 #[cfg(any(feature = "inspector", debug_assertions))]
6131 pub fn with_inspector_state<T: 'static, R>(
6132 &mut self,
6133 _inspector_id: Option<&crate::InspectorElementId>,
6134 cx: &mut App,
6135 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
6136 ) -> R {
6137 if let Some(inspector_id) = _inspector_id
6138 && let Some(inspector) = &self.inspector
6139 {
6140 let inspector = inspector.clone();
6141 let active_element_id = inspector.read(cx).active_element_id();
6142 if Some(inspector_id) == active_element_id {
6143 return inspector.update(cx, |inspector, _cx| {
6144 inspector.with_active_element_state(self, f)
6145 });
6146 }
6147 }
6148 f(&mut None, self)
6149 }
6150
6151 #[cfg(any(feature = "inspector", debug_assertions))]
6152 pub(crate) fn build_inspector_element_id(
6153 &mut self,
6154 path: crate::InspectorElementPath,
6155 ) -> crate::InspectorElementId {
6156 self.invalidator.debug_assert_paint_or_prepaint();
6157 let path = Rc::new(path);
6158 let next_instance_id = self
6159 .next_frame
6160 .next_inspector_instance_ids
6161 .entry(path.clone())
6162 .or_insert(0);
6163 let instance_id = *next_instance_id;
6164 *next_instance_id += 1;
6165 crate::InspectorElementId { path, instance_id }
6166 }
6167
6168 #[cfg(any(feature = "inspector", debug_assertions))]
6169 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
6170 if let Some(inspector) = self.inspector.take() {
6171 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
6172 inspector_element.prepaint_as_root(
6173 point(self.viewport_size.width - inspector_width, px(0.0)),
6174 size(inspector_width, self.viewport_size.height).into(),
6175 self,
6176 cx,
6177 );
6178 self.inspector = Some(inspector);
6179 Some(inspector_element)
6180 } else {
6181 None
6182 }
6183 }
6184
6185 #[cfg(any(feature = "inspector", debug_assertions))]
6186 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
6187 if let Some(mut inspector_element) = inspector_element {
6188 inspector_element.paint(self, cx);
6189 };
6190 }
6191
6192 #[cfg(any(feature = "inspector", debug_assertions))]
6195 pub fn insert_inspector_hitbox(
6196 &mut self,
6197 hitbox_id: HitboxId,
6198 inspector_id: Option<&crate::InspectorElementId>,
6199 cx: &App,
6200 ) {
6201 self.invalidator.debug_assert_paint_or_prepaint();
6202 if !self.is_inspector_picking(cx) {
6203 return;
6204 }
6205 if let Some(inspector_id) = inspector_id {
6206 self.next_frame
6207 .inspector_hitboxes
6208 .insert(hitbox_id, inspector_id.clone());
6209 }
6210 }
6211
6212 #[cfg(any(feature = "inspector", debug_assertions))]
6213 fn paint_inspector_hitbox(&mut self, cx: &App) {
6214 if let Some(inspector) = self.inspector.as_ref() {
6215 let inspector = inspector.read(cx);
6216 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
6217 && let Some(hitbox) = self
6218 .next_frame
6219 .hitboxes
6220 .iter()
6221 .find(|hitbox| hitbox.id == hitbox_id)
6222 {
6223 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
6224 }
6225 }
6226 }
6227
6228 #[cfg(any(feature = "inspector", debug_assertions))]
6229 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6230 let Some(inspector) = self.inspector.clone() else {
6231 return;
6232 };
6233 if event.downcast_ref::<MouseMoveEvent>().is_some() {
6234 inspector.update(cx, |inspector, _cx| {
6235 if let Some((_, inspector_id)) =
6236 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6237 {
6238 inspector.hover(inspector_id, self);
6239 }
6240 });
6241 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
6242 inspector.update(cx, |inspector, _cx| {
6243 if let Some((_, inspector_id)) =
6244 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6245 {
6246 inspector.select(inspector_id, self);
6247 }
6248 });
6249 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
6250 const SCROLL_LINES: f32 = 3.0;
6252 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
6253 let delta_y = event
6254 .delta
6255 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
6256 .y;
6257 if let Some(inspector) = self.inspector.clone() {
6258 inspector.update(cx, |inspector, _cx| {
6259 if let Some(depth) = inspector.pick_depth.as_mut() {
6260 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
6261 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
6262 if *depth < 0.0 {
6263 *depth = 0.0;
6264 } else if *depth > max_depth {
6265 *depth = max_depth;
6266 }
6267 if let Some((_, inspector_id)) =
6268 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6269 {
6270 inspector.set_active_element_id(inspector_id, self);
6271 }
6272 }
6273 });
6274 }
6275 }
6276 }
6277
6278 #[cfg(any(feature = "inspector", debug_assertions))]
6279 fn hovered_inspector_hitbox(
6280 &self,
6281 inspector: &Inspector,
6282 frame: &Frame,
6283 ) -> Option<(HitboxId, crate::InspectorElementId)> {
6284 if let Some(pick_depth) = inspector.pick_depth {
6285 let depth = (pick_depth as i64).try_into().unwrap_or(0);
6286 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
6287 let skip_count = (depth as usize).min(max_skipped);
6288 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
6289 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
6290 return Some((*hitbox_id, inspector_id.clone()));
6291 }
6292 }
6293 }
6294 None
6295 }
6296
6297 #[cfg(any(test, feature = "test-support"))]
6300 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
6301 self.modifiers = modifiers;
6302 }
6303
6304 #[cfg(any(test, feature = "test-support"))]
6308 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
6309 let event = PlatformInput::MouseMove(MouseMoveEvent {
6310 position,
6311 modifiers: self.modifiers,
6312 pressed_button: None,
6313 });
6314 let _ = self.dispatch_event(event, cx);
6315 }
6316}
6317
6318slotmap::new_key_type! {
6320 pub struct WindowId;
6322}
6323
6324impl WindowId {
6325 pub fn as_u64(&self) -> u64 {
6327 self.0.as_ffi()
6328 }
6329}
6330
6331impl From<u64> for WindowId {
6332 fn from(value: u64) -> Self {
6333 WindowId(slotmap::KeyData::from_ffi(value))
6334 }
6335}
6336
6337#[derive(Deref, DerefMut)]
6340pub struct WindowHandle<V> {
6341 #[deref]
6342 #[deref_mut]
6343 pub(crate) any_handle: AnyWindowHandle,
6344 state_type: PhantomData<fn(V) -> V>,
6345}
6346
6347impl<V> Debug for WindowHandle<V> {
6348 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6349 f.debug_struct("WindowHandle")
6350 .field("any_handle", &self.any_handle.id.as_u64())
6351 .finish()
6352 }
6353}
6354
6355impl<V: 'static + Render> WindowHandle<V> {
6356 pub fn new(id: WindowId) -> Self {
6359 WindowHandle {
6360 any_handle: AnyWindowHandle {
6361 id,
6362 state_type: TypeId::of::<V>(),
6363 },
6364 state_type: PhantomData,
6365 }
6366 }
6367
6368 #[cfg(any(test, feature = "test-support"))]
6372 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
6373 where
6374 C: AppContext,
6375 {
6376 cx.update_window(self.any_handle, |root_view, _, _| {
6377 root_view
6378 .downcast::<V>()
6379 .map_err(|_| anyhow!("the type of the window's root view has changed"))
6380 })?
6381 }
6382
6383 pub fn update<C, R>(
6387 &self,
6388 cx: &mut C,
6389 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
6390 ) -> Result<R>
6391 where
6392 C: AppContext,
6393 {
6394 cx.update_window(self.any_handle, |root_view, window, cx| {
6395 let view = root_view
6396 .downcast::<V>()
6397 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6398
6399 Ok(view.update(cx, |view, cx| update(view, window, cx)))
6400 })?
6401 }
6402
6403 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
6407 let x = cx
6408 .windows
6409 .get(self.id)
6410 .and_then(|window| {
6411 window
6412 .as_deref()
6413 .and_then(|window| window.root.clone())
6414 .map(|root_view| root_view.downcast::<V>())
6415 })
6416 .context("window not found")?
6417 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6418
6419 Ok(x.read(cx))
6420 }
6421
6422 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
6426 where
6427 C: AppContext,
6428 {
6429 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
6430 }
6431
6432 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
6436 where
6437 C: AppContext,
6438 {
6439 cx.read_window(self, |root_view, _cx| root_view)
6440 }
6441
6442 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
6447 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
6448 .ok()
6449 }
6450}
6451
6452impl<V> Copy for WindowHandle<V> {}
6453
6454impl<V> Clone for WindowHandle<V> {
6455 fn clone(&self) -> Self {
6456 *self
6457 }
6458}
6459
6460impl<V> PartialEq for WindowHandle<V> {
6461 fn eq(&self, other: &Self) -> bool {
6462 self.any_handle == other.any_handle
6463 }
6464}
6465
6466impl<V> Eq for WindowHandle<V> {}
6467
6468impl<V> Hash for WindowHandle<V> {
6469 fn hash<H: Hasher>(&self, state: &mut H) {
6470 self.any_handle.hash(state);
6471 }
6472}
6473
6474impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
6475 fn from(val: WindowHandle<V>) -> Self {
6476 val.any_handle
6477 }
6478}
6479
6480#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
6482pub struct AnyWindowHandle {
6483 pub(crate) id: WindowId,
6484 state_type: TypeId,
6485}
6486
6487impl AnyWindowHandle {
6488 pub fn window_id(&self) -> WindowId {
6490 self.id
6491 }
6492
6493 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
6496 if TypeId::of::<T>() == self.state_type {
6497 Some(WindowHandle {
6498 any_handle: *self,
6499 state_type: PhantomData,
6500 })
6501 } else {
6502 None
6503 }
6504 }
6505
6506 pub fn update<C, R>(
6510 self,
6511 cx: &mut C,
6512 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
6513 ) -> Result<R>
6514 where
6515 C: AppContext,
6516 {
6517 cx.update_window(self, update)
6518 }
6519
6520 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
6524 where
6525 C: AppContext,
6526 T: 'static,
6527 {
6528 let view = self
6529 .downcast::<T>()
6530 .context("the type of the window's root view has changed")?;
6531
6532 cx.read_window(&view, read)
6533 }
6534}
6535
6536impl HasWindowHandle for Window {
6537 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
6538 self.platform_window.window_handle()
6539 }
6540}
6541
6542impl HasDisplayHandle for Window {
6543 fn display_handle(
6544 &self,
6545 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
6546 self.platform_window.display_handle()
6547 }
6548}
6549
6550#[derive(Clone, Debug, Eq, PartialEq, Hash)]
6555pub enum ElementId {
6556 View(EntityId),
6558 Integer(u64),
6560 Name(SharedString),
6562 Uuid(Uuid),
6564 FocusHandle(FocusId),
6566 NamedInteger(SharedString, u64),
6568 Path(Arc<std::path::Path>),
6570 CodeLocation(core::panic::Location<'static>),
6572 NamedChild(Arc<ElementId>, SharedString),
6574 OpaqueId([u8; 20]),
6576}
6577
6578impl ElementId {
6579 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
6581 Self::NamedInteger(name.into(), integer as u64)
6582 }
6583}
6584
6585impl Display for ElementId {
6586 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6587 match self {
6588 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
6589 ElementId::Integer(ix) => write!(f, "{}", ix)?,
6590 ElementId::Name(name) => write!(f, "{}", name)?,
6591 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
6592 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
6593 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
6594 ElementId::Path(path) => write!(f, "{}", path.display())?,
6595 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
6596 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
6597 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
6598 }
6599
6600 Ok(())
6601 }
6602}
6603
6604impl TryInto<SharedString> for ElementId {
6605 type Error = anyhow::Error;
6606
6607 fn try_into(self) -> anyhow::Result<SharedString> {
6608 if let ElementId::Name(name) = self {
6609 Ok(name)
6610 } else {
6611 anyhow::bail!("element id is not string")
6612 }
6613 }
6614}
6615
6616impl From<usize> for ElementId {
6617 fn from(id: usize) -> Self {
6618 ElementId::Integer(id as u64)
6619 }
6620}
6621
6622impl From<i32> for ElementId {
6623 fn from(id: i32) -> Self {
6624 Self::Integer(id as u64)
6625 }
6626}
6627
6628impl From<SharedString> for ElementId {
6629 fn from(name: SharedString) -> Self {
6630 ElementId::Name(name)
6631 }
6632}
6633
6634impl From<String> for ElementId {
6635 fn from(name: String) -> Self {
6636 ElementId::Name(name.into())
6637 }
6638}
6639
6640impl From<Arc<str>> for ElementId {
6641 fn from(name: Arc<str>) -> Self {
6642 ElementId::Name(name.into())
6643 }
6644}
6645
6646impl From<Arc<std::path::Path>> for ElementId {
6647 fn from(path: Arc<std::path::Path>) -> Self {
6648 ElementId::Path(path)
6649 }
6650}
6651
6652impl From<&'static str> for ElementId {
6653 fn from(name: &'static str) -> Self {
6654 ElementId::Name(SharedString::new_static(name))
6655 }
6656}
6657
6658impl<'a> From<&'a FocusHandle> for ElementId {
6659 fn from(handle: &'a FocusHandle) -> Self {
6660 ElementId::FocusHandle(handle.id)
6661 }
6662}
6663
6664impl From<(&'static str, EntityId)> for ElementId {
6665 fn from((name, id): (&'static str, EntityId)) -> Self {
6666 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
6667 }
6668}
6669
6670impl From<(&'static str, usize)> for ElementId {
6671 fn from((name, id): (&'static str, usize)) -> Self {
6672 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
6673 }
6674}
6675
6676impl From<(SharedString, usize)> for ElementId {
6677 fn from((name, id): (SharedString, usize)) -> Self {
6678 ElementId::NamedInteger(name, id as u64)
6679 }
6680}
6681
6682impl From<(&'static str, u64)> for ElementId {
6683 fn from((name, id): (&'static str, u64)) -> Self {
6684 ElementId::NamedInteger(SharedString::new_static(name), id)
6685 }
6686}
6687
6688impl From<Uuid> for ElementId {
6689 fn from(value: Uuid) -> Self {
6690 Self::Uuid(value)
6691 }
6692}
6693
6694impl From<(&'static str, u32)> for ElementId {
6695 fn from((name, id): (&'static str, u32)) -> Self {
6696 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
6697 }
6698}
6699
6700impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
6701 fn from((id, name): (ElementId, T)) -> Self {
6702 ElementId::NamedChild(Arc::new(id), name.into())
6703 }
6704}
6705
6706impl From<&'static core::panic::Location<'static>> for ElementId {
6707 fn from(location: &'static core::panic::Location<'static>) -> Self {
6708 ElementId::CodeLocation(*location)
6709 }
6710}
6711
6712impl From<[u8; 20]> for ElementId {
6713 fn from(opaque_id: [u8; 20]) -> Self {
6714 ElementId::OpaqueId(opaque_id)
6715 }
6716}
6717
6718#[derive(Clone)]
6721pub struct PaintQuad {
6722 pub bounds: Bounds<Pixels>,
6724 pub corner_radii: Corners<Pixels>,
6726 pub background: Background,
6728 pub border_widths: Edges<Pixels>,
6730 pub border_color: Hsla,
6732 pub border_style: BorderStyle,
6734}
6735
6736impl PaintQuad {
6737 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
6739 PaintQuad {
6740 corner_radii: corner_radii.into(),
6741 ..self
6742 }
6743 }
6744
6745 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
6747 PaintQuad {
6748 border_widths: border_widths.into(),
6749 ..self
6750 }
6751 }
6752
6753 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
6755 PaintQuad {
6756 border_color: border_color.into(),
6757 ..self
6758 }
6759 }
6760
6761 pub fn background(self, background: impl Into<Background>) -> Self {
6763 PaintQuad {
6764 background: background.into(),
6765 ..self
6766 }
6767 }
6768}
6769
6770pub fn quad(
6772 bounds: Bounds<Pixels>,
6773 corner_radii: impl Into<Corners<Pixels>>,
6774 background: impl Into<Background>,
6775 border_widths: impl Into<Edges<Pixels>>,
6776 border_color: impl Into<Hsla>,
6777 border_style: BorderStyle,
6778) -> PaintQuad {
6779 PaintQuad {
6780 bounds,
6781 corner_radii: corner_radii.into(),
6782 background: background.into(),
6783 border_widths: border_widths.into(),
6784 border_color: border_color.into(),
6785 border_style,
6786 }
6787}
6788
6789pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
6791 PaintQuad {
6792 bounds: bounds.into(),
6793 corner_radii: (0.).into(),
6794 background: background.into(),
6795 border_widths: (0.).into(),
6796 border_color: transparent_black(),
6797 border_style: BorderStyle::default(),
6798 }
6799}
6800
6801pub fn outline(
6803 bounds: impl Into<Bounds<Pixels>>,
6804 border_color: impl Into<Hsla>,
6805 border_style: BorderStyle,
6806) -> PaintQuad {
6807 PaintQuad {
6808 bounds: bounds.into(),
6809 corner_radii: (0.).into(),
6810 background: transparent_black().into(),
6811 border_widths: (1.).into(),
6812 border_color: border_color.into(),
6813 border_style,
6814 }
6815}
6816
6817#[cfg(test)]
6818mod tests {
6819 use std::{
6820 cell::{Cell, RefCell},
6821 path::PathBuf,
6822 rc::Rc,
6823 };
6824
6825 use crate::{
6826 AnyWindowHandle, AppContext as _, Bounds, Context, DragMoveEvent, Empty,
6827 ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle,
6828 InputEvent as _, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,
6829 MouseMoveEvent, ParentElement, Pixels, Point, Render, StatefulInteractiveElement as _,
6830 Styled, TestAppContext, Window, WindowAppearance, WindowOptions, canvas, div, point, px,
6831 size,
6832 };
6833
6834 #[gpui::test]
6835 fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
6836 let window = cx.add_window(|_, _| crate::EmptyView);
6837 let platform_window = cx.test_window(window.into());
6838 {
6839 let app = cx.app.borrow_mut();
6840 platform_window.simulate_close();
6841 assert!(app.windows.contains_key(window.window_id()));
6842 }
6843 cx.run_until_parked();
6844 assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
6845 }
6846
6847 #[gpui::test]
6848 fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
6849 struct Child {
6850 renders: usize,
6851 }
6852
6853 impl Render for Child {
6854 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6855 self.renders += 1;
6856 div().size_full().bg(crate::rgb(0xff0000))
6857 }
6858 }
6859
6860 struct Root {
6861 opacity: f32,
6862 width: Pixels,
6863 child: crate::Entity<Child>,
6864 }
6865
6866 impl Render for Root {
6867 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6868 div()
6869 .w(self.width)
6870 .h(px(200.))
6871 .opacity(self.opacity)
6872 .hover(|style| style.opacity(1.))
6873 .child(
6874 self.child
6875 .clone()
6876 .cached(crate::StyleRefinement::default().size(px(100.))),
6877 )
6878 }
6879 }
6880
6881 fn update_and_draw(
6884 window: crate::WindowHandle<Root>,
6885 child: &crate::Entity<Child>,
6886 cx: &mut TestAppContext,
6887 update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
6888 ) -> (f32, usize) {
6889 window
6890 .update(cx, |root, window, cx| {
6891 update(root, window, cx);
6892 cx.notify();
6893 })
6894 .expect("update root");
6895 for _ in 0..3 {
6896 let (alpha, renders, requested_frames) = cx
6897 .update_window(window.into(), |_, window, cx| {
6898 window.draw(cx).clear(cx);
6899 let quads = &window.rendered_frame.scene.quads;
6900 assert_eq!(quads.len(), 1);
6901 let alpha = quads.first().expect("child quad").background.solid.a;
6902 (
6903 alpha,
6904 child.read(cx).renders,
6905 window.simulate_next_frame(cx),
6906 )
6907 })
6908 .expect("draw window");
6909 if requested_frames == 0 {
6910 return (alpha, renders);
6911 }
6912 }
6913 panic!("cached child kept requesting frames");
6914 }
6915
6916 let child = cx.new(|_| Child { renders: 0 });
6917 let window = cx.add_window(|_, _| Root {
6918 opacity: 1.,
6919 width: px(200.),
6920 child: child.clone(),
6921 });
6922 let outside = point(px(500.), px(500.));
6923 let inside = point(px(50.), px(50.));
6924 let beside = point(px(250.), px(50.));
6925
6926 let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
6928 window.simulate_mouse_move(outside, cx)
6929 };
6930 assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
6931 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
6932 let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
6933 assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
6934 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
6935
6936 let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
6938 window.simulate_mouse_move(inside, cx)
6939 };
6940 assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
6941 let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
6942 window.simulate_mouse_move(beside, cx)
6943 };
6944 assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
6945
6946 let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
6949 assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
6950 }
6951 #[gpui::test]
6952 fn bordered_scroll_panes_preserve_bounds_at_fractional_scales(cx: &mut TestAppContext) {
6953 struct Panes {
6954 scroll: [crate::ScrollHandle; 2],
6955 }
6956 impl Render for Panes {
6957 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6958 div()
6959 .size_full()
6960 .flex()
6961 .flex_col()
6962 .child(
6963 div()
6964 .flex()
6965 .flex_1()
6966 .min_h_0()
6967 .children((0..2).map(|index| {
6968 div()
6969 .flex()
6970 .flex_col()
6971 .flex_1()
6972 .min_w_0()
6973 .h_full()
6974 .border_1()
6975 .border_color(crate::rgb(0xffcc00))
6976 .bg(crate::rgb(0x18202a))
6977 .child(
6978 div().h(px(32.5)).flex_shrink_0().bg(crate::rgb(0x00ff00)),
6979 )
6980 .child(
6981 div()
6982 .id(index)
6983 .flex_1()
6984 .min_h_0()
6985 .overflow_y_scroll()
6986 .track_scroll(&self.scroll[index])
6987 .child(div().h(px(2400.25)).bg(crate::rgb(0xff0000))),
6988 )
6989 })),
6990 )
6991 .child(div().h(px(40.5)).flex_shrink_0().bg(crate::rgb(0x0000ff)))
6992 }
6993 }
6994 let scroll = [crate::ScrollHandle::new(), crate::ScrollHandle::new()];
6995 let handle = cx.add_window(|_, _| Panes {
6996 scroll: scroll.clone(),
6997 });
6998 for scale in [1., 1.25, 1.5, 2.] {
6999 cx.simulate_window_scale_factor_change(handle.into(), scale);
7000 for viewport in [size(px(800.), px(600.)), size(px(641.5), px(481.25))] {
7001 cx.simulate_window_resize(handle.into(), viewport);
7002 for offset in [0., -180.25] {
7003 scroll[0].set_offset(point(px(0.), px(offset)));
7004 cx.update_window(handle.into(), |_, window, cx| {
7005 window.refresh();
7006 window.draw(cx).clear(cx);
7007 let quads = &window.rendered_frame.scene.quads;
7008 let strips: Vec<_> = quads
7009 .iter()
7010 .filter(|q| q.border_color == crate::rgb(0xffcc00).into())
7011 .collect();
7012 assert_eq!(strips.len(), 8);
7013 let borders: Vec<_> = strips
7014 .chunks_exact(4)
7015 .map(|group| {
7016 let mut border = *group[0];
7017 for strip in &group[1..] {
7018 assert_eq!(strip.bounds, border.bounds);
7019 border.content_mask.bounds = border
7020 .content_mask
7021 .bounds
7022 .union(&strip.content_mask.bounds);
7023 }
7024 border
7025 })
7026 .collect();
7027 let bodies: Vec<_> = quads
7028 .iter()
7029 .filter(|q| q.background.solid == crate::rgb(0xff0000).into())
7030 .collect();
7031 let footer = quads
7032 .iter()
7033 .find(|q| q.background.solid == crate::rgb(0x0000ff).into())
7034 .unwrap();
7035 assert_eq!(borders.len(), 2);
7036 assert_eq!(bodies.len(), 2);
7037 assert_eq!(borders[0].bounds.top(), borders[1].bounds.top());
7038 assert_eq!(borders[0].bounds.bottom(), borders[1].bounds.bottom());
7039 assert_eq!(borders[0].bounds.right(), borders[1].bounds.left());
7040 assert_eq!(borders[0].bounds.bottom(), footer.bounds.top());
7041 for (border, body) in borders.iter().zip(&bodies) {
7042 assert!(border.content_mask.bounds.contains(&border.bounds.origin));
7043 assert!(border.content_mask.bounds.bottom() >= border.bounds.bottom());
7044 let visible_body = body.bounds.intersect(&body.content_mask.bounds);
7047 assert!(
7048 visible_body.bottom()
7049 <= border.bounds.bottom() - border.border_widths.bottom
7050 );
7051 assert!(
7052 visible_body.left()
7053 >= border.bounds.left() + border.border_widths.left
7054 );
7055 assert!(
7056 visible_body.right()
7057 <= border.bounds.right() - border.border_widths.right
7058 );
7059 }
7060 })
7061 .unwrap();
7062 assert!(scroll[0].max_offset().y > px(0.));
7063 assert!(scroll[1].max_offset().y > px(0.));
7064 assert_eq!(scroll[1].offset().y, px(0.));
7065 }
7066 }
7067 }
7068 }
7069
7070 #[test]
7071 fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
7072 let mut cx = TestAppContext::single();
7073 let window = cx.add_window(|_, _| crate::EmptyView);
7074 let handle: AnyWindowHandle = window.into();
7075 let window_state = |cx: &mut TestAppContext| {
7076 cx.update_window(handle, |_, window, _| {
7077 (
7078 window.scale_factor(),
7079 window.bounds(),
7080 window.viewport_size(),
7081 )
7082 })
7083 .unwrap()
7084 };
7085
7086 let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
7087 assert_eq!(scale_factor, 2.0);
7088
7089 for (scale_factor, resized_size) in [
7090 (1.0, size(px(800.), px(600.))),
7091 (1.25, size(px(640.), px(480.))),
7092 (2.0, size(px(1024.), px(768.))),
7093 ] {
7094 cx.simulate_window_scale_factor_change(handle, scale_factor);
7095 assert_eq!(
7096 window_state(&mut cx),
7097 (scale_factor, expected_bounds, expected_bounds.size)
7098 );
7099
7100 cx.simulate_window_resize(handle, resized_size);
7101 expected_bounds.size = resized_size;
7102 assert_eq!(
7103 window_state(&mut cx),
7104 (scale_factor, expected_bounds, resized_size)
7105 );
7106 }
7107 }
7108
7109 struct AccessibilityFocusFixture {
7110 focus: FocusHandle,
7111 duplicate: bool,
7112 }
7113
7114 impl Render for AccessibilityFocusFixture {
7115 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7116 let mut outer = div().id("dialog-owner").role(accesskit::Role::Dialog);
7117 if self.duplicate {
7118 outer = outer.track_focus(&self.focus);
7119 }
7120 outer.child(
7121 div()
7122 .id("input-owner")
7123 .role(accesskit::Role::TextInput)
7124 .track_focus(&self.focus),
7125 )
7126 }
7127 }
7128
7129 fn draw_accessibility_fixture(cx: &mut TestAppContext, duplicate: bool) -> String {
7130 let (_, cx) = cx.add_window_view(|window, cx| {
7131 let focus = cx.focus_handle();
7132 focus.focus(window, cx);
7133 AccessibilityFocusFixture { focus, duplicate }
7134 });
7135 cx.update(|window, _| window.enable_a11y_for_testing());
7136 cx.run_until_parked();
7137 cx.update(|window, _| {
7138 window
7139 .debug_a11y_tree_json()
7140 .expect("accessibility tree was built")
7141 })
7142 }
7143
7144 #[gpui::test]
7145 fn accessibility_tree_can_be_built_without_native_adapter(cx: &mut TestAppContext) {
7146 let tree = draw_accessibility_fixture(cx, false);
7147 let tree: serde_json::Value = serde_json::from_str(&tree).unwrap();
7148 let focus = tree["gpui_focus"].as_str().expect("focused node");
7149 #[cfg(debug_assertions)]
7150 assert!(
7151 tree["nodes"][focus]["element_id"]
7152 .as_str()
7153 .unwrap()
7154 .contains("input-owner")
7155 );
7156 assert_eq!(tree["nodes"].as_object().unwrap().len(), 3);
7157 }
7158
7159 #[gpui::test]
7160 #[cfg(debug_assertions)]
7161 #[should_panic(expected = "second node")]
7162 fn nested_duplicate_focus_is_detected_in_component_tests(cx: &mut TestAppContext) {
7163 draw_accessibility_fixture(cx, true);
7164 }
7165
7166 struct EmptyView;
7167
7168 impl Render for EmptyView {
7169 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7170 div()
7171 }
7172 }
7173
7174 crate::actions!(pending_timeout_regression, [TimeoutAction]);
7175
7176 struct PendingView {
7177 focus: FocusHandle,
7178 dispatched: Rc<Cell<usize>>,
7179 }
7180
7181 impl Render for PendingView {
7182 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7183 let dispatched = self.dispatched.clone();
7184 div()
7185 .track_focus(&self.focus)
7186 .on_action(move |_: &TimeoutAction, _, _| {
7187 dispatched.set(dispatched.get() + 1);
7188 })
7189 }
7190 }
7191
7192 #[gpui::test]
7193 fn stale_pending_timeout_does_not_consume_replacement(cx: &mut TestAppContext) {
7194 use crate::{KeyBinding, KeyDownEvent, Keystroke, PlatformInput};
7195 use std::time::Duration;
7196 let dispatched = Rc::new(Cell::new(0));
7197 cx.update(|cx| {
7198 cx.bind_keys([
7199 KeyBinding::new("ctrl-k", TimeoutAction, None),
7200 KeyBinding::new("ctrl-k ctrl-c", TimeoutAction, None),
7201 ])
7202 });
7203 let window = cx.add_window(|window, cx| {
7204 let focus = cx.focus_handle();
7205 window.focus(&focus, cx);
7206 PendingView {
7207 focus,
7208 dispatched: dispatched.clone(),
7209 }
7210 });
7211 let send_prefix = |window: &mut Window, cx: &mut crate::App| {
7212 window.dispatch_event(
7213 PlatformInput::KeyDown(KeyDownEvent {
7214 keystroke: Keystroke::parse("ctrl-k").unwrap(),
7215 is_held: false,
7216 prefer_character_input: false,
7217 }),
7218 cx,
7219 );
7220 };
7221 let _stale = cx
7222 .update_window(window.into(), |_, window, cx| {
7223 send_prefix(window, cx);
7224 window.pending_input.as_mut().unwrap().timer.take().unwrap()
7227 })
7228 .unwrap();
7229 cx.executor().advance_clock(Duration::from_millis(500));
7230 cx.update_window(window.into(), |_, window, cx| send_prefix(window, cx))
7231 .unwrap();
7232 assert_eq!(dispatched.get(), 1);
7233 cx.executor().advance_clock(Duration::from_millis(500));
7234 cx.run_until_parked();
7235 window
7236 .update(cx, |_, window, _| assert!(window.has_pending_keystrokes()))
7237 .unwrap();
7238 assert_eq!(dispatched.get(), 1);
7239 cx.executor().advance_clock(Duration::from_millis(500));
7240 cx.run_until_parked();
7241 assert_eq!(dispatched.get(), 2);
7242 }
7243
7244 #[gpui::test]
7245 fn resumed_timeout_cannot_update_replacement_window(cx: &mut TestAppContext) {
7246 use futures::channel::oneshot;
7247 use std::time::Duration;
7248
7249 let old = cx.add_window(|_, _| EmptyView);
7250 let (resume, resumed) = oneshot::channel();
7251 let timer_ready = Rc::new(Cell::new(false));
7252 let completed = Rc::new(Cell::new(false));
7253 let _task = old
7254 .update(cx, |_, window, app| {
7255 let timer_ready = timer_ready.clone();
7256 let completed = completed.clone();
7257 window.spawn(app, async move |cx| {
7258 cx.background_executor.timer(Duration::from_secs(1)).await;
7259 timer_ready.set(true);
7260 resumed.await.unwrap();
7263 assert_eq!(
7264 cx.update_if_present(|_, _| panic!("stale work ran"))
7265 .unwrap(),
7266 None
7267 );
7268 completed.set(true);
7269 })
7270 })
7271 .unwrap();
7272 cx.executor().advance_clock(Duration::from_secs(1));
7273 cx.run_until_parked();
7274 assert!(timer_ready.get());
7275 old.update(cx, |_, window, _| window.remove_window())
7276 .unwrap();
7277 let replacement = cx.add_window(|_, _| EmptyView);
7278 assert_ne!(old.window_id(), replacement.window_id());
7279 resume.send(()).unwrap();
7280 cx.run_until_parked();
7281 assert!(completed.get());
7282 replacement
7283 .update(cx, |_, window, _| assert!(!window.has_pending_keystrokes()))
7284 .unwrap();
7285 }
7286
7287 #[gpui::test]
7288 fn optional_window_update_preserves_unrelated_errors(cx: &mut TestAppContext) {
7289 let window = cx.add_window(|_, _| EmptyView);
7290 let mut context = window
7291 .update(cx, |_, window, app| window.to_async(app))
7292 .unwrap();
7293 assert_eq!(context.update_if_present(|_, _| 42).unwrap(), Some(42));
7294 assert!(
7296 context
7297 .update_if_present(|_, _| Err::<(), _>(anyhow::anyhow!("callback failure")))
7298 .unwrap()
7299 .unwrap()
7300 .is_err()
7301 );
7302 cx.update(|_| {
7303 assert!(context.update_if_present(|_, _| ()).is_err());
7304 });
7305 window
7306 .update(cx, |_, window, _| window.remove_window())
7307 .unwrap();
7308 assert_eq!(context.update_if_present(|_, _| ()).unwrap(), None);
7309 }
7310
7311 struct OpensWindowOnPaint {
7312 opened: Rc<Cell<bool>>,
7313 }
7314
7315 impl Render for OpensWindowOnPaint {
7316 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7317 let opened = self.opened.clone();
7318 div()
7319 .size_full()
7320 .child(canvas(
7321 |_, _, _| {},
7322 move |_, _, _window, cx| {
7323 if !opened.replace(true) {
7324 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
7325 .unwrap();
7326 }
7327 },
7328 ))
7329 .child(div().child("after"))
7333 }
7334 }
7335
7336 #[test]
7342 fn test_window_opened_during_draw_defers_arena_clear() {
7343 let mut cx = TestAppContext::single();
7344
7345 let opened = Rc::new(Cell::new(false));
7346 let window = cx.add_window({
7348 let opened = opened.clone();
7349 move |_, _| OpensWindowOnPaint { opened }
7350 });
7351
7352 assert!(opened.get());
7353 assert_eq!(cx.windows().len(), 2);
7354
7355 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
7358 .unwrap();
7359 }
7360
7361 #[gpui::test]
7362 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
7363 let window = cx.add_window(|_, _| EmptyView);
7364 let observed_appearance = Rc::new(Cell::new(None));
7365 let _subscription = window
7366 .update(cx, {
7367 let observed_appearance = observed_appearance.clone();
7368 move |_, window, _| {
7369 window.observe_window_appearance(move |window, _| {
7370 observed_appearance.set(Some(window.appearance()));
7371 })
7372 }
7373 })
7374 .unwrap();
7375 let test_window = cx.test_window(window.into());
7376
7377 cx.update(|_| {
7378 test_window.simulate_appearance_change(WindowAppearance::Dark);
7379 assert_eq!(observed_appearance.get(), None);
7380 });
7381 cx.run_until_parked();
7382
7383 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
7384 }
7385
7386 struct RootView {
7387 explicit_size: bool,
7388 child_bounds: Rc<Cell<Bounds<Pixels>>>,
7389 }
7390
7391 impl Render for RootView {
7392 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7393 let child_bounds = self.child_bounds.clone();
7394 let root = div().flex().flex_col().child(
7395 canvas(
7396 move |bounds, _, _| child_bounds.set(bounds),
7397 |_, _, _, _| {},
7398 )
7399 .size_full(),
7400 );
7401 if self.explicit_size {
7402 root.w(px(300.)).h(px(200.))
7403 } else {
7404 root
7405 }
7406 }
7407 }
7408
7409 #[test]
7410 fn auto_sized_window_root_fills_the_window() {
7411 let mut cx = TestAppContext::single();
7412 let child_bounds = Rc::new(Cell::new(Bounds::default()));
7413 let window = cx.add_window({
7414 let child_bounds = child_bounds.clone();
7415 move |_, _| RootView {
7416 explicit_size: false,
7417 child_bounds,
7418 }
7419 });
7420
7421 let viewport_size = cx
7422 .update_window(window.into(), |_, window, cx| {
7423 window.draw(cx).clear(cx);
7424 window.viewport_size()
7425 })
7426 .unwrap();
7427
7428 assert_eq!(child_bounds.get().size, viewport_size);
7429 }
7430
7431 #[test]
7432 fn explicitly_sized_window_root_keeps_its_size() {
7433 let mut cx = TestAppContext::single();
7434 let child_bounds = Rc::new(Cell::new(Bounds::default()));
7435 let window = cx.add_window({
7436 let child_bounds = child_bounds.clone();
7437 move |_, _| RootView {
7438 explicit_size: true,
7439 child_bounds,
7440 }
7441 });
7442
7443 cx.update_window(window.into(), |_, window, cx| {
7444 window.draw(cx).clear(cx);
7445 })
7446 .unwrap();
7447
7448 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
7449 }
7450
7451 struct FileDragView {
7452 path: PathBuf,
7453 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7454 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7455 }
7456
7457 impl Render for FileDragView {
7458 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7459 div()
7460 .id("file-drag")
7461 .size_full()
7462 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
7463 .external_drag_payload(|path: &PathBuf, _, _| {
7464 Some(ExternalDragPayload::Files(FileDragPaths::new([(
7465 path.clone(),
7466 true,
7467 )])))
7468 })
7469 .on_drag_move({
7470 let observed_drag_moves = self.observed_drag_moves.clone();
7471 move |event: &DragMoveEvent<PathBuf>, _, _| {
7472 observed_drag_moves.borrow_mut().push(event.event.position);
7473 }
7474 })
7475 .on_drop({
7476 let observed_drops = self.observed_drops.clone();
7477 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
7478 })
7479 }
7480 }
7481
7482 #[gpui::test]
7483 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
7484 struct Drag {
7485 window: AnyWindowHandle,
7486 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7487 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7488 }
7489
7490 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
7491 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
7492 let observed_drops = Rc::new(RefCell::new(Vec::new()));
7493 let window: AnyWindowHandle = cx
7494 .add_window({
7495 let observed_drag_moves = observed_drag_moves.clone();
7496 let observed_drops = observed_drops.clone();
7497 move |_, _| FileDragView {
7498 path,
7499 observed_drag_moves,
7500 observed_drops,
7501 }
7502 })
7503 .into();
7504 cx.test_window(window)
7505 .set_start_external_drag_result(platform_result);
7506
7507 let update_result = cx.update_window(window, |_, window, cx| {
7508 window.draw(cx).clear(cx);
7509 window.dispatch_event(
7510 MouseDownEvent {
7511 position: point(px(10.), px(10.)),
7512 button: MouseButton::Left,
7513 modifiers: Default::default(),
7514 click_count: 1,
7515 first_mouse: false,
7516 }
7517 .to_platform_input(),
7518 cx,
7519 );
7520 window.dispatch_event(
7521 MouseMoveEvent {
7522 position: point(px(20.), px(20.)),
7523 pressed_button: Some(MouseButton::Left),
7524 modifiers: Default::default(),
7525 }
7526 .to_platform_input(),
7527 cx,
7528 );
7529 assert!(cx.active_drag.is_some());
7530 });
7531 assert!(
7532 update_result.is_ok(),
7533 "failed to start drag: {update_result:?}"
7534 );
7535
7536 assert!(cx.test_window(window).external_drag_files().is_empty());
7537 Drag {
7538 window,
7539 observed_drag_moves,
7540 observed_drops,
7541 }
7542 }
7543
7544 let successful_path = PathBuf::from("/tmp/successful-drag");
7545 let successful = start_drag(cx, successful_path.clone(), true);
7546 let outside_position = point(px(-1.), px(20.));
7547 let update_result = cx.update_window(successful.window, |_, window, cx| {
7548 window.dispatch_event(
7549 MouseMoveEvent {
7550 position: outside_position,
7551 pressed_button: Some(MouseButton::Left),
7552 modifiers: Default::default(),
7553 }
7554 .to_platform_input(),
7555 cx,
7556 );
7557 assert!(cx.active_drag.is_none());
7558 });
7559 assert!(
7560 update_result.is_ok(),
7561 "failed to promote drag: {update_result:?}"
7562 );
7563 assert_eq!(
7564 cx.test_window(successful.window).external_drag_files(),
7565 [(successful_path.clone(), true)]
7566 );
7567 assert_eq!(
7570 successful.observed_drag_moves.borrow().last(),
7571 Some(&outside_position)
7572 );
7573
7574 let destination: AnyWindowHandle = cx.add_window(|_, _| EmptyView).into();
7575 let reentry_position = point(px(30.), px(30.));
7576 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
7577 let update_result = cx.update_window(destination, |_, window, cx| {
7578 window.dispatch_event(
7579 FileDropEvent::Entered {
7580 position: reentry_position,
7581 paths: external_paths(),
7582 }
7583 .to_platform_input(),
7584 cx,
7585 );
7586 assert!(
7587 cx.active_drag
7588 .as_ref()
7589 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7590 );
7591 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7592 assert!(cx.active_drag.is_none());
7593 });
7594 assert!(
7595 update_result.is_ok(),
7596 "failed to handle drag in destination window: {update_result:?}"
7597 );
7598
7599 let update_result = cx.update_window(successful.window, |_, window, cx| {
7600 window.dispatch_event(
7601 FileDropEvent::Entered {
7602 position: reentry_position,
7603 paths: external_paths(),
7604 }
7605 .to_platform_input(),
7606 cx,
7607 );
7608 assert!(
7609 cx.active_drag
7610 .as_ref()
7611 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7612 );
7613 assert_eq!(
7614 successful.observed_drag_moves.borrow().last(),
7615 Some(&reentry_position)
7616 );
7617
7618 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7619 assert!(cx.active_drag.is_none());
7620
7621 window.dispatch_event(
7622 FileDropEvent::Entered {
7623 position: reentry_position,
7624 paths: external_paths(),
7625 }
7626 .to_platform_input(),
7627 cx,
7628 );
7629 assert!(
7630 cx.active_drag
7631 .as_ref()
7632 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7633 );
7634
7635 window.dispatch_event(
7636 FileDropEvent::Submit {
7637 position: reentry_position,
7638 }
7639 .to_platform_input(),
7640 cx,
7641 );
7642 assert_eq!(
7643 successful.observed_drops.borrow().as_slice(),
7644 std::slice::from_ref(&successful_path)
7645 );
7646 assert!(cx.active_drag.is_none());
7647
7648 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7649 assert!(cx.active_drag.is_none());
7650 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
7651 assert!(cx.active_drag.is_none());
7652
7653 window.dispatch_event(
7654 FileDropEvent::Entered {
7655 position: reentry_position,
7656 paths: external_paths(),
7657 }
7658 .to_platform_input(),
7659 cx,
7660 );
7661 assert!(
7662 cx.active_drag
7663 .as_ref()
7664 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7665 );
7666 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7667 });
7668 assert!(
7669 update_result.is_ok(),
7670 "failed to restore drag in source window: {update_result:?}"
7671 );
7672
7673 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
7674 let cancelled = start_drag(cx, cancelled_path.clone(), true);
7675 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
7676 window.dispatch_event(
7677 MouseMoveEvent {
7678 position: outside_position,
7679 pressed_button: Some(MouseButton::Left),
7680 modifiers: Default::default(),
7681 }
7682 .to_platform_input(),
7683 cx,
7684 );
7685 assert!(cx.active_drag.is_none());
7686
7687 window.dispatch_event(
7688 FileDropEvent::Entered {
7689 position: reentry_position,
7690 paths: ExternalPaths([cancelled_path].into_iter().collect()),
7691 }
7692 .to_platform_input(),
7693 cx,
7694 );
7695 assert!(
7696 cx.active_drag
7697 .as_ref()
7698 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7699 );
7700 assert!(cx.stop_active_drag(window));
7701 assert!(cx.active_drag.is_none());
7702 });
7703 assert!(
7704 update_result.is_ok(),
7705 "failed to cancel restored drag: {update_result:?}"
7706 );
7707 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
7708
7709 let removed_path = PathBuf::from("/tmp/removed-window-drag");
7710 let removed = start_drag(cx, removed_path, true);
7711 let removed_window_id = removed.window.window_id();
7712 let update_result = cx.update_window(removed.window, |_, window, cx| {
7713 window.dispatch_event(
7714 MouseMoveEvent {
7715 position: outside_position,
7716 pressed_button: Some(MouseButton::Left),
7717 modifiers: Default::default(),
7718 }
7719 .to_platform_input(),
7720 cx,
7721 );
7722 assert!(cx.active_drag.is_none());
7723 window.remove_window();
7724 });
7725 assert!(
7726 update_result.is_ok(),
7727 "failed to remove drag source window: {update_result:?}"
7728 );
7729 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
7730
7731 let failed_path = PathBuf::from("/tmp/failed-drag");
7732 let failed = start_drag(cx, failed_path.clone(), false);
7733 let update_result = cx.update_window(failed.window, |_, window, cx| {
7734 for x_position in [-1., -2.] {
7735 window.dispatch_event(
7736 MouseMoveEvent {
7737 position: point(px(x_position), px(20.)),
7738 pressed_button: Some(MouseButton::Left),
7739 modifiers: Default::default(),
7740 }
7741 .to_platform_input(),
7742 cx,
7743 );
7744 }
7745 assert!(cx.active_drag.is_some());
7746 });
7747 assert!(
7748 update_result.is_ok(),
7749 "failed to retain drag after platform failure: {update_result:?}"
7750 );
7751 assert_eq!(
7752 cx.test_window(failed.window).external_drag_files(),
7753 [(failed_path, true)]
7754 );
7755 }
7756
7757 struct FocusForwarder {
7758 a: FocusHandle,
7759 b: FocusHandle,
7760 }
7761
7762 impl Render for FocusForwarder {
7763 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7764 div()
7765 .size_full()
7766 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
7767 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
7768 }
7769 }
7770
7771 #[gpui::test]
7775 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
7776 let b_focus_count = Rc::new(Cell::new(0));
7777 let window = cx.add_window({
7778 let b_focus_count = b_focus_count.clone();
7779 move |window, cx| {
7780 let a = cx.focus_handle();
7781 let b = cx.focus_handle();
7782 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
7783 let b = this.b.clone();
7784 window.focus(&b, cx);
7785 })
7786 .detach();
7787 cx.on_focus(&b, window, move |_, _, _| {
7788 b_focus_count.set(b_focus_count.get() + 1);
7789 })
7790 .detach();
7791 FocusForwarder { a, b }
7792 }
7793 });
7794
7795 window
7796 .update(cx, |_, window, _| window.activate_window())
7797 .unwrap();
7798 cx.executor().run_until_parked();
7799
7800 window
7801 .update(cx, |this, window, cx| {
7802 let a = this.a.clone();
7803 window.focus(&a, cx);
7804 })
7805 .unwrap();
7806 cx.executor().run_until_parked();
7807
7808 window
7809 .update(cx, |this, window, _| {
7810 assert!(this.b.is_focused(window));
7811 })
7812 .unwrap();
7813 assert_eq!(b_focus_count.get(), 1);
7814 }
7815
7816 #[gpui::test]
7817 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
7818 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
7819
7820 let window = cx.add_window(|_, _| EmptyView);
7821 window
7822 .update(cx, |_, window, _| {
7823 assert!(matches!(
7824 window.window_handle(),
7825 Err(HandleError::NotSupported)
7826 ));
7827 assert!(matches!(
7828 window.display_handle(),
7829 Err(HandleError::NotSupported)
7830 ));
7831 })
7832 .unwrap();
7833 }
7834}