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 windows_composition,
1403 app_id,
1404 window_min_size,
1405 window_decorations,
1406 #[cfg_attr(
1407 not(any(target_os = "linux", target_os = "freebsd")),
1408 allow(unused_variables)
1409 )]
1410 icon,
1411 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1412 tabbing_identifier,
1413 } = options;
1414
1415 let initial_window_title = titlebar
1416 .as_ref()
1417 .and_then(|titlebar| titlebar.title.clone());
1418
1419 let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1420 let mut platform_window = cx.platform.open_window(
1421 handle,
1422 WindowParams {
1423 bounds: window_bounds.get_bounds(),
1424 windows_composition,
1425 titlebar,
1426 kind,
1427 is_movable,
1428 app_owns_titlebar_drag,
1429 is_resizable,
1430 is_minimizable,
1431 focus,
1432 show,
1433 display_id,
1434 window_min_size,
1435 app_id: app_id.clone(),
1436 icon,
1437 #[cfg(target_os = "macos")]
1438 tabbing_identifier,
1439 },
1440 )?;
1441
1442 let tab_bar_visible = platform_window.tab_bar_visible();
1443 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1444 if let Some(tabs) = platform_window.tabbed_windows() {
1445 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1446 }
1447
1448 let display_id = platform_window.display().map(|display| display.id());
1449 let sprite_atlas = platform_window.sprite_atlas();
1450 let mouse_position = platform_window.mouse_position();
1451 let modifiers = platform_window.modifiers();
1452 let capslock = platform_window.capslock();
1453 let content_size = platform_window.content_size();
1454 let scale_factor = platform_window.scale_factor();
1455 let appearance = platform_window.appearance();
1456 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1457 let invalidator = WindowInvalidator::new();
1458 let active = Rc::new(Cell::new(platform_window.is_active()));
1459 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1460 let needs_present = Rc::new(Cell::new(false));
1461 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1462 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1463 let last_frame_time = Rc::new(Cell::new(None));
1464
1465 platform_window
1466 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1467 platform_window.set_background_appearance(window_background);
1468
1469 match window_bounds {
1470 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1471 WindowBounds::Maximized(_) => platform_window.zoom(),
1472 WindowBounds::Windowed(_) => {}
1473 }
1474
1475 let accessibility_force_disabled = cx.accessibility_force_disabled;
1476 let a11y_active_flag = Arc::new(AtomicBool::new(false));
1477
1478 #[cfg(not(target_family = "wasm"))]
1479 if !accessibility_force_disabled {
1480 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
1481 if let Some(title) = &initial_window_title {
1482 initial_root_node.set_label(title.to_string());
1483 }
1484 let initial_tree = accesskit::TreeUpdate {
1485 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
1486 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
1487 tree_id: accesskit::TreeId::ROOT,
1488 focus: ROOT_NODE_ID,
1489 };
1490 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
1491 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
1492 let (action_sender, action_receiver) =
1493 async_channel::unbounded::<accesskit::ActionRequest>();
1494
1495 platform_window.a11y_init(crate::A11yCallbacks {
1496 activation: {
1497 let active_flag = a11y_active_flag.clone();
1498 Box::new(move || {
1499 log::info!("Accessibility activated");
1500 active_flag.store(true, SeqCst);
1501 activation_sender.send_blocking(()).log_err();
1502 Some(initial_tree.clone())
1503 })
1504 },
1505 action: Box::new(move |request| {
1506 action_sender.send_blocking(request).log_err();
1507 }),
1508 deactivation: {
1509 let active_flag = a11y_active_flag.clone();
1510 Box::new(move || {
1511 log::info!("Accessibility deactivated");
1512 active_flag.store(false, SeqCst);
1513 deactivation_sender.send_blocking(()).log_err();
1514 })
1515 },
1516 });
1517
1518 let mut async_cx = cx.to_async();
1524 cx.foreground_executor()
1525 .spawn(async move {
1526 while activation_receiver.recv().await.is_ok() {
1527 handle
1528 .update(&mut async_cx, |_, window, _| window.refresh())
1529 .log_err();
1530 }
1531 })
1532 .detach();
1533
1534 let mut async_cx = cx.to_async();
1535 cx.foreground_executor()
1536 .spawn(async move {
1537 while deactivation_receiver.recv().await.is_ok() {
1538 handle
1539 .update(&mut async_cx, |_, window, _| window.refresh())
1540 .log_err();
1541 }
1542 })
1543 .detach();
1544
1545 let mut async_cx = cx.to_async();
1546 cx.foreground_executor()
1547 .spawn(async move {
1548 while let Ok(request) = action_receiver.recv().await {
1549 handle
1550 .update(&mut async_cx, |_, window, cx| {
1551 window.handle_a11y_action(request, cx);
1552 })
1553 .log_err();
1554 }
1555 })
1556 .detach();
1557 }
1558
1559 platform_window.on_close(Box::new({
1560 let window_id = handle.window_id();
1561 let cx = cx.to_async();
1562 move || {
1563 cx.spawn(async move |cx| {
1566 cx.update(|cx| {
1567 if cx.windows.contains_key(window_id) {
1569 handle
1570 .update(cx, |_, window, _| window.remove_window())
1571 .log_err();
1572 }
1573 SystemWindowTabController::remove_tab(cx, window_id);
1574 });
1575 })
1576 .detach();
1577 }
1578 }));
1579 platform_window.on_request_frame(Box::new({
1580 let mut cx = cx.to_async();
1581 let invalidator = invalidator.clone();
1582 let active = active.clone();
1583 let needs_present = needs_present.clone();
1584 let next_frame_callbacks = next_frame_callbacks.clone();
1585 let input_rate_tracker = input_rate_tracker.clone();
1586 let mut deferred_force_render = false;
1587 move |request_frame_options| {
1588 if draw_in_progress() {
1604 log::debug!("deferring re-entrant window draw request");
1605 deferred_force_render |= request_frame_options.force_render;
1606 return;
1607 }
1608 let force_render =
1612 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
1613
1614 let thermal_state = handle
1615 .update(&mut cx, |_, _, cx| cx.thermal_state())
1616 .log_err();
1617
1618 let min_frame_interval = if request_frame_options.require_presentation
1622 || (!request_frame_options.force_render
1623 && next_frame_callbacks.borrow().is_empty())
1624 {
1625 None
1626 } else if !active.get() && !input_rate_tracker.borrow_mut().is_high_rate() {
1627 Some(Duration::from_micros(33333))
1628 } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
1629 Some(Duration::from_micros(16667))
1630 } else {
1631 None
1632 };
1633
1634 let now = Instant::now();
1635 if let Some(min_interval) = min_frame_interval {
1636 if let Some(last_frame) = last_frame_time.get()
1637 && now.duration_since(last_frame) < min_interval
1638 {
1639 deferred_force_render |= force_render;
1641 handle
1646 .update(&mut cx, |_, window, _| window.complete_frame())
1647 .log_err();
1648 return;
1649 }
1650 }
1651 last_frame_time.set(Some(now));
1652
1653 let next_frame_callbacks = next_frame_callbacks.take();
1654 if !next_frame_callbacks.is_empty() {
1655 handle
1656 .update(&mut cx, |_, window, cx| {
1657 for callback in next_frame_callbacks {
1658 callback(window, cx);
1659 }
1660 })
1661 .log_err();
1662 }
1663
1664 let needs_present = request_frame_options.require_presentation
1668 || needs_present.get()
1669 || input_rate_tracker.borrow_mut().is_high_rate();
1670
1671 if invalidator.is_dirty() || force_render {
1672 measure("frame duration", || {
1673 handle
1674 .update(&mut cx, |_, window, cx| {
1675 if force_render {
1676 window.refresh();
1679 }
1680 let arena_clear_needed = window.draw(cx);
1681 window.present();
1682 arena_clear_needed.clear(cx);
1683 })
1684 .log_err();
1685 })
1686 } else if needs_present {
1687 handle
1688 .update(&mut cx, |_, window, _| window.present())
1689 .log_err();
1690 }
1691
1692 handle
1693 .update(&mut cx, |_, window, _| {
1694 window.complete_frame();
1695 })
1696 .log_err();
1697 }
1698 }));
1699 platform_window.on_resize(Box::new({
1700 let mut cx = cx.to_async();
1701 move |_, _| {
1702 handle
1703 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1704 .log_err();
1705 }
1706 }));
1707 platform_window.on_moved(Box::new({
1708 let mut cx = cx.to_async();
1709 move || {
1710 handle
1711 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1712 .log_err();
1713 }
1714 }));
1715 platform_window.on_appearance_changed(Box::new({
1716 let cx = cx.to_async();
1717 let foreground_executor = cx.foreground_executor().clone();
1718 move || {
1719 let mut cx = cx.clone();
1720 foreground_executor
1723 .spawn(async move {
1724 handle
1725 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1726 .log_err();
1727 })
1728 .detach();
1729 }
1730 }));
1731 platform_window.on_button_layout_changed(Box::new({
1732 let mut cx = cx.to_async();
1733 move || {
1734 handle
1735 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
1736 .log_err();
1737 }
1738 }));
1739 platform_window.on_active_status_change(Box::new({
1740 let mut cx = cx.to_async();
1741 move |active| {
1742 handle
1743 .update(&mut cx, |_, window, cx| {
1744 window.active.set(active);
1745 window.modifiers = window.platform_window.modifiers();
1746 window.capslock = window.platform_window.capslock();
1747 window
1748 .activation_observers
1749 .clone()
1750 .retain(&(), |callback| callback(window, cx));
1751
1752 window.bounds_changed(cx);
1753 window.refresh();
1754
1755 SystemWindowTabController::update_last_active(cx, window.handle.id);
1756 })
1757 .log_err();
1758 }
1759 }));
1760 platform_window.on_hover_status_change(Box::new({
1761 let mut cx = cx.to_async();
1762 move |active| {
1763 handle
1764 .update(&mut cx, |_, window, _| {
1765 window.hovered.set(active);
1766 window.refresh();
1767 })
1768 .log_err();
1769 }
1770 }));
1771 platform_window.on_input({
1772 let mut cx = cx.to_async();
1773 Box::new(move |event| {
1774 handle
1775 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1776 .log_err()
1777 .unwrap_or(DispatchEventResult::default())
1778 })
1779 });
1780 platform_window.on_hit_test_window_control({
1781 let mut cx = cx.to_async();
1782 Box::new(move || {
1783 handle
1784 .update(&mut cx, |_, window, _cx| {
1785 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1786 if window.mouse_hit_test.ids.contains(&hitbox.id) {
1787 return Some(*area);
1788 }
1789 }
1790 None
1791 })
1792 .log_err()
1793 .unwrap_or(None)
1794 })
1795 });
1796 platform_window.on_move_tab_to_new_window({
1797 let mut cx = cx.to_async();
1798 Box::new(move || {
1799 handle
1800 .update(&mut cx, |_, _window, cx| {
1801 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1802 })
1803 .log_err();
1804 })
1805 });
1806 platform_window.on_merge_all_windows({
1807 let mut cx = cx.to_async();
1808 Box::new(move || {
1809 handle
1810 .update(&mut cx, |_, _window, cx| {
1811 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1812 })
1813 .log_err();
1814 })
1815 });
1816 platform_window.on_select_next_tab({
1817 let mut cx = cx.to_async();
1818 Box::new(move || {
1819 handle
1820 .update(&mut cx, |_, _window, cx| {
1821 SystemWindowTabController::select_next_tab(cx, handle.window_id());
1822 })
1823 .log_err();
1824 })
1825 });
1826 platform_window.on_select_previous_tab({
1827 let mut cx = cx.to_async();
1828 Box::new(move || {
1829 handle
1830 .update(&mut cx, |_, _window, cx| {
1831 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1832 })
1833 .log_err();
1834 })
1835 });
1836 platform_window.on_toggle_tab_bar({
1837 let mut cx = cx.to_async();
1838 Box::new(move || {
1839 handle
1840 .update(&mut cx, |_, window, cx| {
1841 let tab_bar_visible = window.platform_window.tab_bar_visible();
1842 SystemWindowTabController::set_visible(cx, tab_bar_visible);
1843 })
1844 .log_err();
1845 })
1846 });
1847
1848 if let Some(app_id) = app_id {
1849 platform_window.set_app_id(&app_id);
1850 }
1851
1852 platform_window.map_window().unwrap();
1853
1854 Ok(Window {
1855 handle,
1856 invalidator,
1857 removed: false,
1858 platform_window,
1859 display_id,
1860 is_resizable,
1861 is_minimizable,
1862 sprite_atlas,
1863 text_system,
1864 text_rendering_mode: cx.text_rendering_mode.clone(),
1865 rem_size: px(16.),
1866 rem_size_override_stack: SmallVec::new(),
1867 viewport_size: content_size,
1868 layout_engine: Some(TaffyLayoutEngine::new()),
1869 root: None,
1870 element_id_stack: SmallVec::default(),
1871 text_style_stack: Vec::new(),
1872 rendered_entity_stack: Vec::new(),
1873 element_offset_stack: Vec::new(),
1874 content_mask_stack: Vec::new(),
1875 element_opacity: 1.0,
1876 requested_autoscroll: None,
1877 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1878 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1879 next_frame_callbacks,
1880 next_hitbox_id: HitboxId(0),
1881 next_tooltip_id: TooltipId::default(),
1882 tooltip_bounds: None,
1883 dirty_views: FxHashSet::default(),
1884 focus_listeners: SubscriberSet::new(),
1885 focus_lost_listeners: SubscriberSet::new(),
1886 default_prevented: true,
1887 mouse_position,
1888 mouse_hit_test: HitTest::default(),
1889 modifiers,
1890 capslock,
1891 scale_factor,
1892 bounds_observers: SubscriberSet::new(),
1893 appearance,
1894 appearance_observers: SubscriberSet::new(),
1895 button_layout_observers: SubscriberSet::new(),
1896 active,
1897 hovered,
1898 needs_present,
1899 input_rate_tracker,
1900 #[cfg(feature = "input-latency-histogram")]
1901 input_latency_tracker: InputLatencyTracker::new()?,
1902 last_input_modality: InputModality::Mouse,
1903 refreshing: false,
1904 activation_observers: SubscriberSet::new(),
1905 focus: None,
1906 focus_enabled: true,
1907 focus_generation: 0,
1908 pending_input: None,
1909 pending_modifier: ModifierState::default(),
1910 pending_input_observers: SubscriberSet::new(),
1911 prompt: None,
1912 client_inset: None,
1913 image_cache_stack: Vec::new(),
1914 captured_hitbox: None,
1915 #[cfg(any(feature = "inspector", debug_assertions))]
1916 inspector: None,
1917 a11y: A11y::new(
1918 a11y_active_flag,
1919 accessibility_force_disabled,
1920 initial_window_title,
1921 ),
1922 })
1923 }
1924
1925 pub(crate) fn new_focus_listener(
1926 &self,
1927 value: AnyWindowFocusListener,
1928 ) -> (Subscription, impl FnOnce() + use<>) {
1929 self.focus_listeners.insert((), value)
1930 }
1931}
1932
1933#[derive(Clone, Debug, Default, PartialEq, Eq)]
1934#[expect(missing_docs)]
1935pub struct DispatchEventResult {
1936 pub propagate: bool,
1937 pub default_prevented: bool,
1938}
1939
1940#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1944#[repr(C)]
1945pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1946 pub bounds: Bounds<P>,
1948}
1949
1950impl ContentMask<Pixels> {
1951 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1953 ContentMask {
1954 bounds: self.bounds.scale(factor),
1955 }
1956 }
1957
1958 pub fn intersect(&self, other: &Self) -> Self {
1960 let bounds = self.bounds.intersect(&other.bounds);
1961 ContentMask { bounds }
1962 }
1963}
1964
1965impl Window {
1966 fn mark_view_dirty(&mut self, view_id: EntityId) {
1967 for view_id in self
1970 .rendered_frame
1971 .dispatch_tree
1972 .view_path_reversed(view_id)
1973 {
1974 if !self.dirty_views.insert(view_id) {
1975 break;
1976 }
1977 }
1978 }
1979
1980 pub fn observe_window_appearance(
1982 &self,
1983 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1984 ) -> Subscription {
1985 let (subscription, activate) = self.appearance_observers.insert(
1986 (),
1987 Box::new(move |window, cx| {
1988 callback(window, cx);
1989 true
1990 }),
1991 );
1992 activate();
1993 subscription
1994 }
1995
1996 pub fn observe_button_layout_changed(
1998 &self,
1999 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2000 ) -> Subscription {
2001 let (subscription, activate) = self.button_layout_observers.insert(
2002 (),
2003 Box::new(move |window, cx| {
2004 callback(window, cx);
2005 true
2006 }),
2007 );
2008 activate();
2009 subscription
2010 }
2011
2012 pub fn replace_root<E>(
2014 &mut self,
2015 cx: &mut App,
2016 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
2017 ) -> Entity<E>
2018 where
2019 E: 'static + Render,
2020 {
2021 let view = cx.new(|cx| build_view(self, cx));
2022 self.root = Some(view.clone().into());
2023 self.refresh();
2024 view
2025 }
2026
2027 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
2029 where
2030 E: 'static + Render,
2031 {
2032 self.root
2033 .as_ref()
2034 .map(|view| view.clone().downcast::<E>().ok())
2035 }
2036
2037 pub fn window_handle(&self) -> AnyWindowHandle {
2039 self.handle
2040 }
2041
2042 pub fn refresh(&mut self) {
2044 if self.invalidator.not_drawing() {
2045 self.refreshing = true;
2046 self.invalidator.set_dirty(true);
2047 }
2048 }
2049
2050 pub fn remove_window(&mut self) {
2052 self.clear_pending_keystrokes();
2053 self.removed = true;
2054 }
2055
2056 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
2058 self.focus
2059 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
2060 }
2061
2062 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
2064 if !self.focus_enabled || self.focus == Some(handle.id) {
2065 return;
2066 }
2067
2068 self.focus = Some(handle.id);
2069 self.focus_generation = self.focus_generation.wrapping_add(1);
2070 self.clear_pending_keystrokes();
2071
2072 let window_handle = self.handle;
2075 cx.defer(move |cx| {
2076 window_handle
2077 .update(cx, |_, window, cx| {
2078 window.pending_input_changed(cx);
2079 })
2080 .ok();
2081 });
2082
2083 self.refresh();
2084 }
2085
2086 pub fn blur(&mut self) {
2088 if !self.focus_enabled {
2089 return;
2090 }
2091
2092 if self.focus.is_some() {
2093 self.focus_generation = self.focus_generation.wrapping_add(1);
2094 }
2095 self.focus = None;
2096 self.refresh();
2097 }
2098
2099 pub fn disable_focus(&mut self) {
2101 self.blur();
2102 self.focus_enabled = false;
2103 }
2104
2105 pub fn focus_next(&mut self, cx: &mut App) {
2107 if !self.focus_enabled {
2108 return;
2109 }
2110
2111 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
2112 self.focus(&handle, cx)
2113 }
2114 }
2115
2116 pub fn focus_prev(&mut self, cx: &mut App) {
2118 if !self.focus_enabled {
2119 return;
2120 }
2121
2122 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
2123 self.focus(&handle, cx)
2124 }
2125 }
2126
2127 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
2129 &self.text_system
2130 }
2131
2132 pub fn text_style(&self) -> TextStyle {
2134 let mut style = TextStyle::default();
2135 for refinement in &self.text_style_stack {
2136 style.refine(refinement);
2137 }
2138 style
2139 }
2140
2141 pub fn is_maximized(&self) -> bool {
2145 self.platform_window.is_maximized()
2146 }
2147
2148 pub fn request_decorations(&self, decorations: WindowDecorations) {
2150 self.platform_window.request_decorations(decorations);
2151 }
2152
2153 pub fn set_exclusive_zone(&self, zone: Pixels) {
2159 self.platform_window.set_exclusive_zone(zone);
2160 }
2161
2162 #[cfg(all(target_os = "linux", feature = "wayland"))]
2167 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
2168 self.platform_window.set_exclusive_edge(edge);
2169 }
2170
2171 pub fn start_window_resize(&self, edge: ResizeEdge) {
2173 if self.is_resizable {
2174 self.platform_window.start_window_resize(edge);
2175 }
2176 }
2177
2178 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
2185 self.platform_window.set_input_region(region);
2186 }
2187
2188 pub fn window_bounds(&self) -> WindowBounds {
2191 self.platform_window.window_bounds()
2192 }
2193
2194 pub fn inner_window_bounds(&self) -> WindowBounds {
2196 self.platform_window.inner_window_bounds()
2197 }
2198
2199 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
2201 let focus_id = self.focused(cx).map(|handle| handle.id);
2202
2203 let window = self.handle;
2204 cx.defer(move |cx| {
2205 window
2206 .update(cx, |_, window, cx| {
2207 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
2208 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
2209 })
2210 .log_err();
2211 })
2212 }
2213
2214 pub(crate) fn dispatch_keystroke_observers(
2215 &mut self,
2216 event: &dyn Any,
2217 action: Option<Box<dyn Action>>,
2218 context_stack: Vec<KeyContext>,
2219 cx: &mut App,
2220 ) {
2221 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2222 return;
2223 };
2224
2225 cx.keystroke_observers.clone().retain(&(), move |callback| {
2226 (callback)(
2227 &KeystrokeEvent {
2228 keystroke: key_down_event.keystroke.clone(),
2229 action: action.as_ref().map(|action| action.boxed_clone()),
2230 context_stack: context_stack.clone(),
2231 },
2232 self,
2233 cx,
2234 )
2235 });
2236 }
2237
2238 pub(crate) fn dispatch_keystroke_interceptors(
2239 &mut self,
2240 event: &dyn Any,
2241 context_stack: Vec<KeyContext>,
2242 cx: &mut App,
2243 ) {
2244 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2245 return;
2246 };
2247
2248 cx.keystroke_interceptors
2249 .clone()
2250 .retain(&(), move |callback| {
2251 (callback)(
2252 &KeystrokeEvent {
2253 keystroke: key_down_event.keystroke.clone(),
2254 action: None,
2255 context_stack: context_stack.clone(),
2256 },
2257 self,
2258 cx,
2259 )
2260 });
2261 }
2262
2263 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2266 let handle = self.handle;
2267 cx.defer(move |cx| {
2268 handle.update(cx, |_, window, cx| f(window, cx)).ok();
2269 });
2270 }
2271
2272 pub fn observe<T: 'static>(
2276 &mut self,
2277 observed: &Entity<T>,
2278 cx: &mut App,
2279 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2280 ) -> Subscription {
2281 let entity_id = observed.entity_id();
2282 let observed = observed.downgrade();
2283 let window_handle = self.handle;
2284 cx.new_observer(
2285 entity_id,
2286 Box::new(move |cx| {
2287 window_handle
2288 .update(cx, |_, window, cx| {
2289 if let Some(handle) = observed.upgrade() {
2290 on_notify(handle, window, cx);
2291 true
2292 } else {
2293 false
2294 }
2295 })
2296 .unwrap_or(false)
2297 }),
2298 )
2299 }
2300
2301 pub fn subscribe<Emitter, Evt>(
2305 &mut self,
2306 entity: &Entity<Emitter>,
2307 cx: &mut App,
2308 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
2309 ) -> Subscription
2310 where
2311 Emitter: EventEmitter<Evt>,
2312 Evt: 'static,
2313 {
2314 let entity_id = entity.entity_id();
2315 let handle = entity.downgrade();
2316 let window_handle = self.handle;
2317 cx.new_subscription(
2318 entity_id,
2319 (
2320 TypeId::of::<Evt>(),
2321 Box::new(move |event, cx| {
2322 window_handle
2323 .update(cx, |_, window, cx| {
2324 if let Some(entity) = handle.upgrade() {
2325 let event = event.downcast_ref().expect("invalid event type");
2326 on_event(entity, event, window, cx);
2327 true
2328 } else {
2329 false
2330 }
2331 })
2332 .unwrap_or(false)
2333 }),
2334 ),
2335 )
2336 }
2337
2338 pub fn observe_release<T>(
2340 &self,
2341 entity: &Entity<T>,
2342 cx: &mut App,
2343 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2344 ) -> Subscription
2345 where
2346 T: 'static,
2347 {
2348 let entity_id = entity.entity_id();
2349 let window_handle = self.handle;
2350 let (subscription, activate) = cx.release_listeners.insert(
2351 entity_id,
2352 Box::new(move |entity, cx| {
2353 let entity = entity.downcast_mut().expect("invalid entity type");
2354 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2355 }),
2356 );
2357 activate();
2358 subscription
2359 }
2360
2361 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2364 AsyncWindowContext::new_context(cx.to_async(), self.handle)
2365 }
2366
2367 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2369 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2370 }
2371
2372 pub fn request_animation_frame(&self) {
2385 let entity = self.current_view();
2386 self.on_next_frame(move |_, cx| cx.notify(entity));
2387 }
2388
2389 #[cfg(any(test, feature = "test-support"))]
2394 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
2395 let callbacks = self.next_frame_callbacks.take();
2396 let count = callbacks.len();
2397 for callback in callbacks {
2398 callback(self, cx);
2399 }
2400 count
2401 }
2402
2403 #[track_caller]
2407 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2408 where
2409 R: 'static,
2410 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2411 {
2412 let handle = self.handle;
2413 cx.spawn(async move |app| {
2414 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2415 f(&mut async_window_cx).await
2416 })
2417 }
2418
2419 #[track_caller]
2423 pub fn spawn_with_priority<AsyncFn, R>(
2424 &self,
2425 priority: Priority,
2426 cx: &App,
2427 f: AsyncFn,
2428 ) -> Task<R>
2429 where
2430 R: 'static,
2431 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2432 {
2433 let handle = self.handle;
2434 cx.spawn_with_priority(priority, async move |app| {
2435 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2436 f(&mut async_window_cx).await
2437 })
2438 }
2439
2440 pub fn bounds_changed(&mut self, cx: &mut App) {
2446 self.scale_factor = self.platform_window.scale_factor();
2447 self.viewport_size = self.platform_window.content_size();
2448 self.display_id = self.platform_window.display().map(|display| display.id());
2449 self.mouse_position = self.platform_window.mouse_position();
2450
2451 self.refresh();
2452
2453 self.bounds_observers
2454 .clone()
2455 .retain(&(), |callback| callback(self, cx));
2456 }
2457
2458 pub fn bounds(&self) -> Bounds<Pixels> {
2460 self.platform_window.bounds()
2461 }
2462
2463 #[cfg(any(test, feature = "test-support"))]
2467 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
2468 self.platform_window
2469 .render_to_image(&self.rendered_frame.scene)
2470 }
2471
2472 pub fn resize(&mut self, size: Size<Pixels>) {
2474 self.platform_window.resize(size);
2475 }
2476
2477 pub fn is_fullscreen(&self) -> bool {
2479 self.platform_window.is_fullscreen()
2480 }
2481
2482 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
2483 self.appearance = self.platform_window.appearance();
2484
2485 self.appearance_observers
2486 .clone()
2487 .retain(&(), |callback| callback(self, cx));
2488 }
2489
2490 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2491 self.button_layout_observers
2492 .clone()
2493 .retain(&(), |callback| callback(self, cx));
2494 }
2495
2496 pub fn appearance(&self) -> WindowAppearance {
2498 self.appearance
2499 }
2500
2501 pub fn viewport_size(&self) -> Size<Pixels> {
2503 self.viewport_size
2504 }
2505
2506 pub fn is_window_active(&self) -> bool {
2508 self.active.get()
2509 }
2510
2511 pub fn is_window_hovered(&self) -> bool {
2515 if cfg!(any(
2516 target_os = "windows",
2517 target_os = "linux",
2518 target_os = "freebsd"
2519 )) {
2520 self.hovered.get()
2521 } else {
2522 self.is_window_active()
2523 }
2524 }
2525
2526 pub fn zoom_window(&self) {
2528 self.platform_window.zoom();
2529 }
2530
2531 pub fn show_window_menu(&self, position: Point<Pixels>) {
2533 self.platform_window.show_window_menu(position)
2534 }
2535
2536 pub fn start_window_move(&self) {
2541 self.platform_window.start_window_move()
2542 }
2543
2544 pub fn set_client_inset(&mut self, inset: Pixels) {
2546 self.client_inset = Some(inset);
2547 self.platform_window.set_client_inset(inset);
2548 }
2549
2550 pub fn client_inset(&self) -> Option<Pixels> {
2552 self.client_inset
2553 }
2554
2555 pub fn window_decorations(&self) -> Decorations {
2557 self.platform_window.window_decorations()
2558 }
2559
2560 pub fn is_resizable(&self) -> bool {
2562 self.is_resizable
2563 }
2564
2565 pub fn is_minimizable(&self) -> bool {
2567 self.is_minimizable
2568 }
2569
2570 pub fn window_controls(&self) -> WindowControls {
2572 self.platform_window.window_controls()
2573 }
2574
2575 pub fn set_window_title(&mut self, title: &str) {
2577 self.platform_window.set_title(title);
2578 self.a11y.set_window_title(title.to_string());
2579 }
2580
2581 #[cfg(target_os = "macos")]
2583 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
2584 self.platform_window.set_traffic_light_position(position);
2585 }
2586
2587 pub fn set_app_id(&mut self, app_id: &str) {
2589 self.platform_window.set_app_id(app_id);
2590 }
2591
2592 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2594 self.platform_window
2595 .set_background_appearance(background_appearance);
2596 }
2597
2598 pub fn set_window_edited(&mut self, edited: bool) {
2600 self.platform_window.set_edited(edited);
2601 }
2602
2603 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
2606 self.platform_window.set_document_path(path);
2607 }
2608
2609 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2611 cx.platform
2612 .displays()
2613 .into_iter()
2614 .find(|display| Some(display.id()) == self.display_id)
2615 }
2616
2617 pub fn show_character_palette(&self) {
2619 self.platform_window.show_character_palette();
2620 }
2621
2622 pub fn scale_factor(&self) -> f32 {
2626 self.scale_factor
2627 }
2628
2629 #[cfg(any(test, feature = "test-support"))]
2631 pub fn set_scale_factor(&mut self, scale_factor: f32) {
2632 self.scale_factor = scale_factor;
2633 self.refresh();
2634 }
2635
2636 pub fn rem_size(&self) -> Pixels {
2639 self.rem_size_override_stack
2640 .last()
2641 .copied()
2642 .unwrap_or(self.rem_size)
2643 }
2644
2645 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2648 self.rem_size = rem_size.into();
2649 }
2650
2651 pub fn with_global_id<R>(
2654 &mut self,
2655 element_id: ElementId,
2656 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2657 ) -> R {
2658 self.with_id(element_id, |this| {
2659 let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2660
2661 f(&global_id, this)
2662 })
2663 }
2664
2665 #[inline]
2667 pub fn with_id<R>(
2668 &mut self,
2669 element_id: impl Into<ElementId>,
2670 f: impl FnOnce(&mut Self) -> R,
2671 ) -> R {
2672 self.element_id_stack.push(element_id.into());
2673 let result = f(self);
2674 self.element_id_stack.pop();
2675 result
2676 }
2677
2678 #[inline]
2684 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2685 where
2686 F: FnOnce(&mut Self) -> R,
2687 {
2688 self.invalidator.debug_assert_paint_or_prepaint();
2689
2690 if let Some(rem_size) = rem_size {
2691 self.rem_size_override_stack.push(rem_size.into());
2692 let result = f(self);
2693 self.rem_size_override_stack.pop();
2694 result
2695 } else {
2696 f(self)
2697 }
2698 }
2699
2700 pub fn line_height(&self) -> Pixels {
2702 self.text_style().line_height_in_pixels(self.rem_size())
2703 }
2704
2705 #[inline]
2707 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
2708 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
2709 }
2710
2711 #[inline]
2713 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
2714 let scale_factor = f64::from(self.scale_factor());
2715 round_half_toward_zero_f64(value * scale_factor) / scale_factor
2716 }
2717
2718 #[inline]
2720 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
2721 bounds.map(|c| self.pixel_snap(c))
2722 }
2723
2724 #[inline]
2726 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
2727 position.map(|c| self.pixel_snap(c))
2728 }
2729
2730 #[inline]
2731 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2732 let scale_factor = self.scale_factor();
2733 let left = round_to_device_pixel(bounds.left().0, scale_factor);
2734 let top = round_to_device_pixel(bounds.top().0, scale_factor);
2735 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
2736 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2737 Bounds::from_corners(
2738 point(ScaledPixels(left), ScaledPixels(top)),
2739 point(ScaledPixels(right), ScaledPixels(bottom)),
2740 )
2741 }
2742
2743 #[inline]
2745 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
2746 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
2747 }
2748
2749 #[inline]
2750 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
2751 edges.map(|e| self.snap_stroke(*e))
2752 }
2753
2754 #[inline]
2756 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2757 let scale_factor = self.scale_factor();
2758 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
2759 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
2760 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
2761 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2762 Bounds::from_corners(
2763 point(ScaledPixels(left), ScaledPixels(top)),
2764 point(ScaledPixels(right), ScaledPixels(bottom)),
2765 )
2766 }
2767
2768 #[inline]
2769 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
2770 ContentMask {
2771 bounds: self.cover_bounds(self.content_mask().bounds),
2772 }
2773 }
2774
2775 pub fn prevent_default(&mut self) {
2778 self.default_prevented = true;
2779 }
2780
2781 pub fn default_prevented(&self) -> bool {
2783 self.default_prevented
2784 }
2785
2786 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2788 let node_id =
2789 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2790 self.rendered_frame
2791 .dispatch_tree
2792 .is_action_available(action, node_id)
2793 }
2794
2795 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2797 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2798 self.rendered_frame
2799 .dispatch_tree
2800 .is_action_available(action, node_id)
2801 }
2802
2803 pub fn mouse_position(&self) -> Point<Pixels> {
2805 self.mouse_position
2806 }
2807
2808 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
2815 self.captured_hitbox = Some(hitbox_id);
2816 }
2817
2818 pub fn release_pointer(&mut self) {
2820 self.captured_hitbox = None;
2821 }
2822
2823 pub fn captured_hitbox(&self) -> Option<HitboxId> {
2825 self.captured_hitbox
2826 }
2827
2828 pub fn modifiers(&self) -> Modifiers {
2830 self.modifiers
2831 }
2832
2833 pub fn last_input_was_keyboard(&self) -> bool {
2836 self.last_input_modality == InputModality::Keyboard
2837 }
2838
2839 pub fn capslock(&self) -> Capslock {
2841 self.capslock
2842 }
2843
2844 fn complete_frame(&self) {
2845 self.platform_window.completed_frame();
2846 }
2847
2848 #[profiling::function]
2851 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2852 let frame_dirty = self.invalidator.take_frame_dirty();
2855 let draw_started_at = profiler::frame_trace_enabled().then(Instant::now);
2856
2857 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
2860
2861 self.invalidate_entities();
2862 cx.entities.clear_accessed();
2863 debug_assert!(self.rendered_entity_stack.is_empty());
2864 self.invalidator.set_dirty(false);
2865 self.requested_autoscroll = None;
2866
2867 if let Some(input_handler) = self.platform_window.take_input_handler() {
2872 if let Some(slot) = self
2873 .rendered_frame
2874 .input_handlers
2875 .iter_mut()
2876 .rev()
2877 .find(|h| h.is_none())
2878 {
2879 *slot = Some(input_handler);
2880 } else {
2881 self.rendered_frame.input_handlers.push(Some(input_handler));
2882 }
2883 }
2884 if !cx.mode.skip_drawing() {
2885 self.draw_roots(cx);
2886 }
2887 self.dirty_views.clear();
2888 self.next_frame.window_active = self.active.get();
2889
2890 if let Some(input_handler) = self
2896 .next_frame
2897 .input_handlers
2898 .iter_mut()
2899 .rev()
2900 .find_map(|h| h.take())
2901 {
2902 self.platform_window.set_input_handler(input_handler);
2903 }
2904
2905 self.layout_engine.as_mut().unwrap().clear();
2906 self.text_system().finish_frame();
2907 self.next_frame.finish(&mut self.rendered_frame);
2908
2909 self.invalidator.set_phase(DrawPhase::Focus);
2910 let previous_focus_path = self.rendered_frame.focus_path();
2911 let previous_window_active = self.rendered_frame.window_active;
2912 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2913 self.next_frame.clear();
2914 let current_focus_path = self.rendered_frame.focus_path();
2915 let current_window_active = self.rendered_frame.window_active;
2916 let mut focus_before_listeners = self.focus;
2917
2918 if previous_focus_path != current_focus_path
2919 || previous_window_active != current_window_active
2920 {
2921 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2922 self.focus_lost_listeners
2923 .clone()
2924 .retain(&(), |listener| listener(self, cx));
2925 focus_before_listeners = self.focus;
2930 }
2931
2932 let event = WindowFocusEvent {
2933 previous_focus_path: if previous_window_active {
2934 previous_focus_path
2935 } else {
2936 Default::default()
2937 },
2938 current_focus_path: if current_window_active {
2939 current_focus_path
2940 } else {
2941 Default::default()
2942 },
2943 };
2944 self.focus_listeners
2945 .clone()
2946 .retain(&(), |listener| listener(&event, self, cx));
2947 }
2948
2949 debug_assert!(self.rendered_entity_stack.is_empty());
2950 self.record_entities_accessed(cx);
2951 self.reset_cursor_style(cx);
2952 self.refreshing = false;
2953 self.invalidator.set_phase(DrawPhase::None);
2954 if self.focus != focus_before_listeners {
2959 self.refresh();
2960 }
2961 self.needs_present.set(true);
2962
2963 if let Some(draw_start) = draw_started_at {
2964 profiler::record_frame_timing(profiler::FrameTiming {
2965 window_id: self.handle.window_id(),
2966 dirty_at: frame_dirty.dirty_at,
2967 invalidations: frame_dirty.invalidations,
2968 draw_start,
2969 draw_end: Instant::now(),
2970 });
2971 }
2972
2973 arena_scope.exit(&cx.element_arena)
2976 }
2977
2978 fn record_entities_accessed(&mut self, cx: &mut App) {
2979 let mut entities_ref = cx.entities.accessed_entities.get_mut();
2980 let mut entities = mem::take(entities_ref.deref_mut());
2981 let handle = self.handle;
2982 cx.record_entities_accessed(
2983 handle,
2984 self.invalidator.clone(),
2986 &entities,
2987 );
2988 let mut entities_ref = cx.entities.accessed_entities.get_mut();
2989 mem::swap(&mut entities, entities_ref.deref_mut());
2990 }
2991
2992 fn invalidate_entities(&mut self) {
2993 let mut views = self.invalidator.take_views();
2994 for entity in views.drain() {
2995 self.mark_view_dirty(entity);
2996 }
2997 self.invalidator.replace_views(views);
2998 }
2999
3000 #[profiling::function]
3001 fn present(&mut self) {
3002 self.platform_window.draw(&self.rendered_frame.scene);
3003 #[cfg(feature = "input-latency-histogram")]
3004 self.input_latency_tracker.record_frame_presented();
3005 self.needs_present.set(false);
3006 profiling::finish_frame!();
3007 }
3008
3009 #[cfg(feature = "bench")]
3015 pub fn present_if_needed(&mut self) {
3016 if self.needs_present.get() {
3017 self.present();
3018 }
3019 }
3020
3021 #[cfg(feature = "input-latency-histogram")]
3023 pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
3024 self.input_latency_tracker.snapshot()
3025 }
3026
3027 fn draw_roots(&mut self, cx: &mut App) {
3028 self.invalidator.set_phase(DrawPhase::Prepaint);
3029 self.tooltip_bounds.take();
3030
3031 self.a11y.sync_active_flag();
3032 if self.a11y.is_active() {
3033 self.a11y.begin_frame();
3034 }
3035
3036 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
3037 let root_size = {
3038 #[cfg(any(feature = "inspector", debug_assertions))]
3039 {
3040 if self.inspector.is_some() {
3041 let mut size = self.viewport_size;
3042 size.width = (size.width - _inspector_width).max(px(0.0));
3043 size
3044 } else {
3045 self.viewport_size
3046 }
3047 }
3048 #[cfg(not(any(feature = "inspector", debug_assertions)))]
3049 {
3050 self.viewport_size
3051 }
3052 };
3053
3054 let scale_factor = self.scale_factor();
3058 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
3059 let root_layout_id = root_element.request_layout(self, cx);
3060 self.layout_engine
3061 .as_mut()
3062 .unwrap()
3063 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
3064 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3065
3066 #[cfg(any(feature = "inspector", debug_assertions))]
3067 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
3068
3069 self.prepaint_deferred_draws(cx);
3070
3071 let mut prompt_element = None;
3072 let mut active_drag_element = None;
3073 let mut tooltip_element = None;
3074 if let Some(prompt) = self.prompt.take() {
3075 let mut element = prompt.view.any_view().into_any_element();
3076 let prompt_layout_id = element.request_layout(self, cx);
3077 self.layout_engine
3078 .as_mut()
3079 .unwrap()
3080 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
3081 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3082 prompt_element = Some(element);
3083 self.prompt = Some(prompt);
3084 } else if let Some(active_drag) = cx.active_drag.take() {
3085 let mut element = active_drag.view.clone().into_any_element();
3086 let offset = self.mouse_position() - active_drag.cursor_offset;
3087 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
3088 active_drag_element = Some(element);
3089 cx.active_drag = Some(active_drag);
3090 } else {
3091 tooltip_element = self.prepaint_tooltip(cx);
3092 }
3093
3094 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
3095
3096 self.invalidator.set_phase(DrawPhase::Paint);
3098 root_element.paint(self, cx);
3099
3100 #[cfg(any(feature = "inspector", debug_assertions))]
3101 self.paint_inspector(inspector_element, cx);
3102
3103 self.paint_deferred_draws(cx);
3104
3105 if let Some(mut prompt_element) = prompt_element {
3106 prompt_element.paint(self, cx);
3107 } else if let Some(mut drag_element) = active_drag_element {
3108 drag_element.paint(self, cx);
3109 } else if let Some(mut tooltip_element) = tooltip_element {
3110 tooltip_element.paint(self, cx);
3111 }
3112
3113 #[cfg(any(feature = "inspector", debug_assertions))]
3114 self.paint_inspector_hitbox(cx);
3115
3116 let a11y_active_start_of_frame = self.a11y.is_active();
3118 self.a11y.sync_active_flag();
3119 let a11y_active_end_of_frame = self.a11y.is_active();
3120
3121 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
3122
3123 if a11y_active_start_of_frame {
3124 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
3127 viewport_size: self.viewport_size,
3128 scale_factor: self.scale_factor,
3129 tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
3130 };
3131 let tree_update = self.a11y.end_frame(frame_info);
3133
3134 if should_send_a11y_update {
3135 log::debug!(
3136 "Sending a11y tree update: {} nodes",
3137 tree_update.nodes.len()
3138 );
3139 self.platform_window.a11y_tree_update(tree_update);
3140 }
3141 }
3142 }
3143
3144 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
3145 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
3147 let Some(Some(tooltip_request)) = self
3148 .next_frame
3149 .tooltip_requests
3150 .get(tooltip_request_index)
3151 .cloned()
3152 else {
3153 log::error!("Unexpectedly absent TooltipRequest");
3154 continue;
3155 };
3156 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
3157 let mouse_position = tooltip_request.tooltip.mouse_position;
3158 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
3159
3160 let mut tooltip_bounds =
3161 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
3162 let window_bounds = Bounds {
3163 origin: Point::default(),
3164 size: self.viewport_size(),
3165 };
3166
3167 if tooltip_bounds.right() > window_bounds.right() {
3168 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
3169 if new_x >= Pixels::ZERO {
3170 tooltip_bounds.origin.x = new_x;
3171 } else {
3172 tooltip_bounds.origin.x = cmp::max(
3173 Pixels::ZERO,
3174 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
3175 );
3176 }
3177 }
3178
3179 if tooltip_bounds.bottom() > window_bounds.bottom() {
3180 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
3181 if new_y >= Pixels::ZERO {
3182 tooltip_bounds.origin.y = new_y;
3183 } else {
3184 tooltip_bounds.origin.y = cmp::max(
3185 Pixels::ZERO,
3186 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
3187 );
3188 }
3189 }
3190
3191 let is_visible =
3195 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
3196 if !is_visible {
3197 continue;
3198 }
3199
3200 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
3201 element.prepaint(window, cx)
3202 });
3203
3204 self.tooltip_bounds = Some(TooltipBounds {
3205 id: tooltip_request.id,
3206 bounds: tooltip_bounds,
3207 });
3208 return Some(element);
3209 }
3210 None
3211 }
3212
3213 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
3214 assert_eq!(self.element_id_stack.len(), 0);
3215
3216 let mut round_start = 0;
3227 let mut depth = 0;
3228 loop {
3229 let round_end = self.next_frame.deferred_draws.len();
3230 if round_start == round_end {
3231 break;
3232 }
3233 assert!(depth < 10, "Exceeded maximum (10) deferred depth");
3235 depth += 1;
3236
3237 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
3239 traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3240
3241 for deferred_draw_ix in traversal_order {
3242 let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
3243 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
3244 self.element_id_stack
3245 .clone_from(&deferred_draw.element_id_stack);
3246 self.text_style_stack
3247 .clone_from(&deferred_draw.text_style_stack);
3248 (
3249 deferred_draw.element.take(),
3250 deferred_draw.parent_node,
3251 deferred_draw.current_view,
3252 deferred_draw.rem_size,
3253 deferred_draw.absolute_offset,
3254 deferred_draw.prepaint_range.clone(),
3255 )
3256 };
3257 self.next_frame.dispatch_tree.set_active_node(parent_node);
3258
3259 let prepaint_start = self.prepaint_index();
3260 if let Some(mut element) = element {
3261 self.with_rendered_view(current_view, |window| {
3262 window.with_rem_size(Some(rem_size), |window| {
3263 window.with_absolute_element_offset(absolute_offset, |window| {
3264 element.prepaint(window, cx);
3265 });
3266 });
3267 });
3268 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
3269 } else {
3270 self.reuse_prepaint(prepaint_range);
3271 }
3272 let prepaint_end = self.prepaint_index();
3273 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
3274 prepaint_start..prepaint_end;
3275 }
3276
3277 self.element_id_stack.clear();
3278 self.text_style_stack.clear();
3279 round_start = round_end;
3280 }
3281 }
3282
3283 fn paint_deferred_draws(&mut self, cx: &mut App) {
3284 assert_eq!(self.element_id_stack.len(), 0);
3285
3286 if self.next_frame.deferred_draws.len() == 0 {
3289 return;
3290 }
3291
3292 let traversal_order = self.deferred_draw_traversal_order();
3293 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
3294 for deferred_draw_ix in traversal_order {
3295 let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
3296 self.element_id_stack
3297 .clone_from(&deferred_draw.element_id_stack);
3298 self.next_frame
3299 .dispatch_tree
3300 .set_active_node(deferred_draw.parent_node);
3301
3302 let paint_start = self.paint_index();
3303 let content_mask = deferred_draw.content_mask;
3304 if let Some(element) = deferred_draw.element.as_mut() {
3305 self.with_rendered_view(deferred_draw.current_view, |window| {
3306 window.with_content_mask(content_mask, |window| {
3307 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
3308 element.paint(window, cx);
3309 });
3310 })
3311 })
3312 } else {
3313 self.reuse_paint(deferred_draw.paint_range.clone());
3314 }
3315 let paint_end = self.paint_index();
3316 deferred_draw.paint_range = paint_start..paint_end;
3317 }
3318 self.next_frame.deferred_draws = deferred_draws;
3319 self.element_id_stack.clear();
3320 }
3321
3322 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
3323 let deferred_count = self.next_frame.deferred_draws.len();
3324 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
3325 sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3326 sorted_indices
3327 }
3328
3329 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
3330 PrepaintStateIndex {
3331 hitboxes_index: self.next_frame.hitboxes.len(),
3332 tooltips_index: self.next_frame.tooltip_requests.len(),
3333 deferred_draws_index: self.next_frame.deferred_draws.len(),
3334 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
3335 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3336 line_layout_index: self.text_system.layout_index(),
3337 }
3338 }
3339
3340 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
3341 self.next_frame.hitboxes.extend(
3342 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
3343 .iter()
3344 .cloned(),
3345 );
3346 self.next_frame.tooltip_requests.extend(
3347 self.rendered_frame.tooltip_requests
3348 [range.start.tooltips_index..range.end.tooltips_index]
3349 .iter_mut()
3350 .map(|request| request.take()),
3351 );
3352 self.next_frame.accessed_element_states.extend(
3353 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3354 ..range.end.accessed_element_states_index]
3355 .iter()
3356 .map(|(id, type_id)| (id.clone(), *type_id)),
3357 );
3358 self.text_system
3359 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3360
3361 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
3362 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
3363 &mut self.rendered_frame.dispatch_tree,
3364 self.focus,
3365 );
3366
3367 if reused_subtree.contains_focus() {
3368 self.next_frame.focus = self.focus;
3369 }
3370
3371 self.next_frame.deferred_draws.extend(
3372 self.rendered_frame.deferred_draws
3373 [range.start.deferred_draws_index..range.end.deferred_draws_index]
3374 .iter()
3375 .map(|deferred_draw| DeferredDraw {
3376 current_view: deferred_draw.current_view,
3377 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
3378 element_id_stack: deferred_draw.element_id_stack.clone(),
3379 text_style_stack: deferred_draw.text_style_stack.clone(),
3380 content_mask: deferred_draw.content_mask,
3381 rem_size: deferred_draw.rem_size,
3382 priority: deferred_draw.priority,
3383 element: None,
3384 absolute_offset: deferred_draw.absolute_offset,
3385 prepaint_range: deferred_draw.prepaint_range.clone(),
3386 paint_range: deferred_draw.paint_range.clone(),
3387 }),
3388 );
3389 }
3390
3391 pub(crate) fn paint_index(&self) -> PaintIndex {
3392 PaintIndex {
3393 scene_index: self.next_frame.scene.len(),
3394 #[cfg(any(test, feature = "test-support"))]
3395 debug_bounds_index: self.next_frame.debug_bounds_records.len(),
3396 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
3397 input_handlers_index: self.next_frame.input_handlers.len(),
3398 cursor_styles_index: self.next_frame.cursor_styles.len(),
3399 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3400 tab_handle_index: self.next_frame.tab_stops.paint_index(),
3401 line_layout_index: self.text_system.layout_index(),
3402 }
3403 }
3404
3405 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
3406 #[cfg(any(test, feature = "test-support"))]
3408 for (selector, bounds) in &self.rendered_frame.debug_bounds_records
3409 [range.start.debug_bounds_index..range.end.debug_bounds_index]
3410 {
3411 self.next_frame
3412 .record_debug_bounds(selector.clone(), *bounds);
3413 }
3414 self.next_frame.cursor_styles.extend(
3415 self.rendered_frame.cursor_styles
3416 [range.start.cursor_styles_index..range.end.cursor_styles_index]
3417 .iter()
3418 .cloned(),
3419 );
3420 self.next_frame.input_handlers.extend(
3421 self.rendered_frame.input_handlers
3422 [range.start.input_handlers_index..range.end.input_handlers_index]
3423 .iter_mut()
3424 .map(|handler| handler.take()),
3425 );
3426 self.next_frame.mouse_listeners.extend(
3427 self.rendered_frame.mouse_listeners
3428 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
3429 .iter_mut()
3430 .map(|listener| listener.take()),
3431 );
3432 self.next_frame.accessed_element_states.extend(
3433 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3434 ..range.end.accessed_element_states_index]
3435 .iter()
3436 .map(|(id, type_id)| (id.clone(), *type_id)),
3437 );
3438 self.next_frame.tab_stops.replay(
3439 &self.rendered_frame.tab_stops.insertion_history
3440 [range.start.tab_handle_index..range.end.tab_handle_index],
3441 );
3442
3443 self.text_system
3444 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3445 self.next_frame.scene.replay(
3446 range.start.scene_index..range.end.scene_index,
3447 &self.rendered_frame.scene,
3448 );
3449 }
3450
3451 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
3455 where
3456 F: FnOnce(&mut Self) -> R,
3457 {
3458 self.invalidator.debug_assert_paint_or_prepaint();
3459 if let Some(style) = style {
3460 self.text_style_stack.push(style);
3461 let result = f(self);
3462 self.text_style_stack.pop();
3463 result
3464 } else {
3465 f(self)
3466 }
3467 }
3468
3469 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
3472 self.invalidator.debug_assert_paint();
3473 self.next_frame.cursor_styles.push(CursorStyleRequest {
3474 hitbox_id: Some(hitbox.id),
3475 style,
3476 });
3477 }
3478
3479 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
3484 self.invalidator.debug_assert_paint();
3485 self.next_frame.cursor_styles.push(CursorStyleRequest {
3486 hitbox_id: None,
3487 style,
3488 })
3489 }
3490
3491 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
3494 self.invalidator.debug_assert_prepaint();
3495 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
3496 self.next_frame
3497 .tooltip_requests
3498 .push(Some(TooltipRequest { id, tooltip }));
3499 id
3500 }
3501
3502 #[inline]
3507 pub fn with_content_mask<R>(
3508 &mut self,
3509 mask: Option<ContentMask<Pixels>>,
3510 f: impl FnOnce(&mut Self) -> R,
3511 ) -> R {
3512 self.invalidator.debug_assert_paint_or_prepaint();
3513 if let Some(mask) = mask {
3514 let mask = mask.intersect(&self.content_mask());
3515 self.content_mask_stack.push(mask);
3516 let result = f(self);
3517 self.content_mask_stack.pop();
3518 result
3519 } else {
3520 f(self)
3521 }
3522 }
3523
3524 pub fn with_element_offset<R>(
3527 &mut self,
3528 offset: Point<Pixels>,
3529 f: impl FnOnce(&mut Self) -> R,
3530 ) -> R {
3531 self.invalidator.debug_assert_prepaint();
3532
3533 if offset.is_zero() {
3534 return f(self);
3535 };
3536
3537 let abs_offset = self.element_offset() + offset;
3538 self.with_absolute_element_offset(abs_offset, f)
3539 }
3540
3541 pub fn with_absolute_element_offset<R>(
3545 &mut self,
3546 offset: Point<Pixels>,
3547 f: impl FnOnce(&mut Self) -> R,
3548 ) -> R {
3549 self.invalidator.debug_assert_prepaint();
3550 self.element_offset_stack.push(offset);
3551 let result = f(self);
3552 self.element_offset_stack.pop();
3553 result
3554 }
3555
3556 pub(crate) fn with_element_opacity<R>(
3557 &mut self,
3558 opacity: Option<f32>,
3559 f: impl FnOnce(&mut Self) -> R,
3560 ) -> R {
3561 self.invalidator.debug_assert_paint_or_prepaint();
3562
3563 let Some(opacity) = opacity else {
3564 return f(self);
3565 };
3566
3567 let previous_opacity = self.element_opacity;
3568 self.element_opacity = previous_opacity * opacity;
3569 let result = f(self);
3570 self.element_opacity = previous_opacity;
3571 result
3572 }
3573
3574 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
3580 self.invalidator.debug_assert_prepaint();
3581 let index = self.prepaint_index();
3582 let result = f(self);
3583 if result.is_err() {
3584 self.next_frame.hitboxes.truncate(index.hitboxes_index);
3585 self.next_frame
3586 .tooltip_requests
3587 .truncate(index.tooltips_index);
3588 self.next_frame
3589 .deferred_draws
3590 .truncate(index.deferred_draws_index);
3591 self.next_frame
3592 .dispatch_tree
3593 .truncate(index.dispatch_tree_index);
3594 self.next_frame
3595 .accessed_element_states
3596 .truncate(index.accessed_element_states_index);
3597 self.text_system.truncate_layouts(index.line_layout_index);
3598 }
3599 result
3600 }
3601
3602 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
3608 self.invalidator.debug_assert_prepaint();
3609 self.requested_autoscroll = Some(bounds);
3610 }
3611
3612 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
3615 self.invalidator.debug_assert_prepaint();
3616 self.requested_autoscroll.take()
3617 }
3618
3619 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3625 let (task, is_first) = cx.fetch_asset::<A>(source);
3626 task.clone().now_or_never().or_else(|| {
3627 if is_first {
3628 let entity_id = self.current_view();
3629 self.spawn(cx, {
3630 let task = task.clone();
3631 async move |cx| {
3632 task.await;
3633
3634 cx.on_next_frame(move |_, cx| {
3635 cx.notify(entity_id);
3636 });
3637 }
3638 })
3639 .detach();
3640 }
3641
3642 None
3643 })
3644 }
3645
3646 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3652 let (task, _) = cx.fetch_asset::<A>(source);
3653 task.now_or_never()
3654 }
3655 pub fn element_offset(&self) -> Point<Pixels> {
3658 self.invalidator.debug_assert_prepaint();
3659 self.element_offset_stack
3660 .last()
3661 .copied()
3662 .unwrap_or_default()
3663 }
3664
3665 #[inline]
3668 pub(crate) fn element_opacity(&self) -> f32 {
3669 self.invalidator.debug_assert_paint_or_prepaint();
3670 self.element_opacity
3671 }
3672
3673 pub fn content_mask(&self) -> ContentMask<Pixels> {
3675 self.invalidator.debug_assert_paint_or_prepaint();
3676 self.content_mask_stack
3677 .last()
3678 .cloned()
3679 .unwrap_or_else(|| ContentMask {
3680 bounds: Bounds {
3681 origin: Point::default(),
3682 size: self.viewport_size,
3683 },
3684 })
3685 }
3686
3687 pub fn with_element_namespace<R>(
3690 &mut self,
3691 element_id: impl Into<ElementId>,
3692 f: impl FnOnce(&mut Self) -> R,
3693 ) -> R {
3694 self.element_id_stack.push(element_id.into());
3695 let result = f(self);
3696 self.element_id_stack.pop();
3697 result
3698 }
3699
3700 pub fn use_keyed_state<S: 'static>(
3702 &mut self,
3703 key: impl Into<ElementId>,
3704 cx: &mut App,
3705 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3706 ) -> Entity<S> {
3707 let current_view = self.current_view();
3708 self.with_global_id(key.into(), |global_id, window| {
3709 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
3710 if let Some(state) = state {
3711 (state.clone(), state)
3712 } else {
3713 let new_state = cx.new(|cx| init(window, cx));
3714 cx.observe(&new_state, move |_, cx| {
3715 cx.notify(current_view);
3716 })
3717 .detach();
3718 (new_state.clone(), new_state)
3719 }
3720 })
3721 })
3722 }
3723
3724 #[track_caller]
3730 pub fn use_state<S: 'static>(
3731 &mut self,
3732 cx: &mut App,
3733 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3734 ) -> Entity<S> {
3735 self.use_keyed_state(
3736 ElementId::CodeLocation(*core::panic::Location::caller()),
3737 cx,
3738 init,
3739 )
3740 }
3741
3742 pub fn with_element_state<S, R>(
3747 &mut self,
3748 global_id: &GlobalElementId,
3749 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
3750 ) -> R
3751 where
3752 S: 'static,
3753 {
3754 self.invalidator.debug_assert_paint_or_prepaint();
3755
3756 let key = (global_id.clone(), TypeId::of::<S>());
3757 self.next_frame.accessed_element_states.push(key.clone());
3758
3759 if let Some(any) = self
3760 .next_frame
3761 .element_states
3762 .remove(&key)
3763 .or_else(|| self.rendered_frame.element_states.remove(&key))
3764 {
3765 let ElementStateBox {
3766 inner,
3767 #[cfg(debug_assertions)]
3768 type_name,
3769 } = any;
3770 let mut state_box = inner
3772 .downcast::<Option<S>>()
3773 .map_err(|_| {
3774 #[cfg(debug_assertions)]
3775 {
3776 anyhow::anyhow!(
3777 "invalid element state type for id, requested {:?}, actual: {:?}",
3778 std::any::type_name::<S>(),
3779 type_name
3780 )
3781 }
3782
3783 #[cfg(not(debug_assertions))]
3784 {
3785 anyhow::anyhow!(
3786 "invalid element state type for id, requested {:?}",
3787 std::any::type_name::<S>(),
3788 )
3789 }
3790 })
3791 .unwrap();
3792
3793 let state = state_box.take().expect(
3794 "reentrant call to with_element_state for the same state type and element id",
3795 );
3796 let (result, state) = f(Some(state), self);
3797 state_box.replace(state);
3798 self.next_frame.element_states.insert(
3799 key,
3800 ElementStateBox {
3801 inner: state_box,
3802 #[cfg(debug_assertions)]
3803 type_name,
3804 },
3805 );
3806 result
3807 } else {
3808 let (result, state) = f(None, self);
3809 self.next_frame.element_states.insert(
3810 key,
3811 ElementStateBox {
3812 inner: Box::new(Some(state)),
3813 #[cfg(debug_assertions)]
3814 type_name: std::any::type_name::<S>(),
3815 },
3816 );
3817 result
3818 }
3819 }
3820
3821 pub fn with_optional_element_state<S, R>(
3828 &mut self,
3829 global_id: Option<&GlobalElementId>,
3830 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
3831 ) -> R
3832 where
3833 S: 'static,
3834 {
3835 self.invalidator.debug_assert_paint_or_prepaint();
3836
3837 if let Some(global_id) = global_id {
3838 self.with_element_state(global_id, |state, cx| {
3839 let (result, state) = f(Some(state), cx);
3840 let state =
3841 state.expect("you must return some state when you pass some element id");
3842 (result, state)
3843 })
3844 } else {
3845 let (result, state) = f(None, self);
3846 debug_assert!(
3847 state.is_none(),
3848 "you must not return an element state when passing None for the global id"
3849 );
3850 result
3851 }
3852 }
3853
3854 #[inline]
3856 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
3857 if let Some(index) = index {
3858 self.next_frame.tab_stops.begin_group(index);
3859 let result = f(self);
3860 self.next_frame.tab_stops.end_group();
3861 result
3862 } else {
3863 f(self)
3864 }
3865 }
3866
3867 pub fn defer_draw(
3876 &mut self,
3877 element: AnyElement,
3878 absolute_offset: Point<Pixels>,
3879 priority: usize,
3880 content_mask: Option<ContentMask<Pixels>>,
3881 ) {
3882 self.invalidator.debug_assert_prepaint();
3883 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3884 self.next_frame.deferred_draws.push(DeferredDraw {
3885 current_view: self.current_view(),
3886 parent_node,
3887 element_id_stack: self.element_id_stack.clone(),
3888 text_style_stack: self.text_style_stack.clone(),
3889 content_mask,
3890 rem_size: self.rem_size(),
3891 priority,
3892 element: Some(element),
3893 absolute_offset,
3894 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3895 paint_range: PaintIndex::default()..PaintIndex::default(),
3896 });
3897 }
3898
3899 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3905 self.invalidator.debug_assert_paint();
3906
3907 let content_mask = self.content_mask();
3908 let clipped_bounds = bounds.intersect(&content_mask.bounds);
3909 if !clipped_bounds.is_empty() {
3910 self.next_frame
3911 .scene
3912 .push_layer(self.cover_bounds(clipped_bounds));
3913 }
3914
3915 let result = f(self);
3916
3917 if !clipped_bounds.is_empty() {
3918 self.next_frame.scene.pop_layer();
3919 }
3920
3921 result
3922 }
3923
3924 pub fn paint_drop_shadows(
3930 &mut self,
3931 bounds: Bounds<Pixels>,
3932 corner_radii: Corners<Pixels>,
3933 shadows: &[BoxShadow],
3934 ) {
3935 self.invalidator.debug_assert_paint();
3936
3937 let scale_factor = self.scale_factor();
3938 let content_mask = self.snapped_content_mask();
3939 let opacity = self.element_opacity();
3940 let element_bounds = self.cover_bounds(bounds);
3941 let element_corner_radii = corner_radii.scale(scale_factor);
3942 for shadow in shadows {
3943 if shadow.inset {
3944 continue;
3945 }
3946 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3947 self.next_frame.scene.insert_primitive(Shadow {
3948 order: 0,
3949 blur_radius: shadow.blur_radius.scale(scale_factor),
3950 bounds: self.cover_bounds(shadow_bounds),
3951 content_mask,
3952 corner_radii: corner_radii.scale(scale_factor),
3953 color: shadow.color.opacity(opacity),
3954 element_bounds,
3955 element_corner_radii,
3956 inset: 0,
3957 pad: 0,
3958 });
3959 }
3960 }
3961
3962 pub fn paint_inset_shadows(
3966 &mut self,
3967 bounds: Bounds<Pixels>,
3968 corner_radii: Corners<Pixels>,
3969 shadows: &[BoxShadow],
3970 ) {
3971 self.invalidator.debug_assert_paint();
3972
3973 let scale_factor = self.scale_factor();
3974 let content_mask = self.snapped_content_mask();
3975 let opacity = self.element_opacity();
3976 let element_bounds = self.cover_bounds(bounds);
3977 let element_corner_radii = corner_radii.scale(scale_factor);
3978 for shadow in shadows {
3979 if !shadow.inset {
3980 continue;
3981 }
3982 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
3983 let zero = Pixels::ZERO;
3986 let hole_corner_radii = Corners {
3987 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
3988 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
3989 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
3990 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
3991 };
3992 self.next_frame.scene.insert_primitive(Shadow {
3993 order: 0,
3994 blur_radius: shadow.blur_radius.scale(scale_factor),
3995 bounds: self.cover_bounds(hole),
3996 content_mask,
3997 corner_radii: hole_corner_radii.scale(scale_factor),
3998 color: shadow.color.opacity(opacity),
3999 element_bounds,
4000 element_corner_radii,
4001 inset: 1,
4002 pad: 0,
4003 });
4004 }
4005 }
4006
4007 pub fn paint_quad(&mut self, quad: PaintQuad) {
4017 self.invalidator.debug_assert_paint();
4018
4019 let opacity = self.element_opacity();
4020 let snapped_bounds = self.snap_bounds(quad.bounds);
4021 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
4022 let quad = Quad {
4023 order: 0,
4024 bounds: snapped_bounds,
4025 content_mask: self.snapped_content_mask(),
4026 background: quad.background.opacity(opacity),
4027 border_color: quad.border_color.opacity(opacity),
4028 corner_radii: quad.corner_radii.scale(self.scale_factor()),
4029 border_widths: snapped_border_widths,
4030 border_style: quad.border_style,
4031 };
4032
4033 if !quad.background.is_transparent() {
4034 self.next_frame.scene.insert_primitive(quad);
4035 return;
4036 }
4037
4038 let radii = &quad.corner_radii;
4044 let widths = &quad.border_widths;
4045
4046 let antialias_slack = point(ScaledPixels(1.0), ScaledPixels(1.0));
4047 let top_left_inset = point(
4048 widths.left,
4049 widths.top.max(radii.top_left).max(radii.top_right),
4050 ) + antialias_slack;
4051 let bottom_right_inset = point(
4052 widths.right,
4053 widths.bottom.max(radii.bottom_left).max(radii.bottom_right),
4054 ) + antialias_slack;
4055
4056 let outer_bounds = quad.bounds;
4057 let inner_bounds = Bounds::from_corners(
4058 outer_bounds.origin + top_left_inset,
4059 outer_bounds.bottom_right() - bottom_right_inset,
4060 );
4061
4062 if inner_bounds.is_empty() {
4063 self.next_frame.scene.insert_primitive(quad);
4064 return;
4065 }
4066
4067 let strips = [
4068 Bounds::from_corners(
4070 outer_bounds.origin,
4071 point(outer_bounds.right(), inner_bounds.top()),
4072 ),
4073 Bounds::from_corners(
4075 point(outer_bounds.left(), inner_bounds.bottom()),
4076 outer_bounds.bottom_right(),
4077 ),
4078 Bounds::from_corners(
4080 point(outer_bounds.left(), inner_bounds.top()),
4081 inner_bounds.bottom_left(),
4082 ),
4083 Bounds::from_corners(
4085 inner_bounds.top_right(),
4086 point(outer_bounds.right(), inner_bounds.bottom()),
4087 ),
4088 ];
4089
4090 for strip in strips {
4091 let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
4092 if !content_mask_bounds.is_empty() {
4093 self.next_frame.scene.insert_primitive(Quad {
4094 content_mask: ContentMask {
4095 bounds: content_mask_bounds,
4096 },
4097 ..quad
4098 });
4099 }
4100 }
4101 }
4102
4103 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
4107 self.invalidator.debug_assert_paint();
4108
4109 let scale_factor = self.scale_factor();
4110 let content_mask = self.content_mask();
4111 let opacity = self.element_opacity();
4112 path.content_mask = content_mask;
4113 let color: Background = color.into();
4114 path.color = color.opacity(opacity);
4115 self.next_frame
4116 .scene
4117 .insert_primitive(path.scale(scale_factor));
4118 }
4119
4120 pub fn paint_underline(
4124 &mut self,
4125 origin: Point<Pixels>,
4126 width: Pixels,
4127 style: &UnderlineStyle,
4128 ) {
4129 self.invalidator.debug_assert_paint();
4130
4131 let scale_factor = self.scale_factor();
4132 let thickness = self.snap_stroke(style.thickness);
4133 let height = if style.wavy {
4134 ScaledPixels(thickness.0 * 3.)
4135 } else {
4136 thickness
4137 };
4138 let bounds = Bounds {
4139 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4140 size: size(self.snap_stroke(width), height),
4141 };
4142 let element_opacity = self.element_opacity();
4143
4144 self.next_frame.scene.insert_primitive(Underline {
4145 order: 0,
4146 pad: 0,
4147 bounds,
4148 content_mask: self.snapped_content_mask(),
4149 color: style.color.unwrap_or_default().opacity(element_opacity),
4150 thickness,
4151 wavy: style.wavy.into(),
4152 });
4153 }
4154
4155 pub fn paint_strikethrough(
4159 &mut self,
4160 origin: Point<Pixels>,
4161 width: Pixels,
4162 style: &StrikethroughStyle,
4163 ) {
4164 self.invalidator.debug_assert_paint();
4165
4166 let scale_factor = self.scale_factor();
4167 let height = style.thickness;
4168 let bounds = Bounds {
4169 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4170 size: size(self.snap_stroke(width), self.snap_stroke(height)),
4171 };
4172 let opacity = self.element_opacity();
4173
4174 self.next_frame.scene.insert_primitive(Underline {
4175 order: 0,
4176 pad: 0,
4177 bounds,
4178 content_mask: self.snapped_content_mask(),
4179 thickness: self.snap_stroke(style.thickness),
4180 color: style.color.unwrap_or_default().opacity(opacity),
4181 wavy: false.into(),
4182 });
4183 }
4184
4185 pub fn paint_glyph(
4194 &mut self,
4195 origin: Point<Pixels>,
4196 font_id: FontId,
4197 glyph_id: GlyphId,
4198 font_size: Pixels,
4199 color: Hsla,
4200 ) -> Result<()> {
4201 self.invalidator.debug_assert_paint();
4202
4203 let element_opacity = self.element_opacity();
4204 let scale_factor = self.scale_factor();
4205 let glyph_origin = origin.scale(scale_factor);
4206
4207 let quantized_origin = Point::new(
4208 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
4209 / SUBPIXEL_VARIANTS_X as f32,
4210 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
4211 / SUBPIXEL_VARIANTS_Y as f32,
4212 );
4213 let subpixel_variant = Point::new(
4214 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
4215 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
4216 );
4217 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
4218 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
4219 let dilation = self.text_system().glyph_dilation_for_color(color);
4220 let params = RenderGlyphParams {
4221 font_id,
4222 glyph_id,
4223 font_size,
4224 subpixel_variant,
4225 scale_factor,
4226 is_emoji: false,
4227 subpixel_rendering,
4228 dilation,
4229 };
4230
4231 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4232 if !raster_bounds.is_zero() {
4233 let tile = self
4234 .sprite_atlas
4235 .get_or_insert_with(¶ms.clone().into(), &mut || {
4236 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4237 Ok(Some((size, Cow::Owned(bytes))))
4238 })?
4239 .expect("Callback above only errors or returns Some");
4240 let bounds = Bounds {
4241 origin: integer_origin + raster_bounds.origin.map(Into::into),
4242 size: tile.bounds.size.map(Into::into),
4243 };
4244 let content_mask = self.snapped_content_mask();
4245
4246 if subpixel_rendering {
4247 self.next_frame.scene.insert_primitive(SubpixelSprite {
4248 order: 0,
4249 pad: 0,
4250 bounds,
4251 content_mask,
4252 color: color.opacity(element_opacity),
4253 tile,
4254 transformation: TransformationMatrix::unit(),
4255 });
4256 } else {
4257 self.next_frame.scene.insert_primitive(MonochromeSprite {
4258 order: 0,
4259 pad: 0,
4260 bounds,
4261 content_mask,
4262 color: color.opacity(element_opacity),
4263 tile,
4264 transformation: TransformationMatrix::unit(),
4265 });
4266 }
4267 }
4268 Ok(())
4269 }
4270
4271 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
4272 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
4273 return false;
4274 }
4275
4276 if !self.platform_window.is_subpixel_rendering_supported() {
4277 return false;
4278 }
4279
4280 let mode = match self.text_rendering_mode.get() {
4281 TextRenderingMode::PlatformDefault => self
4282 .text_system()
4283 .recommended_rendering_mode(font_id, font_size),
4284 mode => mode,
4285 };
4286
4287 mode == TextRenderingMode::Subpixel
4288 }
4289
4290 pub fn paint_emoji(
4299 &mut self,
4300 origin: Point<Pixels>,
4301 font_id: FontId,
4302 glyph_id: GlyphId,
4303 font_size: Pixels,
4304 ) -> Result<()> {
4305 self.invalidator.debug_assert_paint();
4306
4307 let scale_factor = self.scale_factor();
4308 let glyph_origin = origin.scale(scale_factor);
4309 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
4310 let params = RenderGlyphParams {
4311 font_id,
4312 glyph_id,
4313 font_size,
4314 subpixel_variant: Default::default(),
4315 scale_factor,
4316 is_emoji: true,
4317 subpixel_rendering: false,
4318 dilation: 0,
4319 };
4320
4321 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4322 if !raster_bounds.is_zero() {
4323 let tile = self
4324 .sprite_atlas
4325 .get_or_insert_with(¶ms.clone().into(), &mut || {
4326 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4327 Ok(Some((size, Cow::Owned(bytes))))
4328 })?
4329 .expect("Callback above only errors or returns Some");
4330
4331 let bounds = Bounds {
4332 origin: integer_origin + raster_bounds.origin.map(Into::into),
4333 size: tile.bounds.size.map(Into::into),
4334 };
4335 let content_mask = self.snapped_content_mask();
4336 let opacity = self.element_opacity();
4337
4338 self.next_frame.scene.insert_primitive(PolychromeSprite {
4339 order: 0,
4340 pad: 0,
4341 grayscale: false.into(),
4342 bounds,
4343 corner_radii: Default::default(),
4344 content_mask,
4345 tile,
4346 opacity,
4347 });
4348 }
4349 Ok(())
4350 }
4351
4352 pub fn paint_svg(
4356 &mut self,
4357 bounds: Bounds<Pixels>,
4358 path: SharedString,
4359 mut data: Option<&[u8]>,
4360 transformation: TransformationMatrix,
4361 color: Hsla,
4362 cx: &App,
4363 ) -> Result<()> {
4364 self.invalidator.debug_assert_paint();
4365
4366 let element_opacity = self.element_opacity();
4367 let bounds = self.snap_bounds(bounds);
4368
4369 let params = RenderSvgParams {
4370 path,
4371 size: bounds.size.map(|pixels| {
4372 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
4373 }),
4374 };
4375
4376 let Some(tile) =
4377 self.sprite_atlas
4378 .get_or_insert_with(¶ms.clone().into(), &mut || {
4379 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
4380 else {
4381 return Ok(None);
4382 };
4383 Ok(Some((size, Cow::Owned(bytes))))
4384 })?
4385 else {
4386 return Ok(());
4387 };
4388 let content_mask = self.snapped_content_mask();
4389 let svg_bounds = Bounds {
4390 origin: bounds.center()
4391 - Point::new(
4392 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4393 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4394 ),
4395 size: tile
4396 .bounds
4397 .size
4398 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
4399 };
4400 let final_bounds = svg_bounds
4401 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
4402 .map_size(|size| size.ceil());
4403
4404 self.next_frame.scene.insert_primitive(MonochromeSprite {
4405 order: 0,
4406 pad: 0,
4407 bounds: final_bounds,
4408 content_mask,
4409 color: color.opacity(element_opacity),
4410 tile,
4411 transformation,
4412 });
4413
4414 Ok(())
4415 }
4416
4417 pub fn paint_image(
4426 &mut self,
4427 bounds: Bounds<Pixels>,
4428 image_bounds: Bounds<Pixels>,
4429 corner_radii: Corners<Pixels>,
4430 data: Arc<RenderImage>,
4431 frame_index: usize,
4432 grayscale: bool,
4433 ) -> Result<()> {
4434 self.invalidator.debug_assert_paint();
4435
4436 let visible_bounds = bounds.intersect(&image_bounds);
4437 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
4438 return Ok(());
4439 }
4440 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
4441 return Ok(());
4442 }
4443
4444 let params = RenderImageParams {
4445 image_id: data.id,
4446 frame_index,
4447 };
4448
4449 let tile = self
4450 .sprite_atlas
4451 .get_or_insert_with(¶ms.into(), &mut || {
4452 Ok(Some((
4453 data.size(frame_index),
4454 Cow::Borrowed(
4455 data.as_bytes(frame_index)
4456 .expect("It's the caller's job to pass a valid frame index"),
4457 ),
4458 )))
4459 })?
4460 .expect("Callback above only returns Some");
4461
4462 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
4463
4464 let sub_tile = if visible_bounds == image_bounds {
4465 tile
4466 } else {
4467 let x_offset_ratio =
4468 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
4469 let y_offset_ratio =
4470 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
4471 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
4472 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
4473
4474 let tile_origin_x = tile.bounds.origin.x.0;
4475 let tile_origin_y = tile.bounds.origin.y.0;
4476 let tile_width = tile.bounds.size.width.0;
4477 let tile_height = tile.bounds.size.height.0;
4478
4479 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
4480 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
4481 let sub_width = (width_ratio * tile_width as f32).round() as i32;
4482 let sub_height = (height_ratio * tile_height as f32).round() as i32;
4483
4484 let max_x = tile_origin_x + tile_width;
4485 let max_y = tile_origin_y + tile_height;
4486
4487 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
4488 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
4489 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
4490 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
4491
4492 AtlasTile {
4493 bounds: Bounds {
4494 origin: point(
4495 DevicePixels(clamped_origin_x),
4496 DevicePixels(clamped_origin_y),
4497 ),
4498 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
4499 },
4500 ..tile
4501 }
4502 };
4503
4504 let content_mask = self.snapped_content_mask();
4505 let corner_radii = corner_radii
4506 .clamp_radii_for_quad_size(visible_bounds.size)
4507 .scale(self.scale_factor());
4508 let opacity = self.element_opacity();
4509
4510 self.next_frame.scene.insert_primitive(PolychromeSprite {
4511 order: 0,
4512 pad: 0,
4513 grayscale: grayscale.into(),
4514 bounds: visible_bounds_snapped,
4515 content_mask,
4516 corner_radii,
4517 tile: sub_tile,
4518 opacity,
4519 });
4520 Ok(())
4521 }
4522
4523 #[cfg(target_os = "macos")]
4527 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
4528 use crate::PaintSurface;
4529
4530 self.invalidator.debug_assert_paint();
4531
4532 let bounds = self.snap_bounds(bounds);
4533 let content_mask = self.snapped_content_mask();
4534 self.next_frame.scene.insert_primitive(PaintSurface {
4535 order: 0,
4536 bounds,
4537 content_mask,
4538 image_buffer,
4539 });
4540 }
4541
4542 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
4544 for frame_index in 0..data.frame_count() {
4545 let params = RenderImageParams {
4546 image_id: data.id,
4547 frame_index,
4548 };
4549
4550 self.sprite_atlas.remove(¶ms.clone().into());
4551 }
4552
4553 Ok(())
4554 }
4555
4556 #[cfg(any(test, feature = "test-support"))]
4558 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
4559 data.frame_count() > 0
4560 && (0..data.frame_count()).all(|frame_index| {
4561 self.sprite_atlas.contains(
4562 &RenderImageParams {
4563 image_id: data.id,
4564 frame_index,
4565 }
4566 .into(),
4567 )
4568 })
4569 }
4570
4571 #[must_use]
4577 pub fn request_layout(
4578 &mut self,
4579 style: Style,
4580 children: impl IntoIterator<Item = LayoutId>,
4581 cx: &mut App,
4582 ) -> LayoutId {
4583 self.invalidator.debug_assert_prepaint();
4584
4585 cx.layout_id_buffer.clear();
4586 cx.layout_id_buffer.extend(children);
4587 let rem_size = self.rem_size();
4588 let scale_factor = self.scale_factor();
4589
4590 self.layout_engine.as_mut().unwrap().request_layout(
4591 style,
4592 rem_size,
4593 scale_factor,
4594 &cx.layout_id_buffer,
4595 )
4596 }
4597
4598 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
4607 where
4608 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
4609 + 'static,
4610 {
4611 self.invalidator.debug_assert_prepaint();
4612
4613 let rem_size = self.rem_size();
4614 let scale_factor = self.scale_factor();
4615 self.layout_engine
4616 .as_mut()
4617 .unwrap()
4618 .request_measured_layout(style, rem_size, scale_factor, measure)
4619 }
4620
4621 pub fn compute_layout(
4627 &mut self,
4628 layout_id: LayoutId,
4629 available_space: Size<AvailableSpace>,
4630 cx: &mut App,
4631 ) {
4632 self.invalidator.debug_assert_prepaint();
4633
4634 let mut layout_engine = self.layout_engine.take().unwrap();
4635 layout_engine.compute_layout(layout_id, available_space, self, cx);
4636 self.layout_engine = Some(layout_engine);
4637 }
4638
4639 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
4644 self.invalidator.debug_assert_prepaint();
4645
4646 let scale_factor = self.scale_factor();
4647 let mut bounds = self
4648 .layout_engine
4649 .as_mut()
4650 .unwrap()
4651 .layout_bounds(layout_id, scale_factor)
4652 .map(Into::into);
4653 let snapped_offset = self.pixel_snap_point(self.element_offset());
4654 bounds.origin += snapped_offset;
4655 bounds
4656 }
4657
4658 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
4664 self.invalidator.debug_assert_prepaint();
4665
4666 let content_mask = self.content_mask();
4667 let mut id = self.next_hitbox_id;
4668 self.next_hitbox_id = self.next_hitbox_id.next();
4669 let hitbox = Hitbox {
4670 id,
4671 bounds,
4672 content_mask,
4673 behavior,
4674 };
4675 self.next_frame.hitboxes.push(hitbox.clone());
4676 hitbox
4677 }
4678
4679 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
4683 self.invalidator.debug_assert_paint();
4684 self.next_frame.window_control_hitboxes.push((area, hitbox));
4685 }
4686
4687 pub fn set_key_context(&mut self, context: KeyContext) {
4692 self.invalidator.debug_assert_paint();
4693 self.next_frame.dispatch_tree.set_key_context(context);
4694 }
4695
4696 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
4701 self.invalidator.debug_assert_prepaint();
4702 if focus_handle.is_focused(self) {
4703 self.next_frame.focus = Some(focus_handle.id);
4704 }
4705 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
4706 }
4707
4708 pub fn set_view_id(&mut self, view_id: EntityId) {
4714 self.invalidator.debug_assert_prepaint();
4715 self.next_frame.dispatch_tree.set_view_id(view_id);
4716 }
4717
4718 pub fn current_view(&self) -> EntityId {
4720 self.invalidator.debug_assert_paint_or_prepaint();
4721 self.rendered_entity_stack.last().copied().unwrap()
4722 }
4723
4724 #[inline]
4725 pub(crate) fn with_rendered_view<R>(
4726 &mut self,
4727 id: EntityId,
4728 f: impl FnOnce(&mut Self) -> R,
4729 ) -> R {
4730 self.rendered_entity_stack.push(id);
4731 let result = f(self);
4732 self.rendered_entity_stack.pop();
4733 result
4734 }
4735
4736 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
4738 where
4739 F: FnOnce(&mut Self) -> R,
4740 {
4741 if let Some(image_cache) = image_cache {
4742 self.image_cache_stack.push(image_cache);
4743 let result = f(self);
4744 self.image_cache_stack.pop();
4745 result
4746 } else {
4747 f(self)
4748 }
4749 }
4750
4751 pub fn handle_input(
4760 &mut self,
4761 focus_handle: &FocusHandle,
4762 input_handler: impl InputHandler,
4763 cx: &App,
4764 ) {
4765 self.invalidator.debug_assert_paint();
4766
4767 if focus_handle.is_focused(self) {
4768 let cx = self.to_async(cx);
4769 self.next_frame
4770 .input_handlers
4771 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
4772 }
4773 }
4774
4775 pub fn on_mouse_event<Event: MouseEvent>(
4781 &mut self,
4782 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4783 ) {
4784 self.invalidator.debug_assert_paint();
4785
4786 self.next_frame.mouse_listeners.push(Some(Box::new(
4787 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
4788 if let Some(event) = event.downcast_ref() {
4789 listener(event, phase, window, cx)
4790 }
4791 },
4792 )));
4793 }
4794
4795 pub fn on_key_event<Event: KeyEvent>(
4804 &mut self,
4805 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4806 ) {
4807 self.invalidator.debug_assert_paint();
4808
4809 self.next_frame.dispatch_tree.on_key_event(Rc::new(
4810 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
4811 if let Some(event) = event.downcast_ref::<Event>() {
4812 listener(event, phase, window, cx)
4813 }
4814 },
4815 ));
4816 }
4817
4818 pub fn on_modifiers_changed(
4825 &mut self,
4826 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
4827 ) {
4828 self.invalidator.debug_assert_paint();
4829
4830 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
4831 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
4832 listener(event, window, cx)
4833 },
4834 ));
4835 }
4836
4837 pub fn on_focus_in(
4841 &mut self,
4842 handle: &FocusHandle,
4843 cx: &mut App,
4844 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
4845 ) -> Subscription {
4846 let focus_id = handle.id;
4847 let (subscription, activate) =
4848 self.new_focus_listener(Box::new(move |event, window, cx| {
4849 if event.is_focus_in(focus_id) {
4850 listener(window, cx);
4851 }
4852 true
4853 }));
4854 cx.defer(move |_| activate());
4855 subscription
4856 }
4857
4858 pub fn on_focus_out(
4861 &mut self,
4862 handle: &FocusHandle,
4863 cx: &mut App,
4864 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
4865 ) -> Subscription {
4866 let focus_id = handle.id;
4867 let (subscription, activate) =
4868 self.new_focus_listener(Box::new(move |event, window, cx| {
4869 if let Some(blurred_id) = event.previous_focus_path.last().copied()
4870 && event.is_focus_out(focus_id)
4871 {
4872 let event = FocusOutEvent {
4873 blurred: WeakFocusHandle {
4874 id: blurred_id,
4875 handles: Arc::downgrade(&cx.focus_handles),
4876 },
4877 };
4878 listener(event, window, cx)
4879 }
4880 true
4881 }));
4882 cx.defer(move |_| activate());
4883 subscription
4884 }
4885
4886 fn reset_cursor_style(&self, cx: &mut App) {
4887 if self.is_window_hovered() {
4889 let style = cx
4891 .active_drag_cursor_style()
4892 .or_else(|| self.rendered_frame.cursor_style(self))
4893 .unwrap_or(CursorStyle::Arrow);
4894 cx.platform.set_cursor_style(style);
4895 }
4896 }
4897
4898 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
4901 let keystroke = keystroke.with_simulated_ime();
4902 let result = self.dispatch_event(
4903 PlatformInput::KeyDown(KeyDownEvent {
4904 keystroke: keystroke.clone(),
4905 is_held: false,
4906 prefer_character_input: false,
4907 }),
4908 cx,
4909 );
4910 if !result.propagate {
4911 return true;
4912 }
4913
4914 if let Some(input) = keystroke.key_char
4915 && let Some(mut input_handler) = self.platform_window.take_input_handler()
4916 {
4917 input_handler.dispatch_input(&input, self, cx);
4918 self.platform_window.set_input_handler(input_handler);
4919 return true;
4920 }
4921
4922 false
4923 }
4924
4925 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
4928 self.highest_precedence_binding_for_action(action)
4929 .map(|binding| {
4930 binding
4931 .keystrokes()
4932 .iter()
4933 .map(ToString::to_string)
4934 .collect::<Vec<_>>()
4935 .join(" ")
4936 })
4937 .unwrap_or_else(|| action.name().to_string())
4938 }
4939
4940 #[profiling::function]
4942 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
4943 #[cfg(feature = "input-latency-histogram")]
4944 let dispatch_time = Instant::now();
4945 let update_count_before = self.invalidator.update_count();
4946 let old_modality = self.last_input_modality;
4950 self.last_input_modality = match &event {
4951 PlatformInput::KeyDown(_) => InputModality::Keyboard,
4952 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
4953 PlatformInput::Touch(_) => InputModality::Touch,
4954 _ => self.last_input_modality,
4955 };
4956 if self.last_input_modality != old_modality {
4957 self.refresh();
4958 }
4959
4960 cx.propagate_event = true;
4962 self.default_prevented = false;
4964
4965 let event = match event {
4966 PlatformInput::MouseMove(mouse_move) => {
4969 self.mouse_position = mouse_move.position;
4970 self.modifiers = mouse_move.modifiers;
4971 PlatformInput::MouseMove(mouse_move)
4972 }
4973 PlatformInput::MouseDown(mouse_down) => {
4974 self.mouse_position = mouse_down.position;
4975 self.modifiers = mouse_down.modifiers;
4976 PlatformInput::MouseDown(mouse_down)
4977 }
4978 PlatformInput::MouseUp(mouse_up) => {
4979 self.mouse_position = mouse_up.position;
4980 self.modifiers = mouse_up.modifiers;
4981 PlatformInput::MouseUp(mouse_up)
4982 }
4983 PlatformInput::MousePressure(mouse_pressure) => {
4984 PlatformInput::MousePressure(mouse_pressure)
4985 }
4986 PlatformInput::MouseExited(mouse_exited) => {
4987 self.modifiers = mouse_exited.modifiers;
4988 PlatformInput::MouseExited(mouse_exited)
4989 }
4990 PlatformInput::ModifiersChanged(modifiers_changed) => {
4991 self.modifiers = modifiers_changed.modifiers;
4992 self.capslock = modifiers_changed.capslock;
4993 PlatformInput::ModifiersChanged(modifiers_changed)
4994 }
4995 PlatformInput::ScrollWheel(scroll_wheel) => {
4996 self.mouse_position = scroll_wheel.position;
4997 self.modifiers = scroll_wheel.modifiers;
4998 PlatformInput::ScrollWheel(scroll_wheel)
4999 }
5000 PlatformInput::Pinch(pinch) => {
5001 self.mouse_position = pinch.position;
5002 self.modifiers = pinch.modifiers;
5003 PlatformInput::Pinch(pinch)
5004 }
5005 PlatformInput::FileDrop(file_drop) => match file_drop {
5008 FileDropEvent::Entered { position, paths } => {
5009 self.mouse_position = position;
5010 let source_window = self.handle.window_id();
5011 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
5012 cx.active_drag = Some(AnyDrag {
5013 value: Arc::new(paths.clone()),
5014 view: cx.new(|_| paths).into(),
5015 cursor_offset: position,
5016 cursor_style: None,
5017 external_payload_source: None,
5018 });
5019 }
5020 PlatformInput::MouseMove(MouseMoveEvent {
5021 position,
5022 pressed_button: Some(MouseButton::Left),
5023 modifiers: Modifiers::default(),
5024 })
5025 }
5026 FileDropEvent::Pending { position } => {
5027 self.mouse_position = position;
5028 PlatformInput::MouseMove(MouseMoveEvent {
5029 position,
5030 pressed_button: Some(MouseButton::Left),
5031 modifiers: Modifiers::default(),
5032 })
5033 }
5034 FileDropEvent::Submit { position } => {
5035 cx.activate(true);
5036 self.mouse_position = position;
5037 PlatformInput::MouseUp(MouseUpEvent {
5038 button: MouseButton::Left,
5039 position,
5040 modifiers: Modifiers::default(),
5041 click_count: 1,
5042 })
5043 }
5044 FileDropEvent::Exited => {
5045 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
5046 cx.active_drag.take();
5047 }
5048 self.refresh();
5049 PlatformInput::FileDrop(FileDropEvent::Exited)
5050 }
5051 FileDropEvent::Ended => {
5052 cx.end_platform_drag(self.handle.window_id());
5053 self.refresh();
5054 PlatformInput::FileDrop(FileDropEvent::Ended)
5055 }
5056 },
5057 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
5058 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
5059 };
5060
5061 if let Some(any_mouse_event) = event.mouse_event() {
5062 self.dispatch_mouse_event(any_mouse_event, cx);
5063 } else if let Some(any_key_event) = event.keyboard_event() {
5064 self.dispatch_key_event(any_key_event, cx);
5065 }
5066
5067 self.promote_external_drag_to_platform(&event, cx);
5070
5071 if self.invalidator.update_count() > update_count_before {
5072 self.input_rate_tracker.borrow_mut().record_input();
5073 #[cfg(feature = "input-latency-histogram")]
5074 if self.invalidator.not_drawing() {
5075 self.input_latency_tracker.record_input(dispatch_time);
5076 } else {
5077 self.input_latency_tracker.record_mid_draw_input();
5078 }
5079 }
5080
5081 DispatchEventResult {
5082 propagate: cx.propagate_event,
5083 default_prevented: self.default_prevented,
5084 }
5085 }
5086
5087 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
5088 let PlatformInput::MouseMove(mouse_move) = event else {
5089 return;
5090 };
5091 if mouse_move.pressed_button != Some(MouseButton::Left) {
5092 return;
5093 }
5094 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
5095 return;
5096 }
5097 if !self.platform_window.can_start_external_drag() {
5098 return;
5099 }
5100 let Some(payload_source) = cx
5101 .active_drag
5102 .as_mut()
5103 .and_then(|drag| drag.external_payload_source.take())
5104 else {
5105 return;
5106 };
5107 let Some(payload) = payload_source(self, cx) else {
5108 return;
5109 };
5110 if self.platform_window.start_external_drag(&payload)
5111 && cx.hand_active_drag_to_platform(self.handle.window_id())
5112 {
5113 self.refresh();
5114 }
5115 }
5116
5117 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5118 self.mouse_hit_test = self.rendered_frame.hit_test(self.mouse_position());
5119
5120 #[cfg(any(feature = "inspector", debug_assertions))]
5121 if self.is_inspector_picking(cx) {
5122 self.reset_cursor_style(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 self.reset_cursor_style(cx);
5172 }
5173
5174 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
5175 if self.invalidator.is_dirty() {
5176 self.draw(cx).clear(cx);
5177 }
5178
5179 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5180 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5181
5182 let mut keystroke: Option<Keystroke> = None;
5183
5184 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
5185 if event.modifiers.number_of_modifiers() == 0
5186 && self.pending_modifier.modifiers.number_of_modifiers() == 1
5187 && !self.pending_modifier.saw_other_input
5188 {
5189 let key = match self.pending_modifier.modifiers {
5190 modifiers if modifiers.shift => Some("shift"),
5191 modifiers if modifiers.control => Some("control"),
5192 modifiers if modifiers.alt => Some("alt"),
5193 modifiers if modifiers.platform => Some("platform"),
5194 modifiers if modifiers.function => Some("function"),
5195 _ => None,
5196 };
5197 if let Some(key) = key {
5198 keystroke = Some(Keystroke {
5199 key: key.to_string(),
5200 key_char: None,
5201 modifiers: Modifiers::default(),
5202 });
5203 }
5204 }
5205
5206 if self.pending_modifier.modifiers.number_of_modifiers() == 0
5207 && event.modifiers.number_of_modifiers() == 1
5208 {
5209 self.pending_modifier.saw_other_input = false
5210 } else if event.modifiers.number_of_modifiers() > 1 {
5211 self.pending_modifier.saw_other_input = true
5212 }
5213 self.pending_modifier.modifiers = event.modifiers
5214 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
5215 self.pending_modifier.saw_other_input = true;
5216 keystroke = Some(key_down_event.keystroke.clone());
5217 if key_down_event.keystroke.key_char.is_some()
5218 && matches!(
5219 cx.cursor_hide_mode,
5220 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
5221 )
5222 {
5223 cx.platform.hide_cursor_until_mouse_moves();
5224 }
5225 }
5226
5227 let Some(keystroke) = keystroke else {
5228 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5229 return;
5230 };
5231
5232 cx.propagate_event = true;
5233 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
5234 if !cx.propagate_event {
5235 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5236 return;
5237 }
5238
5239 let mut currently_pending = self.pending_input.take().unwrap_or_default();
5240 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
5241 currently_pending = PendingInput::default();
5242 }
5243
5244 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
5245 currently_pending.keystrokes,
5246 keystroke,
5247 &dispatch_path,
5248 );
5249
5250 if !match_result.to_replay.is_empty() {
5251 self.replay_pending_input(match_result.to_replay, cx);
5252 cx.propagate_event = true;
5253 }
5254
5255 if !match_result.pending.is_empty() {
5256 currently_pending.timer.take();
5257 currently_pending.keystrokes = match_result.pending;
5258 currently_pending.focus = self.focus;
5259
5260 let text_input_requires_timeout = event
5261 .downcast_ref::<KeyDownEvent>()
5262 .filter(|key_down| key_down.keystroke.key_char.is_some())
5263 .and_then(|_| self.platform_window.take_input_handler())
5264 .map_or(false, |mut input_handler| {
5265 let accepts = input_handler.accepts_text_input(self, cx);
5266 self.platform_window.set_input_handler(input_handler);
5267 accepts
5268 });
5269
5270 currently_pending.needs_timeout |=
5271 match_result.pending_has_binding || text_input_requires_timeout;
5272
5273 if currently_pending.needs_timeout {
5274 let generation = Rc::new(());
5275 currently_pending.generation = generation.clone();
5276 currently_pending.timer = Some(self.spawn(cx, async move |cx| {
5277 cx.background_executor.timer(Duration::from_secs(1)).await;
5278 cx.update_if_present(move |window, cx| {
5279 if !window
5280 .pending_input
5281 .as_ref()
5282 .is_some_and(|pending| Rc::ptr_eq(&pending.generation, &generation))
5283 {
5284 return;
5285 }
5286 let Some(currently_pending) = window
5287 .pending_input
5288 .take()
5289 .filter(|pending| pending.focus == window.focus)
5290 else {
5291 return;
5292 };
5293
5294 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
5295 let dispatch_path =
5296 window.rendered_frame.dispatch_tree.dispatch_path(node_id);
5297
5298 let to_replay = window
5299 .rendered_frame
5300 .dispatch_tree
5301 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
5302
5303 window.pending_input_changed(cx);
5304 window.replay_pending_input(to_replay, cx)
5305 })
5306 .log_err();
5307 }));
5308 } else {
5309 currently_pending.timer = None;
5310 }
5311 self.pending_input = Some(currently_pending);
5312 self.pending_input_changed(cx);
5313 cx.propagate_event = false;
5314 return;
5315 }
5316
5317 let skip_bindings = event
5318 .downcast_ref::<KeyDownEvent>()
5319 .filter(|key_down_event| key_down_event.prefer_character_input)
5320 .map(|_| {
5321 self.platform_window
5322 .take_input_handler()
5323 .map_or(false, |mut input_handler| {
5324 let accepts = input_handler.accepts_text_input(self, cx);
5325 self.platform_window.set_input_handler(input_handler);
5326 accepts
5329 })
5330 })
5331 .unwrap_or(false);
5332
5333 if !skip_bindings {
5334 for binding in match_result.bindings {
5335 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5336 if !cx.propagate_event {
5337 self.dispatch_keystroke_observers(
5338 event,
5339 Some(binding.action),
5340 match_result.context_stack,
5341 cx,
5342 );
5343 self.pending_input_changed(cx);
5344 return;
5345 }
5346 }
5347 }
5348
5349 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
5350 self.pending_input_changed(cx);
5351 }
5352
5353 fn finish_dispatch_key_event(
5354 &mut self,
5355 event: &dyn Any,
5356 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
5357 context_stack: Vec<KeyContext>,
5358 cx: &mut App,
5359 ) {
5360 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
5361 if !cx.propagate_event {
5362 return;
5363 }
5364
5365 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
5366 if !cx.propagate_event {
5367 return;
5368 }
5369
5370 self.dispatch_keystroke_observers(event, None, context_stack, cx);
5371 }
5372
5373 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
5374 self.pending_input_observers
5375 .clone()
5376 .retain(&(), |callback| callback(self, cx));
5377 }
5378
5379 fn dispatch_key_down_up_event(
5380 &mut self,
5381 event: &dyn Any,
5382 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5383 cx: &mut App,
5384 ) {
5385 for node_id in dispatch_path {
5387 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5388
5389 for key_listener in node.key_listeners.clone() {
5390 key_listener(event, DispatchPhase::Capture, self, cx);
5391 if !cx.propagate_event {
5392 return;
5393 }
5394 }
5395 }
5396
5397 for node_id in dispatch_path.iter().rev() {
5399 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5401 for key_listener in node.key_listeners.clone() {
5402 key_listener(event, DispatchPhase::Bubble, self, cx);
5403 if !cx.propagate_event {
5404 return;
5405 }
5406 }
5407 }
5408 }
5409
5410 fn dispatch_modifiers_changed_event(
5411 &mut self,
5412 event: &dyn Any,
5413 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5414 cx: &mut App,
5415 ) {
5416 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
5417 return;
5418 };
5419 for node_id in dispatch_path.iter().rev() {
5420 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5421 for listener in node.modifiers_changed_listeners.clone() {
5422 listener(event, self, cx);
5423 if !cx.propagate_event {
5424 return;
5425 }
5426 }
5427 }
5428 }
5429
5430 fn active_pending_input(&self) -> Option<&PendingInput> {
5433 self.pending_input
5434 .as_ref()
5435 .filter(|pending_input| pending_input.focus == self.focus)
5436 }
5437
5438 pub fn has_pending_keystrokes(&self) -> bool {
5440 self.active_pending_input().is_some()
5441 }
5442
5443 pub(crate) fn clear_pending_keystrokes(&mut self) {
5444 self.pending_input.take();
5445 }
5446
5447 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
5449 self.active_pending_input()
5450 .map(|pending_input| pending_input.keystrokes.as_slice())
5451 }
5452
5453 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
5454 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5455 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5456
5457 'replay: for replay in replays {
5458 let event = KeyDownEvent {
5459 keystroke: replay.keystroke.clone(),
5460 is_held: false,
5461 prefer_character_input: true,
5462 };
5463
5464 cx.propagate_event = true;
5465 for binding in replay.bindings {
5466 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5467 if !cx.propagate_event {
5468 self.dispatch_keystroke_observers(
5469 &event,
5470 Some(binding.action),
5471 Vec::default(),
5472 cx,
5473 );
5474 continue 'replay;
5475 }
5476 }
5477
5478 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
5479 if !cx.propagate_event {
5480 continue 'replay;
5481 }
5482 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
5483 && let Some(mut input_handler) = self.platform_window.take_input_handler()
5484 {
5485 input_handler.dispatch_input(&input, self, cx);
5486 self.platform_window.set_input_handler(input_handler)
5487 }
5488 }
5489 }
5490
5491 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
5492 focus_id
5493 .and_then(|focus_id| {
5494 self.rendered_frame
5495 .dispatch_tree
5496 .focusable_node_id(focus_id)
5497 })
5498 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
5499 }
5500
5501 fn dispatch_action_on_node(
5502 &mut self,
5503 node_id: DispatchNodeId,
5504 action: &dyn Action,
5505 cx: &mut App,
5506 ) {
5507 self.dispatch_action_on_node_inner(node_id, action, cx);
5508
5509 if !cx.propagate_event
5510 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
5511 && self.last_input_was_keyboard()
5512 {
5513 cx.platform.hide_cursor_until_mouse_moves();
5514 }
5515 }
5516
5517 fn dispatch_action_on_node_inner(
5518 &mut self,
5519 node_id: DispatchNodeId,
5520 action: &dyn Action,
5521 cx: &mut App,
5522 ) {
5523 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5524
5525 cx.propagate_event = true;
5527 if let Some(mut global_listeners) = cx
5528 .global_action_listeners
5529 .remove(&action.as_any().type_id())
5530 {
5531 for listener in &global_listeners {
5532 profiler::update_running_action(action, cx);
5533 listener(action.as_any(), DispatchPhase::Capture, cx);
5534 profiler::save_action_timing();
5535 if !cx.propagate_event {
5536 break;
5537 }
5538 }
5539
5540 global_listeners.extend(
5541 cx.global_action_listeners
5542 .remove(&action.as_any().type_id())
5543 .unwrap_or_default(),
5544 );
5545
5546 cx.global_action_listeners
5547 .insert(action.as_any().type_id(), global_listeners);
5548 }
5549
5550 if !cx.propagate_event {
5551 return;
5552 }
5553
5554 for node_id in &dispatch_path {
5556 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5557 for DispatchActionListener {
5558 action_type,
5559 listener,
5560 } in node.action_listeners.clone()
5561 {
5562 let any_action = action.as_any();
5563 if action_type == any_action.type_id() {
5564 profiler::update_running_action(action, cx);
5565 listener(any_action, DispatchPhase::Capture, self, cx);
5566 profiler::save_action_timing();
5567
5568 if !cx.propagate_event {
5569 return;
5570 }
5571 }
5572 }
5573 }
5574
5575 for node_id in dispatch_path.iter().rev() {
5577 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5578 for DispatchActionListener {
5579 action_type,
5580 listener,
5581 } in node.action_listeners.clone()
5582 {
5583 let any_action = action.as_any();
5584 if action_type == any_action.type_id() {
5585 cx.propagate_event = false; profiler::update_running_action(action, cx);
5587 listener(any_action, DispatchPhase::Bubble, self, cx);
5588 profiler::save_action_timing();
5589
5590 if !cx.propagate_event {
5591 return;
5592 }
5593 }
5594 }
5595 }
5596
5597 if let Some(mut global_listeners) = cx
5599 .global_action_listeners
5600 .remove(&action.as_any().type_id())
5601 {
5602 for listener in global_listeners.iter().rev() {
5603 cx.propagate_event = false; profiler::update_running_action(action, cx);
5606 listener(action.as_any(), DispatchPhase::Bubble, cx);
5607 profiler::save_action_timing();
5608 if !cx.propagate_event {
5609 break;
5610 }
5611 }
5612
5613 global_listeners.extend(
5614 cx.global_action_listeners
5615 .remove(&action.as_any().type_id())
5616 .unwrap_or_default(),
5617 );
5618
5619 cx.global_action_listeners
5620 .insert(action.as_any().type_id(), global_listeners);
5621 }
5622 }
5623
5624 pub fn observe_global<G: Global>(
5627 &mut self,
5628 cx: &mut App,
5629 f: impl Fn(&mut Window, &mut App) + 'static,
5630 ) -> Subscription {
5631 let window_handle = self.handle;
5632 let (subscription, activate) = cx.global_observers.insert(
5633 TypeId::of::<G>(),
5634 Box::new(move |cx| {
5635 window_handle
5636 .update(cx, |_, window, cx| f(window, cx))
5637 .is_ok()
5638 }),
5639 );
5640 cx.defer(move |_| activate());
5641 subscription
5642 }
5643
5644 pub fn activate_window(&self) {
5646 self.platform_window.activate();
5647 }
5648
5649 pub fn request_attention(&self) {
5651 self.platform_window.request_attention();
5652 }
5653
5654 pub fn minimize_window(&self) {
5656 self.platform_window.minimize();
5657 }
5658
5659 pub fn toggle_fullscreen(&self) {
5661 self.platform_window.toggle_fullscreen();
5662 }
5663
5664 pub fn invalidate_character_coordinates(&self) {
5666 self.on_next_frame(|window, cx| {
5667 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
5668 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
5669 window.platform_window.update_ime_position(bounds);
5670 }
5671 window.platform_window.set_input_handler(input_handler);
5672 }
5673 });
5674 }
5675
5676 pub fn prompt<T>(
5680 &mut self,
5681 level: PromptLevel,
5682 message: &str,
5683 detail: Option<&str>,
5684 answers: &[T],
5685 cx: &mut App,
5686 ) -> oneshot::Receiver<usize>
5687 where
5688 T: Clone + Into<PromptButton>,
5689 {
5690 let prompt_builder = cx.prompt_builder.take();
5691 let Some(prompt_builder) = prompt_builder else {
5692 unreachable!("Re-entrant window prompting is not supported by GPUI");
5693 };
5694
5695 let answers = answers
5696 .iter()
5697 .map(|answer| answer.clone().into())
5698 .collect::<Vec<_>>();
5699
5700 let receiver = match &prompt_builder {
5701 PromptBuilder::Default => self
5702 .platform_window
5703 .prompt(level, message, detail, &answers)
5704 .unwrap_or_else(|| {
5705 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
5706 }),
5707 PromptBuilder::Custom(_) => {
5708 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
5709 }
5710 };
5711
5712 cx.prompt_builder = Some(prompt_builder);
5713
5714 receiver
5715 }
5716
5717 fn build_custom_prompt(
5718 &mut self,
5719 prompt_builder: &PromptBuilder,
5720 level: PromptLevel,
5721 message: &str,
5722 detail: Option<&str>,
5723 answers: &[PromptButton],
5724 cx: &mut App,
5725 ) -> oneshot::Receiver<usize> {
5726 let (sender, receiver) = oneshot::channel();
5727 let handle = PromptHandle::new(sender);
5728 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
5729 self.prompt = Some(handle);
5730 receiver
5731 }
5732
5733 pub fn has_active_prompt(&self) -> bool {
5738 self.prompt.is_some()
5739 }
5740
5741 pub fn context_stack(&self) -> Vec<KeyContext> {
5743 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5744 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5745 dispatch_tree
5746 .dispatch_path(node_id)
5747 .iter()
5748 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
5749 .collect()
5750 }
5751
5752 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
5754 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5755 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
5756 for action_type in cx.global_action_listeners.keys() {
5757 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
5758 let action = cx.actions.build_action_type(action_type).ok();
5759 if let Some(action) = action {
5760 actions.insert(ix, action);
5761 }
5762 }
5763 }
5764 actions
5765 }
5766
5767 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
5770 self.rendered_frame
5771 .dispatch_tree
5772 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
5773 }
5774
5775 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
5778 self.rendered_frame
5779 .dispatch_tree
5780 .highest_precedence_binding_for_action(
5781 action,
5782 &self.rendered_frame.dispatch_tree.context_stack,
5783 )
5784 }
5785
5786 pub fn bindings_for_action_in_context(
5788 &self,
5789 action: &dyn Action,
5790 context: KeyContext,
5791 ) -> Vec<KeyBinding> {
5792 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5793 dispatch_tree.bindings_for_action(action, &[context])
5794 }
5795
5796 pub fn highest_precedence_binding_for_action_in_context(
5799 &self,
5800 action: &dyn Action,
5801 context: KeyContext,
5802 ) -> Option<KeyBinding> {
5803 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5804 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
5805 }
5806
5807 pub fn bindings_for_action_in(
5811 &self,
5812 action: &dyn Action,
5813 focus_handle: &FocusHandle,
5814 ) -> Vec<KeyBinding> {
5815 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5816 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
5817 return vec![];
5818 };
5819 dispatch_tree.bindings_for_action(action, &context_stack)
5820 }
5821
5822 pub fn highest_precedence_binding_for_action_in(
5826 &self,
5827 action: &dyn Action,
5828 focus_handle: &FocusHandle,
5829 ) -> Option<KeyBinding> {
5830 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5831 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
5832 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
5833 }
5834
5835 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
5837 self.rendered_frame
5838 .dispatch_tree
5839 .possible_next_bindings_for_input(input, &self.context_stack())
5840 }
5841
5842 fn context_stack_for_focus_handle(
5843 &self,
5844 focus_handle: &FocusHandle,
5845 ) -> Option<Vec<KeyContext>> {
5846 let dispatch_tree = &self.rendered_frame.dispatch_tree;
5847 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
5848 let context_stack: Vec<_> = dispatch_tree
5849 .dispatch_path(node_id)
5850 .into_iter()
5851 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
5852 .collect();
5853 Some(context_stack)
5854 }
5855
5856 pub fn listener_for<T: 'static, E>(
5858 &self,
5859 view: &Entity<T>,
5860 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
5861 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
5862 let view = view.downgrade();
5863 move |e: &E, window: &mut Window, cx: &mut App| {
5864 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
5865 }
5866 }
5867
5868 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
5870 &self,
5871 entity: &Entity<E>,
5872 f: Callback,
5873 ) -> impl Fn(&mut Window, &mut App) + 'static {
5874 let entity = entity.downgrade();
5875 move |window: &mut Window, cx: &mut App| {
5876 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
5877 }
5878 }
5879
5880 pub fn on_window_should_close(
5883 &self,
5884 cx: &App,
5885 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
5886 ) {
5887 let mut cx = self.to_async(cx);
5888 self.platform_window.on_should_close(Box::new(move || {
5889 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
5890 }))
5891 }
5892
5893 pub fn on_action(
5902 &mut self,
5903 action_type: TypeId,
5904 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5905 ) {
5906 self.invalidator.debug_assert_paint();
5907
5908 self.next_frame
5909 .dispatch_tree
5910 .on_action(action_type, Rc::new(listener));
5911 }
5912
5913 pub fn on_action_when(
5922 &mut self,
5923 condition: bool,
5924 action_type: TypeId,
5925 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5926 ) {
5927 self.invalidator.debug_assert_paint();
5928
5929 if condition {
5930 self.next_frame
5931 .dispatch_tree
5932 .on_action(action_type, Rc::new(listener));
5933 }
5934 }
5935
5936 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
5939 self.platform_window.gpu_specs()
5940 }
5941
5942 pub fn titlebar_double_click(&self) {
5945 self.platform_window
5946 .titlebar_double_click(self.is_resizable, self.is_minimizable);
5947 }
5948
5949 pub fn window_title(&self) -> String {
5952 self.platform_window.get_title()
5953 }
5954
5955 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
5958 self.platform_window.tabbed_windows()
5959 }
5960
5961 pub fn tab_bar_visible(&self) -> bool {
5964 self.platform_window.tab_bar_visible()
5965 }
5966
5967 pub fn merge_all_windows(&self) {
5970 self.platform_window.merge_all_windows()
5971 }
5972
5973 pub fn move_tab_to_new_window(&self) {
5976 self.platform_window.move_tab_to_new_window()
5977 }
5978
5979 pub fn toggle_window_tab_overview(&self) {
5982 self.platform_window.toggle_window_tab_overview()
5983 }
5984
5985 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
5988 self.platform_window
5989 .set_tabbing_identifier(tabbing_identifier)
5990 }
5991
5992 pub fn play_system_bell(&self) {
5995 self.platform_window.play_system_bell()
5996 }
5997
5998 pub fn is_a11y_active(&self) -> bool {
6009 self.a11y.is_active()
6010 }
6011
6012 #[cfg(any(test, feature = "test-support"))]
6019 pub fn enable_a11y_for_testing(&mut self) {
6020 self.a11y.enable_for_test();
6021 self.refresh();
6022 }
6023
6024 pub fn debug_a11y_tree_json(&self) -> Option<String> {
6026 self.a11y.debug_tree_json()
6027 }
6028
6029 pub fn on_a11y_action(
6035 &mut self,
6036 node_id: accesskit::NodeId,
6037 action: accesskit::Action,
6038 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
6039 ) {
6040 self.a11y
6041 .action_listeners
6042 .entry(node_id)
6043 .or_default()
6044 .push((action, Box::new(listener)));
6045 }
6046
6047 #[cfg(not(target_family = "wasm"))]
6048 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
6049 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
6052 let extra_data = request.data.as_ref();
6053 let mut matched = false;
6054 for (action, listener) in &mut listeners {
6055 if *action == request.action {
6056 listener(extra_data, self, cx);
6057 matched = true;
6058 }
6059 }
6060 self.a11y
6061 .action_listeners
6062 .insert(request.target_node, listeners);
6063 if matched {
6064 return;
6065 }
6066 }
6067
6068 match request.action {
6070 accesskit::Action::Click => {
6071 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
6072 let center = bounds.center();
6073 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
6074 button: MouseButton::Left,
6075 position: center,
6076 modifiers: Modifiers::default(),
6077 click_count: 1,
6078 first_mouse: false,
6079 });
6080 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
6081 button: MouseButton::Left,
6082 position: center,
6083 modifiers: Modifiers::default(),
6084 click_count: 1,
6085 });
6086 self.dispatch_event(mouse_down, cx);
6087 self.dispatch_event(mouse_up, cx);
6088 }
6089 }
6090 accesskit::Action::Focus => {
6091 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
6092 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
6093 {
6094 self.focus(&handle, cx);
6095 }
6096 }
6097 accesskit::Action::Blur => {
6098 self.blur();
6099 }
6100 _ => {
6101 log::debug!(
6102 "Unhandled a11y action: {:?} on {:?}",
6103 request.action,
6104 request.target_node
6105 );
6106 }
6107 }
6108 }
6109
6110 #[cfg(any(feature = "inspector", debug_assertions))]
6112 pub fn toggle_inspector(&mut self, cx: &mut App) {
6113 self.inspector = match self.inspector {
6114 None => Some(cx.new(|_| Inspector::new())),
6115 Some(_) => None,
6116 };
6117 self.refresh();
6118 }
6119
6120 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
6122 #[cfg(any(feature = "inspector", debug_assertions))]
6123 {
6124 if let Some(inspector) = &self.inspector {
6125 return inspector.read(_cx).is_picking();
6126 }
6127 }
6128 false
6129 }
6130
6131 #[cfg(any(feature = "inspector", debug_assertions))]
6133 pub fn with_inspector_state<T: 'static, R>(
6134 &mut self,
6135 _inspector_id: Option<&crate::InspectorElementId>,
6136 cx: &mut App,
6137 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
6138 ) -> R {
6139 if let Some(inspector_id) = _inspector_id
6140 && let Some(inspector) = &self.inspector
6141 {
6142 let inspector = inspector.clone();
6143 let active_element_id = inspector.read(cx).active_element_id();
6144 if Some(inspector_id) == active_element_id {
6145 return inspector.update(cx, |inspector, _cx| {
6146 inspector.with_active_element_state(self, f)
6147 });
6148 }
6149 }
6150 f(&mut None, self)
6151 }
6152
6153 #[cfg(any(feature = "inspector", debug_assertions))]
6154 pub(crate) fn build_inspector_element_id(
6155 &mut self,
6156 path: crate::InspectorElementPath,
6157 ) -> crate::InspectorElementId {
6158 self.invalidator.debug_assert_paint_or_prepaint();
6159 let path = Rc::new(path);
6160 let next_instance_id = self
6161 .next_frame
6162 .next_inspector_instance_ids
6163 .entry(path.clone())
6164 .or_insert(0);
6165 let instance_id = *next_instance_id;
6166 *next_instance_id += 1;
6167 crate::InspectorElementId { path, instance_id }
6168 }
6169
6170 #[cfg(any(feature = "inspector", debug_assertions))]
6171 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
6172 if let Some(inspector) = self.inspector.take() {
6173 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
6174 inspector_element.prepaint_as_root(
6175 point(self.viewport_size.width - inspector_width, px(0.0)),
6176 size(inspector_width, self.viewport_size.height).into(),
6177 self,
6178 cx,
6179 );
6180 self.inspector = Some(inspector);
6181 Some(inspector_element)
6182 } else {
6183 None
6184 }
6185 }
6186
6187 #[cfg(any(feature = "inspector", debug_assertions))]
6188 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
6189 if let Some(mut inspector_element) = inspector_element {
6190 inspector_element.paint(self, cx);
6191 };
6192 }
6193
6194 #[cfg(any(feature = "inspector", debug_assertions))]
6197 pub fn insert_inspector_hitbox(
6198 &mut self,
6199 hitbox_id: HitboxId,
6200 inspector_id: Option<&crate::InspectorElementId>,
6201 cx: &App,
6202 ) {
6203 self.invalidator.debug_assert_paint_or_prepaint();
6204 if !self.is_inspector_picking(cx) {
6205 return;
6206 }
6207 if let Some(inspector_id) = inspector_id {
6208 self.next_frame
6209 .inspector_hitboxes
6210 .insert(hitbox_id, inspector_id.clone());
6211 }
6212 }
6213
6214 #[cfg(any(feature = "inspector", debug_assertions))]
6215 fn paint_inspector_hitbox(&mut self, cx: &App) {
6216 if let Some(inspector) = self.inspector.as_ref() {
6217 let inspector = inspector.read(cx);
6218 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
6219 && let Some(hitbox) = self
6220 .next_frame
6221 .hitboxes
6222 .iter()
6223 .find(|hitbox| hitbox.id == hitbox_id)
6224 {
6225 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
6226 }
6227 }
6228 }
6229
6230 #[cfg(any(feature = "inspector", debug_assertions))]
6231 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6232 let Some(inspector) = self.inspector.clone() else {
6233 return;
6234 };
6235 if event.downcast_ref::<MouseMoveEvent>().is_some() {
6236 inspector.update(cx, |inspector, _cx| {
6237 if let Some((_, inspector_id)) =
6238 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6239 {
6240 inspector.hover(inspector_id, self);
6241 }
6242 });
6243 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
6244 inspector.update(cx, |inspector, _cx| {
6245 if let Some((_, inspector_id)) =
6246 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6247 {
6248 inspector.select(inspector_id, self);
6249 }
6250 });
6251 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
6252 const SCROLL_LINES: f32 = 3.0;
6254 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
6255 let delta_y = event
6256 .delta
6257 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
6258 .y;
6259 if let Some(inspector) = self.inspector.clone() {
6260 inspector.update(cx, |inspector, _cx| {
6261 if let Some(depth) = inspector.pick_depth.as_mut() {
6262 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
6263 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
6264 if *depth < 0.0 {
6265 *depth = 0.0;
6266 } else if *depth > max_depth {
6267 *depth = max_depth;
6268 }
6269 if let Some((_, inspector_id)) =
6270 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6271 {
6272 inspector.set_active_element_id(inspector_id, self);
6273 }
6274 }
6275 });
6276 }
6277 }
6278 }
6279
6280 #[cfg(any(feature = "inspector", debug_assertions))]
6281 fn hovered_inspector_hitbox(
6282 &self,
6283 inspector: &Inspector,
6284 frame: &Frame,
6285 ) -> Option<(HitboxId, crate::InspectorElementId)> {
6286 if let Some(pick_depth) = inspector.pick_depth {
6287 let depth = (pick_depth as i64).try_into().unwrap_or(0);
6288 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
6289 let skip_count = (depth as usize).min(max_skipped);
6290 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
6291 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
6292 return Some((*hitbox_id, inspector_id.clone()));
6293 }
6294 }
6295 }
6296 None
6297 }
6298
6299 #[cfg(any(test, feature = "test-support"))]
6302 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
6303 self.modifiers = modifiers;
6304 }
6305
6306 #[cfg(any(test, feature = "test-support"))]
6310 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
6311 let event = PlatformInput::MouseMove(MouseMoveEvent {
6312 position,
6313 modifiers: self.modifiers,
6314 pressed_button: None,
6315 });
6316 let _ = self.dispatch_event(event, cx);
6317 }
6318}
6319
6320slotmap::new_key_type! {
6322 pub struct WindowId;
6324}
6325
6326impl WindowId {
6327 pub fn as_u64(&self) -> u64 {
6329 self.0.as_ffi()
6330 }
6331}
6332
6333impl From<u64> for WindowId {
6334 fn from(value: u64) -> Self {
6335 WindowId(slotmap::KeyData::from_ffi(value))
6336 }
6337}
6338
6339#[derive(Deref, DerefMut)]
6342pub struct WindowHandle<V> {
6343 #[deref]
6344 #[deref_mut]
6345 pub(crate) any_handle: AnyWindowHandle,
6346 state_type: PhantomData<fn(V) -> V>,
6347}
6348
6349impl<V> Debug for WindowHandle<V> {
6350 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6351 f.debug_struct("WindowHandle")
6352 .field("any_handle", &self.any_handle.id.as_u64())
6353 .finish()
6354 }
6355}
6356
6357impl<V: 'static + Render> WindowHandle<V> {
6358 pub fn new(id: WindowId) -> Self {
6361 WindowHandle {
6362 any_handle: AnyWindowHandle {
6363 id,
6364 state_type: TypeId::of::<V>(),
6365 },
6366 state_type: PhantomData,
6367 }
6368 }
6369
6370 #[cfg(any(test, feature = "test-support"))]
6374 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
6375 where
6376 C: AppContext,
6377 {
6378 cx.update_window(self.any_handle, |root_view, _, _| {
6379 root_view
6380 .downcast::<V>()
6381 .map_err(|_| anyhow!("the type of the window's root view has changed"))
6382 })?
6383 }
6384
6385 pub fn update<C, R>(
6389 &self,
6390 cx: &mut C,
6391 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
6392 ) -> Result<R>
6393 where
6394 C: AppContext,
6395 {
6396 cx.update_window(self.any_handle, |root_view, window, cx| {
6397 let view = root_view
6398 .downcast::<V>()
6399 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6400
6401 Ok(view.update(cx, |view, cx| update(view, window, cx)))
6402 })?
6403 }
6404
6405 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
6409 let x = cx
6410 .windows
6411 .get(self.id)
6412 .and_then(|window| {
6413 window
6414 .as_deref()
6415 .and_then(|window| window.root.clone())
6416 .map(|root_view| root_view.downcast::<V>())
6417 })
6418 .context("window not found")?
6419 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6420
6421 Ok(x.read(cx))
6422 }
6423
6424 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
6428 where
6429 C: AppContext,
6430 {
6431 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
6432 }
6433
6434 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
6438 where
6439 C: AppContext,
6440 {
6441 cx.read_window(self, |root_view, _cx| root_view)
6442 }
6443
6444 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
6449 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
6450 .ok()
6451 }
6452}
6453
6454impl<V> Copy for WindowHandle<V> {}
6455
6456impl<V> Clone for WindowHandle<V> {
6457 fn clone(&self) -> Self {
6458 *self
6459 }
6460}
6461
6462impl<V> PartialEq for WindowHandle<V> {
6463 fn eq(&self, other: &Self) -> bool {
6464 self.any_handle == other.any_handle
6465 }
6466}
6467
6468impl<V> Eq for WindowHandle<V> {}
6469
6470impl<V> Hash for WindowHandle<V> {
6471 fn hash<H: Hasher>(&self, state: &mut H) {
6472 self.any_handle.hash(state);
6473 }
6474}
6475
6476impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
6477 fn from(val: WindowHandle<V>) -> Self {
6478 val.any_handle
6479 }
6480}
6481
6482#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
6484pub struct AnyWindowHandle {
6485 pub(crate) id: WindowId,
6486 state_type: TypeId,
6487}
6488
6489impl AnyWindowHandle {
6490 pub fn window_id(&self) -> WindowId {
6492 self.id
6493 }
6494
6495 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
6498 if TypeId::of::<T>() == self.state_type {
6499 Some(WindowHandle {
6500 any_handle: *self,
6501 state_type: PhantomData,
6502 })
6503 } else {
6504 None
6505 }
6506 }
6507
6508 pub fn update<C, R>(
6512 self,
6513 cx: &mut C,
6514 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
6515 ) -> Result<R>
6516 where
6517 C: AppContext,
6518 {
6519 cx.update_window(self, update)
6520 }
6521
6522 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
6526 where
6527 C: AppContext,
6528 T: 'static,
6529 {
6530 let view = self
6531 .downcast::<T>()
6532 .context("the type of the window's root view has changed")?;
6533
6534 cx.read_window(&view, read)
6535 }
6536}
6537
6538impl HasWindowHandle for Window {
6539 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
6540 self.platform_window.window_handle()
6541 }
6542}
6543
6544impl HasDisplayHandle for Window {
6545 fn display_handle(
6546 &self,
6547 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
6548 self.platform_window.display_handle()
6549 }
6550}
6551
6552#[derive(Clone, Debug, Eq, PartialEq, Hash)]
6557pub enum ElementId {
6558 View(EntityId),
6560 Integer(u64),
6562 Name(SharedString),
6564 Uuid(Uuid),
6566 FocusHandle(FocusId),
6568 NamedInteger(SharedString, u64),
6570 Path(Arc<std::path::Path>),
6572 CodeLocation(core::panic::Location<'static>),
6574 NamedChild(Arc<ElementId>, SharedString),
6576 OpaqueId([u8; 20]),
6578}
6579
6580impl ElementId {
6581 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
6583 Self::NamedInteger(name.into(), integer as u64)
6584 }
6585}
6586
6587impl Display for ElementId {
6588 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6589 match self {
6590 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
6591 ElementId::Integer(ix) => write!(f, "{}", ix)?,
6592 ElementId::Name(name) => write!(f, "{}", name)?,
6593 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
6594 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
6595 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
6596 ElementId::Path(path) => write!(f, "{}", path.display())?,
6597 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
6598 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
6599 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
6600 }
6601
6602 Ok(())
6603 }
6604}
6605
6606impl TryInto<SharedString> for ElementId {
6607 type Error = anyhow::Error;
6608
6609 fn try_into(self) -> anyhow::Result<SharedString> {
6610 if let ElementId::Name(name) = self {
6611 Ok(name)
6612 } else {
6613 anyhow::bail!("element id is not string")
6614 }
6615 }
6616}
6617
6618impl From<usize> for ElementId {
6619 fn from(id: usize) -> Self {
6620 ElementId::Integer(id as u64)
6621 }
6622}
6623
6624impl From<i32> for ElementId {
6625 fn from(id: i32) -> Self {
6626 Self::Integer(id as u64)
6627 }
6628}
6629
6630impl From<SharedString> for ElementId {
6631 fn from(name: SharedString) -> Self {
6632 ElementId::Name(name)
6633 }
6634}
6635
6636impl From<String> for ElementId {
6637 fn from(name: String) -> Self {
6638 ElementId::Name(name.into())
6639 }
6640}
6641
6642impl From<Arc<str>> for ElementId {
6643 fn from(name: Arc<str>) -> Self {
6644 ElementId::Name(name.into())
6645 }
6646}
6647
6648impl From<Arc<std::path::Path>> for ElementId {
6649 fn from(path: Arc<std::path::Path>) -> Self {
6650 ElementId::Path(path)
6651 }
6652}
6653
6654impl From<&'static str> for ElementId {
6655 fn from(name: &'static str) -> Self {
6656 ElementId::Name(SharedString::new_static(name))
6657 }
6658}
6659
6660impl<'a> From<&'a FocusHandle> for ElementId {
6661 fn from(handle: &'a FocusHandle) -> Self {
6662 ElementId::FocusHandle(handle.id)
6663 }
6664}
6665
6666impl From<(&'static str, EntityId)> for ElementId {
6667 fn from((name, id): (&'static str, EntityId)) -> Self {
6668 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
6669 }
6670}
6671
6672impl From<(&'static str, usize)> for ElementId {
6673 fn from((name, id): (&'static str, usize)) -> Self {
6674 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
6675 }
6676}
6677
6678impl From<(SharedString, usize)> for ElementId {
6679 fn from((name, id): (SharedString, usize)) -> Self {
6680 ElementId::NamedInteger(name, id as u64)
6681 }
6682}
6683
6684impl From<(&'static str, u64)> for ElementId {
6685 fn from((name, id): (&'static str, u64)) -> Self {
6686 ElementId::NamedInteger(SharedString::new_static(name), id)
6687 }
6688}
6689
6690impl From<Uuid> for ElementId {
6691 fn from(value: Uuid) -> Self {
6692 Self::Uuid(value)
6693 }
6694}
6695
6696impl From<(&'static str, u32)> for ElementId {
6697 fn from((name, id): (&'static str, u32)) -> Self {
6698 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
6699 }
6700}
6701
6702impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
6703 fn from((id, name): (ElementId, T)) -> Self {
6704 ElementId::NamedChild(Arc::new(id), name.into())
6705 }
6706}
6707
6708impl From<&'static core::panic::Location<'static>> for ElementId {
6709 fn from(location: &'static core::panic::Location<'static>) -> Self {
6710 ElementId::CodeLocation(*location)
6711 }
6712}
6713
6714impl From<[u8; 20]> for ElementId {
6715 fn from(opaque_id: [u8; 20]) -> Self {
6716 ElementId::OpaqueId(opaque_id)
6717 }
6718}
6719
6720#[derive(Clone)]
6723pub struct PaintQuad {
6724 pub bounds: Bounds<Pixels>,
6726 pub corner_radii: Corners<Pixels>,
6728 pub background: Background,
6730 pub border_widths: Edges<Pixels>,
6732 pub border_color: Hsla,
6734 pub border_style: BorderStyle,
6736}
6737
6738impl PaintQuad {
6739 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
6741 PaintQuad {
6742 corner_radii: corner_radii.into(),
6743 ..self
6744 }
6745 }
6746
6747 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
6749 PaintQuad {
6750 border_widths: border_widths.into(),
6751 ..self
6752 }
6753 }
6754
6755 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
6757 PaintQuad {
6758 border_color: border_color.into(),
6759 ..self
6760 }
6761 }
6762
6763 pub fn background(self, background: impl Into<Background>) -> Self {
6765 PaintQuad {
6766 background: background.into(),
6767 ..self
6768 }
6769 }
6770}
6771
6772pub fn quad(
6774 bounds: Bounds<Pixels>,
6775 corner_radii: impl Into<Corners<Pixels>>,
6776 background: impl Into<Background>,
6777 border_widths: impl Into<Edges<Pixels>>,
6778 border_color: impl Into<Hsla>,
6779 border_style: BorderStyle,
6780) -> PaintQuad {
6781 PaintQuad {
6782 bounds,
6783 corner_radii: corner_radii.into(),
6784 background: background.into(),
6785 border_widths: border_widths.into(),
6786 border_color: border_color.into(),
6787 border_style,
6788 }
6789}
6790
6791pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
6793 PaintQuad {
6794 bounds: bounds.into(),
6795 corner_radii: (0.).into(),
6796 background: background.into(),
6797 border_widths: (0.).into(),
6798 border_color: transparent_black(),
6799 border_style: BorderStyle::default(),
6800 }
6801}
6802
6803pub fn outline(
6805 bounds: impl Into<Bounds<Pixels>>,
6806 border_color: impl Into<Hsla>,
6807 border_style: BorderStyle,
6808) -> PaintQuad {
6809 PaintQuad {
6810 bounds: bounds.into(),
6811 corner_radii: (0.).into(),
6812 background: transparent_black().into(),
6813 border_widths: (1.).into(),
6814 border_color: border_color.into(),
6815 border_style,
6816 }
6817}
6818
6819#[cfg(test)]
6820mod tests {
6821 use std::{
6822 cell::{Cell, RefCell},
6823 path::PathBuf,
6824 rc::Rc,
6825 };
6826
6827 use crate::{
6828 AnyWindowHandle, AppContext as _, Bounds, Context, CursorStyle, DragMoveEvent, Empty,
6829 ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle,
6830 InputEvent as _, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,
6831 MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, Point, Render,
6832 StatefulInteractiveElement as _, Styled, TestAppContext, Window, WindowAppearance,
6833 WindowOptions, canvas, div, point, px, size,
6834 };
6835
6836 #[gpui::test]
6837 fn test_drag_cursor_applies_before_next_paint(cx: &mut TestAppContext) {
6838 struct ResizeHandle;
6839
6840 impl Render for ResizeHandle {
6841 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6842 div().size_full().cursor_text().child(
6843 div()
6844 .id("resize-handle")
6845 .w(px(4.))
6846 .h_full()
6847 .cursor_col_resize()
6848 .on_drag((), |_, _, _, cx| cx.new(|_| Empty)),
6849 )
6850 }
6851 }
6852
6853 let window = cx.add_window(|_, _| ResizeHandle);
6854 let handle_position = point(px(1.), px(10.));
6855 let drag_position = point(px(20.), px(10.));
6856 let cursor_observer = cx.clone();
6857
6858 let update_result = cx.update_window(window.into(), |_, window, cx| {
6859 window.hovered.set(true);
6860 window.active.set(true);
6861 window.draw(cx).clear(cx);
6862 window.dispatch_event(
6863 MouseMoveEvent {
6864 position: handle_position,
6865 ..Default::default()
6866 }
6867 .to_platform_input(),
6868 cx,
6869 );
6870 window.dispatch_event(
6871 MouseDownEvent {
6872 position: handle_position,
6873 button: MouseButton::Left,
6874 ..Default::default()
6875 }
6876 .to_platform_input(),
6877 cx,
6878 );
6879 window.dispatch_event(
6880 MouseMoveEvent {
6881 position: drag_position,
6882 pressed_button: Some(MouseButton::Left),
6883 ..Default::default()
6884 }
6885 .to_platform_input(),
6886 cx,
6887 );
6888 assert!(cx.has_active_drag());
6889 assert_eq!(cursor_observer.cursor_style(), CursorStyle::ResizeColumn);
6891
6892 window.draw(cx).clear(cx);
6893 window.dispatch_event(
6894 MouseUpEvent {
6895 position: drag_position,
6896 button: MouseButton::Left,
6897 ..Default::default()
6898 }
6899 .to_platform_input(),
6900 cx,
6901 );
6902 window.draw(cx).clear(cx);
6903 });
6904 assert!(
6905 update_result.is_ok(),
6906 "failed to run drag: {update_result:?}"
6907 );
6908 assert_eq!(cursor_observer.cursor_style(), CursorStyle::IBeam);
6909 }
6910 #[gpui::test]
6911 fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
6912 let window = cx.add_window(|_, _| crate::EmptyView);
6913 let platform_window = cx.test_window(window.into());
6914 {
6915 let app = cx.app.borrow_mut();
6916 platform_window.simulate_close();
6917 assert!(app.windows.contains_key(window.window_id()));
6918 }
6919 cx.run_until_parked();
6920 assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
6921 }
6922
6923 #[gpui::test]
6924 fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
6925 struct Child {
6926 renders: usize,
6927 }
6928
6929 impl Render for Child {
6930 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6931 self.renders += 1;
6932 div().size_full().bg(crate::rgb(0xff0000))
6933 }
6934 }
6935
6936 struct Root {
6937 opacity: f32,
6938 width: Pixels,
6939 child: crate::Entity<Child>,
6940 }
6941
6942 impl Render for Root {
6943 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
6944 div()
6945 .w(self.width)
6946 .h(px(200.))
6947 .opacity(self.opacity)
6948 .hover(|style| style.opacity(1.))
6949 .child(
6950 self.child
6951 .clone()
6952 .cached(crate::StyleRefinement::default().size(px(100.))),
6953 )
6954 }
6955 }
6956
6957 fn update_and_draw(
6960 window: crate::WindowHandle<Root>,
6961 child: &crate::Entity<Child>,
6962 cx: &mut TestAppContext,
6963 update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
6964 ) -> (f32, usize) {
6965 window
6966 .update(cx, |root, window, cx| {
6967 update(root, window, cx);
6968 cx.notify();
6969 })
6970 .expect("update root");
6971 for _ in 0..3 {
6972 let (alpha, renders, requested_frames) = cx
6973 .update_window(window.into(), |_, window, cx| {
6974 window.draw(cx).clear(cx);
6975 let quads = &window.rendered_frame.scene.quads;
6976 assert_eq!(quads.len(), 1);
6977 let alpha = quads.first().expect("child quad").background.solid.a;
6978 (
6979 alpha,
6980 child.read(cx).renders,
6981 window.simulate_next_frame(cx),
6982 )
6983 })
6984 .expect("draw window");
6985 if requested_frames == 0 {
6986 return (alpha, renders);
6987 }
6988 }
6989 panic!("cached child kept requesting frames");
6990 }
6991
6992 let child = cx.new(|_| Child { renders: 0 });
6993 let window = cx.add_window(|_, _| Root {
6994 opacity: 1.,
6995 width: px(200.),
6996 child: child.clone(),
6997 });
6998 let outside = point(px(500.), px(500.));
6999 let inside = point(px(50.), px(50.));
7000 let beside = point(px(250.), px(50.));
7001
7002 let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
7004 window.simulate_mouse_move(outside, cx)
7005 };
7006 assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
7007 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
7008 let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
7009 assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
7010 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
7011
7012 let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
7014 window.simulate_mouse_move(inside, cx)
7015 };
7016 assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
7017 let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
7018 window.simulate_mouse_move(beside, cx)
7019 };
7020 assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
7021
7022 let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
7025 assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
7026 }
7027 #[gpui::test]
7028 fn bordered_scroll_panes_preserve_bounds_at_fractional_scales(cx: &mut TestAppContext) {
7029 struct Panes {
7030 scroll: [crate::ScrollHandle; 2],
7031 }
7032 impl Render for Panes {
7033 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7034 div()
7035 .size_full()
7036 .flex()
7037 .flex_col()
7038 .child(
7039 div()
7040 .flex()
7041 .flex_1()
7042 .min_h_0()
7043 .children((0..2).map(|index| {
7044 div()
7045 .flex()
7046 .flex_col()
7047 .flex_1()
7048 .min_w_0()
7049 .h_full()
7050 .border_1()
7051 .border_color(crate::rgb(0xffcc00))
7052 .bg(crate::rgb(0x18202a))
7053 .child(
7054 div().h(px(32.5)).flex_shrink_0().bg(crate::rgb(0x00ff00)),
7055 )
7056 .child(
7057 div()
7058 .id(index)
7059 .flex_1()
7060 .min_h_0()
7061 .overflow_y_scroll()
7062 .track_scroll(&self.scroll[index])
7063 .child(div().h(px(2400.25)).bg(crate::rgb(0xff0000))),
7064 )
7065 })),
7066 )
7067 .child(div().h(px(40.5)).flex_shrink_0().bg(crate::rgb(0x0000ff)))
7068 }
7069 }
7070 let scroll = [crate::ScrollHandle::new(), crate::ScrollHandle::new()];
7071 let handle = cx.add_window(|_, _| Panes {
7072 scroll: scroll.clone(),
7073 });
7074 for scale in [1., 1.25, 1.5, 2.] {
7075 cx.simulate_window_scale_factor_change(handle.into(), scale);
7076 for viewport in [size(px(800.), px(600.)), size(px(641.5), px(481.25))] {
7077 cx.simulate_window_resize(handle.into(), viewport);
7078 for offset in [0., -180.25] {
7079 scroll[0].set_offset(point(px(0.), px(offset)));
7080 cx.update_window(handle.into(), |_, window, cx| {
7081 window.refresh();
7082 window.draw(cx).clear(cx);
7083 let quads = &window.rendered_frame.scene.quads;
7084 let strips: Vec<_> = quads
7085 .iter()
7086 .filter(|q| q.border_color == crate::rgb(0xffcc00).into())
7087 .collect();
7088 assert_eq!(strips.len(), 8);
7089 let borders: Vec<_> = strips
7090 .chunks_exact(4)
7091 .map(|group| {
7092 let mut border = *group[0];
7093 for strip in &group[1..] {
7094 assert_eq!(strip.bounds, border.bounds);
7095 border.content_mask.bounds = border
7096 .content_mask
7097 .bounds
7098 .union(&strip.content_mask.bounds);
7099 }
7100 border
7101 })
7102 .collect();
7103 let bodies: Vec<_> = quads
7104 .iter()
7105 .filter(|q| q.background.solid == crate::rgb(0xff0000).into())
7106 .collect();
7107 let footer = quads
7108 .iter()
7109 .find(|q| q.background.solid == crate::rgb(0x0000ff).into())
7110 .unwrap();
7111 assert_eq!(borders.len(), 2);
7112 assert_eq!(bodies.len(), 2);
7113 assert_eq!(borders[0].bounds.top(), borders[1].bounds.top());
7114 assert_eq!(borders[0].bounds.bottom(), borders[1].bounds.bottom());
7115 assert_eq!(borders[0].bounds.right(), borders[1].bounds.left());
7116 assert_eq!(borders[0].bounds.bottom(), footer.bounds.top());
7117 for (border, body) in borders.iter().zip(&bodies) {
7118 assert!(border.content_mask.bounds.contains(&border.bounds.origin));
7119 assert!(border.content_mask.bounds.bottom() >= border.bounds.bottom());
7120 let visible_body = body.bounds.intersect(&body.content_mask.bounds);
7123 assert!(
7124 visible_body.bottom()
7125 <= border.bounds.bottom() - border.border_widths.bottom
7126 );
7127 assert!(
7128 visible_body.left()
7129 >= border.bounds.left() + border.border_widths.left
7130 );
7131 assert!(
7132 visible_body.right()
7133 <= border.bounds.right() - border.border_widths.right
7134 );
7135 }
7136 })
7137 .unwrap();
7138 assert!(scroll[0].max_offset().y > px(0.));
7139 assert!(scroll[1].max_offset().y > px(0.));
7140 assert_eq!(scroll[1].offset().y, px(0.));
7141 }
7142 }
7143 }
7144 }
7145
7146 #[test]
7147 fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
7148 let mut cx = TestAppContext::single();
7149 let window = cx.add_window(|_, _| crate::EmptyView);
7150 let handle: AnyWindowHandle = window.into();
7151 let window_state = |cx: &mut TestAppContext| {
7152 cx.update_window(handle, |_, window, _| {
7153 (
7154 window.scale_factor(),
7155 window.bounds(),
7156 window.viewport_size(),
7157 )
7158 })
7159 .unwrap()
7160 };
7161
7162 let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
7163 assert_eq!(scale_factor, 2.0);
7164
7165 for (scale_factor, resized_size) in [
7166 (1.0, size(px(800.), px(600.))),
7167 (1.25, size(px(640.), px(480.))),
7168 (2.0, size(px(1024.), px(768.))),
7169 ] {
7170 cx.simulate_window_scale_factor_change(handle, scale_factor);
7171 assert_eq!(
7172 window_state(&mut cx),
7173 (scale_factor, expected_bounds, expected_bounds.size)
7174 );
7175
7176 cx.simulate_window_resize(handle, resized_size);
7177 expected_bounds.size = resized_size;
7178 assert_eq!(
7179 window_state(&mut cx),
7180 (scale_factor, expected_bounds, resized_size)
7181 );
7182 }
7183 }
7184
7185 struct AccessibilityFocusFixture {
7186 focus: FocusHandle,
7187 duplicate: bool,
7188 }
7189
7190 impl Render for AccessibilityFocusFixture {
7191 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7192 let mut outer = div().id("dialog-owner").role(accesskit::Role::Dialog);
7193 if self.duplicate {
7194 outer = outer.track_focus(&self.focus);
7195 }
7196 outer.child(
7197 div()
7198 .id("input-owner")
7199 .role(accesskit::Role::TextInput)
7200 .track_focus(&self.focus),
7201 )
7202 }
7203 }
7204
7205 fn draw_accessibility_fixture(cx: &mut TestAppContext, duplicate: bool) -> String {
7206 let (_, cx) = cx.add_window_view(|window, cx| {
7207 let focus = cx.focus_handle();
7208 focus.focus(window, cx);
7209 AccessibilityFocusFixture { focus, duplicate }
7210 });
7211 cx.update(|window, _| window.enable_a11y_for_testing());
7212 cx.run_until_parked();
7213 cx.update(|window, _| {
7214 window
7215 .debug_a11y_tree_json()
7216 .expect("accessibility tree was built")
7217 })
7218 }
7219
7220 #[gpui::test]
7221 fn accessibility_tree_can_be_built_without_native_adapter(cx: &mut TestAppContext) {
7222 let tree = draw_accessibility_fixture(cx, false);
7223 let tree: serde_json::Value = serde_json::from_str(&tree).unwrap();
7224 let focus = tree["gpui_focus"].as_str().expect("focused node");
7225 #[cfg(debug_assertions)]
7226 assert!(
7227 tree["nodes"][focus]["element_id"]
7228 .as_str()
7229 .unwrap()
7230 .contains("input-owner")
7231 );
7232 assert_eq!(tree["nodes"].as_object().unwrap().len(), 3);
7233 }
7234
7235 #[gpui::test]
7236 #[cfg(debug_assertions)]
7237 #[should_panic(expected = "second node")]
7238 fn nested_duplicate_focus_is_detected_in_component_tests(cx: &mut TestAppContext) {
7239 draw_accessibility_fixture(cx, true);
7240 }
7241
7242 struct EmptyView;
7243
7244 impl Render for EmptyView {
7245 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7246 div()
7247 }
7248 }
7249
7250 crate::actions!(pending_timeout_regression, [TimeoutAction]);
7251
7252 struct PendingView {
7253 focus: FocusHandle,
7254 dispatched: Rc<Cell<usize>>,
7255 }
7256
7257 impl Render for PendingView {
7258 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7259 let dispatched = self.dispatched.clone();
7260 div()
7261 .track_focus(&self.focus)
7262 .on_action(move |_: &TimeoutAction, _, _| {
7263 dispatched.set(dispatched.get() + 1);
7264 })
7265 }
7266 }
7267
7268 #[gpui::test]
7269 fn stale_pending_timeout_does_not_consume_replacement(cx: &mut TestAppContext) {
7270 use crate::{KeyBinding, KeyDownEvent, Keystroke, PlatformInput};
7271 use std::time::Duration;
7272 let dispatched = Rc::new(Cell::new(0));
7273 cx.update(|cx| {
7274 cx.bind_keys([
7275 KeyBinding::new("ctrl-k", TimeoutAction, None),
7276 KeyBinding::new("ctrl-k ctrl-c", TimeoutAction, None),
7277 ])
7278 });
7279 let window = cx.add_window(|window, cx| {
7280 let focus = cx.focus_handle();
7281 window.focus(&focus, cx);
7282 PendingView {
7283 focus,
7284 dispatched: dispatched.clone(),
7285 }
7286 });
7287 let send_prefix = |window: &mut Window, cx: &mut crate::App| {
7288 window.dispatch_event(
7289 PlatformInput::KeyDown(KeyDownEvent {
7290 keystroke: Keystroke::parse("ctrl-k").unwrap(),
7291 is_held: false,
7292 prefer_character_input: false,
7293 }),
7294 cx,
7295 );
7296 };
7297 let _stale = cx
7298 .update_window(window.into(), |_, window, cx| {
7299 send_prefix(window, cx);
7300 window.pending_input.as_mut().unwrap().timer.take().unwrap()
7303 })
7304 .unwrap();
7305 cx.executor().advance_clock(Duration::from_millis(500));
7306 cx.update_window(window.into(), |_, window, cx| send_prefix(window, cx))
7307 .unwrap();
7308 assert_eq!(dispatched.get(), 1);
7309 cx.executor().advance_clock(Duration::from_millis(500));
7310 cx.run_until_parked();
7311 window
7312 .update(cx, |_, window, _| assert!(window.has_pending_keystrokes()))
7313 .unwrap();
7314 assert_eq!(dispatched.get(), 1);
7315 cx.executor().advance_clock(Duration::from_millis(500));
7316 cx.run_until_parked();
7317 assert_eq!(dispatched.get(), 2);
7318 }
7319
7320 #[gpui::test]
7321 fn resumed_timeout_cannot_update_replacement_window(cx: &mut TestAppContext) {
7322 use futures::channel::oneshot;
7323 use std::time::Duration;
7324
7325 let old = cx.add_window(|_, _| EmptyView);
7326 let (resume, resumed) = oneshot::channel();
7327 let timer_ready = Rc::new(Cell::new(false));
7328 let completed = Rc::new(Cell::new(false));
7329 let _task = old
7330 .update(cx, |_, window, app| {
7331 let timer_ready = timer_ready.clone();
7332 let completed = completed.clone();
7333 window.spawn(app, async move |cx| {
7334 cx.background_executor.timer(Duration::from_secs(1)).await;
7335 timer_ready.set(true);
7336 resumed.await.unwrap();
7339 assert_eq!(
7340 cx.update_if_present(|_, _| panic!("stale work ran"))
7341 .unwrap(),
7342 None
7343 );
7344 completed.set(true);
7345 })
7346 })
7347 .unwrap();
7348 cx.executor().advance_clock(Duration::from_secs(1));
7349 cx.run_until_parked();
7350 assert!(timer_ready.get());
7351 old.update(cx, |_, window, _| window.remove_window())
7352 .unwrap();
7353 let replacement = cx.add_window(|_, _| EmptyView);
7354 assert_ne!(old.window_id(), replacement.window_id());
7355 resume.send(()).unwrap();
7356 cx.run_until_parked();
7357 assert!(completed.get());
7358 replacement
7359 .update(cx, |_, window, _| assert!(!window.has_pending_keystrokes()))
7360 .unwrap();
7361 }
7362
7363 #[gpui::test]
7364 fn optional_window_update_preserves_unrelated_errors(cx: &mut TestAppContext) {
7365 let window = cx.add_window(|_, _| EmptyView);
7366 let mut context = window
7367 .update(cx, |_, window, app| window.to_async(app))
7368 .unwrap();
7369 assert_eq!(context.update_if_present(|_, _| 42).unwrap(), Some(42));
7370 assert!(
7372 context
7373 .update_if_present(|_, _| Err::<(), _>(anyhow::anyhow!("callback failure")))
7374 .unwrap()
7375 .unwrap()
7376 .is_err()
7377 );
7378 cx.update(|_| {
7379 assert!(context.update_if_present(|_, _| ()).is_err());
7380 });
7381 window
7382 .update(cx, |_, window, _| window.remove_window())
7383 .unwrap();
7384 assert_eq!(context.update_if_present(|_, _| ()).unwrap(), None);
7385 }
7386
7387 struct OpensWindowOnPaint {
7388 opened: Rc<Cell<bool>>,
7389 }
7390
7391 impl Render for OpensWindowOnPaint {
7392 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7393 let opened = self.opened.clone();
7394 div()
7395 .size_full()
7396 .child(canvas(
7397 |_, _, _| {},
7398 move |_, _, _window, cx| {
7399 if !opened.replace(true) {
7400 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
7401 .unwrap();
7402 }
7403 },
7404 ))
7405 .child(div().child("after"))
7409 }
7410 }
7411
7412 #[test]
7418 fn test_window_opened_during_draw_defers_arena_clear() {
7419 let mut cx = TestAppContext::single();
7420
7421 let opened = Rc::new(Cell::new(false));
7422 let window = cx.add_window({
7424 let opened = opened.clone();
7425 move |_, _| OpensWindowOnPaint { opened }
7426 });
7427
7428 assert!(opened.get());
7429 assert_eq!(cx.windows().len(), 2);
7430
7431 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
7434 .unwrap();
7435 }
7436
7437 #[gpui::test]
7438 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
7439 let window = cx.add_window(|_, _| EmptyView);
7440 let observed_appearance = Rc::new(Cell::new(None));
7441 let _subscription = window
7442 .update(cx, {
7443 let observed_appearance = observed_appearance.clone();
7444 move |_, window, _| {
7445 window.observe_window_appearance(move |window, _| {
7446 observed_appearance.set(Some(window.appearance()));
7447 })
7448 }
7449 })
7450 .unwrap();
7451 let test_window = cx.test_window(window.into());
7452
7453 cx.update(|_| {
7454 test_window.simulate_appearance_change(WindowAppearance::Dark);
7455 assert_eq!(observed_appearance.get(), None);
7456 });
7457 cx.run_until_parked();
7458
7459 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
7460 }
7461
7462 struct RootView {
7463 explicit_size: bool,
7464 child_bounds: Rc<Cell<Bounds<Pixels>>>,
7465 }
7466
7467 impl Render for RootView {
7468 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7469 let child_bounds = self.child_bounds.clone();
7470 let root = div().flex().flex_col().child(
7471 canvas(
7472 move |bounds, _, _| child_bounds.set(bounds),
7473 |_, _, _, _| {},
7474 )
7475 .size_full(),
7476 );
7477 if self.explicit_size {
7478 root.w(px(300.)).h(px(200.))
7479 } else {
7480 root
7481 }
7482 }
7483 }
7484
7485 #[test]
7486 fn auto_sized_window_root_fills_the_window() {
7487 let mut cx = TestAppContext::single();
7488 let child_bounds = Rc::new(Cell::new(Bounds::default()));
7489 let window = cx.add_window({
7490 let child_bounds = child_bounds.clone();
7491 move |_, _| RootView {
7492 explicit_size: false,
7493 child_bounds,
7494 }
7495 });
7496
7497 let viewport_size = cx
7498 .update_window(window.into(), |_, window, cx| {
7499 window.draw(cx).clear(cx);
7500 window.viewport_size()
7501 })
7502 .unwrap();
7503
7504 assert_eq!(child_bounds.get().size, viewport_size);
7505 }
7506
7507 #[test]
7508 fn explicitly_sized_window_root_keeps_its_size() {
7509 let mut cx = TestAppContext::single();
7510 let child_bounds = Rc::new(Cell::new(Bounds::default()));
7511 let window = cx.add_window({
7512 let child_bounds = child_bounds.clone();
7513 move |_, _| RootView {
7514 explicit_size: true,
7515 child_bounds,
7516 }
7517 });
7518
7519 cx.update_window(window.into(), |_, window, cx| {
7520 window.draw(cx).clear(cx);
7521 })
7522 .unwrap();
7523
7524 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
7525 }
7526
7527 struct FileDragView {
7528 path: PathBuf,
7529 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7530 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7531 }
7532
7533 impl Render for FileDragView {
7534 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7535 div()
7536 .id("file-drag")
7537 .size_full()
7538 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
7539 .external_drag_payload(|path: &PathBuf, _, _| {
7540 Some(ExternalDragPayload::Files(FileDragPaths::new([(
7541 path.clone(),
7542 true,
7543 )])))
7544 })
7545 .on_drag_move({
7546 let observed_drag_moves = self.observed_drag_moves.clone();
7547 move |event: &DragMoveEvent<PathBuf>, _, _| {
7548 observed_drag_moves.borrow_mut().push(event.event.position);
7549 }
7550 })
7551 .on_drop({
7552 let observed_drops = self.observed_drops.clone();
7553 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
7554 })
7555 }
7556 }
7557
7558 #[gpui::test]
7559 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
7560 struct Drag {
7561 window: AnyWindowHandle,
7562 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7563 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7564 }
7565
7566 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
7567 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
7568 let observed_drops = Rc::new(RefCell::new(Vec::new()));
7569 let window: AnyWindowHandle = cx
7570 .add_window({
7571 let observed_drag_moves = observed_drag_moves.clone();
7572 let observed_drops = observed_drops.clone();
7573 move |_, _| FileDragView {
7574 path,
7575 observed_drag_moves,
7576 observed_drops,
7577 }
7578 })
7579 .into();
7580 cx.test_window(window)
7581 .set_start_external_drag_result(platform_result);
7582
7583 let update_result = cx.update_window(window, |_, window, cx| {
7584 window.draw(cx).clear(cx);
7585 window.dispatch_event(
7586 MouseDownEvent {
7587 position: point(px(10.), px(10.)),
7588 button: MouseButton::Left,
7589 modifiers: Default::default(),
7590 click_count: 1,
7591 first_mouse: false,
7592 }
7593 .to_platform_input(),
7594 cx,
7595 );
7596 window.dispatch_event(
7597 MouseMoveEvent {
7598 position: point(px(20.), px(20.)),
7599 pressed_button: Some(MouseButton::Left),
7600 modifiers: Default::default(),
7601 }
7602 .to_platform_input(),
7603 cx,
7604 );
7605 assert!(cx.active_drag.is_some());
7606 });
7607 assert!(
7608 update_result.is_ok(),
7609 "failed to start drag: {update_result:?}"
7610 );
7611
7612 assert!(cx.test_window(window).external_drag_files().is_empty());
7613 Drag {
7614 window,
7615 observed_drag_moves,
7616 observed_drops,
7617 }
7618 }
7619
7620 let successful_path = PathBuf::from("/tmp/successful-drag");
7621 let successful = start_drag(cx, successful_path.clone(), true);
7622 let outside_position = point(px(-1.), px(20.));
7623 let update_result = cx.update_window(successful.window, |_, window, cx| {
7624 window.dispatch_event(
7625 MouseMoveEvent {
7626 position: outside_position,
7627 pressed_button: Some(MouseButton::Left),
7628 modifiers: Default::default(),
7629 }
7630 .to_platform_input(),
7631 cx,
7632 );
7633 assert!(cx.active_drag.is_none());
7634 });
7635 assert!(
7636 update_result.is_ok(),
7637 "failed to promote drag: {update_result:?}"
7638 );
7639 assert_eq!(
7640 cx.test_window(successful.window).external_drag_files(),
7641 [(successful_path.clone(), true)]
7642 );
7643 assert_eq!(
7646 successful.observed_drag_moves.borrow().last(),
7647 Some(&outside_position)
7648 );
7649
7650 let destination: AnyWindowHandle = cx.add_window(|_, _| EmptyView).into();
7651 let reentry_position = point(px(30.), px(30.));
7652 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
7653 let update_result = cx.update_window(destination, |_, window, cx| {
7654 window.dispatch_event(
7655 FileDropEvent::Entered {
7656 position: reentry_position,
7657 paths: external_paths(),
7658 }
7659 .to_platform_input(),
7660 cx,
7661 );
7662 assert!(
7663 cx.active_drag
7664 .as_ref()
7665 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7666 );
7667 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7668 assert!(cx.active_drag.is_none());
7669 });
7670 assert!(
7671 update_result.is_ok(),
7672 "failed to handle drag in destination window: {update_result:?}"
7673 );
7674
7675 let update_result = cx.update_window(successful.window, |_, window, cx| {
7676 window.dispatch_event(
7677 FileDropEvent::Entered {
7678 position: reentry_position,
7679 paths: external_paths(),
7680 }
7681 .to_platform_input(),
7682 cx,
7683 );
7684 assert!(
7685 cx.active_drag
7686 .as_ref()
7687 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7688 );
7689 assert_eq!(
7690 successful.observed_drag_moves.borrow().last(),
7691 Some(&reentry_position)
7692 );
7693
7694 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7695 assert!(cx.active_drag.is_none());
7696
7697 window.dispatch_event(
7698 FileDropEvent::Entered {
7699 position: reentry_position,
7700 paths: external_paths(),
7701 }
7702 .to_platform_input(),
7703 cx,
7704 );
7705 assert!(
7706 cx.active_drag
7707 .as_ref()
7708 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7709 );
7710
7711 window.dispatch_event(
7712 FileDropEvent::Submit {
7713 position: reentry_position,
7714 }
7715 .to_platform_input(),
7716 cx,
7717 );
7718 assert_eq!(
7719 successful.observed_drops.borrow().as_slice(),
7720 std::slice::from_ref(&successful_path)
7721 );
7722 assert!(cx.active_drag.is_none());
7723
7724 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7725 assert!(cx.active_drag.is_none());
7726 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
7727 assert!(cx.active_drag.is_none());
7728
7729 window.dispatch_event(
7730 FileDropEvent::Entered {
7731 position: reentry_position,
7732 paths: external_paths(),
7733 }
7734 .to_platform_input(),
7735 cx,
7736 );
7737 assert!(
7738 cx.active_drag
7739 .as_ref()
7740 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7741 );
7742 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7743 });
7744 assert!(
7745 update_result.is_ok(),
7746 "failed to restore drag in source window: {update_result:?}"
7747 );
7748
7749 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
7750 let cancelled = start_drag(cx, cancelled_path.clone(), true);
7751 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
7752 window.dispatch_event(
7753 MouseMoveEvent {
7754 position: outside_position,
7755 pressed_button: Some(MouseButton::Left),
7756 modifiers: Default::default(),
7757 }
7758 .to_platform_input(),
7759 cx,
7760 );
7761 assert!(cx.active_drag.is_none());
7762
7763 window.dispatch_event(
7764 FileDropEvent::Entered {
7765 position: reentry_position,
7766 paths: ExternalPaths([cancelled_path].into_iter().collect()),
7767 }
7768 .to_platform_input(),
7769 cx,
7770 );
7771 assert!(
7772 cx.active_drag
7773 .as_ref()
7774 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7775 );
7776 assert!(cx.stop_active_drag(window));
7777 assert!(cx.active_drag.is_none());
7778 });
7779 assert!(
7780 update_result.is_ok(),
7781 "failed to cancel restored drag: {update_result:?}"
7782 );
7783 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
7784
7785 let removed_path = PathBuf::from("/tmp/removed-window-drag");
7786 let removed = start_drag(cx, removed_path, true);
7787 let removed_window_id = removed.window.window_id();
7788 let update_result = cx.update_window(removed.window, |_, window, cx| {
7789 window.dispatch_event(
7790 MouseMoveEvent {
7791 position: outside_position,
7792 pressed_button: Some(MouseButton::Left),
7793 modifiers: Default::default(),
7794 }
7795 .to_platform_input(),
7796 cx,
7797 );
7798 assert!(cx.active_drag.is_none());
7799 window.remove_window();
7800 });
7801 assert!(
7802 update_result.is_ok(),
7803 "failed to remove drag source window: {update_result:?}"
7804 );
7805 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
7806
7807 let failed_path = PathBuf::from("/tmp/failed-drag");
7808 let failed = start_drag(cx, failed_path.clone(), false);
7809 let update_result = cx.update_window(failed.window, |_, window, cx| {
7810 for x_position in [-1., -2.] {
7811 window.dispatch_event(
7812 MouseMoveEvent {
7813 position: point(px(x_position), px(20.)),
7814 pressed_button: Some(MouseButton::Left),
7815 modifiers: Default::default(),
7816 }
7817 .to_platform_input(),
7818 cx,
7819 );
7820 }
7821 assert!(cx.active_drag.is_some());
7822 });
7823 assert!(
7824 update_result.is_ok(),
7825 "failed to retain drag after platform failure: {update_result:?}"
7826 );
7827 assert_eq!(
7828 cx.test_window(failed.window).external_drag_files(),
7829 [(failed_path, true)]
7830 );
7831 }
7832
7833 struct FocusForwarder {
7834 a: FocusHandle,
7835 b: FocusHandle,
7836 }
7837
7838 impl Render for FocusForwarder {
7839 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7840 div()
7841 .size_full()
7842 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
7843 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
7844 }
7845 }
7846
7847 #[gpui::test]
7851 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
7852 let b_focus_count = Rc::new(Cell::new(0));
7853 let window = cx.add_window({
7854 let b_focus_count = b_focus_count.clone();
7855 move |window, cx| {
7856 let a = cx.focus_handle();
7857 let b = cx.focus_handle();
7858 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
7859 let b = this.b.clone();
7860 window.focus(&b, cx);
7861 })
7862 .detach();
7863 cx.on_focus(&b, window, move |_, _, _| {
7864 b_focus_count.set(b_focus_count.get() + 1);
7865 })
7866 .detach();
7867 FocusForwarder { a, b }
7868 }
7869 });
7870
7871 window
7872 .update(cx, |_, window, _| window.activate_window())
7873 .unwrap();
7874 cx.executor().run_until_parked();
7875
7876 window
7877 .update(cx, |this, window, cx| {
7878 let a = this.a.clone();
7879 window.focus(&a, cx);
7880 })
7881 .unwrap();
7882 cx.executor().run_until_parked();
7883
7884 window
7885 .update(cx, |this, window, _| {
7886 assert!(this.b.is_focused(window));
7887 })
7888 .unwrap();
7889 assert_eq!(b_focus_count.get(), 1);
7890 }
7891
7892 #[gpui::test]
7893 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
7894 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
7895
7896 let window = cx.add_window(|_, _| EmptyView);
7897 window
7898 .update(cx, |_, window, _| {
7899 assert!(matches!(
7900 window.window_handle(),
7901 Err(HandleError::NotSupported)
7902 ));
7903 assert!(matches!(
7904 window.display_handle(),
7905 Err(HandleError::NotSupported)
7906 ));
7907 })
7908 .unwrap();
7909 }
7910}