1#[cfg(feature = "profiler")]
3use crate::DebugFrameOverlayMode;
4#[cfg(any(feature = "inspector", debug_assertions))]
5use crate::Inspector;
6#[cfg(feature = "profiler")]
7use crate::profiler;
8use crate::subscription::SingleSubscriberSet;
9use crate::taffy::TaffyLayoutEngine;
10use crate::{
11 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
12 AsyncWindowContext, AtlasTile, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow,
13 Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,
14 DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
15 EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
16 Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent,
17 Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent,
18 MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, PaintedPath, Path,
19 PathHash, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler,
20 PlatformWindow, Point, PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render,
21 RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge,
22 SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow,
23 SharedString, Size, SpriteAnimation, SpriteAnimationId, StrikethroughStyle, Style,
24 SubpixelSprite, Subscription, SystemWindowTab, SystemWindowTabController, TabStopMap, Task,
25 TextInputConfiguration, TextInputStateChange, TextRenderingMode, TextStyle,
26 TextStyleRefinement, ThermalState, TransformationMatrix, Underline, UnderlineStyle,
27 WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations,
28 WindowInsets, WindowOptions, WindowParams, WindowTextSystem, WindowVisibility, point,
29 prelude::*, px, rems, size, transparent_black,
30};
31
32use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
33use crate::interactive::TouchEvent;
34use anyhow::{Context as _, Result, anyhow};
35use collections::{FxHashMap, FxHashSet};
36use derive_more::{Deref, DerefMut};
37use futures::channel::oneshot;
38use gpui_util::post_inc;
39use gpui_util::{ResultExt, measure};
40use itertools::FoldWhile::{Continue, Done};
41use itertools::Itertools;
42#[cfg(any(target_os = "macos", target_os = "ios"))]
43use objc2_core_foundation::CFRetained;
44#[cfg(any(target_os = "macos", target_os = "ios"))]
45use objc2_core_video::CVPixelBuffer;
46use parking_lot::{RwLock, RwLockUpgradableReadGuard};
47use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
48use refineable::Refineable;
49use scheduler::Instant;
50use slotmap::SlotMap;
51use smallvec::SmallVec;
52use std::{
53 any::{Any, TypeId},
54 borrow::Cow,
55 cell::{Cell, RefCell},
56 cmp,
57 fmt::{Debug, Display},
58 hash::{Hash, Hasher},
59 marker::PhantomData,
60 mem,
61 ops::Range,
62 rc::Rc,
63 sync::{
64 Arc, Weak,
65 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
66 },
67 thread::AccessError,
68 time::Duration,
69};
70use uuid::Uuid;
71
72pub(crate) mod a11y;
73mod native_view;
74mod prompts;
75
76pub use a11y::A11ySubtreeBuilder;
77use native_view::NativeViewState;
78pub use native_view::{NativeView, NativeViewId};
79
80use self::a11y::A11y;
81#[cfg(not(target_family = "wasm"))]
82use self::a11y::ROOT_NODE_ID;
83use crate::util::{
84 atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
85 round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
86};
87pub use prompts::*;
88
89pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
91
92pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
95 width: Pixels(900.),
96 height: Pixels(750.),
97};
98
99#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
101pub enum DispatchPhase {
102 #[default]
107 Bubble,
108 Capture,
114}
115
116impl DispatchPhase {
117 #[inline]
119 pub fn bubble(self) -> bool {
120 self == DispatchPhase::Bubble
121 }
122
123 #[inline]
125 pub fn capture(self) -> bool {
126 self == DispatchPhase::Capture
127 }
128}
129
130struct WindowInvalidatorInner {
131 #[cfg(feature = "profiler")]
132 pub window_id: WindowId,
133 pub dirty: bool,
134 pub draw_phase: DrawPhase,
135 pub dirty_views: FxHashSet<EntityId>,
136 pub update_count: usize,
137 #[cfg(feature = "profiler")]
138 pub frame_dirty: FrameDirtyAccumulator,
139 pub platform_waker: Option<Rc<dyn Fn()>>,
140}
141
142#[cfg(feature = "profiler")]
148#[derive(Default)]
149struct FrameDirtyAccumulator {
150 dirty_at: Option<Instant>,
151 invalidations: u64,
152}
153
154#[derive(Clone)]
155pub(crate) struct WindowInvalidator {
156 inner: Rc<RefCell<WindowInvalidatorInner>>,
157}
158
159impl WindowInvalidator {
160 pub fn new(#[allow(unused_variables)] window_id: WindowId) -> Self {
161 WindowInvalidator {
162 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
163 #[cfg(feature = "profiler")]
164 window_id,
165 dirty: true,
166 draw_phase: DrawPhase::None,
167 dirty_views: FxHashSet::default(),
168 update_count: 0,
169 #[cfg(feature = "profiler")]
170 frame_dirty: FrameDirtyAccumulator::default(),
171 platform_waker: None,
172 })),
173 }
174 }
175
176 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
177 let mut inner = self.inner.borrow_mut();
178 inner.update_count += 1;
179 inner.dirty_views.insert(entity);
180 if inner.draw_phase == DrawPhase::None {
181 #[cfg(feature = "profiler")]
182 let dirty_at = Self::record_frame_dirty(&mut inner);
183 let became_dirty = !inner.dirty;
184 inner.dirty = true;
185 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
186 #[cfg(feature = "profiler")]
187 let window_id = inner.window_id;
188 drop(inner);
189 #[cfg(feature = "profiler")]
190 if became_dirty {
191 profiler::journal::record_frame_pending(window_id, dirty_at);
192 }
193 cx.push_effect(Effect::Notify { emitter: entity });
194 if let Some(waker) = waker {
195 waker();
196 }
197 true
198 } else {
199 false
200 }
201 }
202
203 pub fn is_dirty(&self) -> bool {
204 self.inner.borrow().dirty
205 }
206
207 pub fn set_dirty(&self, dirty: bool) {
208 let mut inner = self.inner.borrow_mut();
209 let became_dirty = dirty && !inner.dirty;
210 inner.dirty = dirty;
211 if dirty {
212 inner.update_count += 1;
213 }
214 #[cfg(feature = "profiler")]
215 let dirty_at = dirty.then(|| Self::record_frame_dirty(&mut inner));
216 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
217 #[cfg(feature = "profiler")]
218 let window_id = inner.window_id;
219 drop(inner);
220 #[cfg(feature = "profiler")]
221 if became_dirty && let Some(dirty_at) = dirty_at {
222 profiler::journal::record_frame_pending(window_id, dirty_at);
223 }
224 if let Some(waker) = waker {
225 waker();
226 }
227 }
228
229 pub fn set_platform_waker(&self, waker: Option<Rc<dyn Fn()>>) {
230 let mut inner = self.inner.borrow_mut();
231 inner.platform_waker = waker;
232 let waker = inner.dirty.then(|| inner.platform_waker.clone()).flatten();
233 drop(inner);
234 if let Some(waker) = waker {
235 waker();
236 }
237 }
238
239 pub fn wake_platform(&self) {
243 let waker = self.inner.borrow().platform_waker.clone();
244 if let Some(waker) = waker {
245 waker();
246 }
247 }
248
249 pub fn set_phase(&self, phase: DrawPhase) {
250 self.inner.borrow_mut().draw_phase = phase
251 }
252
253 pub fn update_count(&self) -> usize {
254 self.inner.borrow().update_count
255 }
256
257 #[cfg(feature = "profiler")]
258 fn record_frame_dirty(inner: &mut WindowInvalidatorInner) -> Instant {
259 let dirty_at = *inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
260 inner.frame_dirty.invalidations += 1;
261 dirty_at
262 }
263
264 #[cfg(feature = "profiler")]
265 fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
266 mem::take(&mut self.inner.borrow_mut().frame_dirty)
267 }
268
269 pub fn take_views(&self) -> FxHashSet<EntityId> {
270 mem::take(&mut self.inner.borrow_mut().dirty_views)
271 }
272
273 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
274 self.inner.borrow_mut().dirty_views = views;
275 }
276
277 pub fn not_drawing(&self) -> bool {
278 self.inner.borrow().draw_phase == DrawPhase::None
279 }
280
281 #[track_caller]
282 pub fn debug_assert_paint(&self) {
283 debug_assert!(
284 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
285 "this method can only be called during paint"
286 );
287 }
288
289 #[track_caller]
290 pub fn debug_assert_prepaint(&self) {
291 debug_assert!(
292 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
293 "this method can only be called during request_layout, or prepaint"
294 );
295 }
296
297 #[track_caller]
298 pub fn debug_assert_paint_or_prepaint(&self) {
299 debug_assert!(
300 matches!(
301 self.inner.borrow().draw_phase,
302 DrawPhase::Paint | DrawPhase::Prepaint
303 ),
304 "this method can only be called during request_layout, prepaint, or paint"
305 );
306 }
307}
308
309type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
310
311pub(crate) type AnyWindowFocusListener =
312 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
313
314pub(crate) struct WindowFocusEvent {
315 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
316 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
317}
318
319impl WindowFocusEvent {
320 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
321 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
322 }
323
324 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
325 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
326 }
327}
328
329pub struct FocusOutEvent {
331 pub blurred: WeakFocusHandle,
333}
334
335slotmap::new_key_type! {
336 pub struct FocusId;
338}
339
340thread_local! {
341 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
344
345 static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
349}
350
351pub(crate) fn draw_in_progress() -> bool {
362 CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some())
363}
364
365#[inline(always)]
368pub(crate) fn with_element_arena<R>(callback: impl FnOnce(&mut Arena) -> R) -> R {
369 let mut callback = Some(callback);
370 let mut result = None;
371 let access = with_element_arena_erased(&mut |arena| {
372 result = Some(callback.take().expect("arena callback runs once")(arena));
373 });
374 drop(callback);
375 access.expect("cannot access a Thread Local Storage value during or after destruction");
376 result.expect("arena callback produces a result")
377}
378
379pub(crate) struct ElementArenaScope {
394 entered: *const RefCell<Arena>,
397 previous: Option<*const RefCell<Arena>>,
398 exited: bool,
399}
400
401impl ElementArenaScope {
402 pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
404 arena.borrow_mut().begin_scope();
405 let previous = CURRENT_ELEMENT_ARENA.with(|current| {
406 let prev = current.get();
407 current.set(Some(arena as *const RefCell<Arena>));
408 prev
409 });
410 Self {
411 entered: arena as *const RefCell<Arena>,
412 previous,
413 exited: false,
414 }
415 }
416
417 pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
426 assert!(
427 std::ptr::eq(self.entered, arena),
428 "ElementArenaScope::exit called with a different arena than was entered"
429 );
430 self.exited = true;
431 ArenaClearNeeded::new(arena)
436 }
437}
438
439impl Drop for ElementArenaScope {
440 fn drop(&mut self) {
441 CURRENT_ELEMENT_ARENA.with(|current| {
448 current.set(self.previous);
449 });
450 unsafe { &*self.entered }.borrow_mut().end_scope();
454 if !self.exited && !std::thread::panicking() {
455 debug_assert!(false, "ElementArenaScope dropped without calling exit()");
456 log::error!(
457 "ElementArenaScope dropped without calling exit(); \
458 the arena clear for this draw was never requested"
459 );
460 }
461 }
462}
463
464#[must_use]
466pub struct ArenaClearNeeded {
467 arena: *const RefCell<Arena>,
470}
471
472impl ArenaClearNeeded {
473 fn new(arena: &RefCell<Arena>) -> Self {
476 Self {
477 arena: arena as *const RefCell<Arena>,
478 }
479 }
480
481 pub fn clear(self, cx: &mut App) {
490 assert!(
491 std::ptr::eq(self.arena, &*cx.element_arena),
492 "ArenaClearNeeded::clear called with a different App than the draw ran against"
493 );
494 RefCell::borrow_mut(&cx.element_arena).clear();
495 }
496}
497
498#[derive(Default)]
499pub(crate) struct FocusMap {
500 pub(crate) handles: SlotMap<FocusId, FocusRef>,
501 pub(crate) dropped_handles: Vec<FocusId>,
502}
503
504pub(crate) struct FocusRef {
505 pub(crate) ref_count: AtomicUsize,
506 pub(crate) tab_index: isize,
507 pub(crate) tab_stop: bool,
508}
509
510impl FocusId {
511 pub fn is_focused(&self, window: &Window) -> bool {
513 window.focus == Some(*self)
514 }
515
516 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
519 window
520 .focused(cx)
521 .is_some_and(|focused| self.contains(focused.id, window))
522 }
523
524 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
527 let focused = window.focused(cx);
528 focused.is_some_and(|focused| focused.id.contains(*self, window))
529 }
530
531 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
533 window
534 .rendered_frame
535 .dispatch_tree
536 .focus_contains(*self, other)
537 }
538}
539
540pub struct FocusHandle {
542 pub(crate) id: FocusId,
543 handles: Arc<RwLock<FocusMap>>,
544 pub tab_index: isize,
546 pub tab_stop: bool,
548}
549
550impl std::fmt::Debug for FocusHandle {
551 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
552 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
553 }
554}
555
556impl FocusHandle {
557 pub(crate) fn new(handles: &Arc<RwLock<FocusMap>>) -> Self {
558 let id = handles.write().handles.insert(FocusRef {
559 ref_count: AtomicUsize::new(1),
560 tab_index: 0,
561 tab_stop: false,
562 });
563
564 Self {
565 id,
566 tab_index: 0,
567 tab_stop: false,
568 handles: handles.clone(),
569 }
570 }
571
572 pub(crate) fn for_id(id: FocusId, handles: &Arc<RwLock<FocusMap>>) -> Option<Self> {
573 let lock = handles.read();
574 let focus = lock.handles.get(id)?;
575 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
576 return None;
577 }
578 Some(Self {
579 id,
580 tab_index: focus.tab_index,
581 tab_stop: focus.tab_stop,
582 handles: handles.clone(),
583 })
584 }
585
586 pub fn tab_index(mut self, index: isize) -> Self {
588 self.tab_index = index;
589 if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
590 focus.tab_index = index;
591 }
592 self
593 }
594
595 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
599 self.tab_stop = tab_stop;
600 if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
601 focus.tab_stop = tab_stop;
602 }
603 self
604 }
605
606 pub fn downgrade(&self) -> WeakFocusHandle {
608 WeakFocusHandle {
609 id: self.id,
610 handles: Arc::downgrade(&self.handles),
611 }
612 }
613
614 pub fn focus(&self, window: &mut Window, cx: &mut App) {
616 window.focus(self, cx)
617 }
618
619 pub fn is_focused(&self, window: &Window) -> bool {
621 self.id.is_focused(window)
622 }
623
624 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
627 self.id.contains_focused(window, cx)
628 }
629
630 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
633 self.id.within_focused(window, cx)
634 }
635
636 pub fn contains(&self, other: &Self, window: &Window) -> bool {
638 self.id.contains(other.id, window)
639 }
640
641 pub fn is_rendered(&self, window: &Window) -> bool {
643 window
644 .rendered_frame
645 .dispatch_tree
646 .focusable_node_id(self.id)
647 .is_some()
648 }
649
650 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
652 if let Some(node_id) = window
653 .rendered_frame
654 .dispatch_tree
655 .focusable_node_id(self.id)
656 {
657 window.dispatch_action_on_node(node_id, action, cx)
658 }
659 }
660}
661
662impl Clone for FocusHandle {
663 fn clone(&self) -> Self {
664 Self::for_id(self.id, &self.handles).unwrap()
665 }
666}
667
668impl PartialEq for FocusHandle {
669 fn eq(&self, other: &Self) -> bool {
670 self.id == other.id
671 }
672}
673
674impl Eq for FocusHandle {}
675
676impl Drop for FocusHandle {
677 fn drop(&mut self) {
678 let handles = self.handles.upgradable_read();
679 let focus = handles.handles.get(self.id).expect("focus handle missing");
680 let previous_count = focus.ref_count.fetch_sub(1, SeqCst);
681 assert_ne!(previous_count, 0, "over-released focus handle");
682 if previous_count == 1 {
683 RwLockUpgradableReadGuard::upgrade(handles)
684 .dropped_handles
685 .push(self.id);
686 }
687 }
688}
689
690#[derive(Clone, Debug)]
692pub struct WeakFocusHandle {
693 pub(crate) id: FocusId,
694 pub(crate) handles: Weak<RwLock<FocusMap>>,
695}
696
697impl WeakFocusHandle {
698 pub fn upgrade(&self) -> Option<FocusHandle> {
700 let handles = self.handles.upgrade()?;
701 FocusHandle::for_id(self.id, &handles)
702 }
703}
704
705impl PartialEq for WeakFocusHandle {
706 fn eq(&self, other: &WeakFocusHandle) -> bool {
707 self.id == other.id
708 }
709}
710
711impl Eq for WeakFocusHandle {}
712
713impl PartialEq<FocusHandle> for WeakFocusHandle {
714 fn eq(&self, other: &FocusHandle) -> bool {
715 self.id == other.id
716 }
717}
718
719impl PartialEq<WeakFocusHandle> for FocusHandle {
720 fn eq(&self, other: &WeakFocusHandle) -> bool {
721 self.id == other.id
722 }
723}
724
725pub trait Focusable: 'static {
728 fn focus_handle(&self, cx: &App) -> FocusHandle;
730}
731
732impl<V: Focusable> Focusable for Entity<V> {
733 fn focus_handle(&self, cx: &App) -> FocusHandle {
734 self.read(cx).focus_handle(cx)
735 }
736}
737
738pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
741
742impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
743
744pub struct DismissEvent;
746
747type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
748
749pub(crate) type AnyMouseListener =
750 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
751
752#[derive(Clone)]
753pub(crate) struct CursorStyleRequest {
754 pub(crate) hitbox_id: Option<HitboxId>,
755 pub(crate) style: CursorStyle,
756}
757
758#[derive(Default, Eq, PartialEq)]
759pub(crate) struct HitTest {
760 pub(crate) ids: SmallVec<[HitboxId; 8]>,
761 pub(crate) hover_hitbox_count: usize,
762}
763
764#[derive(Clone, Copy, Debug, Eq, PartialEq)]
766pub enum WindowControlArea {
767 Drag,
769 Close,
771 Max,
773 Min,
775}
776
777#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
779pub struct HitboxId(u64);
780
781#[cfg(any(test, feature = "test-support"))]
782impl HitboxId {
783 pub const fn placeholder() -> Self {
788 Self(0)
789 }
790}
791
792impl HitboxId {
793 pub fn is_hovered(self, window: &Window) -> bool {
800 if window.captured_hitbox == Some(self) {
802 return true;
803 }
804 if window.last_input_was_keyboard() {
805 return false;
806 }
807 self.hit_test(window)
808 }
809
810 pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
815 if window.captured_hitbox == Some(self) {
817 return true;
818 }
819 self.hit_test(window)
820 }
821
822 fn hit_test(self, window: &Window) -> bool {
823 let hit_test = &window.mouse_hit_test;
824 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
825 if self == *id {
826 return true;
827 }
828 }
829 false
830 }
831
832 pub fn should_handle_scroll(self, window: &Window) -> bool {
837 window.mouse_hit_test.ids.contains(&self)
838 }
839
840 pub(crate) fn next(self) -> HitboxId {
841 HitboxId(self.0.wrapping_add(1))
842 }
843}
844
845#[derive(Clone, Debug, Deref)]
848pub struct Hitbox {
849 pub id: HitboxId,
851 #[deref]
853 pub bounds: Bounds<Pixels>,
854 pub content_mask: ContentMask<Pixels>,
856 pub behavior: HitboxBehavior,
858}
859
860impl Hitbox {
861 pub fn is_hovered(&self, window: &Window) -> bool {
878 self.id.is_hovered(window)
879 }
880
881 pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
884 let hit_test = window.rendered_frame.hit_test(position);
885 hit_test
886 .ids
887 .iter()
888 .take(hit_test.hover_hitbox_count)
889 .any(|id| self.id == *id)
890 }
891
892 pub fn should_handle_scroll(&self, window: &Window) -> bool {
899 self.id.should_handle_scroll(window)
900 }
901}
902
903#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
905pub enum HitboxBehavior {
906 #[default]
908 Normal,
909
910 BlockMouse,
932
933 BlockMouseExceptScroll,
960}
961
962#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
964pub struct TooltipId(usize);
965
966impl TooltipId {
967 pub fn is_hovered(&self, window: &Window) -> bool {
969 window
970 .tooltip_bounds
971 .as_ref()
972 .is_some_and(|tooltip_bounds| {
973 tooltip_bounds.id == *self
974 && tooltip_bounds.bounds.contains(&window.mouse_position())
975 })
976 }
977}
978
979pub(crate) struct TooltipBounds {
980 id: TooltipId,
981 bounds: Bounds<Pixels>,
982}
983
984#[derive(Clone)]
985pub(crate) struct TooltipRequest {
986 id: TooltipId,
987 tooltip: AnyTooltip,
988}
989
990#[derive(Clone, Default)]
996pub(crate) struct ElementIdStack {
997 ids: SmallVec<[ElementId; 32]>,
998 hashes: SmallVec<[PathHash; 32]>,
999}
1000
1001impl ElementIdStack {
1002 pub(crate) fn push(&mut self, id: ElementId) {
1003 self.hashes.push(self.hash().extend(&id));
1004 self.ids.push(id);
1005 }
1006
1007 pub(crate) fn pop(&mut self) -> Option<ElementId> {
1008 self.hashes.pop();
1009 self.ids.pop()
1010 }
1011
1012 pub(crate) fn clear(&mut self) {
1013 self.ids.clear();
1014 self.hashes.clear();
1015 }
1016
1017 fn hash(&self) -> PathHash {
1019 self.hashes.last().copied().unwrap_or(PathHash::EMPTY)
1020 }
1021
1022 pub(crate) fn global_id(&self) -> GlobalElementId {
1023 GlobalElementId::with_hash(&self.ids, self.hash())
1024 }
1025}
1026
1027impl std::ops::Deref for ElementIdStack {
1028 type Target = [ElementId];
1029
1030 fn deref(&self) -> &Self::Target {
1031 &self.ids
1032 }
1033}
1034
1035pub(crate) struct DeferredDraw {
1036 current_view: EntityId,
1037 priority: usize,
1038 parent_node: DispatchNodeId,
1039 element_id_stack: ElementIdStack,
1040 text_style_stack: Vec<TextStyleRefinement>,
1041 content_mask: Option<ContentMask<Pixels>>,
1042 rem_size: Pixels,
1043 element: Option<AnyElement>,
1044 absolute_offset: Point<Pixels>,
1045 prepaint_range: Range<PrepaintStateIndex>,
1046 paint_range: Range<PaintIndex>,
1047 accessed_entities: FxHashSet<EntityId>,
1050}
1051
1052pub(crate) struct Frame {
1053 pub(crate) focus: Option<FocusId>,
1054 pub(crate) window_active: bool,
1055 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
1056 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
1057 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
1058 pub(crate) dispatch_tree: DispatchTree,
1059 pub(crate) scene: Scene,
1060 pub(crate) hitboxes: Vec<Hitbox>,
1061 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
1062 pub(crate) deferred_draws: Vec<DeferredDraw>,
1063 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
1064 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
1065 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
1066 #[cfg(any(test, feature = "test-support"))]
1067 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
1068 #[cfg(any(test, feature = "test-support"))]
1069 debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
1070 #[cfg(any(feature = "inspector", debug_assertions))]
1071 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
1072 #[cfg(any(feature = "inspector", debug_assertions))]
1073 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
1074 pub(crate) tab_stops: TabStopMap,
1075}
1076
1077#[derive(Clone, Default)]
1078pub(crate) struct PrepaintStateIndex {
1079 hitboxes_index: usize,
1080 tooltips_index: usize,
1081 deferred_draws_index: usize,
1082 dispatch_tree_index: usize,
1083 accessed_element_states_index: usize,
1084 line_layout_index: LineLayoutIndex,
1085}
1086
1087#[derive(Clone, Default)]
1088pub(crate) struct PaintIndex {
1089 scene_index: usize,
1090 #[cfg(any(test, feature = "test-support"))]
1091 debug_bounds_index: usize,
1092 mouse_listeners_index: usize,
1093 input_handlers_index: usize,
1094 cursor_styles_index: usize,
1095 accessed_element_states_index: usize,
1096 tab_handle_index: usize,
1097 line_layout_index: LineLayoutIndex,
1098}
1099
1100impl Frame {
1101 #[cfg(any(test, feature = "test-support"))]
1102 pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) {
1103 self.debug_bounds.insert(selector.clone(), bounds);
1104 self.debug_bounds_records.push((selector, bounds));
1105 }
1106
1107 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
1108 Frame {
1109 focus: None,
1110 window_active: false,
1111 element_states: FxHashMap::default(),
1112 accessed_element_states: Vec::new(),
1113 mouse_listeners: Vec::new(),
1114 dispatch_tree,
1115 scene: Scene::default(),
1116 hitboxes: Vec::new(),
1117 window_control_hitboxes: Vec::new(),
1118 deferred_draws: Vec::new(),
1119 input_handlers: Vec::new(),
1120 tooltip_requests: Vec::new(),
1121 cursor_styles: Vec::new(),
1122
1123 #[cfg(any(test, feature = "test-support"))]
1124 debug_bounds: FxHashMap::default(),
1125 #[cfg(any(test, feature = "test-support"))]
1126 debug_bounds_records: Vec::new(),
1127
1128 #[cfg(any(feature = "inspector", debug_assertions))]
1129 next_inspector_instance_ids: FxHashMap::default(),
1130
1131 #[cfg(any(feature = "inspector", debug_assertions))]
1132 inspector_hitboxes: FxHashMap::default(),
1133 tab_stops: TabStopMap::default(),
1134 }
1135 }
1136
1137 pub(crate) fn clear(&mut self) {
1138 self.element_states.clear();
1139 self.accessed_element_states.clear();
1140 self.mouse_listeners.clear();
1141 self.dispatch_tree.clear();
1142 self.scene.clear();
1143 self.input_handlers.clear();
1144 self.tooltip_requests.clear();
1145 self.cursor_styles.clear();
1146 self.hitboxes.clear();
1147 self.window_control_hitboxes.clear();
1148 self.deferred_draws.clear();
1149 self.tab_stops.clear();
1150 self.focus = None;
1151
1152 #[cfg(any(test, feature = "test-support"))]
1153 {
1154 self.debug_bounds.clear();
1155 self.debug_bounds_records.clear();
1156 }
1157
1158 #[cfg(any(feature = "inspector", debug_assertions))]
1159 {
1160 self.next_inspector_instance_ids.clear();
1161 self.inspector_hitboxes.clear();
1162 }
1163 }
1164
1165 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1166 self.cursor_styles
1167 .iter()
1168 .rev()
1169 .fold_while(None, |style, request| match request.hitbox_id {
1170 None => Done(Some(request.style)),
1171 Some(hitbox_id) => Continue(style.or_else(|| {
1172 hitbox_id
1173 .is_hovered_ignoring_last_input(window)
1174 .then_some(request.style)
1175 })),
1176 })
1177 .into_inner()
1178 }
1179
1180 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
1181 let mut set_hover_hitbox_count = false;
1182 let mut hit_test = HitTest::default();
1183 for hitbox in self.hitboxes.iter().rev() {
1184 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
1185 if bounds.contains(&position) {
1186 hit_test.ids.push(hitbox.id);
1187 if !set_hover_hitbox_count
1188 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1189 {
1190 hit_test.hover_hitbox_count = hit_test.ids.len();
1191 set_hover_hitbox_count = true;
1192 }
1193 if hitbox.behavior == HitboxBehavior::BlockMouse {
1194 break;
1195 }
1196 }
1197 }
1198 if !set_hover_hitbox_count {
1199 hit_test.hover_hitbox_count = hit_test.ids.len();
1200 }
1201 hit_test
1202 }
1203
1204 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1205 self.focus
1206 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1207 .unwrap_or_default()
1208 }
1209
1210 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1211 for element_state_key in &self.accessed_element_states {
1212 if let Some((element_state_key, element_state)) =
1213 prev_frame.element_states.remove_entry(element_state_key)
1214 {
1215 self.element_states.insert(element_state_key, element_state);
1216 }
1217 }
1218
1219 self.scene.finish();
1220 }
1221}
1222
1223#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1224enum InputModality {
1225 Mouse,
1226 Keyboard,
1227 Touch,
1228}
1229
1230pub struct Window {
1232 pub(crate) handle: AnyWindowHandle,
1233 pub(crate) invalidator: WindowInvalidator,
1234 pub(crate) removed: bool,
1235 pub(crate) platform_window: Box<dyn PlatformWindow>,
1236 pub(crate) display_id: Option<DisplayId>,
1237 pub(crate) display_observers: SingleSubscriberSet<AnyObserver>,
1238 is_resizable: bool,
1239 is_minimizable: bool,
1240 last_window_bounds: WindowBounds,
1241 sprite_atlas: Arc<dyn PlatformAtlas>,
1242 text_system: Rc<WindowTextSystem>,
1243 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1244 rem_size: Pixels,
1245 rem_size_override_stack: SmallVec<[Pixels; 8]>,
1250 pub(crate) viewport_size: Size<Pixels>,
1251 layout_engine: Option<TaffyLayoutEngine>,
1252 pub(crate) root: Option<AnyView>,
1253 pub(crate) element_id_stack: ElementIdStack,
1254 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1255 pub(crate) rendered_entity_stack: Vec<EntityId>,
1256 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1257 pub(crate) element_opacity: f32,
1258 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1259 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1260 last_text_input_configuration: Option<TextInputConfiguration>,
1264 focused_text_input: Option<FocusId>,
1265 pub(crate) image_cache_stack: Vec<AnyImageCache>,
1266 pub(crate) rendered_frame: Frame,
1267 pub(crate) next_frame: Frame,
1268 next_hitbox_id: HitboxId,
1269 native_views: Vec<std::rc::Weak<NativeViewState>>,
1270 next_native_view_id: u64,
1271 pub(crate) next_tooltip_id: TooltipId,
1272 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1273 pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1274 pub(crate) dirty_views: FxHashSet<EntityId>,
1275 focus_listeners: SingleSubscriberSet<AnyWindowFocusListener>,
1276 pub(crate) focus_lost_listeners: SingleSubscriberSet<AnyObserver>,
1277 focus_lost_path: SmallVec<[FocusId; 8]>,
1278 default_prevented: bool,
1279 mouse_position: Point<Pixels>,
1280 mouse_hit_test: HitTest,
1281 modifiers: Modifiers,
1282 capslock: Capslock,
1283 scale_factor: f32,
1284 pub(crate) bounds_observers: SingleSubscriberSet<AnyObserver>,
1285 appearance: WindowAppearance,
1286 pub(crate) appearance_observers: SingleSubscriberSet<AnyObserver>,
1287 pub(crate) button_layout_observers: SingleSubscriberSet<AnyObserver>,
1288 active: Rc<Cell<bool>>,
1289 visibility: WindowVisibility,
1290 pub(crate) visibility_observers:
1291 SingleSubscriberSet<Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
1292 hovered: Rc<Cell<bool>>,
1293 pub(crate) needs_present: Rc<Cell<bool>>,
1294 scene_animation_interval: Rc<Cell<Option<Duration>>>,
1297 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1300 #[cfg(feature = "profiler")]
1301 pub(crate) window_profiler: profiler::WindowProfiler,
1302 last_input_modality: InputModality,
1303 touch_gestures: TouchGestureRecognizer,
1304 touch_prediction_enabled: bool,
1305 long_press_timer: Option<Task<()>>,
1306 long_press_capture: Option<EntityId>,
1307 pub(crate) refreshing: bool,
1308 pub(crate) activation_observers: SingleSubscriberSet<AnyObserver>,
1309 pub(crate) focus: Option<FocusId>,
1310 focus_enabled: bool,
1311 pub(crate) focus_generation: u64,
1314 pending_input: Option<PendingInput>,
1315 pending_modifier: ModifierState,
1316 pub(crate) pending_input_observers: SingleSubscriberSet<AnyObserver>,
1317 prompt: Option<RenderablePromptHandle>,
1318 pub(crate) client_inset: Option<Pixels>,
1319 captured_hitbox: Option<HitboxId>,
1322 #[cfg(any(feature = "inspector", debug_assertions))]
1323 inspector: Option<Entity<Inspector>>,
1324 #[cfg(feature = "profiler")]
1325 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1326 pub(crate) a11y: A11y,
1327}
1328
1329#[derive(Clone, Debug, Default)]
1330struct ModifierState {
1331 modifiers: Modifiers,
1332 saw_other_input: bool,
1333}
1334
1335#[derive(Clone, Debug)]
1338pub(crate) struct InputRateTracker {
1339 timestamps: Vec<Instant>,
1340 window: Duration,
1341 inputs_per_second: u32,
1342 sustain_until: Instant,
1343 sustain_duration: Duration,
1344}
1345
1346const FRAME_INTERVAL_TOLERANCE: Duration = Duration::from_millis(1);
1347
1348#[derive(Default)]
1350struct FramePacer {
1351 last_frame: Option<Instant>,
1352}
1353
1354impl FramePacer {
1355 fn should_defer(&mut self, now: Instant, minimum_interval: Option<Duration>) -> bool {
1356 if let Some(interval) = minimum_interval
1357 && let Some(last_frame) = self.last_frame
1358 {
1359 let deadline = last_frame + interval;
1360 if now + FRAME_INTERVAL_TOLERANCE < deadline {
1361 return true;
1362 }
1363 self.last_frame = Some(if now.saturating_duration_since(deadline) <= interval / 4 {
1367 deadline
1368 } else {
1369 now
1370 });
1371 } else {
1372 self.last_frame = Some(now);
1373 }
1374 false
1375 }
1376}
1377
1378fn minimum_frame_interval(
1379 should_throttle: bool,
1380 inactive_without_high_rate_input: bool,
1381 inactive_frame_interval: Option<Duration>,
1382 low_power_frame_interval: Option<Duration>,
1383 thermal_frame_interval: Option<Duration>,
1384 thermal_state: ThermalState,
1385 power_mode: crate::PowerMode,
1386) -> Option<Duration> {
1387 if !should_throttle {
1388 return None;
1389 }
1390
1391 [
1392 inactive_frame_interval.filter(|_| inactive_without_high_rate_input),
1393 low_power_frame_interval.filter(|_| power_mode == crate::PowerMode::LowPower),
1394 thermal_frame_interval.filter(|_| {
1395 matches!(
1396 thermal_state,
1397 ThermalState::Critical | ThermalState::Serious
1398 )
1399 }),
1400 ]
1401 .into_iter()
1402 .flatten()
1403 .max()
1404}
1405
1406impl Default for InputRateTracker {
1407 fn default() -> Self {
1408 Self {
1409 timestamps: Vec::new(),
1410 window: Duration::from_millis(100),
1411 inputs_per_second: 60,
1412 sustain_until: Instant::now(),
1413 sustain_duration: Duration::from_secs(1),
1414 }
1415 }
1416}
1417
1418impl InputRateTracker {
1419 pub fn record_input(&mut self) {
1420 let now = Instant::now();
1421 self.timestamps.push(now);
1422 self.prune_old_timestamps(now);
1423
1424 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1425 if self.timestamps.len() as u128 >= min_events {
1426 self.sustain_until = now + self.sustain_duration;
1427 }
1428 }
1429
1430 pub fn is_high_rate(&self) -> bool {
1431 Instant::now() < self.sustain_until
1432 }
1433
1434 fn prune_old_timestamps(&mut self, now: Instant) {
1435 self.timestamps
1436 .retain(|&t| now.duration_since(t) <= self.window);
1437 }
1438}
1439
1440#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1441pub(crate) enum DrawPhase {
1442 None,
1443 Prepaint,
1444 Paint,
1445 Focus,
1446}
1447
1448pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
1449
1450pub struct PendingInputStatus<'a> {
1452 keystrokes: &'a [Keystroke],
1453 timeout: Option<PendingInputTimeoutStatus>,
1454}
1455
1456impl<'a> PendingInputStatus<'a> {
1457 pub fn keystrokes(&self) -> &'a [Keystroke] {
1459 self.keystrokes
1460 }
1461
1462 pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
1464 self.timeout
1465 }
1466}
1467
1468#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1470pub struct PendingInputTimeoutStatus {
1471 duration: Duration,
1472 remaining: Duration,
1473 started_at: Option<Instant>,
1474 paused: bool,
1475}
1476
1477impl PendingInputTimeoutStatus {
1478 pub fn duration(&self) -> Duration {
1480 self.duration
1481 }
1482
1483 pub fn remaining(&self, cx: &App) -> Duration {
1485 self.started_at
1486 .map(|started_at| {
1487 self.remaining
1488 .saturating_sub(cx.background_executor().now() - started_at)
1489 })
1490 .unwrap_or(self.remaining)
1491 }
1492
1493 pub fn is_paused(&self) -> bool {
1495 self.paused
1496 }
1497}
1498
1499#[derive(Debug)]
1500struct PendingInputTimeout {
1501 duration: Duration,
1502 remaining: Duration,
1503 state: PendingInputTimeoutState,
1504}
1505
1506#[derive(Debug)]
1507enum PendingInputTimeoutState {
1508 Running { started_at: Instant, task: Task<()> },
1509 Paused { pause: PendingInputTimeoutPause },
1510}
1511
1512#[derive(Debug)]
1513struct PendingInputTimeoutPause {
1514 owner_id: EntityId,
1515 _release_subscription: Subscription,
1516}
1517
1518impl PendingInputTimeout {
1519 fn is_paused(&self) -> bool {
1520 matches!(&self.state, PendingInputTimeoutState::Paused { .. })
1521 }
1522
1523 fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
1524 match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
1525 PendingInputTimeoutState::Running { started_at, task } => {
1526 self.remaining = self.remaining.saturating_sub(now - started_at);
1527 drop(task);
1528 true
1529 }
1530 previous_state @ PendingInputTimeoutState::Paused { .. } => {
1531 self.state = previous_state;
1532 false
1533 }
1534 }
1535 }
1536
1537 fn pause_owner_id(&self) -> Option<EntityId> {
1538 match &self.state {
1539 PendingInputTimeoutState::Running { .. } => None,
1540 PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
1541 }
1542 }
1543
1544 fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
1545 match std::mem::replace(
1546 &mut self.state,
1547 PendingInputTimeoutState::Running { started_at, task },
1548 ) {
1549 PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
1550 previous_state => {
1551 self.state = previous_state;
1552 false
1553 }
1554 }
1555 }
1556
1557 fn reset_duration(&mut self, duration: Duration) {
1558 self.duration = duration;
1559 self.remaining = duration;
1560 }
1561
1562 fn status(&self) -> PendingInputTimeoutStatus {
1563 let (started_at, paused) = match &self.state {
1564 PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
1565 PendingInputTimeoutState::Paused { .. } => (None, true),
1566 };
1567 PendingInputTimeoutStatus {
1568 duration: self.duration,
1569 remaining: self.remaining,
1570 started_at,
1571 paused,
1572 }
1573 }
1574}
1575
1576#[derive(Default, Debug)]
1577struct PendingInput {
1578 keystrokes: SmallVec<[Keystroke; 1]>,
1579 focus: Option<FocusId>,
1580 timeout: Option<PendingInputTimeout>,
1581}
1582
1583pub(crate) struct ElementStateBox {
1584 pub(crate) inner: Box<dyn Any>,
1585 #[cfg(debug_assertions)]
1586 pub(crate) type_name: &'static str,
1587}
1588
1589fn default_bounds(
1590 active_window_bounds: Option<WindowBounds>,
1591 display: Option<&dyn PlatformDisplay>,
1592) -> WindowBounds {
1593 const CASCADE_OFFSET: f32 = 25.0;
1594
1595 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1596
1597 let display_bounds = display
1599 .map(|d| d.visible_bounds())
1600 .unwrap_or_else(default_placement);
1601
1602 let (
1603 Bounds {
1604 origin: base_origin,
1605 size: base_size,
1606 },
1607 window_bounds_ctor,
1608 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1609 Some(bounds) => match bounds {
1610 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1611 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1612 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1613 },
1614 None => (
1615 display
1616 .map(|d| d.default_bounds())
1617 .unwrap_or_else(default_placement),
1618 WindowBounds::Windowed,
1619 ),
1620 };
1621
1622 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1623 let proposed_origin = base_origin + cascade_offset;
1624 let proposed_bounds = Bounds::new(proposed_origin, base_size);
1625
1626 let display_right = display_bounds.origin.x + display_bounds.size.width;
1627 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1628 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1629 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1630
1631 let fits_horizontally = window_right <= display_right;
1632 let fits_vertically = window_bottom <= display_bottom;
1633
1634 let final_origin = match (fits_horizontally, fits_vertically) {
1635 (true, true) => proposed_origin,
1636 (false, true) => point(display_bounds.origin.x, base_origin.y),
1637 (true, false) => point(base_origin.x, display_bounds.origin.y),
1638 (false, false) => display_bounds.origin,
1639 };
1640 window_bounds_ctor(Bounds::new(final_origin, base_size))
1641}
1642
1643impl Window {
1644 pub(crate) fn new(
1645 handle: AnyWindowHandle,
1646 options: WindowOptions,
1647 cx: &mut App,
1648 ) -> Result<Self> {
1649 let WindowOptions {
1650 window_bounds,
1651 titlebar,
1652 focus,
1653 show,
1654 kind,
1655 is_movable,
1656 app_owns_titlebar_drag,
1657 inactive_frame_interval,
1658 low_power_frame_interval,
1659 thermal_frame_interval,
1660 is_resizable,
1661 is_minimizable,
1662 display_id,
1663 window_background,
1664 app_id,
1665 window_min_size,
1666 window_decorations,
1667 #[cfg_attr(
1668 not(any(target_os = "linux", target_os = "freebsd")),
1669 allow(unused_variables)
1670 )]
1671 icon,
1672 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1673 tabbing_identifier,
1674 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1675 use_display_p3,
1676 } = options;
1677
1678 let initial_window_title = titlebar
1679 .as_ref()
1680 .and_then(|titlebar| titlebar.title.clone());
1681
1682 let active_window_placement = cx.active_window_placement();
1683 let target_display_id = display_id.or_else(|| {
1685 active_window_placement
1686 .filter(|_| window_bounds.is_none())
1687 .and_then(|(display_id, _)| display_id)
1688 });
1689 let display = target_display_id
1690 .and_then(|display_id| cx.find_display(display_id))
1691 .or_else(|| cx.primary_display());
1692 let display_id = display
1693 .as_ref()
1694 .map(|display| display.id())
1695 .or(target_display_id);
1696 let active_window_bounds = active_window_placement
1697 .filter(|(active_display_id, _)| *active_display_id == display_id)
1698 .map(|(_, bounds)| bounds);
1699 let window_bounds = window_bounds
1700 .unwrap_or_else(|| default_bounds(active_window_bounds, display.as_deref()));
1701 let mut platform_window = cx.platform.open_window(
1702 handle,
1703 WindowParams {
1704 bounds: window_bounds.get_bounds(),
1705 titlebar,
1706 kind,
1707 is_movable,
1708 app_owns_titlebar_drag,
1709 is_resizable,
1710 is_minimizable,
1711 focus,
1712 show,
1713 display_id,
1714 window_min_size,
1715 app_id: app_id.clone(),
1716 icon,
1717 #[cfg(target_os = "macos")]
1718 tabbing_identifier,
1719 #[cfg(target_os = "macos")]
1720 use_display_p3,
1721 },
1722 )?;
1723
1724 let tab_bar_visible = platform_window.tab_bar_visible();
1725 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1726 if let Some(tabs) = platform_window.tabbed_windows() {
1727 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1728 }
1729
1730 let display_id = platform_window.display().map(|display| display.id());
1731 let sprite_atlas = platform_window.sprite_atlas();
1732 let mouse_position = platform_window.mouse_position();
1733 let modifiers = platform_window.modifiers();
1734 let capslock = platform_window.capslock();
1735 let content_size = platform_window.content_size();
1736 let scale_factor = platform_window.scale_factor();
1737 let appearance = platform_window.appearance();
1738 let text_system = Rc::new(WindowTextSystem::new(cx.text_system().clone()));
1739 let invalidator = WindowInvalidator::new(handle.window_id());
1740 let active = Rc::new(Cell::new(platform_window.is_active()));
1741 let visibility = platform_window.visibility();
1742 #[cfg(feature = "profiler")]
1743 profiler::journal::record_window_visibility(handle.window_id(), visibility);
1744 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1745 let needs_present = Rc::new(Cell::new(false));
1746 let scene_animation_interval = Rc::new(Cell::new(None::<Duration>));
1747 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1748 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1749
1750 platform_window
1751 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1752 platform_window.set_background_appearance(window_background);
1753
1754 match window_bounds {
1755 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1756 WindowBounds::Maximized(_) => platform_window.zoom(),
1757 WindowBounds::Windowed(_) => {}
1758 }
1759
1760 let accessibility_force_disabled = cx.accessibility_force_disabled;
1761 let a11y_active_flag = Arc::new(AtomicBool::new(false));
1762
1763 #[cfg(not(target_family = "wasm"))]
1764 if !accessibility_force_disabled {
1765 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
1766 if let Some(title) = &initial_window_title {
1767 initial_root_node.set_label(title.to_string());
1768 }
1769 let initial_tree = accesskit::TreeUpdate {
1770 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
1771 tree: Some(accesskit::TreeInfo::new(ROOT_NODE_ID)),
1772 tree_id: accesskit::TreeId::ROOT,
1773 focus: ROOT_NODE_ID,
1774 };
1775 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
1776 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
1777 let (action_sender, action_receiver) =
1778 async_channel::unbounded::<accesskit::ActionRequest>();
1779
1780 platform_window.a11y_init(crate::A11yCallbacks {
1781 activation: {
1782 let active_flag = a11y_active_flag.clone();
1783 Box::new(move || {
1784 log::info!("Accessibility activated");
1785 active_flag.store(true, SeqCst);
1786 activation_sender
1787 .send_blocking(())
1788 .with_context(|| {
1789 format!(
1790 "queuing accessibility activation for window {:?}",
1791 handle.window_id()
1792 )
1793 })
1794 .log_err();
1795 Some(initial_tree.clone())
1796 })
1797 },
1798 action: Box::new(move |request| {
1799 action_sender
1800 .send_blocking(request)
1801 .with_context(|| {
1802 format!(
1803 "queuing accessibility action for window {:?}",
1804 handle.window_id()
1805 )
1806 })
1807 .log_err();
1808 }),
1809 deactivation: {
1810 let active_flag = a11y_active_flag.clone();
1811 Box::new(move || {
1812 log::info!("Accessibility deactivated");
1813 active_flag.store(false, SeqCst);
1814 deactivation_sender
1815 .send_blocking(())
1816 .with_context(|| {
1817 format!(
1818 "queuing accessibility deactivation for window {:?}",
1819 handle.window_id()
1820 )
1821 })
1822 .log_err();
1823 })
1824 },
1825 });
1826
1827 let mut async_cx = cx.to_async();
1833 cx.foreground_executor()
1834 .spawn(async move {
1835 while activation_receiver.recv().await.is_ok() {
1836 handle
1837 .update(&mut async_cx, |_, window, _| window.refresh())
1838 .with_context(|| {
1839 format!(
1840 "handling accessibility activation for window {:?}",
1841 handle.window_id()
1842 )
1843 })
1844 .log_err();
1845 }
1846 })
1847 .detach();
1848
1849 let mut async_cx = cx.to_async();
1850 cx.foreground_executor()
1851 .spawn(async move {
1852 while deactivation_receiver.recv().await.is_ok() {
1853 handle
1854 .update(&mut async_cx, |_, window, _| window.refresh())
1855 .with_context(|| {
1856 format!(
1857 "handling accessibility deactivation for window {:?}",
1858 handle.window_id()
1859 )
1860 })
1861 .log_err();
1862 }
1863 })
1864 .detach();
1865
1866 let mut async_cx = cx.to_async();
1867 cx.foreground_executor()
1868 .spawn(async move {
1869 while let Ok(request) = action_receiver.recv().await {
1870 handle
1871 .update(&mut async_cx, |_, window, cx| {
1872 window.handle_a11y_action(request, cx);
1873 })
1874 .with_context(|| {
1875 format!(
1876 "handling accessibility action for window {:?}",
1877 handle.window_id()
1878 )
1879 })
1880 .log_err();
1881 }
1882 })
1883 .detach();
1884 }
1885
1886 platform_window.on_close(Box::new({
1887 let window_id = handle.window_id();
1888 let cx = cx.to_async();
1889 move || {
1890 cx.spawn(async move |cx| {
1893 cx.update(|cx| {
1894 if cx.windows.contains_key(window_id) {
1896 handle
1897 .update(cx, |_, window, _| window.remove_window())
1898 .with_context(|| format!("handling close for window {window_id:?}"))
1899 .log_err();
1900 }
1901 SystemWindowTabController::remove_tab(cx, window_id);
1902 });
1903 })
1904 .detach();
1905 }
1906 }));
1907 platform_window.on_request_frame(Box::new({
1908 let mut cx = cx.to_async();
1909 let invalidator = invalidator.clone();
1910 let active = active.clone();
1911 let needs_present = needs_present.clone();
1912 let scene_animation_interval = scene_animation_interval.clone();
1913 let next_frame_callbacks = next_frame_callbacks.clone();
1914 let input_rate_tracker = input_rate_tracker.clone();
1915 let mut deferred_force_render = false;
1916 let mut frame_pacer = FramePacer::default();
1917 move |request_frame_options| {
1918 #[cfg(feature = "profiler")]
1919 let (_foreground_turn, window_id) = {
1920 let foreground_turn = profiler::journal::foreground_turn();
1921 let window_id = handle.window_id();
1922 profiler::journal::record_platform_signal(profiler::journal::PlatformSignal {
1923 window_id,
1924 signal_at: request_frame_options.signal_at,
1925 handled_at: Instant::now(),
1926 source: request_frame_options.signal_source,
1927 });
1928 (foreground_turn, window_id)
1929 };
1930 if draw_in_progress() {
1946 log::debug!("deferring re-entrant window draw request");
1947 deferred_force_render |= request_frame_options.force_render;
1948 #[cfg(feature = "profiler")]
1949 profiler::journal::record_reentrant_frame_skipped(window_id, Instant::now());
1950 return;
1951 }
1952 let force_render =
1956 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
1957
1958 let power_state = handle
1959 .update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode()))
1960 .with_context(|| {
1961 format!(
1962 "reading power state for frame request for window {:?}",
1963 handle.window_id()
1964 )
1965 })
1966 .log_err();
1967
1968 let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate();
1971 let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty();
1972 let has_demand_besides_animation = invalidator.is_dirty()
1973 || force_render
1974 || has_next_frame_callbacks
1975 || request_frame_options.require_presentation
1976 || needs_present.get()
1977 || high_rate_input;
1978 let has_frame_demand =
1979 has_demand_besides_animation || scene_animation_interval.get().is_some();
1980
1981 let should_throttle = !request_frame_options.require_presentation;
1982 let inactive_without_high_rate_input =
1983 should_throttle && !active.get() && !high_rate_input;
1984 let (thermal_state, power_mode) =
1985 power_state.unwrap_or((ThermalState::Nominal, crate::PowerMode::Unknown));
1986 let min_frame_interval = minimum_frame_interval(
1987 should_throttle,
1988 inactive_without_high_rate_input,
1989 inactive_frame_interval,
1990 low_power_frame_interval,
1991 thermal_frame_interval,
1992 thermal_state,
1993 power_mode,
1994 );
1995 let animation_frame_interval = scene_animation_interval
1996 .get()
1997 .filter(|interval| !has_demand_besides_animation && !interval.is_zero());
1998 let min_frame_interval = min_frame_interval.max(animation_frame_interval);
1999
2000 let now = Instant::now();
2001 if has_frame_demand && frame_pacer.should_defer(now, min_frame_interval) {
2004 deferred_force_render |= force_render;
2006 handle
2008 .update(&mut cx, |_, window, _| {
2009 #[cfg(feature = "profiler")]
2012 if animation_frame_interval.is_none()
2013 || animation_frame_interval != min_frame_interval
2014 {
2015 window.window_profiler.record_frame_throttled();
2016 }
2017 window.platform_window.schedule_frame();
2018 })
2019 .with_context(|| {
2020 format!(
2021 "rescheduling throttled frame for window {:?}",
2022 handle.window_id()
2023 )
2024 })
2025 .log_err();
2026 invalidator.wake_platform();
2029 #[cfg(feature = "profiler")]
2030 profiler::journal::record_frame_skipped(
2031 window_id,
2032 Instant::now(),
2033 if animation_frame_interval.is_some()
2034 && animation_frame_interval == min_frame_interval
2035 {
2036 profiler::journal::FrameSkipReason::AnimationFrameRateLimit
2037 } else if inactive_without_high_rate_input
2038 && inactive_frame_interval == min_frame_interval
2039 {
2040 profiler::journal::FrameSkipReason::InactiveFrameRateLimit
2041 } else if power_mode == crate::PowerMode::LowPower
2042 && low_power_frame_interval == min_frame_interval
2043 {
2044 profiler::journal::FrameSkipReason::LowPowerFrameRateLimit
2045 } else {
2046 profiler::journal::FrameSkipReason::ThermalFrameRateLimit
2047 },
2048 );
2049 return;
2050 }
2051
2052 let pending_next_frame_callbacks = next_frame_callbacks.take();
2053 if !pending_next_frame_callbacks.is_empty() {
2054 handle
2055 .update(&mut cx, |_, window, cx| {
2056 for callback in pending_next_frame_callbacks {
2057 callback(window, cx);
2058 }
2059 })
2060 .with_context(|| {
2061 format!(
2062 "running next-frame callbacks for window {:?}",
2063 handle.window_id()
2064 )
2065 })
2066 .log_err();
2067 }
2068
2069 let should_draw = invalidator.is_dirty() || force_render;
2070 let needs_present = request_frame_options.require_presentation
2071 || needs_present.get()
2072 || scene_animation_interval.get().is_some()
2073 || high_rate_input;
2074 if should_draw {
2075 measure("frame duration", || {
2076 handle
2077 .update(&mut cx, |_, window, cx| {
2078 #[cfg(feature = "profiler")]
2079 window
2080 .window_profiler
2081 .record_frame_signal(request_frame_options.signal_at);
2082 if force_render {
2083 window.refresh();
2086 }
2087 let arena_clear_needed = window.draw(cx);
2088 window.advance_scene_animations(cx);
2089 window.present();
2090 arena_clear_needed.clear(cx);
2091 })
2092 .with_context(|| {
2093 format!(
2094 "drawing and presenting frame for window {:?}",
2095 handle.window_id()
2096 )
2097 })
2098 .log_err();
2099 })
2100 } else if needs_present {
2101 handle
2102 .update(&mut cx, |_, window, cx| {
2103 window.advance_scene_animations(cx);
2104 window.present();
2105 })
2106 .with_context(|| {
2107 format!("presenting frame for window {:?}", handle.window_id())
2108 })
2109 .log_err();
2110 }
2111
2112 handle
2113 .update(&mut cx, |_, window, _| {
2114 if window.invalidator.is_dirty()
2115 || !window.next_frame_callbacks.borrow().is_empty()
2116 || window.scene_animation_interval.get().is_some()
2117 {
2118 window.platform_window.schedule_frame();
2119 }
2120 })
2121 .with_context(|| {
2122 format!(
2123 "scheduling follow-up frame for window {:?}",
2124 handle.window_id()
2125 )
2126 })
2127 .log_err();
2128
2129 if invalidator.is_dirty()
2135 || !next_frame_callbacks.borrow().is_empty()
2136 || scene_animation_interval.get().is_some()
2137 {
2138 invalidator.wake_platform();
2139 }
2140 #[cfg(feature = "profiler")]
2141 if !should_draw {
2142 profiler::journal::record_frame_skipped(
2143 window_id,
2144 Instant::now(),
2145 profiler::journal::FrameSkipReason::NoRenderNeeded,
2146 );
2147 }
2148 }
2149 }));
2150 invalidator.set_platform_waker(platform_window.frame_waker());
2151 platform_window.on_visual_viewport_changed(Box::new({
2152 let mut cx = cx.to_async();
2153 move || {
2154 handle
2155 .update(&mut cx, |_, window, _| window.refresh())
2156 .with_context(|| {
2157 format!(
2158 "handling visual viewport change for window {:?}",
2159 handle.window_id()
2160 )
2161 })
2162 .log_err();
2163 }
2164 }));
2165 platform_window.on_insets_changed(Box::new({
2166 let mut cx = cx.to_async();
2167 move |_| {
2168 handle
2169 .update(&mut cx, |_, window, _| window.refresh())
2170 .with_context(|| {
2171 format!("handling insets change for window {:?}", handle.window_id())
2172 })
2173 .log_err();
2174 }
2175 }));
2176 platform_window.on_resize(Box::new({
2177 let mut cx = cx.to_async();
2178 move |_, _| {
2179 handle
2180 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2181 .with_context(|| format!("handling resize for window {:?}", handle.window_id()))
2182 .log_err();
2183 }
2184 }));
2185 platform_window.on_moved(Box::new({
2186 let mut cx = cx.to_async();
2187 move || {
2188 handle
2189 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2190 .with_context(|| format!("handling move for window {:?}", handle.window_id()))
2191 .log_err();
2192 }
2193 }));
2194 platform_window.on_display_changed(Box::new({
2195 let cx = cx.to_async();
2196 move || cx.update(|cx| Window::display_changed(handle, cx))
2197 }));
2198 platform_window.on_appearance_changed(Box::new({
2199 let cx = cx.to_async();
2200 let foreground_executor = cx.foreground_executor().clone();
2201 move || {
2202 let mut cx = cx.clone();
2203 foreground_executor
2206 .spawn(async move {
2207 handle
2208 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
2209 .with_context(|| {
2210 format!(
2211 "handling appearance change for window {:?}",
2212 handle.window_id()
2213 )
2214 })
2215 .log_err();
2216 })
2217 .detach();
2218 }
2219 }));
2220 platform_window.on_button_layout_changed(Box::new({
2221 let mut cx = cx.to_async();
2222 move || {
2223 handle
2224 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
2225 .with_context(|| {
2226 format!(
2227 "handling button layout change for window {:?}",
2228 handle.window_id()
2229 )
2230 })
2231 .log_err();
2232 }
2233 }));
2234 platform_window.on_active_status_change(Box::new({
2235 let mut cx = cx.to_async();
2236 move |active| {
2237 handle
2238 .update(&mut cx, |_, window, cx| {
2239 window.active.set(active);
2240 window.modifiers = window.platform_window.modifiers();
2241 window.capslock = window.platform_window.capslock();
2242 window
2243 .activation_observers
2244 .clone()
2245 .retain(|callback| callback(window, cx));
2246
2247 window.bounds_changed(cx);
2248 window.refresh();
2249
2250 SystemWindowTabController::update_last_active(cx, window.handle.id);
2251 })
2252 .with_context(|| {
2253 format!(
2254 "handling active status change for window {:?}",
2255 handle.window_id()
2256 )
2257 })
2258 .log_err();
2259 }
2260 }));
2261 platform_window.on_visibility_change(Box::new({
2262 let mut cx = cx.to_async();
2263 move |_| {
2264 handle
2265 .update(&mut cx, |_, window, cx| {
2266 window.refresh_visibility(cx);
2267 })
2268 .with_context(|| {
2269 format!(
2270 "handling visibility change for window {:?}",
2271 handle.window_id()
2272 )
2273 })
2274 .log_err();
2275 }
2276 }));
2277 platform_window.on_hover_status_change(Box::new({
2278 let mut cx = cx.to_async();
2279 move |active| {
2280 handle
2281 .update(&mut cx, |_, window, _| {
2282 window.hovered.set(active);
2283 window.refresh();
2284 })
2285 .with_context(|| {
2286 format!(
2287 "handling hover status change for window {:?}",
2288 handle.window_id()
2289 )
2290 })
2291 .log_err();
2292 }
2293 }));
2294 platform_window.on_input({
2295 let mut cx = cx.to_async();
2296 Box::new(move |event| {
2297 handle
2298 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
2299 .with_context(|| {
2300 format!("dispatching input for window {:?}", handle.window_id())
2301 })
2302 .log_err()
2303 .unwrap_or(DispatchEventResult::default())
2304 })
2305 });
2306 platform_window.on_hit_test_window_control({
2307 let mut cx = cx.to_async();
2308 Box::new(move || {
2309 handle
2310 .update(&mut cx, |_, window, _cx| {
2311 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
2312 if window.mouse_hit_test.ids.contains(&hitbox.id) {
2313 return Some(*area);
2314 }
2315 }
2316 None
2317 })
2318 .with_context(|| {
2319 format!(
2320 "hit-testing window controls for window {:?}",
2321 handle.window_id()
2322 )
2323 })
2324 .log_err()
2325 .unwrap_or(None)
2326 })
2327 });
2328 platform_window.on_hit_test_native_view({
2329 let mut cx = cx.to_async();
2330 Box::new(move |position| {
2331 handle
2334 .update(&mut cx, |_, window, _| {
2335 window.hit_test_native_view(position)
2336 })
2337 .ok()
2338 .flatten()
2339 })
2340 });
2341 platform_window.on_key_down_before_native_view({
2342 let mut cx = cx.to_async();
2343 Box::new(move |event| {
2344 handle
2345 .update(&mut cx, |_, window, cx| {
2346 window.dispatch_key_down_before_native_view(event, cx)
2347 })
2348 .unwrap_or(false)
2349 })
2350 });
2351 platform_window.on_native_view_focused({
2352 let mut cx = cx.to_async();
2353 Box::new(move |id| {
2354 handle
2355 .update(&mut cx, |_, window, cx| window.focus_native_view(id, cx))
2356 .with_context(|| {
2357 format!("focusing a native view in window {:?}", handle.window_id())
2358 })
2359 .log_err();
2360 })
2361 });
2362 platform_window.on_move_tab_to_new_window({
2363 let mut cx = cx.to_async();
2364 Box::new(move || {
2365 handle
2366 .update(&mut cx, |_, _window, cx| {
2367 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
2368 })
2369 .with_context(|| {
2370 format!(
2371 "moving tab to new window from window {:?}",
2372 handle.window_id()
2373 )
2374 })
2375 .log_err();
2376 })
2377 });
2378 platform_window.on_merge_all_windows({
2379 let mut cx = cx.to_async();
2380 Box::new(move || {
2381 handle
2382 .update(&mut cx, |_, _window, cx| {
2383 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
2384 })
2385 .with_context(|| {
2386 format!("merging all windows into window {:?}", handle.window_id())
2387 })
2388 .log_err();
2389 })
2390 });
2391 platform_window.on_select_next_tab({
2392 let mut cx = cx.to_async();
2393 Box::new(move || {
2394 handle
2395 .update(&mut cx, |_, _window, cx| {
2396 SystemWindowTabController::select_next_tab(cx, handle.window_id());
2397 })
2398 .with_context(|| {
2399 format!("selecting next tab for window {:?}", handle.window_id())
2400 })
2401 .log_err();
2402 })
2403 });
2404 platform_window.on_select_previous_tab({
2405 let mut cx = cx.to_async();
2406 Box::new(move || {
2407 handle
2408 .update(&mut cx, |_, _window, cx| {
2409 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
2410 })
2411 .with_context(|| {
2412 format!("selecting previous tab for window {:?}", handle.window_id())
2413 })
2414 .log_err();
2415 })
2416 });
2417 platform_window.on_toggle_tab_bar({
2418 let mut cx = cx.to_async();
2419 Box::new(move || {
2420 handle
2421 .update(&mut cx, |_, window, cx| {
2422 let tab_bar_visible = window.platform_window.tab_bar_visible();
2423 SystemWindowTabController::set_visible(cx, tab_bar_visible);
2424 })
2425 .with_context(|| {
2426 format!("toggling tab bar for window {:?}", handle.window_id())
2427 })
2428 .log_err();
2429 })
2430 });
2431
2432 if let Some(app_id) = app_id {
2433 platform_window.set_app_id(&app_id);
2434 }
2435
2436 platform_window.map_window().unwrap();
2437
2438 Ok(Window {
2439 handle,
2440 invalidator,
2441 removed: false,
2442 platform_window,
2443 display_id,
2444 display_observers: SingleSubscriberSet::new(),
2445 is_resizable,
2446 is_minimizable,
2447 last_window_bounds: window_bounds,
2448 sprite_atlas,
2449 text_system,
2450 text_rendering_mode: cx.text_rendering_mode.clone(),
2451 rem_size: px(16.),
2452 rem_size_override_stack: SmallVec::new(),
2453 viewport_size: content_size,
2454 layout_engine: Some(TaffyLayoutEngine::new()),
2455 root: None,
2456 element_id_stack: ElementIdStack::default(),
2457 text_style_stack: Vec::new(),
2458 rendered_entity_stack: Vec::new(),
2459 element_offset_stack: Vec::new(),
2460 content_mask_stack: Vec::new(),
2461 element_opacity: 1.0,
2462 requested_autoscroll: None,
2463 last_text_input_configuration: None,
2464 focused_text_input: None,
2465 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
2466 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
2467 next_frame_callbacks,
2468 next_hitbox_id: HitboxId(0),
2469 native_views: Vec::new(),
2470 next_native_view_id: 0,
2471 next_tooltip_id: TooltipId::default(),
2472 tooltip_bounds: None,
2473 dirty_views: FxHashSet::default(),
2474 focus_listeners: SingleSubscriberSet::new(),
2475 focus_lost_listeners: SingleSubscriberSet::new(),
2476 focus_lost_path: SmallVec::new(),
2477 default_prevented: true,
2478 mouse_position,
2479 mouse_hit_test: HitTest::default(),
2480 modifiers,
2481 capslock,
2482 scale_factor,
2483 bounds_observers: SingleSubscriberSet::new(),
2484 appearance,
2485 appearance_observers: SingleSubscriberSet::new(),
2486 button_layout_observers: SingleSubscriberSet::new(),
2487 active,
2488 visibility,
2489 visibility_observers: SingleSubscriberSet::new(),
2490 hovered,
2491 needs_present,
2492 scene_animation_interval,
2493 input_rate_tracker,
2494 #[cfg(feature = "profiler")]
2495 window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
2496 last_input_modality: InputModality::Mouse,
2497 touch_gestures: TouchGestureRecognizer::new(
2498 cx.platform
2499 .gestures()
2500 .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
2501 ),
2502 touch_prediction_enabled: true,
2503 long_press_timer: None,
2504 long_press_capture: None,
2505 refreshing: false,
2506 activation_observers: SingleSubscriberSet::new(),
2507 focus: None,
2508 focus_enabled: true,
2509 focus_generation: 0,
2510 pending_input: None,
2511 pending_modifier: ModifierState::default(),
2512 pending_input_observers: SingleSubscriberSet::new(),
2513 prompt: None,
2514 client_inset: None,
2515 image_cache_stack: Vec::new(),
2516 captured_hitbox: None,
2517 #[cfg(any(feature = "inspector", debug_assertions))]
2518 inspector: None,
2519 #[cfg(feature = "profiler")]
2520 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
2521 a11y: A11y::new(
2522 a11y_active_flag,
2523 accessibility_force_disabled,
2524 initial_window_title,
2525 ),
2526 })
2527 }
2528
2529 pub(crate) fn new_focus_listener(
2530 &self,
2531 value: AnyWindowFocusListener,
2532 ) -> (Subscription, impl FnOnce() + use<>) {
2533 self.focus_listeners.insert_pending(value)
2534 }
2535}
2536
2537#[derive(Clone, Debug, Default, PartialEq, Eq)]
2538#[expect(missing_docs)]
2539pub struct DispatchEventResult {
2540 pub propagate: bool,
2541 pub default_prevented: bool,
2542}
2543
2544#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2548#[repr(C)]
2549pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
2550 pub bounds: Bounds<P>,
2552}
2553
2554impl ContentMask<Pixels> {
2555 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
2557 ContentMask {
2558 bounds: self.bounds.scale(factor),
2559 }
2560 }
2561
2562 pub fn intersect(&self, other: &Self) -> Self {
2564 let bounds = self.bounds.intersect(&other.bounds);
2565 ContentMask { bounds }
2566 }
2567}
2568
2569impl Window {
2570 fn mark_view_dirty(&mut self, view_id: EntityId) {
2571 for view_id in self
2574 .rendered_frame
2575 .dispatch_tree
2576 .view_path_reversed(view_id)
2577 {
2578 if !self.dirty_views.insert(view_id) {
2579 break;
2580 }
2581 }
2582 }
2583
2584 pub(crate) fn refresh_visibility(&mut self, cx: &mut App) {
2585 let visibility = self.platform_window.visibility();
2586 if self.visibility != visibility {
2587 self.visibility = visibility;
2588 #[cfg(feature = "profiler")]
2589 profiler::journal::record_window_visibility(self.handle.window_id(), visibility);
2590 self.visibility_observers
2591 .clone()
2592 .retain(|callback| callback(visibility, self, cx));
2593 }
2594 #[cfg(feature = "profiler")]
2595 if self.invalidator.is_dirty() || self.needs_present.get() {
2596 profiler::journal::record_frame_pending(self.handle.window_id(), Instant::now());
2597 }
2598 }
2599
2600 pub(crate) fn debug_state(&self) -> serde_json::Value {
2605 let platform_window = &self.platform_window;
2606 serde_json::json!({
2607 "id": self.handle.window_id().as_u64(),
2608 "title": platform_window.get_title(),
2609 "bounds": platform_window.bounds(),
2610 "window_bounds": format!("{:?}", platform_window.window_bounds()),
2611 "content_size": platform_window.content_size(),
2612 "viewport_size": self.viewport_size,
2613 "scale_factor": {
2614 "cached": self.scale_factor,
2615 "platform": platform_window.scale_factor(),
2616 },
2617 "display_id": {
2618 "cached": self.display_id.map(u64::from),
2619 "platform": platform_window.display().map(|display| u64::from(display.id())),
2620 },
2621 "active": {
2622 "cached": self.active.get(),
2623 "platform": platform_window.is_active(),
2624 },
2625 "hovered": {
2626 "cached": self.hovered.get(),
2627 "platform": platform_window.is_hovered(),
2628 },
2629 "visibility": {
2630 "cached": format!("{:?}", self.visibility),
2631 "platform": format!("{:?}", platform_window.visibility()),
2632 },
2633 "appearance": {
2634 "cached": format!("{:?}", self.appearance),
2635 "platform": format!("{:?}", platform_window.appearance()),
2636 },
2637 "is_fullscreen": platform_window.is_fullscreen(),
2638 "is_maximized": platform_window.is_maximized(),
2639 "mouse_position": {
2640 "cached": self.mouse_position,
2641 "platform": platform_window.mouse_position(),
2642 },
2643 "modifiers": {
2644 "cached": self.modifiers,
2645 "platform": platform_window.modifiers(),
2646 },
2647 "cursor_style": self.rendered_frame.cursor_style(self),
2648 "frame": {
2649 "dirty": self.invalidator.is_dirty(),
2650 "needs_present": self.needs_present.get(),
2651 "refreshing": self.refreshing,
2652 "next_frame_callbacks": self.next_frame_callbacks.borrow().len(),
2653 },
2654 "gpu": platform_window.gpu_specs(),
2655 "platform": platform_window.debug_state(),
2656 })
2657 }
2658
2659 pub fn visibility(&self) -> WindowVisibility {
2662 self.visibility
2663 }
2664
2665 pub fn is_visible(&self) -> bool {
2671 self.visibility.is_visible()
2672 }
2673
2674 pub fn observe_window_visibility(
2676 &self,
2677 mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
2678 ) -> Subscription {
2679 self.visibility_observers
2680 .insert(Box::new(move |visibility, window, cx| {
2681 callback(visibility, window, cx);
2682 true
2683 }))
2684 }
2685
2686 pub fn observe_window_appearance(
2688 &self,
2689 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2690 ) -> Subscription {
2691 self.appearance_observers
2692 .insert(Box::new(move |window, cx| {
2693 callback(window, cx);
2694 true
2695 }))
2696 }
2697
2698 pub fn observe_button_layout_changed(
2700 &self,
2701 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2702 ) -> Subscription {
2703 self.button_layout_observers
2704 .insert(Box::new(move |window, cx| {
2705 callback(window, cx);
2706 true
2707 }))
2708 }
2709
2710 pub fn replace_root<E>(
2712 &mut self,
2713 cx: &mut App,
2714 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
2715 ) -> Entity<E>
2716 where
2717 E: 'static + Render,
2718 {
2719 let view = cx.new(|cx| build_view(self, cx));
2720 self.root = Some(view.clone().into());
2721 self.refresh();
2722 view
2723 }
2724
2725 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
2727 where
2728 E: 'static + Render,
2729 {
2730 self.root
2731 .as_ref()
2732 .map(|view| view.clone().downcast::<E>().ok())
2733 }
2734
2735 pub fn window_handle(&self) -> AnyWindowHandle {
2737 self.handle
2738 }
2739
2740 pub fn refresh(&mut self) {
2742 if self.invalidator.not_drawing() {
2743 self.refreshing = true;
2744 self.invalidator.set_dirty(true);
2745 }
2746 }
2747
2748 pub fn remove_window(&mut self) {
2750 self.removed = true;
2751 }
2752
2753 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
2755 self.focus
2756 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
2757 }
2758
2759 pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
2763 let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
2764 ancestors.iter().rev().find_map(|id| {
2765 self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
2766 FocusHandle::for_id(*id, &cx.focus_handles)
2767 })
2768 }
2769
2770 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
2772 if !self.focus_enabled || self.focus == Some(handle.id) {
2773 return;
2774 }
2775
2776 self.end_composition_before_focusing_native_view(handle.id, cx);
2777 self.focus = Some(handle.id);
2778 self.sync_native_view_focus();
2779 self.focus_generation = self.focus_generation.wrapping_add(1);
2780 self.clear_pending_keystrokes(cx);
2781
2782 self.refresh();
2783 }
2784
2785 pub fn blur(&mut self, cx: &mut App) {
2787 self.clear_pending_keystrokes(cx);
2788
2789 if !self.focus_enabled {
2790 return;
2791 }
2792
2793 if self.focus.is_some() {
2794 self.focus_generation = self.focus_generation.wrapping_add(1);
2795 }
2796 self.focus = None;
2797 self.sync_native_view_focus();
2798 self.refresh();
2799 }
2800
2801 pub fn disable_focus(&mut self, cx: &mut App) {
2803 self.blur(cx);
2804 self.focus_enabled = false;
2805 }
2806
2807 pub fn focus_next(&mut self, cx: &mut App) {
2809 if !self.focus_enabled {
2810 return;
2811 }
2812
2813 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
2814 self.focus(&handle, cx)
2815 }
2816 }
2817
2818 pub fn focus_prev(&mut self, cx: &mut App) {
2820 if !self.focus_enabled {
2821 return;
2822 }
2823
2824 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
2825 self.focus(&handle, cx)
2826 }
2827 }
2828
2829 pub fn text_system(&self) -> &Rc<WindowTextSystem> {
2831 &self.text_system
2832 }
2833
2834 pub fn text_style(&self) -> TextStyle {
2836 let mut style = TextStyle::default();
2837 for refinement in &self.text_style_stack {
2838 style.refine(refinement);
2839 }
2840 style
2841 }
2842
2843 pub fn is_maximized(&self) -> bool {
2847 self.platform_window.is_maximized()
2848 }
2849
2850 pub fn request_decorations(&self, decorations: WindowDecorations) {
2852 self.platform_window.request_decorations(decorations);
2853 }
2854
2855 pub fn set_exclusive_zone(&self, zone: Pixels) {
2861 self.platform_window.set_exclusive_zone(zone);
2862 }
2863
2864 #[cfg(all(target_os = "linux", feature = "wayland"))]
2869 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
2870 self.platform_window.set_exclusive_edge(edge);
2871 }
2872
2873 pub fn start_window_resize(&self, edge: ResizeEdge) {
2875 if self.is_resizable {
2876 self.platform_window.start_window_resize(edge);
2877 }
2878 }
2879
2880 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
2887 self.platform_window.set_input_region(region);
2888 }
2889
2890 pub fn window_bounds(&self) -> WindowBounds {
2893 self.platform_window.window_bounds()
2894 }
2895
2896 pub(crate) fn last_window_bounds(&self) -> WindowBounds {
2897 self.last_window_bounds
2898 }
2899
2900 pub(crate) fn display_id(&self) -> Option<DisplayId> {
2901 self.display_id
2902 }
2903
2904 pub fn inner_window_bounds(&self) -> WindowBounds {
2906 self.platform_window.inner_window_bounds()
2907 }
2908
2909 pub fn native_window_state(&self) -> Option<Vec<u8>> {
2912 self.platform_window.native_window_state()
2913 }
2914
2915 pub fn restore_native_window_state(&self, state: &[u8]) {
2918 self.platform_window.restore_native_window_state(state);
2919 }
2920
2921 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
2923 let focus_id = self.focused(cx).map(|handle| handle.id);
2924
2925 let window = self.handle;
2926 cx.defer(move |cx| {
2927 window
2928 .update(cx, |_, window, cx| {
2929 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
2930 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
2931 })
2932 .with_context(|| format!("dispatching action for window {:?}", window.window_id()))
2933 .log_err();
2934 })
2935 }
2936
2937 pub(crate) fn dispatch_keystroke_observers(
2938 &mut self,
2939 keystroke: &Keystroke,
2940 input_preference: InputPreference,
2941 action: Option<&dyn Action>,
2942 context_stack: Vec<KeyContext>,
2943 cx: &mut App,
2944 ) {
2945 cx.keystroke_observers.clone().retain(move |callback| {
2946 (callback)(
2947 &KeystrokeEvent {
2948 keystroke: keystroke.clone(),
2949 input_preference,
2950 action: action.map(|action| action.boxed_clone()),
2951 context_stack: context_stack.clone(),
2952 },
2953 self,
2954 cx,
2955 )
2956 });
2957 }
2958
2959 pub(crate) fn dispatch_keystroke_interceptors(
2960 &mut self,
2961 keystroke: &Keystroke,
2962 input_preference: InputPreference,
2963 context_stack: Vec<KeyContext>,
2964 cx: &mut App,
2965 ) {
2966 cx.keystroke_interceptors.clone().retain(move |callback| {
2967 (callback)(
2968 &KeystrokeEvent {
2969 keystroke: keystroke.clone(),
2970 input_preference,
2971 action: None,
2972 context_stack: context_stack.clone(),
2973 },
2974 self,
2975 cx,
2976 )
2977 });
2978 }
2979
2980 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2983 let handle = self.handle;
2984 cx.defer(move |cx| {
2985 handle.update(cx, |_, window, cx| f(window, cx)).ok();
2986 });
2987 }
2988
2989 pub fn observe<T: 'static>(
2993 &mut self,
2994 observed: &Entity<T>,
2995 cx: &mut App,
2996 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2997 ) -> Subscription {
2998 let entity_id = observed.entity_id();
2999 let observed = observed.downgrade();
3000 let window_handle = self.handle;
3001 cx.new_observer(
3002 entity_id,
3003 Box::new(move |cx| {
3004 window_handle
3005 .update(cx, |_, window, cx| {
3006 if let Some(handle) = observed.upgrade() {
3007 on_notify(handle, window, cx);
3008 true
3009 } else {
3010 false
3011 }
3012 })
3013 .unwrap_or(false)
3014 }),
3015 )
3016 }
3017
3018 pub fn subscribe<Emitter, Evt>(
3022 &mut self,
3023 entity: &Entity<Emitter>,
3024 cx: &mut App,
3025 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
3026 ) -> Subscription
3027 where
3028 Emitter: EventEmitter<Evt>,
3029 Evt: 'static,
3030 {
3031 let entity_id = entity.entity_id();
3032 let handle = entity.downgrade();
3033 let window_handle = self.handle;
3034 cx.new_subscription(
3035 entity_id,
3036 (
3037 TypeId::of::<Evt>(),
3038 Box::new(move |event, cx| {
3039 window_handle
3040 .update(cx, |_, window, cx| {
3041 if let Some(entity) = handle.upgrade() {
3042 let event = event.downcast_ref().expect("invalid event type");
3043 on_event(entity, event, window, cx);
3044 true
3045 } else {
3046 false
3047 }
3048 })
3049 .unwrap_or(false)
3050 }),
3051 ),
3052 )
3053 }
3054
3055 pub fn observe_release<T>(
3057 &self,
3058 entity: &Entity<T>,
3059 cx: &mut App,
3060 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
3061 ) -> Subscription
3062 where
3063 T: 'static,
3064 {
3065 let entity_id = entity.entity_id();
3066 let window_handle = self.handle;
3067 cx.release_listeners.insert(
3068 entity_id,
3069 Box::new(move |entity, cx| {
3070 let entity = entity.downcast_mut().expect("invalid entity type");
3071 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
3072 }),
3073 )
3074 }
3075
3076 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
3079 AsyncWindowContext::new_context(cx.to_async(), self.handle)
3080 }
3081
3082 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
3084 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
3085 self.platform_window.schedule_frame();
3086 self.invalidator.wake_platform();
3089 }
3090
3091 pub fn request_animation_frame(&self) {
3104 let entity = self.current_view();
3105 self.on_next_frame(move |_, cx| cx.notify(entity));
3106 }
3107
3108 pub(crate) fn advance_scene_animations(&mut self, cx: &App) {
3109 let elapsed = cx.background_executor().now() - cx.synced_animation_epoch;
3110 self.rendered_frame.scene.advance_animations(elapsed);
3111 }
3112
3113 #[cfg(any(test, feature = "test-support"))]
3118 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
3119 let callbacks = self.next_frame_callbacks.take();
3120 let count = callbacks.len();
3121 for callback in callbacks {
3122 callback(self, cx);
3123 }
3124 count
3125 }
3126
3127 #[track_caller]
3131 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
3132 where
3133 R: 'static,
3134 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3135 {
3136 let handle = self.handle;
3137 cx.spawn(async move |app| {
3138 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3139 f(&mut async_window_cx).await
3140 })
3141 }
3142
3143 #[track_caller]
3147 pub fn spawn_with_priority<AsyncFn, R>(
3148 &self,
3149 priority: Priority,
3150 cx: &App,
3151 f: AsyncFn,
3152 ) -> Task<R>
3153 where
3154 R: 'static,
3155 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3156 {
3157 let handle = self.handle;
3158 cx.spawn_with_priority(priority, async move |app| {
3159 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3160 f(&mut async_window_cx).await
3161 })
3162 }
3163
3164 pub fn bounds_changed(&mut self, cx: &mut App) {
3170 let scale_factor = self.platform_window.scale_factor();
3171 if self.scale_factor != scale_factor {
3172 self.scale_factor = scale_factor;
3173 if let Some(layout_engine) = self.layout_engine.as_mut() {
3174 layout_engine.clear_layout_cache();
3175 }
3176 }
3177 self.viewport_size = self.platform_window.content_size();
3178 self.last_window_bounds = self.platform_window.window_bounds();
3179 cx.sync_window_update_entry(self);
3180 self.mouse_position = self.platform_window.mouse_position();
3181
3182 self.refresh();
3183
3184 self.bounds_observers
3185 .clone()
3186 .retain(|callback| callback(self, cx));
3187 }
3188
3189 fn display_changed(handle: AnyWindowHandle, cx: &mut App) {
3190 let moved_to = handle
3191 .update(cx, |_, window, _| {
3192 let display_id = window.platform_window.display().map(|display| display.id());
3193 let moved = display_id != window.display_id;
3194 window.display_id = display_id;
3195 moved.then_some(display_id)
3196 })
3197 .with_context(|| {
3198 format!(
3199 "handling display change for window {:?}",
3200 handle.window_id()
3201 )
3202 })
3203 .log_err()
3204 .flatten();
3205 let Some(display_id) = moved_to else {
3206 return;
3207 };
3208 if let Some(display_id) = display_id
3212 && !cx.knows_display(display_id)
3213 {
3214 cx.displays_changed();
3215 }
3216 handle
3217 .update(cx, |_, window, cx| window.notify_display_observers(cx))
3218 .with_context(|| {
3219 format!(
3220 "notifying display observers for window {:?}",
3221 handle.window_id()
3222 )
3223 })
3224 .log_err();
3225 }
3226
3227 pub(crate) fn notify_display_observers(&mut self, cx: &mut App) {
3228 self.display_observers
3229 .clone()
3230 .retain(|callback| callback(self, cx));
3231 }
3232
3233 pub fn refresh_interval(&self, cx: &App) -> Option<Duration> {
3238 cx.display_refresh_interval(self.display_id?)
3239 }
3240
3241 pub fn observe_window_display(
3246 &self,
3247 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3248 ) -> Subscription {
3249 self.display_observers.insert(Box::new(move |window, cx| {
3250 callback(window, cx);
3251 true
3252 }))
3253 }
3254
3255 pub fn bounds(&self) -> Bounds<Pixels> {
3257 self.platform_window.bounds()
3258 }
3259
3260 pub fn insets(&self) -> WindowInsets {
3262 self.platform_window.insets()
3263 }
3264
3265 #[cfg(any(test, feature = "test-support"))]
3269 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
3270 self.platform_window
3271 .render_to_image(&self.rendered_frame.scene)
3272 }
3273
3274 #[cfg(feature = "bench-support")]
3277 pub fn rendered_scene(&self) -> &Scene {
3278 &self.rendered_frame.scene
3279 }
3280
3281 #[cfg(any(test, feature = "test-support"))]
3286 pub fn painted_quads(&self) -> Vec<Quad> {
3287 self.rendered_frame.scene.quads.clone()
3288 }
3289
3290 #[cfg(any(test, feature = "test-support"))]
3292 pub fn painted_underlines(&self) -> Vec<Underline> {
3293 self.rendered_frame.scene.underlines.clone()
3294 }
3295
3296 pub fn resize(&mut self, size: Size<Pixels>) {
3298 self.platform_window.resize(size);
3299 }
3300
3301 pub fn is_fullscreen(&self) -> bool {
3303 self.platform_window.is_fullscreen()
3304 }
3305
3306 pub fn is_simple_fullscreen(&self) -> bool {
3310 self.platform_window.is_simple_fullscreen()
3311 }
3312
3313 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
3314 self.appearance = self.platform_window.appearance();
3315
3316 self.appearance_observers
3317 .clone()
3318 .retain(|callback| callback(self, cx));
3319 }
3320
3321 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
3322 self.button_layout_observers
3323 .clone()
3324 .retain(|callback| callback(self, cx));
3325 }
3326
3327 pub fn appearance(&self) -> WindowAppearance {
3329 self.appearance
3330 }
3331
3332 pub fn viewport_size(&self) -> Size<Pixels> {
3334 self.viewport_size
3335 }
3336
3337 pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
3343 self.platform_window.visual_viewport_bounds()
3344 }
3345
3346 pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
3351 let insets = self.platform_window.insets().effective();
3352 let viewport = self.viewport_size();
3353 let left = insets.left.max(Pixels::ZERO).min(viewport.width);
3354 let top = insets.top.max(Pixels::ZERO).min(viewport.height);
3355 let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
3356 let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
3357 let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
3358 let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
3359 visible.size.width = visible.size.width.max(Pixels::ZERO);
3360 visible.size.height = visible.size.height.max(Pixels::ZERO);
3361 visible
3362 }
3363
3364 pub fn request_virtual_keyboard(&self) {
3369 self.platform_window.show_soft_keyboard();
3370 }
3371
3372 pub fn dismiss_virtual_keyboard(&self) {
3374 self.platform_window.hide_soft_keyboard();
3375 }
3376
3377 pub fn is_window_active(&self) -> bool {
3379 self.active.get()
3380 }
3381
3382 pub fn is_window_hovered(&self) -> bool {
3386 if cfg!(any(
3387 target_os = "windows",
3388 target_os = "linux",
3389 target_os = "freebsd"
3390 )) {
3391 self.hovered.get()
3392 } else {
3393 self.is_window_active()
3394 }
3395 }
3396
3397 pub fn zoom_window(&self) {
3399 self.platform_window.zoom();
3400 }
3401
3402 pub fn show_window_menu(&self, position: Point<Pixels>) {
3404 self.platform_window.show_window_menu(position)
3405 }
3406
3407 pub fn start_window_move(&self) {
3412 self.platform_window.start_window_move()
3413 }
3414
3415 pub fn set_client_inset(&mut self, inset: Pixels) {
3417 self.client_inset = Some(inset);
3418 self.platform_window.set_client_inset(inset);
3419 }
3420
3421 pub fn set_client_corner_radii(&mut self, radii: Corners<Pixels>) {
3423 self.platform_window.set_client_corner_radii(radii);
3424 }
3425
3426 pub fn client_inset(&self) -> Option<Pixels> {
3428 self.client_inset
3429 }
3430
3431 pub fn window_decorations(&self) -> Decorations {
3433 self.platform_window.window_decorations()
3434 }
3435
3436 pub fn is_resizable(&self) -> bool {
3438 self.is_resizable
3439 }
3440
3441 pub fn is_minimizable(&self) -> bool {
3443 self.is_minimizable
3444 }
3445
3446 pub fn window_controls(&self) -> WindowControls {
3448 self.platform_window.window_controls()
3449 }
3450
3451 pub fn set_window_title(&mut self, title: &str) {
3453 self.platform_window.set_title(title);
3454 self.a11y.set_window_title(title.to_string());
3455 }
3456
3457 #[cfg(target_os = "macos")]
3459 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
3460 self.platform_window.set_traffic_light_position(position);
3461 }
3462
3463 #[cfg(target_os = "macos")]
3465 pub fn set_native_titlebar_visibility(&self, visible: bool) {
3466 self.platform_window.set_native_titlebar_visibility(visible);
3467 }
3468
3469 pub fn set_app_id(&mut self, app_id: &str) {
3471 self.platform_window.set_app_id(app_id);
3472 }
3473
3474 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
3476 self.platform_window
3477 .set_background_appearance(background_appearance);
3478 }
3479
3480 pub fn set_window_edited(&mut self, edited: bool) {
3482 self.platform_window.set_edited(edited);
3483 }
3484
3485 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
3488 self.platform_window.set_document_path(path);
3489 }
3490
3491 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
3493 cx.platform
3494 .displays()
3495 .into_iter()
3496 .find(|display| Some(display.id()) == self.display_id)
3497 }
3498
3499 pub fn show_character_palette(&self) {
3501 self.platform_window.show_character_palette();
3502 }
3503
3504 pub fn scale_factor(&self) -> f32 {
3508 self.scale_factor
3509 }
3510
3511 #[cfg(any(test, feature = "test-support"))]
3513 pub fn set_scale_factor(&mut self, scale_factor: f32) {
3514 if self.scale_factor != scale_factor {
3515 self.scale_factor = scale_factor;
3516 if let Some(layout_engine) = self.layout_engine.as_mut() {
3517 layout_engine.clear_layout_cache();
3518 }
3519 }
3520 self.refresh();
3521 }
3522
3523 pub fn rem_size(&self) -> Pixels {
3526 self.rem_size_override_stack
3527 .last()
3528 .copied()
3529 .unwrap_or(self.rem_size)
3530 }
3531
3532 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
3535 self.rem_size = rem_size.into();
3536 }
3537
3538 pub fn with_global_id<R>(
3541 &mut self,
3542 element_id: ElementId,
3543 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
3544 ) -> R {
3545 self.with_id(element_id, |this| {
3546 let global_id = this.element_id_stack.global_id();
3547
3548 f(&global_id, this)
3549 })
3550 }
3551
3552 #[inline]
3554 pub fn with_id<R>(
3555 &mut self,
3556 element_id: impl Into<ElementId>,
3557 f: impl FnOnce(&mut Self) -> R,
3558 ) -> R {
3559 self.element_id_stack.push(element_id.into());
3560 let result = f(self);
3561 self.element_id_stack.pop();
3562 result
3563 }
3564
3565 #[inline]
3571 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
3572 where
3573 F: FnOnce(&mut Self) -> R,
3574 {
3575 self.invalidator.debug_assert_paint_or_prepaint();
3576
3577 if let Some(rem_size) = rem_size {
3578 self.rem_size_override_stack.push(rem_size.into());
3579 let result = f(self);
3580 self.rem_size_override_stack.pop();
3581 result
3582 } else {
3583 f(self)
3584 }
3585 }
3586
3587 pub fn line_height(&self) -> Pixels {
3589 self.text_style().line_height_in_pixels(self.rem_size())
3590 }
3591
3592 #[inline]
3594 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
3595 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
3596 }
3597
3598 #[inline]
3600 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
3601 let scale_factor = f64::from(self.scale_factor());
3602 round_half_toward_zero_f64(value * scale_factor) / scale_factor
3603 }
3604
3605 #[inline]
3607 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
3608 bounds.map(|c| self.pixel_snap(c))
3609 }
3610
3611 #[inline]
3613 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
3614 position.map(|c| self.pixel_snap(c))
3615 }
3616
3617 pub fn underline_bounds(
3619 &self,
3620 origin: Point<Pixels>,
3621 width: Pixels,
3622 style: &UnderlineStyle,
3623 ) -> Bounds<ScaledPixels> {
3624 let scale_factor = self.scale_factor();
3625 let thickness = self.snap_stroke(style.thickness);
3626 let height = if style.wavy {
3627 ScaledPixels(thickness.0 * 3.)
3628 } else {
3629 thickness
3630 };
3631 Bounds {
3632 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3633 size: size(self.snap_stroke(width), height),
3634 }
3635 }
3636
3637 pub fn paint_underline_with_exclusions(
3639 &mut self,
3640 origin: Point<Pixels>,
3641 width: Pixels,
3642 style: &UnderlineStyle,
3643 exclusions: &[Range<ScaledPixels>],
3644 ) {
3645 self.invalidator.debug_assert_paint();
3646 let underline = self.underline(origin, width, style);
3647 if exclusions.is_empty() {
3648 self.next_frame.scene.insert_primitive(underline);
3649 return;
3650 }
3651
3652 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
3653 if bounds.is_empty() {
3654 return;
3655 }
3656
3657 let mut exclusions = exclusions
3658 .iter()
3659 .filter_map(|span| {
3660 let start = span.start.max(bounds.left());
3661 let end = span.end.min(bounds.right());
3662 (start < end).then_some(start..end)
3663 })
3664 .collect::<SmallVec<[_; 4]>>();
3665 if exclusions.is_empty() {
3666 self.next_frame.scene.insert_primitive(underline);
3667 return;
3668 }
3669 exclusions.sort_unstable_by_key(|span| span.start);
3670
3671 let mut paint_span = |start, end| {
3672 self.next_frame.scene.insert_primitive(Underline {
3673 content_mask: ContentMask {
3674 bounds: Bounds::from_corners(
3675 point(start, bounds.top()),
3676 point(end, bounds.bottom()),
3677 ),
3678 },
3679 ..underline
3680 });
3681 };
3682 let mut start = bounds.left();
3683 for exclusion in exclusions {
3684 if start < exclusion.start {
3685 paint_span(start, exclusion.start);
3686 }
3687 start = start.max(exclusion.end);
3688 }
3689 if start < bounds.right() {
3690 paint_span(start, bounds.right());
3691 }
3692 }
3693
3694 fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline {
3695 Underline {
3696 order: 0,
3697 pad: 0,
3698 bounds: self.underline_bounds(origin, width, style),
3699 content_mask: self.snapped_content_mask(),
3700 color: style
3701 .color
3702 .unwrap_or_default()
3703 .opacity(self.element_opacity()),
3704 thickness: self.snap_stroke(style.thickness),
3705 wavy: style.wavy.into(),
3706 }
3707 }
3708
3709 #[inline]
3710 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
3711 let scale_factor = self.scale_factor();
3712 let left = round_to_device_pixel(bounds.left().0, scale_factor);
3713 let top = round_to_device_pixel(bounds.top().0, scale_factor);
3714 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
3715 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
3716 Bounds::from_corners(
3717 point(ScaledPixels(left), ScaledPixels(top)),
3718 point(ScaledPixels(right), ScaledPixels(bottom)),
3719 )
3720 }
3721
3722 #[inline]
3724 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
3725 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
3726 }
3727
3728 #[inline]
3729 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
3730 edges.map(|e| self.snap_stroke(*e))
3731 }
3732
3733 #[inline]
3735 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
3736 let scale_factor = self.scale_factor();
3737 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
3738 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
3739 if bounds.is_empty() {
3744 return Bounds::new(
3745 point(ScaledPixels(left), ScaledPixels(top)),
3746 Size::default(),
3747 );
3748 }
3749 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
3750 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
3751 Bounds::from_corners(
3752 point(ScaledPixels(left), ScaledPixels(top)),
3753 point(ScaledPixels(right), ScaledPixels(bottom)),
3754 )
3755 }
3756
3757 #[inline]
3758 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
3759 ContentMask {
3760 bounds: self.cover_bounds(self.content_mask().bounds),
3761 }
3762 }
3763
3764 pub fn prevent_default(&mut self) {
3767 self.default_prevented = true;
3768 }
3769
3770 pub fn default_prevented(&self) -> bool {
3772 self.default_prevented
3773 }
3774
3775 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
3777 let node_id =
3778 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
3779 self.rendered_frame
3780 .dispatch_tree
3781 .is_action_available(action, node_id)
3782 }
3783
3784 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
3786 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
3787 self.rendered_frame
3788 .dispatch_tree
3789 .is_action_available(action, node_id)
3790 }
3791
3792 pub fn mouse_position(&self) -> Point<Pixels> {
3794 self.mouse_position
3795 }
3796
3797 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
3804 self.captured_hitbox = Some(hitbox_id);
3805 }
3806
3807 pub fn release_pointer(&mut self) {
3809 self.captured_hitbox = None;
3810 }
3811
3812 pub fn captured_hitbox(&self) -> Option<HitboxId> {
3814 self.captured_hitbox
3815 }
3816
3817 pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
3823 self.long_press_capture = Some(entity.entity_id());
3824 }
3825
3826 pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
3828 self.long_press_capture == Some(entity.entity_id())
3829 }
3830
3831 pub fn modifiers(&self) -> Modifiers {
3833 self.modifiers
3834 }
3835
3836 pub fn last_input_was_keyboard(&self) -> bool {
3839 self.last_input_modality == InputModality::Keyboard
3840 }
3841
3842 pub fn last_input_was_touch(&self) -> bool {
3844 self.last_input_modality == InputModality::Touch
3845 }
3846
3847 pub fn capslock(&self) -> Capslock {
3849 self.capslock
3850 }
3851
3852 #[profiling::function]
3855 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
3856 #[cfg(feature = "profiler")]
3859 let frame_dirty = self.invalidator.take_frame_dirty();
3860 #[cfg(feature = "profiler")]
3861 self.window_profiler.begin_draw();
3862
3863 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
3866
3867 if self.platform_window.prepare_frame() {
3868 self.refresh();
3869 }
3870 self.invalidate_entities();
3871 cx.entities.clear_accessed();
3872 debug_assert!(self.rendered_entity_stack.is_empty());
3873 self.invalidator.set_dirty(false);
3874 self.requested_autoscroll = None;
3875
3876 if let Some(input_handler) = self.platform_window.take_input_handler() {
3881 if let Some(slot) = self
3882 .rendered_frame
3883 .input_handlers
3884 .iter_mut()
3885 .rev()
3886 .find(|h| h.is_none())
3887 {
3888 *slot = Some(input_handler);
3889 } else {
3890 self.rendered_frame.input_handlers.push(Some(input_handler));
3891 }
3892 }
3893 if !cx.mode.skip_drawing() {
3894 self.layout_engine
3895 .as_mut()
3896 .unwrap()
3897 .clear_if_scale_factor_changed(self.scale_factor);
3898 self.draw_roots(cx);
3899 #[cfg(feature = "profiler")]
3900 {
3901 let viewport_size = self.viewport_size;
3902 let scale_factor = self.scale_factor();
3903 self.debug_frame_overlay.paint(
3904 &mut self.next_frame.scene,
3905 viewport_size,
3906 scale_factor,
3907 );
3908 }
3909 }
3910 self.dirty_views.clear();
3911 self.next_frame.window_active = self.active.get();
3912
3913 let focused_text_input = if let Some(mut input_handler) = self
3919 .next_frame
3920 .input_handlers
3921 .iter_mut()
3922 .rev()
3923 .find_map(|h| h.take())
3924 {
3925 let accepts_text_input = input_handler.accepts_text_input(self, cx);
3926 self.platform_window.set_input_handler(input_handler);
3927 self.focus.filter(|_| accepts_text_input)
3928 } else {
3929 None
3930 };
3931 self.apply_text_input_configuration(cx);
3932 let previous = mem::replace(&mut self.focused_text_input, focused_text_input);
3933 if previous.is_some() != focused_text_input.is_some() {
3934 self.platform_window
3935 .text_input_state_changed(if focused_text_input.is_some() {
3936 TextInputStateChange::FocusGained
3937 } else {
3938 TextInputStateChange::FocusLost
3939 });
3940 }
3941
3942 self.layout_engine.as_mut().unwrap().clear();
3943 self.text_system().finish_frame();
3944 self.next_frame.finish(&mut self.rendered_frame);
3945
3946 self.invalidator.set_phase(DrawPhase::Focus);
3947 let previous_focus_path = self.rendered_frame.focus_path();
3948 let previous_window_active = self.rendered_frame.window_active;
3949 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
3950 self.scene_animation_interval
3951 .set(self.rendered_frame.scene.animation_frame_interval());
3952 self.next_frame.clear();
3953 let current_focus_path = self.rendered_frame.focus_path();
3954 let current_window_active = self.rendered_frame.window_active;
3955 let mut focus_before_listeners = self.focus;
3956
3957 if previous_focus_path != current_focus_path
3958 || previous_window_active != current_window_active
3959 {
3960 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
3961 self.focus_lost_path = previous_focus_path.clone();
3962 self.focus_lost_listeners
3963 .clone()
3964 .retain(|listener| listener(self, cx));
3965 self.focus_lost_path = SmallVec::new();
3966 focus_before_listeners = self.focus;
3971 }
3972
3973 let event = WindowFocusEvent {
3974 previous_focus_path: if previous_window_active {
3975 previous_focus_path
3976 } else {
3977 Default::default()
3978 },
3979 current_focus_path: if current_window_active {
3980 current_focus_path
3981 } else {
3982 Default::default()
3983 },
3984 };
3985 self.focus_listeners
3986 .clone()
3987 .retain(|listener| listener(&event, self, cx));
3988 }
3989
3990 debug_assert!(self.rendered_entity_stack.is_empty());
3991 self.record_entities_accessed(cx);
3992 self.reset_cursor_style(cx);
3993 self.refreshing = false;
3994 self.invalidator.set_phase(DrawPhase::None);
3995 if self.focus != focus_before_listeners {
4000 self.refresh();
4001 }
4002 self.needs_present.set(true);
4003
4004 #[cfg(feature = "profiler")]
4005 {
4006 self.window_profiler
4007 .set_refresh_interval(self.refresh_interval(cx));
4008 let draw_duration = self
4009 .window_profiler
4010 .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
4011 self.debug_frame_overlay.record_frame(draw_duration);
4012 }
4013
4014 arena_scope.exit(&cx.element_arena)
4017 }
4018
4019 fn record_entities_accessed(&mut self, cx: &mut App) {
4020 let entities = cx.entities.take_accessed();
4021 let handle = self.handle;
4022 cx.record_entities_accessed(
4023 handle,
4024 self.invalidator.clone(),
4026 &entities,
4027 );
4028 cx.entities.restore_accessed(entities);
4029 }
4030
4031 fn invalidate_entities(&mut self) {
4032 let mut views = self.invalidator.take_views();
4033 for entity in views.drain() {
4034 self.mark_view_dirty(entity);
4035 }
4036 self.invalidator.replace_views(views);
4037 }
4038
4039 #[profiling::function]
4040 fn present(&mut self) {
4041 #[cfg(feature = "profiler")]
4042 let _foreground_turn = profiler::journal::foreground_turn();
4043 #[cfg(feature = "profiler")]
4044 let present_start = Instant::now();
4045 self.platform_window.draw(&self.rendered_frame.scene);
4046 #[cfg(feature = "profiler")]
4047 self.window_profiler.record_present(
4048 present_start,
4049 Instant::now(),
4050 self.active.get(),
4051 !self.next_frame_callbacks.borrow().is_empty()
4052 || self.scene_animation_interval.get().is_some(),
4053 self.scene_animation_interval.get().is_some(),
4054 );
4055 self.needs_present.set(false);
4056 profiling::finish_frame!();
4057 }
4058
4059 #[cfg(all(test, feature = "profiler"))]
4061 pub fn present_if_needed(&mut self) {
4062 if self.needs_present.get() {
4063 self.present();
4064 }
4065 }
4066
4067 #[cfg(feature = "profiler")]
4069 pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
4070 self.window_profiler.input_latency_snapshot()
4071 }
4072
4073 #[cfg(feature = "profiler")]
4075 pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
4076 self.window_profiler.frame_duration_snapshot()
4077 }
4078
4079 #[cfg(feature = "profiler")]
4081 pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
4082 self.debug_frame_overlay.mode()
4083 }
4084
4085 #[cfg(feature = "profiler")]
4087 pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
4088 self.debug_frame_overlay.set_mode(mode);
4089 self.refresh();
4090 }
4091
4092 #[cfg(feature = "profiler")]
4095 pub fn cycle_debug_frame_overlay_mode(&mut self) {
4096 self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
4097 }
4098
4099 #[cfg(feature = "profiler")]
4102 pub fn reset_debug_frame_overlay_stats(&mut self) {
4103 self.debug_frame_overlay.reset_stats();
4104 self.refresh();
4105 }
4106
4107 fn draw_roots(&mut self, cx: &mut App) {
4108 self.invalidator.set_phase(DrawPhase::Prepaint);
4109 self.tooltip_bounds.take();
4110
4111 self.a11y.sync_active_flag();
4112 if self.a11y.is_active() {
4113 self.a11y.begin_frame();
4114 }
4115
4116 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
4117 let root_size = {
4118 #[cfg(any(feature = "inspector", debug_assertions))]
4119 {
4120 if self.inspector.is_some() {
4121 let mut size = self.viewport_size;
4122 size.width = (size.width - _inspector_width).max(px(0.0));
4123 size
4124 } else {
4125 self.viewport_size
4126 }
4127 }
4128 #[cfg(not(any(feature = "inspector", debug_assertions)))]
4129 {
4130 self.viewport_size
4131 }
4132 };
4133
4134 let scale_factor = self.scale_factor();
4138 #[cfg(feature = "profiler")]
4139 let request_layout_start = Instant::now();
4140 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
4141 let root_layout_id = root_element.request_layout(self, cx);
4142 #[cfg(feature = "profiler")]
4143 let prepaint_start = Instant::now();
4144 self.layout_engine
4145 .as_mut()
4146 .unwrap()
4147 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
4148 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
4149
4150 #[cfg(any(feature = "inspector", debug_assertions))]
4151 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
4152
4153 self.prepaint_deferred_draws(cx);
4154
4155 let mut prompt_element = None;
4156 let mut active_drag_element = None;
4157 let mut tooltip_element = None;
4158 if let Some(prompt) = self.prompt.take() {
4159 let mut element = prompt.view.any_view().into_any_element();
4160 let prompt_layout_id = element.request_layout(self, cx);
4161 self.layout_engine
4162 .as_mut()
4163 .unwrap()
4164 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
4165 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
4166 prompt_element = Some(element);
4167 self.prompt = Some(prompt);
4168 } else if let Some(active_drag) = cx.active_drag.take() {
4169 let mut element = active_drag.view.clone().into_any_element();
4170 let offset = self.mouse_position() - active_drag.cursor_offset;
4171 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
4172 active_drag_element = Some(element);
4173 cx.active_drag = Some(active_drag);
4174 } else {
4175 tooltip_element = self.prepaint_tooltip(cx);
4176 }
4177
4178 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
4179
4180 #[cfg(feature = "profiler")]
4182 let paint_start = Instant::now();
4183 self.invalidator.set_phase(DrawPhase::Paint);
4184 root_element.paint(self, cx);
4185
4186 #[cfg(any(feature = "inspector", debug_assertions))]
4187 self.paint_inspector(inspector_element, cx);
4188
4189 self.paint_deferred_draws(cx);
4190
4191 if let Some(mut prompt_element) = prompt_element {
4192 prompt_element.paint(self, cx);
4193 } else if let Some(mut drag_element) = active_drag_element {
4194 drag_element.paint(self, cx);
4195 } else if let Some(mut tooltip_element) = tooltip_element {
4196 tooltip_element.paint(self, cx);
4197 }
4198
4199 #[cfg(any(feature = "inspector", debug_assertions))]
4200 self.paint_inspector_hitbox(cx);
4201
4202 #[cfg(feature = "profiler")]
4203 self.window_profiler
4204 .record_draw_phases(profiler::DrawPhases {
4205 request_layout: prepaint_start.duration_since(request_layout_start),
4206 prepaint: paint_start.duration_since(prepaint_start),
4207 paint: Instant::now().duration_since(paint_start),
4208 });
4209
4210 let a11y_active_start_of_frame = self.a11y.is_active();
4212 self.a11y.sync_active_flag();
4213 let a11y_active_end_of_frame = self.a11y.is_active();
4214
4215 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
4216
4217 if a11y_active_start_of_frame {
4218 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
4221 viewport_size: self.viewport_size,
4222 scale_factor: self.scale_factor,
4223 tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
4224 };
4225 let tree_update = self.a11y.end_frame(frame_info);
4227
4228 if should_send_a11y_update {
4229 log::debug!(
4230 "Sending a11y tree update: {} nodes",
4231 tree_update.nodes.len()
4232 );
4233 self.platform_window.a11y_tree_update(tree_update);
4234 }
4235 }
4236 }
4237
4238 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
4239 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
4241 let Some(Some(tooltip_request)) = self
4242 .next_frame
4243 .tooltip_requests
4244 .get(tooltip_request_index)
4245 .cloned()
4246 else {
4247 log::error!("Unexpectedly absent TooltipRequest");
4248 continue;
4249 };
4250 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
4251 let mouse_position = tooltip_request.tooltip.mouse_position;
4252 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
4253
4254 let mut tooltip_bounds =
4255 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
4256 let window_bounds = Bounds {
4257 origin: Point::default(),
4258 size: self.viewport_size(),
4259 };
4260
4261 if tooltip_bounds.right() > window_bounds.right() {
4262 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
4263 if new_x >= Pixels::ZERO {
4264 tooltip_bounds.origin.x = new_x;
4265 } else {
4266 tooltip_bounds.origin.x = cmp::max(
4267 Pixels::ZERO,
4268 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
4269 );
4270 }
4271 }
4272
4273 if tooltip_bounds.bottom() > window_bounds.bottom() {
4274 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
4275 if new_y >= Pixels::ZERO {
4276 tooltip_bounds.origin.y = new_y;
4277 } else {
4278 tooltip_bounds.origin.y = cmp::max(
4279 Pixels::ZERO,
4280 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
4281 );
4282 }
4283 }
4284
4285 let is_visible =
4289 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
4290 if !is_visible {
4291 continue;
4292 }
4293
4294 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
4295 element.prepaint(window, cx)
4296 });
4297
4298 self.tooltip_bounds = Some(TooltipBounds {
4299 id: tooltip_request.id,
4300 bounds: tooltip_bounds,
4301 });
4302 return Some(element);
4303 }
4304 None
4305 }
4306
4307 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
4308 assert_eq!(self.element_id_stack.len(), 0);
4309
4310 let mut round_start = 0;
4321 let mut depth = 0;
4322 loop {
4323 let round_end = self.next_frame.deferred_draws.len();
4324 if round_start == round_end {
4325 break;
4326 }
4327 assert!(depth < 10, "Exceeded maximum (10) deferred depth");
4329 depth += 1;
4330
4331 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
4333 traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
4334
4335 for deferred_draw_ix in traversal_order {
4336 let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
4337 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
4338 self.element_id_stack
4339 .clone_from(&deferred_draw.element_id_stack);
4340 self.text_style_stack
4341 .clone_from(&deferred_draw.text_style_stack);
4342 (
4343 deferred_draw.element.take(),
4344 deferred_draw.parent_node,
4345 deferred_draw.current_view,
4346 deferred_draw.rem_size,
4347 deferred_draw.absolute_offset,
4348 deferred_draw.prepaint_range.clone(),
4349 )
4350 };
4351 self.next_frame.dispatch_tree.set_active_node(parent_node);
4352
4353 let prepaint_start = self.prepaint_index();
4354 if let Some(mut element) = element {
4355 let content_mask =
4356 self.next_frame.deferred_draws[deferred_draw_ix].content_mask;
4357 let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
4358 self.with_rendered_view(current_view, |window| {
4359 window.with_rem_size(Some(rem_size), |window| {
4360 window.with_absolute_element_offset(absolute_offset, |window| {
4361 window.with_content_mask(content_mask, |window| {
4362 element.prepaint(window, cx);
4363 });
4364 });
4365 });
4366 });
4367 });
4368 self.next_frame.deferred_draws[deferred_draw_ix].accessed_entities =
4369 accessed_entities;
4370 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
4371 } else {
4372 cx.entities.extend_accessed(
4373 self.next_frame.deferred_draws[deferred_draw_ix]
4374 .accessed_entities
4375 .iter()
4376 .copied(),
4377 );
4378 self.reuse_prepaint(prepaint_range);
4379 }
4380 let prepaint_end = self.prepaint_index();
4381 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
4382 prepaint_start..prepaint_end;
4383 }
4384
4385 self.element_id_stack.clear();
4386 self.text_style_stack.clear();
4387 round_start = round_end;
4388 }
4389 }
4390
4391 fn paint_deferred_draws(&mut self, cx: &mut App) {
4392 assert_eq!(self.element_id_stack.len(), 0);
4393
4394 if self.next_frame.deferred_draws.len() == 0 {
4397 return;
4398 }
4399
4400 let traversal_order = self.deferred_draw_traversal_order();
4401 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
4402 for deferred_draw_ix in traversal_order {
4403 let deferred_draw = &mut deferred_draws[deferred_draw_ix];
4404 self.element_id_stack
4405 .clone_from(&deferred_draw.element_id_stack);
4406 self.next_frame
4407 .dispatch_tree
4408 .set_active_node(deferred_draw.parent_node);
4409
4410 let paint_start = self.paint_index();
4411 let content_mask = deferred_draw.content_mask;
4412 if let Some(element) = deferred_draw.element.as_mut() {
4413 let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
4414 self.with_rendered_view(deferred_draw.current_view, |window| {
4415 window.with_content_mask(content_mask, |window| {
4416 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
4417 element.paint(window, cx);
4418 });
4419 })
4420 })
4421 });
4422 deferred_draw.accessed_entities.extend(accessed_entities);
4423 } else {
4424 self.reuse_paint(deferred_draw.paint_range.clone());
4425 }
4426 let paint_end = self.paint_index();
4427 deferred_draw.paint_range = paint_start..paint_end;
4428 }
4429 self.next_frame.deferred_draws = deferred_draws;
4430 self.element_id_stack.clear();
4431 }
4432
4433 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
4434 let deferred_count = self.next_frame.deferred_draws.len();
4435 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
4436 sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
4437 sorted_indices
4438 }
4439
4440 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
4441 PrepaintStateIndex {
4442 hitboxes_index: self.next_frame.hitboxes.len(),
4443 tooltips_index: self.next_frame.tooltip_requests.len(),
4444 deferred_draws_index: self.next_frame.deferred_draws.len(),
4445 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
4446 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
4447 line_layout_index: self.text_system.layout_index(),
4448 }
4449 }
4450
4451 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
4452 self.next_frame.hitboxes.extend(
4453 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
4454 .iter()
4455 .cloned(),
4456 );
4457 self.next_frame.tooltip_requests.extend(
4458 self.rendered_frame.tooltip_requests
4459 [range.start.tooltips_index..range.end.tooltips_index]
4460 .iter_mut()
4461 .map(|request| request.take()),
4462 );
4463 self.next_frame.accessed_element_states.extend(
4464 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
4465 ..range.end.accessed_element_states_index]
4466 .iter()
4467 .map(|(id, type_id)| (id.clone(), *type_id)),
4468 );
4469 self.text_system
4470 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
4471
4472 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
4473 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
4474 &mut self.rendered_frame.dispatch_tree,
4475 self.focus,
4476 );
4477
4478 if reused_subtree.contains_focus() {
4479 self.next_frame.focus = self.focus;
4480 }
4481
4482 self.next_frame.deferred_draws.extend(
4483 self.rendered_frame.deferred_draws
4484 [range.start.deferred_draws_index..range.end.deferred_draws_index]
4485 .iter()
4486 .map(|deferred_draw| DeferredDraw {
4487 current_view: deferred_draw.current_view,
4488 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
4489 element_id_stack: deferred_draw.element_id_stack.clone(),
4490 text_style_stack: deferred_draw.text_style_stack.clone(),
4491 content_mask: deferred_draw.content_mask,
4492 rem_size: deferred_draw.rem_size,
4493 priority: deferred_draw.priority,
4494 element: None,
4495 absolute_offset: deferred_draw.absolute_offset,
4496 prepaint_range: deferred_draw.prepaint_range.clone(),
4497 paint_range: deferred_draw.paint_range.clone(),
4498 accessed_entities: deferred_draw.accessed_entities.clone(),
4499 }),
4500 );
4501 }
4502
4503 pub(crate) fn paint_index(&self) -> PaintIndex {
4504 PaintIndex {
4505 scene_index: self.next_frame.scene.len(),
4506 #[cfg(any(test, feature = "test-support"))]
4507 debug_bounds_index: self.next_frame.debug_bounds_records.len(),
4508 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
4509 input_handlers_index: self.next_frame.input_handlers.len(),
4510 cursor_styles_index: self.next_frame.cursor_styles.len(),
4511 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
4512 tab_handle_index: self.next_frame.tab_stops.paint_index(),
4513 line_layout_index: self.text_system.layout_index(),
4514 }
4515 }
4516
4517 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
4518 #[cfg(any(test, feature = "test-support"))]
4520 for (selector, bounds) in &self.rendered_frame.debug_bounds_records
4521 [range.start.debug_bounds_index..range.end.debug_bounds_index]
4522 {
4523 self.next_frame
4524 .record_debug_bounds(selector.clone(), *bounds);
4525 }
4526 self.next_frame.cursor_styles.extend(
4527 self.rendered_frame.cursor_styles
4528 [range.start.cursor_styles_index..range.end.cursor_styles_index]
4529 .iter()
4530 .cloned(),
4531 );
4532 self.next_frame.input_handlers.extend(
4533 self.rendered_frame.input_handlers
4534 [range.start.input_handlers_index..range.end.input_handlers_index]
4535 .iter_mut()
4536 .map(|handler| handler.take()),
4537 );
4538 self.next_frame.mouse_listeners.extend(
4539 self.rendered_frame.mouse_listeners
4540 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
4541 .iter_mut()
4542 .map(|listener| listener.take()),
4543 );
4544 self.next_frame.accessed_element_states.extend(
4545 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
4546 ..range.end.accessed_element_states_index]
4547 .iter()
4548 .map(|(id, type_id)| (id.clone(), *type_id)),
4549 );
4550 self.next_frame.tab_stops.replay(
4551 &self.rendered_frame.tab_stops.insertion_history
4552 [range.start.tab_handle_index..range.end.tab_handle_index],
4553 );
4554
4555 self.text_system
4556 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
4557 self.next_frame.scene.replay(
4558 range.start.scene_index..range.end.scene_index,
4559 &self.rendered_frame.scene,
4560 );
4561 }
4562
4563 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
4567 where
4568 F: FnOnce(&mut Self) -> R,
4569 {
4570 self.invalidator.debug_assert_paint_or_prepaint();
4571 if let Some(style) = style {
4572 self.text_style_stack.push(style);
4573 let result = f(self);
4574 self.text_style_stack.pop();
4575 result
4576 } else {
4577 f(self)
4578 }
4579 }
4580
4581 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
4584 self.invalidator.debug_assert_paint();
4585 self.next_frame.cursor_styles.push(CursorStyleRequest {
4586 hitbox_id: Some(hitbox.id),
4587 style,
4588 });
4589 }
4590
4591 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
4596 self.invalidator.debug_assert_paint();
4597 self.next_frame.cursor_styles.push(CursorStyleRequest {
4598 hitbox_id: None,
4599 style,
4600 })
4601 }
4602
4603 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
4606 self.invalidator.debug_assert_prepaint();
4607 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
4608 self.next_frame
4609 .tooltip_requests
4610 .push(Some(TooltipRequest { id, tooltip }));
4611 id
4612 }
4613
4614 #[inline]
4619 pub fn with_content_mask<R>(
4620 &mut self,
4621 mask: Option<ContentMask<Pixels>>,
4622 f: impl FnOnce(&mut Self) -> R,
4623 ) -> R {
4624 self.invalidator.debug_assert_paint_or_prepaint();
4625 if let Some(mask) = mask {
4626 let mask = mask.intersect(&self.content_mask());
4627 self.content_mask_stack.push(mask);
4628 let result = f(self);
4629 self.content_mask_stack.pop();
4630 result
4631 } else {
4632 f(self)
4633 }
4634 }
4635
4636 pub fn with_element_offset<R>(
4639 &mut self,
4640 offset: Point<Pixels>,
4641 f: impl FnOnce(&mut Self) -> R,
4642 ) -> R {
4643 self.invalidator.debug_assert_prepaint();
4644
4645 if offset.is_zero() {
4646 return f(self);
4647 };
4648
4649 let abs_offset = self.element_offset() + offset;
4650 self.with_absolute_element_offset(abs_offset, f)
4651 }
4652
4653 pub fn with_absolute_element_offset<R>(
4657 &mut self,
4658 offset: Point<Pixels>,
4659 f: impl FnOnce(&mut Self) -> R,
4660 ) -> R {
4661 self.invalidator.debug_assert_prepaint();
4662 self.element_offset_stack.push(offset);
4663 let result = f(self);
4664 self.element_offset_stack.pop();
4665 result
4666 }
4667
4668 pub(crate) fn with_element_opacity<R>(
4669 &mut self,
4670 opacity: Option<f32>,
4671 f: impl FnOnce(&mut Self) -> R,
4672 ) -> R {
4673 self.invalidator.debug_assert_paint_or_prepaint();
4674
4675 let Some(opacity) = opacity else {
4676 return f(self);
4677 };
4678
4679 let previous_opacity = self.element_opacity;
4680 self.element_opacity = previous_opacity * opacity;
4681 let result = f(self);
4682 self.element_opacity = previous_opacity;
4683 result
4684 }
4685
4686 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
4692 self.invalidator.debug_assert_prepaint();
4693 let index = self.prepaint_index();
4694 let result = f(self);
4695 if result.is_err() {
4696 self.next_frame.hitboxes.truncate(index.hitboxes_index);
4697 self.next_frame
4698 .tooltip_requests
4699 .truncate(index.tooltips_index);
4700 self.next_frame
4701 .deferred_draws
4702 .truncate(index.deferred_draws_index);
4703 self.next_frame
4704 .dispatch_tree
4705 .truncate(index.dispatch_tree_index);
4706 self.next_frame
4707 .accessed_element_states
4708 .truncate(index.accessed_element_states_index);
4709 self.text_system.truncate_layouts(index.line_layout_index);
4710 }
4711 result
4712 }
4713
4714 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
4720 self.invalidator.debug_assert_prepaint();
4721 self.requested_autoscroll = Some(bounds);
4722 }
4723
4724 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
4727 self.invalidator.debug_assert_prepaint();
4728 self.requested_autoscroll.take()
4729 }
4730
4731 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4737 cx.asset_entry::<A>(source).use_by(self.current_view())
4738 }
4739
4740 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4746 cx.fetch_asset::<A>(source)
4747 }
4748 pub fn element_offset(&self) -> Point<Pixels> {
4751 self.invalidator.debug_assert_prepaint();
4752 self.element_offset_stack
4753 .last()
4754 .copied()
4755 .unwrap_or_default()
4756 }
4757
4758 #[inline]
4761 pub(crate) fn element_opacity(&self) -> f32 {
4762 self.invalidator.debug_assert_paint_or_prepaint();
4763 self.element_opacity
4764 }
4765
4766 pub fn content_mask(&self) -> ContentMask<Pixels> {
4768 self.invalidator.debug_assert_paint_or_prepaint();
4769 self.content_mask_stack
4770 .last()
4771 .cloned()
4772 .unwrap_or_else(|| ContentMask {
4773 bounds: Bounds {
4774 origin: Point::default(),
4775 size: self.viewport_size,
4776 },
4777 })
4778 }
4779
4780 pub fn with_element_namespace<R>(
4783 &mut self,
4784 element_id: impl Into<ElementId>,
4785 f: impl FnOnce(&mut Self) -> R,
4786 ) -> R {
4787 self.element_id_stack.push(element_id.into());
4788 let result = f(self);
4789 self.element_id_stack.pop();
4790 result
4791 }
4792
4793 pub fn use_keyed_state<S: 'static>(
4795 &mut self,
4796 key: impl Into<ElementId>,
4797 cx: &mut App,
4798 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4799 ) -> Entity<S> {
4800 let current_view = self.current_view();
4801 self.with_global_id(key.into(), |global_id, window| {
4802 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
4803 if let Some(state) = state {
4804 (state.clone(), state)
4805 } else {
4806 let new_state = cx.new(|cx| init(window, cx));
4807 Self::observe_keyed_state(&new_state, current_view, cx);
4808 (new_state.clone(), new_state)
4809 }
4810 })
4811 })
4812 }
4813
4814 #[track_caller]
4820 pub fn use_state<S: 'static>(
4821 &mut self,
4822 cx: &mut App,
4823 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4824 ) -> Entity<S> {
4825 self.use_keyed_state(
4826 ElementId::CodeLocation(*core::panic::Location::caller()),
4827 cx,
4828 init,
4829 )
4830 }
4831
4832 #[inline(always)]
4837 pub fn with_element_state<S, R>(
4838 &mut self,
4839 global_id: &GlobalElementId,
4840 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
4841 ) -> R
4842 where
4843 S: 'static,
4844 {
4845 self.invalidator.debug_assert_paint_or_prepaint();
4846
4847 let (key, state) = self.take_element_state(global_id, TypeId::of::<S>());
4848
4849 if let Some(any) = state {
4850 let ElementStateBox {
4851 inner,
4852 #[cfg(debug_assertions)]
4853 type_name,
4854 } = any;
4855 let mut state_box = inner
4857 .downcast::<Option<S>>()
4858 .map_err(|_| {
4859 #[cfg(debug_assertions)]
4860 {
4861 anyhow::anyhow!(
4862 "invalid element state type for id, requested {:?}, actual: {:?}",
4863 std::any::type_name::<S>(),
4864 type_name
4865 )
4866 }
4867
4868 #[cfg(not(debug_assertions))]
4869 {
4870 anyhow::anyhow!(
4871 "invalid element state type for id, requested {:?}",
4872 std::any::type_name::<S>(),
4873 )
4874 }
4875 })
4876 .unwrap();
4877
4878 let state = state_box.take().expect(
4879 "reentrant call to with_element_state for the same state type and element id",
4880 );
4881 let (result, state) = f(Some(state), self);
4882 state_box.replace(state);
4883 self.insert_element_state(
4884 key,
4885 ElementStateBox {
4886 inner: state_box,
4887 #[cfg(debug_assertions)]
4888 type_name,
4889 },
4890 );
4891 result
4892 } else {
4893 let (result, state) = f(None, self);
4894 self.insert_element_state(
4895 key,
4896 ElementStateBox {
4897 inner: Box::new(Some(state)),
4898 #[cfg(debug_assertions)]
4899 type_name: std::any::type_name::<S>(),
4900 },
4901 );
4902 result
4903 }
4904 }
4905
4906 pub fn with_optional_element_state<S, R>(
4913 &mut self,
4914 global_id: Option<&GlobalElementId>,
4915 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
4916 ) -> R
4917 where
4918 S: 'static,
4919 {
4920 self.invalidator.debug_assert_paint_or_prepaint();
4921
4922 if let Some(global_id) = global_id {
4923 self.with_element_state(global_id, |state, cx| {
4924 let (result, state) = f(Some(state), cx);
4925 let state =
4926 state.expect("you must return some state when you pass some element id");
4927 (result, state)
4928 })
4929 } else {
4930 let (result, state) = f(None, self);
4931 debug_assert!(
4932 state.is_none(),
4933 "you must not return an element state when passing None for the global id"
4934 );
4935 result
4936 }
4937 }
4938
4939 #[inline]
4941 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
4942 if let Some(index) = index {
4943 self.next_frame.tab_stops.begin_group(index);
4944 let result = f(self);
4945 self.next_frame.tab_stops.end_group();
4946 result
4947 } else {
4948 f(self)
4949 }
4950 }
4951
4952 pub fn defer_draw(
4961 &mut self,
4962 element: AnyElement,
4963 absolute_offset: Point<Pixels>,
4964 priority: usize,
4965 content_mask: Option<ContentMask<Pixels>>,
4966 ) {
4967 self.invalidator.debug_assert_prepaint();
4968 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
4969 self.next_frame.deferred_draws.push(DeferredDraw {
4970 current_view: self.current_view(),
4971 parent_node,
4972 element_id_stack: self.element_id_stack.clone(),
4973 text_style_stack: self.text_style_stack.clone(),
4974 content_mask,
4975 rem_size: self.rem_size(),
4976 priority,
4977 element: Some(element),
4978 absolute_offset,
4979 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
4980 paint_range: PaintIndex::default()..PaintIndex::default(),
4981 accessed_entities: FxHashSet::default(),
4982 });
4983 }
4984
4985 pub fn paint_layer<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
4994 self.invalidator.debug_assert_paint();
4995
4996 self.next_frame.scene.push_layer();
4997 let result = f(self);
4998 self.next_frame.scene.pop_layer();
4999 result
5000 }
5001
5002 pub fn paint_drop_shadows(
5008 &mut self,
5009 bounds: Bounds<Pixels>,
5010 corner_radii: Corners<Pixels>,
5011 shadows: &[BoxShadow],
5012 ) {
5013 self.invalidator.debug_assert_paint();
5014
5015 let scale_factor = self.scale_factor();
5016 let content_mask = self.snapped_content_mask();
5017 let opacity = self.element_opacity();
5018 for shadow in shadows {
5019 if shadow.inset {
5020 continue;
5021 }
5022 let shape_bounds =
5023 self.cover_bounds((bounds + shadow.offset).dilate(shadow.spread_radius));
5024 if shape_bounds.is_empty() {
5025 continue;
5026 }
5027 let blur_radius = shadow.blur_radius.scale(scale_factor);
5028 self.next_frame.scene.insert_primitive(Shadow {
5029 order: 0,
5030 blur_radius,
5031 bounds: shape_bounds.dilate(blur_radius * 3.),
5033 content_mask,
5034 corner_radii: Corners::default(),
5035 color: shadow.color.opacity(opacity),
5036 shape_bounds,
5037 shape_corner_radii: corner_radii.scale(scale_factor),
5038 inset: false.into(),
5039 pad: 0,
5040 });
5041 }
5042 }
5043
5044 pub fn paint_inset_shadows(
5048 &mut self,
5049 bounds: Bounds<Pixels>,
5050 corner_radii: Corners<Pixels>,
5051 shadows: &[BoxShadow],
5052 ) {
5053 self.invalidator.debug_assert_paint();
5054
5055 let scale_factor = self.scale_factor();
5056 let content_mask = self.snapped_content_mask();
5057 let opacity = self.element_opacity();
5058 let element_bounds = self.cover_bounds(bounds);
5059 let element_corner_radii = corner_radii.scale(scale_factor);
5060 for shadow in shadows {
5061 if !shadow.inset {
5062 continue;
5063 }
5064 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
5065 let zero = Pixels::ZERO;
5068 let hole_corner_radii = Corners {
5069 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
5070 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
5071 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
5072 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
5073 };
5074 self.next_frame.scene.insert_primitive(Shadow {
5075 order: 0,
5076 blur_radius: shadow.blur_radius.scale(scale_factor),
5077 bounds: element_bounds,
5078 content_mask,
5079 corner_radii: element_corner_radii,
5080 color: shadow.color.opacity(opacity),
5081 shape_bounds: self.cover_bounds(hole),
5082 shape_corner_radii: hole_corner_radii.scale(scale_factor),
5083 inset: true.into(),
5084 pad: 0,
5085 });
5086 }
5087 }
5088
5089 fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
5090 let size = quad.bounds.size;
5091 let diagonal = (size.width.0 * size.width.0 + size.height.0 * size.height.0).sqrt();
5092 if diagonal == 0. {
5093 return Bounds::default();
5094 }
5095 let cos = size.height.0 / diagonal;
5099 let sin = size.width.0 / diagonal;
5100
5101 let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| {
5104 point(
5105 width_x.max(radius - (radius - width_x) * cos),
5106 width_y.max(radius - (radius - width_y) * sin),
5107 )
5108 };
5109
5110 let radii = &quad.corner_radii;
5111 let widths = &quad.border_widths;
5112 let top_left = corner_inset(radii.top_left, widths.left, widths.top);
5113 let top_right = corner_inset(radii.top_right, widths.right, widths.top);
5114 let bottom_right = corner_inset(radii.bottom_right, widths.right, widths.bottom);
5115 let bottom_left = corner_inset(radii.bottom_left, widths.left, widths.bottom);
5116
5117 let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
5118 Bounds::from_corners(
5119 quad.bounds.origin
5120 + point(top_left.x.max(bottom_left.x), top_left.y.max(top_right.y))
5121 + antialias_inset,
5122 quad.bounds.bottom_right()
5123 - point(
5124 top_right.x.max(bottom_right.x),
5125 bottom_left.y.max(bottom_right.y),
5126 )
5127 - antialias_inset,
5128 )
5129 }
5130
5131 pub fn paint_quad(&mut self, quad: PaintQuad) {
5141 self.invalidator.debug_assert_paint();
5142
5143 let opacity = self.element_opacity();
5144 let snapped_bounds = self.snap_bounds(quad.bounds);
5145 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
5146 let quad = Quad {
5147 order: 0,
5148 bounds: snapped_bounds,
5149 content_mask: self.snapped_content_mask(),
5150 background: quad.background.opacity(opacity),
5151 border_color: quad.border_color.opacity(opacity),
5152 corner_radii: quad.corner_radii.scale(self.scale_factor()),
5153 border_widths: snapped_border_widths,
5154 border_style: quad.border_style,
5155 };
5156 self.insert_quad(quad);
5157 }
5158
5159 fn insert_quad(&mut self, quad: Quad) {
5160 let has_background = !quad.background.is_transparent();
5161 let has_border =
5162 quad.border_widths != Edges::default() && !quad.border_color.is_transparent();
5163 if !has_background && !has_border {
5164 return;
5165 }
5166
5167 let is_rectangle =
5168 quad.border_widths == Edges::default() && quad.corner_radii == Corners::default();
5169 if has_background && is_rectangle {
5170 self.next_frame.scene.insert_primitive(quad);
5171 return;
5172 }
5173
5174 let plain_border = quad.corner_radii == Corners::default()
5175 && quad.border_style == BorderStyle::Solid
5176 && (!has_background || quad.border_color.is_opaque());
5177
5178 let outer_bounds = quad.bounds;
5181 let inner_bounds = if plain_border {
5182 quad.bounds.extend(quad.border_widths.map(|width| -*width))
5183 } else {
5184 Self::largest_border_interior(&quad)
5185 };
5186
5187 let strip_quad = if plain_border {
5191 Quad {
5192 background: quad.border_color.into(),
5193 border_widths: Edges::default(),
5194 ..quad
5195 }
5196 } else {
5197 quad
5198 };
5199
5200 if inner_bounds.is_empty() {
5201 self.next_frame.scene.insert_primitive(strip_quad);
5202 return;
5203 }
5204
5205 if has_background {
5206 self.next_frame.scene.insert_primitive(Quad {
5207 content_mask: ContentMask {
5208 bounds: quad.content_mask.bounds.intersect(&inner_bounds),
5209 },
5210 border_widths: Edges::default(),
5211 corner_radii: Corners::default(),
5212 ..quad
5213 });
5214 }
5215
5216 let strips = [
5217 Bounds::from_corners(
5219 outer_bounds.origin,
5220 point(outer_bounds.right(), inner_bounds.top()),
5221 ),
5222 Bounds::from_corners(
5224 point(outer_bounds.left(), inner_bounds.bottom()),
5225 outer_bounds.bottom_right(),
5226 ),
5227 Bounds::from_corners(
5229 point(outer_bounds.left(), inner_bounds.top()),
5230 inner_bounds.bottom_left(),
5231 ),
5232 Bounds::from_corners(
5234 inner_bounds.top_right(),
5235 point(outer_bounds.right(), inner_bounds.bottom()),
5236 ),
5237 ];
5238
5239 for strip in strips {
5240 self.next_frame.scene.insert_primitive(Quad {
5241 content_mask: ContentMask {
5242 bounds: quad.content_mask.bounds.intersect(&strip),
5243 },
5244 ..strip_quad
5245 });
5246 }
5247 }
5248
5249 pub fn paint_path(&mut self, path: Path, color: impl Into<Background>) {
5253 self.invalidator.debug_assert_paint();
5254
5255 let scale_factor = self.scale_factor();
5256 let content_mask = self.content_mask();
5257 let opacity = self.element_opacity();
5258 let color: Background = color.into();
5259 self.next_frame.scene.insert_primitive(PaintedPath::new(
5260 path,
5261 scale_factor,
5262 content_mask,
5263 color.opacity(opacity),
5264 ));
5265 }
5266
5267 pub fn paint_underline(
5271 &mut self,
5272 origin: Point<Pixels>,
5273 width: Pixels,
5274 style: &UnderlineStyle,
5275 ) {
5276 self.invalidator.debug_assert_paint();
5277 let underline = self.underline(origin, width, style);
5278 self.next_frame.scene.insert_primitive(underline);
5279 }
5280
5281 pub fn paint_strikethrough(
5285 &mut self,
5286 origin: Point<Pixels>,
5287 width: Pixels,
5288 style: &StrikethroughStyle,
5289 ) {
5290 self.invalidator.debug_assert_paint();
5291
5292 let scale_factor = self.scale_factor();
5293 let height = style.thickness;
5294 let bounds = Bounds {
5295 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
5296 size: size(self.snap_stroke(width), self.snap_stroke(height)),
5297 };
5298 let opacity = self.element_opacity();
5299
5300 self.next_frame.scene.insert_primitive(Underline {
5301 order: 0,
5302 pad: 0,
5303 bounds,
5304 content_mask: self.snapped_content_mask(),
5305 thickness: self.snap_stroke(style.thickness),
5306 color: style.color.unwrap_or_default().opacity(opacity),
5307 wavy: false.into(),
5308 });
5309 }
5310
5311 pub fn paint_glyph(
5320 &mut self,
5321 origin: Point<Pixels>,
5322 font_id: FontId,
5323 glyph_id: GlyphId,
5324 font_size: Pixels,
5325 color: Hsla,
5326 ) -> Result<()> {
5327 self.invalidator.debug_assert_paint();
5328
5329 let element_opacity = self.element_opacity();
5330 let scale_factor = self.scale_factor();
5331 let glyph_origin = origin.scale(scale_factor);
5332
5333 let quantized_origin = Point::new(
5334 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
5335 / SUBPIXEL_VARIANTS_X as f32,
5336 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
5337 / SUBPIXEL_VARIANTS_Y as f32,
5338 );
5339 let subpixel_variant = Point::new(
5340 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
5341 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
5342 );
5343 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
5344 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
5345 let dilation = self.text_system().glyph_dilation_for_color(color);
5346 let params = RenderGlyphParams {
5347 font_id,
5348 glyph_id,
5349 font_size,
5350 subpixel_variant,
5351 scale_factor,
5352 is_emoji: false,
5353 subpixel_rendering,
5354 dilation,
5355 };
5356
5357 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
5358 if !raster_bounds.is_zero() {
5359 let tile = self
5360 .sprite_atlas
5361 .get_or_insert_with(params.clone().into(), &mut || {
5362 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
5363 Ok(Some((size, Cow::Owned(bytes))))
5364 })?
5365 .expect("Callback above only errors or returns Some");
5366 let bounds = Bounds {
5367 origin: integer_origin + raster_bounds.origin.map(Into::into),
5368 size: tile.bounds.size.map(Into::into),
5369 };
5370 let content_mask = self.snapped_content_mask();
5371
5372 if subpixel_rendering {
5373 self.next_frame.scene.insert_primitive(SubpixelSprite {
5374 order: 0,
5375 pad: 0,
5376 bounds,
5377 content_mask,
5378 color: color.opacity(element_opacity),
5379 tile,
5380 transformation: TransformationMatrix::unit(),
5381 });
5382 } else {
5383 self.next_frame.scene.insert_primitive(MonochromeSprite {
5384 order: 0,
5385 animation: SpriteAnimationId::NONE,
5386 bounds,
5387 content_mask,
5388 color: color.opacity(element_opacity),
5389 tile,
5390 transformation: TransformationMatrix::unit(),
5391 });
5392 }
5393 }
5394 Ok(())
5395 }
5396
5397 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
5398 if !self.platform_window.is_subpixel_rendering_supported() {
5401 return false;
5402 }
5403
5404 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
5405 return false;
5406 }
5407
5408 let mode = match self.text_rendering_mode.get() {
5409 TextRenderingMode::PlatformDefault => self
5410 .text_system()
5411 .recommended_rendering_mode(font_id, font_size),
5412 mode => mode,
5413 };
5414
5415 mode == TextRenderingMode::Subpixel
5416 }
5417
5418 pub fn paint_emoji(
5427 &mut self,
5428 origin: Point<Pixels>,
5429 font_id: FontId,
5430 glyph_id: GlyphId,
5431 font_size: Pixels,
5432 ) -> Result<()> {
5433 self.invalidator.debug_assert_paint();
5434
5435 let scale_factor = self.scale_factor();
5436 let glyph_origin = origin.scale(scale_factor);
5437 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
5438 let params = RenderGlyphParams {
5439 font_id,
5440 glyph_id,
5441 font_size,
5442 subpixel_variant: Default::default(),
5443 scale_factor,
5444 is_emoji: true,
5445 subpixel_rendering: false,
5446 dilation: 0,
5447 };
5448
5449 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
5450 if !raster_bounds.is_zero() {
5451 let tile = self
5452 .sprite_atlas
5453 .get_or_insert_with(params.clone().into(), &mut || {
5454 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
5455 Ok(Some((size, Cow::Owned(bytes))))
5456 })?
5457 .expect("Callback above only errors or returns Some");
5458
5459 let bounds = Bounds {
5460 origin: integer_origin + raster_bounds.origin.map(Into::into),
5461 size: tile.bounds.size.map(Into::into),
5462 };
5463 let content_mask = self.snapped_content_mask();
5464 let opacity = self.element_opacity();
5465
5466 self.next_frame.scene.insert_primitive(PolychromeSprite {
5467 order: 0,
5468 pad: 0,
5469 grayscale: false.into(),
5470 bounds,
5471 corner_radii: Default::default(),
5472 content_mask,
5473 tile,
5474 opacity,
5475 });
5476 }
5477 Ok(())
5478 }
5479
5480 pub fn paint_svg(
5484 &mut self,
5485 bounds: Bounds<Pixels>,
5486 path: SharedString,
5487 data: Option<&[u8]>,
5488 transformation: TransformationMatrix,
5489 color: Hsla,
5490 cx: &App,
5491 ) -> Result<()> {
5492 self.paint_animated_svg(bounds, path, data, transformation, None, color, cx)
5493 }
5494
5495 pub(crate) fn paint_animated_svg(
5498 &mut self,
5499 bounds: Bounds<Pixels>,
5500 path: SharedString,
5501 data: Option<&[u8]>,
5502 transformation: TransformationMatrix,
5503 animation: Option<SpriteAnimation>,
5504 color: Hsla,
5505 cx: &App,
5506 ) -> Result<()> {
5507 self.invalidator.debug_assert_paint();
5508
5509 let element_opacity = self.element_opacity();
5510 let bounds = self.snap_bounds(bounds);
5511
5512 let params = RenderSvgParams {
5513 path,
5514 size: bounds.size.map(|pixels| {
5515 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
5516 }),
5517 };
5518
5519 let Some(tile) =
5520 self.sprite_atlas
5521 .get_or_insert_with(params.clone().into(), &mut || {
5522 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
5523 else {
5524 return Ok(None);
5525 };
5526 Ok(Some((size, Cow::Owned(bytes))))
5527 })?
5528 else {
5529 return Ok(());
5530 };
5531 let content_mask = self.snapped_content_mask();
5532 let svg_bounds = Bounds {
5533 origin: bounds.center()
5534 - Point::new(
5535 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5536 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5537 ),
5538 size: tile
5539 .bounds
5540 .size
5541 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
5542 };
5543 let final_bounds = svg_bounds
5544 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
5545 .map_size(|size| size.ceil());
5546
5547 let sprite = MonochromeSprite {
5548 order: 0,
5549 animation: SpriteAnimationId::NONE,
5550 bounds: final_bounds,
5551 content_mask,
5552 color: color.opacity(element_opacity),
5553 tile,
5554 transformation,
5555 };
5556 match animation {
5557 Some(animation) => self
5558 .next_frame
5559 .scene
5560 .insert_animated_sprite(sprite, animation),
5561 None => self.next_frame.scene.insert_primitive(sprite),
5562 }
5563
5564 Ok(())
5565 }
5566
5567 pub fn paint_image(
5576 &mut self,
5577 bounds: Bounds<Pixels>,
5578 image_bounds: Bounds<Pixels>,
5579 corner_radii: Corners<Pixels>,
5580 data: Arc<RenderImage>,
5581 frame_index: usize,
5582 grayscale: bool,
5583 ) -> Result<()> {
5584 self.invalidator.debug_assert_paint();
5585
5586 let visible_bounds = bounds.intersect(&image_bounds);
5587 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
5588 return Ok(());
5589 }
5590 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
5591 return Ok(());
5592 }
5593
5594 let params = RenderImageParams {
5595 image_id: data.id,
5596 frame_index,
5597 };
5598
5599 let tile = self
5600 .sprite_atlas
5601 .get_or_insert_with(params.into(), &mut || {
5602 Ok(Some((
5603 data.size(frame_index),
5604 Cow::Borrowed(
5605 data.as_bytes(frame_index)
5606 .expect("It's the caller's job to pass a valid frame index"),
5607 ),
5608 )))
5609 })?
5610 .expect("Callback above only returns Some");
5611
5612 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
5613
5614 let sub_tile = if visible_bounds == image_bounds {
5615 tile
5616 } else {
5617 let x_offset_ratio =
5618 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
5619 let y_offset_ratio =
5620 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
5621 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
5622 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
5623
5624 let tile_origin_x = tile.bounds.origin.x.0;
5625 let tile_origin_y = tile.bounds.origin.y.0;
5626 let tile_width = tile.bounds.size.width.0;
5627 let tile_height = tile.bounds.size.height.0;
5628
5629 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
5630 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
5631 let sub_width = (width_ratio * tile_width as f32).round() as i32;
5632 let sub_height = (height_ratio * tile_height as f32).round() as i32;
5633
5634 let max_x = tile_origin_x + tile_width;
5635 let max_y = tile_origin_y + tile_height;
5636
5637 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
5638 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
5639 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
5640 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
5641
5642 AtlasTile {
5643 bounds: Bounds {
5644 origin: point(
5645 DevicePixels(clamped_origin_x),
5646 DevicePixels(clamped_origin_y),
5647 ),
5648 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
5649 },
5650 ..tile
5651 }
5652 };
5653
5654 let content_mask = self.snapped_content_mask();
5655 let corner_radii = corner_radii
5656 .clamp_radii_for_quad_size(visible_bounds.size)
5657 .scale(self.scale_factor());
5658 let opacity = self.element_opacity();
5659
5660 self.next_frame.scene.insert_primitive(PolychromeSprite {
5661 order: 0,
5662 pad: 0,
5663 grayscale: grayscale.into(),
5664 bounds: visible_bounds_snapped,
5665 content_mask,
5666 corner_radii,
5667 tile: sub_tile,
5668 opacity,
5669 });
5670 Ok(())
5671 }
5672
5673 #[cfg(any(target_os = "macos", target_os = "ios"))]
5677 pub fn paint_surface(
5678 &mut self,
5679 bounds: Bounds<Pixels>,
5680 image_buffer: CFRetained<CVPixelBuffer>,
5681 ) {
5682 use crate::PaintSurface;
5683
5684 self.invalidator.debug_assert_paint();
5685
5686 let bounds = self.snap_bounds(bounds);
5687 let content_mask = self.snapped_content_mask();
5688 self.next_frame.scene.insert_primitive(PaintSurface {
5689 order: 0,
5690 bounds,
5691 content_mask,
5692 image_buffer,
5693 });
5694 }
5695
5696 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
5698 for frame_index in 0..data.frame_count() {
5699 let params = RenderImageParams {
5700 image_id: data.id,
5701 frame_index,
5702 };
5703
5704 self.sprite_atlas.remove(¶ms.into());
5705 }
5706
5707 Ok(())
5708 }
5709
5710 #[cfg(any(test, feature = "test-support"))]
5712 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
5713 data.frame_count() > 0
5714 && (0..data.frame_count()).all(|frame_index| {
5715 self.sprite_atlas.contains(
5716 &RenderImageParams {
5717 image_id: data.id,
5718 frame_index,
5719 }
5720 .into(),
5721 )
5722 })
5723 }
5724
5725 #[must_use]
5731 pub fn request_layout(
5732 &mut self,
5733 style: Style,
5734 children: impl IntoIterator<Item = LayoutId>,
5735 cx: &mut App,
5736 ) -> LayoutId {
5737 self.invalidator.debug_assert_prepaint();
5738
5739 cx.layout_id_buffer.clear();
5740 cx.layout_id_buffer.extend(children);
5741 let rem_size = self.rem_size();
5742 let scale_factor = self.scale_factor();
5743
5744 let scope = self.element_id_stack.hash();
5745 self.layout_engine.as_mut().unwrap().request_layout(
5746 scope,
5747 &style,
5748 rem_size,
5749 scale_factor,
5750 &cx.layout_id_buffer,
5751 )
5752 }
5753
5754 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
5764 where
5765 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
5766 + 'static,
5767 {
5768 self.request_keyed_measure(
5769 &style,
5770 (),
5771 |_, _| false,
5772 move |_, known_dimensions, available_space, _, window, cx| {
5773 measure(known_dimensions, available_space, window, cx)
5774 },
5775 )
5776 }
5777
5778 pub fn request_keyed_measured_layout<K, F>(
5788 &mut self,
5789 style: Style,
5790 key: K,
5791 measure: F,
5792 ) -> LayoutId
5793 where
5794 K: PartialEq + 'static,
5795 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
5796 + 'static,
5797 {
5798 self.request_keyed_measure(
5799 &style,
5800 key,
5801 |key, previous| key == previous,
5802 move |_, known_dimensions, available_space, _, window, cx| {
5803 measure(known_dimensions, available_space, window, cx)
5804 },
5805 )
5806 }
5807
5808 pub(crate) fn request_keyed_measure<K, F>(
5812 &mut self,
5813 style: &Style,
5814 key: K,
5815 reuse: fn(&mut K, &mut K) -> bool,
5816 measure: F,
5817 ) -> LayoutId
5818 where
5819 K: 'static,
5820 F: FnMut(
5821 &K,
5822 Size<Option<Pixels>>,
5823 Size<AvailableSpace>,
5824 bool,
5825 &mut Window,
5826 &mut App,
5827 ) -> Size<Pixels>
5828 + 'static,
5829 {
5830 self.invalidator.debug_assert_prepaint();
5831
5832 let rem_size = self.rem_size();
5833 let scale_factor = self.scale_factor();
5834 let scope = self.element_id_stack.hash();
5835 self.layout_engine.as_mut().unwrap().request_keyed_measure(
5836 scope,
5837 style,
5838 rem_size,
5839 scale_factor,
5840 key,
5841 reuse,
5842 measure,
5843 )
5844 }
5845
5846 #[cfg(test)]
5849 pub(crate) fn clear_layout_cache(&mut self) {
5850 self.layout_engine.as_mut().unwrap().clear_layout_cache();
5851 }
5852
5853 #[cfg(test)]
5854 pub(crate) fn layout_node_count(&self) -> usize {
5855 self.layout_engine.as_ref().unwrap().node_count()
5856 }
5857
5858 pub fn compute_layout(
5864 &mut self,
5865 layout_id: LayoutId,
5866 available_space: Size<AvailableSpace>,
5867 cx: &mut App,
5868 ) {
5869 self.invalidator.debug_assert_prepaint();
5870
5871 let mut layout_engine = self.layout_engine.take().unwrap();
5872 layout_engine.compute_layout(layout_id, available_space, self, cx);
5873 self.layout_engine = Some(layout_engine);
5874 }
5875
5876 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
5881 self.invalidator.debug_assert_prepaint();
5882
5883 let scale_factor = self.scale_factor();
5884 let mut bounds = self
5885 .layout_engine
5886 .as_mut()
5887 .unwrap()
5888 .layout_bounds(layout_id, scale_factor)
5889 .map(Into::into);
5890 let snapped_offset = self.pixel_snap_point(self.element_offset());
5891 bounds.origin += snapped_offset;
5892 bounds
5893 }
5894
5895 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
5901 self.invalidator.debug_assert_prepaint();
5902
5903 let content_mask = self.content_mask();
5904 let id = self.next_hitbox_id;
5905 self.next_hitbox_id = self.next_hitbox_id.next();
5906 let hitbox = Hitbox {
5907 id,
5908 bounds,
5909 content_mask,
5910 behavior,
5911 };
5912 self.next_frame.hitboxes.push(hitbox.clone());
5913 hitbox
5914 }
5915
5916 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
5920 self.invalidator.debug_assert_paint();
5921 self.next_frame.window_control_hitboxes.push((area, hitbox));
5922 }
5923
5924 pub fn set_key_context(&mut self, context: KeyContext) {
5929 self.invalidator.debug_assert_paint();
5930 self.next_frame.dispatch_tree.set_key_context(context);
5931 }
5932
5933 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
5938 self.invalidator.debug_assert_prepaint();
5939 if focus_handle.is_focused(self) {
5940 self.next_frame.focus = Some(focus_handle.id);
5941 }
5942 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
5943 }
5944
5945 pub fn set_view_id(&mut self, view_id: EntityId) {
5951 self.invalidator.debug_assert_prepaint();
5952 self.next_frame.dispatch_tree.set_view_id(view_id);
5953 }
5954
5955 pub fn current_view(&self) -> EntityId {
5957 self.invalidator.debug_assert_paint_or_prepaint();
5958 self.rendered_entity_stack.last().copied().unwrap()
5959 }
5960
5961 #[inline]
5962 pub(crate) fn with_rendered_view<R>(
5963 &mut self,
5964 id: EntityId,
5965 f: impl FnOnce(&mut Self) -> R,
5966 ) -> R {
5967 self.rendered_entity_stack.push(id);
5968 let result = f(self);
5969 self.rendered_entity_stack.pop();
5970 result
5971 }
5972
5973 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
5975 where
5976 F: FnOnce(&mut Self) -> R,
5977 {
5978 if let Some(image_cache) = image_cache {
5979 self.image_cache_stack.push(image_cache);
5980 let result = f(self);
5981 self.image_cache_stack.pop();
5982 result
5983 } else {
5984 f(self)
5985 }
5986 }
5987
5988 pub fn handle_input(
5997 &mut self,
5998 focus_handle: &FocusHandle,
5999 input_handler: impl InputHandler,
6000 cx: &App,
6001 ) {
6002 self.invalidator.debug_assert_paint();
6003
6004 if focus_handle.is_focused(self) {
6005 let cx = self.to_async(cx);
6006 self.next_frame.input_handlers.push(Some(
6007 PlatformInputHandler::new(cx, Box::new(input_handler)).with_focus(focus_handle.id),
6008 ));
6009 }
6010 }
6011
6012 pub fn notify_text_input_changed(&self, focus_handle: &FocusHandle) {
6017 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
6018 self.platform_window
6019 .text_input_state_changed(TextInputStateChange::ContentChanged);
6020 }
6021 }
6022
6023 pub fn notify_text_selection_changed(&self, focus_handle: &FocusHandle) {
6028 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
6029 self.platform_window
6030 .text_input_state_changed(TextInputStateChange::SelectionChanged);
6031 }
6032 }
6033
6034 fn apply_text_input_configuration(&mut self, cx: &mut App) {
6039 let configuration = match self.platform_window.take_input_handler() {
6040 Some(mut input_handler) => {
6041 let configuration = input_handler.text_input_configuration(self, cx);
6042 self.platform_window.set_input_handler(input_handler);
6043 configuration
6044 }
6045 None => TextInputConfiguration::default(),
6046 };
6047 if self.last_text_input_configuration.as_ref() != Some(&configuration) {
6048 self.platform_window
6049 .set_text_input_configuration(configuration.clone());
6050 self.last_text_input_configuration = Some(configuration);
6051 }
6052 }
6053
6054 pub fn on_mouse_event<Event: MouseEvent>(
6060 &mut self,
6061 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
6062 ) {
6063 self.invalidator.debug_assert_paint();
6064
6065 self.next_frame.mouse_listeners.push(Some(Box::new(
6066 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
6067 if let Some(event) = event.downcast_ref() {
6068 listener(event, phase, window, cx)
6069 }
6070 },
6071 )));
6072 }
6073
6074 pub fn on_key_event<Event: KeyEvent>(
6083 &mut self,
6084 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
6085 ) {
6086 self.invalidator.debug_assert_paint();
6087
6088 self.next_frame.dispatch_tree.on_key_event(Rc::new(
6089 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
6090 if let Some(event) = event.downcast_ref::<Event>() {
6091 listener(event, phase, window, cx)
6092 }
6093 },
6094 ));
6095 }
6096
6097 pub fn on_modifiers_changed(
6104 &mut self,
6105 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
6106 ) {
6107 self.invalidator.debug_assert_paint();
6108
6109 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
6110 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
6111 listener(event, window, cx)
6112 },
6113 ));
6114 }
6115
6116 pub fn on_focus_in(
6120 &mut self,
6121 handle: &FocusHandle,
6122 cx: &mut App,
6123 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
6124 ) -> Subscription {
6125 let focus_id = handle.id;
6126 let (subscription, activate) =
6127 self.new_focus_listener(Box::new(move |event, window, cx| {
6128 if event.is_focus_in(focus_id) {
6129 listener(window, cx);
6130 }
6131 true
6132 }));
6133 cx.defer(move |_| activate());
6134 subscription
6135 }
6136
6137 pub fn on_focus_out(
6140 &mut self,
6141 handle: &FocusHandle,
6142 cx: &mut App,
6143 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
6144 ) -> Subscription {
6145 let focus_id = handle.id;
6146 let (subscription, activate) =
6147 self.new_focus_listener(Box::new(move |event, window, cx| {
6148 if let Some(blurred_id) = event.previous_focus_path.last().copied()
6149 && event.is_focus_out(focus_id)
6150 {
6151 let event = FocusOutEvent {
6152 blurred: WeakFocusHandle {
6153 id: blurred_id,
6154 handles: Arc::downgrade(&cx.focus_handles),
6155 },
6156 };
6157 listener(event, window, cx)
6158 }
6159 true
6160 }));
6161 cx.defer(move |_| activate());
6162 subscription
6163 }
6164
6165 fn reset_cursor_style(&self, cx: &mut App) {
6166 if self.is_window_hovered() {
6168 let style = cx
6170 .active_drag_cursor_style()
6171 .or_else(|| self.rendered_frame.cursor_style(self))
6172 .unwrap_or(CursorStyle::Arrow);
6173 cx.platform.set_cursor_style(style);
6174 }
6175 }
6176
6177 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
6180 let keystroke = keystroke.with_simulated_ime();
6181 let result = self.dispatch_event(
6182 PlatformInput::KeyDown(KeyDownEvent {
6183 keystroke: keystroke.clone(),
6184 is_held: false,
6185 prefer_character_input: false,
6186 }),
6187 cx,
6188 );
6189 if !result.propagate {
6190 return true;
6191 }
6192
6193 if let Some(input) = keystroke.key_char
6194 && let Some(mut input_handler) = self.platform_window.take_input_handler()
6195 {
6196 input_handler.dispatch_input(&input, self, cx);
6197 self.platform_window.set_input_handler(input_handler);
6198 return true;
6199 }
6200
6201 false
6202 }
6203
6204 pub fn keystroke_text_for(&self, action: &dyn Action, cx: &App) -> String {
6207 self.highest_precedence_binding_for_action(action)
6208 .map(|binding| {
6209 binding
6210 .keystrokes()
6211 .iter()
6212 .map(|keystroke| keystroke.display(cx.platform_info().os).to_string())
6213 .collect::<Vec<_>>()
6214 .join(" ")
6215 })
6216 .unwrap_or_else(|| action.name().to_string())
6217 }
6218
6219 #[profiling::function]
6221 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
6222 #[cfg(feature = "profiler")]
6223 self.window_profiler.begin_input(event.kind_name());
6224 let update_count_before = self.invalidator.update_count();
6225 let old_modality = self.last_input_modality;
6229 self.last_input_modality = match &event {
6230 PlatformInput::KeyDown(_) => InputModality::Keyboard,
6231 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
6232 PlatformInput::Touch(_) => InputModality::Touch,
6233 _ => self.last_input_modality,
6234 };
6235 if self.last_input_modality != old_modality {
6236 self.refresh();
6237 }
6238
6239 cx.propagate_event = true;
6241 self.default_prevented = false;
6243
6244 let event = match event {
6245 PlatformInput::MouseMove(mouse_move) => {
6248 self.mouse_position = mouse_move.position;
6249 self.modifiers = mouse_move.modifiers;
6250 PlatformInput::MouseMove(mouse_move)
6251 }
6252 PlatformInput::MouseDown(mouse_down) => {
6253 self.mouse_position = mouse_down.position;
6254 self.modifiers = mouse_down.modifiers;
6255 PlatformInput::MouseDown(mouse_down)
6256 }
6257 PlatformInput::MouseUp(mouse_up) => {
6258 self.mouse_position = mouse_up.position;
6259 self.modifiers = mouse_up.modifiers;
6260 PlatformInput::MouseUp(mouse_up)
6261 }
6262 PlatformInput::MousePressure(mouse_pressure) => {
6263 PlatformInput::MousePressure(mouse_pressure)
6264 }
6265 PlatformInput::MouseExited(mouse_exited) => {
6266 self.modifiers = mouse_exited.modifiers;
6267 PlatformInput::MouseExited(mouse_exited)
6268 }
6269 PlatformInput::ModifiersChanged(modifiers_changed) => {
6270 self.modifiers = modifiers_changed.modifiers;
6271 self.capslock = modifiers_changed.capslock;
6272 PlatformInput::ModifiersChanged(modifiers_changed)
6273 }
6274 PlatformInput::Scroll(scroll_wheel) => {
6275 self.mouse_position = scroll_wheel.position;
6276 self.modifiers = scroll_wheel.modifiers;
6277 PlatformInput::Scroll(scroll_wheel)
6278 }
6279 PlatformInput::Pinch(pinch) => {
6280 self.mouse_position = pinch.position;
6281 self.modifiers = pinch.modifiers;
6282 PlatformInput::Pinch(pinch)
6283 }
6284 PlatformInput::FileDrop(file_drop) => match file_drop {
6287 FileDropEvent::Entered { position, paths } => {
6288 self.mouse_position = position;
6289 let source_window = self.handle.window_id();
6290 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
6291 cx.active_drag = Some(AnyDrag {
6292 value: Arc::new(paths.clone()),
6293 view: cx.new(|_| paths).into(),
6294 cursor_offset: position,
6295 cursor_style: None,
6296 external_payload_source: None,
6297 });
6298 }
6299 PlatformInput::MouseMove(MouseMoveEvent {
6300 position,
6301 pressed_button: Some(MouseButton::Left),
6302 modifiers: Modifiers::default(),
6303 })
6304 }
6305 FileDropEvent::Pending { position } => {
6306 self.mouse_position = position;
6307 PlatformInput::MouseMove(MouseMoveEvent {
6308 position,
6309 pressed_button: Some(MouseButton::Left),
6310 modifiers: Modifiers::default(),
6311 })
6312 }
6313 FileDropEvent::Submit { position } => {
6314 cx.activate(true);
6315 self.mouse_position = position;
6316 PlatformInput::MouseUp(MouseUpEvent {
6317 button: MouseButton::Left,
6318 position,
6319 modifiers: Modifiers::default(),
6320 click_count: 1,
6321 })
6322 }
6323 FileDropEvent::Exited => {
6324 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
6325 cx.active_drag.take();
6326 }
6327 self.refresh();
6328 PlatformInput::FileDrop(FileDropEvent::Exited)
6329 }
6330 FileDropEvent::Ended => {
6331 cx.end_platform_drag(self.handle.window_id());
6332 self.refresh();
6333 PlatformInput::FileDrop(FileDropEvent::Ended)
6334 }
6335 },
6336 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
6337 PlatformInput::LongPress(long_press) => {
6338 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
6339 long_press.start_position
6340 } else {
6341 long_press.position
6342 };
6343 if long_press.phase == crate::TouchPhase::Started {
6344 self.long_press_capture = None;
6345 }
6346 PlatformInput::LongPress(long_press)
6347 }
6348 PlatformInput::TouchDrag(touch_drag) => {
6349 self.mouse_position = touch_drag.start_position;
6350 PlatformInput::TouchDrag(touch_drag)
6351 }
6352 PlatformInput::BackGesture(back) => {
6353 self.mouse_position = back.start_position;
6354 PlatformInput::BackGesture(back)
6355 }
6356 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
6357 };
6358
6359 if let Some(any_mouse_event) = event.mouse_event() {
6360 self.dispatch_mouse_event(any_mouse_event, cx);
6361 } else if let Some(any_key_event) = event.keyboard_event() {
6362 self.dispatch_key_event(any_key_event, cx);
6363 } else if let Some(touch_event) = event.touch_event() {
6364 self.dispatch_touch_event(touch_event, cx);
6365 }
6366 if let PlatformInput::LongPress(long_press) = &event {
6367 match long_press.phase {
6368 crate::TouchPhase::Started if !self.default_prevented => {
6369 self.long_press_capture = None;
6370 }
6371 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
6372 self.long_press_capture = None;
6373 }
6374 crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
6375 }
6376 }
6377
6378 self.promote_external_drag_to_platform(&event, cx);
6381
6382 let caused_invalidation = self.invalidator.update_count() > update_count_before;
6383 if caused_invalidation {
6384 self.input_rate_tracker.borrow_mut().record_input();
6385 }
6386 #[cfg(feature = "profiler")]
6387 self.window_profiler.end_input(caused_invalidation);
6388
6389 DispatchEventResult {
6390 propagate: cx.propagate_event,
6391 default_prevented: self.default_prevented,
6392 }
6393 }
6394
6395 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
6396 let PlatformInput::MouseMove(mouse_move) = event else {
6397 return;
6398 };
6399 if mouse_move.pressed_button != Some(MouseButton::Left) {
6400 return;
6401 }
6402 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
6403 return;
6404 }
6405 if !self.platform_window.can_start_external_drag() {
6406 return;
6407 }
6408 let Some(payload_source) = cx
6409 .active_drag
6410 .as_mut()
6411 .and_then(|drag| drag.external_payload_source.take())
6412 else {
6413 return;
6414 };
6415 let Some(payload) = payload_source(self, cx) else {
6416 return;
6417 };
6418 if self.platform_window.start_external_drag(&payload)
6419 && cx.hand_active_drag_to_platform(self.handle.window_id())
6420 {
6421 self.refresh();
6422 }
6423 }
6424
6425 pub fn touch_prediction_enabled(&self) -> bool {
6429 self.touch_prediction_enabled
6430 }
6431
6432 pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
6436 self.touch_prediction_enabled = enabled;
6437 }
6438
6439 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
6443 let mut event = event.clone();
6444 if !self.touch_prediction_enabled {
6445 event.predicted_position = None;
6446 }
6447 let recognized_gestures = self.touch_gestures.handle_event(&event);
6448 if event.phase == crate::TouchPhase::Started
6449 && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
6450 {
6451 self.dispatch_recognized_touch_gesture(touch_drag, cx);
6452 }
6453 if event.phase == crate::TouchPhase::Started
6454 && self.touch_gestures.pending_long_press().is_some()
6455 {
6456 self.long_press_capture = None;
6457 }
6458 let mut tapped = false;
6459 for gesture in recognized_gestures {
6460 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
6461 self.dispatch_recognized_touch_gesture(gesture, cx);
6462 }
6463 if event.phase == crate::TouchPhase::Started {
6464 self.schedule_long_press_timer(cx);
6465 } else if self.touch_gestures.pending_long_press().is_none() {
6466 self.long_press_timer.take();
6467 }
6468 if tapped && self.invalidator.is_dirty() {
6474 self.draw(cx).clear(cx);
6475 }
6476 if self.touch_gestures.has_momentum() {
6477 self.schedule_touch_momentum_tick();
6478 }
6479 }
6480
6481 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
6482 match gesture {
6483 RecognizedTouchGesture::Scroll(scroll_wheel) => {
6484 self.mouse_position = scroll_wheel.position;
6485 cx.propagate_event = true;
6486 self.dispatch_mouse_event(&scroll_wheel, cx);
6487 }
6488 RecognizedTouchGesture::Tap { down, up } => {
6489 self.mouse_position = up.position;
6490 cx.propagate_event = true;
6491 self.dispatch_mouse_event(&down, cx);
6492 cx.propagate_event = true;
6493 self.dispatch_mouse_event(&up, cx);
6494 }
6495 RecognizedTouchGesture::TouchDrag(touch_drag) => {
6496 self.mouse_position = touch_drag.start_position;
6497 cx.propagate_event = true;
6498 self.default_prevented = false;
6499 let started = touch_drag.phase == crate::TouchPhase::Started;
6500 self.dispatch_mouse_event(&touch_drag, cx);
6501 if started {
6502 self.touch_gestures
6503 .resolve_touch_drag(self.default_prevented);
6504 }
6505 }
6506 RecognizedTouchGesture::LongPress(long_press) => {
6507 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
6508 long_press.start_position
6509 } else {
6510 long_press.position
6511 };
6512 cx.propagate_event = true;
6513 self.default_prevented = false;
6514 let started = long_press.phase == crate::TouchPhase::Started;
6515 let ended = matches!(
6516 long_press.phase,
6517 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
6518 );
6519 self.dispatch_mouse_event(&long_press, cx);
6520 if started {
6521 let claimed = self.default_prevented;
6522 self.touch_gestures.resolve_long_press(claimed);
6523 if !claimed {
6524 self.long_press_capture = None;
6525 }
6526 }
6527 if ended {
6528 self.long_press_capture = None;
6529 }
6530 }
6531 }
6532 }
6533
6534 fn schedule_long_press_timer(&mut self, cx: &mut App) {
6535 self.long_press_timer.take();
6536 let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
6537 return;
6538 };
6539 self.long_press_timer = Some(self.spawn(cx, async move |cx| {
6540 cx.background_executor.timer(duration).await;
6541 cx.update(move |window, cx| {
6542 window.long_press_timer.take();
6543 if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
6544 window.dispatch_recognized_touch_gesture(gesture, cx);
6545 }
6546 })
6547 .with_context(|| {
6548 format!(
6549 "handling long-press timer for window {:?}",
6550 cx.window_handle().window_id()
6551 )
6552 })
6553 .log_err();
6554 }));
6555 }
6556
6557 fn schedule_touch_momentum_tick(&mut self) {
6558 self.on_next_frame(|window, cx| {
6559 if let Some(gesture) = window.touch_gestures.tick_momentum() {
6560 window.dispatch_recognized_touch_gesture(gesture, cx);
6561 }
6562 if window.touch_gestures.has_momentum() {
6563 window.schedule_touch_momentum_tick();
6564 }
6565 });
6566 }
6567
6568 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6569 self.mouse_hit_test = self.rendered_frame.hit_test(self.mouse_position());
6570
6571 #[cfg(any(feature = "inspector", debug_assertions))]
6572 if self.is_inspector_picking(cx) {
6573 self.reset_cursor_style(cx);
6574 self.handle_inspector_mouse_event(event, cx);
6575 return;
6577 }
6578
6579 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
6580
6581 for listener in &mut mouse_listeners {
6584 let listener = listener.as_mut().unwrap();
6585 listener(event, DispatchPhase::Capture, self, cx);
6586 if !cx.propagate_event {
6587 break;
6588 }
6589 }
6590
6591 if cx.propagate_event {
6593 for listener in mouse_listeners.iter_mut().rev() {
6594 let listener = listener.as_mut().unwrap();
6595 listener(event, DispatchPhase::Bubble, self, cx);
6596 if !cx.propagate_event {
6597 break;
6598 }
6599 }
6600 }
6601
6602 self.rendered_frame.mouse_listeners = mouse_listeners;
6603
6604 if cx.has_active_drag() {
6605 if event.is::<MouseMoveEvent>() {
6606 self.refresh();
6609 } else if event.is::<MouseUpEvent>() {
6610 cx.active_drag = None;
6613 self.refresh();
6614 }
6615 }
6616
6617 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
6619 self.captured_hitbox = None;
6620 }
6621
6622 self.reset_cursor_style(cx);
6625 }
6626
6627 fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
6630 let prefer_character_input = event
6631 .downcast_ref::<KeyDownEvent>()
6632 .is_some_and(|key_down_event| key_down_event.prefer_character_input);
6633 if !prefer_character_input {
6634 return InputPreference::KeyBindings;
6635 }
6636 let Some(mut input_handler) = self.platform_window.take_input_handler() else {
6637 return InputPreference::KeyBindings;
6638 };
6639 let accepts_text_input = input_handler.accepts_text_input(self, cx);
6640 self.platform_window.set_input_handler(input_handler);
6641 if accepts_text_input {
6642 InputPreference::CharacterInput
6643 } else {
6644 InputPreference::KeyBindings
6645 }
6646 }
6647
6648 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
6649 if self.invalidator.is_dirty() {
6650 self.draw(cx).clear(cx);
6651 }
6652
6653 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6654 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6655
6656 let mut keystroke: Option<Keystroke> = None;
6657
6658 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
6659 if event.modifiers.number_of_modifiers() == 0
6660 && self.pending_modifier.modifiers.number_of_modifiers() == 1
6661 && !self.pending_modifier.saw_other_input
6662 {
6663 let key = match self.pending_modifier.modifiers {
6664 modifiers if modifiers.shift => Some("shift"),
6665 modifiers if modifiers.control => Some("control"),
6666 modifiers if modifiers.alt => Some("alt"),
6667 modifiers if modifiers.platform => Some("platform"),
6668 modifiers if modifiers.function => Some("function"),
6669 _ => None,
6670 };
6671 if let Some(key) = key {
6672 keystroke = Some(Keystroke {
6673 key: key.to_string(),
6674 key_char: None,
6675 modifiers: Modifiers::default(),
6676 });
6677 }
6678 }
6679
6680 if self.pending_modifier.modifiers.number_of_modifiers() == 0
6681 && event.modifiers.number_of_modifiers() == 1
6682 {
6683 self.pending_modifier.saw_other_input = false
6684 } else if event.modifiers.number_of_modifiers() > 1 {
6685 self.pending_modifier.saw_other_input = true
6686 }
6687 self.pending_modifier.modifiers = event.modifiers
6688 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
6689 self.pending_modifier.saw_other_input = true;
6690 keystroke = Some(key_down_event.keystroke.clone());
6691 if key_down_event.keystroke.key_char.is_some()
6692 && matches!(
6693 cx.cursor_hide_mode,
6694 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
6695 )
6696 {
6697 cx.platform.hide_cursor_until_mouse_moves();
6698 }
6699 }
6700
6701 let Some(keystroke) = keystroke else {
6702 self.finish_dispatch_key_event(
6703 event,
6704 None,
6705 InputPreference::KeyBindings,
6706 dispatch_path,
6707 self.context_stack(),
6708 cx,
6709 );
6710 return;
6711 };
6712
6713 let input_preference = self.input_preference(event, cx);
6714
6715 cx.propagate_event = true;
6716 self.dispatch_keystroke_interceptors(
6717 &keystroke,
6718 input_preference,
6719 self.context_stack(),
6720 cx,
6721 );
6722 if !cx.propagate_event {
6723 self.finish_dispatch_key_event(
6724 event,
6725 Some(&keystroke),
6726 input_preference,
6727 dispatch_path,
6728 self.context_stack(),
6729 cx,
6730 );
6731 return;
6732 }
6733
6734 let mut currently_pending = self.pending_input.take().unwrap_or_default();
6735 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
6736 currently_pending = PendingInput::default();
6737 }
6738
6739 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
6740 currently_pending.keystrokes,
6741 keystroke.clone(),
6742 &dispatch_path,
6743 );
6744
6745 if !match_result.to_replay.is_empty() {
6746 self.replay_pending_input(match_result.to_replay, cx);
6747 cx.propagate_event = true;
6748 }
6749
6750 if !match_result.pending.is_empty() {
6751 let previous_timeout = currently_pending.timeout.take();
6752 currently_pending.keystrokes = match_result.pending;
6753 currently_pending.focus = self.focus;
6754
6755 let text_input_requires_timeout = event
6756 .downcast_ref::<KeyDownEvent>()
6757 .filter(|key_down| key_down.keystroke.key_char.is_some())
6758 .and_then(|_| self.platform_window.take_input_handler())
6759 .map_or(false, |mut input_handler| {
6760 let accepts = input_handler.accepts_text_input(self, cx);
6761 self.platform_window.set_input_handler(input_handler);
6762 accepts
6763 });
6764
6765 let standalone_modifier = matches!(currently_pending.keystrokes.as_slice(), [keystroke] if keystroke.is_modifier_key());
6766 let needs_timeout = previous_timeout.is_some()
6767 || match_result.pending_has_binding
6768 || text_input_requires_timeout
6769 || standalone_modifier;
6770 currently_pending.timeout = if needs_timeout {
6771 match previous_timeout {
6772 Some(mut timeout) if timeout.is_paused() => {
6773 timeout.reset_duration(PENDING_INPUT_TIMEOUT);
6774 Some(timeout)
6775 }
6776 previous_timeout => {
6777 drop(previous_timeout);
6778 Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
6779 }
6780 }
6781 } else {
6782 None
6783 };
6784 self.pending_input = Some(currently_pending);
6785 self.pending_input_changed(cx);
6786 cx.propagate_event = false;
6787 return;
6788 }
6789
6790 let input_preference = self.input_preference(event, cx);
6792 if input_preference == InputPreference::KeyBindings {
6793 for binding in match_result.bindings {
6794 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6795 if !cx.propagate_event {
6796 self.dispatch_keystroke_observers(
6797 &keystroke,
6798 input_preference,
6799 Some(binding.action.as_ref()),
6800 match_result.context_stack,
6801 cx,
6802 );
6803 self.pending_input_changed(cx);
6804 return;
6805 }
6806 }
6807 }
6808
6809 self.finish_dispatch_key_event(
6810 event,
6811 Some(&keystroke),
6812 input_preference,
6813 dispatch_path,
6814 match_result.context_stack,
6815 cx,
6816 );
6817 self.pending_input_changed(cx);
6818 }
6819
6820 fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
6821 let (started_at, task) = self.start_pending_input_timeout(duration, cx);
6822 PendingInputTimeout {
6823 duration,
6824 remaining: duration,
6825 state: PendingInputTimeoutState::Running { started_at, task },
6826 }
6827 }
6828
6829 fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
6830 let started_at = cx.background_executor().now();
6831 let task = self.spawn(cx, async move |cx| {
6832 cx.background_executor.timer(remaining).await;
6833 cx.update(move |window, cx| window.flush_pending_input(cx))
6834 .with_context(|| {
6835 format!(
6836 "handling pending input timeout for window {:?}",
6837 cx.window_handle().window_id()
6838 )
6839 })
6840 .log_err();
6841 });
6842 (started_at, task)
6843 }
6844
6845 fn flush_pending_input(&mut self, cx: &mut App) {
6848 let Some(currently_pending) = self
6849 .pending_input
6850 .take()
6851 .filter(|pending| pending.focus == self.focus)
6852 else {
6853 return;
6854 };
6855
6856 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6857 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6858
6859 let to_replay = self
6860 .rendered_frame
6861 .dispatch_tree
6862 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
6863
6864 self.pending_input_changed(cx);
6865 self.replay_pending_input(to_replay, cx)
6866 }
6867
6868 fn finish_dispatch_key_event(
6869 &mut self,
6870 event: &dyn Any,
6871 recognized_keystroke: Option<&Keystroke>,
6872 input_preference: InputPreference,
6873 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
6874 context_stack: Vec<KeyContext>,
6875 cx: &mut App,
6876 ) {
6877 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
6878 if !cx.propagate_event {
6879 return;
6880 }
6881
6882 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
6883 if !cx.propagate_event {
6884 return;
6885 }
6886
6887 if let Some(keystroke) = recognized_keystroke {
6888 self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
6889 }
6890 }
6891
6892 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
6893 self.pending_input_observers
6894 .clone()
6895 .retain(|callback| callback(self, cx));
6896 }
6897
6898 fn defer_pending_input_changed(&self, cx: &mut App) {
6899 let window_handle = self.handle;
6902 cx.defer(move |cx| {
6903 window_handle
6904 .update(cx, |_, window, cx| {
6905 window.pending_input_changed(cx);
6906 })
6907 .ok();
6908 });
6909 }
6910
6911 fn dispatch_key_down_up_event(
6912 &mut self,
6913 event: &dyn Any,
6914 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6915 cx: &mut App,
6916 ) {
6917 for node_id in dispatch_path {
6919 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6920
6921 for key_listener in node.key_listeners.clone() {
6922 key_listener(event, DispatchPhase::Capture, self, cx);
6923 if !cx.propagate_event {
6924 return;
6925 }
6926 }
6927 }
6928
6929 for node_id in dispatch_path.iter().rev() {
6931 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6933 for key_listener in node.key_listeners.clone() {
6934 key_listener(event, DispatchPhase::Bubble, self, cx);
6935 if !cx.propagate_event {
6936 return;
6937 }
6938 }
6939 }
6940 }
6941
6942 fn dispatch_modifiers_changed_event(
6943 &mut self,
6944 event: &dyn Any,
6945 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6946 cx: &mut App,
6947 ) {
6948 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
6949 return;
6950 };
6951 for node_id in dispatch_path.iter().rev() {
6952 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6953 for listener in node.modifiers_changed_listeners.clone() {
6954 listener(event, self, cx);
6955 if !cx.propagate_event {
6956 return;
6957 }
6958 }
6959 }
6960 }
6961
6962 pub fn has_pending_keystrokes(&self) -> bool {
6964 self.pending_input().is_some()
6965 }
6966
6967 #[cfg(test)]
6968 pub(crate) fn pending_input_is_none(&self) -> bool {
6969 self.pending_input.is_none()
6970 }
6971
6972 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
6973 if self.pending_input.take().is_some() {
6974 self.defer_pending_input_changed(cx);
6975 }
6976 }
6977
6978 pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
6981 self.pending_input
6982 .as_ref()
6983 .filter(|pending_input| pending_input.focus == self.focus)
6984 .map(|pending_input| PendingInputStatus {
6985 keystrokes: pending_input.keystrokes.as_slice(),
6986 timeout: pending_input
6987 .timeout
6988 .as_ref()
6989 .map(PendingInputTimeout::status),
6990 })
6991 }
6992
6993 pub fn set_pending_input_timeout_paused<T: 'static>(
6998 &mut self,
6999 owner: &Entity<T>,
7000 paused: bool,
7001 cx: &mut App,
7002 ) -> bool {
7003 let owner_id = owner.entity_id();
7004 if !paused {
7005 return self.resume_pending_input_timeout(owner_id, cx);
7006 }
7007
7008 let timeout = self
7009 .pending_input
7010 .as_ref()
7011 .filter(|pending_input| pending_input.focus == self.focus)
7012 .and_then(|pending_input| pending_input.timeout.as_ref());
7013 let Some(timeout) = timeout else {
7014 return false;
7015 };
7016 if timeout.is_paused() {
7017 return false;
7018 }
7019
7020 let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
7021 window.resume_pending_input_timeout(owner_id, cx);
7022 });
7023 let now = cx.background_executor().now();
7024 let changed = self
7025 .pending_input
7026 .as_mut()
7027 .filter(|pending_input| pending_input.focus == self.focus)
7028 .and_then(|pending_input| pending_input.timeout.as_mut())
7029 .is_some_and(|timeout| {
7030 timeout.pause(
7031 PendingInputTimeoutPause {
7032 owner_id,
7033 _release_subscription: release_subscription,
7034 },
7035 now,
7036 )
7037 });
7038
7039 if changed {
7040 self.defer_pending_input_changed(cx);
7041 }
7042 changed
7043 }
7044
7045 fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
7046 let Some(remaining) = self
7047 .pending_input
7048 .as_ref()
7049 .and_then(|pending_input| pending_input.timeout.as_ref())
7050 .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
7051 .map(|timeout| timeout.remaining)
7052 else {
7053 return false;
7054 };
7055
7056 let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
7057 let changed = self
7058 .pending_input
7059 .as_mut()
7060 .and_then(|pending_input| pending_input.timeout.as_mut())
7061 .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
7062
7063 if changed {
7064 self.defer_pending_input_changed(cx);
7065 }
7066 changed
7067 }
7068
7069 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
7071 self.pending_input()
7072 .map(|pending_input| pending_input.keystrokes())
7073 }
7074
7075 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
7076 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
7077 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
7078
7079 'replay: for replay in replays {
7080 let event = KeyDownEvent {
7081 keystroke: replay.keystroke.clone(),
7082 is_held: false,
7083 prefer_character_input: true,
7084 };
7085
7086 cx.propagate_event = true;
7087 for binding in replay.bindings {
7088 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
7089 if !cx.propagate_event {
7090 self.dispatch_keystroke_observers(
7091 &replay.keystroke,
7092 InputPreference::KeyBindings,
7093 Some(binding.action.as_ref()),
7094 Vec::default(),
7095 cx,
7096 );
7097 continue 'replay;
7098 }
7099 }
7100
7101 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
7102 if !cx.propagate_event {
7103 continue 'replay;
7104 }
7105 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
7106 && let Some(mut input_handler) = self.platform_window.take_input_handler()
7107 {
7108 input_handler.dispatch_input(&input, self, cx);
7109 self.platform_window.set_input_handler(input_handler)
7110 }
7111 }
7112 }
7113
7114 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
7115 focus_id
7116 .and_then(|focus_id| {
7117 self.rendered_frame
7118 .dispatch_tree
7119 .focusable_node_id(focus_id)
7120 })
7121 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
7122 }
7123
7124 fn dispatch_action_on_node(
7125 &mut self,
7126 node_id: DispatchNodeId,
7127 action: &dyn Action,
7128 cx: &mut App,
7129 ) {
7130 self.dispatch_action_on_node_inner(node_id, action, cx);
7131
7132 if !cx.propagate_event
7133 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
7134 && self.last_input_was_keyboard()
7135 {
7136 cx.platform.hide_cursor_until_mouse_moves();
7137 }
7138 }
7139
7140 fn dispatch_action_on_node_inner(
7141 &mut self,
7142 node_id: DispatchNodeId,
7143 action: &dyn Action,
7144 cx: &mut App,
7145 ) {
7146 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
7147
7148 cx.propagate_event = true;
7150 if let Some(mut global_listeners) = cx
7151 .global_action_listeners
7152 .remove(&action.as_any().type_id())
7153 {
7154 for listener in &global_listeners {
7155 #[cfg(feature = "profiler")]
7156 self.window_profiler.begin_action_handler(action, cx);
7157 listener(action.as_any(), DispatchPhase::Capture, cx);
7158 #[cfg(feature = "profiler")]
7159 self.window_profiler.end_action_handler();
7160 if !cx.propagate_event {
7161 break;
7162 }
7163 }
7164
7165 global_listeners.extend(
7166 cx.global_action_listeners
7167 .remove(&action.as_any().type_id())
7168 .unwrap_or_default(),
7169 );
7170
7171 cx.global_action_listeners
7172 .insert(action.as_any().type_id(), global_listeners);
7173 }
7174
7175 if !cx.propagate_event {
7176 return;
7177 }
7178
7179 for node_id in &dispatch_path {
7181 let node = self.rendered_frame.dispatch_tree.node(*node_id);
7182 for DispatchActionListener {
7183 action_type,
7184 listener,
7185 } in node.action_listeners.clone()
7186 {
7187 let any_action = action.as_any();
7188 if action_type == any_action.type_id() {
7189 #[cfg(feature = "profiler")]
7190 self.window_profiler.begin_action_handler(action, cx);
7191 listener(any_action, DispatchPhase::Capture, self, cx);
7192 #[cfg(feature = "profiler")]
7193 self.window_profiler.end_action_handler();
7194
7195 if !cx.propagate_event {
7196 return;
7197 }
7198 }
7199 }
7200 }
7201
7202 for node_id in dispatch_path.iter().rev() {
7204 let node = self.rendered_frame.dispatch_tree.node(*node_id);
7205 for DispatchActionListener {
7206 action_type,
7207 listener,
7208 } in node.action_listeners.clone()
7209 {
7210 let any_action = action.as_any();
7211 if action_type == any_action.type_id() {
7212 cx.propagate_event = false; #[cfg(feature = "profiler")]
7214 self.window_profiler.begin_action_handler(action, cx);
7215 listener(any_action, DispatchPhase::Bubble, self, cx);
7216 #[cfg(feature = "profiler")]
7217 self.window_profiler.end_action_handler();
7218
7219 if !cx.propagate_event {
7220 return;
7221 }
7222 }
7223 }
7224 }
7225
7226 if let Some(mut global_listeners) = cx
7228 .global_action_listeners
7229 .remove(&action.as_any().type_id())
7230 {
7231 for listener in global_listeners.iter().rev() {
7232 cx.propagate_event = false; #[cfg(feature = "profiler")]
7235 self.window_profiler.begin_action_handler(action, cx);
7236 listener(action.as_any(), DispatchPhase::Bubble, cx);
7237 #[cfg(feature = "profiler")]
7238 self.window_profiler.end_action_handler();
7239 if !cx.propagate_event {
7240 break;
7241 }
7242 }
7243
7244 global_listeners.extend(
7245 cx.global_action_listeners
7246 .remove(&action.as_any().type_id())
7247 .unwrap_or_default(),
7248 );
7249
7250 cx.global_action_listeners
7251 .insert(action.as_any().type_id(), global_listeners);
7252 }
7253 }
7254
7255 pub fn observe_global<G: Global>(
7258 &mut self,
7259 cx: &mut App,
7260 f: impl Fn(&mut Window, &mut App) + 'static,
7261 ) -> Subscription {
7262 let window_handle = self.handle;
7263 let (subscription, activate) = cx.global_observers.insert_pending(
7264 TypeId::of::<G>(),
7265 Box::new(move |cx| {
7266 window_handle
7267 .update(cx, |_, window, cx| f(window, cx))
7268 .is_ok()
7269 }),
7270 );
7271 cx.defer(move |_| activate());
7272 subscription
7273 }
7274
7275 pub fn activate_window(&self) {
7277 self.platform_window.activate();
7278 }
7279
7280 pub fn request_attention(&self) {
7282 self.platform_window.request_attention();
7283 }
7284
7285 pub fn minimize_window(&self) {
7287 self.platform_window.minimize();
7288 }
7289
7290 pub fn toggle_fullscreen(&self) {
7292 self.platform_window.toggle_fullscreen();
7293 }
7294
7295 pub fn toggle_simple_fullscreen(&self) {
7300 self.platform_window.toggle_simple_fullscreen();
7301 }
7302
7303 pub fn invalidate_character_coordinates(&self) {
7305 self.on_next_frame(|window, cx| {
7306 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
7307 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
7308 window.platform_window.update_ime_position(bounds);
7309 }
7310 window.platform_window.set_input_handler(input_handler);
7311 }
7312 });
7313 }
7314
7315 pub fn prompt<T>(
7319 &mut self,
7320 level: PromptLevel,
7321 message: &str,
7322 detail: Option<&str>,
7323 answers: &[T],
7324 cx: &mut App,
7325 ) -> oneshot::Receiver<usize>
7326 where
7327 T: Clone + Into<PromptButton>,
7328 {
7329 let prompt_builder = cx.prompt_builder.take();
7330 let Some(prompt_builder) = prompt_builder else {
7331 unreachable!("Re-entrant window prompting is not supported by GPUI");
7332 };
7333
7334 let answers = answers
7335 .iter()
7336 .map(|answer| answer.clone().into())
7337 .collect::<Vec<_>>();
7338
7339 let receiver = match &prompt_builder {
7340 PromptBuilder::Default => self
7341 .platform_window
7342 .prompt(level, message, detail, &answers)
7343 .unwrap_or_else(|| {
7344 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
7345 }),
7346 PromptBuilder::Custom(_) => {
7347 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
7348 }
7349 };
7350
7351 cx.prompt_builder = Some(prompt_builder);
7352
7353 receiver
7354 }
7355
7356 fn build_custom_prompt(
7357 &mut self,
7358 prompt_builder: &PromptBuilder,
7359 level: PromptLevel,
7360 message: &str,
7361 detail: Option<&str>,
7362 answers: &[PromptButton],
7363 cx: &mut App,
7364 ) -> oneshot::Receiver<usize> {
7365 let (sender, receiver) = oneshot::channel();
7366 let handle = PromptHandle::new(sender);
7367 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
7368 self.prompt = Some(handle);
7369 receiver
7370 }
7371
7372 pub fn has_active_prompt(&self) -> bool {
7377 self.prompt.is_some()
7378 }
7379
7380 pub fn context_stack(&self) -> Vec<KeyContext> {
7382 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
7383 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7384 dispatch_tree
7385 .dispatch_path(node_id)
7386 .iter()
7387 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
7388 .collect()
7389 }
7390
7391 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
7393 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
7394 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
7395 for action_type in cx.global_action_listeners.keys() {
7396 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
7397 let action = cx.actions.build_action_type(action_type).ok();
7398 if let Some(action) = action {
7399 actions.insert(ix, action);
7400 }
7401 }
7402 }
7403 actions
7404 }
7405
7406 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
7409 self.rendered_frame
7410 .dispatch_tree
7411 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
7412 }
7413
7414 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
7417 self.rendered_frame
7418 .dispatch_tree
7419 .highest_precedence_binding_for_action(
7420 action,
7421 &self.rendered_frame.dispatch_tree.context_stack,
7422 )
7423 }
7424
7425 pub fn bindings_for_action_in_context(
7427 &self,
7428 action: &dyn Action,
7429 context: KeyContext,
7430 ) -> Vec<KeyBinding> {
7431 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7432 dispatch_tree.bindings_for_action(action, &[context])
7433 }
7434
7435 pub fn highest_precedence_binding_for_action_in_context(
7438 &self,
7439 action: &dyn Action,
7440 context: KeyContext,
7441 ) -> Option<KeyBinding> {
7442 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7443 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
7444 }
7445
7446 pub fn bindings_for_action_in(
7450 &self,
7451 action: &dyn Action,
7452 focus_handle: &FocusHandle,
7453 ) -> Vec<KeyBinding> {
7454 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7455 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
7456 return vec![];
7457 };
7458 dispatch_tree.bindings_for_action(action, &context_stack)
7459 }
7460
7461 pub fn highest_precedence_binding_for_action_in(
7465 &self,
7466 action: &dyn Action,
7467 focus_handle: &FocusHandle,
7468 ) -> Option<KeyBinding> {
7469 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7470 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
7471 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
7472 }
7473
7474 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
7476 self.rendered_frame
7477 .dispatch_tree
7478 .possible_next_bindings_for_input(input, &self.context_stack())
7479 }
7480
7481 fn context_stack_for_focus_handle(
7482 &self,
7483 focus_handle: &FocusHandle,
7484 ) -> Option<Vec<KeyContext>> {
7485 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7486 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
7487 let context_stack: Vec<_> = dispatch_tree
7488 .dispatch_path(node_id)
7489 .into_iter()
7490 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
7491 .collect();
7492 Some(context_stack)
7493 }
7494
7495 pub fn listener_for<T: 'static, E>(
7497 &self,
7498 view: &Entity<T>,
7499 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
7500 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
7501 let view = view.downgrade();
7502 move |e: &E, window: &mut Window, cx: &mut App| {
7503 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
7504 }
7505 }
7506
7507 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
7509 &self,
7510 entity: &Entity<E>,
7511 f: Callback,
7512 ) -> impl Fn(&mut Window, &mut App) + 'static {
7513 let entity = entity.downgrade();
7514 move |window: &mut Window, cx: &mut App| {
7515 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
7516 }
7517 }
7518
7519 pub fn on_window_should_close(
7522 &self,
7523 cx: &App,
7524 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
7525 ) {
7526 let mut cx = self.to_async(cx);
7527 self.platform_window.on_should_close(Box::new(move || {
7528 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
7529 }))
7530 }
7531
7532 pub fn on_action(
7541 &mut self,
7542 action_type: TypeId,
7543 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
7544 ) {
7545 self.invalidator.debug_assert_paint();
7546
7547 self.next_frame
7548 .dispatch_tree
7549 .on_action(action_type, Rc::new(listener));
7550 }
7551
7552 pub fn on_action_when(
7561 &mut self,
7562 condition: bool,
7563 action_type: TypeId,
7564 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
7565 ) {
7566 self.invalidator.debug_assert_paint();
7567
7568 if condition {
7569 self.next_frame
7570 .dispatch_tree
7571 .on_action(action_type, Rc::new(listener));
7572 }
7573 }
7574
7575 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
7578 self.platform_window.gpu_specs()
7579 }
7580
7581 pub fn titlebar_double_click(&self) {
7584 self.platform_window
7585 .titlebar_double_click(self.is_resizable, self.is_minimizable);
7586 }
7587
7588 pub fn window_title(&self) -> String {
7591 self.platform_window.get_title()
7592 }
7593
7594 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
7597 self.platform_window.tabbed_windows()
7598 }
7599
7600 pub fn tab_bar_visible(&self) -> bool {
7603 self.platform_window.tab_bar_visible()
7604 }
7605
7606 pub fn merge_all_windows(&self) {
7609 self.platform_window.merge_all_windows()
7610 }
7611
7612 pub fn move_tab_to_new_window(&self) {
7615 self.platform_window.move_tab_to_new_window()
7616 }
7617
7618 pub fn toggle_window_tab_overview(&self) {
7621 self.platform_window.toggle_window_tab_overview()
7622 }
7623
7624 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
7627 self.platform_window
7628 .set_tabbing_identifier(tabbing_identifier)
7629 }
7630
7631 pub fn play_system_bell(&self) {
7634 self.platform_window.play_system_bell()
7635 }
7636
7637 pub fn is_a11y_enabled(&self) -> bool {
7644 self.a11y.is_enabled()
7645 }
7646
7647 pub fn is_a11y_active(&self) -> bool {
7658 self.a11y.is_active()
7659 }
7660
7661 pub fn debug_a11y_tree_json(&self) -> Option<String> {
7663 self.a11y.debug_tree_json()
7664 }
7665
7666 pub fn on_a11y_action(
7672 &mut self,
7673 node_id: accesskit::NodeId,
7674 action: accesskit::Action,
7675 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
7676 ) {
7677 self.a11y
7678 .action_listeners
7679 .entry(node_id)
7680 .or_default()
7681 .push((action, Box::new(listener)));
7682 }
7683
7684 #[cfg(not(target_family = "wasm"))]
7685 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
7686 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
7689 let extra_data = request.data.as_ref();
7690 let mut matched = false;
7691 for (action, listener) in &mut listeners {
7692 if *action == request.action {
7693 listener(extra_data, self, cx);
7694 matched = true;
7695 }
7696 }
7697 self.a11y
7698 .action_listeners
7699 .insert(request.target_node, listeners);
7700 if matched {
7701 return;
7702 }
7703 }
7704
7705 match request.action {
7707 accesskit::Action::Click => {
7708 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
7709 let center = bounds.center();
7710 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
7711 button: MouseButton::Left,
7712 position: center,
7713 modifiers: Modifiers::default(),
7714 click_count: 1,
7715 first_mouse: false,
7716 });
7717 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
7718 button: MouseButton::Left,
7719 position: center,
7720 modifiers: Modifiers::default(),
7721 click_count: 1,
7722 });
7723 self.dispatch_event(mouse_down, cx);
7724 self.dispatch_event(mouse_up, cx);
7725 }
7726 }
7727 accesskit::Action::Focus => {
7728 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
7729 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
7730 {
7731 self.focus(&handle, cx);
7732 }
7733 }
7734 accesskit::Action::Blur => {
7735 self.blur(cx);
7736 }
7737 _ => {
7738 log::debug!(
7739 "Unhandled a11y action: {:?} on {:?}",
7740 request.action,
7741 request.target_node
7742 );
7743 }
7744 }
7745 }
7746
7747 #[cfg(any(feature = "inspector", debug_assertions))]
7749 pub fn toggle_inspector(&mut self, cx: &mut App) {
7750 self.inspector = match self.inspector {
7751 None => Some(cx.new(|_| Inspector::new())),
7752 Some(_) => {
7753 self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
7754 self.rendered_frame.inspector_hitboxes = FxHashMap::default();
7755 self.next_frame.next_inspector_instance_ids = FxHashMap::default();
7756 self.next_frame.inspector_hitboxes = FxHashMap::default();
7757 None
7758 }
7759 };
7760 self.refresh();
7761 }
7762
7763 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
7765 #[cfg(any(feature = "inspector", debug_assertions))]
7766 {
7767 if let Some(inspector) = &self.inspector {
7768 return inspector.read(_cx).is_picking();
7769 }
7770 }
7771 false
7772 }
7773
7774 #[cfg(any(feature = "inspector", debug_assertions))]
7776 pub fn with_inspector_state<T: 'static, R>(
7777 &mut self,
7778 inspector_id: Option<&crate::InspectorElementId>,
7779 cx: &mut App,
7780 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
7781 ) -> Option<R> {
7782 let inspector_id = inspector_id?;
7783 let inspector = self.inspector.as_ref()?;
7784 if inspector.read(cx).active_element_id() != Some(inspector_id) {
7785 return None;
7786 }
7787 let inspector = inspector.clone();
7788 Some(inspector.update(cx, |inspector, _cx| {
7789 inspector.with_active_element_state(self, f)
7790 }))
7791 }
7792
7793 #[cfg(any(feature = "inspector", debug_assertions))]
7794 pub(crate) fn inspector_enabled(&self) -> bool {
7795 self.inspector.is_some()
7796 }
7797
7798 #[cfg(any(feature = "inspector", debug_assertions))]
7799 pub(crate) fn build_inspector_element_id(
7800 &mut self,
7801 path: crate::InspectorElementPath,
7802 ) -> crate::InspectorElementId {
7803 self.invalidator.debug_assert_paint_or_prepaint();
7804 let path = Rc::new(path);
7805 let next_instance_id = self
7806 .next_frame
7807 .next_inspector_instance_ids
7808 .entry(path.clone())
7809 .or_insert(0);
7810 let instance_id = *next_instance_id;
7811 *next_instance_id += 1;
7812 crate::InspectorElementId { path, instance_id }
7813 }
7814
7815 #[cfg(any(feature = "inspector", debug_assertions))]
7816 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
7817 if let Some(inspector) = self.inspector.take() {
7818 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
7819 inspector_element.prepaint_as_root(
7820 point(self.viewport_size.width - inspector_width, px(0.0)),
7821 size(inspector_width, self.viewport_size.height).into(),
7822 self,
7823 cx,
7824 );
7825 self.inspector = Some(inspector);
7826 Some(inspector_element)
7827 } else {
7828 None
7829 }
7830 }
7831
7832 #[cfg(any(feature = "inspector", debug_assertions))]
7833 fn paint_inspector(&mut self, inspector_element: Option<AnyElement>, cx: &mut App) {
7834 if let Some(mut inspector_element) = inspector_element {
7835 inspector_element.paint(self, cx);
7836 };
7837 }
7838
7839 #[cfg(any(feature = "inspector", debug_assertions))]
7842 pub fn insert_inspector_hitbox(
7843 &mut self,
7844 hitbox_id: HitboxId,
7845 inspector_id: Option<&crate::InspectorElementId>,
7846 cx: &App,
7847 ) {
7848 self.invalidator.debug_assert_paint_or_prepaint();
7849 if !self.is_inspector_picking(cx) {
7850 return;
7851 }
7852 if let Some(inspector_id) = inspector_id {
7853 self.next_frame
7854 .inspector_hitboxes
7855 .insert(hitbox_id, inspector_id.clone());
7856 }
7857 }
7858
7859 #[cfg(any(feature = "inspector", debug_assertions))]
7860 fn paint_inspector_hitbox(&mut self, cx: &App) {
7861 if let Some(inspector) = self.inspector.as_ref() {
7862 let inspector = inspector.read(cx);
7863 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
7864 && let Some(hitbox) = self
7865 .next_frame
7866 .hitboxes
7867 .iter()
7868 .find(|hitbox| hitbox.id == hitbox_id)
7869 {
7870 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
7871 }
7872 }
7873 }
7874
7875 #[cfg(any(feature = "inspector", debug_assertions))]
7876 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
7877 let Some(inspector) = self.inspector.clone() else {
7878 return;
7879 };
7880 if event.downcast_ref::<MouseMoveEvent>().is_some() {
7881 inspector.update(cx, |inspector, _cx| {
7882 if let Some((_, inspector_id)) =
7883 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7884 {
7885 inspector.hover(inspector_id, self);
7886 }
7887 });
7888 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
7889 inspector.update(cx, |inspector, _cx| {
7890 if let Some((_, inspector_id)) =
7891 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7892 {
7893 inspector.select(inspector_id, self);
7894 }
7895 });
7896 } else if let Some(event) = event.downcast_ref::<crate::ScrollEvent>() {
7897 const SCROLL_LINES: f32 = 3.0;
7899 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
7900 let delta_y = event
7901 .delta
7902 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
7903 .y;
7904 inspector.update(cx, |inspector, _cx| {
7905 if let Some(depth) = inspector.pick_depth.as_mut() {
7906 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
7907 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
7908 if *depth < 0.0 {
7909 *depth = 0.0;
7910 } else if *depth > max_depth {
7911 *depth = max_depth;
7912 }
7913 if let Some((_, inspector_id)) =
7914 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7915 {
7916 inspector.set_active_element_id(inspector_id, self);
7917 }
7918 }
7919 });
7920 }
7921 }
7922
7923 #[cfg(any(feature = "inspector", debug_assertions))]
7924 fn hovered_inspector_hitbox(
7925 &self,
7926 inspector: &Inspector,
7927 frame: &Frame,
7928 ) -> Option<(HitboxId, crate::InspectorElementId)> {
7929 if let Some(pick_depth) = inspector.pick_depth {
7930 let depth = (pick_depth as i64).try_into().unwrap_or(0);
7931 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
7932 let skip_count = (depth as usize).min(max_skipped);
7933 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
7934 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
7935 return Some((*hitbox_id, inspector_id.clone()));
7936 }
7937 }
7938 }
7939 None
7940 }
7941
7942 #[cfg(any(test, feature = "test-support"))]
7945 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
7946 self.modifiers = modifiers;
7947 }
7948
7949 #[cfg(any(test, feature = "test-support"))]
7953 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
7954 let event = PlatformInput::MouseMove(MouseMoveEvent {
7955 position,
7956 modifiers: self.modifiers,
7957 pressed_button: None,
7958 });
7959 let _ = self.dispatch_event(event, cx);
7960 }
7961
7962 #[inline(never)]
7963 fn take_element_state(
7964 &mut self,
7965 global_id: &GlobalElementId,
7966 state_type: TypeId,
7967 ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
7968 let key = (global_id.clone(), state_type);
7969 self.next_frame.accessed_element_states.push(key.clone());
7970 let state = self
7971 .next_frame
7972 .element_states
7973 .remove(&key)
7974 .or_else(|| self.rendered_frame.element_states.remove(&key));
7975 (key, state)
7976 }
7977
7978 #[inline(never)]
7979 fn insert_element_state(
7980 &mut self,
7981 key: (GlobalElementId, TypeId),
7982 state: ElementStateBox,
7983 ) -> Option<ElementStateBox> {
7984 self.next_frame.element_states.insert(key, state)
7985 }
7986
7987 #[inline(never)]
7988 fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
7989 cx.observe(state, move |_, cx| {
7990 cx.notify(current_view);
7991 })
7992 .detach();
7993 }
7994}
7995
7996slotmap::new_key_type! {
7998 pub struct WindowId;
8000}
8001
8002impl WindowId {
8003 pub fn as_u64(&self) -> u64 {
8005 self.0.as_ffi()
8006 }
8007}
8008
8009impl From<u64> for WindowId {
8010 fn from(value: u64) -> Self {
8011 WindowId(slotmap::KeyData::from_ffi(value))
8012 }
8013}
8014
8015#[derive(Deref, DerefMut)]
8018pub struct WindowHandle<V> {
8019 #[deref]
8020 #[deref_mut]
8021 pub(crate) any_handle: AnyWindowHandle,
8022 state_type: PhantomData<fn(V) -> V>,
8023}
8024
8025impl<V> Debug for WindowHandle<V> {
8026 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8027 f.debug_struct("WindowHandle")
8028 .field("any_handle", &self.any_handle.id.as_u64())
8029 .finish()
8030 }
8031}
8032
8033impl<V: 'static + Render> WindowHandle<V> {
8034 pub fn new(id: WindowId) -> Self {
8037 WindowHandle {
8038 any_handle: AnyWindowHandle {
8039 id,
8040 state_type: TypeId::of::<V>(),
8041 root_entity_type_name: std::any::type_name::<V>(),
8042 },
8043 state_type: PhantomData,
8044 }
8045 }
8046
8047 #[cfg(any(test, feature = "test-support"))]
8051 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
8052 where
8053 C: AppContext,
8054 {
8055 cx.update_window(self.any_handle, |root_view, _, _| {
8056 root_view
8057 .downcast::<V>()
8058 .map_err(|_| anyhow!("the type of the window's root view has changed"))
8059 })?
8060 }
8061
8062 #[track_caller]
8066 pub fn update<C, R>(
8067 &self,
8068 cx: &mut C,
8069 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
8070 ) -> Result<R>
8071 where
8072 C: AppContext,
8073 {
8074 cx.update_window(self.any_handle, |root_view, window, cx| {
8075 let view = root_view
8076 .downcast::<V>()
8077 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
8078
8079 Ok(view.update(cx, |view, cx| update(view, window, cx)))
8080 })?
8081 }
8082
8083 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
8087 let x = cx
8088 .windows
8089 .get(self.id)
8090 .and_then(|window| {
8091 window
8092 .as_deref()
8093 .and_then(|window| window.root.clone())
8094 .map(|root_view| root_view.downcast::<V>())
8095 })
8096 .context("window not found")?
8097 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
8098
8099 Ok(x.read(cx))
8100 }
8101
8102 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
8106 where
8107 C: AppContext,
8108 {
8109 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
8110 }
8111
8112 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
8116 where
8117 C: AppContext,
8118 {
8119 cx.read_window(self, |root_view, _cx| root_view)
8120 }
8121
8122 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
8127 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
8128 .ok()
8129 }
8130}
8131
8132impl<V> Copy for WindowHandle<V> {}
8133
8134impl<V> Clone for WindowHandle<V> {
8135 fn clone(&self) -> Self {
8136 *self
8137 }
8138}
8139
8140impl<V> PartialEq for WindowHandle<V> {
8141 fn eq(&self, other: &Self) -> bool {
8142 self.any_handle == other.any_handle
8143 }
8144}
8145
8146impl<V> Eq for WindowHandle<V> {}
8147
8148impl<V> Hash for WindowHandle<V> {
8149 fn hash<H: Hasher>(&self, state: &mut H) {
8150 self.any_handle.hash(state);
8151 }
8152}
8153
8154impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
8155 fn from(val: WindowHandle<V>) -> Self {
8156 val.any_handle
8157 }
8158}
8159
8160#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
8162pub struct AnyWindowHandle {
8163 pub(crate) id: WindowId,
8164 state_type: TypeId,
8165 root_entity_type_name: &'static str,
8166}
8167
8168impl AnyWindowHandle {
8169 pub fn window_id(&self) -> WindowId {
8171 self.id
8172 }
8173
8174 pub fn root_entity_type_name(&self) -> &'static str {
8176 self.root_entity_type_name
8177 }
8178
8179 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
8182 if TypeId::of::<T>() == self.state_type {
8183 Some(WindowHandle {
8184 any_handle: *self,
8185 state_type: PhantomData,
8186 })
8187 } else {
8188 None
8189 }
8190 }
8191
8192 #[track_caller]
8196 pub fn update<C, R>(
8197 self,
8198 cx: &mut C,
8199 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
8200 ) -> Result<R>
8201 where
8202 C: AppContext,
8203 {
8204 cx.update_window(self, update)
8205 }
8206
8207 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
8211 where
8212 C: AppContext,
8213 T: 'static,
8214 {
8215 let view = self
8216 .downcast::<T>()
8217 .context("the type of the window's root view has changed")?;
8218
8219 cx.read_window(&view, read)
8220 }
8221}
8222
8223impl HasWindowHandle for Window {
8224 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
8225 self.platform_window.window_handle()
8226 }
8227}
8228
8229impl HasDisplayHandle for Window {
8230 fn display_handle(
8231 &self,
8232 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
8233 self.platform_window.display_handle()
8234 }
8235}
8236
8237#[derive(Clone, Debug, Eq, PartialEq, Hash)]
8242pub enum ElementId {
8243 View(EntityId),
8245 Integer(u64),
8247 Name(SharedString),
8249 Uuid(Uuid),
8251 FocusHandle(FocusId),
8253 NamedInteger(SharedString, u64),
8255 Path(Arc<std::path::Path>),
8257 CodeLocation(core::panic::Location<'static>),
8259 NamedChild(Arc<ElementId>, SharedString),
8261 OpaqueId([u8; 20]),
8263}
8264
8265impl ElementId {
8266 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
8268 Self::NamedInteger(name.into(), integer as u64)
8269 }
8270}
8271
8272impl Display for ElementId {
8273 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
8274 match self {
8275 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
8276 ElementId::Integer(ix) => write!(f, "{}", ix)?,
8277 ElementId::Name(name) => write!(f, "{}", name)?,
8278 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
8279 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
8280 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
8281 ElementId::Path(path) => write!(f, "{}", path.display())?,
8282 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
8283 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
8284 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
8285 }
8286
8287 Ok(())
8288 }
8289}
8290
8291impl TryInto<SharedString> for ElementId {
8292 type Error = anyhow::Error;
8293
8294 fn try_into(self) -> anyhow::Result<SharedString> {
8295 if let ElementId::Name(name) = self {
8296 Ok(name)
8297 } else {
8298 anyhow::bail!("element id is not string")
8299 }
8300 }
8301}
8302
8303impl From<u64> for ElementId {
8304 fn from(id: u64) -> Self {
8305 ElementId::Integer(id)
8306 }
8307}
8308
8309impl From<usize> for ElementId {
8310 fn from(id: usize) -> Self {
8311 ElementId::Integer(id as u64)
8312 }
8313}
8314
8315impl From<i32> for ElementId {
8316 fn from(id: i32) -> Self {
8317 Self::Integer(id as u64)
8318 }
8319}
8320
8321impl From<SharedString> for ElementId {
8322 fn from(name: SharedString) -> Self {
8323 ElementId::Name(name)
8324 }
8325}
8326
8327impl From<String> for ElementId {
8328 fn from(name: String) -> Self {
8329 ElementId::Name(name.into())
8330 }
8331}
8332
8333impl From<Arc<str>> for ElementId {
8334 fn from(name: Arc<str>) -> Self {
8335 ElementId::Name(name.into())
8336 }
8337}
8338
8339impl From<Arc<std::path::Path>> for ElementId {
8340 fn from(path: Arc<std::path::Path>) -> Self {
8341 ElementId::Path(path)
8342 }
8343}
8344
8345impl From<&'static str> for ElementId {
8346 fn from(name: &'static str) -> Self {
8347 ElementId::Name(SharedString::new_static(name))
8348 }
8349}
8350
8351impl<'a> From<&'a FocusHandle> for ElementId {
8352 fn from(handle: &'a FocusHandle) -> Self {
8353 ElementId::FocusHandle(handle.id)
8354 }
8355}
8356
8357impl From<(&'static str, EntityId)> for ElementId {
8358 fn from((name, id): (&'static str, EntityId)) -> Self {
8359 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
8360 }
8361}
8362
8363impl From<(&'static str, usize)> for ElementId {
8364 fn from((name, id): (&'static str, usize)) -> Self {
8365 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
8366 }
8367}
8368
8369impl From<(SharedString, usize)> for ElementId {
8370 fn from((name, id): (SharedString, usize)) -> Self {
8371 ElementId::NamedInteger(name, id as u64)
8372 }
8373}
8374
8375impl From<(&'static str, u64)> for ElementId {
8376 fn from((name, id): (&'static str, u64)) -> Self {
8377 ElementId::NamedInteger(SharedString::new_static(name), id)
8378 }
8379}
8380
8381impl From<Uuid> for ElementId {
8382 fn from(value: Uuid) -> Self {
8383 Self::Uuid(value)
8384 }
8385}
8386
8387impl From<(&'static str, u32)> for ElementId {
8388 fn from((name, id): (&'static str, u32)) -> Self {
8389 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
8390 }
8391}
8392
8393impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
8394 fn from((id, name): (ElementId, T)) -> Self {
8395 ElementId::NamedChild(Arc::new(id), name.into())
8396 }
8397}
8398
8399impl From<&'static core::panic::Location<'static>> for ElementId {
8400 fn from(location: &'static core::panic::Location<'static>) -> Self {
8401 ElementId::CodeLocation(*location)
8402 }
8403}
8404
8405impl From<[u8; 20]> for ElementId {
8406 fn from(opaque_id: [u8; 20]) -> Self {
8407 ElementId::OpaqueId(opaque_id)
8408 }
8409}
8410
8411#[derive(Clone)]
8414pub struct PaintQuad {
8415 pub bounds: Bounds<Pixels>,
8417 pub corner_radii: Corners<Pixels>,
8419 pub background: Background,
8421 pub border_widths: Edges<Pixels>,
8423 pub border_color: Hsla,
8425 pub border_style: BorderStyle,
8427}
8428
8429impl PaintQuad {
8430 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
8432 PaintQuad {
8433 corner_radii: corner_radii.into(),
8434 ..self
8435 }
8436 }
8437
8438 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
8440 PaintQuad {
8441 border_widths: border_widths.into(),
8442 ..self
8443 }
8444 }
8445
8446 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
8448 PaintQuad {
8449 border_color: border_color.into(),
8450 ..self
8451 }
8452 }
8453
8454 pub fn background(self, background: impl Into<Background>) -> Self {
8456 PaintQuad {
8457 background: background.into(),
8458 ..self
8459 }
8460 }
8461}
8462
8463pub fn quad(
8465 bounds: Bounds<Pixels>,
8466 corner_radii: impl Into<Corners<Pixels>>,
8467 background: impl Into<Background>,
8468 border_widths: impl Into<Edges<Pixels>>,
8469 border_color: impl Into<Hsla>,
8470 border_style: BorderStyle,
8471) -> PaintQuad {
8472 PaintQuad {
8473 bounds,
8474 corner_radii: corner_radii.into(),
8475 background: background.into(),
8476 border_widths: border_widths.into(),
8477 border_color: border_color.into(),
8478 border_style,
8479 }
8480}
8481
8482pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
8484 PaintQuad {
8485 bounds: bounds.into(),
8486 corner_radii: (0.).into(),
8487 background: background.into(),
8488 border_widths: (0.).into(),
8489 border_color: transparent_black(),
8490 border_style: BorderStyle::default(),
8491 }
8492}
8493
8494pub fn outline(
8496 bounds: impl Into<Bounds<Pixels>>,
8497 border_color: impl Into<Hsla>,
8498 border_style: BorderStyle,
8499) -> PaintQuad {
8500 PaintQuad {
8501 bounds: bounds.into(),
8502 corner_radii: (0.).into(),
8503 background: transparent_black().into(),
8504 border_widths: (1.).into(),
8505 border_color: border_color.into(),
8506 border_style,
8507 }
8508}
8509
8510#[inline(never)]
8511fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
8512 if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
8513 let arena_cell = unsafe { &*arena_pointer };
8516 callback(&mut arena_cell.borrow_mut());
8517 Ok(())
8518 } else {
8519 ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
8520 }
8521}
8522
8523#[cfg(test)]
8524mod tests {
8525 use std::{
8526 cell::{Cell, RefCell},
8527 path::PathBuf,
8528 rc::Rc,
8529 time::Duration,
8530 };
8531
8532 use crate::{
8533 AnyWindowHandle, AppContext as _, BackGestureEvent, BackGesturePhase, Bounds, ContentMask,
8534 Context, CursorStyle, DispatchPhase, DragMoveEvent, Empty, ExternalDragPayload,
8535 ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle, InputEvent as _,
8536 InteractiveElement as _, IntoElement, KeyDownEvent, Keystroke, LongPressEvent, MouseButton,
8537 MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, PlatformInput, Point,
8538 Render, RequestFrameOptions, ScaledPixels, StatefulInteractiveElement as _, Styled,
8539 TestAppContext, ThermalState, TouchDragEvent, TouchEvent, TouchId, TouchPhase, Underline,
8540 UnderlineStyle, Window, WindowAppearance, WindowOptions, canvas, div, hsla, point, px,
8541 size,
8542 };
8543
8544 #[gpui::test]
8545 async fn test_focus_handle_release(cx: &mut TestAppContext) {
8546 let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
8547 let handle_id = handle.id;
8548 let weak_handle = handle.downgrade();
8549 let retained = handle.clone();
8550 drop(handle);
8551
8552 cx.update(|_| {});
8553 cx.read(|cx| {
8554 let handles = cx.focus_handles.read();
8555 assert_eq!(handles.handles.len(), 2);
8556 assert!(handles.dropped_handles.is_empty());
8557 });
8558 assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));
8559
8560 cx.background_spawn(async move { drop(retained) }).await;
8561 assert_eq!(weak_handle.upgrade(), None);
8562 cx.read(|cx| {
8563 assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);
8564 });
8565 cx.update(|_| {});
8566 cx.read(|cx| {
8567 let handles = cx.focus_handles.read();
8568 assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);
8569 assert!(handles.dropped_handles.is_empty());
8570 });
8571
8572 let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);
8573 assert_eq!(weak_handle.upgrade(), None);
8574 cx.update(|cx| {
8575 drop(replacements);
8576 cx.defer(move |_| drop(survivor));
8577 });
8578 cx.read(|cx| {
8579 let handles = cx.focus_handles.read();
8580 assert_eq!(handles.handles.len(), 0);
8581 assert!(handles.dropped_handles.is_empty());
8582 });
8583 }
8584
8585 #[gpui::test]
8586 fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {
8587 let windows = [
8588 cx.add_window(|_, _| EmptyView),
8589 cx.add_window(|_, _| EmptyView),
8590 cx.add_window(|_, _| EmptyView),
8591 cx.add_window(|_, _| EmptyView),
8592 cx.add_window(|_, _| EmptyView),
8593 ];
8594 let (handle, other_handle, survivor) =
8595 cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));
8596 for window in &windows[..2] {
8597 window
8598 .update(cx, |_, window, cx| window.focus(&handle, cx))
8599 .expect("window exists");
8600 }
8601 windows[2]
8602 .update(cx, |_, window, cx| window.focus(&other_handle, cx))
8603 .expect("window exists");
8604 windows[3]
8605 .update(cx, |_, window, cx| window.focus(&survivor, cx))
8606 .expect("window exists");
8607
8608 cx.update(|cx| {
8609 for _ in 0..1_000 {
8610 drop(cx.focus_handle());
8611 }
8612 drop((handle, other_handle));
8613 });
8614 for window in &windows[..3] {
8615 window
8616 .update(cx, |_, window, _| assert_eq!(window.focus, None))
8617 .expect("window exists");
8618 }
8619 windows[3]
8620 .update(cx, |_, window, cx| {
8621 assert_eq!(window.focused(cx).as_ref(), Some(&survivor));
8622 assert_eq!(window.focus_generation, 1);
8623 })
8624 .expect("window exists");
8625 windows[4]
8626 .update(cx, |_, window, _| {
8627 assert_eq!(window.focus, None);
8628 assert_eq!(window.focus_generation, 0);
8629 })
8630 .expect("window exists");
8631 }
8632
8633 #[gpui::test]
8634 fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
8635 let window = cx.add_window(|_, _| EmptyView);
8636 let platform_window = cx.test_window(window.into());
8637 {
8638 let app = cx.app.borrow_mut();
8639 platform_window.simulate_close();
8640 assert!(app.windows.contains_key(window.window_id()));
8641 }
8642 cx.run_until_parked();
8643 assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
8644 }
8645
8646 #[cfg(feature = "profiler")]
8647 #[gpui::test]
8648 fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
8649 use crate::FrameRequestSource;
8650 use crate::profiler::journal::{
8651 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
8652 };
8653 use scheduler::Instant;
8654
8655 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8656 let window = cx.add_window(|_, _| EmptyView);
8657 let platform_window = cx.test_window(window.into());
8658 platform_window.simulate_frame_request(RequestFrameOptions::default());
8659 let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
8660 let mut collector = journal.collector();
8661
8662 for (signal_at, source) in [
8663 (Some(Instant::now()), FrameRequestSource::NativeCallback),
8664 (Some(Instant::now()), FrameRequestSource::LocalSchedule),
8665 (None, FrameRequestSource::NativeCallback),
8666 ] {
8667 platform_window.simulate_frame_request(RequestFrameOptions {
8668 signal_at,
8669 signal_source: source,
8670 require_presentation: true,
8671 ..Default::default()
8672 });
8673 let entries = collector.collect_unseen().entries;
8674 let signal_index = entries
8675 .iter()
8676 .position(|entry| {
8677 matches!(
8678 entry,
8679 ForegroundJournalEntry::PlatformSignal(signal)
8680 if signal.window_id == window.window_id()
8681 && signal.signal_at == signal_at
8682 && signal.source == source
8683 && signal_at.is_none_or(|at| signal.handled_at >= at)
8684 )
8685 })
8686 .expect("frame request metadata");
8687 let skip_index = entries
8688 .iter()
8689 .position(|entry| {
8690 matches!(
8691 entry,
8692 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
8693 if skipped.window_id == window.window_id()
8694 && skipped.reason == FrameSkipReason::NoRenderNeeded
8695 )
8696 })
8697 .expect("completed no-render boundary");
8698 assert!(signal_index < skip_index);
8699 }
8700 }
8701
8702 #[cfg(feature = "profiler")]
8703 #[gpui::test]
8704 fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
8705 use crate::profiler::journal::{
8706 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
8707 };
8708 use scheduler::Instant;
8709
8710 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8712 let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
8713 let mut collector = journal.collector();
8714 for (initially_dirty, schedule_callback) in [(true, false), (false, true)] {
8715 let window = cx
8717 .app
8718 .borrow_mut()
8719 .open_window(
8720 WindowOptions {
8721 inactive_frame_interval: Some(Duration::from_secs(3600)),
8722 ..Default::default()
8723 },
8724 |_, cx| cx.new(|_| EmptyView),
8725 )
8726 .expect("open inactive test window");
8727 let platform_window = cx.test_window(window.into());
8728 platform_window.simulate_active_status_change(false);
8729 platform_window.simulate_frame_request(RequestFrameOptions::default());
8730 let callback_ran = Rc::new(Cell::new(false));
8731 let draws_before = window
8732 .update(cx, |_, window, _| {
8733 let draws_before = window
8734 .frame_duration_snapshot()
8735 .draw_duration_histogram
8736 .len();
8737 if initially_dirty {
8738 window.refresh();
8739 }
8740 if schedule_callback {
8741 window.on_next_frame({
8742 let callback_ran = callback_ran.clone();
8743 move |window, _| {
8744 callback_ran.set(true);
8745 window.refresh();
8746 }
8747 });
8748 }
8749 draws_before
8750 })
8751 .expect("schedule throttled frame");
8752 let input_at = Instant::now();
8754 journal::record_input(journal::InputTiming {
8755 kind: "test",
8756 start: input_at,
8757 end: input_at,
8758 caused_invalidation: false,
8759 });
8760 collector.collect_unseen();
8761 let wakes_before = platform_window.frame_wake_count();
8762 platform_window.simulate_frame_request(RequestFrameOptions {
8763 signal_at: Some(Instant::now()),
8764 ..Default::default()
8765 });
8766 window
8767 .update(cx, |_, window, _| {
8768 assert_eq!(
8769 window
8770 .frame_duration_snapshot()
8771 .draw_duration_histogram
8772 .len(),
8773 draws_before,
8774 );
8775 })
8776 .expect("inspect deferred frame");
8777 assert!(!callback_ran.get());
8778 assert!(platform_window.frame_scheduled());
8779 assert!(platform_window.frame_wake_count() > wakes_before);
8780 assert!(collector.collect_unseen().entries.iter().any(|entry| {
8781 matches!(
8782 entry,
8783 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
8784 if skipped.window_id == window.window_id()
8785 && skipped.reason == FrameSkipReason::InactiveFrameRateLimit
8786 )
8787 }));
8788 platform_window.simulate_frame_request(RequestFrameOptions {
8789 signal_at: Some(Instant::now()),
8790 require_presentation: true,
8791 ..Default::default()
8792 });
8793 window
8794 .update(cx, |_, window, _| {
8795 assert_eq!(
8796 window
8797 .frame_duration_snapshot()
8798 .draw_duration_histogram
8799 .len(),
8800 draws_before + 1,
8801 );
8802 })
8803 .expect("inspect presented frame");
8804 assert_eq!(callback_ran.get(), schedule_callback);
8805 }
8806 }
8807
8808 #[cfg(feature = "profiler")]
8809 #[gpui::test]
8810 fn test_throttled_input_records_no_input_latency(cx: &mut TestAppContext) {
8811 struct NotifiesOnMouseMove;
8812
8813 impl Render for NotifiesOnMouseMove {
8814 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8815 div()
8816 .size_full()
8817 .on_mouse_move(cx.listener(|_, _, _, cx| cx.notify()))
8818 }
8819 }
8820
8821 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8823 let window = cx
8824 .app
8825 .borrow_mut()
8826 .open_window(
8827 WindowOptions {
8828 inactive_frame_interval: Some(Duration::from_secs(3600)),
8831 ..Default::default()
8832 },
8833 |_, cx| cx.new(|_| NotifiesOnMouseMove),
8834 )
8835 .expect("open test window");
8836 let mut platform_window = cx.test_window(window.into());
8837 let unthrottled_frame = RequestFrameOptions {
8838 require_presentation: true,
8839 ..Default::default()
8840 };
8841 let move_mouse = |platform_window: &mut crate::TestWindow, x| {
8842 platform_window.simulate_input(PlatformInput::MouseMove(MouseMoveEvent {
8843 position: point(px(x), px(10.)),
8844 pressed_button: None,
8845 modifiers: Default::default(),
8846 }));
8847 };
8848 let samples = |cx: &mut TestAppContext| {
8850 window
8851 .update(cx, |_, window, _| {
8852 let frames = window.frame_duration_snapshot();
8853 (
8854 window.input_latency_snapshot().latency_histogram.len(),
8855 frames.dirty_to_present_histogram.len(),
8856 frames.draw_duration_histogram.len(),
8857 )
8858 })
8859 .expect("read window profiler")
8860 };
8861
8862 platform_window.simulate_active_status_change(false);
8863 platform_window.simulate_frame_request(unthrottled_frame);
8864 let (_, dirty_before, draws_before) = samples(cx);
8865
8866 move_mouse(&mut platform_window, 10.);
8867 platform_window.simulate_frame_request(RequestFrameOptions::default());
8868 assert_eq!(
8869 samples(cx),
8870 (0, dirty_before, draws_before),
8871 "the inactive window's frame should be throttled"
8872 );
8873 move_mouse(&mut platform_window, 20.);
8874 platform_window.simulate_frame_request(unthrottled_frame);
8875 assert_eq!(samples(cx), (0, dirty_before, draws_before + 1));
8876
8877 platform_window.simulate_active_status_change(true);
8878 platform_window.simulate_frame_request(unthrottled_frame);
8879 move_mouse(&mut platform_window, 30.);
8880 platform_window.simulate_frame_request(RequestFrameOptions::default());
8881 let (input_samples, dirty_samples, _) = samples(cx);
8882 assert_eq!(input_samples, 1);
8883 assert!(dirty_samples > dirty_before);
8884 }
8885
8886 #[gpui::test]
8889 fn test_debug_state_reports_cached_and_platform_values(cx: &mut TestAppContext) {
8890 use crate::WindowVisibility;
8891
8892 let window = cx.add_window(|_, _| EmptyView);
8893 let window_id = window.window_id().as_u64();
8894 let window_state = |cx: &mut TestAppContext| {
8895 let state = cx.update(|cx| cx.debug_state());
8896 state["windows"]
8897 .as_array()
8898 .and_then(|windows| windows.iter().find(|window| window["id"] == window_id))
8899 .cloned()
8900 .expect("the open window is listed")
8901 };
8902
8903 let state = window_state(cx);
8904 assert_eq!(state["visibility"]["cached"], "Visible");
8905 assert_eq!(state["visibility"]["platform"], "Visible");
8906
8907 cx.test_window(window.into())
8908 .simulate_visibility_change(WindowVisibility::Hidden);
8909 let state = window_state(cx);
8910 assert_eq!(state["visibility"]["cached"], "Hidden");
8911 assert_eq!(state["visibility"]["platform"], "Hidden");
8912 }
8913
8914 #[gpui::test]
8918 fn test_window_visibility(cx: &mut TestAppContext) {
8919 use crate::WindowVisibility;
8920
8921 let window = cx.add_window(|_, _| EmptyView);
8922 let observed = Rc::new(RefCell::new(Vec::new()));
8923 let _subscription = window
8924 .update(cx, {
8925 let observed = observed.clone();
8926 move |_, window, _| {
8927 assert_eq!(window.visibility(), WindowVisibility::Visible);
8928 assert!(window.is_visible());
8929 window.observe_window_visibility(move |visibility, window, _| {
8930 assert_eq!(window.visibility(), visibility);
8931 observed.borrow_mut().push(visibility);
8932 })
8933 }
8934 })
8935 .unwrap();
8936 let test_window = cx.test_window(window.into());
8937 let frame_wake_count = test_window.frame_wake_count();
8938
8939 test_window.simulate_visibility_change(WindowVisibility::Hidden);
8940 assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
8941 window
8942 .update(cx, |_, window, _| assert!(!window.is_visible()))
8943 .unwrap();
8944
8945 test_window.simulate_visibility_change(WindowVisibility::Hidden);
8947 assert_eq!(observed.borrow().len(), 1);
8948
8949 test_window.simulate_visibility_change(WindowVisibility::Visible);
8950 assert_eq!(
8951 *observed.borrow(),
8952 [WindowVisibility::Hidden, WindowVisibility::Visible]
8953 );
8954 window
8955 .update(cx, |_, window, _| assert!(window.is_visible()))
8956 .unwrap();
8957 assert_eq!(test_window.frame_wake_count(), frame_wake_count);
8958 }
8959
8960 #[gpui::test]
8963 fn test_display_tracking(cx: &mut TestAppContext) {
8964 use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
8965
8966 let sixty_hertz = Duration::from_secs(1) / 60;
8967 let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
8968 let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
8969
8970 let display_events = Rc::new(RefCell::new(Vec::new()));
8971 let _display_subscription = cx.update({
8972 let display_events = display_events.clone();
8973 move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
8974 });
8975
8976 let window = cx.add_window(|window, cx| DisplayTracker {
8977 refresh_intervals: Vec::new(),
8978 _subscription: cx.observe_window_display(
8979 window,
8980 |tracker: &mut DisplayTracker, window, cx| {
8981 tracker.refresh_intervals.push(window.refresh_interval(cx));
8982 },
8983 ),
8984 });
8985 let window_notifications = Rc::new(RefCell::new(Vec::new()));
8986 let _window_subscription = window
8987 .update(cx, {
8988 let window_notifications = window_notifications.clone();
8989 move |_, window, cx| {
8990 assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
8991 window.observe_window_display(move |window, cx| {
8992 window_notifications
8993 .borrow_mut()
8994 .push((window.display_id, window.refresh_interval(cx)));
8995 })
8996 }
8997 })
8998 .unwrap();
8999 let test_window = cx.test_window(window.into());
9000
9001 cx.test_platform()
9006 .connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
9007 test_window.simulate_move_to_display(DisplayId(2));
9008 assert_eq!(
9009 window_notifications.take(),
9010 [(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
9011 );
9012 assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
9013 cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
9014 assert!(window_notifications.borrow().is_empty());
9015
9016 test_window.simulate_move_to_display(DisplayId(2));
9018 assert!(window_notifications.borrow().is_empty());
9019
9020 cx.simulate_display_refresh_interval_change(
9021 DisplayId(2),
9022 Some(one_hundred_forty_four_hertz),
9023 );
9024 assert_eq!(
9025 window_notifications.take(),
9026 [(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
9027 );
9028
9029 cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
9031 cx.simulate_display_removed(DisplayId(1));
9032 assert!(window_notifications.borrow().is_empty());
9033
9034 assert_eq!(
9035 display_events.take(),
9036 [
9037 DisplayEvent::Changed {
9038 id: DisplayId(2),
9039 changes: DisplayChanges::REFRESH_INTERVAL,
9040 },
9041 DisplayEvent::Changed {
9042 id: DisplayId(1),
9043 changes: DisplayChanges::REFRESH_INTERVAL,
9044 },
9045 DisplayEvent::Removed(DisplayId(1)),
9046 ]
9047 );
9048 window
9049 .update(cx, |tracker, _, _| {
9050 assert_eq!(
9051 tracker.refresh_intervals,
9052 [
9053 Some(one_hundred_twenty_hertz),
9054 Some(one_hundred_forty_four_hertz)
9055 ]
9056 );
9057 })
9058 .unwrap();
9059
9060 struct DisplayTracker {
9061 refresh_intervals: Vec<Option<Duration>>,
9062 _subscription: Subscription,
9063 }
9064
9065 impl Render for DisplayTracker {
9066 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9067 Empty
9068 }
9069 }
9070 }
9071
9072 #[gpui::test]
9073 fn test_window_opened_from_bounds_observer_uses_new_bounds(cx: &mut TestAppContext) {
9074 use crate::Subscription;
9075
9076 struct BoundsObserver {
9077 _subscription: Subscription,
9078 }
9079
9080 impl Render for BoundsObserver {
9081 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9082 Empty
9083 }
9084 }
9085
9086 let opened_window = Rc::new(Cell::new(None));
9087 let window = cx.add_window({
9088 let opened_window = opened_window.clone();
9089 move |window, cx| BoundsObserver {
9090 _subscription: cx.observe_window_bounds(window, move |_, _, cx| {
9091 let handle = cx
9092 .open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
9093 .unwrap();
9094 opened_window.set(Some(AnyWindowHandle::from(handle)));
9095 }),
9096 }
9097 });
9098 window
9099 .update(cx, |_, window, _| window.activate_window())
9100 .unwrap();
9101
9102 let new_size = size(px(400.), px(300.));
9103 cx.simulate_window_resize(window.into(), new_size);
9104
9105 let opened_window = opened_window
9106 .take()
9107 .expect("bounds observer should have opened a window");
9108 let opened_size = opened_window
9109 .update(cx, |_, window, _| window.bounds().size)
9110 .unwrap();
9111 assert_eq!(opened_size, new_size);
9112 }
9113
9114 #[gpui::test]
9115 fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
9116 let window = cx.add_window(|_, _| EmptyView);
9117 let mut platform_window = cx.test_window(window.into());
9118 platform_window.simulate_resize(size(px(400.), px(800.)));
9119 window
9120 .update(cx, |_, window, _| {
9121 assert_eq!(
9122 window.visual_viewport_bounds(),
9123 Bounds::new(Point::default(), size(px(400.), px(800.)))
9124 );
9125 assert_eq!(
9126 window.fully_visible_bounds(),
9127 window.visual_viewport_bounds()
9128 );
9129 })
9130 .unwrap();
9131
9132 platform_window.simulate_frame_request(RequestFrameOptions::default());
9133 let wakes = platform_window.frame_wake_count();
9134 let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
9135 platform_window.simulate_visual_viewport_change(visual_bounds);
9136 assert!(platform_window.frame_wake_count() > wakes);
9137 platform_window.simulate_frame_request(RequestFrameOptions::default());
9138 let wakes = platform_window.frame_wake_count();
9139 let insets = crate::WindowInsets {
9140 safe_area: crate::Edges {
9141 top: px(60.),
9142 right: px(20.),
9143 bottom: px(30.),
9144 left: px(-10.),
9145 },
9146 ime: crate::Edges {
9147 bottom: px(350.),
9148 ..Default::default()
9149 },
9150 ..Default::default()
9151 };
9152 platform_window.simulate_insets_change(insets.clone());
9153 assert!(platform_window.frame_wake_count() > wakes);
9154 window
9155 .update(cx, |_, window, cx| {
9156 let focus = cx.focus_handle();
9157 window.focus(&focus, cx);
9158 assert_eq!(window.insets(), insets);
9159 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
9160 assert_eq!(window.visual_viewport_bounds(), visual_bounds);
9161 assert_eq!(
9162 window.fully_visible_bounds(),
9163 Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
9164 );
9165 window.request_virtual_keyboard();
9166 window.dismiss_virtual_keyboard();
9167 assert!(focus.is_focused(window));
9168 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
9169 })
9170 .unwrap();
9171 assert_eq!(platform_window.virtual_keyboard_requests(), 1);
9172 assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
9173
9174 platform_window.simulate_insets_change(crate::WindowInsets {
9175 safe_area: crate::Edges {
9176 top: px(900.),
9177 left: px(500.),
9178 ..Default::default()
9179 },
9180 ..Default::default()
9181 });
9182 window
9183 .update(cx, |_, window, _| {
9184 assert_eq!(
9185 window.fully_visible_bounds().size,
9186 size(Pixels::ZERO, Pixels::ZERO)
9187 );
9188 })
9189 .unwrap();
9190
9191 use crate::PlatformWindow as _;
9193 platform_window.on_insets_changed(Box::new(|_| {}));
9194 platform_window.simulate_insets_change(crate::WindowInsets::default());
9195 window
9196 .update(cx, |_, window, _| {
9197 assert_eq!(window.insets(), crate::WindowInsets::default());
9198 })
9199 .unwrap();
9200 }
9201
9202 #[test]
9203 fn frame_throttle_tracks_display_refreshes() {
9204 let start = super::Instant::now();
9205 for (elapsed, interval) in [
9206 (Duration::from_micros(16_666), Duration::from_micros(16_667)),
9207 (Duration::from_micros(33_332), Duration::from_micros(33_333)),
9208 ] {
9209 let mut pacer = super::FramePacer::default();
9210 assert!(!pacer.should_defer(start, Some(interval)));
9211 assert!(pacer.should_defer(start + elapsed / 2, Some(interval)));
9212 assert!(!pacer.should_defer(start + elapsed, Some(interval)));
9213 }
9214 }
9215
9216 #[test]
9217 fn frame_throttle_preserves_cadence_without_catching_up_after_stalls() {
9218 let start = super::Instant::now();
9219 let interval = Duration::from_micros(33_333);
9220 let mut pacer = super::FramePacer::default();
9221 assert!(!pacer.should_defer(start, Some(interval)));
9222 let delayed_frame = start + interval + Duration::from_millis(5);
9223 assert!(!pacer.should_defer(delayed_frame, Some(interval)));
9224 assert!(pacer.should_defer(start + interval + interval / 2, Some(interval)));
9225 assert!(!pacer.should_defer(start + interval * 2, Some(interval)));
9226
9227 let after_stall = start + interval * 4 - Duration::from_millis(1);
9229 assert!(!pacer.should_defer(after_stall, Some(interval)));
9230 assert!(pacer.should_defer(after_stall + interval / 2, Some(interval)));
9231 assert!(!pacer.should_defer(after_stall + interval, Some(interval)));
9232 let mandatory_frame = after_stall + interval + Duration::from_millis(2);
9234 assert!(!pacer.should_defer(mandatory_frame, None));
9235 assert!(pacer.should_defer(mandatory_frame + interval / 2, Some(interval)));
9236 }
9237
9238 #[test]
9239 fn power_modes_preserve_frame_limits() {
9240 let options = WindowOptions::default();
9241 for (power_mode, active_interval, thermal_interval) in [
9242 (
9243 crate::PowerMode::LowPower,
9244 Some(Duration::from_micros(33_333)),
9245 Duration::from_micros(33_333),
9246 ),
9247 (
9248 crate::PowerMode::Unknown,
9249 None,
9250 Duration::from_micros(16_667),
9251 ),
9252 (
9253 crate::PowerMode::Balanced,
9254 None,
9255 Duration::from_micros(16_667),
9256 ),
9257 (
9258 crate::PowerMode::HighPower,
9259 None,
9260 Duration::from_micros(16_667),
9261 ),
9262 ] {
9263 assert_eq!(
9264 super::minimum_frame_interval(
9265 true,
9266 false,
9267 options.inactive_frame_interval,
9268 options.low_power_frame_interval,
9269 options.thermal_frame_interval,
9270 ThermalState::Nominal,
9271 power_mode,
9272 ),
9273 active_interval,
9274 );
9275 assert_eq!(
9276 super::minimum_frame_interval(
9277 true,
9278 false,
9279 options.inactive_frame_interval,
9280 options.low_power_frame_interval,
9281 options.thermal_frame_interval,
9282 ThermalState::Serious,
9283 power_mode,
9284 ),
9285 Some(thermal_interval),
9286 );
9287 }
9288 }
9289
9290 #[test]
9291 fn frame_limits_combine_enabled_intervals() {
9292 let short = Some(Duration::from_millis(10));
9293 let long = Some(Duration::from_millis(100));
9294 for (inactive, low_power, thermal, expected) in [
9295 (long, short, short, long),
9296 (short, long, short, long),
9297 (short, short, long, long),
9298 (long, None, None, long),
9299 (None, long, None, long),
9300 (None, None, long, long),
9301 (None, None, None, None),
9302 ] {
9303 assert_eq!(
9304 super::minimum_frame_interval(
9305 true,
9306 true,
9307 inactive,
9308 low_power,
9309 thermal,
9310 ThermalState::Critical,
9311 crate::PowerMode::LowPower,
9312 ),
9313 expected,
9314 );
9315 }
9316 assert_eq!(
9317 super::minimum_frame_interval(
9318 false,
9319 true,
9320 long,
9321 long,
9322 long,
9323 ThermalState::Critical,
9324 crate::PowerMode::LowPower,
9325 ),
9326 None,
9327 );
9328 }
9329
9330 struct EmptyView;
9331
9332 impl Render for EmptyView {
9333 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9334 div()
9335 }
9336 }
9337
9338 struct OpensWindowOnPaint {
9339 opened: Rc<Cell<bool>>,
9340 }
9341
9342 impl Render for OpensWindowOnPaint {
9343 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9344 let opened = self.opened.clone();
9345 div()
9346 .size_full()
9347 .child(canvas(
9348 |_, _, _| {},
9349 move |_, _, _window, cx| {
9350 if !opened.replace(true) {
9351 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
9352 .unwrap();
9353 }
9354 },
9355 ))
9356 .child(div().child("after"))
9360 }
9361 }
9362
9363 #[test]
9369 fn test_window_opened_during_draw_defers_arena_clear() {
9370 let mut cx = TestAppContext::single();
9371
9372 let opened = Rc::new(Cell::new(false));
9373 let window = cx.add_window({
9375 let opened = opened.clone();
9376 move |_, _| OpensWindowOnPaint { opened }
9377 });
9378
9379 assert!(opened.get());
9380 assert_eq!(cx.windows().len(), 2);
9381
9382 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
9385 .unwrap();
9386 }
9387
9388 #[test]
9389 fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
9390 let mut cx = TestAppContext::single();
9391 let window = cx.add_window(|_, _| EmptyView);
9392 let handle: AnyWindowHandle = window.into();
9393 let window_state = |cx: &mut TestAppContext| {
9394 cx.update_window(handle, |_, window, _| {
9395 (
9396 window.scale_factor(),
9397 window.bounds(),
9398 window.viewport_size(),
9399 )
9400 })
9401 .unwrap()
9402 };
9403
9404 let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
9405 assert_eq!(scale_factor, 2.0);
9406
9407 for (scale_factor, resized_size) in [
9408 (1.0, size(px(800.), px(600.))),
9409 (1.25, size(px(640.), px(480.))),
9410 (2.0, size(px(1024.), px(768.))),
9411 ] {
9412 cx.simulate_window_scale_factor_change(handle, scale_factor);
9413 assert_eq!(
9414 window_state(&mut cx),
9415 (scale_factor, expected_bounds, expected_bounds.size)
9416 );
9417
9418 cx.simulate_window_resize(handle, resized_size);
9419 expected_bounds.size = resized_size;
9420 assert_eq!(
9421 window_state(&mut cx),
9422 (scale_factor, expected_bounds, resized_size)
9423 );
9424 }
9425 }
9426
9427 #[gpui::test]
9428 fn test_fullscreen_toggle_reports_current_bounds(cx: &mut TestAppContext) {
9429 let window = cx.add_window(|_, _| EmptyView);
9430 let handle = AnyWindowHandle::from(window);
9431 let notifications = Rc::new(Cell::new(0));
9432 window
9433 .update(cx, {
9434 let notifications = notifications.clone();
9435 |_, window, cx| {
9436 cx.observe_window_bounds(window, move |_, _, _| {
9437 notifications.set(notifications.get() + 1)
9438 })
9439 .detach();
9440 }
9441 })
9442 .unwrap();
9443 let window_state = |cx: &mut TestAppContext| {
9444 cx.update_window(handle, |_, window, _| {
9445 (
9446 window.is_fullscreen(),
9447 window.bounds().size,
9448 window.viewport_size(),
9449 )
9450 })
9451 .unwrap()
9452 };
9453 let initial_size = window_state(cx).1;
9454
9455 window
9456 .update(cx, |_, window, _| window.toggle_fullscreen())
9457 .unwrap();
9458 cx.run_until_parked();
9459 assert_eq!(window_state(cx), (true, initial_size, initial_size));
9460 assert_eq!(notifications.get(), 1);
9461
9462 let resized_size = size(px(800.), px(600.));
9463 window
9464 .update(cx, |_, window, _| window.toggle_fullscreen())
9465 .unwrap();
9466 cx.simulate_window_resize(handle, resized_size);
9467 cx.run_until_parked();
9468 assert_eq!(window_state(cx), (false, resized_size, resized_size));
9469 }
9470
9471 #[gpui::test]
9476 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
9477 let window = cx.add_window(|_, _| EmptyView);
9478 let test_window = cx.test_window(window.into());
9479 test_window.simulate_active_status_change(true);
9481
9482 assert!(
9486 test_window.frame_wake_count() >= 1,
9487 "opening a window must wake the frame source for the initial frame"
9488 );
9489
9490 test_window.simulate_frame_request(RequestFrameOptions::default());
9492
9493 let baseline = test_window.frame_wake_count();
9496 test_window.simulate_frame_request(RequestFrameOptions::default());
9497 window.update(cx, |_, _, _| {}).unwrap();
9498 assert_eq!(
9499 test_window.frame_wake_count(),
9500 baseline,
9501 "clean frames and non-notifying updates must not wake the frame source"
9502 );
9503
9504 window.update(cx, |_, _, cx| cx.notify()).unwrap();
9506 assert!(
9507 test_window.frame_wake_count() > baseline,
9508 "notifying a view in an idle window must wake the frame source"
9509 );
9510
9511 test_window.simulate_frame_request(RequestFrameOptions::default());
9513 let baseline = test_window.frame_wake_count();
9514 test_window.simulate_frame_request(RequestFrameOptions::default());
9515 assert_eq!(
9516 test_window.frame_wake_count(),
9517 baseline,
9518 "serving demand must return the window to idle"
9519 );
9520
9521 window
9523 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
9524 .unwrap();
9525 assert!(
9526 test_window.frame_wake_count() > baseline,
9527 "scheduling a next-frame callback in an idle window must wake the frame source"
9528 );
9529 }
9530
9531 #[gpui::test]
9536 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
9537 let window = cx.add_window(|_, _| EmptyView);
9538 let test_window = cx.test_window(window.into());
9539 test_window.simulate_frame_request(RequestFrameOptions::default());
9542
9543 let callback_ran = Rc::new(Cell::new(false));
9544 window
9545 .update(cx, {
9546 let callback_ran = callback_ran.clone();
9547 move |_, window, _| {
9548 window.on_next_frame(move |_, _| callback_ran.set(true));
9549 }
9550 })
9551 .unwrap();
9552
9553 let baseline = test_window.frame_wake_count();
9554 test_window.simulate_frame_request(RequestFrameOptions::default());
9555 assert!(
9562 test_window.frame_wake_count() > baseline || callback_ran.get(),
9563 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
9564 );
9565 }
9566
9567 #[gpui::test]
9568 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
9569 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
9570
9571 let window = cx.add_window(|_, _| EmptyView);
9572 window
9573 .update(cx, |_, window, _| {
9574 assert!(matches!(
9575 window.window_handle(),
9576 Err(HandleError::NotSupported)
9577 ));
9578 assert!(matches!(
9579 window.display_handle(),
9580 Err(HandleError::NotSupported)
9581 ));
9582 })
9583 .unwrap();
9584 }
9585
9586 #[gpui::test]
9587 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
9588 let window = cx.add_window(|_, _| EmptyView);
9589 let observed_appearance = Rc::new(Cell::new(None));
9590 let _subscription = window
9591 .update(cx, {
9592 let observed_appearance = observed_appearance.clone();
9593 move |_, window, _| {
9594 window.observe_window_appearance(move |window, _| {
9595 observed_appearance.set(Some(window.appearance()));
9596 })
9597 }
9598 })
9599 .unwrap();
9600 let test_window = cx.test_window(window.into());
9601
9602 cx.update(|_| {
9603 test_window.simulate_appearance_change(WindowAppearance::Dark);
9604 assert_eq!(observed_appearance.get(), None);
9605 });
9606 cx.run_until_parked();
9607
9608 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
9609 }
9610
9611 #[gpui::test]
9612 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
9613 let window = cx.add_window(|_, _| Empty);
9614 let test_window = cx.test_window(window.into());
9615
9616 assert!(test_window.simulate_scheduled_frame());
9617 assert!(test_window.simulate_scheduled_frame());
9618 assert!(!test_window.frame_scheduled());
9619
9620 cx.update_window(window.into(), |_, window, _| {
9621 window.active.set(true);
9622 window.on_next_frame(|_, _| {});
9623 })
9624 .unwrap();
9625 assert!(
9626 test_window.frame_scheduled(),
9627 "queuing work on a parked window must wake the render loop"
9628 );
9629
9630 assert!(test_window.simulate_scheduled_frame());
9631 assert!(
9632 test_window.frame_scheduled(),
9633 "presenting the frame must await one compositor callback"
9634 );
9635 assert!(test_window.simulate_scheduled_frame());
9636 assert!(!test_window.frame_scheduled());
9637 }
9638
9639 #[gpui::test]
9640 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
9641 let window = cx.add_window(|_, _| Empty);
9642 let test_window = cx.test_window(window.into());
9643
9644 assert!(test_window.simulate_scheduled_frame());
9645 assert!(test_window.simulate_scheduled_frame());
9646 assert!(!test_window.frame_scheduled());
9647
9648 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
9649 .unwrap();
9650
9651 assert!(
9652 test_window.frame_scheduled(),
9653 "a rendered scene awaiting presentation must wake the render loop"
9654 );
9655 }
9656
9657 #[gpui::test]
9658 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
9659 let window = cx.add_window(|_, _| Empty);
9660 let test_window = cx.test_window(window.into());
9661
9662 let callback_ran = Rc::new(Cell::new(false));
9663 cx.update_window(window.into(), |_, window, _| {
9664 window.active.set(true);
9667 let callback_ran = callback_ran.clone();
9668 window.on_next_frame(move |window, _| {
9669 window.on_next_frame(move |_, _| callback_ran.set(true));
9670 });
9671 })
9672 .unwrap();
9673
9674 assert!(test_window.simulate_scheduled_frame());
9675 assert!(!callback_ran.get());
9676 assert!(
9677 test_window.frame_scheduled(),
9678 "a callback queued mid-frame must schedule a follow-up before the loop parks"
9679 );
9680
9681 assert!(test_window.simulate_scheduled_frame());
9682 assert!(callback_ran.get());
9683 }
9684
9685 struct RootView {
9686 explicit_size: bool,
9687 child_bounds: Rc<Cell<Bounds<Pixels>>>,
9688 }
9689
9690 impl Render for RootView {
9691 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9692 let child_bounds = self.child_bounds.clone();
9693 let root = div().flex().flex_col().child(
9694 canvas(
9695 move |bounds, _, _| child_bounds.set(bounds),
9696 |_, _, _, _| {},
9697 )
9698 .size_full(),
9699 );
9700 if self.explicit_size {
9701 root.w(px(300.)).h(px(200.))
9702 } else {
9703 root
9704 }
9705 }
9706 }
9707
9708 #[test]
9709 fn auto_sized_window_root_fills_the_window() {
9710 let mut cx = TestAppContext::single();
9711 let child_bounds = Rc::new(Cell::new(Bounds::default()));
9712 let window = cx.add_window({
9713 let child_bounds = child_bounds.clone();
9714 move |_, _| RootView {
9715 explicit_size: false,
9716 child_bounds,
9717 }
9718 });
9719
9720 let viewport_size = cx
9721 .update_window(window.into(), |_, window, cx| {
9722 window.draw(cx).clear(cx);
9723 window.viewport_size()
9724 })
9725 .unwrap();
9726
9727 assert_eq!(child_bounds.get().size, viewport_size);
9728 }
9729
9730 #[test]
9731 fn explicitly_sized_window_root_keeps_its_size() {
9732 let mut cx = TestAppContext::single();
9733 let child_bounds = Rc::new(Cell::new(Bounds::default()));
9734 let window = cx.add_window({
9735 let child_bounds = child_bounds.clone();
9736 move |_, _| RootView {
9737 explicit_size: true,
9738 child_bounds,
9739 }
9740 });
9741
9742 cx.update_window(window.into(), |_, window, cx| {
9743 window.draw(cx).clear(cx);
9744 })
9745 .unwrap();
9746
9747 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
9748 }
9749
9750 struct FileDragView {
9751 path: PathBuf,
9752 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
9753 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
9754 }
9755
9756 struct FileDropExitView(Rc<Cell<usize>>);
9757
9758 impl Render for FileDropExitView {
9759 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9760 div().size_full().on_file_drop_exit({
9761 let observed_file_drop_exit = self.0.clone();
9762 move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
9763 })
9764 }
9765 }
9766
9767 impl Render for FileDragView {
9768 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9769 div()
9770 .id("file-drag")
9771 .size_full()
9772 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
9773 .external_drag_payload(|path: &PathBuf, _, _| {
9774 Some(ExternalDragPayload::Files(FileDragPaths::new([(
9775 path.clone(),
9776 true,
9777 )])))
9778 })
9779 .on_drag_move({
9780 let observed_drag_moves = self.observed_drag_moves.clone();
9781 move |event: &DragMoveEvent<PathBuf>, _, _| {
9782 observed_drag_moves.borrow_mut().push(event.event.position);
9783 }
9784 })
9785 .on_drop({
9786 let observed_drops = self.observed_drops.clone();
9787 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
9788 })
9789 }
9790 }
9791
9792 #[gpui::test]
9793 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
9794 struct Drag {
9795 window: AnyWindowHandle,
9796 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
9797 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
9798 }
9799
9800 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
9801 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
9802 let observed_drops = Rc::new(RefCell::new(Vec::new()));
9803 let window: AnyWindowHandle = cx
9804 .add_window({
9805 let observed_drag_moves = observed_drag_moves.clone();
9806 let observed_drops = observed_drops.clone();
9807 move |_, _| FileDragView {
9808 path,
9809 observed_drag_moves,
9810 observed_drops,
9811 }
9812 })
9813 .into();
9814 cx.test_window(window)
9815 .set_start_external_drag_result(platform_result);
9816
9817 let update_result = cx.update_window(window, |_, window, cx| {
9818 window.draw(cx).clear(cx);
9819 window.dispatch_event(
9820 MouseDownEvent {
9821 position: point(px(10.), px(10.)),
9822 button: MouseButton::Left,
9823 modifiers: Default::default(),
9824 click_count: 1,
9825 first_mouse: false,
9826 }
9827 .to_platform_input(),
9828 cx,
9829 );
9830 window.dispatch_event(
9831 MouseMoveEvent {
9832 position: point(px(20.), px(20.)),
9833 pressed_button: Some(MouseButton::Left),
9834 modifiers: Default::default(),
9835 }
9836 .to_platform_input(),
9837 cx,
9838 );
9839 assert!(cx.active_drag.is_some());
9840 });
9841 assert!(
9842 update_result.is_ok(),
9843 "failed to start drag: {update_result:?}"
9844 );
9845
9846 assert!(cx.test_window(window).external_drag_files().is_empty());
9847 Drag {
9848 window,
9849 observed_drag_moves,
9850 observed_drops,
9851 }
9852 }
9853
9854 let successful_path = PathBuf::from("/tmp/successful-drag");
9855 let successful = start_drag(cx, successful_path.clone(), true);
9856 let outside_position = point(px(-1.), px(20.));
9857 let update_result = cx.update_window(successful.window, |_, window, cx| {
9858 window.dispatch_event(
9859 MouseMoveEvent {
9860 position: outside_position,
9861 pressed_button: Some(MouseButton::Left),
9862 modifiers: Default::default(),
9863 }
9864 .to_platform_input(),
9865 cx,
9866 );
9867 assert!(cx.active_drag.is_none());
9868 });
9869 assert!(
9870 update_result.is_ok(),
9871 "failed to promote drag: {update_result:?}"
9872 );
9873 assert_eq!(
9874 cx.test_window(successful.window).external_drag_files(),
9875 [(successful_path.clone(), true)]
9876 );
9877 assert_eq!(
9880 successful.observed_drag_moves.borrow().last(),
9881 Some(&outside_position)
9882 );
9883
9884 let first_destination_exit_count = Rc::new(Cell::new(0));
9885 let first_destination: AnyWindowHandle = cx
9886 .add_window({
9887 let first_destination_exit_count = first_destination_exit_count.clone();
9888 move |_, _| FileDropExitView(first_destination_exit_count)
9889 })
9890 .into();
9891 let second_destination_exit_count = Rc::new(Cell::new(0));
9892 let second_destination: AnyWindowHandle = cx
9893 .add_window({
9894 let second_destination_exit_count = second_destination_exit_count.clone();
9895 move |_, _| FileDropExitView(second_destination_exit_count)
9896 })
9897 .into();
9898 let reentry_position = point(px(30.), px(30.));
9899 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
9900 let update_result = cx.update_window(first_destination, |_, window, cx| {
9901 window.draw(cx).clear(cx);
9902 window.dispatch_event(
9903 FileDropEvent::Entered {
9904 position: reentry_position,
9905 paths: external_paths(),
9906 }
9907 .to_platform_input(),
9908 cx,
9909 );
9910 assert!(
9911 cx.active_drag
9912 .as_ref()
9913 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9914 );
9915 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9916 assert!(cx.active_drag.is_none());
9917 assert_eq!(first_destination_exit_count.get(), 1);
9918 assert_eq!(second_destination_exit_count.get(), 0);
9919 });
9920 assert!(
9921 update_result.is_ok(),
9922 "failed to handle drag in first destination window: {update_result:?}"
9923 );
9924
9925 let update_result = cx.update_window(second_destination, |_, window, cx| {
9926 window.draw(cx).clear(cx);
9927 window.dispatch_event(
9928 PlatformInput::KeyDown(KeyDownEvent {
9929 keystroke: Keystroke::parse("down").expect("valid keystroke"),
9930 is_held: false,
9931 prefer_character_input: false,
9932 }),
9933 cx,
9934 );
9935 window.dispatch_event(
9936 FileDropEvent::Entered {
9937 position: reentry_position,
9938 paths: external_paths(),
9939 }
9940 .to_platform_input(),
9941 cx,
9942 );
9943 assert!(
9944 cx.active_drag
9945 .as_ref()
9946 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9947 );
9948 assert_eq!(first_destination_exit_count.get(), 1);
9949 assert_eq!(second_destination_exit_count.get(), 0);
9950
9951 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9952 assert!(cx.active_drag.is_none());
9953 assert_eq!(first_destination_exit_count.get(), 1);
9954 assert_eq!(second_destination_exit_count.get(), 1);
9955 });
9956 assert!(
9957 update_result.is_ok(),
9958 "failed to handle drag in second destination window: {update_result:?}"
9959 );
9960
9961 let update_result = cx.update_window(successful.window, |_, window, cx| {
9962 window.dispatch_event(
9963 FileDropEvent::Entered {
9964 position: reentry_position,
9965 paths: external_paths(),
9966 }
9967 .to_platform_input(),
9968 cx,
9969 );
9970 assert!(
9971 cx.active_drag
9972 .as_ref()
9973 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9974 );
9975 assert_eq!(
9976 successful.observed_drag_moves.borrow().last(),
9977 Some(&reentry_position)
9978 );
9979
9980 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9981 assert!(cx.active_drag.is_none());
9982
9983 window.dispatch_event(
9984 FileDropEvent::Entered {
9985 position: reentry_position,
9986 paths: external_paths(),
9987 }
9988 .to_platform_input(),
9989 cx,
9990 );
9991 assert!(
9992 cx.active_drag
9993 .as_ref()
9994 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9995 );
9996
9997 window.dispatch_event(
9998 FileDropEvent::Submit {
9999 position: reentry_position,
10000 }
10001 .to_platform_input(),
10002 cx,
10003 );
10004 assert_eq!(
10005 successful.observed_drops.borrow().as_slice(),
10006 std::slice::from_ref(&successful_path)
10007 );
10008 assert!(cx.active_drag.is_none());
10009
10010 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
10011 assert!(cx.active_drag.is_none());
10012 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
10013 assert!(cx.active_drag.is_none());
10014
10015 window.dispatch_event(
10016 FileDropEvent::Entered {
10017 position: reentry_position,
10018 paths: external_paths(),
10019 }
10020 .to_platform_input(),
10021 cx,
10022 );
10023 assert!(
10024 cx.active_drag
10025 .as_ref()
10026 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
10027 );
10028 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
10029 });
10030 assert!(
10031 update_result.is_ok(),
10032 "failed to restore drag in source window: {update_result:?}"
10033 );
10034
10035 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
10036 let cancelled = start_drag(cx, cancelled_path.clone(), true);
10037 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
10038 window.dispatch_event(
10039 MouseMoveEvent {
10040 position: outside_position,
10041 pressed_button: Some(MouseButton::Left),
10042 modifiers: Default::default(),
10043 }
10044 .to_platform_input(),
10045 cx,
10046 );
10047 assert!(cx.active_drag.is_none());
10048
10049 window.dispatch_event(
10050 FileDropEvent::Entered {
10051 position: reentry_position,
10052 paths: ExternalPaths([cancelled_path].into_iter().collect()),
10053 }
10054 .to_platform_input(),
10055 cx,
10056 );
10057 assert!(
10058 cx.active_drag
10059 .as_ref()
10060 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
10061 );
10062 assert!(cx.stop_active_drag(window));
10063 assert!(cx.active_drag.is_none());
10064 });
10065 assert!(
10066 update_result.is_ok(),
10067 "failed to cancel restored drag: {update_result:?}"
10068 );
10069 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
10070
10071 let removed_path = PathBuf::from("/tmp/removed-window-drag");
10072 let removed = start_drag(cx, removed_path, true);
10073 let removed_window_id = removed.window.window_id();
10074 let update_result = cx.update_window(removed.window, |_, window, cx| {
10075 window.dispatch_event(
10076 MouseMoveEvent {
10077 position: outside_position,
10078 pressed_button: Some(MouseButton::Left),
10079 modifiers: Default::default(),
10080 }
10081 .to_platform_input(),
10082 cx,
10083 );
10084 assert!(cx.active_drag.is_none());
10085 window.remove_window();
10086 });
10087 assert!(
10088 update_result.is_ok(),
10089 "failed to remove drag source window: {update_result:?}"
10090 );
10091 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
10092
10093 let failed_path = PathBuf::from("/tmp/failed-drag");
10094 let failed = start_drag(cx, failed_path.clone(), false);
10095 let update_result = cx.update_window(failed.window, |_, window, cx| {
10096 for x_position in [-1., -2.] {
10097 window.dispatch_event(
10098 MouseMoveEvent {
10099 position: point(px(x_position), px(20.)),
10100 pressed_button: Some(MouseButton::Left),
10101 modifiers: Default::default(),
10102 }
10103 .to_platform_input(),
10104 cx,
10105 );
10106 }
10107 assert!(cx.active_drag.is_some());
10108 });
10109 assert!(
10110 update_result.is_ok(),
10111 "failed to retain drag after platform failure: {update_result:?}"
10112 );
10113 assert_eq!(
10114 cx.test_window(failed.window).external_drag_files(),
10115 [(failed_path, true)]
10116 );
10117 }
10118
10119 struct FocusForwarder {
10120 a: FocusHandle,
10121 b: FocusHandle,
10122 }
10123
10124 impl Render for FocusForwarder {
10125 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10126 div()
10127 .size_full()
10128 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
10129 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
10130 }
10131 }
10132
10133 #[gpui::test]
10137 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
10138 let b_focus_count = Rc::new(Cell::new(0));
10139 let window = cx.add_window({
10140 let b_focus_count = b_focus_count.clone();
10141 move |window, cx| {
10142 let a = cx.focus_handle();
10143 let b = cx.focus_handle();
10144 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
10145 let b = this.b.clone();
10146 window.focus(&b, cx);
10147 })
10148 .detach();
10149 cx.on_focus(&b, window, move |_, _, _| {
10150 b_focus_count.set(b_focus_count.get() + 1);
10151 })
10152 .detach();
10153 FocusForwarder { a, b }
10154 }
10155 });
10156
10157 window
10158 .update(cx, |_, window, _| window.activate_window())
10159 .unwrap();
10160 cx.executor().run_until_parked();
10161
10162 window
10163 .update(cx, |this, window, cx| {
10164 let a = this.a.clone();
10165 window.focus(&a, cx);
10166 })
10167 .unwrap();
10168 cx.executor().run_until_parked();
10169
10170 window
10171 .update(cx, |this, window, _| {
10172 assert!(this.b.is_focused(window));
10173 })
10174 .unwrap();
10175 assert_eq!(b_focus_count.get(), 1);
10176 }
10177
10178 #[gpui::test]
10179 fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
10180 let events = Rc::new(RefCell::new(Vec::new()));
10181 let window = cx.add_window({
10182 let events = events.clone();
10183 move |_, _| TouchDragListener { events }
10184 });
10185 let touch = TouchId(1);
10186
10187 dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
10188 dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
10189 dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
10190
10191 assert_eq!(
10192 events.borrow().as_slice(),
10193 [
10194 (TouchPhase::Started, px(10.)),
10195 (TouchPhase::Moved, px(30.)),
10196 (TouchPhase::Ended, px(40.)),
10197 ]
10198 );
10199 }
10200
10201 #[gpui::test]
10202 fn back_gesture_is_claimed_by_the_innermost_listener(cx: &mut TestAppContext) {
10203 let claims = Rc::new(RefCell::new(Vec::new()));
10204 let window = cx.add_window({
10205 let claims = claims.clone();
10206 move |_, _| BackListeners { claims }
10207 });
10208 let dispatch_back = |cx: &mut TestAppContext, x: f32| {
10209 window
10210 .update(cx, |_, window, cx| {
10211 window
10212 .dispatch_event(
10213 BackGestureEvent {
10214 phase: BackGesturePhase::Started,
10215 start_position: point(px(x), px(10.)),
10216 progress: 0.,
10217 }
10218 .to_platform_input(),
10219 cx,
10220 )
10221 .default_prevented
10222 })
10223 .unwrap()
10224 };
10225 assert!(dispatch_back(cx, 10.));
10226 assert!(dispatch_back(cx, 80.));
10227 assert!(!dispatch_back(cx, 150.));
10228 assert_eq!(claims.borrow().as_slice(), ["inner", "outer"]);
10229 }
10230
10231 struct BackListeners {
10232 claims: Rc<RefCell<Vec<&'static str>>>,
10233 }
10234
10235 impl Render for BackListeners {
10236 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
10237 let claim = |name: &'static str| {
10238 let claims = self.claims.clone();
10239 move |_: &BackGestureEvent, _: &mut Window, _: &mut crate::App| {
10240 claims.borrow_mut().push(name)
10241 }
10242 };
10243 div().size_full().child(
10244 div()
10245 .w(px(100.))
10246 .h_full()
10247 .on_back_gesture(claim("outer"))
10248 .child(div().w(px(50.)).h_full().on_back_gesture(claim("inner"))),
10249 )
10250 }
10251 }
10252
10253 struct TouchDragListener {
10254 events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
10255 }
10256
10257 impl Render for TouchDragListener {
10258 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
10259 let events = self.events.clone();
10260 canvas(
10261 |_, _, _| {},
10262 move |_, _, window, _| {
10263 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
10264 if phase != DispatchPhase::Bubble {
10265 return;
10266 }
10267 events.borrow_mut().push((event.phase, event.position.x));
10268 if event.phase == TouchPhase::Started {
10269 window.prevent_default();
10270 }
10271 });
10272 },
10273 )
10274 }
10275 }
10276
10277 #[gpui::test]
10278 fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
10279 for response in [
10280 LongPressResponse::PreventDefault,
10281 LongPressResponse::StopPropagation,
10282 LongPressResponse::None,
10283 ] {
10284 let phases = Rc::new(RefCell::new(Vec::new()));
10285 let window = cx.add_window({
10286 let phases = phases.clone();
10287 move |_, _| LongPressListener { phases, response }
10288 });
10289 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
10290 cx.executor().advance_clock(Duration::from_millis(501));
10291 cx.executor().run_until_parked();
10292 window
10293 .update(cx, |_, window, _| {
10294 assert_eq!(
10295 window.long_press_capture.is_some(),
10296 response == LongPressResponse::PreventDefault
10297 );
10298 })
10299 .unwrap();
10300 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
10301 dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
10302 window
10303 .update(cx, |_, window, _| {
10304 assert!(window.long_press_capture.is_none());
10305 })
10306 .unwrap();
10307
10308 let phases = phases.borrow();
10309 if response == LongPressResponse::PreventDefault {
10310 assert_eq!(
10311 phases.as_slice(),
10312 [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
10313 );
10314 } else {
10315 assert_eq!(phases.as_slice(), [TouchPhase::Started]);
10316 }
10317 }
10318 }
10319
10320 #[gpui::test]
10321 fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
10322 let phases = Rc::new(RefCell::new(Vec::new()));
10323 let window = cx.add_window({
10324 let phases = phases.clone();
10325 move |_, _| LongPressListener {
10326 phases,
10327 response: LongPressResponse::None,
10328 }
10329 });
10330 window
10331 .update(cx, |_, window, _| {
10332 window.prevent_default();
10333 })
10334 .unwrap();
10335
10336 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
10337 cx.executor().advance_clock(Duration::from_millis(501));
10338 cx.executor().run_until_parked();
10339 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
10340
10341 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
10342 }
10343
10344 #[gpui::test]
10345 fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
10346 for (phase, position) in [
10347 (TouchPhase::Ended, 0.),
10348 (TouchPhase::Cancelled, 0.),
10349 (TouchPhase::Moved, 20.),
10350 ] {
10351 let phases = Rc::new(RefCell::new(Vec::new()));
10352 let window = cx.add_window({
10353 let phases = phases.clone();
10354 move |_, _| LongPressListener {
10355 phases,
10356 response: LongPressResponse::PreventDefault,
10357 }
10358 });
10359 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
10360 dispatch_touch(window, cx, TouchId(1), phase, position);
10361 cx.executor().advance_clock(Duration::from_millis(501));
10362 cx.executor().run_until_parked();
10363
10364 assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
10365 }
10366 }
10367
10368 #[gpui::test]
10369 fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
10370 let phases = Rc::new(RefCell::new(Vec::new()));
10371 let window = cx.add_window({
10372 let phases = phases.clone();
10373 move |_, _| LongPressListener {
10374 phases,
10375 response: LongPressResponse::PreventDefault,
10376 }
10377 });
10378 let first_touch = TouchId(1);
10379 dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
10380 cx.executor().advance_clock(Duration::from_millis(250));
10381 dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
10382 dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
10383
10384 cx.executor().advance_clock(Duration::from_millis(251));
10385 cx.executor().run_until_parked();
10386 assert!(phases.borrow().is_empty());
10387
10388 cx.executor().advance_clock(Duration::from_millis(250));
10389 cx.executor().run_until_parked();
10390 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
10391 }
10392
10393 #[gpui::test]
10394 fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
10395 test_paint_at_scales(cx, |window| {
10396 let (numerator, denominator) = match window.scale_factor() {
10397 1.0 => (1, 1),
10398 1.25 => (5, 4),
10399 1.5 => (3, 2),
10400 2.0 => (2, 1),
10401 3.0 => (3, 1),
10402 scale => panic!("unexpected scale {scale}"),
10403 };
10404 let snap = |quarters: i32| {
10405 let scaled = quarters * numerator;
10406 let divisor = 4 * denominator;
10407 let rounded =
10408 scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
10409 ScaledPixels((scaled.signum() * rounded) as f32)
10410 };
10411 let stroke = |quarters| {
10412 if quarters == 0 {
10413 ScaledPixels(0.)
10414 } else {
10415 snap(quarters).max(ScaledPixels(1.))
10416 }
10417 };
10418
10419 for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
10420 for width in [0, 1, 3, 84] {
10421 for thickness in [0, 1, 4, 7] {
10422 for wavy in [false, true] {
10423 let style = UnderlineStyle {
10424 thickness: px(thickness as f32 / 4.),
10425 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
10426 wavy,
10427 };
10428 let bounds = Bounds::new(
10429 point(snap(origin), snap(-origin)),
10430 size(
10431 stroke(width),
10432 stroke(thickness) * if wavy { 3. } else { 1. },
10433 ),
10434 );
10435 let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
10436 let width = px(width as f32 / 4.);
10437 assert_eq!(window.underline_bounds(origin, width, &style), bounds);
10438 let original = paint_test_underlines(window, |window| {
10439 window.paint_underline(origin, width, &style);
10440 })
10441 .to_vec();
10442 assert_eq!(original.len(), usize::from(!bounds.is_empty()));
10443 if let Some(underline) = original.first() {
10444 assert_eq!(underline.bounds, bounds);
10445 assert_eq!(underline.thickness, stroke(thickness));
10446 assert_eq!(underline.wavy, wavy.into());
10447 assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
10448 }
10449
10450 let underlines = paint_test_underlines(window, |window| {
10451 window.paint_underline_with_exclusions(origin, width, &style, &[]);
10452 });
10453 assert_eq!(underlines.len(), original.len());
10454 for (actual, original) in underlines.iter().zip(&original) {
10455 assert_same_underline_geometry(actual, original);
10456 assert_eq!(actual.content_mask, original.content_mask);
10457 }
10458
10459 let left = bounds.left().0 as i32;
10460 let right = bounds.right().0 as i32;
10461 let exclusions = [
10462 (15, 25),
10463 (3, 7),
10464 (5, 10),
10465 (10, 12),
10466 (0, 0),
10467 (4, 2),
10468 (-50, -1),
10469 (70, 100),
10470 ]
10471 .map(|(start, end)| {
10472 ScaledPixels((left + start) as f32)
10473 ..ScaledPixels((left + end) as f32)
10474 });
10475 let underlines = paint_test_underlines(window, |window| {
10476 window.paint_underline_with_exclusions(
10477 origin,
10478 width,
10479 &style,
10480 &exclusions,
10481 );
10482 });
10483 let expected = (left..right)
10484 .filter(|column| {
10485 !bounds.is_empty()
10486 && !exclusions.iter().any(|span| {
10487 span.contains(&ScaledPixels(*column as f32))
10488 })
10489 })
10490 .collect::<Vec<_>>();
10491 assert_eq!(underline_device_columns(underlines), expected);
10492 for underline in underlines {
10493 assert_same_underline_geometry(underline, &original[0]);
10494 }
10495 }
10496 }
10497 }
10498 }
10499 });
10500 }
10501
10502 #[gpui::test]
10503 fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
10504 test_paint_at_scales(cx, |window| {
10505 if window.scale_factor() != 2.0 {
10506 return;
10507 }
10508 let style = UnderlineStyle {
10509 thickness: px(1.),
10510 color: None,
10511 wavy: true,
10512 };
10513 let origin = point(px(2.888_183_8), px(15.357_917));
10514 let width = px(23.848_145) - origin.x;
10515 let original = paint_test_underlines(window, |window| {
10516 window.paint_underline(origin, width, &style);
10517 })[0];
10518 assert_eq!(original.bounds.left(), ScaledPixels(6.));
10519 assert_eq!(original.bounds.right(), ScaledPixels(48.));
10520 let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
10521 assert_eq!(point_bounds.left(), ScaledPixels(6.));
10522 assert_eq!(point_bounds.right(), ScaledPixels(28.));
10523
10524 let underlines = paint_test_underlines(window, |window| {
10525 window.paint_underline_with_exclusions(
10526 origin,
10527 width,
10528 &style,
10529 &[point_bounds.left()..point_bounds.right()],
10530 );
10531 });
10532 assert_eq!(underlines.len(), 1);
10533 assert_same_underline_geometry(&underlines[0], &original);
10534 assert_eq!(
10535 underline_device_columns(underlines),
10536 (28..48).collect::<Vec<_>>()
10537 );
10538 });
10539 }
10540
10541 #[gpui::test]
10542 fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
10543 test_paint_at_scales(cx, |window| {
10544 let scale = window.scale_factor();
10545 let original_mask = window.content_mask();
10546 let original_opacity = window.element_opacity();
10547 let mask = ContentMask {
10548 bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
10549 };
10550 let style = UnderlineStyle {
10551 thickness: px(2.),
10552 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
10553 wavy: true,
10554 };
10555 let origin = point(px(-1.25), px(9.25));
10556 let width = px(24.);
10557 window.with_content_mask(Some(mask), |window| {
10558 window.with_element_opacity(Some(0.5), |window| {
10559 window.with_element_opacity(Some(0.5), |window| {
10560 let original = paint_test_underlines(window, |window| {
10561 window.paint_underline(origin, width, &style);
10562 })[0];
10563 assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
10564 let underlines = paint_test_underlines(window, |window| {
10565 window.paint_underline_with_exclusions(
10566 origin,
10567 width,
10568 &style,
10569 &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
10570 );
10571 });
10572 assert_eq!(underlines.len(), 2);
10573 let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
10574 |(left, right)| {
10575 Bounds::from_corners(
10576 point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
10577 point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
10578 )
10579 },
10580 );
10581 assert_eq!(
10582 underlines
10583 .iter()
10584 .map(|underline| underline.content_mask.bounds)
10585 .collect::<Vec<_>>(),
10586 expected
10587 );
10588 for underline in underlines {
10589 assert_same_underline_geometry(underline, &original);
10590 }
10591 });
10592 });
10593 });
10594 assert_eq!(window.content_mask(), original_mask);
10595 assert_eq!(window.element_opacity(), original_opacity);
10596 });
10597 }
10598
10599 #[gpui::test]
10600 fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
10601 test_paint_at_scales(cx, |window| {
10602 let style = UnderlineStyle {
10603 thickness: px(1.),
10604 color: None,
10605 wavy: true,
10606 };
10607 let origin = point(px(-4.), px(-1.));
10608 let width = px(8.);
10609 let left = (-4. * window.scale_factor()) as i32;
10610 let right = (4. * window.scale_factor()) as i32;
10611 let endpoints = [-16, -8, -1, 0, 1, 8, 16];
10612 for first_start in endpoints {
10613 for first_end in endpoints {
10614 for second_start in endpoints {
10615 for second_end in endpoints {
10616 let exclusions = [first_start..first_end, second_start..second_end];
10617 let expected = (left..right)
10618 .filter(|column| {
10619 !exclusions.iter().any(|span| span.contains(column))
10620 })
10621 .collect::<Vec<_>>();
10622 let exclusions = exclusions.map(|span| {
10623 ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
10624 });
10625 let underlines = paint_test_underlines(window, |window| {
10626 window.paint_underline_with_exclusions(
10627 origin,
10628 width,
10629 &style,
10630 &exclusions,
10631 );
10632 });
10633 assert_eq!(
10634 underline_device_columns(underlines),
10635 expected,
10636 "{exclusions:?}"
10637 );
10638 }
10639 }
10640 }
10641 }
10642 });
10643 }
10644
10645 #[gpui::test]
10646 fn test_empty_content_masks_remain_empty_when_snapped(cx: &mut TestAppContext) {
10647 test_paint_at_scales(cx, |window| {
10648 let viewport = ContentMask {
10649 bounds: Bounds::from_corners(point(px(20.), px(20.)), point(px(100.), px(100.))),
10650 };
10651 for fraction in [0., 0.25, 0.5, 0.75] {
10652 for bounds in [
10653 Bounds::new(point(px(30.), px(120. + fraction)), size(px(40.), px(20.))),
10654 Bounds::new(point(px(120. + fraction), px(30.)), size(px(20.), px(40.))),
10655 Bounds::new(
10656 point(px(120. + fraction), px(120. + fraction)),
10657 size(px(20.), px(20.)),
10658 ),
10659 Bounds::new(
10660 point(px(30. + fraction), px(40. + fraction)),
10661 size(px(0.), px(20.)),
10662 ),
10663 Bounds::new(
10664 point(px(30. + fraction), px(40. + fraction)),
10665 size(px(20.), px(0.)),
10666 ),
10667 ] {
10668 window.with_content_mask(Some(viewport), |window| {
10669 window.with_content_mask(Some(ContentMask { bounds }), |window| {
10670 assert!(window.content_mask().bounds.is_empty());
10671 assert!(
10672 window.snapped_content_mask().bounds.is_empty(),
10673 "scale={}, bounds={bounds:?}",
10674 window.scale_factor(),
10675 );
10676 let count = window.next_frame.scene.len();
10677 window.paint_quad(crate::fill(bounds, crate::red()));
10678 window.paint_quad(crate::outline(
10679 bounds,
10680 crate::red(),
10681 Default::default(),
10682 ));
10683 assert_eq!(window.next_frame.scene.len(), count);
10684 });
10685 });
10686 }
10687 }
10688 });
10689 }
10690
10691 #[gpui::test]
10692 fn test_nonempty_content_masks_keep_covering_fractional_edges(cx: &mut TestAppContext) {
10693 test_paint_at_scales(cx, |window| {
10694 let bounds = Bounds::new(point(px(30.25), px(40.25)), size(px(0.125), px(0.125)));
10695 window.with_content_mask(Some(ContentMask { bounds }), |window| {
10696 let snapped = window.snapped_content_mask().bounds;
10697 let scale = window.scale_factor();
10698 assert_eq!(snapped, window.cover_bounds(bounds));
10699 assert!(!snapped.is_empty());
10700 assert_eq!(snapped.left().0, (30.25 * scale).floor());
10701 assert_eq!(snapped.top().0, (40.25 * scale).floor());
10702 assert_eq!(snapped.right().0, (30.375 * scale).ceil());
10703 assert_eq!(snapped.bottom().0, (40.375 * scale).ceil());
10704 });
10705 });
10706 }
10707
10708 #[gpui::test]
10709 fn test_empty_shadow_bounds_are_not_painted(cx: &mut TestAppContext) {
10710 test_paint_at_scales(cx, |window| {
10711 let shadow = crate::BoxShadow::new(px(0.25), px(0.5), crate::red()).blur_radius(px(4.));
10712 for origin in [point(px(30.25), px(40.25)), point(px(-30.25), px(-40.25))] {
10713 for size in [
10714 size(px(20.), px(0.)),
10715 size(px(0.), px(20.)),
10716 size(px(0.), px(0.)),
10717 ] {
10718 let bounds = Bounds::new(origin, size);
10719 let count = window.next_frame.scene.len();
10720 window.paint_drop_shadows(
10721 bounds,
10722 Default::default(),
10723 std::slice::from_ref(&shadow),
10724 );
10725 assert_eq!(
10726 window.next_frame.scene.len(),
10727 count,
10728 "scale={}, bounds={bounds:?}",
10729 window.scale_factor()
10730 );
10731 assert!(window.cover_bounds(bounds).is_empty());
10732 }
10733 }
10734 let bounds = Bounds::new(point(px(30.25), px(40.25)), size(px(20.), px(20.)));
10735 let collapsed_shadow = shadow.clone().spread_radius(px(-10.));
10736 let shape_bounds =
10737 (bounds + collapsed_shadow.offset).dilate(collapsed_shadow.spread_radius);
10738 let count = window.next_frame.scene.len();
10739 window.paint_drop_shadows(bounds, Default::default(), &[collapsed_shadow]);
10740 assert_eq!(window.next_frame.scene.len(), count);
10741 assert!(window.cover_bounds(shape_bounds).is_empty());
10742
10743 window.paint_drop_shadows(bounds, Default::default(), &[shadow]);
10744 assert_eq!(window.next_frame.scene.len(), count + 1);
10745 });
10746 }
10747
10748 #[gpui::test]
10749 fn test_collapsed_inset_shadow_hole_is_an_empty_point_on_the_pixel_grid(
10750 cx: &mut TestAppContext,
10751 ) {
10752 test_paint_at_scales(cx, |window| {
10753 let bounds = Bounds::new(point(px(30.25), px(40.25)), size(px(20.), px(20.)));
10754 for blur_radius in [px(0.), px(4.)] {
10755 for spread_radius in [px(10.), px(12.3), px(15.), px(30.)] {
10756 let shadow = crate::BoxShadow::new(px(0.), px(0.), crate::red())
10757 .blur_radius(blur_radius)
10758 .spread_radius(spread_radius)
10759 .inset();
10760 window.next_frame.scene.clear();
10761 window.paint_inset_shadows(bounds, Default::default(), &[shadow]);
10762 let shadows = &window.next_frame.scene.shadows;
10763 assert_eq!(shadows.len(), 1);
10764 let hole = shadows[0].shape_bounds;
10765 let message = format!(
10766 "scale={}, blur={blur_radius:?}, spread={spread_radius:?}, hole={hole:?}",
10767 window.scale_factor()
10768 );
10769 assert_eq!(hole.size, crate::Size::default(), "{message}");
10770 assert_eq!(hole.origin.x.0.fract(), 0., "{message}");
10771 assert_eq!(hole.origin.y.0.fract(), 0., "{message}");
10772 }
10773 }
10774 });
10775 }
10776
10777 struct PaintTestView(Rc<dyn Fn(&mut Window)>);
10778
10779 impl Render for PaintTestView {
10780 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10781 let paint = self.0.clone();
10782 canvas(
10783 |_, _, _| {},
10784 move |_, _, window, _| {
10785 window.content_mask_stack.push(ContentMask {
10786 bounds: Bounds::from_corners(
10787 point(px(-1000.), px(-1000.)),
10788 point(px(1000.), px(1000.)),
10789 ),
10790 });
10791 paint(window);
10792 window.content_mask_stack.pop();
10793 },
10794 )
10795 .size_full()
10796 }
10797 }
10798
10799 fn test_paint_at_scales(cx: &mut TestAppContext, paint: impl Fn(&mut Window) + 'static) {
10800 let window = cx.add_window(move |_, _| PaintTestView(Rc::new(paint)));
10801 for scale in [1., 1.25, 1.5, 2., 3.] {
10802 cx.simulate_window_scale_factor_change(window.into(), scale);
10803 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
10804 .unwrap();
10805 }
10806 }
10807
10808 #[derive(Clone, Copy, PartialEq)]
10809 enum LongPressResponse {
10810 PreventDefault,
10811 StopPropagation,
10812 None,
10813 }
10814
10815 struct LongPressListener {
10816 phases: Rc<RefCell<Vec<TouchPhase>>>,
10817 response: LongPressResponse,
10818 }
10819
10820 impl Render for LongPressListener {
10821 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
10822 let entity = cx.entity();
10823 let phases = self.phases.clone();
10824 let response = self.response;
10825 canvas(
10826 |_, _, _| {},
10827 move |_, _, window, _| {
10828 window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
10829 if phase != DispatchPhase::Bubble {
10830 return;
10831 }
10832 phases.borrow_mut().push(event.phase);
10833 match response {
10834 LongPressResponse::PreventDefault => {
10835 window.capture_long_press(&entity);
10836 window.prevent_default();
10837 }
10838 LongPressResponse::StopPropagation => cx.stop_propagation(),
10839 LongPressResponse::None => {}
10840 }
10841 });
10842 },
10843 )
10844 }
10845 }
10846
10847 fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
10848 window.next_frame.scene.clear();
10849 paint(window);
10850 &window.next_frame.scene.underlines
10851 }
10852
10853 fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
10854 assert_eq!(actual.bounds, expected.bounds);
10855 assert_eq!(actual.thickness, expected.thickness);
10856 assert_eq!(actual.wavy, expected.wavy);
10857 assert_eq!(actual.color, expected.color);
10858 assert_eq!(actual.pad, expected.pad);
10859 }
10860
10861 fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
10862 underlines
10863 .iter()
10864 .flat_map(|underline| {
10865 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
10866 bounds.left().0 as i32..bounds.right().0 as i32
10867 })
10868 .collect()
10869 }
10870
10871 actions!(window_test, [StandaloneModifierAction]);
10872
10873 struct StandaloneModifierView {
10874 focus_handle: FocusHandle,
10875 action_count: usize,
10876 }
10877
10878 impl Render for StandaloneModifierView {
10879 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
10880 div()
10881 .key_context("StandaloneModifier")
10882 .track_focus(&self.focus_handle)
10883 .on_action(cx.listener(|this, _: &StandaloneModifierAction, _, _| {
10884 this.action_count += 1;
10885 }))
10886 }
10887 }
10888
10889 #[gpui::test]
10890 fn test_standalone_modifier_sequence_timeout_and_recovery(cx: &mut TestAppContext) {
10891 use crate::{KeyBinding, Modifiers};
10892
10893 cx.update(|cx| {
10894 cx.bind_keys([KeyBinding::new(
10895 "shift shift",
10896 StandaloneModifierAction,
10897 Some("StandaloneModifier"),
10898 )]);
10899 });
10900 let (view, cx) = cx.add_window_view(|window, cx| {
10901 let focus_handle = cx.focus_handle();
10902 window.focus(&focus_handle, cx);
10903 StandaloneModifierView {
10904 focus_handle,
10905 action_count: 0,
10906 }
10907 });
10908 let shift = Modifiers {
10909 shift: true,
10910 ..Modifiers::default()
10911 };
10912 cx.simulate_modifiers_change(shift);
10913 cx.simulate_modifiers_change(Modifiers::default());
10914 cx.update(|window, _| {
10915 assert_eq!(
10916 window.pending_input_keystrokes(),
10917 Some([Keystroke::parse("shift").expect("valid keystroke")].as_slice())
10918 );
10919 });
10920 cx.background_executor.advance_clock(Duration::from_secs(2));
10921 cx.run_until_parked();
10922 cx.update(|window, cx| {
10923 assert!(!window.has_pending_keystrokes());
10924 assert_eq!(view.read(cx).action_count, 0);
10925 });
10926
10927 cx.simulate_modifiers_change(shift);
10928 cx.simulate_modifiers_change(Modifiers::default());
10929 cx.update(|window, cx| {
10930 assert!(window.has_pending_keystrokes());
10931 assert_eq!(view.read(cx).action_count, 0);
10932 });
10933
10934 cx.simulate_modifiers_change(shift);
10935 cx.simulate_modifiers_change(Modifiers::default());
10936 cx.update(|window, cx| {
10937 assert!(!window.has_pending_keystrokes());
10938 assert_eq!(view.read(cx).action_count, 1);
10939 });
10940 }
10941
10942 #[gpui::test]
10943 fn test_standalone_modifier_sequence_dispatches_before_timeout(cx: &mut TestAppContext) {
10944 use crate::{KeyBinding, Modifiers};
10945
10946 cx.update(|cx| {
10947 cx.bind_keys([KeyBinding::new(
10948 "shift shift",
10949 StandaloneModifierAction,
10950 Some("StandaloneModifier"),
10951 )]);
10952 });
10953 let (view, cx) = cx.add_window_view(|window, cx| {
10954 let focus_handle = cx.focus_handle();
10955 window.focus(&focus_handle, cx);
10956 StandaloneModifierView {
10957 focus_handle,
10958 action_count: 0,
10959 }
10960 });
10961 let shift = Modifiers {
10962 shift: true,
10963 ..Modifiers::default()
10964 };
10965 cx.simulate_modifiers_change(shift);
10966 cx.simulate_modifiers_change(Modifiers::default());
10967 cx.background_executor
10968 .advance_clock(Duration::from_millis(500));
10969 cx.update(|window, cx| {
10970 assert!(window.has_pending_keystrokes());
10971 assert_eq!(view.read(cx).action_count, 0);
10972 });
10973 cx.simulate_modifiers_change(shift);
10974 cx.simulate_modifiers_change(Modifiers::default());
10975 cx.update(|window, cx| {
10976 assert!(!window.has_pending_keystrokes());
10977 assert_eq!(view.read(cx).action_count, 1);
10978 });
10979 cx.background_executor.advance_clock(Duration::from_secs(2));
10980 cx.run_until_parked();
10981 cx.update(|window, cx| {
10982 assert!(!window.has_pending_keystrokes());
10983 assert_eq!(view.read(cx).action_count, 1);
10984 });
10985 }
10986
10987 fn dispatch_touch<T: 'static>(
10988 window: crate::WindowHandle<T>,
10989 cx: &mut TestAppContext,
10990 id: TouchId,
10991 phase: TouchPhase,
10992 x: f32,
10993 ) {
10994 window
10995 .update(cx, |_, window, cx| {
10996 window.dispatch_event(
10997 TouchEvent {
10998 id,
10999 phase,
11000 position: point(px(x), px(0.)),
11001 predicted_position: None,
11002 force: None,
11003 }
11004 .to_platform_input(),
11005 cx,
11006 );
11007 })
11008 .unwrap();
11009 }
11010
11011 #[gpui::test]
11012 fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
11013 struct Child {
11014 renders: usize,
11015 }
11016
11017 impl Render for Child {
11018 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
11019 self.renders += 1;
11020 div().size_full().bg(crate::rgb(0xff0000))
11021 }
11022 }
11023
11024 struct Root {
11025 opacity: f32,
11026 width: Pixels,
11027 child: crate::Entity<Child>,
11028 }
11029
11030 impl Render for Root {
11031 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
11032 div()
11033 .w(self.width)
11034 .h(px(200.))
11035 .opacity(self.opacity)
11036 .hover(|style| style.opacity(1.))
11037 .child(
11038 self.child
11039 .clone()
11040 .cached(crate::StyleRefinement::default().size(px(100.))),
11041 )
11042 }
11043 }
11044
11045 fn update_and_draw(
11048 window: crate::WindowHandle<Root>,
11049 child: &crate::Entity<Child>,
11050 cx: &mut TestAppContext,
11051 update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
11052 ) -> (f32, usize) {
11053 window
11054 .update(cx, |root, window, cx| {
11055 update(root, window, cx);
11056 cx.notify();
11057 })
11058 .expect("update root");
11059 for _ in 0..3 {
11060 let (alpha, renders, requested_frames) = cx
11061 .update_window(window.into(), |_, window, cx| {
11062 window.draw(cx).clear(cx);
11063 let quads = &window.rendered_frame.scene.quads;
11064 assert_eq!(quads.len(), 1);
11065 let alpha = quads.first().expect("child quad").background.solid.a;
11066 (
11067 alpha,
11068 child.read(cx).renders,
11069 window.simulate_next_frame(cx),
11070 )
11071 })
11072 .expect("draw window");
11073 if requested_frames == 0 {
11074 return (alpha, renders);
11075 }
11076 }
11077 panic!("cached child kept requesting frames");
11078 }
11079
11080 let child = cx.new(|_| Child { renders: 0 });
11081 let window = cx.add_window(|_, _| Root {
11082 opacity: 1.,
11083 width: px(200.),
11084 child: child.clone(),
11085 });
11086 let outside = point(px(500.), px(500.));
11087 let inside = point(px(50.), px(50.));
11088 let beside = point(px(250.), px(50.));
11089
11090 let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
11092 window.simulate_mouse_move(outside, cx)
11093 };
11094 assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
11095 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
11096 let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
11097 assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
11098 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
11099
11100 let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
11102 window.simulate_mouse_move(inside, cx)
11103 };
11104 assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
11105 let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
11106 window.simulate_mouse_move(beside, cx)
11107 };
11108 assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
11109
11110 let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
11113 assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
11114 }
11115
11116 #[gpui::test]
11117 fn test_drag_cursor_applies_before_next_paint(cx: &mut TestAppContext) {
11118 struct ResizeHandle;
11119
11120 impl Render for ResizeHandle {
11121 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
11122 div().size_full().cursor_text().child(
11123 div()
11124 .id("resize-handle")
11125 .w(px(4.))
11126 .h_full()
11127 .cursor_col_resize()
11128 .on_drag((), |_, _, _, cx| cx.new(|_| Empty)),
11129 )
11130 }
11131 }
11132
11133 let window = cx.add_window(|_, _| ResizeHandle);
11134 let handle_position = point(px(1.), px(10.));
11135 let drag_position = point(px(20.), px(10.));
11136 let cursor_observer = cx.clone();
11137
11138 let update_result = cx.update_window(window.into(), |_, window, cx| {
11139 window.hovered.set(true);
11140 window.active.set(true);
11141 window.draw(cx).clear(cx);
11142 window.dispatch_event(
11143 MouseMoveEvent {
11144 position: handle_position,
11145 ..Default::default()
11146 }
11147 .to_platform_input(),
11148 cx,
11149 );
11150 window.dispatch_event(
11151 MouseDownEvent {
11152 position: handle_position,
11153 button: MouseButton::Left,
11154 ..Default::default()
11155 }
11156 .to_platform_input(),
11157 cx,
11158 );
11159 window.dispatch_event(
11160 MouseMoveEvent {
11161 position: drag_position,
11162 pressed_button: Some(MouseButton::Left),
11163 ..Default::default()
11164 }
11165 .to_platform_input(),
11166 cx,
11167 );
11168 assert!(cx.has_active_drag());
11169 assert_eq!(
11171 cursor_observer.test_platform().cursor_style(),
11172 CursorStyle::ResizeColumn
11173 );
11174
11175 window.draw(cx).clear(cx);
11176 window.dispatch_event(
11177 MouseUpEvent {
11178 position: drag_position,
11179 button: MouseButton::Left,
11180 ..Default::default()
11181 }
11182 .to_platform_input(),
11183 cx,
11184 );
11185 window.draw(cx).clear(cx);
11186 });
11187 assert!(
11188 update_result.is_ok(),
11189 "failed to run drag: {update_result:?}"
11190 );
11191 assert_eq!(
11192 cursor_observer.test_platform().cursor_style(),
11193 CursorStyle::IBeam
11194 );
11195 }
11196}
11197
11198#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
11199mod inspector_tests {
11200 use super::*;
11201 use crate::{
11202 DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
11203 };
11204
11205 #[gpui::test]
11206 fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
11207 let windows = [
11208 cx.add_window(|_, cx| InspectorTestRoot {
11209 child: cx.new(|_| InspectorTestView::default()),
11210 }),
11211 cx.add_window(|_, cx| InspectorTestRoot {
11212 child: cx.new(|_| InspectorTestView::default()),
11213 }),
11214 ];
11215 for window in windows {
11216 assert_closed_inspector(window.into(), cx);
11217 }
11218 for _ in 0..2 {
11219 cx.update_window(windows[0].into(), |root, window, cx| {
11220 let root = root.downcast::<InspectorTestRoot>().expect("test root");
11221 let child_widths = root.read(cx).child.read(cx).child_widths.clone();
11222 window.toggle_inspector(cx);
11223 window.draw(cx).clear(cx);
11224 assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
11225 let path = window
11226 .rendered_frame
11227 .next_inspector_instance_ids
11228 .iter()
11229 .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
11230 .expect("anonymous siblings share an inspector path");
11231 let selected_id = InspectorElementId {
11232 path,
11233 instance_id: 1,
11234 };
11235 let position = window
11236 .rendered_frame
11237 .hitboxes
11238 .iter()
11239 .find(|hitbox| {
11240 window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
11241 == Some(&selected_id)
11242 })
11243 .expect("middle sibling is pickable")
11244 .bounds
11245 .center();
11246 window.simulate_mouse_move(position, cx);
11247 window.dispatch_event(
11248 PlatformInput::MouseDown(MouseDownEvent {
11249 position,
11250 button: MouseButton::Left,
11251 modifiers: Modifiers::default(),
11252 click_count: 1,
11253 first_mouse: false,
11254 }),
11255 cx,
11256 );
11257 window.dispatch_event(
11258 PlatformInput::MouseUp(MouseUpEvent {
11259 position,
11260 button: MouseButton::Left,
11261 modifiers: Modifiers::default(),
11262 click_count: 1,
11263 }),
11264 cx,
11265 );
11266 assert!(!window.is_inspector_picking(cx));
11267 assert_eq!(
11268 window
11269 .inspector
11270 .as_ref()
11271 .expect("open inspector")
11272 .read(cx)
11273 .active_element_id(),
11274 Some(&selected_id)
11275 );
11276 window.draw(cx).clear(cx);
11277 window.with_inspector_state::<DivInspectorState, _>(
11278 Some(&selected_id),
11279 cx,
11280 |state, _| {
11281 let state = state.as_mut().expect("selected div has style state");
11282 assert_eq!(
11283 state.base_style.size.width,
11284 Some(crate::Length::from(px(10.)))
11285 );
11286 state.base_style.size.width = Some(crate::Length::from(px(25.)));
11287 },
11288 );
11289 window.refresh();
11290 window.draw(cx).clear(cx);
11291 assert_eq!(
11292 child_widths.borrow().as_slice(),
11293 &[px(10.), px(25.), px(10.)]
11294 );
11295 })
11296 .expect("pick and edit a cached child");
11297 assert_closed_inspector(windows[1].into(), cx);
11298 windows[0]
11299 .update(cx, |_, window, cx| window.toggle_inspector(cx))
11300 .expect("close inspector");
11301 assert_closed_inspector(windows[0].into(), cx);
11302 }
11303 }
11304
11305 struct InspectorTestRoot {
11306 child: Entity<InspectorTestView>,
11307 }
11308
11309 impl Render for InspectorTestRoot {
11310 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
11311 self.child
11312 .clone()
11313 .cached(StyleRefinement::default().size(px(100.)))
11314 }
11315 }
11316
11317 #[derive(Default)]
11318 struct InspectorTestView {
11319 child_widths: Rc<RefCell<Vec<Pixels>>>,
11320 }
11321
11322 impl Render for InspectorTestView {
11323 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
11324 let child_widths = self.child_widths.clone();
11325 div()
11326 .on_children_prepainted(move |bounds, _, _| {
11327 *child_widths.borrow_mut() =
11328 bounds.iter().map(|bounds| bounds.size.width).collect();
11329 })
11330 .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
11331 .id("inspector-root")
11332 .flex()
11333 .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
11334 }
11335 }
11336
11337 fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
11338 cx.update_window(window, |root, window, cx| {
11339 window.draw(cx).clear(cx);
11340 window.draw(cx).clear(cx);
11341 let root = root.downcast::<InspectorTestRoot>().expect("test root");
11342 assert_eq!(
11343 root.read(cx)
11344 .child
11345 .read(cx)
11346 .child_widths
11347 .borrow()
11348 .as_slice(),
11349 &[px(10.); 3]
11350 );
11351 for frame in [&window.rendered_frame, &window.next_frame] {
11352 assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
11353 assert_eq!(frame.inspector_hitboxes.capacity(), 0);
11354 }
11355 })
11356 .expect("closed inspector has no bookkeeping and no style overrides");
11357 }
11358}