1#[cfg(feature = "profiler")]
3use crate::DebugFrameOverlayMode;
4#[cfg(any(feature = "inspector", debug_assertions))]
5use crate::Inspector;
6#[cfg(feature = "profiler")]
7use crate::profiler;
8use crate::subscription::SingleSubscriberSet;
9use crate::taffy::TaffyLayoutEngine;
10use crate::{
11 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
12 AsyncWindowContext, AtlasTile, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow,
13 Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,
14 DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
15 EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
16 Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent,
17 Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent,
18 MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels,
19 PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
20 PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams,
21 RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
22 ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubpixelSprite,
23 Subscription, SystemWindowTab, SystemWindowTabController, TabStopMap, Task,
24 TextInputConfiguration, TextInputStateChange, TextRenderingMode, TextStyle,
25 TextStyleRefinement, ThermalState, TransformationMatrix, Underline, UnderlineStyle,
26 WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations,
27 WindowInsets, WindowOptions, WindowParams, WindowTextSystem, WindowVisibility, point,
28 prelude::*, px, rems, size, transparent_black,
29};
30
31use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
32use crate::interactive::TouchEvent;
33use anyhow::{Context as _, Result, anyhow};
34use collections::{FxHashMap, FxHashSet};
35use derive_more::{Deref, DerefMut};
36use futures::channel::oneshot;
37use gpui_util::post_inc;
38use gpui_util::{ResultExt, measure};
39use itertools::FoldWhile::{Continue, Done};
40use itertools::Itertools;
41#[cfg(any(target_os = "macos", target_os = "ios"))]
42use objc2_core_foundation::CFRetained;
43#[cfg(any(target_os = "macos", target_os = "ios"))]
44use objc2_core_video::CVPixelBuffer;
45use parking_lot::{RwLock, RwLockUpgradableReadGuard};
46use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
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
125pub(crate) struct 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)]
144pub(crate) struct FrameDirtyAccumulator {
145 dirty_at: Option<Instant>,
146 invalidations: u64,
147}
148
149#[derive(Clone)]
150pub(crate) struct WindowInvalidator {
151 pub(crate) 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
346fn 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 dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
638 if let Some(node_id) = window
639 .rendered_frame
640 .dispatch_tree
641 .focusable_node_id(self.id)
642 {
643 window.dispatch_action_on_node(node_id, action, cx)
644 }
645 }
646}
647
648impl Clone for FocusHandle {
649 fn clone(&self) -> Self {
650 Self::for_id(self.id, &self.handles).unwrap()
651 }
652}
653
654impl PartialEq for FocusHandle {
655 fn eq(&self, other: &Self) -> bool {
656 self.id == other.id
657 }
658}
659
660impl Eq for FocusHandle {}
661
662impl Drop for FocusHandle {
663 fn drop(&mut self) {
664 let handles = self.handles.upgradable_read();
665 let focus = handles.handles.get(self.id).expect("focus handle missing");
666 let previous_count = focus.ref_count.fetch_sub(1, SeqCst);
667 assert_ne!(previous_count, 0, "over-released focus handle");
668 if previous_count == 1 {
669 RwLockUpgradableReadGuard::upgrade(handles)
670 .dropped_handles
671 .push(self.id);
672 }
673 }
674}
675
676#[derive(Clone, Debug)]
678pub struct WeakFocusHandle {
679 pub(crate) id: FocusId,
680 pub(crate) handles: Weak<RwLock<FocusMap>>,
681}
682
683impl WeakFocusHandle {
684 pub fn upgrade(&self) -> Option<FocusHandle> {
686 let handles = self.handles.upgrade()?;
687 FocusHandle::for_id(self.id, &handles)
688 }
689}
690
691impl PartialEq for WeakFocusHandle {
692 fn eq(&self, other: &WeakFocusHandle) -> bool {
693 self.id == other.id
694 }
695}
696
697impl Eq for WeakFocusHandle {}
698
699impl PartialEq<FocusHandle> for WeakFocusHandle {
700 fn eq(&self, other: &FocusHandle) -> bool {
701 self.id == other.id
702 }
703}
704
705impl PartialEq<WeakFocusHandle> for FocusHandle {
706 fn eq(&self, other: &WeakFocusHandle) -> bool {
707 self.id == other.id
708 }
709}
710
711pub trait Focusable: 'static {
714 fn focus_handle(&self, cx: &App) -> FocusHandle;
716}
717
718impl<V: Focusable> Focusable for Entity<V> {
719 fn focus_handle(&self, cx: &App) -> FocusHandle {
720 self.read(cx).focus_handle(cx)
721 }
722}
723
724pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
727
728impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
729
730pub struct DismissEvent;
732
733type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
734
735pub(crate) type AnyMouseListener =
736 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
737
738#[derive(Clone)]
739pub(crate) struct CursorStyleRequest {
740 pub(crate) hitbox_id: Option<HitboxId>,
741 pub(crate) style: CursorStyle,
742}
743
744#[derive(Default, Eq, PartialEq)]
745pub(crate) struct HitTest {
746 pub(crate) ids: SmallVec<[HitboxId; 8]>,
747 pub(crate) hover_hitbox_count: usize,
748}
749
750#[derive(Clone, Copy, Debug, Eq, PartialEq)]
752pub enum WindowControlArea {
753 Drag,
755 Close,
757 Max,
759 Min,
761}
762
763#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
765pub struct HitboxId(u64);
766
767#[cfg(feature = "test-support")]
768impl HitboxId {
769 pub const fn placeholder() -> Self {
774 Self(0)
775 }
776}
777
778impl HitboxId {
779 pub fn is_hovered(self, window: &Window) -> bool {
786 if let Some(hovered) = crate::fast::retained::note_hover_read(window, self) {
787 return hovered;
788 }
789 if window.captured_hitbox == Some(self) {
791 return true;
792 }
793 if crate::fast::layers::hover_freeze::hides_hover(window) {
794 return false;
795 }
796 self.hit_test(window)
797 }
798
799 pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
804 if window.captured_hitbox == Some(self) {
806 return true;
807 }
808 self.hit_test(window)
809 }
810
811 pub(crate) fn hit_test(self, window: &Window) -> bool {
812 let hit_test = &window.mouse_hit_test;
813 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
814 if self == *id {
815 return true;
816 }
817 }
818 false
819 }
820
821 pub fn should_handle_scroll(self, window: &Window) -> bool {
826 window.mouse_hit_test.ids.contains(&self)
827 }
828
829 fn next(self) -> HitboxId {
830 HitboxId(self.0.wrapping_add(1))
831 }
832}
833
834#[derive(Clone, Debug, Deref)]
837pub struct Hitbox {
838 pub id: HitboxId,
840 #[deref]
842 pub bounds: Bounds<Pixels>,
843 pub content_mask: ContentMask<Pixels>,
845 pub behavior: HitboxBehavior,
847}
848
849impl Hitbox {
850 pub fn is_hovered(&self, window: &Window) -> bool {
867 self.id.is_hovered(window)
868 }
869
870 pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
873 let hit_test = window.rendered_frame.hit_test(position);
874 hit_test
875 .ids
876 .iter()
877 .take(hit_test.hover_hitbox_count)
878 .any(|id| self.id == *id)
879 }
880
881 pub fn should_handle_scroll(&self, window: &Window) -> bool {
888 self.id.should_handle_scroll(window)
889 }
890}
891
892#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
894pub enum HitboxBehavior {
895 #[default]
897 Normal,
898
899 BlockMouse,
921
922 BlockMouseExceptScroll,
949}
950
951#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
953pub struct TooltipId(usize);
954
955impl TooltipId {
956 pub fn is_hovered(&self, window: &Window) -> bool {
958 window
959 .tooltip_bounds
960 .as_ref()
961 .is_some_and(|tooltip_bounds| {
962 tooltip_bounds.id == *self
963 && tooltip_bounds.bounds.contains(&window.mouse_position())
964 })
965 }
966}
967
968pub(crate) struct TooltipBounds {
969 id: TooltipId,
970 bounds: Bounds<Pixels>,
971}
972
973#[derive(Clone)]
974pub(crate) struct TooltipRequest {
975 id: TooltipId,
976 tooltip: AnyTooltip,
977}
978
979#[derive(Clone, Default)]
985pub(crate) struct ElementIdStack {
986 ids: SmallVec<[ElementId; 32]>,
987 hashes: SmallVec<[u64; 32]>,
988}
989
990impl ElementIdStack {
991 pub(crate) fn push(&mut self, id: ElementId) {
992 self.hashes.push(crate::extend_path_hash(self.hash(), &id));
993 self.ids.push(id);
994 }
995
996 pub(crate) fn pop(&mut self) -> Option<ElementId> {
997 self.hashes.pop();
998 self.ids.pop()
999 }
1000
1001 pub(crate) fn clear(&mut self) {
1002 self.ids.clear();
1003 self.hashes.clear();
1004 }
1005
1006 pub(crate) fn hash(&self) -> u64 {
1008 self.hashes
1009 .last()
1010 .copied()
1011 .unwrap_or(crate::EMPTY_PATH_HASH)
1012 }
1013
1014 pub(crate) fn global_id(&self) -> GlobalElementId {
1015 GlobalElementId::with_hash(&self.ids, self.hash())
1016 }
1017}
1018
1019impl std::ops::Deref for ElementIdStack {
1020 type Target = [ElementId];
1021
1022 fn deref(&self) -> &Self::Target {
1023 &self.ids
1024 }
1025}
1026
1027pub(crate) struct DeferredDraw {
1028 pub(crate) current_view: EntityId,
1029 pub(crate) priority: usize,
1030 pub(crate) parent_node: DispatchNodeId,
1031 pub(crate) element_id_stack: ElementIdStack,
1032 pub(crate) text_style_stack: crate::fast::text_style::TextStyleStack,
1033 pub(crate) content_mask: Option<ContentMask<Pixels>>,
1034 pub(crate) rem_size: Pixels,
1035 pub(crate) element: Option<AnyElement>,
1036 pub(crate) absolute_offset: Point<Pixels>,
1037 pub(crate) prepaint_range: Range<PrepaintStateIndex>,
1038 pub(crate) paint_range: Range<PaintIndex>,
1039 pub(crate) accessed_entities: FxHashSet<EntityId>,
1042 pub(crate) enclosing_retained: crate::fast::retained::EnclosingRetained,
1043}
1044
1045pub(crate) struct Frame {
1046 pub(crate) focus: Option<FocusId>,
1047 pub(crate) window_active: bool,
1048 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
1049 pub(crate) accessed_element_states: Vec<(GlobalElementId, TypeId)>,
1050 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
1051 pub(crate) dispatch_tree: DispatchTree,
1052 pub(crate) scene: Scene,
1053 pub(crate) fast_composition_starts: crate::fast::composition::SurfaceStarts,
1054 pub(crate) fast_composition_input: crate::fast::composition::SurfaceInput,
1055 pub(crate) hitboxes: Vec<Hitbox>,
1056 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
1057 pub(crate) deferred_draws: Vec<DeferredDraw>,
1058 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
1059 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
1060 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
1061 #[cfg(any(test, feature = "test-support"))]
1062 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
1063 #[cfg(any(test, feature = "test-support"))]
1064 pub(crate) debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
1065 #[cfg(any(feature = "inspector", debug_assertions))]
1066 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
1067 #[cfg(any(feature = "inspector", debug_assertions))]
1068 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
1069 pub(crate) tab_stops: TabStopMap,
1070 pub(crate) retained: crate::fast::retained::RetainedSubtrees,
1071}
1072
1073#[derive(Clone, Default)]
1074pub(crate) struct PrepaintStateIndex {
1075 pub(crate) hitboxes_index: usize,
1076 pub(crate) tooltips_index: usize,
1077 pub(crate) deferred_draws_index: usize,
1078 pub(crate) dispatch_tree_index: usize,
1079 pub(crate) accessed_element_states_index: usize,
1080 pub(crate) line_layout_index: LineLayoutIndex,
1081 pub(crate) fast_a11y_index: usize,
1082}
1083
1084#[derive(Clone, Default)]
1085pub(crate) struct PaintIndex {
1086 pub(crate) scene_index: usize,
1087 #[cfg(any(test, feature = "test-support"))]
1088 pub(crate) debug_bounds_index: usize,
1089 pub(crate) fast: crate::fast::retained::FastPaintIndex,
1090 pub(crate) mouse_listeners_index: usize,
1091 pub(crate) input_handlers_index: usize,
1092 pub(crate) cursor_styles_index: usize,
1093 pub(crate) accessed_element_states_index: usize,
1094 pub(crate) tab_handle_index: usize,
1095 pub(crate) 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 fast_composition_starts: crate::fast::composition::SurfaceStarts::default(),
1115 fast_composition_input: crate::fast::composition::SurfaceInput::default(),
1116 hitboxes: Vec::new(),
1117 window_control_hitboxes: Vec::new(),
1118 deferred_draws: Vec::new(),
1119 input_handlers: Vec::new(),
1120 tooltip_requests: Vec::new(),
1121 cursor_styles: Vec::new(),
1122
1123 #[cfg(any(test, feature = "test-support"))]
1124 debug_bounds: FxHashMap::default(),
1125 #[cfg(any(test, feature = "test-support"))]
1126 debug_bounds_records: Vec::new(),
1127
1128 #[cfg(any(feature = "inspector", debug_assertions))]
1129 next_inspector_instance_ids: FxHashMap::default(),
1130
1131 #[cfg(any(feature = "inspector", debug_assertions))]
1132 inspector_hitboxes: FxHashMap::default(),
1133 tab_stops: TabStopMap::default(),
1134 retained: crate::fast::retained::RetainedSubtrees::default(),
1135 }
1136 }
1137
1138 pub(crate) fn clear(&mut self) {
1139 self.element_states.clear();
1140 self.accessed_element_states.clear();
1141 self.mouse_listeners.clear();
1142 self.dispatch_tree.clear();
1143 self.scene.clear();
1144 crate::fast::composition::SurfaceStarts::clear(&mut self.fast_composition_starts);
1145 self.input_handlers.clear();
1146 self.tooltip_requests.clear();
1147 self.cursor_styles.clear();
1148 self.hitboxes.clear();
1149 crate::fast::composition::SurfaceInput::clear(&mut self.fast_composition_input);
1150 self.window_control_hitboxes.clear();
1151 self.deferred_draws.clear();
1152 self.tab_stops.clear();
1153 crate::fast::retained::RetainedSubtrees::clear(&mut self.retained);
1154 self.focus = None;
1155
1156 #[cfg(any(test, feature = "test-support"))]
1157 {
1158 self.debug_bounds.clear();
1159 self.debug_bounds_records.clear();
1160 }
1161
1162 #[cfg(any(feature = "inspector", debug_assertions))]
1163 {
1164 self.next_inspector_instance_ids.clear();
1165 self.inspector_hitboxes.clear();
1166 }
1167 }
1168
1169 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1170 self.cursor_styles
1171 .iter()
1172 .rev()
1173 .fold_while(None, |style, request| match request.hitbox_id {
1174 None => Done(Some(request.style)),
1175 Some(hitbox_id) => Continue(style.or_else(|| {
1176 hitbox_id
1177 .is_hovered_ignoring_last_input(window)
1178 .then_some(request.style)
1179 })),
1180 })
1181 .into_inner()
1182 }
1183
1184 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
1185 if let Some(hit_test) = crate::fast::composition::hit_test(self, position) {
1186 return hit_test;
1187 }
1188 let mut set_hover_hitbox_count = false;
1189 let mut hit_test = HitTest::default();
1190 for hitbox in self.hitboxes.iter().rev() {
1191 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
1192 if bounds.contains(&position) {
1193 hit_test.ids.push(hitbox.id);
1194 if !set_hover_hitbox_count
1195 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1196 {
1197 hit_test.hover_hitbox_count = hit_test.ids.len();
1198 set_hover_hitbox_count = true;
1199 }
1200 if hitbox.behavior == HitboxBehavior::BlockMouse {
1201 break;
1202 }
1203 }
1204 }
1205 if !set_hover_hitbox_count {
1206 hit_test.hover_hitbox_count = hit_test.ids.len();
1207 }
1208 hit_test
1209 }
1210
1211 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1212 self.focus
1213 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1214 .unwrap_or_default()
1215 }
1216
1217 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1218 for element_state_key in &self.accessed_element_states {
1219 if let Some((element_state_key, element_state)) =
1220 prev_frame.element_states.remove_entry(element_state_key)
1221 {
1222 self.element_states.insert(element_state_key, element_state);
1223 }
1224 }
1225
1226 self.scene.finish();
1227 }
1228}
1229
1230#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1231enum InputModality {
1232 Mouse,
1233 Keyboard,
1234 Touch,
1235}
1236
1237pub struct Window {
1239 pub(crate) handle: AnyWindowHandle,
1240 pub(crate) invalidator: WindowInvalidator,
1241 pub(crate) removed: bool,
1242 pub(crate) platform_window: Box<dyn PlatformWindow>,
1243 pub(crate) display_id: Option<DisplayId>,
1244 pub(crate) display_observers: SingleSubscriberSet<AnyObserver>,
1245 is_resizable: bool,
1246 is_minimizable: bool,
1247 pub(crate) sprite_atlas: Arc<dyn PlatformAtlas>,
1248 pub(crate) text_system: Rc<WindowTextSystem>,
1249 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1250 rem_size: Pixels,
1251 pub(crate) rem_size_override_stack: SmallVec<[Pixels; 8]>,
1256 pub(crate) viewport_size: Size<Pixels>,
1257 pub(crate) layout_engine: Option<TaffyLayoutEngine>,
1258 pub(crate) fast_layout: crate::fast::layout_key::WindowLayout,
1259 pub(crate) root: Option<AnyView>,
1260 pub(crate) element_id_stack: ElementIdStack,
1261 pub(crate) global_ids: crate::fast::global_id::GlobalIdCache,
1262 pub(crate) retained_state: crate::fast::retained::RetainedState,
1263 pub(crate) text_style_stack: crate::fast::text_style::TextStyleStack,
1264 pub(crate) fast_glyph_bounds: crate::fast::glyphs::GlyphBoundsCache,
1265 pub(crate) fast_layers: crate::fast::layers::WindowLayers,
1266 pub(crate) fast_composition: crate::fast::composition::WindowCompositionHandle,
1267 pub(crate) rendered_entity_stack: Vec<EntityId>,
1268 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1269 pub(crate) element_opacity: f32,
1270 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1271 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1272 last_text_input_configuration: Option<TextInputConfiguration>,
1276 focused_text_input: Option<FocusId>,
1277 pub(crate) image_cache_stack: Vec<AnyImageCache>,
1278 pub(crate) rendered_frame: Frame,
1279 pub(crate) next_frame: Frame,
1280 next_hitbox_id: HitboxId,
1281 pub(crate) next_tooltip_id: TooltipId,
1282 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1283 pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1284 pub(crate) dirty_views: FxHashSet<EntityId>,
1285 focus_listeners: SingleSubscriberSet<AnyWindowFocusListener>,
1286 pub(crate) focus_lost_listeners: SingleSubscriberSet<AnyObserver>,
1287 focus_lost_path: SmallVec<[FocusId; 8]>,
1288 pub(crate) default_prevented: bool,
1289 pub(crate) mouse_position: Point<Pixels>,
1290 pub(crate) mouse_hit_test: HitTest,
1291 modifiers: Modifiers,
1292 capslock: Capslock,
1293 scale_factor: f32,
1294 pub(crate) bounds_observers: SingleSubscriberSet<AnyObserver>,
1295 appearance: WindowAppearance,
1296 pub(crate) appearance_observers: SingleSubscriberSet<AnyObserver>,
1297 pub(crate) button_layout_observers: SingleSubscriberSet<AnyObserver>,
1298 pub(crate) active: Rc<Cell<bool>>,
1299 visibility: WindowVisibility,
1300 pub(crate) visibility_observers:
1301 SingleSubscriberSet<Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
1302 pub(crate) hovered: Rc<Cell<bool>>,
1303 pub(crate) needs_present: Rc<Cell<bool>>,
1304 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1307 #[cfg(feature = "profiler")]
1308 pub(crate) window_profiler: profiler::WindowProfiler,
1309 last_input_modality: InputModality,
1310 touch_gestures: TouchGestureRecognizer,
1311 touch_prediction_enabled: bool,
1312 long_press_timer: Option<Task<()>>,
1313 long_press_capture: Option<EntityId>,
1314 pub(crate) refreshing: bool,
1315 pub(crate) activation_observers: SingleSubscriberSet<AnyObserver>,
1316 pub(crate) focus: Option<FocusId>,
1317 focus_enabled: bool,
1318 pub(crate) focus_generation: u64,
1321 pending_input: Option<PendingInput>,
1322 pending_modifier: ModifierState,
1323 pub(crate) pending_input_observers: SingleSubscriberSet<AnyObserver>,
1324 prompt: Option<RenderablePromptHandle>,
1325 pub(crate) client_inset: Option<Pixels>,
1326 pub(crate) captured_hitbox: Option<HitboxId>,
1329 #[cfg(any(feature = "inspector", debug_assertions))]
1330 pub(crate) inspector: Option<Entity<Inspector>>,
1331 #[cfg(feature = "profiler")]
1332 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1333 pub(crate) a11y: A11y,
1334}
1335
1336#[derive(Clone, Debug, Default)]
1337struct ModifierState {
1338 modifiers: Modifiers,
1339 saw_other_input: bool,
1340}
1341
1342#[derive(Clone, Debug)]
1345pub(crate) struct InputRateTracker {
1346 timestamps: Vec<Instant>,
1347 window: Duration,
1348 inputs_per_second: u32,
1349 sustain_until: Instant,
1350 sustain_duration: Duration,
1351}
1352
1353const FRAME_INTERVAL_TOLERANCE: Duration = Duration::from_millis(1);
1354
1355#[derive(Default)]
1357struct FramePacer {
1358 last_frame: Option<Instant>,
1359}
1360
1361impl FramePacer {
1362 fn should_defer(&mut self, now: Instant, minimum_interval: Option<Duration>) -> bool {
1363 if let Some(interval) = minimum_interval
1364 && let Some(last_frame) = self.last_frame
1365 {
1366 let deadline = last_frame + interval;
1367 if now + FRAME_INTERVAL_TOLERANCE < deadline {
1368 return true;
1369 }
1370 self.last_frame = Some(if now.saturating_duration_since(deadline) <= interval / 4 {
1374 deadline
1375 } else {
1376 now
1377 });
1378 } else {
1379 self.last_frame = Some(now);
1380 }
1381 false
1382 }
1383}
1384
1385fn minimum_frame_interval(
1386 should_throttle: bool,
1387 inactive_without_high_rate_input: bool,
1388 inactive_frame_interval: Option<Duration>,
1389 low_power_frame_interval: Option<Duration>,
1390 thermal_frame_interval: Option<Duration>,
1391 thermal_state: ThermalState,
1392 power_mode: crate::PowerMode,
1393) -> Option<Duration> {
1394 if !should_throttle {
1395 return None;
1396 }
1397
1398 [
1399 inactive_frame_interval.filter(|_| inactive_without_high_rate_input),
1400 low_power_frame_interval.filter(|_| power_mode == crate::PowerMode::LowPower),
1401 thermal_frame_interval.filter(|_| {
1402 matches!(
1403 thermal_state,
1404 ThermalState::Critical | ThermalState::Serious
1405 )
1406 }),
1407 ]
1408 .into_iter()
1409 .flatten()
1410 .max()
1411}
1412
1413impl Default for InputRateTracker {
1414 fn default() -> Self {
1415 Self {
1416 timestamps: Vec::new(),
1417 window: Duration::from_millis(100),
1418 inputs_per_second: 60,
1419 sustain_until: Instant::now(),
1420 sustain_duration: Duration::from_secs(1),
1421 }
1422 }
1423}
1424
1425impl InputRateTracker {
1426 pub fn record_input(&mut self) {
1427 let now = Instant::now();
1428 self.timestamps.push(now);
1429 self.prune_old_timestamps(now);
1430
1431 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1432 if self.timestamps.len() as u128 >= min_events {
1433 self.sustain_until = now + self.sustain_duration;
1434 }
1435 }
1436
1437 pub fn is_high_rate(&self) -> bool {
1438 Instant::now() < self.sustain_until
1439 }
1440
1441 fn prune_old_timestamps(&mut self, now: Instant) {
1442 self.timestamps
1443 .retain(|&t| now.duration_since(t) <= self.window);
1444 }
1445}
1446
1447#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1448pub(crate) enum DrawPhase {
1449 None,
1450 Prepaint,
1451 Paint,
1452 Focus,
1453}
1454
1455pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
1456
1457pub struct PendingInputStatus<'a> {
1459 keystrokes: &'a [Keystroke],
1460 timeout: Option<PendingInputTimeoutStatus>,
1461}
1462
1463impl<'a> PendingInputStatus<'a> {
1464 pub fn keystrokes(&self) -> &'a [Keystroke] {
1466 self.keystrokes
1467 }
1468
1469 pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
1471 self.timeout
1472 }
1473}
1474
1475#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1477pub struct PendingInputTimeoutStatus {
1478 duration: Duration,
1479 remaining: Duration,
1480 started_at: Option<Instant>,
1481 paused: bool,
1482}
1483
1484impl PendingInputTimeoutStatus {
1485 pub fn duration(&self) -> Duration {
1487 self.duration
1488 }
1489
1490 pub fn remaining(&self, cx: &App) -> Duration {
1492 self.started_at
1493 .map(|started_at| {
1494 self.remaining
1495 .saturating_sub(cx.background_executor().now() - started_at)
1496 })
1497 .unwrap_or(self.remaining)
1498 }
1499
1500 pub fn is_paused(&self) -> bool {
1502 self.paused
1503 }
1504}
1505
1506#[derive(Debug)]
1507struct PendingInputTimeout {
1508 duration: Duration,
1509 remaining: Duration,
1510 state: PendingInputTimeoutState,
1511}
1512
1513#[derive(Debug)]
1514enum PendingInputTimeoutState {
1515 Running { started_at: Instant, task: Task<()> },
1516 Paused { pause: PendingInputTimeoutPause },
1517}
1518
1519#[derive(Debug)]
1520struct PendingInputTimeoutPause {
1521 owner_id: EntityId,
1522 _release_subscription: Subscription,
1523}
1524
1525impl PendingInputTimeout {
1526 fn is_paused(&self) -> bool {
1527 matches!(&self.state, PendingInputTimeoutState::Paused { .. })
1528 }
1529
1530 fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
1531 match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
1532 PendingInputTimeoutState::Running { started_at, task } => {
1533 self.remaining = self.remaining.saturating_sub(now - started_at);
1534 drop(task);
1535 true
1536 }
1537 previous_state @ PendingInputTimeoutState::Paused { .. } => {
1538 self.state = previous_state;
1539 false
1540 }
1541 }
1542 }
1543
1544 fn pause_owner_id(&self) -> Option<EntityId> {
1545 match &self.state {
1546 PendingInputTimeoutState::Running { .. } => None,
1547 PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
1548 }
1549 }
1550
1551 fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
1552 match std::mem::replace(
1553 &mut self.state,
1554 PendingInputTimeoutState::Running { started_at, task },
1555 ) {
1556 PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
1557 previous_state => {
1558 self.state = previous_state;
1559 false
1560 }
1561 }
1562 }
1563
1564 fn reset_duration(&mut self, duration: Duration) {
1565 self.duration = duration;
1566 self.remaining = duration;
1567 }
1568
1569 fn status(&self) -> PendingInputTimeoutStatus {
1570 let (started_at, paused) = match &self.state {
1571 PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
1572 PendingInputTimeoutState::Paused { .. } => (None, true),
1573 };
1574 PendingInputTimeoutStatus {
1575 duration: self.duration,
1576 remaining: self.remaining,
1577 started_at,
1578 paused,
1579 }
1580 }
1581}
1582
1583#[derive(Default, Debug)]
1584struct PendingInput {
1585 keystrokes: SmallVec<[Keystroke; 1]>,
1586 focus: Option<FocusId>,
1587 timeout: Option<PendingInputTimeout>,
1588}
1589
1590pub(crate) struct ElementStateBox {
1591 pub(crate) inner: Box<dyn Any>,
1592 #[cfg(debug_assertions)]
1593 pub(crate) type_name: &'static str,
1594}
1595
1596fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1597 let active_window_bounds = cx
1602 .active_window()
1603 .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1604
1605 const CASCADE_OFFSET: f32 = 25.0;
1606
1607 let display = display_id
1608 .map(|id| cx.find_display(id))
1609 .unwrap_or_else(|| cx.primary_display());
1610
1611 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1612
1613 let display_bounds = display
1615 .as_ref()
1616 .map(|d| d.visible_bounds())
1617 .unwrap_or_else(default_placement);
1618
1619 let (
1620 Bounds {
1621 origin: base_origin,
1622 size: base_size,
1623 },
1624 window_bounds_ctor,
1625 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1626 Some(bounds) => match bounds {
1627 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1628 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1629 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1630 },
1631 None => (
1632 display
1633 .as_ref()
1634 .map(|d| d.default_bounds())
1635 .unwrap_or_else(default_placement),
1636 WindowBounds::Windowed,
1637 ),
1638 };
1639
1640 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1641 let proposed_origin = base_origin + cascade_offset;
1642 let proposed_bounds = Bounds::new(proposed_origin, base_size);
1643
1644 let display_right = display_bounds.origin.x + display_bounds.size.width;
1645 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1646 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1647 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1648
1649 let fits_horizontally = window_right <= display_right;
1650 let fits_vertically = window_bottom <= display_bottom;
1651
1652 let final_origin = match (fits_horizontally, fits_vertically) {
1653 (true, true) => proposed_origin,
1654 (false, true) => point(display_bounds.origin.x, base_origin.y),
1655 (true, false) => point(base_origin.x, display_bounds.origin.y),
1656 (false, false) => display_bounds.origin,
1657 };
1658 window_bounds_ctor(Bounds::new(final_origin, base_size))
1659}
1660
1661impl Window {
1662 pub(crate) fn new(
1663 handle: AnyWindowHandle,
1664 options: WindowOptions,
1665 cx: &mut App,
1666 ) -> Result<Self> {
1667 let WindowOptions {
1668 window_bounds,
1669 titlebar,
1670 focus,
1671 show,
1672 kind,
1673 is_movable,
1674 app_owns_titlebar_drag,
1675 inactive_frame_interval,
1676 low_power_frame_interval,
1677 thermal_frame_interval,
1678 is_resizable,
1679 is_minimizable,
1680 display_id,
1681 window_background,
1682 app_id,
1683 window_min_size,
1684 window_decorations,
1685 #[cfg_attr(
1686 not(any(target_os = "linux", target_os = "freebsd")),
1687 allow(unused_variables)
1688 )]
1689 icon,
1690 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1691 tabbing_identifier,
1692 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1693 use_display_p3,
1694 } = options;
1695
1696 let initial_window_title = titlebar
1697 .as_ref()
1698 .and_then(|titlebar| titlebar.title.clone());
1699
1700 let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1701 let mut platform_window = cx.platform.open_window(
1702 handle,
1703 WindowParams {
1704 bounds: window_bounds.get_bounds(),
1705 titlebar,
1706 kind,
1707 is_movable,
1708 app_owns_titlebar_drag,
1709 is_resizable,
1710 is_minimizable,
1711 focus,
1712 show,
1713 display_id,
1714 window_min_size,
1715 app_id: app_id.clone(),
1716 icon,
1717 #[cfg(target_os = "macos")]
1718 tabbing_identifier,
1719 #[cfg(target_os = "macos")]
1720 use_display_p3,
1721 },
1722 )?;
1723
1724 let tab_bar_visible = platform_window.tab_bar_visible();
1725 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1726 if let Some(tabs) = platform_window.tabbed_windows() {
1727 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1728 }
1729
1730 let display_id = platform_window.display().map(|display| display.id());
1731 let sprite_atlas = platform_window.sprite_atlas();
1732 let mouse_position = platform_window.mouse_position();
1733 let modifiers = platform_window.modifiers();
1734 let capslock = platform_window.capslock();
1735 let content_size = platform_window.content_size();
1736 let scale_factor = platform_window.scale_factor();
1737 let appearance = platform_window.appearance();
1738 let text_system = Rc::new(WindowTextSystem::new(cx.text_system().clone()));
1739 let invalidator = WindowInvalidator::new(handle.window_id());
1740 let active = Rc::new(Cell::new(platform_window.is_active()));
1741 let visibility = platform_window.visibility();
1742 #[cfg(feature = "profiler")]
1743 profiler::journal::record_window_visibility(handle.window_id(), visibility);
1744 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1745 let needs_present = Rc::new(Cell::new(false));
1746 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1747 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1748
1749 platform_window
1750 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1751 platform_window.set_background_appearance(window_background);
1752
1753 match window_bounds {
1754 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1755 WindowBounds::Maximized(_) => platform_window.zoom(),
1756 WindowBounds::Windowed(_) => {}
1757 }
1758
1759 let accessibility_force_disabled = cx.accessibility_force_disabled;
1760 let a11y_active_flag = Arc::new(AtomicBool::new(false));
1761
1762 #[cfg(not(target_family = "wasm"))]
1763 if !accessibility_force_disabled {
1764 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
1765 if let Some(title) = &initial_window_title {
1766 initial_root_node.set_label(title.to_string());
1767 }
1768 let initial_tree = accesskit::TreeUpdate {
1769 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
1770 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
1771 tree_id: accesskit::TreeId::ROOT,
1772 focus: ROOT_NODE_ID,
1773 };
1774 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
1775 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
1776 let (action_sender, action_receiver) =
1777 async_channel::unbounded::<accesskit::ActionRequest>();
1778
1779 platform_window.a11y_init(crate::A11yCallbacks {
1780 activation: {
1781 let active_flag = a11y_active_flag.clone();
1782 Box::new(move || {
1783 log::info!("Accessibility activated");
1784 active_flag.store(true, SeqCst);
1785 activation_sender
1786 .send_blocking(())
1787 .with_context(|| {
1788 format!(
1789 "queuing accessibility activation for window {:?}",
1790 handle.window_id()
1791 )
1792 })
1793 .log_err();
1794 Some(initial_tree.clone())
1795 })
1796 },
1797 action: Box::new(move |request| {
1798 action_sender
1799 .send_blocking(request)
1800 .with_context(|| {
1801 format!(
1802 "queuing accessibility action for window {:?}",
1803 handle.window_id()
1804 )
1805 })
1806 .log_err();
1807 }),
1808 deactivation: {
1809 let active_flag = a11y_active_flag.clone();
1810 Box::new(move || {
1811 log::info!("Accessibility deactivated");
1812 active_flag.store(false, SeqCst);
1813 deactivation_sender
1814 .send_blocking(())
1815 .with_context(|| {
1816 format!(
1817 "queuing accessibility deactivation for window {:?}",
1818 handle.window_id()
1819 )
1820 })
1821 .log_err();
1822 })
1823 },
1824 });
1825
1826 let mut async_cx = cx.to_async();
1832 cx.foreground_executor()
1833 .spawn(async move {
1834 while activation_receiver.recv().await.is_ok() {
1835 handle
1836 .update(&mut async_cx, |_, window, _| window.refresh())
1837 .with_context(|| {
1838 format!(
1839 "handling accessibility activation for window {:?}",
1840 handle.window_id()
1841 )
1842 })
1843 .log_err();
1844 }
1845 })
1846 .detach();
1847
1848 let mut async_cx = cx.to_async();
1849 cx.foreground_executor()
1850 .spawn(async move {
1851 while deactivation_receiver.recv().await.is_ok() {
1852 handle
1853 .update(&mut async_cx, |_, window, _| window.refresh())
1854 .with_context(|| {
1855 format!(
1856 "handling accessibility deactivation for window {:?}",
1857 handle.window_id()
1858 )
1859 })
1860 .log_err();
1861 }
1862 })
1863 .detach();
1864
1865 let mut async_cx = cx.to_async();
1866 cx.foreground_executor()
1867 .spawn(async move {
1868 while let Ok(request) = action_receiver.recv().await {
1869 handle
1870 .update(&mut async_cx, |_, window, cx| {
1871 window.handle_a11y_action(request, cx);
1872 })
1873 .with_context(|| {
1874 format!(
1875 "handling accessibility action for window {:?}",
1876 handle.window_id()
1877 )
1878 })
1879 .log_err();
1880 }
1881 })
1882 .detach();
1883 }
1884
1885 platform_window.on_close(Box::new({
1886 let window_id = handle.window_id();
1887 let cx = cx.to_async();
1888 move || {
1889 cx.spawn(async move |cx| {
1892 cx.update(|cx| {
1893 if cx.windows.contains_key(window_id) {
1895 handle
1896 .update(cx, |_, window, _| window.remove_window())
1897 .with_context(|| format!("handling close for window {window_id:?}"))
1898 .log_err();
1899 }
1900 SystemWindowTabController::remove_tab(cx, window_id);
1901 });
1902 })
1903 .detach();
1904 }
1905 }));
1906 platform_window.on_request_frame(Box::new({
1907 let mut cx = cx.to_async();
1908 let invalidator = invalidator.clone();
1909 let active = active.clone();
1910 let needs_present = needs_present.clone();
1911 let next_frame_callbacks = next_frame_callbacks.clone();
1912 let input_rate_tracker = input_rate_tracker.clone();
1913 let mut deferred_force_render = false;
1914 let mut frame_pacer = FramePacer::default();
1915 move |request_frame_options| {
1916 #[cfg(feature = "profiler")]
1917 let (_foreground_turn, window_id) = {
1918 let foreground_turn = profiler::journal::foreground_turn();
1919 let window_id = handle.window_id();
1920 profiler::journal::record_platform_signal(profiler::journal::PlatformSignal {
1921 window_id,
1922 signal_at: request_frame_options.signal_at,
1923 handled_at: Instant::now(),
1924 source: request_frame_options.signal_source,
1925 });
1926 (foreground_turn, window_id)
1927 };
1928 if draw_in_progress() {
1944 log::debug!("deferring re-entrant window draw request");
1945 deferred_force_render |= request_frame_options.force_render;
1946 #[cfg(feature = "profiler")]
1947 profiler::journal::record_reentrant_frame_skipped(window_id, Instant::now());
1948 return;
1949 }
1950 let force_render =
1954 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
1955
1956 let power_state = handle
1957 .update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode()))
1958 .with_context(|| {
1959 format!(
1960 "reading power state for frame request for window {:?}",
1961 handle.window_id()
1962 )
1963 })
1964 .log_err();
1965
1966 let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate();
1969 let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty();
1970 let has_frame_demand = invalidator.is_dirty()
1971 || force_render
1972 || has_next_frame_callbacks
1973 || request_frame_options.require_presentation
1974 || needs_present.get()
1975 || high_rate_input;
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
1992 let now = Instant::now();
1993 if has_frame_demand && frame_pacer.should_defer(now, min_frame_interval) {
1996 deferred_force_render |= force_render;
1998 handle
2000 .update(&mut cx, |_, window, _| {
2001 window.platform_window.schedule_frame();
2002 })
2003 .with_context(|| {
2004 format!(
2005 "rescheduling throttled frame for window {:?}",
2006 handle.window_id()
2007 )
2008 })
2009 .log_err();
2010 invalidator.wake_platform();
2013 #[cfg(feature = "profiler")]
2014 profiler::journal::record_frame_skipped(
2015 window_id,
2016 Instant::now(),
2017 if inactive_without_high_rate_input
2018 && inactive_frame_interval == min_frame_interval
2019 {
2020 profiler::journal::FrameSkipReason::InactiveFrameRateLimit
2021 } else if power_mode == crate::PowerMode::LowPower
2022 && low_power_frame_interval == min_frame_interval
2023 {
2024 profiler::journal::FrameSkipReason::LowPowerFrameRateLimit
2025 } else {
2026 profiler::journal::FrameSkipReason::ThermalFrameRateLimit
2027 },
2028 );
2029 return;
2030 }
2031
2032 let pending_next_frame_callbacks = next_frame_callbacks.take();
2033 if !pending_next_frame_callbacks.is_empty() {
2034 handle
2035 .update(&mut cx, |_, window, cx| {
2036 for callback in pending_next_frame_callbacks {
2037 callback(window, cx);
2038 }
2039 })
2040 .with_context(|| {
2041 format!(
2042 "running next-frame callbacks for window {:?}",
2043 handle.window_id()
2044 )
2045 })
2046 .log_err();
2047 }
2048
2049 let should_draw = invalidator.is_dirty() || force_render;
2050 let needs_present = request_frame_options.require_presentation
2051 || needs_present.get()
2052 || high_rate_input;
2053 if should_draw {
2054 measure("frame duration", || {
2055 handle
2056 .update(&mut cx, |_, window, cx| {
2057 #[cfg(feature = "profiler")]
2058 window
2059 .window_profiler
2060 .record_frame_signal(request_frame_options.signal_at);
2061 if force_render {
2062 window.refresh();
2065 }
2066 let arena_clear_needed = window.draw(cx);
2067 window.present();
2068 arena_clear_needed.clear(cx);
2069 })
2070 .with_context(|| {
2071 format!(
2072 "drawing and presenting frame for window {:?}",
2073 handle.window_id()
2074 )
2075 })
2076 .log_err();
2077 })
2078 } else if needs_present {
2079 handle
2080 .update(&mut cx, |_, window, _| window.present())
2081 .with_context(|| {
2082 format!("presenting frame for window {:?}", handle.window_id())
2083 })
2084 .log_err();
2085 }
2086
2087 handle
2088 .update(&mut cx, |_, window, _| {
2089 if window.invalidator.is_dirty()
2090 || !window.next_frame_callbacks.borrow().is_empty()
2091 {
2092 window.platform_window.schedule_frame();
2093 }
2094 })
2095 .with_context(|| {
2096 format!(
2097 "scheduling follow-up frame for window {:?}",
2098 handle.window_id()
2099 )
2100 })
2101 .log_err();
2102
2103 if invalidator.is_dirty() || !next_frame_callbacks.borrow().is_empty() {
2109 invalidator.wake_platform();
2110 }
2111 #[cfg(feature = "profiler")]
2112 if !should_draw {
2113 profiler::journal::record_frame_skipped(
2114 window_id,
2115 Instant::now(),
2116 profiler::journal::FrameSkipReason::NoRenderNeeded,
2117 );
2118 }
2119 }
2120 }));
2121 invalidator.set_platform_waker(platform_window.frame_waker());
2122 platform_window.on_visual_viewport_changed(Box::new({
2123 let mut cx = cx.to_async();
2124 move || {
2125 handle
2126 .update(&mut cx, |_, window, _| window.refresh())
2127 .with_context(|| {
2128 format!(
2129 "handling visual viewport change for window {:?}",
2130 handle.window_id()
2131 )
2132 })
2133 .log_err();
2134 }
2135 }));
2136 platform_window.on_insets_changed(Box::new({
2137 let mut cx = cx.to_async();
2138 move |_| {
2139 handle
2140 .update(&mut cx, |_, window, _| window.refresh())
2141 .with_context(|| {
2142 format!("handling insets change for window {:?}", handle.window_id())
2143 })
2144 .log_err();
2145 }
2146 }));
2147 platform_window.on_resize(Box::new({
2148 let mut cx = cx.to_async();
2149 move |_, _| {
2150 handle
2151 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2152 .with_context(|| format!("handling resize for window {:?}", handle.window_id()))
2153 .log_err();
2154 }
2155 }));
2156 platform_window.on_moved(Box::new({
2157 let mut cx = cx.to_async();
2158 move || {
2159 handle
2160 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2161 .with_context(|| format!("handling move for window {:?}", handle.window_id()))
2162 .log_err();
2163 }
2164 }));
2165 platform_window.on_display_changed(Box::new({
2166 let cx = cx.to_async();
2167 move || cx.update(|cx| Window::display_changed(handle, cx))
2168 }));
2169 platform_window.on_appearance_changed(Box::new({
2170 let cx = cx.to_async();
2171 let foreground_executor = cx.foreground_executor().clone();
2172 move || {
2173 let mut cx = cx.clone();
2174 foreground_executor
2177 .spawn(async move {
2178 handle
2179 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
2180 .with_context(|| {
2181 format!(
2182 "handling appearance change for window {:?}",
2183 handle.window_id()
2184 )
2185 })
2186 .log_err();
2187 })
2188 .detach();
2189 }
2190 }));
2191 platform_window.on_button_layout_changed(Box::new({
2192 let mut cx = cx.to_async();
2193 move || {
2194 handle
2195 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
2196 .with_context(|| {
2197 format!(
2198 "handling button layout change for window {:?}",
2199 handle.window_id()
2200 )
2201 })
2202 .log_err();
2203 }
2204 }));
2205 platform_window.on_active_status_change(Box::new({
2206 let mut cx = cx.to_async();
2207 move |active| {
2208 handle
2209 .update(&mut cx, |_, window, cx| {
2210 window.active.set(active);
2211 window.modifiers = window.platform_window.modifiers();
2212 window.capslock = window.platform_window.capslock();
2213 window
2214 .activation_observers
2215 .clone()
2216 .retain(|callback| callback(window, cx));
2217
2218 window.bounds_changed(cx);
2219 window.refresh();
2220
2221 SystemWindowTabController::update_last_active(cx, window.handle.id);
2222 })
2223 .with_context(|| {
2224 format!(
2225 "handling active status change for window {:?}",
2226 handle.window_id()
2227 )
2228 })
2229 .log_err();
2230 }
2231 }));
2232 platform_window.on_visibility_change(Box::new({
2233 let mut cx = cx.to_async();
2234 move |_| {
2235 handle
2236 .update(&mut cx, |_, window, cx| {
2237 window.refresh_visibility(cx);
2238 })
2239 .with_context(|| {
2240 format!(
2241 "handling visibility change for window {:?}",
2242 handle.window_id()
2243 )
2244 })
2245 .log_err();
2246 }
2247 }));
2248 platform_window.on_hover_status_change(Box::new({
2249 let mut cx = cx.to_async();
2250 move |active| {
2251 handle
2252 .update(&mut cx, |_, window, _| {
2253 window.hovered.set(active);
2254 window.refresh();
2255 })
2256 .with_context(|| {
2257 format!(
2258 "handling hover status change for window {:?}",
2259 handle.window_id()
2260 )
2261 })
2262 .log_err();
2263 }
2264 }));
2265 platform_window.on_input({
2266 let mut cx = cx.to_async();
2267 Box::new(move |event| {
2268 handle
2269 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
2270 .with_context(|| {
2271 format!("dispatching input for window {:?}", handle.window_id())
2272 })
2273 .log_err()
2274 .unwrap_or(DispatchEventResult::default())
2275 })
2276 });
2277 platform_window.on_hit_test_window_control({
2278 let mut cx = cx.to_async();
2279 Box::new(move || {
2280 handle
2281 .update(&mut cx, |_, window, _cx| {
2282 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
2283 if window.mouse_hit_test.ids.contains(&hitbox.id) {
2284 return Some(*area);
2285 }
2286 }
2287 None
2288 })
2289 .with_context(|| {
2290 format!(
2291 "hit-testing window controls for window {:?}",
2292 handle.window_id()
2293 )
2294 })
2295 .log_err()
2296 .unwrap_or(None)
2297 })
2298 });
2299 platform_window.on_move_tab_to_new_window({
2300 let mut cx = cx.to_async();
2301 Box::new(move || {
2302 handle
2303 .update(&mut cx, |_, _window, cx| {
2304 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
2305 })
2306 .with_context(|| {
2307 format!(
2308 "moving tab to new window from window {:?}",
2309 handle.window_id()
2310 )
2311 })
2312 .log_err();
2313 })
2314 });
2315 platform_window.on_merge_all_windows({
2316 let mut cx = cx.to_async();
2317 Box::new(move || {
2318 handle
2319 .update(&mut cx, |_, _window, cx| {
2320 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
2321 })
2322 .with_context(|| {
2323 format!("merging all windows into window {:?}", handle.window_id())
2324 })
2325 .log_err();
2326 })
2327 });
2328 platform_window.on_select_next_tab({
2329 let mut cx = cx.to_async();
2330 Box::new(move || {
2331 handle
2332 .update(&mut cx, |_, _window, cx| {
2333 SystemWindowTabController::select_next_tab(cx, handle.window_id());
2334 })
2335 .with_context(|| {
2336 format!("selecting next tab for window {:?}", handle.window_id())
2337 })
2338 .log_err();
2339 })
2340 });
2341 platform_window.on_select_previous_tab({
2342 let mut cx = cx.to_async();
2343 Box::new(move || {
2344 handle
2345 .update(&mut cx, |_, _window, cx| {
2346 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
2347 })
2348 .with_context(|| {
2349 format!("selecting previous tab for window {:?}", handle.window_id())
2350 })
2351 .log_err();
2352 })
2353 });
2354 platform_window.on_toggle_tab_bar({
2355 let mut cx = cx.to_async();
2356 Box::new(move || {
2357 handle
2358 .update(&mut cx, |_, window, cx| {
2359 let tab_bar_visible = window.platform_window.tab_bar_visible();
2360 SystemWindowTabController::set_visible(cx, tab_bar_visible);
2361 })
2362 .with_context(|| {
2363 format!("toggling tab bar for window {:?}", handle.window_id())
2364 })
2365 .log_err();
2366 })
2367 });
2368
2369 if let Some(app_id) = app_id {
2370 platform_window.set_app_id(&app_id);
2371 }
2372
2373 platform_window.map_window().unwrap();
2374
2375 Ok(Window {
2376 handle,
2377 invalidator,
2378 removed: false,
2379 platform_window,
2380 display_id,
2381 display_observers: SingleSubscriberSet::new(),
2382 is_resizable,
2383 is_minimizable,
2384 sprite_atlas,
2385 text_system,
2386 text_rendering_mode: cx.text_rendering_mode.clone(),
2387 rem_size: px(16.),
2388 rem_size_override_stack: SmallVec::new(),
2389 viewport_size: content_size,
2390 layout_engine: Some(TaffyLayoutEngine::new()),
2391 fast_layout: crate::fast::layout_key::WindowLayout::default(),
2392 root: None,
2393 element_id_stack: ElementIdStack::default(),
2394 global_ids: crate::fast::global_id::GlobalIdCache::default(),
2395 retained_state: crate::fast::retained::RetainedState::new(cx),
2396 text_style_stack: crate::fast::text_style::TextStyleStack::default(),
2397 fast_glyph_bounds: crate::fast::glyphs::GlyphBoundsCache::default(),
2398 fast_layers: crate::fast::layers::WindowLayers::default(),
2399 fast_composition: crate::fast::composition::WindowCompositionHandle::default(),
2400 rendered_entity_stack: Vec::new(),
2401 element_offset_stack: Vec::new(),
2402 content_mask_stack: Vec::new(),
2403 element_opacity: 1.0,
2404 requested_autoscroll: None,
2405 last_text_input_configuration: None,
2406 focused_text_input: None,
2407 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
2408 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
2409 next_frame_callbacks,
2410 next_hitbox_id: HitboxId(0),
2411 next_tooltip_id: TooltipId::default(),
2412 tooltip_bounds: None,
2413 dirty_views: FxHashSet::default(),
2414 focus_listeners: SingleSubscriberSet::new(),
2415 focus_lost_listeners: SingleSubscriberSet::new(),
2416 focus_lost_path: SmallVec::new(),
2417 default_prevented: true,
2418 mouse_position,
2419 mouse_hit_test: HitTest::default(),
2420 modifiers,
2421 capslock,
2422 scale_factor,
2423 bounds_observers: SingleSubscriberSet::new(),
2424 appearance,
2425 appearance_observers: SingleSubscriberSet::new(),
2426 button_layout_observers: SingleSubscriberSet::new(),
2427 active,
2428 visibility,
2429 visibility_observers: SingleSubscriberSet::new(),
2430 hovered,
2431 needs_present,
2432 input_rate_tracker,
2433 #[cfg(feature = "profiler")]
2434 window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
2435 last_input_modality: InputModality::Mouse,
2436 touch_gestures: TouchGestureRecognizer::new(
2437 cx.platform
2438 .gestures()
2439 .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
2440 ),
2441 touch_prediction_enabled: true,
2442 long_press_timer: None,
2443 long_press_capture: None,
2444 refreshing: false,
2445 activation_observers: SingleSubscriberSet::new(),
2446 focus: None,
2447 focus_enabled: true,
2448 focus_generation: 0,
2449 pending_input: None,
2450 pending_modifier: ModifierState::default(),
2451 pending_input_observers: SingleSubscriberSet::new(),
2452 prompt: None,
2453 client_inset: None,
2454 image_cache_stack: Vec::new(),
2455 captured_hitbox: None,
2456 #[cfg(any(feature = "inspector", debug_assertions))]
2457 inspector: None,
2458 #[cfg(feature = "profiler")]
2459 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
2460 a11y: A11y::new(
2461 a11y_active_flag,
2462 accessibility_force_disabled,
2463 initial_window_title,
2464 ),
2465 })
2466 }
2467
2468 pub(crate) fn new_focus_listener(
2469 &self,
2470 value: AnyWindowFocusListener,
2471 ) -> (Subscription, impl FnOnce() + use<>) {
2472 self.focus_listeners.insert_pending(value)
2473 }
2474}
2475
2476#[derive(Clone, Debug, Default, PartialEq, Eq)]
2477#[expect(missing_docs)]
2478pub struct DispatchEventResult {
2479 pub propagate: bool,
2480 pub default_prevented: bool,
2481}
2482
2483#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2487#[repr(C)]
2488pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
2489 pub bounds: Bounds<P>,
2491}
2492
2493impl ContentMask<Pixels> {
2494 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
2496 ContentMask {
2497 bounds: self.bounds.scale(factor),
2498 }
2499 }
2500
2501 pub fn intersect(&self, other: &Self) -> Self {
2503 let bounds = self.bounds.intersect(&other.bounds);
2504 ContentMask { bounds }
2505 }
2506}
2507
2508impl Window {
2509 fn mark_view_dirty(&mut self, view_id: EntityId) {
2510 for view_id in self
2513 .rendered_frame
2514 .dispatch_tree
2515 .view_path_reversed(view_id)
2516 {
2517 if !self.dirty_views.insert(view_id) {
2518 break;
2519 }
2520 }
2521 }
2522
2523 pub(crate) fn refresh_visibility(&mut self, cx: &mut App) {
2524 let visibility = self.platform_window.visibility();
2525 if self.visibility != visibility {
2526 self.visibility = visibility;
2527 #[cfg(feature = "profiler")]
2528 profiler::journal::record_window_visibility(self.handle.window_id(), visibility);
2529 self.visibility_observers
2530 .clone()
2531 .retain(|callback| callback(visibility, self, cx));
2532 }
2533 #[cfg(feature = "profiler")]
2534 if self.invalidator.is_dirty() || self.needs_present.get() {
2535 profiler::journal::record_frame_pending(self.handle.window_id(), Instant::now());
2536 }
2537 }
2538
2539 pub fn visibility(&self) -> WindowVisibility {
2542 self.visibility
2543 }
2544
2545 pub fn is_visible(&self) -> bool {
2551 self.visibility.is_visible()
2552 }
2553
2554 pub fn observe_window_visibility(
2556 &self,
2557 mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
2558 ) -> Subscription {
2559 self.visibility_observers
2560 .insert(Box::new(move |visibility, window, cx| {
2561 callback(visibility, window, cx);
2562 true
2563 }))
2564 }
2565
2566 pub fn observe_window_appearance(
2568 &self,
2569 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2570 ) -> Subscription {
2571 self.appearance_observers
2572 .insert(Box::new(move |window, cx| {
2573 callback(window, cx);
2574 true
2575 }))
2576 }
2577
2578 pub fn observe_button_layout_changed(
2580 &self,
2581 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2582 ) -> Subscription {
2583 self.button_layout_observers
2584 .insert(Box::new(move |window, cx| {
2585 callback(window, cx);
2586 true
2587 }))
2588 }
2589
2590 pub fn replace_root<E>(
2592 &mut self,
2593 cx: &mut App,
2594 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
2595 ) -> Entity<E>
2596 where
2597 E: 'static + Render,
2598 {
2599 let view = cx.new(|cx| build_view(self, cx));
2600 self.root = Some(view.clone().into());
2601 self.refresh();
2602 view
2603 }
2604
2605 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
2607 where
2608 E: 'static + Render,
2609 {
2610 self.root
2611 .as_ref()
2612 .map(|view| view.clone().downcast::<E>().ok())
2613 }
2614
2615 pub fn window_handle(&self) -> AnyWindowHandle {
2617 self.handle
2618 }
2619
2620 pub fn refresh(&mut self) {
2622 if self.invalidator.not_drawing() {
2623 self.refreshing = true;
2624 self.invalidator.set_dirty(true);
2625 }
2626 }
2627
2628 pub fn remove_window(&mut self) {
2630 self.removed = true;
2631 }
2632
2633 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
2635 self.focus
2636 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
2637 }
2638
2639 pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
2643 let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
2644 ancestors.iter().rev().find_map(|id| {
2645 self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
2646 FocusHandle::for_id(*id, &cx.focus_handles)
2647 })
2648 }
2649
2650 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
2652 if !self.focus_enabled || self.focus == Some(handle.id) {
2653 return;
2654 }
2655
2656 self.focus = Some(handle.id);
2657 self.focus_generation = self.focus_generation.wrapping_add(1);
2658 self.clear_pending_keystrokes(cx);
2659
2660 self.refresh();
2661 }
2662
2663 pub fn blur(&mut self, cx: &mut App) {
2665 self.clear_pending_keystrokes(cx);
2666
2667 if !self.focus_enabled {
2668 return;
2669 }
2670
2671 if self.focus.is_some() {
2672 self.focus_generation = self.focus_generation.wrapping_add(1);
2673 }
2674 self.focus = None;
2675 self.refresh();
2676 }
2677
2678 pub fn disable_focus(&mut self, cx: &mut App) {
2680 self.blur(cx);
2681 self.focus_enabled = false;
2682 }
2683
2684 pub fn focus_next(&mut self, cx: &mut App) {
2686 if !self.focus_enabled {
2687 return;
2688 }
2689
2690 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
2691 self.focus(&handle, cx)
2692 }
2693 }
2694
2695 pub fn focus_prev(&mut self, cx: &mut App) {
2697 if !self.focus_enabled {
2698 return;
2699 }
2700
2701 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
2702 self.focus(&handle, cx)
2703 }
2704 }
2705
2706 pub fn text_system(&self) -> &Rc<WindowTextSystem> {
2708 &self.text_system
2709 }
2710
2711 pub fn text_style(&self) -> TextStyle {
2713 (*crate::fast::text_style::text_style(self)).clone()
2714 }
2715
2716 pub fn is_maximized(&self) -> bool {
2720 self.platform_window.is_maximized()
2721 }
2722
2723 pub fn request_decorations(&self, decorations: WindowDecorations) {
2725 self.platform_window.request_decorations(decorations);
2726 }
2727
2728 pub fn set_exclusive_zone(&self, zone: Pixels) {
2734 self.platform_window.set_exclusive_zone(zone);
2735 }
2736
2737 #[cfg(all(target_os = "linux", feature = "wayland"))]
2742 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
2743 self.platform_window.set_exclusive_edge(edge);
2744 }
2745
2746 pub fn start_window_resize(&self, edge: ResizeEdge) {
2748 if self.is_resizable {
2749 self.platform_window.start_window_resize(edge);
2750 }
2751 }
2752
2753 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
2760 self.platform_window.set_input_region(region);
2761 }
2762
2763 pub fn window_bounds(&self) -> WindowBounds {
2766 self.platform_window.window_bounds()
2767 }
2768
2769 pub fn inner_window_bounds(&self) -> WindowBounds {
2771 self.platform_window.inner_window_bounds()
2772 }
2773
2774 pub fn native_window_state(&self) -> Option<Vec<u8>> {
2777 self.platform_window.native_window_state()
2778 }
2779
2780 pub fn restore_native_window_state(&self, state: &[u8]) {
2783 self.platform_window.restore_native_window_state(state);
2784 }
2785
2786 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
2788 let focus_id = self.focused(cx).map(|handle| handle.id);
2789
2790 let window = self.handle;
2791 cx.defer(move |cx| {
2792 window
2793 .update(cx, |_, window, cx| {
2794 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
2795 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
2796 })
2797 .with_context(|| format!("dispatching action for window {:?}", window.window_id()))
2798 .log_err();
2799 })
2800 }
2801
2802 pub(crate) fn dispatch_keystroke_observers(
2803 &mut self,
2804 keystroke: &Keystroke,
2805 input_preference: InputPreference,
2806 action: Option<&dyn Action>,
2807 context_stack: Vec<KeyContext>,
2808 cx: &mut App,
2809 ) {
2810 cx.keystroke_observers.clone().retain(move |callback| {
2811 (callback)(
2812 &KeystrokeEvent {
2813 keystroke: keystroke.clone(),
2814 input_preference,
2815 action: action.map(|action| action.boxed_clone()),
2816 context_stack: context_stack.clone(),
2817 },
2818 self,
2819 cx,
2820 )
2821 });
2822 }
2823
2824 pub(crate) fn dispatch_keystroke_interceptors(
2825 &mut self,
2826 keystroke: &Keystroke,
2827 input_preference: InputPreference,
2828 context_stack: Vec<KeyContext>,
2829 cx: &mut App,
2830 ) {
2831 cx.keystroke_interceptors.clone().retain(move |callback| {
2832 (callback)(
2833 &KeystrokeEvent {
2834 keystroke: keystroke.clone(),
2835 input_preference,
2836 action: None,
2837 context_stack: context_stack.clone(),
2838 },
2839 self,
2840 cx,
2841 )
2842 });
2843 }
2844
2845 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2848 let handle = self.handle;
2849 cx.defer(move |cx| {
2850 handle.update(cx, |_, window, cx| f(window, cx)).ok();
2851 });
2852 }
2853
2854 pub fn observe<T: 'static>(
2858 &mut self,
2859 observed: &Entity<T>,
2860 cx: &mut App,
2861 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2862 ) -> Subscription {
2863 let entity_id = observed.entity_id();
2864 let observed = observed.downgrade();
2865 let window_handle = self.handle;
2866 cx.new_observer(
2867 entity_id,
2868 Box::new(move |cx| {
2869 window_handle
2870 .update(cx, |_, window, cx| {
2871 if let Some(handle) = observed.upgrade() {
2872 on_notify(handle, window, cx);
2873 true
2874 } else {
2875 false
2876 }
2877 })
2878 .unwrap_or(false)
2879 }),
2880 )
2881 }
2882
2883 pub fn subscribe<Emitter, Evt>(
2887 &mut self,
2888 entity: &Entity<Emitter>,
2889 cx: &mut App,
2890 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
2891 ) -> Subscription
2892 where
2893 Emitter: EventEmitter<Evt>,
2894 Evt: 'static,
2895 {
2896 let entity_id = entity.entity_id();
2897 let handle = entity.downgrade();
2898 let window_handle = self.handle;
2899 cx.new_subscription(
2900 entity_id,
2901 (
2902 TypeId::of::<Evt>(),
2903 Box::new(move |event, cx| {
2904 window_handle
2905 .update(cx, |_, window, cx| {
2906 if let Some(entity) = handle.upgrade() {
2907 let event = event.downcast_ref().expect("invalid event type");
2908 on_event(entity, event, window, cx);
2909 true
2910 } else {
2911 false
2912 }
2913 })
2914 .unwrap_or(false)
2915 }),
2916 ),
2917 )
2918 }
2919
2920 pub fn observe_release<T>(
2922 &self,
2923 entity: &Entity<T>,
2924 cx: &mut App,
2925 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2926 ) -> Subscription
2927 where
2928 T: 'static,
2929 {
2930 let entity_id = entity.entity_id();
2931 let window_handle = self.handle;
2932 cx.release_listeners.insert(
2933 entity_id,
2934 Box::new(move |entity, cx| {
2935 let entity = entity.downcast_mut().expect("invalid entity type");
2936 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2937 }),
2938 )
2939 }
2940
2941 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2944 AsyncWindowContext::new_context(cx.to_async(), self.handle)
2945 }
2946
2947 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2949 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2950 self.platform_window.schedule_frame();
2951 self.invalidator.wake_platform();
2954 }
2955
2956 pub fn request_animation_frame(&self) {
2969 let entity = self.current_view();
2970 crate::fast::layers::invalidate::note_animation_frame(self, entity);
2971 self.on_next_frame(move |_, cx| cx.notify(entity));
2972 }
2973
2974 #[cfg(any(test, feature = "test-support"))]
2979 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
2980 let callbacks = self.next_frame_callbacks.take();
2981 let count = callbacks.len();
2982 for callback in callbacks {
2983 callback(self, cx);
2984 }
2985 count
2986 }
2987
2988 #[track_caller]
2992 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2993 where
2994 R: 'static,
2995 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2996 {
2997 let handle = self.handle;
2998 cx.spawn(async move |app| {
2999 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3000 f(&mut async_window_cx).await
3001 })
3002 }
3003
3004 #[track_caller]
3008 pub fn spawn_with_priority<AsyncFn, R>(
3009 &self,
3010 priority: Priority,
3011 cx: &App,
3012 f: AsyncFn,
3013 ) -> Task<R>
3014 where
3015 R: 'static,
3016 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3017 {
3018 let handle = self.handle;
3019 cx.spawn_with_priority(priority, async move |app| {
3020 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3021 f(&mut async_window_cx).await
3022 })
3023 }
3024
3025 pub fn bounds_changed(&mut self, cx: &mut App) {
3031 self.scale_factor = self.platform_window.scale_factor();
3032 self.viewport_size = self.platform_window.content_size();
3033 self.mouse_position = self.platform_window.mouse_position();
3034
3035 self.refresh();
3036
3037 self.bounds_observers
3038 .clone()
3039 .retain(|callback| callback(self, cx));
3040 }
3041
3042 fn display_changed(handle: AnyWindowHandle, cx: &mut App) {
3043 let moved_to = handle
3044 .update(cx, |_, window, _| {
3045 let display_id = window.platform_window.display().map(|display| display.id());
3046 let moved = display_id != window.display_id;
3047 window.display_id = display_id;
3048 moved.then_some(display_id)
3049 })
3050 .with_context(|| {
3051 format!(
3052 "handling display change for window {:?}",
3053 handle.window_id()
3054 )
3055 })
3056 .log_err()
3057 .flatten();
3058 let Some(display_id) = moved_to else {
3059 return;
3060 };
3061 if let Some(display_id) = display_id
3065 && !cx.knows_display(display_id)
3066 {
3067 cx.displays_changed();
3068 }
3069 handle
3070 .update(cx, |_, window, cx| window.notify_display_observers(cx))
3071 .with_context(|| {
3072 format!(
3073 "notifying display observers for window {:?}",
3074 handle.window_id()
3075 )
3076 })
3077 .log_err();
3078 }
3079
3080 pub(crate) fn notify_display_observers(&mut self, cx: &mut App) {
3081 self.display_observers
3082 .clone()
3083 .retain(|callback| callback(self, cx));
3084 }
3085
3086 pub fn refresh_interval(&self, cx: &App) -> Option<Duration> {
3091 cx.display_refresh_interval(self.display_id?)
3092 }
3093
3094 pub fn observe_window_display(
3099 &self,
3100 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3101 ) -> Subscription {
3102 self.display_observers.insert(Box::new(move |window, cx| {
3103 callback(window, cx);
3104 true
3105 }))
3106 }
3107
3108 pub fn bounds(&self) -> Bounds<Pixels> {
3110 self.platform_window.bounds()
3111 }
3112
3113 pub fn insets(&self) -> WindowInsets {
3115 self.platform_window.insets()
3116 }
3117
3118 #[cfg(any(test, feature = "test-support"))]
3122 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
3123 self.platform_window
3124 .render_to_image(&self.rendered_frame.scene)
3125 }
3126
3127 #[cfg(feature = "bench-support")]
3130 pub fn rendered_scene(&self) -> &Scene {
3131 &self.rendered_frame.scene
3132 }
3133
3134 #[cfg(any(test, feature = "test-support"))]
3139 pub fn painted_quads(&self) -> Vec<Quad> {
3140 self.rendered_frame.scene.quads.clone()
3141 }
3142
3143 #[cfg(any(test, feature = "test-support"))]
3145 pub fn painted_underlines(&self) -> Vec<Underline> {
3146 self.rendered_frame.scene.underlines.clone()
3147 }
3148
3149 pub fn resize(&mut self, size: Size<Pixels>) {
3151 self.platform_window.resize(size);
3152 }
3153
3154 pub fn is_fullscreen(&self) -> bool {
3156 self.platform_window.is_fullscreen()
3157 }
3158
3159 pub fn is_simple_fullscreen(&self) -> bool {
3163 self.platform_window.is_simple_fullscreen()
3164 }
3165
3166 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
3167 self.appearance = self.platform_window.appearance();
3168
3169 self.appearance_observers
3170 .clone()
3171 .retain(|callback| callback(self, cx));
3172 }
3173
3174 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
3175 self.button_layout_observers
3176 .clone()
3177 .retain(|callback| callback(self, cx));
3178 }
3179
3180 pub fn appearance(&self) -> WindowAppearance {
3182 self.appearance
3183 }
3184
3185 pub fn viewport_size(&self) -> Size<Pixels> {
3187 self.viewport_size
3188 }
3189
3190 pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
3196 self.platform_window.visual_viewport_bounds()
3197 }
3198
3199 pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
3204 let insets = self.platform_window.insets().effective();
3205 let viewport = self.viewport_size();
3206 let left = insets.left.max(Pixels::ZERO).min(viewport.width);
3207 let top = insets.top.max(Pixels::ZERO).min(viewport.height);
3208 let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
3209 let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
3210 let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
3211 let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
3212 visible.size.width = visible.size.width.max(Pixels::ZERO);
3213 visible.size.height = visible.size.height.max(Pixels::ZERO);
3214 visible
3215 }
3216
3217 pub fn request_virtual_keyboard(&self) {
3222 self.platform_window.show_soft_keyboard();
3223 }
3224
3225 pub fn dismiss_virtual_keyboard(&self) {
3227 self.platform_window.hide_soft_keyboard();
3228 }
3229
3230 pub fn is_window_active(&self) -> bool {
3232 self.active.get()
3233 }
3234
3235 pub fn is_window_hovered(&self) -> bool {
3239 if cfg!(any(
3240 target_os = "windows",
3241 target_os = "linux",
3242 target_os = "freebsd"
3243 )) {
3244 self.hovered.get()
3245 } else {
3246 self.is_window_active()
3247 }
3248 }
3249
3250 pub fn zoom_window(&self) {
3252 self.platform_window.zoom();
3253 }
3254
3255 pub fn show_window_menu(&self, position: Point<Pixels>) {
3257 self.platform_window.show_window_menu(position)
3258 }
3259
3260 pub fn start_window_move(&self) {
3265 self.platform_window.start_window_move()
3266 }
3267
3268 pub fn set_client_inset(&mut self, inset: Pixels) {
3270 self.client_inset = Some(inset);
3271 self.platform_window.set_client_inset(inset);
3272 }
3273
3274 pub fn set_client_corner_radii(&mut self, radii: Corners<Pixels>) {
3276 self.platform_window.set_client_corner_radii(radii);
3277 }
3278
3279 pub fn client_inset(&self) -> Option<Pixels> {
3281 self.client_inset
3282 }
3283
3284 pub fn window_decorations(&self) -> Decorations {
3286 self.platform_window.window_decorations()
3287 }
3288
3289 pub fn is_resizable(&self) -> bool {
3291 self.is_resizable
3292 }
3293
3294 pub fn is_minimizable(&self) -> bool {
3296 self.is_minimizable
3297 }
3298
3299 pub fn window_controls(&self) -> WindowControls {
3301 self.platform_window.window_controls()
3302 }
3303
3304 pub fn set_window_title(&mut self, title: &str) {
3306 self.platform_window.set_title(title);
3307 self.a11y.set_window_title(title.to_string());
3308 }
3309
3310 #[cfg(target_os = "macos")]
3312 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
3313 self.platform_window.set_traffic_light_position(position);
3314 }
3315
3316 pub fn set_app_id(&mut self, app_id: &str) {
3318 self.platform_window.set_app_id(app_id);
3319 }
3320
3321 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
3323 self.platform_window
3324 .set_background_appearance(background_appearance);
3325 }
3326
3327 pub fn set_window_edited(&mut self, edited: bool) {
3329 self.platform_window.set_edited(edited);
3330 }
3331
3332 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
3335 self.platform_window.set_document_path(path);
3336 }
3337
3338 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
3340 cx.platform
3341 .displays()
3342 .into_iter()
3343 .find(|display| Some(display.id()) == self.display_id)
3344 }
3345
3346 pub fn show_character_palette(&self) {
3348 self.platform_window.show_character_palette();
3349 }
3350
3351 pub fn scale_factor(&self) -> f32 {
3355 self.scale_factor
3356 }
3357
3358 #[cfg(any(test, feature = "test-support"))]
3360 pub fn set_scale_factor(&mut self, scale_factor: f32) {
3361 self.scale_factor = scale_factor;
3362 self.refresh();
3363 }
3364
3365 pub fn rem_size(&self) -> Pixels {
3368 self.rem_size_override_stack
3369 .last()
3370 .copied()
3371 .unwrap_or(self.rem_size)
3372 }
3373
3374 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
3377 self.rem_size = rem_size.into();
3378 }
3379
3380 pub fn with_global_id<R>(
3383 &mut self,
3384 element_id: ElementId,
3385 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
3386 ) -> R {
3387 self.with_id(element_id, |this| {
3388 let global_id = crate::fast::global_id::current(this);
3389
3390 f(&global_id, this)
3391 })
3392 }
3393
3394 #[inline]
3396 pub fn with_id<R>(
3397 &mut self,
3398 element_id: impl Into<ElementId>,
3399 f: impl FnOnce(&mut Self) -> R,
3400 ) -> R {
3401 self.element_id_stack.push(element_id.into());
3402 let result = f(self);
3403 self.element_id_stack.pop();
3404 result
3405 }
3406
3407 #[inline]
3413 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
3414 where
3415 F: FnOnce(&mut Self) -> R,
3416 {
3417 self.invalidator.debug_assert_paint_or_prepaint();
3418
3419 if let Some(rem_size) = rem_size {
3420 self.rem_size_override_stack.push(rem_size.into());
3421 let result = f(self);
3422 self.rem_size_override_stack.pop();
3423 result
3424 } else {
3425 f(self)
3426 }
3427 }
3428
3429 pub fn line_height(&self) -> Pixels {
3431 self.text_style().line_height_in_pixels(self.rem_size())
3432 }
3433
3434 #[inline]
3436 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
3437 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
3438 }
3439
3440 #[inline]
3442 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
3443 let scale_factor = f64::from(self.scale_factor());
3444 round_half_toward_zero_f64(value * scale_factor) / scale_factor
3445 }
3446
3447 #[inline]
3449 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
3450 bounds.map(|c| self.pixel_snap(c))
3451 }
3452
3453 #[inline]
3455 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
3456 position.map(|c| self.pixel_snap(c))
3457 }
3458
3459 pub fn underline_bounds(
3461 &self,
3462 origin: Point<Pixels>,
3463 width: Pixels,
3464 style: &UnderlineStyle,
3465 ) -> Bounds<ScaledPixels> {
3466 let scale_factor = self.scale_factor();
3467 let thickness = self.snap_stroke(style.thickness);
3468 let height = if style.wavy {
3469 ScaledPixels(thickness.0 * 3.)
3470 } else {
3471 thickness
3472 };
3473 Bounds {
3474 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3475 size: size(self.snap_stroke(width), height),
3476 }
3477 }
3478
3479 pub fn paint_underline_with_exclusions(
3481 &mut self,
3482 origin: Point<Pixels>,
3483 width: Pixels,
3484 style: &UnderlineStyle,
3485 exclusions: &[Range<ScaledPixels>],
3486 ) {
3487 self.invalidator.debug_assert_paint();
3488 let underline = self.underline(origin, width, style);
3489 if exclusions.is_empty() {
3490 self.next_frame.scene.insert_primitive(underline);
3491 return;
3492 }
3493
3494 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
3495 if bounds.is_empty() {
3496 return;
3497 }
3498
3499 let mut exclusions = exclusions
3500 .iter()
3501 .filter_map(|span| {
3502 let start = span.start.max(bounds.left());
3503 let end = span.end.min(bounds.right());
3504 (start < end).then_some(start..end)
3505 })
3506 .collect::<SmallVec<[_; 4]>>();
3507 if exclusions.is_empty() {
3508 self.next_frame.scene.insert_primitive(underline);
3509 return;
3510 }
3511 exclusions.sort_unstable_by_key(|span| span.start);
3512
3513 let mut paint_span = |start, end| {
3514 self.next_frame.scene.insert_primitive(Underline {
3515 content_mask: ContentMask {
3516 bounds: Bounds::from_corners(
3517 point(start, bounds.top()),
3518 point(end, bounds.bottom()),
3519 ),
3520 },
3521 ..underline
3522 });
3523 };
3524 let mut start = bounds.left();
3525 for exclusion in exclusions {
3526 if start < exclusion.start {
3527 paint_span(start, exclusion.start);
3528 }
3529 start = start.max(exclusion.end);
3530 }
3531 if start < bounds.right() {
3532 paint_span(start, bounds.right());
3533 }
3534 }
3535
3536 fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline {
3537 Underline {
3538 order: 0,
3539 pad: 0,
3540 bounds: self.underline_bounds(origin, width, style),
3541 content_mask: self.snapped_content_mask(),
3542 color: style
3543 .color
3544 .unwrap_or_default()
3545 .opacity(self.element_opacity()),
3546 thickness: self.snap_stroke(style.thickness),
3547 wavy: style.wavy.into(),
3548 }
3549 }
3550
3551 #[inline]
3552 pub(crate) fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
3553 let scale_factor = self.scale_factor();
3554 let left = round_to_device_pixel(bounds.left().0, scale_factor);
3555 let top = round_to_device_pixel(bounds.top().0, scale_factor);
3556 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
3557 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
3558 Bounds::from_corners(
3559 point(ScaledPixels(left), ScaledPixels(top)),
3560 point(ScaledPixels(right), ScaledPixels(bottom)),
3561 )
3562 }
3563
3564 #[inline]
3566 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
3567 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
3568 }
3569
3570 #[inline]
3571 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
3572 edges.map(|e| self.snap_stroke(*e))
3573 }
3574
3575 #[inline]
3577 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
3578 let scale_factor = self.scale_factor();
3579 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
3580 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
3581 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
3582 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
3583 Bounds::from_corners(
3584 point(ScaledPixels(left), ScaledPixels(top)),
3585 point(ScaledPixels(right), ScaledPixels(bottom)),
3586 )
3587 }
3588
3589 #[inline]
3590 pub(crate) fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
3591 ContentMask {
3592 bounds: self.cover_bounds(self.content_mask().bounds),
3593 }
3594 }
3595
3596 pub fn prevent_default(&mut self) {
3599 self.default_prevented = true;
3600 }
3601
3602 pub fn default_prevented(&self) -> bool {
3604 self.default_prevented
3605 }
3606
3607 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
3609 let node_id =
3610 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
3611 self.rendered_frame
3612 .dispatch_tree
3613 .is_action_available(action, node_id)
3614 }
3615
3616 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
3618 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
3619 self.rendered_frame
3620 .dispatch_tree
3621 .is_action_available(action, node_id)
3622 }
3623
3624 pub fn mouse_position(&self) -> Point<Pixels> {
3626 crate::fast::dependencies::read_pointer(self);
3627 self.mouse_position
3628 }
3629
3630 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
3637 self.captured_hitbox = Some(hitbox_id);
3638 }
3639
3640 pub fn release_pointer(&mut self) {
3642 self.captured_hitbox = None;
3643 }
3644
3645 pub fn captured_hitbox(&self) -> Option<HitboxId> {
3647 self.captured_hitbox
3648 }
3649
3650 pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
3656 self.long_press_capture = Some(entity.entity_id());
3657 }
3658
3659 pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
3661 self.long_press_capture == Some(entity.entity_id())
3662 }
3663
3664 pub fn modifiers(&self) -> Modifiers {
3666 crate::fast::dependencies::read_keys(self);
3667 self.modifiers
3668 }
3669
3670 pub fn last_input_was_keyboard(&self) -> bool {
3673 self.last_input_modality == InputModality::Keyboard
3674 }
3675
3676 pub fn last_input_was_touch(&self) -> bool {
3678 self.last_input_modality == InputModality::Touch
3679 }
3680
3681 pub fn capslock(&self) -> Capslock {
3683 crate::fast::dependencies::read_keys(self);
3684 self.capslock
3685 }
3686
3687 #[profiling::function]
3690 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
3691 #[cfg(feature = "profiler")]
3694 let frame_dirty = self.invalidator.take_frame_dirty();
3695 #[cfg(feature = "profiler")]
3696 self.window_profiler.begin_draw();
3697
3698 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
3701
3702 if self.platform_window.prepare_frame() {
3703 self.refresh();
3704 }
3705 self.invalidate_entities();
3706 cx.entities.clear_accessed();
3707 debug_assert!(self.rendered_entity_stack.is_empty());
3708 self.invalidator.set_dirty(false);
3709 self.requested_autoscroll = None;
3710
3711 if let Some(input_handler) = self.platform_window.take_input_handler() {
3716 crate::fast::retained::note_restored_input_handler(self, &input_handler);
3717 if let Some(slot) = self
3718 .rendered_frame
3719 .input_handlers
3720 .iter_mut()
3721 .rev()
3722 .find(|h| h.is_none())
3723 {
3724 *slot = Some(input_handler);
3725 } else {
3726 self.rendered_frame.input_handlers.push(Some(input_handler));
3727 }
3728 }
3729 if !cx.mode.skip_drawing() {
3730 self.draw_roots(cx);
3731 #[cfg(feature = "profiler")]
3732 {
3733 let viewport_size = self.viewport_size;
3734 let scale_factor = self.scale_factor();
3735 self.debug_frame_overlay.paint(
3736 &mut self.next_frame.scene,
3737 viewport_size,
3738 scale_factor,
3739 );
3740 }
3741 }
3742 self.dirty_views.clear();
3743 self.next_frame.window_active = self.active.get();
3744
3745 let focused_text_input = if let Some(mut input_handler) = self
3751 .next_frame
3752 .input_handlers
3753 .iter_mut()
3754 .rev()
3755 .find_map(|h| h.take())
3756 {
3757 let accepts_text_input = input_handler.accepts_text_input(self, cx);
3758 crate::fast::retained::note_installed_input_handler(self, &input_handler);
3759 self.platform_window.set_input_handler(input_handler);
3760 self.focus.filter(|_| accepts_text_input)
3761 } else {
3762 None
3763 };
3764 self.apply_text_input_configuration(cx);
3765 let previous = mem::replace(&mut self.focused_text_input, focused_text_input);
3766 if previous.is_some() != focused_text_input.is_some() {
3767 self.platform_window
3768 .text_input_state_changed(if focused_text_input.is_some() {
3769 TextInputStateChange::FocusGained
3770 } else {
3771 TextInputStateChange::FocusLost
3772 });
3773 }
3774
3775 self.layout_engine.as_mut().unwrap().clear();
3776 crate::fast::layout_key::WindowLayout::end_frame(&mut self.fast_layout);
3777 self.text_system().finish_frame();
3778 crate::fast::global_id::GlobalIdCache::finish_frame(&mut self.global_ids);
3779 crate::fast::retained::finish_retained_frame(self);
3780 self.next_frame.finish(&mut self.rendered_frame);
3781
3782 self.invalidator.set_phase(DrawPhase::Focus);
3783 let previous_focus_path = self.rendered_frame.focus_path();
3784 let previous_window_active = self.rendered_frame.window_active;
3785 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
3786 self.next_frame.clear();
3787 let current_focus_path = self.rendered_frame.focus_path();
3788 let current_window_active = self.rendered_frame.window_active;
3789 let mut focus_before_listeners = self.focus;
3790
3791 if previous_focus_path != current_focus_path
3792 || previous_window_active != current_window_active
3793 {
3794 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
3795 self.focus_lost_path = previous_focus_path.clone();
3796 self.focus_lost_listeners
3797 .clone()
3798 .retain(|listener| listener(self, cx));
3799 self.focus_lost_path = SmallVec::new();
3800 focus_before_listeners = self.focus;
3805 }
3806
3807 let event = WindowFocusEvent {
3808 previous_focus_path: if previous_window_active {
3809 previous_focus_path
3810 } else {
3811 Default::default()
3812 },
3813 current_focus_path: if current_window_active {
3814 current_focus_path
3815 } else {
3816 Default::default()
3817 },
3818 };
3819 self.focus_listeners
3820 .clone()
3821 .retain(|listener| listener(&event, self, cx));
3822 }
3823
3824 debug_assert!(self.rendered_entity_stack.is_empty());
3825 self.record_entities_accessed(cx);
3826 self.reset_cursor_style(cx);
3827 self.refreshing = false;
3828 self.invalidator.set_phase(DrawPhase::None);
3829 crate::fast::layers::hover_freeze::release_unhovered(self, cx);
3830 if self.focus != focus_before_listeners {
3835 self.refresh();
3836 }
3837 self.needs_present.set(true);
3838
3839 #[cfg(feature = "profiler")]
3840 {
3841 self.window_profiler
3842 .set_refresh_interval(self.refresh_interval(cx));
3843 let draw_duration = self
3844 .window_profiler
3845 .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
3846 self.debug_frame_overlay.record_frame(draw_duration);
3847 }
3848
3849 arena_scope.exit(&cx.element_arena)
3852 }
3853
3854 fn record_entities_accessed(&mut self, cx: &mut App) {
3855 let entities = cx.entities.take_accessed();
3856 let handle = self.handle;
3857 cx.record_entities_accessed(
3858 handle,
3859 self.invalidator.clone(),
3861 &entities,
3862 );
3863 cx.entities.restore_accessed(entities);
3864 }
3865
3866 fn invalidate_entities(&mut self) {
3867 let mut views = self.invalidator.take_views();
3868 crate::fast::retained::RetainedState::note_notified(&mut self.retained_state, &views);
3869 for entity in views.drain() {
3870 self.mark_view_dirty(entity);
3871 }
3872 self.invalidator.replace_views(views);
3873 }
3874
3875 #[profiling::function]
3876 fn present(&mut self) {
3877 #[cfg(feature = "profiler")]
3878 let _foreground_turn = profiler::journal::foreground_turn();
3879 #[cfg(feature = "profiler")]
3880 let present_start = Instant::now();
3881 crate::fast::composition::present(self);
3882 #[cfg(feature = "profiler")]
3883 self.window_profiler.record_present(
3884 present_start,
3885 Instant::now(),
3886 self.active.get(),
3887 !self.next_frame_callbacks.borrow().is_empty(),
3888 );
3889 self.needs_present.set(false);
3890 profiling::finish_frame!();
3891 }
3892
3893 #[cfg(all(test, feature = "profiler"))]
3895 pub fn present_if_needed(&mut self) {
3896 if self.needs_present.get() {
3897 self.present();
3898 }
3899 }
3900
3901 #[cfg(feature = "profiler")]
3903 pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
3904 self.window_profiler.input_latency_snapshot()
3905 }
3906
3907 #[cfg(feature = "profiler")]
3909 pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
3910 self.window_profiler.frame_duration_snapshot()
3911 }
3912
3913 #[cfg(feature = "profiler")]
3915 pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
3916 self.debug_frame_overlay.mode()
3917 }
3918
3919 #[cfg(feature = "profiler")]
3921 pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
3922 self.debug_frame_overlay.set_mode(mode);
3923 self.refresh();
3924 }
3925
3926 #[cfg(feature = "profiler")]
3929 pub fn cycle_debug_frame_overlay_mode(&mut self) {
3930 self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
3931 }
3932
3933 #[cfg(feature = "profiler")]
3936 pub fn reset_debug_frame_overlay_stats(&mut self) {
3937 self.debug_frame_overlay.reset_stats();
3938 self.refresh();
3939 }
3940
3941 fn draw_roots(&mut self, cx: &mut App) {
3942 crate::fast::retained::begin_frame(self, cx);
3943 self.invalidator.set_phase(DrawPhase::Prepaint);
3944 self.tooltip_bounds.take();
3945
3946 self.a11y.sync_active_flag();
3947 if self.a11y.is_active() {
3948 self.a11y.begin_frame();
3949 }
3950
3951 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
3952 let root_size = {
3953 #[cfg(any(feature = "inspector", debug_assertions))]
3954 {
3955 if self.inspector.is_some() {
3956 let mut size = self.viewport_size;
3957 size.width = (size.width - _inspector_width).max(px(0.0));
3958 size
3959 } else {
3960 self.viewport_size
3961 }
3962 }
3963 #[cfg(not(any(feature = "inspector", debug_assertions)))]
3964 {
3965 self.viewport_size
3966 }
3967 };
3968
3969 let scale_factor = self.scale_factor();
3973 #[cfg(feature = "profiler")]
3974 let request_layout_start = Instant::now();
3975 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
3976 let root_layout_id = root_element.request_layout(self, cx);
3977 crate::fast::stats::FramePhaseTimes::end_build(&mut self.fast_layout.phase_times);
3978 #[cfg(feature = "profiler")]
3979 let prepaint_start = Instant::now();
3980 self.layout_engine
3981 .as_mut()
3982 .unwrap()
3983 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
3984 crate::fast::composition::begin_base_prepaint(self);
3985 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3986
3987 #[cfg(any(feature = "inspector", debug_assertions))]
3988 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
3989
3990 crate::fast::composition::begin_overlay_prepaint(self);
3991 self.prepaint_deferred_draws(cx);
3992
3993 let mut prompt_element = None;
3994 let mut active_drag_element = None;
3995 let mut tooltip_element = None;
3996 if let Some(prompt) = self.prompt.take() {
3997 let mut element = prompt.view.any_view().into_any_element();
3998 let prompt_layout_id = element.request_layout(self, cx);
3999 self.layout_engine
4000 .as_mut()
4001 .unwrap()
4002 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
4003 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
4004 prompt_element = Some(element);
4005 self.prompt = Some(prompt);
4006 } else if let Some(active_drag) = cx.active_drag.take() {
4007 let mut element = active_drag.view.clone().into_any_element();
4008 let offset = self.mouse_position() - active_drag.cursor_offset;
4009 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
4010 active_drag_element = Some(element);
4011 cx.active_drag = Some(active_drag);
4012 } else {
4013 tooltip_element = self.prepaint_tooltip(cx);
4014 }
4015
4016 crate::fast::stats::FramePhaseTimes::end_prepaint(&mut self.fast_layout.phase_times);
4017 crate::fast::composition::finish_input(self);
4018 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
4019
4020 #[cfg(feature = "profiler")]
4022 let paint_start = Instant::now();
4023 self.invalidator.set_phase(DrawPhase::Paint);
4024 crate::fast::composition::begin_base(self);
4025 root_element.paint(self, cx);
4026
4027 #[cfg(any(feature = "inspector", debug_assertions))]
4028 self.paint_inspector(inspector_element, cx);
4029
4030 crate::fast::composition::begin_overlay(self);
4031 self.paint_deferred_draws(cx);
4032
4033 if let Some(mut prompt_element) = prompt_element {
4034 prompt_element.paint(self, cx);
4035 } else if let Some(mut drag_element) = active_drag_element {
4036 drag_element.paint(self, cx);
4037 } else if let Some(mut tooltip_element) = tooltip_element {
4038 tooltip_element.paint(self, cx);
4039 }
4040
4041 #[cfg(any(feature = "inspector", debug_assertions))]
4042 self.paint_inspector_hitbox(cx);
4043 crate::fast::stats::FramePhaseTimes::end_paint(&mut self.fast_layout.phase_times);
4044
4045 #[cfg(feature = "profiler")]
4046 self.window_profiler
4047 .record_draw_phases(profiler::DrawPhases {
4048 request_layout: prepaint_start.duration_since(request_layout_start),
4049 prepaint: paint_start.duration_since(prepaint_start),
4050 paint: Instant::now().duration_since(paint_start),
4051 });
4052
4053 let a11y_active_start_of_frame = self.a11y.is_active();
4055 self.a11y.sync_active_flag();
4056 let a11y_active_end_of_frame = self.a11y.is_active();
4057
4058 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
4059
4060 if a11y_active_start_of_frame {
4061 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
4064 viewport_size: self.viewport_size,
4065 scale_factor: self.scale_factor,
4066 };
4067 let tree_update = self.a11y.end_frame(frame_info);
4069
4070 if should_send_a11y_update {
4071 log::debug!(
4072 "Sending a11y tree update: {} nodes",
4073 tree_update.nodes.len()
4074 );
4075 self.platform_window.a11y_tree_update(tree_update);
4076 }
4077 }
4078 }
4079
4080 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
4081 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
4083 let Some(Some(tooltip_request)) = self
4084 .next_frame
4085 .tooltip_requests
4086 .get(tooltip_request_index)
4087 .cloned()
4088 else {
4089 log::error!("Unexpectedly absent TooltipRequest");
4090 continue;
4091 };
4092 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
4093 let mouse_position = tooltip_request.tooltip.mouse_position;
4094 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
4095
4096 let mut tooltip_bounds =
4097 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
4098 let window_bounds = Bounds {
4099 origin: Point::default(),
4100 size: self.viewport_size(),
4101 };
4102
4103 if tooltip_bounds.right() > window_bounds.right() {
4104 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
4105 if new_x >= Pixels::ZERO {
4106 tooltip_bounds.origin.x = new_x;
4107 } else {
4108 tooltip_bounds.origin.x = cmp::max(
4109 Pixels::ZERO,
4110 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
4111 );
4112 }
4113 }
4114
4115 if tooltip_bounds.bottom() > window_bounds.bottom() {
4116 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
4117 if new_y >= Pixels::ZERO {
4118 tooltip_bounds.origin.y = new_y;
4119 } else {
4120 tooltip_bounds.origin.y = cmp::max(
4121 Pixels::ZERO,
4122 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
4123 );
4124 }
4125 }
4126
4127 let is_visible =
4131 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
4132 if !is_visible {
4133 continue;
4134 }
4135
4136 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
4137 element.prepaint(window, cx)
4138 });
4139
4140 self.tooltip_bounds = Some(TooltipBounds {
4141 id: tooltip_request.id,
4142 bounds: tooltip_bounds,
4143 });
4144 return Some(element);
4145 }
4146 None
4147 }
4148
4149 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
4150 assert_eq!(self.element_id_stack.len(), 0);
4151
4152 let mut round_start = 0;
4163 let mut depth = 0;
4164 loop {
4165 let round_end = self.next_frame.deferred_draws.len();
4166 if round_start == round_end {
4167 break;
4168 }
4169 assert!(depth < 10, "Exceeded maximum (10) deferred depth");
4171 depth += 1;
4172
4173 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
4175 traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
4176
4177 for deferred_draw_ix in traversal_order {
4178 let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
4179 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
4180 self.element_id_stack
4181 .clone_from(&deferred_draw.element_id_stack);
4182 self.text_style_stack
4183 .clone_from(&deferred_draw.text_style_stack);
4184 (
4185 deferred_draw.element.take(),
4186 deferred_draw.parent_node,
4187 deferred_draw.current_view,
4188 deferred_draw.rem_size,
4189 deferred_draw.absolute_offset,
4190 deferred_draw.prepaint_range.clone(),
4191 )
4192 };
4193 self.next_frame.dispatch_tree.set_active_node(parent_node);
4194
4195 let prepaint_start = self.prepaint_index();
4196 if let Some(mut element) = element {
4197 let recording =
4198 crate::fast::retained::begin_deferred_prepaint(self, deferred_draw_ix, cx);
4199 let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
4200 self.with_rendered_view(current_view, |window| {
4201 window.with_rem_size(Some(rem_size), |window| {
4202 window.with_absolute_element_offset(absolute_offset, |window| {
4203 element.prepaint(window, cx);
4204 });
4205 });
4206 });
4207 });
4208 crate::fast::retained::finish_deferred(self, recording, cx);
4209 self.next_frame.deferred_draws[deferred_draw_ix].accessed_entities =
4210 accessed_entities;
4211 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
4212 } else {
4213 cx.entities.extend_accessed(
4214 self.next_frame.deferred_draws[deferred_draw_ix]
4215 .accessed_entities
4216 .iter()
4217 .copied(),
4218 );
4219 self.reuse_prepaint(prepaint_range);
4220 }
4221 let prepaint_end = self.prepaint_index();
4222 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
4223 prepaint_start..prepaint_end;
4224 }
4225
4226 self.element_id_stack.clear();
4227 self.text_style_stack.clear();
4228 round_start = round_end;
4229 }
4230 }
4231
4232 fn paint_deferred_draws(&mut self, cx: &mut App) {
4233 assert_eq!(self.element_id_stack.len(), 0);
4234
4235 if self.next_frame.deferred_draws.len() == 0 {
4238 return;
4239 }
4240
4241 let traversal_order = self.deferred_draw_traversal_order();
4242 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
4243 for deferred_draw_ix in traversal_order {
4244 let deferred_draw = &mut deferred_draws[deferred_draw_ix];
4245 self.element_id_stack
4246 .clone_from(&deferred_draw.element_id_stack);
4247 self.next_frame
4248 .dispatch_tree
4249 .set_active_node(deferred_draw.parent_node);
4250
4251 let paint_start = self.paint_index();
4252 let content_mask = deferred_draw.content_mask;
4253 if let Some(element) = deferred_draw.element.as_mut() {
4254 let enclosing = &deferred_draw.enclosing_retained;
4255 let recording = crate::fast::retained::begin_deferred_paint(self, enclosing, cx);
4256 let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
4257 self.with_rendered_view(deferred_draw.current_view, |window| {
4258 window.with_content_mask(content_mask, |window| {
4259 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
4260 element.paint(window, cx);
4261 });
4262 })
4263 })
4264 });
4265 crate::fast::retained::finish_deferred(self, recording, cx);
4266 deferred_draw.accessed_entities.extend(accessed_entities);
4267 } else {
4268 self.reuse_paint(deferred_draw.paint_range.clone());
4269 }
4270 let paint_end = self.paint_index();
4271 deferred_draw.paint_range = paint_start..paint_end;
4272 }
4273 self.next_frame.deferred_draws = deferred_draws;
4274 self.element_id_stack.clear();
4275 }
4276
4277 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
4278 let deferred_count = self.next_frame.deferred_draws.len();
4279 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
4280 sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
4281 sorted_indices
4282 }
4283
4284 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
4285 PrepaintStateIndex {
4286 hitboxes_index: self.next_frame.hitboxes.len(),
4287 tooltips_index: self.next_frame.tooltip_requests.len(),
4288 deferred_draws_index: self.next_frame.deferred_draws.len(),
4289 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
4290 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
4291 line_layout_index: self.text_system.layout_index(),
4292 fast_a11y_index: crate::fast::a11y::ops_index(self),
4293 }
4294 }
4295
4296 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
4297 crate::fast::a11y::reuse_prepaint(self, &range);
4298 self.next_frame.hitboxes.extend(
4299 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
4300 .iter()
4301 .cloned(),
4302 );
4303 self.next_frame.tooltip_requests.extend(
4304 self.rendered_frame.tooltip_requests
4305 [range.start.tooltips_index..range.end.tooltips_index]
4306 .iter_mut()
4307 .map(|request| request.take()),
4308 );
4309 self.next_frame.accessed_element_states.extend(
4310 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
4311 ..range.end.accessed_element_states_index]
4312 .iter()
4313 .map(|(id, type_id)| (id.clone(), *type_id)),
4314 );
4315 self.text_system
4316 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
4317
4318 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
4319 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
4320 &mut self.rendered_frame.dispatch_tree,
4321 self.focus,
4322 );
4323
4324 if reused_subtree.contains_focus() {
4325 self.next_frame.focus = self.focus;
4326 }
4327
4328 self.next_frame.deferred_draws.extend(
4329 self.rendered_frame.deferred_draws
4330 [range.start.deferred_draws_index..range.end.deferred_draws_index]
4331 .iter()
4332 .map(|deferred_draw| DeferredDraw {
4333 current_view: deferred_draw.current_view,
4334 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
4335 element_id_stack: deferred_draw.element_id_stack.clone(),
4336 text_style_stack: deferred_draw.text_style_stack.clone(),
4337 content_mask: deferred_draw.content_mask,
4338 rem_size: deferred_draw.rem_size,
4339 priority: deferred_draw.priority,
4340 element: None,
4341 absolute_offset: deferred_draw.absolute_offset,
4342 prepaint_range: deferred_draw.prepaint_range.clone(),
4343 paint_range: deferred_draw.paint_range.clone(),
4344 accessed_entities: deferred_draw.accessed_entities.clone(),
4345 enclosing_retained: crate::fast::retained::EnclosingRetained::default(),
4346 }),
4347 );
4348 }
4349
4350 pub(crate) fn paint_index(&self) -> PaintIndex {
4351 PaintIndex {
4352 scene_index: self.next_frame.scene.len(),
4353 #[cfg(any(test, feature = "test-support"))]
4354 debug_bounds_index: self.next_frame.debug_bounds_records.len(),
4355 fast: crate::fast::retained::FastPaintIndex::new(self),
4356 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
4357 input_handlers_index: self.next_frame.input_handlers.len(),
4358 cursor_styles_index: self.next_frame.cursor_styles.len(),
4359 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
4360 tab_handle_index: self.next_frame.tab_stops.paint_index(),
4361 line_layout_index: self.text_system.layout_index(),
4362 }
4363 }
4364
4365 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
4366 crate::fast::retained::reuse_paint_records(self, &range);
4367 crate::fast::composition::reuse_starts(self, &range);
4368 #[cfg(any(test, feature = "test-support"))]
4370 for (selector, bounds) in &self.rendered_frame.debug_bounds_records
4371 [range.start.debug_bounds_index..range.end.debug_bounds_index]
4372 {
4373 self.next_frame
4374 .record_debug_bounds(selector.clone(), *bounds);
4375 }
4376 self.next_frame.cursor_styles.extend(
4377 self.rendered_frame.cursor_styles
4378 [range.start.cursor_styles_index..range.end.cursor_styles_index]
4379 .iter()
4380 .cloned(),
4381 );
4382 self.next_frame.input_handlers.extend(
4383 self.rendered_frame.input_handlers
4384 [range.start.input_handlers_index..range.end.input_handlers_index]
4385 .iter_mut()
4386 .map(|handler| handler.take()),
4387 );
4388 self.next_frame.mouse_listeners.extend(
4389 self.rendered_frame.mouse_listeners
4390 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
4391 .iter_mut()
4392 .map(|listener| listener.take()),
4393 );
4394 self.next_frame.accessed_element_states.extend(
4395 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
4396 ..range.end.accessed_element_states_index]
4397 .iter()
4398 .map(|(id, type_id)| (id.clone(), *type_id)),
4399 );
4400 self.next_frame.tab_stops.replay(
4401 &self.rendered_frame.tab_stops.insertion_history
4402 [range.start.tab_handle_index..range.end.tab_handle_index],
4403 );
4404
4405 self.text_system
4406 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
4407 self.next_frame.scene.replay(
4408 range.start.scene_index..range.end.scene_index,
4409 &self.rendered_frame.scene,
4410 );
4411 }
4412
4413 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
4417 where
4418 F: FnOnce(&mut Self) -> R,
4419 {
4420 self.invalidator.debug_assert_paint_or_prepaint();
4421 if let Some(style) = style {
4422 self.text_style_stack.push(style);
4423 let result = f(self);
4424 self.text_style_stack.pop();
4425 result
4426 } else {
4427 f(self)
4428 }
4429 }
4430
4431 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
4434 self.invalidator.debug_assert_paint();
4435 self.next_frame.cursor_styles.push(CursorStyleRequest {
4436 hitbox_id: Some(hitbox.id),
4437 style,
4438 });
4439 }
4440
4441 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
4446 self.invalidator.debug_assert_paint();
4447 self.next_frame.cursor_styles.push(CursorStyleRequest {
4448 hitbox_id: None,
4449 style,
4450 })
4451 }
4452
4453 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
4456 self.invalidator.debug_assert_prepaint();
4457 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
4458 self.next_frame
4459 .tooltip_requests
4460 .push(Some(TooltipRequest { id, tooltip }));
4461 id
4462 }
4463
4464 #[inline]
4469 pub fn with_content_mask<R>(
4470 &mut self,
4471 mask: Option<ContentMask<Pixels>>,
4472 f: impl FnOnce(&mut Self) -> R,
4473 ) -> R {
4474 self.invalidator.debug_assert_paint_or_prepaint();
4475 if let Some(mask) = mask {
4476 let mask = mask.intersect(&self.content_mask());
4477 self.content_mask_stack.push(mask);
4478 let result = f(self);
4479 self.content_mask_stack.pop();
4480 result
4481 } else {
4482 f(self)
4483 }
4484 }
4485
4486 pub fn with_element_offset<R>(
4489 &mut self,
4490 offset: Point<Pixels>,
4491 f: impl FnOnce(&mut Self) -> R,
4492 ) -> R {
4493 self.invalidator.debug_assert_prepaint();
4494
4495 if offset.is_zero() {
4496 return f(self);
4497 };
4498
4499 let abs_offset = self.element_offset() + offset;
4500 self.with_absolute_element_offset(abs_offset, f)
4501 }
4502
4503 pub fn with_absolute_element_offset<R>(
4507 &mut self,
4508 offset: Point<Pixels>,
4509 f: impl FnOnce(&mut Self) -> R,
4510 ) -> R {
4511 self.invalidator.debug_assert_prepaint();
4512 self.element_offset_stack.push(offset);
4513 let result = f(self);
4514 self.element_offset_stack.pop();
4515 result
4516 }
4517
4518 pub(crate) fn with_element_opacity<R>(
4519 &mut self,
4520 opacity: Option<f32>,
4521 f: impl FnOnce(&mut Self) -> R,
4522 ) -> R {
4523 self.invalidator.debug_assert_paint_or_prepaint();
4524
4525 let Some(opacity) = opacity else {
4526 return f(self);
4527 };
4528
4529 let previous_opacity = self.element_opacity;
4530 self.element_opacity = previous_opacity * opacity;
4531 let result = f(self);
4532 self.element_opacity = previous_opacity;
4533 result
4534 }
4535
4536 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
4542 self.invalidator.debug_assert_prepaint();
4543 let index = self.prepaint_index();
4544 let result = f(self);
4545 if result.is_err() {
4546 self.next_frame.hitboxes.truncate(index.hitboxes_index);
4547 self.next_frame
4548 .tooltip_requests
4549 .truncate(index.tooltips_index);
4550 self.next_frame
4551 .deferred_draws
4552 .truncate(index.deferred_draws_index);
4553 self.next_frame
4554 .dispatch_tree
4555 .truncate(index.dispatch_tree_index);
4556 self.next_frame
4557 .accessed_element_states
4558 .truncate(index.accessed_element_states_index);
4559 self.text_system.truncate_layouts(index.line_layout_index);
4560 }
4561 result
4562 }
4563
4564 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
4570 self.invalidator.debug_assert_prepaint();
4571 self.requested_autoscroll = Some(bounds);
4572 }
4573
4574 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
4577 self.invalidator.debug_assert_prepaint();
4578 self.requested_autoscroll.take()
4579 }
4580
4581 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4587 cx.asset_entry::<A>(source).use_by(self.current_view())
4588 }
4589
4590 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4596 cx.fetch_asset::<A>(source)
4597 }
4598 pub fn element_offset(&self) -> Point<Pixels> {
4601 self.invalidator.debug_assert_prepaint();
4602 self.element_offset_stack
4603 .last()
4604 .copied()
4605 .unwrap_or_default()
4606 }
4607
4608 #[inline]
4611 pub(crate) fn element_opacity(&self) -> f32 {
4612 self.invalidator.debug_assert_paint_or_prepaint();
4613 self.element_opacity
4614 }
4615
4616 pub fn content_mask(&self) -> ContentMask<Pixels> {
4618 self.invalidator.debug_assert_paint_or_prepaint();
4619 self.content_mask_stack
4620 .last()
4621 .cloned()
4622 .unwrap_or_else(|| ContentMask {
4623 bounds: Bounds {
4624 origin: Point::default(),
4625 size: self.viewport_size,
4626 },
4627 })
4628 }
4629
4630 pub fn with_element_namespace<R>(
4633 &mut self,
4634 element_id: impl Into<ElementId>,
4635 f: impl FnOnce(&mut Self) -> R,
4636 ) -> R {
4637 self.element_id_stack.push(element_id.into());
4638 let result = f(self);
4639 self.element_id_stack.pop();
4640 result
4641 }
4642
4643 pub fn use_keyed_state<S: 'static>(
4645 &mut self,
4646 key: impl Into<ElementId>,
4647 cx: &mut App,
4648 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4649 ) -> Entity<S> {
4650 let current_view = self.current_view();
4651 self.with_global_id(key.into(), |global_id, window| {
4652 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
4653 if let Some(state) = state {
4654 (state.clone(), state)
4655 } else {
4656 let new_state = cx.new(|cx| init(window, cx));
4657 Self::observe_keyed_state(&new_state, current_view, cx);
4658 (new_state.clone(), new_state)
4659 }
4660 })
4661 })
4662 }
4663
4664 #[track_caller]
4670 pub fn use_state<S: 'static>(
4671 &mut self,
4672 cx: &mut App,
4673 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4674 ) -> Entity<S> {
4675 self.use_keyed_state(
4676 ElementId::CodeLocation(*core::panic::Location::caller()),
4677 cx,
4678 init,
4679 )
4680 }
4681
4682 #[inline(always)]
4687 pub fn with_element_state<S, R>(
4688 &mut self,
4689 global_id: &GlobalElementId,
4690 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
4691 ) -> R
4692 where
4693 S: 'static,
4694 {
4695 self.invalidator.debug_assert_paint_or_prepaint();
4696
4697 let (key, state) = self.take_element_state(global_id, TypeId::of::<S>());
4698
4699 if let Some(any) = state {
4700 let ElementStateBox {
4701 inner,
4702 #[cfg(debug_assertions)]
4703 type_name,
4704 } = any;
4705 let mut state_box = inner
4707 .downcast::<Option<S>>()
4708 .map_err(|_| {
4709 #[cfg(debug_assertions)]
4710 {
4711 anyhow::anyhow!(
4712 "invalid element state type for id, requested {:?}, actual: {:?}",
4713 std::any::type_name::<S>(),
4714 type_name
4715 )
4716 }
4717
4718 #[cfg(not(debug_assertions))]
4719 {
4720 anyhow::anyhow!(
4721 "invalid element state type for id, requested {:?}",
4722 std::any::type_name::<S>(),
4723 )
4724 }
4725 })
4726 .unwrap();
4727
4728 let state = state_box.take().expect(
4729 "reentrant call to with_element_state for the same state type and element id",
4730 );
4731 let (result, state) = f(Some(state), self);
4732 state_box.replace(state);
4733 self.insert_element_state(
4734 key,
4735 ElementStateBox {
4736 inner: state_box,
4737 #[cfg(debug_assertions)]
4738 type_name,
4739 },
4740 );
4741 result
4742 } else {
4743 let (result, state) = f(None, self);
4744 self.insert_element_state(
4745 key,
4746 ElementStateBox {
4747 inner: Box::new(Some(state)),
4748 #[cfg(debug_assertions)]
4749 type_name: std::any::type_name::<S>(),
4750 },
4751 );
4752 result
4753 }
4754 }
4755
4756 pub fn with_optional_element_state<S, R>(
4763 &mut self,
4764 global_id: Option<&GlobalElementId>,
4765 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
4766 ) -> R
4767 where
4768 S: 'static,
4769 {
4770 self.invalidator.debug_assert_paint_or_prepaint();
4771
4772 if let Some(global_id) = global_id {
4773 self.with_element_state(global_id, |state, cx| {
4774 let (result, state) = f(Some(state), cx);
4775 let state =
4776 state.expect("you must return some state when you pass some element id");
4777 (result, state)
4778 })
4779 } else {
4780 let (result, state) = f(None, self);
4781 debug_assert!(
4782 state.is_none(),
4783 "you must not return an element state when passing None for the global id"
4784 );
4785 result
4786 }
4787 }
4788
4789 #[inline]
4791 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
4792 if let Some(index) = index {
4793 self.next_frame.tab_stops.begin_group(index);
4794 let result = f(self);
4795 self.next_frame.tab_stops.end_group();
4796 result
4797 } else {
4798 f(self)
4799 }
4800 }
4801
4802 pub fn defer_draw(
4811 &mut self,
4812 element: AnyElement,
4813 absolute_offset: Point<Pixels>,
4814 priority: usize,
4815 content_mask: Option<ContentMask<Pixels>>,
4816 ) {
4817 self.invalidator.debug_assert_prepaint();
4818 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
4819 self.next_frame.deferred_draws.push(DeferredDraw {
4820 current_view: self.current_view(),
4821 parent_node,
4822 element_id_stack: self.element_id_stack.clone(),
4823 text_style_stack: self.text_style_stack.clone(),
4824 content_mask,
4825 rem_size: self.rem_size(),
4826 priority,
4827 element: Some(element),
4828 absolute_offset,
4829 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
4830 paint_range: PaintIndex::default()..PaintIndex::default(),
4831 accessed_entities: FxHashSet::default(),
4832 enclosing_retained: crate::fast::retained::enclosing_retained(self),
4833 });
4834 }
4835
4836 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
4842 self.invalidator.debug_assert_paint();
4843
4844 let content_mask = self.content_mask();
4845 let clipped_bounds = bounds.intersect(&content_mask.bounds);
4846 if !clipped_bounds.is_empty() {
4847 self.next_frame
4848 .scene
4849 .push_layer(self.cover_bounds(clipped_bounds));
4850 }
4851
4852 let result = f(self);
4853
4854 if !clipped_bounds.is_empty() {
4855 self.next_frame.scene.pop_layer();
4856 }
4857
4858 result
4859 }
4860
4861 pub fn paint_drop_shadows(
4867 &mut self,
4868 bounds: Bounds<Pixels>,
4869 corner_radii: Corners<Pixels>,
4870 shadows: &[BoxShadow],
4871 ) {
4872 self.invalidator.debug_assert_paint();
4873
4874 let scale_factor = self.scale_factor();
4875 let content_mask = self.snapped_content_mask();
4876 let opacity = self.element_opacity();
4877 let element_bounds = self.cover_bounds(bounds);
4878 let element_corner_radii = corner_radii.scale(scale_factor);
4879 for shadow in shadows {
4880 if shadow.inset {
4881 continue;
4882 }
4883 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
4884 self.next_frame.scene.insert_primitive(Shadow {
4885 order: 0,
4886 blur_radius: shadow.blur_radius.scale(scale_factor),
4887 bounds: self.cover_bounds(shadow_bounds),
4888 content_mask,
4889 corner_radii: corner_radii.scale(scale_factor),
4890 color: shadow.color.opacity(opacity),
4891 element_bounds,
4892 element_corner_radii,
4893 inset: 0,
4894 pad: 0,
4895 });
4896 }
4897 }
4898
4899 pub fn paint_inset_shadows(
4903 &mut self,
4904 bounds: Bounds<Pixels>,
4905 corner_radii: Corners<Pixels>,
4906 shadows: &[BoxShadow],
4907 ) {
4908 self.invalidator.debug_assert_paint();
4909
4910 let scale_factor = self.scale_factor();
4911 let content_mask = self.snapped_content_mask();
4912 let opacity = self.element_opacity();
4913 let element_bounds = self.cover_bounds(bounds);
4914 let element_corner_radii = corner_radii.scale(scale_factor);
4915 for shadow in shadows {
4916 if !shadow.inset {
4917 continue;
4918 }
4919 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
4920 let zero = Pixels::ZERO;
4923 let hole_corner_radii = Corners {
4924 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
4925 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
4926 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
4927 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
4928 };
4929 self.next_frame.scene.insert_primitive(Shadow {
4930 order: 0,
4931 blur_radius: shadow.blur_radius.scale(scale_factor),
4932 bounds: self.cover_bounds(hole),
4933 content_mask,
4934 corner_radii: hole_corner_radii.scale(scale_factor),
4935 color: shadow.color.opacity(opacity),
4936 element_bounds,
4937 element_corner_radii,
4938 inset: 1,
4939 pad: 0,
4940 });
4941 }
4942 }
4943
4944 fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
4945 let radii = &quad.corner_radii;
4946 let widths = &quad.border_widths;
4947 let edge_radii = Edges {
4948 top: radii.top_left.max(radii.top_right),
4949 right: radii.top_right.max(radii.bottom_right),
4950 bottom: radii.bottom_left.max(radii.bottom_right),
4951 left: radii.top_left.max(radii.bottom_left),
4952 };
4953
4954 let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
4955 let inset_bounds = |top_left_inset, bottom_right_inset| {
4956 Bounds::from_corners(
4957 quad.bounds.origin + top_left_inset + antialias_inset,
4958 quad.bounds.bottom_right() - bottom_right_inset - antialias_inset,
4959 )
4960 };
4961
4962 let horizontal_band = inset_bounds(
4965 point(widths.left, widths.top.max(edge_radii.top)),
4966 point(widths.right, widths.bottom.max(edge_radii.bottom)),
4967 );
4968 let vertical_band = inset_bounds(
4969 point(widths.left.max(edge_radii.left), widths.top),
4970 point(widths.right.max(edge_radii.right), widths.bottom),
4971 );
4972
4973 let area = |bounds: &Bounds<ScaledPixels>| {
4974 bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.)
4975 };
4976 if area(&horizontal_band) >= area(&vertical_band) {
4977 horizontal_band
4978 } else {
4979 vertical_band
4980 }
4981 }
4982
4983 pub fn paint_quad(&mut self, quad: PaintQuad) {
4993 self.invalidator.debug_assert_paint();
4994
4995 let opacity = self.element_opacity();
4996 let snapped_bounds = self.snap_bounds(quad.bounds);
4997 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
4998 let quad = Quad {
4999 order: 0,
5000 bounds: snapped_bounds,
5001 content_mask: self.snapped_content_mask(),
5002 background: quad.background.opacity(opacity),
5003 border_color: quad.border_color.opacity(opacity),
5004 corner_radii: quad.corner_radii.scale(self.scale_factor()),
5005 border_widths: snapped_border_widths,
5006 border_style: quad.border_style,
5007 };
5008
5009 if !quad.background.is_transparent() {
5010 self.next_frame.scene.insert_primitive(quad);
5011 return;
5012 }
5013
5014 let outer_bounds = quad.bounds;
5017 let inner_bounds = Self::largest_border_interior(&quad);
5018
5019 if inner_bounds.is_empty() {
5020 self.next_frame.scene.insert_primitive(quad);
5021 return;
5022 }
5023
5024 let strips = [
5025 Bounds::from_corners(
5027 outer_bounds.origin,
5028 point(outer_bounds.right(), inner_bounds.top()),
5029 ),
5030 Bounds::from_corners(
5032 point(outer_bounds.left(), inner_bounds.bottom()),
5033 outer_bounds.bottom_right(),
5034 ),
5035 Bounds::from_corners(
5037 point(outer_bounds.left(), inner_bounds.top()),
5038 inner_bounds.bottom_left(),
5039 ),
5040 Bounds::from_corners(
5042 inner_bounds.top_right(),
5043 point(outer_bounds.right(), inner_bounds.bottom()),
5044 ),
5045 ];
5046
5047 for strip in strips {
5048 let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
5049 if !content_mask_bounds.is_empty() {
5050 self.next_frame.scene.insert_primitive(Quad {
5051 content_mask: ContentMask {
5052 bounds: content_mask_bounds,
5053 },
5054 ..quad
5055 });
5056 }
5057 }
5058 }
5059
5060 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
5064 self.invalidator.debug_assert_paint();
5065
5066 let scale_factor = self.scale_factor();
5067 let content_mask = self.content_mask();
5068 let opacity = self.element_opacity();
5069 path.content_mask = content_mask;
5070 let color: Background = color.into();
5071 path.color = color.opacity(opacity);
5072 self.next_frame
5073 .scene
5074 .insert_primitive(crate::fast::layers::paint::snap_path(
5075 path.scale(scale_factor),
5076 ));
5077 }
5078
5079 pub fn paint_underline(
5083 &mut self,
5084 origin: Point<Pixels>,
5085 width: Pixels,
5086 style: &UnderlineStyle,
5087 ) {
5088 self.invalidator.debug_assert_paint();
5089 let underline = self.underline(origin, width, style);
5090 self.next_frame.scene.insert_primitive(underline);
5091 }
5092
5093 pub fn paint_strikethrough(
5097 &mut self,
5098 origin: Point<Pixels>,
5099 width: Pixels,
5100 style: &StrikethroughStyle,
5101 ) {
5102 self.invalidator.debug_assert_paint();
5103
5104 let scale_factor = self.scale_factor();
5105 let height = style.thickness;
5106 let bounds = Bounds {
5107 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
5108 size: size(self.snap_stroke(width), self.snap_stroke(height)),
5109 };
5110 let opacity = self.element_opacity();
5111
5112 self.next_frame.scene.insert_primitive(Underline {
5113 order: 0,
5114 pad: 0,
5115 bounds,
5116 content_mask: self.snapped_content_mask(),
5117 thickness: self.snap_stroke(style.thickness),
5118 color: style.color.unwrap_or_default().opacity(opacity),
5119 wavy: false.into(),
5120 });
5121 }
5122
5123 pub fn paint_glyph(
5132 &mut self,
5133 origin: Point<Pixels>,
5134 font_id: FontId,
5135 glyph_id: GlyphId,
5136 font_size: Pixels,
5137 color: Hsla,
5138 ) -> Result<()> {
5139 self.invalidator.debug_assert_paint();
5140
5141 let element_opacity = self.element_opacity();
5142 let scale_factor = self.scale_factor();
5143 let glyph_origin = origin.scale(scale_factor);
5144
5145 let (integer_origin, subpixel_variant) = crate::fast::glyphs::quantize_origin(glyph_origin);
5146 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
5147 let dilation = self.text_system().glyph_dilation_for_color(color);
5148 let params = RenderGlyphParams {
5149 font_id,
5150 glyph_id,
5151 font_size,
5152 subpixel_variant,
5153 scale_factor,
5154 is_emoji: false,
5155 subpixel_rendering,
5156 dilation,
5157 };
5158
5159 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
5160 if !raster_bounds.is_zero() {
5161 let tile = self
5162 .sprite_atlas
5163 .get_or_insert_with(params.clone().into(), &mut || {
5164 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
5165 Ok(Some((size, Cow::Owned(bytes))))
5166 })?
5167 .expect("Callback above only errors or returns Some");
5168 let bounds = Bounds {
5169 origin: integer_origin + raster_bounds.origin.map(Into::into),
5170 size: tile.bounds.size.map(Into::into),
5171 };
5172 let content_mask = self.snapped_content_mask();
5173
5174 if subpixel_rendering {
5175 self.next_frame.scene.insert_primitive(SubpixelSprite {
5176 order: 0,
5177 pad: 0,
5178 bounds,
5179 content_mask,
5180 color: color.opacity(element_opacity),
5181 tile,
5182 transformation: TransformationMatrix::unit(),
5183 });
5184 } else {
5185 self.next_frame.scene.insert_primitive(MonochromeSprite {
5186 order: 0,
5187 pad: 0,
5188 bounds,
5189 content_mask,
5190 color: color.opacity(element_opacity),
5191 tile,
5192 transformation: TransformationMatrix::unit(),
5193 });
5194 }
5195 }
5196 Ok(())
5197 }
5198
5199 pub(crate) fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
5200 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
5201 return false;
5202 }
5203
5204 if !self.platform_window.is_subpixel_rendering_supported() {
5205 return false;
5206 }
5207
5208 let mode = match self.text_rendering_mode.get() {
5209 TextRenderingMode::PlatformDefault => self
5210 .text_system()
5211 .recommended_rendering_mode(font_id, font_size),
5212 mode => mode,
5213 };
5214
5215 mode == TextRenderingMode::Subpixel
5216 }
5217
5218 pub fn paint_emoji(
5227 &mut self,
5228 origin: Point<Pixels>,
5229 font_id: FontId,
5230 glyph_id: GlyphId,
5231 font_size: Pixels,
5232 ) -> Result<()> {
5233 self.invalidator.debug_assert_paint();
5234
5235 let scale_factor = self.scale_factor();
5236 let glyph_origin = origin.scale(scale_factor);
5237 let integer_origin = crate::fast::glyphs::quantize_emoji_origin(glyph_origin);
5238 let params = RenderGlyphParams {
5239 font_id,
5240 glyph_id,
5241 font_size,
5242 subpixel_variant: Default::default(),
5243 scale_factor,
5244 is_emoji: true,
5245 subpixel_rendering: false,
5246 dilation: 0,
5247 };
5248
5249 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
5250 if !raster_bounds.is_zero() {
5251 let tile = self
5252 .sprite_atlas
5253 .get_or_insert_with(params.clone().into(), &mut || {
5254 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
5255 Ok(Some((size, Cow::Owned(bytes))))
5256 })?
5257 .expect("Callback above only errors or returns Some");
5258
5259 let bounds = Bounds {
5260 origin: integer_origin + raster_bounds.origin.map(Into::into),
5261 size: tile.bounds.size.map(Into::into),
5262 };
5263 let content_mask = self.snapped_content_mask();
5264 let opacity = self.element_opacity();
5265
5266 self.next_frame.scene.insert_primitive(PolychromeSprite {
5267 order: 0,
5268 pad: 0,
5269 grayscale: false.into(),
5270 bounds,
5271 corner_radii: Default::default(),
5272 content_mask,
5273 tile,
5274 opacity,
5275 });
5276 }
5277 Ok(())
5278 }
5279
5280 pub fn paint_svg(
5284 &mut self,
5285 bounds: Bounds<Pixels>,
5286 path: SharedString,
5287 data: Option<&[u8]>,
5288 transformation: TransformationMatrix,
5289 color: Hsla,
5290 cx: &App,
5291 ) -> Result<()> {
5292 self.invalidator.debug_assert_paint();
5293
5294 let element_opacity = self.element_opacity();
5295 let bounds = self.snap_bounds(bounds);
5296
5297 let params = RenderSvgParams {
5298 path,
5299 size: bounds.size.map(|pixels| {
5300 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
5301 }),
5302 };
5303
5304 let Some(tile) =
5305 self.sprite_atlas
5306 .get_or_insert_with(params.clone().into(), &mut || {
5307 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
5308 else {
5309 return Ok(None);
5310 };
5311 Ok(Some((size, Cow::Owned(bytes))))
5312 })?
5313 else {
5314 return Ok(());
5315 };
5316 let content_mask = self.snapped_content_mask();
5317 let svg_bounds = Bounds {
5318 origin: bounds.center()
5319 - Point::new(
5320 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5321 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5322 ),
5323 size: tile
5324 .bounds
5325 .size
5326 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
5327 };
5328 let final_bounds = svg_bounds
5329 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
5330 .map_size(|size| size.ceil());
5331
5332 self.next_frame.scene.insert_primitive(MonochromeSprite {
5333 order: 0,
5334 pad: 0,
5335 bounds: final_bounds,
5336 content_mask,
5337 color: color.opacity(element_opacity),
5338 tile,
5339 transformation,
5340 });
5341
5342 Ok(())
5343 }
5344
5345 pub fn paint_image(
5354 &mut self,
5355 bounds: Bounds<Pixels>,
5356 image_bounds: Bounds<Pixels>,
5357 corner_radii: Corners<Pixels>,
5358 data: Arc<RenderImage>,
5359 frame_index: usize,
5360 grayscale: bool,
5361 ) -> Result<()> {
5362 self.invalidator.debug_assert_paint();
5363
5364 let visible_bounds = bounds.intersect(&image_bounds);
5365 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
5366 return Ok(());
5367 }
5368 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
5369 return Ok(());
5370 }
5371
5372 let params = RenderImageParams {
5373 image_id: data.id,
5374 frame_index,
5375 };
5376
5377 let tile = self
5378 .sprite_atlas
5379 .get_or_insert_with(params.into(), &mut || {
5380 Ok(Some((
5381 data.size(frame_index),
5382 Cow::Borrowed(
5383 data.as_bytes(frame_index)
5384 .expect("It's the caller's job to pass a valid frame index"),
5385 ),
5386 )))
5387 })?
5388 .expect("Callback above only returns Some");
5389
5390 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
5391
5392 let sub_tile = if visible_bounds == image_bounds {
5393 tile
5394 } else {
5395 let x_offset_ratio =
5396 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
5397 let y_offset_ratio =
5398 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
5399 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
5400 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
5401
5402 let tile_origin_x = tile.bounds.origin.x.0;
5403 let tile_origin_y = tile.bounds.origin.y.0;
5404 let tile_width = tile.bounds.size.width.0;
5405 let tile_height = tile.bounds.size.height.0;
5406
5407 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
5408 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
5409 let sub_width = (width_ratio * tile_width as f32).round() as i32;
5410 let sub_height = (height_ratio * tile_height as f32).round() as i32;
5411
5412 let max_x = tile_origin_x + tile_width;
5413 let max_y = tile_origin_y + tile_height;
5414
5415 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
5416 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
5417 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
5418 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
5419
5420 AtlasTile {
5421 bounds: Bounds {
5422 origin: point(
5423 DevicePixels(clamped_origin_x),
5424 DevicePixels(clamped_origin_y),
5425 ),
5426 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
5427 },
5428 ..tile
5429 }
5430 };
5431
5432 let content_mask = self.snapped_content_mask();
5433 let corner_radii = corner_radii
5434 .clamp_radii_for_quad_size(visible_bounds.size)
5435 .scale(self.scale_factor());
5436 let opacity = self.element_opacity();
5437
5438 self.next_frame.scene.insert_primitive(PolychromeSprite {
5439 order: 0,
5440 pad: 0,
5441 grayscale: grayscale.into(),
5442 bounds: visible_bounds_snapped,
5443 content_mask,
5444 corner_radii,
5445 tile: sub_tile,
5446 opacity,
5447 });
5448 Ok(())
5449 }
5450
5451 #[cfg(any(target_os = "macos", target_os = "ios"))]
5455 pub fn paint_surface(
5456 &mut self,
5457 bounds: Bounds<Pixels>,
5458 image_buffer: CFRetained<CVPixelBuffer>,
5459 ) {
5460 use crate::PaintSurface;
5461
5462 self.invalidator.debug_assert_paint();
5463
5464 let bounds = self.snap_bounds(bounds);
5465 let content_mask = self.snapped_content_mask();
5466 self.next_frame.scene.insert_primitive(PaintSurface {
5467 order: 0,
5468 bounds,
5469 content_mask,
5470 image_buffer,
5471 });
5472 }
5473
5474 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
5476 for frame_index in 0..data.frame_count() {
5477 let params = RenderImageParams {
5478 image_id: data.id,
5479 frame_index,
5480 };
5481
5482 self.sprite_atlas.remove(¶ms.clone().into());
5483 }
5484
5485 Ok(())
5486 }
5487
5488 #[cfg(any(test, feature = "test-support"))]
5490 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
5491 data.frame_count() > 0
5492 && (0..data.frame_count()).all(|frame_index| {
5493 self.sprite_atlas.contains(
5494 &RenderImageParams {
5495 image_id: data.id,
5496 frame_index,
5497 }
5498 .into(),
5499 )
5500 })
5501 }
5502
5503 #[must_use]
5509 pub fn request_layout(
5510 &mut self,
5511 style: Style,
5512 children: impl IntoIterator<Item = LayoutId>,
5513 cx: &mut App,
5514 ) -> LayoutId {
5515 self.invalidator.debug_assert_prepaint();
5516
5517 cx.layout_id_buffer.clear();
5518 cx.layout_id_buffer.extend(children);
5519 let rem_size = self.rem_size();
5520 let scale_factor = self.scale_factor();
5521
5522 let fast_key = crate::fast::layout_key::layout_key(self);
5523 self.layout_engine.as_mut().unwrap().request_layout(
5524 fast_key,
5525 style,
5526 rem_size,
5527 scale_factor,
5528 &cx.layout_id_buffer,
5529 )
5530 }
5531
5532 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
5541 where
5542 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
5543 + 'static,
5544 {
5545 self.invalidator.debug_assert_prepaint();
5546
5547 let rem_size = self.rem_size();
5548 let scale_factor = self.scale_factor();
5549 let fast_key = crate::fast::layout_key::layout_key(self);
5550 self.layout_engine
5551 .as_mut()
5552 .unwrap()
5553 .request_measured_layout(fast_key, style, rem_size, scale_factor, measure)
5554 }
5555
5556 pub fn compute_layout(
5562 &mut self,
5563 layout_id: LayoutId,
5564 available_space: Size<AvailableSpace>,
5565 cx: &mut App,
5566 ) {
5567 self.invalidator.debug_assert_prepaint();
5568
5569 let mut layout_engine = self.layout_engine.take().unwrap();
5570 layout_engine.compute_layout(layout_id, available_space, self, cx);
5571 self.layout_engine = Some(layout_engine);
5572 }
5573
5574 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
5579 self.invalidator.debug_assert_prepaint();
5580
5581 let scale_factor = self.scale_factor();
5582 let mut bounds = self
5583 .layout_engine
5584 .as_mut()
5585 .unwrap()
5586 .layout_bounds(layout_id, scale_factor)
5587 .map(Into::into);
5588 let snapped_offset = self.pixel_snap_point(self.element_offset());
5589 bounds.origin += snapped_offset;
5590 bounds
5591 }
5592
5593 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
5599 self.invalidator.debug_assert_prepaint();
5600
5601 let content_mask = crate::fast::layers::input::hitbox_mask(self);
5602 let id = self.next_hitbox_id;
5603 self.next_hitbox_id = self.next_hitbox_id.next();
5604 let hitbox = Hitbox {
5605 id,
5606 bounds,
5607 content_mask,
5608 behavior,
5609 };
5610 self.next_frame.hitboxes.push(hitbox.clone());
5611 crate::fast::composition::record_input(self, id);
5612 hitbox
5613 }
5614
5615 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
5619 self.invalidator.debug_assert_paint();
5620 self.next_frame.window_control_hitboxes.push((area, hitbox));
5621 }
5622
5623 pub fn set_key_context(&mut self, context: KeyContext) {
5628 self.invalidator.debug_assert_paint();
5629 self.next_frame.dispatch_tree.set_key_context(context);
5630 }
5631
5632 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
5637 self.invalidator.debug_assert_prepaint();
5638 if focus_handle.is_focused(self) {
5639 self.next_frame.focus = Some(focus_handle.id);
5640 }
5641 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
5642 }
5643
5644 pub fn set_view_id(&mut self, view_id: EntityId) {
5650 self.invalidator.debug_assert_prepaint();
5651 self.next_frame.dispatch_tree.set_view_id(view_id);
5652 }
5653
5654 pub fn current_view(&self) -> EntityId {
5656 self.invalidator.debug_assert_paint_or_prepaint();
5657 self.rendered_entity_stack.last().copied().unwrap()
5658 }
5659
5660 #[inline]
5661 pub(crate) fn with_rendered_view<R>(
5662 &mut self,
5663 id: EntityId,
5664 f: impl FnOnce(&mut Self) -> R,
5665 ) -> R {
5666 self.rendered_entity_stack.push(id);
5667 let result = f(self);
5668 self.rendered_entity_stack.pop();
5669 result
5670 }
5671
5672 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
5674 where
5675 F: FnOnce(&mut Self) -> R,
5676 {
5677 if let Some(image_cache) = image_cache {
5678 self.image_cache_stack.push(image_cache);
5679 let result = f(self);
5680 self.image_cache_stack.pop();
5681 result
5682 } else {
5683 f(self)
5684 }
5685 }
5686
5687 pub fn handle_input(
5696 &mut self,
5697 focus_handle: &FocusHandle,
5698 input_handler: impl InputHandler,
5699 cx: &App,
5700 ) {
5701 self.invalidator.debug_assert_paint();
5702
5703 if focus_handle.is_focused(self) {
5704 let cx = self.to_async(cx);
5705 self.next_frame.input_handlers.push(Some(
5706 PlatformInputHandler::new(cx, Box::new(input_handler)).with_focus(focus_handle.id),
5707 ));
5708 }
5709 }
5710
5711 pub fn notify_text_input_changed(&self, focus_handle: &FocusHandle) {
5716 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
5717 self.platform_window
5718 .text_input_state_changed(TextInputStateChange::ContentChanged);
5719 }
5720 }
5721
5722 pub fn notify_text_selection_changed(&self, focus_handle: &FocusHandle) {
5727 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
5728 self.platform_window
5729 .text_input_state_changed(TextInputStateChange::SelectionChanged);
5730 }
5731 }
5732
5733 fn apply_text_input_configuration(&mut self, cx: &mut App) {
5738 let configuration = match self.platform_window.take_input_handler() {
5739 Some(mut input_handler) => {
5740 let configuration = input_handler.text_input_configuration(self, cx);
5741 self.platform_window.set_input_handler(input_handler);
5742 configuration
5743 }
5744 None => TextInputConfiguration::default(),
5745 };
5746 if self.last_text_input_configuration.as_ref() != Some(&configuration) {
5747 self.platform_window
5748 .set_text_input_configuration(configuration.clone());
5749 self.last_text_input_configuration = Some(configuration);
5750 }
5751 }
5752
5753 pub fn on_mouse_event<Event: MouseEvent>(
5759 &mut self,
5760 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5761 ) {
5762 self.invalidator.debug_assert_paint();
5763
5764 self.next_frame.mouse_listeners.push(Some(Box::new(
5765 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
5766 if let Some(event) = event.downcast_ref() {
5767 listener(event, phase, window, cx)
5768 }
5769 },
5770 )));
5771 }
5772
5773 pub fn on_key_event<Event: KeyEvent>(
5782 &mut self,
5783 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5784 ) {
5785 self.invalidator.debug_assert_paint();
5786
5787 self.next_frame.dispatch_tree.on_key_event(Rc::new(
5788 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
5789 if let Some(event) = event.downcast_ref::<Event>() {
5790 listener(event, phase, window, cx)
5791 }
5792 },
5793 ));
5794 }
5795
5796 pub fn on_modifiers_changed(
5803 &mut self,
5804 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
5805 ) {
5806 self.invalidator.debug_assert_paint();
5807
5808 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
5809 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
5810 listener(event, window, cx)
5811 },
5812 ));
5813 }
5814
5815 pub fn on_focus_in(
5819 &mut self,
5820 handle: &FocusHandle,
5821 cx: &mut App,
5822 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
5823 ) -> Subscription {
5824 let focus_id = handle.id;
5825 let (subscription, activate) =
5826 self.new_focus_listener(Box::new(move |event, window, cx| {
5827 if event.is_focus_in(focus_id) {
5828 listener(window, cx);
5829 }
5830 true
5831 }));
5832 cx.defer(move |_| activate());
5833 subscription
5834 }
5835
5836 pub fn on_focus_out(
5839 &mut self,
5840 handle: &FocusHandle,
5841 cx: &mut App,
5842 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
5843 ) -> Subscription {
5844 let focus_id = handle.id;
5845 let (subscription, activate) =
5846 self.new_focus_listener(Box::new(move |event, window, cx| {
5847 if let Some(blurred_id) = event.previous_focus_path.last().copied()
5848 && event.is_focus_out(focus_id)
5849 {
5850 let event = FocusOutEvent {
5851 blurred: WeakFocusHandle {
5852 id: blurred_id,
5853 handles: Arc::downgrade(&cx.focus_handles),
5854 },
5855 };
5856 listener(event, window, cx)
5857 }
5858 true
5859 }));
5860 cx.defer(move |_| activate());
5861 subscription
5862 }
5863
5864 fn reset_cursor_style(&self, cx: &mut App) {
5865 if self.is_window_hovered() {
5867 let style = cx
5869 .active_drag_cursor_style()
5870 .or_else(|| self.rendered_frame.cursor_style(self))
5871 .unwrap_or(CursorStyle::Arrow);
5872 cx.platform.set_cursor_style(style);
5873 }
5874 }
5875
5876 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
5879 let keystroke = keystroke.with_simulated_ime();
5880 let result = self.dispatch_event(
5881 PlatformInput::KeyDown(KeyDownEvent {
5882 keystroke: keystroke.clone(),
5883 is_held: false,
5884 prefer_character_input: false,
5885 }),
5886 cx,
5887 );
5888 if !result.propagate {
5889 return true;
5890 }
5891
5892 if let Some(input) = keystroke.key_char
5893 && let Some(mut input_handler) = self.platform_window.take_input_handler()
5894 {
5895 input_handler.dispatch_input(&input, self, cx);
5896 self.platform_window.set_input_handler(input_handler);
5897 return true;
5898 }
5899
5900 false
5901 }
5902
5903 pub fn keystroke_text_for(&self, action: &dyn Action, cx: &App) -> String {
5906 self.highest_precedence_binding_for_action(action)
5907 .map(|binding| {
5908 binding
5909 .keystrokes()
5910 .iter()
5911 .map(|keystroke| keystroke.display(cx.platform_info().os).to_string())
5912 .collect::<Vec<_>>()
5913 .join(" ")
5914 })
5915 .unwrap_or_else(|| action.name().to_string())
5916 }
5917
5918 #[profiling::function]
5920 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
5921 #[cfg(feature = "profiler")]
5922 self.window_profiler.begin_input(event.kind_name());
5923 let update_count_before = self.invalidator.update_count();
5924 let old_modality = self.last_input_modality;
5928 self.last_input_modality = match &event {
5929 PlatformInput::KeyDown(_) => InputModality::Keyboard,
5930 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
5931 PlatformInput::Touch(_) => InputModality::Touch,
5932 _ => self.last_input_modality,
5933 };
5934 if self.last_input_modality != old_modality {
5935 self.refresh();
5936 }
5937
5938 let ambient = crate::fast::dependencies::AmbientInput::of(self);
5939 cx.propagate_event = true;
5941 self.default_prevented = false;
5943
5944 let event = match event {
5945 PlatformInput::MouseMove(mouse_move) => {
5948 self.mouse_position = mouse_move.position;
5949 self.modifiers = mouse_move.modifiers;
5950 PlatformInput::MouseMove(mouse_move)
5951 }
5952 PlatformInput::MouseDown(mouse_down) => {
5953 self.mouse_position = mouse_down.position;
5954 self.modifiers = mouse_down.modifiers;
5955 PlatformInput::MouseDown(mouse_down)
5956 }
5957 PlatformInput::MouseUp(mouse_up) => {
5958 self.mouse_position = mouse_up.position;
5959 self.modifiers = mouse_up.modifiers;
5960 PlatformInput::MouseUp(mouse_up)
5961 }
5962 PlatformInput::MousePressure(mouse_pressure) => {
5963 PlatformInput::MousePressure(mouse_pressure)
5964 }
5965 PlatformInput::MouseExited(mouse_exited) => {
5966 self.modifiers = mouse_exited.modifiers;
5967 PlatformInput::MouseExited(mouse_exited)
5968 }
5969 PlatformInput::ModifiersChanged(modifiers_changed) => {
5970 self.modifiers = modifiers_changed.modifiers;
5971 self.capslock = modifiers_changed.capslock;
5972 PlatformInput::ModifiersChanged(modifiers_changed)
5973 }
5974 PlatformInput::Scroll(scroll_wheel) => {
5975 self.mouse_position = scroll_wheel.position;
5976 self.modifiers = scroll_wheel.modifiers;
5977 PlatformInput::Scroll(scroll_wheel)
5978 }
5979 PlatformInput::Pinch(pinch) => {
5980 self.mouse_position = pinch.position;
5981 self.modifiers = pinch.modifiers;
5982 PlatformInput::Pinch(pinch)
5983 }
5984 PlatformInput::FileDrop(file_drop) => match file_drop {
5987 FileDropEvent::Entered { position, paths } => {
5988 self.mouse_position = position;
5989 let source_window = self.handle.window_id();
5990 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
5991 cx.active_drag = Some(AnyDrag {
5992 value: Arc::new(paths.clone()),
5993 view: cx.new(|_| paths).into(),
5994 cursor_offset: position,
5995 cursor_style: None,
5996 external_payload_source: None,
5997 });
5998 }
5999 PlatformInput::MouseMove(MouseMoveEvent {
6000 position,
6001 pressed_button: Some(MouseButton::Left),
6002 modifiers: Modifiers::default(),
6003 })
6004 }
6005 FileDropEvent::Pending { position } => {
6006 self.mouse_position = position;
6007 PlatformInput::MouseMove(MouseMoveEvent {
6008 position,
6009 pressed_button: Some(MouseButton::Left),
6010 modifiers: Modifiers::default(),
6011 })
6012 }
6013 FileDropEvent::Submit { position } => {
6014 cx.activate(true);
6015 self.mouse_position = position;
6016 PlatformInput::MouseUp(MouseUpEvent {
6017 button: MouseButton::Left,
6018 position,
6019 modifiers: Modifiers::default(),
6020 click_count: 1,
6021 })
6022 }
6023 FileDropEvent::Exited => {
6024 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
6025 cx.active_drag.take();
6026 }
6027 self.refresh();
6028 PlatformInput::FileDrop(FileDropEvent::Exited)
6029 }
6030 FileDropEvent::Ended => {
6031 cx.end_platform_drag(self.handle.window_id());
6032 self.refresh();
6033 PlatformInput::FileDrop(FileDropEvent::Ended)
6034 }
6035 },
6036 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
6037 PlatformInput::LongPress(long_press) => {
6038 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
6039 long_press.start_position
6040 } else {
6041 long_press.position
6042 };
6043 if long_press.phase == crate::TouchPhase::Started {
6044 self.long_press_capture = None;
6045 }
6046 PlatformInput::LongPress(long_press)
6047 }
6048 PlatformInput::TouchDrag(touch_drag) => {
6049 self.mouse_position = touch_drag.start_position;
6050 PlatformInput::TouchDrag(touch_drag)
6051 }
6052 PlatformInput::BackGesture(back) => {
6053 self.mouse_position = back.start_position;
6054 PlatformInput::BackGesture(back)
6055 }
6056 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
6057 };
6058 crate::fast::dependencies::AmbientInput::stamp_changes(ambient, self, cx);
6059 crate::fast::layers::input::before_dispatch(self, cx, &event);
6060
6061 let native_target = crate::fast::composition::event_target(self, &event);
6062 if let Some(any_mouse_event) = event.mouse_event() {
6063 self.dispatch_mouse_event(any_mouse_event, cx);
6064 } else if let Some(any_key_event) = event.keyboard_event() {
6065 self.dispatch_key_event(any_key_event, cx);
6066 } else if let Some(touch_event) = event.touch_event() {
6067 self.dispatch_touch_event(touch_event, cx);
6068 }
6069 crate::fast::composition::dispatch_native(
6070 self,
6071 &event,
6072 native_target,
6073 &mut cx.propagate_event,
6074 );
6075 crate::fast::layers::wheel::end_dispatch(self, cx);
6076 if let PlatformInput::LongPress(long_press) = &event {
6077 match long_press.phase {
6078 crate::TouchPhase::Started if !self.default_prevented => {
6079 self.long_press_capture = None;
6080 }
6081 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
6082 self.long_press_capture = None;
6083 }
6084 crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
6085 }
6086 }
6087
6088 self.promote_external_drag_to_platform(&event, cx);
6091
6092 let caused_invalidation = self.invalidator.update_count() > update_count_before;
6093 if caused_invalidation {
6094 self.input_rate_tracker.borrow_mut().record_input();
6095 }
6096 #[cfg(feature = "profiler")]
6097 self.window_profiler.end_input(caused_invalidation);
6098
6099 DispatchEventResult {
6100 propagate: cx.propagate_event,
6101 default_prevented: self.default_prevented,
6102 }
6103 }
6104
6105 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
6106 let PlatformInput::MouseMove(mouse_move) = event else {
6107 return;
6108 };
6109 if mouse_move.pressed_button != Some(MouseButton::Left) {
6110 return;
6111 }
6112 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
6113 return;
6114 }
6115 if !self.platform_window.can_start_external_drag() {
6116 return;
6117 }
6118 let Some(payload_source) = cx
6119 .active_drag
6120 .as_mut()
6121 .and_then(|drag| drag.external_payload_source.take())
6122 else {
6123 return;
6124 };
6125 let Some(payload) = payload_source(self, cx) else {
6126 return;
6127 };
6128 if self.platform_window.start_external_drag(&payload)
6129 && cx.hand_active_drag_to_platform(self.handle.window_id())
6130 {
6131 self.refresh();
6132 }
6133 }
6134
6135 pub fn touch_prediction_enabled(&self) -> bool {
6139 self.touch_prediction_enabled
6140 }
6141
6142 pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
6146 self.touch_prediction_enabled = enabled;
6147 }
6148
6149 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
6153 let mut event = event.clone();
6154 if !self.touch_prediction_enabled {
6155 event.predicted_position = None;
6156 }
6157 let recognized_gestures = self.touch_gestures.handle_event(&event);
6158 if event.phase == crate::TouchPhase::Started
6159 && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
6160 {
6161 self.dispatch_recognized_touch_gesture(touch_drag, cx);
6162 }
6163 if event.phase == crate::TouchPhase::Started
6164 && self.touch_gestures.pending_long_press().is_some()
6165 {
6166 self.long_press_capture = None;
6167 }
6168 let mut tapped = false;
6169 for gesture in recognized_gestures {
6170 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
6171 self.dispatch_recognized_touch_gesture(gesture, cx);
6172 }
6173 if event.phase == crate::TouchPhase::Started {
6174 self.schedule_long_press_timer(cx);
6175 } else if self.touch_gestures.pending_long_press().is_none() {
6176 self.long_press_timer.take();
6177 }
6178 if tapped && self.invalidator.is_dirty() {
6184 self.draw(cx).clear(cx);
6185 }
6186 if self.touch_gestures.has_momentum() {
6187 self.schedule_touch_momentum_tick();
6188 }
6189 }
6190
6191 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
6192 match gesture {
6193 RecognizedTouchGesture::Scroll(scroll_wheel) => {
6194 self.mouse_position = scroll_wheel.position;
6195 cx.propagate_event = true;
6196 self.dispatch_mouse_event(&scroll_wheel, cx);
6197 }
6198 RecognizedTouchGesture::Tap { down, up } => {
6199 self.mouse_position = up.position;
6200 cx.propagate_event = true;
6201 self.dispatch_mouse_event(&down, cx);
6202 cx.propagate_event = true;
6203 self.dispatch_mouse_event(&up, cx);
6204 }
6205 RecognizedTouchGesture::TouchDrag(touch_drag) => {
6206 self.mouse_position = touch_drag.start_position;
6207 cx.propagate_event = true;
6208 self.default_prevented = false;
6209 let started = touch_drag.phase == crate::TouchPhase::Started;
6210 self.dispatch_mouse_event(&touch_drag, cx);
6211 if started {
6212 self.touch_gestures
6213 .resolve_touch_drag(self.default_prevented);
6214 }
6215 }
6216 RecognizedTouchGesture::LongPress(long_press) => {
6217 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
6218 long_press.start_position
6219 } else {
6220 long_press.position
6221 };
6222 cx.propagate_event = true;
6223 self.default_prevented = false;
6224 let started = long_press.phase == crate::TouchPhase::Started;
6225 let ended = matches!(
6226 long_press.phase,
6227 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
6228 );
6229 self.dispatch_mouse_event(&long_press, cx);
6230 if started {
6231 let claimed = self.default_prevented;
6232 self.touch_gestures.resolve_long_press(claimed);
6233 if !claimed {
6234 self.long_press_capture = None;
6235 }
6236 }
6237 if ended {
6238 self.long_press_capture = None;
6239 }
6240 }
6241 }
6242 }
6243
6244 fn schedule_long_press_timer(&mut self, cx: &mut App) {
6245 self.long_press_timer.take();
6246 let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
6247 return;
6248 };
6249 self.long_press_timer = Some(self.spawn(cx, async move |cx| {
6250 cx.background_executor.timer(duration).await;
6251 cx.update(move |window, cx| {
6252 window.long_press_timer.take();
6253 if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
6254 window.dispatch_recognized_touch_gesture(gesture, cx);
6255 }
6256 })
6257 .with_context(|| {
6258 format!(
6259 "handling long-press timer for window {:?}",
6260 cx.window_handle().window_id()
6261 )
6262 })
6263 .log_err();
6264 }));
6265 }
6266
6267 fn schedule_touch_momentum_tick(&mut self) {
6268 self.on_next_frame(|window, cx| {
6269 if let Some(gesture) = window.touch_gestures.tick_momentum() {
6270 window.dispatch_recognized_touch_gesture(gesture, cx);
6271 }
6272 if window.touch_gestures.has_momentum() {
6273 window.schedule_touch_momentum_tick();
6274 }
6275 });
6276 }
6277
6278 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6279 self.mouse_hit_test = self.rendered_frame.hit_test(self.mouse_position());
6280
6281 #[cfg(any(feature = "inspector", debug_assertions))]
6282 if self.is_inspector_picking(cx) {
6283 self.reset_cursor_style(cx);
6284 self.handle_inspector_mouse_event(event, cx);
6285 return;
6287 }
6288
6289 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
6290
6291 for listener in &mut mouse_listeners {
6294 let listener = listener.as_mut().unwrap();
6295 listener(event, DispatchPhase::Capture, self, cx);
6296 if !cx.propagate_event {
6297 break;
6298 }
6299 }
6300
6301 if crate::fast::composition::bubble_mouse(self, event, cx) {
6303 for listener in mouse_listeners.iter_mut().rev() {
6304 let listener = listener.as_mut().unwrap();
6305 listener(event, DispatchPhase::Bubble, self, cx);
6306 if !cx.propagate_event {
6307 break;
6308 }
6309 }
6310 }
6311
6312 self.rendered_frame.mouse_listeners = mouse_listeners;
6313
6314 if cx.has_active_drag() {
6315 if event.is::<MouseMoveEvent>() {
6316 self.refresh();
6319 } else if event.is::<MouseUpEvent>() {
6320 cx.active_drag = None;
6323 self.refresh();
6324 }
6325 }
6326
6327 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
6329 self.captured_hitbox = None;
6330 }
6331
6332 self.reset_cursor_style(cx);
6335 }
6336
6337 fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
6340 let prefer_character_input = event
6341 .downcast_ref::<KeyDownEvent>()
6342 .is_some_and(|key_down_event| key_down_event.prefer_character_input);
6343 if !prefer_character_input {
6344 return InputPreference::KeyBindings;
6345 }
6346 let Some(mut input_handler) = self.platform_window.take_input_handler() else {
6347 return InputPreference::KeyBindings;
6348 };
6349 let accepts_text_input = input_handler.accepts_text_input(self, cx);
6350 self.platform_window.set_input_handler(input_handler);
6351 if accepts_text_input {
6352 InputPreference::CharacterInput
6353 } else {
6354 InputPreference::KeyBindings
6355 }
6356 }
6357
6358 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
6359 if self.invalidator.is_dirty() {
6360 self.draw(cx).clear(cx);
6361 }
6362
6363 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6364 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6365
6366 let mut keystroke: Option<Keystroke> = None;
6367
6368 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
6369 if event.modifiers.number_of_modifiers() == 0
6370 && self.pending_modifier.modifiers.number_of_modifiers() == 1
6371 && !self.pending_modifier.saw_other_input
6372 {
6373 let key = match self.pending_modifier.modifiers {
6374 modifiers if modifiers.shift => Some("shift"),
6375 modifiers if modifiers.control => Some("control"),
6376 modifiers if modifiers.alt => Some("alt"),
6377 modifiers if modifiers.platform => Some("platform"),
6378 modifiers if modifiers.function => Some("function"),
6379 _ => None,
6380 };
6381 if let Some(key) = key {
6382 keystroke = Some(Keystroke {
6383 key: key.to_string(),
6384 key_char: None,
6385 modifiers: Modifiers::default(),
6386 });
6387 }
6388 }
6389
6390 if self.pending_modifier.modifiers.number_of_modifiers() == 0
6391 && event.modifiers.number_of_modifiers() == 1
6392 {
6393 self.pending_modifier.saw_other_input = false
6394 } else if event.modifiers.number_of_modifiers() > 1 {
6395 self.pending_modifier.saw_other_input = true
6396 }
6397 self.pending_modifier.modifiers = event.modifiers
6398 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
6399 self.pending_modifier.saw_other_input = true;
6400 keystroke = Some(key_down_event.keystroke.clone());
6401 if key_down_event.keystroke.key_char.is_some()
6402 && matches!(
6403 cx.cursor_hide_mode,
6404 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
6405 )
6406 {
6407 cx.platform.hide_cursor_until_mouse_moves();
6408 }
6409 }
6410
6411 let Some(keystroke) = keystroke else {
6412 self.finish_dispatch_key_event(
6413 event,
6414 None,
6415 InputPreference::KeyBindings,
6416 dispatch_path,
6417 self.context_stack(),
6418 cx,
6419 );
6420 return;
6421 };
6422
6423 let input_preference = self.input_preference(event, cx);
6424
6425 cx.propagate_event = true;
6426 self.dispatch_keystroke_interceptors(
6427 &keystroke,
6428 input_preference,
6429 self.context_stack(),
6430 cx,
6431 );
6432 if !cx.propagate_event {
6433 self.finish_dispatch_key_event(
6434 event,
6435 Some(&keystroke),
6436 input_preference,
6437 dispatch_path,
6438 self.context_stack(),
6439 cx,
6440 );
6441 return;
6442 }
6443
6444 let mut currently_pending = self.pending_input.take().unwrap_or_default();
6445 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
6446 currently_pending = PendingInput::default();
6447 }
6448
6449 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
6450 currently_pending.keystrokes,
6451 keystroke.clone(),
6452 &dispatch_path,
6453 );
6454
6455 if !match_result.to_replay.is_empty() {
6456 self.replay_pending_input(match_result.to_replay, cx);
6457 cx.propagate_event = true;
6458 }
6459
6460 if !match_result.pending.is_empty() {
6461 let previous_timeout = currently_pending.timeout.take();
6462 currently_pending.keystrokes = match_result.pending;
6463 currently_pending.focus = self.focus;
6464
6465 let text_input_requires_timeout = event
6466 .downcast_ref::<KeyDownEvent>()
6467 .filter(|key_down| key_down.keystroke.key_char.is_some())
6468 .and_then(|_| self.platform_window.take_input_handler())
6469 .map_or(false, |mut input_handler| {
6470 let accepts = input_handler.accepts_text_input(self, cx);
6471 self.platform_window.set_input_handler(input_handler);
6472 accepts
6473 });
6474
6475 let standalone_modifier = matches!(currently_pending.keystrokes.as_slice(), [keystroke] if keystroke.is_modifier_key());
6476 let needs_timeout = previous_timeout.is_some()
6477 || match_result.pending_has_binding
6478 || text_input_requires_timeout
6479 || standalone_modifier;
6480 currently_pending.timeout = if needs_timeout {
6481 match previous_timeout {
6482 Some(mut timeout) if timeout.is_paused() => {
6483 timeout.reset_duration(PENDING_INPUT_TIMEOUT);
6484 Some(timeout)
6485 }
6486 previous_timeout => {
6487 drop(previous_timeout);
6488 Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
6489 }
6490 }
6491 } else {
6492 None
6493 };
6494 self.pending_input = Some(currently_pending);
6495 self.pending_input_changed(cx);
6496 cx.propagate_event = false;
6497 return;
6498 }
6499
6500 let input_preference = self.input_preference(event, cx);
6502 if input_preference == InputPreference::KeyBindings {
6503 for binding in match_result.bindings {
6504 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6505 if !cx.propagate_event {
6506 self.dispatch_keystroke_observers(
6507 &keystroke,
6508 input_preference,
6509 Some(binding.action.as_ref()),
6510 match_result.context_stack,
6511 cx,
6512 );
6513 self.pending_input_changed(cx);
6514 return;
6515 }
6516 }
6517 }
6518
6519 self.finish_dispatch_key_event(
6520 event,
6521 Some(&keystroke),
6522 input_preference,
6523 dispatch_path,
6524 match_result.context_stack,
6525 cx,
6526 );
6527 self.pending_input_changed(cx);
6528 }
6529
6530 fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
6531 let (started_at, task) = self.start_pending_input_timeout(duration, cx);
6532 PendingInputTimeout {
6533 duration,
6534 remaining: duration,
6535 state: PendingInputTimeoutState::Running { started_at, task },
6536 }
6537 }
6538
6539 fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
6540 let started_at = cx.background_executor().now();
6541 let task = self.spawn(cx, async move |cx| {
6542 cx.background_executor.timer(remaining).await;
6543 cx.update(move |window, cx| {
6544 let Some(currently_pending) = window
6545 .pending_input
6546 .take()
6547 .filter(|pending| pending.focus == window.focus)
6548 else {
6549 return;
6550 };
6551
6552 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
6553 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
6554
6555 let to_replay = window
6556 .rendered_frame
6557 .dispatch_tree
6558 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
6559
6560 window.pending_input_changed(cx);
6561 window.replay_pending_input(to_replay, cx)
6562 })
6563 .with_context(|| {
6564 format!(
6565 "handling pending input timeout for window {:?}",
6566 cx.window_handle().window_id()
6567 )
6568 })
6569 .log_err();
6570 });
6571 (started_at, task)
6572 }
6573
6574 fn finish_dispatch_key_event(
6575 &mut self,
6576 event: &dyn Any,
6577 recognized_keystroke: Option<&Keystroke>,
6578 input_preference: InputPreference,
6579 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
6580 context_stack: Vec<KeyContext>,
6581 cx: &mut App,
6582 ) {
6583 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
6584 if !cx.propagate_event {
6585 return;
6586 }
6587
6588 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
6589 if !cx.propagate_event {
6590 return;
6591 }
6592
6593 if let Some(keystroke) = recognized_keystroke {
6594 self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
6595 }
6596 }
6597
6598 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
6599 self.pending_input_observers
6600 .clone()
6601 .retain(|callback| callback(self, cx));
6602 }
6603
6604 fn defer_pending_input_changed(&self, cx: &mut App) {
6605 let window_handle = self.handle;
6608 cx.defer(move |cx| {
6609 window_handle
6610 .update(cx, |_, window, cx| {
6611 window.pending_input_changed(cx);
6612 })
6613 .ok();
6614 });
6615 }
6616
6617 fn dispatch_key_down_up_event(
6618 &mut self,
6619 event: &dyn Any,
6620 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6621 cx: &mut App,
6622 ) {
6623 for node_id in dispatch_path {
6625 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6626
6627 for key_listener in node.key_listeners.clone() {
6628 key_listener(event, DispatchPhase::Capture, self, cx);
6629 if !cx.propagate_event {
6630 return;
6631 }
6632 }
6633 }
6634
6635 for node_id in dispatch_path.iter().rev() {
6637 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6639 for key_listener in node.key_listeners.clone() {
6640 key_listener(event, DispatchPhase::Bubble, self, cx);
6641 if !cx.propagate_event {
6642 return;
6643 }
6644 }
6645 }
6646 }
6647
6648 fn dispatch_modifiers_changed_event(
6649 &mut self,
6650 event: &dyn Any,
6651 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6652 cx: &mut App,
6653 ) {
6654 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
6655 return;
6656 };
6657 for node_id in dispatch_path.iter().rev() {
6658 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6659 for listener in node.modifiers_changed_listeners.clone() {
6660 listener(event, self, cx);
6661 if !cx.propagate_event {
6662 return;
6663 }
6664 }
6665 }
6666 }
6667
6668 pub fn has_pending_keystrokes(&self) -> bool {
6670 self.pending_input().is_some()
6671 }
6672
6673 #[cfg(test)]
6674 pub(crate) fn pending_input_is_none(&self) -> bool {
6675 self.pending_input.is_none()
6676 }
6677
6678 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
6679 if self.pending_input.take().is_some() {
6680 self.defer_pending_input_changed(cx);
6681 }
6682 }
6683
6684 pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
6687 self.pending_input
6688 .as_ref()
6689 .filter(|pending_input| pending_input.focus == self.focus)
6690 .map(|pending_input| PendingInputStatus {
6691 keystrokes: pending_input.keystrokes.as_slice(),
6692 timeout: pending_input
6693 .timeout
6694 .as_ref()
6695 .map(PendingInputTimeout::status),
6696 })
6697 }
6698
6699 pub fn set_pending_input_timeout_paused<T: 'static>(
6704 &mut self,
6705 owner: &Entity<T>,
6706 paused: bool,
6707 cx: &mut App,
6708 ) -> bool {
6709 let owner_id = owner.entity_id();
6710 if !paused {
6711 return self.resume_pending_input_timeout(owner_id, cx);
6712 }
6713
6714 let timeout = self
6715 .pending_input
6716 .as_ref()
6717 .filter(|pending_input| pending_input.focus == self.focus)
6718 .and_then(|pending_input| pending_input.timeout.as_ref());
6719 let Some(timeout) = timeout else {
6720 return false;
6721 };
6722 if timeout.is_paused() {
6723 return false;
6724 }
6725
6726 let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
6727 window.resume_pending_input_timeout(owner_id, cx);
6728 });
6729 let now = cx.background_executor().now();
6730 let changed = self
6731 .pending_input
6732 .as_mut()
6733 .filter(|pending_input| pending_input.focus == self.focus)
6734 .and_then(|pending_input| pending_input.timeout.as_mut())
6735 .is_some_and(|timeout| {
6736 timeout.pause(
6737 PendingInputTimeoutPause {
6738 owner_id,
6739 _release_subscription: release_subscription,
6740 },
6741 now,
6742 )
6743 });
6744
6745 if changed {
6746 self.defer_pending_input_changed(cx);
6747 }
6748 changed
6749 }
6750
6751 fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
6752 let Some(remaining) = self
6753 .pending_input
6754 .as_ref()
6755 .and_then(|pending_input| pending_input.timeout.as_ref())
6756 .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
6757 .map(|timeout| timeout.remaining)
6758 else {
6759 return false;
6760 };
6761
6762 let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
6763 let changed = self
6764 .pending_input
6765 .as_mut()
6766 .and_then(|pending_input| pending_input.timeout.as_mut())
6767 .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
6768
6769 if changed {
6770 self.defer_pending_input_changed(cx);
6771 }
6772 changed
6773 }
6774
6775 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
6777 self.pending_input()
6778 .map(|pending_input| pending_input.keystrokes())
6779 }
6780
6781 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
6782 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6783 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6784
6785 'replay: for replay in replays {
6786 let event = KeyDownEvent {
6787 keystroke: replay.keystroke.clone(),
6788 is_held: false,
6789 prefer_character_input: true,
6790 };
6791
6792 cx.propagate_event = true;
6793 for binding in replay.bindings {
6794 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6795 if !cx.propagate_event {
6796 self.dispatch_keystroke_observers(
6797 &replay.keystroke,
6798 InputPreference::KeyBindings,
6799 Some(binding.action.as_ref()),
6800 Vec::default(),
6801 cx,
6802 );
6803 continue 'replay;
6804 }
6805 }
6806
6807 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
6808 if !cx.propagate_event {
6809 continue 'replay;
6810 }
6811 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
6812 && let Some(mut input_handler) = self.platform_window.take_input_handler()
6813 {
6814 input_handler.dispatch_input(&input, self, cx);
6815 self.platform_window.set_input_handler(input_handler)
6816 }
6817 }
6818 }
6819
6820 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
6821 focus_id
6822 .and_then(|focus_id| {
6823 self.rendered_frame
6824 .dispatch_tree
6825 .focusable_node_id(focus_id)
6826 })
6827 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
6828 }
6829
6830 fn dispatch_action_on_node(
6831 &mut self,
6832 node_id: DispatchNodeId,
6833 action: &dyn Action,
6834 cx: &mut App,
6835 ) {
6836 self.dispatch_action_on_node_inner(node_id, action, cx);
6837
6838 if !cx.propagate_event
6839 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
6840 && self.last_input_was_keyboard()
6841 {
6842 cx.platform.hide_cursor_until_mouse_moves();
6843 }
6844 }
6845
6846 fn dispatch_action_on_node_inner(
6847 &mut self,
6848 node_id: DispatchNodeId,
6849 action: &dyn Action,
6850 cx: &mut App,
6851 ) {
6852 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6853
6854 cx.propagate_event = true;
6856 if let Some(mut global_listeners) = cx
6857 .global_action_listeners
6858 .remove(&action.as_any().type_id())
6859 {
6860 for listener in &global_listeners {
6861 #[cfg(feature = "profiler")]
6862 self.window_profiler.begin_action_handler(action, cx);
6863 listener(action.as_any(), DispatchPhase::Capture, cx);
6864 #[cfg(feature = "profiler")]
6865 self.window_profiler.end_action_handler();
6866 if !cx.propagate_event {
6867 break;
6868 }
6869 }
6870
6871 global_listeners.extend(
6872 cx.global_action_listeners
6873 .remove(&action.as_any().type_id())
6874 .unwrap_or_default(),
6875 );
6876
6877 cx.global_action_listeners
6878 .insert(action.as_any().type_id(), global_listeners);
6879 }
6880
6881 if !cx.propagate_event {
6882 return;
6883 }
6884
6885 for node_id in &dispatch_path {
6887 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6888 for DispatchActionListener {
6889 action_type,
6890 listener,
6891 } in node.action_listeners.clone()
6892 {
6893 let any_action = action.as_any();
6894 if action_type == any_action.type_id() {
6895 #[cfg(feature = "profiler")]
6896 self.window_profiler.begin_action_handler(action, cx);
6897 listener(any_action, DispatchPhase::Capture, self, cx);
6898 #[cfg(feature = "profiler")]
6899 self.window_profiler.end_action_handler();
6900
6901 if !cx.propagate_event {
6902 return;
6903 }
6904 }
6905 }
6906 }
6907
6908 for node_id in dispatch_path.iter().rev() {
6910 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6911 for DispatchActionListener {
6912 action_type,
6913 listener,
6914 } in node.action_listeners.clone()
6915 {
6916 let any_action = action.as_any();
6917 if action_type == any_action.type_id() {
6918 cx.propagate_event = false; #[cfg(feature = "profiler")]
6920 self.window_profiler.begin_action_handler(action, cx);
6921 listener(any_action, DispatchPhase::Bubble, self, cx);
6922 #[cfg(feature = "profiler")]
6923 self.window_profiler.end_action_handler();
6924
6925 if !cx.propagate_event {
6926 return;
6927 }
6928 }
6929 }
6930 }
6931
6932 if let Some(mut global_listeners) = cx
6934 .global_action_listeners
6935 .remove(&action.as_any().type_id())
6936 {
6937 for listener in global_listeners.iter().rev() {
6938 cx.propagate_event = false; #[cfg(feature = "profiler")]
6941 self.window_profiler.begin_action_handler(action, cx);
6942 listener(action.as_any(), DispatchPhase::Bubble, cx);
6943 #[cfg(feature = "profiler")]
6944 self.window_profiler.end_action_handler();
6945 if !cx.propagate_event {
6946 break;
6947 }
6948 }
6949
6950 global_listeners.extend(
6951 cx.global_action_listeners
6952 .remove(&action.as_any().type_id())
6953 .unwrap_or_default(),
6954 );
6955
6956 cx.global_action_listeners
6957 .insert(action.as_any().type_id(), global_listeners);
6958 }
6959 }
6960
6961 pub fn observe_global<G: Global>(
6964 &mut self,
6965 cx: &mut App,
6966 f: impl Fn(&mut Window, &mut App) + 'static,
6967 ) -> Subscription {
6968 let window_handle = self.handle;
6969 let (subscription, activate) = cx.global_observers.insert_pending(
6970 TypeId::of::<G>(),
6971 Box::new(move |cx| {
6972 window_handle
6973 .update(cx, |_, window, cx| f(window, cx))
6974 .is_ok()
6975 }),
6976 );
6977 cx.defer(move |_| activate());
6978 subscription
6979 }
6980
6981 pub fn activate_window(&self) {
6983 self.platform_window.activate();
6984 }
6985
6986 pub fn request_attention(&self) {
6988 self.platform_window.request_attention();
6989 }
6990
6991 pub fn minimize_window(&self) {
6993 self.platform_window.minimize();
6994 }
6995
6996 pub fn toggle_fullscreen(&self) {
6998 self.platform_window.toggle_fullscreen();
6999 }
7000
7001 pub fn toggle_simple_fullscreen(&self) {
7006 self.platform_window.toggle_simple_fullscreen();
7007 }
7008
7009 pub fn invalidate_character_coordinates(&self) {
7011 self.on_next_frame(|window, cx| {
7012 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
7013 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
7014 window.platform_window.update_ime_position(bounds);
7015 }
7016 window.platform_window.set_input_handler(input_handler);
7017 }
7018 });
7019 }
7020
7021 pub fn prompt<T>(
7025 &mut self,
7026 level: PromptLevel,
7027 message: &str,
7028 detail: Option<&str>,
7029 answers: &[T],
7030 cx: &mut App,
7031 ) -> oneshot::Receiver<usize>
7032 where
7033 T: Clone + Into<PromptButton>,
7034 {
7035 let prompt_builder = cx.prompt_builder.take();
7036 let Some(prompt_builder) = prompt_builder else {
7037 unreachable!("Re-entrant window prompting is not supported by GPUI");
7038 };
7039
7040 let answers = answers
7041 .iter()
7042 .map(|answer| answer.clone().into())
7043 .collect::<Vec<_>>();
7044
7045 let receiver = match &prompt_builder {
7046 PromptBuilder::Default => self
7047 .platform_window
7048 .prompt(level, message, detail, &answers)
7049 .unwrap_or_else(|| {
7050 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
7051 }),
7052 PromptBuilder::Custom(_) => {
7053 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
7054 }
7055 };
7056
7057 cx.prompt_builder = Some(prompt_builder);
7058
7059 receiver
7060 }
7061
7062 fn build_custom_prompt(
7063 &mut self,
7064 prompt_builder: &PromptBuilder,
7065 level: PromptLevel,
7066 message: &str,
7067 detail: Option<&str>,
7068 answers: &[PromptButton],
7069 cx: &mut App,
7070 ) -> oneshot::Receiver<usize> {
7071 let (sender, receiver) = oneshot::channel();
7072 let handle = PromptHandle::new(sender);
7073 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
7074 self.prompt = Some(handle);
7075 receiver
7076 }
7077
7078 pub fn has_active_prompt(&self) -> bool {
7083 self.prompt.is_some()
7084 }
7085
7086 pub fn context_stack(&self) -> Vec<KeyContext> {
7088 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
7089 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7090 dispatch_tree
7091 .dispatch_path(node_id)
7092 .iter()
7093 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
7094 .collect()
7095 }
7096
7097 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
7099 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
7100 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
7101 for action_type in cx.global_action_listeners.keys() {
7102 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
7103 let action = cx.actions.build_action_type(action_type).ok();
7104 if let Some(action) = action {
7105 actions.insert(ix, action);
7106 }
7107 }
7108 }
7109 actions
7110 }
7111
7112 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
7115 self.rendered_frame
7116 .dispatch_tree
7117 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
7118 }
7119
7120 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
7123 self.rendered_frame
7124 .dispatch_tree
7125 .highest_precedence_binding_for_action(
7126 action,
7127 &self.rendered_frame.dispatch_tree.context_stack,
7128 )
7129 }
7130
7131 pub fn bindings_for_action_in_context(
7133 &self,
7134 action: &dyn Action,
7135 context: KeyContext,
7136 ) -> Vec<KeyBinding> {
7137 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7138 dispatch_tree.bindings_for_action(action, &[context])
7139 }
7140
7141 pub fn highest_precedence_binding_for_action_in_context(
7144 &self,
7145 action: &dyn Action,
7146 context: KeyContext,
7147 ) -> Option<KeyBinding> {
7148 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7149 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
7150 }
7151
7152 pub fn bindings_for_action_in(
7156 &self,
7157 action: &dyn Action,
7158 focus_handle: &FocusHandle,
7159 ) -> Vec<KeyBinding> {
7160 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7161 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
7162 return vec![];
7163 };
7164 dispatch_tree.bindings_for_action(action, &context_stack)
7165 }
7166
7167 pub fn highest_precedence_binding_for_action_in(
7171 &self,
7172 action: &dyn Action,
7173 focus_handle: &FocusHandle,
7174 ) -> Option<KeyBinding> {
7175 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7176 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
7177 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
7178 }
7179
7180 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
7182 self.rendered_frame
7183 .dispatch_tree
7184 .possible_next_bindings_for_input(input, &self.context_stack())
7185 }
7186
7187 fn context_stack_for_focus_handle(
7188 &self,
7189 focus_handle: &FocusHandle,
7190 ) -> Option<Vec<KeyContext>> {
7191 let dispatch_tree = &self.rendered_frame.dispatch_tree;
7192 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
7193 let context_stack: Vec<_> = dispatch_tree
7194 .dispatch_path(node_id)
7195 .into_iter()
7196 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
7197 .collect();
7198 Some(context_stack)
7199 }
7200
7201 pub fn listener_for<T: 'static, E>(
7203 &self,
7204 view: &Entity<T>,
7205 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
7206 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
7207 let view = view.downgrade();
7208 move |e: &E, window: &mut Window, cx: &mut App| {
7209 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
7210 }
7211 }
7212
7213 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
7215 &self,
7216 entity: &Entity<E>,
7217 f: Callback,
7218 ) -> impl Fn(&mut Window, &mut App) + 'static {
7219 let entity = entity.downgrade();
7220 move |window: &mut Window, cx: &mut App| {
7221 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
7222 }
7223 }
7224
7225 pub fn on_window_should_close(
7228 &self,
7229 cx: &App,
7230 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
7231 ) {
7232 let mut cx = self.to_async(cx);
7233 self.platform_window.on_should_close(Box::new(move || {
7234 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
7235 }))
7236 }
7237
7238 pub fn on_action(
7247 &mut self,
7248 action_type: TypeId,
7249 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
7250 ) {
7251 self.invalidator.debug_assert_paint();
7252
7253 self.next_frame
7254 .dispatch_tree
7255 .on_action(action_type, Rc::new(listener));
7256 }
7257
7258 pub fn on_action_when(
7267 &mut self,
7268 condition: bool,
7269 action_type: TypeId,
7270 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
7271 ) {
7272 self.invalidator.debug_assert_paint();
7273
7274 if condition {
7275 self.next_frame
7276 .dispatch_tree
7277 .on_action(action_type, Rc::new(listener));
7278 }
7279 }
7280
7281 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
7284 self.platform_window.gpu_specs()
7285 }
7286
7287 pub fn titlebar_double_click(&self) {
7290 self.platform_window
7291 .titlebar_double_click(self.is_resizable, self.is_minimizable);
7292 }
7293
7294 pub fn window_title(&self) -> String {
7297 self.platform_window.get_title()
7298 }
7299
7300 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
7303 self.platform_window.tabbed_windows()
7304 }
7305
7306 pub fn tab_bar_visible(&self) -> bool {
7309 self.platform_window.tab_bar_visible()
7310 }
7311
7312 pub fn merge_all_windows(&self) {
7315 self.platform_window.merge_all_windows()
7316 }
7317
7318 pub fn move_tab_to_new_window(&self) {
7321 self.platform_window.move_tab_to_new_window()
7322 }
7323
7324 pub fn toggle_window_tab_overview(&self) {
7327 self.platform_window.toggle_window_tab_overview()
7328 }
7329
7330 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
7333 self.platform_window
7334 .set_tabbing_identifier(tabbing_identifier)
7335 }
7336
7337 pub fn play_system_bell(&self) {
7340 self.platform_window.play_system_bell()
7341 }
7342
7343 pub fn is_a11y_enabled(&self) -> bool {
7350 self.a11y.is_enabled()
7351 }
7352
7353 pub fn is_a11y_active(&self) -> bool {
7364 self.a11y.is_active()
7365 }
7366
7367 pub fn debug_a11y_tree_json(&self) -> Option<String> {
7369 crate::fast::a11y::debug_tree_json(self)
7370 }
7371
7372 pub fn on_a11y_action(
7378 &mut self,
7379 node_id: accesskit::NodeId,
7380 action: accesskit::Action,
7381 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
7382 ) {
7383 crate::fast::a11y::A11yLog::action(&mut self.a11y.nodes.fast, node_id, action);
7384 self.a11y
7385 .action_listeners
7386 .entry(node_id)
7387 .or_default()
7388 .push((action, Box::new(listener)));
7389 }
7390
7391 #[cfg(not(target_family = "wasm"))]
7392 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
7393 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
7396 let extra_data = request.data.as_ref();
7397 let mut matched = false;
7398 for (action, listener) in &mut listeners {
7399 if *action == request.action {
7400 listener(extra_data, self, cx);
7401 matched = true;
7402 }
7403 }
7404 self.a11y
7405 .action_listeners
7406 .insert(request.target_node, listeners);
7407 if matched {
7408 return;
7409 }
7410 }
7411
7412 match request.action {
7414 accesskit::Action::Click => {
7415 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
7416 let center = bounds.center();
7417 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
7418 button: MouseButton::Left,
7419 position: center,
7420 modifiers: Modifiers::default(),
7421 click_count: 1,
7422 first_mouse: false,
7423 });
7424 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
7425 button: MouseButton::Left,
7426 position: center,
7427 modifiers: Modifiers::default(),
7428 click_count: 1,
7429 });
7430 self.dispatch_event(mouse_down, cx);
7431 self.dispatch_event(mouse_up, cx);
7432 }
7433 }
7434 accesskit::Action::Focus => {
7435 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
7436 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
7437 {
7438 self.focus(&handle, cx);
7439 }
7440 }
7441 accesskit::Action::Blur => {
7442 self.blur(cx);
7443 }
7444 _ => {
7445 log::debug!(
7446 "Unhandled a11y action: {:?} on {:?}",
7447 request.action,
7448 request.target_node
7449 );
7450 }
7451 }
7452 }
7453
7454 #[cfg(any(feature = "inspector", debug_assertions))]
7456 pub fn toggle_inspector(&mut self, cx: &mut App) {
7457 self.inspector = match self.inspector {
7458 None => Some(cx.new(|_| Inspector::new())),
7459 Some(_) => {
7460 self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
7461 self.rendered_frame.inspector_hitboxes = FxHashMap::default();
7462 self.next_frame.next_inspector_instance_ids = FxHashMap::default();
7463 self.next_frame.inspector_hitboxes = FxHashMap::default();
7464 None
7465 }
7466 };
7467 self.refresh();
7468 }
7469
7470 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
7472 #[cfg(any(feature = "inspector", debug_assertions))]
7473 {
7474 if let Some(inspector) = &self.inspector {
7475 return inspector.read(_cx).is_picking();
7476 }
7477 }
7478 false
7479 }
7480
7481 #[cfg(any(feature = "inspector", debug_assertions))]
7483 pub fn with_inspector_state<T: 'static, R>(
7484 &mut self,
7485 inspector_id: Option<&crate::InspectorElementId>,
7486 cx: &mut App,
7487 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
7488 ) -> Option<R> {
7489 let inspector_id = inspector_id?;
7490 let inspector = self.inspector.as_ref()?;
7491 if inspector.read(cx).active_element_id() != Some(inspector_id) {
7492 return None;
7493 }
7494 let inspector = inspector.clone();
7495 Some(inspector.update(cx, |inspector, _cx| {
7496 inspector.with_active_element_state(self, f)
7497 }))
7498 }
7499
7500 #[cfg(any(feature = "inspector", debug_assertions))]
7501 pub(crate) fn inspector_enabled(&self) -> bool {
7502 self.inspector.is_some()
7503 }
7504
7505 #[cfg(any(feature = "inspector", debug_assertions))]
7506 pub(crate) fn build_inspector_element_id(
7507 &mut self,
7508 path: crate::InspectorElementPath,
7509 ) -> crate::InspectorElementId {
7510 self.invalidator.debug_assert_paint_or_prepaint();
7511 let path = Rc::new(path);
7512 let next_instance_id = self
7513 .next_frame
7514 .next_inspector_instance_ids
7515 .entry(path.clone())
7516 .or_insert(0);
7517 let instance_id = *next_instance_id;
7518 *next_instance_id += 1;
7519 crate::InspectorElementId { path, instance_id }
7520 }
7521
7522 #[cfg(any(feature = "inspector", debug_assertions))]
7523 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
7524 if let Some(inspector) = self.inspector.take() {
7525 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
7526 inspector_element.prepaint_as_root(
7527 point(self.viewport_size.width - inspector_width, px(0.0)),
7528 size(inspector_width, self.viewport_size.height).into(),
7529 self,
7530 cx,
7531 );
7532 self.inspector = Some(inspector);
7533 Some(inspector_element)
7534 } else {
7535 None
7536 }
7537 }
7538
7539 #[cfg(any(feature = "inspector", debug_assertions))]
7540 fn paint_inspector(&mut self, inspector_element: Option<AnyElement>, cx: &mut App) {
7541 if let Some(mut inspector_element) = inspector_element {
7542 inspector_element.paint(self, cx);
7543 };
7544 }
7545
7546 #[cfg(any(feature = "inspector", debug_assertions))]
7549 pub fn insert_inspector_hitbox(
7550 &mut self,
7551 hitbox_id: HitboxId,
7552 inspector_id: Option<&crate::InspectorElementId>,
7553 cx: &App,
7554 ) {
7555 self.invalidator.debug_assert_paint_or_prepaint();
7556 if !self.is_inspector_picking(cx) {
7557 return;
7558 }
7559 if let Some(inspector_id) = inspector_id {
7560 self.next_frame
7561 .inspector_hitboxes
7562 .insert(hitbox_id, inspector_id.clone());
7563 }
7564 }
7565
7566 #[cfg(any(feature = "inspector", debug_assertions))]
7567 fn paint_inspector_hitbox(&mut self, cx: &App) {
7568 if let Some(inspector) = self.inspector.as_ref() {
7569 let inspector = inspector.read(cx);
7570 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
7571 && let Some(hitbox) = self
7572 .next_frame
7573 .hitboxes
7574 .iter()
7575 .find(|hitbox| hitbox.id == hitbox_id)
7576 {
7577 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
7578 }
7579 }
7580 }
7581
7582 #[cfg(any(feature = "inspector", debug_assertions))]
7583 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
7584 let Some(inspector) = self.inspector.clone() else {
7585 return;
7586 };
7587 if event.downcast_ref::<MouseMoveEvent>().is_some() {
7588 inspector.update(cx, |inspector, _cx| {
7589 if let Some((_, inspector_id)) =
7590 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7591 {
7592 inspector.hover(inspector_id, self);
7593 }
7594 });
7595 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
7596 inspector.update(cx, |inspector, _cx| {
7597 if let Some((_, inspector_id)) =
7598 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7599 {
7600 inspector.select(inspector_id, self);
7601 }
7602 });
7603 } else if let Some(event) = event.downcast_ref::<crate::ScrollEvent>() {
7604 const SCROLL_LINES: f32 = 3.0;
7606 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
7607 let delta_y = event
7608 .delta
7609 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
7610 .y;
7611 if let Some(inspector) = self.inspector.clone() {
7612 inspector.update(cx, |inspector, _cx| {
7613 if let Some(depth) = inspector.pick_depth.as_mut() {
7614 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
7615 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
7616 if *depth < 0.0 {
7617 *depth = 0.0;
7618 } else if *depth > max_depth {
7619 *depth = max_depth;
7620 }
7621 if let Some((_, inspector_id)) =
7622 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7623 {
7624 inspector.set_active_element_id(inspector_id, self);
7625 }
7626 }
7627 });
7628 }
7629 }
7630 }
7631
7632 #[cfg(any(feature = "inspector", debug_assertions))]
7633 fn hovered_inspector_hitbox(
7634 &self,
7635 inspector: &Inspector,
7636 frame: &Frame,
7637 ) -> Option<(HitboxId, crate::InspectorElementId)> {
7638 if let Some(pick_depth) = inspector.pick_depth {
7639 let depth = (pick_depth as i64).try_into().unwrap_or(0);
7640 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
7641 let skip_count = (depth as usize).min(max_skipped);
7642 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
7643 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
7644 return Some((*hitbox_id, inspector_id.clone()));
7645 }
7646 }
7647 }
7648 None
7649 }
7650
7651 #[cfg(any(test, feature = "test-support"))]
7654 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
7655 self.modifiers = modifiers;
7656 }
7657
7658 #[cfg(any(test, feature = "test-support"))]
7662 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
7663 let event = PlatformInput::MouseMove(MouseMoveEvent {
7664 position,
7665 modifiers: self.modifiers,
7666 pressed_button: None,
7667 });
7668 let _ = self.dispatch_event(event, cx);
7669 }
7670
7671 #[inline(never)]
7672 fn take_element_state(
7673 &mut self,
7674 global_id: &GlobalElementId,
7675 state_type: TypeId,
7676 ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
7677 let key = (global_id.clone(), state_type);
7678 self.next_frame.accessed_element_states.push(key.clone());
7679 let state = self
7680 .next_frame
7681 .element_states
7682 .remove(&key)
7683 .or_else(|| self.rendered_frame.element_states.remove(&key));
7684 (key, state)
7685 }
7686
7687 #[inline(never)]
7688 fn insert_element_state(
7689 &mut self,
7690 key: (GlobalElementId, TypeId),
7691 state: ElementStateBox,
7692 ) -> Option<ElementStateBox> {
7693 self.next_frame.element_states.insert(key, state)
7694 }
7695
7696 #[inline(never)]
7697 fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
7698 cx.observe(state, move |_, cx| {
7699 cx.notify(current_view);
7700 })
7701 .detach();
7702 }
7703}
7704
7705slotmap::new_key_type! {
7707 pub struct WindowId;
7709}
7710
7711impl WindowId {
7712 pub fn as_u64(&self) -> u64 {
7714 self.0.as_ffi()
7715 }
7716}
7717
7718impl From<u64> for WindowId {
7719 fn from(value: u64) -> Self {
7720 WindowId(slotmap::KeyData::from_ffi(value))
7721 }
7722}
7723
7724#[derive(Deref, DerefMut)]
7727pub struct WindowHandle<V> {
7728 #[deref]
7729 #[deref_mut]
7730 pub(crate) any_handle: AnyWindowHandle,
7731 state_type: PhantomData<fn(V) -> V>,
7732}
7733
7734impl<V> Debug for WindowHandle<V> {
7735 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7736 f.debug_struct("WindowHandle")
7737 .field("any_handle", &self.any_handle.id.as_u64())
7738 .finish()
7739 }
7740}
7741
7742impl<V: 'static + Render> WindowHandle<V> {
7743 pub fn new(id: WindowId) -> Self {
7746 WindowHandle {
7747 any_handle: AnyWindowHandle {
7748 id,
7749 state_type: TypeId::of::<V>(),
7750 root_entity_type_name: std::any::type_name::<V>(),
7751 },
7752 state_type: PhantomData,
7753 }
7754 }
7755
7756 #[cfg(any(test, feature = "test-support"))]
7760 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
7761 where
7762 C: AppContext,
7763 {
7764 cx.update_window(self.any_handle, |root_view, _, _| {
7765 root_view
7766 .downcast::<V>()
7767 .map_err(|_| anyhow!("the type of the window's root view has changed"))
7768 })?
7769 }
7770
7771 #[track_caller]
7775 pub fn update<C, R>(
7776 &self,
7777 cx: &mut C,
7778 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
7779 ) -> Result<R>
7780 where
7781 C: AppContext,
7782 {
7783 cx.update_window(self.any_handle, |root_view, window, cx| {
7784 let view = root_view
7785 .downcast::<V>()
7786 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7787
7788 Ok(view.update(cx, |view, cx| update(view, window, cx)))
7789 })?
7790 }
7791
7792 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
7796 let x = cx
7797 .windows
7798 .get(self.id)
7799 .and_then(|window| {
7800 window
7801 .as_deref()
7802 .and_then(|window| window.root.clone())
7803 .map(|root_view| root_view.downcast::<V>())
7804 })
7805 .context("window not found")?
7806 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7807
7808 Ok(x.read(cx))
7809 }
7810
7811 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
7815 where
7816 C: AppContext,
7817 {
7818 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
7819 }
7820
7821 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
7825 where
7826 C: AppContext,
7827 {
7828 cx.read_window(self, |root_view, _cx| root_view)
7829 }
7830
7831 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
7836 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
7837 .ok()
7838 }
7839}
7840
7841impl<V> Copy for WindowHandle<V> {}
7842
7843impl<V> Clone for WindowHandle<V> {
7844 fn clone(&self) -> Self {
7845 *self
7846 }
7847}
7848
7849impl<V> PartialEq for WindowHandle<V> {
7850 fn eq(&self, other: &Self) -> bool {
7851 self.any_handle == other.any_handle
7852 }
7853}
7854
7855impl<V> Eq for WindowHandle<V> {}
7856
7857impl<V> Hash for WindowHandle<V> {
7858 fn hash<H: Hasher>(&self, state: &mut H) {
7859 self.any_handle.hash(state);
7860 }
7861}
7862
7863impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
7864 fn from(val: WindowHandle<V>) -> Self {
7865 val.any_handle
7866 }
7867}
7868
7869#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
7871pub struct AnyWindowHandle {
7872 pub(crate) id: WindowId,
7873 state_type: TypeId,
7874 root_entity_type_name: &'static str,
7875}
7876
7877impl AnyWindowHandle {
7878 pub fn window_id(&self) -> WindowId {
7880 self.id
7881 }
7882
7883 pub fn root_entity_type_name(&self) -> &'static str {
7885 self.root_entity_type_name
7886 }
7887
7888 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
7891 if TypeId::of::<T>() == self.state_type {
7892 Some(WindowHandle {
7893 any_handle: *self,
7894 state_type: PhantomData,
7895 })
7896 } else {
7897 None
7898 }
7899 }
7900
7901 #[track_caller]
7905 pub fn update<C, R>(
7906 self,
7907 cx: &mut C,
7908 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
7909 ) -> Result<R>
7910 where
7911 C: AppContext,
7912 {
7913 cx.update_window(self, update)
7914 }
7915
7916 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
7920 where
7921 C: AppContext,
7922 T: 'static,
7923 {
7924 let view = self
7925 .downcast::<T>()
7926 .context("the type of the window's root view has changed")?;
7927
7928 cx.read_window(&view, read)
7929 }
7930}
7931
7932impl HasWindowHandle for Window {
7933 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
7934 self.platform_window.window_handle()
7935 }
7936}
7937
7938impl HasDisplayHandle for Window {
7939 fn display_handle(
7940 &self,
7941 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
7942 self.platform_window.display_handle()
7943 }
7944}
7945
7946#[derive(Clone, Debug, Eq, PartialEq, Hash)]
7951pub enum ElementId {
7952 View(EntityId),
7954 Integer(u64),
7956 Name(SharedString),
7958 Uuid(Uuid),
7960 FocusHandle(FocusId),
7962 NamedInteger(SharedString, u64),
7964 Path(Arc<std::path::Path>),
7966 CodeLocation(core::panic::Location<'static>),
7968 NamedChild(Arc<ElementId>, SharedString),
7970 OpaqueId([u8; 20]),
7972}
7973
7974impl ElementId {
7975 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
7977 Self::NamedInteger(name.into(), integer as u64)
7978 }
7979}
7980
7981impl Display for ElementId {
7982 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7983 match self {
7984 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
7985 ElementId::Integer(ix) => write!(f, "{}", ix)?,
7986 ElementId::Name(name) => write!(f, "{}", name)?,
7987 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
7988 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
7989 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
7990 ElementId::Path(path) => write!(f, "{}", path.display())?,
7991 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
7992 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
7993 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
7994 }
7995
7996 Ok(())
7997 }
7998}
7999
8000impl TryInto<SharedString> for ElementId {
8001 type Error = anyhow::Error;
8002
8003 fn try_into(self) -> anyhow::Result<SharedString> {
8004 if let ElementId::Name(name) = self {
8005 Ok(name)
8006 } else {
8007 anyhow::bail!("element id is not string")
8008 }
8009 }
8010}
8011
8012impl From<u64> for ElementId {
8013 fn from(id: u64) -> Self {
8014 ElementId::Integer(id)
8015 }
8016}
8017
8018impl From<usize> for ElementId {
8019 fn from(id: usize) -> Self {
8020 ElementId::Integer(id as u64)
8021 }
8022}
8023
8024impl From<i32> for ElementId {
8025 fn from(id: i32) -> Self {
8026 Self::Integer(id as u64)
8027 }
8028}
8029
8030impl From<SharedString> for ElementId {
8031 fn from(name: SharedString) -> Self {
8032 ElementId::Name(name)
8033 }
8034}
8035
8036impl From<String> for ElementId {
8037 fn from(name: String) -> Self {
8038 ElementId::Name(name.into())
8039 }
8040}
8041
8042impl From<Arc<str>> for ElementId {
8043 fn from(name: Arc<str>) -> Self {
8044 ElementId::Name(name.into())
8045 }
8046}
8047
8048impl From<Arc<std::path::Path>> for ElementId {
8049 fn from(path: Arc<std::path::Path>) -> Self {
8050 ElementId::Path(path)
8051 }
8052}
8053
8054impl From<&'static str> for ElementId {
8055 fn from(name: &'static str) -> Self {
8056 ElementId::Name(SharedString::new_static(name))
8057 }
8058}
8059
8060impl<'a> From<&'a FocusHandle> for ElementId {
8061 fn from(handle: &'a FocusHandle) -> Self {
8062 ElementId::FocusHandle(handle.id)
8063 }
8064}
8065
8066impl From<(&'static str, EntityId)> for ElementId {
8067 fn from((name, id): (&'static str, EntityId)) -> Self {
8068 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
8069 }
8070}
8071
8072impl From<(&'static str, usize)> for ElementId {
8073 fn from((name, id): (&'static str, usize)) -> Self {
8074 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
8075 }
8076}
8077
8078impl From<(SharedString, usize)> for ElementId {
8079 fn from((name, id): (SharedString, usize)) -> Self {
8080 ElementId::NamedInteger(name, id as u64)
8081 }
8082}
8083
8084impl From<(&'static str, u64)> for ElementId {
8085 fn from((name, id): (&'static str, u64)) -> Self {
8086 ElementId::NamedInteger(SharedString::new_static(name), id)
8087 }
8088}
8089
8090impl From<Uuid> for ElementId {
8091 fn from(value: Uuid) -> Self {
8092 Self::Uuid(value)
8093 }
8094}
8095
8096impl From<(&'static str, u32)> for ElementId {
8097 fn from((name, id): (&'static str, u32)) -> Self {
8098 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
8099 }
8100}
8101
8102impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
8103 fn from((id, name): (ElementId, T)) -> Self {
8104 ElementId::NamedChild(Arc::new(id), name.into())
8105 }
8106}
8107
8108impl From<&'static core::panic::Location<'static>> for ElementId {
8109 fn from(location: &'static core::panic::Location<'static>) -> Self {
8110 ElementId::CodeLocation(*location)
8111 }
8112}
8113
8114impl From<[u8; 20]> for ElementId {
8115 fn from(opaque_id: [u8; 20]) -> Self {
8116 ElementId::OpaqueId(opaque_id)
8117 }
8118}
8119
8120#[derive(Clone)]
8123pub struct PaintQuad {
8124 pub bounds: Bounds<Pixels>,
8126 pub corner_radii: Corners<Pixels>,
8128 pub background: Background,
8130 pub border_widths: Edges<Pixels>,
8132 pub border_color: Hsla,
8134 pub border_style: BorderStyle,
8136}
8137
8138impl PaintQuad {
8139 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
8141 PaintQuad {
8142 corner_radii: corner_radii.into(),
8143 ..self
8144 }
8145 }
8146
8147 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
8149 PaintQuad {
8150 border_widths: border_widths.into(),
8151 ..self
8152 }
8153 }
8154
8155 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
8157 PaintQuad {
8158 border_color: border_color.into(),
8159 ..self
8160 }
8161 }
8162
8163 pub fn background(self, background: impl Into<Background>) -> Self {
8165 PaintQuad {
8166 background: background.into(),
8167 ..self
8168 }
8169 }
8170}
8171
8172pub fn quad(
8174 bounds: Bounds<Pixels>,
8175 corner_radii: impl Into<Corners<Pixels>>,
8176 background: impl Into<Background>,
8177 border_widths: impl Into<Edges<Pixels>>,
8178 border_color: impl Into<Hsla>,
8179 border_style: BorderStyle,
8180) -> PaintQuad {
8181 PaintQuad {
8182 bounds,
8183 corner_radii: corner_radii.into(),
8184 background: background.into(),
8185 border_widths: border_widths.into(),
8186 border_color: border_color.into(),
8187 border_style,
8188 }
8189}
8190
8191pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
8193 PaintQuad {
8194 bounds: bounds.into(),
8195 corner_radii: (0.).into(),
8196 background: background.into(),
8197 border_widths: (0.).into(),
8198 border_color: transparent_black(),
8199 border_style: BorderStyle::default(),
8200 }
8201}
8202
8203pub fn outline(
8205 bounds: impl Into<Bounds<Pixels>>,
8206 border_color: impl Into<Hsla>,
8207 border_style: BorderStyle,
8208) -> PaintQuad {
8209 PaintQuad {
8210 bounds: bounds.into(),
8211 corner_radii: (0.).into(),
8212 background: transparent_black().into(),
8213 border_widths: (1.).into(),
8214 border_color: border_color.into(),
8215 border_style,
8216 }
8217}
8218
8219#[inline(never)]
8220fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
8221 if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
8222 let arena_cell = unsafe { &*arena_pointer };
8225 callback(&mut arena_cell.borrow_mut());
8226 Ok(())
8227 } else {
8228 ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
8229 }
8230}
8231
8232#[cfg(test)]
8233mod tests {
8234 use std::{
8235 cell::{Cell, RefCell},
8236 path::PathBuf,
8237 rc::Rc,
8238 time::Duration,
8239 };
8240
8241 use crate::{
8242 AnyWindowHandle, AppContext as _, BackGestureEvent, BackGesturePhase, Bounds, ContentMask,
8243 Context, CursorStyle, DispatchPhase, DragMoveEvent, Empty, ExternalDragPayload,
8244 ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle, InputEvent as _,
8245 InteractiveElement as _, IntoElement, KeyDownEvent, Keystroke, LongPressEvent, MouseButton,
8246 MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, PlatformInput, Point,
8247 Render, RequestFrameOptions, ScaledPixels, StatefulInteractiveElement as _, Styled,
8248 TestAppContext, ThermalState, TouchDragEvent, TouchEvent, TouchId, TouchPhase, Underline,
8249 UnderlineStyle, Window, WindowAppearance, WindowOptions, canvas, div, hsla, point, px,
8250 size,
8251 };
8252
8253 #[gpui::test]
8254 async fn test_focus_handle_release(cx: &mut TestAppContext) {
8255 let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
8256 let handle_id = handle.id;
8257 let weak_handle = handle.downgrade();
8258 let retained = handle.clone();
8259 drop(handle);
8260
8261 cx.update(|_| {});
8262 cx.read(|cx| {
8263 let handles = cx.focus_handles.read();
8264 assert_eq!(handles.handles.len(), 2);
8265 assert!(handles.dropped_handles.is_empty());
8266 });
8267 assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));
8268
8269 cx.background_spawn(async move { drop(retained) }).await;
8270 assert_eq!(weak_handle.upgrade(), None);
8271 cx.read(|cx| {
8272 assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);
8273 });
8274 cx.update(|_| {});
8275 cx.read(|cx| {
8276 let handles = cx.focus_handles.read();
8277 assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);
8278 assert!(handles.dropped_handles.is_empty());
8279 });
8280
8281 let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);
8282 assert_eq!(weak_handle.upgrade(), None);
8283 cx.update(|cx| {
8284 drop(replacements);
8285 cx.defer(move |_| drop(survivor));
8286 });
8287 cx.read(|cx| {
8288 let handles = cx.focus_handles.read();
8289 assert_eq!(handles.handles.len(), 0);
8290 assert!(handles.dropped_handles.is_empty());
8291 });
8292 }
8293
8294 #[gpui::test]
8295 fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {
8296 let windows = [
8297 cx.add_window(|_, _| EmptyView),
8298 cx.add_window(|_, _| EmptyView),
8299 cx.add_window(|_, _| EmptyView),
8300 cx.add_window(|_, _| EmptyView),
8301 cx.add_window(|_, _| EmptyView),
8302 ];
8303 let (handle, other_handle, survivor) =
8304 cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));
8305 for window in &windows[..2] {
8306 window
8307 .update(cx, |_, window, cx| window.focus(&handle, cx))
8308 .expect("window exists");
8309 }
8310 windows[2]
8311 .update(cx, |_, window, cx| window.focus(&other_handle, cx))
8312 .expect("window exists");
8313 windows[3]
8314 .update(cx, |_, window, cx| window.focus(&survivor, cx))
8315 .expect("window exists");
8316
8317 cx.update(|cx| {
8318 for _ in 0..1_000 {
8319 drop(cx.focus_handle());
8320 }
8321 drop((handle, other_handle));
8322 });
8323 for window in &windows[..3] {
8324 window
8325 .update(cx, |_, window, _| assert_eq!(window.focus, None))
8326 .expect("window exists");
8327 }
8328 windows[3]
8329 .update(cx, |_, window, cx| {
8330 assert_eq!(window.focused(cx).as_ref(), Some(&survivor));
8331 assert_eq!(window.focus_generation, 1);
8332 })
8333 .expect("window exists");
8334 windows[4]
8335 .update(cx, |_, window, _| {
8336 assert_eq!(window.focus, None);
8337 assert_eq!(window.focus_generation, 0);
8338 })
8339 .expect("window exists");
8340 }
8341
8342 #[gpui::test]
8343 fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
8344 let window = cx.add_window(|_, _| EmptyView);
8345 let platform_window = cx.test_window(window.into());
8346 {
8347 let app = cx.app.borrow_mut();
8348 platform_window.simulate_close();
8349 assert!(app.windows.contains_key(window.window_id()));
8350 }
8351 cx.run_until_parked();
8352 assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
8353 }
8354
8355 #[cfg(feature = "profiler")]
8356 #[gpui::test]
8357 fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
8358 use crate::FrameRequestSource;
8359 use crate::profiler::journal::{
8360 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
8361 };
8362 use scheduler::Instant;
8363
8364 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8365 let window = cx.add_window(|_, _| EmptyView);
8366 let platform_window = cx.test_window(window.into());
8367 platform_window.simulate_frame_request(RequestFrameOptions::default());
8368 let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
8369 let mut collector = journal.collector();
8370
8371 for (signal_at, source) in [
8372 (Some(Instant::now()), FrameRequestSource::NativeCallback),
8373 (Some(Instant::now()), FrameRequestSource::LocalSchedule),
8374 (None, FrameRequestSource::NativeCallback),
8375 ] {
8376 platform_window.simulate_frame_request(RequestFrameOptions {
8377 signal_at,
8378 signal_source: source,
8379 require_presentation: true,
8380 ..Default::default()
8381 });
8382 let entries = collector.collect_unseen().entries;
8383 let signal_index = entries
8384 .iter()
8385 .position(|entry| {
8386 matches!(
8387 entry,
8388 ForegroundJournalEntry::PlatformSignal(signal)
8389 if signal.window_id == window.window_id()
8390 && signal.signal_at == signal_at
8391 && signal.source == source
8392 && signal_at.is_none_or(|at| signal.handled_at >= at)
8393 )
8394 })
8395 .expect("frame request metadata");
8396 let skip_index = entries
8397 .iter()
8398 .position(|entry| {
8399 matches!(
8400 entry,
8401 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
8402 if skipped.window_id == window.window_id()
8403 && skipped.reason == FrameSkipReason::NoRenderNeeded
8404 )
8405 })
8406 .expect("completed no-render boundary");
8407 assert!(signal_index < skip_index);
8408 }
8409 }
8410
8411 #[cfg(feature = "profiler")]
8412 #[gpui::test]
8413 fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
8414 use crate::profiler::journal::{
8415 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
8416 };
8417 use scheduler::Instant;
8418
8419 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8421 let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
8422 let mut collector = journal.collector();
8423 for (initially_dirty, schedule_callback) in [(true, false), (false, true)] {
8424 let window = cx
8426 .app
8427 .borrow_mut()
8428 .open_window(
8429 WindowOptions {
8430 inactive_frame_interval: Some(Duration::from_secs(3600)),
8431 ..Default::default()
8432 },
8433 |_, cx| cx.new(|_| EmptyView),
8434 )
8435 .expect("open inactive test window");
8436 let platform_window = cx.test_window(window.into());
8437 platform_window.simulate_active_status_change(false);
8438 platform_window.simulate_frame_request(RequestFrameOptions::default());
8439 let callback_ran = Rc::new(Cell::new(false));
8440 let draws_before = window
8441 .update(cx, |_, window, _| {
8442 let draws_before = window
8443 .frame_duration_snapshot()
8444 .draw_duration_histogram
8445 .len();
8446 if initially_dirty {
8447 window.refresh();
8448 }
8449 if schedule_callback {
8450 window.on_next_frame({
8451 let callback_ran = callback_ran.clone();
8452 move |window, _| {
8453 callback_ran.set(true);
8454 window.refresh();
8455 }
8456 });
8457 }
8458 draws_before
8459 })
8460 .expect("schedule throttled frame");
8461 let input_at = Instant::now();
8463 journal::record_input(journal::InputTiming {
8464 kind: "test",
8465 start: input_at,
8466 end: input_at,
8467 caused_invalidation: false,
8468 });
8469 collector.collect_unseen();
8470 let wakes_before = platform_window.frame_wake_count();
8471 platform_window.simulate_frame_request(RequestFrameOptions {
8472 signal_at: Some(Instant::now()),
8473 ..Default::default()
8474 });
8475 window
8476 .update(cx, |_, window, _| {
8477 assert_eq!(
8478 window
8479 .frame_duration_snapshot()
8480 .draw_duration_histogram
8481 .len(),
8482 draws_before,
8483 );
8484 })
8485 .expect("inspect deferred frame");
8486 assert!(!callback_ran.get());
8487 assert!(platform_window.frame_scheduled());
8488 assert!(platform_window.frame_wake_count() > wakes_before);
8489 assert!(collector.collect_unseen().entries.iter().any(|entry| {
8490 matches!(
8491 entry,
8492 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
8493 if skipped.window_id == window.window_id()
8494 && skipped.reason == FrameSkipReason::InactiveFrameRateLimit
8495 )
8496 }));
8497 platform_window.simulate_frame_request(RequestFrameOptions {
8498 signal_at: Some(Instant::now()),
8499 require_presentation: true,
8500 ..Default::default()
8501 });
8502 window
8503 .update(cx, |_, window, _| {
8504 assert_eq!(
8505 window
8506 .frame_duration_snapshot()
8507 .draw_duration_histogram
8508 .len(),
8509 draws_before + 1,
8510 );
8511 })
8512 .expect("inspect presented frame");
8513 assert_eq!(callback_ran.get(), schedule_callback);
8514 }
8515 }
8516
8517 #[gpui::test]
8521 fn test_window_visibility(cx: &mut TestAppContext) {
8522 use crate::WindowVisibility;
8523
8524 let window = cx.add_window(|_, _| EmptyView);
8525 let observed = Rc::new(RefCell::new(Vec::new()));
8526 let _subscription = window
8527 .update(cx, {
8528 let observed = observed.clone();
8529 move |_, window, _| {
8530 assert_eq!(window.visibility(), WindowVisibility::Visible);
8531 assert!(window.is_visible());
8532 window.observe_window_visibility(move |visibility, window, _| {
8533 assert_eq!(window.visibility(), visibility);
8534 observed.borrow_mut().push(visibility);
8535 })
8536 }
8537 })
8538 .unwrap();
8539 let test_window = cx.test_window(window.into());
8540 let frame_wake_count = test_window.frame_wake_count();
8541
8542 test_window.simulate_visibility_change(WindowVisibility::Hidden);
8543 assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
8544 window
8545 .update(cx, |_, window, _| assert!(!window.is_visible()))
8546 .unwrap();
8547
8548 test_window.simulate_visibility_change(WindowVisibility::Hidden);
8550 assert_eq!(observed.borrow().len(), 1);
8551
8552 test_window.simulate_visibility_change(WindowVisibility::Visible);
8553 assert_eq!(
8554 *observed.borrow(),
8555 [WindowVisibility::Hidden, WindowVisibility::Visible]
8556 );
8557 window
8558 .update(cx, |_, window, _| assert!(window.is_visible()))
8559 .unwrap();
8560 assert_eq!(test_window.frame_wake_count(), frame_wake_count);
8561 }
8562
8563 #[gpui::test]
8566 fn test_display_tracking(cx: &mut TestAppContext) {
8567 use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
8568
8569 let sixty_hertz = Duration::from_secs(1) / 60;
8570 let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
8571 let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
8572
8573 let display_events = Rc::new(RefCell::new(Vec::new()));
8574 let _display_subscription = cx.update({
8575 let display_events = display_events.clone();
8576 move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
8577 });
8578
8579 let window = cx.add_window(|window, cx| DisplayTracker {
8580 refresh_intervals: Vec::new(),
8581 _subscription: cx.observe_window_display(
8582 window,
8583 |tracker: &mut DisplayTracker, window, cx| {
8584 tracker.refresh_intervals.push(window.refresh_interval(cx));
8585 },
8586 ),
8587 });
8588 let window_notifications = Rc::new(RefCell::new(Vec::new()));
8589 let _window_subscription = window
8590 .update(cx, {
8591 let window_notifications = window_notifications.clone();
8592 move |_, window, cx| {
8593 assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
8594 window.observe_window_display(move |window, cx| {
8595 window_notifications
8596 .borrow_mut()
8597 .push((window.display_id, window.refresh_interval(cx)));
8598 })
8599 }
8600 })
8601 .unwrap();
8602 let test_window = cx.test_window(window.into());
8603
8604 cx.test_platform()
8609 .connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
8610 test_window.simulate_move_to_display(DisplayId(2));
8611 assert_eq!(
8612 window_notifications.take(),
8613 [(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
8614 );
8615 assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
8616 cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
8617 assert!(window_notifications.borrow().is_empty());
8618
8619 test_window.simulate_move_to_display(DisplayId(2));
8621 assert!(window_notifications.borrow().is_empty());
8622
8623 cx.simulate_display_refresh_interval_change(
8624 DisplayId(2),
8625 Some(one_hundred_forty_four_hertz),
8626 );
8627 assert_eq!(
8628 window_notifications.take(),
8629 [(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
8630 );
8631
8632 cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
8634 cx.simulate_display_removed(DisplayId(1));
8635 assert!(window_notifications.borrow().is_empty());
8636
8637 assert_eq!(
8638 display_events.take(),
8639 [
8640 DisplayEvent::Changed {
8641 id: DisplayId(2),
8642 changes: DisplayChanges::REFRESH_INTERVAL,
8643 },
8644 DisplayEvent::Changed {
8645 id: DisplayId(1),
8646 changes: DisplayChanges::REFRESH_INTERVAL,
8647 },
8648 DisplayEvent::Removed(DisplayId(1)),
8649 ]
8650 );
8651 window
8652 .update(cx, |tracker, _, _| {
8653 assert_eq!(
8654 tracker.refresh_intervals,
8655 [
8656 Some(one_hundred_twenty_hertz),
8657 Some(one_hundred_forty_four_hertz)
8658 ]
8659 );
8660 })
8661 .unwrap();
8662
8663 struct DisplayTracker {
8664 refresh_intervals: Vec<Option<Duration>>,
8665 _subscription: Subscription,
8666 }
8667
8668 impl Render for DisplayTracker {
8669 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8670 Empty
8671 }
8672 }
8673 }
8674
8675 #[gpui::test]
8676 fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
8677 let window = cx.add_window(|_, _| EmptyView);
8678 let mut platform_window = cx.test_window(window.into());
8679 platform_window.simulate_resize(size(px(400.), px(800.)));
8680 window
8681 .update(cx, |_, window, _| {
8682 assert_eq!(
8683 window.visual_viewport_bounds(),
8684 Bounds::new(Point::default(), size(px(400.), px(800.)))
8685 );
8686 assert_eq!(
8687 window.fully_visible_bounds(),
8688 window.visual_viewport_bounds()
8689 );
8690 })
8691 .unwrap();
8692
8693 platform_window.simulate_frame_request(RequestFrameOptions::default());
8694 let wakes = platform_window.frame_wake_count();
8695 let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
8696 platform_window.simulate_visual_viewport_change(visual_bounds);
8697 assert!(platform_window.frame_wake_count() > wakes);
8698 platform_window.simulate_frame_request(RequestFrameOptions::default());
8699 let wakes = platform_window.frame_wake_count();
8700 let insets = crate::WindowInsets {
8701 safe_area: crate::Edges {
8702 top: px(60.),
8703 right: px(20.),
8704 bottom: px(30.),
8705 left: px(-10.),
8706 },
8707 ime: crate::Edges {
8708 bottom: px(350.),
8709 ..Default::default()
8710 },
8711 ..Default::default()
8712 };
8713 platform_window.simulate_insets_change(insets.clone());
8714 assert!(platform_window.frame_wake_count() > wakes);
8715 window
8716 .update(cx, |_, window, cx| {
8717 let focus = cx.focus_handle();
8718 window.focus(&focus, cx);
8719 assert_eq!(window.insets(), insets);
8720 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
8721 assert_eq!(window.visual_viewport_bounds(), visual_bounds);
8722 assert_eq!(
8723 window.fully_visible_bounds(),
8724 Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
8725 );
8726 window.request_virtual_keyboard();
8727 window.dismiss_virtual_keyboard();
8728 assert!(focus.is_focused(window));
8729 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
8730 })
8731 .unwrap();
8732 assert_eq!(platform_window.virtual_keyboard_requests(), 1);
8733 assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
8734
8735 platform_window.simulate_insets_change(crate::WindowInsets {
8736 safe_area: crate::Edges {
8737 top: px(900.),
8738 left: px(500.),
8739 ..Default::default()
8740 },
8741 ..Default::default()
8742 });
8743 window
8744 .update(cx, |_, window, _| {
8745 assert_eq!(
8746 window.fully_visible_bounds().size,
8747 size(Pixels::ZERO, Pixels::ZERO)
8748 );
8749 })
8750 .unwrap();
8751
8752 use crate::PlatformWindow as _;
8754 platform_window.on_insets_changed(Box::new(|_| {}));
8755 platform_window.simulate_insets_change(crate::WindowInsets::default());
8756 window
8757 .update(cx, |_, window, _| {
8758 assert_eq!(window.insets(), crate::WindowInsets::default());
8759 })
8760 .unwrap();
8761 }
8762
8763 #[test]
8764 fn frame_throttle_tracks_display_refreshes() {
8765 let start = super::Instant::now();
8766 for (elapsed, interval) in [
8767 (Duration::from_micros(16_666), Duration::from_micros(16_667)),
8768 (Duration::from_micros(33_332), Duration::from_micros(33_333)),
8769 ] {
8770 let mut pacer = super::FramePacer::default();
8771 assert!(!pacer.should_defer(start, Some(interval)));
8772 assert!(pacer.should_defer(start + elapsed / 2, Some(interval)));
8773 assert!(!pacer.should_defer(start + elapsed, Some(interval)));
8774 }
8775 }
8776
8777 #[test]
8778 fn frame_throttle_preserves_cadence_without_catching_up_after_stalls() {
8779 let start = super::Instant::now();
8780 let interval = Duration::from_micros(33_333);
8781 let mut pacer = super::FramePacer::default();
8782 assert!(!pacer.should_defer(start, Some(interval)));
8783 let delayed_frame = start + interval + Duration::from_millis(5);
8784 assert!(!pacer.should_defer(delayed_frame, Some(interval)));
8785 assert!(pacer.should_defer(start + interval + interval / 2, Some(interval)));
8786 assert!(!pacer.should_defer(start + interval * 2, Some(interval)));
8787
8788 let after_stall = start + interval * 4 - Duration::from_millis(1);
8790 assert!(!pacer.should_defer(after_stall, Some(interval)));
8791 assert!(pacer.should_defer(after_stall + interval / 2, Some(interval)));
8792 assert!(!pacer.should_defer(after_stall + interval, Some(interval)));
8793 let mandatory_frame = after_stall + interval + Duration::from_millis(2);
8795 assert!(!pacer.should_defer(mandatory_frame, None));
8796 assert!(pacer.should_defer(mandatory_frame + interval / 2, Some(interval)));
8797 }
8798
8799 #[test]
8800 fn power_modes_preserve_frame_limits() {
8801 let options = WindowOptions::default();
8802 for (power_mode, active_interval, thermal_interval) in [
8803 (
8804 crate::PowerMode::LowPower,
8805 Some(Duration::from_micros(33_333)),
8806 Duration::from_micros(33_333),
8807 ),
8808 (
8809 crate::PowerMode::Unknown,
8810 None,
8811 Duration::from_micros(16_667),
8812 ),
8813 (
8814 crate::PowerMode::Balanced,
8815 None,
8816 Duration::from_micros(16_667),
8817 ),
8818 (
8819 crate::PowerMode::HighPower,
8820 None,
8821 Duration::from_micros(16_667),
8822 ),
8823 ] {
8824 assert_eq!(
8825 super::minimum_frame_interval(
8826 true,
8827 false,
8828 options.inactive_frame_interval,
8829 options.low_power_frame_interval,
8830 options.thermal_frame_interval,
8831 ThermalState::Nominal,
8832 power_mode,
8833 ),
8834 active_interval,
8835 );
8836 assert_eq!(
8837 super::minimum_frame_interval(
8838 true,
8839 false,
8840 options.inactive_frame_interval,
8841 options.low_power_frame_interval,
8842 options.thermal_frame_interval,
8843 ThermalState::Serious,
8844 power_mode,
8845 ),
8846 Some(thermal_interval),
8847 );
8848 }
8849 }
8850
8851 #[test]
8852 fn frame_limits_combine_enabled_intervals() {
8853 let short = Some(Duration::from_millis(10));
8854 let long = Some(Duration::from_millis(100));
8855 for (inactive, low_power, thermal, expected) in [
8856 (long, short, short, long),
8857 (short, long, short, long),
8858 (short, short, long, long),
8859 (long, None, None, long),
8860 (None, long, None, long),
8861 (None, None, long, long),
8862 (None, None, None, None),
8863 ] {
8864 assert_eq!(
8865 super::minimum_frame_interval(
8866 true,
8867 true,
8868 inactive,
8869 low_power,
8870 thermal,
8871 ThermalState::Critical,
8872 crate::PowerMode::LowPower,
8873 ),
8874 expected,
8875 );
8876 }
8877 assert_eq!(
8878 super::minimum_frame_interval(
8879 false,
8880 true,
8881 long,
8882 long,
8883 long,
8884 ThermalState::Critical,
8885 crate::PowerMode::LowPower,
8886 ),
8887 None,
8888 );
8889 }
8890
8891 struct EmptyView;
8892
8893 impl Render for EmptyView {
8894 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8895 div()
8896 }
8897 }
8898
8899 struct OpensWindowOnPaint {
8900 opened: Rc<Cell<bool>>,
8901 }
8902
8903 impl Render for OpensWindowOnPaint {
8904 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8905 let opened = self.opened.clone();
8906 div()
8907 .size_full()
8908 .child(canvas(
8909 |_, _, _| {},
8910 move |_, _, _window, cx| {
8911 if !opened.replace(true) {
8912 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
8913 .unwrap();
8914 }
8915 },
8916 ))
8917 .child(div().child("after"))
8921 }
8922 }
8923
8924 #[test]
8930 fn test_window_opened_during_draw_defers_arena_clear() {
8931 let mut cx = TestAppContext::single();
8932
8933 let opened = Rc::new(Cell::new(false));
8934 let window = cx.add_window({
8936 let opened = opened.clone();
8937 move |_, _| OpensWindowOnPaint { opened }
8938 });
8939
8940 assert!(opened.get());
8941 assert_eq!(cx.windows().len(), 2);
8942
8943 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8946 .unwrap();
8947 }
8948
8949 #[test]
8950 fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
8951 let mut cx = TestAppContext::single();
8952 let window = cx.add_window(|_, _| EmptyView);
8953 let handle: AnyWindowHandle = window.into();
8954 let window_state = |cx: &mut TestAppContext| {
8955 cx.update_window(handle, |_, window, _| {
8956 (
8957 window.scale_factor(),
8958 window.bounds(),
8959 window.viewport_size(),
8960 )
8961 })
8962 .unwrap()
8963 };
8964
8965 let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
8966 assert_eq!(scale_factor, 2.0);
8967
8968 for (scale_factor, resized_size) in [
8969 (1.0, size(px(800.), px(600.))),
8970 (1.25, size(px(640.), px(480.))),
8971 (2.0, size(px(1024.), px(768.))),
8972 ] {
8973 cx.simulate_window_scale_factor_change(handle, scale_factor);
8974 assert_eq!(
8975 window_state(&mut cx),
8976 (scale_factor, expected_bounds, expected_bounds.size)
8977 );
8978
8979 cx.simulate_window_resize(handle, resized_size);
8980 expected_bounds.size = resized_size;
8981 assert_eq!(
8982 window_state(&mut cx),
8983 (scale_factor, expected_bounds, resized_size)
8984 );
8985 }
8986 }
8987
8988 #[gpui::test]
8993 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
8994 let window = cx.add_window(|_, _| EmptyView);
8995 let test_window = cx.test_window(window.into());
8996 test_window.simulate_active_status_change(true);
8998
8999 assert!(
9003 test_window.frame_wake_count() >= 1,
9004 "opening a window must wake the frame source for the initial frame"
9005 );
9006
9007 test_window.simulate_frame_request(RequestFrameOptions::default());
9009
9010 let baseline = test_window.frame_wake_count();
9013 test_window.simulate_frame_request(RequestFrameOptions::default());
9014 window.update(cx, |_, _, _| {}).unwrap();
9015 assert_eq!(
9016 test_window.frame_wake_count(),
9017 baseline,
9018 "clean frames and non-notifying updates must not wake the frame source"
9019 );
9020
9021 window.update(cx, |_, _, cx| cx.notify()).unwrap();
9023 assert!(
9024 test_window.frame_wake_count() > baseline,
9025 "notifying a view in an idle window must wake the frame source"
9026 );
9027
9028 test_window.simulate_frame_request(RequestFrameOptions::default());
9030 let baseline = test_window.frame_wake_count();
9031 test_window.simulate_frame_request(RequestFrameOptions::default());
9032 assert_eq!(
9033 test_window.frame_wake_count(),
9034 baseline,
9035 "serving demand must return the window to idle"
9036 );
9037
9038 window
9040 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
9041 .unwrap();
9042 assert!(
9043 test_window.frame_wake_count() > baseline,
9044 "scheduling a next-frame callback in an idle window must wake the frame source"
9045 );
9046 }
9047
9048 #[gpui::test]
9053 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
9054 let window = cx.add_window(|_, _| EmptyView);
9055 let test_window = cx.test_window(window.into());
9056 test_window.simulate_frame_request(RequestFrameOptions::default());
9059
9060 let callback_ran = Rc::new(Cell::new(false));
9061 window
9062 .update(cx, {
9063 let callback_ran = callback_ran.clone();
9064 move |_, window, _| {
9065 window.on_next_frame(move |_, _| callback_ran.set(true));
9066 }
9067 })
9068 .unwrap();
9069
9070 let baseline = test_window.frame_wake_count();
9071 test_window.simulate_frame_request(RequestFrameOptions::default());
9072 assert!(
9079 test_window.frame_wake_count() > baseline || callback_ran.get(),
9080 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
9081 );
9082 }
9083
9084 #[gpui::test]
9085 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
9086 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
9087
9088 let window = cx.add_window(|_, _| EmptyView);
9089 window
9090 .update(cx, |_, window, _| {
9091 assert!(matches!(
9092 window.window_handle(),
9093 Err(HandleError::NotSupported)
9094 ));
9095 assert!(matches!(
9096 window.display_handle(),
9097 Err(HandleError::NotSupported)
9098 ));
9099 })
9100 .unwrap();
9101 }
9102
9103 #[gpui::test]
9104 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
9105 let window = cx.add_window(|_, _| EmptyView);
9106 let observed_appearance = Rc::new(Cell::new(None));
9107 let _subscription = window
9108 .update(cx, {
9109 let observed_appearance = observed_appearance.clone();
9110 move |_, window, _| {
9111 window.observe_window_appearance(move |window, _| {
9112 observed_appearance.set(Some(window.appearance()));
9113 })
9114 }
9115 })
9116 .unwrap();
9117 let test_window = cx.test_window(window.into());
9118
9119 cx.update(|_| {
9120 test_window.simulate_appearance_change(WindowAppearance::Dark);
9121 assert_eq!(observed_appearance.get(), None);
9122 });
9123 cx.run_until_parked();
9124
9125 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
9126 }
9127
9128 #[gpui::test]
9129 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
9130 let window = cx.add_window(|_, _| Empty);
9131 let test_window = cx.test_window(window.into());
9132
9133 assert!(test_window.simulate_scheduled_frame());
9134 assert!(test_window.simulate_scheduled_frame());
9135 assert!(!test_window.frame_scheduled());
9136
9137 cx.update_window(window.into(), |_, window, _| {
9138 window.active.set(true);
9139 window.on_next_frame(|_, _| {});
9140 })
9141 .unwrap();
9142 assert!(
9143 test_window.frame_scheduled(),
9144 "queuing work on a parked window must wake the render loop"
9145 );
9146
9147 assert!(test_window.simulate_scheduled_frame());
9148 assert!(
9149 test_window.frame_scheduled(),
9150 "presenting the frame must await one compositor callback"
9151 );
9152 assert!(test_window.simulate_scheduled_frame());
9153 assert!(!test_window.frame_scheduled());
9154 }
9155
9156 #[gpui::test]
9157 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
9158 let window = cx.add_window(|_, _| Empty);
9159 let test_window = cx.test_window(window.into());
9160
9161 assert!(test_window.simulate_scheduled_frame());
9162 assert!(test_window.simulate_scheduled_frame());
9163 assert!(!test_window.frame_scheduled());
9164
9165 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
9166 .unwrap();
9167
9168 assert!(
9169 test_window.frame_scheduled(),
9170 "a rendered scene awaiting presentation must wake the render loop"
9171 );
9172 }
9173
9174 #[gpui::test]
9175 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
9176 let window = cx.add_window(|_, _| Empty);
9177 let test_window = cx.test_window(window.into());
9178
9179 let callback_ran = Rc::new(Cell::new(false));
9180 cx.update_window(window.into(), |_, window, _| {
9181 window.active.set(true);
9184 let callback_ran = callback_ran.clone();
9185 window.on_next_frame(move |window, _| {
9186 window.on_next_frame(move |_, _| callback_ran.set(true));
9187 });
9188 })
9189 .unwrap();
9190
9191 assert!(test_window.simulate_scheduled_frame());
9192 assert!(!callback_ran.get());
9193 assert!(
9194 test_window.frame_scheduled(),
9195 "a callback queued mid-frame must schedule a follow-up before the loop parks"
9196 );
9197
9198 assert!(test_window.simulate_scheduled_frame());
9199 assert!(callback_ran.get());
9200 }
9201
9202 struct RootView {
9203 explicit_size: bool,
9204 child_bounds: Rc<Cell<Bounds<Pixels>>>,
9205 }
9206
9207 impl Render for RootView {
9208 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9209 let child_bounds = self.child_bounds.clone();
9210 let root = div().flex().flex_col().child(
9211 canvas(
9212 move |bounds, _, _| child_bounds.set(bounds),
9213 |_, _, _, _| {},
9214 )
9215 .size_full(),
9216 );
9217 if self.explicit_size {
9218 root.w(px(300.)).h(px(200.))
9219 } else {
9220 root
9221 }
9222 }
9223 }
9224
9225 #[test]
9226 fn auto_sized_window_root_fills_the_window() {
9227 let mut cx = TestAppContext::single();
9228 let child_bounds = Rc::new(Cell::new(Bounds::default()));
9229 let window = cx.add_window({
9230 let child_bounds = child_bounds.clone();
9231 move |_, _| RootView {
9232 explicit_size: false,
9233 child_bounds,
9234 }
9235 });
9236
9237 let viewport_size = cx
9238 .update_window(window.into(), |_, window, cx| {
9239 window.draw(cx).clear(cx);
9240 window.viewport_size()
9241 })
9242 .unwrap();
9243
9244 assert_eq!(child_bounds.get().size, viewport_size);
9245 }
9246
9247 #[test]
9248 fn explicitly_sized_window_root_keeps_its_size() {
9249 let mut cx = TestAppContext::single();
9250 let child_bounds = Rc::new(Cell::new(Bounds::default()));
9251 let window = cx.add_window({
9252 let child_bounds = child_bounds.clone();
9253 move |_, _| RootView {
9254 explicit_size: true,
9255 child_bounds,
9256 }
9257 });
9258
9259 cx.update_window(window.into(), |_, window, cx| {
9260 window.draw(cx).clear(cx);
9261 })
9262 .unwrap();
9263
9264 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
9265 }
9266
9267 struct FileDragView {
9268 path: PathBuf,
9269 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
9270 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
9271 }
9272
9273 struct FileDropExitView(Rc<Cell<usize>>);
9274
9275 impl Render for FileDropExitView {
9276 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9277 div().size_full().on_file_drop_exit({
9278 let observed_file_drop_exit = self.0.clone();
9279 move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
9280 })
9281 }
9282 }
9283
9284 impl Render for FileDragView {
9285 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9286 div()
9287 .id("file-drag")
9288 .size_full()
9289 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
9290 .external_drag_payload(|path: &PathBuf, _, _| {
9291 Some(ExternalDragPayload::Files(FileDragPaths::new([(
9292 path.clone(),
9293 true,
9294 )])))
9295 })
9296 .on_drag_move({
9297 let observed_drag_moves = self.observed_drag_moves.clone();
9298 move |event: &DragMoveEvent<PathBuf>, _, _| {
9299 observed_drag_moves.borrow_mut().push(event.event.position);
9300 }
9301 })
9302 .on_drop({
9303 let observed_drops = self.observed_drops.clone();
9304 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
9305 })
9306 }
9307 }
9308
9309 #[gpui::test]
9310 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
9311 struct Drag {
9312 window: AnyWindowHandle,
9313 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
9314 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
9315 }
9316
9317 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
9318 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
9319 let observed_drops = Rc::new(RefCell::new(Vec::new()));
9320 let window: AnyWindowHandle = cx
9321 .add_window({
9322 let observed_drag_moves = observed_drag_moves.clone();
9323 let observed_drops = observed_drops.clone();
9324 move |_, _| FileDragView {
9325 path,
9326 observed_drag_moves,
9327 observed_drops,
9328 }
9329 })
9330 .into();
9331 cx.test_window(window)
9332 .set_start_external_drag_result(platform_result);
9333
9334 let update_result = cx.update_window(window, |_, window, cx| {
9335 window.draw(cx).clear(cx);
9336 window.dispatch_event(
9337 MouseDownEvent {
9338 position: point(px(10.), px(10.)),
9339 button: MouseButton::Left,
9340 modifiers: Default::default(),
9341 click_count: 1,
9342 first_mouse: false,
9343 }
9344 .to_platform_input(),
9345 cx,
9346 );
9347 window.dispatch_event(
9348 MouseMoveEvent {
9349 position: point(px(20.), px(20.)),
9350 pressed_button: Some(MouseButton::Left),
9351 modifiers: Default::default(),
9352 }
9353 .to_platform_input(),
9354 cx,
9355 );
9356 assert!(cx.active_drag.is_some());
9357 });
9358 assert!(
9359 update_result.is_ok(),
9360 "failed to start drag: {update_result:?}"
9361 );
9362
9363 assert!(cx.test_window(window).external_drag_files().is_empty());
9364 Drag {
9365 window,
9366 observed_drag_moves,
9367 observed_drops,
9368 }
9369 }
9370
9371 let successful_path = PathBuf::from("/tmp/successful-drag");
9372 let successful = start_drag(cx, successful_path.clone(), true);
9373 let outside_position = point(px(-1.), px(20.));
9374 let update_result = cx.update_window(successful.window, |_, window, cx| {
9375 window.dispatch_event(
9376 MouseMoveEvent {
9377 position: outside_position,
9378 pressed_button: Some(MouseButton::Left),
9379 modifiers: Default::default(),
9380 }
9381 .to_platform_input(),
9382 cx,
9383 );
9384 assert!(cx.active_drag.is_none());
9385 });
9386 assert!(
9387 update_result.is_ok(),
9388 "failed to promote drag: {update_result:?}"
9389 );
9390 assert_eq!(
9391 cx.test_window(successful.window).external_drag_files(),
9392 [(successful_path.clone(), true)]
9393 );
9394 assert_eq!(
9397 successful.observed_drag_moves.borrow().last(),
9398 Some(&outside_position)
9399 );
9400
9401 let first_destination_exit_count = Rc::new(Cell::new(0));
9402 let first_destination: AnyWindowHandle = cx
9403 .add_window({
9404 let first_destination_exit_count = first_destination_exit_count.clone();
9405 move |_, _| FileDropExitView(first_destination_exit_count)
9406 })
9407 .into();
9408 let second_destination_exit_count = Rc::new(Cell::new(0));
9409 let second_destination: AnyWindowHandle = cx
9410 .add_window({
9411 let second_destination_exit_count = second_destination_exit_count.clone();
9412 move |_, _| FileDropExitView(second_destination_exit_count)
9413 })
9414 .into();
9415 let reentry_position = point(px(30.), px(30.));
9416 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
9417 let update_result = cx.update_window(first_destination, |_, window, cx| {
9418 window.draw(cx).clear(cx);
9419 window.dispatch_event(
9420 FileDropEvent::Entered {
9421 position: reentry_position,
9422 paths: external_paths(),
9423 }
9424 .to_platform_input(),
9425 cx,
9426 );
9427 assert!(
9428 cx.active_drag
9429 .as_ref()
9430 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9431 );
9432 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9433 assert!(cx.active_drag.is_none());
9434 assert_eq!(first_destination_exit_count.get(), 1);
9435 assert_eq!(second_destination_exit_count.get(), 0);
9436 });
9437 assert!(
9438 update_result.is_ok(),
9439 "failed to handle drag in first destination window: {update_result:?}"
9440 );
9441
9442 let update_result = cx.update_window(second_destination, |_, window, cx| {
9443 window.draw(cx).clear(cx);
9444 window.dispatch_event(
9445 PlatformInput::KeyDown(KeyDownEvent {
9446 keystroke: Keystroke::parse("down").expect("valid keystroke"),
9447 is_held: false,
9448 prefer_character_input: false,
9449 }),
9450 cx,
9451 );
9452 window.dispatch_event(
9453 FileDropEvent::Entered {
9454 position: reentry_position,
9455 paths: external_paths(),
9456 }
9457 .to_platform_input(),
9458 cx,
9459 );
9460 assert!(
9461 cx.active_drag
9462 .as_ref()
9463 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9464 );
9465 assert_eq!(first_destination_exit_count.get(), 1);
9466 assert_eq!(second_destination_exit_count.get(), 0);
9467
9468 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9469 assert!(cx.active_drag.is_none());
9470 assert_eq!(first_destination_exit_count.get(), 1);
9471 assert_eq!(second_destination_exit_count.get(), 1);
9472 });
9473 assert!(
9474 update_result.is_ok(),
9475 "failed to handle drag in second destination window: {update_result:?}"
9476 );
9477
9478 let update_result = cx.update_window(successful.window, |_, window, cx| {
9479 window.dispatch_event(
9480 FileDropEvent::Entered {
9481 position: reentry_position,
9482 paths: external_paths(),
9483 }
9484 .to_platform_input(),
9485 cx,
9486 );
9487 assert!(
9488 cx.active_drag
9489 .as_ref()
9490 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9491 );
9492 assert_eq!(
9493 successful.observed_drag_moves.borrow().last(),
9494 Some(&reentry_position)
9495 );
9496
9497 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9498 assert!(cx.active_drag.is_none());
9499
9500 window.dispatch_event(
9501 FileDropEvent::Entered {
9502 position: reentry_position,
9503 paths: external_paths(),
9504 }
9505 .to_platform_input(),
9506 cx,
9507 );
9508 assert!(
9509 cx.active_drag
9510 .as_ref()
9511 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9512 );
9513
9514 window.dispatch_event(
9515 FileDropEvent::Submit {
9516 position: reentry_position,
9517 }
9518 .to_platform_input(),
9519 cx,
9520 );
9521 assert_eq!(
9522 successful.observed_drops.borrow().as_slice(),
9523 std::slice::from_ref(&successful_path)
9524 );
9525 assert!(cx.active_drag.is_none());
9526
9527 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9528 assert!(cx.active_drag.is_none());
9529 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
9530 assert!(cx.active_drag.is_none());
9531
9532 window.dispatch_event(
9533 FileDropEvent::Entered {
9534 position: reentry_position,
9535 paths: external_paths(),
9536 }
9537 .to_platform_input(),
9538 cx,
9539 );
9540 assert!(
9541 cx.active_drag
9542 .as_ref()
9543 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9544 );
9545 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9546 });
9547 assert!(
9548 update_result.is_ok(),
9549 "failed to restore drag in source window: {update_result:?}"
9550 );
9551
9552 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
9553 let cancelled = start_drag(cx, cancelled_path.clone(), true);
9554 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
9555 window.dispatch_event(
9556 MouseMoveEvent {
9557 position: outside_position,
9558 pressed_button: Some(MouseButton::Left),
9559 modifiers: Default::default(),
9560 }
9561 .to_platform_input(),
9562 cx,
9563 );
9564 assert!(cx.active_drag.is_none());
9565
9566 window.dispatch_event(
9567 FileDropEvent::Entered {
9568 position: reentry_position,
9569 paths: ExternalPaths([cancelled_path].into_iter().collect()),
9570 }
9571 .to_platform_input(),
9572 cx,
9573 );
9574 assert!(
9575 cx.active_drag
9576 .as_ref()
9577 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9578 );
9579 assert!(cx.stop_active_drag(window));
9580 assert!(cx.active_drag.is_none());
9581 });
9582 assert!(
9583 update_result.is_ok(),
9584 "failed to cancel restored drag: {update_result:?}"
9585 );
9586 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
9587
9588 let removed_path = PathBuf::from("/tmp/removed-window-drag");
9589 let removed = start_drag(cx, removed_path, true);
9590 let removed_window_id = removed.window.window_id();
9591 let update_result = cx.update_window(removed.window, |_, window, cx| {
9592 window.dispatch_event(
9593 MouseMoveEvent {
9594 position: outside_position,
9595 pressed_button: Some(MouseButton::Left),
9596 modifiers: Default::default(),
9597 }
9598 .to_platform_input(),
9599 cx,
9600 );
9601 assert!(cx.active_drag.is_none());
9602 window.remove_window();
9603 });
9604 assert!(
9605 update_result.is_ok(),
9606 "failed to remove drag source window: {update_result:?}"
9607 );
9608 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
9609
9610 let failed_path = PathBuf::from("/tmp/failed-drag");
9611 let failed = start_drag(cx, failed_path.clone(), false);
9612 let update_result = cx.update_window(failed.window, |_, window, cx| {
9613 for x_position in [-1., -2.] {
9614 window.dispatch_event(
9615 MouseMoveEvent {
9616 position: point(px(x_position), px(20.)),
9617 pressed_button: Some(MouseButton::Left),
9618 modifiers: Default::default(),
9619 }
9620 .to_platform_input(),
9621 cx,
9622 );
9623 }
9624 assert!(cx.active_drag.is_some());
9625 });
9626 assert!(
9627 update_result.is_ok(),
9628 "failed to retain drag after platform failure: {update_result:?}"
9629 );
9630 assert_eq!(
9631 cx.test_window(failed.window).external_drag_files(),
9632 [(failed_path, true)]
9633 );
9634 }
9635
9636 struct FocusForwarder {
9637 a: FocusHandle,
9638 b: FocusHandle,
9639 }
9640
9641 impl Render for FocusForwarder {
9642 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9643 div()
9644 .size_full()
9645 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
9646 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
9647 }
9648 }
9649
9650 #[gpui::test]
9654 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
9655 let b_focus_count = Rc::new(Cell::new(0));
9656 let window = cx.add_window({
9657 let b_focus_count = b_focus_count.clone();
9658 move |window, cx| {
9659 let a = cx.focus_handle();
9660 let b = cx.focus_handle();
9661 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
9662 let b = this.b.clone();
9663 window.focus(&b, cx);
9664 })
9665 .detach();
9666 cx.on_focus(&b, window, move |_, _, _| {
9667 b_focus_count.set(b_focus_count.get() + 1);
9668 })
9669 .detach();
9670 FocusForwarder { a, b }
9671 }
9672 });
9673
9674 window
9675 .update(cx, |_, window, _| window.activate_window())
9676 .unwrap();
9677 cx.executor().run_until_parked();
9678
9679 window
9680 .update(cx, |this, window, cx| {
9681 let a = this.a.clone();
9682 window.focus(&a, cx);
9683 })
9684 .unwrap();
9685 cx.executor().run_until_parked();
9686
9687 window
9688 .update(cx, |this, window, _| {
9689 assert!(this.b.is_focused(window));
9690 })
9691 .unwrap();
9692 assert_eq!(b_focus_count.get(), 1);
9693 }
9694
9695 #[gpui::test]
9696 fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
9697 let events = Rc::new(RefCell::new(Vec::new()));
9698 let window = cx.add_window({
9699 let events = events.clone();
9700 move |_, _| TouchDragListener { events }
9701 });
9702 let touch = TouchId(1);
9703
9704 dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
9705 dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
9706 dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
9707
9708 assert_eq!(
9709 events.borrow().as_slice(),
9710 [
9711 (TouchPhase::Started, px(10.)),
9712 (TouchPhase::Moved, px(30.)),
9713 (TouchPhase::Ended, px(40.)),
9714 ]
9715 );
9716 }
9717
9718 #[gpui::test]
9719 fn back_gesture_is_claimed_by_the_innermost_listener(cx: &mut TestAppContext) {
9720 let claims = Rc::new(RefCell::new(Vec::new()));
9721 let window = cx.add_window({
9722 let claims = claims.clone();
9723 move |_, _| BackListeners { claims }
9724 });
9725 let dispatch_back = |cx: &mut TestAppContext, x: f32| {
9726 window
9727 .update(cx, |_, window, cx| {
9728 window
9729 .dispatch_event(
9730 BackGestureEvent {
9731 phase: BackGesturePhase::Started,
9732 start_position: point(px(x), px(10.)),
9733 progress: 0.,
9734 }
9735 .to_platform_input(),
9736 cx,
9737 )
9738 .default_prevented
9739 })
9740 .unwrap()
9741 };
9742 assert!(dispatch_back(cx, 10.));
9743 assert!(dispatch_back(cx, 80.));
9744 assert!(!dispatch_back(cx, 150.));
9745 assert_eq!(claims.borrow().as_slice(), ["inner", "outer"]);
9746 }
9747
9748 struct BackListeners {
9749 claims: Rc<RefCell<Vec<&'static str>>>,
9750 }
9751
9752 impl Render for BackListeners {
9753 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9754 let claim = |name: &'static str| {
9755 let claims = self.claims.clone();
9756 move |_: &BackGestureEvent, _: &mut Window, _: &mut crate::App| {
9757 claims.borrow_mut().push(name)
9758 }
9759 };
9760 div().size_full().child(
9761 div()
9762 .w(px(100.))
9763 .h_full()
9764 .on_back_gesture(claim("outer"))
9765 .child(div().w(px(50.)).h_full().on_back_gesture(claim("inner"))),
9766 )
9767 }
9768 }
9769
9770 struct TouchDragListener {
9771 events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
9772 }
9773
9774 impl Render for TouchDragListener {
9775 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9776 let events = self.events.clone();
9777 canvas(
9778 |_, _, _| {},
9779 move |_, _, window, _| {
9780 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
9781 if phase != DispatchPhase::Bubble {
9782 return;
9783 }
9784 events.borrow_mut().push((event.phase, event.position.x));
9785 if event.phase == TouchPhase::Started {
9786 window.prevent_default();
9787 }
9788 });
9789 },
9790 )
9791 }
9792 }
9793
9794 #[gpui::test]
9795 fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
9796 for response in [
9797 LongPressResponse::PreventDefault,
9798 LongPressResponse::StopPropagation,
9799 LongPressResponse::None,
9800 ] {
9801 let phases = Rc::new(RefCell::new(Vec::new()));
9802 let window = cx.add_window({
9803 let phases = phases.clone();
9804 move |_, _| LongPressListener { phases, response }
9805 });
9806 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9807 cx.executor().advance_clock(Duration::from_millis(501));
9808 cx.executor().run_until_parked();
9809 window
9810 .update(cx, |_, window, _| {
9811 assert_eq!(
9812 window.long_press_capture.is_some(),
9813 response == LongPressResponse::PreventDefault
9814 );
9815 })
9816 .unwrap();
9817 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
9818 dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
9819 window
9820 .update(cx, |_, window, _| {
9821 assert!(window.long_press_capture.is_none());
9822 })
9823 .unwrap();
9824
9825 let phases = phases.borrow();
9826 if response == LongPressResponse::PreventDefault {
9827 assert_eq!(
9828 phases.as_slice(),
9829 [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
9830 );
9831 } else {
9832 assert_eq!(phases.as_slice(), [TouchPhase::Started]);
9833 }
9834 }
9835 }
9836
9837 #[gpui::test]
9838 fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
9839 let phases = Rc::new(RefCell::new(Vec::new()));
9840 let window = cx.add_window({
9841 let phases = phases.clone();
9842 move |_, _| LongPressListener {
9843 phases,
9844 response: LongPressResponse::None,
9845 }
9846 });
9847 window
9848 .update(cx, |_, window, _| {
9849 window.prevent_default();
9850 })
9851 .unwrap();
9852
9853 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9854 cx.executor().advance_clock(Duration::from_millis(501));
9855 cx.executor().run_until_parked();
9856 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
9857
9858 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
9859 }
9860
9861 #[gpui::test]
9862 fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
9863 for (phase, position) in [
9864 (TouchPhase::Ended, 0.),
9865 (TouchPhase::Cancelled, 0.),
9866 (TouchPhase::Moved, 20.),
9867 ] {
9868 let phases = Rc::new(RefCell::new(Vec::new()));
9869 let window = cx.add_window({
9870 let phases = phases.clone();
9871 move |_, _| LongPressListener {
9872 phases,
9873 response: LongPressResponse::PreventDefault,
9874 }
9875 });
9876 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9877 dispatch_touch(window, cx, TouchId(1), phase, position);
9878 cx.executor().advance_clock(Duration::from_millis(501));
9879 cx.executor().run_until_parked();
9880
9881 assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
9882 }
9883 }
9884
9885 #[gpui::test]
9886 fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
9887 let phases = Rc::new(RefCell::new(Vec::new()));
9888 let window = cx.add_window({
9889 let phases = phases.clone();
9890 move |_, _| LongPressListener {
9891 phases,
9892 response: LongPressResponse::PreventDefault,
9893 }
9894 });
9895 let first_touch = TouchId(1);
9896 dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
9897 cx.executor().advance_clock(Duration::from_millis(250));
9898 dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
9899 dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
9900
9901 cx.executor().advance_clock(Duration::from_millis(251));
9902 cx.executor().run_until_parked();
9903 assert!(phases.borrow().is_empty());
9904
9905 cx.executor().advance_clock(Duration::from_millis(250));
9906 cx.executor().run_until_parked();
9907 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
9908 }
9909
9910 #[gpui::test]
9911 fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
9912 test_underline_paint_at_scales(cx, |window| {
9913 let (numerator, denominator) = match window.scale_factor() {
9914 1.0 => (1, 1),
9915 1.25 => (5, 4),
9916 1.5 => (3, 2),
9917 2.0 => (2, 1),
9918 3.0 => (3, 1),
9919 scale => panic!("unexpected scale {scale}"),
9920 };
9921 let snap = |quarters: i32| {
9922 let scaled = quarters * numerator;
9923 let divisor = 4 * denominator;
9924 let rounded =
9925 scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
9926 ScaledPixels((scaled.signum() * rounded) as f32)
9927 };
9928 let stroke = |quarters| {
9929 if quarters == 0 {
9930 ScaledPixels(0.)
9931 } else {
9932 snap(quarters).max(ScaledPixels(1.))
9933 }
9934 };
9935
9936 for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
9937 for width in [0, 1, 3, 84] {
9938 for thickness in [0, 1, 4, 7] {
9939 for wavy in [false, true] {
9940 let style = UnderlineStyle {
9941 thickness: px(thickness as f32 / 4.),
9942 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
9943 wavy,
9944 };
9945 let bounds = Bounds::new(
9946 point(snap(origin), snap(-origin)),
9947 size(
9948 stroke(width),
9949 stroke(thickness) * if wavy { 3. } else { 1. },
9950 ),
9951 );
9952 let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
9953 let width = px(width as f32 / 4.);
9954 assert_eq!(window.underline_bounds(origin, width, &style), bounds);
9955 let original = paint_test_underlines(window, |window| {
9956 window.paint_underline(origin, width, &style);
9957 })
9958 .to_vec();
9959 assert_eq!(original.len(), usize::from(!bounds.is_empty()));
9960 if let Some(underline) = original.first() {
9961 assert_eq!(underline.bounds, bounds);
9962 assert_eq!(underline.thickness, stroke(thickness));
9963 assert_eq!(underline.wavy, wavy.into());
9964 assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
9965 }
9966
9967 let underlines = paint_test_underlines(window, |window| {
9968 window.paint_underline_with_exclusions(origin, width, &style, &[]);
9969 });
9970 assert_eq!(underlines.len(), original.len());
9971 for (actual, original) in underlines.iter().zip(&original) {
9972 assert_same_underline_geometry(actual, original);
9973 assert_eq!(actual.content_mask, original.content_mask);
9974 }
9975
9976 let left = bounds.left().0 as i32;
9977 let right = bounds.right().0 as i32;
9978 let exclusions = [
9979 (15, 25),
9980 (3, 7),
9981 (5, 10),
9982 (10, 12),
9983 (0, 0),
9984 (4, 2),
9985 (-50, -1),
9986 (70, 100),
9987 ]
9988 .map(|(start, end)| {
9989 ScaledPixels((left + start) as f32)
9990 ..ScaledPixels((left + end) as f32)
9991 });
9992 let underlines = paint_test_underlines(window, |window| {
9993 window.paint_underline_with_exclusions(
9994 origin,
9995 width,
9996 &style,
9997 &exclusions,
9998 );
9999 });
10000 let expected = (left..right)
10001 .filter(|column| {
10002 !bounds.is_empty()
10003 && !exclusions.iter().any(|span| {
10004 span.contains(&ScaledPixels(*column as f32))
10005 })
10006 })
10007 .collect::<Vec<_>>();
10008 assert_eq!(underline_device_columns(underlines), expected);
10009 for underline in underlines {
10010 assert_same_underline_geometry(underline, &original[0]);
10011 }
10012 }
10013 }
10014 }
10015 }
10016 });
10017 }
10018
10019 #[gpui::test]
10020 fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
10021 test_underline_paint_at_scales(cx, |window| {
10022 if window.scale_factor() != 2.0 {
10023 return;
10024 }
10025 let style = UnderlineStyle {
10026 thickness: px(1.),
10027 color: None,
10028 wavy: true,
10029 };
10030 let origin = point(px(2.888_183_8), px(15.357_917));
10031 let width = px(23.848_145) - origin.x;
10032 let original = paint_test_underlines(window, |window| {
10033 window.paint_underline(origin, width, &style);
10034 })[0];
10035 assert_eq!(original.bounds.left(), ScaledPixels(6.));
10036 assert_eq!(original.bounds.right(), ScaledPixels(48.));
10037 let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
10038 assert_eq!(point_bounds.left(), ScaledPixels(6.));
10039 assert_eq!(point_bounds.right(), ScaledPixels(28.));
10040
10041 let underlines = paint_test_underlines(window, |window| {
10042 window.paint_underline_with_exclusions(
10043 origin,
10044 width,
10045 &style,
10046 &[point_bounds.left()..point_bounds.right()],
10047 );
10048 });
10049 assert_eq!(underlines.len(), 1);
10050 assert_same_underline_geometry(&underlines[0], &original);
10051 assert_eq!(
10052 underline_device_columns(underlines),
10053 (28..48).collect::<Vec<_>>()
10054 );
10055 });
10056 }
10057
10058 #[gpui::test]
10059 fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
10060 test_underline_paint_at_scales(cx, |window| {
10061 let scale = window.scale_factor();
10062 let original_mask = window.content_mask();
10063 let original_opacity = window.element_opacity();
10064 let mask = ContentMask {
10065 bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
10066 };
10067 let style = UnderlineStyle {
10068 thickness: px(2.),
10069 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
10070 wavy: true,
10071 };
10072 let origin = point(px(-1.25), px(9.25));
10073 let width = px(24.);
10074 window.with_content_mask(Some(mask), |window| {
10075 window.with_element_opacity(Some(0.5), |window| {
10076 window.with_element_opacity(Some(0.5), |window| {
10077 let original = paint_test_underlines(window, |window| {
10078 window.paint_underline(origin, width, &style);
10079 })[0];
10080 assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
10081 let underlines = paint_test_underlines(window, |window| {
10082 window.paint_underline_with_exclusions(
10083 origin,
10084 width,
10085 &style,
10086 &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
10087 );
10088 });
10089 assert_eq!(underlines.len(), 2);
10090 let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
10091 |(left, right)| {
10092 Bounds::from_corners(
10093 point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
10094 point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
10095 )
10096 },
10097 );
10098 assert_eq!(
10099 underlines
10100 .iter()
10101 .map(|underline| underline.content_mask.bounds)
10102 .collect::<Vec<_>>(),
10103 expected
10104 );
10105 for underline in underlines {
10106 assert_same_underline_geometry(underline, &original);
10107 }
10108 });
10109 });
10110 });
10111 assert_eq!(window.content_mask(), original_mask);
10112 assert_eq!(window.element_opacity(), original_opacity);
10113 });
10114 }
10115
10116 #[gpui::test]
10117 fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
10118 test_underline_paint_at_scales(cx, |window| {
10119 let style = UnderlineStyle {
10120 thickness: px(1.),
10121 color: None,
10122 wavy: true,
10123 };
10124 let origin = point(px(-4.), px(-1.));
10125 let width = px(8.);
10126 let left = (-4. * window.scale_factor()) as i32;
10127 let right = (4. * window.scale_factor()) as i32;
10128 let endpoints = [-16, -8, -1, 0, 1, 8, 16];
10129 for first_start in endpoints {
10130 for first_end in endpoints {
10131 for second_start in endpoints {
10132 for second_end in endpoints {
10133 let exclusions = [first_start..first_end, second_start..second_end];
10134 let expected = (left..right)
10135 .filter(|column| {
10136 !exclusions.iter().any(|span| span.contains(column))
10137 })
10138 .collect::<Vec<_>>();
10139 let exclusions = exclusions.map(|span| {
10140 ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
10141 });
10142 let underlines = paint_test_underlines(window, |window| {
10143 window.paint_underline_with_exclusions(
10144 origin,
10145 width,
10146 &style,
10147 &exclusions,
10148 );
10149 });
10150 assert_eq!(
10151 underline_device_columns(underlines),
10152 expected,
10153 "{exclusions:?}"
10154 );
10155 }
10156 }
10157 }
10158 }
10159 });
10160 }
10161
10162 #[derive(Clone, Copy, PartialEq)]
10163 enum LongPressResponse {
10164 PreventDefault,
10165 StopPropagation,
10166 None,
10167 }
10168
10169 struct LongPressListener {
10170 phases: Rc<RefCell<Vec<TouchPhase>>>,
10171 response: LongPressResponse,
10172 }
10173
10174 impl Render for LongPressListener {
10175 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
10176 let entity = cx.entity();
10177 let phases = self.phases.clone();
10178 let response = self.response;
10179 canvas(
10180 |_, _, _| {},
10181 move |_, _, window, _| {
10182 window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
10183 if phase != DispatchPhase::Bubble {
10184 return;
10185 }
10186 phases.borrow_mut().push(event.phase);
10187 match response {
10188 LongPressResponse::PreventDefault => {
10189 window.capture_long_press(&entity);
10190 window.prevent_default();
10191 }
10192 LongPressResponse::StopPropagation => cx.stop_propagation(),
10193 LongPressResponse::None => {}
10194 }
10195 });
10196 },
10197 )
10198 }
10199 }
10200
10201 struct UnderlineTestView(Rc<dyn Fn(&mut Window)>);
10202
10203 impl Render for UnderlineTestView {
10204 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10205 let paint = self.0.clone();
10206 canvas(
10207 |_, _, _| {},
10208 move |_, _, window, _| {
10209 window.content_mask_stack.push(ContentMask {
10210 bounds: Bounds::from_corners(
10211 point(px(-1000.), px(-1000.)),
10212 point(px(1000.), px(1000.)),
10213 ),
10214 });
10215 paint(window);
10216 window.content_mask_stack.pop();
10217 },
10218 )
10219 .size_full()
10220 }
10221 }
10222
10223 fn test_underline_paint_at_scales(
10224 cx: &mut TestAppContext,
10225 paint: impl Fn(&mut Window) + 'static,
10226 ) {
10227 let window = cx.add_window(move |_, _| UnderlineTestView(Rc::new(paint)));
10228 for scale in [1., 1.25, 1.5, 2., 3.] {
10229 cx.simulate_window_scale_factor_change(window.into(), scale);
10230 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
10231 .unwrap();
10232 }
10233 }
10234
10235 fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
10236 window.next_frame.scene.clear();
10237 paint(window);
10238 &window.next_frame.scene.underlines
10239 }
10240
10241 fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
10242 assert_eq!(actual.bounds, expected.bounds);
10243 assert_eq!(actual.thickness, expected.thickness);
10244 assert_eq!(actual.wavy, expected.wavy);
10245 assert_eq!(actual.color, expected.color);
10246 assert_eq!(actual.pad, expected.pad);
10247 }
10248
10249 fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
10250 underlines
10251 .iter()
10252 .flat_map(|underline| {
10253 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
10254 bounds.left().0 as i32..bounds.right().0 as i32
10255 })
10256 .collect()
10257 }
10258
10259 actions!(window_test, [StandaloneModifierAction]);
10260
10261 struct StandaloneModifierView {
10262 focus_handle: FocusHandle,
10263 action_count: usize,
10264 }
10265
10266 impl Render for StandaloneModifierView {
10267 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
10268 div()
10269 .key_context("StandaloneModifier")
10270 .track_focus(&self.focus_handle)
10271 .on_action(cx.listener(|this, _: &StandaloneModifierAction, _, _| {
10272 this.action_count += 1;
10273 }))
10274 }
10275 }
10276
10277 #[gpui::test]
10278 fn test_standalone_modifier_sequence_timeout_and_recovery(cx: &mut TestAppContext) {
10279 use crate::{KeyBinding, Modifiers};
10280
10281 cx.update(|cx| {
10282 cx.bind_keys([KeyBinding::new(
10283 "shift shift",
10284 StandaloneModifierAction,
10285 Some("StandaloneModifier"),
10286 )]);
10287 });
10288 let (view, cx) = cx.add_window_view(|window, cx| {
10289 let focus_handle = cx.focus_handle();
10290 window.focus(&focus_handle, cx);
10291 StandaloneModifierView {
10292 focus_handle,
10293 action_count: 0,
10294 }
10295 });
10296 let shift = Modifiers {
10297 shift: true,
10298 ..Modifiers::default()
10299 };
10300 cx.simulate_modifiers_change(shift);
10301 cx.simulate_modifiers_change(Modifiers::default());
10302 cx.update(|window, _| {
10303 assert_eq!(
10304 window.pending_input_keystrokes(),
10305 Some([Keystroke::parse("shift").expect("valid keystroke")].as_slice())
10306 );
10307 });
10308 cx.background_executor.advance_clock(Duration::from_secs(2));
10309 cx.run_until_parked();
10310 cx.update(|window, cx| {
10311 assert!(!window.has_pending_keystrokes());
10312 assert_eq!(view.read(cx).action_count, 0);
10313 });
10314
10315 cx.simulate_modifiers_change(shift);
10316 cx.simulate_modifiers_change(Modifiers::default());
10317 cx.update(|window, cx| {
10318 assert!(window.has_pending_keystrokes());
10319 assert_eq!(view.read(cx).action_count, 0);
10320 });
10321
10322 cx.simulate_modifiers_change(shift);
10323 cx.simulate_modifiers_change(Modifiers::default());
10324 cx.update(|window, cx| {
10325 assert!(!window.has_pending_keystrokes());
10326 assert_eq!(view.read(cx).action_count, 1);
10327 });
10328 }
10329
10330 #[gpui::test]
10331 fn test_standalone_modifier_sequence_dispatches_before_timeout(cx: &mut TestAppContext) {
10332 use crate::{KeyBinding, Modifiers};
10333
10334 cx.update(|cx| {
10335 cx.bind_keys([KeyBinding::new(
10336 "shift shift",
10337 StandaloneModifierAction,
10338 Some("StandaloneModifier"),
10339 )]);
10340 });
10341 let (view, cx) = cx.add_window_view(|window, cx| {
10342 let focus_handle = cx.focus_handle();
10343 window.focus(&focus_handle, cx);
10344 StandaloneModifierView {
10345 focus_handle,
10346 action_count: 0,
10347 }
10348 });
10349 let shift = Modifiers {
10350 shift: true,
10351 ..Modifiers::default()
10352 };
10353 cx.simulate_modifiers_change(shift);
10354 cx.simulate_modifiers_change(Modifiers::default());
10355 cx.background_executor
10356 .advance_clock(Duration::from_millis(500));
10357 cx.update(|window, cx| {
10358 assert!(window.has_pending_keystrokes());
10359 assert_eq!(view.read(cx).action_count, 0);
10360 });
10361 cx.simulate_modifiers_change(shift);
10362 cx.simulate_modifiers_change(Modifiers::default());
10363 cx.update(|window, cx| {
10364 assert!(!window.has_pending_keystrokes());
10365 assert_eq!(view.read(cx).action_count, 1);
10366 });
10367 cx.background_executor.advance_clock(Duration::from_secs(2));
10368 cx.run_until_parked();
10369 cx.update(|window, cx| {
10370 assert!(!window.has_pending_keystrokes());
10371 assert_eq!(view.read(cx).action_count, 1);
10372 });
10373 }
10374
10375 fn dispatch_touch<T: 'static>(
10376 window: crate::WindowHandle<T>,
10377 cx: &mut TestAppContext,
10378 id: TouchId,
10379 phase: TouchPhase,
10380 x: f32,
10381 ) {
10382 window
10383 .update(cx, |_, window, cx| {
10384 window.dispatch_event(
10385 TouchEvent {
10386 id,
10387 phase,
10388 position: point(px(x), px(0.)),
10389 predicted_position: None,
10390 force: None,
10391 }
10392 .to_platform_input(),
10393 cx,
10394 );
10395 })
10396 .unwrap();
10397 }
10398
10399 #[gpui::test]
10400 fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
10401 struct Child {
10402 renders: usize,
10403 }
10404
10405 impl Render for Child {
10406 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10407 self.renders += 1;
10408 div().size_full().bg(crate::rgb(0xff0000))
10409 }
10410 }
10411
10412 struct Root {
10413 opacity: f32,
10414 width: Pixels,
10415 child: crate::Entity<Child>,
10416 }
10417
10418 impl Render for Root {
10419 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10420 div()
10421 .w(self.width)
10422 .h(px(200.))
10423 .opacity(self.opacity)
10424 .hover(|style| style.opacity(1.))
10425 .child(
10426 self.child
10427 .clone()
10428 .cached(crate::StyleRefinement::default().size(px(100.))),
10429 )
10430 }
10431 }
10432
10433 fn update_and_draw(
10436 window: crate::WindowHandle<Root>,
10437 child: &crate::Entity<Child>,
10438 cx: &mut TestAppContext,
10439 update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
10440 ) -> (f32, usize) {
10441 window
10442 .update(cx, |root, window, cx| {
10443 update(root, window, cx);
10444 cx.notify();
10445 })
10446 .expect("update root");
10447 for _ in 0..3 {
10448 let (alpha, renders, requested_frames) = cx
10449 .update_window(window.into(), |_, window, cx| {
10450 window.draw(cx).clear(cx);
10451 let quads = &window.rendered_frame.scene.quads;
10452 assert_eq!(quads.len(), 1);
10453 let alpha = quads.first().expect("child quad").background.solid.a;
10454 (
10455 alpha,
10456 child.read(cx).renders,
10457 window.simulate_next_frame(cx),
10458 )
10459 })
10460 .expect("draw window");
10461 if requested_frames == 0 {
10462 return (alpha, renders);
10463 }
10464 }
10465 panic!("cached child kept requesting frames");
10466 }
10467
10468 let child = cx.new(|_| Child { renders: 0 });
10469 let window = cx.add_window(|_, _| Root {
10470 opacity: 1.,
10471 width: px(200.),
10472 child: child.clone(),
10473 });
10474 let outside = point(px(500.), px(500.));
10475 let inside = point(px(50.), px(50.));
10476 let beside = point(px(250.), px(50.));
10477
10478 let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
10480 window.simulate_mouse_move(outside, cx)
10481 };
10482 assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
10483 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
10484 let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
10485 assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
10486 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
10487
10488 let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
10490 window.simulate_mouse_move(inside, cx)
10491 };
10492 assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
10493 let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
10494 window.simulate_mouse_move(beside, cx)
10495 };
10496 assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
10497
10498 let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
10501 assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
10502 }
10503
10504 #[gpui::test]
10505 fn test_drag_cursor_applies_before_next_paint(cx: &mut TestAppContext) {
10506 struct ResizeHandle;
10507
10508 impl Render for ResizeHandle {
10509 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
10510 div().size_full().cursor_text().child(
10511 div()
10512 .id("resize-handle")
10513 .w(px(4.))
10514 .h_full()
10515 .cursor_col_resize()
10516 .on_drag((), |_, _, _, cx| cx.new(|_| Empty)),
10517 )
10518 }
10519 }
10520
10521 let window = cx.add_window(|_, _| ResizeHandle);
10522 let handle_position = point(px(1.), px(10.));
10523 let drag_position = point(px(20.), px(10.));
10524 let cursor_observer = cx.clone();
10525
10526 let update_result = cx.update_window(window.into(), |_, window, cx| {
10527 window.hovered.set(true);
10528 window.active.set(true);
10529 window.draw(cx).clear(cx);
10530 window.dispatch_event(
10531 MouseMoveEvent {
10532 position: handle_position,
10533 ..Default::default()
10534 }
10535 .to_platform_input(),
10536 cx,
10537 );
10538 window.dispatch_event(
10539 MouseDownEvent {
10540 position: handle_position,
10541 button: MouseButton::Left,
10542 ..Default::default()
10543 }
10544 .to_platform_input(),
10545 cx,
10546 );
10547 window.dispatch_event(
10548 MouseMoveEvent {
10549 position: drag_position,
10550 pressed_button: Some(MouseButton::Left),
10551 ..Default::default()
10552 }
10553 .to_platform_input(),
10554 cx,
10555 );
10556 assert!(cx.has_active_drag());
10557 assert_eq!(
10559 cursor_observer.test_platform().cursor_style(),
10560 CursorStyle::ResizeColumn
10561 );
10562
10563 window.draw(cx).clear(cx);
10564 window.dispatch_event(
10565 MouseUpEvent {
10566 position: drag_position,
10567 button: MouseButton::Left,
10568 ..Default::default()
10569 }
10570 .to_platform_input(),
10571 cx,
10572 );
10573 window.draw(cx).clear(cx);
10574 });
10575 assert!(
10576 update_result.is_ok(),
10577 "failed to run drag: {update_result:?}"
10578 );
10579 assert_eq!(
10580 cursor_observer.test_platform().cursor_style(),
10581 CursorStyle::IBeam
10582 );
10583 }
10584}
10585
10586#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
10587mod inspector_tests {
10588 use super::*;
10589 use crate::{
10590 DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
10591 };
10592
10593 #[gpui::test]
10594 fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
10595 let windows = [
10596 cx.add_window(|_, cx| InspectorTestRoot {
10597 child: cx.new(|_| InspectorTestView::default()),
10598 }),
10599 cx.add_window(|_, cx| InspectorTestRoot {
10600 child: cx.new(|_| InspectorTestView::default()),
10601 }),
10602 ];
10603 for window in windows {
10604 assert_closed_inspector(window.into(), cx);
10605 }
10606 for _ in 0..2 {
10607 cx.update_window(windows[0].into(), |root, window, cx| {
10608 let root = root.downcast::<InspectorTestRoot>().expect("test root");
10609 let child_widths = root.read(cx).child.read(cx).child_widths.clone();
10610 window.toggle_inspector(cx);
10611 window.draw(cx).clear(cx);
10612 assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
10613 let path = window
10614 .rendered_frame
10615 .next_inspector_instance_ids
10616 .iter()
10617 .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
10618 .expect("anonymous siblings share an inspector path");
10619 let selected_id = InspectorElementId {
10620 path,
10621 instance_id: 1,
10622 };
10623 let position = window
10624 .rendered_frame
10625 .hitboxes
10626 .iter()
10627 .find(|hitbox| {
10628 window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
10629 == Some(&selected_id)
10630 })
10631 .expect("middle sibling is pickable")
10632 .bounds
10633 .center();
10634 window.simulate_mouse_move(position, cx);
10635 window.dispatch_event(
10636 PlatformInput::MouseDown(MouseDownEvent {
10637 position,
10638 button: MouseButton::Left,
10639 modifiers: Modifiers::default(),
10640 click_count: 1,
10641 first_mouse: false,
10642 }),
10643 cx,
10644 );
10645 window.dispatch_event(
10646 PlatformInput::MouseUp(MouseUpEvent {
10647 position,
10648 button: MouseButton::Left,
10649 modifiers: Modifiers::default(),
10650 click_count: 1,
10651 }),
10652 cx,
10653 );
10654 assert!(!window.is_inspector_picking(cx));
10655 assert_eq!(
10656 window
10657 .inspector
10658 .as_ref()
10659 .expect("open inspector")
10660 .read(cx)
10661 .active_element_id(),
10662 Some(&selected_id)
10663 );
10664 window.draw(cx).clear(cx);
10665 window.with_inspector_state::<DivInspectorState, _>(
10666 Some(&selected_id),
10667 cx,
10668 |state, _| {
10669 let state = state.as_mut().expect("selected div has style state");
10670 assert_eq!(
10671 state.base_style.size.width,
10672 Some(crate::Length::from(px(10.)))
10673 );
10674 state.base_style.size.width = Some(crate::Length::from(px(25.)));
10675 },
10676 );
10677 window.refresh();
10678 window.draw(cx).clear(cx);
10679 assert_eq!(
10680 child_widths.borrow().as_slice(),
10681 &[px(10.), px(25.), px(10.)]
10682 );
10683 })
10684 .expect("pick and edit a cached child");
10685 assert_closed_inspector(windows[1].into(), cx);
10686 windows[0]
10687 .update(cx, |_, window, cx| window.toggle_inspector(cx))
10688 .expect("close inspector");
10689 assert_closed_inspector(windows[0].into(), cx);
10690 }
10691 }
10692
10693 struct InspectorTestRoot {
10694 child: Entity<InspectorTestView>,
10695 }
10696
10697 impl Render for InspectorTestRoot {
10698 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
10699 self.child
10700 .clone()
10701 .cached(StyleRefinement::default().size(px(100.)))
10702 }
10703 }
10704
10705 #[derive(Default)]
10706 struct InspectorTestView {
10707 child_widths: Rc<RefCell<Vec<Pixels>>>,
10708 }
10709
10710 impl Render for InspectorTestView {
10711 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
10712 let child_widths = self.child_widths.clone();
10713 div()
10714 .on_children_prepainted(move |bounds, _, _| {
10715 *child_widths.borrow_mut() =
10716 bounds.iter().map(|bounds| bounds.size.width).collect();
10717 })
10718 .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
10719 .id("inspector-root")
10720 .flex()
10721 .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
10722 }
10723 }
10724
10725 fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
10726 cx.update_window(window, |root, window, cx| {
10727 window.draw(cx).clear(cx);
10728 window.draw(cx).clear(cx);
10729 let root = root.downcast::<InspectorTestRoot>().expect("test root");
10730 assert_eq!(
10731 root.read(cx)
10732 .child
10733 .read(cx)
10734 .child_widths
10735 .borrow()
10736 .as_slice(),
10737 &[px(10.); 3]
10738 );
10739 for frame in [&window.rendered_frame, &window.next_frame] {
10740 assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
10741 assert_eq!(frame.inspector_hitboxes.capacity(), 0);
10742 }
10743 })
10744 .expect("closed inspector has no bookkeeping and no style overrides");
10745 }
10746}