1#[cfg(feature = "profiler")]
2use crate::DebugFrameOverlayMode;
3#[cfg(any(feature = "inspector", debug_assertions))]
4use crate::Inspector;
5#[cfg(feature = "profiler")]
6use crate::profiler;
7use crate::{
8 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
9 AsyncWindowContext, AtlasTile, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow,
10 Capslock, ContentMask, Context, Corners, CursorHideMode, CursorStyle, DEFAULT_WINDOW_SIZE,
11 Decorations, DevicePixels, DispatchActionListener, DispatchEventResult, DispatchNodeId,
12 DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter, FileDropEvent, FontId,
13 Global, GlobalElementId, GlyphId, GpuSpecs, Hsla, InputHandler, IsZero, KeyBinding, KeyContext,
14 KeyDownEvent, KeyEvent, Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, MeasureContext,
15 MeasureHandles, Modifiers, ModifiersChangedEvent, MonochromeSprite, MouseButton, MouseEvent,
16 MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
17 PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, Priority, PromptButton,
18 PromptLevel, Quad, Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams,
19 Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y,
20 ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubpixelSprite,
21 SubscriberSet, Subscription, SystemWindowTab, SystemWindowTabController, TabStopMap, Task,
22 TextInputConfiguration, TextInputStateChange, TextRenderingMode, TextStyle,
23 TextStyleRefinement, ThermalState, TransformationMatrix, Underline, UnderlineStyle,
24 WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowControls,
25 WindowDecorations, WindowId, WindowMetrics, WindowOptions, WindowParams, WindowTextSystem,
26 WindowVisibility, new_platform_input_handler, point, prelude::*, px, rems, size,
27 transparent_black,
28};
29
30use crate::TouchEvent;
31use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
32use anyhow::{Context as _, Result, anyhow};
33use arc_swap::ArcSwap;
34use collections::{FxHashMap, FxHashSet};
35use derive_more::{Deref, DerefMut};
36use futures::channel::oneshot;
37use gpui_engine::FrameSession;
38use gpui_util::post_inc;
39use gpui_util::{ResultExt, measure};
40use itertools::FoldWhile::{Continue, Done};
41use itertools::Itertools;
42use parking_lot::RwLock;
43use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
44use refineable::Refineable;
45use scheduler::Instant;
46use slotmap::SlotMap;
47use smallvec::SmallVec;
48use std::{
49 any::{Any, TypeId},
50 borrow::Cow,
51 cell::{Cell, RefCell},
52 cmp,
53 fmt::{Debug, Display},
54 hash::{Hash, Hasher},
55 marker::PhantomData,
56 mem,
57 ops::{DerefMut, Range},
58 rc::Rc,
59 sync::{
60 Arc, Weak,
61 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
62 },
63 time::Duration,
64};
65use uuid::Uuid;
66
67pub(crate) mod a11y;
68mod frame_pipeline;
69#[cfg(target_os = "macos")]
70mod mac;
71mod prompts;
72
73pub use a11y::A11ySubtreeBuilder;
74pub use frame_pipeline::{FramePipeline, StandardImmediatePipeline};
75#[cfg(target_os = "macos")]
76pub use mac::*;
77
78use self::a11y::A11y;
79#[cfg(not(target_family = "wasm"))]
80use self::a11y::ROOT_NODE_ID;
81use crate::engine_layout::to_engine_layout_style;
82use crate::util::{
83 atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
84 round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
85};
86pub use prompts::*;
87
88pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
91 width: Pixels(900.),
92 height: Pixels(750.),
93};
94
95struct WindowMeasureContext<'a> {
102 core: &'a mut WindowHostCore,
103 frame_state: &'a mut WindowFrameState,
104 cx: &'a mut App,
105}
106
107impl MeasureContext for WindowMeasureContext<'_> {
108 fn handles(&mut self) -> MeasureHandles<'_> {
109 MeasureHandles {
110 window: (self.core, self.frame_state),
111 app: self.cx,
112 }
113 }
114}
115
116#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
118pub enum DispatchPhase {
119 #[default]
124 Bubble,
125 Capture,
131}
132
133impl DispatchPhase {
134 #[inline]
136 pub fn bubble(self) -> bool {
137 self == DispatchPhase::Bubble
138 }
139
140 #[inline]
142 pub fn capture(self) -> bool {
143 self == DispatchPhase::Capture
144 }
145}
146
147struct WindowInvalidatorInner {
148 #[cfg(feature = "profiler")]
149 pub window_id: WindowId,
150 pub dirty: bool,
151 pub draw_phase: DrawPhase,
152 pub dirty_views: FxHashSet<EntityId>,
153 pub update_count: usize,
154 #[cfg(feature = "profiler")]
155 pub frame_dirty: FrameDirtyAccumulator,
156 pub platform_waker: Option<Rc<dyn Fn()>>,
157}
158
159#[cfg(feature = "profiler")]
165#[derive(Default)]
166struct FrameDirtyAccumulator {
167 dirty_at: Option<Instant>,
168 invalidations: u64,
169}
170
171#[derive(Clone)]
172pub(crate) struct WindowInvalidator {
173 inner: Rc<RefCell<WindowInvalidatorInner>>,
174}
175
176impl WindowInvalidator {
177 pub fn new(#[allow(unused_variables)] window_id: WindowId) -> Self {
178 WindowInvalidator {
179 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
180 #[cfg(feature = "profiler")]
181 window_id,
182 dirty: true,
183 draw_phase: DrawPhase::None,
184 dirty_views: FxHashSet::default(),
185 update_count: 0,
186 #[cfg(feature = "profiler")]
187 frame_dirty: FrameDirtyAccumulator::default(),
188 platform_waker: None,
189 })),
190 }
191 }
192
193 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
194 let mut inner = self.inner.borrow_mut();
195 inner.update_count += 1;
196 inner.dirty_views.insert(entity);
197 if inner.draw_phase == DrawPhase::None {
198 #[cfg(feature = "profiler")]
199 let dirty_at = Self::record_frame_dirty(&mut inner);
200 let became_dirty = !inner.dirty;
201 inner.dirty = true;
202 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
203 #[cfg(feature = "profiler")]
204 let window_id = inner.window_id;
205 drop(inner);
206 #[cfg(feature = "profiler")]
207 if became_dirty {
208 profiler::journal::record_frame_pending(window_id, dirty_at);
209 }
210 cx.push_effect(Effect::Notify { emitter: entity });
211 if let Some(waker) = waker {
212 waker();
213 }
214 true
215 } else {
216 false
217 }
218 }
219
220 pub fn is_dirty(&self) -> bool {
221 self.inner.borrow().dirty
222 }
223
224 pub fn set_dirty(&self, dirty: bool) {
225 let mut inner = self.inner.borrow_mut();
226 let became_dirty = dirty && !inner.dirty;
227 inner.dirty = dirty;
228 if dirty {
229 inner.update_count += 1;
230 }
231 #[cfg(feature = "profiler")]
232 let dirty_at = dirty.then(|| Self::record_frame_dirty(&mut inner));
233 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
234 #[cfg(feature = "profiler")]
235 let window_id = inner.window_id;
236 drop(inner);
237 #[cfg(feature = "profiler")]
238 if became_dirty && let Some(dirty_at) = dirty_at {
239 profiler::journal::record_frame_pending(window_id, dirty_at);
240 }
241 if let Some(waker) = waker {
242 waker();
243 }
244 }
245
246 pub fn set_platform_waker(&self, waker: Option<Rc<dyn Fn()>>) {
247 let mut inner = self.inner.borrow_mut();
248 inner.platform_waker = waker;
249 let waker = inner.dirty.then(|| inner.platform_waker.clone()).flatten();
250 drop(inner);
251 if let Some(waker) = waker {
252 waker();
253 }
254 }
255
256 pub fn wake_platform(&self) {
260 let waker = self.inner.borrow().platform_waker.clone();
261 if let Some(waker) = waker {
262 waker();
263 }
264 }
265
266 pub fn set_phase(&self, phase: DrawPhase) {
267 self.inner.borrow_mut().draw_phase = phase
268 }
269
270 pub fn update_count(&self) -> usize {
271 self.inner.borrow().update_count
272 }
273
274 #[cfg(feature = "profiler")]
275 fn record_frame_dirty(inner: &mut WindowInvalidatorInner) -> Instant {
276 let dirty_at = *inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
277 inner.frame_dirty.invalidations += 1;
278 dirty_at
279 }
280
281 #[cfg(feature = "profiler")]
282 fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
283 mem::take(&mut self.inner.borrow_mut().frame_dirty)
284 }
285
286 pub fn take_views(&self) -> FxHashSet<EntityId> {
287 mem::take(&mut self.inner.borrow_mut().dirty_views)
288 }
289
290 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
291 self.inner.borrow_mut().dirty_views = views;
292 }
293
294 pub fn not_drawing(&self) -> bool {
295 self.inner.borrow().draw_phase == DrawPhase::None
296 }
297
298 #[track_caller]
299 pub fn debug_assert_paint(&self) {
300 debug_assert!(
301 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
302 "this method can only be called during paint"
303 );
304 }
305
306 #[track_caller]
307 pub fn debug_assert_prepaint(&self) {
308 debug_assert!(
309 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
310 "this method can only be called during request_layout, or prepaint"
311 );
312 }
313
314 #[track_caller]
315 pub fn debug_assert_paint_or_prepaint(&self) {
316 debug_assert!(
317 matches!(
318 self.inner.borrow().draw_phase,
319 DrawPhase::Paint | DrawPhase::Prepaint
320 ),
321 "this method can only be called during request_layout, prepaint, or paint"
322 );
323 }
324}
325
326type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
327
328pub(crate) type AnyWindowFocusListener =
329 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
330
331pub(crate) struct WindowFocusEvent {
332 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
333 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
334}
335
336impl WindowFocusEvent {
337 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
338 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
339 }
340
341 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
342 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
343 }
344}
345
346pub struct FocusOutEvent {
348 pub blurred: WeakFocusHandle,
350}
351
352slotmap::new_key_type! {
353 pub struct FocusId;
355}
356
357thread_local! {
358 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
361
362 static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
366}
367
368fn draw_in_progress() -> bool {
379 CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some())
380}
381
382pub(crate) fn with_element_arena<R>(f: impl FnOnce(&mut Arena) -> R) -> R {
385 CURRENT_ELEMENT_ARENA.with(|current| {
386 if let Some(arena_ptr) = current.get() {
387 let arena_cell = unsafe { &*arena_ptr };
390 f(&mut arena_cell.borrow_mut())
391 } else {
392 ELEMENT_ARENA.with_borrow_mut(f)
393 }
394 })
395}
396
397pub(crate) struct ElementArenaScope {
412 entered: *const RefCell<Arena>,
415 previous: Option<*const RefCell<Arena>>,
416 exited: bool,
417}
418
419impl ElementArenaScope {
420 pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
422 arena.borrow_mut().begin_scope();
423 let previous = CURRENT_ELEMENT_ARENA.with(|current| {
424 let prev = current.get();
425 current.set(Some(arena as *const RefCell<Arena>));
426 prev
427 });
428 Self {
429 entered: arena as *const RefCell<Arena>,
430 previous,
431 exited: false,
432 }
433 }
434
435 pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
444 assert!(
445 std::ptr::eq(self.entered, arena),
446 "ElementArenaScope::exit called with a different arena than was entered"
447 );
448 self.exited = true;
449 ArenaClearNeeded::new(arena)
454 }
455}
456
457impl Drop for ElementArenaScope {
458 fn drop(&mut self) {
459 CURRENT_ELEMENT_ARENA.with(|current| {
466 current.set(self.previous);
467 });
468 unsafe { &*self.entered }.borrow_mut().end_scope();
472 if !self.exited && !std::thread::panicking() {
473 debug_assert!(false, "ElementArenaScope dropped without calling exit()");
474 log::error!(
475 "ElementArenaScope dropped without calling exit(); \
476 the arena clear for this draw was never requested"
477 );
478 }
479 }
480}
481
482#[must_use]
484pub struct ArenaClearNeeded {
485 arena: *const RefCell<Arena>,
488}
489
490impl ArenaClearNeeded {
491 fn new(arena: &RefCell<Arena>) -> Self {
494 Self {
495 arena: arena as *const RefCell<Arena>,
496 }
497 }
498
499 pub fn clear(self, cx: &mut App) {
508 assert!(
509 std::ptr::eq(self.arena, &cx.element_arena),
510 "ArenaClearNeeded::clear called with a different App than the draw ran against"
511 );
512 cx.element_arena.borrow_mut().clear();
513 }
514}
515
516pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;
517pub(crate) struct FocusRef {
518 pub(crate) ref_count: AtomicUsize,
519 pub(crate) tab_index: isize,
520 pub(crate) tab_stop: bool,
521}
522
523impl FocusId {
524 pub fn is_focused(&self, window: &Window) -> bool {
526 window.core.focus == Some(*self)
527 }
528
529 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
532 window
533 .focused(cx)
534 .is_some_and(|focused| self.contains(focused.id, window))
535 }
536
537 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
540 let focused = window.focused(cx);
541 focused.is_some_and(|focused| focused.id.contains(*self, window))
542 }
543
544 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
546 window
547 .frame_state
548 .rendered_frame
549 .dispatch_tree
550 .focus_contains(*self, other)
551 }
552}
553
554pub struct FocusHandle {
556 pub(crate) id: FocusId,
557 handles: Arc<FocusMap>,
558 pub tab_index: isize,
560 pub tab_stop: bool,
562}
563
564impl std::fmt::Debug for FocusHandle {
565 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
566 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
567 }
568}
569
570impl FocusHandle {
571 pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
572 let id = handles.write().insert(FocusRef {
573 ref_count: AtomicUsize::new(1),
574 tab_index: 0,
575 tab_stop: false,
576 });
577
578 Self {
579 id,
580 tab_index: 0,
581 tab_stop: false,
582 handles: handles.clone(),
583 }
584 }
585
586 pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
587 let lock = handles.read();
588 let focus = lock.get(id)?;
589 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
590 return None;
591 }
592 Some(Self {
593 id,
594 tab_index: focus.tab_index,
595 tab_stop: focus.tab_stop,
596 handles: handles.clone(),
597 })
598 }
599
600 pub fn tab_index(mut self, index: isize) -> Self {
602 self.tab_index = index;
603 if let Some(focus) = self.handles.write().get_mut(self.id) {
604 focus.tab_index = index;
605 }
606 self
607 }
608
609 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
613 self.tab_stop = tab_stop;
614 if let Some(focus) = self.handles.write().get_mut(self.id) {
615 focus.tab_stop = tab_stop;
616 }
617 self
618 }
619
620 pub fn downgrade(&self) -> WeakFocusHandle {
622 WeakFocusHandle {
623 id: self.id,
624 handles: Arc::downgrade(&self.handles),
625 }
626 }
627
628 pub fn focus(&self, window: &mut Window, cx: &mut App) {
630 window.focus(self, cx)
631 }
632
633 pub fn is_focused(&self, window: &Window) -> bool {
635 self.id.is_focused(window)
636 }
637
638 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
641 self.id.contains_focused(window, cx)
642 }
643
644 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
647 self.id.within_focused(window, cx)
648 }
649
650 pub fn contains(&self, other: &Self, window: &Window) -> bool {
652 self.id.contains(other.id, window)
653 }
654
655 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
657 if let Some(node_id) = window
658 .frame_state
659 .rendered_frame
660 .dispatch_tree
661 .focusable_node_id(self.id)
662 {
663 window.dispatch_action_on_node(node_id, action, cx)
664 }
665 }
666}
667
668impl Clone for FocusHandle {
669 fn clone(&self) -> Self {
670 Self::for_id(self.id, &self.handles).unwrap()
671 }
672}
673
674impl PartialEq for FocusHandle {
675 fn eq(&self, other: &Self) -> bool {
676 self.id == other.id
677 }
678}
679
680impl Eq for FocusHandle {}
681
682impl Drop for FocusHandle {
683 fn drop(&mut self) {
684 self.handles
685 .read()
686 .get(self.id)
687 .unwrap()
688 .ref_count
689 .fetch_sub(1, SeqCst);
690 }
691}
692
693#[derive(Clone, Debug)]
695pub struct WeakFocusHandle {
696 pub(crate) id: FocusId,
697 pub(crate) handles: Weak<FocusMap>,
698}
699
700impl WeakFocusHandle {
701 pub fn upgrade(&self) -> Option<FocusHandle> {
703 let handles = self.handles.upgrade()?;
704 FocusHandle::for_id(self.id, &handles)
705 }
706}
707
708impl PartialEq for WeakFocusHandle {
709 fn eq(&self, other: &WeakFocusHandle) -> bool {
710 self.id == other.id
711 }
712}
713
714impl Eq for WeakFocusHandle {}
715
716impl PartialEq<FocusHandle> for WeakFocusHandle {
717 fn eq(&self, other: &FocusHandle) -> bool {
718 self.id == other.id
719 }
720}
721
722impl PartialEq<WeakFocusHandle> for FocusHandle {
723 fn eq(&self, other: &WeakFocusHandle) -> bool {
724 self.id == other.id
725 }
726}
727
728pub trait Focusable: 'static {
731 fn focus_handle(&self, cx: &App) -> FocusHandle;
733}
734
735impl<V: Focusable> Focusable for Entity<V> {
736 fn focus_handle(&self, cx: &App) -> FocusHandle {
737 self.read(cx).focus_handle(cx)
738 }
739}
740
741pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
744
745impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
746
747pub struct DismissEvent;
749
750type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
751
752pub(crate) type AnyMouseListener =
753 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
754
755#[derive(Clone)]
756pub(crate) struct CursorStyleRequest {
757 pub(crate) hitbox_id: Option<HitboxId>,
758 pub(crate) style: CursorStyle,
759}
760
761#[derive(Default, Eq, PartialEq)]
762pub(crate) struct HitTest {
763 pub(crate) ids: SmallVec<[HitboxId; 8]>,
764 pub(crate) hover_hitbox_count: usize,
765}
766
767#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
769pub struct HitboxId(u64);
770
771#[cfg(feature = "test-support")]
772impl HitboxId {
773 pub const fn placeholder() -> Self {
778 Self(0)
779 }
780}
781
782impl HitboxId {
783 pub fn is_hovered(self, window: &Window) -> bool {
790 if window.core.captured_hitbox == Some(self) {
792 return true;
793 }
794 if window.last_input_was_keyboard() {
795 return false;
796 }
797 self.hit_test(window)
798 }
799
800 pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
805 if window.core.captured_hitbox == Some(self) {
807 return true;
808 }
809 self.hit_test(window)
810 }
811
812 fn hit_test(self, window: &Window) -> bool {
813 let hit_test = &window.core.mouse_hit_test;
814 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
815 if self == *id {
816 return true;
817 }
818 }
819 false
820 }
821
822 pub fn should_handle_scroll(self, window: &Window) -> bool {
827 window.core.mouse_hit_test.ids.contains(&self)
828 }
829
830 fn next(mut self) -> HitboxId {
831 HitboxId(self.0.wrapping_add(1))
832 }
833}
834
835#[derive(Clone, Debug, Deref)]
838pub struct Hitbox {
839 pub id: HitboxId,
841 #[deref]
843 pub bounds: Bounds<Pixels>,
844 pub content_mask: ContentMask<Pixels>,
846 pub behavior: HitboxBehavior,
848}
849
850impl Hitbox {
851 pub fn is_hovered(&self, window: &Window) -> bool {
868 self.id.is_hovered(window)
869 }
870
871 pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
874 let hit_test = window.frame_state.rendered_frame.hit_test(position);
875 hit_test
876 .ids
877 .iter()
878 .take(hit_test.hover_hitbox_count)
879 .any(|id| self.id == *id)
880 }
881
882 pub fn should_handle_scroll(&self, window: &Window) -> bool {
889 self.id.should_handle_scroll(window)
890 }
891}
892
893#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
895pub enum HitboxBehavior {
896 #[default]
898 Normal,
899
900 BlockMouse,
922
923 BlockMouseExceptScroll,
950}
951
952#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
954pub struct TooltipId(usize);
955
956impl TooltipId {
957 pub fn is_hovered(&self, window: &Window) -> bool {
959 window
960 .frame_state
961 .tooltip_bounds
962 .as_ref()
963 .is_some_and(|tooltip_bounds| {
964 tooltip_bounds.id == *self
965 && tooltip_bounds.bounds.contains(&window.mouse_position())
966 })
967 }
968}
969
970pub(crate) struct TooltipBounds {
971 id: TooltipId,
972 bounds: Bounds<Pixels>,
973}
974
975#[derive(Clone)]
976pub(crate) struct TooltipRequest {
977 id: TooltipId,
978 tooltip: AnyTooltip,
979}
980
981pub(crate) struct DeferredDraw {
982 current_view: EntityId,
983 priority: usize,
984 parent_node: DispatchNodeId,
985 element_id_stack: SmallVec<[ElementId; 32]>,
986 text_style_stack: Vec<TextStyleRefinement>,
987 content_mask: Option<ContentMask<Pixels>>,
988 rem_size: Pixels,
989 element: Option<AnyElement>,
990 absolute_offset: Point<Pixels>,
991 prepaint_range: Range<PrepaintStateIndex>,
992 paint_range: Range<PaintIndex>,
993}
994
995pub(crate) struct Frame {
996 pub(crate) focus: Option<FocusId>,
997 pub(crate) window_active: bool,
998 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
999 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
1000 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
1001 pub(crate) dispatch_tree: DispatchTree,
1002 pub(crate) scene: Scene,
1003 pub(crate) hitboxes: Vec<Hitbox>,
1004 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
1005 pub(crate) deferred_draws: Vec<DeferredDraw>,
1006 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
1007 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
1008 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
1009 #[cfg(any(test, feature = "test-support"))]
1010 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
1011 #[cfg(any(feature = "inspector", debug_assertions))]
1012 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
1013 #[cfg(any(feature = "inspector", debug_assertions))]
1014 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
1015 pub(crate) tab_stops: TabStopMap,
1016}
1017
1018#[derive(Clone, Default)]
1019pub(crate) struct PrepaintStateIndex {
1020 hitboxes_index: usize,
1021 tooltips_index: usize,
1022 deferred_draws_index: usize,
1023 dispatch_tree_index: usize,
1024 accessed_element_states_index: usize,
1025 line_layout_index: LineLayoutIndex,
1026}
1027
1028#[derive(Clone, Default)]
1029pub(crate) struct PaintIndex {
1030 scene_index: usize,
1031 mouse_listeners_index: usize,
1032 input_handlers_index: usize,
1033 cursor_styles_index: usize,
1034 accessed_element_states_index: usize,
1035 tab_handle_index: usize,
1036 line_layout_index: LineLayoutIndex,
1037}
1038
1039impl Frame {
1040 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
1041 Frame {
1042 focus: None,
1043 window_active: false,
1044 element_states: FxHashMap::default(),
1045 accessed_element_states: Vec::new(),
1046 mouse_listeners: Vec::new(),
1047 dispatch_tree,
1048 scene: Scene::default(),
1049 hitboxes: Vec::new(),
1050 window_control_hitboxes: Vec::new(),
1051 deferred_draws: Vec::new(),
1052 input_handlers: Vec::new(),
1053 tooltip_requests: Vec::new(),
1054 cursor_styles: Vec::new(),
1055
1056 #[cfg(any(test, feature = "test-support"))]
1057 debug_bounds: FxHashMap::default(),
1058
1059 #[cfg(any(feature = "inspector", debug_assertions))]
1060 next_inspector_instance_ids: FxHashMap::default(),
1061
1062 #[cfg(any(feature = "inspector", debug_assertions))]
1063 inspector_hitboxes: FxHashMap::default(),
1064 tab_stops: TabStopMap::default(),
1065 }
1066 }
1067
1068 pub(crate) fn clear(&mut self) {
1069 self.element_states.clear();
1070 self.accessed_element_states.clear();
1071 self.mouse_listeners.clear();
1072 self.dispatch_tree.clear();
1073 self.scene.clear();
1074 self.input_handlers.clear();
1075 self.tooltip_requests.clear();
1076 self.cursor_styles.clear();
1077 self.hitboxes.clear();
1078 self.window_control_hitboxes.clear();
1079 self.deferred_draws.clear();
1080 self.tab_stops.clear();
1081 self.focus = None;
1082
1083 #[cfg(any(test, feature = "test-support"))]
1084 {
1085 self.debug_bounds.clear();
1086 }
1087
1088 #[cfg(any(feature = "inspector", debug_assertions))]
1089 {
1090 self.next_inspector_instance_ids.clear();
1091 self.inspector_hitboxes.clear();
1092 }
1093 }
1094
1095 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1096 self.cursor_styles
1097 .iter()
1098 .rev()
1099 .fold_while(None, |style, request| match request.hitbox_id {
1100 None => Done(Some(request.style)),
1101 Some(hitbox_id) => Continue(style.or_else(|| {
1102 hitbox_id
1103 .is_hovered_ignoring_last_input(window)
1104 .then_some(request.style)
1105 })),
1106 })
1107 .into_inner()
1108 }
1109
1110 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
1111 let mut set_hover_hitbox_count = false;
1112 let mut hit_test = HitTest::default();
1113 for hitbox in self.hitboxes.iter().rev() {
1114 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
1115 if bounds.contains(&position) {
1116 hit_test.ids.push(hitbox.id);
1117 if !set_hover_hitbox_count
1118 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1119 {
1120 hit_test.hover_hitbox_count = hit_test.ids.len();
1121 set_hover_hitbox_count = true;
1122 }
1123 if hitbox.behavior == HitboxBehavior::BlockMouse {
1124 break;
1125 }
1126 }
1127 }
1128 if !set_hover_hitbox_count {
1129 hit_test.hover_hitbox_count = hit_test.ids.len();
1130 }
1131 hit_test
1132 }
1133
1134 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1135 self.focus
1136 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1137 .unwrap_or_default()
1138 }
1139
1140 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1141 for element_state_key in &self.accessed_element_states {
1142 if let Some((element_state_key, element_state)) =
1143 prev_frame.element_states.remove_entry(element_state_key)
1144 {
1145 self.element_states.insert(element_state_key, element_state);
1146 }
1147 }
1148
1149 self.scene.finish();
1150 }
1151}
1152
1153#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1154enum InputModality {
1155 Mouse,
1156 Keyboard,
1157 Touch,
1158}
1159
1160#[cfg(debug_assertions)]
1170#[derive(Copy, Clone, PartialEq, Eq, Debug)]
1171pub(crate) enum FramePhase {
1172 Idle,
1174 Begun,
1176 Evaluated,
1178 LaidOut,
1180 Painted,
1182 Finished,
1184 Completed,
1186}
1187
1188#[cfg(debug_assertions)]
1189impl FramePhase {
1190 #[track_caller]
1192 fn enter(&mut self, from: &[FramePhase], next: FramePhase, method: &'static str) {
1193 debug_assert!(
1194 from.contains(self),
1195 "{method} ran while the frame was {self:?}, but it must follow one of {from:?}"
1196 );
1197 *self = next;
1198 }
1199}
1200
1201pub(crate) struct WindowFrameState {
1202 rem_size_override_stack: SmallVec<[Pixels; 8]>,
1207 layout_session: Rc<FrameSession>,
1208 pub(crate) inspector_element_id: Option<crate::InspectorElementId>,
1213 pub(crate) dirty_views: FxHashSet<EntityId>,
1215 focus_lost_path: SmallVec<[FocusId; 8]>,
1218 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
1219 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1220 pub(crate) rendered_entity_stack: Vec<EntityId>,
1221 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1222 pub(crate) element_opacity: f32,
1223 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1224 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1225 pub(crate) image_cache_stack: Vec<AnyImageCache>,
1226 pub(crate) rendered_frame: Frame,
1227 pub(crate) next_frame: Frame,
1228 next_hitbox_id: HitboxId,
1229 pub(crate) next_tooltip_id: TooltipId,
1230 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1231 #[cfg(debug_assertions)]
1233 frame_phase: FramePhase,
1234}
1235
1236pub(crate) struct WindowHostCore {
1242 pub(crate) handle: AnyWindowHandle,
1243 pub(crate) invalidator: WindowInvalidator,
1244 frame_pipeline: Rc<RefCell<Box<dyn FramePipeline>>>,
1249 pub(crate) removed: bool,
1250 metrics: Arc<ArcSwap<WindowMetrics>>,
1252 pub(crate) platform_window: Box<dyn PlatformWindow>,
1253 display_id: Option<DisplayId>,
1254 is_resizable: bool,
1255 is_minimizable: bool,
1256 sprite_atlas: Arc<dyn PlatformAtlas>,
1257 text_system: Arc<WindowTextSystem>,
1258 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1259 rem_size: Pixels,
1260 pub(crate) viewport_size: Size<Pixels>,
1261 pub(crate) root: Option<AnyView>,
1262 last_text_input_configuration: Option<TextInputConfiguration>,
1266 focused_text_input_active: bool,
1267 pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1268 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
1269 pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
1270 default_prevented: bool,
1271 mouse_position: Point<Pixels>,
1272 mouse_hit_test: HitTest,
1273 modifiers: Modifiers,
1274 capslock: Capslock,
1275 scale_factor: f32,
1276 pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
1277 appearance: WindowAppearance,
1278 pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
1279 pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>,
1280 active: Rc<Cell<bool>>,
1281 visibility: WindowVisibility,
1282 pub(crate) visibility_observers:
1283 SubscriberSet<(), Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
1284 hovered: Rc<Cell<bool>>,
1285 pub(crate) needs_present: Rc<Cell<bool>>,
1286 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1289 #[cfg(feature = "profiler")]
1290 window_profiler: profiler::WindowProfiler,
1291 last_input_modality: InputModality,
1292 touch_gestures: TouchGestureRecognizer,
1293 touch_prediction_enabled: bool,
1294 long_press_timer: Option<Task<()>>,
1295 long_press_capture: Option<EntityId>,
1296 pub(crate) refreshing: bool,
1297 pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
1298 pub(crate) focus: Option<FocusId>,
1299 focus_enabled: bool,
1300 pub(crate) focus_generation: u64,
1303 pending_input: Option<PendingInput>,
1304 pending_modifier: ModifierState,
1305 pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
1306 prompt: Option<RenderablePromptHandle>,
1307 pub(crate) client_inset: Option<Pixels>,
1308 captured_hitbox: Option<HitboxId>,
1311 #[cfg(any(feature = "inspector", debug_assertions))]
1312 inspector: Option<Entity<Inspector>>,
1313 #[cfg(feature = "profiler")]
1314 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1315 pub(crate) a11y: A11y,
1316}
1317
1318impl WindowHostCore {
1319 fn metrics_handle(&self) -> WindowMetricsHandle {
1320 WindowMetricsHandle {
1321 id: self.handle.window_id(),
1322 metrics: self.metrics.clone(),
1323 }
1324 }
1325
1326 pub(crate) fn should_render_frame(&self) -> bool {
1329 let is_dirty = self.invalidator.is_dirty();
1330 let metrics = self.metrics.load();
1331 self.frame_pipeline
1332 .borrow_mut()
1333 .should_render(is_dirty, &metrics)
1334 }
1335}
1336
1337pub struct WindowMetricsHandle {
1343 id: WindowId,
1344 metrics: Arc<ArcSwap<WindowMetrics>>,
1345}
1346
1347impl WindowMetricsHandle {
1348 pub fn id(&self) -> WindowId {
1350 self.id
1351 }
1352
1353 pub fn snapshot(&self) -> Arc<WindowMetrics> {
1358 self.metrics.load_full()
1359 }
1360
1361 pub fn bounds(&self) -> Bounds<Pixels> {
1363 self.metrics.load().bounds
1364 }
1365
1366 pub fn viewport(&self) -> Bounds<Pixels> {
1371 self.metrics.load().viewport
1372 }
1373
1374 pub fn content_size(&self) -> Size<Pixels> {
1376 self.metrics.load().content_size
1377 }
1378
1379 pub fn scale_factor(&self) -> f32 {
1381 self.metrics.load().scale_factor
1382 }
1383
1384 pub fn display_id(&self) -> Option<DisplayId> {
1386 self.metrics.load().display_id
1387 }
1388
1389 pub fn is_active(&self) -> bool {
1391 self.metrics.load().is_active
1392 }
1393
1394 pub fn is_fullscreen(&self) -> bool {
1396 self.metrics.load().is_fullscreen
1397 }
1398}
1399
1400pub struct Window<'frame> {
1416 pub(crate) core: &'frame mut WindowHostCore,
1419 pub(crate) frame_state: &'frame mut WindowFrameState,
1421}
1422
1423pub(crate) struct WindowHost {
1429 pub(crate) core: WindowHostCore,
1430 pub(crate) frame_state: WindowFrameState,
1431}
1432
1433impl WindowHost {
1434 pub(crate) fn with_window<R>(&mut self, f: impl FnOnce(&mut Window<'_>) -> R) -> R {
1436 let core = &mut self.core;
1437 let frame_state = &mut self.frame_state;
1438 f(&mut Window { core, frame_state })
1439 }
1440}
1441
1442#[derive(Clone, Debug, Default)]
1443struct ModifierState {
1444 modifiers: Modifiers,
1445 saw_other_input: bool,
1446}
1447
1448#[derive(Clone, Debug)]
1451pub(crate) struct InputRateTracker {
1452 timestamps: Vec<Instant>,
1453 window: Duration,
1454 inputs_per_second: u32,
1455 sustain_until: Instant,
1456 sustain_duration: Duration,
1457}
1458
1459impl Default for InputRateTracker {
1460 fn default() -> Self {
1461 Self {
1462 timestamps: Vec::new(),
1463 window: Duration::from_millis(100),
1464 inputs_per_second: 60,
1465 sustain_until: Instant::now(),
1466 sustain_duration: Duration::from_secs(1),
1467 }
1468 }
1469}
1470
1471impl InputRateTracker {
1472 pub fn record_input(&mut self) {
1473 let now = Instant::now();
1474 self.timestamps.push(now);
1475 self.prune_old_timestamps(now);
1476
1477 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1478 if self.timestamps.len() as u128 >= min_events {
1479 self.sustain_until = now + self.sustain_duration;
1480 }
1481 }
1482
1483 pub fn is_high_rate(&self) -> bool {
1484 Instant::now() < self.sustain_until
1485 }
1486
1487 fn prune_old_timestamps(&mut self, now: Instant) {
1488 self.timestamps
1489 .retain(|&t| now.duration_since(t) <= self.window);
1490 }
1491}
1492
1493#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1494pub(crate) enum DrawPhase {
1495 None,
1496 Prepaint,
1497 Paint,
1498 Focus,
1499}
1500
1501pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
1502
1503pub struct PendingInputStatus<'a> {
1505 keystrokes: &'a [Keystroke],
1506 timeout: Option<PendingInputTimeoutStatus>,
1507}
1508
1509impl<'a> PendingInputStatus<'a> {
1510 pub fn keystrokes(&self) -> &'a [Keystroke] {
1512 self.keystrokes
1513 }
1514
1515 pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
1517 self.timeout
1518 }
1519}
1520
1521#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1523pub struct PendingInputTimeoutStatus {
1524 duration: Duration,
1525 remaining: Duration,
1526 started_at: Option<Instant>,
1527 paused: bool,
1528}
1529
1530impl PendingInputTimeoutStatus {
1531 pub fn duration(&self) -> Duration {
1533 self.duration
1534 }
1535
1536 pub fn remaining(&self, cx: &App) -> Duration {
1538 self.started_at
1539 .map(|started_at| {
1540 self.remaining
1541 .saturating_sub(cx.background_executor().now() - started_at)
1542 })
1543 .unwrap_or(self.remaining)
1544 }
1545
1546 pub fn is_paused(&self) -> bool {
1548 self.paused
1549 }
1550}
1551
1552#[derive(Debug)]
1553struct PendingInputTimeout {
1554 duration: Duration,
1555 remaining: Duration,
1556 state: PendingInputTimeoutState,
1557}
1558
1559#[derive(Debug)]
1560enum PendingInputTimeoutState {
1561 Running { started_at: Instant, task: Task<()> },
1562 Paused { pause: PendingInputTimeoutPause },
1563}
1564
1565#[derive(Debug)]
1566struct PendingInputTimeoutPause {
1567 owner_id: EntityId,
1568 _release_subscription: Subscription,
1569}
1570
1571impl PendingInputTimeout {
1572 fn is_paused(&self) -> bool {
1573 matches!(&self.state, PendingInputTimeoutState::Paused { .. })
1574 }
1575
1576 fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
1577 match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
1578 PendingInputTimeoutState::Running { started_at, task } => {
1579 self.remaining = self.remaining.saturating_sub(now - started_at);
1580 drop(task);
1581 true
1582 }
1583 previous_state @ PendingInputTimeoutState::Paused { .. } => {
1584 self.state = previous_state;
1585 false
1586 }
1587 }
1588 }
1589
1590 fn pause_owner_id(&self) -> Option<EntityId> {
1591 match &self.state {
1592 PendingInputTimeoutState::Running { .. } => None,
1593 PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
1594 }
1595 }
1596
1597 fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
1598 match std::mem::replace(
1599 &mut self.state,
1600 PendingInputTimeoutState::Running { started_at, task },
1601 ) {
1602 PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
1603 previous_state => {
1604 self.state = previous_state;
1605 false
1606 }
1607 }
1608 }
1609
1610 fn reset_duration(&mut self, duration: Duration) {
1611 self.duration = duration;
1612 self.remaining = duration;
1613 }
1614
1615 fn status(&self) -> PendingInputTimeoutStatus {
1616 let (started_at, paused) = match &self.state {
1617 PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
1618 PendingInputTimeoutState::Paused { .. } => (None, true),
1619 };
1620 PendingInputTimeoutStatus {
1621 duration: self.duration,
1622 remaining: self.remaining,
1623 started_at,
1624 paused,
1625 }
1626 }
1627}
1628
1629#[derive(Default, Debug)]
1630struct PendingInput {
1631 keystrokes: SmallVec<[Keystroke; 1]>,
1632 focus: Option<FocusId>,
1633 timeout: Option<PendingInputTimeout>,
1634}
1635
1636pub(crate) struct ElementStateBox {
1637 pub(crate) inner: Box<dyn Any>,
1638 #[cfg(debug_assertions)]
1639 pub(crate) type_name: &'static str,
1640}
1641
1642fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1643 let active_window_bounds = cx
1648 .active_window()
1649 .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1650
1651 const CASCADE_OFFSET: f32 = 25.0;
1652
1653 let display = display_id
1654 .map(|id| cx.find_display(id))
1655 .unwrap_or_else(|| cx.primary_display());
1656
1657 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1658
1659 let display_bounds = display
1661 .as_ref()
1662 .map(|d| d.visible_bounds())
1663 .unwrap_or_else(default_placement);
1664
1665 let (
1666 Bounds {
1667 origin: base_origin,
1668 size: base_size,
1669 },
1670 window_bounds_ctor,
1671 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1672 Some(bounds) => match bounds {
1673 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1674 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1675 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1676 },
1677 None => (
1678 display
1679 .as_ref()
1680 .map(|d| d.default_bounds())
1681 .unwrap_or_else(default_placement),
1682 WindowBounds::Windowed,
1683 ),
1684 };
1685
1686 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1687 let proposed_origin = base_origin + cascade_offset;
1688 let proposed_bounds = Bounds::new(proposed_origin, base_size);
1689
1690 let display_right = display_bounds.origin.x + display_bounds.size.width;
1691 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1692 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1693 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1694
1695 let fits_horizontally = window_right <= display_right;
1696 let fits_vertically = window_bottom <= display_bottom;
1697
1698 let final_origin = match (fits_horizontally, fits_vertically) {
1699 (true, true) => proposed_origin,
1700 (false, true) => point(display_bounds.origin.x, base_origin.y),
1701 (true, false) => point(base_origin.x, display_bounds.origin.y),
1702 (false, false) => display_bounds.origin,
1703 };
1704 window_bounds_ctor(Bounds::new(final_origin, base_size))
1705}
1706
1707impl WindowHost {
1708 pub(crate) fn new(
1709 handle: AnyWindowHandle,
1710 options: WindowOptions,
1711 cx: &mut App,
1712 ) -> Result<Self> {
1713 let WindowOptions {
1714 window_bounds,
1715 titlebar,
1716 focus,
1717 show,
1718 kind,
1719 is_movable,
1720 app_owns_titlebar_drag,
1721 inactive_frame_interval,
1722 is_resizable,
1723 is_minimizable,
1724 display_id,
1725 window_background,
1726 app_id,
1727 window_min_size,
1728 window_decorations,
1729 #[cfg_attr(
1730 not(any(target_os = "linux", target_os = "freebsd")),
1731 allow(unused_variables)
1732 )]
1733 icon,
1734 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1735 tabbing_identifier,
1736 } = options;
1737
1738 let initial_window_title = titlebar
1739 .as_ref()
1740 .and_then(|titlebar| titlebar.title.clone());
1741
1742 let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1743 let mut platform_window = cx.platform.open_window(
1744 handle.window_id(),
1745 WindowParams {
1746 bounds: window_bounds.get_bounds(),
1747 titlebar,
1748 kind,
1749 is_movable,
1750 app_owns_titlebar_drag,
1751 is_resizable,
1752 is_minimizable,
1753 focus,
1754 show,
1755 display_id,
1756 window_min_size,
1757 app_id: app_id.clone(),
1758 icon,
1759 #[cfg(target_os = "macos")]
1760 tabbing_identifier,
1761 },
1762 )?;
1763
1764 let tab_bar_visible = platform_window.tab_bar_visible();
1765 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1766 if let Some(tabs) = platform_window.tabbed_windows() {
1767 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1768 }
1769
1770 let display_id = platform_window.display().map(|display| display.id());
1771 let mut sprite_atlas = None;
1772 platform_window.with_renderer(&mut |renderer| {
1773 sprite_atlas = Some(renderer.sprite_atlas());
1774 });
1775 let sprite_atlas = sprite_atlas
1776 .ok_or_else(|| anyhow!("platform window did not provide a scene renderer"))?;
1777 let mouse_position = platform_window.mouse_position();
1778 let modifiers = platform_window.modifiers();
1779 let capslock = platform_window.capslock();
1780 let content_size = platform_window.content_size();
1781 let scale_factor = platform_window.scale_factor();
1782 let appearance = platform_window.appearance();
1783 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1784 let invalidator = WindowInvalidator::new(handle.window_id());
1785 let active = Rc::new(Cell::new(platform_window.is_active()));
1786 let visibility = platform_window.visibility();
1787 let metrics = Arc::new(ArcSwap::from_pointee(WindowMetrics {
1788 bounds: platform_window.bounds(),
1789 viewport: platform_window.visual_viewport_bounds(),
1790 content_size,
1791 scale_factor,
1792 display_id,
1793 is_active: active.get(),
1794 is_fullscreen: platform_window.is_fullscreen(),
1795 }));
1796 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1797 let needs_present = Rc::new(Cell::new(false));
1798 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1799 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1800 let last_frame_time = Rc::new(Cell::new(None));
1801
1802 platform_window
1803 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1804 platform_window.set_background_appearance(window_background);
1805
1806 match window_bounds {
1807 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1808 WindowBounds::Maximized(_) => platform_window.zoom(),
1809 WindowBounds::Windowed(_) => {}
1810 }
1811
1812 let accessibility_force_disabled = cx.accessibility_force_disabled;
1813 let a11y_active_flag = Arc::new(AtomicBool::new(false));
1814
1815 #[cfg(not(target_family = "wasm"))]
1816 if !accessibility_force_disabled {
1817 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
1818 if let Some(title) = &initial_window_title {
1819 initial_root_node.set_label(title.to_string());
1820 }
1821 let initial_tree = accesskit::TreeUpdate {
1822 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
1823 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
1824 tree_id: accesskit::TreeId::ROOT,
1825 focus: ROOT_NODE_ID,
1826 };
1827 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
1828 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
1829 let (action_sender, action_receiver) =
1830 async_channel::unbounded::<accesskit::ActionRequest>();
1831
1832 platform_window.a11y_init(crate::A11yCallbacks {
1833 activation: {
1834 let active_flag = a11y_active_flag.clone();
1835 Box::new(move || {
1836 log::info!("Accessibility activated");
1837 active_flag.store(true, SeqCst);
1838 activation_sender.send_blocking(()).log_err();
1839 Some(initial_tree.clone())
1840 })
1841 },
1842 action: Box::new(move |request| {
1843 action_sender.send_blocking(request).log_err();
1844 }),
1845 deactivation: {
1846 let active_flag = a11y_active_flag.clone();
1847 Box::new(move || {
1848 log::info!("Accessibility deactivated");
1849 active_flag.store(false, SeqCst);
1850 deactivation_sender.send_blocking(()).log_err();
1851 })
1852 },
1853 });
1854
1855 let mut async_cx = cx.to_async();
1861 cx.foreground_executor()
1862 .spawn(async move {
1863 while activation_receiver.recv().await.is_ok() {
1864 handle
1865 .update(&mut async_cx, |_, window, _| window.refresh())
1866 .log_err();
1867 }
1868 })
1869 .detach();
1870
1871 let mut async_cx = cx.to_async();
1872 cx.foreground_executor()
1873 .spawn(async move {
1874 while deactivation_receiver.recv().await.is_ok() {
1875 handle
1876 .update(&mut async_cx, |_, window, _| window.refresh())
1877 .log_err();
1878 }
1879 })
1880 .detach();
1881
1882 let mut async_cx = cx.to_async();
1883 cx.foreground_executor()
1884 .spawn(async move {
1885 while let Ok(request) = action_receiver.recv().await {
1886 handle
1887 .update(&mut async_cx, |_, window, cx| {
1888 window.handle_a11y_action(request, cx);
1889 })
1890 .log_err();
1891 }
1892 })
1893 .detach();
1894 }
1895
1896 platform_window.on_close(Box::new({
1897 let window_id = handle.window_id();
1898 let mut cx = cx.to_async();
1899 move || {
1900 let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
1901 let _ = cx.update(|cx| {
1902 SystemWindowTabController::remove_tab(cx, window_id);
1903 });
1904 }
1905 }));
1906 platform_window.on_request_frame(Box::new({
1907 let mut cx = cx.to_async();
1908 let invalidator = invalidator.clone();
1909 let active = active.clone();
1910 let needs_present = needs_present.clone();
1911 let next_frame_callbacks = next_frame_callbacks.clone();
1912 let input_rate_tracker = input_rate_tracker.clone();
1913 let mut deferred_force_render = false;
1914 move |request_frame_options| {
1915 #[cfg(feature = "profiler")]
1916 let _foreground_turn = profiler::journal::foreground_turn();
1917 if draw_in_progress() {
1933 log::debug!("deferring re-entrant window draw request");
1934 deferred_force_render |= request_frame_options.force_render;
1935 return;
1936 }
1937 let force_render =
1941 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
1942
1943 let thermal_state = handle
1944 .update(&mut cx, |_, _, cx| cx.thermal_state())
1945 .log_err();
1946
1947 let min_frame_interval = if request_frame_options.require_presentation
1951 || (!request_frame_options.force_render
1952 && next_frame_callbacks.borrow().is_empty())
1953 {
1954 None
1955 } else if !active.get() && !input_rate_tracker.borrow_mut().is_high_rate() {
1956 inactive_frame_interval
1957 } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
1958 Some(Duration::from_micros(16667))
1959 } else {
1960 None
1961 };
1962
1963 let now = Instant::now();
1964 if let Some(min_interval) = min_frame_interval {
1965 if let Some(last_frame) = last_frame_time.get()
1966 && now.duration_since(last_frame) < min_interval
1967 {
1968 deferred_force_render |= force_render;
1970 handle
1972 .update(&mut cx, |_, window, _| {
1973 window.core.platform_window.schedule_frame();
1974 })
1975 .log_err();
1976 invalidator.wake_platform();
1981 return;
1982 }
1983 }
1984 last_frame_time.set(Some(now));
1985
1986 let pending_next_frame_callbacks = next_frame_callbacks.take();
1987 if !pending_next_frame_callbacks.is_empty() {
1988 handle
1989 .update(&mut cx, |_, window, cx| {
1990 for callback in pending_next_frame_callbacks {
1991 callback(window, cx);
1992 }
1993 })
1994 .log_err();
1995 }
1996
1997 let needs_present = request_frame_options.require_presentation
2001 || needs_present.get()
2002 || input_rate_tracker.borrow_mut().is_high_rate();
2003
2004 if invalidator.is_dirty() || force_render {
2005 measure("frame duration", || {
2006 handle
2007 .update(&mut cx, |_, window, cx| {
2008 if force_render {
2009 window.refresh();
2012 }
2013 if force_render || window.core.should_render_frame() {
2016 let arena_clear_needed = window.draw(cx);
2017 window.present();
2018 arena_clear_needed.clear(cx);
2019 }
2020 })
2021 .log_err();
2022 })
2023 } else if needs_present {
2024 handle
2025 .update(&mut cx, |_, window, _| window.present())
2026 .log_err();
2027 }
2028
2029 handle
2030 .update(&mut cx, |_, window, _| {
2031 if window.core.invalidator.is_dirty()
2032 || !window.core.next_frame_callbacks.borrow().is_empty()
2033 {
2034 window.core.platform_window.schedule_frame();
2035 }
2036 })
2037 .log_err();
2038
2039 if invalidator.is_dirty() || !next_frame_callbacks.borrow().is_empty() {
2045 invalidator.wake_platform();
2046 }
2047 }
2048 }));
2049 invalidator.set_platform_waker(platform_window.frame_waker());
2050 platform_window.on_visual_viewport_changed(Box::new({
2051 let mut cx = cx.to_async();
2052 move || {
2053 handle
2054 .update(&mut cx, |_, window, _| window.refresh())
2055 .log_err();
2056 }
2057 }));
2058 platform_window.on_insets_changed(Box::new({
2059 let mut cx = cx.to_async();
2060 move |_| {
2061 handle
2062 .update(&mut cx, |_, window, _| window.refresh())
2063 .log_err();
2064 }
2065 }));
2066 platform_window.on_resize(Box::new({
2067 let mut cx = cx.to_async();
2068 move |_, _| {
2069 handle
2070 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2071 .log_err();
2072 }
2073 }));
2074 platform_window.on_moved(Box::new({
2075 let mut cx = cx.to_async();
2076 move || {
2077 handle
2078 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2079 .log_err();
2080 }
2081 }));
2082 platform_window.on_appearance_changed(Box::new({
2083 let cx = cx.to_async();
2084 let foreground_executor = cx.foreground_executor().clone();
2085 move || {
2086 let mut cx = cx.clone();
2087 foreground_executor
2090 .spawn(async move {
2091 handle
2092 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
2093 .log_err();
2094 })
2095 .detach();
2096 }
2097 }));
2098 platform_window.on_button_layout_changed(Box::new({
2099 let mut cx = cx.to_async();
2100 move || {
2101 handle
2102 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
2103 .log_err();
2104 }
2105 }));
2106 platform_window.on_active_status_change(Box::new({
2107 let mut cx = cx.to_async();
2108 move |active| {
2109 handle
2110 .update(&mut cx, |_, window, cx| {
2111 window.core.active.set(active);
2112 window.core.modifiers = window.core.platform_window.modifiers();
2113 window.core.capslock = window.core.platform_window.capslock();
2114 window
2115 .core
2116 .activation_observers
2117 .clone()
2118 .retain(&(), |callback| callback(window, cx));
2119
2120 window.bounds_changed(cx);
2121 window.refresh();
2122
2123 SystemWindowTabController::update_last_active(cx, window.core.handle.id);
2124 })
2125 .log_err();
2126 }
2127 }));
2128 platform_window.on_visibility_change(Box::new({
2129 let mut cx = cx.to_async();
2130 move |visibility| {
2131 handle
2132 .update(&mut cx, |_, window, cx| {
2133 if window.core.visibility == visibility {
2134 return;
2135 }
2136 window.core.visibility = visibility;
2137 window
2138 .core
2139 .visibility_observers
2140 .clone()
2141 .retain(&(), |callback| callback(visibility, window, cx));
2142 })
2143 .log_err();
2144 }
2145 }));
2146 platform_window.on_hover_status_change(Box::new({
2147 let mut cx = cx.to_async();
2148 move |active| {
2149 handle
2150 .update(&mut cx, |_, window, _| {
2151 window.core.hovered.set(active);
2152 window.refresh();
2153 })
2154 .log_err();
2155 }
2156 }));
2157 platform_window.on_input({
2158 let mut cx = cx.to_async();
2159 Box::new(move |event| {
2160 handle
2161 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
2162 .log_err()
2163 .unwrap_or(DispatchEventResult::default())
2164 })
2165 });
2166 platform_window.on_hit_test_window_control({
2167 let mut cx = cx.to_async();
2168 Box::new(move || {
2169 handle
2170 .update(&mut cx, |_, window, _cx| {
2171 for (area, hitbox) in
2172 &window.frame_state.rendered_frame.window_control_hitboxes
2173 {
2174 if window.core.mouse_hit_test.ids.contains(&hitbox.id) {
2175 return Some(*area);
2176 }
2177 }
2178 None
2179 })
2180 .log_err()
2181 .unwrap_or(None)
2182 })
2183 });
2184 platform_window.on_move_tab_to_new_window({
2185 let mut cx = cx.to_async();
2186 Box::new(move || {
2187 handle
2188 .update(&mut cx, |_, _window, cx| {
2189 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
2190 })
2191 .log_err();
2192 })
2193 });
2194 platform_window.on_merge_all_windows({
2195 let mut cx = cx.to_async();
2196 Box::new(move || {
2197 handle
2198 .update(&mut cx, |_, _window, cx| {
2199 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
2200 })
2201 .log_err();
2202 })
2203 });
2204 platform_window.on_select_next_tab({
2205 let mut cx = cx.to_async();
2206 Box::new(move || {
2207 handle
2208 .update(&mut cx, |_, _window, cx| {
2209 SystemWindowTabController::select_next_tab(cx, handle.window_id());
2210 })
2211 .log_err();
2212 })
2213 });
2214 platform_window.on_select_previous_tab({
2215 let mut cx = cx.to_async();
2216 Box::new(move || {
2217 handle
2218 .update(&mut cx, |_, _window, cx| {
2219 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
2220 })
2221 .log_err();
2222 })
2223 });
2224 platform_window.on_toggle_tab_bar({
2225 let mut cx = cx.to_async();
2226 Box::new(move || {
2227 handle
2228 .update(&mut cx, |_, window, cx| {
2229 let tab_bar_visible = window.core.platform_window.tab_bar_visible();
2230 SystemWindowTabController::set_visible(cx, tab_bar_visible);
2231 })
2232 .log_err();
2233 })
2234 });
2235
2236 if let Some(app_id) = app_id {
2237 platform_window.set_app_id(&app_id);
2238 }
2239
2240 platform_window.map_window().unwrap();
2241
2242 Ok(WindowHost {
2243 core: WindowHostCore {
2244 handle,
2245 invalidator,
2246 frame_pipeline: Rc::new(RefCell::new(cx.new_frame_pipeline(handle.window_id()))),
2247 removed: false,
2248 metrics,
2249 platform_window,
2250 display_id,
2251 is_resizable,
2252 is_minimizable,
2253 sprite_atlas,
2254 text_system,
2255 text_rendering_mode: cx.text_rendering_mode.clone(),
2256 rem_size: px(16.),
2257 viewport_size: content_size,
2258 root: None,
2259 last_text_input_configuration: None,
2260 focused_text_input_active: false,
2261 next_frame_callbacks,
2262 focus_listeners: SubscriberSet::new(),
2263 focus_lost_listeners: SubscriberSet::new(),
2264 default_prevented: true,
2265 mouse_position,
2266 mouse_hit_test: HitTest::default(),
2267 modifiers,
2268 capslock,
2269 scale_factor,
2270 bounds_observers: SubscriberSet::new(),
2271 appearance,
2272 appearance_observers: SubscriberSet::new(),
2273 button_layout_observers: SubscriberSet::new(),
2274 active,
2275 visibility,
2276 visibility_observers: SubscriberSet::new(),
2277 hovered,
2278 needs_present,
2279 input_rate_tracker,
2280 #[cfg(feature = "profiler")]
2281 window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
2282 last_input_modality: InputModality::Mouse,
2283 touch_gestures: TouchGestureRecognizer::new(
2284 cx.platform
2285 .gestures()
2286 .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
2287 ),
2288 touch_prediction_enabled: true,
2289 long_press_timer: None,
2290 long_press_capture: None,
2291 refreshing: false,
2292 activation_observers: SubscriberSet::new(),
2293 focus: None,
2294 focus_enabled: true,
2295 focus_generation: 0,
2296 pending_input: None,
2297 pending_modifier: ModifierState::default(),
2298 pending_input_observers: SubscriberSet::new(),
2299 prompt: None,
2300 client_inset: None,
2301 captured_hitbox: None,
2302 #[cfg(any(feature = "inspector", debug_assertions))]
2303 inspector: None,
2304 #[cfg(feature = "profiler")]
2305 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
2306 a11y: A11y::new(
2307 a11y_active_flag,
2308 accessibility_force_disabled,
2309 initial_window_title,
2310 ),
2311 },
2312 frame_state: WindowFrameState {
2313 rem_size_override_stack: SmallVec::new(),
2314 layout_session: Rc::new(FrameSession::new(cx.new_layout_engine())),
2315 inspector_element_id: None,
2316 dirty_views: FxHashSet::default(),
2317 focus_lost_path: SmallVec::new(),
2318 element_id_stack: SmallVec::default(),
2319 text_style_stack: Vec::new(),
2320 rendered_entity_stack: Vec::new(),
2321 element_offset_stack: Vec::new(),
2322 element_opacity: 1.0,
2323 content_mask_stack: Vec::new(),
2324 requested_autoscroll: None,
2325 image_cache_stack: Vec::new(),
2326 rendered_frame: Frame::new(DispatchTree::new(
2327 cx.keymap.clone(),
2328 cx.actions.clone(),
2329 )),
2330 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
2331 next_hitbox_id: HitboxId(0),
2332 next_tooltip_id: TooltipId::default(),
2333 tooltip_bounds: None,
2334 #[cfg(debug_assertions)]
2335 frame_phase: FramePhase::Idle,
2336 },
2337 })
2338 }
2339}
2340
2341pub struct PreparedRoots {
2353 pub root: AnyElement,
2355 pub prompt: Option<AnyElement>,
2357 pub tooltip: Option<AnyElement>,
2359 pub drag: Option<(AnyElement, Point<Pixels>)>,
2362 pub inspector: Option<AnyElement>,
2364}
2365
2366impl Window<'_> {
2367 pub(crate) fn new_focus_listener(
2368 &self,
2369 value: AnyWindowFocusListener,
2370 ) -> (Subscription, impl FnOnce() + use<>) {
2371 self.core.focus_listeners.insert((), value)
2372 }
2373
2374 fn mark_view_dirty(&mut self, view_id: EntityId) {
2375 for view_id in self
2378 .frame_state
2379 .rendered_frame
2380 .dispatch_tree
2381 .view_path_reversed(view_id)
2382 {
2383 if !self.frame_state.dirty_views.insert(view_id) {
2384 break;
2385 }
2386 }
2387 }
2388
2389 pub fn visibility(&self) -> WindowVisibility {
2392 self.core.visibility
2393 }
2394
2395 pub fn is_visible(&self) -> bool {
2401 self.core.visibility.is_visible()
2402 }
2403
2404 pub fn observe_window_visibility(
2406 &self,
2407 mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
2408 ) -> Subscription {
2409 let (subscription, activate) = self.core.visibility_observers.insert(
2410 (),
2411 Box::new(move |visibility, window, cx| {
2412 callback(visibility, window, cx);
2413 true
2414 }),
2415 );
2416 activate();
2417 subscription
2418 }
2419
2420 pub fn observe_window_appearance(
2422 &self,
2423 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2424 ) -> Subscription {
2425 let (subscription, activate) = self.core.appearance_observers.insert(
2426 (),
2427 Box::new(move |window, cx| {
2428 callback(window, cx);
2429 true
2430 }),
2431 );
2432 activate();
2433 subscription
2434 }
2435
2436 pub fn observe_button_layout_changed(
2438 &self,
2439 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2440 ) -> Subscription {
2441 let (subscription, activate) = self.core.button_layout_observers.insert(
2442 (),
2443 Box::new(move |window, cx| {
2444 callback(window, cx);
2445 true
2446 }),
2447 );
2448 activate();
2449 subscription
2450 }
2451
2452 pub fn replace_root<E>(
2454 &mut self,
2455 cx: &mut App,
2456 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
2457 ) -> Entity<E>
2458 where
2459 E: 'static + Render,
2460 {
2461 let view = cx.new(|cx| build_view(self, cx));
2462 self.core.root = Some(view.clone().into());
2463 self.refresh();
2464 view
2465 }
2466
2467 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
2469 where
2470 E: 'static + Render,
2471 {
2472 self.core
2473 .root
2474 .as_ref()
2475 .map(|view| view.clone().downcast::<E>().ok())
2476 }
2477
2478 pub fn window_handle(&self) -> AnyWindowHandle {
2480 self.core.handle
2481 }
2482
2483 pub fn metrics_handle(&self) -> WindowMetricsHandle {
2489 self.core.metrics_handle()
2490 }
2491
2492 pub fn refresh(&mut self) {
2494 if self.core.invalidator.not_drawing() {
2495 self.core.refreshing = true;
2496 self.core.invalidator.set_dirty(true);
2497 }
2498 }
2499
2500 pub fn remove_window(&mut self) {
2502 self.core.removed = true;
2503 }
2504
2505 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
2507 self.core
2508 .focus
2509 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
2510 }
2511
2512 pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
2516 let (_leaf, ancestors) = self.frame_state.focus_lost_path.split_last()?;
2517 ancestors.iter().rev().find_map(|id| {
2518 self.frame_state
2519 .rendered_frame
2520 .dispatch_tree
2521 .focusable_node_id(*id)?;
2522 FocusHandle::for_id(*id, &cx.focus_handles)
2523 })
2524 }
2525
2526 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
2528 if !self.core.focus_enabled || self.core.focus == Some(handle.id) {
2529 return;
2530 }
2531
2532 self.core.focus = Some(handle.id);
2533 self.core.focus_generation = self.core.focus_generation.wrapping_add(1);
2534 self.clear_pending_keystrokes(cx);
2535
2536 self.refresh();
2537 }
2538
2539 pub fn blur(&mut self, cx: &mut App) {
2541 self.clear_pending_keystrokes(cx);
2542
2543 if !self.core.focus_enabled {
2544 return;
2545 }
2546
2547 if self.core.focus.is_some() {
2548 self.core.focus_generation = self.core.focus_generation.wrapping_add(1);
2549 }
2550 self.core.focus = None;
2551 self.refresh();
2552 }
2553
2554 pub fn disable_focus(&mut self, cx: &mut App) {
2556 self.blur(cx);
2557 self.core.focus_enabled = false;
2558 }
2559
2560 pub fn focus_next(&mut self, cx: &mut App) {
2562 if !self.core.focus_enabled {
2563 return;
2564 }
2565
2566 if let Some(handle) = self
2567 .frame_state
2568 .rendered_frame
2569 .tab_stops
2570 .next(self.core.focus.as_ref())
2571 {
2572 self.focus(&handle, cx)
2573 }
2574 }
2575
2576 pub fn focus_prev(&mut self, cx: &mut App) {
2578 if !self.core.focus_enabled {
2579 return;
2580 }
2581
2582 if let Some(handle) = self
2583 .frame_state
2584 .rendered_frame
2585 .tab_stops
2586 .prev(self.core.focus.as_ref())
2587 {
2588 self.focus(&handle, cx)
2589 }
2590 }
2591
2592 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
2594 &self.core.text_system
2595 }
2596
2597 pub fn text_style(&self) -> TextStyle {
2599 let mut style = TextStyle::default();
2600 for refinement in &self.frame_state.text_style_stack {
2601 style.refine(refinement);
2602 }
2603 style
2604 }
2605
2606 pub fn is_maximized(&self) -> bool {
2610 self.core.platform_window.is_maximized()
2611 }
2612
2613 pub fn request_decorations(&self, decorations: WindowDecorations) {
2615 self.core.platform_window.request_decorations(decorations);
2616 }
2617
2618 pub fn set_exclusive_zone(&self, zone: Pixels) {
2624 self.core.platform_window.set_exclusive_zone(zone);
2625 }
2626
2627 #[cfg(all(target_os = "linux", feature = "wayland"))]
2632 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
2633 self.core.platform_window.set_exclusive_edge(edge);
2634 }
2635
2636 pub fn start_window_resize(&self, edge: ResizeEdge) {
2638 if self.core.is_resizable {
2639 self.core.platform_window.start_window_resize(edge);
2640 }
2641 }
2642
2643 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
2650 self.core.platform_window.set_input_region(region);
2651 }
2652
2653 pub fn window_bounds(&self) -> WindowBounds {
2656 self.core.platform_window.window_bounds()
2657 }
2658
2659 pub fn inner_window_bounds(&self) -> WindowBounds {
2661 self.core.platform_window.inner_window_bounds()
2662 }
2663
2664 pub fn native_window_state(&self) -> Option<Vec<u8>> {
2667 self.core.platform_window.native_window_state()
2668 }
2669
2670 pub fn restore_native_window_state(&self, state: &[u8]) {
2673 self.core.platform_window.restore_native_window_state(state);
2674 }
2675
2676 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
2678 let focus_id = self.focused(cx).map(|handle| handle.id);
2679
2680 let window = self.core.handle;
2681 cx.defer(move |cx| {
2682 window
2683 .update(cx, |_, window, cx| {
2684 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
2685 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
2686 })
2687 .log_err();
2688 })
2689 }
2690
2691 pub(crate) fn dispatch_keystroke_observers(
2692 &mut self,
2693 event: &dyn Any,
2694 action: Option<Box<dyn Action>>,
2695 context_stack: Vec<KeyContext>,
2696 cx: &mut App,
2697 ) {
2698 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2699 return;
2700 };
2701
2702 cx.keystroke_observers.clone().retain(&(), move |callback| {
2703 (callback)(
2704 &KeystrokeEvent {
2705 keystroke: key_down_event.keystroke.clone(),
2706 action: action.as_ref().map(|action| action.boxed_clone()),
2707 context_stack: context_stack.clone(),
2708 },
2709 self,
2710 cx,
2711 )
2712 });
2713 }
2714
2715 pub(crate) fn dispatch_keystroke_interceptors(
2716 &mut self,
2717 event: &dyn Any,
2718 context_stack: Vec<KeyContext>,
2719 cx: &mut App,
2720 ) {
2721 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2722 return;
2723 };
2724
2725 cx.keystroke_interceptors
2726 .clone()
2727 .retain(&(), move |callback| {
2728 (callback)(
2729 &KeystrokeEvent {
2730 keystroke: key_down_event.keystroke.clone(),
2731 action: None,
2732 context_stack: context_stack.clone(),
2733 },
2734 self,
2735 cx,
2736 )
2737 });
2738 }
2739
2740 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2743 let handle = self.core.handle;
2744 cx.defer(move |cx| {
2745 handle.update(cx, |_, window, cx| f(window, cx)).ok();
2746 });
2747 }
2748
2749 pub fn observe<T: 'static>(
2753 &mut self,
2754 observed: &Entity<T>,
2755 cx: &mut App,
2756 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2757 ) -> Subscription {
2758 let entity_id = observed.entity_id();
2759 let observed = observed.downgrade();
2760 let window_handle = self.core.handle;
2761 cx.new_observer(
2762 entity_id,
2763 Box::new(move |cx| {
2764 window_handle
2765 .update(cx, |_, window, cx| {
2766 if let Some(handle) = observed.upgrade() {
2767 on_notify(handle, window, cx);
2768 true
2769 } else {
2770 false
2771 }
2772 })
2773 .unwrap_or(false)
2774 }),
2775 )
2776 }
2777
2778 pub fn subscribe<Emitter, Evt>(
2782 &mut self,
2783 entity: &Entity<Emitter>,
2784 cx: &mut App,
2785 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
2786 ) -> Subscription
2787 where
2788 Emitter: EventEmitter<Evt>,
2789 Evt: 'static,
2790 {
2791 let entity_id = entity.entity_id();
2792 let handle = entity.downgrade();
2793 let window_handle = self.core.handle;
2794 cx.new_subscription(
2795 entity_id,
2796 (
2797 TypeId::of::<Evt>(),
2798 Box::new(move |event, cx| {
2799 window_handle
2800 .update(cx, |_, window, cx| {
2801 if let Some(entity) = handle.upgrade() {
2802 let event = event.downcast_ref().expect("invalid event type");
2803 on_event(entity, event, window, cx);
2804 true
2805 } else {
2806 false
2807 }
2808 })
2809 .unwrap_or(false)
2810 }),
2811 ),
2812 )
2813 }
2814
2815 pub fn observe_release<T>(
2817 &self,
2818 entity: &Entity<T>,
2819 cx: &mut App,
2820 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2821 ) -> Subscription
2822 where
2823 T: 'static,
2824 {
2825 let entity_id = entity.entity_id();
2826 let window_handle = self.core.handle;
2827 let (subscription, activate) = cx.release_listeners.insert(
2828 entity_id,
2829 Box::new(move |entity, cx| {
2830 let entity = entity.downcast_mut().expect("invalid entity type");
2831 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2832 }),
2833 );
2834 activate();
2835 subscription
2836 }
2837
2838 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2841 AsyncWindowContext::new_context(cx.to_async(), self.core.handle)
2842 }
2843
2844 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2846 RefCell::borrow_mut(&self.core.next_frame_callbacks).push(Box::new(callback));
2847 self.core.platform_window.schedule_frame();
2848 self.core.invalidator.wake_platform();
2851 }
2852
2853 pub fn request_animation_frame(&self) {
2866 let entity = self.current_view();
2867 self.on_next_frame(move |_, cx| cx.notify(entity));
2868 }
2869
2870 #[cfg(any(test, feature = "test-support"))]
2875 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
2876 let callbacks = self.core.next_frame_callbacks.take();
2877 let count = callbacks.len();
2878 for callback in callbacks {
2879 callback(self, cx);
2880 }
2881 count
2882 }
2883
2884 #[track_caller]
2888 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2889 where
2890 R: 'static,
2891 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2892 {
2893 let handle = self.core.handle;
2894 cx.spawn(async move |app| {
2895 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2896 f(&mut async_window_cx).await
2897 })
2898 }
2899
2900 #[track_caller]
2904 pub fn spawn_with_priority<AsyncFn, R>(
2905 &self,
2906 priority: Priority,
2907 cx: &App,
2908 f: AsyncFn,
2909 ) -> Task<R>
2910 where
2911 R: 'static,
2912 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2913 {
2914 let handle = self.core.handle;
2915 cx.spawn_with_priority(priority, async move |app| {
2916 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2917 f(&mut async_window_cx).await
2918 })
2919 }
2920
2921 fn sync_metrics(&self) {
2927 self.core.metrics.store(Arc::new(WindowMetrics {
2928 bounds: self.core.platform_window.bounds(),
2929 viewport: self.core.platform_window.visual_viewport_bounds(),
2930 content_size: self.core.viewport_size,
2931 scale_factor: self.core.scale_factor,
2932 display_id: self.core.display_id,
2933 is_active: self.core.active.get(),
2934 is_fullscreen: self.core.platform_window.is_fullscreen(),
2935 }));
2936 }
2937
2938 pub fn bounds_changed(&mut self, cx: &mut App) {
2944 self.core.scale_factor = self.core.platform_window.scale_factor();
2945 self.core.viewport_size = self.core.platform_window.content_size();
2946 self.core.display_id = self
2947 .core
2948 .platform_window
2949 .display()
2950 .map(|display| display.id());
2951 self.core.mouse_position = self.core.platform_window.mouse_position();
2952
2953 self.sync_metrics();
2954 self.refresh();
2955
2956 self.core
2957 .bounds_observers
2958 .clone()
2959 .retain(&(), |callback| callback(self, cx));
2960 }
2961
2962 pub fn bounds(&self) -> Bounds<Pixels> {
2964 self.core.platform_window.bounds()
2965 }
2966
2967 #[cfg(any(test, feature = "test-support"))]
2971 pub fn render_to_image(&mut self) -> anyhow::Result<image::RgbaImage> {
2972 let size = self.bounds().size.to_device_pixels(self.scale_factor());
2973 let scene = &self.frame_state.rendered_frame.scene;
2974 let mut result = None;
2975 self.core.platform_window.with_renderer(&mut |renderer| {
2976 result = Some(renderer.render_scene_to_image(scene, size));
2977 });
2978 result.unwrap_or_else(|| anyhow::bail!("platform window does not support image capture"))
2979 }
2980
2981 #[cfg(any(test, feature = "test-support"))]
2986 pub fn painted_quads(&self) -> Vec<Quad> {
2987 self.frame_state.rendered_frame.scene.quads.clone()
2988 }
2989
2990 pub fn resize(&mut self, size: Size<Pixels>) {
2992 self.core.platform_window.resize(size);
2993 }
2994
2995 pub fn is_fullscreen(&self) -> bool {
2997 self.core.platform_window.is_fullscreen()
2998 }
2999
3000 pub fn is_simple_fullscreen(&self) -> bool {
3004 self.core.platform_window.is_simple_fullscreen()
3005 }
3006
3007 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
3008 self.core.appearance = self.core.platform_window.appearance();
3009
3010 self.core
3011 .appearance_observers
3012 .clone()
3013 .retain(&(), |callback| callback(self, cx));
3014 }
3015
3016 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
3017 self.core
3018 .button_layout_observers
3019 .clone()
3020 .retain(&(), |callback| callback(self, cx));
3021 }
3022
3023 pub fn appearance(&self) -> WindowAppearance {
3025 self.core.appearance
3026 }
3027
3028 pub fn viewport_size(&self) -> Size<Pixels> {
3030 self.core.viewport_size
3031 }
3032
3033 pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
3039 self.core.platform_window.visual_viewport_bounds()
3040 }
3041
3042 pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
3047 let insets = self.core.platform_window.insets().effective();
3048 let viewport = self.viewport_size();
3049 let left = insets.left.max(Pixels::ZERO).min(viewport.width);
3050 let top = insets.top.max(Pixels::ZERO).min(viewport.height);
3051 let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
3052 let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
3053 let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
3054 let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
3055 visible.size.width = visible.size.width.max(Pixels::ZERO);
3056 visible.size.height = visible.size.height.max(Pixels::ZERO);
3057 visible
3058 }
3059
3060 pub fn request_virtual_keyboard(&self) {
3065 self.core.platform_window.show_soft_keyboard();
3066 }
3067
3068 pub fn dismiss_virtual_keyboard(&self) {
3070 self.core.platform_window.hide_soft_keyboard();
3071 }
3072
3073 pub fn is_window_active(&self) -> bool {
3075 self.core.active.get()
3076 }
3077
3078 pub fn is_window_hovered(&self) -> bool {
3082 if cfg!(any(
3083 target_os = "windows",
3084 target_os = "linux",
3085 target_os = "freebsd"
3086 )) {
3087 self.core.hovered.get()
3088 } else {
3089 self.is_window_active()
3090 }
3091 }
3092
3093 pub fn zoom_window(&self) {
3095 self.core.platform_window.zoom();
3096 }
3097
3098 pub fn show_window_menu(&self, position: Point<Pixels>) {
3100 self.core.platform_window.show_window_menu(position)
3101 }
3102
3103 pub fn start_window_move(&self) {
3108 self.core.platform_window.start_window_move()
3109 }
3110
3111 pub fn set_client_inset(&mut self, inset: Pixels) {
3113 self.core.client_inset = Some(inset);
3114 self.core.platform_window.set_client_inset(inset);
3115 }
3116
3117 pub fn client_inset(&self) -> Option<Pixels> {
3119 self.core.client_inset
3120 }
3121
3122 pub fn window_decorations(&self) -> Decorations {
3124 self.core.platform_window.window_decorations()
3125 }
3126
3127 pub fn is_resizable(&self) -> bool {
3129 self.core.is_resizable
3130 }
3131
3132 pub fn is_minimizable(&self) -> bool {
3134 self.core.is_minimizable
3135 }
3136
3137 pub fn window_controls(&self) -> WindowControls {
3139 self.core.platform_window.window_controls()
3140 }
3141
3142 pub fn set_window_title(&mut self, title: &str) {
3144 self.core.platform_window.set_title(title);
3145 self.core.a11y.set_window_title(title.to_string());
3146 }
3147
3148 #[cfg(target_os = "macos")]
3150 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
3151 self.core
3152 .platform_window
3153 .set_traffic_light_position(position);
3154 }
3155
3156 pub fn set_app_id(&mut self, app_id: &str) {
3158 self.core.platform_window.set_app_id(app_id);
3159 }
3160
3161 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
3163 self.core
3164 .platform_window
3165 .set_background_appearance(background_appearance);
3166 }
3167
3168 pub fn set_window_edited(&mut self, edited: bool) {
3170 self.core.platform_window.set_edited(edited);
3171 }
3172
3173 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
3176 self.core.platform_window.set_document_path(path);
3177 }
3178
3179 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
3181 cx.platform
3182 .displays()
3183 .into_iter()
3184 .find(|display| Some(display.id()) == self.core.display_id)
3185 }
3186
3187 pub fn show_character_palette(&self) {
3189 self.core.platform_window.show_character_palette();
3190 }
3191
3192 pub fn scale_factor(&self) -> f32 {
3196 self.core.scale_factor
3197 }
3198
3199 #[cfg(any(test, feature = "test-support"))]
3201 pub fn set_scale_factor(&mut self, scale_factor: f32) {
3202 self.core.scale_factor = scale_factor;
3203 self.sync_metrics();
3204 self.refresh();
3205 }
3206
3207 pub fn rem_size(&self) -> Pixels {
3210 self.frame_state
3211 .rem_size_override_stack
3212 .last()
3213 .copied()
3214 .unwrap_or(self.core.rem_size)
3215 }
3216
3217 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
3220 self.core.rem_size = rem_size.into();
3221 }
3222
3223 pub fn with_global_id<R>(
3226 &mut self,
3227 element_id: ElementId,
3228 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
3229 ) -> R {
3230 self.with_id(element_id, |this| {
3231 let global_id = GlobalElementId(Arc::from(&*this.frame_state.element_id_stack));
3232
3233 f(&global_id, this)
3234 })
3235 }
3236
3237 #[inline]
3239 pub fn with_id<R>(
3240 &mut self,
3241 element_id: impl Into<ElementId>,
3242 f: impl FnOnce(&mut Self) -> R,
3243 ) -> R {
3244 self.frame_state.element_id_stack.push(element_id.into());
3245 let result = f(self);
3246 self.frame_state.element_id_stack.pop();
3247 result
3248 }
3249
3250 #[inline]
3256 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
3257 where
3258 F: FnOnce(&mut Self) -> R,
3259 {
3260 self.core.invalidator.debug_assert_paint_or_prepaint();
3261
3262 if let Some(rem_size) = rem_size {
3263 self.frame_state
3264 .rem_size_override_stack
3265 .push(rem_size.into());
3266 let result = f(self);
3267 self.frame_state.rem_size_override_stack.pop();
3268 result
3269 } else {
3270 f(self)
3271 }
3272 }
3273
3274 pub fn line_height(&self) -> Pixels {
3276 self.text_style().line_height_in_pixels(self.rem_size())
3277 }
3278
3279 #[inline]
3281 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
3282 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
3283 }
3284
3285 #[inline]
3287 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
3288 let scale_factor = f64::from(self.scale_factor());
3289 round_half_toward_zero_f64(value * scale_factor) / scale_factor
3290 }
3291
3292 #[inline]
3294 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
3295 bounds.map(|c| self.pixel_snap(c))
3296 }
3297
3298 #[inline]
3300 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
3301 position.map(|c| self.pixel_snap(c))
3302 }
3303
3304 #[inline]
3305 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
3306 let scale_factor = self.scale_factor();
3307 let left = round_to_device_pixel(bounds.left().0, scale_factor);
3308 let top = round_to_device_pixel(bounds.top().0, scale_factor);
3309 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
3310 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
3311 Bounds::from_corners(
3312 point(ScaledPixels(left), ScaledPixels(top)),
3313 point(ScaledPixels(right), ScaledPixels(bottom)),
3314 )
3315 }
3316
3317 #[inline]
3319 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
3320 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
3321 }
3322
3323 #[inline]
3324 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
3325 edges.map(|e| self.snap_stroke(*e))
3326 }
3327
3328 #[inline]
3330 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
3331 let scale_factor = self.scale_factor();
3332 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
3333 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
3334 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
3335 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
3336 Bounds::from_corners(
3337 point(ScaledPixels(left), ScaledPixels(top)),
3338 point(ScaledPixels(right), ScaledPixels(bottom)),
3339 )
3340 }
3341
3342 #[inline]
3343 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
3344 ContentMask {
3345 bounds: self.cover_bounds(self.content_mask().bounds),
3346 }
3347 }
3348
3349 pub fn prevent_default(&mut self) {
3352 self.core.default_prevented = true;
3353 }
3354
3355 pub fn default_prevented(&self) -> bool {
3357 self.core.default_prevented
3358 }
3359
3360 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
3362 let node_id =
3363 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
3364 self.frame_state
3365 .rendered_frame
3366 .dispatch_tree
3367 .is_action_available(action, node_id)
3368 }
3369
3370 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
3372 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
3373 self.frame_state
3374 .rendered_frame
3375 .dispatch_tree
3376 .is_action_available(action, node_id)
3377 }
3378
3379 pub fn mouse_position(&self) -> Point<Pixels> {
3381 self.core.mouse_position
3382 }
3383
3384 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
3391 self.core.captured_hitbox = Some(hitbox_id);
3392 }
3393
3394 pub fn release_pointer(&mut self) {
3396 self.core.captured_hitbox = None;
3397 }
3398
3399 pub fn captured_hitbox(&self) -> Option<HitboxId> {
3401 self.core.captured_hitbox
3402 }
3403
3404 pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
3410 self.core.long_press_capture = Some(entity.entity_id());
3411 }
3412
3413 pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
3415 self.core.long_press_capture == Some(entity.entity_id())
3416 }
3417
3418 pub fn modifiers(&self) -> Modifiers {
3420 self.core.modifiers
3421 }
3422
3423 pub fn last_input_was_keyboard(&self) -> bool {
3426 self.core.last_input_modality == InputModality::Keyboard
3427 }
3428
3429 pub(crate) fn last_input_was_touch(&self) -> bool {
3430 self.core.last_input_modality == InputModality::Touch
3431 }
3432
3433 pub fn capslock(&self) -> Capslock {
3435 self.core.capslock
3436 }
3437
3438 #[doc(hidden)]
3445 #[profiling::function]
3446 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
3447 let pipeline = self.core.frame_pipeline.clone();
3448 pipeline.borrow_mut().draw(self, cx)
3449 }
3450
3451 pub fn begin_frame(&mut self, cx: &mut App) {
3456 #[cfg(debug_assertions)]
3457 self.frame_state.frame_phase.enter(
3458 &[FramePhase::Idle, FramePhase::Completed],
3459 FramePhase::Begun,
3460 "begin_frame",
3461 );
3462 if self.core.platform_window.prepare_frame() {
3463 self.refresh();
3464 }
3465 self.sync_metrics();
3466 self.invalidate_entities();
3467 cx.entities.clear_accessed();
3468 debug_assert!(self.frame_state.rendered_entity_stack.is_empty());
3469 self.core.invalidator.set_dirty(false);
3470 self.frame_state.requested_autoscroll = None;
3471 }
3472
3473 fn restore_input_handler(&mut self) {
3478 if let Some(input_handler) = self.core.platform_window.take_input_handler() {
3479 if let Some(slot) = self
3480 .frame_state
3481 .rendered_frame
3482 .input_handlers
3483 .iter_mut()
3484 .rev()
3485 .find(|h| h.is_none())
3486 {
3487 *slot = Some(input_handler);
3488 } else {
3489 self.frame_state
3490 .rendered_frame
3491 .input_handlers
3492 .push(Some(input_handler));
3493 }
3494 }
3495 }
3496
3497 pub fn finish_frame(&mut self, cx: &mut App) {
3507 #[cfg(debug_assertions)]
3508 self.frame_state.frame_phase.enter(
3509 &[FramePhase::Begun, FramePhase::Painted],
3510 FramePhase::Finished,
3511 "finish_frame",
3512 );
3513 self.frame_state.dirty_views.clear();
3514 self.frame_state.next_frame.window_active = self.core.active.get();
3515
3516 let focused_text_input_active = if let Some(mut input_handler) = self
3521 .frame_state
3522 .next_frame
3523 .input_handlers
3524 .iter_mut()
3525 .rev()
3526 .find_map(|h| h.take())
3527 {
3528 let accepts_text_input = input_handler.accepts_text_input(self, cx);
3529 self.core.platform_window.set_input_handler(input_handler);
3530 accepts_text_input
3531 } else {
3532 false
3533 };
3534 self.apply_text_input_configuration(cx);
3535 if focused_text_input_active != self.core.focused_text_input_active {
3536 self.core.focused_text_input_active = focused_text_input_active;
3537 self.core
3538 .platform_window
3539 .text_input_state_changed(if focused_text_input_active {
3540 TextInputStateChange::FocusGained
3541 } else {
3542 TextInputStateChange::FocusLost
3543 });
3544 }
3545
3546 self.frame_state.layout_session.clear();
3547 self.text_system().finish_frame();
3548 self.frame_state
3549 .next_frame
3550 .finish(&mut self.frame_state.rendered_frame);
3551 }
3552
3553 pub fn complete_frame(&mut self, cx: &mut App) -> Option<FocusId> {
3561 #[cfg(debug_assertions)]
3562 self.frame_state.frame_phase.enter(
3563 &[FramePhase::Finished],
3564 FramePhase::Completed,
3565 "complete_frame",
3566 );
3567 self.core.invalidator.set_phase(DrawPhase::Focus);
3568 let previous_focus_path = self.frame_state.rendered_frame.focus_path();
3569 let previous_window_active = self.frame_state.rendered_frame.window_active;
3570 mem::swap(
3571 &mut self.frame_state.rendered_frame,
3572 &mut self.frame_state.next_frame,
3573 );
3574 self.frame_state.next_frame.clear();
3575 let current_focus_path = self.frame_state.rendered_frame.focus_path();
3576 let current_window_active = self.frame_state.rendered_frame.window_active;
3577 let mut focus_before_listeners = self.core.focus;
3578
3579 if previous_focus_path != current_focus_path
3580 || previous_window_active != current_window_active
3581 {
3582 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
3583 self.frame_state.focus_lost_path = previous_focus_path.clone();
3584 self.core
3585 .focus_lost_listeners
3586 .clone()
3587 .retain(&(), |listener| listener(self, cx));
3588 self.frame_state.focus_lost_path = SmallVec::new();
3589 focus_before_listeners = self.core.focus;
3594 }
3595
3596 let event = WindowFocusEvent {
3597 previous_focus_path: if previous_window_active {
3598 previous_focus_path
3599 } else {
3600 Default::default()
3601 },
3602 current_focus_path: if current_window_active {
3603 current_focus_path
3604 } else {
3605 Default::default()
3606 },
3607 };
3608 self.core
3609 .focus_listeners
3610 .clone()
3611 .retain(&(), |listener| listener(&event, self, cx));
3612 }
3613
3614 focus_before_listeners
3615 }
3616
3617 pub fn end_frame(&mut self, cx: &mut App, focus_before_listeners: Option<FocusId>) {
3621 #[cfg(debug_assertions)]
3622 self.frame_state
3623 .frame_phase
3624 .enter(&[FramePhase::Completed], FramePhase::Idle, "end_frame");
3625 debug_assert!(self.frame_state.rendered_entity_stack.is_empty());
3626 self.record_entities_accessed(cx);
3627 self.reset_cursor_style(cx);
3628 self.core.refreshing = false;
3629 self.core.invalidator.set_phase(DrawPhase::None);
3630 if self.core.focus != focus_before_listeners {
3635 self.refresh();
3636 }
3637 self.core.needs_present.set(true);
3638 }
3639 fn record_entities_accessed(&mut self, cx: &mut App) {
3640 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3641 let mut entities = mem::take(entities_ref.deref_mut());
3642 let handle = self.core.handle;
3643 cx.record_entities_accessed(
3644 handle,
3645 self.core.invalidator.clone(),
3647 &entities,
3648 );
3649 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3650 mem::swap(&mut entities, entities_ref.deref_mut());
3651 }
3652
3653 fn invalidate_entities(&mut self) {
3654 let mut views = self.core.invalidator.take_views();
3655 for entity in views.drain() {
3656 self.mark_view_dirty(entity);
3657 }
3658 self.core.invalidator.replace_views(views);
3659 }
3660
3661 #[profiling::function]
3662 fn present(&mut self) {
3663 #[cfg(feature = "profiler")]
3664 let _foreground_turn = profiler::journal::foreground_turn();
3665 #[cfg(feature = "profiler")]
3666 let present_start = Instant::now();
3667 self.core
3668 .platform_window
3669 .present(&mut |renderer| renderer.draw(&self.frame_state.rendered_frame.scene));
3670 #[cfg(feature = "profiler")]
3671 self.core.window_profiler.record_present(
3672 present_start,
3673 Instant::now(),
3674 self.core.active.get(),
3675 !self.core.next_frame_callbacks.borrow().is_empty(),
3676 );
3677 self.core.needs_present.set(false);
3678 profiling::finish_frame!();
3679 }
3680
3681 #[cfg(all(test, feature = "profiler"))]
3683 pub(crate) fn present_if_needed(&mut self) {
3684 if self.core.needs_present.get() {
3685 self.present();
3686 }
3687 }
3688
3689 #[cfg(feature = "profiler")]
3691 pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
3692 self.core.window_profiler.input_latency_snapshot()
3693 }
3694
3695 #[cfg(feature = "profiler")]
3697 pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
3698 self.core.window_profiler.frame_duration_snapshot()
3699 }
3700
3701 #[cfg(feature = "profiler")]
3703 pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
3704 self.core.debug_frame_overlay.mode()
3705 }
3706
3707 #[cfg(feature = "profiler")]
3709 pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
3710 self.core.debug_frame_overlay.set_mode(mode);
3711 self.refresh();
3712 }
3713
3714 #[cfg(feature = "profiler")]
3717 pub fn cycle_debug_frame_overlay_mode(&mut self) {
3718 self.set_debug_frame_overlay_mode(self.core.debug_frame_overlay.mode().next());
3719 }
3720
3721 #[cfg(feature = "profiler")]
3724 pub fn reset_debug_frame_overlay_stats(&mut self) {
3725 self.core.debug_frame_overlay.reset_stats();
3726 self.refresh();
3727 }
3728
3729 pub fn evaluate_roots(&mut self, cx: &mut App) -> PreparedRoots {
3735 #[cfg(debug_assertions)]
3736 self.frame_state.frame_phase.enter(
3737 &[FramePhase::Begun],
3738 FramePhase::Evaluated,
3739 "evaluate_roots",
3740 );
3741 let root = self.core.root.as_ref().unwrap().clone().into_any_element();
3742
3743 let mut prompt = None;
3746 let mut drag = None;
3747 if let Some(handle) = self.core.prompt.take() {
3748 prompt = Some(handle.view.any_view().into_any_element());
3749 self.core.prompt = Some(handle);
3750 } else if let Some(active_drag) = cx.active_drag.take() {
3751 let origin = self.mouse_position() - active_drag.cursor_offset;
3752 drag = Some((active_drag.view.clone().into_any_element(), origin));
3753 cx.active_drag = Some(active_drag);
3754 }
3755
3756 PreparedRoots {
3757 root,
3758 prompt,
3759 tooltip: None,
3760 drag,
3761 inspector: None,
3762 }
3763 }
3764
3765 pub fn layout_roots(&mut self, roots: &mut PreparedRoots, cx: &mut App) {
3768 #[cfg(debug_assertions)]
3769 self.frame_state.frame_phase.enter(
3770 &[FramePhase::Evaluated],
3771 FramePhase::LaidOut,
3772 "layout_roots",
3773 );
3774 self.core.invalidator.set_phase(DrawPhase::Prepaint);
3775 self.frame_state.tooltip_bounds.take();
3776
3777 self.core.a11y.sync_active_flag();
3778 if self.core.a11y.is_active() {
3779 self.core.a11y.begin_frame();
3780 }
3781
3782 #[cfg(any(feature = "inspector", debug_assertions))]
3783 let inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
3784 let root_size = {
3785 #[cfg(any(feature = "inspector", debug_assertions))]
3786 {
3787 if self.core.inspector.is_some() {
3788 let mut size = self.core.viewport_size;
3789 size.width = (size.width - inspector_width).max(px(0.0));
3790 size
3791 } else {
3792 self.core.viewport_size
3793 }
3794 }
3795 #[cfg(not(any(feature = "inspector", debug_assertions)))]
3796 {
3797 self.core.viewport_size
3798 }
3799 };
3800
3801 let scale_factor = self.scale_factor();
3805 let root_layout_id = roots.root.request_layout(self, cx);
3806 self.frame_state.layout_session.stretch_auto_size_to_fill(
3807 root_layout_id,
3808 root_size,
3809 scale_factor,
3810 );
3811 roots
3812 .root
3813 .prepaint_as_root(Point::default(), root_size.into(), self, cx);
3814
3815 #[cfg(any(feature = "inspector", debug_assertions))]
3816 {
3817 roots.inspector = self.prepaint_inspector(inspector_width, cx);
3818 }
3819
3820 self.prepaint_deferred_draws(cx);
3821
3822 if let Some(prompt) = roots.prompt.as_mut() {
3823 let prompt_layout_id = prompt.request_layout(self, cx);
3824 self.frame_state.layout_session.stretch_auto_size_to_fill(
3825 prompt_layout_id,
3826 root_size,
3827 scale_factor,
3828 );
3829 prompt.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3830 } else if let Some((drag, origin)) = roots.drag.as_mut() {
3831 drag.prepaint_as_root(*origin, AvailableSpace::min_size(), self, cx);
3832 } else {
3833 roots.tooltip = self.prepaint_tooltip(cx);
3834 }
3835
3836 self.core.mouse_hit_test = self
3837 .frame_state
3838 .next_frame
3839 .hit_test(self.core.mouse_position);
3840 }
3841
3842 pub fn paint_roots(&mut self, mut roots: PreparedRoots, cx: &mut App) {
3844 #[cfg(debug_assertions)]
3845 self.frame_state.frame_phase.enter(
3846 &[FramePhase::LaidOut],
3847 FramePhase::Painted,
3848 "paint_roots",
3849 );
3850 self.core.invalidator.set_phase(DrawPhase::Paint);
3851 roots.root.paint(self, cx);
3852
3853 #[cfg(any(feature = "inspector", debug_assertions))]
3854 self.paint_inspector(roots.inspector.take(), cx);
3855
3856 self.paint_deferred_draws(cx);
3857
3858 if let Some(mut prompt) = roots.prompt.take() {
3859 prompt.paint(self, cx);
3860 } else if let Some((mut drag, _)) = roots.drag.take() {
3861 drag.paint(self, cx);
3862 } else if let Some(mut tooltip) = roots.tooltip.take() {
3863 tooltip.paint(self, cx);
3864 }
3865
3866 #[cfg(any(feature = "inspector", debug_assertions))]
3867 self.paint_inspector_hitbox(cx);
3868
3869 let a11y_active_start_of_frame = self.core.a11y.is_active();
3871 self.core.a11y.sync_active_flag();
3872 let a11y_active_end_of_frame = self.core.a11y.is_active();
3873
3874 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
3875
3876 if a11y_active_start_of_frame {
3877 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
3880 viewport_size: self.core.viewport_size,
3881 scale_factor: self.core.scale_factor,
3882 tab_stop_count: self.frame_state.next_frame.tab_stops.tab_stop_count(),
3883 };
3884 let tree_update = self.core.a11y.end_frame(frame_info);
3886
3887 if should_send_a11y_update {
3888 log::debug!(
3889 "Sending a11y tree update: {} nodes",
3890 tree_update.nodes.len()
3891 );
3892 self.core.platform_window.a11y_tree_update(tree_update);
3893 }
3894 }
3895 }
3896
3897 pub fn draw_roots(&mut self, cx: &mut App) {
3903 let mut roots = self.evaluate_roots(cx);
3904 self.layout_roots(&mut roots, cx);
3905 self.paint_roots(roots, cx);
3906 }
3907
3908 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
3909 for tooltip_request_index in (0..self.frame_state.next_frame.tooltip_requests.len()).rev() {
3911 let Some(Some(tooltip_request)) = self
3912 .frame_state
3913 .next_frame
3914 .tooltip_requests
3915 .get(tooltip_request_index)
3916 .cloned()
3917 else {
3918 log::error!("Unexpectedly absent TooltipRequest");
3919 continue;
3920 };
3921 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
3922 let mouse_position = tooltip_request.tooltip.mouse_position;
3923 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
3924
3925 let mut tooltip_bounds =
3926 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
3927 let window_bounds = Bounds {
3928 origin: Point::default(),
3929 size: self.viewport_size(),
3930 };
3931
3932 if tooltip_bounds.right() > window_bounds.right() {
3933 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
3934 if new_x >= Pixels::ZERO {
3935 tooltip_bounds.origin.x = new_x;
3936 } else {
3937 tooltip_bounds.origin.x = cmp::max(
3938 Pixels::ZERO,
3939 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
3940 );
3941 }
3942 }
3943
3944 if tooltip_bounds.bottom() > window_bounds.bottom() {
3945 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
3946 if new_y >= Pixels::ZERO {
3947 tooltip_bounds.origin.y = new_y;
3948 } else {
3949 tooltip_bounds.origin.y = cmp::max(
3950 Pixels::ZERO,
3951 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
3952 );
3953 }
3954 }
3955
3956 let is_visible =
3960 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
3961 if !is_visible {
3962 continue;
3963 }
3964
3965 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
3966 element.prepaint(window, cx)
3967 });
3968
3969 self.frame_state.tooltip_bounds = Some(TooltipBounds {
3970 id: tooltip_request.id,
3971 bounds: tooltip_bounds,
3972 });
3973 return Some(element);
3974 }
3975 None
3976 }
3977
3978 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
3979 assert_eq!(self.frame_state.element_id_stack.len(), 0);
3980
3981 let mut round_start = 0;
3992 let mut depth = 0;
3993 loop {
3994 let round_end = self.frame_state.next_frame.deferred_draws.len();
3995 if round_start == round_end {
3996 break;
3997 }
3998 assert!(depth < 10, "Exceeded maximum (10) deferred depth");
4000 depth += 1;
4001
4002 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
4004 traversal_order
4005 .sort_by_key(|ix| self.frame_state.next_frame.deferred_draws[*ix].priority);
4006
4007 for deferred_draw_ix in traversal_order {
4008 let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
4009 let deferred_draw =
4010 &mut self.frame_state.next_frame.deferred_draws[deferred_draw_ix];
4011 self.frame_state
4012 .element_id_stack
4013 .clone_from(&deferred_draw.element_id_stack);
4014 self.frame_state
4015 .text_style_stack
4016 .clone_from(&deferred_draw.text_style_stack);
4017 (
4018 deferred_draw.element.take(),
4019 deferred_draw.parent_node,
4020 deferred_draw.current_view,
4021 deferred_draw.rem_size,
4022 deferred_draw.absolute_offset,
4023 deferred_draw.prepaint_range.clone(),
4024 )
4025 };
4026 self.frame_state
4027 .next_frame
4028 .dispatch_tree
4029 .set_active_node(parent_node);
4030
4031 let prepaint_start = self.prepaint_index();
4032 if let Some(mut element) = element {
4033 self.with_rendered_view(current_view, |window| {
4034 window.with_rem_size(Some(rem_size), |window| {
4035 window.with_absolute_element_offset(absolute_offset, |window| {
4036 element.prepaint(window, cx);
4037 });
4038 });
4039 });
4040 self.frame_state.next_frame.deferred_draws[deferred_draw_ix].element =
4041 Some(element);
4042 } else {
4043 self.reuse_prepaint(prepaint_range);
4044 }
4045 let prepaint_end = self.prepaint_index();
4046 self.frame_state.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
4047 prepaint_start..prepaint_end;
4048 }
4049
4050 self.frame_state.element_id_stack.clear();
4051 self.frame_state.text_style_stack.clear();
4052 round_start = round_end;
4053 }
4054 }
4055
4056 fn paint_deferred_draws(&mut self, cx: &mut App) {
4057 assert_eq!(self.frame_state.element_id_stack.len(), 0);
4058
4059 if self.frame_state.next_frame.deferred_draws.len() == 0 {
4062 return;
4063 }
4064
4065 let traversal_order = self.deferred_draw_traversal_order();
4066 let mut deferred_draws = mem::take(&mut self.frame_state.next_frame.deferred_draws);
4067 for deferred_draw_ix in traversal_order {
4068 let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
4069 self.frame_state
4070 .element_id_stack
4071 .clone_from(&deferred_draw.element_id_stack);
4072 self.frame_state
4073 .next_frame
4074 .dispatch_tree
4075 .set_active_node(deferred_draw.parent_node);
4076
4077 let paint_start = self.paint_index();
4078 let content_mask = deferred_draw.content_mask;
4079 if let Some(element) = deferred_draw.element.as_mut() {
4080 self.with_rendered_view(deferred_draw.current_view, |window| {
4081 window.with_content_mask(content_mask, |window| {
4082 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
4083 element.paint(window, cx);
4084 });
4085 })
4086 })
4087 } else {
4088 self.reuse_paint(deferred_draw.paint_range.clone());
4089 }
4090 let paint_end = self.paint_index();
4091 deferred_draw.paint_range = paint_start..paint_end;
4092 }
4093 self.frame_state.next_frame.deferred_draws = deferred_draws;
4094 self.frame_state.element_id_stack.clear();
4095 }
4096
4097 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
4098 let deferred_count = self.frame_state.next_frame.deferred_draws.len();
4099 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
4100 sorted_indices.sort_by_key(|ix| self.frame_state.next_frame.deferred_draws[*ix].priority);
4101 sorted_indices
4102 }
4103
4104 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
4105 PrepaintStateIndex {
4106 hitboxes_index: self.frame_state.next_frame.hitboxes.len(),
4107 tooltips_index: self.frame_state.next_frame.tooltip_requests.len(),
4108 deferred_draws_index: self.frame_state.next_frame.deferred_draws.len(),
4109 dispatch_tree_index: self.frame_state.next_frame.dispatch_tree.len(),
4110 accessed_element_states_index: self
4111 .frame_state
4112 .next_frame
4113 .accessed_element_states
4114 .len(),
4115 line_layout_index: self.core.text_system.layout_index(),
4116 }
4117 }
4118
4119 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
4120 self.frame_state.next_frame.hitboxes.extend(
4121 self.frame_state.rendered_frame.hitboxes
4122 [range.start.hitboxes_index..range.end.hitboxes_index]
4123 .iter()
4124 .cloned(),
4125 );
4126 self.frame_state.next_frame.tooltip_requests.extend(
4127 self.frame_state.rendered_frame.tooltip_requests
4128 [range.start.tooltips_index..range.end.tooltips_index]
4129 .iter_mut()
4130 .map(|request| request.take()),
4131 );
4132 self.frame_state.next_frame.accessed_element_states.extend(
4133 self.frame_state.rendered_frame.accessed_element_states[range
4134 .start
4135 .accessed_element_states_index
4136 ..range.end.accessed_element_states_index]
4137 .iter()
4138 .map(|(id, type_id)| (id.clone(), *type_id)),
4139 );
4140 self.core
4141 .text_system
4142 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
4143
4144 let reused_subtree = self.frame_state.next_frame.dispatch_tree.reuse_subtree(
4145 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
4146 &mut self.frame_state.rendered_frame.dispatch_tree,
4147 self.core.focus,
4148 );
4149
4150 if reused_subtree.contains_focus() {
4151 self.frame_state.next_frame.focus = self.core.focus;
4152 }
4153
4154 self.frame_state.next_frame.deferred_draws.extend(
4155 self.frame_state.rendered_frame.deferred_draws
4156 [range.start.deferred_draws_index..range.end.deferred_draws_index]
4157 .iter()
4158 .map(|deferred_draw| DeferredDraw {
4159 current_view: deferred_draw.current_view,
4160 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
4161 element_id_stack: deferred_draw.element_id_stack.clone(),
4162 text_style_stack: deferred_draw.text_style_stack.clone(),
4163 content_mask: deferred_draw.content_mask,
4164 rem_size: deferred_draw.rem_size,
4165 priority: deferred_draw.priority,
4166 element: None,
4167 absolute_offset: deferred_draw.absolute_offset,
4168 prepaint_range: deferred_draw.prepaint_range.clone(),
4169 paint_range: deferred_draw.paint_range.clone(),
4170 }),
4171 );
4172 }
4173
4174 pub(crate) fn paint_index(&self) -> PaintIndex {
4175 PaintIndex {
4176 scene_index: self.frame_state.next_frame.scene.len(),
4177 mouse_listeners_index: self.frame_state.next_frame.mouse_listeners.len(),
4178 input_handlers_index: self.frame_state.next_frame.input_handlers.len(),
4179 cursor_styles_index: self.frame_state.next_frame.cursor_styles.len(),
4180 accessed_element_states_index: self
4181 .frame_state
4182 .next_frame
4183 .accessed_element_states
4184 .len(),
4185 tab_handle_index: self.frame_state.next_frame.tab_stops.paint_index(),
4186 line_layout_index: self.core.text_system.layout_index(),
4187 }
4188 }
4189
4190 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
4191 self.frame_state.next_frame.cursor_styles.extend(
4192 self.frame_state.rendered_frame.cursor_styles
4193 [range.start.cursor_styles_index..range.end.cursor_styles_index]
4194 .iter()
4195 .cloned(),
4196 );
4197 self.frame_state.next_frame.input_handlers.extend(
4198 self.frame_state.rendered_frame.input_handlers
4199 [range.start.input_handlers_index..range.end.input_handlers_index]
4200 .iter_mut()
4201 .map(|handler| handler.take()),
4202 );
4203 self.frame_state.next_frame.mouse_listeners.extend(
4204 self.frame_state.rendered_frame.mouse_listeners
4205 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
4206 .iter_mut()
4207 .map(|listener| listener.take()),
4208 );
4209 self.frame_state.next_frame.accessed_element_states.extend(
4210 self.frame_state.rendered_frame.accessed_element_states[range
4211 .start
4212 .accessed_element_states_index
4213 ..range.end.accessed_element_states_index]
4214 .iter()
4215 .map(|(id, type_id)| (id.clone(), *type_id)),
4216 );
4217 self.frame_state.next_frame.tab_stops.replay(
4218 &self.frame_state.rendered_frame.tab_stops.insertion_history
4219 [range.start.tab_handle_index..range.end.tab_handle_index],
4220 );
4221
4222 self.core
4223 .text_system
4224 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
4225 self.frame_state.next_frame.scene.replay(
4226 range.start.scene_index..range.end.scene_index,
4227 &self.frame_state.rendered_frame.scene,
4228 );
4229 }
4230
4231 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
4235 where
4236 F: FnOnce(&mut Self) -> R,
4237 {
4238 self.core.invalidator.debug_assert_paint_or_prepaint();
4239 if let Some(style) = style {
4240 self.frame_state.text_style_stack.push(style);
4241 let result = f(self);
4242 self.frame_state.text_style_stack.pop();
4243 result
4244 } else {
4245 f(self)
4246 }
4247 }
4248
4249 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
4252 self.core.invalidator.debug_assert_paint();
4253 self.frame_state
4254 .next_frame
4255 .cursor_styles
4256 .push(CursorStyleRequest {
4257 hitbox_id: Some(hitbox.id),
4258 style,
4259 });
4260 }
4261
4262 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
4267 self.core.invalidator.debug_assert_paint();
4268 self.frame_state
4269 .next_frame
4270 .cursor_styles
4271 .push(CursorStyleRequest {
4272 hitbox_id: None,
4273 style,
4274 })
4275 }
4276
4277 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
4280 self.core.invalidator.debug_assert_prepaint();
4281 let id = TooltipId(post_inc(&mut self.frame_state.next_tooltip_id.0));
4282 self.frame_state
4283 .next_frame
4284 .tooltip_requests
4285 .push(Some(TooltipRequest { id, tooltip }));
4286 id
4287 }
4288
4289 #[inline]
4294 pub fn with_content_mask<R>(
4295 &mut self,
4296 mask: Option<ContentMask<Pixels>>,
4297 f: impl FnOnce(&mut Self) -> R,
4298 ) -> R {
4299 self.core.invalidator.debug_assert_paint_or_prepaint();
4300 if let Some(mask) = mask {
4301 let mask = mask.intersect(&self.content_mask());
4302 self.frame_state.content_mask_stack.push(mask);
4303 let result = f(self);
4304 self.frame_state.content_mask_stack.pop();
4305 result
4306 } else {
4307 f(self)
4308 }
4309 }
4310
4311 pub fn with_element_offset<R>(
4314 &mut self,
4315 offset: Point<Pixels>,
4316 f: impl FnOnce(&mut Self) -> R,
4317 ) -> R {
4318 self.core.invalidator.debug_assert_prepaint();
4319
4320 if offset.is_zero() {
4321 return f(self);
4322 };
4323
4324 let abs_offset = self.element_offset() + offset;
4325 self.with_absolute_element_offset(abs_offset, f)
4326 }
4327
4328 pub fn with_absolute_element_offset<R>(
4332 &mut self,
4333 offset: Point<Pixels>,
4334 f: impl FnOnce(&mut Self) -> R,
4335 ) -> R {
4336 self.core.invalidator.debug_assert_prepaint();
4337 self.frame_state.element_offset_stack.push(offset);
4338 let result = f(self);
4339 self.frame_state.element_offset_stack.pop();
4340 result
4341 }
4342
4343 pub(crate) fn with_element_opacity<R>(
4344 &mut self,
4345 opacity: Option<f32>,
4346 f: impl FnOnce(&mut Self) -> R,
4347 ) -> R {
4348 self.core.invalidator.debug_assert_paint_or_prepaint();
4349
4350 let Some(opacity) = opacity else {
4351 return f(self);
4352 };
4353
4354 let previous_opacity = self.frame_state.element_opacity;
4355 self.frame_state.element_opacity = previous_opacity * opacity;
4356 let result = f(self);
4357 self.frame_state.element_opacity = previous_opacity;
4358 result
4359 }
4360
4361 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
4367 self.core.invalidator.debug_assert_prepaint();
4368 let index = self.prepaint_index();
4369 let result = f(self);
4370 if result.is_err() {
4371 self.frame_state
4372 .next_frame
4373 .hitboxes
4374 .truncate(index.hitboxes_index);
4375 self.frame_state
4376 .next_frame
4377 .tooltip_requests
4378 .truncate(index.tooltips_index);
4379 self.frame_state
4380 .next_frame
4381 .deferred_draws
4382 .truncate(index.deferred_draws_index);
4383 self.frame_state
4384 .next_frame
4385 .dispatch_tree
4386 .truncate(index.dispatch_tree_index);
4387 self.frame_state
4388 .next_frame
4389 .accessed_element_states
4390 .truncate(index.accessed_element_states_index);
4391 self.core
4392 .text_system
4393 .truncate_layouts(index.line_layout_index);
4394 }
4395 result
4396 }
4397
4398 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
4404 self.core.invalidator.debug_assert_prepaint();
4405 self.frame_state.requested_autoscroll = Some(bounds);
4406 }
4407
4408 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
4411 self.core.invalidator.debug_assert_prepaint();
4412 self.frame_state.requested_autoscroll.take()
4413 }
4414
4415 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4421 cx.asset_entry::<A>(source).use_by(self.current_view())
4422 }
4423
4424 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4430 cx.fetch_asset::<A>(source)
4431 }
4432 pub fn element_offset(&self) -> Point<Pixels> {
4435 self.core.invalidator.debug_assert_prepaint();
4436 self.frame_state
4437 .element_offset_stack
4438 .last()
4439 .copied()
4440 .unwrap_or_default()
4441 }
4442
4443 #[inline]
4446 pub(crate) fn element_opacity(&self) -> f32 {
4447 self.core.invalidator.debug_assert_paint_or_prepaint();
4448 self.frame_state.element_opacity
4449 }
4450
4451 pub fn content_mask(&self) -> ContentMask<Pixels> {
4453 self.core.invalidator.debug_assert_paint_or_prepaint();
4454 self.frame_state
4455 .content_mask_stack
4456 .last()
4457 .cloned()
4458 .unwrap_or_else(|| ContentMask {
4459 bounds: Bounds {
4460 origin: Point::default(),
4461 size: self.core.viewport_size,
4462 },
4463 })
4464 }
4465
4466 pub fn with_element_namespace<R>(
4469 &mut self,
4470 element_id: impl Into<ElementId>,
4471 f: impl FnOnce(&mut Self) -> R,
4472 ) -> R {
4473 self.frame_state.element_id_stack.push(element_id.into());
4474 let result = f(self);
4475 self.frame_state.element_id_stack.pop();
4476 result
4477 }
4478
4479 pub fn use_keyed_state<S: 'static>(
4481 &mut self,
4482 key: impl Into<ElementId>,
4483 cx: &mut App,
4484 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4485 ) -> Entity<S> {
4486 let current_view = self.current_view();
4487 self.with_global_id(key.into(), |global_id, window| {
4488 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
4489 if let Some(state) = state {
4490 (state.clone(), state)
4491 } else {
4492 let new_state = cx.new(|cx| init(window, cx));
4493 cx.observe(&new_state, move |_, cx| {
4494 cx.notify(current_view);
4495 })
4496 .detach();
4497 (new_state.clone(), new_state)
4498 }
4499 })
4500 })
4501 }
4502
4503 #[track_caller]
4509 pub fn use_state<S: 'static>(
4510 &mut self,
4511 cx: &mut App,
4512 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4513 ) -> Entity<S> {
4514 self.use_keyed_state(
4515 ElementId::CodeLocation(*core::panic::Location::caller()),
4516 cx,
4517 init,
4518 )
4519 }
4520
4521 pub fn with_element_state<S, R>(
4526 &mut self,
4527 global_id: &GlobalElementId,
4528 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
4529 ) -> R
4530 where
4531 S: 'static,
4532 {
4533 self.core.invalidator.debug_assert_paint_or_prepaint();
4534
4535 let key = (global_id.clone(), TypeId::of::<S>());
4536 self.frame_state
4537 .next_frame
4538 .accessed_element_states
4539 .push(key.clone());
4540
4541 if let Some(any) = self
4542 .frame_state
4543 .next_frame
4544 .element_states
4545 .remove(&key)
4546 .or_else(|| self.frame_state.rendered_frame.element_states.remove(&key))
4547 {
4548 let ElementStateBox {
4549 inner,
4550 #[cfg(debug_assertions)]
4551 type_name,
4552 } = any;
4553 let mut state_box = inner
4555 .downcast::<Option<S>>()
4556 .map_err(|_| {
4557 #[cfg(debug_assertions)]
4558 {
4559 anyhow::anyhow!(
4560 "invalid element state type for id, requested {:?}, actual: {:?}",
4561 std::any::type_name::<S>(),
4562 type_name
4563 )
4564 }
4565
4566 #[cfg(not(debug_assertions))]
4567 {
4568 anyhow::anyhow!(
4569 "invalid element state type for id, requested {:?}",
4570 std::any::type_name::<S>(),
4571 )
4572 }
4573 })
4574 .unwrap();
4575
4576 let state = state_box.take().expect(
4577 "reentrant call to with_element_state for the same state type and element id",
4578 );
4579 let (result, state) = f(Some(state), self);
4580 state_box.replace(state);
4581 self.frame_state.next_frame.element_states.insert(
4582 key,
4583 ElementStateBox {
4584 inner: state_box,
4585 #[cfg(debug_assertions)]
4586 type_name,
4587 },
4588 );
4589 result
4590 } else {
4591 let (result, state) = f(None, self);
4592 self.frame_state.next_frame.element_states.insert(
4593 key,
4594 ElementStateBox {
4595 inner: Box::new(Some(state)),
4596 #[cfg(debug_assertions)]
4597 type_name: std::any::type_name::<S>(),
4598 },
4599 );
4600 result
4601 }
4602 }
4603
4604 pub fn with_optional_element_state<S, R>(
4611 &mut self,
4612 global_id: Option<&GlobalElementId>,
4613 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
4614 ) -> R
4615 where
4616 S: 'static,
4617 {
4618 self.core.invalidator.debug_assert_paint_or_prepaint();
4619
4620 if let Some(global_id) = global_id {
4621 self.with_element_state(global_id, |state, cx| {
4622 let (result, state) = f(Some(state), cx);
4623 let state =
4624 state.expect("you must return some state when you pass some element id");
4625 (result, state)
4626 })
4627 } else {
4628 let (result, state) = f(None, self);
4629 debug_assert!(
4630 state.is_none(),
4631 "you must not return an element state when passing None for the global id"
4632 );
4633 result
4634 }
4635 }
4636
4637 #[inline]
4639 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
4640 if let Some(index) = index {
4641 self.frame_state.next_frame.tab_stops.begin_group(index);
4642 let result = f(self);
4643 self.frame_state.next_frame.tab_stops.end_group();
4644 result
4645 } else {
4646 f(self)
4647 }
4648 }
4649
4650 pub fn defer_draw(
4659 &mut self,
4660 element: AnyElement,
4661 absolute_offset: Point<Pixels>,
4662 priority: usize,
4663 content_mask: Option<ContentMask<Pixels>>,
4664 ) {
4665 self.core.invalidator.debug_assert_prepaint();
4666 let parent_node = self
4667 .frame_state
4668 .next_frame
4669 .dispatch_tree
4670 .active_node_id()
4671 .unwrap();
4672 self.frame_state
4673 .next_frame
4674 .deferred_draws
4675 .push(DeferredDraw {
4676 current_view: self.current_view(),
4677 parent_node,
4678 element_id_stack: self.frame_state.element_id_stack.clone(),
4679 text_style_stack: self.frame_state.text_style_stack.clone(),
4680 content_mask,
4681 rem_size: self.rem_size(),
4682 priority,
4683 element: Some(element),
4684 absolute_offset,
4685 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
4686 paint_range: PaintIndex::default()..PaintIndex::default(),
4687 });
4688 }
4689
4690 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
4696 self.core.invalidator.debug_assert_paint();
4697
4698 let content_mask = self.content_mask();
4699 let clipped_bounds = bounds.intersect(&content_mask.bounds);
4700 if !clipped_bounds.is_empty() {
4701 self.frame_state
4702 .next_frame
4703 .scene
4704 .push_layer(self.cover_bounds(clipped_bounds));
4705 }
4706
4707 let result = f(self);
4708
4709 if !clipped_bounds.is_empty() {
4710 self.frame_state.next_frame.scene.pop_layer();
4711 }
4712
4713 result
4714 }
4715
4716 pub fn paint_drop_shadows(
4723 &mut self,
4724 bounds: Bounds<Pixels>,
4725 corner_radii: Corners<Pixels>,
4726 shadows: &[BoxShadow],
4727 ) {
4728 self.core.invalidator.debug_assert_paint();
4729
4730 let scale_factor = self.scale_factor();
4731 let content_mask = self.snapped_content_mask();
4732 let opacity = self.element_opacity();
4733 let element_bounds = self.cover_bounds(bounds);
4734 let element_corner_radii = corner_radii.scale(scale_factor);
4735 for shadow in shadows {
4736 if shadow.inset {
4737 continue;
4738 }
4739 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
4740 self.frame_state.next_frame.scene.insert_primitive(Shadow {
4741 order: 0,
4742 blur_radius: shadow.blur_radius.scale(scale_factor),
4743 bounds: self.cover_bounds(shadow_bounds),
4744 content_mask,
4745 corner_radii: corner_radii.scale(scale_factor),
4746 color: shadow.color.opacity(opacity),
4747 element_bounds,
4748 element_corner_radii,
4749 inset: 0,
4750 pad: 0,
4751 });
4752 }
4753 }
4754
4755 pub fn paint_inset_shadows(
4760 &mut self,
4761 bounds: Bounds<Pixels>,
4762 corner_radii: Corners<Pixels>,
4763 shadows: &[BoxShadow],
4764 ) {
4765 self.core.invalidator.debug_assert_paint();
4766
4767 let scale_factor = self.scale_factor();
4768 let content_mask = self.snapped_content_mask();
4769 let opacity = self.element_opacity();
4770 let element_bounds = self.cover_bounds(bounds);
4771 let element_corner_radii = corner_radii.scale(scale_factor);
4772 for shadow in shadows {
4773 if !shadow.inset {
4774 continue;
4775 }
4776 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
4777 let zero = Pixels::ZERO;
4780 let hole_corner_radii = Corners {
4781 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
4782 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
4783 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
4784 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
4785 };
4786 self.frame_state.next_frame.scene.insert_primitive(Shadow {
4787 order: 0,
4788 blur_radius: shadow.blur_radius.scale(scale_factor),
4789 bounds: self.cover_bounds(hole),
4790 content_mask,
4791 corner_radii: hole_corner_radii.scale(scale_factor),
4792 color: shadow.color.opacity(opacity),
4793 element_bounds,
4794 element_corner_radii,
4795 inset: 1,
4796 pad: 0,
4797 });
4798 }
4799 }
4800
4801 fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
4802 let radii = &quad.corner_radii;
4803 let widths = &quad.border_widths;
4804 let edge_radii = Edges {
4805 top: radii.top_left.max(radii.top_right),
4806 right: radii.top_right.max(radii.bottom_right),
4807 bottom: radii.bottom_left.max(radii.bottom_right),
4808 left: radii.top_left.max(radii.bottom_left),
4809 };
4810
4811 let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
4812 let inset_bounds = |top_left_inset, bottom_right_inset| {
4813 Bounds::from_corners(
4814 quad.bounds.origin + top_left_inset + antialias_inset,
4815 quad.bounds.bottom_right() - bottom_right_inset - antialias_inset,
4816 )
4817 };
4818
4819 let horizontal_band = inset_bounds(
4822 point(widths.left, widths.top.max(edge_radii.top)),
4823 point(widths.right, widths.bottom.max(edge_radii.bottom)),
4824 );
4825 let vertical_band = inset_bounds(
4826 point(widths.left.max(edge_radii.left), widths.top),
4827 point(widths.right.max(edge_radii.right), widths.bottom),
4828 );
4829
4830 let area = |bounds: &Bounds<ScaledPixels>| {
4831 bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.)
4832 };
4833 if area(&horizontal_band) >= area(&vertical_band) {
4834 horizontal_band
4835 } else {
4836 vertical_band
4837 }
4838 }
4839
4840 pub fn paint_quad(&mut self, quad: PaintQuad) {
4851 self.core.invalidator.debug_assert_paint();
4852
4853 let opacity = self.element_opacity();
4854 let snapped_bounds = self.snap_bounds(quad.bounds);
4855 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
4856 let quad = Quad {
4857 order: 0,
4858 bounds: snapped_bounds,
4859 content_mask: self.snapped_content_mask(),
4860 background: quad.background.opacity(opacity),
4861 border_color: quad.border_color.opacity(opacity),
4862 corner_radii: quad.corner_radii.scale(self.scale_factor()),
4863 border_widths: snapped_border_widths,
4864 border_style: quad.border_style,
4865 };
4866
4867 if !quad.background.is_transparent() {
4868 self.frame_state.next_frame.scene.insert_primitive(quad);
4869 return;
4870 }
4871
4872 let outer_bounds = quad.bounds;
4875 let inner_bounds = Self::largest_border_interior(&quad);
4876
4877 if inner_bounds.is_empty() {
4878 self.frame_state.next_frame.scene.insert_primitive(quad);
4879 return;
4880 }
4881
4882 let strips = [
4883 Bounds::from_corners(
4885 outer_bounds.origin,
4886 point(outer_bounds.right(), inner_bounds.top()),
4887 ),
4888 Bounds::from_corners(
4890 point(outer_bounds.left(), inner_bounds.bottom()),
4891 outer_bounds.bottom_right(),
4892 ),
4893 Bounds::from_corners(
4895 point(outer_bounds.left(), inner_bounds.top()),
4896 inner_bounds.bottom_left(),
4897 ),
4898 Bounds::from_corners(
4900 inner_bounds.top_right(),
4901 point(outer_bounds.right(), inner_bounds.bottom()),
4902 ),
4903 ];
4904
4905 for strip in strips {
4906 let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
4907 if !content_mask_bounds.is_empty() {
4908 self.frame_state.next_frame.scene.insert_primitive(Quad {
4909 content_mask: ContentMask {
4910 bounds: content_mask_bounds,
4911 },
4912 ..quad
4913 });
4914 }
4915 }
4916 }
4917
4918 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
4923 self.core.invalidator.debug_assert_paint();
4924
4925 let scale_factor = self.scale_factor();
4926 let content_mask = self.content_mask();
4927 let opacity = self.element_opacity();
4928 path.content_mask = content_mask;
4929 let color: Background = color.into();
4930 path.color = color.opacity(opacity);
4931 self.frame_state
4932 .next_frame
4933 .scene
4934 .insert_primitive(path.scale(scale_factor));
4935 }
4936
4937 pub fn paint_underline(
4941 &mut self,
4942 origin: Point<Pixels>,
4943 width: Pixels,
4944 style: &UnderlineStyle,
4945 ) {
4946 self.core.invalidator.debug_assert_paint();
4947
4948 let scale_factor = self.scale_factor();
4949 let thickness = self.snap_stroke(style.thickness);
4950 let height = if style.wavy {
4951 ScaledPixels(thickness.0 * 3.)
4952 } else {
4953 thickness
4954 };
4955 let bounds = Bounds {
4956 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4957 size: size(self.snap_stroke(width), height),
4958 };
4959 let element_opacity = self.element_opacity();
4960
4961 self.frame_state
4962 .next_frame
4963 .scene
4964 .insert_primitive(Underline {
4965 order: 0,
4966 pad: 0,
4967 bounds,
4968 content_mask: self.snapped_content_mask(),
4969 color: style.color.unwrap_or_default().opacity(element_opacity),
4970 thickness,
4971 wavy: style.wavy.into(),
4972 });
4973 }
4974
4975 pub fn paint_strikethrough(
4979 &mut self,
4980 origin: Point<Pixels>,
4981 width: Pixels,
4982 style: &StrikethroughStyle,
4983 ) {
4984 self.core.invalidator.debug_assert_paint();
4985
4986 let scale_factor = self.scale_factor();
4987 let height = style.thickness;
4988 let bounds = Bounds {
4989 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4990 size: size(self.snap_stroke(width), self.snap_stroke(height)),
4991 };
4992 let opacity = self.element_opacity();
4993
4994 self.frame_state
4995 .next_frame
4996 .scene
4997 .insert_primitive(Underline {
4998 order: 0,
4999 pad: 0,
5000 bounds,
5001 content_mask: self.snapped_content_mask(),
5002 thickness: self.snap_stroke(style.thickness),
5003 color: style.color.unwrap_or_default().opacity(opacity),
5004 wavy: false.into(),
5005 });
5006 }
5007
5008 pub fn paint_glyph(
5017 &mut self,
5018 origin: Point<Pixels>,
5019 font_id: FontId,
5020 glyph_id: GlyphId,
5021 font_size: Pixels,
5022 color: Hsla,
5023 ) -> Result<()> {
5024 self.core.invalidator.debug_assert_paint();
5025
5026 let element_opacity = self.element_opacity();
5027 let scale_factor = self.scale_factor();
5028 let glyph_origin = origin.scale(scale_factor);
5029
5030 let quantized_origin = Point::new(
5031 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
5032 / SUBPIXEL_VARIANTS_X as f32,
5033 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
5034 / SUBPIXEL_VARIANTS_Y as f32,
5035 );
5036 let subpixel_variant = Point::new(
5037 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
5038 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
5039 );
5040 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
5041 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
5042 let dilation = self.text_system().glyph_dilation_for_color(color);
5043 let params = RenderGlyphParams {
5044 font_id,
5045 glyph_id,
5046 font_size,
5047 subpixel_variant,
5048 scale_factor,
5049 is_emoji: false,
5050 subpixel_rendering,
5051 dilation,
5052 };
5053
5054 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
5055 if !raster_bounds.is_zero() {
5056 let tile = self
5057 .core
5058 .sprite_atlas
5059 .get_or_insert_with(¶ms.clone().into(), &mut || {
5060 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
5061 Ok(Some((size, Cow::Owned(bytes))))
5062 })?
5063 .expect("Callback above only errors or returns Some");
5064 let bounds = Bounds {
5065 origin: integer_origin + raster_bounds.origin.map(Into::into),
5066 size: tile.bounds.size.map(Into::into),
5067 };
5068 let content_mask = self.snapped_content_mask();
5069
5070 if subpixel_rendering {
5071 self.frame_state
5072 .next_frame
5073 .scene
5074 .insert_primitive(SubpixelSprite {
5075 order: 0,
5076 pad: 0,
5077 bounds,
5078 content_mask,
5079 color: color.opacity(element_opacity),
5080 tile,
5081 transformation: TransformationMatrix::unit(),
5082 });
5083 } else {
5084 self.frame_state
5085 .next_frame
5086 .scene
5087 .insert_primitive(MonochromeSprite {
5088 order: 0,
5089 pad: 0,
5090 bounds,
5091 content_mask,
5092 color: color.opacity(element_opacity),
5093 tile,
5094 transformation: TransformationMatrix::unit(),
5095 });
5096 }
5097 }
5098 Ok(())
5099 }
5100
5101 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
5102 if self.core.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
5103 return false;
5104 }
5105
5106 if !self.core.platform_window.is_subpixel_rendering_supported() {
5107 return false;
5108 }
5109
5110 let mode = match self.core.text_rendering_mode.get() {
5111 TextRenderingMode::PlatformDefault => self
5112 .text_system()
5113 .recommended_rendering_mode(font_id, font_size),
5114 mode => mode,
5115 };
5116
5117 mode == TextRenderingMode::Subpixel
5118 }
5119
5120 pub fn paint_emoji(
5129 &mut self,
5130 origin: Point<Pixels>,
5131 font_id: FontId,
5132 glyph_id: GlyphId,
5133 font_size: Pixels,
5134 ) -> Result<()> {
5135 self.core.invalidator.debug_assert_paint();
5136
5137 let scale_factor = self.scale_factor();
5138 let glyph_origin = origin.scale(scale_factor);
5139 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
5140 let params = RenderGlyphParams {
5141 font_id,
5142 glyph_id,
5143 font_size,
5144 subpixel_variant: Default::default(),
5145 scale_factor,
5146 is_emoji: true,
5147 subpixel_rendering: false,
5148 dilation: 0,
5149 };
5150
5151 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
5152 if !raster_bounds.is_zero() {
5153 let tile = self
5154 .core
5155 .sprite_atlas
5156 .get_or_insert_with(¶ms.clone().into(), &mut || {
5157 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
5158 Ok(Some((size, Cow::Owned(bytes))))
5159 })?
5160 .expect("Callback above only errors or returns Some");
5161
5162 let bounds = Bounds {
5163 origin: integer_origin + raster_bounds.origin.map(Into::into),
5164 size: tile.bounds.size.map(Into::into),
5165 };
5166 let content_mask = self.snapped_content_mask();
5167 let opacity = self.element_opacity();
5168
5169 self.frame_state
5170 .next_frame
5171 .scene
5172 .insert_primitive(PolychromeSprite {
5173 order: 0,
5174 pad: 0,
5175 grayscale: false.into(),
5176 bounds,
5177 corner_radii: Default::default(),
5178 content_mask,
5179 tile,
5180 opacity,
5181 });
5182 }
5183 Ok(())
5184 }
5185
5186 pub fn paint_svg(
5190 &mut self,
5191 bounds: Bounds<Pixels>,
5192 path: SharedString,
5193 mut data: Option<&[u8]>,
5194 transformation: TransformationMatrix,
5195 color: Hsla,
5196 cx: &App,
5197 ) -> Result<()> {
5198 self.core.invalidator.debug_assert_paint();
5199
5200 let element_opacity = self.element_opacity();
5201 let bounds = self.snap_bounds(bounds);
5202
5203 let params = RenderSvgParams {
5204 path,
5205 size: bounds.size.map(|pixels| {
5206 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
5207 }),
5208 };
5209
5210 let Some(tile) =
5211 self.core
5212 .sprite_atlas
5213 .get_or_insert_with(¶ms.clone().into(), &mut || {
5214 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
5215 else {
5216 return Ok(None);
5217 };
5218 Ok(Some((size, Cow::Owned(bytes))))
5219 })?
5220 else {
5221 return Ok(());
5222 };
5223 let content_mask = self.snapped_content_mask();
5224 let svg_bounds = Bounds {
5225 origin: bounds.center()
5226 - Point::new(
5227 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5228 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5229 ),
5230 size: tile
5231 .bounds
5232 .size
5233 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
5234 };
5235 let final_bounds = svg_bounds
5236 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
5237 .map_size(|size| size.ceil());
5238
5239 self.frame_state
5240 .next_frame
5241 .scene
5242 .insert_primitive(MonochromeSprite {
5243 order: 0,
5244 pad: 0,
5245 bounds: final_bounds,
5246 content_mask,
5247 color: color.opacity(element_opacity),
5248 tile,
5249 transformation,
5250 });
5251
5252 Ok(())
5253 }
5254
5255 pub fn paint_image(
5265 &mut self,
5266 bounds: Bounds<Pixels>,
5267 image_bounds: Bounds<Pixels>,
5268 corner_radii: Corners<Pixels>,
5269 data: Arc<RenderImage>,
5270 frame_index: usize,
5271 grayscale: bool,
5272 ) -> Result<()> {
5273 self.core.invalidator.debug_assert_paint();
5274
5275 let visible_bounds = bounds.intersect(&image_bounds);
5276 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
5277 return Ok(());
5278 }
5279 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
5280 return Ok(());
5281 }
5282
5283 let params = RenderImageParams {
5284 image_id: data.id,
5285 frame_index,
5286 };
5287
5288 let tile = self
5289 .core
5290 .sprite_atlas
5291 .get_or_insert_with(¶ms.into(), &mut || {
5292 Ok(Some((
5293 data.size(frame_index),
5294 Cow::Borrowed(
5295 data.as_bytes(frame_index)
5296 .expect("It's the caller's job to pass a valid frame index"),
5297 ),
5298 )))
5299 })?
5300 .expect("Callback above only returns Some");
5301
5302 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
5303
5304 let sub_tile = if visible_bounds == image_bounds {
5305 tile
5306 } else {
5307 let x_offset_ratio =
5308 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
5309 let y_offset_ratio =
5310 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
5311 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
5312 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
5313
5314 let tile_origin_x = tile.bounds.origin.x.0;
5315 let tile_origin_y = tile.bounds.origin.y.0;
5316 let tile_width = tile.bounds.size.width.0;
5317 let tile_height = tile.bounds.size.height.0;
5318
5319 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
5320 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
5321 let sub_width = (width_ratio * tile_width as f32).round() as i32;
5322 let sub_height = (height_ratio * tile_height as f32).round() as i32;
5323
5324 let max_x = tile_origin_x + tile_width;
5325 let max_y = tile_origin_y + tile_height;
5326
5327 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
5328 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
5329 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
5330 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
5331
5332 AtlasTile {
5333 bounds: Bounds {
5334 origin: point(
5335 DevicePixels(clamped_origin_x),
5336 DevicePixels(clamped_origin_y),
5337 ),
5338 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
5339 },
5340 ..tile
5341 }
5342 };
5343
5344 let content_mask = self.snapped_content_mask();
5345 let corner_radii = corner_radii
5346 .clamp_radii_for_quad_size(visible_bounds.size)
5347 .scale(self.scale_factor());
5348 let opacity = self.element_opacity();
5349
5350 self.frame_state
5351 .next_frame
5352 .scene
5353 .insert_primitive(PolychromeSprite {
5354 order: 0,
5355 pad: 0,
5356 grayscale: grayscale.into(),
5357 bounds: visible_bounds_snapped,
5358 content_mask,
5359 corner_radii,
5360 tile: sub_tile,
5361 opacity,
5362 });
5363 Ok(())
5364 }
5365
5366 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
5368 for frame_index in 0..data.frame_count() {
5369 let params = RenderImageParams {
5370 image_id: data.id,
5371 frame_index,
5372 };
5373
5374 self.core.sprite_atlas.remove(¶ms.clone().into());
5375 }
5376
5377 Ok(())
5378 }
5379
5380 #[cfg(any(test, feature = "test-support"))]
5382 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
5383 data.frame_count() > 0
5384 && (0..data.frame_count()).all(|frame_index| {
5385 self.core.sprite_atlas.contains(
5386 &RenderImageParams {
5387 image_id: data.id,
5388 frame_index,
5389 }
5390 .into(),
5391 )
5392 })
5393 }
5394
5395 #[must_use]
5402 pub fn request_layout(
5403 &mut self,
5404 style: Style,
5405 children: impl IntoIterator<Item = LayoutId>,
5406 cx: &mut App,
5407 ) -> LayoutId {
5408 self.core.invalidator.debug_assert_prepaint();
5409
5410 cx.layout_id_buffer.clear();
5411 cx.layout_id_buffer.extend(children);
5412 let rem_size = self.rem_size();
5413 let scale_factor = self.scale_factor();
5414 let engine_style = to_engine_layout_style(&style);
5415
5416 self.frame_state.layout_session.request_layout(
5417 &engine_style,
5418 rem_size,
5419 scale_factor,
5420 &cx.layout_id_buffer,
5421 )
5422 }
5423
5424 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
5434 where
5435 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
5436 + 'static,
5437 {
5438 self.core.invalidator.debug_assert_prepaint();
5439
5440 let rem_size = self.rem_size();
5441 let scale_factor = self.scale_factor();
5442 let engine_style = to_engine_layout_style(&style);
5443 let measure = move |known_dimensions, available_space, context: &mut dyn MeasureContext| {
5444 let MeasureHandles { window, app } = context.handles();
5445 let (core, frame_state) = window;
5446 let core = core
5447 .downcast_mut::<WindowHostCore>()
5448 .expect("measure context window half should be a window's core");
5449 let frame_state = frame_state
5450 .downcast_mut::<WindowFrameState>()
5451 .expect("measure context window half should be a window's frame state");
5452 let cx = app
5453 .downcast_mut::<App>()
5454 .expect("measure context app should be an App");
5455 measure(
5456 known_dimensions,
5457 available_space,
5458 &mut Window { core, frame_state },
5459 cx,
5460 )
5461 };
5462 self.frame_state.layout_session.request_measured_layout(
5463 &engine_style,
5464 rem_size,
5465 scale_factor,
5466 Box::new(measure),
5467 )
5468 }
5469
5470 pub(crate) fn compute_layout(
5476 &mut self,
5477 layout_id: LayoutId,
5478 available_space: Size<AvailableSpace>,
5479 cx: &mut App,
5480 ) {
5481 self.core.invalidator.debug_assert_prepaint();
5482
5483 let scale_factor = self.scale_factor();
5484 let layout_session = self.frame_state.layout_session.clone();
5485 let core = &mut *self.core;
5486 let frame_state = &mut *self.frame_state;
5487 layout_session.compute_layout(
5488 layout_id,
5489 available_space,
5490 scale_factor,
5491 &mut WindowMeasureContext {
5492 core,
5493 frame_state,
5494 cx,
5495 },
5496 );
5497 }
5498
5499 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
5505 self.core.invalidator.debug_assert_prepaint();
5506
5507 let scale_factor = self.scale_factor();
5508 let mut bounds = self
5509 .frame_state
5510 .layout_session
5511 .layout_bounds(layout_id, scale_factor)
5512 .map(Into::into);
5513 let snapped_offset = self.pixel_snap_point(self.element_offset());
5514 bounds.origin += snapped_offset;
5515 bounds
5516 }
5517
5518 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
5525 self.core.invalidator.debug_assert_prepaint();
5526
5527 let content_mask = self.content_mask();
5528 let mut id = self.frame_state.next_hitbox_id;
5529 self.frame_state.next_hitbox_id = self.frame_state.next_hitbox_id.next();
5530 let hitbox = Hitbox {
5531 id,
5532 bounds,
5533 content_mask,
5534 behavior,
5535 };
5536 self.frame_state.next_frame.hitboxes.push(hitbox.clone());
5537 hitbox
5538 }
5539
5540 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
5544 self.core.invalidator.debug_assert_paint();
5545 self.frame_state
5546 .next_frame
5547 .window_control_hitboxes
5548 .push((area, hitbox));
5549 }
5550
5551 pub fn set_key_context(&mut self, context: KeyContext) {
5556 self.core.invalidator.debug_assert_paint();
5557 self.frame_state
5558 .next_frame
5559 .dispatch_tree
5560 .set_key_context(context);
5561 }
5562
5563 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
5568 self.core.invalidator.debug_assert_prepaint();
5569 if focus_handle.is_focused(self) {
5570 self.frame_state.next_frame.focus = Some(focus_handle.id);
5571 }
5572 self.frame_state
5573 .next_frame
5574 .dispatch_tree
5575 .set_focus_id(focus_handle.id);
5576 }
5577
5578 pub fn set_view_id(&mut self, view_id: EntityId) {
5584 self.core.invalidator.debug_assert_prepaint();
5585 self.frame_state
5586 .next_frame
5587 .dispatch_tree
5588 .set_view_id(view_id);
5589 }
5590
5591 pub fn current_view(&self) -> EntityId {
5593 self.core.invalidator.debug_assert_paint_or_prepaint();
5594 self.frame_state
5595 .rendered_entity_stack
5596 .last()
5597 .copied()
5598 .unwrap()
5599 }
5600
5601 #[inline]
5602 pub(crate) fn with_rendered_view<R>(
5603 &mut self,
5604 id: EntityId,
5605 f: impl FnOnce(&mut Self) -> R,
5606 ) -> R {
5607 self.frame_state.rendered_entity_stack.push(id);
5608 let result = f(self);
5609 self.frame_state.rendered_entity_stack.pop();
5610 result
5611 }
5612
5613 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
5615 where
5616 F: FnOnce(&mut Self) -> R,
5617 {
5618 if let Some(image_cache) = image_cache {
5619 self.frame_state.image_cache_stack.push(image_cache);
5620 let result = f(self);
5621 self.frame_state.image_cache_stack.pop();
5622 result
5623 } else {
5624 f(self)
5625 }
5626 }
5627
5628 pub fn handle_input(
5637 &mut self,
5638 focus_handle: &FocusHandle,
5639 input_handler: impl InputHandler,
5640 cx: &App,
5641 ) {
5642 self.core.invalidator.debug_assert_paint();
5643
5644 if focus_handle.is_focused(self) {
5645 let cx = self.to_async(cx);
5646 self.frame_state
5647 .next_frame
5648 .input_handlers
5649 .push(Some(new_platform_input_handler(
5650 cx,
5651 Box::new(input_handler),
5652 )));
5653 }
5654 }
5655
5656 fn apply_text_input_configuration(&mut self, cx: &mut App) {
5661 let configuration = match self.core.platform_window.take_input_handler() {
5662 Some(mut input_handler) => {
5663 let configuration = input_handler.text_input_configuration(self, cx);
5664 self.core.platform_window.set_input_handler(input_handler);
5665 configuration
5666 }
5667 None => TextInputConfiguration::default(),
5668 };
5669 if self.core.last_text_input_configuration.as_ref() != Some(&configuration) {
5670 self.core
5671 .platform_window
5672 .set_text_input_configuration(configuration.clone());
5673 self.core.last_text_input_configuration = Some(configuration);
5674 }
5675 }
5676
5677 pub fn on_mouse_event<Event: MouseEvent>(
5683 &mut self,
5684 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5685 ) {
5686 self.core.invalidator.debug_assert_paint();
5687
5688 self.frame_state
5689 .next_frame
5690 .mouse_listeners
5691 .push(Some(Box::new(
5692 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
5693 if let Some(event) = event.downcast_ref() {
5694 listener(event, phase, window, cx)
5695 }
5696 },
5697 )));
5698 }
5699
5700 pub fn on_key_event<Event: KeyEvent>(
5709 &mut self,
5710 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5711 ) {
5712 self.core.invalidator.debug_assert_paint();
5713
5714 self.frame_state
5715 .next_frame
5716 .dispatch_tree
5717 .on_key_event(Rc::new(
5718 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
5719 if let Some(event) = event.downcast_ref::<Event>() {
5720 listener(event, phase, window, cx)
5721 }
5722 },
5723 ));
5724 }
5725
5726 pub fn on_modifiers_changed(
5733 &mut self,
5734 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
5735 ) {
5736 self.core.invalidator.debug_assert_paint();
5737
5738 self.frame_state
5739 .next_frame
5740 .dispatch_tree
5741 .on_modifiers_changed(Rc::new(
5742 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
5743 listener(event, window, cx)
5744 },
5745 ));
5746 }
5747
5748 pub fn on_focus_in(
5752 &mut self,
5753 handle: &FocusHandle,
5754 cx: &mut App,
5755 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
5756 ) -> Subscription {
5757 let focus_id = handle.id;
5758 let (subscription, activate) =
5759 self.new_focus_listener(Box::new(move |event, window, cx| {
5760 if event.is_focus_in(focus_id) {
5761 listener(window, cx);
5762 }
5763 true
5764 }));
5765 cx.defer(move |_| activate());
5766 subscription
5767 }
5768
5769 pub fn on_focus_out(
5772 &mut self,
5773 handle: &FocusHandle,
5774 cx: &mut App,
5775 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
5776 ) -> Subscription {
5777 let focus_id = handle.id;
5778 let (subscription, activate) =
5779 self.new_focus_listener(Box::new(move |event, window, cx| {
5780 if let Some(blurred_id) = event.previous_focus_path.last().copied()
5781 && event.is_focus_out(focus_id)
5782 {
5783 let event = FocusOutEvent {
5784 blurred: WeakFocusHandle {
5785 id: blurred_id,
5786 handles: Arc::downgrade(&cx.focus_handles),
5787 },
5788 };
5789 listener(event, window, cx)
5790 }
5791 true
5792 }));
5793 cx.defer(move |_| activate());
5794 subscription
5795 }
5796
5797 fn reset_cursor_style(&self, cx: &mut App) {
5798 if self.is_window_hovered() {
5800 let style = self
5801 .frame_state
5802 .rendered_frame
5803 .cursor_style(self)
5804 .unwrap_or(CursorStyle::Arrow);
5805 cx.platform.set_cursor_style(style);
5806 }
5807 }
5808
5809 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
5812 let keystroke = keystroke.with_simulated_ime();
5813 let result = self.dispatch_event(
5814 PlatformInput::KeyDown(KeyDownEvent {
5815 keystroke: keystroke.clone(),
5816 is_held: false,
5817 prefer_character_input: false,
5818 }),
5819 cx,
5820 );
5821 if !result.propagate {
5822 return true;
5823 }
5824
5825 if let Some(input) = keystroke.key_char
5826 && let Some(mut input_handler) = self.core.platform_window.take_input_handler()
5827 {
5828 input_handler.dispatch_input(&input, self, cx);
5829 self.core.platform_window.set_input_handler(input_handler);
5830 return true;
5831 }
5832
5833 false
5834 }
5835
5836 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
5839 self.highest_precedence_binding_for_action(action)
5840 .map(|binding| {
5841 binding
5842 .keystrokes()
5843 .iter()
5844 .map(ToString::to_string)
5845 .collect::<Vec<_>>()
5846 .join(" ")
5847 })
5848 .unwrap_or_else(|| action.name().to_string())
5849 }
5850
5851 #[profiling::function]
5853 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
5854 #[cfg(feature = "profiler")]
5855 self.core.window_profiler.begin_input(event.kind_name());
5856 let update_count_before = self.core.invalidator.update_count();
5857 let old_modality = self.core.last_input_modality;
5861 self.core.last_input_modality = match &event {
5862 PlatformInput::KeyDown(_) => InputModality::Keyboard,
5863 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
5864 PlatformInput::Touch(_) => InputModality::Touch,
5865 _ => self.core.last_input_modality,
5866 };
5867 if self.core.last_input_modality != old_modality {
5868 self.refresh();
5869 }
5870
5871 cx.propagate_event = true;
5873 self.core.default_prevented = false;
5875
5876 let event = match event {
5877 PlatformInput::MouseMove(mouse_move) => {
5880 self.core.mouse_position = mouse_move.position;
5881 self.core.modifiers = mouse_move.modifiers;
5882 PlatformInput::MouseMove(mouse_move)
5883 }
5884 PlatformInput::MouseDown(mouse_down) => {
5885 self.core.mouse_position = mouse_down.position;
5886 self.core.modifiers = mouse_down.modifiers;
5887 PlatformInput::MouseDown(mouse_down)
5888 }
5889 PlatformInput::MouseUp(mouse_up) => {
5890 self.core.mouse_position = mouse_up.position;
5891 self.core.modifiers = mouse_up.modifiers;
5892 PlatformInput::MouseUp(mouse_up)
5893 }
5894 PlatformInput::MousePressure(mouse_pressure) => {
5895 PlatformInput::MousePressure(mouse_pressure)
5896 }
5897 PlatformInput::MouseExited(mouse_exited) => {
5898 self.core.modifiers = mouse_exited.modifiers;
5899 PlatformInput::MouseExited(mouse_exited)
5900 }
5901 PlatformInput::ModifiersChanged(modifiers_changed) => {
5902 self.core.modifiers = modifiers_changed.modifiers;
5903 self.core.capslock = modifiers_changed.capslock;
5904 PlatformInput::ModifiersChanged(modifiers_changed)
5905 }
5906 PlatformInput::ScrollWheel(scroll_wheel) => {
5907 self.core.mouse_position = scroll_wheel.position;
5908 self.core.modifiers = scroll_wheel.modifiers;
5909 PlatformInput::ScrollWheel(scroll_wheel)
5910 }
5911 PlatformInput::Pinch(pinch) => {
5912 self.core.mouse_position = pinch.position;
5913 self.core.modifiers = pinch.modifiers;
5914 PlatformInput::Pinch(pinch)
5915 }
5916 PlatformInput::FileDrop(file_drop) => match file_drop {
5919 FileDropEvent::Entered { position, paths } => {
5920 self.core.mouse_position = position;
5921 let source_window = self.core.handle.window_id();
5922 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
5923 cx.active_drag = Some(AnyDrag {
5924 value: Arc::new(paths.clone()),
5925 view: cx.new(|_| paths).into(),
5926 cursor_offset: position,
5927 cursor_style: None,
5928 external_payload_source: None,
5929 });
5930 }
5931 PlatformInput::MouseMove(MouseMoveEvent {
5932 position,
5933 pressed_button: Some(MouseButton::Left),
5934 modifiers: Modifiers::default(),
5935 })
5936 }
5937 FileDropEvent::Pending { position } => {
5938 self.core.mouse_position = position;
5939 PlatformInput::MouseMove(MouseMoveEvent {
5940 position,
5941 pressed_button: Some(MouseButton::Left),
5942 modifiers: Modifiers::default(),
5943 })
5944 }
5945 FileDropEvent::Submit { position } => {
5946 cx.activate(true);
5947 self.core.mouse_position = position;
5948 PlatformInput::MouseUp(MouseUpEvent {
5949 button: MouseButton::Left,
5950 position,
5951 modifiers: Modifiers::default(),
5952 click_count: 1,
5953 })
5954 }
5955 FileDropEvent::Exited => {
5956 if !cx.hand_restored_drag_to_platform(self.core.handle.window_id()) {
5957 cx.active_drag.take();
5958 }
5959 self.refresh();
5960 PlatformInput::FileDrop(FileDropEvent::Exited)
5961 }
5962 FileDropEvent::Ended => {
5963 cx.end_platform_drag(self.core.handle.window_id());
5964 self.refresh();
5965 PlatformInput::FileDrop(FileDropEvent::Ended)
5966 }
5967 },
5968 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
5969 PlatformInput::LongPress(long_press) => {
5970 self.core.mouse_position = if long_press.phase == crate::TouchPhase::Started {
5971 long_press.start_position
5972 } else {
5973 long_press.position
5974 };
5975 if long_press.phase == crate::TouchPhase::Started {
5976 self.core.long_press_capture = None;
5977 }
5978 PlatformInput::LongPress(long_press)
5979 }
5980 PlatformInput::TouchDrag(touch_drag) => {
5981 self.core.mouse_position = touch_drag.start_position;
5982 PlatformInput::TouchDrag(touch_drag)
5983 }
5984 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
5985 };
5986
5987 if let Some(any_mouse_event) = event.mouse_event() {
5988 self.dispatch_mouse_event(any_mouse_event, cx);
5989 } else if let Some(any_key_event) = event.keyboard_event() {
5990 self.dispatch_key_event(any_key_event, cx);
5991 } else if let Some(touch_event) = event.touch_event() {
5992 self.dispatch_touch_event(touch_event, cx);
5993 }
5994 if let PlatformInput::LongPress(long_press) = &event {
5995 match long_press.phase {
5996 crate::TouchPhase::Started if !self.core.default_prevented => {
5997 self.core.long_press_capture = None;
5998 }
5999 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
6000 self.core.long_press_capture = None;
6001 }
6002 crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
6003 }
6004 }
6005
6006 self.promote_external_drag_to_platform(&event, cx);
6009
6010 let caused_invalidation = self.core.invalidator.update_count() > update_count_before;
6011 if caused_invalidation {
6012 self.core.input_rate_tracker.borrow_mut().record_input();
6013 }
6014 #[cfg(feature = "profiler")]
6015 self.core.window_profiler.end_input(caused_invalidation);
6016
6017 DispatchEventResult {
6018 propagate: cx.propagate_event,
6019 default_prevented: self.core.default_prevented,
6020 }
6021 }
6022
6023 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
6024 let PlatformInput::MouseMove(mouse_move) = event else {
6025 return;
6026 };
6027 if mouse_move.pressed_button != Some(MouseButton::Left) {
6028 return;
6029 }
6030 if Bounds::new(Point::default(), self.core.viewport_size).contains(&mouse_move.position) {
6031 return;
6032 }
6033 if !self.core.platform_window.can_start_external_drag() {
6034 return;
6035 }
6036 let Some(payload_source) = cx
6037 .active_drag
6038 .as_mut()
6039 .and_then(|drag| drag.external_payload_source.take())
6040 else {
6041 return;
6042 };
6043 let Some(payload) = payload_source(self, cx) else {
6044 return;
6045 };
6046 if self.core.platform_window.start_external_drag(&payload)
6047 && cx.hand_active_drag_to_platform(self.core.handle.window_id())
6048 {
6049 self.refresh();
6050 }
6051 }
6052
6053 pub fn touch_prediction_enabled(&self) -> bool {
6057 self.core.touch_prediction_enabled
6058 }
6059
6060 pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
6064 self.core.touch_prediction_enabled = enabled;
6065 }
6066
6067 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
6071 let mut event = event.clone();
6072 if !self.core.touch_prediction_enabled {
6073 event.predicted_position = None;
6074 }
6075 let recognized_gestures = self.core.touch_gestures.handle_event(&event);
6076 if event.phase == crate::TouchPhase::Started
6077 && let Some(touch_drag) = self.core.touch_gestures.offer_touch_drag(event.id)
6078 {
6079 self.dispatch_recognized_touch_gesture(touch_drag, cx);
6080 }
6081 if event.phase == crate::TouchPhase::Started
6082 && self.core.touch_gestures.pending_long_press().is_some()
6083 {
6084 self.core.long_press_capture = None;
6085 }
6086 let mut tapped = false;
6087 for gesture in recognized_gestures {
6088 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
6089 self.dispatch_recognized_touch_gesture(gesture, cx);
6090 }
6091 if event.phase == crate::TouchPhase::Started {
6092 self.schedule_long_press_timer(cx);
6093 } else if self.core.touch_gestures.pending_long_press().is_none() {
6094 self.core.long_press_timer.take();
6095 }
6096 if tapped && self.core.invalidator.is_dirty() {
6102 self.draw(cx).clear(cx);
6103 }
6104 if self.core.touch_gestures.has_momentum() {
6105 self.schedule_touch_momentum_tick();
6106 }
6107 }
6108
6109 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
6110 match gesture {
6111 RecognizedTouchGesture::Scroll(scroll_wheel) => {
6112 self.core.mouse_position = scroll_wheel.position;
6113 cx.propagate_event = true;
6114 self.dispatch_mouse_event(&scroll_wheel, cx);
6115 }
6116 RecognizedTouchGesture::Tap { down, up } => {
6117 self.core.mouse_position = up.position;
6118 cx.propagate_event = true;
6119 self.dispatch_mouse_event(&down, cx);
6120 cx.propagate_event = true;
6121 self.dispatch_mouse_event(&up, cx);
6122 }
6123 RecognizedTouchGesture::TouchDrag(touch_drag) => {
6124 self.core.mouse_position = touch_drag.start_position;
6125 cx.propagate_event = true;
6126 self.core.default_prevented = false;
6127 let started = touch_drag.phase == crate::TouchPhase::Started;
6128 self.dispatch_mouse_event(&touch_drag, cx);
6129 if started {
6130 self.core
6131 .touch_gestures
6132 .resolve_touch_drag(self.core.default_prevented);
6133 }
6134 }
6135 RecognizedTouchGesture::LongPress(long_press) => {
6136 self.core.mouse_position = if long_press.phase == crate::TouchPhase::Started {
6137 long_press.start_position
6138 } else {
6139 long_press.position
6140 };
6141 cx.propagate_event = true;
6142 self.core.default_prevented = false;
6143 let started = long_press.phase == crate::TouchPhase::Started;
6144 let ended = matches!(
6145 long_press.phase,
6146 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
6147 );
6148 self.dispatch_mouse_event(&long_press, cx);
6149 if started {
6150 let claimed = self.core.default_prevented;
6151 self.core.touch_gestures.resolve_long_press(claimed);
6152 if !claimed {
6153 self.core.long_press_capture = None;
6154 }
6155 }
6156 if ended {
6157 self.core.long_press_capture = None;
6158 }
6159 }
6160 }
6161 }
6162
6163 fn schedule_long_press_timer(&mut self, cx: &mut App) {
6164 self.core.long_press_timer.take();
6165 let Some((touch_id, duration)) = self.core.touch_gestures.pending_long_press() else {
6166 return;
6167 };
6168 self.core.long_press_timer = Some(self.spawn(cx, async move |cx| {
6169 cx.background_executor.timer(duration).await;
6170 cx.update(move |window, cx| {
6171 window.core.long_press_timer.take();
6172 if let Some(gesture) = window.core.touch_gestures.offer_long_press(touch_id) {
6173 window.dispatch_recognized_touch_gesture(gesture, cx);
6174 }
6175 })
6176 .log_err();
6177 }));
6178 }
6179
6180 fn schedule_touch_momentum_tick(&mut self) {
6181 self.on_next_frame(|window, cx| {
6182 if let Some(gesture) = window.core.touch_gestures.tick_momentum() {
6183 window.dispatch_recognized_touch_gesture(gesture, cx);
6184 }
6185 if window.core.touch_gestures.has_momentum() {
6186 window.schedule_touch_momentum_tick();
6187 }
6188 });
6189 }
6190
6191 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6192 let hit_test = self
6193 .frame_state
6194 .rendered_frame
6195 .hit_test(self.mouse_position());
6196 if hit_test != self.core.mouse_hit_test {
6197 self.core.mouse_hit_test = hit_test;
6198 self.reset_cursor_style(cx);
6199 }
6200
6201 #[cfg(any(feature = "inspector", debug_assertions))]
6202 if self.is_inspector_picking(cx) {
6203 self.handle_inspector_mouse_event(event, cx);
6204 return;
6206 }
6207
6208 let mut mouse_listeners = mem::take(&mut self.frame_state.rendered_frame.mouse_listeners);
6209
6210 for listener in &mut mouse_listeners {
6213 let listener = listener.as_mut().unwrap();
6214 listener(event, DispatchPhase::Capture, self, cx);
6215 if !cx.propagate_event {
6216 break;
6217 }
6218 }
6219
6220 if cx.propagate_event {
6222 for listener in mouse_listeners.iter_mut().rev() {
6223 let listener = listener.as_mut().unwrap();
6224 listener(event, DispatchPhase::Bubble, self, cx);
6225 if !cx.propagate_event {
6226 break;
6227 }
6228 }
6229 }
6230
6231 self.frame_state.rendered_frame.mouse_listeners = mouse_listeners;
6232
6233 if cx.has_active_drag() {
6234 if event.is::<MouseMoveEvent>() {
6235 self.refresh();
6238 } else if event.is::<MouseUpEvent>() {
6239 cx.active_drag = None;
6242 self.refresh();
6243 }
6244 }
6245
6246 if event.is::<MouseUpEvent>() && self.core.captured_hitbox.is_some() {
6248 self.core.captured_hitbox = None;
6249 }
6250 }
6251
6252 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
6253 if self.core.invalidator.is_dirty() {
6254 self.draw(cx).clear(cx);
6255 }
6256
6257 let node_id = self.focus_node_id_in_rendered_frame(self.core.focus);
6258 let dispatch_path = self
6259 .frame_state
6260 .rendered_frame
6261 .dispatch_tree
6262 .dispatch_path(node_id);
6263
6264 let mut keystroke: Option<Keystroke> = None;
6265
6266 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
6267 if event.modifiers.number_of_modifiers() == 0
6268 && self.core.pending_modifier.modifiers.number_of_modifiers() == 1
6269 && !self.core.pending_modifier.saw_other_input
6270 {
6271 let key = match self.core.pending_modifier.modifiers {
6272 modifiers if modifiers.shift => Some("shift"),
6273 modifiers if modifiers.control => Some("control"),
6274 modifiers if modifiers.alt => Some("alt"),
6275 modifiers if modifiers.platform => Some("platform"),
6276 modifiers if modifiers.function => Some("function"),
6277 _ => None,
6278 };
6279 if let Some(key) = key {
6280 keystroke = Some(Keystroke {
6281 key: key.to_string(),
6282 key_char: None,
6283 modifiers: Modifiers::default(),
6284 });
6285 }
6286 }
6287
6288 if self.core.pending_modifier.modifiers.number_of_modifiers() == 0
6289 && event.modifiers.number_of_modifiers() == 1
6290 {
6291 self.core.pending_modifier.saw_other_input = false
6292 } else if event.modifiers.number_of_modifiers() > 1 {
6293 self.core.pending_modifier.saw_other_input = true
6294 }
6295 self.core.pending_modifier.modifiers = event.modifiers
6296 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
6297 self.core.pending_modifier.saw_other_input = true;
6298 keystroke = Some(key_down_event.keystroke.clone());
6299 if key_down_event.keystroke.key_char.is_some()
6300 && matches!(
6301 cx.cursor_hide_mode,
6302 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
6303 )
6304 {
6305 cx.platform.hide_cursor_until_mouse_moves();
6306 }
6307 }
6308
6309 let Some(keystroke) = keystroke else {
6310 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
6311 return;
6312 };
6313
6314 cx.propagate_event = true;
6315 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
6316 if !cx.propagate_event {
6317 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
6318 return;
6319 }
6320
6321 let mut currently_pending = self.core.pending_input.take().unwrap_or_default();
6322 if currently_pending.focus.is_some() && currently_pending.focus != self.core.focus {
6323 currently_pending = PendingInput::default();
6324 }
6325
6326 let match_result = self.frame_state.rendered_frame.dispatch_tree.dispatch_key(
6327 currently_pending.keystrokes,
6328 keystroke,
6329 &dispatch_path,
6330 );
6331
6332 if !match_result.to_replay.is_empty() {
6333 self.replay_pending_input(match_result.to_replay, cx);
6334 cx.propagate_event = true;
6335 }
6336
6337 if !match_result.pending.is_empty() {
6338 let previous_timeout = currently_pending.timeout.take();
6339 currently_pending.keystrokes = match_result.pending;
6340 currently_pending.focus = self.core.focus;
6341
6342 let text_input_requires_timeout = event
6343 .downcast_ref::<KeyDownEvent>()
6344 .filter(|key_down| key_down.keystroke.key_char.is_some())
6345 .and_then(|_| self.core.platform_window.take_input_handler())
6346 .map_or(false, |mut input_handler| {
6347 let accepts = input_handler.accepts_text_input(self, cx);
6348 self.core.platform_window.set_input_handler(input_handler);
6349 accepts
6350 });
6351
6352 let needs_timeout = previous_timeout.is_some()
6353 || match_result.pending_has_binding
6354 || text_input_requires_timeout;
6355 currently_pending.timeout = if needs_timeout {
6356 match previous_timeout {
6357 Some(mut timeout) if timeout.is_paused() => {
6358 timeout.reset_duration(PENDING_INPUT_TIMEOUT);
6359 Some(timeout)
6360 }
6361 previous_timeout => {
6362 drop(previous_timeout);
6363 Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
6364 }
6365 }
6366 } else {
6367 None
6368 };
6369 self.core.pending_input = Some(currently_pending);
6370 self.pending_input_changed(cx);
6371 cx.propagate_event = false;
6372 return;
6373 }
6374
6375 let skip_bindings = event
6376 .downcast_ref::<KeyDownEvent>()
6377 .filter(|key_down_event| key_down_event.prefer_character_input)
6378 .map(|_| {
6379 self.core
6380 .platform_window
6381 .take_input_handler()
6382 .map_or(false, |mut input_handler| {
6383 let accepts = input_handler.accepts_text_input(self, cx);
6384 self.core.platform_window.set_input_handler(input_handler);
6385 accepts
6388 })
6389 })
6390 .unwrap_or(false);
6391
6392 if !skip_bindings {
6393 for binding in match_result.bindings {
6394 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6395 if !cx.propagate_event {
6396 self.dispatch_keystroke_observers(
6397 event,
6398 Some(binding.action),
6399 match_result.context_stack,
6400 cx,
6401 );
6402 self.pending_input_changed(cx);
6403 return;
6404 }
6405 }
6406 }
6407
6408 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
6409 self.pending_input_changed(cx);
6410 }
6411
6412 fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
6413 let (started_at, task) = self.start_pending_input_timeout(duration, cx);
6414 PendingInputTimeout {
6415 duration,
6416 remaining: duration,
6417 state: PendingInputTimeoutState::Running { started_at, task },
6418 }
6419 }
6420
6421 fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
6422 let started_at = cx.background_executor().now();
6423 let task = self.spawn(cx, async move |cx| {
6424 cx.background_executor.timer(remaining).await;
6425 cx.update(move |window, cx| {
6426 let Some(currently_pending) = window
6427 .core
6428 .pending_input
6429 .take()
6430 .filter(|pending| pending.focus == window.core.focus)
6431 else {
6432 return;
6433 };
6434
6435 let node_id = window.focus_node_id_in_rendered_frame(window.core.focus);
6436 let dispatch_path = window
6437 .frame_state
6438 .rendered_frame
6439 .dispatch_tree
6440 .dispatch_path(node_id);
6441
6442 let to_replay = window
6443 .frame_state
6444 .rendered_frame
6445 .dispatch_tree
6446 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
6447
6448 window.pending_input_changed(cx);
6449 window.replay_pending_input(to_replay, cx)
6450 })
6451 .log_err();
6452 });
6453 (started_at, task)
6454 }
6455
6456 fn finish_dispatch_key_event(
6457 &mut self,
6458 event: &dyn Any,
6459 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
6460 context_stack: Vec<KeyContext>,
6461 cx: &mut App,
6462 ) {
6463 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
6464 if !cx.propagate_event {
6465 return;
6466 }
6467
6468 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
6469 if !cx.propagate_event {
6470 return;
6471 }
6472
6473 self.dispatch_keystroke_observers(event, None, context_stack, cx);
6474 }
6475
6476 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
6477 self.core
6478 .pending_input_observers
6479 .clone()
6480 .retain(&(), |callback| callback(self, cx));
6481 }
6482
6483 fn defer_pending_input_changed(&self, cx: &mut App) {
6484 let window_handle = self.core.handle;
6487 cx.defer(move |cx| {
6488 window_handle
6489 .update(cx, |_, window, cx| {
6490 window.pending_input_changed(cx);
6491 })
6492 .ok();
6493 });
6494 }
6495
6496 fn dispatch_key_down_up_event(
6497 &mut self,
6498 event: &dyn Any,
6499 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6500 cx: &mut App,
6501 ) {
6502 for node_id in dispatch_path {
6504 let node = self.frame_state.rendered_frame.dispatch_tree.node(*node_id);
6505
6506 for key_listener in node.key_listeners.clone() {
6507 key_listener(event, DispatchPhase::Capture, self, cx);
6508 if !cx.propagate_event {
6509 return;
6510 }
6511 }
6512 }
6513
6514 for node_id in dispatch_path.iter().rev() {
6516 let node = self.frame_state.rendered_frame.dispatch_tree.node(*node_id);
6518 for key_listener in node.key_listeners.clone() {
6519 key_listener(event, DispatchPhase::Bubble, self, cx);
6520 if !cx.propagate_event {
6521 return;
6522 }
6523 }
6524 }
6525 }
6526
6527 fn dispatch_modifiers_changed_event(
6528 &mut self,
6529 event: &dyn Any,
6530 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6531 cx: &mut App,
6532 ) {
6533 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
6534 return;
6535 };
6536 for node_id in dispatch_path.iter().rev() {
6537 let node = self.frame_state.rendered_frame.dispatch_tree.node(*node_id);
6538 for listener in node.modifiers_changed_listeners.clone() {
6539 listener(event, self, cx);
6540 if !cx.propagate_event {
6541 return;
6542 }
6543 }
6544 }
6545 }
6546
6547 pub fn has_pending_keystrokes(&self) -> bool {
6549 self.pending_input().is_some()
6550 }
6551
6552 #[cfg(test)]
6553 pub(crate) fn pending_input_is_none(&self) -> bool {
6554 self.core.pending_input.is_none()
6555 }
6556
6557 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
6558 if self.core.pending_input.take().is_some() {
6559 self.defer_pending_input_changed(cx);
6560 }
6561 }
6562
6563 pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
6566 self.core
6567 .pending_input
6568 .as_ref()
6569 .filter(|pending_input| pending_input.focus == self.core.focus)
6570 .map(|pending_input| PendingInputStatus {
6571 keystrokes: pending_input.keystrokes.as_slice(),
6572 timeout: pending_input
6573 .timeout
6574 .as_ref()
6575 .map(PendingInputTimeout::status),
6576 })
6577 }
6578
6579 pub fn set_pending_input_timeout_paused<T: 'static>(
6584 &mut self,
6585 owner: &Entity<T>,
6586 paused: bool,
6587 cx: &mut App,
6588 ) -> bool {
6589 let owner_id = owner.entity_id();
6590 if !paused {
6591 return self.resume_pending_input_timeout(owner_id, cx);
6592 }
6593
6594 let timeout = self
6595 .core
6596 .pending_input
6597 .as_ref()
6598 .filter(|pending_input| pending_input.focus == self.core.focus)
6599 .and_then(|pending_input| pending_input.timeout.as_ref());
6600 let Some(timeout) = timeout else {
6601 return false;
6602 };
6603 if timeout.is_paused() {
6604 return false;
6605 }
6606
6607 let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
6608 window.resume_pending_input_timeout(owner_id, cx);
6609 });
6610 let now = cx.background_executor().now();
6611 let changed = self
6612 .core
6613 .pending_input
6614 .as_mut()
6615 .filter(|pending_input| pending_input.focus == self.core.focus)
6616 .and_then(|pending_input| pending_input.timeout.as_mut())
6617 .is_some_and(|timeout| {
6618 timeout.pause(
6619 PendingInputTimeoutPause {
6620 owner_id,
6621 _release_subscription: release_subscription,
6622 },
6623 now,
6624 )
6625 });
6626
6627 if changed {
6628 self.defer_pending_input_changed(cx);
6629 }
6630 changed
6631 }
6632
6633 fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
6634 let Some(remaining) = self
6635 .core
6636 .pending_input
6637 .as_ref()
6638 .and_then(|pending_input| pending_input.timeout.as_ref())
6639 .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
6640 .map(|timeout| timeout.remaining)
6641 else {
6642 return false;
6643 };
6644
6645 let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
6646 let changed = self
6647 .core
6648 .pending_input
6649 .as_mut()
6650 .and_then(|pending_input| pending_input.timeout.as_mut())
6651 .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
6652
6653 if changed {
6654 self.defer_pending_input_changed(cx);
6655 }
6656 changed
6657 }
6658
6659 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
6661 self.pending_input()
6662 .map(|pending_input| pending_input.keystrokes())
6663 }
6664
6665 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
6666 let node_id = self.focus_node_id_in_rendered_frame(self.core.focus);
6667 let dispatch_path = self
6668 .frame_state
6669 .rendered_frame
6670 .dispatch_tree
6671 .dispatch_path(node_id);
6672
6673 'replay: for replay in replays {
6674 let event = KeyDownEvent {
6675 keystroke: replay.keystroke.clone(),
6676 is_held: false,
6677 prefer_character_input: true,
6678 };
6679
6680 cx.propagate_event = true;
6681 for binding in replay.bindings {
6682 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6683 if !cx.propagate_event {
6684 self.dispatch_keystroke_observers(
6685 &event,
6686 Some(binding.action),
6687 Vec::default(),
6688 cx,
6689 );
6690 continue 'replay;
6691 }
6692 }
6693
6694 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
6695 if !cx.propagate_event {
6696 continue 'replay;
6697 }
6698 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
6699 && let Some(mut input_handler) = self.core.platform_window.take_input_handler()
6700 {
6701 input_handler.dispatch_input(&input, self, cx);
6702 self.core.platform_window.set_input_handler(input_handler)
6703 }
6704 }
6705 }
6706
6707 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
6708 focus_id
6709 .and_then(|focus_id| {
6710 self.frame_state
6711 .rendered_frame
6712 .dispatch_tree
6713 .focusable_node_id(focus_id)
6714 })
6715 .unwrap_or_else(|| self.frame_state.rendered_frame.dispatch_tree.root_node_id())
6716 }
6717
6718 fn dispatch_action_on_node(
6719 &mut self,
6720 node_id: DispatchNodeId,
6721 action: &dyn Action,
6722 cx: &mut App,
6723 ) {
6724 self.dispatch_action_on_node_inner(node_id, action, cx);
6725
6726 if !cx.propagate_event
6727 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
6728 && self.last_input_was_keyboard()
6729 {
6730 cx.platform.hide_cursor_until_mouse_moves();
6731 }
6732 }
6733
6734 fn dispatch_action_on_node_inner(
6735 &mut self,
6736 node_id: DispatchNodeId,
6737 action: &dyn Action,
6738 cx: &mut App,
6739 ) {
6740 let dispatch_path = self
6741 .frame_state
6742 .rendered_frame
6743 .dispatch_tree
6744 .dispatch_path(node_id);
6745
6746 cx.propagate_event = true;
6748 if let Some(mut global_listeners) = cx
6749 .global_action_listeners
6750 .remove(&action.as_any().type_id())
6751 {
6752 for listener in &global_listeners {
6753 #[cfg(feature = "profiler")]
6754 self.core.window_profiler.begin_action_handler(action, cx);
6755 listener(action.as_any(), DispatchPhase::Capture, cx);
6756 #[cfg(feature = "profiler")]
6757 self.core.window_profiler.end_action_handler();
6758 if !cx.propagate_event {
6759 break;
6760 }
6761 }
6762
6763 global_listeners.extend(
6764 cx.global_action_listeners
6765 .remove(&action.as_any().type_id())
6766 .unwrap_or_default(),
6767 );
6768
6769 cx.global_action_listeners
6770 .insert(action.as_any().type_id(), global_listeners);
6771 }
6772
6773 if !cx.propagate_event {
6774 return;
6775 }
6776
6777 for node_id in &dispatch_path {
6779 let node = self.frame_state.rendered_frame.dispatch_tree.node(*node_id);
6780 for DispatchActionListener {
6781 action_type,
6782 listener,
6783 } in node.action_listeners.clone()
6784 {
6785 let any_action = action.as_any();
6786 if action_type == any_action.type_id() {
6787 #[cfg(feature = "profiler")]
6788 self.core.window_profiler.begin_action_handler(action, cx);
6789 listener(any_action, DispatchPhase::Capture, self, cx);
6790 #[cfg(feature = "profiler")]
6791 self.core.window_profiler.end_action_handler();
6792
6793 if !cx.propagate_event {
6794 return;
6795 }
6796 }
6797 }
6798 }
6799
6800 for node_id in dispatch_path.iter().rev() {
6802 let node = self.frame_state.rendered_frame.dispatch_tree.node(*node_id);
6803 for DispatchActionListener {
6804 action_type,
6805 listener,
6806 } in node.action_listeners.clone()
6807 {
6808 let any_action = action.as_any();
6809 if action_type == any_action.type_id() {
6810 cx.propagate_event = false; #[cfg(feature = "profiler")]
6812 self.core.window_profiler.begin_action_handler(action, cx);
6813 listener(any_action, DispatchPhase::Bubble, self, cx);
6814 #[cfg(feature = "profiler")]
6815 self.core.window_profiler.end_action_handler();
6816
6817 if !cx.propagate_event {
6818 return;
6819 }
6820 }
6821 }
6822 }
6823
6824 if let Some(mut global_listeners) = cx
6826 .global_action_listeners
6827 .remove(&action.as_any().type_id())
6828 {
6829 for listener in global_listeners.iter().rev() {
6830 cx.propagate_event = false; #[cfg(feature = "profiler")]
6833 self.core.window_profiler.begin_action_handler(action, cx);
6834 listener(action.as_any(), DispatchPhase::Bubble, cx);
6835 #[cfg(feature = "profiler")]
6836 self.core.window_profiler.end_action_handler();
6837 if !cx.propagate_event {
6838 break;
6839 }
6840 }
6841
6842 global_listeners.extend(
6843 cx.global_action_listeners
6844 .remove(&action.as_any().type_id())
6845 .unwrap_or_default(),
6846 );
6847
6848 cx.global_action_listeners
6849 .insert(action.as_any().type_id(), global_listeners);
6850 }
6851 }
6852
6853 pub fn observe_global<G: Global>(
6856 &mut self,
6857 cx: &mut App,
6858 f: impl Fn(&mut Window, &mut App) + 'static,
6859 ) -> Subscription {
6860 let window_handle = self.core.handle;
6861 let (subscription, activate) = cx.global_observers.insert(
6862 TypeId::of::<G>(),
6863 Box::new(move |cx| {
6864 window_handle
6865 .update(cx, |_, window, cx| f(window, cx))
6866 .is_ok()
6867 }),
6868 );
6869 cx.defer(move |_| activate());
6870 subscription
6871 }
6872
6873 pub fn activate_window(&self) {
6875 self.core.platform_window.activate();
6876 }
6877
6878 pub fn request_attention(&self) {
6880 self.core.platform_window.request_attention();
6881 }
6882
6883 pub fn minimize_window(&self) {
6885 self.core.platform_window.minimize();
6886 }
6887
6888 pub fn toggle_fullscreen(&self) {
6890 self.core.platform_window.toggle_fullscreen();
6891 }
6892
6893 pub fn toggle_simple_fullscreen(&self) {
6898 self.core.platform_window.toggle_simple_fullscreen();
6899 }
6900
6901 pub fn invalidate_character_coordinates(&self) {
6903 self.on_next_frame(|window, cx| {
6904 if let Some(mut input_handler) = window.core.platform_window.take_input_handler() {
6905 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
6906 window.core.platform_window.update_ime_position(bounds);
6907 }
6908 window.core.platform_window.set_input_handler(input_handler);
6909 }
6910 });
6911 }
6912
6913 pub fn prompt<T>(
6917 &mut self,
6918 level: PromptLevel,
6919 message: &str,
6920 detail: Option<&str>,
6921 answers: &[T],
6922 cx: &mut App,
6923 ) -> oneshot::Receiver<usize>
6924 where
6925 T: Clone + Into<PromptButton>,
6926 {
6927 let prompt_builder = cx.prompt_builder.take();
6928 let Some(prompt_builder) = prompt_builder else {
6929 unreachable!("Re-entrant window prompting is not supported by GPUI");
6930 };
6931
6932 let answers = answers
6933 .iter()
6934 .map(|answer| answer.clone().into())
6935 .collect::<Vec<_>>();
6936
6937 let receiver = match &prompt_builder {
6938 PromptBuilder::Default => self
6939 .core
6940 .platform_window
6941 .prompt(level, message, detail, &answers)
6942 .unwrap_or_else(|| {
6943 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6944 }),
6945 PromptBuilder::Custom(_) => {
6946 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6947 }
6948 };
6949
6950 cx.prompt_builder = Some(prompt_builder);
6951
6952 receiver
6953 }
6954
6955 fn build_custom_prompt(
6956 &mut self,
6957 prompt_builder: &PromptBuilder,
6958 level: PromptLevel,
6959 message: &str,
6960 detail: Option<&str>,
6961 answers: &[PromptButton],
6962 cx: &mut App,
6963 ) -> oneshot::Receiver<usize> {
6964 let (sender, receiver) = oneshot::channel();
6965 let handle = PromptHandle::new(sender);
6966 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
6967 self.core.prompt = Some(handle);
6968 receiver
6969 }
6970
6971 pub fn has_active_prompt(&self) -> bool {
6976 self.core.prompt.is_some()
6977 }
6978
6979 pub fn context_stack(&self) -> Vec<KeyContext> {
6981 let node_id = self.focus_node_id_in_rendered_frame(self.core.focus);
6982 let dispatch_tree = &self.frame_state.rendered_frame.dispatch_tree;
6983 dispatch_tree
6984 .dispatch_path(node_id)
6985 .iter()
6986 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
6987 .collect()
6988 }
6989
6990 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
6992 let node_id = self.focus_node_id_in_rendered_frame(self.core.focus);
6993 let mut actions = self
6994 .frame_state
6995 .rendered_frame
6996 .dispatch_tree
6997 .available_actions(node_id);
6998 for action_type in cx.global_action_listeners.keys() {
6999 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
7000 let action = cx.actions.build_action_type(action_type).ok();
7001 if let Some(action) = action {
7002 actions.insert(ix, action);
7003 }
7004 }
7005 }
7006 actions
7007 }
7008
7009 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
7012 self.frame_state
7013 .rendered_frame
7014 .dispatch_tree
7015 .bindings_for_action(
7016 action,
7017 &self.frame_state.rendered_frame.dispatch_tree.context_stack,
7018 )
7019 }
7020
7021 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
7024 self.frame_state
7025 .rendered_frame
7026 .dispatch_tree
7027 .highest_precedence_binding_for_action(
7028 action,
7029 &self.frame_state.rendered_frame.dispatch_tree.context_stack,
7030 )
7031 }
7032
7033 pub fn bindings_for_action_in_context(
7035 &self,
7036 action: &dyn Action,
7037 context: KeyContext,
7038 ) -> Vec<KeyBinding> {
7039 let dispatch_tree = &self.frame_state.rendered_frame.dispatch_tree;
7040 dispatch_tree.bindings_for_action(action, &[context])
7041 }
7042
7043 pub fn highest_precedence_binding_for_action_in_context(
7046 &self,
7047 action: &dyn Action,
7048 context: KeyContext,
7049 ) -> Option<KeyBinding> {
7050 let dispatch_tree = &self.frame_state.rendered_frame.dispatch_tree;
7051 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
7052 }
7053
7054 pub fn bindings_for_action_in(
7058 &self,
7059 action: &dyn Action,
7060 focus_handle: &FocusHandle,
7061 ) -> Vec<KeyBinding> {
7062 let dispatch_tree = &self.frame_state.rendered_frame.dispatch_tree;
7063 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
7064 return vec![];
7065 };
7066 dispatch_tree.bindings_for_action(action, &context_stack)
7067 }
7068
7069 pub fn highest_precedence_binding_for_action_in(
7073 &self,
7074 action: &dyn Action,
7075 focus_handle: &FocusHandle,
7076 ) -> Option<KeyBinding> {
7077 let dispatch_tree = &self.frame_state.rendered_frame.dispatch_tree;
7078 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
7079 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
7080 }
7081
7082 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
7084 self.frame_state
7085 .rendered_frame
7086 .dispatch_tree
7087 .possible_next_bindings_for_input(input, &self.context_stack())
7088 }
7089
7090 fn context_stack_for_focus_handle(
7091 &self,
7092 focus_handle: &FocusHandle,
7093 ) -> Option<Vec<KeyContext>> {
7094 let dispatch_tree = &self.frame_state.rendered_frame.dispatch_tree;
7095 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
7096 let context_stack: Vec<_> = dispatch_tree
7097 .dispatch_path(node_id)
7098 .into_iter()
7099 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
7100 .collect();
7101 Some(context_stack)
7102 }
7103
7104 pub fn listener_for<T: 'static, E>(
7106 &self,
7107 view: &Entity<T>,
7108 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
7109 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
7110 let view = view.downgrade();
7111 move |e: &E, window: &mut Window, cx: &mut App| {
7112 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
7113 }
7114 }
7115
7116 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
7118 &self,
7119 entity: &Entity<E>,
7120 f: Callback,
7121 ) -> impl Fn(&mut Window, &mut App) + 'static {
7122 let entity = entity.downgrade();
7123 move |window: &mut Window, cx: &mut App| {
7124 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
7125 }
7126 }
7127
7128 pub fn on_window_should_close(
7131 &self,
7132 cx: &App,
7133 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
7134 ) {
7135 let mut cx = self.to_async(cx);
7136 self.core.platform_window.on_should_close(Box::new(move || {
7137 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
7138 }))
7139 }
7140
7141 pub fn on_action(
7150 &mut self,
7151 action_type: TypeId,
7152 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
7153 ) {
7154 self.core.invalidator.debug_assert_paint();
7155
7156 self.frame_state
7157 .next_frame
7158 .dispatch_tree
7159 .on_action(action_type, Rc::new(listener));
7160 }
7161
7162 pub fn on_action_when(
7171 &mut self,
7172 condition: bool,
7173 action_type: TypeId,
7174 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
7175 ) {
7176 self.core.invalidator.debug_assert_paint();
7177
7178 if condition {
7179 self.frame_state
7180 .next_frame
7181 .dispatch_tree
7182 .on_action(action_type, Rc::new(listener));
7183 }
7184 }
7185
7186 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
7189 self.core.platform_window.gpu_specs()
7190 }
7191
7192 pub fn titlebar_double_click(&self) {
7195 self.core
7196 .platform_window
7197 .titlebar_double_click(self.core.is_resizable, self.core.is_minimizable);
7198 }
7199
7200 pub fn window_title(&self) -> String {
7203 self.core.platform_window.get_title()
7204 }
7205
7206 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
7209 self.core.platform_window.tabbed_windows()
7210 }
7211
7212 pub fn tab_bar_visible(&self) -> bool {
7215 self.core.platform_window.tab_bar_visible()
7216 }
7217
7218 pub fn merge_all_windows(&self) {
7221 self.core.platform_window.merge_all_windows()
7222 }
7223
7224 pub fn move_tab_to_new_window(&self) {
7227 self.core.platform_window.move_tab_to_new_window()
7228 }
7229
7230 pub fn toggle_window_tab_overview(&self) {
7233 self.core.platform_window.toggle_window_tab_overview()
7234 }
7235
7236 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
7239 self.core
7240 .platform_window
7241 .set_tabbing_identifier(tabbing_identifier)
7242 }
7243
7244 pub fn play_system_bell(&self) {
7247 self.core.platform_window.play_system_bell()
7248 }
7249
7250 pub fn is_a11y_active(&self) -> bool {
7261 self.core.a11y.is_active()
7262 }
7263
7264 pub fn debug_a11y_tree_json(&self) -> Option<String> {
7266 self.core.a11y.debug_tree_json()
7267 }
7268
7269 pub fn on_a11y_action(
7275 &mut self,
7276 node_id: accesskit::NodeId,
7277 action: accesskit::Action,
7278 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
7279 ) {
7280 self.core
7281 .a11y
7282 .action_listeners
7283 .entry(node_id)
7284 .or_default()
7285 .push((action, Box::new(listener)));
7286 }
7287
7288 #[cfg(not(target_family = "wasm"))]
7289 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
7290 if let Some(mut listeners) = self.core.a11y.action_listeners.remove(&request.target_node) {
7293 let extra_data = request.data.as_ref();
7294 let mut matched = false;
7295 for (action, listener) in &mut listeners {
7296 if *action == request.action {
7297 listener(extra_data, self, cx);
7298 matched = true;
7299 }
7300 }
7301 self.core
7302 .a11y
7303 .action_listeners
7304 .insert(request.target_node, listeners);
7305 if matched {
7306 return;
7307 }
7308 }
7309
7310 match request.action {
7312 accesskit::Action::Click => {
7313 if let Some(bounds) = self
7314 .core
7315 .a11y
7316 .node_bounds
7317 .get(&request.target_node)
7318 .copied()
7319 {
7320 let center = bounds.center();
7321 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
7322 button: MouseButton::Left,
7323 position: center,
7324 modifiers: Modifiers::default(),
7325 click_count: 1,
7326 first_mouse: false,
7327 });
7328 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
7329 button: MouseButton::Left,
7330 position: center,
7331 modifiers: Modifiers::default(),
7332 click_count: 1,
7333 });
7334 self.dispatch_event(mouse_down, cx);
7335 self.dispatch_event(mouse_up, cx);
7336 }
7337 }
7338 accesskit::Action::Focus => {
7339 if let Some(focus_id) = self.core.a11y.focus_ids.get(&request.target_node).copied()
7340 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
7341 {
7342 self.focus(&handle, cx);
7343 }
7344 }
7345 accesskit::Action::Blur => {
7346 self.blur(cx);
7347 }
7348 _ => {
7349 log::debug!(
7350 "Unhandled a11y action: {:?} on {:?}",
7351 request.action,
7352 request.target_node
7353 );
7354 }
7355 }
7356 }
7357
7358 #[cfg(any(feature = "inspector", debug_assertions))]
7360 pub fn toggle_inspector(&mut self, cx: &mut App) {
7361 self.core.inspector = match self.core.inspector {
7362 None => Some(cx.new(|_| Inspector::new())),
7363 Some(_) => None,
7364 };
7365 self.refresh();
7366 }
7367
7368 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
7370 #[cfg(any(feature = "inspector", debug_assertions))]
7371 {
7372 if let Some(inspector) = &self.core.inspector {
7373 return inspector.read(_cx).is_picking();
7374 }
7375 }
7376 false
7377 }
7378
7379 pub(crate) fn set_inspector_element_id(
7383 &mut self,
7384 inspector_element_id: Option<crate::InspectorElementId>,
7385 ) -> Option<crate::InspectorElementId> {
7386 std::mem::replace(
7387 &mut self.frame_state.inspector_element_id,
7388 inspector_element_id,
7389 )
7390 }
7391
7392 #[cfg(any(feature = "inspector", debug_assertions))]
7397 pub fn with_inspector_state<T: 'static, R>(
7398 &mut self,
7399 inspector_id: Option<&crate::InspectorElementId>,
7400 cx: &mut App,
7401 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
7402 ) -> R {
7403 if let Some(inspector_id) = inspector_id
7404 && let Some(inspector) = &self.core.inspector
7405 {
7406 let inspector = inspector.clone();
7407 let active_element_id = inspector.read(cx).active_element_id();
7408 if Some(inspector_id) == active_element_id {
7409 return inspector.update(cx, |inspector, _cx| {
7410 inspector.with_active_element_state(self, f)
7411 });
7412 }
7413 }
7414 f(&mut None, self)
7415 }
7416
7417 #[cfg(any(feature = "inspector", debug_assertions))]
7423 pub fn with_current_inspector_state<T: 'static, R>(
7424 &mut self,
7425 cx: &mut App,
7426 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
7427 ) -> R {
7428 let inspector_id = self.frame_state.inspector_element_id.clone();
7429 self.with_inspector_state(inspector_id.as_ref(), cx, f)
7430 }
7431
7432 #[cfg(any(feature = "inspector", debug_assertions))]
7433 pub(crate) fn build_inspector_element_id(
7434 &mut self,
7435 path: crate::InspectorElementPath,
7436 ) -> crate::InspectorElementId {
7437 self.core.invalidator.debug_assert_paint_or_prepaint();
7438 let path = Rc::new(path);
7439 let next_instance_id = self
7440 .frame_state
7441 .next_frame
7442 .next_inspector_instance_ids
7443 .entry(path.clone())
7444 .or_insert(0);
7445 let instance_id = *next_instance_id;
7446 *next_instance_id += 1;
7447 crate::InspectorElementId { path, instance_id }
7448 }
7449
7450 #[cfg(any(feature = "inspector", debug_assertions))]
7451 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
7452 if let Some(inspector) = self.core.inspector.take() {
7453 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
7454 inspector_element.prepaint_as_root(
7455 point(self.core.viewport_size.width - inspector_width, px(0.0)),
7456 size(inspector_width, self.core.viewport_size.height).into(),
7457 self,
7458 cx,
7459 );
7460 self.core.inspector = Some(inspector);
7461 Some(inspector_element)
7462 } else {
7463 None
7464 }
7465 }
7466
7467 #[cfg(any(feature = "inspector", debug_assertions))]
7468 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
7469 if let Some(mut inspector_element) = inspector_element {
7470 inspector_element.paint(self, cx);
7471 };
7472 }
7473
7474 #[cfg(any(feature = "inspector", debug_assertions))]
7480 pub(crate) fn insert_inspector_hitbox(&mut self, hitbox_id: HitboxId, cx: &App) {
7481 self.core.invalidator.debug_assert_paint_or_prepaint();
7482 if !self.is_inspector_picking(cx) {
7483 return;
7484 }
7485 if let Some(inspector_id) = self.frame_state.inspector_element_id.clone() {
7486 self.frame_state
7487 .next_frame
7488 .inspector_hitboxes
7489 .insert(hitbox_id, inspector_id);
7490 }
7491 }
7492
7493 #[cfg(any(feature = "inspector", debug_assertions))]
7494 fn paint_inspector_hitbox(&mut self, cx: &App) {
7495 if let Some(inspector) = self.core.inspector.as_ref() {
7496 let inspector = inspector.read(cx);
7497 if let Some((hitbox_id, _)) =
7498 self.hovered_inspector_hitbox(inspector, &self.frame_state.next_frame)
7499 && let Some(hitbox) = self
7500 .frame_state
7501 .next_frame
7502 .hitboxes
7503 .iter()
7504 .find(|hitbox| hitbox.id == hitbox_id)
7505 {
7506 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
7507 }
7508 }
7509 }
7510
7511 #[cfg(any(feature = "inspector", debug_assertions))]
7512 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
7513 let Some(inspector) = self.core.inspector.clone() else {
7514 return;
7515 };
7516 if event.downcast_ref::<MouseMoveEvent>().is_some() {
7517 inspector.update(cx, |inspector, _cx| {
7518 if let Some((_, inspector_id)) =
7519 self.hovered_inspector_hitbox(inspector, &self.frame_state.rendered_frame)
7520 {
7521 inspector.hover(inspector_id, self);
7522 }
7523 });
7524 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
7525 inspector.update(cx, |inspector, _cx| {
7526 if let Some((_, inspector_id)) =
7527 self.hovered_inspector_hitbox(inspector, &self.frame_state.rendered_frame)
7528 {
7529 inspector.select(inspector_id, self);
7530 }
7531 });
7532 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
7533 const SCROLL_LINES: f32 = 3.0;
7535 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
7536 let delta_y = event
7537 .delta
7538 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
7539 .y;
7540 if let Some(inspector) = self.core.inspector.clone() {
7541 inspector.update(cx, |inspector, _cx| {
7542 if let Some(depth) = inspector.pick_depth.as_mut() {
7543 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
7544 let max_depth = self.core.mouse_hit_test.ids.len() as f32 - 0.5;
7545 if *depth < 0.0 {
7546 *depth = 0.0;
7547 } else if *depth > max_depth {
7548 *depth = max_depth;
7549 }
7550 if let Some((_, inspector_id)) = self
7551 .hovered_inspector_hitbox(inspector, &self.frame_state.rendered_frame)
7552 {
7553 inspector.set_active_element_id(inspector_id, self);
7554 }
7555 }
7556 });
7557 }
7558 }
7559 }
7560
7561 #[cfg(any(feature = "inspector", debug_assertions))]
7562 fn hovered_inspector_hitbox(
7563 &self,
7564 inspector: &Inspector,
7565 frame: &Frame,
7566 ) -> Option<(HitboxId, crate::InspectorElementId)> {
7567 if let Some(pick_depth) = inspector.pick_depth {
7568 let depth = (pick_depth as i64).try_into().unwrap_or(0);
7569 let max_skipped = self.core.mouse_hit_test.ids.len().saturating_sub(1);
7570 let skip_count = (depth as usize).min(max_skipped);
7571 for hitbox_id in self.core.mouse_hit_test.ids.iter().skip(skip_count) {
7572 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
7573 return Some((*hitbox_id, inspector_id.clone()));
7574 }
7575 }
7576 }
7577 None
7578 }
7579
7580 #[cfg(any(test, feature = "test-support"))]
7583 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
7584 self.core.modifiers = modifiers;
7585 }
7586
7587 #[cfg(any(test, feature = "test-support"))]
7591 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
7592 let event = PlatformInput::MouseMove(MouseMoveEvent {
7593 position,
7594 modifiers: self.core.modifiers,
7595 pressed_button: None,
7596 });
7597 let _ = self.dispatch_event(event, cx);
7598 }
7599}
7600
7601#[derive(Deref, DerefMut)]
7604pub struct WindowHandle<V> {
7605 #[deref]
7606 #[deref_mut]
7607 pub(crate) any_handle: AnyWindowHandle,
7608 state_type: PhantomData<fn(V) -> V>,
7609}
7610
7611impl<V> Debug for WindowHandle<V> {
7612 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7613 f.debug_struct("WindowHandle")
7614 .field("any_handle", &self.any_handle.id.as_u64())
7615 .finish()
7616 }
7617}
7618
7619impl<V: 'static + Render> WindowHandle<V> {
7620 pub fn new(id: WindowId) -> Self {
7623 WindowHandle {
7624 any_handle: AnyWindowHandle {
7625 id,
7626 state_type: TypeId::of::<V>(),
7627 root_entity_type_name: std::any::type_name::<V>(),
7628 },
7629 state_type: PhantomData,
7630 }
7631 }
7632
7633 #[cfg(any(test, feature = "test-support"))]
7637 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
7638 where
7639 C: AppContext,
7640 {
7641 cx.update_window(self.any_handle, |root_view, _, _| {
7642 root_view
7643 .downcast::<V>()
7644 .map_err(|_| anyhow!("the type of the window's root view has changed"))
7645 })?
7646 }
7647
7648 pub fn update<C, R>(
7652 &self,
7653 cx: &mut C,
7654 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
7655 ) -> Result<R>
7656 where
7657 C: AppContext,
7658 {
7659 cx.update_window(self.any_handle, |root_view, window, cx| {
7660 let view = root_view
7661 .downcast::<V>()
7662 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7663
7664 Ok(view.update(cx, |view, cx| update(view, window, cx)))
7665 })?
7666 }
7667
7668 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
7672 let x = cx
7673 .windows
7674 .cell(self.id)
7675 .and_then(|cell| cell.borrow().core.root.clone())
7676 .map(|root_view| root_view.downcast::<V>())
7677 .context("window not found")?
7678 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7679
7680 Ok(x.read(cx))
7681 }
7682
7683 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
7687 where
7688 C: AppContext,
7689 {
7690 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
7691 }
7692
7693 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
7697 where
7698 C: AppContext,
7699 {
7700 cx.read_window(self, |root_view, _cx| root_view)
7701 }
7702
7703 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
7708 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
7709 .ok()
7710 }
7711}
7712
7713impl<V> Copy for WindowHandle<V> {}
7714
7715impl<V> Clone for WindowHandle<V> {
7716 fn clone(&self) -> Self {
7717 *self
7718 }
7719}
7720
7721impl<V> PartialEq for WindowHandle<V> {
7722 fn eq(&self, other: &Self) -> bool {
7723 self.any_handle == other.any_handle
7724 }
7725}
7726
7727impl<V> Eq for WindowHandle<V> {}
7728
7729impl<V> Hash for WindowHandle<V> {
7730 fn hash<H: Hasher>(&self, state: &mut H) {
7731 self.any_handle.hash(state);
7732 }
7733}
7734
7735impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
7736 fn from(val: WindowHandle<V>) -> Self {
7737 val.any_handle
7738 }
7739}
7740
7741#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
7743pub struct AnyWindowHandle {
7744 pub(crate) id: WindowId,
7745 state_type: TypeId,
7746 root_entity_type_name: &'static str,
7747}
7748
7749impl AnyWindowHandle {
7750 pub fn window_id(&self) -> WindowId {
7752 self.id
7753 }
7754
7755 pub fn metrics(&self, cx: &App) -> Option<WindowMetricsHandle> {
7762 cx.windows
7763 .cell(self.id)
7764 .map(|cell| cell.borrow().core.metrics_handle())
7765 }
7766
7767 pub fn root_entity_type_name(&self) -> &'static str {
7769 self.root_entity_type_name
7770 }
7771
7772 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
7775 if TypeId::of::<T>() == self.state_type {
7776 Some(WindowHandle {
7777 any_handle: *self,
7778 state_type: PhantomData,
7779 })
7780 } else {
7781 None
7782 }
7783 }
7784
7785 pub fn update<C, R>(
7789 self,
7790 cx: &mut C,
7791 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
7792 ) -> Result<R>
7793 where
7794 C: AppContext,
7795 {
7796 cx.update_window(self, update)
7797 }
7798
7799 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
7803 where
7804 C: AppContext,
7805 T: 'static,
7806 {
7807 let view = self
7808 .downcast::<T>()
7809 .context("the type of the window's root view has changed")?;
7810
7811 cx.read_window(&view, read)
7812 }
7813}
7814
7815impl HasWindowHandle for Window<'_> {
7816 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
7817 self.core.platform_window.window_handle()
7818 }
7819}
7820
7821impl HasDisplayHandle for Window<'_> {
7822 fn display_handle(
7823 &self,
7824 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
7825 self.core.platform_window.display_handle()
7826 }
7827}
7828
7829#[derive(Clone, Debug, Eq, PartialEq, Hash)]
7834pub enum ElementId {
7835 View(EntityId),
7837 Integer(u64),
7839 Name(SharedString),
7841 Uuid(Uuid),
7843 FocusHandle(FocusId),
7845 NamedInteger(SharedString, u64),
7847 Path(Arc<std::path::Path>),
7849 CodeLocation(core::panic::Location<'static>),
7851 NamedChild(Arc<ElementId>, SharedString),
7853 OpaqueId([u8; 20]),
7855}
7856
7857impl ElementId {
7858 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
7860 Self::NamedInteger(name.into(), integer as u64)
7861 }
7862}
7863
7864impl Display for ElementId {
7865 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7866 match self {
7867 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
7868 ElementId::Integer(ix) => write!(f, "{}", ix)?,
7869 ElementId::Name(name) => write!(f, "{}", name)?,
7870 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
7871 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
7872 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
7873 ElementId::Path(path) => write!(f, "{}", path.display())?,
7874 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
7875 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
7876 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
7877 }
7878
7879 Ok(())
7880 }
7881}
7882
7883impl TryInto<SharedString> for ElementId {
7884 type Error = anyhow::Error;
7885
7886 fn try_into(self) -> anyhow::Result<SharedString> {
7887 if let ElementId::Name(name) = self {
7888 Ok(name)
7889 } else {
7890 anyhow::bail!("element id is not string")
7891 }
7892 }
7893}
7894
7895impl From<usize> for ElementId {
7896 fn from(id: usize) -> Self {
7897 ElementId::Integer(id as u64)
7898 }
7899}
7900
7901impl From<i32> for ElementId {
7902 fn from(id: i32) -> Self {
7903 Self::Integer(id as u64)
7904 }
7905}
7906
7907impl From<SharedString> for ElementId {
7908 fn from(name: SharedString) -> Self {
7909 ElementId::Name(name)
7910 }
7911}
7912
7913impl From<String> for ElementId {
7914 fn from(name: String) -> Self {
7915 ElementId::Name(name.into())
7916 }
7917}
7918
7919impl From<Arc<str>> for ElementId {
7920 fn from(name: Arc<str>) -> Self {
7921 ElementId::Name(name.into())
7922 }
7923}
7924
7925impl From<Arc<std::path::Path>> for ElementId {
7926 fn from(path: Arc<std::path::Path>) -> Self {
7927 ElementId::Path(path)
7928 }
7929}
7930
7931impl From<&'static str> for ElementId {
7932 fn from(name: &'static str) -> Self {
7933 ElementId::Name(SharedString::new_static(name))
7934 }
7935}
7936
7937impl<'a> From<&'a FocusHandle> for ElementId {
7938 fn from(handle: &'a FocusHandle) -> Self {
7939 ElementId::FocusHandle(handle.id)
7940 }
7941}
7942
7943impl From<(&'static str, EntityId)> for ElementId {
7944 fn from((name, id): (&'static str, EntityId)) -> Self {
7945 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
7946 }
7947}
7948
7949impl From<(&'static str, usize)> for ElementId {
7950 fn from((name, id): (&'static str, usize)) -> Self {
7951 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
7952 }
7953}
7954
7955impl From<(SharedString, usize)> for ElementId {
7956 fn from((name, id): (SharedString, usize)) -> Self {
7957 ElementId::NamedInteger(name, id as u64)
7958 }
7959}
7960
7961impl From<(&'static str, u64)> for ElementId {
7962 fn from((name, id): (&'static str, u64)) -> Self {
7963 ElementId::NamedInteger(SharedString::new_static(name), id)
7964 }
7965}
7966
7967impl From<Uuid> for ElementId {
7968 fn from(value: Uuid) -> Self {
7969 Self::Uuid(value)
7970 }
7971}
7972
7973impl From<(&'static str, u32)> for ElementId {
7974 fn from((name, id): (&'static str, u32)) -> Self {
7975 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
7976 }
7977}
7978
7979impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
7980 fn from((id, name): (ElementId, T)) -> Self {
7981 ElementId::NamedChild(Arc::new(id), name.into())
7982 }
7983}
7984
7985impl From<&'static core::panic::Location<'static>> for ElementId {
7986 fn from(location: &'static core::panic::Location<'static>) -> Self {
7987 ElementId::CodeLocation(*location)
7988 }
7989}
7990
7991impl From<[u8; 20]> for ElementId {
7992 fn from(opaque_id: [u8; 20]) -> Self {
7993 ElementId::OpaqueId(opaque_id)
7994 }
7995}
7996
7997#[derive(Clone)]
8000pub struct PaintQuad {
8001 pub bounds: Bounds<Pixels>,
8003 pub corner_radii: Corners<Pixels>,
8005 pub background: Background,
8007 pub border_widths: Edges<Pixels>,
8009 pub border_color: Hsla,
8011 pub border_style: BorderStyle,
8013}
8014
8015impl PaintQuad {
8016 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
8018 PaintQuad {
8019 corner_radii: corner_radii.into(),
8020 ..self
8021 }
8022 }
8023
8024 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
8026 PaintQuad {
8027 border_widths: border_widths.into(),
8028 ..self
8029 }
8030 }
8031
8032 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
8034 PaintQuad {
8035 border_color: border_color.into(),
8036 ..self
8037 }
8038 }
8039
8040 pub fn background(self, background: impl Into<Background>) -> Self {
8042 PaintQuad {
8043 background: background.into(),
8044 ..self
8045 }
8046 }
8047}
8048
8049pub fn quad(
8051 bounds: Bounds<Pixels>,
8052 corner_radii: impl Into<Corners<Pixels>>,
8053 background: impl Into<Background>,
8054 border_widths: impl Into<Edges<Pixels>>,
8055 border_color: impl Into<Hsla>,
8056 border_style: BorderStyle,
8057) -> PaintQuad {
8058 PaintQuad {
8059 bounds,
8060 corner_radii: corner_radii.into(),
8061 background: background.into(),
8062 border_widths: border_widths.into(),
8063 border_color: border_color.into(),
8064 border_style,
8065 }
8066}
8067
8068pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
8070 PaintQuad {
8071 bounds: bounds.into(),
8072 corner_radii: (0.).into(),
8073 background: background.into(),
8074 border_widths: (0.).into(),
8075 border_color: transparent_black(),
8076 border_style: BorderStyle::default(),
8077 }
8078}
8079
8080pub fn outline(
8082 bounds: impl Into<Bounds<Pixels>>,
8083 border_color: impl Into<Hsla>,
8084 border_style: BorderStyle,
8085) -> PaintQuad {
8086 PaintQuad {
8087 bounds: bounds.into(),
8088 corner_radii: (0.).into(),
8089 background: transparent_black().into(),
8090 border_widths: (1.).into(),
8091 border_color: border_color.into(),
8092 border_style,
8093 }
8094}
8095
8096#[cfg(test)]
8097mod tests {
8098 use std::{
8099 cell::{Cell, RefCell},
8100 path::PathBuf,
8101 rc::Rc,
8102 time::Duration,
8103 };
8104
8105 use crate::{
8106 AnyWindowHandle, App, AppContext as _, ArenaClearNeeded, Bounds, Context, DispatchPhase,
8107 DragMoveEvent, Empty, ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent,
8108 FocusHandle, FocusId, FramePipeline, InputEvent as _, InteractiveElement as _, IntoElement,
8109 KeyDownEvent, Keystroke, LongPressEvent, MouseButton, MouseDownEvent, MouseMoveEvent,
8110 ParentElement, Pixels, PlatformInput, Point, Render, RequestFrameOptions,
8111 StandardImmediatePipeline, StatefulInteractiveElement as _, Styled, TestAppContext,
8112 TouchDragEvent, TouchEvent, TouchId, TouchPhase, Window, WindowAppearance, WindowMetrics,
8113 WindowOptions, canvas, div, point, px, size,
8114 };
8115
8116 #[gpui::test]
8120 fn test_window_visibility(cx: &mut TestAppContext) {
8121 use crate::WindowVisibility;
8122
8123 let window = cx.add_window(|_, _| EmptyView);
8124 let observed = Rc::new(RefCell::new(Vec::new()));
8125 let _subscription = window
8126 .update(cx, {
8127 let observed = observed.clone();
8128 move |_, window, _| {
8129 assert_eq!(window.visibility(), WindowVisibility::Visible);
8130 assert!(window.is_visible());
8131 window.observe_window_visibility(move |visibility, window, _| {
8132 assert_eq!(window.visibility(), visibility);
8133 observed.borrow_mut().push(visibility);
8134 })
8135 }
8136 })
8137 .unwrap();
8138 let test_window = cx.test_window(window.into());
8139 let frame_wake_count = test_window.frame_wake_count();
8140
8141 test_window.simulate_visibility_change(WindowVisibility::Hidden);
8142 assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
8143 window
8144 .update(cx, |_, window, _| assert!(!window.is_visible()))
8145 .unwrap();
8146
8147 test_window.simulate_visibility_change(WindowVisibility::Hidden);
8149 assert_eq!(observed.borrow().len(), 1);
8150
8151 test_window.simulate_visibility_change(WindowVisibility::Visible);
8152 assert_eq!(
8153 *observed.borrow(),
8154 [WindowVisibility::Hidden, WindowVisibility::Visible]
8155 );
8156 window
8157 .update(cx, |_, window, _| assert!(window.is_visible()))
8158 .unwrap();
8159 assert_eq!(test_window.frame_wake_count(), frame_wake_count);
8160 }
8161
8162 #[gpui::test]
8165 fn a_window_draws_through_its_frame_pipeline(cx: &mut TestAppContext) {
8166 let recorded: Rc<RefCell<Vec<&'static str>>> = Rc::new(RefCell::new(Vec::new()));
8167 let recorder = recorded.clone();
8168 cx.update(move |cx| {
8169 cx.set_frame_pipeline_factory(Rc::new(move |_| {
8170 Box::new(RecordingPipeline(recorder.clone()))
8171 }));
8172 });
8173
8174 let window = cx.add_window(|_, _| EmptyView);
8175 recorded.borrow_mut().clear();
8176 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8177 .unwrap();
8178
8179 let phases = recorded.borrow();
8180 assert!(
8181 phases.starts_with(&[
8182 "begin_frame",
8183 "draw_roots",
8184 "finish_frame",
8185 "complete_frame",
8186 "end_frame"
8187 ]),
8188 "frame ran {phases:?}"
8189 );
8190 }
8191
8192 struct RecordingPipeline(Rc<RefCell<Vec<&'static str>>>);
8195
8196 impl FramePipeline for RecordingPipeline {
8197 fn begin_frame(&mut self, window: &mut Window, cx: &mut App) {
8198 self.0.borrow_mut().push("begin_frame");
8199 window.begin_frame(cx);
8200 }
8201
8202 fn draw_roots(&mut self, window: &mut Window, cx: &mut App) {
8203 self.0.borrow_mut().push("draw_roots");
8204 window.draw_roots(cx);
8205 }
8206
8207 fn finish_frame(&mut self, window: &mut Window, cx: &mut App) {
8208 self.0.borrow_mut().push("finish_frame");
8209 window.finish_frame(cx);
8210 }
8211
8212 fn complete_frame(&mut self, window: &mut Window, cx: &mut App) -> Option<FocusId> {
8213 self.0.borrow_mut().push("complete_frame");
8214 window.complete_frame(cx)
8215 }
8216
8217 fn end_frame(
8218 &mut self,
8219 window: &mut Window,
8220 cx: &mut App,
8221 focus_before_listeners: Option<FocusId>,
8222 ) {
8223 self.0.borrow_mut().push("end_frame");
8224 window.end_frame(cx, focus_before_listeners);
8225 }
8226 }
8227
8228 #[gpui::test]
8231 fn a_frame_that_skips_drawing_still_completes(cx: &mut TestAppContext) {
8232 cx.skip_drawing();
8233 let window = cx.add_window(|_, _| EmptyView);
8234
8235 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8236 .unwrap();
8237 }
8238
8239 #[cfg(debug_assertions)]
8242 #[gpui::test]
8243 #[should_panic(expected = "paint_roots ran while the frame was Evaluated")]
8244 fn a_frame_pass_out_of_order_is_rejected(cx: &mut TestAppContext) {
8245 let window = cx.add_window(|_, _| EmptyView);
8246
8247 cx.update_window(window.into(), |_, window, cx| {
8248 window.begin_frame(cx);
8249 let roots = window.evaluate_roots(cx);
8250 window.paint_roots(roots, cx);
8253 })
8254 .unwrap();
8255 }
8256
8257 struct PacingPipeline {
8259 frames: Rc<Cell<usize>>,
8260 asks: Rc<Cell<usize>>,
8261 allow: bool,
8262 }
8263
8264 impl FramePipeline for PacingPipeline {
8265 fn should_render(&mut self, is_dirty: bool, _metrics: &WindowMetrics) -> bool {
8266 self.asks.set(self.asks.get() + 1);
8267 self.allow && is_dirty
8268 }
8269
8270 fn draw(&mut self, window: &mut Window, cx: &mut App) -> ArenaClearNeeded {
8271 self.frames.set(self.frames.get() + 1);
8272 FramePipeline::draw(&mut StandardImmediatePipeline, window, cx)
8273 }
8274 }
8275
8276 fn install_pacing_pipeline(
8278 cx: &mut TestAppContext,
8279 frames: Rc<Cell<usize>>,
8280 asks: Rc<Cell<usize>>,
8281 allow: bool,
8282 ) {
8283 cx.update(move |cx| {
8284 cx.set_frame_pipeline_factory(Rc::new(move |_| {
8285 Box::new(PacingPipeline {
8286 frames: frames.clone(),
8287 asks: asks.clone(),
8288 allow,
8289 })
8290 }));
8291 });
8292 }
8293
8294 #[gpui::test]
8296 fn a_pipeline_can_defer_a_frame(cx: &mut TestAppContext) {
8297 let frames = Rc::new(Cell::new(0));
8298 let asks = Rc::new(Cell::new(0));
8299 install_pacing_pipeline(cx, frames.clone(), asks.clone(), false);
8300 let window = cx.add_window(|_, _| EmptyView);
8301 let test_window = cx.test_window(window.into());
8302 frames.set(0);
8303 asks.set(0);
8304
8305 window.update(cx, |_, _, cx| cx.notify()).unwrap();
8306 test_window.simulate_frame_request(RequestFrameOptions::default());
8307
8308 assert!(asks.get() > 0, "the pipeline was asked about the frame");
8309 assert_eq!(frames.get(), 0, "the deferred frame was never drawn");
8310 }
8311
8312 #[gpui::test]
8314 fn a_pipeline_can_allow_a_frame(cx: &mut TestAppContext) {
8315 let frames = Rc::new(Cell::new(0));
8316 let asks = Rc::new(Cell::new(0));
8317 install_pacing_pipeline(cx, frames.clone(), asks, true);
8318 let window = cx.add_window(|_, _| EmptyView);
8319 frames.set(0);
8320
8321 window.update(cx, |_, _, cx| cx.notify()).unwrap();
8322
8323 assert!(frames.get() > 0, "the allowed frame was drawn");
8324 }
8325
8326 #[gpui::test]
8327 fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
8328 let window = cx.add_window(|_, _| EmptyView);
8329 let mut platform_window = cx.test_window(window.into());
8330 platform_window.simulate_resize(size(px(400.), px(800.)));
8331 window
8332 .update(cx, |_, window, _| {
8333 assert_eq!(
8334 window.visual_viewport_bounds(),
8335 Bounds::new(Point::default(), size(px(400.), px(800.)))
8336 );
8337 assert_eq!(
8338 window.fully_visible_bounds(),
8339 window.visual_viewport_bounds()
8340 );
8341 })
8342 .unwrap();
8343
8344 platform_window.simulate_frame_request(RequestFrameOptions::default());
8345 let wakes = platform_window.frame_wake_count();
8346 let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
8347 platform_window.simulate_visual_viewport_change(visual_bounds);
8348 assert!(platform_window.frame_wake_count() > wakes);
8349 platform_window.simulate_frame_request(RequestFrameOptions::default());
8350 let wakes = platform_window.frame_wake_count();
8351 platform_window.simulate_insets_change(crate::WindowInsets {
8352 safe_area: crate::Edges {
8353 top: px(60.),
8354 right: px(20.),
8355 bottom: px(30.),
8356 left: px(-10.),
8357 },
8358 ime: crate::Edges {
8359 bottom: px(350.),
8360 ..Default::default()
8361 },
8362 });
8363 assert!(platform_window.frame_wake_count() > wakes);
8364 window
8365 .update(cx, |_, window, _| {
8366 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
8367 assert_eq!(window.visual_viewport_bounds(), visual_bounds);
8368 assert_eq!(
8369 window.fully_visible_bounds(),
8370 Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
8371 );
8372 window.request_virtual_keyboard();
8373 window.dismiss_virtual_keyboard();
8374 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
8375 })
8376 .unwrap();
8377 assert_eq!(platform_window.virtual_keyboard_requests(), 1);
8378 assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
8379
8380 platform_window.simulate_insets_change(crate::WindowInsets {
8381 safe_area: crate::Edges {
8382 top: px(900.),
8383 left: px(500.),
8384 ..Default::default()
8385 },
8386 ..Default::default()
8387 });
8388 window
8389 .update(cx, |_, window, _| {
8390 assert_eq!(
8391 window.fully_visible_bounds().size,
8392 size(Pixels::ZERO, Pixels::ZERO)
8393 );
8394 })
8395 .unwrap();
8396 }
8397
8398 struct EmptyView;
8399
8400 impl Render for EmptyView {
8401 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8402 div()
8403 }
8404 }
8405
8406 struct OpensWindowOnPaint {
8407 opened: Rc<Cell<bool>>,
8408 }
8409
8410 impl Render for OpensWindowOnPaint {
8411 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8412 let opened = self.opened.clone();
8413 div()
8414 .size_full()
8415 .child(canvas(
8416 |_, _, _| {},
8417 move |_, _, _window, cx| {
8418 if !opened.replace(true) {
8419 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
8420 .unwrap();
8421 }
8422 },
8423 ))
8424 .child(div().child("after"))
8428 }
8429 }
8430
8431 #[test]
8437 fn test_window_opened_during_draw_defers_arena_clear() {
8438 let mut cx = TestAppContext::single();
8439
8440 let opened = Rc::new(Cell::new(false));
8441 let window = cx.add_window({
8443 let opened = opened.clone();
8444 move |_, _| OpensWindowOnPaint { opened }
8445 });
8446
8447 assert!(opened.get());
8448 assert_eq!(cx.windows().len(), 2);
8449
8450 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8453 .unwrap();
8454 }
8455
8456 #[test]
8457 fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
8458 let mut cx = TestAppContext::single();
8459 let window = cx.add_window(|_, _| EmptyView);
8460 let handle: AnyWindowHandle = window.into();
8461 let window_state = |cx: &mut TestAppContext| {
8462 cx.update_window(handle, |_, window, _| {
8463 (
8464 window.scale_factor(),
8465 window.bounds(),
8466 window.viewport_size(),
8467 )
8468 })
8469 .unwrap()
8470 };
8471
8472 let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
8473 assert_eq!(scale_factor, 2.0);
8474
8475 for (scale_factor, resized_size) in [
8476 (1.0, size(px(800.), px(600.))),
8477 (1.25, size(px(640.), px(480.))),
8478 (2.0, size(px(1024.), px(768.))),
8479 ] {
8480 cx.simulate_window_scale_factor_change(handle, scale_factor);
8481 assert_eq!(
8482 window_state(&mut cx),
8483 (scale_factor, expected_bounds, expected_bounds.size)
8484 );
8485
8486 cx.simulate_window_resize(handle, resized_size);
8487 expected_bounds.size = resized_size;
8488 assert_eq!(
8489 window_state(&mut cx),
8490 (scale_factor, expected_bounds, resized_size)
8491 );
8492 }
8493 }
8494
8495 #[gpui::test]
8496 fn metrics_handle_agrees_with_the_window_and_tracks_resizes(cx: &mut TestAppContext) {
8497 let window = cx.add_window(|_, _| EmptyView);
8498 let handle: AnyWindowHandle = window.into();
8499
8500 let metrics = cx.read(|app| handle.metrics(app).expect("window is open"));
8501 assert_eq!(metrics.id(), handle.window_id());
8502 assert!(metrics.display_id().is_some());
8503
8504 let window_state = |cx: &mut TestAppContext| {
8506 cx.update_window(handle, |_, window, _| {
8507 assert_eq!(metrics.bounds(), window.bounds());
8508 assert_eq!(metrics.viewport(), window.visual_viewport_bounds());
8509 assert_eq!(metrics.content_size(), window.viewport_size());
8510 assert_eq!(metrics.scale_factor(), window.scale_factor());
8511 assert_eq!(metrics.is_active(), window.is_window_active());
8512 assert_eq!(metrics.is_fullscreen(), window.is_fullscreen());
8513 })
8514 .unwrap();
8515 };
8516 window_state(cx);
8517
8518 cx.simulate_window_resize(handle, size(px(800.), px(600.)));
8519 cx.simulate_window_scale_factor_change(handle, 1.25);
8520
8521 assert_eq!(metrics.content_size(), size(px(800.), px(600.)));
8524 assert_eq!(metrics.scale_factor(), 1.25);
8525 window_state(cx);
8526 }
8527
8528 #[gpui::test]
8532 fn metrics_track_viewport_changes_that_do_not_resize(cx: &mut TestAppContext) {
8533 let window = cx.add_window(|_, _| EmptyView);
8534 let handle: AnyWindowHandle = window.into();
8535 let metrics = cx.read(|app| handle.metrics(app).expect("window is open"));
8536
8537 let narrow = Bounds::new(point(px(0.), px(120.)), size(px(400.), px(680.)));
8538 assert_ne!(metrics.viewport(), narrow);
8539
8540 cx.simulate_window_visual_viewport_change(handle, narrow);
8541 assert_eq!(metrics.viewport(), narrow);
8542
8543 cx.update_window(handle, |_, window, _| {
8544 assert_eq!(metrics.viewport(), window.visual_viewport_bounds());
8545 assert_eq!(metrics.content_size(), window.viewport_size());
8547 })
8548 .unwrap();
8549 }
8550
8551 #[gpui::test]
8555 fn updating_a_window_from_within_its_own_update_reports_an_error(cx: &mut TestAppContext) {
8556 let window = cx.add_window(|_, _| EmptyView);
8557 let handle: AnyWindowHandle = window.into();
8558
8559 let nested_error = cx
8560 .update_window(handle, |_, _window, cx| {
8561 cx.update_window(handle, |_, _, _| ())
8562 .map_err(|error| error.to_string())
8563 .unwrap_err()
8564 })
8565 .expect("the outer update completes");
8566
8567 assert!(
8568 nested_error.contains("already being updated"),
8569 "unexpected error: {nested_error}"
8570 );
8571 }
8572
8573 #[gpui::test]
8576 fn a_window_can_be_updated_from_within_another_windows_update(cx: &mut TestAppContext) {
8577 let first: AnyWindowHandle = cx.add_window(|_, _| EmptyView).into();
8578 let second: AnyWindowHandle = cx.add_window(|_, _| EmptyView).into();
8579
8580 let expected = cx
8581 .update_window(second, |_, window, _| window.viewport_size())
8582 .expect("the window can be updated on its own");
8583
8584 let from_inner = cx
8585 .update_window(first, |_, _window, cx| {
8586 cx.update_window(second, |_, window, _| window.viewport_size())
8587 .expect("the inner update succeeds")
8588 })
8589 .expect("the outer update completes");
8590
8591 assert_eq!(from_inner, expected);
8592 }
8593
8594 #[gpui::test]
8597 fn metrics_handle_is_readable_from_another_thread(cx: &mut TestAppContext) {
8598 let window = cx.add_window(|_, _| EmptyView);
8599 let handle: AnyWindowHandle = window.into();
8600 cx.simulate_window_resize(handle, size(px(640.), px(480.)));
8601 let metrics = cx.read(|app| handle.metrics(app).expect("window is open"));
8602
8603 let (id, content_size, scale_factor) = std::thread::spawn(move || {
8604 (metrics.id(), metrics.content_size(), metrics.scale_factor())
8605 })
8606 .join()
8607 .expect("the metrics reader did not panic");
8608
8609 assert_eq!(id, handle.window_id());
8610 assert_eq!(content_size, size(px(640.), px(480.)));
8611 assert_eq!(scale_factor, 2.0);
8612 }
8613
8614 #[gpui::test]
8619 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
8620 let window = cx.add_window(|_, _| EmptyView);
8621 let test_window = cx.test_window(window.into());
8622
8623 assert!(
8627 test_window.frame_wake_count() >= 1,
8628 "opening a window must wake the frame source for the initial frame"
8629 );
8630
8631 test_window.simulate_frame_request(RequestFrameOptions::default());
8633
8634 let baseline = test_window.frame_wake_count();
8637 test_window.simulate_frame_request(RequestFrameOptions::default());
8638 window.update(cx, |_, _, _| {}).unwrap();
8639 assert_eq!(
8640 test_window.frame_wake_count(),
8641 baseline,
8642 "clean frames and non-notifying updates must not wake the frame source"
8643 );
8644
8645 window.update(cx, |_, _, cx| cx.notify()).unwrap();
8647 assert!(
8648 test_window.frame_wake_count() > baseline,
8649 "notifying a view in an idle window must wake the frame source"
8650 );
8651
8652 test_window.simulate_frame_request(RequestFrameOptions::default());
8654 let baseline = test_window.frame_wake_count();
8655 test_window.simulate_frame_request(RequestFrameOptions::default());
8656 assert_eq!(
8657 test_window.frame_wake_count(),
8658 baseline,
8659 "serving demand must return the window to idle"
8660 );
8661
8662 window
8664 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
8665 .unwrap();
8666 assert!(
8667 test_window.frame_wake_count() > baseline,
8668 "scheduling a next-frame callback in an idle window must wake the frame source"
8669 );
8670 }
8671
8672 #[gpui::test]
8677 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
8678 let window = cx.add_window(|_, _| EmptyView);
8679 let test_window = cx.test_window(window.into());
8680 test_window.simulate_frame_request(RequestFrameOptions::default());
8683
8684 let callback_ran = Rc::new(Cell::new(false));
8685 window
8686 .update(cx, {
8687 let callback_ran = callback_ran.clone();
8688 move |_, window, _| {
8689 window.on_next_frame(move |_, _| callback_ran.set(true));
8690 }
8691 })
8692 .unwrap();
8693
8694 let baseline = test_window.frame_wake_count();
8695 test_window.simulate_frame_request(RequestFrameOptions::default());
8696 assert!(
8703 test_window.frame_wake_count() > baseline || callback_ran.get(),
8704 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
8705 );
8706 }
8707
8708 #[gpui::test]
8709 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
8710 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
8711
8712 let window = cx.add_window(|_, _| EmptyView);
8713 window
8714 .update(cx, |_, window, _| {
8715 assert!(matches!(
8716 window.window_handle(),
8717 Err(HandleError::NotSupported)
8718 ));
8719 assert!(matches!(
8720 window.display_handle(),
8721 Err(HandleError::NotSupported)
8722 ));
8723 })
8724 .unwrap();
8725 }
8726
8727 #[gpui::test]
8728 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
8729 let window = cx.add_window(|_, _| EmptyView);
8730 let observed_appearance = Rc::new(Cell::new(None));
8731 let _subscription = window
8732 .update(cx, {
8733 let observed_appearance = observed_appearance.clone();
8734 move |_, window, _| {
8735 window.observe_window_appearance(move |window, _| {
8736 observed_appearance.set(Some(window.appearance()));
8737 })
8738 }
8739 })
8740 .unwrap();
8741 let test_window = cx.test_window(window.into());
8742
8743 cx.update(|_| {
8744 test_window.simulate_appearance_change(WindowAppearance::Dark);
8745 assert_eq!(observed_appearance.get(), None);
8746 });
8747 cx.run_until_parked();
8748
8749 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
8750 }
8751
8752 #[gpui::test]
8753 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
8754 let window = cx.add_window(|_, _| Empty);
8755 let test_window = cx.test_window(window.into());
8756
8757 assert!(test_window.simulate_scheduled_frame());
8758 assert!(test_window.simulate_scheduled_frame());
8759 assert!(!test_window.frame_scheduled());
8760
8761 cx.update_window(window.into(), |_, window, _| {
8762 window.core.active.set(true);
8763 window.on_next_frame(|_, _| {});
8764 })
8765 .unwrap();
8766 assert!(
8767 test_window.frame_scheduled(),
8768 "queuing work on a parked window must wake the render loop"
8769 );
8770
8771 assert!(test_window.simulate_scheduled_frame());
8772 assert!(
8773 test_window.frame_scheduled(),
8774 "presenting the frame must await one compositor callback"
8775 );
8776 assert!(test_window.simulate_scheduled_frame());
8777 assert!(!test_window.frame_scheduled());
8778 }
8779
8780 #[gpui::test]
8781 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
8782 let window = cx.add_window(|_, _| Empty);
8783 let test_window = cx.test_window(window.into());
8784
8785 assert!(test_window.simulate_scheduled_frame());
8786 assert!(test_window.simulate_scheduled_frame());
8787 assert!(!test_window.frame_scheduled());
8788
8789 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8790 .unwrap();
8791
8792 assert!(
8793 test_window.frame_scheduled(),
8794 "a rendered scene awaiting presentation must wake the render loop"
8795 );
8796 }
8797
8798 #[gpui::test]
8799 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
8800 let window = cx.add_window(|_, _| Empty);
8801 let test_window = cx.test_window(window.into());
8802
8803 let callback_ran = Rc::new(Cell::new(false));
8804 cx.update_window(window.into(), |_, window, _| {
8805 window.core.active.set(true);
8808 let callback_ran = callback_ran.clone();
8809 window.on_next_frame(move |window, _| {
8810 window.on_next_frame(move |_, _| callback_ran.set(true));
8811 });
8812 })
8813 .unwrap();
8814
8815 assert!(test_window.simulate_scheduled_frame());
8816 assert!(!callback_ran.get());
8817 assert!(
8818 test_window.frame_scheduled(),
8819 "a callback queued mid-frame must schedule a follow-up before the loop parks"
8820 );
8821
8822 assert!(test_window.simulate_scheduled_frame());
8823 assert!(callback_ran.get());
8824 }
8825
8826 struct RootView {
8827 explicit_size: bool,
8828 child_bounds: Rc<Cell<Bounds<Pixels>>>,
8829 }
8830
8831 impl Render for RootView {
8832 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8833 let child_bounds = self.child_bounds.clone();
8834 let root = div().flex().flex_col().child(
8835 canvas(
8836 move |bounds, _, _| child_bounds.set(bounds),
8837 |_, _, _, _| {},
8838 )
8839 .size_full(),
8840 );
8841 if self.explicit_size {
8842 root.w(px(300.)).h(px(200.))
8843 } else {
8844 root
8845 }
8846 }
8847 }
8848
8849 #[test]
8850 fn auto_sized_window_root_fills_the_window() {
8851 let mut cx = TestAppContext::single();
8852 let child_bounds = Rc::new(Cell::new(Bounds::default()));
8853 let window = cx.add_window({
8854 let child_bounds = child_bounds.clone();
8855 move |_, _| RootView {
8856 explicit_size: false,
8857 child_bounds,
8858 }
8859 });
8860
8861 let viewport_size = cx
8862 .update_window(window.into(), |_, window, cx| {
8863 window.draw(cx).clear(cx);
8864 window.viewport_size()
8865 })
8866 .unwrap();
8867
8868 assert_eq!(child_bounds.get().size, viewport_size);
8869 }
8870
8871 #[test]
8872 fn explicitly_sized_window_root_keeps_its_size() {
8873 let mut cx = TestAppContext::single();
8874 let child_bounds = Rc::new(Cell::new(Bounds::default()));
8875 let window = cx.add_window({
8876 let child_bounds = child_bounds.clone();
8877 move |_, _| RootView {
8878 explicit_size: true,
8879 child_bounds,
8880 }
8881 });
8882
8883 cx.update_window(window.into(), |_, window, cx| {
8884 window.draw(cx).clear(cx);
8885 })
8886 .unwrap();
8887
8888 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
8889 }
8890
8891 struct FileDragView {
8892 path: PathBuf,
8893 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
8894 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
8895 }
8896
8897 struct FileDropExitView(Rc<Cell<usize>>);
8898
8899 impl Render for FileDropExitView {
8900 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8901 div().size_full().on_file_drop_exit({
8902 let observed_file_drop_exit = self.0.clone();
8903 move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
8904 })
8905 }
8906 }
8907
8908 impl Render for FileDragView {
8909 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8910 div()
8911 .id("file-drag")
8912 .size_full()
8913 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
8914 .external_drag_payload(|path: &PathBuf, _, _| {
8915 Some(ExternalDragPayload::Files(FileDragPaths::new([(
8916 path.clone(),
8917 true,
8918 )])))
8919 })
8920 .on_drag_move({
8921 let observed_drag_moves = self.observed_drag_moves.clone();
8922 move |event: &DragMoveEvent<PathBuf>, _, _| {
8923 observed_drag_moves.borrow_mut().push(event.event.position);
8924 }
8925 })
8926 .on_drop({
8927 let observed_drops = self.observed_drops.clone();
8928 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
8929 })
8930 }
8931 }
8932
8933 #[gpui::test]
8934 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
8935 struct Drag {
8936 window: AnyWindowHandle,
8937 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
8938 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
8939 }
8940
8941 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
8942 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
8943 let observed_drops = Rc::new(RefCell::new(Vec::new()));
8944 let window: AnyWindowHandle = cx
8945 .add_window({
8946 let observed_drag_moves = observed_drag_moves.clone();
8947 let observed_drops = observed_drops.clone();
8948 move |_, _| FileDragView {
8949 path,
8950 observed_drag_moves,
8951 observed_drops,
8952 }
8953 })
8954 .into();
8955 cx.test_window(window)
8956 .set_start_external_drag_result(platform_result);
8957
8958 let update_result = cx.update_window(window, |_, window, cx| {
8959 window.draw(cx).clear(cx);
8960 window.dispatch_event(
8961 MouseDownEvent {
8962 position: point(px(10.), px(10.)),
8963 button: MouseButton::Left,
8964 modifiers: Default::default(),
8965 click_count: 1,
8966 first_mouse: false,
8967 }
8968 .to_platform_input(),
8969 cx,
8970 );
8971 window.dispatch_event(
8972 MouseMoveEvent {
8973 position: point(px(20.), px(20.)),
8974 pressed_button: Some(MouseButton::Left),
8975 modifiers: Default::default(),
8976 }
8977 .to_platform_input(),
8978 cx,
8979 );
8980 assert!(cx.active_drag.is_some());
8981 });
8982 assert!(
8983 update_result.is_ok(),
8984 "failed to start drag: {update_result:?}"
8985 );
8986
8987 assert!(cx.test_window(window).external_drag_files().is_empty());
8988 Drag {
8989 window,
8990 observed_drag_moves,
8991 observed_drops,
8992 }
8993 }
8994
8995 let successful_path = PathBuf::from("/tmp/successful-drag");
8996 let successful = start_drag(cx, successful_path.clone(), true);
8997 let outside_position = point(px(-1.), px(20.));
8998 let update_result = cx.update_window(successful.window, |_, window, cx| {
8999 window.dispatch_event(
9000 MouseMoveEvent {
9001 position: outside_position,
9002 pressed_button: Some(MouseButton::Left),
9003 modifiers: Default::default(),
9004 }
9005 .to_platform_input(),
9006 cx,
9007 );
9008 assert!(cx.active_drag.is_none());
9009 });
9010 assert!(
9011 update_result.is_ok(),
9012 "failed to promote drag: {update_result:?}"
9013 );
9014 assert_eq!(
9015 cx.test_window(successful.window).external_drag_files(),
9016 [(successful_path.clone(), true)]
9017 );
9018 assert_eq!(
9021 successful.observed_drag_moves.borrow().last(),
9022 Some(&outside_position)
9023 );
9024
9025 let first_destination_exit_count = Rc::new(Cell::new(0));
9026 let first_destination: AnyWindowHandle = cx
9027 .add_window({
9028 let first_destination_exit_count = first_destination_exit_count.clone();
9029 move |_, _| FileDropExitView(first_destination_exit_count)
9030 })
9031 .into();
9032 let second_destination_exit_count = Rc::new(Cell::new(0));
9033 let second_destination: AnyWindowHandle = cx
9034 .add_window({
9035 let second_destination_exit_count = second_destination_exit_count.clone();
9036 move |_, _| FileDropExitView(second_destination_exit_count)
9037 })
9038 .into();
9039 let reentry_position = point(px(30.), px(30.));
9040 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
9041 let update_result = cx.update_window(first_destination, |_, window, cx| {
9042 window.draw(cx).clear(cx);
9043 window.dispatch_event(
9044 FileDropEvent::Entered {
9045 position: reentry_position,
9046 paths: external_paths(),
9047 }
9048 .to_platform_input(),
9049 cx,
9050 );
9051 assert!(
9052 cx.active_drag
9053 .as_ref()
9054 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9055 );
9056 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9057 assert!(cx.active_drag.is_none());
9058 assert_eq!(first_destination_exit_count.get(), 1);
9059 assert_eq!(second_destination_exit_count.get(), 0);
9060 });
9061 assert!(
9062 update_result.is_ok(),
9063 "failed to handle drag in first destination window: {update_result:?}"
9064 );
9065
9066 let update_result = cx.update_window(second_destination, |_, window, cx| {
9067 window.draw(cx).clear(cx);
9068 window.dispatch_event(
9069 PlatformInput::KeyDown(KeyDownEvent {
9070 keystroke: Keystroke::parse("down").expect("valid keystroke"),
9071 is_held: false,
9072 prefer_character_input: false,
9073 }),
9074 cx,
9075 );
9076 window.dispatch_event(
9077 FileDropEvent::Entered {
9078 position: reentry_position,
9079 paths: external_paths(),
9080 }
9081 .to_platform_input(),
9082 cx,
9083 );
9084 assert!(
9085 cx.active_drag
9086 .as_ref()
9087 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9088 );
9089 assert_eq!(first_destination_exit_count.get(), 1);
9090 assert_eq!(second_destination_exit_count.get(), 0);
9091
9092 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9093 assert!(cx.active_drag.is_none());
9094 assert_eq!(first_destination_exit_count.get(), 1);
9095 assert_eq!(second_destination_exit_count.get(), 1);
9096 });
9097 assert!(
9098 update_result.is_ok(),
9099 "failed to handle drag in second destination window: {update_result:?}"
9100 );
9101
9102 let update_result = cx.update_window(successful.window, |_, window, cx| {
9103 window.dispatch_event(
9104 FileDropEvent::Entered {
9105 position: reentry_position,
9106 paths: external_paths(),
9107 }
9108 .to_platform_input(),
9109 cx,
9110 );
9111 assert!(
9112 cx.active_drag
9113 .as_ref()
9114 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9115 );
9116 assert_eq!(
9117 successful.observed_drag_moves.borrow().last(),
9118 Some(&reentry_position)
9119 );
9120
9121 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9122 assert!(cx.active_drag.is_none());
9123
9124 window.dispatch_event(
9125 FileDropEvent::Entered {
9126 position: reentry_position,
9127 paths: external_paths(),
9128 }
9129 .to_platform_input(),
9130 cx,
9131 );
9132 assert!(
9133 cx.active_drag
9134 .as_ref()
9135 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9136 );
9137
9138 window.dispatch_event(
9139 FileDropEvent::Submit {
9140 position: reentry_position,
9141 }
9142 .to_platform_input(),
9143 cx,
9144 );
9145 assert_eq!(
9146 successful.observed_drops.borrow().as_slice(),
9147 std::slice::from_ref(&successful_path)
9148 );
9149 assert!(cx.active_drag.is_none());
9150
9151 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9152 assert!(cx.active_drag.is_none());
9153 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
9154 assert!(cx.active_drag.is_none());
9155
9156 window.dispatch_event(
9157 FileDropEvent::Entered {
9158 position: reentry_position,
9159 paths: external_paths(),
9160 }
9161 .to_platform_input(),
9162 cx,
9163 );
9164 assert!(
9165 cx.active_drag
9166 .as_ref()
9167 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9168 );
9169 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9170 });
9171 assert!(
9172 update_result.is_ok(),
9173 "failed to restore drag in source window: {update_result:?}"
9174 );
9175
9176 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
9177 let cancelled = start_drag(cx, cancelled_path.clone(), true);
9178 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
9179 window.dispatch_event(
9180 MouseMoveEvent {
9181 position: outside_position,
9182 pressed_button: Some(MouseButton::Left),
9183 modifiers: Default::default(),
9184 }
9185 .to_platform_input(),
9186 cx,
9187 );
9188 assert!(cx.active_drag.is_none());
9189
9190 window.dispatch_event(
9191 FileDropEvent::Entered {
9192 position: reentry_position,
9193 paths: ExternalPaths([cancelled_path].into_iter().collect()),
9194 }
9195 .to_platform_input(),
9196 cx,
9197 );
9198 assert!(
9199 cx.active_drag
9200 .as_ref()
9201 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9202 );
9203 assert!(cx.stop_active_drag(window));
9204 assert!(cx.active_drag.is_none());
9205 });
9206 assert!(
9207 update_result.is_ok(),
9208 "failed to cancel restored drag: {update_result:?}"
9209 );
9210 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
9211
9212 let removed_path = PathBuf::from("/tmp/removed-window-drag");
9213 let removed = start_drag(cx, removed_path, true);
9214 let removed_window_id = removed.window.window_id();
9215 let update_result = cx.update_window(removed.window, |_, window, cx| {
9216 window.dispatch_event(
9217 MouseMoveEvent {
9218 position: outside_position,
9219 pressed_button: Some(MouseButton::Left),
9220 modifiers: Default::default(),
9221 }
9222 .to_platform_input(),
9223 cx,
9224 );
9225 assert!(cx.active_drag.is_none());
9226 window.remove_window();
9227 });
9228 assert!(
9229 update_result.is_ok(),
9230 "failed to remove drag source window: {update_result:?}"
9231 );
9232 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
9233
9234 let failed_path = PathBuf::from("/tmp/failed-drag");
9235 let failed = start_drag(cx, failed_path.clone(), false);
9236 let update_result = cx.update_window(failed.window, |_, window, cx| {
9237 for x_position in [-1., -2.] {
9238 window.dispatch_event(
9239 MouseMoveEvent {
9240 position: point(px(x_position), px(20.)),
9241 pressed_button: Some(MouseButton::Left),
9242 modifiers: Default::default(),
9243 }
9244 .to_platform_input(),
9245 cx,
9246 );
9247 }
9248 assert!(cx.active_drag.is_some());
9249 });
9250 assert!(
9251 update_result.is_ok(),
9252 "failed to retain drag after platform failure: {update_result:?}"
9253 );
9254 assert_eq!(
9255 cx.test_window(failed.window).external_drag_files(),
9256 [(failed_path, true)]
9257 );
9258 }
9259
9260 struct FocusForwarder {
9261 a: FocusHandle,
9262 b: FocusHandle,
9263 }
9264
9265 impl Render for FocusForwarder {
9266 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9267 div()
9268 .size_full()
9269 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
9270 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
9271 }
9272 }
9273
9274 #[gpui::test]
9278 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
9279 let b_focus_count = Rc::new(Cell::new(0));
9280 let window = cx.add_window({
9281 let b_focus_count = b_focus_count.clone();
9282 move |window, cx| {
9283 let a = cx.focus_handle();
9284 let b = cx.focus_handle();
9285 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
9286 let b = this.b.clone();
9287 window.focus(&b, cx);
9288 })
9289 .detach();
9290 cx.on_focus(&b, window, move |_, _, _| {
9291 b_focus_count.set(b_focus_count.get() + 1);
9292 })
9293 .detach();
9294 FocusForwarder { a, b }
9295 }
9296 });
9297
9298 window
9299 .update(cx, |_, window, _| window.activate_window())
9300 .unwrap();
9301 cx.executor().run_until_parked();
9302
9303 window
9304 .update(cx, |this, window, cx| {
9305 let a = this.a.clone();
9306 window.focus(&a, cx);
9307 })
9308 .unwrap();
9309 cx.executor().run_until_parked();
9310
9311 window
9312 .update(cx, |this, window, _| {
9313 assert!(this.b.is_focused(window));
9314 })
9315 .unwrap();
9316 assert_eq!(b_focus_count.get(), 1);
9317 }
9318
9319 #[gpui::test]
9320 fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
9321 let events = Rc::new(RefCell::new(Vec::new()));
9322 let window = cx.add_window({
9323 let events = events.clone();
9324 move |_, _| TouchDragListener { events }
9325 });
9326 let touch = TouchId(1);
9327
9328 dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
9329 dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
9330 dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
9331
9332 assert_eq!(
9333 events.borrow().as_slice(),
9334 [
9335 (TouchPhase::Started, px(10.)),
9336 (TouchPhase::Moved, px(30.)),
9337 (TouchPhase::Ended, px(40.)),
9338 ]
9339 );
9340 }
9341
9342 struct TouchDragListener {
9343 events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
9344 }
9345
9346 impl Render for TouchDragListener {
9347 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9348 let events = self.events.clone();
9349 canvas(
9350 |_, _, _| {},
9351 move |_, _, window, _| {
9352 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
9353 if phase != DispatchPhase::Bubble {
9354 return;
9355 }
9356 events.borrow_mut().push((event.phase, event.position.x));
9357 if event.phase == TouchPhase::Started {
9358 window.prevent_default();
9359 }
9360 });
9361 },
9362 )
9363 }
9364 }
9365
9366 #[gpui::test]
9367 fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
9368 for response in [
9369 LongPressResponse::PreventDefault,
9370 LongPressResponse::StopPropagation,
9371 LongPressResponse::None,
9372 ] {
9373 let phases = Rc::new(RefCell::new(Vec::new()));
9374 let window = cx.add_window({
9375 let phases = phases.clone();
9376 move |_, _| LongPressListener { phases, response }
9377 });
9378 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9379 cx.executor().advance_clock(Duration::from_millis(501));
9380 cx.executor().run_until_parked();
9381 window
9382 .update(cx, |_, window, _| {
9383 assert_eq!(
9384 window.core.long_press_capture.is_some(),
9385 response == LongPressResponse::PreventDefault
9386 );
9387 })
9388 .unwrap();
9389 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
9390 dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
9391 window
9392 .update(cx, |_, window, _| {
9393 assert!(window.core.long_press_capture.is_none());
9394 })
9395 .unwrap();
9396
9397 let phases = phases.borrow();
9398 if response == LongPressResponse::PreventDefault {
9399 assert_eq!(
9400 phases.as_slice(),
9401 [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
9402 );
9403 } else {
9404 assert_eq!(phases.as_slice(), [TouchPhase::Started]);
9405 }
9406 }
9407 }
9408
9409 #[gpui::test]
9410 fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
9411 let phases = Rc::new(RefCell::new(Vec::new()));
9412 let window = cx.add_window({
9413 let phases = phases.clone();
9414 move |_, _| LongPressListener {
9415 phases,
9416 response: LongPressResponse::None,
9417 }
9418 });
9419 window
9420 .update(cx, |_, window, _| {
9421 window.prevent_default();
9422 })
9423 .unwrap();
9424
9425 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9426 cx.executor().advance_clock(Duration::from_millis(501));
9427 cx.executor().run_until_parked();
9428 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
9429
9430 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
9431 }
9432
9433 #[gpui::test]
9434 fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
9435 for (phase, position) in [
9436 (TouchPhase::Ended, 0.),
9437 (TouchPhase::Cancelled, 0.),
9438 (TouchPhase::Moved, 20.),
9439 ] {
9440 let phases = Rc::new(RefCell::new(Vec::new()));
9441 let window = cx.add_window({
9442 let phases = phases.clone();
9443 move |_, _| LongPressListener {
9444 phases,
9445 response: LongPressResponse::PreventDefault,
9446 }
9447 });
9448 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9449 dispatch_touch(window, cx, TouchId(1), phase, position);
9450 cx.executor().advance_clock(Duration::from_millis(501));
9451 cx.executor().run_until_parked();
9452
9453 assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
9454 }
9455 }
9456
9457 #[gpui::test]
9458 fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
9459 let phases = Rc::new(RefCell::new(Vec::new()));
9460 let window = cx.add_window({
9461 let phases = phases.clone();
9462 move |_, _| LongPressListener {
9463 phases,
9464 response: LongPressResponse::PreventDefault,
9465 }
9466 });
9467 let first_touch = TouchId(1);
9468 dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
9469 cx.executor().advance_clock(Duration::from_millis(250));
9470 dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
9471 dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
9472
9473 cx.executor().advance_clock(Duration::from_millis(251));
9474 cx.executor().run_until_parked();
9475 assert!(phases.borrow().is_empty());
9476
9477 cx.executor().advance_clock(Duration::from_millis(250));
9478 cx.executor().run_until_parked();
9479 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
9480 }
9481
9482 #[derive(Clone, Copy, PartialEq)]
9483 enum LongPressResponse {
9484 PreventDefault,
9485 StopPropagation,
9486 None,
9487 }
9488
9489 struct LongPressListener {
9490 phases: Rc<RefCell<Vec<TouchPhase>>>,
9491 response: LongPressResponse,
9492 }
9493
9494 impl Render for LongPressListener {
9495 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
9496 let entity = cx.entity();
9497 let phases = self.phases.clone();
9498 let response = self.response;
9499 canvas(
9500 |_, _, _| {},
9501 move |_, _, window, _| {
9502 window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
9503 if phase != DispatchPhase::Bubble {
9504 return;
9505 }
9506 phases.borrow_mut().push(event.phase);
9507 match response {
9508 LongPressResponse::PreventDefault => {
9509 window.capture_long_press(&entity);
9510 window.prevent_default();
9511 }
9512 LongPressResponse::StopPropagation => cx.stop_propagation(),
9513 LongPressResponse::None => {}
9514 }
9515 });
9516 },
9517 )
9518 }
9519 }
9520
9521 fn dispatch_touch<T: 'static>(
9522 window: crate::WindowHandle<T>,
9523 cx: &mut TestAppContext,
9524 id: TouchId,
9525 phase: TouchPhase,
9526 x: f32,
9527 ) {
9528 window
9529 .update(cx, |_, window, cx| {
9530 window.dispatch_event(
9531 TouchEvent {
9532 id,
9533 phase,
9534 position: point(px(x), px(0.)),
9535 predicted_position: None,
9536 force: None,
9537 }
9538 .to_platform_input(),
9539 cx,
9540 );
9541 })
9542 .unwrap();
9543 }
9544}