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::{
9 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
10 AsyncWindowContext, AtlasTile, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow,
11 Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,
12 DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
13 EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
14 Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent,
15 Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent,
16 MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels,
17 PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point,
18 PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams,
19 RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
20 ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubpixelSprite,
21 SubscriberSet, Subscription, SystemWindowTab, SystemWindowTabController, TabStopMap,
22 TaffyLayoutEngine, Task, TextInputConfiguration, TextInputStateChange, TextRenderingMode,
23 TextStyle, TextStyleRefinement, ThermalState, TransformationMatrix, Underline, UnderlineStyle,
24 WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations,
25 WindowInsets, WindowOptions, WindowParams, WindowTextSystem, WindowVisibility, point,
26 prelude::*, px, rems, size, transparent_black,
27};
28
29use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
30use crate::interactive::TouchEvent;
31use anyhow::{Context as _, Result, anyhow};
32use collections::{FxHashMap, FxHashSet};
33use derive_more::{Deref, DerefMut};
34use futures::channel::oneshot;
35use gpui_util::post_inc;
36use gpui_util::{ResultExt, measure};
37use itertools::FoldWhile::{Continue, Done};
38use itertools::Itertools;
39#[cfg(any(target_os = "macos", target_os = "ios"))]
40use objc2_core_foundation::CFRetained;
41#[cfg(any(target_os = "macos", target_os = "ios"))]
42use objc2_core_video::CVPixelBuffer;
43use parking_lot::{RwLock, RwLockUpgradableReadGuard};
44use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
45use scheduler::Instant;
46use slotmap::SlotMap;
47use smallvec::SmallVec;
48use std::{
49 any::{Any, TypeId},
50 borrow::Cow,
51 cell::{Cell, RefCell},
52 cmp,
53 fmt::{Debug, Display},
54 hash::{Hash, Hasher},
55 marker::PhantomData,
56 mem,
57 ops::{DerefMut, Range},
58 rc::Rc,
59 sync::{
60 Arc, Weak,
61 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
62 },
63 thread::AccessError,
64 time::Duration,
65};
66use uuid::Uuid;
67
68pub(crate) mod a11y;
69mod prompts;
70
71pub use a11y::A11ySubtreeBuilder;
72
73use self::a11y::A11y;
74#[cfg(not(target_family = "wasm"))]
75use self::a11y::ROOT_NODE_ID;
76use crate::util::{
77 atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
78 round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
79};
80pub use prompts::*;
81
82pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
84
85pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
88 width: Pixels(900.),
89 height: Pixels(750.),
90};
91
92#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
94pub enum DispatchPhase {
95 #[default]
100 Bubble,
101 Capture,
107}
108
109impl DispatchPhase {
110 #[inline]
112 pub fn bubble(self) -> bool {
113 self == DispatchPhase::Bubble
114 }
115
116 #[inline]
118 pub fn capture(self) -> bool {
119 self == DispatchPhase::Capture
120 }
121}
122
123pub(crate) struct WindowInvalidatorInner {
124 #[cfg(feature = "profiler")]
125 pub window_id: WindowId,
126 pub dirty: bool,
127 pub draw_phase: DrawPhase,
128 pub dirty_views: FxHashSet<EntityId>,
129 pub update_count: usize,
130 #[cfg(feature = "profiler")]
131 pub frame_dirty: FrameDirtyAccumulator,
132 pub platform_waker: Option<Rc<dyn Fn()>>,
133}
134
135#[cfg(feature = "profiler")]
141#[derive(Default)]
142struct FrameDirtyAccumulator {
143 dirty_at: Option<Instant>,
144 invalidations: u64,
145}
146
147#[derive(Clone, Copy)]
149enum FrameRateLimit {
150 Inactive,
152 Thermal,
154}
155
156#[derive(Clone)]
157pub(crate) struct WindowInvalidator {
158 pub(crate) inner: Rc<RefCell<WindowInvalidatorInner>>,
159}
160
161impl WindowInvalidator {
162 pub fn new(#[allow(unused_variables)] window_id: WindowId) -> Self {
163 WindowInvalidator {
164 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
165 #[cfg(feature = "profiler")]
166 window_id,
167 dirty: true,
168 draw_phase: DrawPhase::None,
169 dirty_views: FxHashSet::default(),
170 update_count: 0,
171 #[cfg(feature = "profiler")]
172 frame_dirty: FrameDirtyAccumulator::default(),
173 platform_waker: None,
174 })),
175 }
176 }
177
178 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
179 let mut inner = self.inner.borrow_mut();
180 inner.update_count += 1;
181 inner.dirty_views.insert(entity);
182 if inner.draw_phase == DrawPhase::None {
183 #[cfg(feature = "profiler")]
184 let dirty_at = Self::record_frame_dirty(&mut inner);
185 let became_dirty = !inner.dirty;
186 inner.dirty = true;
187 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
188 #[cfg(feature = "profiler")]
189 let window_id = inner.window_id;
190 drop(inner);
191 #[cfg(feature = "profiler")]
192 if became_dirty {
193 profiler::journal::record_frame_pending(window_id, dirty_at);
194 }
195 cx.push_effect(Effect::Notify { emitter: entity });
196 if let Some(waker) = waker {
197 waker();
198 }
199 true
200 } else {
201 false
202 }
203 }
204
205 pub fn is_dirty(&self) -> bool {
206 self.inner.borrow().dirty
207 }
208
209 pub fn set_dirty(&self, dirty: bool) {
210 let mut inner = self.inner.borrow_mut();
211 let became_dirty = dirty && !inner.dirty;
212 inner.dirty = dirty;
213 if dirty {
214 inner.update_count += 1;
215 }
216 #[cfg(feature = "profiler")]
217 let dirty_at = dirty.then(|| Self::record_frame_dirty(&mut inner));
218 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
219 #[cfg(feature = "profiler")]
220 let window_id = inner.window_id;
221 drop(inner);
222 #[cfg(feature = "profiler")]
223 if became_dirty && let Some(dirty_at) = dirty_at {
224 profiler::journal::record_frame_pending(window_id, dirty_at);
225 }
226 if let Some(waker) = waker {
227 waker();
228 }
229 }
230
231 pub fn set_platform_waker(&self, waker: Option<Rc<dyn Fn()>>) {
232 let mut inner = self.inner.borrow_mut();
233 inner.platform_waker = waker;
234 let waker = inner.dirty.then(|| inner.platform_waker.clone()).flatten();
235 drop(inner);
236 if let Some(waker) = waker {
237 waker();
238 }
239 }
240
241 pub fn wake_platform(&self) {
245 let waker = self.inner.borrow().platform_waker.clone();
246 if let Some(waker) = waker {
247 waker();
248 }
249 }
250
251 pub fn set_phase(&self, phase: DrawPhase) {
252 self.inner.borrow_mut().draw_phase = phase
253 }
254
255 pub fn update_count(&self) -> usize {
256 self.inner.borrow().update_count
257 }
258
259 #[cfg(feature = "profiler")]
260 fn record_frame_dirty(inner: &mut WindowInvalidatorInner) -> Instant {
261 let dirty_at = *inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
262 inner.frame_dirty.invalidations += 1;
263 dirty_at
264 }
265
266 #[cfg(feature = "profiler")]
267 fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
268 mem::take(&mut self.inner.borrow_mut().frame_dirty)
269 }
270
271 pub fn take_views(&self) -> FxHashSet<EntityId> {
272 mem::take(&mut self.inner.borrow_mut().dirty_views)
273 }
274
275 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
276 self.inner.borrow_mut().dirty_views = views;
277 }
278
279 pub fn not_drawing(&self) -> bool {
280 self.inner.borrow().draw_phase == DrawPhase::None
281 }
282
283 #[track_caller]
284 pub fn debug_assert_paint(&self) {
285 debug_assert!(
286 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
287 "this method can only be called during paint"
288 );
289 }
290
291 #[track_caller]
292 pub fn debug_assert_prepaint(&self) {
293 debug_assert!(
294 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
295 "this method can only be called during request_layout, or prepaint"
296 );
297 }
298
299 #[track_caller]
300 pub fn debug_assert_paint_or_prepaint(&self) {
301 debug_assert!(
302 matches!(
303 self.inner.borrow().draw_phase,
304 DrawPhase::Paint | DrawPhase::Prepaint
305 ),
306 "this method can only be called during request_layout, prepaint, or paint"
307 );
308 }
309}
310
311type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
312
313pub(crate) type AnyWindowFocusListener =
314 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
315
316pub(crate) struct WindowFocusEvent {
317 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
318 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
319}
320
321impl WindowFocusEvent {
322 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
323 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
324 }
325
326 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
327 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
328 }
329}
330
331pub struct FocusOutEvent {
333 pub blurred: WeakFocusHandle,
335}
336
337slotmap::new_key_type! {
338 pub struct FocusId;
340}
341
342thread_local! {
343 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
346
347 static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
351}
352
353fn draw_in_progress() -> bool {
364 CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some())
365}
366
367#[inline(always)]
370pub(crate) fn with_element_arena<R>(callback: impl FnOnce(&mut Arena) -> R) -> R {
371 let mut callback = Some(callback);
372 let mut result = None;
373 let access = with_element_arena_erased(&mut |arena| {
374 result = Some(callback.take().expect("arena callback runs once")(arena));
375 });
376 drop(callback);
377 access.expect("cannot access a Thread Local Storage value during or after destruction");
378 result.expect("arena callback produces a result")
379}
380
381pub(crate) struct ElementArenaScope {
396 entered: *const RefCell<Arena>,
399 previous: Option<*const RefCell<Arena>>,
400 exited: bool,
401}
402
403impl ElementArenaScope {
404 pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
406 arena.borrow_mut().begin_scope();
407 let previous = CURRENT_ELEMENT_ARENA.with(|current| {
408 let prev = current.get();
409 current.set(Some(arena as *const RefCell<Arena>));
410 prev
411 });
412 Self {
413 entered: arena as *const RefCell<Arena>,
414 previous,
415 exited: false,
416 }
417 }
418
419 pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
428 assert!(
429 std::ptr::eq(self.entered, arena),
430 "ElementArenaScope::exit called with a different arena than was entered"
431 );
432 self.exited = true;
433 ArenaClearNeeded::new(arena)
438 }
439}
440
441impl Drop for ElementArenaScope {
442 fn drop(&mut self) {
443 CURRENT_ELEMENT_ARENA.with(|current| {
450 current.set(self.previous);
451 });
452 unsafe { &*self.entered }.borrow_mut().end_scope();
456 if !self.exited && !std::thread::panicking() {
457 debug_assert!(false, "ElementArenaScope dropped without calling exit()");
458 log::error!(
459 "ElementArenaScope dropped without calling exit(); \
460 the arena clear for this draw was never requested"
461 );
462 }
463 }
464}
465
466#[must_use]
468pub struct ArenaClearNeeded {
469 arena: *const RefCell<Arena>,
472}
473
474impl ArenaClearNeeded {
475 fn new(arena: &RefCell<Arena>) -> Self {
478 Self {
479 arena: arena as *const RefCell<Arena>,
480 }
481 }
482
483 pub fn clear(self, cx: &mut App) {
492 assert!(
493 std::ptr::eq(self.arena, &cx.element_arena),
494 "ArenaClearNeeded::clear called with a different App than the draw ran against"
495 );
496 cx.element_arena.borrow_mut().clear();
497 }
498}
499
500#[derive(Default)]
501pub(crate) struct FocusMap {
502 pub(crate) handles: SlotMap<FocusId, FocusRef>,
503 pub(crate) dropped_handles: Vec<FocusId>,
504}
505
506pub(crate) struct FocusRef {
507 pub(crate) ref_count: AtomicUsize,
508 pub(crate) tab_index: isize,
509 pub(crate) tab_stop: bool,
510}
511
512impl FocusId {
513 pub fn is_focused(&self, window: &Window) -> bool {
515 window.focus == Some(*self)
516 }
517
518 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
521 window
522 .focused(cx)
523 .is_some_and(|focused| self.contains(focused.id, window))
524 }
525
526 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
529 let focused = window.focused(cx);
530 focused.is_some_and(|focused| focused.id.contains(*self, window))
531 }
532
533 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
535 window
536 .rendered_frame
537 .dispatch_tree
538 .focus_contains(*self, other)
539 }
540}
541
542pub struct FocusHandle {
544 pub(crate) id: FocusId,
545 handles: Arc<RwLock<FocusMap>>,
546 pub tab_index: isize,
548 pub tab_stop: bool,
550}
551
552impl std::fmt::Debug for FocusHandle {
553 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
554 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
555 }
556}
557
558impl FocusHandle {
559 pub(crate) fn new(handles: &Arc<RwLock<FocusMap>>) -> Self {
560 let id = handles.write().handles.insert(FocusRef {
561 ref_count: AtomicUsize::new(1),
562 tab_index: 0,
563 tab_stop: false,
564 });
565
566 Self {
567 id,
568 tab_index: 0,
569 tab_stop: false,
570 handles: handles.clone(),
571 }
572 }
573
574 pub(crate) fn for_id(id: FocusId, handles: &Arc<RwLock<FocusMap>>) -> Option<Self> {
575 let lock = handles.read();
576 let focus = lock.handles.get(id)?;
577 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
578 return None;
579 }
580 Some(Self {
581 id,
582 tab_index: focus.tab_index,
583 tab_stop: focus.tab_stop,
584 handles: handles.clone(),
585 })
586 }
587
588 pub fn tab_index(mut self, index: isize) -> Self {
590 self.tab_index = index;
591 if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
592 focus.tab_index = index;
593 }
594 self
595 }
596
597 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
601 self.tab_stop = tab_stop;
602 if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
603 focus.tab_stop = tab_stop;
604 }
605 self
606 }
607
608 pub fn downgrade(&self) -> WeakFocusHandle {
610 WeakFocusHandle {
611 id: self.id,
612 handles: Arc::downgrade(&self.handles),
613 }
614 }
615
616 pub fn focus(&self, window: &mut Window, cx: &mut App) {
618 window.focus(self, cx)
619 }
620
621 pub fn is_focused(&self, window: &Window) -> bool {
623 self.id.is_focused(window)
624 }
625
626 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
629 self.id.contains_focused(window, cx)
630 }
631
632 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
635 self.id.within_focused(window, cx)
636 }
637
638 pub fn contains(&self, other: &Self, window: &Window) -> bool {
640 self.id.contains(other.id, window)
641 }
642
643 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
645 if let Some(node_id) = window
646 .rendered_frame
647 .dispatch_tree
648 .focusable_node_id(self.id)
649 {
650 window.dispatch_action_on_node(node_id, action, cx)
651 }
652 }
653}
654
655impl Clone for FocusHandle {
656 fn clone(&self) -> Self {
657 Self::for_id(self.id, &self.handles).unwrap()
658 }
659}
660
661impl PartialEq for FocusHandle {
662 fn eq(&self, other: &Self) -> bool {
663 self.id == other.id
664 }
665}
666
667impl Eq for FocusHandle {}
668
669impl Drop for FocusHandle {
670 fn drop(&mut self) {
671 let handles = self.handles.upgradable_read();
672 let focus = handles.handles.get(self.id).expect("focus handle missing");
673 let previous_count = focus.ref_count.fetch_sub(1, SeqCst);
674 assert_ne!(previous_count, 0, "over-released focus handle");
675 if previous_count == 1 {
676 RwLockUpgradableReadGuard::upgrade(handles)
677 .dropped_handles
678 .push(self.id);
679 }
680 }
681}
682
683#[derive(Clone, Debug)]
685pub struct WeakFocusHandle {
686 pub(crate) id: FocusId,
687 pub(crate) handles: Weak<RwLock<FocusMap>>,
688}
689
690impl WeakFocusHandle {
691 pub fn upgrade(&self) -> Option<FocusHandle> {
693 let handles = self.handles.upgrade()?;
694 FocusHandle::for_id(self.id, &handles)
695 }
696}
697
698impl PartialEq for WeakFocusHandle {
699 fn eq(&self, other: &WeakFocusHandle) -> bool {
700 self.id == other.id
701 }
702}
703
704impl Eq for WeakFocusHandle {}
705
706impl PartialEq<FocusHandle> for WeakFocusHandle {
707 fn eq(&self, other: &FocusHandle) -> bool {
708 self.id == other.id
709 }
710}
711
712impl PartialEq<WeakFocusHandle> for FocusHandle {
713 fn eq(&self, other: &WeakFocusHandle) -> bool {
714 self.id == other.id
715 }
716}
717
718pub trait Focusable: 'static {
721 fn focus_handle(&self, cx: &App) -> FocusHandle;
723}
724
725impl<V: Focusable> Focusable for Entity<V> {
726 fn focus_handle(&self, cx: &App) -> FocusHandle {
727 self.read(cx).focus_handle(cx)
728 }
729}
730
731pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
734
735impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
736
737pub struct DismissEvent;
739
740type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
741
742pub(crate) type AnyMouseListener =
743 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
744
745#[derive(Clone)]
746pub(crate) struct CursorStyleRequest {
747 pub(crate) hitbox_id: Option<HitboxId>,
748 pub(crate) style: CursorStyle,
749}
750
751#[derive(Default, Eq, PartialEq)]
752pub(crate) struct HitTest {
753 pub(crate) ids: SmallVec<[HitboxId; 8]>,
754 pub(crate) hover_hitbox_count: usize,
755}
756
757#[derive(Clone, Copy, Debug, Eq, PartialEq)]
759pub enum WindowControlArea {
760 Drag,
762 Close,
764 Max,
766 Min,
768}
769
770#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
772pub struct HitboxId(u64);
773
774#[cfg(feature = "test-support")]
775impl HitboxId {
776 pub const fn placeholder() -> Self {
781 Self(0)
782 }
783}
784
785impl HitboxId {
786 pub fn is_hovered(self, window: &Window) -> bool {
793 if let Some(hovered) = crate::fast::retained::note_hover_read(window, self) {
794 return hovered;
795 }
796 if window.captured_hitbox == Some(self) {
798 return true;
799 }
800 if crate::fast::layers::hover_freeze::hides_hover(window) {
801 return false;
802 }
803 self.hit_test(window)
804 }
805
806 pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
811 if window.captured_hitbox == Some(self) {
813 return true;
814 }
815 self.hit_test(window)
816 }
817
818 pub(crate) fn hit_test(self, window: &Window) -> bool {
819 let hit_test = &window.mouse_hit_test;
820 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
821 if self == *id {
822 return true;
823 }
824 }
825 false
826 }
827
828 pub fn should_handle_scroll(self, window: &Window) -> bool {
833 window.mouse_hit_test.ids.contains(&self)
834 }
835
836 fn next(mut self) -> HitboxId {
837 HitboxId(self.0.wrapping_add(1))
838 }
839}
840
841#[derive(Clone, Debug, Deref)]
844pub struct Hitbox {
845 pub id: HitboxId,
847 #[deref]
849 pub bounds: Bounds<Pixels>,
850 pub content_mask: ContentMask<Pixels>,
852 pub behavior: HitboxBehavior,
854}
855
856impl Hitbox {
857 pub fn is_hovered(&self, window: &Window) -> bool {
874 self.id.is_hovered(window)
875 }
876
877 pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
880 let hit_test = window.rendered_frame.hit_test(position);
881 hit_test
882 .ids
883 .iter()
884 .take(hit_test.hover_hitbox_count)
885 .any(|id| self.id == *id)
886 }
887
888 pub fn should_handle_scroll(&self, window: &Window) -> bool {
895 self.id.should_handle_scroll(window)
896 }
897}
898
899#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
901pub enum HitboxBehavior {
902 #[default]
904 Normal,
905
906 BlockMouse,
928
929 BlockMouseExceptScroll,
956}
957
958#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
960pub struct TooltipId(usize);
961
962impl TooltipId {
963 pub fn is_hovered(&self, window: &Window) -> bool {
965 window
966 .tooltip_bounds
967 .as_ref()
968 .is_some_and(|tooltip_bounds| {
969 tooltip_bounds.id == *self
970 && tooltip_bounds.bounds.contains(&window.mouse_position())
971 })
972 }
973}
974
975pub(crate) struct TooltipBounds {
976 id: TooltipId,
977 bounds: Bounds<Pixels>,
978}
979
980#[derive(Clone)]
981pub(crate) struct TooltipRequest {
982 id: TooltipId,
983 tooltip: AnyTooltip,
984}
985
986#[derive(Clone, Default)]
992pub(crate) struct ElementIdStack {
993 ids: SmallVec<[ElementId; 32]>,
994 hashes: SmallVec<[u64; 32]>,
995}
996
997impl ElementIdStack {
998 pub(crate) fn push(&mut self, id: ElementId) {
999 self.hashes.push(crate::extend_path_hash(self.hash(), &id));
1000 self.ids.push(id);
1001 }
1002
1003 pub(crate) fn pop(&mut self) -> Option<ElementId> {
1004 self.hashes.pop();
1005 self.ids.pop()
1006 }
1007
1008 pub(crate) fn clear(&mut self) {
1009 self.ids.clear();
1010 self.hashes.clear();
1011 }
1012
1013 pub(crate) fn hash(&self) -> u64 {
1015 self.hashes
1016 .last()
1017 .copied()
1018 .unwrap_or(crate::EMPTY_PATH_HASH)
1019 }
1020
1021 pub(crate) fn global_id(&self) -> GlobalElementId {
1022 GlobalElementId::with_hash(&self.ids, self.hash())
1023 }
1024}
1025
1026impl std::ops::Deref for ElementIdStack {
1027 type Target = [ElementId];
1028
1029 fn deref(&self) -> &Self::Target {
1030 &self.ids
1031 }
1032}
1033
1034pub(crate) struct DeferredDraw {
1035 pub(crate) current_view: EntityId,
1036 pub(crate) priority: usize,
1037 pub(crate) parent_node: DispatchNodeId,
1038 pub(crate) element_id_stack: ElementIdStack,
1039 pub(crate) text_style_stack: crate::fast::text_style::TextStyleStack,
1040 pub(crate) content_mask: Option<ContentMask<Pixels>>,
1041 pub(crate) rem_size: Pixels,
1042 pub(crate) element: Option<AnyElement>,
1043 pub(crate) absolute_offset: Point<Pixels>,
1044 pub(crate) prepaint_range: Range<PrepaintStateIndex>,
1045 pub(crate) paint_range: Range<PaintIndex>,
1046 pub(crate) enclosing_retained: crate::fast::retained::EnclosingRetained,
1047}
1048
1049pub(crate) struct Frame {
1050 pub(crate) focus: Option<FocusId>,
1051 pub(crate) window_active: bool,
1052 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
1053 pub(crate) accessed_element_states: Vec<(GlobalElementId, TypeId)>,
1054 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
1055 pub(crate) dispatch_tree: DispatchTree,
1056 pub(crate) scene: Scene,
1057 pub(crate) fast_composition_starts: crate::fast::composition::SurfaceStarts,
1058 pub(crate) fast_composition_input: crate::fast::composition::SurfaceInput,
1059 pub(crate) hitboxes: Vec<Hitbox>,
1060 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
1061 pub(crate) deferred_draws: Vec<DeferredDraw>,
1062 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
1063 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
1064 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
1065 #[cfg(any(test, feature = "test-support"))]
1066 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
1067 #[cfg(any(test, feature = "test-support"))]
1068 pub(crate) debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
1069 #[cfg(any(feature = "inspector", debug_assertions))]
1070 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
1071 #[cfg(any(feature = "inspector", debug_assertions))]
1072 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
1073 pub(crate) tab_stops: TabStopMap,
1074 pub(crate) retained: crate::fast::retained::RetainedSubtrees,
1075}
1076
1077#[derive(Clone, Default)]
1078pub(crate) struct PrepaintStateIndex {
1079 pub(crate) hitboxes_index: usize,
1080 pub(crate) tooltips_index: usize,
1081 pub(crate) deferred_draws_index: usize,
1082 pub(crate) dispatch_tree_index: usize,
1083 pub(crate) accessed_element_states_index: usize,
1084 pub(crate) line_layout_index: LineLayoutIndex,
1085 pub(crate) fast_a11y_index: usize,
1086}
1087
1088#[derive(Clone, Default)]
1089pub(crate) struct PaintIndex {
1090 pub(crate) scene_index: usize,
1091 #[cfg(any(test, feature = "test-support"))]
1092 pub(crate) debug_bounds_index: usize,
1093 pub(crate) fast: crate::fast::retained::FastPaintIndex,
1094 pub(crate) mouse_listeners_index: usize,
1095 pub(crate) input_handlers_index: usize,
1096 pub(crate) cursor_styles_index: usize,
1097 pub(crate) accessed_element_states_index: usize,
1098 pub(crate) tab_handle_index: usize,
1099 pub(crate) line_layout_index: LineLayoutIndex,
1100}
1101
1102impl Frame {
1103 #[cfg(any(test, feature = "test-support"))]
1104 pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) {
1105 self.debug_bounds.insert(selector.clone(), bounds);
1106 self.debug_bounds_records.push((selector, bounds));
1107 }
1108
1109 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
1110 Frame {
1111 focus: None,
1112 window_active: false,
1113 element_states: FxHashMap::default(),
1114 accessed_element_states: Vec::new(),
1115 mouse_listeners: Vec::new(),
1116 dispatch_tree,
1117 scene: Scene::default(),
1118 fast_composition_starts: crate::fast::composition::SurfaceStarts::default(),
1119 fast_composition_input: crate::fast::composition::SurfaceInput::default(),
1120 hitboxes: Vec::new(),
1121 window_control_hitboxes: Vec::new(),
1122 deferred_draws: Vec::new(),
1123 input_handlers: Vec::new(),
1124 tooltip_requests: Vec::new(),
1125 cursor_styles: Vec::new(),
1126
1127 #[cfg(any(test, feature = "test-support"))]
1128 debug_bounds: FxHashMap::default(),
1129 #[cfg(any(test, feature = "test-support"))]
1130 debug_bounds_records: Vec::new(),
1131
1132 #[cfg(any(feature = "inspector", debug_assertions))]
1133 next_inspector_instance_ids: FxHashMap::default(),
1134
1135 #[cfg(any(feature = "inspector", debug_assertions))]
1136 inspector_hitboxes: FxHashMap::default(),
1137 tab_stops: TabStopMap::default(),
1138 retained: crate::fast::retained::RetainedSubtrees::default(),
1139 }
1140 }
1141
1142 pub(crate) fn clear(&mut self) {
1143 self.element_states.clear();
1144 self.accessed_element_states.clear();
1145 self.mouse_listeners.clear();
1146 self.dispatch_tree.clear();
1147 self.scene.clear();
1148 crate::fast::composition::SurfaceStarts::clear(&mut self.fast_composition_starts);
1149 self.input_handlers.clear();
1150 self.tooltip_requests.clear();
1151 self.cursor_styles.clear();
1152 self.hitboxes.clear();
1153 crate::fast::composition::SurfaceInput::clear(&mut self.fast_composition_input);
1154 self.window_control_hitboxes.clear();
1155 self.deferred_draws.clear();
1156 self.tab_stops.clear();
1157 crate::fast::retained::RetainedSubtrees::clear(&mut self.retained);
1158 self.focus = None;
1159
1160 #[cfg(any(test, feature = "test-support"))]
1161 {
1162 self.debug_bounds.clear();
1163 self.debug_bounds_records.clear();
1164 }
1165
1166 #[cfg(any(feature = "inspector", debug_assertions))]
1167 {
1168 self.next_inspector_instance_ids.clear();
1169 self.inspector_hitboxes.clear();
1170 }
1171 }
1172
1173 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1174 self.cursor_styles
1175 .iter()
1176 .rev()
1177 .fold_while(None, |style, request| match request.hitbox_id {
1178 None => Done(Some(request.style)),
1179 Some(hitbox_id) => Continue(style.or_else(|| {
1180 hitbox_id
1181 .is_hovered_ignoring_last_input(window)
1182 .then_some(request.style)
1183 })),
1184 })
1185 .into_inner()
1186 }
1187
1188 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
1189 if let Some(hit_test) = crate::fast::composition::hit_test(self, position) {
1190 return hit_test;
1191 }
1192 let mut set_hover_hitbox_count = false;
1193 let mut hit_test = HitTest::default();
1194 for hitbox in self.hitboxes.iter().rev() {
1195 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
1196 if bounds.contains(&position) {
1197 hit_test.ids.push(hitbox.id);
1198 if !set_hover_hitbox_count
1199 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1200 {
1201 hit_test.hover_hitbox_count = hit_test.ids.len();
1202 set_hover_hitbox_count = true;
1203 }
1204 if hitbox.behavior == HitboxBehavior::BlockMouse {
1205 break;
1206 }
1207 }
1208 }
1209 if !set_hover_hitbox_count {
1210 hit_test.hover_hitbox_count = hit_test.ids.len();
1211 }
1212 hit_test
1213 }
1214
1215 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1216 self.focus
1217 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1218 .unwrap_or_default()
1219 }
1220
1221 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1222 for element_state_key in &self.accessed_element_states {
1223 if let Some((element_state_key, element_state)) =
1224 prev_frame.element_states.remove_entry(element_state_key)
1225 {
1226 self.element_states.insert(element_state_key, element_state);
1227 }
1228 }
1229
1230 self.scene.finish();
1231 }
1232}
1233
1234#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1235enum InputModality {
1236 Mouse,
1237 Keyboard,
1238 Touch,
1239}
1240
1241pub struct Window {
1243 pub(crate) handle: AnyWindowHandle,
1244 pub(crate) invalidator: WindowInvalidator,
1245 pub(crate) removed: bool,
1246 pub(crate) platform_window: Box<dyn PlatformWindow>,
1247 pub(crate) display_id: Option<DisplayId>,
1248 pub(crate) display_observers: SubscriberSet<(), AnyObserver>,
1249 is_resizable: bool,
1250 is_minimizable: bool,
1251 pub(crate) sprite_atlas: Arc<dyn PlatformAtlas>,
1252 pub(crate) text_system: Arc<WindowTextSystem>,
1253 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1254 rem_size: Pixels,
1255 pub(crate) rem_size_override_stack: SmallVec<[Pixels; 8]>,
1260 pub(crate) viewport_size: Size<Pixels>,
1261 pub(crate) layout_engine: Option<TaffyLayoutEngine>,
1262 pub(crate) fast_layout: crate::fast::layout_key::WindowLayout,
1263 pub(crate) root: Option<AnyView>,
1264 pub(crate) element_id_stack: ElementIdStack,
1265 pub(crate) global_ids: crate::fast::global_id::GlobalIdCache,
1266 pub(crate) retained_state: crate::fast::retained::RetainedState,
1267 pub(crate) text_style_stack: crate::fast::text_style::TextStyleStack,
1268 pub(crate) fast_glyph_bounds: crate::fast::glyphs::GlyphBoundsCache,
1269 pub(crate) fast_layers: crate::fast::layers::WindowLayers,
1270 pub(crate) fast_composition: crate::fast::composition::WindowCompositionHandle,
1271 pub(crate) rendered_entity_stack: Vec<EntityId>,
1272 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1273 pub(crate) element_opacity: f32,
1274 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1275 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1276 last_text_input_configuration: Option<TextInputConfiguration>,
1280 focused_text_input: Option<FocusId>,
1281 pub(crate) image_cache_stack: Vec<AnyImageCache>,
1282 pub(crate) rendered_frame: Frame,
1283 pub(crate) next_frame: Frame,
1284 next_hitbox_id: HitboxId,
1285 pub(crate) next_tooltip_id: TooltipId,
1286 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1287 pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1288 pub(crate) dirty_views: FxHashSet<EntityId>,
1289 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
1290 pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
1291 focus_lost_path: SmallVec<[FocusId; 8]>,
1292 pub(crate) default_prevented: bool,
1293 pub(crate) mouse_position: Point<Pixels>,
1294 pub(crate) mouse_hit_test: HitTest,
1295 modifiers: Modifiers,
1296 capslock: Capslock,
1297 scale_factor: f32,
1298 pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
1299 appearance: WindowAppearance,
1300 pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
1301 pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>,
1302 pub(crate) active: Rc<Cell<bool>>,
1303 visibility: WindowVisibility,
1304 pub(crate) visibility_observers:
1305 SubscriberSet<(), Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
1306 pub(crate) hovered: Rc<Cell<bool>>,
1307 pub(crate) needs_present: Rc<Cell<bool>>,
1308 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1311 #[cfg(feature = "profiler")]
1312 pub(crate) window_profiler: profiler::WindowProfiler,
1313 last_input_modality: InputModality,
1314 touch_gestures: TouchGestureRecognizer,
1315 touch_prediction_enabled: bool,
1316 long_press_timer: Option<Task<()>>,
1317 long_press_capture: Option<EntityId>,
1318 pub(crate) refreshing: bool,
1319 pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
1320 pub(crate) focus: Option<FocusId>,
1321 focus_enabled: bool,
1322 pub(crate) focus_generation: u64,
1325 pending_input: Option<PendingInput>,
1326 pending_modifier: ModifierState,
1327 pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
1328 prompt: Option<RenderablePromptHandle>,
1329 pub(crate) client_inset: Option<Pixels>,
1330 pub(crate) captured_hitbox: Option<HitboxId>,
1333 #[cfg(any(feature = "inspector", debug_assertions))]
1334 pub(crate) inspector: Option<Entity<Inspector>>,
1335 #[cfg(feature = "profiler")]
1336 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1337 pub(crate) a11y: A11y,
1338}
1339
1340#[derive(Clone, Debug, Default)]
1341struct ModifierState {
1342 modifiers: Modifiers,
1343 saw_other_input: bool,
1344}
1345
1346#[derive(Clone, Debug)]
1349pub(crate) struct InputRateTracker {
1350 timestamps: Vec<Instant>,
1351 window: Duration,
1352 inputs_per_second: u32,
1353 sustain_until: Instant,
1354 sustain_duration: Duration,
1355}
1356
1357impl Default for InputRateTracker {
1358 fn default() -> Self {
1359 Self {
1360 timestamps: Vec::new(),
1361 window: Duration::from_millis(100),
1362 inputs_per_second: 60,
1363 sustain_until: Instant::now(),
1364 sustain_duration: Duration::from_secs(1),
1365 }
1366 }
1367}
1368
1369impl InputRateTracker {
1370 pub fn record_input(&mut self) {
1371 let now = Instant::now();
1372 self.timestamps.push(now);
1373 self.prune_old_timestamps(now);
1374
1375 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1376 if self.timestamps.len() as u128 >= min_events {
1377 self.sustain_until = now + self.sustain_duration;
1378 }
1379 }
1380
1381 pub fn is_high_rate(&self) -> bool {
1382 Instant::now() < self.sustain_until
1383 }
1384
1385 fn prune_old_timestamps(&mut self, now: Instant) {
1386 self.timestamps
1387 .retain(|&t| now.duration_since(t) <= self.window);
1388 }
1389}
1390
1391#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1392pub(crate) enum DrawPhase {
1393 None,
1394 Prepaint,
1395 Paint,
1396 Focus,
1397}
1398
1399pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
1400
1401pub struct PendingInputStatus<'a> {
1403 keystrokes: &'a [Keystroke],
1404 timeout: Option<PendingInputTimeoutStatus>,
1405}
1406
1407impl<'a> PendingInputStatus<'a> {
1408 pub fn keystrokes(&self) -> &'a [Keystroke] {
1410 self.keystrokes
1411 }
1412
1413 pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
1415 self.timeout
1416 }
1417}
1418
1419#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1421pub struct PendingInputTimeoutStatus {
1422 duration: Duration,
1423 remaining: Duration,
1424 started_at: Option<Instant>,
1425 paused: bool,
1426}
1427
1428impl PendingInputTimeoutStatus {
1429 pub fn duration(&self) -> Duration {
1431 self.duration
1432 }
1433
1434 pub fn remaining(&self, cx: &App) -> Duration {
1436 self.started_at
1437 .map(|started_at| {
1438 self.remaining
1439 .saturating_sub(cx.background_executor().now() - started_at)
1440 })
1441 .unwrap_or(self.remaining)
1442 }
1443
1444 pub fn is_paused(&self) -> bool {
1446 self.paused
1447 }
1448}
1449
1450#[derive(Debug)]
1451struct PendingInputTimeout {
1452 duration: Duration,
1453 remaining: Duration,
1454 state: PendingInputTimeoutState,
1455}
1456
1457#[derive(Debug)]
1458enum PendingInputTimeoutState {
1459 Running { started_at: Instant, task: Task<()> },
1460 Paused { pause: PendingInputTimeoutPause },
1461}
1462
1463#[derive(Debug)]
1464struct PendingInputTimeoutPause {
1465 owner_id: EntityId,
1466 _release_subscription: Subscription,
1467}
1468
1469impl PendingInputTimeout {
1470 fn is_paused(&self) -> bool {
1471 matches!(&self.state, PendingInputTimeoutState::Paused { .. })
1472 }
1473
1474 fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
1475 match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
1476 PendingInputTimeoutState::Running { started_at, task } => {
1477 self.remaining = self.remaining.saturating_sub(now - started_at);
1478 drop(task);
1479 true
1480 }
1481 previous_state @ PendingInputTimeoutState::Paused { .. } => {
1482 self.state = previous_state;
1483 false
1484 }
1485 }
1486 }
1487
1488 fn pause_owner_id(&self) -> Option<EntityId> {
1489 match &self.state {
1490 PendingInputTimeoutState::Running { .. } => None,
1491 PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
1492 }
1493 }
1494
1495 fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
1496 match std::mem::replace(
1497 &mut self.state,
1498 PendingInputTimeoutState::Running { started_at, task },
1499 ) {
1500 PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
1501 previous_state => {
1502 self.state = previous_state;
1503 false
1504 }
1505 }
1506 }
1507
1508 fn reset_duration(&mut self, duration: Duration) {
1509 self.duration = duration;
1510 self.remaining = duration;
1511 }
1512
1513 fn status(&self) -> PendingInputTimeoutStatus {
1514 let (started_at, paused) = match &self.state {
1515 PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
1516 PendingInputTimeoutState::Paused { .. } => (None, true),
1517 };
1518 PendingInputTimeoutStatus {
1519 duration: self.duration,
1520 remaining: self.remaining,
1521 started_at,
1522 paused,
1523 }
1524 }
1525}
1526
1527#[derive(Default, Debug)]
1528struct PendingInput {
1529 keystrokes: SmallVec<[Keystroke; 1]>,
1530 focus: Option<FocusId>,
1531 timeout: Option<PendingInputTimeout>,
1532}
1533
1534pub(crate) struct ElementStateBox {
1535 pub(crate) inner: Box<dyn Any>,
1536 #[cfg(debug_assertions)]
1537 pub(crate) type_name: &'static str,
1538}
1539
1540fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1541 let active_window_bounds = cx
1546 .active_window()
1547 .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1548
1549 const CASCADE_OFFSET: f32 = 25.0;
1550
1551 let display = display_id
1552 .map(|id| cx.find_display(id))
1553 .unwrap_or_else(|| cx.primary_display());
1554
1555 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1556
1557 let display_bounds = display
1559 .as_ref()
1560 .map(|d| d.visible_bounds())
1561 .unwrap_or_else(default_placement);
1562
1563 let (
1564 Bounds {
1565 origin: base_origin,
1566 size: base_size,
1567 },
1568 window_bounds_ctor,
1569 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1570 Some(bounds) => match bounds {
1571 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1572 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1573 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1574 },
1575 None => (
1576 display
1577 .as_ref()
1578 .map(|d| d.default_bounds())
1579 .unwrap_or_else(default_placement),
1580 WindowBounds::Windowed,
1581 ),
1582 };
1583
1584 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1585 let proposed_origin = base_origin + cascade_offset;
1586 let proposed_bounds = Bounds::new(proposed_origin, base_size);
1587
1588 let display_right = display_bounds.origin.x + display_bounds.size.width;
1589 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1590 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1591 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1592
1593 let fits_horizontally = window_right <= display_right;
1594 let fits_vertically = window_bottom <= display_bottom;
1595
1596 let final_origin = match (fits_horizontally, fits_vertically) {
1597 (true, true) => proposed_origin,
1598 (false, true) => point(display_bounds.origin.x, base_origin.y),
1599 (true, false) => point(base_origin.x, display_bounds.origin.y),
1600 (false, false) => display_bounds.origin,
1601 };
1602 window_bounds_ctor(Bounds::new(final_origin, base_size))
1603}
1604
1605impl Window {
1606 pub(crate) fn new(
1607 handle: AnyWindowHandle,
1608 options: WindowOptions,
1609 cx: &mut App,
1610 ) -> Result<Self> {
1611 let WindowOptions {
1612 window_bounds,
1613 titlebar,
1614 focus,
1615 show,
1616 kind,
1617 is_movable,
1618 app_owns_titlebar_drag,
1619 inactive_frame_interval,
1620 is_resizable,
1621 is_minimizable,
1622 display_id,
1623 window_background,
1624 app_id,
1625 window_min_size,
1626 window_decorations,
1627 #[cfg_attr(
1628 not(any(target_os = "linux", target_os = "freebsd")),
1629 allow(unused_variables)
1630 )]
1631 icon,
1632 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1633 tabbing_identifier,
1634 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1635 use_display_p3,
1636 } = options;
1637
1638 let initial_window_title = titlebar
1639 .as_ref()
1640 .and_then(|titlebar| titlebar.title.clone());
1641
1642 let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1643 let mut platform_window = cx.platform.open_window(
1644 handle,
1645 WindowParams {
1646 bounds: window_bounds.get_bounds(),
1647 titlebar,
1648 kind,
1649 is_movable,
1650 app_owns_titlebar_drag,
1651 is_resizable,
1652 is_minimizable,
1653 focus,
1654 show,
1655 display_id,
1656 window_min_size,
1657 app_id: app_id.clone(),
1658 icon,
1659 #[cfg(target_os = "macos")]
1660 tabbing_identifier,
1661 #[cfg(target_os = "macos")]
1662 use_display_p3,
1663 },
1664 )?;
1665
1666 let tab_bar_visible = platform_window.tab_bar_visible();
1667 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1668 if let Some(tabs) = platform_window.tabbed_windows() {
1669 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1670 }
1671
1672 let display_id = platform_window.display().map(|display| display.id());
1673 let sprite_atlas = platform_window.sprite_atlas();
1674 let mouse_position = platform_window.mouse_position();
1675 let modifiers = platform_window.modifiers();
1676 let capslock = platform_window.capslock();
1677 let content_size = platform_window.content_size();
1678 let scale_factor = platform_window.scale_factor();
1679 let appearance = platform_window.appearance();
1680 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1681 let invalidator = WindowInvalidator::new(handle.window_id());
1682 let active = Rc::new(Cell::new(platform_window.is_active()));
1683 let visibility = platform_window.visibility();
1684 #[cfg(feature = "profiler")]
1685 profiler::journal::record_window_visibility(handle.window_id(), visibility);
1686 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1687 let needs_present = Rc::new(Cell::new(false));
1688 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1689 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1690 let last_frame_time = Rc::new(Cell::new(None));
1691
1692 platform_window
1693 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1694 platform_window.set_background_appearance(window_background);
1695
1696 match window_bounds {
1697 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1698 WindowBounds::Maximized(_) => platform_window.zoom(),
1699 WindowBounds::Windowed(_) => {}
1700 }
1701
1702 let accessibility_force_disabled = cx.accessibility_force_disabled;
1703 let a11y_active_flag = Arc::new(AtomicBool::new(false));
1704
1705 #[cfg(not(target_family = "wasm"))]
1706 if !accessibility_force_disabled {
1707 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
1708 if let Some(title) = &initial_window_title {
1709 initial_root_node.set_label(title.to_string());
1710 }
1711 let initial_tree = accesskit::TreeUpdate {
1712 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
1713 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
1714 tree_id: accesskit::TreeId::ROOT,
1715 focus: ROOT_NODE_ID,
1716 };
1717 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
1718 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
1719 let (action_sender, action_receiver) =
1720 async_channel::unbounded::<accesskit::ActionRequest>();
1721
1722 platform_window.a11y_init(crate::A11yCallbacks {
1723 activation: {
1724 let active_flag = a11y_active_flag.clone();
1725 Box::new(move || {
1726 log::info!("Accessibility activated");
1727 active_flag.store(true, SeqCst);
1728 activation_sender.send_blocking(()).log_err();
1729 Some(initial_tree.clone())
1730 })
1731 },
1732 action: Box::new(move |request| {
1733 action_sender.send_blocking(request).log_err();
1734 }),
1735 deactivation: {
1736 let active_flag = a11y_active_flag.clone();
1737 Box::new(move || {
1738 log::info!("Accessibility deactivated");
1739 active_flag.store(false, SeqCst);
1740 deactivation_sender.send_blocking(()).log_err();
1741 })
1742 },
1743 });
1744
1745 let mut async_cx = cx.to_async();
1751 cx.foreground_executor()
1752 .spawn(async move {
1753 while activation_receiver.recv().await.is_ok() {
1754 handle
1755 .update(&mut async_cx, |_, window, _| window.refresh())
1756 .log_err();
1757 }
1758 })
1759 .detach();
1760
1761 let mut async_cx = cx.to_async();
1762 cx.foreground_executor()
1763 .spawn(async move {
1764 while deactivation_receiver.recv().await.is_ok() {
1765 handle
1766 .update(&mut async_cx, |_, window, _| window.refresh())
1767 .log_err();
1768 }
1769 })
1770 .detach();
1771
1772 let mut async_cx = cx.to_async();
1773 cx.foreground_executor()
1774 .spawn(async move {
1775 while let Ok(request) = action_receiver.recv().await {
1776 handle
1777 .update(&mut async_cx, |_, window, cx| {
1778 window.handle_a11y_action(request, cx);
1779 })
1780 .log_err();
1781 }
1782 })
1783 .detach();
1784 }
1785
1786 platform_window.on_close(Box::new({
1787 let window_id = handle.window_id();
1788 let mut cx = cx.to_async();
1789 move || {
1790 let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
1791 let _ = cx.update(|cx| {
1792 SystemWindowTabController::remove_tab(cx, window_id);
1793 });
1794 }
1795 }));
1796 platform_window.on_request_frame(Box::new({
1797 let mut cx = cx.to_async();
1798 let invalidator = invalidator.clone();
1799 let active = active.clone();
1800 let needs_present = needs_present.clone();
1801 let next_frame_callbacks = next_frame_callbacks.clone();
1802 let input_rate_tracker = input_rate_tracker.clone();
1803 let mut deferred_force_render = false;
1804 move |request_frame_options| {
1805 #[cfg(feature = "profiler")]
1806 let (_foreground_turn, window_id) = {
1807 let foreground_turn = profiler::journal::foreground_turn();
1808 let window_id = handle.window_id();
1809 profiler::journal::record_platform_signal(profiler::journal::PlatformSignal {
1810 window_id,
1811 signal_at: request_frame_options.signal_at,
1812 handled_at: Instant::now(),
1813 source: request_frame_options.signal_source,
1814 });
1815 (foreground_turn, window_id)
1816 };
1817 if draw_in_progress() {
1833 log::debug!("deferring re-entrant window draw request");
1834 deferred_force_render |= request_frame_options.force_render;
1835 #[cfg(feature = "profiler")]
1836 profiler::journal::record_reentrant_frame_skipped(window_id, Instant::now());
1837 return;
1838 }
1839 let force_render =
1843 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
1844
1845 let thermal_state = handle
1846 .update(&mut cx, |_, _, cx| cx.thermal_state())
1847 .log_err();
1848
1849 let min_frame_interval = if request_frame_options.require_presentation
1853 || (!request_frame_options.force_render
1854 && next_frame_callbacks.borrow().is_empty())
1855 {
1856 None
1857 } else if !active.get() && !input_rate_tracker.borrow_mut().is_high_rate() {
1858 inactive_frame_interval.map(|interval| (interval, FrameRateLimit::Inactive))
1859 } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
1860 Some((Duration::from_micros(16667), FrameRateLimit::Thermal))
1861 } else {
1862 None
1863 };
1864
1865 let now = Instant::now();
1866 #[cfg_attr(not(feature = "profiler"), expect(unused_variables))]
1867 if let Some((min_interval, limit)) = min_frame_interval {
1868 if let Some(last_frame) = last_frame_time.get()
1869 && now.duration_since(last_frame) < min_interval
1870 {
1871 deferred_force_render |= force_render;
1873 handle
1875 .update(&mut cx, |_, window, _| {
1876 window.platform_window.schedule_frame();
1877 })
1878 .log_err();
1879 invalidator.wake_platform();
1884 #[cfg(feature = "profiler")]
1885 profiler::journal::record_frame_skipped(
1886 window_id,
1887 Instant::now(),
1888 match limit {
1889 FrameRateLimit::Inactive => {
1890 profiler::journal::FrameSkipReason::InactiveFrameRateLimit
1891 }
1892 FrameRateLimit::Thermal => {
1893 profiler::journal::FrameSkipReason::ThermalFrameRateLimit
1894 }
1895 },
1896 );
1897 return;
1898 }
1899 }
1900 last_frame_time.set(Some(now));
1901
1902 let pending_next_frame_callbacks = next_frame_callbacks.take();
1903 if !pending_next_frame_callbacks.is_empty() {
1904 handle
1905 .update(&mut cx, |_, window, cx| {
1906 for callback in pending_next_frame_callbacks {
1907 callback(window, cx);
1908 }
1909 })
1910 .log_err();
1911 }
1912
1913 let needs_present = request_frame_options.require_presentation
1917 || needs_present.get()
1918 || input_rate_tracker.borrow_mut().is_high_rate();
1919
1920 let should_draw = invalidator.is_dirty() || force_render;
1921 if should_draw {
1922 measure("frame duration", || {
1923 handle
1924 .update(&mut cx, |_, window, cx| {
1925 #[cfg(feature = "profiler")]
1926 window
1927 .window_profiler
1928 .record_frame_signal(request_frame_options.signal_at);
1929 if force_render {
1930 window.refresh();
1933 }
1934 let arena_clear_needed = window.draw(cx);
1935 window.present();
1936 arena_clear_needed.clear(cx);
1937 })
1938 .log_err();
1939 })
1940 } else if needs_present {
1941 handle
1942 .update(&mut cx, |_, window, _| window.present())
1943 .log_err();
1944 }
1945
1946 handle
1947 .update(&mut cx, |_, window, _| {
1948 if window.invalidator.is_dirty()
1949 || !window.next_frame_callbacks.borrow().is_empty()
1950 {
1951 window.platform_window.schedule_frame();
1952 }
1953 })
1954 .log_err();
1955
1956 if invalidator.is_dirty() || !next_frame_callbacks.borrow().is_empty() {
1962 invalidator.wake_platform();
1963 }
1964 #[cfg(feature = "profiler")]
1965 if !should_draw {
1966 profiler::journal::record_frame_skipped(
1967 window_id,
1968 Instant::now(),
1969 profiler::journal::FrameSkipReason::NoRenderNeeded,
1970 );
1971 }
1972 }
1973 }));
1974 invalidator.set_platform_waker(platform_window.frame_waker());
1975 platform_window.on_visual_viewport_changed(Box::new({
1976 let mut cx = cx.to_async();
1977 move || {
1978 handle
1979 .update(&mut cx, |_, window, _| window.refresh())
1980 .log_err();
1981 }
1982 }));
1983 platform_window.on_insets_changed(Box::new({
1984 let mut cx = cx.to_async();
1985 move |_| {
1986 handle
1987 .update(&mut cx, |_, window, _| window.refresh())
1988 .log_err();
1989 }
1990 }));
1991 platform_window.on_resize(Box::new({
1992 let mut cx = cx.to_async();
1993 move |_, _| {
1994 handle
1995 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1996 .log_err();
1997 }
1998 }));
1999 platform_window.on_moved(Box::new({
2000 let mut cx = cx.to_async();
2001 move || {
2002 handle
2003 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2004 .log_err();
2005 }
2006 }));
2007 platform_window.on_display_changed(Box::new({
2008 let cx = cx.to_async();
2009 move || cx.update(|cx| Window::display_changed(handle, cx))
2010 }));
2011 platform_window.on_appearance_changed(Box::new({
2012 let cx = cx.to_async();
2013 let foreground_executor = cx.foreground_executor().clone();
2014 move || {
2015 let mut cx = cx.clone();
2016 foreground_executor
2019 .spawn(async move {
2020 handle
2021 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
2022 .log_err();
2023 })
2024 .detach();
2025 }
2026 }));
2027 platform_window.on_button_layout_changed(Box::new({
2028 let mut cx = cx.to_async();
2029 move || {
2030 handle
2031 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
2032 .log_err();
2033 }
2034 }));
2035 platform_window.on_active_status_change(Box::new({
2036 let mut cx = cx.to_async();
2037 move |active| {
2038 handle
2039 .update(&mut cx, |_, window, cx| {
2040 window.active.set(active);
2041 window.modifiers = window.platform_window.modifiers();
2042 window.capslock = window.platform_window.capslock();
2043 window
2044 .activation_observers
2045 .clone()
2046 .retain(&(), |callback| callback(window, cx));
2047
2048 window.bounds_changed(cx);
2049 window.refresh();
2050
2051 SystemWindowTabController::update_last_active(cx, window.handle.id);
2052 })
2053 .log_err();
2054 }
2055 }));
2056 platform_window.on_visibility_change(Box::new({
2057 let mut cx = cx.to_async();
2058 move |_| {
2059 handle
2060 .update(&mut cx, |_, window, cx| {
2061 window.refresh_visibility(cx);
2062 })
2063 .log_err();
2064 }
2065 }));
2066 platform_window.on_hover_status_change(Box::new({
2067 let mut cx = cx.to_async();
2068 move |active| {
2069 handle
2070 .update(&mut cx, |_, window, _| {
2071 window.hovered.set(active);
2072 window.refresh();
2073 })
2074 .log_err();
2075 }
2076 }));
2077 platform_window.on_input({
2078 let mut cx = cx.to_async();
2079 Box::new(move |event| {
2080 handle
2081 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
2082 .log_err()
2083 .unwrap_or(DispatchEventResult::default())
2084 })
2085 });
2086 platform_window.on_hit_test_window_control({
2087 let mut cx = cx.to_async();
2088 Box::new(move || {
2089 handle
2090 .update(&mut cx, |_, window, _cx| {
2091 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
2092 if window.mouse_hit_test.ids.contains(&hitbox.id) {
2093 return Some(*area);
2094 }
2095 }
2096 None
2097 })
2098 .log_err()
2099 .unwrap_or(None)
2100 })
2101 });
2102 platform_window.on_move_tab_to_new_window({
2103 let mut cx = cx.to_async();
2104 Box::new(move || {
2105 handle
2106 .update(&mut cx, |_, _window, cx| {
2107 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
2108 })
2109 .log_err();
2110 })
2111 });
2112 platform_window.on_merge_all_windows({
2113 let mut cx = cx.to_async();
2114 Box::new(move || {
2115 handle
2116 .update(&mut cx, |_, _window, cx| {
2117 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
2118 })
2119 .log_err();
2120 })
2121 });
2122 platform_window.on_select_next_tab({
2123 let mut cx = cx.to_async();
2124 Box::new(move || {
2125 handle
2126 .update(&mut cx, |_, _window, cx| {
2127 SystemWindowTabController::select_next_tab(cx, handle.window_id());
2128 })
2129 .log_err();
2130 })
2131 });
2132 platform_window.on_select_previous_tab({
2133 let mut cx = cx.to_async();
2134 Box::new(move || {
2135 handle
2136 .update(&mut cx, |_, _window, cx| {
2137 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
2138 })
2139 .log_err();
2140 })
2141 });
2142 platform_window.on_toggle_tab_bar({
2143 let mut cx = cx.to_async();
2144 Box::new(move || {
2145 handle
2146 .update(&mut cx, |_, window, cx| {
2147 let tab_bar_visible = window.platform_window.tab_bar_visible();
2148 SystemWindowTabController::set_visible(cx, tab_bar_visible);
2149 })
2150 .log_err();
2151 })
2152 });
2153
2154 if let Some(app_id) = app_id {
2155 platform_window.set_app_id(&app_id);
2156 }
2157
2158 platform_window.map_window().unwrap();
2159
2160 Ok(Window {
2161 handle,
2162 invalidator,
2163 removed: false,
2164 platform_window,
2165 display_id,
2166 display_observers: SubscriberSet::new(),
2167 is_resizable,
2168 is_minimizable,
2169 sprite_atlas,
2170 text_system,
2171 text_rendering_mode: cx.text_rendering_mode.clone(),
2172 rem_size: px(16.),
2173 rem_size_override_stack: SmallVec::new(),
2174 viewport_size: content_size,
2175 layout_engine: Some(TaffyLayoutEngine::new()),
2176 fast_layout: crate::fast::layout_key::WindowLayout::default(),
2177 root: None,
2178 element_id_stack: ElementIdStack::default(),
2179 global_ids: crate::fast::global_id::GlobalIdCache::default(),
2180 retained_state: crate::fast::retained::RetainedState::new(cx),
2181 text_style_stack: crate::fast::text_style::TextStyleStack::default(),
2182 fast_glyph_bounds: crate::fast::glyphs::GlyphBoundsCache::default(),
2183 fast_layers: crate::fast::layers::WindowLayers::default(),
2184 fast_composition: crate::fast::composition::WindowCompositionHandle::default(),
2185 rendered_entity_stack: Vec::new(),
2186 element_offset_stack: Vec::new(),
2187 content_mask_stack: Vec::new(),
2188 element_opacity: 1.0,
2189 requested_autoscroll: None,
2190 last_text_input_configuration: None,
2191 focused_text_input: None,
2192 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
2193 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
2194 next_frame_callbacks,
2195 next_hitbox_id: HitboxId(0),
2196 next_tooltip_id: TooltipId::default(),
2197 tooltip_bounds: None,
2198 dirty_views: FxHashSet::default(),
2199 focus_listeners: SubscriberSet::new(),
2200 focus_lost_listeners: SubscriberSet::new(),
2201 focus_lost_path: SmallVec::new(),
2202 default_prevented: true,
2203 mouse_position,
2204 mouse_hit_test: HitTest::default(),
2205 modifiers,
2206 capslock,
2207 scale_factor,
2208 bounds_observers: SubscriberSet::new(),
2209 appearance,
2210 appearance_observers: SubscriberSet::new(),
2211 button_layout_observers: SubscriberSet::new(),
2212 active,
2213 visibility,
2214 visibility_observers: SubscriberSet::new(),
2215 hovered,
2216 needs_present,
2217 input_rate_tracker,
2218 #[cfg(feature = "profiler")]
2219 window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
2220 last_input_modality: InputModality::Mouse,
2221 touch_gestures: TouchGestureRecognizer::new(
2222 cx.platform
2223 .gestures()
2224 .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
2225 ),
2226 touch_prediction_enabled: true,
2227 long_press_timer: None,
2228 long_press_capture: None,
2229 refreshing: false,
2230 activation_observers: SubscriberSet::new(),
2231 focus: None,
2232 focus_enabled: true,
2233 focus_generation: 0,
2234 pending_input: None,
2235 pending_modifier: ModifierState::default(),
2236 pending_input_observers: SubscriberSet::new(),
2237 prompt: None,
2238 client_inset: None,
2239 image_cache_stack: Vec::new(),
2240 captured_hitbox: None,
2241 #[cfg(any(feature = "inspector", debug_assertions))]
2242 inspector: None,
2243 #[cfg(feature = "profiler")]
2244 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
2245 a11y: A11y::new(
2246 a11y_active_flag,
2247 accessibility_force_disabled,
2248 initial_window_title,
2249 ),
2250 })
2251 }
2252
2253 pub(crate) fn new_focus_listener(
2254 &self,
2255 value: AnyWindowFocusListener,
2256 ) -> (Subscription, impl FnOnce() + use<>) {
2257 self.focus_listeners.insert((), value)
2258 }
2259}
2260
2261#[derive(Clone, Debug, Default, PartialEq, Eq)]
2262#[expect(missing_docs)]
2263pub struct DispatchEventResult {
2264 pub propagate: bool,
2265 pub default_prevented: bool,
2266}
2267
2268#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2272#[repr(C)]
2273pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
2274 pub bounds: Bounds<P>,
2276}
2277
2278impl ContentMask<Pixels> {
2279 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
2281 ContentMask {
2282 bounds: self.bounds.scale(factor),
2283 }
2284 }
2285
2286 pub fn intersect(&self, other: &Self) -> Self {
2288 let bounds = self.bounds.intersect(&other.bounds);
2289 ContentMask { bounds }
2290 }
2291}
2292
2293impl Window {
2294 fn mark_view_dirty(&mut self, view_id: EntityId) {
2295 for view_id in self
2298 .rendered_frame
2299 .dispatch_tree
2300 .view_path_reversed(view_id)
2301 {
2302 if !self.dirty_views.insert(view_id) {
2303 break;
2304 }
2305 }
2306 }
2307
2308 pub(crate) fn refresh_visibility(&mut self, cx: &mut App) {
2309 let visibility = self.platform_window.visibility();
2310 if self.visibility != visibility {
2311 self.visibility = visibility;
2312 #[cfg(feature = "profiler")]
2313 profiler::journal::record_window_visibility(self.handle.window_id(), visibility);
2314 self.visibility_observers
2315 .clone()
2316 .retain(&(), |callback| callback(visibility, self, cx));
2317 }
2318 #[cfg(feature = "profiler")]
2319 if self.invalidator.is_dirty() || self.needs_present.get() {
2320 profiler::journal::record_frame_pending(self.handle.window_id(), Instant::now());
2321 }
2322 }
2323
2324 pub fn visibility(&self) -> WindowVisibility {
2327 self.visibility
2328 }
2329
2330 pub fn is_visible(&self) -> bool {
2336 self.visibility.is_visible()
2337 }
2338
2339 pub fn observe_window_visibility(
2341 &self,
2342 mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
2343 ) -> Subscription {
2344 let (subscription, activate) = self.visibility_observers.insert(
2345 (),
2346 Box::new(move |visibility, window, cx| {
2347 callback(visibility, window, cx);
2348 true
2349 }),
2350 );
2351 activate();
2352 subscription
2353 }
2354
2355 pub fn observe_window_appearance(
2357 &self,
2358 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2359 ) -> Subscription {
2360 let (subscription, activate) = self.appearance_observers.insert(
2361 (),
2362 Box::new(move |window, cx| {
2363 callback(window, cx);
2364 true
2365 }),
2366 );
2367 activate();
2368 subscription
2369 }
2370
2371 pub fn observe_button_layout_changed(
2373 &self,
2374 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2375 ) -> Subscription {
2376 let (subscription, activate) = self.button_layout_observers.insert(
2377 (),
2378 Box::new(move |window, cx| {
2379 callback(window, cx);
2380 true
2381 }),
2382 );
2383 activate();
2384 subscription
2385 }
2386
2387 pub fn replace_root<E>(
2389 &mut self,
2390 cx: &mut App,
2391 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
2392 ) -> Entity<E>
2393 where
2394 E: 'static + Render,
2395 {
2396 let view = cx.new(|cx| build_view(self, cx));
2397 self.root = Some(view.clone().into());
2398 self.refresh();
2399 view
2400 }
2401
2402 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
2404 where
2405 E: 'static + Render,
2406 {
2407 self.root
2408 .as_ref()
2409 .map(|view| view.clone().downcast::<E>().ok())
2410 }
2411
2412 pub fn window_handle(&self) -> AnyWindowHandle {
2414 self.handle
2415 }
2416
2417 pub fn refresh(&mut self) {
2419 if self.invalidator.not_drawing() {
2420 self.refreshing = true;
2421 self.invalidator.set_dirty(true);
2422 }
2423 }
2424
2425 pub fn remove_window(&mut self) {
2427 self.removed = true;
2428 }
2429
2430 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
2432 self.focus
2433 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
2434 }
2435
2436 pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
2440 let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
2441 ancestors.iter().rev().find_map(|id| {
2442 self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
2443 FocusHandle::for_id(*id, &cx.focus_handles)
2444 })
2445 }
2446
2447 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
2449 if !self.focus_enabled || self.focus == Some(handle.id) {
2450 return;
2451 }
2452
2453 self.focus = Some(handle.id);
2454 self.focus_generation = self.focus_generation.wrapping_add(1);
2455 self.clear_pending_keystrokes(cx);
2456
2457 self.refresh();
2458 }
2459
2460 pub fn blur(&mut self, cx: &mut App) {
2462 self.clear_pending_keystrokes(cx);
2463
2464 if !self.focus_enabled {
2465 return;
2466 }
2467
2468 if self.focus.is_some() {
2469 self.focus_generation = self.focus_generation.wrapping_add(1);
2470 }
2471 self.focus = None;
2472 self.refresh();
2473 }
2474
2475 pub fn disable_focus(&mut self, cx: &mut App) {
2477 self.blur(cx);
2478 self.focus_enabled = false;
2479 }
2480
2481 pub fn focus_next(&mut self, cx: &mut App) {
2483 if !self.focus_enabled {
2484 return;
2485 }
2486
2487 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
2488 self.focus(&handle, cx)
2489 }
2490 }
2491
2492 pub fn focus_prev(&mut self, cx: &mut App) {
2494 if !self.focus_enabled {
2495 return;
2496 }
2497
2498 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
2499 self.focus(&handle, cx)
2500 }
2501 }
2502
2503 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
2505 &self.text_system
2506 }
2507
2508 pub fn text_style(&self) -> TextStyle {
2510 (*crate::fast::text_style::text_style(self)).clone()
2511 }
2512
2513 pub fn is_maximized(&self) -> bool {
2517 self.platform_window.is_maximized()
2518 }
2519
2520 pub fn request_decorations(&self, decorations: WindowDecorations) {
2522 self.platform_window.request_decorations(decorations);
2523 }
2524
2525 pub fn set_exclusive_zone(&self, zone: Pixels) {
2531 self.platform_window.set_exclusive_zone(zone);
2532 }
2533
2534 #[cfg(all(target_os = "linux", feature = "wayland"))]
2539 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
2540 self.platform_window.set_exclusive_edge(edge);
2541 }
2542
2543 pub fn start_window_resize(&self, edge: ResizeEdge) {
2545 if self.is_resizable {
2546 self.platform_window.start_window_resize(edge);
2547 }
2548 }
2549
2550 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
2557 self.platform_window.set_input_region(region);
2558 }
2559
2560 pub fn window_bounds(&self) -> WindowBounds {
2563 self.platform_window.window_bounds()
2564 }
2565
2566 pub fn inner_window_bounds(&self) -> WindowBounds {
2568 self.platform_window.inner_window_bounds()
2569 }
2570
2571 pub fn native_window_state(&self) -> Option<Vec<u8>> {
2574 self.platform_window.native_window_state()
2575 }
2576
2577 pub fn restore_native_window_state(&self, state: &[u8]) {
2580 self.platform_window.restore_native_window_state(state);
2581 }
2582
2583 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
2585 let focus_id = self.focused(cx).map(|handle| handle.id);
2586
2587 let window = self.handle;
2588 cx.defer(move |cx| {
2589 window
2590 .update(cx, |_, window, cx| {
2591 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
2592 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
2593 })
2594 .log_err();
2595 })
2596 }
2597
2598 pub(crate) fn dispatch_keystroke_observers(
2599 &mut self,
2600 keystroke: &Keystroke,
2601 input_preference: InputPreference,
2602 action: Option<&dyn Action>,
2603 context_stack: Vec<KeyContext>,
2604 cx: &mut App,
2605 ) {
2606 cx.keystroke_observers.clone().retain(&(), move |callback| {
2607 (callback)(
2608 &KeystrokeEvent {
2609 keystroke: keystroke.clone(),
2610 input_preference,
2611 action: action.map(|action| action.boxed_clone()),
2612 context_stack: context_stack.clone(),
2613 },
2614 self,
2615 cx,
2616 )
2617 });
2618 }
2619
2620 pub(crate) fn dispatch_keystroke_interceptors(
2621 &mut self,
2622 keystroke: &Keystroke,
2623 input_preference: InputPreference,
2624 context_stack: Vec<KeyContext>,
2625 cx: &mut App,
2626 ) {
2627 cx.keystroke_interceptors
2628 .clone()
2629 .retain(&(), move |callback| {
2630 (callback)(
2631 &KeystrokeEvent {
2632 keystroke: keystroke.clone(),
2633 input_preference,
2634 action: None,
2635 context_stack: context_stack.clone(),
2636 },
2637 self,
2638 cx,
2639 )
2640 });
2641 }
2642
2643 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2646 let handle = self.handle;
2647 cx.defer(move |cx| {
2648 handle.update(cx, |_, window, cx| f(window, cx)).ok();
2649 });
2650 }
2651
2652 pub fn observe<T: 'static>(
2656 &mut self,
2657 observed: &Entity<T>,
2658 cx: &mut App,
2659 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2660 ) -> Subscription {
2661 let entity_id = observed.entity_id();
2662 let observed = observed.downgrade();
2663 let window_handle = self.handle;
2664 cx.new_observer(
2665 entity_id,
2666 Box::new(move |cx| {
2667 window_handle
2668 .update(cx, |_, window, cx| {
2669 if let Some(handle) = observed.upgrade() {
2670 on_notify(handle, window, cx);
2671 true
2672 } else {
2673 false
2674 }
2675 })
2676 .unwrap_or(false)
2677 }),
2678 )
2679 }
2680
2681 pub fn subscribe<Emitter, Evt>(
2685 &mut self,
2686 entity: &Entity<Emitter>,
2687 cx: &mut App,
2688 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
2689 ) -> Subscription
2690 where
2691 Emitter: EventEmitter<Evt>,
2692 Evt: 'static,
2693 {
2694 let entity_id = entity.entity_id();
2695 let handle = entity.downgrade();
2696 let window_handle = self.handle;
2697 cx.new_subscription(
2698 entity_id,
2699 (
2700 TypeId::of::<Evt>(),
2701 Box::new(move |event, cx| {
2702 window_handle
2703 .update(cx, |_, window, cx| {
2704 if let Some(entity) = handle.upgrade() {
2705 let event = event.downcast_ref().expect("invalid event type");
2706 on_event(entity, event, window, cx);
2707 true
2708 } else {
2709 false
2710 }
2711 })
2712 .unwrap_or(false)
2713 }),
2714 ),
2715 )
2716 }
2717
2718 pub fn observe_release<T>(
2720 &self,
2721 entity: &Entity<T>,
2722 cx: &mut App,
2723 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2724 ) -> Subscription
2725 where
2726 T: 'static,
2727 {
2728 let entity_id = entity.entity_id();
2729 let window_handle = self.handle;
2730 let (subscription, activate) = cx.release_listeners.insert(
2731 entity_id,
2732 Box::new(move |entity, cx| {
2733 let entity = entity.downcast_mut().expect("invalid entity type");
2734 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2735 }),
2736 );
2737 activate();
2738 subscription
2739 }
2740
2741 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2744 AsyncWindowContext::new_context(cx.to_async(), self.handle)
2745 }
2746
2747 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2749 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2750 self.platform_window.schedule_frame();
2751 self.invalidator.wake_platform();
2754 }
2755
2756 pub fn request_animation_frame(&self) {
2769 let entity = self.current_view();
2770 crate::fast::layers::invalidate::note_animation_frame(self, entity);
2771 self.on_next_frame(move |_, cx| cx.notify(entity));
2772 }
2773
2774 #[cfg(any(test, feature = "test-support"))]
2779 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
2780 let callbacks = self.next_frame_callbacks.take();
2781 let count = callbacks.len();
2782 for callback in callbacks {
2783 callback(self, cx);
2784 }
2785 count
2786 }
2787
2788 #[track_caller]
2792 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2793 where
2794 R: 'static,
2795 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2796 {
2797 let handle = self.handle;
2798 cx.spawn(async move |app| {
2799 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2800 f(&mut async_window_cx).await
2801 })
2802 }
2803
2804 #[track_caller]
2808 pub fn spawn_with_priority<AsyncFn, R>(
2809 &self,
2810 priority: Priority,
2811 cx: &App,
2812 f: AsyncFn,
2813 ) -> Task<R>
2814 where
2815 R: 'static,
2816 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2817 {
2818 let handle = self.handle;
2819 cx.spawn_with_priority(priority, async move |app| {
2820 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2821 f(&mut async_window_cx).await
2822 })
2823 }
2824
2825 pub fn bounds_changed(&mut self, cx: &mut App) {
2831 self.scale_factor = self.platform_window.scale_factor();
2832 self.viewport_size = self.platform_window.content_size();
2833 self.mouse_position = self.platform_window.mouse_position();
2834
2835 self.refresh();
2836
2837 self.bounds_observers
2838 .clone()
2839 .retain(&(), |callback| callback(self, cx));
2840 }
2841
2842 fn display_changed(handle: AnyWindowHandle, cx: &mut App) {
2843 let moved_to = handle
2844 .update(cx, |_, window, _| {
2845 let display_id = window.platform_window.display().map(|display| display.id());
2846 let moved = display_id != window.display_id;
2847 window.display_id = display_id;
2848 moved.then_some(display_id)
2849 })
2850 .log_err()
2851 .flatten();
2852 let Some(display_id) = moved_to else {
2853 return;
2854 };
2855 if let Some(display_id) = display_id
2859 && !cx.knows_display(display_id)
2860 {
2861 cx.displays_changed();
2862 }
2863 handle
2864 .update(cx, |_, window, cx| window.notify_display_observers(cx))
2865 .log_err();
2866 }
2867
2868 pub(crate) fn notify_display_observers(&mut self, cx: &mut App) {
2869 self.display_observers
2870 .clone()
2871 .retain(&(), |callback| callback(self, cx));
2872 }
2873
2874 pub fn refresh_interval(&self, cx: &App) -> Option<Duration> {
2879 cx.display_refresh_interval(self.display_id?)
2880 }
2881
2882 pub fn observe_window_display(
2887 &self,
2888 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2889 ) -> Subscription {
2890 let (subscription, activate) = self.display_observers.insert(
2891 (),
2892 Box::new(move |window, cx| {
2893 callback(window, cx);
2894 true
2895 }),
2896 );
2897 activate();
2898 subscription
2899 }
2900
2901 pub fn bounds(&self) -> Bounds<Pixels> {
2903 self.platform_window.bounds()
2904 }
2905
2906 pub fn insets(&self) -> WindowInsets {
2908 self.platform_window.insets()
2909 }
2910
2911 #[cfg(any(test, feature = "test-support"))]
2915 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
2916 self.platform_window
2917 .render_to_image(&self.rendered_frame.scene)
2918 }
2919
2920 #[cfg(any(test, feature = "test-support"))]
2925 pub fn painted_quads(&self) -> Vec<Quad> {
2926 self.rendered_frame.scene.quads.clone()
2927 }
2928
2929 #[cfg(any(test, feature = "test-support"))]
2931 pub fn painted_underlines(&self) -> Vec<Underline> {
2932 self.rendered_frame.scene.underlines.clone()
2933 }
2934
2935 pub fn resize(&mut self, size: Size<Pixels>) {
2937 self.platform_window.resize(size);
2938 }
2939
2940 pub fn is_fullscreen(&self) -> bool {
2942 self.platform_window.is_fullscreen()
2943 }
2944
2945 pub fn is_simple_fullscreen(&self) -> bool {
2949 self.platform_window.is_simple_fullscreen()
2950 }
2951
2952 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
2953 self.appearance = self.platform_window.appearance();
2954
2955 self.appearance_observers
2956 .clone()
2957 .retain(&(), |callback| callback(self, cx));
2958 }
2959
2960 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2961 self.button_layout_observers
2962 .clone()
2963 .retain(&(), |callback| callback(self, cx));
2964 }
2965
2966 pub fn appearance(&self) -> WindowAppearance {
2968 self.appearance
2969 }
2970
2971 pub fn viewport_size(&self) -> Size<Pixels> {
2973 self.viewport_size
2974 }
2975
2976 pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
2982 self.platform_window.visual_viewport_bounds()
2983 }
2984
2985 pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
2990 let insets = self.platform_window.insets().effective();
2991 let viewport = self.viewport_size();
2992 let left = insets.left.max(Pixels::ZERO).min(viewport.width);
2993 let top = insets.top.max(Pixels::ZERO).min(viewport.height);
2994 let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
2995 let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
2996 let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
2997 let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
2998 visible.size.width = visible.size.width.max(Pixels::ZERO);
2999 visible.size.height = visible.size.height.max(Pixels::ZERO);
3000 visible
3001 }
3002
3003 pub fn request_virtual_keyboard(&self) {
3008 self.platform_window.show_soft_keyboard();
3009 }
3010
3011 pub fn dismiss_virtual_keyboard(&self) {
3013 self.platform_window.hide_soft_keyboard();
3014 }
3015
3016 pub fn is_window_active(&self) -> bool {
3018 self.active.get()
3019 }
3020
3021 pub fn is_window_hovered(&self) -> bool {
3025 if cfg!(any(
3026 target_os = "windows",
3027 target_os = "linux",
3028 target_os = "freebsd"
3029 )) {
3030 self.hovered.get()
3031 } else {
3032 self.is_window_active()
3033 }
3034 }
3035
3036 pub fn zoom_window(&self) {
3038 self.platform_window.zoom();
3039 }
3040
3041 pub fn show_window_menu(&self, position: Point<Pixels>) {
3043 self.platform_window.show_window_menu(position)
3044 }
3045
3046 pub fn start_window_move(&self) {
3051 self.platform_window.start_window_move()
3052 }
3053
3054 pub fn set_client_inset(&mut self, inset: Pixels) {
3056 self.client_inset = Some(inset);
3057 self.platform_window.set_client_inset(inset);
3058 }
3059
3060 pub fn client_inset(&self) -> Option<Pixels> {
3062 self.client_inset
3063 }
3064
3065 pub fn window_decorations(&self) -> Decorations {
3067 self.platform_window.window_decorations()
3068 }
3069
3070 pub fn is_resizable(&self) -> bool {
3072 self.is_resizable
3073 }
3074
3075 pub fn is_minimizable(&self) -> bool {
3077 self.is_minimizable
3078 }
3079
3080 pub fn window_controls(&self) -> WindowControls {
3082 self.platform_window.window_controls()
3083 }
3084
3085 pub fn set_window_title(&mut self, title: &str) {
3087 self.platform_window.set_title(title);
3088 self.a11y.set_window_title(title.to_string());
3089 }
3090
3091 #[cfg(target_os = "macos")]
3093 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
3094 self.platform_window.set_traffic_light_position(position);
3095 }
3096
3097 pub fn set_app_id(&mut self, app_id: &str) {
3099 self.platform_window.set_app_id(app_id);
3100 }
3101
3102 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
3104 self.platform_window
3105 .set_background_appearance(background_appearance);
3106 }
3107
3108 pub fn set_window_edited(&mut self, edited: bool) {
3110 self.platform_window.set_edited(edited);
3111 }
3112
3113 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
3116 self.platform_window.set_document_path(path);
3117 }
3118
3119 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
3121 cx.platform
3122 .displays()
3123 .into_iter()
3124 .find(|display| Some(display.id()) == self.display_id)
3125 }
3126
3127 pub fn show_character_palette(&self) {
3129 self.platform_window.show_character_palette();
3130 }
3131
3132 pub fn scale_factor(&self) -> f32 {
3136 self.scale_factor
3137 }
3138
3139 #[cfg(any(test, feature = "test-support"))]
3141 pub fn set_scale_factor(&mut self, scale_factor: f32) {
3142 self.scale_factor = scale_factor;
3143 self.refresh();
3144 }
3145
3146 pub fn rem_size(&self) -> Pixels {
3149 self.rem_size_override_stack
3150 .last()
3151 .copied()
3152 .unwrap_or(self.rem_size)
3153 }
3154
3155 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
3158 self.rem_size = rem_size.into();
3159 }
3160
3161 pub fn with_global_id<R>(
3164 &mut self,
3165 element_id: ElementId,
3166 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
3167 ) -> R {
3168 self.with_id(element_id, |this| {
3169 let global_id = crate::fast::global_id::current(this);
3170
3171 f(&global_id, this)
3172 })
3173 }
3174
3175 #[inline]
3177 pub fn with_id<R>(
3178 &mut self,
3179 element_id: impl Into<ElementId>,
3180 f: impl FnOnce(&mut Self) -> R,
3181 ) -> R {
3182 self.element_id_stack.push(element_id.into());
3183 let result = f(self);
3184 self.element_id_stack.pop();
3185 result
3186 }
3187
3188 #[inline]
3194 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
3195 where
3196 F: FnOnce(&mut Self) -> R,
3197 {
3198 self.invalidator.debug_assert_paint_or_prepaint();
3199
3200 if let Some(rem_size) = rem_size {
3201 self.rem_size_override_stack.push(rem_size.into());
3202 let result = f(self);
3203 self.rem_size_override_stack.pop();
3204 result
3205 } else {
3206 f(self)
3207 }
3208 }
3209
3210 pub fn line_height(&self) -> Pixels {
3212 self.text_style().line_height_in_pixels(self.rem_size())
3213 }
3214
3215 #[inline]
3217 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
3218 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
3219 }
3220
3221 #[inline]
3223 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
3224 let scale_factor = f64::from(self.scale_factor());
3225 round_half_toward_zero_f64(value * scale_factor) / scale_factor
3226 }
3227
3228 #[inline]
3230 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
3231 bounds.map(|c| self.pixel_snap(c))
3232 }
3233
3234 #[inline]
3236 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
3237 position.map(|c| self.pixel_snap(c))
3238 }
3239
3240 pub fn underline_bounds(
3242 &self,
3243 origin: Point<Pixels>,
3244 width: Pixels,
3245 style: &UnderlineStyle,
3246 ) -> Bounds<ScaledPixels> {
3247 let scale_factor = self.scale_factor();
3248 let thickness = self.snap_stroke(style.thickness);
3249 let height = if style.wavy {
3250 ScaledPixels(thickness.0 * 3.)
3251 } else {
3252 thickness
3253 };
3254 Bounds {
3255 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3256 size: size(self.snap_stroke(width), height),
3257 }
3258 }
3259
3260 pub fn paint_underline_with_exclusions(
3262 &mut self,
3263 origin: Point<Pixels>,
3264 width: Pixels,
3265 style: &UnderlineStyle,
3266 exclusions: &[Range<ScaledPixels>],
3267 ) {
3268 self.invalidator.debug_assert_paint();
3269 let underline = self.underline(origin, width, style);
3270 if exclusions.is_empty() {
3271 self.next_frame.scene.insert_primitive(underline);
3272 return;
3273 }
3274
3275 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
3276 if bounds.is_empty() {
3277 return;
3278 }
3279
3280 let mut exclusions = exclusions
3281 .iter()
3282 .filter_map(|span| {
3283 let start = span.start.max(bounds.left());
3284 let end = span.end.min(bounds.right());
3285 (start < end).then_some(start..end)
3286 })
3287 .collect::<SmallVec<[_; 4]>>();
3288 if exclusions.is_empty() {
3289 self.next_frame.scene.insert_primitive(underline);
3290 return;
3291 }
3292 exclusions.sort_unstable_by_key(|span| span.start);
3293
3294 let mut paint_span = |start, end| {
3295 self.next_frame.scene.insert_primitive(Underline {
3296 content_mask: ContentMask {
3297 bounds: Bounds::from_corners(
3298 point(start, bounds.top()),
3299 point(end, bounds.bottom()),
3300 ),
3301 },
3302 ..underline
3303 });
3304 };
3305 let mut start = bounds.left();
3306 for exclusion in exclusions {
3307 if start < exclusion.start {
3308 paint_span(start, exclusion.start);
3309 }
3310 start = start.max(exclusion.end);
3311 }
3312 if start < bounds.right() {
3313 paint_span(start, bounds.right());
3314 }
3315 }
3316
3317 fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline {
3318 Underline {
3319 order: 0,
3320 pad: 0,
3321 bounds: self.underline_bounds(origin, width, style),
3322 content_mask: self.snapped_content_mask(),
3323 color: style
3324 .color
3325 .unwrap_or_default()
3326 .opacity(self.element_opacity()),
3327 thickness: self.snap_stroke(style.thickness),
3328 wavy: style.wavy.into(),
3329 }
3330 }
3331
3332 #[inline]
3333 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
3334 let scale_factor = self.scale_factor();
3335 let left = round_to_device_pixel(bounds.left().0, scale_factor);
3336 let top = round_to_device_pixel(bounds.top().0, scale_factor);
3337 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
3338 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
3339 Bounds::from_corners(
3340 point(ScaledPixels(left), ScaledPixels(top)),
3341 point(ScaledPixels(right), ScaledPixels(bottom)),
3342 )
3343 }
3344
3345 #[inline]
3347 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
3348 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
3349 }
3350
3351 #[inline]
3352 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
3353 edges.map(|e| self.snap_stroke(*e))
3354 }
3355
3356 #[inline]
3358 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
3359 let scale_factor = self.scale_factor();
3360 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
3361 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
3362 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
3363 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
3364 Bounds::from_corners(
3365 point(ScaledPixels(left), ScaledPixels(top)),
3366 point(ScaledPixels(right), ScaledPixels(bottom)),
3367 )
3368 }
3369
3370 #[inline]
3371 pub(crate) fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
3372 ContentMask {
3373 bounds: self.cover_bounds(self.content_mask().bounds),
3374 }
3375 }
3376
3377 pub fn prevent_default(&mut self) {
3380 self.default_prevented = true;
3381 }
3382
3383 pub fn default_prevented(&self) -> bool {
3385 self.default_prevented
3386 }
3387
3388 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
3390 let node_id =
3391 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
3392 self.rendered_frame
3393 .dispatch_tree
3394 .is_action_available(action, node_id)
3395 }
3396
3397 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
3399 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
3400 self.rendered_frame
3401 .dispatch_tree
3402 .is_action_available(action, node_id)
3403 }
3404
3405 pub fn mouse_position(&self) -> Point<Pixels> {
3407 crate::fast::dependencies::read_pointer(self);
3408 self.mouse_position
3409 }
3410
3411 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
3418 self.captured_hitbox = Some(hitbox_id);
3419 }
3420
3421 pub fn release_pointer(&mut self) {
3423 self.captured_hitbox = None;
3424 }
3425
3426 pub fn captured_hitbox(&self) -> Option<HitboxId> {
3428 self.captured_hitbox
3429 }
3430
3431 pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
3437 self.long_press_capture = Some(entity.entity_id());
3438 }
3439
3440 pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
3442 self.long_press_capture == Some(entity.entity_id())
3443 }
3444
3445 pub fn modifiers(&self) -> Modifiers {
3447 crate::fast::dependencies::read_keys(self);
3448 self.modifiers
3449 }
3450
3451 pub fn last_input_was_keyboard(&self) -> bool {
3454 self.last_input_modality == InputModality::Keyboard
3455 }
3456
3457 pub fn last_input_was_touch(&self) -> bool {
3459 self.last_input_modality == InputModality::Touch
3460 }
3461
3462 pub fn capslock(&self) -> Capslock {
3464 crate::fast::dependencies::read_keys(self);
3465 self.capslock
3466 }
3467
3468 #[profiling::function]
3471 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
3472 #[cfg(feature = "profiler")]
3475 let frame_dirty = self.invalidator.take_frame_dirty();
3476 #[cfg(feature = "profiler")]
3477 self.window_profiler.begin_draw();
3478
3479 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
3482
3483 if self.platform_window.prepare_frame() {
3484 self.refresh();
3485 }
3486 self.invalidate_entities();
3487 cx.entities.clear_accessed();
3488 debug_assert!(self.rendered_entity_stack.is_empty());
3489 self.invalidator.set_dirty(false);
3490 self.requested_autoscroll = None;
3491
3492 if let Some(input_handler) = self.platform_window.take_input_handler() {
3497 crate::fast::retained::note_restored_input_handler(self, &input_handler);
3498 if let Some(slot) = self
3499 .rendered_frame
3500 .input_handlers
3501 .iter_mut()
3502 .rev()
3503 .find(|h| h.is_none())
3504 {
3505 *slot = Some(input_handler);
3506 } else {
3507 self.rendered_frame.input_handlers.push(Some(input_handler));
3508 }
3509 }
3510 if !cx.mode.skip_drawing() {
3511 self.draw_roots(cx);
3512 #[cfg(feature = "profiler")]
3513 {
3514 let viewport_size = self.viewport_size;
3515 let scale_factor = self.scale_factor();
3516 self.debug_frame_overlay.paint(
3517 &mut self.next_frame.scene,
3518 viewport_size,
3519 scale_factor,
3520 );
3521 }
3522 }
3523 self.dirty_views.clear();
3524 self.next_frame.window_active = self.active.get();
3525
3526 let focused_text_input = if let Some(mut input_handler) = self
3532 .next_frame
3533 .input_handlers
3534 .iter_mut()
3535 .rev()
3536 .find_map(|h| h.take())
3537 {
3538 let accepts_text_input = input_handler.accepts_text_input(self, cx);
3539 crate::fast::retained::note_installed_input_handler(self, &input_handler);
3540 self.platform_window.set_input_handler(input_handler);
3541 self.focus.filter(|_| accepts_text_input)
3542 } else {
3543 None
3544 };
3545 self.apply_text_input_configuration(cx);
3546 let previous = mem::replace(&mut self.focused_text_input, focused_text_input);
3547 if previous.is_some() != focused_text_input.is_some() {
3548 self.platform_window
3549 .text_input_state_changed(if focused_text_input.is_some() {
3550 TextInputStateChange::FocusGained
3551 } else {
3552 TextInputStateChange::FocusLost
3553 });
3554 }
3555
3556 self.layout_engine.as_mut().unwrap().clear();
3557 crate::fast::layout_key::WindowLayout::end_frame(&mut self.fast_layout);
3558 self.text_system().finish_frame();
3559 crate::fast::global_id::GlobalIdCache::finish_frame(&mut self.global_ids);
3560 crate::fast::retained::finish_retained_frame(self);
3561 self.next_frame.finish(&mut self.rendered_frame);
3562
3563 self.invalidator.set_phase(DrawPhase::Focus);
3564 let previous_focus_path = self.rendered_frame.focus_path();
3565 let previous_window_active = self.rendered_frame.window_active;
3566 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
3567 self.next_frame.clear();
3568 let current_focus_path = self.rendered_frame.focus_path();
3569 let current_window_active = self.rendered_frame.window_active;
3570 let mut focus_before_listeners = self.focus;
3571
3572 if previous_focus_path != current_focus_path
3573 || previous_window_active != current_window_active
3574 {
3575 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
3576 self.focus_lost_path = previous_focus_path.clone();
3577 self.focus_lost_listeners
3578 .clone()
3579 .retain(&(), |listener| listener(self, cx));
3580 self.focus_lost_path = SmallVec::new();
3581 focus_before_listeners = self.focus;
3586 }
3587
3588 let event = WindowFocusEvent {
3589 previous_focus_path: if previous_window_active {
3590 previous_focus_path
3591 } else {
3592 Default::default()
3593 },
3594 current_focus_path: if current_window_active {
3595 current_focus_path
3596 } else {
3597 Default::default()
3598 },
3599 };
3600 self.focus_listeners
3601 .clone()
3602 .retain(&(), |listener| listener(&event, self, cx));
3603 }
3604
3605 debug_assert!(self.rendered_entity_stack.is_empty());
3606 self.record_entities_accessed(cx);
3607 self.reset_cursor_style(cx);
3608 self.refreshing = false;
3609 self.invalidator.set_phase(DrawPhase::None);
3610 if self.focus != focus_before_listeners {
3615 self.refresh();
3616 }
3617 self.needs_present.set(true);
3618
3619 #[cfg(feature = "profiler")]
3620 {
3621 self.window_profiler
3622 .set_refresh_interval(self.refresh_interval(cx));
3623 let draw_duration = self
3624 .window_profiler
3625 .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
3626 self.debug_frame_overlay.record_frame(draw_duration);
3627 }
3628
3629 arena_scope.exit(&cx.element_arena)
3632 }
3633
3634 fn record_entities_accessed(&mut self, cx: &mut App) {
3635 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3636 let mut entities = mem::take(entities_ref.deref_mut());
3637 let handle = self.handle;
3638 cx.record_entities_accessed(
3639 handle,
3640 self.invalidator.clone(),
3642 &entities,
3643 );
3644 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3645 mem::swap(&mut entities, entities_ref.deref_mut());
3646 }
3647
3648 fn invalidate_entities(&mut self) {
3649 let mut views = self.invalidator.take_views();
3650 crate::fast::retained::RetainedState::note_notified(&mut self.retained_state, &views);
3651 for entity in views.drain() {
3652 self.mark_view_dirty(entity);
3653 }
3654 self.invalidator.replace_views(views);
3655 }
3656
3657 #[profiling::function]
3658 fn present(&mut self) {
3659 #[cfg(feature = "profiler")]
3660 let _foreground_turn = profiler::journal::foreground_turn();
3661 #[cfg(feature = "profiler")]
3662 let present_start = Instant::now();
3663 crate::fast::composition::present(self);
3664 #[cfg(feature = "profiler")]
3665 self.window_profiler.record_present(
3666 present_start,
3667 Instant::now(),
3668 self.active.get(),
3669 !self.next_frame_callbacks.borrow().is_empty(),
3670 );
3671 self.needs_present.set(false);
3672 profiling::finish_frame!();
3673 }
3674
3675 #[cfg(all(test, feature = "profiler"))]
3677 pub fn present_if_needed(&mut self) {
3678 if self.needs_present.get() {
3679 self.present();
3680 }
3681 }
3682
3683 #[cfg(feature = "profiler")]
3685 pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
3686 self.window_profiler.input_latency_snapshot()
3687 }
3688
3689 #[cfg(feature = "profiler")]
3691 pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
3692 self.window_profiler.frame_duration_snapshot()
3693 }
3694
3695 #[cfg(feature = "profiler")]
3697 pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
3698 self.debug_frame_overlay.mode()
3699 }
3700
3701 #[cfg(feature = "profiler")]
3703 pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
3704 self.debug_frame_overlay.set_mode(mode);
3705 self.refresh();
3706 }
3707
3708 #[cfg(feature = "profiler")]
3711 pub fn cycle_debug_frame_overlay_mode(&mut self) {
3712 self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
3713 }
3714
3715 #[cfg(feature = "profiler")]
3718 pub fn reset_debug_frame_overlay_stats(&mut self) {
3719 self.debug_frame_overlay.reset_stats();
3720 self.refresh();
3721 }
3722
3723 fn draw_roots(&mut self, cx: &mut App) {
3724 crate::fast::retained::begin_frame(self, cx);
3725 self.invalidator.set_phase(DrawPhase::Prepaint);
3726 self.tooltip_bounds.take();
3727
3728 self.a11y.sync_active_flag();
3729 if self.a11y.is_active() {
3730 self.a11y.begin_frame();
3731 }
3732
3733 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
3734 let root_size = {
3735 #[cfg(any(feature = "inspector", debug_assertions))]
3736 {
3737 if self.inspector.is_some() {
3738 let mut size = self.viewport_size;
3739 size.width = (size.width - _inspector_width).max(px(0.0));
3740 size
3741 } else {
3742 self.viewport_size
3743 }
3744 }
3745 #[cfg(not(any(feature = "inspector", debug_assertions)))]
3746 {
3747 self.viewport_size
3748 }
3749 };
3750
3751 let scale_factor = self.scale_factor();
3755 #[cfg(feature = "profiler")]
3756 let request_layout_start = Instant::now();
3757 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
3758 let root_layout_id = root_element.request_layout(self, cx);
3759 crate::fast::stats::FramePhaseTimes::end_build(&mut self.fast_layout.phase_times);
3760 #[cfg(feature = "profiler")]
3761 let prepaint_start = Instant::now();
3762 self.layout_engine
3763 .as_mut()
3764 .unwrap()
3765 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
3766 crate::fast::composition::begin_base_prepaint(self);
3767 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3768
3769 #[cfg(any(feature = "inspector", debug_assertions))]
3770 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
3771
3772 crate::fast::composition::begin_overlay_prepaint(self);
3773 self.prepaint_deferred_draws(cx);
3774
3775 let mut prompt_element = None;
3776 let mut active_drag_element = None;
3777 let mut tooltip_element = None;
3778 if let Some(prompt) = self.prompt.take() {
3779 let mut element = prompt.view.any_view().into_any_element();
3780 let prompt_layout_id = element.request_layout(self, cx);
3781 self.layout_engine
3782 .as_mut()
3783 .unwrap()
3784 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
3785 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3786 prompt_element = Some(element);
3787 self.prompt = Some(prompt);
3788 } else if let Some(active_drag) = cx.active_drag.take() {
3789 let mut element = active_drag.view.clone().into_any_element();
3790 let offset = self.mouse_position() - active_drag.cursor_offset;
3791 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
3792 active_drag_element = Some(element);
3793 cx.active_drag = Some(active_drag);
3794 } else {
3795 tooltip_element = self.prepaint_tooltip(cx);
3796 }
3797
3798 crate::fast::stats::FramePhaseTimes::end_prepaint(&mut self.fast_layout.phase_times);
3799 crate::fast::composition::finish_input(self);
3800 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
3801
3802 #[cfg(feature = "profiler")]
3804 let paint_start = Instant::now();
3805 self.invalidator.set_phase(DrawPhase::Paint);
3806 crate::fast::composition::begin_base(self);
3807 root_element.paint(self, cx);
3808
3809 #[cfg(any(feature = "inspector", debug_assertions))]
3810 self.paint_inspector(inspector_element, cx);
3811
3812 crate::fast::composition::begin_overlay(self);
3813 self.paint_deferred_draws(cx);
3814
3815 if let Some(mut prompt_element) = prompt_element {
3816 prompt_element.paint(self, cx);
3817 } else if let Some(mut drag_element) = active_drag_element {
3818 drag_element.paint(self, cx);
3819 } else if let Some(mut tooltip_element) = tooltip_element {
3820 tooltip_element.paint(self, cx);
3821 }
3822
3823 #[cfg(any(feature = "inspector", debug_assertions))]
3824 self.paint_inspector_hitbox(cx);
3825 crate::fast::stats::FramePhaseTimes::end_paint(&mut self.fast_layout.phase_times);
3826
3827 #[cfg(feature = "profiler")]
3828 self.window_profiler
3829 .record_draw_phases(profiler::DrawPhases {
3830 request_layout: prepaint_start.duration_since(request_layout_start),
3831 prepaint: paint_start.duration_since(prepaint_start),
3832 paint: Instant::now().duration_since(paint_start),
3833 });
3834
3835 let a11y_active_start_of_frame = self.a11y.is_active();
3837 self.a11y.sync_active_flag();
3838 let a11y_active_end_of_frame = self.a11y.is_active();
3839
3840 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
3841
3842 if a11y_active_start_of_frame {
3843 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
3846 viewport_size: self.viewport_size,
3847 scale_factor: self.scale_factor,
3848 tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
3849 };
3850 let tree_update = self.a11y.end_frame(frame_info);
3852
3853 if should_send_a11y_update {
3854 log::debug!(
3855 "Sending a11y tree update: {} nodes",
3856 tree_update.nodes.len()
3857 );
3858 self.platform_window.a11y_tree_update(tree_update);
3859 }
3860 }
3861 }
3862
3863 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
3864 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
3866 let Some(Some(tooltip_request)) = self
3867 .next_frame
3868 .tooltip_requests
3869 .get(tooltip_request_index)
3870 .cloned()
3871 else {
3872 log::error!("Unexpectedly absent TooltipRequest");
3873 continue;
3874 };
3875 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
3876 let mouse_position = tooltip_request.tooltip.mouse_position;
3877 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
3878
3879 let mut tooltip_bounds =
3880 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
3881 let window_bounds = Bounds {
3882 origin: Point::default(),
3883 size: self.viewport_size(),
3884 };
3885
3886 if tooltip_bounds.right() > window_bounds.right() {
3887 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
3888 if new_x >= Pixels::ZERO {
3889 tooltip_bounds.origin.x = new_x;
3890 } else {
3891 tooltip_bounds.origin.x = cmp::max(
3892 Pixels::ZERO,
3893 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
3894 );
3895 }
3896 }
3897
3898 if tooltip_bounds.bottom() > window_bounds.bottom() {
3899 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
3900 if new_y >= Pixels::ZERO {
3901 tooltip_bounds.origin.y = new_y;
3902 } else {
3903 tooltip_bounds.origin.y = cmp::max(
3904 Pixels::ZERO,
3905 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
3906 );
3907 }
3908 }
3909
3910 let is_visible =
3914 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
3915 if !is_visible {
3916 continue;
3917 }
3918
3919 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
3920 element.prepaint(window, cx)
3921 });
3922
3923 self.tooltip_bounds = Some(TooltipBounds {
3924 id: tooltip_request.id,
3925 bounds: tooltip_bounds,
3926 });
3927 return Some(element);
3928 }
3929 None
3930 }
3931
3932 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
3933 assert_eq!(self.element_id_stack.len(), 0);
3934
3935 let mut round_start = 0;
3946 let mut depth = 0;
3947 loop {
3948 let round_end = self.next_frame.deferred_draws.len();
3949 if round_start == round_end {
3950 break;
3951 }
3952 assert!(depth < 10, "Exceeded maximum (10) deferred depth");
3954 depth += 1;
3955
3956 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
3958 traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3959
3960 for deferred_draw_ix in traversal_order {
3961 let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
3962 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
3963 self.element_id_stack
3964 .clone_from(&deferred_draw.element_id_stack);
3965 self.text_style_stack
3966 .clone_from(&deferred_draw.text_style_stack);
3967 (
3968 deferred_draw.element.take(),
3969 deferred_draw.parent_node,
3970 deferred_draw.current_view,
3971 deferred_draw.rem_size,
3972 deferred_draw.absolute_offset,
3973 deferred_draw.prepaint_range.clone(),
3974 )
3975 };
3976 self.next_frame.dispatch_tree.set_active_node(parent_node);
3977
3978 let prepaint_start = self.prepaint_index();
3979 if let Some(mut element) = element {
3980 let recording =
3981 crate::fast::retained::begin_deferred_prepaint(self, deferred_draw_ix, cx);
3982 self.with_rendered_view(current_view, |window| {
3983 window.with_rem_size(Some(rem_size), |window| {
3984 window.with_absolute_element_offset(absolute_offset, |window| {
3985 element.prepaint(window, cx);
3986 });
3987 });
3988 });
3989 crate::fast::retained::finish_deferred(self, recording, cx);
3990 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
3991 } else {
3992 self.reuse_prepaint(prepaint_range);
3993 }
3994 let prepaint_end = self.prepaint_index();
3995 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
3996 prepaint_start..prepaint_end;
3997 }
3998
3999 self.element_id_stack.clear();
4000 self.text_style_stack.clear();
4001 round_start = round_end;
4002 }
4003 }
4004
4005 fn paint_deferred_draws(&mut self, cx: &mut App) {
4006 assert_eq!(self.element_id_stack.len(), 0);
4007
4008 if self.next_frame.deferred_draws.len() == 0 {
4011 return;
4012 }
4013
4014 let traversal_order = self.deferred_draw_traversal_order();
4015 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
4016 for deferred_draw_ix in traversal_order {
4017 let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
4018 self.element_id_stack
4019 .clone_from(&deferred_draw.element_id_stack);
4020 self.next_frame
4021 .dispatch_tree
4022 .set_active_node(deferred_draw.parent_node);
4023
4024 let paint_start = self.paint_index();
4025 let content_mask = deferred_draw.content_mask;
4026 if let Some(element) = deferred_draw.element.as_mut() {
4027 let enclosing = &deferred_draw.enclosing_retained;
4028 let recording = crate::fast::retained::begin_deferred_paint(self, enclosing, cx);
4029 self.with_rendered_view(deferred_draw.current_view, |window| {
4030 window.with_content_mask(content_mask, |window| {
4031 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
4032 element.paint(window, cx);
4033 });
4034 })
4035 });
4036 crate::fast::retained::finish_deferred(self, recording, cx);
4037 } else {
4038 self.reuse_paint(deferred_draw.paint_range.clone());
4039 }
4040 let paint_end = self.paint_index();
4041 deferred_draw.paint_range = paint_start..paint_end;
4042 }
4043 self.next_frame.deferred_draws = deferred_draws;
4044 self.element_id_stack.clear();
4045 }
4046
4047 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
4048 let deferred_count = self.next_frame.deferred_draws.len();
4049 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
4050 sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
4051 sorted_indices
4052 }
4053
4054 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
4055 PrepaintStateIndex {
4056 hitboxes_index: self.next_frame.hitboxes.len(),
4057 tooltips_index: self.next_frame.tooltip_requests.len(),
4058 deferred_draws_index: self.next_frame.deferred_draws.len(),
4059 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
4060 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
4061 line_layout_index: self.text_system.layout_index(),
4062 fast_a11y_index: crate::fast::a11y::ops_index(self),
4063 }
4064 }
4065
4066 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
4067 crate::fast::a11y::reuse_prepaint(self, &range);
4068 self.next_frame.hitboxes.extend(
4069 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
4070 .iter()
4071 .cloned(),
4072 );
4073 self.next_frame.tooltip_requests.extend(
4074 self.rendered_frame.tooltip_requests
4075 [range.start.tooltips_index..range.end.tooltips_index]
4076 .iter_mut()
4077 .map(|request| request.take()),
4078 );
4079 self.next_frame.accessed_element_states.extend(
4080 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
4081 ..range.end.accessed_element_states_index]
4082 .iter()
4083 .map(|(id, type_id)| (id.clone(), *type_id)),
4084 );
4085 self.text_system
4086 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
4087
4088 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
4089 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
4090 &mut self.rendered_frame.dispatch_tree,
4091 self.focus,
4092 );
4093
4094 if reused_subtree.contains_focus() {
4095 self.next_frame.focus = self.focus;
4096 }
4097
4098 self.next_frame.deferred_draws.extend(
4099 self.rendered_frame.deferred_draws
4100 [range.start.deferred_draws_index..range.end.deferred_draws_index]
4101 .iter()
4102 .map(|deferred_draw| DeferredDraw {
4103 current_view: deferred_draw.current_view,
4104 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
4105 element_id_stack: deferred_draw.element_id_stack.clone(),
4106 text_style_stack: deferred_draw.text_style_stack.clone(),
4107 content_mask: deferred_draw.content_mask,
4108 rem_size: deferred_draw.rem_size,
4109 priority: deferred_draw.priority,
4110 element: None,
4111 absolute_offset: deferred_draw.absolute_offset,
4112 prepaint_range: deferred_draw.prepaint_range.clone(),
4113 paint_range: deferred_draw.paint_range.clone(),
4114 enclosing_retained: crate::fast::retained::EnclosingRetained::default(),
4115 }),
4116 );
4117 }
4118
4119 pub(crate) fn paint_index(&self) -> PaintIndex {
4120 PaintIndex {
4121 scene_index: self.next_frame.scene.len(),
4122 #[cfg(any(test, feature = "test-support"))]
4123 debug_bounds_index: self.next_frame.debug_bounds_records.len(),
4124 fast: crate::fast::retained::FastPaintIndex::new(self),
4125 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
4126 input_handlers_index: self.next_frame.input_handlers.len(),
4127 cursor_styles_index: self.next_frame.cursor_styles.len(),
4128 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
4129 tab_handle_index: self.next_frame.tab_stops.paint_index(),
4130 line_layout_index: self.text_system.layout_index(),
4131 }
4132 }
4133
4134 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
4135 crate::fast::retained::reuse_paint_records(self, &range);
4136 crate::fast::composition::reuse_starts(self, &range);
4137 #[cfg(any(test, feature = "test-support"))]
4139 for (selector, bounds) in &self.rendered_frame.debug_bounds_records
4140 [range.start.debug_bounds_index..range.end.debug_bounds_index]
4141 {
4142 self.next_frame
4143 .record_debug_bounds(selector.clone(), *bounds);
4144 }
4145 self.next_frame.cursor_styles.extend(
4146 self.rendered_frame.cursor_styles
4147 [range.start.cursor_styles_index..range.end.cursor_styles_index]
4148 .iter()
4149 .cloned(),
4150 );
4151 self.next_frame.input_handlers.extend(
4152 self.rendered_frame.input_handlers
4153 [range.start.input_handlers_index..range.end.input_handlers_index]
4154 .iter_mut()
4155 .map(|handler| handler.take()),
4156 );
4157 self.next_frame.mouse_listeners.extend(
4158 self.rendered_frame.mouse_listeners
4159 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
4160 .iter_mut()
4161 .map(|listener| listener.take()),
4162 );
4163 self.next_frame.accessed_element_states.extend(
4164 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
4165 ..range.end.accessed_element_states_index]
4166 .iter()
4167 .map(|(id, type_id)| (id.clone(), *type_id)),
4168 );
4169 self.next_frame.tab_stops.replay(
4170 &self.rendered_frame.tab_stops.insertion_history
4171 [range.start.tab_handle_index..range.end.tab_handle_index],
4172 );
4173
4174 self.text_system
4175 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
4176 self.next_frame.scene.replay(
4177 range.start.scene_index..range.end.scene_index,
4178 &self.rendered_frame.scene,
4179 );
4180 }
4181
4182 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
4186 where
4187 F: FnOnce(&mut Self) -> R,
4188 {
4189 self.invalidator.debug_assert_paint_or_prepaint();
4190 if let Some(style) = style {
4191 self.text_style_stack.push(style);
4192 let result = f(self);
4193 self.text_style_stack.pop();
4194 result
4195 } else {
4196 f(self)
4197 }
4198 }
4199
4200 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
4203 self.invalidator.debug_assert_paint();
4204 self.next_frame.cursor_styles.push(CursorStyleRequest {
4205 hitbox_id: Some(hitbox.id),
4206 style,
4207 });
4208 }
4209
4210 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
4215 self.invalidator.debug_assert_paint();
4216 self.next_frame.cursor_styles.push(CursorStyleRequest {
4217 hitbox_id: None,
4218 style,
4219 })
4220 }
4221
4222 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
4225 self.invalidator.debug_assert_prepaint();
4226 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
4227 self.next_frame
4228 .tooltip_requests
4229 .push(Some(TooltipRequest { id, tooltip }));
4230 id
4231 }
4232
4233 #[inline]
4238 pub fn with_content_mask<R>(
4239 &mut self,
4240 mask: Option<ContentMask<Pixels>>,
4241 f: impl FnOnce(&mut Self) -> R,
4242 ) -> R {
4243 self.invalidator.debug_assert_paint_or_prepaint();
4244 if let Some(mask) = mask {
4245 let mask = mask.intersect(&self.content_mask());
4246 self.content_mask_stack.push(mask);
4247 let result = f(self);
4248 self.content_mask_stack.pop();
4249 result
4250 } else {
4251 f(self)
4252 }
4253 }
4254
4255 pub fn with_element_offset<R>(
4258 &mut self,
4259 offset: Point<Pixels>,
4260 f: impl FnOnce(&mut Self) -> R,
4261 ) -> R {
4262 self.invalidator.debug_assert_prepaint();
4263
4264 if offset.is_zero() {
4265 return f(self);
4266 };
4267
4268 let abs_offset = self.element_offset() + offset;
4269 self.with_absolute_element_offset(abs_offset, f)
4270 }
4271
4272 pub fn with_absolute_element_offset<R>(
4276 &mut self,
4277 offset: Point<Pixels>,
4278 f: impl FnOnce(&mut Self) -> R,
4279 ) -> R {
4280 self.invalidator.debug_assert_prepaint();
4281 self.element_offset_stack.push(offset);
4282 let result = f(self);
4283 self.element_offset_stack.pop();
4284 result
4285 }
4286
4287 pub(crate) fn with_element_opacity<R>(
4288 &mut self,
4289 opacity: Option<f32>,
4290 f: impl FnOnce(&mut Self) -> R,
4291 ) -> R {
4292 self.invalidator.debug_assert_paint_or_prepaint();
4293
4294 let Some(opacity) = opacity else {
4295 return f(self);
4296 };
4297
4298 let previous_opacity = self.element_opacity;
4299 self.element_opacity = previous_opacity * opacity;
4300 let result = f(self);
4301 self.element_opacity = previous_opacity;
4302 result
4303 }
4304
4305 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
4311 self.invalidator.debug_assert_prepaint();
4312 let index = self.prepaint_index();
4313 let result = f(self);
4314 if result.is_err() {
4315 self.next_frame.hitboxes.truncate(index.hitboxes_index);
4316 self.next_frame
4317 .tooltip_requests
4318 .truncate(index.tooltips_index);
4319 self.next_frame
4320 .deferred_draws
4321 .truncate(index.deferred_draws_index);
4322 self.next_frame
4323 .dispatch_tree
4324 .truncate(index.dispatch_tree_index);
4325 self.next_frame
4326 .accessed_element_states
4327 .truncate(index.accessed_element_states_index);
4328 self.text_system.truncate_layouts(index.line_layout_index);
4329 }
4330 result
4331 }
4332
4333 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
4339 self.invalidator.debug_assert_prepaint();
4340 self.requested_autoscroll = Some(bounds);
4341 }
4342
4343 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
4346 self.invalidator.debug_assert_prepaint();
4347 self.requested_autoscroll.take()
4348 }
4349
4350 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4356 cx.asset_entry::<A>(source).use_by(self.current_view())
4357 }
4358
4359 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
4365 cx.fetch_asset::<A>(source)
4366 }
4367 pub fn element_offset(&self) -> Point<Pixels> {
4370 self.invalidator.debug_assert_prepaint();
4371 self.element_offset_stack
4372 .last()
4373 .copied()
4374 .unwrap_or_default()
4375 }
4376
4377 #[inline]
4380 pub(crate) fn element_opacity(&self) -> f32 {
4381 self.invalidator.debug_assert_paint_or_prepaint();
4382 self.element_opacity
4383 }
4384
4385 pub fn content_mask(&self) -> ContentMask<Pixels> {
4387 self.invalidator.debug_assert_paint_or_prepaint();
4388 self.content_mask_stack
4389 .last()
4390 .cloned()
4391 .unwrap_or_else(|| ContentMask {
4392 bounds: Bounds {
4393 origin: Point::default(),
4394 size: self.viewport_size,
4395 },
4396 })
4397 }
4398
4399 pub fn with_element_namespace<R>(
4402 &mut self,
4403 element_id: impl Into<ElementId>,
4404 f: impl FnOnce(&mut Self) -> R,
4405 ) -> R {
4406 self.element_id_stack.push(element_id.into());
4407 let result = f(self);
4408 self.element_id_stack.pop();
4409 result
4410 }
4411
4412 pub fn use_keyed_state<S: 'static>(
4414 &mut self,
4415 key: impl Into<ElementId>,
4416 cx: &mut App,
4417 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4418 ) -> Entity<S> {
4419 let current_view = self.current_view();
4420 self.with_global_id(key.into(), |global_id, window| {
4421 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
4422 if let Some(state) = state {
4423 (state.clone(), state)
4424 } else {
4425 let new_state = cx.new(|cx| init(window, cx));
4426 Self::observe_keyed_state(&new_state, current_view, cx);
4427 (new_state.clone(), new_state)
4428 }
4429 })
4430 })
4431 }
4432
4433 #[track_caller]
4439 pub fn use_state<S: 'static>(
4440 &mut self,
4441 cx: &mut App,
4442 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4443 ) -> Entity<S> {
4444 self.use_keyed_state(
4445 ElementId::CodeLocation(*core::panic::Location::caller()),
4446 cx,
4447 init,
4448 )
4449 }
4450
4451 #[inline(always)]
4456 pub fn with_element_state<S, R>(
4457 &mut self,
4458 global_id: &GlobalElementId,
4459 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
4460 ) -> R
4461 where
4462 S: 'static,
4463 {
4464 self.invalidator.debug_assert_paint_or_prepaint();
4465
4466 let (key, state) = self.take_element_state(global_id, TypeId::of::<S>());
4467
4468 if let Some(any) = state {
4469 let ElementStateBox {
4470 inner,
4471 #[cfg(debug_assertions)]
4472 type_name,
4473 } = any;
4474 let mut state_box = inner
4476 .downcast::<Option<S>>()
4477 .map_err(|_| {
4478 #[cfg(debug_assertions)]
4479 {
4480 anyhow::anyhow!(
4481 "invalid element state type for id, requested {:?}, actual: {:?}",
4482 std::any::type_name::<S>(),
4483 type_name
4484 )
4485 }
4486
4487 #[cfg(not(debug_assertions))]
4488 {
4489 anyhow::anyhow!(
4490 "invalid element state type for id, requested {:?}",
4491 std::any::type_name::<S>(),
4492 )
4493 }
4494 })
4495 .unwrap();
4496
4497 let state = state_box.take().expect(
4498 "reentrant call to with_element_state for the same state type and element id",
4499 );
4500 let (result, state) = f(Some(state), self);
4501 state_box.replace(state);
4502 self.insert_element_state(
4503 key,
4504 ElementStateBox {
4505 inner: state_box,
4506 #[cfg(debug_assertions)]
4507 type_name,
4508 },
4509 );
4510 result
4511 } else {
4512 let (result, state) = f(None, self);
4513 self.insert_element_state(
4514 key,
4515 ElementStateBox {
4516 inner: Box::new(Some(state)),
4517 #[cfg(debug_assertions)]
4518 type_name: std::any::type_name::<S>(),
4519 },
4520 );
4521 result
4522 }
4523 }
4524
4525 pub fn with_optional_element_state<S, R>(
4532 &mut self,
4533 global_id: Option<&GlobalElementId>,
4534 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
4535 ) -> R
4536 where
4537 S: 'static,
4538 {
4539 self.invalidator.debug_assert_paint_or_prepaint();
4540
4541 if let Some(global_id) = global_id {
4542 self.with_element_state(global_id, |state, cx| {
4543 let (result, state) = f(Some(state), cx);
4544 let state =
4545 state.expect("you must return some state when you pass some element id");
4546 (result, state)
4547 })
4548 } else {
4549 let (result, state) = f(None, self);
4550 debug_assert!(
4551 state.is_none(),
4552 "you must not return an element state when passing None for the global id"
4553 );
4554 result
4555 }
4556 }
4557
4558 #[inline]
4560 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
4561 if let Some(index) = index {
4562 self.next_frame.tab_stops.begin_group(index);
4563 let result = f(self);
4564 self.next_frame.tab_stops.end_group();
4565 result
4566 } else {
4567 f(self)
4568 }
4569 }
4570
4571 pub fn defer_draw(
4580 &mut self,
4581 element: AnyElement,
4582 absolute_offset: Point<Pixels>,
4583 priority: usize,
4584 content_mask: Option<ContentMask<Pixels>>,
4585 ) {
4586 self.invalidator.debug_assert_prepaint();
4587 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
4588 self.next_frame.deferred_draws.push(DeferredDraw {
4589 current_view: self.current_view(),
4590 parent_node,
4591 element_id_stack: self.element_id_stack.clone(),
4592 text_style_stack: self.text_style_stack.clone(),
4593 content_mask,
4594 rem_size: self.rem_size(),
4595 priority,
4596 element: Some(element),
4597 absolute_offset,
4598 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
4599 paint_range: PaintIndex::default()..PaintIndex::default(),
4600 enclosing_retained: crate::fast::retained::enclosing_retained(self),
4601 });
4602 }
4603
4604 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
4610 self.invalidator.debug_assert_paint();
4611
4612 let content_mask = self.content_mask();
4613 let clipped_bounds = bounds.intersect(&content_mask.bounds);
4614 if !clipped_bounds.is_empty() {
4615 self.next_frame
4616 .scene
4617 .push_layer(self.cover_bounds(clipped_bounds));
4618 }
4619
4620 let result = f(self);
4621
4622 if !clipped_bounds.is_empty() {
4623 self.next_frame.scene.pop_layer();
4624 }
4625
4626 result
4627 }
4628
4629 pub fn paint_drop_shadows(
4635 &mut self,
4636 bounds: Bounds<Pixels>,
4637 corner_radii: Corners<Pixels>,
4638 shadows: &[BoxShadow],
4639 ) {
4640 self.invalidator.debug_assert_paint();
4641
4642 let scale_factor = self.scale_factor();
4643 let content_mask = self.snapped_content_mask();
4644 let opacity = self.element_opacity();
4645 let element_bounds = self.cover_bounds(bounds);
4646 let element_corner_radii = corner_radii.scale(scale_factor);
4647 for shadow in shadows {
4648 if shadow.inset {
4649 continue;
4650 }
4651 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
4652 self.next_frame.scene.insert_primitive(Shadow {
4653 order: 0,
4654 blur_radius: shadow.blur_radius.scale(scale_factor),
4655 bounds: self.cover_bounds(shadow_bounds),
4656 content_mask,
4657 corner_radii: corner_radii.scale(scale_factor),
4658 color: shadow.color.opacity(opacity),
4659 element_bounds,
4660 element_corner_radii,
4661 inset: 0,
4662 pad: 0,
4663 });
4664 }
4665 }
4666
4667 pub fn paint_inset_shadows(
4671 &mut self,
4672 bounds: Bounds<Pixels>,
4673 corner_radii: Corners<Pixels>,
4674 shadows: &[BoxShadow],
4675 ) {
4676 self.invalidator.debug_assert_paint();
4677
4678 let scale_factor = self.scale_factor();
4679 let content_mask = self.snapped_content_mask();
4680 let opacity = self.element_opacity();
4681 let element_bounds = self.cover_bounds(bounds);
4682 let element_corner_radii = corner_radii.scale(scale_factor);
4683 for shadow in shadows {
4684 if !shadow.inset {
4685 continue;
4686 }
4687 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
4688 let zero = Pixels::ZERO;
4691 let hole_corner_radii = Corners {
4692 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
4693 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
4694 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
4695 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
4696 };
4697 self.next_frame.scene.insert_primitive(Shadow {
4698 order: 0,
4699 blur_radius: shadow.blur_radius.scale(scale_factor),
4700 bounds: self.cover_bounds(hole),
4701 content_mask,
4702 corner_radii: hole_corner_radii.scale(scale_factor),
4703 color: shadow.color.opacity(opacity),
4704 element_bounds,
4705 element_corner_radii,
4706 inset: 1,
4707 pad: 0,
4708 });
4709 }
4710 }
4711
4712 fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
4713 let radii = &quad.corner_radii;
4714 let widths = &quad.border_widths;
4715 let edge_radii = Edges {
4716 top: radii.top_left.max(radii.top_right),
4717 right: radii.top_right.max(radii.bottom_right),
4718 bottom: radii.bottom_left.max(radii.bottom_right),
4719 left: radii.top_left.max(radii.bottom_left),
4720 };
4721
4722 let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
4723 let inset_bounds = |top_left_inset, bottom_right_inset| {
4724 Bounds::from_corners(
4725 quad.bounds.origin + top_left_inset + antialias_inset,
4726 quad.bounds.bottom_right() - bottom_right_inset - antialias_inset,
4727 )
4728 };
4729
4730 let horizontal_band = inset_bounds(
4733 point(widths.left, widths.top.max(edge_radii.top)),
4734 point(widths.right, widths.bottom.max(edge_radii.bottom)),
4735 );
4736 let vertical_band = inset_bounds(
4737 point(widths.left.max(edge_radii.left), widths.top),
4738 point(widths.right.max(edge_radii.right), widths.bottom),
4739 );
4740
4741 let area = |bounds: &Bounds<ScaledPixels>| {
4742 bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.)
4743 };
4744 if area(&horizontal_band) >= area(&vertical_band) {
4745 horizontal_band
4746 } else {
4747 vertical_band
4748 }
4749 }
4750
4751 pub fn paint_quad(&mut self, quad: PaintQuad) {
4761 self.invalidator.debug_assert_paint();
4762
4763 let opacity = self.element_opacity();
4764 let snapped_bounds = self.snap_bounds(quad.bounds);
4765 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
4766 let quad = Quad {
4767 order: 0,
4768 bounds: snapped_bounds,
4769 content_mask: self.snapped_content_mask(),
4770 background: quad.background.opacity(opacity),
4771 border_color: quad.border_color.opacity(opacity),
4772 corner_radii: quad.corner_radii.scale(self.scale_factor()),
4773 border_widths: snapped_border_widths,
4774 border_style: quad.border_style,
4775 };
4776
4777 if !quad.background.is_transparent() {
4778 self.next_frame.scene.insert_primitive(quad);
4779 return;
4780 }
4781
4782 let outer_bounds = quad.bounds;
4785 let inner_bounds = Self::largest_border_interior(&quad);
4786
4787 if inner_bounds.is_empty() {
4788 self.next_frame.scene.insert_primitive(quad);
4789 return;
4790 }
4791
4792 let strips = [
4793 Bounds::from_corners(
4795 outer_bounds.origin,
4796 point(outer_bounds.right(), inner_bounds.top()),
4797 ),
4798 Bounds::from_corners(
4800 point(outer_bounds.left(), inner_bounds.bottom()),
4801 outer_bounds.bottom_right(),
4802 ),
4803 Bounds::from_corners(
4805 point(outer_bounds.left(), inner_bounds.top()),
4806 inner_bounds.bottom_left(),
4807 ),
4808 Bounds::from_corners(
4810 inner_bounds.top_right(),
4811 point(outer_bounds.right(), inner_bounds.bottom()),
4812 ),
4813 ];
4814
4815 for strip in strips {
4816 let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
4817 if !content_mask_bounds.is_empty() {
4818 self.next_frame.scene.insert_primitive(Quad {
4819 content_mask: ContentMask {
4820 bounds: content_mask_bounds,
4821 },
4822 ..quad
4823 });
4824 }
4825 }
4826 }
4827
4828 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
4832 self.invalidator.debug_assert_paint();
4833
4834 let scale_factor = self.scale_factor();
4835 let content_mask = self.content_mask();
4836 let opacity = self.element_opacity();
4837 path.content_mask = content_mask;
4838 let color: Background = color.into();
4839 path.color = color.opacity(opacity);
4840 self.next_frame
4841 .scene
4842 .insert_primitive(crate::fast::layers::paint::snap_path(
4843 path.scale(scale_factor),
4844 ));
4845 }
4846
4847 pub fn paint_underline(
4851 &mut self,
4852 origin: Point<Pixels>,
4853 width: Pixels,
4854 style: &UnderlineStyle,
4855 ) {
4856 self.invalidator.debug_assert_paint();
4857 let underline = self.underline(origin, width, style);
4858 self.next_frame.scene.insert_primitive(underline);
4859 }
4860
4861 pub fn paint_strikethrough(
4865 &mut self,
4866 origin: Point<Pixels>,
4867 width: Pixels,
4868 style: &StrikethroughStyle,
4869 ) {
4870 self.invalidator.debug_assert_paint();
4871
4872 let scale_factor = self.scale_factor();
4873 let height = style.thickness;
4874 let bounds = Bounds {
4875 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4876 size: size(self.snap_stroke(width), self.snap_stroke(height)),
4877 };
4878 let opacity = self.element_opacity();
4879
4880 self.next_frame.scene.insert_primitive(Underline {
4881 order: 0,
4882 pad: 0,
4883 bounds,
4884 content_mask: self.snapped_content_mask(),
4885 thickness: self.snap_stroke(style.thickness),
4886 color: style.color.unwrap_or_default().opacity(opacity),
4887 wavy: false.into(),
4888 });
4889 }
4890
4891 pub fn paint_glyph(
4900 &mut self,
4901 origin: Point<Pixels>,
4902 font_id: FontId,
4903 glyph_id: GlyphId,
4904 font_size: Pixels,
4905 color: Hsla,
4906 ) -> Result<()> {
4907 self.invalidator.debug_assert_paint();
4908
4909 let element_opacity = self.element_opacity();
4910 let scale_factor = self.scale_factor();
4911 let glyph_origin = origin.scale(scale_factor);
4912
4913 let (integer_origin, subpixel_variant) = crate::fast::glyphs::quantize_origin(glyph_origin);
4914 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
4915 let dilation = self.text_system().glyph_dilation_for_color(color);
4916 let params = RenderGlyphParams {
4917 font_id,
4918 glyph_id,
4919 font_size,
4920 subpixel_variant,
4921 scale_factor,
4922 is_emoji: false,
4923 subpixel_rendering,
4924 dilation,
4925 };
4926
4927 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4928 if !raster_bounds.is_zero() {
4929 let tile = self
4930 .sprite_atlas
4931 .get_or_insert_with(params.clone().into(), &mut || {
4932 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4933 Ok(Some((size, Cow::Owned(bytes))))
4934 })?
4935 .expect("Callback above only errors or returns Some");
4936 let bounds = Bounds {
4937 origin: integer_origin + raster_bounds.origin.map(Into::into),
4938 size: tile.bounds.size.map(Into::into),
4939 };
4940 let content_mask = self.snapped_content_mask();
4941
4942 if subpixel_rendering {
4943 self.next_frame.scene.insert_primitive(SubpixelSprite {
4944 order: 0,
4945 pad: 0,
4946 bounds,
4947 content_mask,
4948 color: color.opacity(element_opacity),
4949 tile,
4950 transformation: TransformationMatrix::unit(),
4951 });
4952 } else {
4953 self.next_frame.scene.insert_primitive(MonochromeSprite {
4954 order: 0,
4955 pad: 0,
4956 bounds,
4957 content_mask,
4958 color: color.opacity(element_opacity),
4959 tile,
4960 transformation: TransformationMatrix::unit(),
4961 });
4962 }
4963 }
4964 Ok(())
4965 }
4966
4967 pub(crate) fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
4968 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
4969 return false;
4970 }
4971
4972 if !self.platform_window.is_subpixel_rendering_supported() {
4973 return false;
4974 }
4975
4976 let mode = match self.text_rendering_mode.get() {
4977 TextRenderingMode::PlatformDefault => self
4978 .text_system()
4979 .recommended_rendering_mode(font_id, font_size),
4980 mode => mode,
4981 };
4982
4983 mode == TextRenderingMode::Subpixel
4984 }
4985
4986 pub fn paint_emoji(
4995 &mut self,
4996 origin: Point<Pixels>,
4997 font_id: FontId,
4998 glyph_id: GlyphId,
4999 font_size: Pixels,
5000 ) -> Result<()> {
5001 self.invalidator.debug_assert_paint();
5002
5003 let scale_factor = self.scale_factor();
5004 let glyph_origin = origin.scale(scale_factor);
5005 let integer_origin = crate::fast::glyphs::quantize_emoji_origin(glyph_origin);
5006 let params = RenderGlyphParams {
5007 font_id,
5008 glyph_id,
5009 font_size,
5010 subpixel_variant: Default::default(),
5011 scale_factor,
5012 is_emoji: true,
5013 subpixel_rendering: false,
5014 dilation: 0,
5015 };
5016
5017 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
5018 if !raster_bounds.is_zero() {
5019 let tile = self
5020 .sprite_atlas
5021 .get_or_insert_with(params.clone().into(), &mut || {
5022 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
5023 Ok(Some((size, Cow::Owned(bytes))))
5024 })?
5025 .expect("Callback above only errors or returns Some");
5026
5027 let bounds = Bounds {
5028 origin: integer_origin + raster_bounds.origin.map(Into::into),
5029 size: tile.bounds.size.map(Into::into),
5030 };
5031 let content_mask = self.snapped_content_mask();
5032 let opacity = self.element_opacity();
5033
5034 self.next_frame.scene.insert_primitive(PolychromeSprite {
5035 order: 0,
5036 pad: 0,
5037 grayscale: false.into(),
5038 bounds,
5039 corner_radii: Default::default(),
5040 content_mask,
5041 tile,
5042 opacity,
5043 });
5044 }
5045 Ok(())
5046 }
5047
5048 pub fn paint_svg(
5052 &mut self,
5053 bounds: Bounds<Pixels>,
5054 path: SharedString,
5055 mut data: Option<&[u8]>,
5056 transformation: TransformationMatrix,
5057 color: Hsla,
5058 cx: &App,
5059 ) -> Result<()> {
5060 self.invalidator.debug_assert_paint();
5061
5062 let element_opacity = self.element_opacity();
5063 let bounds = self.snap_bounds(bounds);
5064
5065 let params = RenderSvgParams {
5066 path,
5067 size: bounds.size.map(|pixels| {
5068 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
5069 }),
5070 };
5071
5072 let Some(tile) =
5073 self.sprite_atlas
5074 .get_or_insert_with(params.clone().into(), &mut || {
5075 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
5076 else {
5077 return Ok(None);
5078 };
5079 Ok(Some((size, Cow::Owned(bytes))))
5080 })?
5081 else {
5082 return Ok(());
5083 };
5084 let content_mask = self.snapped_content_mask();
5085 let svg_bounds = Bounds {
5086 origin: bounds.center()
5087 - Point::new(
5088 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5089 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
5090 ),
5091 size: tile
5092 .bounds
5093 .size
5094 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
5095 };
5096 let final_bounds = svg_bounds
5097 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
5098 .map_size(|size| size.ceil());
5099
5100 self.next_frame.scene.insert_primitive(MonochromeSprite {
5101 order: 0,
5102 pad: 0,
5103 bounds: final_bounds,
5104 content_mask,
5105 color: color.opacity(element_opacity),
5106 tile,
5107 transformation,
5108 });
5109
5110 Ok(())
5111 }
5112
5113 pub fn paint_image(
5122 &mut self,
5123 bounds: Bounds<Pixels>,
5124 image_bounds: Bounds<Pixels>,
5125 corner_radii: Corners<Pixels>,
5126 data: Arc<RenderImage>,
5127 frame_index: usize,
5128 grayscale: bool,
5129 ) -> Result<()> {
5130 self.invalidator.debug_assert_paint();
5131
5132 let visible_bounds = bounds.intersect(&image_bounds);
5133 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
5134 return Ok(());
5135 }
5136 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
5137 return Ok(());
5138 }
5139
5140 let params = RenderImageParams {
5141 image_id: data.id,
5142 frame_index,
5143 };
5144
5145 let tile = self
5146 .sprite_atlas
5147 .get_or_insert_with(params.into(), &mut || {
5148 Ok(Some((
5149 data.size(frame_index),
5150 Cow::Borrowed(
5151 data.as_bytes(frame_index)
5152 .expect("It's the caller's job to pass a valid frame index"),
5153 ),
5154 )))
5155 })?
5156 .expect("Callback above only returns Some");
5157
5158 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
5159
5160 let sub_tile = if visible_bounds == image_bounds {
5161 tile
5162 } else {
5163 let x_offset_ratio =
5164 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
5165 let y_offset_ratio =
5166 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
5167 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
5168 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
5169
5170 let tile_origin_x = tile.bounds.origin.x.0;
5171 let tile_origin_y = tile.bounds.origin.y.0;
5172 let tile_width = tile.bounds.size.width.0;
5173 let tile_height = tile.bounds.size.height.0;
5174
5175 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
5176 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
5177 let sub_width = (width_ratio * tile_width as f32).round() as i32;
5178 let sub_height = (height_ratio * tile_height as f32).round() as i32;
5179
5180 let max_x = tile_origin_x + tile_width;
5181 let max_y = tile_origin_y + tile_height;
5182
5183 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
5184 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
5185 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
5186 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
5187
5188 AtlasTile {
5189 bounds: Bounds {
5190 origin: point(
5191 DevicePixels(clamped_origin_x),
5192 DevicePixels(clamped_origin_y),
5193 ),
5194 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
5195 },
5196 ..tile
5197 }
5198 };
5199
5200 let content_mask = self.snapped_content_mask();
5201 let corner_radii = corner_radii
5202 .clamp_radii_for_quad_size(visible_bounds.size)
5203 .scale(self.scale_factor());
5204 let opacity = self.element_opacity();
5205
5206 self.next_frame.scene.insert_primitive(PolychromeSprite {
5207 order: 0,
5208 pad: 0,
5209 grayscale: grayscale.into(),
5210 bounds: visible_bounds_snapped,
5211 content_mask,
5212 corner_radii,
5213 tile: sub_tile,
5214 opacity,
5215 });
5216 Ok(())
5217 }
5218
5219 #[cfg(any(target_os = "macos", target_os = "ios"))]
5223 pub fn paint_surface(
5224 &mut self,
5225 bounds: Bounds<Pixels>,
5226 image_buffer: CFRetained<CVPixelBuffer>,
5227 ) {
5228 use crate::PaintSurface;
5229
5230 self.invalidator.debug_assert_paint();
5231
5232 let bounds = self.snap_bounds(bounds);
5233 let content_mask = self.snapped_content_mask();
5234 self.next_frame.scene.insert_primitive(PaintSurface {
5235 order: 0,
5236 bounds,
5237 content_mask,
5238 image_buffer,
5239 });
5240 }
5241
5242 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
5244 for frame_index in 0..data.frame_count() {
5245 let params = RenderImageParams {
5246 image_id: data.id,
5247 frame_index,
5248 };
5249
5250 self.sprite_atlas.remove(¶ms.clone().into());
5251 }
5252
5253 Ok(())
5254 }
5255
5256 #[cfg(any(test, feature = "test-support"))]
5258 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
5259 data.frame_count() > 0
5260 && (0..data.frame_count()).all(|frame_index| {
5261 self.sprite_atlas.contains(
5262 &RenderImageParams {
5263 image_id: data.id,
5264 frame_index,
5265 }
5266 .into(),
5267 )
5268 })
5269 }
5270
5271 #[must_use]
5277 pub fn request_layout(
5278 &mut self,
5279 style: Style,
5280 children: impl IntoIterator<Item = LayoutId>,
5281 cx: &mut App,
5282 ) -> LayoutId {
5283 self.invalidator.debug_assert_prepaint();
5284
5285 cx.layout_id_buffer.clear();
5286 cx.layout_id_buffer.extend(children);
5287 let rem_size = self.rem_size();
5288 let scale_factor = self.scale_factor();
5289
5290 let fast_key = crate::fast::layout_key::layout_key(self);
5291 self.layout_engine.as_mut().unwrap().request_layout(
5292 fast_key,
5293 style,
5294 rem_size,
5295 scale_factor,
5296 &cx.layout_id_buffer,
5297 )
5298 }
5299
5300 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
5309 where
5310 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
5311 + 'static,
5312 {
5313 self.invalidator.debug_assert_prepaint();
5314
5315 let rem_size = self.rem_size();
5316 let scale_factor = self.scale_factor();
5317 let fast_key = crate::fast::layout_key::layout_key(self);
5318 self.layout_engine
5319 .as_mut()
5320 .unwrap()
5321 .request_measured_layout(fast_key, style, rem_size, scale_factor, measure)
5322 }
5323
5324 pub fn compute_layout(
5330 &mut self,
5331 layout_id: LayoutId,
5332 available_space: Size<AvailableSpace>,
5333 cx: &mut App,
5334 ) {
5335 self.invalidator.debug_assert_prepaint();
5336
5337 let mut layout_engine = self.layout_engine.take().unwrap();
5338 layout_engine.compute_layout(layout_id, available_space, self, cx);
5339 self.layout_engine = Some(layout_engine);
5340 }
5341
5342 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
5347 self.invalidator.debug_assert_prepaint();
5348
5349 let scale_factor = self.scale_factor();
5350 let mut bounds = self
5351 .layout_engine
5352 .as_mut()
5353 .unwrap()
5354 .layout_bounds(layout_id, scale_factor)
5355 .map(Into::into);
5356 let snapped_offset = self.pixel_snap_point(self.element_offset());
5357 bounds.origin += snapped_offset;
5358 bounds
5359 }
5360
5361 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
5367 self.invalidator.debug_assert_prepaint();
5368
5369 let content_mask = crate::fast::layers::input::hitbox_mask(self);
5370 let mut id = self.next_hitbox_id;
5371 self.next_hitbox_id = self.next_hitbox_id.next();
5372 let hitbox = Hitbox {
5373 id,
5374 bounds,
5375 content_mask,
5376 behavior,
5377 };
5378 self.next_frame.hitboxes.push(hitbox.clone());
5379 crate::fast::composition::record_input(self, id);
5380 hitbox
5381 }
5382
5383 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
5387 self.invalidator.debug_assert_paint();
5388 self.next_frame.window_control_hitboxes.push((area, hitbox));
5389 }
5390
5391 pub fn set_key_context(&mut self, context: KeyContext) {
5396 self.invalidator.debug_assert_paint();
5397 self.next_frame.dispatch_tree.set_key_context(context);
5398 }
5399
5400 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
5405 self.invalidator.debug_assert_prepaint();
5406 if focus_handle.is_focused(self) {
5407 self.next_frame.focus = Some(focus_handle.id);
5408 }
5409 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
5410 }
5411
5412 pub fn set_view_id(&mut self, view_id: EntityId) {
5418 self.invalidator.debug_assert_prepaint();
5419 self.next_frame.dispatch_tree.set_view_id(view_id);
5420 }
5421
5422 pub fn current_view(&self) -> EntityId {
5424 self.invalidator.debug_assert_paint_or_prepaint();
5425 self.rendered_entity_stack.last().copied().unwrap()
5426 }
5427
5428 #[inline]
5429 pub(crate) fn with_rendered_view<R>(
5430 &mut self,
5431 id: EntityId,
5432 f: impl FnOnce(&mut Self) -> R,
5433 ) -> R {
5434 self.rendered_entity_stack.push(id);
5435 let result = f(self);
5436 self.rendered_entity_stack.pop();
5437 result
5438 }
5439
5440 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
5442 where
5443 F: FnOnce(&mut Self) -> R,
5444 {
5445 if let Some(image_cache) = image_cache {
5446 self.image_cache_stack.push(image_cache);
5447 let result = f(self);
5448 self.image_cache_stack.pop();
5449 result
5450 } else {
5451 f(self)
5452 }
5453 }
5454
5455 pub fn handle_input(
5464 &mut self,
5465 focus_handle: &FocusHandle,
5466 input_handler: impl InputHandler,
5467 cx: &App,
5468 ) {
5469 self.invalidator.debug_assert_paint();
5470
5471 if focus_handle.is_focused(self) {
5472 let cx = self.to_async(cx);
5473 self.next_frame.input_handlers.push(Some(
5474 PlatformInputHandler::new(cx, Box::new(input_handler)).with_focus(focus_handle.id),
5475 ));
5476 }
5477 }
5478
5479 pub fn notify_text_input_changed(&self, focus_handle: &FocusHandle) {
5484 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
5485 self.platform_window
5486 .text_input_state_changed(TextInputStateChange::ContentChanged);
5487 }
5488 }
5489
5490 pub fn notify_text_selection_changed(&self, focus_handle: &FocusHandle) {
5495 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
5496 self.platform_window
5497 .text_input_state_changed(TextInputStateChange::SelectionChanged);
5498 }
5499 }
5500
5501 fn apply_text_input_configuration(&mut self, cx: &mut App) {
5506 let configuration = match self.platform_window.take_input_handler() {
5507 Some(mut input_handler) => {
5508 let configuration = input_handler.text_input_configuration(self, cx);
5509 self.platform_window.set_input_handler(input_handler);
5510 configuration
5511 }
5512 None => TextInputConfiguration::default(),
5513 };
5514 if self.last_text_input_configuration.as_ref() != Some(&configuration) {
5515 self.platform_window
5516 .set_text_input_configuration(configuration.clone());
5517 self.last_text_input_configuration = Some(configuration);
5518 }
5519 }
5520
5521 pub fn on_mouse_event<Event: MouseEvent>(
5527 &mut self,
5528 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5529 ) {
5530 self.invalidator.debug_assert_paint();
5531
5532 self.next_frame.mouse_listeners.push(Some(Box::new(
5533 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
5534 if let Some(event) = event.downcast_ref() {
5535 listener(event, phase, window, cx)
5536 }
5537 },
5538 )));
5539 }
5540
5541 pub fn on_key_event<Event: KeyEvent>(
5550 &mut self,
5551 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5552 ) {
5553 self.invalidator.debug_assert_paint();
5554
5555 self.next_frame.dispatch_tree.on_key_event(Rc::new(
5556 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
5557 if let Some(event) = event.downcast_ref::<Event>() {
5558 listener(event, phase, window, cx)
5559 }
5560 },
5561 ));
5562 }
5563
5564 pub fn on_modifiers_changed(
5571 &mut self,
5572 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
5573 ) {
5574 self.invalidator.debug_assert_paint();
5575
5576 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
5577 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
5578 listener(event, window, cx)
5579 },
5580 ));
5581 }
5582
5583 pub fn on_focus_in(
5587 &mut self,
5588 handle: &FocusHandle,
5589 cx: &mut App,
5590 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
5591 ) -> Subscription {
5592 let focus_id = handle.id;
5593 let (subscription, activate) =
5594 self.new_focus_listener(Box::new(move |event, window, cx| {
5595 if event.is_focus_in(focus_id) {
5596 listener(window, cx);
5597 }
5598 true
5599 }));
5600 cx.defer(move |_| activate());
5601 subscription
5602 }
5603
5604 pub fn on_focus_out(
5607 &mut self,
5608 handle: &FocusHandle,
5609 cx: &mut App,
5610 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
5611 ) -> Subscription {
5612 let focus_id = handle.id;
5613 let (subscription, activate) =
5614 self.new_focus_listener(Box::new(move |event, window, cx| {
5615 if let Some(blurred_id) = event.previous_focus_path.last().copied()
5616 && event.is_focus_out(focus_id)
5617 {
5618 let event = FocusOutEvent {
5619 blurred: WeakFocusHandle {
5620 id: blurred_id,
5621 handles: Arc::downgrade(&cx.focus_handles),
5622 },
5623 };
5624 listener(event, window, cx)
5625 }
5626 true
5627 }));
5628 cx.defer(move |_| activate());
5629 subscription
5630 }
5631
5632 fn reset_cursor_style(&self, cx: &mut App) {
5633 if self.is_window_hovered() {
5635 let style = self
5636 .rendered_frame
5637 .cursor_style(self)
5638 .unwrap_or(CursorStyle::Arrow);
5639 cx.platform.set_cursor_style(style);
5640 }
5641 }
5642
5643 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
5646 let keystroke = keystroke.with_simulated_ime();
5647 let result = self.dispatch_event(
5648 PlatformInput::KeyDown(KeyDownEvent {
5649 keystroke: keystroke.clone(),
5650 is_held: false,
5651 prefer_character_input: false,
5652 }),
5653 cx,
5654 );
5655 if !result.propagate {
5656 return true;
5657 }
5658
5659 if let Some(input) = keystroke.key_char
5660 && let Some(mut input_handler) = self.platform_window.take_input_handler()
5661 {
5662 input_handler.dispatch_input(&input, self, cx);
5663 self.platform_window.set_input_handler(input_handler);
5664 return true;
5665 }
5666
5667 false
5668 }
5669
5670 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
5673 self.highest_precedence_binding_for_action(action)
5674 .map(|binding| {
5675 binding
5676 .keystrokes()
5677 .iter()
5678 .map(ToString::to_string)
5679 .collect::<Vec<_>>()
5680 .join(" ")
5681 })
5682 .unwrap_or_else(|| action.name().to_string())
5683 }
5684
5685 #[profiling::function]
5687 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
5688 #[cfg(feature = "profiler")]
5689 self.window_profiler.begin_input(event.kind_name());
5690 let update_count_before = self.invalidator.update_count();
5691 let old_modality = self.last_input_modality;
5695 self.last_input_modality = match &event {
5696 PlatformInput::KeyDown(_) => InputModality::Keyboard,
5697 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
5698 PlatformInput::Touch(_) => InputModality::Touch,
5699 _ => self.last_input_modality,
5700 };
5701 if self.last_input_modality != old_modality {
5702 self.refresh();
5703 }
5704
5705 let ambient = crate::fast::dependencies::AmbientInput::of(self);
5706 cx.propagate_event = true;
5708 self.default_prevented = false;
5710
5711 let event = match event {
5712 PlatformInput::MouseMove(mouse_move) => {
5715 self.mouse_position = mouse_move.position;
5716 self.modifiers = mouse_move.modifiers;
5717 PlatformInput::MouseMove(mouse_move)
5718 }
5719 PlatformInput::MouseDown(mouse_down) => {
5720 self.mouse_position = mouse_down.position;
5721 self.modifiers = mouse_down.modifiers;
5722 PlatformInput::MouseDown(mouse_down)
5723 }
5724 PlatformInput::MouseUp(mouse_up) => {
5725 self.mouse_position = mouse_up.position;
5726 self.modifiers = mouse_up.modifiers;
5727 PlatformInput::MouseUp(mouse_up)
5728 }
5729 PlatformInput::MousePressure(mouse_pressure) => {
5730 PlatformInput::MousePressure(mouse_pressure)
5731 }
5732 PlatformInput::MouseExited(mouse_exited) => {
5733 self.modifiers = mouse_exited.modifiers;
5734 PlatformInput::MouseExited(mouse_exited)
5735 }
5736 PlatformInput::ModifiersChanged(modifiers_changed) => {
5737 self.modifiers = modifiers_changed.modifiers;
5738 self.capslock = modifiers_changed.capslock;
5739 PlatformInput::ModifiersChanged(modifiers_changed)
5740 }
5741 PlatformInput::ScrollWheel(scroll_wheel) => {
5742 self.mouse_position = scroll_wheel.position;
5743 self.modifiers = scroll_wheel.modifiers;
5744 PlatformInput::ScrollWheel(scroll_wheel)
5745 }
5746 PlatformInput::Pinch(pinch) => {
5747 self.mouse_position = pinch.position;
5748 self.modifiers = pinch.modifiers;
5749 PlatformInput::Pinch(pinch)
5750 }
5751 PlatformInput::FileDrop(file_drop) => match file_drop {
5754 FileDropEvent::Entered { position, paths } => {
5755 self.mouse_position = position;
5756 let source_window = self.handle.window_id();
5757 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
5758 cx.active_drag = Some(AnyDrag {
5759 value: Arc::new(paths.clone()),
5760 view: cx.new(|_| paths).into(),
5761 cursor_offset: position,
5762 cursor_style: None,
5763 external_payload_source: None,
5764 });
5765 }
5766 PlatformInput::MouseMove(MouseMoveEvent {
5767 position,
5768 pressed_button: Some(MouseButton::Left),
5769 modifiers: Modifiers::default(),
5770 })
5771 }
5772 FileDropEvent::Pending { position } => {
5773 self.mouse_position = position;
5774 PlatformInput::MouseMove(MouseMoveEvent {
5775 position,
5776 pressed_button: Some(MouseButton::Left),
5777 modifiers: Modifiers::default(),
5778 })
5779 }
5780 FileDropEvent::Submit { position } => {
5781 cx.activate(true);
5782 self.mouse_position = position;
5783 PlatformInput::MouseUp(MouseUpEvent {
5784 button: MouseButton::Left,
5785 position,
5786 modifiers: Modifiers::default(),
5787 click_count: 1,
5788 })
5789 }
5790 FileDropEvent::Exited => {
5791 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
5792 cx.active_drag.take();
5793 }
5794 self.refresh();
5795 PlatformInput::FileDrop(FileDropEvent::Exited)
5796 }
5797 FileDropEvent::Ended => {
5798 cx.end_platform_drag(self.handle.window_id());
5799 self.refresh();
5800 PlatformInput::FileDrop(FileDropEvent::Ended)
5801 }
5802 },
5803 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
5804 PlatformInput::LongPress(long_press) => {
5805 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
5806 long_press.start_position
5807 } else {
5808 long_press.position
5809 };
5810 if long_press.phase == crate::TouchPhase::Started {
5811 self.long_press_capture = None;
5812 }
5813 PlatformInput::LongPress(long_press)
5814 }
5815 PlatformInput::TouchDrag(touch_drag) => {
5816 self.mouse_position = touch_drag.start_position;
5817 PlatformInput::TouchDrag(touch_drag)
5818 }
5819 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
5820 };
5821 crate::fast::dependencies::AmbientInput::stamp_changes(ambient, self, cx);
5822 crate::fast::layers::input::before_dispatch(self, cx, &event);
5823
5824 let native_target = crate::fast::composition::event_target(self, &event);
5825 if let Some(any_mouse_event) = event.mouse_event() {
5826 self.dispatch_mouse_event(any_mouse_event, cx);
5827 } else if let Some(any_key_event) = event.keyboard_event() {
5828 self.dispatch_key_event(any_key_event, cx);
5829 } else if let Some(touch_event) = event.touch_event() {
5830 self.dispatch_touch_event(touch_event, cx);
5831 }
5832 crate::fast::composition::dispatch_native(
5833 self,
5834 &event,
5835 native_target,
5836 &mut cx.propagate_event,
5837 );
5838 crate::fast::layers::wheel::end_dispatch(self, cx);
5839 if let PlatformInput::LongPress(long_press) = &event {
5840 match long_press.phase {
5841 crate::TouchPhase::Started if !self.default_prevented => {
5842 self.long_press_capture = None;
5843 }
5844 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
5845 self.long_press_capture = None;
5846 }
5847 crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
5848 }
5849 }
5850
5851 self.promote_external_drag_to_platform(&event, cx);
5854
5855 let caused_invalidation = self.invalidator.update_count() > update_count_before;
5856 if caused_invalidation {
5857 self.input_rate_tracker.borrow_mut().record_input();
5858 }
5859 #[cfg(feature = "profiler")]
5860 self.window_profiler.end_input(caused_invalidation);
5861
5862 DispatchEventResult {
5863 propagate: cx.propagate_event,
5864 default_prevented: self.default_prevented,
5865 }
5866 }
5867
5868 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
5869 let PlatformInput::MouseMove(mouse_move) = event else {
5870 return;
5871 };
5872 if mouse_move.pressed_button != Some(MouseButton::Left) {
5873 return;
5874 }
5875 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
5876 return;
5877 }
5878 if !self.platform_window.can_start_external_drag() {
5879 return;
5880 }
5881 let Some(payload_source) = cx
5882 .active_drag
5883 .as_mut()
5884 .and_then(|drag| drag.external_payload_source.take())
5885 else {
5886 return;
5887 };
5888 let Some(payload) = payload_source(self, cx) else {
5889 return;
5890 };
5891 if self.platform_window.start_external_drag(&payload)
5892 && cx.hand_active_drag_to_platform(self.handle.window_id())
5893 {
5894 self.refresh();
5895 }
5896 }
5897
5898 pub fn touch_prediction_enabled(&self) -> bool {
5902 self.touch_prediction_enabled
5903 }
5904
5905 pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
5909 self.touch_prediction_enabled = enabled;
5910 }
5911
5912 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
5916 let mut event = event.clone();
5917 if !self.touch_prediction_enabled {
5918 event.predicted_position = None;
5919 }
5920 let recognized_gestures = self.touch_gestures.handle_event(&event);
5921 if event.phase == crate::TouchPhase::Started
5922 && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
5923 {
5924 self.dispatch_recognized_touch_gesture(touch_drag, cx);
5925 }
5926 if event.phase == crate::TouchPhase::Started
5927 && self.touch_gestures.pending_long_press().is_some()
5928 {
5929 self.long_press_capture = None;
5930 }
5931 let mut tapped = false;
5932 for gesture in recognized_gestures {
5933 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
5934 self.dispatch_recognized_touch_gesture(gesture, cx);
5935 }
5936 if event.phase == crate::TouchPhase::Started {
5937 self.schedule_long_press_timer(cx);
5938 } else if self.touch_gestures.pending_long_press().is_none() {
5939 self.long_press_timer.take();
5940 }
5941 if tapped && self.invalidator.is_dirty() {
5947 self.draw(cx).clear(cx);
5948 }
5949 if self.touch_gestures.has_momentum() {
5950 self.schedule_touch_momentum_tick();
5951 }
5952 }
5953
5954 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
5955 match gesture {
5956 RecognizedTouchGesture::Scroll(scroll_wheel) => {
5957 self.mouse_position = scroll_wheel.position;
5958 cx.propagate_event = true;
5959 self.dispatch_mouse_event(&scroll_wheel, cx);
5960 }
5961 RecognizedTouchGesture::Tap { down, up } => {
5962 self.mouse_position = up.position;
5963 cx.propagate_event = true;
5964 self.dispatch_mouse_event(&down, cx);
5965 cx.propagate_event = true;
5966 self.dispatch_mouse_event(&up, cx);
5967 }
5968 RecognizedTouchGesture::TouchDrag(touch_drag) => {
5969 self.mouse_position = touch_drag.start_position;
5970 cx.propagate_event = true;
5971 self.default_prevented = false;
5972 let started = touch_drag.phase == crate::TouchPhase::Started;
5973 self.dispatch_mouse_event(&touch_drag, cx);
5974 if started {
5975 self.touch_gestures
5976 .resolve_touch_drag(self.default_prevented);
5977 }
5978 }
5979 RecognizedTouchGesture::LongPress(long_press) => {
5980 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
5981 long_press.start_position
5982 } else {
5983 long_press.position
5984 };
5985 cx.propagate_event = true;
5986 self.default_prevented = false;
5987 let started = long_press.phase == crate::TouchPhase::Started;
5988 let ended = matches!(
5989 long_press.phase,
5990 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
5991 );
5992 self.dispatch_mouse_event(&long_press, cx);
5993 if started {
5994 let claimed = self.default_prevented;
5995 self.touch_gestures.resolve_long_press(claimed);
5996 if !claimed {
5997 self.long_press_capture = None;
5998 }
5999 }
6000 if ended {
6001 self.long_press_capture = None;
6002 }
6003 }
6004 }
6005 }
6006
6007 fn schedule_long_press_timer(&mut self, cx: &mut App) {
6008 self.long_press_timer.take();
6009 let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
6010 return;
6011 };
6012 self.long_press_timer = Some(self.spawn(cx, async move |cx| {
6013 cx.background_executor.timer(duration).await;
6014 cx.update(move |window, cx| {
6015 window.long_press_timer.take();
6016 if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
6017 window.dispatch_recognized_touch_gesture(gesture, cx);
6018 }
6019 })
6020 .log_err();
6021 }));
6022 }
6023
6024 fn schedule_touch_momentum_tick(&mut self) {
6025 self.on_next_frame(|window, cx| {
6026 if let Some(gesture) = window.touch_gestures.tick_momentum() {
6027 window.dispatch_recognized_touch_gesture(gesture, cx);
6028 }
6029 if window.touch_gestures.has_momentum() {
6030 window.schedule_touch_momentum_tick();
6031 }
6032 });
6033 }
6034
6035 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6036 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
6037 if hit_test != self.mouse_hit_test {
6038 self.mouse_hit_test = hit_test;
6039 self.reset_cursor_style(cx);
6040 }
6041
6042 #[cfg(any(feature = "inspector", debug_assertions))]
6043 if self.is_inspector_picking(cx) {
6044 self.handle_inspector_mouse_event(event, cx);
6045 return;
6047 }
6048
6049 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
6050
6051 for listener in &mut mouse_listeners {
6054 let listener = listener.as_mut().unwrap();
6055 listener(event, DispatchPhase::Capture, self, cx);
6056 if !cx.propagate_event {
6057 break;
6058 }
6059 }
6060
6061 if crate::fast::composition::bubble_mouse(self, event, cx) {
6063 for listener in mouse_listeners.iter_mut().rev() {
6064 let listener = listener.as_mut().unwrap();
6065 listener(event, DispatchPhase::Bubble, self, cx);
6066 if !cx.propagate_event {
6067 break;
6068 }
6069 }
6070 }
6071
6072 self.rendered_frame.mouse_listeners = mouse_listeners;
6073
6074 if cx.has_active_drag() {
6075 if event.is::<MouseMoveEvent>() {
6076 self.refresh();
6079 } else if event.is::<MouseUpEvent>() {
6080 cx.active_drag = None;
6083 self.refresh();
6084 }
6085 }
6086
6087 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
6089 self.captured_hitbox = None;
6090 }
6091 }
6092
6093 fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
6096 let prefer_character_input = event
6097 .downcast_ref::<KeyDownEvent>()
6098 .is_some_and(|key_down_event| key_down_event.prefer_character_input);
6099 if !prefer_character_input {
6100 return InputPreference::KeyBindings;
6101 }
6102 let Some(mut input_handler) = self.platform_window.take_input_handler() else {
6103 return InputPreference::KeyBindings;
6104 };
6105 let accepts_text_input = input_handler.accepts_text_input(self, cx);
6106 self.platform_window.set_input_handler(input_handler);
6107 if accepts_text_input {
6108 InputPreference::CharacterInput
6109 } else {
6110 InputPreference::KeyBindings
6111 }
6112 }
6113
6114 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
6115 if self.invalidator.is_dirty() {
6116 self.draw(cx).clear(cx);
6117 }
6118
6119 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6120 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6121
6122 let mut keystroke: Option<Keystroke> = None;
6123
6124 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
6125 if event.modifiers.number_of_modifiers() == 0
6126 && self.pending_modifier.modifiers.number_of_modifiers() == 1
6127 && !self.pending_modifier.saw_other_input
6128 {
6129 let key = match self.pending_modifier.modifiers {
6130 modifiers if modifiers.shift => Some("shift"),
6131 modifiers if modifiers.control => Some("control"),
6132 modifiers if modifiers.alt => Some("alt"),
6133 modifiers if modifiers.platform => Some("platform"),
6134 modifiers if modifiers.function => Some("function"),
6135 _ => None,
6136 };
6137 if let Some(key) = key {
6138 keystroke = Some(Keystroke {
6139 key: key.to_string(),
6140 key_char: None,
6141 modifiers: Modifiers::default(),
6142 });
6143 }
6144 }
6145
6146 if self.pending_modifier.modifiers.number_of_modifiers() == 0
6147 && event.modifiers.number_of_modifiers() == 1
6148 {
6149 self.pending_modifier.saw_other_input = false
6150 } else if event.modifiers.number_of_modifiers() > 1 {
6151 self.pending_modifier.saw_other_input = true
6152 }
6153 self.pending_modifier.modifiers = event.modifiers
6154 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
6155 self.pending_modifier.saw_other_input = true;
6156 keystroke = Some(key_down_event.keystroke.clone());
6157 if key_down_event.keystroke.key_char.is_some()
6158 && matches!(
6159 cx.cursor_hide_mode,
6160 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
6161 )
6162 {
6163 cx.platform.hide_cursor_until_mouse_moves();
6164 }
6165 }
6166
6167 let Some(keystroke) = keystroke else {
6168 self.finish_dispatch_key_event(
6169 event,
6170 None,
6171 InputPreference::KeyBindings,
6172 dispatch_path,
6173 self.context_stack(),
6174 cx,
6175 );
6176 return;
6177 };
6178
6179 let input_preference = self.input_preference(event, cx);
6180
6181 cx.propagate_event = true;
6182 self.dispatch_keystroke_interceptors(
6183 &keystroke,
6184 input_preference,
6185 self.context_stack(),
6186 cx,
6187 );
6188 if !cx.propagate_event {
6189 self.finish_dispatch_key_event(
6190 event,
6191 Some(&keystroke),
6192 input_preference,
6193 dispatch_path,
6194 self.context_stack(),
6195 cx,
6196 );
6197 return;
6198 }
6199
6200 let mut currently_pending = self.pending_input.take().unwrap_or_default();
6201 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
6202 currently_pending = PendingInput::default();
6203 }
6204
6205 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
6206 currently_pending.keystrokes,
6207 keystroke.clone(),
6208 &dispatch_path,
6209 );
6210
6211 if !match_result.to_replay.is_empty() {
6212 self.replay_pending_input(match_result.to_replay, cx);
6213 cx.propagate_event = true;
6214 }
6215
6216 if !match_result.pending.is_empty() {
6217 let previous_timeout = currently_pending.timeout.take();
6218 currently_pending.keystrokes = match_result.pending;
6219 currently_pending.focus = self.focus;
6220
6221 let text_input_requires_timeout = event
6222 .downcast_ref::<KeyDownEvent>()
6223 .filter(|key_down| key_down.keystroke.key_char.is_some())
6224 .and_then(|_| self.platform_window.take_input_handler())
6225 .map_or(false, |mut input_handler| {
6226 let accepts = input_handler.accepts_text_input(self, cx);
6227 self.platform_window.set_input_handler(input_handler);
6228 accepts
6229 });
6230
6231 let needs_timeout = previous_timeout.is_some()
6232 || match_result.pending_has_binding
6233 || text_input_requires_timeout;
6234 currently_pending.timeout = if needs_timeout {
6235 match previous_timeout {
6236 Some(mut timeout) if timeout.is_paused() => {
6237 timeout.reset_duration(PENDING_INPUT_TIMEOUT);
6238 Some(timeout)
6239 }
6240 previous_timeout => {
6241 drop(previous_timeout);
6242 Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
6243 }
6244 }
6245 } else {
6246 None
6247 };
6248 self.pending_input = Some(currently_pending);
6249 self.pending_input_changed(cx);
6250 cx.propagate_event = false;
6251 return;
6252 }
6253
6254 let input_preference = self.input_preference(event, cx);
6256 if input_preference == InputPreference::KeyBindings {
6257 for binding in match_result.bindings {
6258 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6259 if !cx.propagate_event {
6260 self.dispatch_keystroke_observers(
6261 &keystroke,
6262 input_preference,
6263 Some(binding.action.as_ref()),
6264 match_result.context_stack,
6265 cx,
6266 );
6267 self.pending_input_changed(cx);
6268 return;
6269 }
6270 }
6271 }
6272
6273 self.finish_dispatch_key_event(
6274 event,
6275 Some(&keystroke),
6276 input_preference,
6277 dispatch_path,
6278 match_result.context_stack,
6279 cx,
6280 );
6281 self.pending_input_changed(cx);
6282 }
6283
6284 fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
6285 let (started_at, task) = self.start_pending_input_timeout(duration, cx);
6286 PendingInputTimeout {
6287 duration,
6288 remaining: duration,
6289 state: PendingInputTimeoutState::Running { started_at, task },
6290 }
6291 }
6292
6293 fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
6294 let started_at = cx.background_executor().now();
6295 let task = self.spawn(cx, async move |cx| {
6296 cx.background_executor.timer(remaining).await;
6297 cx.update(move |window, cx| {
6298 let Some(currently_pending) = window
6299 .pending_input
6300 .take()
6301 .filter(|pending| pending.focus == window.focus)
6302 else {
6303 return;
6304 };
6305
6306 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
6307 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
6308
6309 let to_replay = window
6310 .rendered_frame
6311 .dispatch_tree
6312 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
6313
6314 window.pending_input_changed(cx);
6315 window.replay_pending_input(to_replay, cx)
6316 })
6317 .log_err();
6318 });
6319 (started_at, task)
6320 }
6321
6322 fn finish_dispatch_key_event(
6323 &mut self,
6324 event: &dyn Any,
6325 recognized_keystroke: Option<&Keystroke>,
6326 input_preference: InputPreference,
6327 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
6328 context_stack: Vec<KeyContext>,
6329 cx: &mut App,
6330 ) {
6331 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
6332 if !cx.propagate_event {
6333 return;
6334 }
6335
6336 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
6337 if !cx.propagate_event {
6338 return;
6339 }
6340
6341 if let Some(keystroke) = recognized_keystroke {
6342 self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
6343 }
6344 }
6345
6346 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
6347 self.pending_input_observers
6348 .clone()
6349 .retain(&(), |callback| callback(self, cx));
6350 }
6351
6352 fn defer_pending_input_changed(&self, cx: &mut App) {
6353 let window_handle = self.handle;
6356 cx.defer(move |cx| {
6357 window_handle
6358 .update(cx, |_, window, cx| {
6359 window.pending_input_changed(cx);
6360 })
6361 .ok();
6362 });
6363 }
6364
6365 fn dispatch_key_down_up_event(
6366 &mut self,
6367 event: &dyn Any,
6368 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6369 cx: &mut App,
6370 ) {
6371 for node_id in dispatch_path {
6373 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6374
6375 for key_listener in node.key_listeners.clone() {
6376 key_listener(event, DispatchPhase::Capture, self, cx);
6377 if !cx.propagate_event {
6378 return;
6379 }
6380 }
6381 }
6382
6383 for node_id in dispatch_path.iter().rev() {
6385 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6387 for key_listener in node.key_listeners.clone() {
6388 key_listener(event, DispatchPhase::Bubble, self, cx);
6389 if !cx.propagate_event {
6390 return;
6391 }
6392 }
6393 }
6394 }
6395
6396 fn dispatch_modifiers_changed_event(
6397 &mut self,
6398 event: &dyn Any,
6399 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6400 cx: &mut App,
6401 ) {
6402 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
6403 return;
6404 };
6405 for node_id in dispatch_path.iter().rev() {
6406 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6407 for listener in node.modifiers_changed_listeners.clone() {
6408 listener(event, self, cx);
6409 if !cx.propagate_event {
6410 return;
6411 }
6412 }
6413 }
6414 }
6415
6416 pub fn has_pending_keystrokes(&self) -> bool {
6418 self.pending_input().is_some()
6419 }
6420
6421 #[cfg(test)]
6422 pub(crate) fn pending_input_is_none(&self) -> bool {
6423 self.pending_input.is_none()
6424 }
6425
6426 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
6427 if self.pending_input.take().is_some() {
6428 self.defer_pending_input_changed(cx);
6429 }
6430 }
6431
6432 pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
6435 self.pending_input
6436 .as_ref()
6437 .filter(|pending_input| pending_input.focus == self.focus)
6438 .map(|pending_input| PendingInputStatus {
6439 keystrokes: pending_input.keystrokes.as_slice(),
6440 timeout: pending_input
6441 .timeout
6442 .as_ref()
6443 .map(PendingInputTimeout::status),
6444 })
6445 }
6446
6447 pub fn set_pending_input_timeout_paused<T: 'static>(
6452 &mut self,
6453 owner: &Entity<T>,
6454 paused: bool,
6455 cx: &mut App,
6456 ) -> bool {
6457 let owner_id = owner.entity_id();
6458 if !paused {
6459 return self.resume_pending_input_timeout(owner_id, cx);
6460 }
6461
6462 let timeout = self
6463 .pending_input
6464 .as_ref()
6465 .filter(|pending_input| pending_input.focus == self.focus)
6466 .and_then(|pending_input| pending_input.timeout.as_ref());
6467 let Some(timeout) = timeout else {
6468 return false;
6469 };
6470 if timeout.is_paused() {
6471 return false;
6472 }
6473
6474 let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
6475 window.resume_pending_input_timeout(owner_id, cx);
6476 });
6477 let now = cx.background_executor().now();
6478 let changed = self
6479 .pending_input
6480 .as_mut()
6481 .filter(|pending_input| pending_input.focus == self.focus)
6482 .and_then(|pending_input| pending_input.timeout.as_mut())
6483 .is_some_and(|timeout| {
6484 timeout.pause(
6485 PendingInputTimeoutPause {
6486 owner_id,
6487 _release_subscription: release_subscription,
6488 },
6489 now,
6490 )
6491 });
6492
6493 if changed {
6494 self.defer_pending_input_changed(cx);
6495 }
6496 changed
6497 }
6498
6499 fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
6500 let Some(remaining) = self
6501 .pending_input
6502 .as_ref()
6503 .and_then(|pending_input| pending_input.timeout.as_ref())
6504 .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
6505 .map(|timeout| timeout.remaining)
6506 else {
6507 return false;
6508 };
6509
6510 let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
6511 let changed = self
6512 .pending_input
6513 .as_mut()
6514 .and_then(|pending_input| pending_input.timeout.as_mut())
6515 .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
6516
6517 if changed {
6518 self.defer_pending_input_changed(cx);
6519 }
6520 changed
6521 }
6522
6523 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
6525 self.pending_input()
6526 .map(|pending_input| pending_input.keystrokes())
6527 }
6528
6529 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
6530 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6531 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6532
6533 'replay: for replay in replays {
6534 let event = KeyDownEvent {
6535 keystroke: replay.keystroke.clone(),
6536 is_held: false,
6537 prefer_character_input: true,
6538 };
6539
6540 cx.propagate_event = true;
6541 for binding in replay.bindings {
6542 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6543 if !cx.propagate_event {
6544 self.dispatch_keystroke_observers(
6545 &replay.keystroke,
6546 InputPreference::KeyBindings,
6547 Some(binding.action.as_ref()),
6548 Vec::default(),
6549 cx,
6550 );
6551 continue 'replay;
6552 }
6553 }
6554
6555 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
6556 if !cx.propagate_event {
6557 continue 'replay;
6558 }
6559 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
6560 && let Some(mut input_handler) = self.platform_window.take_input_handler()
6561 {
6562 input_handler.dispatch_input(&input, self, cx);
6563 self.platform_window.set_input_handler(input_handler)
6564 }
6565 }
6566 }
6567
6568 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
6569 focus_id
6570 .and_then(|focus_id| {
6571 self.rendered_frame
6572 .dispatch_tree
6573 .focusable_node_id(focus_id)
6574 })
6575 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
6576 }
6577
6578 fn dispatch_action_on_node(
6579 &mut self,
6580 node_id: DispatchNodeId,
6581 action: &dyn Action,
6582 cx: &mut App,
6583 ) {
6584 self.dispatch_action_on_node_inner(node_id, action, cx);
6585
6586 if !cx.propagate_event
6587 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
6588 && self.last_input_was_keyboard()
6589 {
6590 cx.platform.hide_cursor_until_mouse_moves();
6591 }
6592 }
6593
6594 fn dispatch_action_on_node_inner(
6595 &mut self,
6596 node_id: DispatchNodeId,
6597 action: &dyn Action,
6598 cx: &mut App,
6599 ) {
6600 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6601
6602 cx.propagate_event = true;
6604 if let Some(mut global_listeners) = cx
6605 .global_action_listeners
6606 .remove(&action.as_any().type_id())
6607 {
6608 for listener in &global_listeners {
6609 #[cfg(feature = "profiler")]
6610 self.window_profiler.begin_action_handler(action, cx);
6611 listener(action.as_any(), DispatchPhase::Capture, cx);
6612 #[cfg(feature = "profiler")]
6613 self.window_profiler.end_action_handler();
6614 if !cx.propagate_event {
6615 break;
6616 }
6617 }
6618
6619 global_listeners.extend(
6620 cx.global_action_listeners
6621 .remove(&action.as_any().type_id())
6622 .unwrap_or_default(),
6623 );
6624
6625 cx.global_action_listeners
6626 .insert(action.as_any().type_id(), global_listeners);
6627 }
6628
6629 if !cx.propagate_event {
6630 return;
6631 }
6632
6633 for node_id in &dispatch_path {
6635 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6636 for DispatchActionListener {
6637 action_type,
6638 listener,
6639 } in node.action_listeners.clone()
6640 {
6641 let any_action = action.as_any();
6642 if action_type == any_action.type_id() {
6643 #[cfg(feature = "profiler")]
6644 self.window_profiler.begin_action_handler(action, cx);
6645 listener(any_action, DispatchPhase::Capture, self, cx);
6646 #[cfg(feature = "profiler")]
6647 self.window_profiler.end_action_handler();
6648
6649 if !cx.propagate_event {
6650 return;
6651 }
6652 }
6653 }
6654 }
6655
6656 for node_id in dispatch_path.iter().rev() {
6658 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6659 for DispatchActionListener {
6660 action_type,
6661 listener,
6662 } in node.action_listeners.clone()
6663 {
6664 let any_action = action.as_any();
6665 if action_type == any_action.type_id() {
6666 cx.propagate_event = false; #[cfg(feature = "profiler")]
6668 self.window_profiler.begin_action_handler(action, cx);
6669 listener(any_action, DispatchPhase::Bubble, self, cx);
6670 #[cfg(feature = "profiler")]
6671 self.window_profiler.end_action_handler();
6672
6673 if !cx.propagate_event {
6674 return;
6675 }
6676 }
6677 }
6678 }
6679
6680 if let Some(mut global_listeners) = cx
6682 .global_action_listeners
6683 .remove(&action.as_any().type_id())
6684 {
6685 for listener in global_listeners.iter().rev() {
6686 cx.propagate_event = false; #[cfg(feature = "profiler")]
6689 self.window_profiler.begin_action_handler(action, cx);
6690 listener(action.as_any(), DispatchPhase::Bubble, cx);
6691 #[cfg(feature = "profiler")]
6692 self.window_profiler.end_action_handler();
6693 if !cx.propagate_event {
6694 break;
6695 }
6696 }
6697
6698 global_listeners.extend(
6699 cx.global_action_listeners
6700 .remove(&action.as_any().type_id())
6701 .unwrap_or_default(),
6702 );
6703
6704 cx.global_action_listeners
6705 .insert(action.as_any().type_id(), global_listeners);
6706 }
6707 }
6708
6709 pub fn observe_global<G: Global>(
6712 &mut self,
6713 cx: &mut App,
6714 f: impl Fn(&mut Window, &mut App) + 'static,
6715 ) -> Subscription {
6716 let window_handle = self.handle;
6717 let (subscription, activate) = cx.global_observers.insert(
6718 TypeId::of::<G>(),
6719 Box::new(move |cx| {
6720 window_handle
6721 .update(cx, |_, window, cx| f(window, cx))
6722 .is_ok()
6723 }),
6724 );
6725 cx.defer(move |_| activate());
6726 subscription
6727 }
6728
6729 pub fn activate_window(&self) {
6731 self.platform_window.activate();
6732 }
6733
6734 pub fn request_attention(&self) {
6736 self.platform_window.request_attention();
6737 }
6738
6739 pub fn minimize_window(&self) {
6741 self.platform_window.minimize();
6742 }
6743
6744 pub fn toggle_fullscreen(&self) {
6746 self.platform_window.toggle_fullscreen();
6747 }
6748
6749 pub fn toggle_simple_fullscreen(&self) {
6754 self.platform_window.toggle_simple_fullscreen();
6755 }
6756
6757 pub fn invalidate_character_coordinates(&self) {
6759 self.on_next_frame(|window, cx| {
6760 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
6761 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
6762 window.platform_window.update_ime_position(bounds);
6763 }
6764 window.platform_window.set_input_handler(input_handler);
6765 }
6766 });
6767 }
6768
6769 pub fn prompt<T>(
6773 &mut self,
6774 level: PromptLevel,
6775 message: &str,
6776 detail: Option<&str>,
6777 answers: &[T],
6778 cx: &mut App,
6779 ) -> oneshot::Receiver<usize>
6780 where
6781 T: Clone + Into<PromptButton>,
6782 {
6783 let prompt_builder = cx.prompt_builder.take();
6784 let Some(prompt_builder) = prompt_builder else {
6785 unreachable!("Re-entrant window prompting is not supported by GPUI");
6786 };
6787
6788 let answers = answers
6789 .iter()
6790 .map(|answer| answer.clone().into())
6791 .collect::<Vec<_>>();
6792
6793 let receiver = match &prompt_builder {
6794 PromptBuilder::Default => self
6795 .platform_window
6796 .prompt(level, message, detail, &answers)
6797 .unwrap_or_else(|| {
6798 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6799 }),
6800 PromptBuilder::Custom(_) => {
6801 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6802 }
6803 };
6804
6805 cx.prompt_builder = Some(prompt_builder);
6806
6807 receiver
6808 }
6809
6810 fn build_custom_prompt(
6811 &mut self,
6812 prompt_builder: &PromptBuilder,
6813 level: PromptLevel,
6814 message: &str,
6815 detail: Option<&str>,
6816 answers: &[PromptButton],
6817 cx: &mut App,
6818 ) -> oneshot::Receiver<usize> {
6819 let (sender, receiver) = oneshot::channel();
6820 let handle = PromptHandle::new(sender);
6821 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
6822 self.prompt = Some(handle);
6823 receiver
6824 }
6825
6826 pub fn has_active_prompt(&self) -> bool {
6831 self.prompt.is_some()
6832 }
6833
6834 pub fn context_stack(&self) -> Vec<KeyContext> {
6836 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6837 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6838 dispatch_tree
6839 .dispatch_path(node_id)
6840 .iter()
6841 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
6842 .collect()
6843 }
6844
6845 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
6847 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6848 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
6849 for action_type in cx.global_action_listeners.keys() {
6850 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
6851 let action = cx.actions.build_action_type(action_type).ok();
6852 if let Some(action) = action {
6853 actions.insert(ix, action);
6854 }
6855 }
6856 }
6857 actions
6858 }
6859
6860 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
6863 self.rendered_frame
6864 .dispatch_tree
6865 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
6866 }
6867
6868 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
6871 self.rendered_frame
6872 .dispatch_tree
6873 .highest_precedence_binding_for_action(
6874 action,
6875 &self.rendered_frame.dispatch_tree.context_stack,
6876 )
6877 }
6878
6879 pub fn bindings_for_action_in_context(
6881 &self,
6882 action: &dyn Action,
6883 context: KeyContext,
6884 ) -> Vec<KeyBinding> {
6885 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6886 dispatch_tree.bindings_for_action(action, &[context])
6887 }
6888
6889 pub fn highest_precedence_binding_for_action_in_context(
6892 &self,
6893 action: &dyn Action,
6894 context: KeyContext,
6895 ) -> Option<KeyBinding> {
6896 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6897 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
6898 }
6899
6900 pub fn bindings_for_action_in(
6904 &self,
6905 action: &dyn Action,
6906 focus_handle: &FocusHandle,
6907 ) -> Vec<KeyBinding> {
6908 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6909 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
6910 return vec![];
6911 };
6912 dispatch_tree.bindings_for_action(action, &context_stack)
6913 }
6914
6915 pub fn highest_precedence_binding_for_action_in(
6919 &self,
6920 action: &dyn Action,
6921 focus_handle: &FocusHandle,
6922 ) -> Option<KeyBinding> {
6923 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6924 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
6925 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
6926 }
6927
6928 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
6930 self.rendered_frame
6931 .dispatch_tree
6932 .possible_next_bindings_for_input(input, &self.context_stack())
6933 }
6934
6935 fn context_stack_for_focus_handle(
6936 &self,
6937 focus_handle: &FocusHandle,
6938 ) -> Option<Vec<KeyContext>> {
6939 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6940 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
6941 let context_stack: Vec<_> = dispatch_tree
6942 .dispatch_path(node_id)
6943 .into_iter()
6944 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
6945 .collect();
6946 Some(context_stack)
6947 }
6948
6949 pub fn listener_for<T: 'static, E>(
6951 &self,
6952 view: &Entity<T>,
6953 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
6954 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
6955 let view = view.downgrade();
6956 move |e: &E, window: &mut Window, cx: &mut App| {
6957 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
6958 }
6959 }
6960
6961 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
6963 &self,
6964 entity: &Entity<E>,
6965 f: Callback,
6966 ) -> impl Fn(&mut Window, &mut App) + 'static {
6967 let entity = entity.downgrade();
6968 move |window: &mut Window, cx: &mut App| {
6969 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
6970 }
6971 }
6972
6973 pub fn on_window_should_close(
6976 &self,
6977 cx: &App,
6978 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
6979 ) {
6980 let mut cx = self.to_async(cx);
6981 self.platform_window.on_should_close(Box::new(move || {
6982 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
6983 }))
6984 }
6985
6986 pub fn on_action(
6995 &mut self,
6996 action_type: TypeId,
6997 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
6998 ) {
6999 self.invalidator.debug_assert_paint();
7000
7001 self.next_frame
7002 .dispatch_tree
7003 .on_action(action_type, Rc::new(listener));
7004 }
7005
7006 pub fn on_action_when(
7015 &mut self,
7016 condition: bool,
7017 action_type: TypeId,
7018 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
7019 ) {
7020 self.invalidator.debug_assert_paint();
7021
7022 if condition {
7023 self.next_frame
7024 .dispatch_tree
7025 .on_action(action_type, Rc::new(listener));
7026 }
7027 }
7028
7029 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
7032 self.platform_window.gpu_specs()
7033 }
7034
7035 pub fn titlebar_double_click(&self) {
7038 self.platform_window
7039 .titlebar_double_click(self.is_resizable, self.is_minimizable);
7040 }
7041
7042 pub fn window_title(&self) -> String {
7045 self.platform_window.get_title()
7046 }
7047
7048 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
7051 self.platform_window.tabbed_windows()
7052 }
7053
7054 pub fn tab_bar_visible(&self) -> bool {
7057 self.platform_window.tab_bar_visible()
7058 }
7059
7060 pub fn merge_all_windows(&self) {
7063 self.platform_window.merge_all_windows()
7064 }
7065
7066 pub fn move_tab_to_new_window(&self) {
7069 self.platform_window.move_tab_to_new_window()
7070 }
7071
7072 pub fn toggle_window_tab_overview(&self) {
7075 self.platform_window.toggle_window_tab_overview()
7076 }
7077
7078 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
7081 self.platform_window
7082 .set_tabbing_identifier(tabbing_identifier)
7083 }
7084
7085 pub fn play_system_bell(&self) {
7088 self.platform_window.play_system_bell()
7089 }
7090
7091 pub fn is_a11y_enabled(&self) -> bool {
7098 self.a11y.is_enabled()
7099 }
7100
7101 pub fn is_a11y_active(&self) -> bool {
7112 self.a11y.is_active()
7113 }
7114
7115 pub fn debug_a11y_tree_json(&self) -> Option<String> {
7117 self.a11y.debug_tree_json()
7118 }
7119
7120 pub fn on_a11y_action(
7126 &mut self,
7127 node_id: accesskit::NodeId,
7128 action: accesskit::Action,
7129 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
7130 ) {
7131 crate::fast::a11y::A11yLog::action(&mut self.a11y.nodes.fast, node_id, action);
7132 self.a11y
7133 .action_listeners
7134 .entry(node_id)
7135 .or_default()
7136 .push((action, Box::new(listener)));
7137 }
7138
7139 #[cfg(not(target_family = "wasm"))]
7140 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
7141 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
7144 let extra_data = request.data.as_ref();
7145 let mut matched = false;
7146 for (action, listener) in &mut listeners {
7147 if *action == request.action {
7148 listener(extra_data, self, cx);
7149 matched = true;
7150 }
7151 }
7152 self.a11y
7153 .action_listeners
7154 .insert(request.target_node, listeners);
7155 if matched {
7156 return;
7157 }
7158 }
7159
7160 match request.action {
7162 accesskit::Action::Click => {
7163 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
7164 let center = bounds.center();
7165 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
7166 button: MouseButton::Left,
7167 position: center,
7168 modifiers: Modifiers::default(),
7169 click_count: 1,
7170 first_mouse: false,
7171 });
7172 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
7173 button: MouseButton::Left,
7174 position: center,
7175 modifiers: Modifiers::default(),
7176 click_count: 1,
7177 });
7178 self.dispatch_event(mouse_down, cx);
7179 self.dispatch_event(mouse_up, cx);
7180 }
7181 }
7182 accesskit::Action::Focus => {
7183 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
7184 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
7185 {
7186 self.focus(&handle, cx);
7187 }
7188 }
7189 accesskit::Action::Blur => {
7190 self.blur(cx);
7191 }
7192 _ => {
7193 log::debug!(
7194 "Unhandled a11y action: {:?} on {:?}",
7195 request.action,
7196 request.target_node
7197 );
7198 }
7199 }
7200 }
7201
7202 #[cfg(any(feature = "inspector", debug_assertions))]
7204 pub fn toggle_inspector(&mut self, cx: &mut App) {
7205 self.inspector = match self.inspector {
7206 None => Some(cx.new(|_| Inspector::new())),
7207 Some(_) => {
7208 self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
7209 self.rendered_frame.inspector_hitboxes = FxHashMap::default();
7210 self.next_frame.next_inspector_instance_ids = FxHashMap::default();
7211 self.next_frame.inspector_hitboxes = FxHashMap::default();
7212 None
7213 }
7214 };
7215 self.refresh();
7216 }
7217
7218 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
7220 #[cfg(any(feature = "inspector", debug_assertions))]
7221 {
7222 if let Some(inspector) = &self.inspector {
7223 return inspector.read(_cx).is_picking();
7224 }
7225 }
7226 false
7227 }
7228
7229 #[cfg(any(feature = "inspector", debug_assertions))]
7231 pub fn with_inspector_state<T: 'static, R>(
7232 &mut self,
7233 inspector_id: Option<&crate::InspectorElementId>,
7234 cx: &mut App,
7235 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
7236 ) -> Option<R> {
7237 let inspector_id = inspector_id?;
7238 let inspector = self.inspector.as_ref()?;
7239 if inspector.read(cx).active_element_id() != Some(inspector_id) {
7240 return None;
7241 }
7242 let inspector = inspector.clone();
7243 Some(inspector.update(cx, |inspector, _cx| {
7244 inspector.with_active_element_state(self, f)
7245 }))
7246 }
7247
7248 #[cfg(any(feature = "inspector", debug_assertions))]
7249 pub(crate) fn inspector_enabled(&self) -> bool {
7250 self.inspector.is_some()
7251 }
7252
7253 #[cfg(any(feature = "inspector", debug_assertions))]
7254 pub(crate) fn build_inspector_element_id(
7255 &mut self,
7256 path: crate::InspectorElementPath,
7257 ) -> crate::InspectorElementId {
7258 self.invalidator.debug_assert_paint_or_prepaint();
7259 let path = Rc::new(path);
7260 let next_instance_id = self
7261 .next_frame
7262 .next_inspector_instance_ids
7263 .entry(path.clone())
7264 .or_insert(0);
7265 let instance_id = *next_instance_id;
7266 *next_instance_id += 1;
7267 crate::InspectorElementId { path, instance_id }
7268 }
7269
7270 #[cfg(any(feature = "inspector", debug_assertions))]
7271 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
7272 if let Some(inspector) = self.inspector.take() {
7273 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
7274 inspector_element.prepaint_as_root(
7275 point(self.viewport_size.width - inspector_width, px(0.0)),
7276 size(inspector_width, self.viewport_size.height).into(),
7277 self,
7278 cx,
7279 );
7280 self.inspector = Some(inspector);
7281 Some(inspector_element)
7282 } else {
7283 None
7284 }
7285 }
7286
7287 #[cfg(any(feature = "inspector", debug_assertions))]
7288 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
7289 if let Some(mut inspector_element) = inspector_element {
7290 inspector_element.paint(self, cx);
7291 };
7292 }
7293
7294 #[cfg(any(feature = "inspector", debug_assertions))]
7297 pub fn insert_inspector_hitbox(
7298 &mut self,
7299 hitbox_id: HitboxId,
7300 inspector_id: Option<&crate::InspectorElementId>,
7301 cx: &App,
7302 ) {
7303 self.invalidator.debug_assert_paint_or_prepaint();
7304 if !self.is_inspector_picking(cx) {
7305 return;
7306 }
7307 if let Some(inspector_id) = inspector_id {
7308 self.next_frame
7309 .inspector_hitboxes
7310 .insert(hitbox_id, inspector_id.clone());
7311 }
7312 }
7313
7314 #[cfg(any(feature = "inspector", debug_assertions))]
7315 fn paint_inspector_hitbox(&mut self, cx: &App) {
7316 if let Some(inspector) = self.inspector.as_ref() {
7317 let inspector = inspector.read(cx);
7318 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
7319 && let Some(hitbox) = self
7320 .next_frame
7321 .hitboxes
7322 .iter()
7323 .find(|hitbox| hitbox.id == hitbox_id)
7324 {
7325 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
7326 }
7327 }
7328 }
7329
7330 #[cfg(any(feature = "inspector", debug_assertions))]
7331 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
7332 let Some(inspector) = self.inspector.clone() else {
7333 return;
7334 };
7335 if event.downcast_ref::<MouseMoveEvent>().is_some() {
7336 inspector.update(cx, |inspector, _cx| {
7337 if let Some((_, inspector_id)) =
7338 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7339 {
7340 inspector.hover(inspector_id, self);
7341 }
7342 });
7343 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
7344 inspector.update(cx, |inspector, _cx| {
7345 if let Some((_, inspector_id)) =
7346 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7347 {
7348 inspector.select(inspector_id, self);
7349 }
7350 });
7351 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
7352 const SCROLL_LINES: f32 = 3.0;
7354 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
7355 let delta_y = event
7356 .delta
7357 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
7358 .y;
7359 if let Some(inspector) = self.inspector.clone() {
7360 inspector.update(cx, |inspector, _cx| {
7361 if let Some(depth) = inspector.pick_depth.as_mut() {
7362 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
7363 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
7364 if *depth < 0.0 {
7365 *depth = 0.0;
7366 } else if *depth > max_depth {
7367 *depth = max_depth;
7368 }
7369 if let Some((_, inspector_id)) =
7370 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7371 {
7372 inspector.set_active_element_id(inspector_id, self);
7373 }
7374 }
7375 });
7376 }
7377 }
7378 }
7379
7380 #[cfg(any(feature = "inspector", debug_assertions))]
7381 fn hovered_inspector_hitbox(
7382 &self,
7383 inspector: &Inspector,
7384 frame: &Frame,
7385 ) -> Option<(HitboxId, crate::InspectorElementId)> {
7386 if let Some(pick_depth) = inspector.pick_depth {
7387 let depth = (pick_depth as i64).try_into().unwrap_or(0);
7388 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
7389 let skip_count = (depth as usize).min(max_skipped);
7390 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
7391 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
7392 return Some((*hitbox_id, inspector_id.clone()));
7393 }
7394 }
7395 }
7396 None
7397 }
7398
7399 #[cfg(any(test, feature = "test-support"))]
7402 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
7403 self.modifiers = modifiers;
7404 }
7405
7406 #[cfg(any(test, feature = "test-support"))]
7410 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
7411 let event = PlatformInput::MouseMove(MouseMoveEvent {
7412 position,
7413 modifiers: self.modifiers,
7414 pressed_button: None,
7415 });
7416 let _ = self.dispatch_event(event, cx);
7417 }
7418
7419 #[inline(never)]
7420 fn take_element_state(
7421 &mut self,
7422 global_id: &GlobalElementId,
7423 state_type: TypeId,
7424 ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
7425 let key = (global_id.clone(), state_type);
7426 self.next_frame.accessed_element_states.push(key.clone());
7427 let state = self
7428 .next_frame
7429 .element_states
7430 .remove(&key)
7431 .or_else(|| self.rendered_frame.element_states.remove(&key));
7432 (key, state)
7433 }
7434
7435 #[inline(never)]
7436 fn insert_element_state(
7437 &mut self,
7438 key: (GlobalElementId, TypeId),
7439 state: ElementStateBox,
7440 ) -> Option<ElementStateBox> {
7441 self.next_frame.element_states.insert(key, state)
7442 }
7443
7444 #[inline(never)]
7445 fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
7446 cx.observe(state, move |_, cx| {
7447 cx.notify(current_view);
7448 })
7449 .detach();
7450 }
7451}
7452
7453slotmap::new_key_type! {
7455 pub struct WindowId;
7457}
7458
7459impl WindowId {
7460 pub fn as_u64(&self) -> u64 {
7462 self.0.as_ffi()
7463 }
7464}
7465
7466impl From<u64> for WindowId {
7467 fn from(value: u64) -> Self {
7468 WindowId(slotmap::KeyData::from_ffi(value))
7469 }
7470}
7471
7472#[derive(Deref, DerefMut)]
7475pub struct WindowHandle<V> {
7476 #[deref]
7477 #[deref_mut]
7478 pub(crate) any_handle: AnyWindowHandle,
7479 state_type: PhantomData<fn(V) -> V>,
7480}
7481
7482impl<V> Debug for WindowHandle<V> {
7483 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7484 f.debug_struct("WindowHandle")
7485 .field("any_handle", &self.any_handle.id.as_u64())
7486 .finish()
7487 }
7488}
7489
7490impl<V: 'static + Render> WindowHandle<V> {
7491 pub fn new(id: WindowId) -> Self {
7494 WindowHandle {
7495 any_handle: AnyWindowHandle {
7496 id,
7497 state_type: TypeId::of::<V>(),
7498 root_entity_type_name: std::any::type_name::<V>(),
7499 },
7500 state_type: PhantomData,
7501 }
7502 }
7503
7504 #[cfg(any(test, feature = "test-support"))]
7508 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
7509 where
7510 C: AppContext,
7511 {
7512 cx.update_window(self.any_handle, |root_view, _, _| {
7513 root_view
7514 .downcast::<V>()
7515 .map_err(|_| anyhow!("the type of the window's root view has changed"))
7516 })?
7517 }
7518
7519 pub fn update<C, R>(
7523 &self,
7524 cx: &mut C,
7525 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
7526 ) -> Result<R>
7527 where
7528 C: AppContext,
7529 {
7530 cx.update_window(self.any_handle, |root_view, window, cx| {
7531 let view = root_view
7532 .downcast::<V>()
7533 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7534
7535 Ok(view.update(cx, |view, cx| update(view, window, cx)))
7536 })?
7537 }
7538
7539 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
7543 let x = cx
7544 .windows
7545 .get(self.id)
7546 .and_then(|window| {
7547 window
7548 .as_deref()
7549 .and_then(|window| window.root.clone())
7550 .map(|root_view| root_view.downcast::<V>())
7551 })
7552 .context("window not found")?
7553 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7554
7555 Ok(x.read(cx))
7556 }
7557
7558 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
7562 where
7563 C: AppContext,
7564 {
7565 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
7566 }
7567
7568 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
7572 where
7573 C: AppContext,
7574 {
7575 cx.read_window(self, |root_view, _cx| root_view)
7576 }
7577
7578 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
7583 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
7584 .ok()
7585 }
7586}
7587
7588impl<V> Copy for WindowHandle<V> {}
7589
7590impl<V> Clone for WindowHandle<V> {
7591 fn clone(&self) -> Self {
7592 *self
7593 }
7594}
7595
7596impl<V> PartialEq for WindowHandle<V> {
7597 fn eq(&self, other: &Self) -> bool {
7598 self.any_handle == other.any_handle
7599 }
7600}
7601
7602impl<V> Eq for WindowHandle<V> {}
7603
7604impl<V> Hash for WindowHandle<V> {
7605 fn hash<H: Hasher>(&self, state: &mut H) {
7606 self.any_handle.hash(state);
7607 }
7608}
7609
7610impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
7611 fn from(val: WindowHandle<V>) -> Self {
7612 val.any_handle
7613 }
7614}
7615
7616#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
7618pub struct AnyWindowHandle {
7619 pub(crate) id: WindowId,
7620 state_type: TypeId,
7621 root_entity_type_name: &'static str,
7622}
7623
7624impl AnyWindowHandle {
7625 pub fn window_id(&self) -> WindowId {
7627 self.id
7628 }
7629
7630 pub fn root_entity_type_name(&self) -> &'static str {
7632 self.root_entity_type_name
7633 }
7634
7635 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
7638 if TypeId::of::<T>() == self.state_type {
7639 Some(WindowHandle {
7640 any_handle: *self,
7641 state_type: PhantomData,
7642 })
7643 } else {
7644 None
7645 }
7646 }
7647
7648 pub fn update<C, R>(
7652 self,
7653 cx: &mut C,
7654 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
7655 ) -> Result<R>
7656 where
7657 C: AppContext,
7658 {
7659 cx.update_window(self, update)
7660 }
7661
7662 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
7666 where
7667 C: AppContext,
7668 T: 'static,
7669 {
7670 let view = self
7671 .downcast::<T>()
7672 .context("the type of the window's root view has changed")?;
7673
7674 cx.read_window(&view, read)
7675 }
7676}
7677
7678impl HasWindowHandle for Window {
7679 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
7680 self.platform_window.window_handle()
7681 }
7682}
7683
7684impl HasDisplayHandle for Window {
7685 fn display_handle(
7686 &self,
7687 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
7688 self.platform_window.display_handle()
7689 }
7690}
7691
7692#[derive(Clone, Debug, Eq, PartialEq, Hash)]
7697pub enum ElementId {
7698 View(EntityId),
7700 Integer(u64),
7702 Name(SharedString),
7704 Uuid(Uuid),
7706 FocusHandle(FocusId),
7708 NamedInteger(SharedString, u64),
7710 Path(Arc<std::path::Path>),
7712 CodeLocation(core::panic::Location<'static>),
7714 NamedChild(Arc<ElementId>, SharedString),
7716 OpaqueId([u8; 20]),
7718}
7719
7720impl ElementId {
7721 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
7723 Self::NamedInteger(name.into(), integer as u64)
7724 }
7725}
7726
7727impl Display for ElementId {
7728 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7729 match self {
7730 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
7731 ElementId::Integer(ix) => write!(f, "{}", ix)?,
7732 ElementId::Name(name) => write!(f, "{}", name)?,
7733 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
7734 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
7735 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
7736 ElementId::Path(path) => write!(f, "{}", path.display())?,
7737 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
7738 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
7739 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
7740 }
7741
7742 Ok(())
7743 }
7744}
7745
7746impl TryInto<SharedString> for ElementId {
7747 type Error = anyhow::Error;
7748
7749 fn try_into(self) -> anyhow::Result<SharedString> {
7750 if let ElementId::Name(name) = self {
7751 Ok(name)
7752 } else {
7753 anyhow::bail!("element id is not string")
7754 }
7755 }
7756}
7757
7758impl From<u64> for ElementId {
7759 fn from(id: u64) -> Self {
7760 ElementId::Integer(id)
7761 }
7762}
7763
7764impl From<usize> for ElementId {
7765 fn from(id: usize) -> Self {
7766 ElementId::Integer(id as u64)
7767 }
7768}
7769
7770impl From<i32> for ElementId {
7771 fn from(id: i32) -> Self {
7772 Self::Integer(id as u64)
7773 }
7774}
7775
7776impl From<SharedString> for ElementId {
7777 fn from(name: SharedString) -> Self {
7778 ElementId::Name(name)
7779 }
7780}
7781
7782impl From<String> for ElementId {
7783 fn from(name: String) -> Self {
7784 ElementId::Name(name.into())
7785 }
7786}
7787
7788impl From<Arc<str>> for ElementId {
7789 fn from(name: Arc<str>) -> Self {
7790 ElementId::Name(name.into())
7791 }
7792}
7793
7794impl From<Arc<std::path::Path>> for ElementId {
7795 fn from(path: Arc<std::path::Path>) -> Self {
7796 ElementId::Path(path)
7797 }
7798}
7799
7800impl From<&'static str> for ElementId {
7801 fn from(name: &'static str) -> Self {
7802 ElementId::Name(SharedString::new_static(name))
7803 }
7804}
7805
7806impl<'a> From<&'a FocusHandle> for ElementId {
7807 fn from(handle: &'a FocusHandle) -> Self {
7808 ElementId::FocusHandle(handle.id)
7809 }
7810}
7811
7812impl From<(&'static str, EntityId)> for ElementId {
7813 fn from((name, id): (&'static str, EntityId)) -> Self {
7814 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
7815 }
7816}
7817
7818impl From<(&'static str, usize)> for ElementId {
7819 fn from((name, id): (&'static str, usize)) -> Self {
7820 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
7821 }
7822}
7823
7824impl From<(SharedString, usize)> for ElementId {
7825 fn from((name, id): (SharedString, usize)) -> Self {
7826 ElementId::NamedInteger(name, id as u64)
7827 }
7828}
7829
7830impl From<(&'static str, u64)> for ElementId {
7831 fn from((name, id): (&'static str, u64)) -> Self {
7832 ElementId::NamedInteger(SharedString::new_static(name), id)
7833 }
7834}
7835
7836impl From<Uuid> for ElementId {
7837 fn from(value: Uuid) -> Self {
7838 Self::Uuid(value)
7839 }
7840}
7841
7842impl From<(&'static str, u32)> for ElementId {
7843 fn from((name, id): (&'static str, u32)) -> Self {
7844 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
7845 }
7846}
7847
7848impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
7849 fn from((id, name): (ElementId, T)) -> Self {
7850 ElementId::NamedChild(Arc::new(id), name.into())
7851 }
7852}
7853
7854impl From<&'static core::panic::Location<'static>> for ElementId {
7855 fn from(location: &'static core::panic::Location<'static>) -> Self {
7856 ElementId::CodeLocation(*location)
7857 }
7858}
7859
7860impl From<[u8; 20]> for ElementId {
7861 fn from(opaque_id: [u8; 20]) -> Self {
7862 ElementId::OpaqueId(opaque_id)
7863 }
7864}
7865
7866#[derive(Clone)]
7869pub struct PaintQuad {
7870 pub bounds: Bounds<Pixels>,
7872 pub corner_radii: Corners<Pixels>,
7874 pub background: Background,
7876 pub border_widths: Edges<Pixels>,
7878 pub border_color: Hsla,
7880 pub border_style: BorderStyle,
7882}
7883
7884impl PaintQuad {
7885 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
7887 PaintQuad {
7888 corner_radii: corner_radii.into(),
7889 ..self
7890 }
7891 }
7892
7893 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
7895 PaintQuad {
7896 border_widths: border_widths.into(),
7897 ..self
7898 }
7899 }
7900
7901 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
7903 PaintQuad {
7904 border_color: border_color.into(),
7905 ..self
7906 }
7907 }
7908
7909 pub fn background(self, background: impl Into<Background>) -> Self {
7911 PaintQuad {
7912 background: background.into(),
7913 ..self
7914 }
7915 }
7916}
7917
7918pub fn quad(
7920 bounds: Bounds<Pixels>,
7921 corner_radii: impl Into<Corners<Pixels>>,
7922 background: impl Into<Background>,
7923 border_widths: impl Into<Edges<Pixels>>,
7924 border_color: impl Into<Hsla>,
7925 border_style: BorderStyle,
7926) -> PaintQuad {
7927 PaintQuad {
7928 bounds,
7929 corner_radii: corner_radii.into(),
7930 background: background.into(),
7931 border_widths: border_widths.into(),
7932 border_color: border_color.into(),
7933 border_style,
7934 }
7935}
7936
7937pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
7939 PaintQuad {
7940 bounds: bounds.into(),
7941 corner_radii: (0.).into(),
7942 background: background.into(),
7943 border_widths: (0.).into(),
7944 border_color: transparent_black(),
7945 border_style: BorderStyle::default(),
7946 }
7947}
7948
7949pub fn outline(
7951 bounds: impl Into<Bounds<Pixels>>,
7952 border_color: impl Into<Hsla>,
7953 border_style: BorderStyle,
7954) -> PaintQuad {
7955 PaintQuad {
7956 bounds: bounds.into(),
7957 corner_radii: (0.).into(),
7958 background: transparent_black().into(),
7959 border_widths: (1.).into(),
7960 border_color: border_color.into(),
7961 border_style,
7962 }
7963}
7964
7965#[inline(never)]
7966fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
7967 if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
7968 let arena_cell = unsafe { &*arena_pointer };
7971 callback(&mut arena_cell.borrow_mut());
7972 Ok(())
7973 } else {
7974 ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
7975 }
7976}
7977
7978#[cfg(test)]
7979mod tests {
7980 use std::{
7981 cell::{Cell, RefCell},
7982 path::PathBuf,
7983 rc::Rc,
7984 time::Duration,
7985 };
7986
7987 use crate::{
7988 AnyWindowHandle, AppContext as _, Bounds, ContentMask, Context, DispatchPhase,
7989 DragMoveEvent, Empty, ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent,
7990 FocusHandle, InputEvent as _, InteractiveElement as _, IntoElement, KeyDownEvent,
7991 Keystroke, LongPressEvent, MouseButton, MouseDownEvent, MouseMoveEvent, ParentElement,
7992 Pixels, PlatformInput, Point, Render, RequestFrameOptions, ScaledPixels,
7993 StatefulInteractiveElement as _, Styled, TestAppContext, TouchDragEvent, TouchEvent,
7994 TouchId, TouchPhase, Underline, UnderlineStyle, Window, WindowAppearance, WindowOptions,
7995 canvas, div, hsla, point, px, size,
7996 };
7997
7998 #[gpui::test]
7999 async fn test_focus_handle_release(cx: &mut TestAppContext) {
8000 let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
8001 let handle_id = handle.id;
8002 let weak_handle = handle.downgrade();
8003 let retained = handle.clone();
8004 drop(handle);
8005
8006 cx.update(|_| {});
8007 cx.read(|cx| {
8008 let handles = cx.focus_handles.read();
8009 assert_eq!(handles.handles.len(), 2);
8010 assert!(handles.dropped_handles.is_empty());
8011 });
8012 assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));
8013
8014 cx.background_spawn(async move { drop(retained) }).await;
8015 assert_eq!(weak_handle.upgrade(), None);
8016 cx.read(|cx| {
8017 assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);
8018 });
8019 cx.update(|_| {});
8020 cx.read(|cx| {
8021 let handles = cx.focus_handles.read();
8022 assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);
8023 assert!(handles.dropped_handles.is_empty());
8024 });
8025
8026 let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);
8027 assert_eq!(weak_handle.upgrade(), None);
8028 cx.update(|cx| {
8029 drop(replacements);
8030 cx.defer(move |_| drop(survivor));
8031 });
8032 cx.read(|cx| {
8033 let handles = cx.focus_handles.read();
8034 assert_eq!(handles.handles.len(), 0);
8035 assert!(handles.dropped_handles.is_empty());
8036 });
8037 }
8038
8039 #[gpui::test]
8040 fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {
8041 let windows = [
8042 cx.add_window(|_, _| EmptyView),
8043 cx.add_window(|_, _| EmptyView),
8044 cx.add_window(|_, _| EmptyView),
8045 cx.add_window(|_, _| EmptyView),
8046 cx.add_window(|_, _| EmptyView),
8047 ];
8048 let (handle, other_handle, survivor) =
8049 cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));
8050 for window in &windows[..2] {
8051 window
8052 .update(cx, |_, window, cx| window.focus(&handle, cx))
8053 .expect("window exists");
8054 }
8055 windows[2]
8056 .update(cx, |_, window, cx| window.focus(&other_handle, cx))
8057 .expect("window exists");
8058 windows[3]
8059 .update(cx, |_, window, cx| window.focus(&survivor, cx))
8060 .expect("window exists");
8061
8062 cx.update(|cx| {
8063 for _ in 0..1_000 {
8064 drop(cx.focus_handle());
8065 }
8066 drop((handle, other_handle));
8067 });
8068 for window in &windows[..3] {
8069 window
8070 .update(cx, |_, window, _| assert_eq!(window.focus, None))
8071 .expect("window exists");
8072 }
8073 windows[3]
8074 .update(cx, |_, window, cx| {
8075 assert_eq!(window.focused(cx).as_ref(), Some(&survivor));
8076 assert_eq!(window.focus_generation, 1);
8077 })
8078 .expect("window exists");
8079 windows[4]
8080 .update(cx, |_, window, _| {
8081 assert_eq!(window.focus, None);
8082 assert_eq!(window.focus_generation, 0);
8083 })
8084 .expect("window exists");
8085 }
8086
8087 #[cfg(feature = "profiler")]
8088 #[gpui::test]
8089 fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
8090 use crate::FrameRequestSource;
8091 use crate::profiler::journal::{
8092 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
8093 };
8094 use scheduler::Instant;
8095
8096 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8097 let window = cx.add_window(|_, _| EmptyView);
8098 let platform_window = cx.test_window(window.into());
8099 platform_window.simulate_frame_request(RequestFrameOptions::default());
8100 let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
8101 let mut collector = journal.collector();
8102
8103 for (signal_at, source) in [
8104 (Some(Instant::now()), FrameRequestSource::NativeCallback),
8105 (Some(Instant::now()), FrameRequestSource::LocalSchedule),
8106 (None, FrameRequestSource::NativeCallback),
8107 ] {
8108 platform_window.simulate_frame_request(RequestFrameOptions {
8109 signal_at,
8110 signal_source: source,
8111 require_presentation: true,
8112 ..Default::default()
8113 });
8114 let entries = collector.collect_unseen().entries;
8115 let signal_index = entries
8116 .iter()
8117 .position(|entry| {
8118 matches!(
8119 entry,
8120 ForegroundJournalEntry::PlatformSignal(signal)
8121 if signal.window_id == window.window_id()
8122 && signal.signal_at == signal_at
8123 && signal.source == source
8124 && signal_at.is_none_or(|at| signal.handled_at >= at)
8125 )
8126 })
8127 .expect("frame request metadata");
8128 let skip_index = entries
8129 .iter()
8130 .position(|entry| {
8131 matches!(
8132 entry,
8133 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
8134 if skipped.window_id == window.window_id()
8135 && skipped.reason == FrameSkipReason::NoRenderNeeded
8136 )
8137 })
8138 .expect("completed no-render boundary");
8139 assert!(signal_index < skip_index);
8140 }
8141 }
8142
8143 #[cfg(feature = "profiler")]
8144 #[gpui::test]
8145 fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
8146 use crate::profiler::journal::{
8147 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
8148 };
8149 use scheduler::Instant;
8150
8151 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8153 let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
8154 let mut collector = journal.collector();
8155 for initially_dirty in [true, false] {
8156 let window = cx
8158 .app
8159 .borrow_mut()
8160 .open_window(
8161 WindowOptions {
8162 inactive_frame_interval: Some(Duration::from_secs(3600)),
8163 ..Default::default()
8164 },
8165 |_, cx| cx.new(|_| EmptyView),
8166 )
8167 .expect("open inactive test window");
8168 let platform_window = cx.test_window(window.into());
8169 platform_window.simulate_active_status_change(false);
8170 platform_window.simulate_frame_request(RequestFrameOptions::default());
8171 let callback_ran = Rc::new(Cell::new(false));
8172 let draws_before = window
8173 .update(cx, |_, window, _| {
8174 let draws_before = window
8175 .frame_duration_snapshot()
8176 .draw_duration_histogram
8177 .len();
8178 if initially_dirty {
8179 window.refresh();
8180 }
8181 window.on_next_frame({
8182 let callback_ran = callback_ran.clone();
8183 move |window, _| {
8184 callback_ran.set(true);
8185 window.refresh();
8186 }
8187 });
8188 draws_before
8189 })
8190 .expect("schedule throttled frame");
8191 let input_at = Instant::now();
8193 journal::record_input(journal::InputTiming {
8194 kind: "test",
8195 start: input_at,
8196 end: input_at,
8197 caused_invalidation: false,
8198 });
8199 collector.collect_unseen();
8200 platform_window.simulate_frame_request(RequestFrameOptions {
8201 signal_at: Some(Instant::now()),
8202 ..Default::default()
8203 });
8204 window
8205 .update(cx, |_, window, _| {
8206 assert_eq!(
8207 window
8208 .frame_duration_snapshot()
8209 .draw_duration_histogram
8210 .len(),
8211 draws_before,
8212 );
8213 })
8214 .expect("inspect deferred frame");
8215 assert!(!callback_ran.get());
8216 assert!(collector.collect_unseen().entries.iter().any(|entry| {
8217 matches!(
8218 entry,
8219 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
8220 if skipped.window_id == window.window_id()
8221 && skipped.reason == FrameSkipReason::InactiveFrameRateLimit
8222 )
8223 }));
8224 platform_window.simulate_frame_request(RequestFrameOptions {
8225 signal_at: Some(Instant::now()),
8226 require_presentation: true,
8227 ..Default::default()
8228 });
8229 window
8230 .update(cx, |_, window, _| {
8231 assert_eq!(
8232 window
8233 .frame_duration_snapshot()
8234 .draw_duration_histogram
8235 .len(),
8236 draws_before + 1,
8237 );
8238 })
8239 .expect("inspect presented frame");
8240 assert!(callback_ran.get());
8241 }
8242 }
8243
8244 #[gpui::test]
8248 fn test_window_visibility(cx: &mut TestAppContext) {
8249 use crate::WindowVisibility;
8250
8251 let window = cx.add_window(|_, _| EmptyView);
8252 let observed = Rc::new(RefCell::new(Vec::new()));
8253 let _subscription = window
8254 .update(cx, {
8255 let observed = observed.clone();
8256 move |_, window, _| {
8257 assert_eq!(window.visibility(), WindowVisibility::Visible);
8258 assert!(window.is_visible());
8259 window.observe_window_visibility(move |visibility, window, _| {
8260 assert_eq!(window.visibility(), visibility);
8261 observed.borrow_mut().push(visibility);
8262 })
8263 }
8264 })
8265 .unwrap();
8266 let test_window = cx.test_window(window.into());
8267 let frame_wake_count = test_window.frame_wake_count();
8268
8269 test_window.simulate_visibility_change(WindowVisibility::Hidden);
8270 assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
8271 window
8272 .update(cx, |_, window, _| assert!(!window.is_visible()))
8273 .unwrap();
8274
8275 test_window.simulate_visibility_change(WindowVisibility::Hidden);
8277 assert_eq!(observed.borrow().len(), 1);
8278
8279 test_window.simulate_visibility_change(WindowVisibility::Visible);
8280 assert_eq!(
8281 *observed.borrow(),
8282 [WindowVisibility::Hidden, WindowVisibility::Visible]
8283 );
8284 window
8285 .update(cx, |_, window, _| assert!(window.is_visible()))
8286 .unwrap();
8287 assert_eq!(test_window.frame_wake_count(), frame_wake_count);
8288 }
8289
8290 #[gpui::test]
8293 fn test_display_tracking(cx: &mut TestAppContext) {
8294 use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
8295
8296 let sixty_hertz = Duration::from_secs(1) / 60;
8297 let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
8298 let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
8299
8300 let display_events = Rc::new(RefCell::new(Vec::new()));
8301 let _display_subscription = cx.update({
8302 let display_events = display_events.clone();
8303 move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
8304 });
8305
8306 let window = cx.add_window(|window, cx| DisplayTracker {
8307 refresh_intervals: Vec::new(),
8308 _subscription: cx.observe_window_display(
8309 window,
8310 |tracker: &mut DisplayTracker, window, cx| {
8311 tracker.refresh_intervals.push(window.refresh_interval(cx));
8312 },
8313 ),
8314 });
8315 let window_notifications = Rc::new(RefCell::new(Vec::new()));
8316 let _window_subscription = window
8317 .update(cx, {
8318 let window_notifications = window_notifications.clone();
8319 move |_, window, cx| {
8320 assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
8321 window.observe_window_display(move |window, cx| {
8322 window_notifications
8323 .borrow_mut()
8324 .push((window.display_id, window.refresh_interval(cx)));
8325 })
8326 }
8327 })
8328 .unwrap();
8329 let test_window = cx.test_window(window.into());
8330
8331 cx.test_platform()
8336 .connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
8337 test_window.simulate_move_to_display(DisplayId(2));
8338 assert_eq!(
8339 window_notifications.take(),
8340 [(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
8341 );
8342 assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
8343 cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
8344 assert!(window_notifications.borrow().is_empty());
8345
8346 test_window.simulate_move_to_display(DisplayId(2));
8348 assert!(window_notifications.borrow().is_empty());
8349
8350 cx.simulate_display_refresh_interval_change(
8351 DisplayId(2),
8352 Some(one_hundred_forty_four_hertz),
8353 );
8354 assert_eq!(
8355 window_notifications.take(),
8356 [(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
8357 );
8358
8359 cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
8361 cx.simulate_display_removed(DisplayId(1));
8362 assert!(window_notifications.borrow().is_empty());
8363
8364 assert_eq!(
8365 display_events.take(),
8366 [
8367 DisplayEvent::Changed {
8368 id: DisplayId(2),
8369 changes: DisplayChanges::REFRESH_INTERVAL,
8370 },
8371 DisplayEvent::Changed {
8372 id: DisplayId(1),
8373 changes: DisplayChanges::REFRESH_INTERVAL,
8374 },
8375 DisplayEvent::Removed(DisplayId(1)),
8376 ]
8377 );
8378 window
8379 .update(cx, |tracker, _, _| {
8380 assert_eq!(
8381 tracker.refresh_intervals,
8382 [
8383 Some(one_hundred_twenty_hertz),
8384 Some(one_hundred_forty_four_hertz)
8385 ]
8386 );
8387 })
8388 .unwrap();
8389
8390 struct DisplayTracker {
8391 refresh_intervals: Vec<Option<Duration>>,
8392 _subscription: Subscription,
8393 }
8394
8395 impl Render for DisplayTracker {
8396 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8397 Empty
8398 }
8399 }
8400 }
8401
8402 #[gpui::test]
8403 fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
8404 let window = cx.add_window(|_, _| EmptyView);
8405 let mut platform_window = cx.test_window(window.into());
8406 platform_window.simulate_resize(size(px(400.), px(800.)));
8407 window
8408 .update(cx, |_, window, _| {
8409 assert_eq!(
8410 window.visual_viewport_bounds(),
8411 Bounds::new(Point::default(), size(px(400.), px(800.)))
8412 );
8413 assert_eq!(
8414 window.fully_visible_bounds(),
8415 window.visual_viewport_bounds()
8416 );
8417 })
8418 .unwrap();
8419
8420 platform_window.simulate_frame_request(RequestFrameOptions::default());
8421 let wakes = platform_window.frame_wake_count();
8422 let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
8423 platform_window.simulate_visual_viewport_change(visual_bounds);
8424 assert!(platform_window.frame_wake_count() > wakes);
8425 platform_window.simulate_frame_request(RequestFrameOptions::default());
8426 let wakes = platform_window.frame_wake_count();
8427 let insets = crate::WindowInsets {
8428 safe_area: crate::Edges {
8429 top: px(60.),
8430 right: px(20.),
8431 bottom: px(30.),
8432 left: px(-10.),
8433 },
8434 ime: crate::Edges {
8435 bottom: px(350.),
8436 ..Default::default()
8437 },
8438 };
8439 platform_window.simulate_insets_change(insets.clone());
8440 assert!(platform_window.frame_wake_count() > wakes);
8441 window
8442 .update(cx, |_, window, cx| {
8443 let focus = cx.focus_handle();
8444 window.focus(&focus, cx);
8445 assert_eq!(window.insets(), insets);
8446 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
8447 assert_eq!(window.visual_viewport_bounds(), visual_bounds);
8448 assert_eq!(
8449 window.fully_visible_bounds(),
8450 Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
8451 );
8452 window.request_virtual_keyboard();
8453 window.dismiss_virtual_keyboard();
8454 assert!(focus.is_focused(window));
8455 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
8456 })
8457 .unwrap();
8458 assert_eq!(platform_window.virtual_keyboard_requests(), 1);
8459 assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
8460
8461 platform_window.simulate_insets_change(crate::WindowInsets {
8462 safe_area: crate::Edges {
8463 top: px(900.),
8464 left: px(500.),
8465 ..Default::default()
8466 },
8467 ..Default::default()
8468 });
8469 window
8470 .update(cx, |_, window, _| {
8471 assert_eq!(
8472 window.fully_visible_bounds().size,
8473 size(Pixels::ZERO, Pixels::ZERO)
8474 );
8475 })
8476 .unwrap();
8477
8478 use crate::PlatformWindow as _;
8480 platform_window.on_insets_changed(Box::new(|_| {}));
8481 platform_window.simulate_insets_change(crate::WindowInsets::default());
8482 window
8483 .update(cx, |_, window, _| {
8484 assert_eq!(window.insets(), crate::WindowInsets::default());
8485 })
8486 .unwrap();
8487 }
8488
8489 struct EmptyView;
8490
8491 impl Render for EmptyView {
8492 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8493 div()
8494 }
8495 }
8496
8497 struct OpensWindowOnPaint {
8498 opened: Rc<Cell<bool>>,
8499 }
8500
8501 impl Render for OpensWindowOnPaint {
8502 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8503 let opened = self.opened.clone();
8504 div()
8505 .size_full()
8506 .child(canvas(
8507 |_, _, _| {},
8508 move |_, _, _window, cx| {
8509 if !opened.replace(true) {
8510 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
8511 .unwrap();
8512 }
8513 },
8514 ))
8515 .child(div().child("after"))
8519 }
8520 }
8521
8522 #[test]
8528 fn test_window_opened_during_draw_defers_arena_clear() {
8529 let mut cx = TestAppContext::single();
8530
8531 let opened = Rc::new(Cell::new(false));
8532 let window = cx.add_window({
8534 let opened = opened.clone();
8535 move |_, _| OpensWindowOnPaint { opened }
8536 });
8537
8538 assert!(opened.get());
8539 assert_eq!(cx.windows().len(), 2);
8540
8541 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8544 .unwrap();
8545 }
8546
8547 #[test]
8548 fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
8549 let mut cx = TestAppContext::single();
8550 let window = cx.add_window(|_, _| EmptyView);
8551 let handle: AnyWindowHandle = window.into();
8552 let window_state = |cx: &mut TestAppContext| {
8553 cx.update_window(handle, |_, window, _| {
8554 (
8555 window.scale_factor(),
8556 window.bounds(),
8557 window.viewport_size(),
8558 )
8559 })
8560 .unwrap()
8561 };
8562
8563 let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
8564 assert_eq!(scale_factor, 2.0);
8565
8566 for (scale_factor, resized_size) in [
8567 (1.0, size(px(800.), px(600.))),
8568 (1.25, size(px(640.), px(480.))),
8569 (2.0, size(px(1024.), px(768.))),
8570 ] {
8571 cx.simulate_window_scale_factor_change(handle, scale_factor);
8572 assert_eq!(
8573 window_state(&mut cx),
8574 (scale_factor, expected_bounds, expected_bounds.size)
8575 );
8576
8577 cx.simulate_window_resize(handle, resized_size);
8578 expected_bounds.size = resized_size;
8579 assert_eq!(
8580 window_state(&mut cx),
8581 (scale_factor, expected_bounds, resized_size)
8582 );
8583 }
8584 }
8585
8586 #[gpui::test]
8591 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
8592 let window = cx.add_window(|_, _| EmptyView);
8593 let test_window = cx.test_window(window.into());
8594
8595 assert!(
8599 test_window.frame_wake_count() >= 1,
8600 "opening a window must wake the frame source for the initial frame"
8601 );
8602
8603 test_window.simulate_frame_request(RequestFrameOptions::default());
8605
8606 let baseline = test_window.frame_wake_count();
8609 test_window.simulate_frame_request(RequestFrameOptions::default());
8610 window.update(cx, |_, _, _| {}).unwrap();
8611 assert_eq!(
8612 test_window.frame_wake_count(),
8613 baseline,
8614 "clean frames and non-notifying updates must not wake the frame source"
8615 );
8616
8617 window.update(cx, |_, _, cx| cx.notify()).unwrap();
8619 assert!(
8620 test_window.frame_wake_count() > baseline,
8621 "notifying a view in an idle window must wake the frame source"
8622 );
8623
8624 test_window.simulate_frame_request(RequestFrameOptions::default());
8626 let baseline = test_window.frame_wake_count();
8627 test_window.simulate_frame_request(RequestFrameOptions::default());
8628 assert_eq!(
8629 test_window.frame_wake_count(),
8630 baseline,
8631 "serving demand must return the window to idle"
8632 );
8633
8634 window
8636 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
8637 .unwrap();
8638 assert!(
8639 test_window.frame_wake_count() > baseline,
8640 "scheduling a next-frame callback in an idle window must wake the frame source"
8641 );
8642 }
8643
8644 #[gpui::test]
8649 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
8650 let window = cx.add_window(|_, _| EmptyView);
8651 let test_window = cx.test_window(window.into());
8652 test_window.simulate_frame_request(RequestFrameOptions::default());
8655
8656 let callback_ran = Rc::new(Cell::new(false));
8657 window
8658 .update(cx, {
8659 let callback_ran = callback_ran.clone();
8660 move |_, window, _| {
8661 window.on_next_frame(move |_, _| callback_ran.set(true));
8662 }
8663 })
8664 .unwrap();
8665
8666 let baseline = test_window.frame_wake_count();
8667 test_window.simulate_frame_request(RequestFrameOptions::default());
8668 assert!(
8675 test_window.frame_wake_count() > baseline || callback_ran.get(),
8676 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
8677 );
8678 }
8679
8680 #[gpui::test]
8681 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
8682 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
8683
8684 let window = cx.add_window(|_, _| EmptyView);
8685 window
8686 .update(cx, |_, window, _| {
8687 assert!(matches!(
8688 window.window_handle(),
8689 Err(HandleError::NotSupported)
8690 ));
8691 assert!(matches!(
8692 window.display_handle(),
8693 Err(HandleError::NotSupported)
8694 ));
8695 })
8696 .unwrap();
8697 }
8698
8699 #[gpui::test]
8700 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
8701 let window = cx.add_window(|_, _| EmptyView);
8702 let observed_appearance = Rc::new(Cell::new(None));
8703 let _subscription = window
8704 .update(cx, {
8705 let observed_appearance = observed_appearance.clone();
8706 move |_, window, _| {
8707 window.observe_window_appearance(move |window, _| {
8708 observed_appearance.set(Some(window.appearance()));
8709 })
8710 }
8711 })
8712 .unwrap();
8713 let test_window = cx.test_window(window.into());
8714
8715 cx.update(|_| {
8716 test_window.simulate_appearance_change(WindowAppearance::Dark);
8717 assert_eq!(observed_appearance.get(), None);
8718 });
8719 cx.run_until_parked();
8720
8721 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
8722 }
8723
8724 #[gpui::test]
8725 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
8726 let window = cx.add_window(|_, _| Empty);
8727 let test_window = cx.test_window(window.into());
8728
8729 assert!(test_window.simulate_scheduled_frame());
8730 assert!(test_window.simulate_scheduled_frame());
8731 assert!(!test_window.frame_scheduled());
8732
8733 cx.update_window(window.into(), |_, window, _| {
8734 window.active.set(true);
8735 window.on_next_frame(|_, _| {});
8736 })
8737 .unwrap();
8738 assert!(
8739 test_window.frame_scheduled(),
8740 "queuing work on a parked window must wake the render loop"
8741 );
8742
8743 assert!(test_window.simulate_scheduled_frame());
8744 assert!(
8745 test_window.frame_scheduled(),
8746 "presenting the frame must await one compositor callback"
8747 );
8748 assert!(test_window.simulate_scheduled_frame());
8749 assert!(!test_window.frame_scheduled());
8750 }
8751
8752 #[gpui::test]
8753 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
8754 let window = cx.add_window(|_, _| Empty);
8755 let test_window = cx.test_window(window.into());
8756
8757 assert!(test_window.simulate_scheduled_frame());
8758 assert!(test_window.simulate_scheduled_frame());
8759 assert!(!test_window.frame_scheduled());
8760
8761 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8762 .unwrap();
8763
8764 assert!(
8765 test_window.frame_scheduled(),
8766 "a rendered scene awaiting presentation must wake the render loop"
8767 );
8768 }
8769
8770 #[gpui::test]
8771 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
8772 let window = cx.add_window(|_, _| Empty);
8773 let test_window = cx.test_window(window.into());
8774
8775 let callback_ran = Rc::new(Cell::new(false));
8776 cx.update_window(window.into(), |_, window, _| {
8777 window.active.set(true);
8780 let callback_ran = callback_ran.clone();
8781 window.on_next_frame(move |window, _| {
8782 window.on_next_frame(move |_, _| callback_ran.set(true));
8783 });
8784 })
8785 .unwrap();
8786
8787 assert!(test_window.simulate_scheduled_frame());
8788 assert!(!callback_ran.get());
8789 assert!(
8790 test_window.frame_scheduled(),
8791 "a callback queued mid-frame must schedule a follow-up before the loop parks"
8792 );
8793
8794 assert!(test_window.simulate_scheduled_frame());
8795 assert!(callback_ran.get());
8796 }
8797
8798 struct RootView {
8799 explicit_size: bool,
8800 child_bounds: Rc<Cell<Bounds<Pixels>>>,
8801 }
8802
8803 impl Render for RootView {
8804 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8805 let child_bounds = self.child_bounds.clone();
8806 let root = div().flex().flex_col().child(
8807 canvas(
8808 move |bounds, _, _| child_bounds.set(bounds),
8809 |_, _, _, _| {},
8810 )
8811 .size_full(),
8812 );
8813 if self.explicit_size {
8814 root.w(px(300.)).h(px(200.))
8815 } else {
8816 root
8817 }
8818 }
8819 }
8820
8821 #[test]
8822 fn auto_sized_window_root_fills_the_window() {
8823 let mut cx = TestAppContext::single();
8824 let child_bounds = Rc::new(Cell::new(Bounds::default()));
8825 let window = cx.add_window({
8826 let child_bounds = child_bounds.clone();
8827 move |_, _| RootView {
8828 explicit_size: false,
8829 child_bounds,
8830 }
8831 });
8832
8833 let viewport_size = cx
8834 .update_window(window.into(), |_, window, cx| {
8835 window.draw(cx).clear(cx);
8836 window.viewport_size()
8837 })
8838 .unwrap();
8839
8840 assert_eq!(child_bounds.get().size, viewport_size);
8841 }
8842
8843 #[test]
8844 fn explicitly_sized_window_root_keeps_its_size() {
8845 let mut cx = TestAppContext::single();
8846 let child_bounds = Rc::new(Cell::new(Bounds::default()));
8847 let window = cx.add_window({
8848 let child_bounds = child_bounds.clone();
8849 move |_, _| RootView {
8850 explicit_size: true,
8851 child_bounds,
8852 }
8853 });
8854
8855 cx.update_window(window.into(), |_, window, cx| {
8856 window.draw(cx).clear(cx);
8857 })
8858 .unwrap();
8859
8860 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
8861 }
8862
8863 struct FileDragView {
8864 path: PathBuf,
8865 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
8866 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
8867 }
8868
8869 struct FileDropExitView(Rc<Cell<usize>>);
8870
8871 impl Render for FileDropExitView {
8872 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8873 div().size_full().on_file_drop_exit({
8874 let observed_file_drop_exit = self.0.clone();
8875 move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
8876 })
8877 }
8878 }
8879
8880 impl Render for FileDragView {
8881 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8882 div()
8883 .id("file-drag")
8884 .size_full()
8885 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
8886 .external_drag_payload(|path: &PathBuf, _, _| {
8887 Some(ExternalDragPayload::Files(FileDragPaths::new([(
8888 path.clone(),
8889 true,
8890 )])))
8891 })
8892 .on_drag_move({
8893 let observed_drag_moves = self.observed_drag_moves.clone();
8894 move |event: &DragMoveEvent<PathBuf>, _, _| {
8895 observed_drag_moves.borrow_mut().push(event.event.position);
8896 }
8897 })
8898 .on_drop({
8899 let observed_drops = self.observed_drops.clone();
8900 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
8901 })
8902 }
8903 }
8904
8905 #[gpui::test]
8906 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
8907 struct Drag {
8908 window: AnyWindowHandle,
8909 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
8910 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
8911 }
8912
8913 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
8914 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
8915 let observed_drops = Rc::new(RefCell::new(Vec::new()));
8916 let window: AnyWindowHandle = cx
8917 .add_window({
8918 let observed_drag_moves = observed_drag_moves.clone();
8919 let observed_drops = observed_drops.clone();
8920 move |_, _| FileDragView {
8921 path,
8922 observed_drag_moves,
8923 observed_drops,
8924 }
8925 })
8926 .into();
8927 cx.test_window(window)
8928 .set_start_external_drag_result(platform_result);
8929
8930 let update_result = cx.update_window(window, |_, window, cx| {
8931 window.draw(cx).clear(cx);
8932 window.dispatch_event(
8933 MouseDownEvent {
8934 position: point(px(10.), px(10.)),
8935 button: MouseButton::Left,
8936 modifiers: Default::default(),
8937 click_count: 1,
8938 first_mouse: false,
8939 }
8940 .to_platform_input(),
8941 cx,
8942 );
8943 window.dispatch_event(
8944 MouseMoveEvent {
8945 position: point(px(20.), px(20.)),
8946 pressed_button: Some(MouseButton::Left),
8947 modifiers: Default::default(),
8948 }
8949 .to_platform_input(),
8950 cx,
8951 );
8952 assert!(cx.active_drag.is_some());
8953 });
8954 assert!(
8955 update_result.is_ok(),
8956 "failed to start drag: {update_result:?}"
8957 );
8958
8959 assert!(cx.test_window(window).external_drag_files().is_empty());
8960 Drag {
8961 window,
8962 observed_drag_moves,
8963 observed_drops,
8964 }
8965 }
8966
8967 let successful_path = PathBuf::from("/tmp/successful-drag");
8968 let successful = start_drag(cx, successful_path.clone(), true);
8969 let outside_position = point(px(-1.), px(20.));
8970 let update_result = cx.update_window(successful.window, |_, window, cx| {
8971 window.dispatch_event(
8972 MouseMoveEvent {
8973 position: outside_position,
8974 pressed_button: Some(MouseButton::Left),
8975 modifiers: Default::default(),
8976 }
8977 .to_platform_input(),
8978 cx,
8979 );
8980 assert!(cx.active_drag.is_none());
8981 });
8982 assert!(
8983 update_result.is_ok(),
8984 "failed to promote drag: {update_result:?}"
8985 );
8986 assert_eq!(
8987 cx.test_window(successful.window).external_drag_files(),
8988 [(successful_path.clone(), true)]
8989 );
8990 assert_eq!(
8993 successful.observed_drag_moves.borrow().last(),
8994 Some(&outside_position)
8995 );
8996
8997 let first_destination_exit_count = Rc::new(Cell::new(0));
8998 let first_destination: AnyWindowHandle = cx
8999 .add_window({
9000 let first_destination_exit_count = first_destination_exit_count.clone();
9001 move |_, _| FileDropExitView(first_destination_exit_count)
9002 })
9003 .into();
9004 let second_destination_exit_count = Rc::new(Cell::new(0));
9005 let second_destination: AnyWindowHandle = cx
9006 .add_window({
9007 let second_destination_exit_count = second_destination_exit_count.clone();
9008 move |_, _| FileDropExitView(second_destination_exit_count)
9009 })
9010 .into();
9011 let reentry_position = point(px(30.), px(30.));
9012 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
9013 let update_result = cx.update_window(first_destination, |_, window, cx| {
9014 window.draw(cx).clear(cx);
9015 window.dispatch_event(
9016 FileDropEvent::Entered {
9017 position: reentry_position,
9018 paths: external_paths(),
9019 }
9020 .to_platform_input(),
9021 cx,
9022 );
9023 assert!(
9024 cx.active_drag
9025 .as_ref()
9026 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9027 );
9028 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9029 assert!(cx.active_drag.is_none());
9030 assert_eq!(first_destination_exit_count.get(), 1);
9031 assert_eq!(second_destination_exit_count.get(), 0);
9032 });
9033 assert!(
9034 update_result.is_ok(),
9035 "failed to handle drag in first destination window: {update_result:?}"
9036 );
9037
9038 let update_result = cx.update_window(second_destination, |_, window, cx| {
9039 window.draw(cx).clear(cx);
9040 window.dispatch_event(
9041 PlatformInput::KeyDown(KeyDownEvent {
9042 keystroke: Keystroke::parse("down").expect("valid keystroke"),
9043 is_held: false,
9044 prefer_character_input: false,
9045 }),
9046 cx,
9047 );
9048 window.dispatch_event(
9049 FileDropEvent::Entered {
9050 position: reentry_position,
9051 paths: external_paths(),
9052 }
9053 .to_platform_input(),
9054 cx,
9055 );
9056 assert!(
9057 cx.active_drag
9058 .as_ref()
9059 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9060 );
9061 assert_eq!(first_destination_exit_count.get(), 1);
9062 assert_eq!(second_destination_exit_count.get(), 0);
9063
9064 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9065 assert!(cx.active_drag.is_none());
9066 assert_eq!(first_destination_exit_count.get(), 1);
9067 assert_eq!(second_destination_exit_count.get(), 1);
9068 });
9069 assert!(
9070 update_result.is_ok(),
9071 "failed to handle drag in second destination window: {update_result:?}"
9072 );
9073
9074 let update_result = cx.update_window(successful.window, |_, window, cx| {
9075 window.dispatch_event(
9076 FileDropEvent::Entered {
9077 position: reentry_position,
9078 paths: external_paths(),
9079 }
9080 .to_platform_input(),
9081 cx,
9082 );
9083 assert!(
9084 cx.active_drag
9085 .as_ref()
9086 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9087 );
9088 assert_eq!(
9089 successful.observed_drag_moves.borrow().last(),
9090 Some(&reentry_position)
9091 );
9092
9093 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9094 assert!(cx.active_drag.is_none());
9095
9096 window.dispatch_event(
9097 FileDropEvent::Entered {
9098 position: reentry_position,
9099 paths: external_paths(),
9100 }
9101 .to_platform_input(),
9102 cx,
9103 );
9104 assert!(
9105 cx.active_drag
9106 .as_ref()
9107 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9108 );
9109
9110 window.dispatch_event(
9111 FileDropEvent::Submit {
9112 position: reentry_position,
9113 }
9114 .to_platform_input(),
9115 cx,
9116 );
9117 assert_eq!(
9118 successful.observed_drops.borrow().as_slice(),
9119 std::slice::from_ref(&successful_path)
9120 );
9121 assert!(cx.active_drag.is_none());
9122
9123 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9124 assert!(cx.active_drag.is_none());
9125 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
9126 assert!(cx.active_drag.is_none());
9127
9128 window.dispatch_event(
9129 FileDropEvent::Entered {
9130 position: reentry_position,
9131 paths: external_paths(),
9132 }
9133 .to_platform_input(),
9134 cx,
9135 );
9136 assert!(
9137 cx.active_drag
9138 .as_ref()
9139 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9140 );
9141 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9142 });
9143 assert!(
9144 update_result.is_ok(),
9145 "failed to restore drag in source window: {update_result:?}"
9146 );
9147
9148 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
9149 let cancelled = start_drag(cx, cancelled_path.clone(), true);
9150 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
9151 window.dispatch_event(
9152 MouseMoveEvent {
9153 position: outside_position,
9154 pressed_button: Some(MouseButton::Left),
9155 modifiers: Default::default(),
9156 }
9157 .to_platform_input(),
9158 cx,
9159 );
9160 assert!(cx.active_drag.is_none());
9161
9162 window.dispatch_event(
9163 FileDropEvent::Entered {
9164 position: reentry_position,
9165 paths: ExternalPaths([cancelled_path].into_iter().collect()),
9166 }
9167 .to_platform_input(),
9168 cx,
9169 );
9170 assert!(
9171 cx.active_drag
9172 .as_ref()
9173 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9174 );
9175 assert!(cx.stop_active_drag(window));
9176 assert!(cx.active_drag.is_none());
9177 });
9178 assert!(
9179 update_result.is_ok(),
9180 "failed to cancel restored drag: {update_result:?}"
9181 );
9182 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
9183
9184 let removed_path = PathBuf::from("/tmp/removed-window-drag");
9185 let removed = start_drag(cx, removed_path, true);
9186 let removed_window_id = removed.window.window_id();
9187 let update_result = cx.update_window(removed.window, |_, window, cx| {
9188 window.dispatch_event(
9189 MouseMoveEvent {
9190 position: outside_position,
9191 pressed_button: Some(MouseButton::Left),
9192 modifiers: Default::default(),
9193 }
9194 .to_platform_input(),
9195 cx,
9196 );
9197 assert!(cx.active_drag.is_none());
9198 window.remove_window();
9199 });
9200 assert!(
9201 update_result.is_ok(),
9202 "failed to remove drag source window: {update_result:?}"
9203 );
9204 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
9205
9206 let failed_path = PathBuf::from("/tmp/failed-drag");
9207 let failed = start_drag(cx, failed_path.clone(), false);
9208 let update_result = cx.update_window(failed.window, |_, window, cx| {
9209 for x_position in [-1., -2.] {
9210 window.dispatch_event(
9211 MouseMoveEvent {
9212 position: point(px(x_position), px(20.)),
9213 pressed_button: Some(MouseButton::Left),
9214 modifiers: Default::default(),
9215 }
9216 .to_platform_input(),
9217 cx,
9218 );
9219 }
9220 assert!(cx.active_drag.is_some());
9221 });
9222 assert!(
9223 update_result.is_ok(),
9224 "failed to retain drag after platform failure: {update_result:?}"
9225 );
9226 assert_eq!(
9227 cx.test_window(failed.window).external_drag_files(),
9228 [(failed_path, true)]
9229 );
9230 }
9231
9232 struct FocusForwarder {
9233 a: FocusHandle,
9234 b: FocusHandle,
9235 }
9236
9237 impl Render for FocusForwarder {
9238 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9239 div()
9240 .size_full()
9241 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
9242 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
9243 }
9244 }
9245
9246 #[gpui::test]
9250 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
9251 let b_focus_count = Rc::new(Cell::new(0));
9252 let window = cx.add_window({
9253 let b_focus_count = b_focus_count.clone();
9254 move |window, cx| {
9255 let a = cx.focus_handle();
9256 let b = cx.focus_handle();
9257 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
9258 let b = this.b.clone();
9259 window.focus(&b, cx);
9260 })
9261 .detach();
9262 cx.on_focus(&b, window, move |_, _, _| {
9263 b_focus_count.set(b_focus_count.get() + 1);
9264 })
9265 .detach();
9266 FocusForwarder { a, b }
9267 }
9268 });
9269
9270 window
9271 .update(cx, |_, window, _| window.activate_window())
9272 .unwrap();
9273 cx.executor().run_until_parked();
9274
9275 window
9276 .update(cx, |this, window, cx| {
9277 let a = this.a.clone();
9278 window.focus(&a, cx);
9279 })
9280 .unwrap();
9281 cx.executor().run_until_parked();
9282
9283 window
9284 .update(cx, |this, window, _| {
9285 assert!(this.b.is_focused(window));
9286 })
9287 .unwrap();
9288 assert_eq!(b_focus_count.get(), 1);
9289 }
9290
9291 #[gpui::test]
9292 fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
9293 let events = Rc::new(RefCell::new(Vec::new()));
9294 let window = cx.add_window({
9295 let events = events.clone();
9296 move |_, _| TouchDragListener { events }
9297 });
9298 let touch = TouchId(1);
9299
9300 dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
9301 dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
9302 dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
9303
9304 assert_eq!(
9305 events.borrow().as_slice(),
9306 [
9307 (TouchPhase::Started, px(10.)),
9308 (TouchPhase::Moved, px(30.)),
9309 (TouchPhase::Ended, px(40.)),
9310 ]
9311 );
9312 }
9313
9314 struct TouchDragListener {
9315 events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
9316 }
9317
9318 impl Render for TouchDragListener {
9319 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9320 let events = self.events.clone();
9321 canvas(
9322 |_, _, _| {},
9323 move |_, _, window, _| {
9324 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
9325 if phase != DispatchPhase::Bubble {
9326 return;
9327 }
9328 events.borrow_mut().push((event.phase, event.position.x));
9329 if event.phase == TouchPhase::Started {
9330 window.prevent_default();
9331 }
9332 });
9333 },
9334 )
9335 }
9336 }
9337
9338 #[gpui::test]
9339 fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
9340 for response in [
9341 LongPressResponse::PreventDefault,
9342 LongPressResponse::StopPropagation,
9343 LongPressResponse::None,
9344 ] {
9345 let phases = Rc::new(RefCell::new(Vec::new()));
9346 let window = cx.add_window({
9347 let phases = phases.clone();
9348 move |_, _| LongPressListener { phases, response }
9349 });
9350 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9351 cx.executor().advance_clock(Duration::from_millis(501));
9352 cx.executor().run_until_parked();
9353 window
9354 .update(cx, |_, window, _| {
9355 assert_eq!(
9356 window.long_press_capture.is_some(),
9357 response == LongPressResponse::PreventDefault
9358 );
9359 })
9360 .unwrap();
9361 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
9362 dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
9363 window
9364 .update(cx, |_, window, _| {
9365 assert!(window.long_press_capture.is_none());
9366 })
9367 .unwrap();
9368
9369 let phases = phases.borrow();
9370 if response == LongPressResponse::PreventDefault {
9371 assert_eq!(
9372 phases.as_slice(),
9373 [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
9374 );
9375 } else {
9376 assert_eq!(phases.as_slice(), [TouchPhase::Started]);
9377 }
9378 }
9379 }
9380
9381 #[gpui::test]
9382 fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
9383 let phases = Rc::new(RefCell::new(Vec::new()));
9384 let window = cx.add_window({
9385 let phases = phases.clone();
9386 move |_, _| LongPressListener {
9387 phases,
9388 response: LongPressResponse::None,
9389 }
9390 });
9391 window
9392 .update(cx, |_, window, _| {
9393 window.prevent_default();
9394 })
9395 .unwrap();
9396
9397 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9398 cx.executor().advance_clock(Duration::from_millis(501));
9399 cx.executor().run_until_parked();
9400 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
9401
9402 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
9403 }
9404
9405 #[gpui::test]
9406 fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
9407 for (phase, position) in [
9408 (TouchPhase::Ended, 0.),
9409 (TouchPhase::Cancelled, 0.),
9410 (TouchPhase::Moved, 20.),
9411 ] {
9412 let phases = Rc::new(RefCell::new(Vec::new()));
9413 let window = cx.add_window({
9414 let phases = phases.clone();
9415 move |_, _| LongPressListener {
9416 phases,
9417 response: LongPressResponse::PreventDefault,
9418 }
9419 });
9420 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9421 dispatch_touch(window, cx, TouchId(1), phase, position);
9422 cx.executor().advance_clock(Duration::from_millis(501));
9423 cx.executor().run_until_parked();
9424
9425 assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
9426 }
9427 }
9428
9429 #[gpui::test]
9430 fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
9431 let phases = Rc::new(RefCell::new(Vec::new()));
9432 let window = cx.add_window({
9433 let phases = phases.clone();
9434 move |_, _| LongPressListener {
9435 phases,
9436 response: LongPressResponse::PreventDefault,
9437 }
9438 });
9439 let first_touch = TouchId(1);
9440 dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
9441 cx.executor().advance_clock(Duration::from_millis(250));
9442 dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
9443 dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
9444
9445 cx.executor().advance_clock(Duration::from_millis(251));
9446 cx.executor().run_until_parked();
9447 assert!(phases.borrow().is_empty());
9448
9449 cx.executor().advance_clock(Duration::from_millis(250));
9450 cx.executor().run_until_parked();
9451 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
9452 }
9453
9454 #[gpui::test]
9455 fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
9456 test_underline_paint_at_scales(cx, |window| {
9457 let (numerator, denominator) = match window.scale_factor() {
9458 1.0 => (1, 1),
9459 1.25 => (5, 4),
9460 1.5 => (3, 2),
9461 2.0 => (2, 1),
9462 3.0 => (3, 1),
9463 scale => panic!("unexpected scale {scale}"),
9464 };
9465 let snap = |quarters: i32| {
9466 let scaled = quarters * numerator;
9467 let divisor = 4 * denominator;
9468 let rounded =
9469 scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
9470 ScaledPixels((scaled.signum() * rounded) as f32)
9471 };
9472 let stroke = |quarters| {
9473 if quarters == 0 {
9474 ScaledPixels(0.)
9475 } else {
9476 snap(quarters).max(ScaledPixels(1.))
9477 }
9478 };
9479
9480 for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
9481 for width in [0, 1, 3, 84] {
9482 for thickness in [0, 1, 4, 7] {
9483 for wavy in [false, true] {
9484 let style = UnderlineStyle {
9485 thickness: px(thickness as f32 / 4.),
9486 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
9487 wavy,
9488 };
9489 let bounds = Bounds::new(
9490 point(snap(origin), snap(-origin)),
9491 size(
9492 stroke(width),
9493 stroke(thickness) * if wavy { 3. } else { 1. },
9494 ),
9495 );
9496 let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
9497 let width = px(width as f32 / 4.);
9498 assert_eq!(window.underline_bounds(origin, width, &style), bounds);
9499 let original = paint_test_underlines(window, |window| {
9500 window.paint_underline(origin, width, &style);
9501 })
9502 .to_vec();
9503 assert_eq!(original.len(), usize::from(!bounds.is_empty()));
9504 if let Some(underline) = original.first() {
9505 assert_eq!(underline.bounds, bounds);
9506 assert_eq!(underline.thickness, stroke(thickness));
9507 assert_eq!(underline.wavy, wavy.into());
9508 assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
9509 }
9510
9511 let underlines = paint_test_underlines(window, |window| {
9512 window.paint_underline_with_exclusions(origin, width, &style, &[]);
9513 });
9514 assert_eq!(underlines.len(), original.len());
9515 for (actual, original) in underlines.iter().zip(&original) {
9516 assert_same_underline_geometry(actual, original);
9517 assert_eq!(actual.content_mask, original.content_mask);
9518 }
9519
9520 let left = bounds.left().0 as i32;
9521 let right = bounds.right().0 as i32;
9522 let exclusions = [
9523 (15, 25),
9524 (3, 7),
9525 (5, 10),
9526 (10, 12),
9527 (0, 0),
9528 (4, 2),
9529 (-50, -1),
9530 (70, 100),
9531 ]
9532 .map(|(start, end)| {
9533 ScaledPixels((left + start) as f32)
9534 ..ScaledPixels((left + end) as f32)
9535 });
9536 let underlines = paint_test_underlines(window, |window| {
9537 window.paint_underline_with_exclusions(
9538 origin,
9539 width,
9540 &style,
9541 &exclusions,
9542 );
9543 });
9544 let expected = (left..right)
9545 .filter(|column| {
9546 !bounds.is_empty()
9547 && !exclusions.iter().any(|span| {
9548 span.contains(&ScaledPixels(*column as f32))
9549 })
9550 })
9551 .collect::<Vec<_>>();
9552 assert_eq!(underline_device_columns(underlines), expected);
9553 for underline in underlines {
9554 assert_same_underline_geometry(underline, &original[0]);
9555 }
9556 }
9557 }
9558 }
9559 }
9560 });
9561 }
9562
9563 #[gpui::test]
9564 fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
9565 test_underline_paint_at_scales(cx, |window| {
9566 if window.scale_factor() != 2.0 {
9567 return;
9568 }
9569 let style = UnderlineStyle {
9570 thickness: px(1.),
9571 color: None,
9572 wavy: true,
9573 };
9574 let origin = point(px(2.888_183_8), px(15.357_917));
9575 let width = px(23.848_145) - origin.x;
9576 let original = paint_test_underlines(window, |window| {
9577 window.paint_underline(origin, width, &style);
9578 })[0];
9579 assert_eq!(original.bounds.left(), ScaledPixels(6.));
9580 assert_eq!(original.bounds.right(), ScaledPixels(48.));
9581 let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
9582 assert_eq!(point_bounds.left(), ScaledPixels(6.));
9583 assert_eq!(point_bounds.right(), ScaledPixels(28.));
9584
9585 let underlines = paint_test_underlines(window, |window| {
9586 window.paint_underline_with_exclusions(
9587 origin,
9588 width,
9589 &style,
9590 &[point_bounds.left()..point_bounds.right()],
9591 );
9592 });
9593 assert_eq!(underlines.len(), 1);
9594 assert_same_underline_geometry(&underlines[0], &original);
9595 assert_eq!(
9596 underline_device_columns(underlines),
9597 (28..48).collect::<Vec<_>>()
9598 );
9599 });
9600 }
9601
9602 #[gpui::test]
9603 fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
9604 test_underline_paint_at_scales(cx, |window| {
9605 let scale = window.scale_factor();
9606 let original_mask = window.content_mask();
9607 let original_opacity = window.element_opacity();
9608 let mask = ContentMask {
9609 bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
9610 };
9611 let style = UnderlineStyle {
9612 thickness: px(2.),
9613 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
9614 wavy: true,
9615 };
9616 let origin = point(px(-1.25), px(9.25));
9617 let width = px(24.);
9618 window.with_content_mask(Some(mask), |window| {
9619 window.with_element_opacity(Some(0.5), |window| {
9620 window.with_element_opacity(Some(0.5), |window| {
9621 let original = paint_test_underlines(window, |window| {
9622 window.paint_underline(origin, width, &style);
9623 })[0];
9624 assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
9625 let underlines = paint_test_underlines(window, |window| {
9626 window.paint_underline_with_exclusions(
9627 origin,
9628 width,
9629 &style,
9630 &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
9631 );
9632 });
9633 assert_eq!(underlines.len(), 2);
9634 let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
9635 |(left, right)| {
9636 Bounds::from_corners(
9637 point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
9638 point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
9639 )
9640 },
9641 );
9642 assert_eq!(
9643 underlines
9644 .iter()
9645 .map(|underline| underline.content_mask.bounds)
9646 .collect::<Vec<_>>(),
9647 expected
9648 );
9649 for underline in underlines {
9650 assert_same_underline_geometry(underline, &original);
9651 }
9652 });
9653 });
9654 });
9655 assert_eq!(window.content_mask(), original_mask);
9656 assert_eq!(window.element_opacity(), original_opacity);
9657 });
9658 }
9659
9660 #[gpui::test]
9661 fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
9662 test_underline_paint_at_scales(cx, |window| {
9663 let style = UnderlineStyle {
9664 thickness: px(1.),
9665 color: None,
9666 wavy: true,
9667 };
9668 let origin = point(px(-4.), px(-1.));
9669 let width = px(8.);
9670 let left = (-4. * window.scale_factor()) as i32;
9671 let right = (4. * window.scale_factor()) as i32;
9672 let endpoints = [-16, -8, -1, 0, 1, 8, 16];
9673 for first_start in endpoints {
9674 for first_end in endpoints {
9675 for second_start in endpoints {
9676 for second_end in endpoints {
9677 let exclusions = [first_start..first_end, second_start..second_end];
9678 let expected = (left..right)
9679 .filter(|column| {
9680 !exclusions.iter().any(|span| span.contains(column))
9681 })
9682 .collect::<Vec<_>>();
9683 let exclusions = exclusions.map(|span| {
9684 ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
9685 });
9686 let underlines = paint_test_underlines(window, |window| {
9687 window.paint_underline_with_exclusions(
9688 origin,
9689 width,
9690 &style,
9691 &exclusions,
9692 );
9693 });
9694 assert_eq!(
9695 underline_device_columns(underlines),
9696 expected,
9697 "{exclusions:?}"
9698 );
9699 }
9700 }
9701 }
9702 }
9703 });
9704 }
9705
9706 #[derive(Clone, Copy, PartialEq)]
9707 enum LongPressResponse {
9708 PreventDefault,
9709 StopPropagation,
9710 None,
9711 }
9712
9713 struct LongPressListener {
9714 phases: Rc<RefCell<Vec<TouchPhase>>>,
9715 response: LongPressResponse,
9716 }
9717
9718 impl Render for LongPressListener {
9719 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
9720 let entity = cx.entity();
9721 let phases = self.phases.clone();
9722 let response = self.response;
9723 canvas(
9724 |_, _, _| {},
9725 move |_, _, window, _| {
9726 window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
9727 if phase != DispatchPhase::Bubble {
9728 return;
9729 }
9730 phases.borrow_mut().push(event.phase);
9731 match response {
9732 LongPressResponse::PreventDefault => {
9733 window.capture_long_press(&entity);
9734 window.prevent_default();
9735 }
9736 LongPressResponse::StopPropagation => cx.stop_propagation(),
9737 LongPressResponse::None => {}
9738 }
9739 });
9740 },
9741 )
9742 }
9743 }
9744
9745 struct UnderlineTestView(Rc<dyn Fn(&mut Window)>);
9746
9747 impl Render for UnderlineTestView {
9748 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9749 let paint = self.0.clone();
9750 canvas(
9751 |_, _, _| {},
9752 move |_, _, window, _| {
9753 window.content_mask_stack.push(ContentMask {
9754 bounds: Bounds::from_corners(
9755 point(px(-1000.), px(-1000.)),
9756 point(px(1000.), px(1000.)),
9757 ),
9758 });
9759 paint(window);
9760 window.content_mask_stack.pop();
9761 },
9762 )
9763 .size_full()
9764 }
9765 }
9766
9767 fn test_underline_paint_at_scales(
9768 cx: &mut TestAppContext,
9769 paint: impl Fn(&mut Window) + 'static,
9770 ) {
9771 let window = cx.add_window(move |_, _| UnderlineTestView(Rc::new(paint)));
9772 for scale in [1., 1.25, 1.5, 2., 3.] {
9773 cx.simulate_window_scale_factor_change(window.into(), scale);
9774 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
9775 .unwrap();
9776 }
9777 }
9778
9779 fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
9780 window.next_frame.scene.clear();
9781 paint(window);
9782 &window.next_frame.scene.underlines
9783 }
9784
9785 fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
9786 assert_eq!(actual.bounds, expected.bounds);
9787 assert_eq!(actual.thickness, expected.thickness);
9788 assert_eq!(actual.wavy, expected.wavy);
9789 assert_eq!(actual.color, expected.color);
9790 assert_eq!(actual.pad, expected.pad);
9791 }
9792
9793 fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
9794 underlines
9795 .iter()
9796 .flat_map(|underline| {
9797 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
9798 bounds.left().0 as i32..bounds.right().0 as i32
9799 })
9800 .collect()
9801 }
9802
9803 fn dispatch_touch<T: 'static>(
9804 window: crate::WindowHandle<T>,
9805 cx: &mut TestAppContext,
9806 id: TouchId,
9807 phase: TouchPhase,
9808 x: f32,
9809 ) {
9810 window
9811 .update(cx, |_, window, cx| {
9812 window.dispatch_event(
9813 TouchEvent {
9814 id,
9815 phase,
9816 position: point(px(x), px(0.)),
9817 predicted_position: None,
9818 force: None,
9819 }
9820 .to_platform_input(),
9821 cx,
9822 );
9823 })
9824 .unwrap();
9825 }
9826}
9827
9828#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
9829mod inspector_tests {
9830 use super::*;
9831 use crate::{
9832 DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
9833 };
9834
9835 #[gpui::test]
9836 fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
9837 let windows = [
9838 cx.add_window(|_, cx| InspectorTestRoot {
9839 child: cx.new(|_| InspectorTestView::default()),
9840 }),
9841 cx.add_window(|_, cx| InspectorTestRoot {
9842 child: cx.new(|_| InspectorTestView::default()),
9843 }),
9844 ];
9845 for window in windows {
9846 assert_closed_inspector(window.into(), cx);
9847 }
9848 for _ in 0..2 {
9849 cx.update_window(windows[0].into(), |root, window, cx| {
9850 let root = root.downcast::<InspectorTestRoot>().expect("test root");
9851 let child_widths = root.read(cx).child.read(cx).child_widths.clone();
9852 window.toggle_inspector(cx);
9853 window.draw(cx).clear(cx);
9854 assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
9855 let path = window
9856 .rendered_frame
9857 .next_inspector_instance_ids
9858 .iter()
9859 .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
9860 .expect("anonymous siblings share an inspector path");
9861 let selected_id = InspectorElementId {
9862 path,
9863 instance_id: 1,
9864 };
9865 let position = window
9866 .rendered_frame
9867 .hitboxes
9868 .iter()
9869 .find(|hitbox| {
9870 window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
9871 == Some(&selected_id)
9872 })
9873 .expect("middle sibling is pickable")
9874 .bounds
9875 .center();
9876 window.simulate_mouse_move(position, cx);
9877 window.dispatch_event(
9878 PlatformInput::MouseDown(MouseDownEvent {
9879 position,
9880 button: MouseButton::Left,
9881 modifiers: Modifiers::default(),
9882 click_count: 1,
9883 first_mouse: false,
9884 }),
9885 cx,
9886 );
9887 window.dispatch_event(
9888 PlatformInput::MouseUp(MouseUpEvent {
9889 position,
9890 button: MouseButton::Left,
9891 modifiers: Modifiers::default(),
9892 click_count: 1,
9893 }),
9894 cx,
9895 );
9896 assert!(!window.is_inspector_picking(cx));
9897 assert_eq!(
9898 window
9899 .inspector
9900 .as_ref()
9901 .expect("open inspector")
9902 .read(cx)
9903 .active_element_id(),
9904 Some(&selected_id)
9905 );
9906 window.draw(cx).clear(cx);
9907 window.with_inspector_state::<DivInspectorState, _>(
9908 Some(&selected_id),
9909 cx,
9910 |state, _| {
9911 let state = state.as_mut().expect("selected div has style state");
9912 assert_eq!(
9913 state.base_style.size.width,
9914 Some(crate::Length::from(px(10.)))
9915 );
9916 state.base_style.size.width = Some(crate::Length::from(px(25.)));
9917 },
9918 );
9919 window.refresh();
9920 window.draw(cx).clear(cx);
9921 assert_eq!(
9922 child_widths.borrow().as_slice(),
9923 &[px(10.), px(25.), px(10.)]
9924 );
9925 })
9926 .expect("pick and edit a cached child");
9927 assert_closed_inspector(windows[1].into(), cx);
9928 windows[0]
9929 .update(cx, |_, window, cx| window.toggle_inspector(cx))
9930 .expect("close inspector");
9931 assert_closed_inspector(windows[0].into(), cx);
9932 }
9933 }
9934
9935 struct InspectorTestRoot {
9936 child: Entity<InspectorTestView>,
9937 }
9938
9939 impl Render for InspectorTestRoot {
9940 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9941 self.child
9942 .clone()
9943 .cached(StyleRefinement::default().size(px(100.)))
9944 }
9945 }
9946
9947 #[derive(Default)]
9948 struct InspectorTestView {
9949 child_widths: Rc<RefCell<Vec<Pixels>>>,
9950 }
9951
9952 impl Render for InspectorTestView {
9953 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9954 let child_widths = self.child_widths.clone();
9955 div()
9956 .on_children_prepainted(move |bounds, _, _| {
9957 *child_widths.borrow_mut() =
9958 bounds.iter().map(|bounds| bounds.size.width).collect();
9959 })
9960 .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
9961 .id("inspector-root")
9962 .flex()
9963 .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
9964 }
9965 }
9966
9967 fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
9968 cx.update_window(window, |root, window, cx| {
9969 window.draw(cx).clear(cx);
9970 window.draw(cx).clear(cx);
9971 let root = root.downcast::<InspectorTestRoot>().expect("test root");
9972 assert_eq!(
9973 root.read(cx)
9974 .child
9975 .read(cx)
9976 .child_widths
9977 .borrow()
9978 .as_slice(),
9979 &[px(10.); 3]
9980 );
9981 for frame in [&window.rendered_frame, &window.next_frame] {
9982 assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
9983 assert_eq!(frame.inspector_hitboxes.capacity(), 0);
9984 }
9985 })
9986 .expect("closed inspector has no bookkeeping and no style overrides");
9987 }
9988}