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