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