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, cx: &App) -> String {
5673 self.highest_precedence_binding_for_action(action)
5674 .map(|binding| {
5675 binding
5676 .keystrokes()
5677 .iter()
5678 .map(|keystroke| keystroke.display(cx.platform_info().os).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::Scroll(scroll_wheel) => {
5742 self.mouse_position = scroll_wheel.position;
5743 self.modifiers = scroll_wheel.modifiers;
5744 PlatformInput::Scroll(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::BackGesture(back) => {
5820 self.mouse_position = back.start_position;
5821 PlatformInput::BackGesture(back)
5822 }
5823 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
5824 };
5825 crate::fast::dependencies::AmbientInput::stamp_changes(ambient, self, cx);
5826 crate::fast::layers::input::before_dispatch(self, cx, &event);
5827
5828 let native_target = crate::fast::composition::event_target(self, &event);
5829 if let Some(any_mouse_event) = event.mouse_event() {
5830 self.dispatch_mouse_event(any_mouse_event, cx);
5831 } else if let Some(any_key_event) = event.keyboard_event() {
5832 self.dispatch_key_event(any_key_event, cx);
5833 } else if let Some(touch_event) = event.touch_event() {
5834 self.dispatch_touch_event(touch_event, cx);
5835 }
5836 crate::fast::composition::dispatch_native(
5837 self,
5838 &event,
5839 native_target,
5840 &mut cx.propagate_event,
5841 );
5842 crate::fast::layers::wheel::end_dispatch(self, cx);
5843 if let PlatformInput::LongPress(long_press) = &event {
5844 match long_press.phase {
5845 crate::TouchPhase::Started if !self.default_prevented => {
5846 self.long_press_capture = None;
5847 }
5848 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
5849 self.long_press_capture = None;
5850 }
5851 crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
5852 }
5853 }
5854
5855 self.promote_external_drag_to_platform(&event, cx);
5858
5859 let caused_invalidation = self.invalidator.update_count() > update_count_before;
5860 if caused_invalidation {
5861 self.input_rate_tracker.borrow_mut().record_input();
5862 }
5863 #[cfg(feature = "profiler")]
5864 self.window_profiler.end_input(caused_invalidation);
5865
5866 DispatchEventResult {
5867 propagate: cx.propagate_event,
5868 default_prevented: self.default_prevented,
5869 }
5870 }
5871
5872 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
5873 let PlatformInput::MouseMove(mouse_move) = event else {
5874 return;
5875 };
5876 if mouse_move.pressed_button != Some(MouseButton::Left) {
5877 return;
5878 }
5879 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
5880 return;
5881 }
5882 if !self.platform_window.can_start_external_drag() {
5883 return;
5884 }
5885 let Some(payload_source) = cx
5886 .active_drag
5887 .as_mut()
5888 .and_then(|drag| drag.external_payload_source.take())
5889 else {
5890 return;
5891 };
5892 let Some(payload) = payload_source(self, cx) else {
5893 return;
5894 };
5895 if self.platform_window.start_external_drag(&payload)
5896 && cx.hand_active_drag_to_platform(self.handle.window_id())
5897 {
5898 self.refresh();
5899 }
5900 }
5901
5902 pub fn touch_prediction_enabled(&self) -> bool {
5906 self.touch_prediction_enabled
5907 }
5908
5909 pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
5913 self.touch_prediction_enabled = enabled;
5914 }
5915
5916 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
5920 let mut event = event.clone();
5921 if !self.touch_prediction_enabled {
5922 event.predicted_position = None;
5923 }
5924 let recognized_gestures = self.touch_gestures.handle_event(&event);
5925 if event.phase == crate::TouchPhase::Started
5926 && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
5927 {
5928 self.dispatch_recognized_touch_gesture(touch_drag, cx);
5929 }
5930 if event.phase == crate::TouchPhase::Started
5931 && self.touch_gestures.pending_long_press().is_some()
5932 {
5933 self.long_press_capture = None;
5934 }
5935 let mut tapped = false;
5936 for gesture in recognized_gestures {
5937 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
5938 self.dispatch_recognized_touch_gesture(gesture, cx);
5939 }
5940 if event.phase == crate::TouchPhase::Started {
5941 self.schedule_long_press_timer(cx);
5942 } else if self.touch_gestures.pending_long_press().is_none() {
5943 self.long_press_timer.take();
5944 }
5945 if tapped && self.invalidator.is_dirty() {
5951 self.draw(cx).clear(cx);
5952 }
5953 if self.touch_gestures.has_momentum() {
5954 self.schedule_touch_momentum_tick();
5955 }
5956 }
5957
5958 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
5959 match gesture {
5960 RecognizedTouchGesture::Scroll(scroll_wheel) => {
5961 self.mouse_position = scroll_wheel.position;
5962 cx.propagate_event = true;
5963 self.dispatch_mouse_event(&scroll_wheel, cx);
5964 }
5965 RecognizedTouchGesture::Tap { down, up } => {
5966 self.mouse_position = up.position;
5967 cx.propagate_event = true;
5968 self.dispatch_mouse_event(&down, cx);
5969 cx.propagate_event = true;
5970 self.dispatch_mouse_event(&up, cx);
5971 }
5972 RecognizedTouchGesture::TouchDrag(touch_drag) => {
5973 self.mouse_position = touch_drag.start_position;
5974 cx.propagate_event = true;
5975 self.default_prevented = false;
5976 let started = touch_drag.phase == crate::TouchPhase::Started;
5977 self.dispatch_mouse_event(&touch_drag, cx);
5978 if started {
5979 self.touch_gestures
5980 .resolve_touch_drag(self.default_prevented);
5981 }
5982 }
5983 RecognizedTouchGesture::LongPress(long_press) => {
5984 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
5985 long_press.start_position
5986 } else {
5987 long_press.position
5988 };
5989 cx.propagate_event = true;
5990 self.default_prevented = false;
5991 let started = long_press.phase == crate::TouchPhase::Started;
5992 let ended = matches!(
5993 long_press.phase,
5994 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
5995 );
5996 self.dispatch_mouse_event(&long_press, cx);
5997 if started {
5998 let claimed = self.default_prevented;
5999 self.touch_gestures.resolve_long_press(claimed);
6000 if !claimed {
6001 self.long_press_capture = None;
6002 }
6003 }
6004 if ended {
6005 self.long_press_capture = None;
6006 }
6007 }
6008 }
6009 }
6010
6011 fn schedule_long_press_timer(&mut self, cx: &mut App) {
6012 self.long_press_timer.take();
6013 let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
6014 return;
6015 };
6016 self.long_press_timer = Some(self.spawn(cx, async move |cx| {
6017 cx.background_executor.timer(duration).await;
6018 cx.update(move |window, cx| {
6019 window.long_press_timer.take();
6020 if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
6021 window.dispatch_recognized_touch_gesture(gesture, cx);
6022 }
6023 })
6024 .log_err();
6025 }));
6026 }
6027
6028 fn schedule_touch_momentum_tick(&mut self) {
6029 self.on_next_frame(|window, cx| {
6030 if let Some(gesture) = window.touch_gestures.tick_momentum() {
6031 window.dispatch_recognized_touch_gesture(gesture, cx);
6032 }
6033 if window.touch_gestures.has_momentum() {
6034 window.schedule_touch_momentum_tick();
6035 }
6036 });
6037 }
6038
6039 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6040 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
6041 if hit_test != self.mouse_hit_test {
6042 self.mouse_hit_test = hit_test;
6043 self.reset_cursor_style(cx);
6044 }
6045
6046 #[cfg(any(feature = "inspector", debug_assertions))]
6047 if self.is_inspector_picking(cx) {
6048 self.handle_inspector_mouse_event(event, cx);
6049 return;
6051 }
6052
6053 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
6054
6055 for listener in &mut mouse_listeners {
6058 let listener = listener.as_mut().unwrap();
6059 listener(event, DispatchPhase::Capture, self, cx);
6060 if !cx.propagate_event {
6061 break;
6062 }
6063 }
6064
6065 if crate::fast::composition::bubble_mouse(self, event, cx) {
6067 for listener in mouse_listeners.iter_mut().rev() {
6068 let listener = listener.as_mut().unwrap();
6069 listener(event, DispatchPhase::Bubble, self, cx);
6070 if !cx.propagate_event {
6071 break;
6072 }
6073 }
6074 }
6075
6076 self.rendered_frame.mouse_listeners = mouse_listeners;
6077
6078 if cx.has_active_drag() {
6079 if event.is::<MouseMoveEvent>() {
6080 self.refresh();
6083 } else if event.is::<MouseUpEvent>() {
6084 cx.active_drag = None;
6087 self.refresh();
6088 }
6089 }
6090
6091 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
6093 self.captured_hitbox = None;
6094 }
6095 }
6096
6097 fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
6100 let prefer_character_input = event
6101 .downcast_ref::<KeyDownEvent>()
6102 .is_some_and(|key_down_event| key_down_event.prefer_character_input);
6103 if !prefer_character_input {
6104 return InputPreference::KeyBindings;
6105 }
6106 let Some(mut input_handler) = self.platform_window.take_input_handler() else {
6107 return InputPreference::KeyBindings;
6108 };
6109 let accepts_text_input = input_handler.accepts_text_input(self, cx);
6110 self.platform_window.set_input_handler(input_handler);
6111 if accepts_text_input {
6112 InputPreference::CharacterInput
6113 } else {
6114 InputPreference::KeyBindings
6115 }
6116 }
6117
6118 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
6119 if self.invalidator.is_dirty() {
6120 self.draw(cx).clear(cx);
6121 }
6122
6123 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6124 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6125
6126 let mut keystroke: Option<Keystroke> = None;
6127
6128 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
6129 if event.modifiers.number_of_modifiers() == 0
6130 && self.pending_modifier.modifiers.number_of_modifiers() == 1
6131 && !self.pending_modifier.saw_other_input
6132 {
6133 let key = match self.pending_modifier.modifiers {
6134 modifiers if modifiers.shift => Some("shift"),
6135 modifiers if modifiers.control => Some("control"),
6136 modifiers if modifiers.alt => Some("alt"),
6137 modifiers if modifiers.platform => Some("platform"),
6138 modifiers if modifiers.function => Some("function"),
6139 _ => None,
6140 };
6141 if let Some(key) = key {
6142 keystroke = Some(Keystroke {
6143 key: key.to_string(),
6144 key_char: None,
6145 modifiers: Modifiers::default(),
6146 });
6147 }
6148 }
6149
6150 if self.pending_modifier.modifiers.number_of_modifiers() == 0
6151 && event.modifiers.number_of_modifiers() == 1
6152 {
6153 self.pending_modifier.saw_other_input = false
6154 } else if event.modifiers.number_of_modifiers() > 1 {
6155 self.pending_modifier.saw_other_input = true
6156 }
6157 self.pending_modifier.modifiers = event.modifiers
6158 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
6159 self.pending_modifier.saw_other_input = true;
6160 keystroke = Some(key_down_event.keystroke.clone());
6161 if key_down_event.keystroke.key_char.is_some()
6162 && matches!(
6163 cx.cursor_hide_mode,
6164 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
6165 )
6166 {
6167 cx.platform.hide_cursor_until_mouse_moves();
6168 }
6169 }
6170
6171 let Some(keystroke) = keystroke else {
6172 self.finish_dispatch_key_event(
6173 event,
6174 None,
6175 InputPreference::KeyBindings,
6176 dispatch_path,
6177 self.context_stack(),
6178 cx,
6179 );
6180 return;
6181 };
6182
6183 let input_preference = self.input_preference(event, cx);
6184
6185 cx.propagate_event = true;
6186 self.dispatch_keystroke_interceptors(
6187 &keystroke,
6188 input_preference,
6189 self.context_stack(),
6190 cx,
6191 );
6192 if !cx.propagate_event {
6193 self.finish_dispatch_key_event(
6194 event,
6195 Some(&keystroke),
6196 input_preference,
6197 dispatch_path,
6198 self.context_stack(),
6199 cx,
6200 );
6201 return;
6202 }
6203
6204 let mut currently_pending = self.pending_input.take().unwrap_or_default();
6205 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
6206 currently_pending = PendingInput::default();
6207 }
6208
6209 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
6210 currently_pending.keystrokes,
6211 keystroke.clone(),
6212 &dispatch_path,
6213 );
6214
6215 if !match_result.to_replay.is_empty() {
6216 self.replay_pending_input(match_result.to_replay, cx);
6217 cx.propagate_event = true;
6218 }
6219
6220 if !match_result.pending.is_empty() {
6221 let previous_timeout = currently_pending.timeout.take();
6222 currently_pending.keystrokes = match_result.pending;
6223 currently_pending.focus = self.focus;
6224
6225 let text_input_requires_timeout = event
6226 .downcast_ref::<KeyDownEvent>()
6227 .filter(|key_down| key_down.keystroke.key_char.is_some())
6228 .and_then(|_| self.platform_window.take_input_handler())
6229 .map_or(false, |mut input_handler| {
6230 let accepts = input_handler.accepts_text_input(self, cx);
6231 self.platform_window.set_input_handler(input_handler);
6232 accepts
6233 });
6234
6235 let needs_timeout = previous_timeout.is_some()
6236 || match_result.pending_has_binding
6237 || text_input_requires_timeout;
6238 currently_pending.timeout = if needs_timeout {
6239 match previous_timeout {
6240 Some(mut timeout) if timeout.is_paused() => {
6241 timeout.reset_duration(PENDING_INPUT_TIMEOUT);
6242 Some(timeout)
6243 }
6244 previous_timeout => {
6245 drop(previous_timeout);
6246 Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
6247 }
6248 }
6249 } else {
6250 None
6251 };
6252 self.pending_input = Some(currently_pending);
6253 self.pending_input_changed(cx);
6254 cx.propagate_event = false;
6255 return;
6256 }
6257
6258 let input_preference = self.input_preference(event, cx);
6260 if input_preference == InputPreference::KeyBindings {
6261 for binding in match_result.bindings {
6262 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6263 if !cx.propagate_event {
6264 self.dispatch_keystroke_observers(
6265 &keystroke,
6266 input_preference,
6267 Some(binding.action.as_ref()),
6268 match_result.context_stack,
6269 cx,
6270 );
6271 self.pending_input_changed(cx);
6272 return;
6273 }
6274 }
6275 }
6276
6277 self.finish_dispatch_key_event(
6278 event,
6279 Some(&keystroke),
6280 input_preference,
6281 dispatch_path,
6282 match_result.context_stack,
6283 cx,
6284 );
6285 self.pending_input_changed(cx);
6286 }
6287
6288 fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
6289 let (started_at, task) = self.start_pending_input_timeout(duration, cx);
6290 PendingInputTimeout {
6291 duration,
6292 remaining: duration,
6293 state: PendingInputTimeoutState::Running { started_at, task },
6294 }
6295 }
6296
6297 fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
6298 let started_at = cx.background_executor().now();
6299 let task = self.spawn(cx, async move |cx| {
6300 cx.background_executor.timer(remaining).await;
6301 cx.update(move |window, cx| {
6302 let Some(currently_pending) = window
6303 .pending_input
6304 .take()
6305 .filter(|pending| pending.focus == window.focus)
6306 else {
6307 return;
6308 };
6309
6310 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
6311 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
6312
6313 let to_replay = window
6314 .rendered_frame
6315 .dispatch_tree
6316 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
6317
6318 window.pending_input_changed(cx);
6319 window.replay_pending_input(to_replay, cx)
6320 })
6321 .log_err();
6322 });
6323 (started_at, task)
6324 }
6325
6326 fn finish_dispatch_key_event(
6327 &mut self,
6328 event: &dyn Any,
6329 recognized_keystroke: Option<&Keystroke>,
6330 input_preference: InputPreference,
6331 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
6332 context_stack: Vec<KeyContext>,
6333 cx: &mut App,
6334 ) {
6335 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
6336 if !cx.propagate_event {
6337 return;
6338 }
6339
6340 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
6341 if !cx.propagate_event {
6342 return;
6343 }
6344
6345 if let Some(keystroke) = recognized_keystroke {
6346 self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
6347 }
6348 }
6349
6350 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
6351 self.pending_input_observers
6352 .clone()
6353 .retain(&(), |callback| callback(self, cx));
6354 }
6355
6356 fn defer_pending_input_changed(&self, cx: &mut App) {
6357 let window_handle = self.handle;
6360 cx.defer(move |cx| {
6361 window_handle
6362 .update(cx, |_, window, cx| {
6363 window.pending_input_changed(cx);
6364 })
6365 .ok();
6366 });
6367 }
6368
6369 fn dispatch_key_down_up_event(
6370 &mut self,
6371 event: &dyn Any,
6372 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6373 cx: &mut App,
6374 ) {
6375 for node_id in dispatch_path {
6377 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6378
6379 for key_listener in node.key_listeners.clone() {
6380 key_listener(event, DispatchPhase::Capture, self, cx);
6381 if !cx.propagate_event {
6382 return;
6383 }
6384 }
6385 }
6386
6387 for node_id in dispatch_path.iter().rev() {
6389 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6391 for key_listener in node.key_listeners.clone() {
6392 key_listener(event, DispatchPhase::Bubble, self, cx);
6393 if !cx.propagate_event {
6394 return;
6395 }
6396 }
6397 }
6398 }
6399
6400 fn dispatch_modifiers_changed_event(
6401 &mut self,
6402 event: &dyn Any,
6403 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
6404 cx: &mut App,
6405 ) {
6406 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
6407 return;
6408 };
6409 for node_id in dispatch_path.iter().rev() {
6410 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6411 for listener in node.modifiers_changed_listeners.clone() {
6412 listener(event, self, cx);
6413 if !cx.propagate_event {
6414 return;
6415 }
6416 }
6417 }
6418 }
6419
6420 pub fn has_pending_keystrokes(&self) -> bool {
6422 self.pending_input().is_some()
6423 }
6424
6425 #[cfg(test)]
6426 pub(crate) fn pending_input_is_none(&self) -> bool {
6427 self.pending_input.is_none()
6428 }
6429
6430 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
6431 if self.pending_input.take().is_some() {
6432 self.defer_pending_input_changed(cx);
6433 }
6434 }
6435
6436 pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
6439 self.pending_input
6440 .as_ref()
6441 .filter(|pending_input| pending_input.focus == self.focus)
6442 .map(|pending_input| PendingInputStatus {
6443 keystrokes: pending_input.keystrokes.as_slice(),
6444 timeout: pending_input
6445 .timeout
6446 .as_ref()
6447 .map(PendingInputTimeout::status),
6448 })
6449 }
6450
6451 pub fn set_pending_input_timeout_paused<T: 'static>(
6456 &mut self,
6457 owner: &Entity<T>,
6458 paused: bool,
6459 cx: &mut App,
6460 ) -> bool {
6461 let owner_id = owner.entity_id();
6462 if !paused {
6463 return self.resume_pending_input_timeout(owner_id, cx);
6464 }
6465
6466 let timeout = self
6467 .pending_input
6468 .as_ref()
6469 .filter(|pending_input| pending_input.focus == self.focus)
6470 .and_then(|pending_input| pending_input.timeout.as_ref());
6471 let Some(timeout) = timeout else {
6472 return false;
6473 };
6474 if timeout.is_paused() {
6475 return false;
6476 }
6477
6478 let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
6479 window.resume_pending_input_timeout(owner_id, cx);
6480 });
6481 let now = cx.background_executor().now();
6482 let changed = self
6483 .pending_input
6484 .as_mut()
6485 .filter(|pending_input| pending_input.focus == self.focus)
6486 .and_then(|pending_input| pending_input.timeout.as_mut())
6487 .is_some_and(|timeout| {
6488 timeout.pause(
6489 PendingInputTimeoutPause {
6490 owner_id,
6491 _release_subscription: release_subscription,
6492 },
6493 now,
6494 )
6495 });
6496
6497 if changed {
6498 self.defer_pending_input_changed(cx);
6499 }
6500 changed
6501 }
6502
6503 fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
6504 let Some(remaining) = self
6505 .pending_input
6506 .as_ref()
6507 .and_then(|pending_input| pending_input.timeout.as_ref())
6508 .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
6509 .map(|timeout| timeout.remaining)
6510 else {
6511 return false;
6512 };
6513
6514 let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
6515 let changed = self
6516 .pending_input
6517 .as_mut()
6518 .and_then(|pending_input| pending_input.timeout.as_mut())
6519 .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
6520
6521 if changed {
6522 self.defer_pending_input_changed(cx);
6523 }
6524 changed
6525 }
6526
6527 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
6529 self.pending_input()
6530 .map(|pending_input| pending_input.keystrokes())
6531 }
6532
6533 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
6534 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6535 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6536
6537 'replay: for replay in replays {
6538 let event = KeyDownEvent {
6539 keystroke: replay.keystroke.clone(),
6540 is_held: false,
6541 prefer_character_input: true,
6542 };
6543
6544 cx.propagate_event = true;
6545 for binding in replay.bindings {
6546 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6547 if !cx.propagate_event {
6548 self.dispatch_keystroke_observers(
6549 &replay.keystroke,
6550 InputPreference::KeyBindings,
6551 Some(binding.action.as_ref()),
6552 Vec::default(),
6553 cx,
6554 );
6555 continue 'replay;
6556 }
6557 }
6558
6559 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
6560 if !cx.propagate_event {
6561 continue 'replay;
6562 }
6563 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
6564 && let Some(mut input_handler) = self.platform_window.take_input_handler()
6565 {
6566 input_handler.dispatch_input(&input, self, cx);
6567 self.platform_window.set_input_handler(input_handler)
6568 }
6569 }
6570 }
6571
6572 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
6573 focus_id
6574 .and_then(|focus_id| {
6575 self.rendered_frame
6576 .dispatch_tree
6577 .focusable_node_id(focus_id)
6578 })
6579 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
6580 }
6581
6582 fn dispatch_action_on_node(
6583 &mut self,
6584 node_id: DispatchNodeId,
6585 action: &dyn Action,
6586 cx: &mut App,
6587 ) {
6588 self.dispatch_action_on_node_inner(node_id, action, cx);
6589
6590 if !cx.propagate_event
6591 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
6592 && self.last_input_was_keyboard()
6593 {
6594 cx.platform.hide_cursor_until_mouse_moves();
6595 }
6596 }
6597
6598 fn dispatch_action_on_node_inner(
6599 &mut self,
6600 node_id: DispatchNodeId,
6601 action: &dyn Action,
6602 cx: &mut App,
6603 ) {
6604 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6605
6606 cx.propagate_event = true;
6608 if let Some(mut global_listeners) = cx
6609 .global_action_listeners
6610 .remove(&action.as_any().type_id())
6611 {
6612 for listener in &global_listeners {
6613 #[cfg(feature = "profiler")]
6614 self.window_profiler.begin_action_handler(action, cx);
6615 listener(action.as_any(), DispatchPhase::Capture, cx);
6616 #[cfg(feature = "profiler")]
6617 self.window_profiler.end_action_handler();
6618 if !cx.propagate_event {
6619 break;
6620 }
6621 }
6622
6623 global_listeners.extend(
6624 cx.global_action_listeners
6625 .remove(&action.as_any().type_id())
6626 .unwrap_or_default(),
6627 );
6628
6629 cx.global_action_listeners
6630 .insert(action.as_any().type_id(), global_listeners);
6631 }
6632
6633 if !cx.propagate_event {
6634 return;
6635 }
6636
6637 for node_id in &dispatch_path {
6639 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6640 for DispatchActionListener {
6641 action_type,
6642 listener,
6643 } in node.action_listeners.clone()
6644 {
6645 let any_action = action.as_any();
6646 if action_type == any_action.type_id() {
6647 #[cfg(feature = "profiler")]
6648 self.window_profiler.begin_action_handler(action, cx);
6649 listener(any_action, DispatchPhase::Capture, self, cx);
6650 #[cfg(feature = "profiler")]
6651 self.window_profiler.end_action_handler();
6652
6653 if !cx.propagate_event {
6654 return;
6655 }
6656 }
6657 }
6658 }
6659
6660 for node_id in dispatch_path.iter().rev() {
6662 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6663 for DispatchActionListener {
6664 action_type,
6665 listener,
6666 } in node.action_listeners.clone()
6667 {
6668 let any_action = action.as_any();
6669 if action_type == any_action.type_id() {
6670 cx.propagate_event = false; #[cfg(feature = "profiler")]
6672 self.window_profiler.begin_action_handler(action, cx);
6673 listener(any_action, DispatchPhase::Bubble, self, cx);
6674 #[cfg(feature = "profiler")]
6675 self.window_profiler.end_action_handler();
6676
6677 if !cx.propagate_event {
6678 return;
6679 }
6680 }
6681 }
6682 }
6683
6684 if let Some(mut global_listeners) = cx
6686 .global_action_listeners
6687 .remove(&action.as_any().type_id())
6688 {
6689 for listener in global_listeners.iter().rev() {
6690 cx.propagate_event = false; #[cfg(feature = "profiler")]
6693 self.window_profiler.begin_action_handler(action, cx);
6694 listener(action.as_any(), DispatchPhase::Bubble, cx);
6695 #[cfg(feature = "profiler")]
6696 self.window_profiler.end_action_handler();
6697 if !cx.propagate_event {
6698 break;
6699 }
6700 }
6701
6702 global_listeners.extend(
6703 cx.global_action_listeners
6704 .remove(&action.as_any().type_id())
6705 .unwrap_or_default(),
6706 );
6707
6708 cx.global_action_listeners
6709 .insert(action.as_any().type_id(), global_listeners);
6710 }
6711 }
6712
6713 pub fn observe_global<G: Global>(
6716 &mut self,
6717 cx: &mut App,
6718 f: impl Fn(&mut Window, &mut App) + 'static,
6719 ) -> Subscription {
6720 let window_handle = self.handle;
6721 let (subscription, activate) = cx.global_observers.insert(
6722 TypeId::of::<G>(),
6723 Box::new(move |cx| {
6724 window_handle
6725 .update(cx, |_, window, cx| f(window, cx))
6726 .is_ok()
6727 }),
6728 );
6729 cx.defer(move |_| activate());
6730 subscription
6731 }
6732
6733 pub fn activate_window(&self) {
6735 self.platform_window.activate();
6736 }
6737
6738 pub fn request_attention(&self) {
6740 self.platform_window.request_attention();
6741 }
6742
6743 pub fn minimize_window(&self) {
6745 self.platform_window.minimize();
6746 }
6747
6748 pub fn toggle_fullscreen(&self) {
6750 self.platform_window.toggle_fullscreen();
6751 }
6752
6753 pub fn toggle_simple_fullscreen(&self) {
6758 self.platform_window.toggle_simple_fullscreen();
6759 }
6760
6761 pub fn invalidate_character_coordinates(&self) {
6763 self.on_next_frame(|window, cx| {
6764 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
6765 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
6766 window.platform_window.update_ime_position(bounds);
6767 }
6768 window.platform_window.set_input_handler(input_handler);
6769 }
6770 });
6771 }
6772
6773 pub fn prompt<T>(
6777 &mut self,
6778 level: PromptLevel,
6779 message: &str,
6780 detail: Option<&str>,
6781 answers: &[T],
6782 cx: &mut App,
6783 ) -> oneshot::Receiver<usize>
6784 where
6785 T: Clone + Into<PromptButton>,
6786 {
6787 let prompt_builder = cx.prompt_builder.take();
6788 let Some(prompt_builder) = prompt_builder else {
6789 unreachable!("Re-entrant window prompting is not supported by GPUI");
6790 };
6791
6792 let answers = answers
6793 .iter()
6794 .map(|answer| answer.clone().into())
6795 .collect::<Vec<_>>();
6796
6797 let receiver = match &prompt_builder {
6798 PromptBuilder::Default => self
6799 .platform_window
6800 .prompt(level, message, detail, &answers)
6801 .unwrap_or_else(|| {
6802 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6803 }),
6804 PromptBuilder::Custom(_) => {
6805 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6806 }
6807 };
6808
6809 cx.prompt_builder = Some(prompt_builder);
6810
6811 receiver
6812 }
6813
6814 fn build_custom_prompt(
6815 &mut self,
6816 prompt_builder: &PromptBuilder,
6817 level: PromptLevel,
6818 message: &str,
6819 detail: Option<&str>,
6820 answers: &[PromptButton],
6821 cx: &mut App,
6822 ) -> oneshot::Receiver<usize> {
6823 let (sender, receiver) = oneshot::channel();
6824 let handle = PromptHandle::new(sender);
6825 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
6826 self.prompt = Some(handle);
6827 receiver
6828 }
6829
6830 pub fn has_active_prompt(&self) -> bool {
6835 self.prompt.is_some()
6836 }
6837
6838 pub fn context_stack(&self) -> Vec<KeyContext> {
6840 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6841 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6842 dispatch_tree
6843 .dispatch_path(node_id)
6844 .iter()
6845 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
6846 .collect()
6847 }
6848
6849 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
6851 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6852 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
6853 for action_type in cx.global_action_listeners.keys() {
6854 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
6855 let action = cx.actions.build_action_type(action_type).ok();
6856 if let Some(action) = action {
6857 actions.insert(ix, action);
6858 }
6859 }
6860 }
6861 actions
6862 }
6863
6864 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
6867 self.rendered_frame
6868 .dispatch_tree
6869 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
6870 }
6871
6872 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
6875 self.rendered_frame
6876 .dispatch_tree
6877 .highest_precedence_binding_for_action(
6878 action,
6879 &self.rendered_frame.dispatch_tree.context_stack,
6880 )
6881 }
6882
6883 pub fn bindings_for_action_in_context(
6885 &self,
6886 action: &dyn Action,
6887 context: KeyContext,
6888 ) -> Vec<KeyBinding> {
6889 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6890 dispatch_tree.bindings_for_action(action, &[context])
6891 }
6892
6893 pub fn highest_precedence_binding_for_action_in_context(
6896 &self,
6897 action: &dyn Action,
6898 context: KeyContext,
6899 ) -> Option<KeyBinding> {
6900 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6901 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
6902 }
6903
6904 pub fn bindings_for_action_in(
6908 &self,
6909 action: &dyn Action,
6910 focus_handle: &FocusHandle,
6911 ) -> Vec<KeyBinding> {
6912 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6913 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
6914 return vec![];
6915 };
6916 dispatch_tree.bindings_for_action(action, &context_stack)
6917 }
6918
6919 pub fn highest_precedence_binding_for_action_in(
6923 &self,
6924 action: &dyn Action,
6925 focus_handle: &FocusHandle,
6926 ) -> Option<KeyBinding> {
6927 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6928 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
6929 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
6930 }
6931
6932 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
6934 self.rendered_frame
6935 .dispatch_tree
6936 .possible_next_bindings_for_input(input, &self.context_stack())
6937 }
6938
6939 fn context_stack_for_focus_handle(
6940 &self,
6941 focus_handle: &FocusHandle,
6942 ) -> Option<Vec<KeyContext>> {
6943 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6944 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
6945 let context_stack: Vec<_> = dispatch_tree
6946 .dispatch_path(node_id)
6947 .into_iter()
6948 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
6949 .collect();
6950 Some(context_stack)
6951 }
6952
6953 pub fn listener_for<T: 'static, E>(
6955 &self,
6956 view: &Entity<T>,
6957 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
6958 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
6959 let view = view.downgrade();
6960 move |e: &E, window: &mut Window, cx: &mut App| {
6961 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
6962 }
6963 }
6964
6965 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
6967 &self,
6968 entity: &Entity<E>,
6969 f: Callback,
6970 ) -> impl Fn(&mut Window, &mut App) + 'static {
6971 let entity = entity.downgrade();
6972 move |window: &mut Window, cx: &mut App| {
6973 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
6974 }
6975 }
6976
6977 pub fn on_window_should_close(
6980 &self,
6981 cx: &App,
6982 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
6983 ) {
6984 let mut cx = self.to_async(cx);
6985 self.platform_window.on_should_close(Box::new(move || {
6986 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
6987 }))
6988 }
6989
6990 pub fn on_action(
6999 &mut self,
7000 action_type: TypeId,
7001 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
7002 ) {
7003 self.invalidator.debug_assert_paint();
7004
7005 self.next_frame
7006 .dispatch_tree
7007 .on_action(action_type, Rc::new(listener));
7008 }
7009
7010 pub fn on_action_when(
7019 &mut self,
7020 condition: bool,
7021 action_type: TypeId,
7022 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
7023 ) {
7024 self.invalidator.debug_assert_paint();
7025
7026 if condition {
7027 self.next_frame
7028 .dispatch_tree
7029 .on_action(action_type, Rc::new(listener));
7030 }
7031 }
7032
7033 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
7036 self.platform_window.gpu_specs()
7037 }
7038
7039 pub fn titlebar_double_click(&self) {
7042 self.platform_window
7043 .titlebar_double_click(self.is_resizable, self.is_minimizable);
7044 }
7045
7046 pub fn window_title(&self) -> String {
7049 self.platform_window.get_title()
7050 }
7051
7052 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
7055 self.platform_window.tabbed_windows()
7056 }
7057
7058 pub fn tab_bar_visible(&self) -> bool {
7061 self.platform_window.tab_bar_visible()
7062 }
7063
7064 pub fn merge_all_windows(&self) {
7067 self.platform_window.merge_all_windows()
7068 }
7069
7070 pub fn move_tab_to_new_window(&self) {
7073 self.platform_window.move_tab_to_new_window()
7074 }
7075
7076 pub fn toggle_window_tab_overview(&self) {
7079 self.platform_window.toggle_window_tab_overview()
7080 }
7081
7082 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
7085 self.platform_window
7086 .set_tabbing_identifier(tabbing_identifier)
7087 }
7088
7089 pub fn play_system_bell(&self) {
7092 self.platform_window.play_system_bell()
7093 }
7094
7095 pub fn is_a11y_enabled(&self) -> bool {
7102 self.a11y.is_enabled()
7103 }
7104
7105 pub fn is_a11y_active(&self) -> bool {
7116 self.a11y.is_active()
7117 }
7118
7119 pub fn debug_a11y_tree_json(&self) -> Option<String> {
7121 self.a11y.debug_tree_json()
7122 }
7123
7124 pub fn on_a11y_action(
7130 &mut self,
7131 node_id: accesskit::NodeId,
7132 action: accesskit::Action,
7133 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
7134 ) {
7135 crate::fast::a11y::A11yLog::action(&mut self.a11y.nodes.fast, node_id, action);
7136 self.a11y
7137 .action_listeners
7138 .entry(node_id)
7139 .or_default()
7140 .push((action, Box::new(listener)));
7141 }
7142
7143 #[cfg(not(target_family = "wasm"))]
7144 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
7145 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
7148 let extra_data = request.data.as_ref();
7149 let mut matched = false;
7150 for (action, listener) in &mut listeners {
7151 if *action == request.action {
7152 listener(extra_data, self, cx);
7153 matched = true;
7154 }
7155 }
7156 self.a11y
7157 .action_listeners
7158 .insert(request.target_node, listeners);
7159 if matched {
7160 return;
7161 }
7162 }
7163
7164 match request.action {
7166 accesskit::Action::Click => {
7167 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
7168 let center = bounds.center();
7169 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
7170 button: MouseButton::Left,
7171 position: center,
7172 modifiers: Modifiers::default(),
7173 click_count: 1,
7174 first_mouse: false,
7175 });
7176 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
7177 button: MouseButton::Left,
7178 position: center,
7179 modifiers: Modifiers::default(),
7180 click_count: 1,
7181 });
7182 self.dispatch_event(mouse_down, cx);
7183 self.dispatch_event(mouse_up, cx);
7184 }
7185 }
7186 accesskit::Action::Focus => {
7187 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
7188 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
7189 {
7190 self.focus(&handle, cx);
7191 }
7192 }
7193 accesskit::Action::Blur => {
7194 self.blur(cx);
7195 }
7196 _ => {
7197 log::debug!(
7198 "Unhandled a11y action: {:?} on {:?}",
7199 request.action,
7200 request.target_node
7201 );
7202 }
7203 }
7204 }
7205
7206 #[cfg(any(feature = "inspector", debug_assertions))]
7208 pub fn toggle_inspector(&mut self, cx: &mut App) {
7209 self.inspector = match self.inspector {
7210 None => Some(cx.new(|_| Inspector::new())),
7211 Some(_) => {
7212 self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
7213 self.rendered_frame.inspector_hitboxes = FxHashMap::default();
7214 self.next_frame.next_inspector_instance_ids = FxHashMap::default();
7215 self.next_frame.inspector_hitboxes = FxHashMap::default();
7216 None
7217 }
7218 };
7219 self.refresh();
7220 }
7221
7222 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
7224 #[cfg(any(feature = "inspector", debug_assertions))]
7225 {
7226 if let Some(inspector) = &self.inspector {
7227 return inspector.read(_cx).is_picking();
7228 }
7229 }
7230 false
7231 }
7232
7233 #[cfg(any(feature = "inspector", debug_assertions))]
7235 pub fn with_inspector_state<T: 'static, R>(
7236 &mut self,
7237 inspector_id: Option<&crate::InspectorElementId>,
7238 cx: &mut App,
7239 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
7240 ) -> Option<R> {
7241 let inspector_id = inspector_id?;
7242 let inspector = self.inspector.as_ref()?;
7243 if inspector.read(cx).active_element_id() != Some(inspector_id) {
7244 return None;
7245 }
7246 let inspector = inspector.clone();
7247 Some(inspector.update(cx, |inspector, _cx| {
7248 inspector.with_active_element_state(self, f)
7249 }))
7250 }
7251
7252 #[cfg(any(feature = "inspector", debug_assertions))]
7253 pub(crate) fn inspector_enabled(&self) -> bool {
7254 self.inspector.is_some()
7255 }
7256
7257 #[cfg(any(feature = "inspector", debug_assertions))]
7258 pub(crate) fn build_inspector_element_id(
7259 &mut self,
7260 path: crate::InspectorElementPath,
7261 ) -> crate::InspectorElementId {
7262 self.invalidator.debug_assert_paint_or_prepaint();
7263 let path = Rc::new(path);
7264 let next_instance_id = self
7265 .next_frame
7266 .next_inspector_instance_ids
7267 .entry(path.clone())
7268 .or_insert(0);
7269 let instance_id = *next_instance_id;
7270 *next_instance_id += 1;
7271 crate::InspectorElementId { path, instance_id }
7272 }
7273
7274 #[cfg(any(feature = "inspector", debug_assertions))]
7275 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
7276 if let Some(inspector) = self.inspector.take() {
7277 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
7278 inspector_element.prepaint_as_root(
7279 point(self.viewport_size.width - inspector_width, px(0.0)),
7280 size(inspector_width, self.viewport_size.height).into(),
7281 self,
7282 cx,
7283 );
7284 self.inspector = Some(inspector);
7285 Some(inspector_element)
7286 } else {
7287 None
7288 }
7289 }
7290
7291 #[cfg(any(feature = "inspector", debug_assertions))]
7292 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
7293 if let Some(mut inspector_element) = inspector_element {
7294 inspector_element.paint(self, cx);
7295 };
7296 }
7297
7298 #[cfg(any(feature = "inspector", debug_assertions))]
7301 pub fn insert_inspector_hitbox(
7302 &mut self,
7303 hitbox_id: HitboxId,
7304 inspector_id: Option<&crate::InspectorElementId>,
7305 cx: &App,
7306 ) {
7307 self.invalidator.debug_assert_paint_or_prepaint();
7308 if !self.is_inspector_picking(cx) {
7309 return;
7310 }
7311 if let Some(inspector_id) = inspector_id {
7312 self.next_frame
7313 .inspector_hitboxes
7314 .insert(hitbox_id, inspector_id.clone());
7315 }
7316 }
7317
7318 #[cfg(any(feature = "inspector", debug_assertions))]
7319 fn paint_inspector_hitbox(&mut self, cx: &App) {
7320 if let Some(inspector) = self.inspector.as_ref() {
7321 let inspector = inspector.read(cx);
7322 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
7323 && let Some(hitbox) = self
7324 .next_frame
7325 .hitboxes
7326 .iter()
7327 .find(|hitbox| hitbox.id == hitbox_id)
7328 {
7329 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
7330 }
7331 }
7332 }
7333
7334 #[cfg(any(feature = "inspector", debug_assertions))]
7335 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
7336 let Some(inspector) = self.inspector.clone() else {
7337 return;
7338 };
7339 if event.downcast_ref::<MouseMoveEvent>().is_some() {
7340 inspector.update(cx, |inspector, _cx| {
7341 if let Some((_, inspector_id)) =
7342 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7343 {
7344 inspector.hover(inspector_id, self);
7345 }
7346 });
7347 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
7348 inspector.update(cx, |inspector, _cx| {
7349 if let Some((_, inspector_id)) =
7350 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7351 {
7352 inspector.select(inspector_id, self);
7353 }
7354 });
7355 } else if let Some(event) = event.downcast_ref::<crate::ScrollEvent>() {
7356 const SCROLL_LINES: f32 = 3.0;
7358 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
7359 let delta_y = event
7360 .delta
7361 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
7362 .y;
7363 if let Some(inspector) = self.inspector.clone() {
7364 inspector.update(cx, |inspector, _cx| {
7365 if let Some(depth) = inspector.pick_depth.as_mut() {
7366 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
7367 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
7368 if *depth < 0.0 {
7369 *depth = 0.0;
7370 } else if *depth > max_depth {
7371 *depth = max_depth;
7372 }
7373 if let Some((_, inspector_id)) =
7374 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
7375 {
7376 inspector.set_active_element_id(inspector_id, self);
7377 }
7378 }
7379 });
7380 }
7381 }
7382 }
7383
7384 #[cfg(any(feature = "inspector", debug_assertions))]
7385 fn hovered_inspector_hitbox(
7386 &self,
7387 inspector: &Inspector,
7388 frame: &Frame,
7389 ) -> Option<(HitboxId, crate::InspectorElementId)> {
7390 if let Some(pick_depth) = inspector.pick_depth {
7391 let depth = (pick_depth as i64).try_into().unwrap_or(0);
7392 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
7393 let skip_count = (depth as usize).min(max_skipped);
7394 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
7395 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
7396 return Some((*hitbox_id, inspector_id.clone()));
7397 }
7398 }
7399 }
7400 None
7401 }
7402
7403 #[cfg(any(test, feature = "test-support"))]
7406 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
7407 self.modifiers = modifiers;
7408 }
7409
7410 #[cfg(any(test, feature = "test-support"))]
7414 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
7415 let event = PlatformInput::MouseMove(MouseMoveEvent {
7416 position,
7417 modifiers: self.modifiers,
7418 pressed_button: None,
7419 });
7420 let _ = self.dispatch_event(event, cx);
7421 }
7422
7423 #[inline(never)]
7424 fn take_element_state(
7425 &mut self,
7426 global_id: &GlobalElementId,
7427 state_type: TypeId,
7428 ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
7429 let key = (global_id.clone(), state_type);
7430 self.next_frame.accessed_element_states.push(key.clone());
7431 let state = self
7432 .next_frame
7433 .element_states
7434 .remove(&key)
7435 .or_else(|| self.rendered_frame.element_states.remove(&key));
7436 (key, state)
7437 }
7438
7439 #[inline(never)]
7440 fn insert_element_state(
7441 &mut self,
7442 key: (GlobalElementId, TypeId),
7443 state: ElementStateBox,
7444 ) -> Option<ElementStateBox> {
7445 self.next_frame.element_states.insert(key, state)
7446 }
7447
7448 #[inline(never)]
7449 fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
7450 cx.observe(state, move |_, cx| {
7451 cx.notify(current_view);
7452 })
7453 .detach();
7454 }
7455}
7456
7457slotmap::new_key_type! {
7459 pub struct WindowId;
7461}
7462
7463impl WindowId {
7464 pub fn as_u64(&self) -> u64 {
7466 self.0.as_ffi()
7467 }
7468}
7469
7470impl From<u64> for WindowId {
7471 fn from(value: u64) -> Self {
7472 WindowId(slotmap::KeyData::from_ffi(value))
7473 }
7474}
7475
7476#[derive(Deref, DerefMut)]
7479pub struct WindowHandle<V> {
7480 #[deref]
7481 #[deref_mut]
7482 pub(crate) any_handle: AnyWindowHandle,
7483 state_type: PhantomData<fn(V) -> V>,
7484}
7485
7486impl<V> Debug for WindowHandle<V> {
7487 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7488 f.debug_struct("WindowHandle")
7489 .field("any_handle", &self.any_handle.id.as_u64())
7490 .finish()
7491 }
7492}
7493
7494impl<V: 'static + Render> WindowHandle<V> {
7495 pub fn new(id: WindowId) -> Self {
7498 WindowHandle {
7499 any_handle: AnyWindowHandle {
7500 id,
7501 state_type: TypeId::of::<V>(),
7502 root_entity_type_name: std::any::type_name::<V>(),
7503 },
7504 state_type: PhantomData,
7505 }
7506 }
7507
7508 #[cfg(any(test, feature = "test-support"))]
7512 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
7513 where
7514 C: AppContext,
7515 {
7516 cx.update_window(self.any_handle, |root_view, _, _| {
7517 root_view
7518 .downcast::<V>()
7519 .map_err(|_| anyhow!("the type of the window's root view has changed"))
7520 })?
7521 }
7522
7523 pub fn update<C, R>(
7527 &self,
7528 cx: &mut C,
7529 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
7530 ) -> Result<R>
7531 where
7532 C: AppContext,
7533 {
7534 cx.update_window(self.any_handle, |root_view, window, cx| {
7535 let view = root_view
7536 .downcast::<V>()
7537 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7538
7539 Ok(view.update(cx, |view, cx| update(view, window, cx)))
7540 })?
7541 }
7542
7543 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
7547 let x = cx
7548 .windows
7549 .get(self.id)
7550 .and_then(|window| {
7551 window
7552 .as_deref()
7553 .and_then(|window| window.root.clone())
7554 .map(|root_view| root_view.downcast::<V>())
7555 })
7556 .context("window not found")?
7557 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
7558
7559 Ok(x.read(cx))
7560 }
7561
7562 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
7566 where
7567 C: AppContext,
7568 {
7569 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
7570 }
7571
7572 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
7576 where
7577 C: AppContext,
7578 {
7579 cx.read_window(self, |root_view, _cx| root_view)
7580 }
7581
7582 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
7587 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
7588 .ok()
7589 }
7590}
7591
7592impl<V> Copy for WindowHandle<V> {}
7593
7594impl<V> Clone for WindowHandle<V> {
7595 fn clone(&self) -> Self {
7596 *self
7597 }
7598}
7599
7600impl<V> PartialEq for WindowHandle<V> {
7601 fn eq(&self, other: &Self) -> bool {
7602 self.any_handle == other.any_handle
7603 }
7604}
7605
7606impl<V> Eq for WindowHandle<V> {}
7607
7608impl<V> Hash for WindowHandle<V> {
7609 fn hash<H: Hasher>(&self, state: &mut H) {
7610 self.any_handle.hash(state);
7611 }
7612}
7613
7614impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
7615 fn from(val: WindowHandle<V>) -> Self {
7616 val.any_handle
7617 }
7618}
7619
7620#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
7622pub struct AnyWindowHandle {
7623 pub(crate) id: WindowId,
7624 state_type: TypeId,
7625 root_entity_type_name: &'static str,
7626}
7627
7628impl AnyWindowHandle {
7629 pub fn window_id(&self) -> WindowId {
7631 self.id
7632 }
7633
7634 pub fn root_entity_type_name(&self) -> &'static str {
7636 self.root_entity_type_name
7637 }
7638
7639 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
7642 if TypeId::of::<T>() == self.state_type {
7643 Some(WindowHandle {
7644 any_handle: *self,
7645 state_type: PhantomData,
7646 })
7647 } else {
7648 None
7649 }
7650 }
7651
7652 pub fn update<C, R>(
7656 self,
7657 cx: &mut C,
7658 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
7659 ) -> Result<R>
7660 where
7661 C: AppContext,
7662 {
7663 cx.update_window(self, update)
7664 }
7665
7666 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
7670 where
7671 C: AppContext,
7672 T: 'static,
7673 {
7674 let view = self
7675 .downcast::<T>()
7676 .context("the type of the window's root view has changed")?;
7677
7678 cx.read_window(&view, read)
7679 }
7680}
7681
7682impl HasWindowHandle for Window {
7683 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
7684 self.platform_window.window_handle()
7685 }
7686}
7687
7688impl HasDisplayHandle for Window {
7689 fn display_handle(
7690 &self,
7691 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
7692 self.platform_window.display_handle()
7693 }
7694}
7695
7696#[derive(Clone, Debug, Eq, PartialEq, Hash)]
7701pub enum ElementId {
7702 View(EntityId),
7704 Integer(u64),
7706 Name(SharedString),
7708 Uuid(Uuid),
7710 FocusHandle(FocusId),
7712 NamedInteger(SharedString, u64),
7714 Path(Arc<std::path::Path>),
7716 CodeLocation(core::panic::Location<'static>),
7718 NamedChild(Arc<ElementId>, SharedString),
7720 OpaqueId([u8; 20]),
7722}
7723
7724impl ElementId {
7725 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
7727 Self::NamedInteger(name.into(), integer as u64)
7728 }
7729}
7730
7731impl Display for ElementId {
7732 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7733 match self {
7734 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
7735 ElementId::Integer(ix) => write!(f, "{}", ix)?,
7736 ElementId::Name(name) => write!(f, "{}", name)?,
7737 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
7738 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
7739 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
7740 ElementId::Path(path) => write!(f, "{}", path.display())?,
7741 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
7742 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
7743 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
7744 }
7745
7746 Ok(())
7747 }
7748}
7749
7750impl TryInto<SharedString> for ElementId {
7751 type Error = anyhow::Error;
7752
7753 fn try_into(self) -> anyhow::Result<SharedString> {
7754 if let ElementId::Name(name) = self {
7755 Ok(name)
7756 } else {
7757 anyhow::bail!("element id is not string")
7758 }
7759 }
7760}
7761
7762impl From<u64> for ElementId {
7763 fn from(id: u64) -> Self {
7764 ElementId::Integer(id)
7765 }
7766}
7767
7768impl From<usize> for ElementId {
7769 fn from(id: usize) -> Self {
7770 ElementId::Integer(id as u64)
7771 }
7772}
7773
7774impl From<i32> for ElementId {
7775 fn from(id: i32) -> Self {
7776 Self::Integer(id as u64)
7777 }
7778}
7779
7780impl From<SharedString> for ElementId {
7781 fn from(name: SharedString) -> Self {
7782 ElementId::Name(name)
7783 }
7784}
7785
7786impl From<String> for ElementId {
7787 fn from(name: String) -> Self {
7788 ElementId::Name(name.into())
7789 }
7790}
7791
7792impl From<Arc<str>> for ElementId {
7793 fn from(name: Arc<str>) -> Self {
7794 ElementId::Name(name.into())
7795 }
7796}
7797
7798impl From<Arc<std::path::Path>> for ElementId {
7799 fn from(path: Arc<std::path::Path>) -> Self {
7800 ElementId::Path(path)
7801 }
7802}
7803
7804impl From<&'static str> for ElementId {
7805 fn from(name: &'static str) -> Self {
7806 ElementId::Name(SharedString::new_static(name))
7807 }
7808}
7809
7810impl<'a> From<&'a FocusHandle> for ElementId {
7811 fn from(handle: &'a FocusHandle) -> Self {
7812 ElementId::FocusHandle(handle.id)
7813 }
7814}
7815
7816impl From<(&'static str, EntityId)> for ElementId {
7817 fn from((name, id): (&'static str, EntityId)) -> Self {
7818 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
7819 }
7820}
7821
7822impl From<(&'static str, usize)> for ElementId {
7823 fn from((name, id): (&'static str, usize)) -> Self {
7824 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
7825 }
7826}
7827
7828impl From<(SharedString, usize)> for ElementId {
7829 fn from((name, id): (SharedString, usize)) -> Self {
7830 ElementId::NamedInteger(name, id as u64)
7831 }
7832}
7833
7834impl From<(&'static str, u64)> for ElementId {
7835 fn from((name, id): (&'static str, u64)) -> Self {
7836 ElementId::NamedInteger(SharedString::new_static(name), id)
7837 }
7838}
7839
7840impl From<Uuid> for ElementId {
7841 fn from(value: Uuid) -> Self {
7842 Self::Uuid(value)
7843 }
7844}
7845
7846impl From<(&'static str, u32)> for ElementId {
7847 fn from((name, id): (&'static str, u32)) -> Self {
7848 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
7849 }
7850}
7851
7852impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
7853 fn from((id, name): (ElementId, T)) -> Self {
7854 ElementId::NamedChild(Arc::new(id), name.into())
7855 }
7856}
7857
7858impl From<&'static core::panic::Location<'static>> for ElementId {
7859 fn from(location: &'static core::panic::Location<'static>) -> Self {
7860 ElementId::CodeLocation(*location)
7861 }
7862}
7863
7864impl From<[u8; 20]> for ElementId {
7865 fn from(opaque_id: [u8; 20]) -> Self {
7866 ElementId::OpaqueId(opaque_id)
7867 }
7868}
7869
7870#[derive(Clone)]
7873pub struct PaintQuad {
7874 pub bounds: Bounds<Pixels>,
7876 pub corner_radii: Corners<Pixels>,
7878 pub background: Background,
7880 pub border_widths: Edges<Pixels>,
7882 pub border_color: Hsla,
7884 pub border_style: BorderStyle,
7886}
7887
7888impl PaintQuad {
7889 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
7891 PaintQuad {
7892 corner_radii: corner_radii.into(),
7893 ..self
7894 }
7895 }
7896
7897 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
7899 PaintQuad {
7900 border_widths: border_widths.into(),
7901 ..self
7902 }
7903 }
7904
7905 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
7907 PaintQuad {
7908 border_color: border_color.into(),
7909 ..self
7910 }
7911 }
7912
7913 pub fn background(self, background: impl Into<Background>) -> Self {
7915 PaintQuad {
7916 background: background.into(),
7917 ..self
7918 }
7919 }
7920}
7921
7922pub fn quad(
7924 bounds: Bounds<Pixels>,
7925 corner_radii: impl Into<Corners<Pixels>>,
7926 background: impl Into<Background>,
7927 border_widths: impl Into<Edges<Pixels>>,
7928 border_color: impl Into<Hsla>,
7929 border_style: BorderStyle,
7930) -> PaintQuad {
7931 PaintQuad {
7932 bounds,
7933 corner_radii: corner_radii.into(),
7934 background: background.into(),
7935 border_widths: border_widths.into(),
7936 border_color: border_color.into(),
7937 border_style,
7938 }
7939}
7940
7941pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
7943 PaintQuad {
7944 bounds: bounds.into(),
7945 corner_radii: (0.).into(),
7946 background: background.into(),
7947 border_widths: (0.).into(),
7948 border_color: transparent_black(),
7949 border_style: BorderStyle::default(),
7950 }
7951}
7952
7953pub fn outline(
7955 bounds: impl Into<Bounds<Pixels>>,
7956 border_color: impl Into<Hsla>,
7957 border_style: BorderStyle,
7958) -> PaintQuad {
7959 PaintQuad {
7960 bounds: bounds.into(),
7961 corner_radii: (0.).into(),
7962 background: transparent_black().into(),
7963 border_widths: (1.).into(),
7964 border_color: border_color.into(),
7965 border_style,
7966 }
7967}
7968
7969#[inline(never)]
7970fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
7971 if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
7972 let arena_cell = unsafe { &*arena_pointer };
7975 callback(&mut arena_cell.borrow_mut());
7976 Ok(())
7977 } else {
7978 ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
7979 }
7980}
7981
7982#[cfg(test)]
7983mod tests {
7984 use std::{
7985 cell::{Cell, RefCell},
7986 path::PathBuf,
7987 rc::Rc,
7988 time::Duration,
7989 };
7990
7991 use crate::{
7992 AnyWindowHandle, AppContext as _, BackGestureEvent, BackGesturePhase, Bounds, ContentMask,
7993 Context, DispatchPhase, DragMoveEvent, Empty, ExternalDragPayload, ExternalPaths,
7994 FileDragPaths, FileDropEvent, FocusHandle, InputEvent as _, InteractiveElement as _,
7995 IntoElement, KeyDownEvent, Keystroke, LongPressEvent, MouseButton, MouseDownEvent,
7996 MouseMoveEvent, ParentElement, Pixels, PlatformInput, Point, Render, RequestFrameOptions,
7997 ScaledPixels, StatefulInteractiveElement as _, Styled, TestAppContext, TouchDragEvent,
7998 TouchEvent, TouchId, TouchPhase, Underline, UnderlineStyle, Window, WindowAppearance,
7999 WindowOptions, canvas, div, hsla, point, px, size,
8000 };
8001
8002 #[gpui::test]
8003 async fn test_focus_handle_release(cx: &mut TestAppContext) {
8004 let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
8005 let handle_id = handle.id;
8006 let weak_handle = handle.downgrade();
8007 let retained = handle.clone();
8008 drop(handle);
8009
8010 cx.update(|_| {});
8011 cx.read(|cx| {
8012 let handles = cx.focus_handles.read();
8013 assert_eq!(handles.handles.len(), 2);
8014 assert!(handles.dropped_handles.is_empty());
8015 });
8016 assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));
8017
8018 cx.background_spawn(async move { drop(retained) }).await;
8019 assert_eq!(weak_handle.upgrade(), None);
8020 cx.read(|cx| {
8021 assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);
8022 });
8023 cx.update(|_| {});
8024 cx.read(|cx| {
8025 let handles = cx.focus_handles.read();
8026 assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);
8027 assert!(handles.dropped_handles.is_empty());
8028 });
8029
8030 let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);
8031 assert_eq!(weak_handle.upgrade(), None);
8032 cx.update(|cx| {
8033 drop(replacements);
8034 cx.defer(move |_| drop(survivor));
8035 });
8036 cx.read(|cx| {
8037 let handles = cx.focus_handles.read();
8038 assert_eq!(handles.handles.len(), 0);
8039 assert!(handles.dropped_handles.is_empty());
8040 });
8041 }
8042
8043 #[gpui::test]
8044 fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {
8045 let windows = [
8046 cx.add_window(|_, _| EmptyView),
8047 cx.add_window(|_, _| EmptyView),
8048 cx.add_window(|_, _| EmptyView),
8049 cx.add_window(|_, _| EmptyView),
8050 cx.add_window(|_, _| EmptyView),
8051 ];
8052 let (handle, other_handle, survivor) =
8053 cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));
8054 for window in &windows[..2] {
8055 window
8056 .update(cx, |_, window, cx| window.focus(&handle, cx))
8057 .expect("window exists");
8058 }
8059 windows[2]
8060 .update(cx, |_, window, cx| window.focus(&other_handle, cx))
8061 .expect("window exists");
8062 windows[3]
8063 .update(cx, |_, window, cx| window.focus(&survivor, cx))
8064 .expect("window exists");
8065
8066 cx.update(|cx| {
8067 for _ in 0..1_000 {
8068 drop(cx.focus_handle());
8069 }
8070 drop((handle, other_handle));
8071 });
8072 for window in &windows[..3] {
8073 window
8074 .update(cx, |_, window, _| assert_eq!(window.focus, None))
8075 .expect("window exists");
8076 }
8077 windows[3]
8078 .update(cx, |_, window, cx| {
8079 assert_eq!(window.focused(cx).as_ref(), Some(&survivor));
8080 assert_eq!(window.focus_generation, 1);
8081 })
8082 .expect("window exists");
8083 windows[4]
8084 .update(cx, |_, window, _| {
8085 assert_eq!(window.focus, None);
8086 assert_eq!(window.focus_generation, 0);
8087 })
8088 .expect("window exists");
8089 }
8090
8091 #[cfg(feature = "profiler")]
8092 #[gpui::test]
8093 fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
8094 use crate::FrameRequestSource;
8095 use crate::profiler::journal::{
8096 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
8097 };
8098 use scheduler::Instant;
8099
8100 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8101 let window = cx.add_window(|_, _| EmptyView);
8102 let platform_window = cx.test_window(window.into());
8103 platform_window.simulate_frame_request(RequestFrameOptions::default());
8104 let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
8105 let mut collector = journal.collector();
8106
8107 for (signal_at, source) in [
8108 (Some(Instant::now()), FrameRequestSource::NativeCallback),
8109 (Some(Instant::now()), FrameRequestSource::LocalSchedule),
8110 (None, FrameRequestSource::NativeCallback),
8111 ] {
8112 platform_window.simulate_frame_request(RequestFrameOptions {
8113 signal_at,
8114 signal_source: source,
8115 require_presentation: true,
8116 ..Default::default()
8117 });
8118 let entries = collector.collect_unseen().entries;
8119 let signal_index = entries
8120 .iter()
8121 .position(|entry| {
8122 matches!(
8123 entry,
8124 ForegroundJournalEntry::PlatformSignal(signal)
8125 if signal.window_id == window.window_id()
8126 && signal.signal_at == signal_at
8127 && signal.source == source
8128 && signal_at.is_none_or(|at| signal.handled_at >= at)
8129 )
8130 })
8131 .expect("frame request metadata");
8132 let skip_index = entries
8133 .iter()
8134 .position(|entry| {
8135 matches!(
8136 entry,
8137 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
8138 if skipped.window_id == window.window_id()
8139 && skipped.reason == FrameSkipReason::NoRenderNeeded
8140 )
8141 })
8142 .expect("completed no-render boundary");
8143 assert!(signal_index < skip_index);
8144 }
8145 }
8146
8147 #[cfg(feature = "profiler")]
8148 #[gpui::test]
8149 fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
8150 use crate::profiler::journal::{
8151 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
8152 };
8153 use scheduler::Instant;
8154
8155 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
8157 let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
8158 let mut collector = journal.collector();
8159 for initially_dirty in [true, false] {
8160 let window = cx
8162 .app
8163 .borrow_mut()
8164 .open_window(
8165 WindowOptions {
8166 inactive_frame_interval: Some(Duration::from_secs(3600)),
8167 ..Default::default()
8168 },
8169 |_, cx| cx.new(|_| EmptyView),
8170 )
8171 .expect("open inactive test window");
8172 let platform_window = cx.test_window(window.into());
8173 platform_window.simulate_active_status_change(false);
8174 platform_window.simulate_frame_request(RequestFrameOptions::default());
8175 let callback_ran = Rc::new(Cell::new(false));
8176 let draws_before = window
8177 .update(cx, |_, window, _| {
8178 let draws_before = window
8179 .frame_duration_snapshot()
8180 .draw_duration_histogram
8181 .len();
8182 if initially_dirty {
8183 window.refresh();
8184 }
8185 window.on_next_frame({
8186 let callback_ran = callback_ran.clone();
8187 move |window, _| {
8188 callback_ran.set(true);
8189 window.refresh();
8190 }
8191 });
8192 draws_before
8193 })
8194 .expect("schedule throttled frame");
8195 let input_at = Instant::now();
8197 journal::record_input(journal::InputTiming {
8198 kind: "test",
8199 start: input_at,
8200 end: input_at,
8201 caused_invalidation: false,
8202 });
8203 collector.collect_unseen();
8204 platform_window.simulate_frame_request(RequestFrameOptions {
8205 signal_at: Some(Instant::now()),
8206 ..Default::default()
8207 });
8208 window
8209 .update(cx, |_, window, _| {
8210 assert_eq!(
8211 window
8212 .frame_duration_snapshot()
8213 .draw_duration_histogram
8214 .len(),
8215 draws_before,
8216 );
8217 })
8218 .expect("inspect deferred frame");
8219 assert!(!callback_ran.get());
8220 assert!(collector.collect_unseen().entries.iter().any(|entry| {
8221 matches!(
8222 entry,
8223 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
8224 if skipped.window_id == window.window_id()
8225 && skipped.reason == FrameSkipReason::InactiveFrameRateLimit
8226 )
8227 }));
8228 platform_window.simulate_frame_request(RequestFrameOptions {
8229 signal_at: Some(Instant::now()),
8230 require_presentation: true,
8231 ..Default::default()
8232 });
8233 window
8234 .update(cx, |_, window, _| {
8235 assert_eq!(
8236 window
8237 .frame_duration_snapshot()
8238 .draw_duration_histogram
8239 .len(),
8240 draws_before + 1,
8241 );
8242 })
8243 .expect("inspect presented frame");
8244 assert!(callback_ran.get());
8245 }
8246 }
8247
8248 #[gpui::test]
8252 fn test_window_visibility(cx: &mut TestAppContext) {
8253 use crate::WindowVisibility;
8254
8255 let window = cx.add_window(|_, _| EmptyView);
8256 let observed = Rc::new(RefCell::new(Vec::new()));
8257 let _subscription = window
8258 .update(cx, {
8259 let observed = observed.clone();
8260 move |_, window, _| {
8261 assert_eq!(window.visibility(), WindowVisibility::Visible);
8262 assert!(window.is_visible());
8263 window.observe_window_visibility(move |visibility, window, _| {
8264 assert_eq!(window.visibility(), visibility);
8265 observed.borrow_mut().push(visibility);
8266 })
8267 }
8268 })
8269 .unwrap();
8270 let test_window = cx.test_window(window.into());
8271 let frame_wake_count = test_window.frame_wake_count();
8272
8273 test_window.simulate_visibility_change(WindowVisibility::Hidden);
8274 assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
8275 window
8276 .update(cx, |_, window, _| assert!(!window.is_visible()))
8277 .unwrap();
8278
8279 test_window.simulate_visibility_change(WindowVisibility::Hidden);
8281 assert_eq!(observed.borrow().len(), 1);
8282
8283 test_window.simulate_visibility_change(WindowVisibility::Visible);
8284 assert_eq!(
8285 *observed.borrow(),
8286 [WindowVisibility::Hidden, WindowVisibility::Visible]
8287 );
8288 window
8289 .update(cx, |_, window, _| assert!(window.is_visible()))
8290 .unwrap();
8291 assert_eq!(test_window.frame_wake_count(), frame_wake_count);
8292 }
8293
8294 #[gpui::test]
8297 fn test_display_tracking(cx: &mut TestAppContext) {
8298 use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
8299
8300 let sixty_hertz = Duration::from_secs(1) / 60;
8301 let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
8302 let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
8303
8304 let display_events = Rc::new(RefCell::new(Vec::new()));
8305 let _display_subscription = cx.update({
8306 let display_events = display_events.clone();
8307 move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
8308 });
8309
8310 let window = cx.add_window(|window, cx| DisplayTracker {
8311 refresh_intervals: Vec::new(),
8312 _subscription: cx.observe_window_display(
8313 window,
8314 |tracker: &mut DisplayTracker, window, cx| {
8315 tracker.refresh_intervals.push(window.refresh_interval(cx));
8316 },
8317 ),
8318 });
8319 let window_notifications = Rc::new(RefCell::new(Vec::new()));
8320 let _window_subscription = window
8321 .update(cx, {
8322 let window_notifications = window_notifications.clone();
8323 move |_, window, cx| {
8324 assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
8325 window.observe_window_display(move |window, cx| {
8326 window_notifications
8327 .borrow_mut()
8328 .push((window.display_id, window.refresh_interval(cx)));
8329 })
8330 }
8331 })
8332 .unwrap();
8333 let test_window = cx.test_window(window.into());
8334
8335 cx.test_platform()
8340 .connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
8341 test_window.simulate_move_to_display(DisplayId(2));
8342 assert_eq!(
8343 window_notifications.take(),
8344 [(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
8345 );
8346 assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
8347 cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
8348 assert!(window_notifications.borrow().is_empty());
8349
8350 test_window.simulate_move_to_display(DisplayId(2));
8352 assert!(window_notifications.borrow().is_empty());
8353
8354 cx.simulate_display_refresh_interval_change(
8355 DisplayId(2),
8356 Some(one_hundred_forty_four_hertz),
8357 );
8358 assert_eq!(
8359 window_notifications.take(),
8360 [(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
8361 );
8362
8363 cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
8365 cx.simulate_display_removed(DisplayId(1));
8366 assert!(window_notifications.borrow().is_empty());
8367
8368 assert_eq!(
8369 display_events.take(),
8370 [
8371 DisplayEvent::Changed {
8372 id: DisplayId(2),
8373 changes: DisplayChanges::REFRESH_INTERVAL,
8374 },
8375 DisplayEvent::Changed {
8376 id: DisplayId(1),
8377 changes: DisplayChanges::REFRESH_INTERVAL,
8378 },
8379 DisplayEvent::Removed(DisplayId(1)),
8380 ]
8381 );
8382 window
8383 .update(cx, |tracker, _, _| {
8384 assert_eq!(
8385 tracker.refresh_intervals,
8386 [
8387 Some(one_hundred_twenty_hertz),
8388 Some(one_hundred_forty_four_hertz)
8389 ]
8390 );
8391 })
8392 .unwrap();
8393
8394 struct DisplayTracker {
8395 refresh_intervals: Vec<Option<Duration>>,
8396 _subscription: Subscription,
8397 }
8398
8399 impl Render for DisplayTracker {
8400 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8401 Empty
8402 }
8403 }
8404 }
8405
8406 #[gpui::test]
8407 fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
8408 let window = cx.add_window(|_, _| EmptyView);
8409 let mut platform_window = cx.test_window(window.into());
8410 platform_window.simulate_resize(size(px(400.), px(800.)));
8411 window
8412 .update(cx, |_, window, _| {
8413 assert_eq!(
8414 window.visual_viewport_bounds(),
8415 Bounds::new(Point::default(), size(px(400.), px(800.)))
8416 );
8417 assert_eq!(
8418 window.fully_visible_bounds(),
8419 window.visual_viewport_bounds()
8420 );
8421 })
8422 .unwrap();
8423
8424 platform_window.simulate_frame_request(RequestFrameOptions::default());
8425 let wakes = platform_window.frame_wake_count();
8426 let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
8427 platform_window.simulate_visual_viewport_change(visual_bounds);
8428 assert!(platform_window.frame_wake_count() > wakes);
8429 platform_window.simulate_frame_request(RequestFrameOptions::default());
8430 let wakes = platform_window.frame_wake_count();
8431 let insets = crate::WindowInsets {
8432 safe_area: crate::Edges {
8433 top: px(60.),
8434 right: px(20.),
8435 bottom: px(30.),
8436 left: px(-10.),
8437 },
8438 ime: crate::Edges {
8439 bottom: px(350.),
8440 ..Default::default()
8441 },
8442 ..Default::default()
8443 };
8444 platform_window.simulate_insets_change(insets.clone());
8445 assert!(platform_window.frame_wake_count() > wakes);
8446 window
8447 .update(cx, |_, window, cx| {
8448 let focus = cx.focus_handle();
8449 window.focus(&focus, cx);
8450 assert_eq!(window.insets(), insets);
8451 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
8452 assert_eq!(window.visual_viewport_bounds(), visual_bounds);
8453 assert_eq!(
8454 window.fully_visible_bounds(),
8455 Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
8456 );
8457 window.request_virtual_keyboard();
8458 window.dismiss_virtual_keyboard();
8459 assert!(focus.is_focused(window));
8460 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
8461 })
8462 .unwrap();
8463 assert_eq!(platform_window.virtual_keyboard_requests(), 1);
8464 assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
8465
8466 platform_window.simulate_insets_change(crate::WindowInsets {
8467 safe_area: crate::Edges {
8468 top: px(900.),
8469 left: px(500.),
8470 ..Default::default()
8471 },
8472 ..Default::default()
8473 });
8474 window
8475 .update(cx, |_, window, _| {
8476 assert_eq!(
8477 window.fully_visible_bounds().size,
8478 size(Pixels::ZERO, Pixels::ZERO)
8479 );
8480 })
8481 .unwrap();
8482
8483 use crate::PlatformWindow as _;
8485 platform_window.on_insets_changed(Box::new(|_| {}));
8486 platform_window.simulate_insets_change(crate::WindowInsets::default());
8487 window
8488 .update(cx, |_, window, _| {
8489 assert_eq!(window.insets(), crate::WindowInsets::default());
8490 })
8491 .unwrap();
8492 }
8493
8494 struct EmptyView;
8495
8496 impl Render for EmptyView {
8497 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8498 div()
8499 }
8500 }
8501
8502 struct OpensWindowOnPaint {
8503 opened: Rc<Cell<bool>>,
8504 }
8505
8506 impl Render for OpensWindowOnPaint {
8507 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8508 let opened = self.opened.clone();
8509 div()
8510 .size_full()
8511 .child(canvas(
8512 |_, _, _| {},
8513 move |_, _, _window, cx| {
8514 if !opened.replace(true) {
8515 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
8516 .unwrap();
8517 }
8518 },
8519 ))
8520 .child(div().child("after"))
8524 }
8525 }
8526
8527 #[test]
8533 fn test_window_opened_during_draw_defers_arena_clear() {
8534 let mut cx = TestAppContext::single();
8535
8536 let opened = Rc::new(Cell::new(false));
8537 let window = cx.add_window({
8539 let opened = opened.clone();
8540 move |_, _| OpensWindowOnPaint { opened }
8541 });
8542
8543 assert!(opened.get());
8544 assert_eq!(cx.windows().len(), 2);
8545
8546 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8549 .unwrap();
8550 }
8551
8552 #[test]
8553 fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
8554 let mut cx = TestAppContext::single();
8555 let window = cx.add_window(|_, _| EmptyView);
8556 let handle: AnyWindowHandle = window.into();
8557 let window_state = |cx: &mut TestAppContext| {
8558 cx.update_window(handle, |_, window, _| {
8559 (
8560 window.scale_factor(),
8561 window.bounds(),
8562 window.viewport_size(),
8563 )
8564 })
8565 .unwrap()
8566 };
8567
8568 let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
8569 assert_eq!(scale_factor, 2.0);
8570
8571 for (scale_factor, resized_size) in [
8572 (1.0, size(px(800.), px(600.))),
8573 (1.25, size(px(640.), px(480.))),
8574 (2.0, size(px(1024.), px(768.))),
8575 ] {
8576 cx.simulate_window_scale_factor_change(handle, scale_factor);
8577 assert_eq!(
8578 window_state(&mut cx),
8579 (scale_factor, expected_bounds, expected_bounds.size)
8580 );
8581
8582 cx.simulate_window_resize(handle, resized_size);
8583 expected_bounds.size = resized_size;
8584 assert_eq!(
8585 window_state(&mut cx),
8586 (scale_factor, expected_bounds, resized_size)
8587 );
8588 }
8589 }
8590
8591 #[gpui::test]
8596 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
8597 let window = cx.add_window(|_, _| EmptyView);
8598 let test_window = cx.test_window(window.into());
8599
8600 assert!(
8604 test_window.frame_wake_count() >= 1,
8605 "opening a window must wake the frame source for the initial frame"
8606 );
8607
8608 test_window.simulate_frame_request(RequestFrameOptions::default());
8610
8611 let baseline = test_window.frame_wake_count();
8614 test_window.simulate_frame_request(RequestFrameOptions::default());
8615 window.update(cx, |_, _, _| {}).unwrap();
8616 assert_eq!(
8617 test_window.frame_wake_count(),
8618 baseline,
8619 "clean frames and non-notifying updates must not wake the frame source"
8620 );
8621
8622 window.update(cx, |_, _, cx| cx.notify()).unwrap();
8624 assert!(
8625 test_window.frame_wake_count() > baseline,
8626 "notifying a view in an idle window must wake the frame source"
8627 );
8628
8629 test_window.simulate_frame_request(RequestFrameOptions::default());
8631 let baseline = test_window.frame_wake_count();
8632 test_window.simulate_frame_request(RequestFrameOptions::default());
8633 assert_eq!(
8634 test_window.frame_wake_count(),
8635 baseline,
8636 "serving demand must return the window to idle"
8637 );
8638
8639 window
8641 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
8642 .unwrap();
8643 assert!(
8644 test_window.frame_wake_count() > baseline,
8645 "scheduling a next-frame callback in an idle window must wake the frame source"
8646 );
8647 }
8648
8649 #[gpui::test]
8654 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
8655 let window = cx.add_window(|_, _| EmptyView);
8656 let test_window = cx.test_window(window.into());
8657 test_window.simulate_frame_request(RequestFrameOptions::default());
8660
8661 let callback_ran = Rc::new(Cell::new(false));
8662 window
8663 .update(cx, {
8664 let callback_ran = callback_ran.clone();
8665 move |_, window, _| {
8666 window.on_next_frame(move |_, _| callback_ran.set(true));
8667 }
8668 })
8669 .unwrap();
8670
8671 let baseline = test_window.frame_wake_count();
8672 test_window.simulate_frame_request(RequestFrameOptions::default());
8673 assert!(
8680 test_window.frame_wake_count() > baseline || callback_ran.get(),
8681 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
8682 );
8683 }
8684
8685 #[gpui::test]
8686 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
8687 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
8688
8689 let window = cx.add_window(|_, _| EmptyView);
8690 window
8691 .update(cx, |_, window, _| {
8692 assert!(matches!(
8693 window.window_handle(),
8694 Err(HandleError::NotSupported)
8695 ));
8696 assert!(matches!(
8697 window.display_handle(),
8698 Err(HandleError::NotSupported)
8699 ));
8700 })
8701 .unwrap();
8702 }
8703
8704 #[gpui::test]
8705 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
8706 let window = cx.add_window(|_, _| EmptyView);
8707 let observed_appearance = Rc::new(Cell::new(None));
8708 let _subscription = window
8709 .update(cx, {
8710 let observed_appearance = observed_appearance.clone();
8711 move |_, window, _| {
8712 window.observe_window_appearance(move |window, _| {
8713 observed_appearance.set(Some(window.appearance()));
8714 })
8715 }
8716 })
8717 .unwrap();
8718 let test_window = cx.test_window(window.into());
8719
8720 cx.update(|_| {
8721 test_window.simulate_appearance_change(WindowAppearance::Dark);
8722 assert_eq!(observed_appearance.get(), None);
8723 });
8724 cx.run_until_parked();
8725
8726 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
8727 }
8728
8729 #[gpui::test]
8730 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
8731 let window = cx.add_window(|_, _| Empty);
8732 let test_window = cx.test_window(window.into());
8733
8734 assert!(test_window.simulate_scheduled_frame());
8735 assert!(test_window.simulate_scheduled_frame());
8736 assert!(!test_window.frame_scheduled());
8737
8738 cx.update_window(window.into(), |_, window, _| {
8739 window.active.set(true);
8740 window.on_next_frame(|_, _| {});
8741 })
8742 .unwrap();
8743 assert!(
8744 test_window.frame_scheduled(),
8745 "queuing work on a parked window must wake the render loop"
8746 );
8747
8748 assert!(test_window.simulate_scheduled_frame());
8749 assert!(
8750 test_window.frame_scheduled(),
8751 "presenting the frame must await one compositor callback"
8752 );
8753 assert!(test_window.simulate_scheduled_frame());
8754 assert!(!test_window.frame_scheduled());
8755 }
8756
8757 #[gpui::test]
8758 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
8759 let window = cx.add_window(|_, _| Empty);
8760 let test_window = cx.test_window(window.into());
8761
8762 assert!(test_window.simulate_scheduled_frame());
8763 assert!(test_window.simulate_scheduled_frame());
8764 assert!(!test_window.frame_scheduled());
8765
8766 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
8767 .unwrap();
8768
8769 assert!(
8770 test_window.frame_scheduled(),
8771 "a rendered scene awaiting presentation must wake the render loop"
8772 );
8773 }
8774
8775 #[gpui::test]
8776 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
8777 let window = cx.add_window(|_, _| Empty);
8778 let test_window = cx.test_window(window.into());
8779
8780 let callback_ran = Rc::new(Cell::new(false));
8781 cx.update_window(window.into(), |_, window, _| {
8782 window.active.set(true);
8785 let callback_ran = callback_ran.clone();
8786 window.on_next_frame(move |window, _| {
8787 window.on_next_frame(move |_, _| callback_ran.set(true));
8788 });
8789 })
8790 .unwrap();
8791
8792 assert!(test_window.simulate_scheduled_frame());
8793 assert!(!callback_ran.get());
8794 assert!(
8795 test_window.frame_scheduled(),
8796 "a callback queued mid-frame must schedule a follow-up before the loop parks"
8797 );
8798
8799 assert!(test_window.simulate_scheduled_frame());
8800 assert!(callback_ran.get());
8801 }
8802
8803 struct RootView {
8804 explicit_size: bool,
8805 child_bounds: Rc<Cell<Bounds<Pixels>>>,
8806 }
8807
8808 impl Render for RootView {
8809 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8810 let child_bounds = self.child_bounds.clone();
8811 let root = div().flex().flex_col().child(
8812 canvas(
8813 move |bounds, _, _| child_bounds.set(bounds),
8814 |_, _, _, _| {},
8815 )
8816 .size_full(),
8817 );
8818 if self.explicit_size {
8819 root.w(px(300.)).h(px(200.))
8820 } else {
8821 root
8822 }
8823 }
8824 }
8825
8826 #[test]
8827 fn auto_sized_window_root_fills_the_window() {
8828 let mut cx = TestAppContext::single();
8829 let child_bounds = Rc::new(Cell::new(Bounds::default()));
8830 let window = cx.add_window({
8831 let child_bounds = child_bounds.clone();
8832 move |_, _| RootView {
8833 explicit_size: false,
8834 child_bounds,
8835 }
8836 });
8837
8838 let viewport_size = cx
8839 .update_window(window.into(), |_, window, cx| {
8840 window.draw(cx).clear(cx);
8841 window.viewport_size()
8842 })
8843 .unwrap();
8844
8845 assert_eq!(child_bounds.get().size, viewport_size);
8846 }
8847
8848 #[test]
8849 fn explicitly_sized_window_root_keeps_its_size() {
8850 let mut cx = TestAppContext::single();
8851 let child_bounds = Rc::new(Cell::new(Bounds::default()));
8852 let window = cx.add_window({
8853 let child_bounds = child_bounds.clone();
8854 move |_, _| RootView {
8855 explicit_size: true,
8856 child_bounds,
8857 }
8858 });
8859
8860 cx.update_window(window.into(), |_, window, cx| {
8861 window.draw(cx).clear(cx);
8862 })
8863 .unwrap();
8864
8865 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
8866 }
8867
8868 struct FileDragView {
8869 path: PathBuf,
8870 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
8871 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
8872 }
8873
8874 struct FileDropExitView(Rc<Cell<usize>>);
8875
8876 impl Render for FileDropExitView {
8877 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8878 div().size_full().on_file_drop_exit({
8879 let observed_file_drop_exit = self.0.clone();
8880 move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
8881 })
8882 }
8883 }
8884
8885 impl Render for FileDragView {
8886 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8887 div()
8888 .id("file-drag")
8889 .size_full()
8890 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
8891 .external_drag_payload(|path: &PathBuf, _, _| {
8892 Some(ExternalDragPayload::Files(FileDragPaths::new([(
8893 path.clone(),
8894 true,
8895 )])))
8896 })
8897 .on_drag_move({
8898 let observed_drag_moves = self.observed_drag_moves.clone();
8899 move |event: &DragMoveEvent<PathBuf>, _, _| {
8900 observed_drag_moves.borrow_mut().push(event.event.position);
8901 }
8902 })
8903 .on_drop({
8904 let observed_drops = self.observed_drops.clone();
8905 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
8906 })
8907 }
8908 }
8909
8910 #[gpui::test]
8911 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
8912 struct Drag {
8913 window: AnyWindowHandle,
8914 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
8915 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
8916 }
8917
8918 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
8919 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
8920 let observed_drops = Rc::new(RefCell::new(Vec::new()));
8921 let window: AnyWindowHandle = cx
8922 .add_window({
8923 let observed_drag_moves = observed_drag_moves.clone();
8924 let observed_drops = observed_drops.clone();
8925 move |_, _| FileDragView {
8926 path,
8927 observed_drag_moves,
8928 observed_drops,
8929 }
8930 })
8931 .into();
8932 cx.test_window(window)
8933 .set_start_external_drag_result(platform_result);
8934
8935 let update_result = cx.update_window(window, |_, window, cx| {
8936 window.draw(cx).clear(cx);
8937 window.dispatch_event(
8938 MouseDownEvent {
8939 position: point(px(10.), px(10.)),
8940 button: MouseButton::Left,
8941 modifiers: Default::default(),
8942 click_count: 1,
8943 first_mouse: false,
8944 }
8945 .to_platform_input(),
8946 cx,
8947 );
8948 window.dispatch_event(
8949 MouseMoveEvent {
8950 position: point(px(20.), px(20.)),
8951 pressed_button: Some(MouseButton::Left),
8952 modifiers: Default::default(),
8953 }
8954 .to_platform_input(),
8955 cx,
8956 );
8957 assert!(cx.active_drag.is_some());
8958 });
8959 assert!(
8960 update_result.is_ok(),
8961 "failed to start drag: {update_result:?}"
8962 );
8963
8964 assert!(cx.test_window(window).external_drag_files().is_empty());
8965 Drag {
8966 window,
8967 observed_drag_moves,
8968 observed_drops,
8969 }
8970 }
8971
8972 let successful_path = PathBuf::from("/tmp/successful-drag");
8973 let successful = start_drag(cx, successful_path.clone(), true);
8974 let outside_position = point(px(-1.), px(20.));
8975 let update_result = cx.update_window(successful.window, |_, window, cx| {
8976 window.dispatch_event(
8977 MouseMoveEvent {
8978 position: outside_position,
8979 pressed_button: Some(MouseButton::Left),
8980 modifiers: Default::default(),
8981 }
8982 .to_platform_input(),
8983 cx,
8984 );
8985 assert!(cx.active_drag.is_none());
8986 });
8987 assert!(
8988 update_result.is_ok(),
8989 "failed to promote drag: {update_result:?}"
8990 );
8991 assert_eq!(
8992 cx.test_window(successful.window).external_drag_files(),
8993 [(successful_path.clone(), true)]
8994 );
8995 assert_eq!(
8998 successful.observed_drag_moves.borrow().last(),
8999 Some(&outside_position)
9000 );
9001
9002 let first_destination_exit_count = Rc::new(Cell::new(0));
9003 let first_destination: AnyWindowHandle = cx
9004 .add_window({
9005 let first_destination_exit_count = first_destination_exit_count.clone();
9006 move |_, _| FileDropExitView(first_destination_exit_count)
9007 })
9008 .into();
9009 let second_destination_exit_count = Rc::new(Cell::new(0));
9010 let second_destination: AnyWindowHandle = cx
9011 .add_window({
9012 let second_destination_exit_count = second_destination_exit_count.clone();
9013 move |_, _| FileDropExitView(second_destination_exit_count)
9014 })
9015 .into();
9016 let reentry_position = point(px(30.), px(30.));
9017 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
9018 let update_result = cx.update_window(first_destination, |_, window, cx| {
9019 window.draw(cx).clear(cx);
9020 window.dispatch_event(
9021 FileDropEvent::Entered {
9022 position: reentry_position,
9023 paths: external_paths(),
9024 }
9025 .to_platform_input(),
9026 cx,
9027 );
9028 assert!(
9029 cx.active_drag
9030 .as_ref()
9031 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9032 );
9033 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9034 assert!(cx.active_drag.is_none());
9035 assert_eq!(first_destination_exit_count.get(), 1);
9036 assert_eq!(second_destination_exit_count.get(), 0);
9037 });
9038 assert!(
9039 update_result.is_ok(),
9040 "failed to handle drag in first destination window: {update_result:?}"
9041 );
9042
9043 let update_result = cx.update_window(second_destination, |_, window, cx| {
9044 window.draw(cx).clear(cx);
9045 window.dispatch_event(
9046 PlatformInput::KeyDown(KeyDownEvent {
9047 keystroke: Keystroke::parse("down").expect("valid keystroke"),
9048 is_held: false,
9049 prefer_character_input: false,
9050 }),
9051 cx,
9052 );
9053 window.dispatch_event(
9054 FileDropEvent::Entered {
9055 position: reentry_position,
9056 paths: external_paths(),
9057 }
9058 .to_platform_input(),
9059 cx,
9060 );
9061 assert!(
9062 cx.active_drag
9063 .as_ref()
9064 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9065 );
9066 assert_eq!(first_destination_exit_count.get(), 1);
9067 assert_eq!(second_destination_exit_count.get(), 0);
9068
9069 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9070 assert!(cx.active_drag.is_none());
9071 assert_eq!(first_destination_exit_count.get(), 1);
9072 assert_eq!(second_destination_exit_count.get(), 1);
9073 });
9074 assert!(
9075 update_result.is_ok(),
9076 "failed to handle drag in second destination window: {update_result:?}"
9077 );
9078
9079 let update_result = cx.update_window(successful.window, |_, window, cx| {
9080 window.dispatch_event(
9081 FileDropEvent::Entered {
9082 position: reentry_position,
9083 paths: external_paths(),
9084 }
9085 .to_platform_input(),
9086 cx,
9087 );
9088 assert!(
9089 cx.active_drag
9090 .as_ref()
9091 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9092 );
9093 assert_eq!(
9094 successful.observed_drag_moves.borrow().last(),
9095 Some(&reentry_position)
9096 );
9097
9098 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9099 assert!(cx.active_drag.is_none());
9100
9101 window.dispatch_event(
9102 FileDropEvent::Entered {
9103 position: reentry_position,
9104 paths: external_paths(),
9105 }
9106 .to_platform_input(),
9107 cx,
9108 );
9109 assert!(
9110 cx.active_drag
9111 .as_ref()
9112 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9113 );
9114
9115 window.dispatch_event(
9116 FileDropEvent::Submit {
9117 position: reentry_position,
9118 }
9119 .to_platform_input(),
9120 cx,
9121 );
9122 assert_eq!(
9123 successful.observed_drops.borrow().as_slice(),
9124 std::slice::from_ref(&successful_path)
9125 );
9126 assert!(cx.active_drag.is_none());
9127
9128 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9129 assert!(cx.active_drag.is_none());
9130 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
9131 assert!(cx.active_drag.is_none());
9132
9133 window.dispatch_event(
9134 FileDropEvent::Entered {
9135 position: reentry_position,
9136 paths: external_paths(),
9137 }
9138 .to_platform_input(),
9139 cx,
9140 );
9141 assert!(
9142 cx.active_drag
9143 .as_ref()
9144 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
9145 );
9146 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
9147 });
9148 assert!(
9149 update_result.is_ok(),
9150 "failed to restore drag in source window: {update_result:?}"
9151 );
9152
9153 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
9154 let cancelled = start_drag(cx, cancelled_path.clone(), true);
9155 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
9156 window.dispatch_event(
9157 MouseMoveEvent {
9158 position: outside_position,
9159 pressed_button: Some(MouseButton::Left),
9160 modifiers: Default::default(),
9161 }
9162 .to_platform_input(),
9163 cx,
9164 );
9165 assert!(cx.active_drag.is_none());
9166
9167 window.dispatch_event(
9168 FileDropEvent::Entered {
9169 position: reentry_position,
9170 paths: ExternalPaths([cancelled_path].into_iter().collect()),
9171 }
9172 .to_platform_input(),
9173 cx,
9174 );
9175 assert!(
9176 cx.active_drag
9177 .as_ref()
9178 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
9179 );
9180 assert!(cx.stop_active_drag(window));
9181 assert!(cx.active_drag.is_none());
9182 });
9183 assert!(
9184 update_result.is_ok(),
9185 "failed to cancel restored drag: {update_result:?}"
9186 );
9187 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
9188
9189 let removed_path = PathBuf::from("/tmp/removed-window-drag");
9190 let removed = start_drag(cx, removed_path, true);
9191 let removed_window_id = removed.window.window_id();
9192 let update_result = cx.update_window(removed.window, |_, window, cx| {
9193 window.dispatch_event(
9194 MouseMoveEvent {
9195 position: outside_position,
9196 pressed_button: Some(MouseButton::Left),
9197 modifiers: Default::default(),
9198 }
9199 .to_platform_input(),
9200 cx,
9201 );
9202 assert!(cx.active_drag.is_none());
9203 window.remove_window();
9204 });
9205 assert!(
9206 update_result.is_ok(),
9207 "failed to remove drag source window: {update_result:?}"
9208 );
9209 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
9210
9211 let failed_path = PathBuf::from("/tmp/failed-drag");
9212 let failed = start_drag(cx, failed_path.clone(), false);
9213 let update_result = cx.update_window(failed.window, |_, window, cx| {
9214 for x_position in [-1., -2.] {
9215 window.dispatch_event(
9216 MouseMoveEvent {
9217 position: point(px(x_position), px(20.)),
9218 pressed_button: Some(MouseButton::Left),
9219 modifiers: Default::default(),
9220 }
9221 .to_platform_input(),
9222 cx,
9223 );
9224 }
9225 assert!(cx.active_drag.is_some());
9226 });
9227 assert!(
9228 update_result.is_ok(),
9229 "failed to retain drag after platform failure: {update_result:?}"
9230 );
9231 assert_eq!(
9232 cx.test_window(failed.window).external_drag_files(),
9233 [(failed_path, true)]
9234 );
9235 }
9236
9237 struct FocusForwarder {
9238 a: FocusHandle,
9239 b: FocusHandle,
9240 }
9241
9242 impl Render for FocusForwarder {
9243 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9244 div()
9245 .size_full()
9246 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
9247 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
9248 }
9249 }
9250
9251 #[gpui::test]
9255 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
9256 let b_focus_count = Rc::new(Cell::new(0));
9257 let window = cx.add_window({
9258 let b_focus_count = b_focus_count.clone();
9259 move |window, cx| {
9260 let a = cx.focus_handle();
9261 let b = cx.focus_handle();
9262 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
9263 let b = this.b.clone();
9264 window.focus(&b, cx);
9265 })
9266 .detach();
9267 cx.on_focus(&b, window, move |_, _, _| {
9268 b_focus_count.set(b_focus_count.get() + 1);
9269 })
9270 .detach();
9271 FocusForwarder { a, b }
9272 }
9273 });
9274
9275 window
9276 .update(cx, |_, window, _| window.activate_window())
9277 .unwrap();
9278 cx.executor().run_until_parked();
9279
9280 window
9281 .update(cx, |this, window, cx| {
9282 let a = this.a.clone();
9283 window.focus(&a, cx);
9284 })
9285 .unwrap();
9286 cx.executor().run_until_parked();
9287
9288 window
9289 .update(cx, |this, window, _| {
9290 assert!(this.b.is_focused(window));
9291 })
9292 .unwrap();
9293 assert_eq!(b_focus_count.get(), 1);
9294 }
9295
9296 #[gpui::test]
9297 fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
9298 let events = Rc::new(RefCell::new(Vec::new()));
9299 let window = cx.add_window({
9300 let events = events.clone();
9301 move |_, _| TouchDragListener { events }
9302 });
9303 let touch = TouchId(1);
9304
9305 dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
9306 dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
9307 dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
9308
9309 assert_eq!(
9310 events.borrow().as_slice(),
9311 [
9312 (TouchPhase::Started, px(10.)),
9313 (TouchPhase::Moved, px(30.)),
9314 (TouchPhase::Ended, px(40.)),
9315 ]
9316 );
9317 }
9318
9319 #[gpui::test]
9320 fn back_gesture_is_claimed_by_the_innermost_listener(cx: &mut TestAppContext) {
9321 let claims = Rc::new(RefCell::new(Vec::new()));
9322 let window = cx.add_window({
9323 let claims = claims.clone();
9324 move |_, _| BackListeners { claims }
9325 });
9326 let dispatch_back = |cx: &mut TestAppContext, x: f32| {
9327 window
9328 .update(cx, |_, window, cx| {
9329 window
9330 .dispatch_event(
9331 BackGestureEvent {
9332 phase: BackGesturePhase::Started,
9333 start_position: point(px(x), px(10.)),
9334 progress: 0.,
9335 }
9336 .to_platform_input(),
9337 cx,
9338 )
9339 .default_prevented
9340 })
9341 .unwrap()
9342 };
9343 assert!(dispatch_back(cx, 10.));
9344 assert!(dispatch_back(cx, 80.));
9345 assert!(!dispatch_back(cx, 150.));
9346 assert_eq!(claims.borrow().as_slice(), ["inner", "outer"]);
9347 }
9348
9349 struct BackListeners {
9350 claims: Rc<RefCell<Vec<&'static str>>>,
9351 }
9352
9353 impl Render for BackListeners {
9354 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9355 let claim = |name: &'static str| {
9356 let claims = self.claims.clone();
9357 move |_: &BackGestureEvent, _: &mut Window, _: &mut crate::App| {
9358 claims.borrow_mut().push(name)
9359 }
9360 };
9361 div().size_full().child(
9362 div()
9363 .w(px(100.))
9364 .h_full()
9365 .on_back_gesture(claim("outer"))
9366 .child(div().w(px(50.)).h_full().on_back_gesture(claim("inner"))),
9367 )
9368 }
9369 }
9370
9371 struct TouchDragListener {
9372 events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
9373 }
9374
9375 impl Render for TouchDragListener {
9376 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9377 let events = self.events.clone();
9378 canvas(
9379 |_, _, _| {},
9380 move |_, _, window, _| {
9381 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
9382 if phase != DispatchPhase::Bubble {
9383 return;
9384 }
9385 events.borrow_mut().push((event.phase, event.position.x));
9386 if event.phase == TouchPhase::Started {
9387 window.prevent_default();
9388 }
9389 });
9390 },
9391 )
9392 }
9393 }
9394
9395 #[gpui::test]
9396 fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
9397 for response in [
9398 LongPressResponse::PreventDefault,
9399 LongPressResponse::StopPropagation,
9400 LongPressResponse::None,
9401 ] {
9402 let phases = Rc::new(RefCell::new(Vec::new()));
9403 let window = cx.add_window({
9404 let phases = phases.clone();
9405 move |_, _| LongPressListener { phases, response }
9406 });
9407 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9408 cx.executor().advance_clock(Duration::from_millis(501));
9409 cx.executor().run_until_parked();
9410 window
9411 .update(cx, |_, window, _| {
9412 assert_eq!(
9413 window.long_press_capture.is_some(),
9414 response == LongPressResponse::PreventDefault
9415 );
9416 })
9417 .unwrap();
9418 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
9419 dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
9420 window
9421 .update(cx, |_, window, _| {
9422 assert!(window.long_press_capture.is_none());
9423 })
9424 .unwrap();
9425
9426 let phases = phases.borrow();
9427 if response == LongPressResponse::PreventDefault {
9428 assert_eq!(
9429 phases.as_slice(),
9430 [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
9431 );
9432 } else {
9433 assert_eq!(phases.as_slice(), [TouchPhase::Started]);
9434 }
9435 }
9436 }
9437
9438 #[gpui::test]
9439 fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
9440 let phases = Rc::new(RefCell::new(Vec::new()));
9441 let window = cx.add_window({
9442 let phases = phases.clone();
9443 move |_, _| LongPressListener {
9444 phases,
9445 response: LongPressResponse::None,
9446 }
9447 });
9448 window
9449 .update(cx, |_, window, _| {
9450 window.prevent_default();
9451 })
9452 .unwrap();
9453
9454 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9455 cx.executor().advance_clock(Duration::from_millis(501));
9456 cx.executor().run_until_parked();
9457 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
9458
9459 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
9460 }
9461
9462 #[gpui::test]
9463 fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
9464 for (phase, position) in [
9465 (TouchPhase::Ended, 0.),
9466 (TouchPhase::Cancelled, 0.),
9467 (TouchPhase::Moved, 20.),
9468 ] {
9469 let phases = Rc::new(RefCell::new(Vec::new()));
9470 let window = cx.add_window({
9471 let phases = phases.clone();
9472 move |_, _| LongPressListener {
9473 phases,
9474 response: LongPressResponse::PreventDefault,
9475 }
9476 });
9477 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
9478 dispatch_touch(window, cx, TouchId(1), phase, position);
9479 cx.executor().advance_clock(Duration::from_millis(501));
9480 cx.executor().run_until_parked();
9481
9482 assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
9483 }
9484 }
9485
9486 #[gpui::test]
9487 fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
9488 let phases = Rc::new(RefCell::new(Vec::new()));
9489 let window = cx.add_window({
9490 let phases = phases.clone();
9491 move |_, _| LongPressListener {
9492 phases,
9493 response: LongPressResponse::PreventDefault,
9494 }
9495 });
9496 let first_touch = TouchId(1);
9497 dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
9498 cx.executor().advance_clock(Duration::from_millis(250));
9499 dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
9500 dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
9501
9502 cx.executor().advance_clock(Duration::from_millis(251));
9503 cx.executor().run_until_parked();
9504 assert!(phases.borrow().is_empty());
9505
9506 cx.executor().advance_clock(Duration::from_millis(250));
9507 cx.executor().run_until_parked();
9508 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
9509 }
9510
9511 #[gpui::test]
9512 fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
9513 test_underline_paint_at_scales(cx, |window| {
9514 let (numerator, denominator) = match window.scale_factor() {
9515 1.0 => (1, 1),
9516 1.25 => (5, 4),
9517 1.5 => (3, 2),
9518 2.0 => (2, 1),
9519 3.0 => (3, 1),
9520 scale => panic!("unexpected scale {scale}"),
9521 };
9522 let snap = |quarters: i32| {
9523 let scaled = quarters * numerator;
9524 let divisor = 4 * denominator;
9525 let rounded =
9526 scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
9527 ScaledPixels((scaled.signum() * rounded) as f32)
9528 };
9529 let stroke = |quarters| {
9530 if quarters == 0 {
9531 ScaledPixels(0.)
9532 } else {
9533 snap(quarters).max(ScaledPixels(1.))
9534 }
9535 };
9536
9537 for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
9538 for width in [0, 1, 3, 84] {
9539 for thickness in [0, 1, 4, 7] {
9540 for wavy in [false, true] {
9541 let style = UnderlineStyle {
9542 thickness: px(thickness as f32 / 4.),
9543 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
9544 wavy,
9545 };
9546 let bounds = Bounds::new(
9547 point(snap(origin), snap(-origin)),
9548 size(
9549 stroke(width),
9550 stroke(thickness) * if wavy { 3. } else { 1. },
9551 ),
9552 );
9553 let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
9554 let width = px(width as f32 / 4.);
9555 assert_eq!(window.underline_bounds(origin, width, &style), bounds);
9556 let original = paint_test_underlines(window, |window| {
9557 window.paint_underline(origin, width, &style);
9558 })
9559 .to_vec();
9560 assert_eq!(original.len(), usize::from(!bounds.is_empty()));
9561 if let Some(underline) = original.first() {
9562 assert_eq!(underline.bounds, bounds);
9563 assert_eq!(underline.thickness, stroke(thickness));
9564 assert_eq!(underline.wavy, wavy.into());
9565 assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
9566 }
9567
9568 let underlines = paint_test_underlines(window, |window| {
9569 window.paint_underline_with_exclusions(origin, width, &style, &[]);
9570 });
9571 assert_eq!(underlines.len(), original.len());
9572 for (actual, original) in underlines.iter().zip(&original) {
9573 assert_same_underline_geometry(actual, original);
9574 assert_eq!(actual.content_mask, original.content_mask);
9575 }
9576
9577 let left = bounds.left().0 as i32;
9578 let right = bounds.right().0 as i32;
9579 let exclusions = [
9580 (15, 25),
9581 (3, 7),
9582 (5, 10),
9583 (10, 12),
9584 (0, 0),
9585 (4, 2),
9586 (-50, -1),
9587 (70, 100),
9588 ]
9589 .map(|(start, end)| {
9590 ScaledPixels((left + start) as f32)
9591 ..ScaledPixels((left + end) as f32)
9592 });
9593 let underlines = paint_test_underlines(window, |window| {
9594 window.paint_underline_with_exclusions(
9595 origin,
9596 width,
9597 &style,
9598 &exclusions,
9599 );
9600 });
9601 let expected = (left..right)
9602 .filter(|column| {
9603 !bounds.is_empty()
9604 && !exclusions.iter().any(|span| {
9605 span.contains(&ScaledPixels(*column as f32))
9606 })
9607 })
9608 .collect::<Vec<_>>();
9609 assert_eq!(underline_device_columns(underlines), expected);
9610 for underline in underlines {
9611 assert_same_underline_geometry(underline, &original[0]);
9612 }
9613 }
9614 }
9615 }
9616 }
9617 });
9618 }
9619
9620 #[gpui::test]
9621 fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
9622 test_underline_paint_at_scales(cx, |window| {
9623 if window.scale_factor() != 2.0 {
9624 return;
9625 }
9626 let style = UnderlineStyle {
9627 thickness: px(1.),
9628 color: None,
9629 wavy: true,
9630 };
9631 let origin = point(px(2.888_183_8), px(15.357_917));
9632 let width = px(23.848_145) - origin.x;
9633 let original = paint_test_underlines(window, |window| {
9634 window.paint_underline(origin, width, &style);
9635 })[0];
9636 assert_eq!(original.bounds.left(), ScaledPixels(6.));
9637 assert_eq!(original.bounds.right(), ScaledPixels(48.));
9638 let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
9639 assert_eq!(point_bounds.left(), ScaledPixels(6.));
9640 assert_eq!(point_bounds.right(), ScaledPixels(28.));
9641
9642 let underlines = paint_test_underlines(window, |window| {
9643 window.paint_underline_with_exclusions(
9644 origin,
9645 width,
9646 &style,
9647 &[point_bounds.left()..point_bounds.right()],
9648 );
9649 });
9650 assert_eq!(underlines.len(), 1);
9651 assert_same_underline_geometry(&underlines[0], &original);
9652 assert_eq!(
9653 underline_device_columns(underlines),
9654 (28..48).collect::<Vec<_>>()
9655 );
9656 });
9657 }
9658
9659 #[gpui::test]
9660 fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
9661 test_underline_paint_at_scales(cx, |window| {
9662 let scale = window.scale_factor();
9663 let original_mask = window.content_mask();
9664 let original_opacity = window.element_opacity();
9665 let mask = ContentMask {
9666 bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
9667 };
9668 let style = UnderlineStyle {
9669 thickness: px(2.),
9670 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
9671 wavy: true,
9672 };
9673 let origin = point(px(-1.25), px(9.25));
9674 let width = px(24.);
9675 window.with_content_mask(Some(mask), |window| {
9676 window.with_element_opacity(Some(0.5), |window| {
9677 window.with_element_opacity(Some(0.5), |window| {
9678 let original = paint_test_underlines(window, |window| {
9679 window.paint_underline(origin, width, &style);
9680 })[0];
9681 assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
9682 let underlines = paint_test_underlines(window, |window| {
9683 window.paint_underline_with_exclusions(
9684 origin,
9685 width,
9686 &style,
9687 &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
9688 );
9689 });
9690 assert_eq!(underlines.len(), 2);
9691 let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
9692 |(left, right)| {
9693 Bounds::from_corners(
9694 point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
9695 point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
9696 )
9697 },
9698 );
9699 assert_eq!(
9700 underlines
9701 .iter()
9702 .map(|underline| underline.content_mask.bounds)
9703 .collect::<Vec<_>>(),
9704 expected
9705 );
9706 for underline in underlines {
9707 assert_same_underline_geometry(underline, &original);
9708 }
9709 });
9710 });
9711 });
9712 assert_eq!(window.content_mask(), original_mask);
9713 assert_eq!(window.element_opacity(), original_opacity);
9714 });
9715 }
9716
9717 #[gpui::test]
9718 fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
9719 test_underline_paint_at_scales(cx, |window| {
9720 let style = UnderlineStyle {
9721 thickness: px(1.),
9722 color: None,
9723 wavy: true,
9724 };
9725 let origin = point(px(-4.), px(-1.));
9726 let width = px(8.);
9727 let left = (-4. * window.scale_factor()) as i32;
9728 let right = (4. * window.scale_factor()) as i32;
9729 let endpoints = [-16, -8, -1, 0, 1, 8, 16];
9730 for first_start in endpoints {
9731 for first_end in endpoints {
9732 for second_start in endpoints {
9733 for second_end in endpoints {
9734 let exclusions = [first_start..first_end, second_start..second_end];
9735 let expected = (left..right)
9736 .filter(|column| {
9737 !exclusions.iter().any(|span| span.contains(column))
9738 })
9739 .collect::<Vec<_>>();
9740 let exclusions = exclusions.map(|span| {
9741 ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
9742 });
9743 let underlines = paint_test_underlines(window, |window| {
9744 window.paint_underline_with_exclusions(
9745 origin,
9746 width,
9747 &style,
9748 &exclusions,
9749 );
9750 });
9751 assert_eq!(
9752 underline_device_columns(underlines),
9753 expected,
9754 "{exclusions:?}"
9755 );
9756 }
9757 }
9758 }
9759 }
9760 });
9761 }
9762
9763 #[derive(Clone, Copy, PartialEq)]
9764 enum LongPressResponse {
9765 PreventDefault,
9766 StopPropagation,
9767 None,
9768 }
9769
9770 struct LongPressListener {
9771 phases: Rc<RefCell<Vec<TouchPhase>>>,
9772 response: LongPressResponse,
9773 }
9774
9775 impl Render for LongPressListener {
9776 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
9777 let entity = cx.entity();
9778 let phases = self.phases.clone();
9779 let response = self.response;
9780 canvas(
9781 |_, _, _| {},
9782 move |_, _, window, _| {
9783 window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
9784 if phase != DispatchPhase::Bubble {
9785 return;
9786 }
9787 phases.borrow_mut().push(event.phase);
9788 match response {
9789 LongPressResponse::PreventDefault => {
9790 window.capture_long_press(&entity);
9791 window.prevent_default();
9792 }
9793 LongPressResponse::StopPropagation => cx.stop_propagation(),
9794 LongPressResponse::None => {}
9795 }
9796 });
9797 },
9798 )
9799 }
9800 }
9801
9802 struct UnderlineTestView(Rc<dyn Fn(&mut Window)>);
9803
9804 impl Render for UnderlineTestView {
9805 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
9806 let paint = self.0.clone();
9807 canvas(
9808 |_, _, _| {},
9809 move |_, _, window, _| {
9810 window.content_mask_stack.push(ContentMask {
9811 bounds: Bounds::from_corners(
9812 point(px(-1000.), px(-1000.)),
9813 point(px(1000.), px(1000.)),
9814 ),
9815 });
9816 paint(window);
9817 window.content_mask_stack.pop();
9818 },
9819 )
9820 .size_full()
9821 }
9822 }
9823
9824 fn test_underline_paint_at_scales(
9825 cx: &mut TestAppContext,
9826 paint: impl Fn(&mut Window) + 'static,
9827 ) {
9828 let window = cx.add_window(move |_, _| UnderlineTestView(Rc::new(paint)));
9829 for scale in [1., 1.25, 1.5, 2., 3.] {
9830 cx.simulate_window_scale_factor_change(window.into(), scale);
9831 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
9832 .unwrap();
9833 }
9834 }
9835
9836 fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
9837 window.next_frame.scene.clear();
9838 paint(window);
9839 &window.next_frame.scene.underlines
9840 }
9841
9842 fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
9843 assert_eq!(actual.bounds, expected.bounds);
9844 assert_eq!(actual.thickness, expected.thickness);
9845 assert_eq!(actual.wavy, expected.wavy);
9846 assert_eq!(actual.color, expected.color);
9847 assert_eq!(actual.pad, expected.pad);
9848 }
9849
9850 fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
9851 underlines
9852 .iter()
9853 .flat_map(|underline| {
9854 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
9855 bounds.left().0 as i32..bounds.right().0 as i32
9856 })
9857 .collect()
9858 }
9859
9860 fn dispatch_touch<T: 'static>(
9861 window: crate::WindowHandle<T>,
9862 cx: &mut TestAppContext,
9863 id: TouchId,
9864 phase: TouchPhase,
9865 x: f32,
9866 ) {
9867 window
9868 .update(cx, |_, window, cx| {
9869 window.dispatch_event(
9870 TouchEvent {
9871 id,
9872 phase,
9873 position: point(px(x), px(0.)),
9874 predicted_position: None,
9875 force: None,
9876 }
9877 .to_platform_input(),
9878 cx,
9879 );
9880 })
9881 .unwrap();
9882 }
9883}
9884
9885#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
9886mod inspector_tests {
9887 use super::*;
9888 use crate::{
9889 DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
9890 };
9891
9892 #[gpui::test]
9893 fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
9894 let windows = [
9895 cx.add_window(|_, cx| InspectorTestRoot {
9896 child: cx.new(|_| InspectorTestView::default()),
9897 }),
9898 cx.add_window(|_, cx| InspectorTestRoot {
9899 child: cx.new(|_| InspectorTestView::default()),
9900 }),
9901 ];
9902 for window in windows {
9903 assert_closed_inspector(window.into(), cx);
9904 }
9905 for _ in 0..2 {
9906 cx.update_window(windows[0].into(), |root, window, cx| {
9907 let root = root.downcast::<InspectorTestRoot>().expect("test root");
9908 let child_widths = root.read(cx).child.read(cx).child_widths.clone();
9909 window.toggle_inspector(cx);
9910 window.draw(cx).clear(cx);
9911 assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
9912 let path = window
9913 .rendered_frame
9914 .next_inspector_instance_ids
9915 .iter()
9916 .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
9917 .expect("anonymous siblings share an inspector path");
9918 let selected_id = InspectorElementId {
9919 path,
9920 instance_id: 1,
9921 };
9922 let position = window
9923 .rendered_frame
9924 .hitboxes
9925 .iter()
9926 .find(|hitbox| {
9927 window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
9928 == Some(&selected_id)
9929 })
9930 .expect("middle sibling is pickable")
9931 .bounds
9932 .center();
9933 window.simulate_mouse_move(position, cx);
9934 window.dispatch_event(
9935 PlatformInput::MouseDown(MouseDownEvent {
9936 position,
9937 button: MouseButton::Left,
9938 modifiers: Modifiers::default(),
9939 click_count: 1,
9940 first_mouse: false,
9941 }),
9942 cx,
9943 );
9944 window.dispatch_event(
9945 PlatformInput::MouseUp(MouseUpEvent {
9946 position,
9947 button: MouseButton::Left,
9948 modifiers: Modifiers::default(),
9949 click_count: 1,
9950 }),
9951 cx,
9952 );
9953 assert!(!window.is_inspector_picking(cx));
9954 assert_eq!(
9955 window
9956 .inspector
9957 .as_ref()
9958 .expect("open inspector")
9959 .read(cx)
9960 .active_element_id(),
9961 Some(&selected_id)
9962 );
9963 window.draw(cx).clear(cx);
9964 window.with_inspector_state::<DivInspectorState, _>(
9965 Some(&selected_id),
9966 cx,
9967 |state, _| {
9968 let state = state.as_mut().expect("selected div has style state");
9969 assert_eq!(
9970 state.base_style.size.width,
9971 Some(crate::Length::from(px(10.)))
9972 );
9973 state.base_style.size.width = Some(crate::Length::from(px(25.)));
9974 },
9975 );
9976 window.refresh();
9977 window.draw(cx).clear(cx);
9978 assert_eq!(
9979 child_widths.borrow().as_slice(),
9980 &[px(10.), px(25.), px(10.)]
9981 );
9982 })
9983 .expect("pick and edit a cached child");
9984 assert_closed_inspector(windows[1].into(), cx);
9985 windows[0]
9986 .update(cx, |_, window, cx| window.toggle_inspector(cx))
9987 .expect("close inspector");
9988 assert_closed_inspector(windows[0].into(), cx);
9989 }
9990 }
9991
9992 struct InspectorTestRoot {
9993 child: Entity<InspectorTestView>,
9994 }
9995
9996 impl Render for InspectorTestRoot {
9997 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
9998 self.child
9999 .clone()
10000 .cached(StyleRefinement::default().size(px(100.)))
10001 }
10002 }
10003
10004 #[derive(Default)]
10005 struct InspectorTestView {
10006 child_widths: Rc<RefCell<Vec<Pixels>>>,
10007 }
10008
10009 impl Render for InspectorTestView {
10010 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
10011 let child_widths = self.child_widths.clone();
10012 div()
10013 .on_children_prepainted(move |bounds, _, _| {
10014 *child_widths.borrow_mut() =
10015 bounds.iter().map(|bounds| bounds.size.width).collect();
10016 })
10017 .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
10018 .id("inspector-root")
10019 .flex()
10020 .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
10021 }
10022 }
10023
10024 fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
10025 cx.update_window(window, |root, window, cx| {
10026 window.draw(cx).clear(cx);
10027 window.draw(cx).clear(cx);
10028 let root = root.downcast::<InspectorTestRoot>().expect("test root");
10029 assert_eq!(
10030 root.read(cx)
10031 .child
10032 .read(cx)
10033 .child_widths
10034 .borrow()
10035 .as_slice(),
10036 &[px(10.); 3]
10037 );
10038 for frame in [&window.rendered_frame, &window.next_frame] {
10039 assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
10040 assert_eq!(frame.inspector_hitboxes.capacity(), 0);
10041 }
10042 })
10043 .expect("closed inspector has no bookkeeping and no style overrides");
10044 }
10045}