1#[cfg(feature = "profiler")]
2use crate::DebugFrameOverlayMode;
3#[cfg(any(feature = "inspector", debug_assertions))]
4use crate::Inspector;
5#[cfg(feature = "profiler")]
6use crate::profiler;
7use crate::subscription::SingleSubscriberSet;
8use crate::taffy::TaffyLayoutEngine;
9use crate::{
10 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
11 AsyncWindowContext, AtlasKey, AtlasStats, AtlasTile, AvailableSpace, BackdropBlurRect, Background, BorderStyle,
12 EffectQuad, EffectSpec,
13 Bounds, BoxShadow,
14 Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,
15 DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
16 EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
17 GlyphShadowParams, GpuTextureHandle,
18 Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent,
19 Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent,
20 MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, PaintedPath, Path,
21 Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow,
22 Point, PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams,
23 RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
24 SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,
25 SpriteAnimation, SpriteAnimationId, StrikethroughStyle, Style, SubpixelSprite, Subscription,
26 SystemWindowTab, SystemWindowTabController, TabStopMap, Task, TextInputConfiguration,
27 TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState,
28 TileSource, TileWrite, TransformationMatrix, Underline, UnderlineStyle, WindowAppearance,
29 WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations, WindowInsets,
30 WindowOptions, WindowParams, WindowTextSystem, WindowVisibility, blur_glyph_coverage, point,
31 prelude::*, px, rems, size, transparent_black,
32};
33
34use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
35use crate::interactive::TouchEvent;
36use crate::util::impl_deref;
37use anyhow::{Context as _, Result, anyhow};
38use collections::{FxHashMap, FxHashSet};
39use futures::channel::oneshot;
40use gpui_util::post_inc;
41use gpui_util::{ResultExt, measure};
42use itertools::FoldWhile::{Continue, Done};
43use itertools::Itertools;
44#[cfg(any(target_os = "macos", target_os = "ios"))]
45use objc2_core_foundation::CFRetained;
46#[cfg(any(target_os = "macos", target_os = "ios"))]
47use objc2_core_video::CVPixelBuffer;
48use parking_lot::{RwLock, RwLockUpgradableReadGuard};
49use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
50use refineable::Refineable;
51use scheduler::Instant;
52use slotmap::SlotMap;
53use smallvec::SmallVec;
54use std::{
55 any::{Any, TypeId},
56 borrow::Cow,
57 cell::{Cell, RefCell},
58 cmp,
59 fmt::{Debug, Display},
60 hash::{Hash, Hasher},
61 marker::PhantomData,
62 mem,
63 ops::{Add, Div, Range, Sub},
64 rc::Rc,
65 sync::{
66 Arc, Weak,
67 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
68 },
69 thread::AccessError,
70 time::Duration,
71};
72use uuid::Uuid;
73
74pub(crate) mod a11y;
75mod prompts;
76
77pub use a11y::A11ySubtreeBuilder;
78
79use self::a11y::A11y;
80#[cfg(not(target_family = "wasm"))]
81use self::a11y::ROOT_NODE_ID;
82use crate::util::{
83 atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
84 round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
85};
86pub use prompts::*;
87
88pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
90
91pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
94 width: Pixels(900.),
95 height: Pixels(750.),
96};
97
98#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
100pub enum DispatchPhase {
101 #[default]
106 Bubble,
107 Capture,
113}
114
115impl DispatchPhase {
116 #[inline]
118 pub fn bubble(self) -> bool {
119 self == DispatchPhase::Bubble
120 }
121
122 #[inline]
124 pub fn capture(self) -> bool {
125 self == DispatchPhase::Capture
126 }
127}
128
129struct WindowInvalidatorInner {
130 #[cfg(feature = "profiler")]
131 pub window_id: WindowId,
132 pub dirty: bool,
133 pub draw_phase: DrawPhase,
134 pub dirty_views: FxHashSet<EntityId>,
135 pub update_count: usize,
136 #[cfg(feature = "profiler")]
137 pub frame_dirty: FrameDirtyAccumulator,
138 pub platform_waker: Option<Rc<dyn Fn()>>,
139}
140
141#[cfg(feature = "profiler")]
147#[derive(Default)]
148struct FrameDirtyAccumulator {
149 dirty_at: Option<Instant>,
150 invalidations: u64,
151}
152
153#[derive(Clone)]
154pub(crate) struct WindowInvalidator {
155 inner: Rc<RefCell<WindowInvalidatorInner>>,
156}
157
158impl WindowInvalidator {
159 pub fn new(#[allow(unused_variables)] window_id: WindowId) -> Self {
160 WindowInvalidator {
161 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
162 #[cfg(feature = "profiler")]
163 window_id,
164 dirty: true,
165 draw_phase: DrawPhase::None,
166 dirty_views: FxHashSet::default(),
167 update_count: 0,
168 #[cfg(feature = "profiler")]
169 frame_dirty: FrameDirtyAccumulator::default(),
170 platform_waker: None,
171 })),
172 }
173 }
174
175 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
176 let mut inner = self.inner.borrow_mut();
177 inner.update_count += 1;
178 inner.dirty_views.insert(entity);
179 if inner.draw_phase == DrawPhase::None {
180 #[cfg(feature = "profiler")]
181 let dirty_at = Self::record_frame_dirty(&mut inner);
182 let became_dirty = !inner.dirty;
183 inner.dirty = true;
184 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
185 #[cfg(feature = "profiler")]
186 let window_id = inner.window_id;
187 drop(inner);
188 #[cfg(feature = "profiler")]
189 if became_dirty {
190 profiler::journal::record_frame_pending(window_id, dirty_at);
191 }
192 cx.push_effect(Effect::Notify { emitter: entity });
193 if let Some(waker) = waker {
194 waker();
195 }
196 true
197 } else {
198 false
199 }
200 }
201
202 pub fn is_dirty(&self) -> bool {
203 self.inner.borrow().dirty
204 }
205
206 pub fn set_dirty(&self, dirty: bool) {
207 let mut inner = self.inner.borrow_mut();
208 let became_dirty = dirty && !inner.dirty;
209 inner.dirty = dirty;
210 if dirty {
211 inner.update_count += 1;
212 }
213 #[cfg(feature = "profiler")]
214 let dirty_at = dirty.then(|| Self::record_frame_dirty(&mut inner));
215 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
216 #[cfg(feature = "profiler")]
217 let window_id = inner.window_id;
218 drop(inner);
219 #[cfg(feature = "profiler")]
220 if became_dirty && let Some(dirty_at) = dirty_at {
221 profiler::journal::record_frame_pending(window_id, dirty_at);
222 }
223 if let Some(waker) = waker {
224 waker();
225 }
226 }
227
228 pub fn set_platform_waker(&self, waker: Option<Rc<dyn Fn()>>) {
229 let mut inner = self.inner.borrow_mut();
230 inner.platform_waker = waker;
231 let waker = inner.dirty.then(|| inner.platform_waker.clone()).flatten();
232 drop(inner);
233 if let Some(waker) = waker {
234 waker();
235 }
236 }
237
238 pub fn wake_platform(&self) {
242 let waker = self.inner.borrow().platform_waker.clone();
243 if let Some(waker) = waker {
244 waker();
245 }
246 }
247
248 pub fn set_phase(&self, phase: DrawPhase) {
249 self.inner.borrow_mut().draw_phase = phase
250 }
251
252 pub fn update_count(&self) -> usize {
253 self.inner.borrow().update_count
254 }
255
256 #[cfg(feature = "profiler")]
257 fn record_frame_dirty(inner: &mut WindowInvalidatorInner) -> Instant {
258 let dirty_at = *inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
259 inner.frame_dirty.invalidations += 1;
260 dirty_at
261 }
262
263 #[cfg(feature = "profiler")]
264 fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
265 mem::take(&mut self.inner.borrow_mut().frame_dirty)
266 }
267
268 pub fn take_views(&self) -> FxHashSet<EntityId> {
269 mem::take(&mut self.inner.borrow_mut().dirty_views)
270 }
271
272 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
273 self.inner.borrow_mut().dirty_views = views;
274 }
275
276 pub fn not_drawing(&self) -> bool {
277 self.inner.borrow().draw_phase == DrawPhase::None
278 }
279
280 pub fn is_painting(&self) -> bool {
282 self.inner.borrow().draw_phase == DrawPhase::Paint
283 }
284
285 #[track_caller]
286 pub fn debug_assert_paint(&self) {
287 debug_assert!(
288 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
289 "this method can only be called during paint"
290 );
291 }
292
293 #[track_caller]
294 pub fn debug_assert_prepaint(&self) {
295 debug_assert!(
296 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
297 "this method can only be called during request_layout, or prepaint"
298 );
299 }
300
301 #[track_caller]
302 pub fn debug_assert_paint_or_prepaint(&self) {
303 debug_assert!(
304 matches!(
305 self.inner.borrow().draw_phase,
306 DrawPhase::Paint | DrawPhase::Prepaint
307 ),
308 "this method can only be called during request_layout, prepaint, or paint"
309 );
310 }
311}
312
313type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
314
315pub(crate) type AnyWindowFocusListener =
316 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
317
318pub(crate) struct WindowFocusEvent {
319 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
320 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
321}
322
323impl WindowFocusEvent {
324 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
325 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
326 }
327
328 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
329 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
330 }
331}
332
333pub struct FocusOutEvent {
335 pub blurred: WeakFocusHandle,
337}
338
339slotmap::new_key_type! {
340 pub struct FocusId;
342}
343
344thread_local! {
345 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
348
349 static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
353}
354
355pub(crate) fn draw_in_progress() -> bool {
366 CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some())
367}
368
369#[derive(Clone, Copy, Debug, PartialEq, Eq)]
371pub enum FrameOutcome {
372 Drew,
374 NoDraw,
376 Throttled,
378}
379
380#[derive(Clone, Copy, Debug)]
382pub struct FrameWork {
383 pub window_id: WindowId,
385 pub started: Instant,
387 pub ended: Instant,
389 pub outcome: FrameOutcome,
391}
392
393static FRAME_OBSERVER: std::sync::OnceLock<fn(FrameWork)> = std::sync::OnceLock::new();
394
395pub fn observe_frames(observer: fn(FrameWork)) {
398 let _ = FRAME_OBSERVER.set(observer);
399}
400
401fn report_frame(window_id: WindowId, started: Instant, outcome: FrameOutcome) {
402 if let Some(observer) = FRAME_OBSERVER.get() {
403 observer(FrameWork { window_id, started, ended: Instant::now(), outcome });
404 }
405}
406
407#[inline(always)]
410pub(crate) fn with_element_arena<R>(callback: impl FnOnce(&mut Arena) -> R) -> R {
411 let mut callback = Some(callback);
412 let mut result = None;
413 let access = with_element_arena_erased(&mut |arena| {
414 result = Some(callback.take().expect("arena callback runs once")(arena));
415 });
416 drop(callback);
417 access.expect("cannot access a Thread Local Storage value during or after destruction");
418 result.expect("arena callback produces a result")
419}
420
421pub(crate) struct ElementArenaScope {
436 entered: *const RefCell<Arena>,
439 previous: Option<*const RefCell<Arena>>,
440 exited: bool,
441}
442
443impl ElementArenaScope {
444 pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
446 arena.borrow_mut().begin_scope();
447 let previous = CURRENT_ELEMENT_ARENA.with(|current| {
448 let prev = current.get();
449 current.set(Some(arena as *const RefCell<Arena>));
450 prev
451 });
452 Self {
453 entered: arena as *const RefCell<Arena>,
454 previous,
455 exited: false,
456 }
457 }
458
459 pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
468 assert!(
469 std::ptr::eq(self.entered, arena),
470 "ElementArenaScope::exit called with a different arena than was entered"
471 );
472 self.exited = true;
473 ArenaClearNeeded::new(arena)
478 }
479}
480
481impl Drop for ElementArenaScope {
482 fn drop(&mut self) {
483 CURRENT_ELEMENT_ARENA.with(|current| {
490 current.set(self.previous);
491 });
492 unsafe { &*self.entered }.borrow_mut().end_scope();
496 if !self.exited && !std::thread::panicking() {
497 debug_assert!(false, "ElementArenaScope dropped without calling exit()");
498 log::error!(
499 "ElementArenaScope dropped without calling exit(); \
500 the arena clear for this draw was never requested"
501 );
502 }
503 }
504}
505
506#[must_use]
508pub struct ArenaClearNeeded {
509 arena: *const RefCell<Arena>,
512}
513
514impl ArenaClearNeeded {
515 fn new(arena: &RefCell<Arena>) -> Self {
518 Self {
519 arena: arena as *const RefCell<Arena>,
520 }
521 }
522
523 pub fn clear(self, cx: &mut App) {
532 assert!(
533 std::ptr::eq(self.arena, &*cx.element_arena),
534 "ArenaClearNeeded::clear called with a different App than the draw ran against"
535 );
536 RefCell::borrow_mut(&cx.element_arena).clear();
537 }
538}
539
540#[derive(Default)]
541pub(crate) struct FocusMap {
542 pub(crate) handles: SlotMap<FocusId, FocusRef>,
543 pub(crate) dropped_handles: Vec<FocusId>,
544}
545
546pub(crate) struct FocusRef {
547 pub(crate) ref_count: AtomicUsize,
548 pub(crate) tab_index: isize,
549 pub(crate) tab_stop: bool,
550}
551
552impl FocusId {
553 pub fn is_focused(&self, window: &Window) -> bool {
555 window.focus == Some(*self)
556 }
557
558 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
561 window
562 .focused(cx)
563 .is_some_and(|focused| self.contains(focused.id, window))
564 }
565
566 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
569 let focused = window.focused(cx);
570 focused.is_some_and(|focused| focused.id.contains(*self, window))
571 }
572
573 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
575 window
576 .rendered_frame
577 .dispatch_tree
578 .focus_contains(*self, other)
579 }
580}
581
582pub struct FocusHandle {
584 pub(crate) id: FocusId,
585 handles: Arc<RwLock<FocusMap>>,
586 pub tab_index: isize,
588 pub tab_stop: bool,
590}
591
592impl std::fmt::Debug for FocusHandle {
593 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
594 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
595 }
596}
597
598impl FocusHandle {
599 pub(crate) fn new(handles: &Arc<RwLock<FocusMap>>) -> Self {
600 let id = handles.write().handles.insert(FocusRef {
601 ref_count: AtomicUsize::new(1),
602 tab_index: 0,
603 tab_stop: false,
604 });
605
606 Self {
607 id,
608 tab_index: 0,
609 tab_stop: false,
610 handles: handles.clone(),
611 }
612 }
613
614 pub(crate) fn for_id(id: FocusId, handles: &Arc<RwLock<FocusMap>>) -> Option<Self> {
615 let lock = handles.read();
616 let focus = lock.handles.get(id)?;
617 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
618 return None;
619 }
620 Some(Self {
621 id,
622 tab_index: focus.tab_index,
623 tab_stop: focus.tab_stop,
624 handles: handles.clone(),
625 })
626 }
627
628 pub fn tab_index(mut self, index: isize) -> Self {
630 self.tab_index = index;
631 if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
632 focus.tab_index = index;
633 }
634 self
635 }
636
637 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
641 self.tab_stop = tab_stop;
642 if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
643 focus.tab_stop = tab_stop;
644 }
645 self
646 }
647
648 pub fn downgrade(&self) -> WeakFocusHandle {
650 WeakFocusHandle {
651 id: self.id,
652 handles: Arc::downgrade(&self.handles),
653 }
654 }
655
656 pub fn focus(&self, window: &mut Window, cx: &mut App) {
658 window.focus(self, cx)
659 }
660
661 pub fn is_focused(&self, window: &Window) -> bool {
663 self.id.is_focused(window)
664 }
665
666 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
669 self.id.contains_focused(window, cx)
670 }
671
672 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
675 self.id.within_focused(window, cx)
676 }
677
678 pub fn contains(&self, other: &Self, window: &Window) -> bool {
680 self.id.contains(other.id, window)
681 }
682
683 pub fn is_rendered(&self, window: &Window) -> bool {
685 window
686 .rendered_frame
687 .dispatch_tree
688 .focusable_node_id(self.id)
689 .is_some()
690 }
691
692 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
694 if let Some(node_id) = window
695 .rendered_frame
696 .dispatch_tree
697 .focusable_node_id(self.id)
698 {
699 window.dispatch_action_on_node(node_id, action, cx)
700 }
701 }
702}
703
704impl Clone for FocusHandle {
705 fn clone(&self) -> Self {
706 Self::for_id(self.id, &self.handles).unwrap()
707 }
708}
709
710impl PartialEq for FocusHandle {
711 fn eq(&self, other: &Self) -> bool {
712 self.id == other.id
713 }
714}
715
716impl Eq for FocusHandle {}
717
718impl Drop for FocusHandle {
719 fn drop(&mut self) {
720 let handles = self.handles.upgradable_read();
721 let focus = handles.handles.get(self.id).expect("focus handle missing");
722 let previous_count = focus.ref_count.fetch_sub(1, SeqCst);
723 assert_ne!(previous_count, 0, "over-released focus handle");
724 if previous_count == 1 {
725 RwLockUpgradableReadGuard::upgrade(handles)
726 .dropped_handles
727 .push(self.id);
728 }
729 }
730}
731
732#[derive(Clone, Debug)]
734pub struct WeakFocusHandle {
735 pub(crate) id: FocusId,
736 pub(crate) handles: Weak<RwLock<FocusMap>>,
737}
738
739impl WeakFocusHandle {
740 pub fn upgrade(&self) -> Option<FocusHandle> {
742 let handles = self.handles.upgrade()?;
743 FocusHandle::for_id(self.id, &handles)
744 }
745}
746
747impl PartialEq for WeakFocusHandle {
748 fn eq(&self, other: &WeakFocusHandle) -> bool {
749 self.id == other.id
750 }
751}
752
753impl Eq for WeakFocusHandle {}
754
755impl PartialEq<FocusHandle> for WeakFocusHandle {
756 fn eq(&self, other: &FocusHandle) -> bool {
757 self.id == other.id
758 }
759}
760
761impl PartialEq<WeakFocusHandle> for FocusHandle {
762 fn eq(&self, other: &WeakFocusHandle) -> bool {
763 self.id == other.id
764 }
765}
766
767pub trait Focusable: 'static {
770 fn focus_handle(&self, cx: &App) -> FocusHandle;
772}
773
774impl<V: Focusable> Focusable for Entity<V> {
775 fn focus_handle(&self, cx: &App) -> FocusHandle {
776 self.read(cx).focus_handle(cx)
777 }
778}
779
780pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
783
784impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
785
786pub struct DismissEvent;
788
789type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
790
791pub(crate) type AnyMouseListener =
792 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
793
794#[derive(Clone)]
795pub(crate) struct CursorStyleRequest {
796 pub(crate) hitbox_id: Option<HitboxId>,
797 pub(crate) style: CursorStyle,
798}
799
800#[derive(Default, Eq, PartialEq)]
801pub(crate) struct HitTest {
802 pub(crate) ids: SmallVec<[HitboxId; 8]>,
803 pub(crate) hover_hitbox_count: usize,
804}
805
806#[derive(Clone, Copy, Debug, Eq, PartialEq)]
808pub enum WindowControlArea {
809 Drag,
811 Close,
813 Max,
815 Min,
817 NoDrag,
826}
827
828#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
830pub struct HitboxId(u64);
831
832#[cfg(feature = "test-support")]
833impl HitboxId {
834 pub const fn placeholder() -> Self {
839 Self(0)
840 }
841}
842
843impl HitboxId {
844 pub const VN_PICK: HitboxId = HitboxId(u64::MAX);
848
849 pub fn is_hovered(self, window: &Window) -> bool {
856 if window.captured_hitbox == Some(self) {
858 return true;
859 }
860 if window.last_input_was_keyboard() {
861 return false;
862 }
863 self.hit_test(window)
864 }
865
866 pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
871 if window.captured_hitbox == Some(self) {
873 return true;
874 }
875 self.hit_test(window)
876 }
877
878 fn hit_test(self, window: &Window) -> bool {
879 if !window.pointer_inside {
884 return false;
885 }
886 let hit_test = &window.mouse_hit_test;
887 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
888 if self == *id {
889 return true;
890 }
891 }
892 false
893 }
894
895 pub fn should_handle_scroll(self, window: &Window) -> bool {
900 window.mouse_hit_test.ids.contains(&self)
901 }
902
903 fn next(self) -> HitboxId {
904 HitboxId(self.0.wrapping_add(1))
905 }
906}
907
908#[inline]
916fn transform_bounds(
917 matrix: TransformationMatrix,
918 bounds: Bounds<Pixels>,
919 scale_factor: f32,
920) -> Bounds<Pixels> {
921 if matrix.is_unit() {
922 return bounds;
923 }
924 let map = |p: Point<Pixels>| {
928 let d = matrix.apply(Point::new(px(p.x.0 * scale_factor), px(p.y.0 * scale_factor)));
929 Point::new(px(d.x.0 / scale_factor), px(d.y.0 / scale_factor))
930 };
931 let corners = [
932 map(bounds.origin),
933 map(bounds.top_right()),
934 map(bounds.bottom_left()),
935 map(bounds.bottom_right()),
936 ];
937 let min_x = corners.iter().map(|p| p.x).fold(Pixels::MAX, Pixels::min);
938 let max_x = corners.iter().map(|p| p.x).fold(Pixels::MIN, Pixels::max);
939 let min_y = corners.iter().map(|p| p.y).fold(Pixels::MAX, Pixels::min);
940 let max_y = corners.iter().map(|p| p.y).fold(Pixels::MIN, Pixels::max);
941 Bounds::from_corners(Point::new(min_x, min_y), Point::new(max_x, max_y))
942}
943
944fn vn_history_key(element: u64, spec: &EffectSpec) -> u64 {
951 use std::hash::{Hash, Hasher};
952 if element == 0 || spec.flags & crate::EFFECT_FLAG_HISTORY == 0 {
953 return 0;
954 }
955 let mut hasher = collections::FxHasher::default();
956 (element, spec.id).hash(&mut hasher);
957 hasher.finish().max(1)
958}
959
960#[derive(Clone, Copy, Debug, PartialEq)]
965struct VnEffectPhase {
966 at: f32,
967 phase: f64,
968}
969
970impl VnEffectPhase {
971 const KEEP: f32 = 10.;
973
974 fn advance(previous: Option<Self>, speed: f32, now: f32) -> Self {
975 match previous {
976 None => Self {
977 at: now,
978 phase: f64::from(speed) * f64::from(now),
979 },
980 Some(previous) if now > previous.at => Self {
981 at: now,
982 phase: previous.phase + f64::from(speed) * f64::from(now - previous.at),
983 },
984 Some(previous) => previous,
985 }
986 }
987
988 fn speed(&self, now: f32) -> Option<f32> {
991 (now > 1e-3).then(|| (self.phase / f64::from(now)) as f32)
992 }
993}
994
995fn vn_phase_key(element: u64, spec: &EffectSpec) -> u64 {
996 use std::hash::{Hash, Hasher};
997 let mut hasher = collections::FxHasher::default();
998 (element, spec.id, "phase").hash(&mut hasher);
999 hasher.finish()
1000}
1001
1002fn transform_mask(
1003 matrix: TransformationMatrix,
1004 mask: ContentMask<Pixels>,
1005 scale_factor: f32,
1006) -> ContentMask<Pixels> {
1007 let bounds = transform_bounds(matrix, mask.bounds, scale_factor);
1008 if !mask.is_rounded() || matrix.is_unit() {
1009 return ContentMask {
1010 bounds,
1011 corner_radii: mask.corner_radii,
1012 };
1013 }
1014 let [[a, b], [c, d]] = matrix.rotation_scale;
1015 let corner_radii = if b == 0. && c == 0. && a > 0. && d > 0. {
1016 let factor = a.min(d);
1017 mask.corner_radii
1018 .map(|radius| *radius * factor)
1019 .clamp_radii_for_quad_size(bounds.size)
1020 } else {
1021 Corners::default()
1022 };
1023 ContentMask {
1024 bounds,
1025 corner_radii,
1026 }
1027}
1028
1029#[derive(Clone, Debug)]
1032pub struct Hitbox {
1033 pub id: HitboxId,
1035 pub bounds: Bounds<Pixels>,
1037 pub content_mask: ContentMask<Pixels>,
1039 pub behavior: HitboxBehavior,
1041 pub transformation: TransformationMatrix,
1050 pub vn_clip: Option<Arc<crate::VnClipNode>>,
1054}
1055
1056impl_deref!([] Hitbox => bounds: Bounds<Pixels>);
1057
1058impl Hitbox {
1059 pub fn is_hovered(&self, window: &Window) -> bool {
1076 self.id.is_hovered(window)
1077 }
1078
1079 pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
1082 let hit_test = window
1085 .rendered_frame
1086 .hit_test(position, window.scale_factor);
1087 hit_test
1088 .ids
1089 .iter()
1090 .take(hit_test.hover_hitbox_count)
1091 .any(|id| self.id == *id)
1092 }
1093
1094 pub fn should_handle_scroll(&self, window: &Window) -> bool {
1101 self.id.should_handle_scroll(window)
1102 }
1103}
1104
1105pub const VN_TAG_PASSIVE: u32 = 1 << 31;
1111
1112#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1114pub enum VnHitKind {
1115 Down,
1117 Up,
1119 Scroll,
1121}
1122
1123pub type VnHitRefiner = Rc<dyn Fn(VnHitKind, Point<Pixels>, &mut Window, &mut App)>;
1127
1128#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1130pub enum VnPointerLock {
1131 System {
1133 unadjusted: bool,
1135 },
1136 Simulated,
1139}
1140
1141#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1143pub enum HitboxBehavior {
1144 #[default]
1146 Normal,
1147
1148 BlockMouse,
1170
1171 BlockMouseExceptScroll,
1198}
1199
1200#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
1202pub struct TooltipId(usize);
1203
1204impl TooltipId {
1205 pub fn is_hovered(&self, window: &Window) -> bool {
1207 window
1208 .tooltip_bounds
1209 .as_ref()
1210 .is_some_and(|tooltip_bounds| {
1211 tooltip_bounds.id == *self
1212 && tooltip_bounds.bounds.contains(&window.mouse_position())
1213 })
1214 }
1215}
1216
1217pub(crate) struct TooltipBounds {
1218 id: TooltipId,
1219 bounds: Bounds<Pixels>,
1220}
1221
1222#[derive(Clone)]
1223pub(crate) struct TooltipRequest {
1224 id: TooltipId,
1225 tooltip: AnyTooltip,
1226}
1227
1228#[derive(Clone, Default)]
1234pub(crate) struct ElementIdStack {
1235 ids: SmallVec<[ElementId; 32]>,
1236 hashes: SmallVec<[u64; 32]>,
1237}
1238
1239impl ElementIdStack {
1240 pub(crate) fn push(&mut self, id: ElementId) {
1241 self.hashes.push(crate::extend_path_hash(self.hash(), &id));
1242 self.ids.push(id);
1243 }
1244
1245 pub(crate) fn pop(&mut self) -> Option<ElementId> {
1246 self.hashes.pop();
1247 self.ids.pop()
1248 }
1249
1250 pub(crate) fn clear(&mut self) {
1251 self.ids.clear();
1252 self.hashes.clear();
1253 }
1254
1255 fn hash(&self) -> u64 {
1257 self.hashes
1258 .last()
1259 .copied()
1260 .unwrap_or(crate::EMPTY_PATH_HASH)
1261 }
1262
1263 pub(crate) fn global_id(&self) -> GlobalElementId {
1264 GlobalElementId::with_hash(&self.ids, self.hash())
1265 }
1266}
1267
1268impl std::ops::Deref for ElementIdStack {
1269 type Target = [ElementId];
1270
1271 fn deref(&self) -> &Self::Target {
1272 &self.ids
1273 }
1274}
1275
1276pub(crate) struct DeferredDraw {
1277 current_view: EntityId,
1278 priority: usize,
1279 parent_node: DispatchNodeId,
1280 element_id_stack: ElementIdStack,
1281 text_style_stack: Vec<TextStyleRefinement>,
1282 content_mask: Option<ContentMask<Pixels>>,
1283 rem_size: Pixels,
1284 element: Option<AnyElement>,
1285 absolute_offset: Point<Pixels>,
1286 element_transform: TransformationMatrix,
1295 a11y_parent: Option<accesskit::NodeId>,
1299 vn_stack: Option<Rc<[u128]>>,
1303 element_opacity: f32,
1308 vn_clip: Option<Arc<crate::VnClipNode>>,
1313 vn_scope: Option<VnDeferScope>,
1316 prepaint_range: Range<PrepaintStateIndex>,
1317 paint_range: Range<PaintIndex>,
1318 accessed_entities: FxHashSet<EntityId>,
1321}
1322
1323#[derive(Clone, Debug)]
1330pub(crate) struct VnDeferScope {
1331 id: u64,
1332 clip: Option<Arc<crate::VnClipNode>>,
1333}
1334
1335pub(crate) fn vn_element_key(id: Option<&GlobalElementId>) -> u64 {
1339 use std::hash::{Hash, Hasher};
1340 id.map_or(0, |id| {
1341 let mut hasher = collections::FxHasher::default();
1342 for id in id.iter() {
1343 if !matches!(id, ElementId::View(_)) {
1344 id.hash(&mut hasher);
1345 }
1346 }
1347 hasher.finish().max(1)
1348 })
1349}
1350
1351impl DeferredDraw {
1352 fn order(&self) -> (usize, Option<&[u128]>) {
1354 (self.priority, self.vn_stack.as_deref())
1355 }
1356}
1357
1358pub(crate) struct Frame {
1359 pub(crate) focus: Option<FocusId>,
1360 pub(crate) window_active: bool,
1361 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
1362 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
1363 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
1364 pub(crate) dispatch_tree: DispatchTree,
1365 pub(crate) scene: Scene,
1366 pub(crate) hitboxes: Vec<Hitbox>,
1367 pub(crate) vn_tagged_hitboxes: Vec<(u32, Hitbox)>,
1377 pub(crate) vn_hit_order: Vec<u32>,
1386 pub(crate) vn_deferred_tagged: Range<usize>,
1391 vn_tagged_order: std::cell::OnceCell<Option<Vec<u32>>>,
1394 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
1395 pub(crate) deferred_draws: Vec<DeferredDraw>,
1396 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
1397 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
1398 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
1399 #[cfg(any(test, feature = "test-support"))]
1400 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
1401 #[cfg(any(test, feature = "test-support"))]
1402 debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
1403 #[cfg(any(feature = "inspector", debug_assertions))]
1404 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
1405 #[cfg(any(feature = "inspector", debug_assertions))]
1406 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
1407 pub(crate) tab_stops: TabStopMap,
1408}
1409
1410#[derive(Clone, Default)]
1411pub(crate) struct PrepaintStateIndex {
1412 hitboxes_index: usize,
1413 vn_tagged_hitboxes_index: usize,
1417 tooltips_index: usize,
1418 deferred_draws_index: usize,
1419 dispatch_tree_index: usize,
1420 accessed_element_states_index: usize,
1421 line_layout_index: LineLayoutIndex,
1422}
1423
1424#[derive(Clone, Default)]
1425pub(crate) struct PaintIndex {
1426 scene_index: usize,
1427 #[cfg(any(test, feature = "test-support"))]
1428 debug_bounds_index: usize,
1429 mouse_listeners_index: usize,
1430 input_handlers_index: usize,
1431 cursor_styles_index: usize,
1432 window_control_hitboxes_index: usize,
1433 accessed_element_states_index: usize,
1434 tab_handle_index: usize,
1435 line_layout_index: LineLayoutIndex,
1436}
1437
1438impl Frame {
1439 #[cfg(any(test, feature = "test-support"))]
1440 pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) {
1441 self.debug_bounds.insert(selector.clone(), bounds);
1442 self.debug_bounds_records.push((selector, bounds));
1443 }
1444
1445 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
1446 Frame {
1447 focus: None,
1448 window_active: false,
1449 element_states: FxHashMap::default(),
1450 accessed_element_states: Vec::new(),
1451 mouse_listeners: Vec::new(),
1452 dispatch_tree,
1453 scene: Scene::default(),
1454 hitboxes: Vec::new(),
1455 vn_tagged_hitboxes: Vec::new(),
1456 vn_hit_order: Vec::new(),
1457 vn_deferred_tagged: 0..0,
1458 vn_tagged_order: std::cell::OnceCell::new(),
1459 window_control_hitboxes: Vec::new(),
1460 deferred_draws: Vec::new(),
1461 input_handlers: Vec::new(),
1462 tooltip_requests: Vec::new(),
1463 cursor_styles: Vec::new(),
1464
1465 #[cfg(any(test, feature = "test-support"))]
1466 debug_bounds: FxHashMap::default(),
1467 #[cfg(any(test, feature = "test-support"))]
1468 debug_bounds_records: Vec::new(),
1469
1470 #[cfg(any(feature = "inspector", debug_assertions))]
1471 next_inspector_instance_ids: FxHashMap::default(),
1472
1473 #[cfg(any(feature = "inspector", debug_assertions))]
1474 inspector_hitboxes: FxHashMap::default(),
1475 tab_stops: TabStopMap::default(),
1476 }
1477 }
1478
1479 pub(crate) fn clear(&mut self) {
1480 self.element_states.clear();
1481 self.accessed_element_states.clear();
1482 self.mouse_listeners.clear();
1483 self.dispatch_tree.clear();
1484 self.scene.clear();
1485 self.input_handlers.clear();
1486 self.tooltip_requests.clear();
1487 self.cursor_styles.clear();
1488 self.hitboxes.clear();
1489 self.vn_tagged_hitboxes.clear();
1490 self.vn_hit_order.clear();
1491 self.vn_deferred_tagged = 0..0;
1492 self.vn_tagged_order = std::cell::OnceCell::new();
1493 self.window_control_hitboxes.clear();
1494 self.deferred_draws.clear();
1495 self.tab_stops.clear();
1496 self.focus = None;
1497
1498 #[cfg(any(test, feature = "test-support"))]
1499 {
1500 self.debug_bounds.clear();
1501 self.debug_bounds_records.clear();
1502 }
1503
1504 #[cfg(any(feature = "inspector", debug_assertions))]
1505 {
1506 self.next_inspector_instance_ids.clear();
1507 self.inspector_hitboxes.clear();
1508 }
1509 }
1510
1511 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1512 self.cursor_styles
1513 .iter()
1514 .rev()
1515 .fold_while(None, |style, request| match request.hitbox_id {
1516 None => Done(Some(request.style)),
1517 Some(hitbox_id) => Continue(style.or_else(|| {
1518 hitbox_id
1519 .is_hovered_ignoring_last_input(window)
1520 .then_some(request.style)
1521 })),
1522 })
1523 .into_inner()
1524 }
1525
1526 fn box_contains(hitbox: &Hitbox, position: Point<Pixels>, scale_factor: f32) -> bool {
1528 let local = if hitbox.transformation.is_unit() {
1542 position
1543 } else {
1544 match hitbox.transformation.inverse() {
1545 Some(inverse) => {
1546 let d = inverse.apply(Point::new(
1547 px(position.x.0 * scale_factor),
1548 px(position.y.0 * scale_factor),
1549 ));
1550 Point::new(px(d.x.0 / scale_factor), px(d.y.0 / scale_factor))
1551 }
1552 None => return false,
1553 }
1554 };
1555 hitbox.content_mask.contains(&position)
1564 && hitbox.bounds.contains(&local)
1565 && hitbox.vn_clip.as_ref().is_none_or(|clip| {
1568 clip.contains([position.x.0 * scale_factor, position.y.0 * scale_factor])
1569 })
1570 }
1571
1572 fn vn_tagged_paint_order(&self) -> Option<&[u32]> {
1579 self.vn_tagged_order
1580 .get_or_init(|| {
1581 let deferred = self.vn_deferred_tagged.clone();
1582 if deferred.is_empty() {
1583 return None;
1584 }
1585 let len = self.vn_tagged_hitboxes.len();
1586 let mut order: Vec<u32> = Vec::with_capacity(len);
1587 order.extend(0..deferred.start as u32);
1588 let draws = &self.deferred_draws;
1589 let mut traversal = (0..draws.len()).collect::<Vec<_>>();
1590 traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
1591 for ix in traversal {
1592 let range = &draws[ix].prepaint_range;
1593 let (start, end) = (
1594 range.start.vn_tagged_hitboxes_index,
1595 range.end.vn_tagged_hitboxes_index,
1596 );
1597 if start >= deferred.start && end <= deferred.end && start < end {
1598 order.extend(start as u32..end as u32);
1599 }
1600 }
1601 order.extend(deferred.end as u32..len as u32);
1602 (order.len() == len).then_some(order)
1605 })
1606 .as_deref()
1607 }
1608
1609 fn topmost_hitboxes(&self) -> impl Iterator<Item = &Hitbox> {
1612 let in_paint_order = self.vn_hit_order.len() == self.hitboxes.len();
1613 (0..self.hitboxes.len()).rev().map(move |index| {
1614 let index = if in_paint_order { self.vn_hit_order[index] as usize } else { index };
1615 &self.hitboxes[index]
1616 })
1617 }
1618
1619 pub(crate) fn hit_test(&self, position: Point<Pixels>, scale_factor: f32) -> HitTest {
1620 let mut set_hover_hitbox_count = false;
1621 let mut hit_test = HitTest::default();
1622 for hitbox in self.topmost_hitboxes() {
1623 if Self::box_contains(hitbox, position, scale_factor) {
1624 hit_test.ids.push(hitbox.id);
1625 if !set_hover_hitbox_count
1626 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1627 {
1628 hit_test.hover_hitbox_count = hit_test.ids.len();
1629 set_hover_hitbox_count = true;
1630 }
1631 if hitbox.behavior == HitboxBehavior::BlockMouse {
1632 break;
1633 }
1634 }
1635 }
1636 if !set_hover_hitbox_count {
1637 hit_test.hover_hitbox_count = hit_test.ids.len();
1638 }
1639 hit_test
1640 }
1641
1642 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1643 self.focus
1644 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1645 .unwrap_or_default()
1646 }
1647
1648 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1649 for element_state_key in &self.accessed_element_states {
1650 if let Some((element_state_key, element_state)) =
1651 prev_frame.element_states.remove_entry(element_state_key)
1652 {
1653 self.element_states.insert(element_state_key, element_state);
1654 }
1655 }
1656
1657 self.scene.finish();
1658 }
1659}
1660
1661#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1662enum InputModality {
1663 Mouse,
1664 Keyboard,
1665 Touch,
1666}
1667
1668struct VnEffectPointer {
1671 moved: f32,
1674 entered: f32,
1675 left: f32,
1676 views: FxHashSet<EntityId>,
1678}
1679
1680impl VnEffectPointer {
1681 const NEVER: f32 = -1.0e4;
1683
1684 fn new(inside: bool) -> Self {
1685 let (entered, left) = if inside {
1686 (Self::NEVER, Self::NEVER - 1.)
1687 } else {
1688 (Self::NEVER - 1., Self::NEVER)
1689 };
1690 Self {
1691 moved: Self::NEVER,
1692 entered,
1693 left,
1694 views: FxHashSet::default(),
1695 }
1696 }
1697
1698 fn update(&mut self, was_inside: bool, inside: bool, moved: bool, cx: &mut App) {
1699 if was_inside == inside && !moved {
1700 return;
1701 }
1702 let now = crate::effect_clock_seconds();
1703 if moved {
1704 self.moved = now;
1705 }
1706 if inside && !was_inside {
1707 self.entered = now;
1708 } else if was_inside && !inside {
1709 self.left = now;
1710 }
1711 for view in self.views.drain() {
1712 cx.notify(view);
1713 }
1714 }
1715}
1716
1717pub struct Window {
1719 pub(crate) handle: AnyWindowHandle,
1720 pub(crate) invalidator: WindowInvalidator,
1721 pub(crate) removed: bool,
1722 pub(crate) platform_window: Box<dyn PlatformWindow>,
1723 pub(crate) display_id: Option<DisplayId>,
1724 pub(crate) display_observers: SingleSubscriberSet<AnyObserver>,
1725 is_resizable: bool,
1726 is_minimizable: bool,
1727 last_window_bounds: WindowBounds,
1728 sprite_atlas: Arc<dyn PlatformAtlas>,
1729 text_system: Rc<WindowTextSystem>,
1730 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1731 rem_size: Pixels,
1732 rem_size_override_stack: SmallVec<[Pixels; 8]>,
1737 pub(crate) viewport_size: Size<Pixels>,
1738 layout_engine: Option<TaffyLayoutEngine>,
1739 pub(crate) root: Option<AnyView>,
1740 pub(crate) element_id_stack: ElementIdStack,
1741 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1742 pub(crate) rendered_entity_stack: Vec<EntityId>,
1743 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1744 pub(crate) element_opacity: f32,
1745 element_image_tint: Hsla,
1748 pub(crate) element_transform: TransformationMatrix,
1756 vn_hitbox_tag: u32,
1760 vn_tag_fresh: bool,
1764 vn_tag_transform: Option<TransformationMatrix>,
1767 vn_tag_every_hitbox: bool,
1772 vn_pick_every_box: bool,
1775 vn_hit_refiner: Option<VnHitRefiner>,
1777 input_interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
1779 vn_key_event_seq: u64,
1781 vn_pointer_lock: Option<(VnPointerLock, Point<Pixels>)>,
1783 vn_raw_mouse_position: Option<Point<Pixels>>,
1785 vn_mouse_movement: Point<Pixels>,
1787 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1788 pub(crate) vn_clip_stack: Option<Arc<crate::VnClipNode>>,
1792 vn_capture_records: FxHashMap<u64, (crate::VnCaptureInfo, Bounds<ScaledPixels>)>,
1795 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1796 last_text_input_configuration: Option<TextInputConfiguration>,
1800 focused_text_input: Option<FocusId>,
1801 pub(crate) image_cache_stack: Vec<AnyImageCache>,
1802 pub(crate) rendered_frame: Frame,
1803 pub(crate) next_frame: Frame,
1804 next_hitbox_id: HitboxId,
1805 pub(crate) next_tooltip_id: TooltipId,
1806 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1807 pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1808 pub(crate) next_frame_wanted: Rc<Cell<bool>>,
1811 pub(crate) dirty_views: FxHashSet<EntityId>,
1812 focus_listeners: SingleSubscriberSet<AnyWindowFocusListener>,
1813 pub(crate) focus_lost_listeners: SingleSubscriberSet<AnyObserver>,
1814 focus_lost_path: SmallVec<[FocusId; 8]>,
1815 default_prevented: bool,
1816 mouse_position: Point<Pixels>,
1817 mouse_hit_test: HitTest,
1818 modifiers: Modifiers,
1819 capslock: Capslock,
1820 scale_factor: f32,
1821 pub(crate) bounds_observers: SingleSubscriberSet<AnyObserver>,
1822 appearance: WindowAppearance,
1823 pub(crate) appearance_observers: SingleSubscriberSet<AnyObserver>,
1824 pub(crate) button_layout_observers: SingleSubscriberSet<AnyObserver>,
1825 active: Rc<Cell<bool>>,
1826 assume_active: bool,
1828 visibility: WindowVisibility,
1829 pub(crate) visibility_observers:
1830 SingleSubscriberSet<Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
1831 hovered: Rc<Cell<bool>>,
1832 pointer_inside: bool,
1846 vn_effect_pointer: VnEffectPointer,
1847 vn_effect_element: u64,
1850 vn_effect_phases: FxHashMap<u64, VnEffectPhase>,
1853 vn_defer_scope: Option<VnDeferScope>,
1856 vn_scopes_painted: FxHashSet<u64>,
1859 pub(crate) needs_present: Rc<Cell<bool>>,
1860 scene_animation_interval: Rc<Cell<Option<Duration>>>,
1863 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1866 #[cfg(feature = "profiler")]
1867 pub(crate) window_profiler: profiler::WindowProfiler,
1868 last_input_modality: InputModality,
1869 touch_gestures: TouchGestureRecognizer,
1870 touch_prediction_enabled: bool,
1871 long_press_timer: Option<Task<()>>,
1872 long_press_capture: Option<EntityId>,
1873 pub(crate) refreshing: bool,
1874 pub(crate) activation_observers: SingleSubscriberSet<AnyObserver>,
1875 pub(crate) focus: Option<FocusId>,
1876 focus_enabled: bool,
1877 pub(crate) focus_generation: u64,
1880 pending_input: Option<PendingInput>,
1881 pending_modifier: ModifierState,
1882 pub(crate) pending_input_observers: SingleSubscriberSet<AnyObserver>,
1883 prompt: Option<RenderablePromptHandle>,
1884 pub(crate) client_inset: Option<Pixels>,
1885 captured_hitbox: Option<HitboxId>,
1888 #[cfg(any(feature = "inspector", debug_assertions))]
1889 inspector: Option<Entity<Inspector>>,
1890 #[cfg(feature = "profiler")]
1891 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1892 pub(crate) a11y: A11y,
1893}
1894
1895#[derive(Clone, Debug, Default)]
1896struct ModifierState {
1897 modifiers: Modifiers,
1898 saw_other_input: bool,
1899}
1900
1901#[derive(Clone, Debug)]
1904pub(crate) struct InputRateTracker {
1905 timestamps: Vec<Instant>,
1906 window: Duration,
1907 inputs_per_second: u32,
1908 sustain_until: Instant,
1909 sustain_duration: Duration,
1910}
1911
1912const FRAME_INTERVAL_TOLERANCE: Duration = Duration::from_millis(1);
1913
1914#[derive(Default)]
1916struct FramePacer {
1917 last_frame: Option<Instant>,
1918}
1919
1920impl FramePacer {
1921 fn should_defer(&mut self, now: Instant, minimum_interval: Option<Duration>) -> bool {
1922 if let Some(interval) = minimum_interval
1923 && let Some(last_frame) = self.last_frame
1924 {
1925 let deadline = last_frame + interval;
1926 if now + FRAME_INTERVAL_TOLERANCE < deadline {
1927 return true;
1928 }
1929 self.last_frame = Some(if now.saturating_duration_since(deadline) <= interval / 4 {
1933 deadline
1934 } else {
1935 now
1936 });
1937 } else {
1938 self.last_frame = Some(now);
1939 }
1940 false
1941 }
1942}
1943
1944fn minimum_frame_interval(
1945 should_throttle: bool,
1946 inactive_without_high_rate_input: bool,
1947 inactive_frame_interval: Option<Duration>,
1948 low_power_frame_interval: Option<Duration>,
1949 thermal_frame_interval: Option<Duration>,
1950 thermal_state: ThermalState,
1951 power_mode: crate::PowerMode,
1952) -> Option<Duration> {
1953 if !should_throttle {
1954 return None;
1955 }
1956
1957 [
1958 inactive_frame_interval.filter(|_| inactive_without_high_rate_input),
1959 low_power_frame_interval.filter(|_| power_mode == crate::PowerMode::LowPower),
1960 thermal_frame_interval.filter(|_| {
1961 matches!(
1962 thermal_state,
1963 ThermalState::Critical | ThermalState::Serious
1964 )
1965 }),
1966 ]
1967 .into_iter()
1968 .flatten()
1969 .max()
1970}
1971
1972impl Default for InputRateTracker {
1973 fn default() -> Self {
1974 Self {
1975 timestamps: Vec::new(),
1976 window: Duration::from_millis(100),
1977 inputs_per_second: 60,
1978 sustain_until: Instant::now(),
1979 sustain_duration: Duration::from_secs(1),
1980 }
1981 }
1982}
1983
1984impl InputRateTracker {
1985 pub fn record_input(&mut self) {
1986 let now = Instant::now();
1987 self.timestamps.push(now);
1988 self.prune_old_timestamps(now);
1989
1990 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1991 if self.timestamps.len() as u128 >= min_events {
1992 self.sustain_until = now + self.sustain_duration;
1993 }
1994 }
1995
1996 pub fn is_high_rate(&self) -> bool {
1997 Instant::now() < self.sustain_until
1998 }
1999
2000 fn prune_old_timestamps(&mut self, now: Instant) {
2001 self.timestamps
2002 .retain(|&t| now.duration_since(t) <= self.window);
2003 }
2004}
2005
2006#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2007pub(crate) enum DrawPhase {
2008 None,
2009 Prepaint,
2010 Paint,
2011 Focus,
2012}
2013
2014pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
2015
2016pub struct PendingInputStatus<'a> {
2018 keystrokes: &'a [Keystroke],
2019 timeout: Option<PendingInputTimeoutStatus>,
2020}
2021
2022impl<'a> PendingInputStatus<'a> {
2023 pub fn keystrokes(&self) -> &'a [Keystroke] {
2025 self.keystrokes
2026 }
2027
2028 pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
2030 self.timeout
2031 }
2032}
2033
2034#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2036pub struct PendingInputTimeoutStatus {
2037 duration: Duration,
2038 remaining: Duration,
2039 started_at: Option<Instant>,
2040 paused: bool,
2041}
2042
2043impl PendingInputTimeoutStatus {
2044 pub fn duration(&self) -> Duration {
2046 self.duration
2047 }
2048
2049 pub fn remaining(&self, cx: &App) -> Duration {
2051 self.started_at
2052 .map(|started_at| {
2053 self.remaining
2054 .saturating_sub(cx.background_executor().now() - started_at)
2055 })
2056 .unwrap_or(self.remaining)
2057 }
2058
2059 pub fn is_paused(&self) -> bool {
2061 self.paused
2062 }
2063}
2064
2065#[derive(Debug)]
2066struct PendingInputTimeout {
2067 duration: Duration,
2068 remaining: Duration,
2069 state: PendingInputTimeoutState,
2070}
2071
2072#[derive(Debug)]
2073enum PendingInputTimeoutState {
2074 Running { started_at: Instant, task: Task<()> },
2075 Paused { pause: PendingInputTimeoutPause },
2076}
2077
2078#[derive(Debug)]
2079struct PendingInputTimeoutPause {
2080 owner_id: EntityId,
2081 _release_subscription: Subscription,
2082}
2083
2084impl PendingInputTimeout {
2085 fn is_paused(&self) -> bool {
2086 matches!(&self.state, PendingInputTimeoutState::Paused { .. })
2087 }
2088
2089 fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
2090 match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
2091 PendingInputTimeoutState::Running { started_at, task } => {
2092 self.remaining = self.remaining.saturating_sub(now - started_at);
2093 drop(task);
2094 true
2095 }
2096 previous_state @ PendingInputTimeoutState::Paused { .. } => {
2097 self.state = previous_state;
2098 false
2099 }
2100 }
2101 }
2102
2103 fn pause_owner_id(&self) -> Option<EntityId> {
2104 match &self.state {
2105 PendingInputTimeoutState::Running { .. } => None,
2106 PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
2107 }
2108 }
2109
2110 fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
2111 match std::mem::replace(
2112 &mut self.state,
2113 PendingInputTimeoutState::Running { started_at, task },
2114 ) {
2115 PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
2116 previous_state => {
2117 self.state = previous_state;
2118 false
2119 }
2120 }
2121 }
2122
2123 fn reset_duration(&mut self, duration: Duration) {
2124 self.duration = duration;
2125 self.remaining = duration;
2126 }
2127
2128 fn status(&self) -> PendingInputTimeoutStatus {
2129 let (started_at, paused) = match &self.state {
2130 PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
2131 PendingInputTimeoutState::Paused { .. } => (None, true),
2132 };
2133 PendingInputTimeoutStatus {
2134 duration: self.duration,
2135 remaining: self.remaining,
2136 started_at,
2137 paused,
2138 }
2139 }
2140}
2141
2142#[derive(Default, Debug)]
2143struct PendingInput {
2144 keystrokes: SmallVec<[Keystroke; 1]>,
2145 focus: Option<FocusId>,
2146 timeout: Option<PendingInputTimeout>,
2147}
2148
2149pub(crate) struct ElementStateBox {
2150 pub(crate) inner: Box<dyn Any>,
2151 #[cfg(debug_assertions)]
2152 pub(crate) type_name: &'static str,
2153}
2154
2155fn default_bounds(
2156 active_window_bounds: Option<WindowBounds>,
2157 display: Option<&dyn PlatformDisplay>,
2158) -> WindowBounds {
2159 const CASCADE_OFFSET: f32 = 25.0;
2160
2161 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
2162
2163 let display_bounds = display
2165 .map(|d| d.visible_bounds())
2166 .unwrap_or_else(default_placement);
2167
2168 let (
2169 Bounds {
2170 origin: base_origin,
2171 size: base_size,
2172 },
2173 window_bounds_ctor,
2174 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
2175 Some(bounds) => match bounds {
2176 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
2177 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
2178 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
2179 },
2180 None => (
2181 display
2182 .map(|d| d.default_bounds())
2183 .unwrap_or_else(default_placement),
2184 WindowBounds::Windowed,
2185 ),
2186 };
2187
2188 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
2189 let proposed_origin = base_origin + cascade_offset;
2190 let proposed_bounds = Bounds::new(proposed_origin, base_size);
2191
2192 let display_right = display_bounds.origin.x + display_bounds.size.width;
2193 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
2194 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
2195 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
2196
2197 let fits_horizontally = window_right <= display_right;
2198 let fits_vertically = window_bottom <= display_bottom;
2199
2200 let final_origin = match (fits_horizontally, fits_vertically) {
2201 (true, true) => proposed_origin,
2202 (false, true) => point(display_bounds.origin.x, base_origin.y),
2203 (true, false) => point(base_origin.x, display_bounds.origin.y),
2204 (false, false) => display_bounds.origin,
2205 };
2206 window_bounds_ctor(Bounds::new(final_origin, base_size))
2207}
2208
2209impl Window {
2210 pub(crate) fn new(
2211 handle: AnyWindowHandle,
2212 options: WindowOptions,
2213 cx: &mut App,
2214 ) -> Result<Self> {
2215 let WindowOptions {
2216 window_bounds,
2217 titlebar,
2218 focus,
2219 show,
2220 kind,
2221 is_movable,
2222 app_owns_titlebar_drag,
2223 inactive_frame_interval,
2224 low_power_frame_interval,
2225 thermal_frame_interval,
2226 is_resizable,
2227 is_minimizable,
2228 display_id,
2229 window_background,
2230 app_id,
2231 window_min_size,
2232 window_decorations,
2233 #[cfg_attr(
2234 not(any(target_os = "linux", target_os = "freebsd")),
2235 allow(unused_variables)
2236 )]
2237 icon,
2238 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
2239 tabbing_identifier,
2240 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
2241 use_display_p3,
2242 } = options;
2243
2244 let initial_window_title = titlebar
2245 .as_ref()
2246 .and_then(|titlebar| titlebar.title.clone());
2247
2248 let active_window_placement = cx.active_window_placement();
2249 let target_display_id = display_id.or_else(|| {
2251 active_window_placement
2252 .filter(|_| window_bounds.is_none())
2253 .and_then(|(display_id, _)| display_id)
2254 });
2255 let display = target_display_id
2256 .and_then(|display_id| cx.find_display(display_id))
2257 .or_else(|| cx.primary_display());
2258 let display_id = display
2259 .as_ref()
2260 .map(|display| display.id())
2261 .or(target_display_id);
2262 let active_window_bounds = active_window_placement
2263 .filter(|(active_display_id, _)| *active_display_id == display_id)
2264 .map(|(_, bounds)| bounds);
2265 let window_bounds = window_bounds
2266 .unwrap_or_else(|| default_bounds(active_window_bounds, display.as_deref()));
2267 let mut platform_window = cx.platform.open_window(
2268 handle,
2269 WindowParams {
2270 bounds: window_bounds.get_bounds(),
2271 titlebar,
2272 kind,
2273 is_movable,
2274 app_owns_titlebar_drag,
2275 is_resizable,
2276 is_minimizable,
2277 focus,
2278 show,
2279 display_id,
2280 window_min_size,
2281 app_id: app_id.clone(),
2282 icon,
2283 #[cfg(target_os = "macos")]
2284 tabbing_identifier,
2285 #[cfg(target_os = "macos")]
2286 use_display_p3,
2287 },
2288 )?;
2289
2290 let tab_bar_visible = platform_window.tab_bar_visible();
2291 SystemWindowTabController::init_visible(cx, tab_bar_visible);
2292 if let Some(tabs) = platform_window.tabbed_windows() {
2293 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
2294 }
2295
2296 let display_id = platform_window.display().map(|display| display.id());
2297 let sprite_atlas = platform_window.sprite_atlas();
2298 let mouse_position = platform_window.mouse_position();
2299 let modifiers = platform_window.modifiers();
2300 let capslock = platform_window.capslock();
2301 let content_size = platform_window.content_size();
2302 let scale_factor = platform_window.scale_factor();
2303 let appearance = platform_window.appearance();
2304 let text_system = Rc::new(WindowTextSystem::new(cx.text_system().clone()));
2305 let invalidator = WindowInvalidator::new(handle.window_id());
2306 let active = Rc::new(Cell::new(platform_window.is_active()));
2307 let visibility = platform_window.visibility();
2308 #[cfg(feature = "profiler")]
2309 profiler::journal::record_window_visibility(handle.window_id(), visibility);
2310 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
2311 let needs_present = Rc::new(Cell::new(false));
2312 let scene_animation_interval = Rc::new(Cell::new(None::<Duration>));
2313 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
2314 let next_frame_wanted: Rc<Cell<bool>> = Default::default();
2315 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
2316
2317 platform_window
2318 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
2319 platform_window.set_background_appearance(window_background);
2320
2321 match window_bounds {
2322 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
2323 WindowBounds::Maximized(_) => platform_window.zoom(),
2324 WindowBounds::Windowed(_) => {}
2325 }
2326
2327 let accessibility_force_disabled = cx.accessibility_force_disabled;
2328 let a11y_active_flag = Arc::new(AtomicBool::new(false));
2329
2330 #[cfg(not(target_family = "wasm"))]
2331 if !accessibility_force_disabled {
2332 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
2333 if let Some(title) = &initial_window_title {
2334 initial_root_node.set_label(title.to_string());
2335 }
2336 let initial_tree = accesskit::TreeUpdate {
2337 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
2338 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
2339 tree_id: accesskit::TreeId::ROOT,
2340 focus: ROOT_NODE_ID,
2341 };
2342 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
2343 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
2344 let (action_sender, action_receiver) =
2345 async_channel::unbounded::<accesskit::ActionRequest>();
2346
2347 platform_window.a11y_init(crate::A11yCallbacks {
2348 activation: {
2349 let active_flag = a11y_active_flag.clone();
2350 Box::new(move || {
2351 log::info!("Accessibility activated");
2352 active_flag.store(true, SeqCst);
2353 activation_sender
2354 .send_blocking(())
2355 .with_context(|| {
2356 format!(
2357 "queuing accessibility activation for window {:?}",
2358 handle.window_id()
2359 )
2360 })
2361 .log_err();
2362 Some(initial_tree.clone())
2363 })
2364 },
2365 action: Box::new(move |request| {
2366 action_sender
2367 .send_blocking(request)
2368 .with_context(|| {
2369 format!(
2370 "queuing accessibility action for window {:?}",
2371 handle.window_id()
2372 )
2373 })
2374 .log_err();
2375 }),
2376 deactivation: {
2377 let active_flag = a11y_active_flag.clone();
2378 Box::new(move || {
2379 log::info!("Accessibility deactivated");
2380 active_flag.store(false, SeqCst);
2381 deactivation_sender
2382 .send_blocking(())
2383 .with_context(|| {
2384 format!(
2385 "queuing accessibility deactivation for window {:?}",
2386 handle.window_id()
2387 )
2388 })
2389 .log_err();
2390 })
2391 },
2392 });
2393
2394 let mut async_cx = cx.to_async();
2400 cx.foreground_executor()
2401 .spawn(async move {
2402 while activation_receiver.recv().await.is_ok() {
2403 handle
2404 .update(&mut async_cx, |_, window, _| window.refresh())
2405 .with_context(|| {
2406 format!(
2407 "handling accessibility activation for window {:?}",
2408 handle.window_id()
2409 )
2410 })
2411 .log_err();
2412 }
2413 })
2414 .detach();
2415
2416 let mut async_cx = cx.to_async();
2417 cx.foreground_executor()
2418 .spawn(async move {
2419 while deactivation_receiver.recv().await.is_ok() {
2420 handle
2421 .update(&mut async_cx, |_, window, _| window.refresh())
2422 .with_context(|| {
2423 format!(
2424 "handling accessibility deactivation for window {:?}",
2425 handle.window_id()
2426 )
2427 })
2428 .log_err();
2429 }
2430 })
2431 .detach();
2432
2433 let mut async_cx = cx.to_async();
2434 cx.foreground_executor()
2435 .spawn(async move {
2436 while let Ok(request) = action_receiver.recv().await {
2437 handle
2438 .update(&mut async_cx, |_, window, cx| {
2439 window.handle_a11y_action(request, cx);
2440 })
2441 .with_context(|| {
2442 format!(
2443 "handling accessibility action for window {:?}",
2444 handle.window_id()
2445 )
2446 })
2447 .log_err();
2448 }
2449 })
2450 .detach();
2451 }
2452
2453 platform_window.on_close(Box::new({
2454 let window_id = handle.window_id();
2455 let cx = cx.to_async();
2456 move || {
2457 cx.spawn(async move |cx| {
2460 cx.update(|cx| {
2461 if cx.windows.contains_key(window_id) {
2463 handle
2464 .update(cx, |_, window, _| window.remove_window())
2465 .with_context(|| format!("handling close for window {window_id:?}"))
2466 .log_err();
2467 }
2468 SystemWindowTabController::remove_tab(cx, window_id);
2469 });
2470 })
2471 .detach();
2472 }
2473 }));
2474 platform_window.on_request_frame(Box::new({
2475 let mut cx = cx.to_async();
2476 let invalidator = invalidator.clone();
2477 let active = active.clone();
2478 let needs_present = needs_present.clone();
2479 let scene_animation_interval = scene_animation_interval.clone();
2480 let next_frame_callbacks = next_frame_callbacks.clone();
2481 let next_frame_wanted = next_frame_wanted.clone();
2482 let input_rate_tracker = input_rate_tracker.clone();
2483 let mut deferred_force_render = false;
2484 let mut frame_pacer = FramePacer::default();
2485 move |request_frame_options| {
2486 #[cfg(feature = "profiler")]
2487 let (_foreground_turn, window_id) = {
2488 let foreground_turn = profiler::journal::foreground_turn();
2489 let window_id = handle.window_id();
2490 profiler::journal::record_platform_signal(profiler::journal::PlatformSignal {
2491 window_id,
2492 signal_at: request_frame_options.signal_at,
2493 handled_at: Instant::now(),
2494 source: request_frame_options.signal_source,
2495 });
2496 (foreground_turn, window_id)
2497 };
2498 if draw_in_progress() {
2514 log::debug!("deferring re-entrant window draw request");
2515 deferred_force_render |= request_frame_options.force_render;
2516 #[cfg(feature = "profiler")]
2517 profiler::journal::record_reentrant_frame_skipped(window_id, Instant::now());
2518 return;
2519 }
2520 let force_render =
2524 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
2525
2526 let power_state = handle
2527 .update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode()))
2528 .with_context(|| {
2529 format!(
2530 "reading power state for frame request for window {:?}",
2531 handle.window_id()
2532 )
2533 })
2534 .log_err();
2535
2536 let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate();
2539 let present_for_high_rate_input = cfg!(target_os = "macos") && high_rate_input;
2543 let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty();
2544 let wants_frame_besides_animation = invalidator.is_dirty()
2549 || force_render
2550 || next_frame_wanted.get()
2551 || request_frame_options.require_presentation
2552 || needs_present.get()
2553 || present_for_high_rate_input;
2554 let has_demand_besides_animation =
2555 wants_frame_besides_animation || has_next_frame_callbacks;
2556 let wants_frame =
2557 wants_frame_besides_animation || scene_animation_interval.get().is_some();
2558 let has_frame_demand = wants_frame || has_next_frame_callbacks;
2559
2560 let should_throttle = !request_frame_options.require_presentation;
2561 let inactive_without_high_rate_input =
2562 should_throttle && !active.get() && !high_rate_input;
2563 let (thermal_state, power_mode) =
2564 power_state.unwrap_or((ThermalState::Nominal, crate::PowerMode::Unknown));
2565 let min_frame_interval = minimum_frame_interval(
2566 should_throttle,
2567 inactive_without_high_rate_input,
2568 inactive_frame_interval,
2569 low_power_frame_interval,
2570 thermal_frame_interval,
2571 thermal_state,
2572 power_mode,
2573 );
2574 let animation_frame_interval = scene_animation_interval
2575 .get()
2576 .filter(|interval| !has_demand_besides_animation && !interval.is_zero());
2577 let min_frame_interval = min_frame_interval.max(animation_frame_interval);
2578
2579 let now = Instant::now();
2580 if has_frame_demand && frame_pacer.should_defer(now, min_frame_interval) {
2583 deferred_force_render |= force_render;
2585 if wants_frame {
2587 handle
2589 .update(&mut cx, |_, window, _| {
2590 window.platform_window.schedule_frame();
2591 })
2592 .with_context(|| {
2593 format!(
2594 "rescheduling throttled frame for window {:?}",
2595 handle.window_id()
2596 )
2597 })
2598 .log_err();
2599 invalidator.wake_platform();
2602 }
2603 #[cfg(feature = "profiler")]
2604 profiler::journal::record_frame_skipped(
2605 window_id,
2606 Instant::now(),
2607 if animation_frame_interval.is_some()
2608 && animation_frame_interval == min_frame_interval
2609 {
2610 profiler::journal::FrameSkipReason::AnimationFrameRateLimit
2611 } else if inactive_without_high_rate_input
2612 && inactive_frame_interval == min_frame_interval
2613 {
2614 profiler::journal::FrameSkipReason::InactiveFrameRateLimit
2615 } else if power_mode == crate::PowerMode::LowPower
2616 && low_power_frame_interval == min_frame_interval
2617 {
2618 profiler::journal::FrameSkipReason::LowPowerFrameRateLimit
2619 } else {
2620 profiler::journal::FrameSkipReason::ThermalFrameRateLimit
2621 },
2622 );
2623 report_frame(handle.window_id(), now, FrameOutcome::Throttled);
2624 return;
2625 }
2626
2627 if !next_frame_callbacks.borrow().is_empty() {
2628 handle
2629 .update(&mut cx, |_, window, cx| {
2630 window.next_frame_wanted.set(false);
2634 for callback in next_frame_callbacks.take() {
2635 callback(window, cx);
2636 }
2637 })
2638 .with_context(|| {
2639 format!(
2640 "running next-frame callbacks for window {:?}",
2641 handle.window_id()
2642 )
2643 })
2644 .log_err();
2645 }
2646
2647 let should_draw = invalidator.is_dirty() || force_render;
2648 let needs_present = request_frame_options.require_presentation
2649 || needs_present.get()
2650 || scene_animation_interval.get().is_some()
2651 || present_for_high_rate_input;
2652 if should_draw {
2653 measure("frame duration", || {
2654 handle
2655 .update(&mut cx, |_, window, cx| {
2656 #[cfg(feature = "profiler")]
2657 window
2658 .window_profiler
2659 .record_frame_signal(request_frame_options.signal_at);
2660 if force_render {
2661 window.refresh();
2664 }
2665 let arena_clear_needed = window.draw(cx);
2666 window.advance_scene_animations(cx);
2667 window.present();
2668 arena_clear_needed.clear(cx);
2669 })
2670 .with_context(|| {
2671 format!(
2672 "drawing and presenting frame for window {:?}",
2673 handle.window_id()
2674 )
2675 })
2676 .log_err();
2677 })
2678 } else if needs_present {
2679 handle
2680 .update(&mut cx, |_, window, cx| {
2681 window.advance_scene_animations(cx);
2682 window.present();
2683 })
2684 .with_context(|| {
2685 format!("presenting frame for window {:?}", handle.window_id())
2686 })
2687 .log_err();
2688 }
2689
2690 handle
2691 .update(&mut cx, |_, window, _| {
2692 if window.invalidator.is_dirty()
2693 || window.next_frame_wanted.get()
2694 || window.scene_animation_interval.get().is_some()
2695 {
2696 window.platform_window.schedule_frame();
2697 }
2698 })
2699 .with_context(|| {
2700 format!(
2701 "scheduling follow-up frame for window {:?}",
2702 handle.window_id()
2703 )
2704 })
2705 .log_err();
2706
2707 if invalidator.is_dirty()
2713 || next_frame_wanted.get()
2714 || scene_animation_interval.get().is_some()
2715 {
2716 invalidator.wake_platform();
2717 }
2718 #[cfg(feature = "profiler")]
2719 if !should_draw {
2720 profiler::journal::record_frame_skipped(
2721 window_id,
2722 Instant::now(),
2723 profiler::journal::FrameSkipReason::NoRenderNeeded,
2724 );
2725 }
2726 if should_draw {
2727 report_frame(handle.window_id(), now, FrameOutcome::Drew);
2728 } else if has_next_frame_callbacks || needs_present {
2729 report_frame(handle.window_id(), now, FrameOutcome::NoDraw);
2730 }
2731 }
2732 }));
2733 invalidator.set_platform_waker(platform_window.frame_waker());
2734 platform_window.on_visual_viewport_changed(Box::new({
2735 let mut cx = cx.to_async();
2736 move || {
2737 handle
2738 .update(&mut cx, |_, window, _| window.refresh())
2739 .with_context(|| {
2740 format!(
2741 "handling visual viewport change for window {:?}",
2742 handle.window_id()
2743 )
2744 })
2745 .log_err();
2746 }
2747 }));
2748 platform_window.on_insets_changed(Box::new({
2749 let mut cx = cx.to_async();
2750 move |_| {
2751 handle
2752 .update(&mut cx, |_, window, _| window.refresh())
2753 .with_context(|| {
2754 format!("handling insets change for window {:?}", handle.window_id())
2755 })
2756 .log_err();
2757 }
2758 }));
2759 platform_window.on_resize(Box::new({
2760 let mut cx = cx.to_async();
2761 move |_, _| {
2762 handle
2763 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2764 .with_context(|| format!("handling resize for window {:?}", handle.window_id()))
2765 .log_err();
2766 }
2767 }));
2768 platform_window.on_moved(Box::new({
2769 let mut cx = cx.to_async();
2770 move || {
2771 handle
2772 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2773 .with_context(|| format!("handling move for window {:?}", handle.window_id()))
2774 .log_err();
2775 }
2776 }));
2777 platform_window.on_display_changed(Box::new({
2778 let cx = cx.to_async();
2779 move || cx.update(|cx| Window::display_changed(handle, cx))
2780 }));
2781 platform_window.on_appearance_changed(Box::new({
2782 let cx = cx.to_async();
2783 let foreground_executor = cx.foreground_executor().clone();
2784 move || {
2785 let mut cx = cx.clone();
2786 foreground_executor
2789 .spawn(async move {
2790 handle
2791 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
2792 .with_context(|| {
2793 format!(
2794 "handling appearance change for window {:?}",
2795 handle.window_id()
2796 )
2797 })
2798 .log_err();
2799 })
2800 .detach();
2801 }
2802 }));
2803 platform_window.on_button_layout_changed(Box::new({
2804 let mut cx = cx.to_async();
2805 move || {
2806 handle
2807 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
2808 .with_context(|| {
2809 format!(
2810 "handling button layout change for window {:?}",
2811 handle.window_id()
2812 )
2813 })
2814 .log_err();
2815 }
2816 }));
2817 platform_window.on_active_status_change(Box::new({
2818 let mut cx = cx.to_async();
2819 move |active| {
2820 handle
2821 .update(&mut cx, |_, window, cx| {
2822 if window.assume_active {
2826 return;
2827 }
2828 window.active.set(active);
2829 window.modifiers = window.platform_window.modifiers();
2830 window.capslock = window.platform_window.capslock();
2831 window
2832 .activation_observers
2833 .clone()
2834 .retain(|callback| callback(window, cx));
2835
2836 window.bounds_changed(cx);
2837 window.refresh();
2838
2839 SystemWindowTabController::update_last_active(cx, window.handle.id);
2840 })
2841 .with_context(|| {
2842 format!(
2843 "handling active status change for window {:?}",
2844 handle.window_id()
2845 )
2846 })
2847 .log_err();
2848 }
2849 }));
2850 platform_window.on_visibility_change(Box::new({
2851 let mut cx = cx.to_async();
2852 move |_| {
2853 handle
2854 .update(&mut cx, |_, window, cx| {
2855 window.refresh_visibility(cx);
2856 })
2857 .with_context(|| {
2858 format!(
2859 "handling visibility change for window {:?}",
2860 handle.window_id()
2861 )
2862 })
2863 .log_err();
2864 }
2865 }));
2866 platform_window.on_hover_status_change(Box::new({
2867 let mut cx = cx.to_async();
2868 move |active| {
2869 handle
2870 .update(&mut cx, |_, window, cx| {
2871 window.hovered.set(active);
2872 let was_inside = std::mem::replace(&mut window.pointer_inside, active);
2873 window
2874 .vn_effect_pointer
2875 .update(was_inside, active, false, cx);
2876 window.refresh();
2877 })
2878 .with_context(|| {
2879 format!(
2880 "handling hover status change for window {:?}",
2881 handle.window_id()
2882 )
2883 })
2884 .log_err();
2885 }
2886 }));
2887 platform_window.on_input({
2888 let mut cx = cx.to_async();
2889 Box::new(move |event| {
2890 handle
2891 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
2892 .with_context(|| {
2893 format!("dispatching input for window {:?}", handle.window_id())
2894 })
2895 .log_err()
2896 .unwrap_or(DispatchEventResult::default())
2897 })
2898 });
2899 platform_window.on_hit_test_window_control_at({
2900 let mut cx = cx.to_async();
2901 Box::new(move |position| {
2902 handle
2903 .update(&mut cx, |_, window, _cx| {
2904 let position = position.unwrap_or_else(|| window.platform_window.mouse_position());
2909 window.window_control_area_at(position)
2910 })
2911 .with_context(|| {
2912 format!(
2913 "hit-testing window controls for window {:?}",
2914 handle.window_id()
2915 )
2916 })
2917 .log_err()
2918 .unwrap_or(None)
2919 })
2920 });
2921 platform_window.on_move_tab_to_new_window({
2922 let mut cx = cx.to_async();
2923 Box::new(move || {
2924 handle
2925 .update(&mut cx, |_, _window, cx| {
2926 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
2927 })
2928 .with_context(|| {
2929 format!(
2930 "moving tab to new window from window {:?}",
2931 handle.window_id()
2932 )
2933 })
2934 .log_err();
2935 })
2936 });
2937 platform_window.on_merge_all_windows({
2938 let mut cx = cx.to_async();
2939 Box::new(move || {
2940 handle
2941 .update(&mut cx, |_, _window, cx| {
2942 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
2943 })
2944 .with_context(|| {
2945 format!("merging all windows into window {:?}", handle.window_id())
2946 })
2947 .log_err();
2948 })
2949 });
2950 platform_window.on_select_next_tab({
2951 let mut cx = cx.to_async();
2952 Box::new(move || {
2953 handle
2954 .update(&mut cx, |_, _window, cx| {
2955 SystemWindowTabController::select_next_tab(cx, handle.window_id());
2956 })
2957 .with_context(|| {
2958 format!("selecting next tab for window {:?}", handle.window_id())
2959 })
2960 .log_err();
2961 })
2962 });
2963 platform_window.on_select_previous_tab({
2964 let mut cx = cx.to_async();
2965 Box::new(move || {
2966 handle
2967 .update(&mut cx, |_, _window, cx| {
2968 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
2969 })
2970 .with_context(|| {
2971 format!("selecting previous tab for window {:?}", handle.window_id())
2972 })
2973 .log_err();
2974 })
2975 });
2976 platform_window.on_toggle_tab_bar({
2977 let mut cx = cx.to_async();
2978 Box::new(move || {
2979 handle
2980 .update(&mut cx, |_, window, cx| {
2981 let tab_bar_visible = window.platform_window.tab_bar_visible();
2982 SystemWindowTabController::set_visible(cx, tab_bar_visible);
2983 })
2984 .with_context(|| {
2985 format!("toggling tab bar for window {:?}", handle.window_id())
2986 })
2987 .log_err();
2988 })
2989 });
2990
2991 if let Some(app_id) = app_id {
2992 platform_window.set_app_id(&app_id);
2993 }
2994
2995 platform_window.map_window().unwrap();
2996
2997 Ok(Window {
2998 handle,
2999 invalidator,
3000 removed: false,
3001 platform_window,
3002 display_id,
3003 display_observers: SingleSubscriberSet::new(),
3004 is_resizable,
3005 is_minimizable,
3006 last_window_bounds: window_bounds,
3007 sprite_atlas,
3008 text_system,
3009 text_rendering_mode: cx.text_rendering_mode.clone(),
3010 rem_size: px(16.),
3011 rem_size_override_stack: SmallVec::new(),
3012 viewport_size: content_size,
3013 layout_engine: Some(TaffyLayoutEngine::new()),
3014 root: None,
3015 element_id_stack: ElementIdStack::default(),
3016 text_style_stack: Vec::new(),
3017 rendered_entity_stack: Vec::new(),
3018 element_offset_stack: Vec::new(),
3019 content_mask_stack: Vec::new(),
3020 vn_clip_stack: None,
3021 vn_capture_records: FxHashMap::default(),
3022 element_opacity: 1.0,
3023 element_image_tint: Hsla::transparent_black(),
3024 element_transform: TransformationMatrix::unit(),
3025 vn_hitbox_tag: 0,
3026 vn_tag_fresh: false,
3027 vn_tag_transform: None,
3028 vn_tag_every_hitbox: false,
3029 vn_pick_every_box: false,
3030 vn_hit_refiner: None,
3031 input_interceptor: None,
3032 vn_key_event_seq: 0,
3033 vn_pointer_lock: None,
3034 vn_raw_mouse_position: None,
3035 vn_mouse_movement: Point::default(),
3036 requested_autoscroll: None,
3037 last_text_input_configuration: None,
3038 focused_text_input: None,
3039 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
3040 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
3041 next_frame_callbacks,
3042 next_frame_wanted,
3043 next_hitbox_id: HitboxId(0),
3044 next_tooltip_id: TooltipId::default(),
3045 tooltip_bounds: None,
3046 dirty_views: FxHashSet::default(),
3047 focus_listeners: SingleSubscriberSet::new(),
3048 focus_lost_listeners: SingleSubscriberSet::new(),
3049 focus_lost_path: SmallVec::new(),
3050 default_prevented: true,
3051 mouse_position,
3052 mouse_hit_test: HitTest::default(),
3053 modifiers,
3054 capslock,
3055 scale_factor,
3056 bounds_observers: SingleSubscriberSet::new(),
3057 appearance,
3058 appearance_observers: SingleSubscriberSet::new(),
3059 button_layout_observers: SingleSubscriberSet::new(),
3060 active,
3061 assume_active: false,
3062 visibility,
3063 visibility_observers: SingleSubscriberSet::new(),
3064 vn_effect_pointer: VnEffectPointer::new(hovered.get()),
3065 vn_effect_element: 0,
3066 vn_effect_phases: FxHashMap::default(),
3067 vn_defer_scope: None,
3068 vn_scopes_painted: FxHashSet::default(),
3069 pointer_inside: hovered.get(),
3070 hovered,
3071 needs_present,
3072 scene_animation_interval,
3073 input_rate_tracker,
3074 #[cfg(feature = "profiler")]
3075 window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
3076 last_input_modality: InputModality::Mouse,
3077 touch_gestures: TouchGestureRecognizer::new(
3078 cx.platform
3079 .gestures()
3080 .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
3081 ),
3082 touch_prediction_enabled: true,
3083 long_press_timer: None,
3084 long_press_capture: None,
3085 refreshing: false,
3086 activation_observers: SingleSubscriberSet::new(),
3087 focus: None,
3088 focus_enabled: true,
3089 focus_generation: 0,
3090 pending_input: None,
3091 pending_modifier: ModifierState::default(),
3092 pending_input_observers: SingleSubscriberSet::new(),
3093 prompt: None,
3094 client_inset: None,
3095 image_cache_stack: Vec::new(),
3096 captured_hitbox: None,
3097 #[cfg(any(feature = "inspector", debug_assertions))]
3098 inspector: None,
3099 #[cfg(feature = "profiler")]
3100 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
3101 a11y: A11y::new(
3102 a11y_active_flag,
3103 accessibility_force_disabled,
3104 initial_window_title,
3105 ),
3106 })
3107 }
3108
3109 pub(crate) fn new_focus_listener(
3110 &self,
3111 value: AnyWindowFocusListener,
3112 ) -> (Subscription, impl FnOnce() + use<>) {
3113 self.focus_listeners.insert_pending(value)
3114 }
3115}
3116
3117#[derive(Clone, Debug, Default, PartialEq, Eq)]
3118#[expect(missing_docs)]
3119pub struct DispatchEventResult {
3120 pub propagate: bool,
3121 pub default_prevented: bool,
3122}
3123
3124#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3134#[repr(C)]
3135pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
3136 pub bounds: Bounds<P>,
3138 pub corner_radii: Corners<P>,
3141}
3142
3143impl<P: Clone + Debug + Default + PartialEq> ContentMask<P> {
3144 pub fn rect(bounds: Bounds<P>) -> Self {
3146 ContentMask {
3147 bounds,
3148 corner_radii: Corners::default(),
3149 }
3150 }
3151
3152 pub fn is_rounded(&self) -> bool {
3154 self.corner_radii != Corners::default()
3155 }
3156}
3157
3158impl ContentMask<Pixels> {
3159 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
3161 ContentMask {
3162 bounds: self.bounds.scale(factor),
3163 corner_radii: self.corner_radii.scale(factor),
3164 }
3165 }
3166}
3167
3168impl<P> ContentMask<P>
3169where
3170 P: Copy
3171 + Ord
3172 + Debug
3173 + Default
3174 + Add<P, Output = P>
3175 + Sub<P, Output = P>
3176 + Div<f32, Output = P>
3177 + Into<f64>,
3178{
3179 pub fn intersect(&self, other: &Self) -> Self {
3195 let bounds = self.bounds.intersect(&other.bounds);
3196 if !self.is_rounded() && !other.is_rounded() {
3197 return ContentMask::rect(bounds);
3198 }
3199 let at = |mask: &Self, left: bool, top: bool| {
3200 let x = if left { mask.bounds.left() } else { mask.bounds.right() };
3201 let y = if top { mask.bounds.top() } else { mask.bounds.bottom() };
3202 (x, y)
3203 };
3204 let radius = |left: bool, top: bool, mine: P, theirs: P| {
3205 let here = at(&ContentMask::rect(bounds), left, top);
3206 let mine = if at(self, left, top) == here { mine } else { P::default() };
3207 let theirs = if at(other, left, top) == here { theirs } else { P::default() };
3208 mine.max(theirs)
3209 };
3210 let (a, b) = (&self.corner_radii, &other.corner_radii);
3211 let corner_radii = Corners {
3212 top_left: radius(true, true, a.top_left, b.top_left),
3213 top_right: radius(false, true, a.top_right, b.top_right),
3214 bottom_right: radius(false, false, a.bottom_right, b.bottom_right),
3215 bottom_left: radius(true, false, a.bottom_left, b.bottom_left),
3216 }
3217 .clamp_radii_for_quad_size(bounds.size);
3218 ContentMask {
3219 bounds,
3220 corner_radii,
3221 }
3222 }
3223
3224 pub fn contains(&self, point: &Point<P>) -> bool {
3228 if !self.bounds.contains(point) {
3229 return false;
3230 }
3231 if !self.is_rounded() {
3232 return true;
3233 }
3234 let b = &self.bounds;
3235 let r = &self.corner_radii;
3236 for (radius, cx, cy, left, top) in [
3237 (r.top_left, b.left() + r.top_left, b.top() + r.top_left, true, true),
3238 (r.top_right, b.right() - r.top_right, b.top() + r.top_right, false, true),
3239 (r.bottom_right, b.right() - r.bottom_right, b.bottom() - r.bottom_right, false, false),
3240 (r.bottom_left, b.left() + r.bottom_left, b.bottom() - r.bottom_left, true, false),
3241 ] {
3242 let in_x = if left { point.x < cx } else { point.x > cx };
3243 let in_y = if top { point.y < cy } else { point.y > cy };
3244 if radius > P::default() && in_x && in_y {
3245 let (dx, dy): (f64, f64) = ((point.x - cx).into(), (point.y - cy).into());
3246 let radius: f64 = radius.into();
3247 return dx * dx + dy * dy <= radius * radius;
3248 }
3249 }
3250 true
3251 }
3252}
3253
3254impl Window {
3255 fn mark_view_dirty(&mut self, view_id: EntityId) {
3256 for view_id in self
3259 .rendered_frame
3260 .dispatch_tree
3261 .view_path_reversed(view_id)
3262 {
3263 if !self.dirty_views.insert(view_id) {
3264 break;
3265 }
3266 }
3267 }
3268
3269 pub(crate) fn refresh_visibility(&mut self, cx: &mut App) {
3270 let visibility = self.platform_window.visibility();
3271 if self.visibility != visibility {
3272 self.visibility = visibility;
3273 #[cfg(feature = "profiler")]
3274 profiler::journal::record_window_visibility(self.handle.window_id(), visibility);
3275 self.visibility_observers
3276 .clone()
3277 .retain(|callback| callback(visibility, self, cx));
3278 }
3279 #[cfg(feature = "profiler")]
3280 if self.invalidator.is_dirty() || self.needs_present.get() {
3281 profiler::journal::record_frame_pending(self.handle.window_id(), Instant::now());
3282 }
3283 }
3284
3285 pub(crate) fn debug_state(&self) -> serde_json::Value {
3290 let platform_window = &self.platform_window;
3291 serde_json::json!({
3292 "id": self.handle.window_id().as_u64(),
3293 "title": platform_window.get_title(),
3294 "bounds": platform_window.bounds(),
3295 "window_bounds": format!("{:?}", platform_window.window_bounds()),
3296 "content_size": platform_window.content_size(),
3297 "viewport_size": self.viewport_size,
3298 "scale_factor": {
3299 "cached": self.scale_factor,
3300 "platform": platform_window.scale_factor(),
3301 },
3302 "display_id": {
3303 "cached": self.display_id.map(u64::from),
3304 "platform": platform_window.display().map(|display| u64::from(display.id())),
3305 },
3306 "active": {
3307 "cached": self.active.get(),
3308 "platform": platform_window.is_active(),
3309 },
3310 "hovered": {
3311 "cached": self.hovered.get(),
3312 "platform": platform_window.is_hovered(),
3313 },
3314 "visibility": {
3315 "cached": format!("{:?}", self.visibility),
3316 "platform": format!("{:?}", platform_window.visibility()),
3317 },
3318 "appearance": {
3319 "cached": format!("{:?}", self.appearance),
3320 "platform": format!("{:?}", platform_window.appearance()),
3321 },
3322 "is_fullscreen": platform_window.is_fullscreen(),
3323 "is_maximized": platform_window.is_maximized(),
3324 "mouse_position": {
3325 "cached": self.mouse_position,
3326 "platform": platform_window.mouse_position(),
3327 },
3328 "modifiers": {
3329 "cached": self.modifiers,
3330 "platform": platform_window.modifiers(),
3331 },
3332 "cursor_style": self.rendered_frame.cursor_style(self),
3333 "frame": {
3334 "dirty": self.invalidator.is_dirty(),
3335 "needs_present": self.needs_present.get(),
3336 "refreshing": self.refreshing,
3337 "next_frame_callbacks": self.next_frame_callbacks.borrow().len(),
3338 },
3339 "gpu": platform_window.gpu_specs(),
3340 "platform": platform_window.debug_state(),
3341 })
3342 }
3343
3344 pub fn visibility(&self) -> WindowVisibility {
3347 self.visibility
3348 }
3349
3350 pub fn is_visible(&self) -> bool {
3356 self.visibility.is_visible()
3357 }
3358
3359 pub fn observe_window_visibility(
3361 &self,
3362 mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
3363 ) -> Subscription {
3364 self.visibility_observers
3365 .insert(Box::new(move |visibility, window, cx| {
3366 callback(visibility, window, cx);
3367 true
3368 }))
3369 }
3370
3371 pub fn observe_window_activation(
3374 &self,
3375 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3376 ) -> Subscription {
3377 self.activation_observers
3378 .insert(Box::new(move |window, cx| {
3379 callback(window, cx);
3380 true
3381 }))
3382 }
3383
3384 pub fn observe_window_appearance(
3386 &self,
3387 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3388 ) -> Subscription {
3389 self.appearance_observers
3390 .insert(Box::new(move |window, cx| {
3391 callback(window, cx);
3392 true
3393 }))
3394 }
3395
3396 pub fn observe_button_layout_changed(
3398 &self,
3399 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3400 ) -> Subscription {
3401 self.button_layout_observers
3402 .insert(Box::new(move |window, cx| {
3403 callback(window, cx);
3404 true
3405 }))
3406 }
3407
3408 pub fn replace_root<E>(
3410 &mut self,
3411 cx: &mut App,
3412 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
3413 ) -> Entity<E>
3414 where
3415 E: 'static + Render,
3416 {
3417 let view = cx.new(|cx| build_view(self, cx));
3418 self.root = Some(view.clone().into());
3419 self.refresh();
3420 view
3421 }
3422
3423 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
3425 where
3426 E: 'static + Render,
3427 {
3428 self.root
3429 .as_ref()
3430 .map(|view| view.clone().downcast::<E>().ok())
3431 }
3432
3433 pub fn window_handle(&self) -> AnyWindowHandle {
3435 self.handle
3436 }
3437
3438 pub fn refresh(&mut self) {
3440 if self.invalidator.not_drawing() {
3441 self.refreshing = true;
3442 self.invalidator.set_dirty(true);
3443 }
3444 }
3445
3446 pub fn remove_window(&mut self) {
3448 self.removed = true;
3449 }
3450
3451 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
3453 self.focus
3454 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
3455 }
3456
3457 pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
3461 let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
3462 ancestors.iter().rev().find_map(|id| {
3463 self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
3464 FocusHandle::for_id(*id, &cx.focus_handles)
3465 })
3466 }
3467
3468 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
3470 if !self.focus_enabled || self.focus == Some(handle.id) {
3471 return;
3472 }
3473
3474 self.focus = Some(handle.id);
3475 self.focus_generation = self.focus_generation.wrapping_add(1);
3476 self.clear_pending_keystrokes(cx);
3477
3478 self.refresh();
3479 }
3480
3481 pub fn blur(&mut self, cx: &mut App) {
3483 self.clear_pending_keystrokes(cx);
3484
3485 if !self.focus_enabled {
3486 return;
3487 }
3488
3489 if self.focus.is_some() {
3490 self.focus_generation = self.focus_generation.wrapping_add(1);
3491 }
3492 self.focus = None;
3493 self.refresh();
3494 }
3495
3496 pub fn disable_focus(&mut self, cx: &mut App) {
3498 self.blur(cx);
3499 self.focus_enabled = false;
3500 }
3501
3502 pub fn focus_next(&mut self, cx: &mut App) {
3504 if !self.focus_enabled {
3505 return;
3506 }
3507
3508 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
3509 self.focus(&handle, cx)
3510 }
3511 }
3512
3513 pub fn focus_prev(&mut self, cx: &mut App) {
3515 if !self.focus_enabled {
3516 return;
3517 }
3518
3519 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
3520 self.focus(&handle, cx)
3521 }
3522 }
3523
3524 pub fn text_system(&self) -> &Rc<WindowTextSystem> {
3526 &self.text_system
3527 }
3528
3529 pub fn text_style(&self) -> TextStyle {
3531 let mut style = TextStyle::default();
3532 for refinement in &self.text_style_stack {
3533 style.refine(refinement);
3534 }
3535 style
3536 }
3537
3538 pub fn is_maximized(&self) -> bool {
3542 self.platform_window.is_maximized()
3543 }
3544
3545 pub fn request_decorations(&self, decorations: WindowDecorations) {
3547 self.platform_window.request_decorations(decorations);
3548 }
3549
3550 pub fn set_exclusive_zone(&self, zone: Pixels) {
3556 self.platform_window.set_exclusive_zone(zone);
3557 }
3558
3559 #[cfg(all(target_os = "linux", feature = "wayland"))]
3564 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
3565 self.platform_window.set_exclusive_edge(edge);
3566 }
3567
3568 pub fn start_window_resize(&self, edge: ResizeEdge) {
3570 if self.is_resizable {
3571 self.platform_window.start_window_resize(edge);
3572 }
3573 }
3574
3575 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
3582 self.platform_window.set_input_region(region);
3583 }
3584
3585 pub fn window_bounds(&self) -> WindowBounds {
3588 self.platform_window.window_bounds()
3589 }
3590
3591 pub(crate) fn last_window_bounds(&self) -> WindowBounds {
3592 self.last_window_bounds
3593 }
3594
3595 pub(crate) fn display_id(&self) -> Option<DisplayId> {
3596 self.display_id
3597 }
3598
3599 pub fn inner_window_bounds(&self) -> WindowBounds {
3601 self.platform_window.inner_window_bounds()
3602 }
3603
3604 pub fn vn_composition_underlay(&self) -> Option<(usize, usize)> {
3608 self.platform_window.vn_composition_underlay()
3609 }
3610
3611 pub fn vn_set_maximized(&self, maximized: bool) {
3613 self.platform_window.vn_set_maximized(maximized)
3614 }
3615
3616 pub fn vn_is_zoomed(&self) -> bool {
3618 self.platform_window.vn_is_zoomed()
3619 }
3620
3621 pub fn vn_is_minimized(&self) -> bool {
3623 self.platform_window.vn_is_minimized()
3624 }
3625
3626 pub fn vn_unminimize(&self) {
3628 self.platform_window.vn_unminimize()
3629 }
3630
3631 pub fn vn_hide(&self) -> bool {
3633 self.platform_window.vn_hide()
3634 }
3635
3636 pub fn vn_is_shown(&self) -> bool {
3638 self.platform_window.vn_is_shown()
3639 }
3640
3641 pub fn vn_set_frame(&self, origin: Option<Point<Pixels>>, size: Option<Size<Pixels>>) -> bool {
3644 self.platform_window.vn_set_frame(origin, size)
3645 }
3646
3647 pub fn vn_set_always_on_top(&self, on: bool) -> bool {
3649 self.platform_window.vn_set_always_on_top(on)
3650 }
3651
3652 pub fn vn_set_maximizable(&self, maximizable: bool) {
3654 self.platform_window.vn_set_maximizable(maximizable)
3655 }
3656
3657 pub fn vn_set_ignore_mouse(&self, ignore: bool) -> bool {
3659 self.platform_window.vn_set_ignore_mouse(ignore)
3660 }
3661
3662 pub fn vn_set_content_protection(&self, on: bool) -> bool {
3664 self.platform_window.vn_set_content_protection(on)
3665 }
3666
3667 pub fn vn_request_close(&self) {
3669 self.platform_window.vn_request_close()
3670 }
3671
3672 pub fn native_window_state(&self) -> Option<Vec<u8>> {
3675 self.platform_window.native_window_state()
3676 }
3677
3678 pub fn restore_native_window_state(&self, state: &[u8]) {
3681 self.platform_window.restore_native_window_state(state);
3682 }
3683
3684 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
3686 let focus_id = self.focused(cx).map(|handle| handle.id);
3687
3688 let window = self.handle;
3689 cx.defer(move |cx| {
3690 window
3691 .update(cx, |_, window, cx| {
3692 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
3693 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
3694 })
3695 .with_context(|| format!("dispatching action for window {:?}", window.window_id()))
3696 .log_err();
3697 })
3698 }
3699
3700 pub(crate) fn dispatch_keystroke_observers(
3701 &mut self,
3702 keystroke: &Keystroke,
3703 input_preference: InputPreference,
3704 action: Option<&dyn Action>,
3705 context_stack: Vec<KeyContext>,
3706 cx: &mut App,
3707 ) {
3708 cx.keystroke_observers.clone().retain(move |callback| {
3709 (callback)(
3710 &KeystrokeEvent {
3711 keystroke: keystroke.clone(),
3712 input_preference,
3713 action: action.map(|action| action.boxed_clone()),
3714 context_stack: context_stack.clone(),
3715 },
3716 self,
3717 cx,
3718 )
3719 });
3720 }
3721
3722 pub(crate) fn dispatch_keystroke_interceptors(
3723 &mut self,
3724 keystroke: &Keystroke,
3725 input_preference: InputPreference,
3726 context_stack: Vec<KeyContext>,
3727 cx: &mut App,
3728 ) {
3729 cx.keystroke_interceptors.clone().retain(move |callback| {
3730 (callback)(
3731 &KeystrokeEvent {
3732 keystroke: keystroke.clone(),
3733 input_preference,
3734 action: None,
3735 context_stack: context_stack.clone(),
3736 },
3737 self,
3738 cx,
3739 )
3740 });
3741 }
3742
3743 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
3746 let handle = self.handle;
3747 cx.defer(move |cx| {
3748 handle.update(cx, |_, window, cx| f(window, cx)).ok();
3749 });
3750 }
3751
3752 pub fn observe<T: 'static>(
3756 &mut self,
3757 observed: &Entity<T>,
3758 cx: &mut App,
3759 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
3760 ) -> Subscription {
3761 let entity_id = observed.entity_id();
3762 let observed = observed.downgrade();
3763 let window_handle = self.handle;
3764 cx.new_observer(
3765 entity_id,
3766 Box::new(move |cx| {
3767 window_handle
3768 .update(cx, |_, window, cx| {
3769 if let Some(handle) = observed.upgrade() {
3770 on_notify(handle, window, cx);
3771 true
3772 } else {
3773 false
3774 }
3775 })
3776 .unwrap_or(false)
3777 }),
3778 )
3779 }
3780
3781 pub fn subscribe<Emitter, Evt>(
3785 &mut self,
3786 entity: &Entity<Emitter>,
3787 cx: &mut App,
3788 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
3789 ) -> Subscription
3790 where
3791 Emitter: EventEmitter<Evt>,
3792 Evt: 'static,
3793 {
3794 let entity_id = entity.entity_id();
3795 let handle = entity.downgrade();
3796 let window_handle = self.handle;
3797 cx.new_subscription(
3798 entity_id,
3799 (
3800 TypeId::of::<Evt>(),
3801 Box::new(move |event, cx| {
3802 window_handle
3803 .update(cx, |_, window, cx| {
3804 if let Some(entity) = handle.upgrade() {
3805 let event = event.downcast_ref().expect("invalid event type");
3806 on_event(entity, event, window, cx);
3807 true
3808 } else {
3809 false
3810 }
3811 })
3812 .unwrap_or(false)
3813 }),
3814 ),
3815 )
3816 }
3817
3818 pub fn observe_release<T>(
3820 &self,
3821 entity: &Entity<T>,
3822 cx: &mut App,
3823 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
3824 ) -> Subscription
3825 where
3826 T: 'static,
3827 {
3828 let entity_id = entity.entity_id();
3829 let window_handle = self.handle;
3830 cx.release_listeners.insert(
3831 entity_id,
3832 Box::new(move |entity, cx| {
3833 let entity = entity.downcast_mut().expect("invalid entity type");
3834 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
3835 }),
3836 )
3837 }
3838
3839 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
3842 AsyncWindowContext::new_context(cx.to_async(), self.handle)
3843 }
3844
3845 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
3847 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
3848 self.next_frame_wanted.set(true);
3849 self.platform_window.schedule_frame();
3850 self.invalidator.wake_platform();
3853 }
3854
3855 pub fn on_next_frame_passive(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
3861 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
3862 }
3863
3864 pub fn request_animation_frame(&self) {
3877 let entity = self.current_view();
3878 self.on_next_frame(move |_, cx| cx.notify(entity));
3879 }
3880
3881 pub(crate) fn advance_scene_animations(&mut self, cx: &App) {
3882 let elapsed = cx.background_executor().now() - cx.synced_animation_epoch;
3883 self.rendered_frame.scene.advance_animations(elapsed);
3884 }
3885
3886 #[cfg(any(test, feature = "test-support"))]
3891 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
3892 let callbacks = self.next_frame_callbacks.take();
3893 self.next_frame_wanted.set(false);
3894 let count = callbacks.len();
3895 for callback in callbacks {
3896 callback(self, cx);
3897 }
3898 count
3899 }
3900
3901 #[track_caller]
3905 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
3906 where
3907 R: 'static,
3908 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3909 {
3910 let handle = self.handle;
3911 cx.spawn(async move |app| {
3912 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3913 f(&mut async_window_cx).await
3914 })
3915 }
3916
3917 #[track_caller]
3921 pub fn spawn_with_priority<AsyncFn, R>(
3922 &self,
3923 priority: Priority,
3924 cx: &App,
3925 f: AsyncFn,
3926 ) -> Task<R>
3927 where
3928 R: 'static,
3929 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3930 {
3931 let handle = self.handle;
3932 cx.spawn_with_priority(priority, async move |app| {
3933 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3934 f(&mut async_window_cx).await
3935 })
3936 }
3937
3938 pub fn bounds_changed(&mut self, cx: &mut App) {
3944 self.scale_factor = self.platform_window.scale_factor();
3945 self.viewport_size = self.platform_window.content_size();
3946 self.last_window_bounds = self.platform_window.window_bounds();
3947 cx.sync_window_update_entry(self);
3948 self.mouse_position = self.platform_window.mouse_position();
3949
3950 self.refresh();
3951
3952 self.bounds_observers
3953 .clone()
3954 .retain(|callback| callback(self, cx));
3955 }
3956
3957 fn display_changed(handle: AnyWindowHandle, cx: &mut App) {
3958 let moved_to = handle
3959 .update(cx, |_, window, _| {
3960 let display_id = window.platform_window.display().map(|display| display.id());
3961 let moved = display_id != window.display_id;
3962 window.display_id = display_id;
3963 moved.then_some(display_id)
3964 })
3965 .with_context(|| {
3966 format!(
3967 "handling display change for window {:?}",
3968 handle.window_id()
3969 )
3970 })
3971 .log_err()
3972 .flatten();
3973 let Some(display_id) = moved_to else {
3974 return;
3975 };
3976 if let Some(display_id) = display_id
3980 && !cx.knows_display(display_id)
3981 {
3982 cx.displays_changed();
3983 }
3984 handle
3985 .update(cx, |_, window, cx| window.notify_display_observers(cx))
3986 .with_context(|| {
3987 format!(
3988 "notifying display observers for window {:?}",
3989 handle.window_id()
3990 )
3991 })
3992 .log_err();
3993 }
3994
3995 pub(crate) fn notify_display_observers(&mut self, cx: &mut App) {
3996 self.display_observers
3997 .clone()
3998 .retain(|callback| callback(self, cx));
3999 }
4000
4001 pub fn refresh_interval(&self, cx: &App) -> Option<Duration> {
4006 cx.display_refresh_interval(self.display_id?)
4007 }
4008
4009 pub fn observe_window_display(
4014 &self,
4015 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
4016 ) -> Subscription {
4017 self.display_observers.insert(Box::new(move |window, cx| {
4018 callback(window, cx);
4019 true
4020 }))
4021 }
4022
4023 pub fn bounds(&self) -> Bounds<Pixels> {
4025 self.platform_window.bounds()
4026 }
4027
4028 pub fn insets(&self) -> WindowInsets {
4030 self.platform_window.insets()
4031 }
4032
4033 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
4047 self.platform_window
4048 .render_to_image(&self.rendered_frame.scene)
4049 }
4050
4051 #[cfg(feature = "bench-support")]
4054 pub fn rendered_scene(&self) -> &Scene {
4055 &self.rendered_frame.scene
4056 }
4057
4058 #[cfg(any(test, feature = "test-support"))]
4063 pub fn painted_quads(&self) -> Vec<Quad> {
4064 self.rendered_frame.scene.quads.clone()
4065 }
4066
4067 #[cfg(any(test, feature = "test-support"))]
4069 pub fn painted_underlines(&self) -> Vec<Underline> {
4070 self.rendered_frame.scene.underlines.clone()
4071 }
4072
4073 pub fn resize(&mut self, size: Size<Pixels>) {
4075 self.platform_window.resize(size);
4076 }
4077
4078 pub fn is_fullscreen(&self) -> bool {
4080 self.platform_window.is_fullscreen()
4081 }
4082
4083 pub fn is_simple_fullscreen(&self) -> bool {
4087 self.platform_window.is_simple_fullscreen()
4088 }
4089
4090 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
4091 self.appearance = self.platform_window.appearance();
4092
4093 self.appearance_observers
4094 .clone()
4095 .retain(|callback| callback(self, cx));
4096 }
4097
4098 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
4099 self.button_layout_observers
4100 .clone()
4101 .retain(|callback| callback(self, cx));
4102 }
4103
4104 pub fn appearance(&self) -> WindowAppearance {
4106 self.appearance
4107 }
4108
4109 pub fn viewport_size(&self) -> Size<Pixels> {
4111 self.viewport_size
4112 }
4113
4114 pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
4120 self.platform_window.visual_viewport_bounds()
4121 }
4122
4123 pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
4128 let insets = self.platform_window.insets().effective();
4129 let viewport = self.viewport_size();
4130 let left = insets.left.max(Pixels::ZERO).min(viewport.width);
4131 let top = insets.top.max(Pixels::ZERO).min(viewport.height);
4132 let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
4133 let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
4134 let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
4135 let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
4136 visible.size.width = visible.size.width.max(Pixels::ZERO);
4137 visible.size.height = visible.size.height.max(Pixels::ZERO);
4138 visible
4139 }
4140
4141 pub fn request_virtual_keyboard(&self) {
4146 self.platform_window.show_soft_keyboard();
4147 }
4148
4149 pub fn dismiss_virtual_keyboard(&self) {
4151 self.platform_window.hide_soft_keyboard();
4152 }
4153
4154 pub fn is_window_active(&self) -> bool {
4156 self.active.get()
4157 }
4158
4159 pub fn set_assume_active(&mut self, on: bool) {
4172 self.assume_active = on;
4173 let active = on || self.platform_window.is_active();
4174 if self.active.replace(active) != active {
4175 self.refresh();
4176 }
4177 }
4178
4179 pub fn is_window_hovered(&self) -> bool {
4183 if cfg!(any(
4184 target_os = "windows",
4185 target_os = "linux",
4186 target_os = "freebsd"
4187 )) {
4188 self.hovered.get()
4189 } else {
4190 self.is_window_active()
4191 }
4192 }
4193
4194 pub fn zoom_window(&self) {
4196 self.platform_window.zoom();
4197 }
4198
4199 pub fn show_window_menu(&self, position: Point<Pixels>) {
4201 self.platform_window.show_window_menu(position)
4202 }
4203
4204 pub fn start_window_move(&self) {
4209 self.platform_window.start_window_move()
4210 }
4211
4212 pub fn set_client_inset(&mut self, inset: Pixels) {
4214 self.client_inset = Some(inset);
4215 self.platform_window.set_client_inset(inset);
4216 }
4217
4218 pub fn set_client_corner_radii(&mut self, radii: Corners<Pixels>) {
4220 self.platform_window.set_client_corner_radii(radii);
4221 }
4222
4223 pub fn client_inset(&self) -> Option<Pixels> {
4225 self.client_inset
4226 }
4227
4228 pub fn window_decorations(&self) -> Decorations {
4230 self.platform_window.window_decorations()
4231 }
4232
4233 pub fn is_resizable(&self) -> bool {
4235 self.is_resizable
4236 }
4237
4238 pub fn is_minimizable(&self) -> bool {
4240 self.is_minimizable
4241 }
4242
4243 pub fn window_controls(&self) -> WindowControls {
4245 self.platform_window.window_controls()
4246 }
4247
4248 pub fn set_window_title(&mut self, title: &str) {
4250 self.platform_window.set_title(title);
4251 self.a11y.set_window_title(title.to_string());
4252 }
4253
4254 #[cfg(target_os = "macos")]
4256 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
4257 self.platform_window.set_traffic_light_position(position);
4258 }
4259
4260 #[cfg(target_os = "macos")]
4262 pub fn set_native_titlebar_visibility(&self, visible: bool) {
4263 self.platform_window.set_native_titlebar_visibility(visible);
4264 }
4265
4266 pub fn set_app_id(&mut self, app_id: &str) {
4268 self.platform_window.set_app_id(app_id);
4269 }
4270
4271 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
4273 self.platform_window
4274 .set_background_appearance(background_appearance);
4275 }
4276
4277 pub fn is_background_appearance_drawn(&self) -> bool {
4283 self.platform_window.is_background_appearance_drawn()
4284 }
4285
4286 pub fn set_window_edited(&mut self, edited: bool) {
4288 self.platform_window.set_edited(edited);
4289 }
4290
4291 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
4294 self.platform_window.set_document_path(path);
4295 }
4296
4297 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
4299 cx.platform
4300 .displays()
4301 .into_iter()
4302 .find(|display| Some(display.id()) == self.display_id)
4303 }
4304
4305 pub fn show_character_palette(&self) {
4307 self.platform_window.show_character_palette();
4308 }
4309
4310 pub fn scale_factor(&self) -> f32 {
4314 self.scale_factor
4315 }
4316
4317 #[cfg(any(test, feature = "test-support"))]
4319 pub fn set_scale_factor(&mut self, scale_factor: f32) {
4320 self.scale_factor = scale_factor;
4321 self.refresh();
4322 }
4323
4324 pub fn rem_size(&self) -> Pixels {
4327 self.rem_size_override_stack
4328 .last()
4329 .copied()
4330 .unwrap_or(self.rem_size)
4331 }
4332
4333 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
4336 self.rem_size = rem_size.into();
4337 }
4338
4339 pub fn with_global_id<R>(
4342 &mut self,
4343 element_id: ElementId,
4344 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
4345 ) -> R {
4346 self.with_id(element_id, |this| {
4347 let global_id = this.element_id_stack.global_id();
4348
4349 f(&global_id, this)
4350 })
4351 }
4352
4353 #[inline]
4355 pub fn with_id<R>(
4356 &mut self,
4357 element_id: impl Into<ElementId>,
4358 f: impl FnOnce(&mut Self) -> R,
4359 ) -> R {
4360 self.element_id_stack.push(element_id.into());
4361 let result = f(self);
4362 self.element_id_stack.pop();
4363 result
4364 }
4365
4366 #[inline]
4372 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
4373 where
4374 F: FnOnce(&mut Self) -> R,
4375 {
4376 self.invalidator.debug_assert_paint_or_prepaint();
4377
4378 if let Some(rem_size) = rem_size {
4379 self.rem_size_override_stack.push(rem_size.into());
4380 let result = f(self);
4381 self.rem_size_override_stack.pop();
4382 result
4383 } else {
4384 f(self)
4385 }
4386 }
4387
4388 pub fn line_height(&self) -> Pixels {
4390 self.text_style().line_height_in_pixels(self.rem_size())
4391 }
4392
4393 #[inline]
4395 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
4396 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
4397 }
4398
4399 #[inline]
4401 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
4402 let scale_factor = f64::from(self.scale_factor());
4403 round_half_toward_zero_f64(value * scale_factor) / scale_factor
4404 }
4405
4406 #[inline]
4408 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
4409 bounds.map(|c| self.pixel_snap(c))
4410 }
4411
4412 #[inline]
4414 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
4415 position.map(|c| self.pixel_snap(c))
4416 }
4417
4418 pub fn underline_bounds(
4420 &self,
4421 origin: Point<Pixels>,
4422 width: Pixels,
4423 style: &UnderlineStyle,
4424 ) -> Bounds<ScaledPixels> {
4425 let scale_factor = self.scale_factor();
4426 let thickness = self.snap_stroke(style.thickness);
4427 let height = if style.wavy {
4428 ScaledPixels(thickness.0 * 3.)
4429 } else {
4430 thickness
4431 };
4432 Bounds {
4433 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4434 size: size(self.snap_stroke(width), height),
4435 }
4436 }
4437
4438 pub fn paint_underline_with_exclusions(
4440 &mut self,
4441 origin: Point<Pixels>,
4442 width: Pixels,
4443 style: &UnderlineStyle,
4444 exclusions: &[Range<ScaledPixels>],
4445 ) {
4446 self.invalidator.debug_assert_paint();
4447 let underline = self.underline(origin, width, style);
4448 if exclusions.is_empty() {
4449 self.next_frame.scene.insert_primitive(underline);
4450 return;
4451 }
4452
4453 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
4454 if bounds.is_empty() {
4455 return;
4456 }
4457
4458 let mut exclusions = exclusions
4459 .iter()
4460 .filter_map(|span| {
4461 let start = span.start.max(bounds.left());
4462 let end = span.end.min(bounds.right());
4463 (start < end).then_some(start..end)
4464 })
4465 .collect::<SmallVec<[_; 4]>>();
4466 if exclusions.is_empty() {
4467 self.next_frame.scene.insert_primitive(underline);
4468 return;
4469 }
4470 exclusions.sort_unstable_by_key(|span| span.start);
4471
4472 let mut paint_span = |start, end| {
4473 let span = ContentMask::rect(Bounds::from_corners(
4476 point(start, bounds.top()),
4477 point(end, bounds.bottom()),
4478 ));
4479 self.next_frame.scene.insert_primitive(Underline {
4480 content_mask: underline.content_mask.intersect(&span),
4481 ..underline
4482 });
4483 };
4484 let mut start = bounds.left();
4485 for exclusion in exclusions {
4486 if start < exclusion.start {
4487 paint_span(start, exclusion.start);
4488 }
4489 start = start.max(exclusion.end);
4490 }
4491 if start < bounds.right() {
4492 paint_span(start, bounds.right());
4493 }
4494 }
4495
4496 fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline {
4497 Underline {
4498 order: 0,
4499 pad: 0,
4500 bounds: self.underline_bounds(origin, width, style),
4501 content_mask: self.snapped_content_mask(),
4502 color: style
4503 .color
4504 .unwrap_or_default()
4505 .opacity(self.element_opacity()),
4506 thickness: self.snap_stroke(style.thickness),
4507 wavy: style.wavy.into(),
4508 transformation: self.element_transform,
4511 }
4512 }
4513
4514 #[inline]
4515 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
4516 let scale_factor = self.scale_factor();
4517 let left = round_to_device_pixel(bounds.left().0, scale_factor);
4518 let top = round_to_device_pixel(bounds.top().0, scale_factor);
4519 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
4520 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
4521 Bounds::from_corners(
4522 point(ScaledPixels(left), ScaledPixels(top)),
4523 point(ScaledPixels(right), ScaledPixels(bottom)),
4524 )
4525 }
4526
4527 #[inline]
4529 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
4530 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
4531 }
4532
4533 #[inline]
4534 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
4535 edges.map(|e| self.snap_stroke(*e))
4536 }
4537
4538 #[inline]
4540 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
4541 let scale_factor = self.scale_factor();
4542 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
4543 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
4544 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
4545 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
4546 Bounds::from_corners(
4547 point(ScaledPixels(left), ScaledPixels(top)),
4548 point(ScaledPixels(right), ScaledPixels(bottom)),
4549 )
4550 }
4551
4552 #[inline]
4553 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
4554 let mask = self.content_mask();
4555 ContentMask {
4556 bounds: self.cover_bounds(mask.bounds),
4557 corner_radii: mask.corner_radii.scale(self.scale_factor()),
4561 }
4562 }
4563
4564 pub fn prevent_default(&mut self) {
4567 self.default_prevented = true;
4568 }
4569
4570 pub fn default_prevented(&self) -> bool {
4572 self.default_prevented
4573 }
4574
4575 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
4577 let node_id =
4578 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
4579 self.rendered_frame
4580 .dispatch_tree
4581 .is_action_available(action, node_id)
4582 }
4583
4584 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
4586 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
4587 self.rendered_frame
4588 .dispatch_tree
4589 .is_action_available(action, node_id)
4590 }
4591
4592 pub fn mouse_position(&self) -> Point<Pixels> {
4594 self.mouse_position
4595 }
4596
4597 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
4604 self.captured_hitbox = Some(hitbox_id);
4605 }
4606
4607 pub fn release_pointer(&mut self) {
4609 self.captured_hitbox = None;
4610 }
4611
4612 pub fn captured_hitbox(&self) -> Option<HitboxId> {
4614 self.captured_hitbox
4615 }
4616
4617 pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
4623 self.long_press_capture = Some(entity.entity_id());
4624 }
4625
4626 pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
4628 self.long_press_capture == Some(entity.entity_id())
4629 }
4630
4631 pub fn modifiers(&self) -> Modifiers {
4633 self.modifiers
4634 }
4635
4636 pub fn last_input_was_keyboard(&self) -> bool {
4639 self.last_input_modality == InputModality::Keyboard
4640 }
4641
4642 pub fn last_input_was_touch(&self) -> bool {
4644 self.last_input_modality == InputModality::Touch
4645 }
4646
4647 pub fn capslock(&self) -> Capslock {
4649 self.capslock
4650 }
4651
4652 #[profiling::function]
4655 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
4656 let _profile_window = crate::native_profiling::window_scope(self.platform_window.as_ref());
4657 let _profile = crate::native_profiling::current_span("native", "GPUI draw");
4658 #[cfg(feature = "profiler")]
4661 let frame_dirty = self.invalidator.take_frame_dirty();
4662 #[cfg(feature = "profiler")]
4663 self.window_profiler.begin_draw();
4664
4665 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
4668
4669 if self.platform_window.prepare_frame() {
4670 self.refresh();
4671 }
4672 self.invalidate_entities();
4673 cx.entities.clear_accessed();
4674 debug_assert!(self.rendered_entity_stack.is_empty());
4675 self.invalidator.set_dirty(false);
4676 self.requested_autoscroll = None;
4677
4678 if let Some(input_handler) = self.platform_window.take_input_handler() {
4683 if let Some(slot) = self
4684 .rendered_frame
4685 .input_handlers
4686 .iter_mut()
4687 .rev()
4688 .find(|h| h.is_none())
4689 {
4690 *slot = Some(input_handler);
4691 } else {
4692 self.rendered_frame.input_handlers.push(Some(input_handler));
4693 }
4694 }
4695 if !cx.mode.skip_drawing() {
4696 self.vn_scopes_painted.clear();
4697 self.draw_roots(cx);
4698 let now = crate::effect_clock_seconds();
4699 self.vn_effect_phases
4700 .retain(|_, phase| now - phase.at < VnEffectPhase::KEEP);
4701 #[cfg(feature = "profiler")]
4702 {
4703 let viewport_size = self.viewport_size;
4704 let scale_factor = self.scale_factor();
4705 self.debug_frame_overlay.paint(
4706 &mut self.next_frame.scene,
4707 viewport_size,
4708 scale_factor,
4709 );
4710 }
4711 }
4712 let _finalize = crate::native_profiling::current_span("native", "GPUI finalize frame");
4713 self.dirty_views.clear();
4714 self.next_frame.window_active = self.active.get();
4715
4716 let focused_text_input = if let Some(mut input_handler) = self
4722 .next_frame
4723 .input_handlers
4724 .iter_mut()
4725 .rev()
4726 .find_map(|h| h.take())
4727 {
4728 let accepts_text_input = input_handler.accepts_text_input(self, cx);
4729 self.platform_window.set_input_handler(input_handler);
4730 self.focus.filter(|_| accepts_text_input)
4731 } else {
4732 None
4733 };
4734 self.apply_text_input_configuration(cx);
4735 let previous = mem::replace(&mut self.focused_text_input, focused_text_input);
4736 if previous.is_some() != focused_text_input.is_some() {
4737 self.platform_window
4738 .text_input_state_changed(if focused_text_input.is_some() {
4739 TextInputStateChange::FocusGained
4740 } else {
4741 TextInputStateChange::FocusLost
4742 });
4743 }
4744
4745 {
4746 let _profile = crate::native_profiling::current_span("native", "GPUI finish layout and text");
4747 self.layout_engine.as_mut().unwrap().clear();
4748 self.text_system().finish_frame();
4749 }
4750 {
4751 let _profile = crate::native_profiling::current_span("native", "GPUI finish scene");
4752 self.next_frame.finish(&mut self.rendered_frame);
4753 self.vn_settle_captures();
4754 }
4755
4756 self.invalidator.set_phase(DrawPhase::Focus);
4757 let previous_focus_path = self.rendered_frame.focus_path();
4758 let previous_window_active = self.rendered_frame.window_active;
4759 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
4760 self.scene_animation_interval
4761 .set(self.rendered_frame.scene.animation_frame_interval());
4762 {
4763 let _profile = crate::native_profiling::current_span("native", "GPUI clear previous frame");
4764 self.next_frame.clear();
4765 }
4766 let current_focus_path = self.rendered_frame.focus_path();
4767 let current_window_active = self.rendered_frame.window_active;
4768 let mut focus_before_listeners = self.focus;
4769
4770 if previous_focus_path != current_focus_path
4771 || previous_window_active != current_window_active
4772 {
4773 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
4774 self.focus_lost_path = previous_focus_path.clone();
4775 self.focus_lost_listeners
4776 .clone()
4777 .retain(|listener| listener(self, cx));
4778 self.focus_lost_path = SmallVec::new();
4779 focus_before_listeners = self.focus;
4784 }
4785
4786 let event = WindowFocusEvent {
4787 previous_focus_path: if previous_window_active {
4788 previous_focus_path
4789 } else {
4790 Default::default()
4791 },
4792 current_focus_path: if current_window_active {
4793 current_focus_path
4794 } else {
4795 Default::default()
4796 },
4797 };
4798 self.focus_listeners
4799 .clone()
4800 .retain(|listener| listener(&event, self, cx));
4801 }
4802
4803 debug_assert!(self.rendered_entity_stack.is_empty());
4804 self.record_entities_accessed(cx);
4805 self.reset_cursor_style(cx);
4806 self.refreshing = false;
4807 self.invalidator.set_phase(DrawPhase::None);
4808 if self.focus != focus_before_listeners {
4813 self.refresh();
4814 }
4815 self.needs_present.set(true);
4816
4817 #[cfg(feature = "profiler")]
4818 {
4819 self.window_profiler
4820 .set_refresh_interval(self.refresh_interval(cx));
4821 let draw_duration = self
4822 .window_profiler
4823 .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
4824 self.debug_frame_overlay.record_frame(draw_duration);
4825 }
4826
4827 arena_scope.exit(&cx.element_arena)
4830 }
4831
4832 fn record_entities_accessed(&mut self, cx: &mut App) {
4833 let entities = cx.entities.take_accessed();
4834 let handle = self.handle;
4835 cx.record_entities_accessed(
4836 handle,
4837 self.invalidator.clone(),
4839 &entities,
4840 );
4841 cx.entities.restore_accessed(entities);
4842 }
4843
4844 fn invalidate_entities(&mut self) {
4845 let mut views = self.invalidator.take_views();
4846 for entity in views.drain() {
4847 self.mark_view_dirty(entity);
4848 }
4849 self.invalidator.replace_views(views);
4850 }
4851
4852 #[profiling::function]
4853 fn present(&mut self) {
4854 #[cfg(feature = "profiler")]
4855 let _foreground_turn = profiler::journal::foreground_turn();
4856 #[cfg(feature = "profiler")]
4857 let present_start = Instant::now();
4858 self.platform_window.draw(&self.rendered_frame.scene);
4859 #[cfg(feature = "profiler")]
4860 self.window_profiler.record_present(
4861 present_start,
4862 Instant::now(),
4863 self.active.get(),
4864 !self.next_frame_callbacks.borrow().is_empty(),
4865 );
4866 self.needs_present.set(false);
4867 profiling::finish_frame!();
4868 }
4869
4870 #[cfg(all(test, feature = "profiler"))]
4872 pub fn present_if_needed(&mut self) {
4873 if self.needs_present.get() {
4874 self.present();
4875 }
4876 }
4877
4878 #[cfg(feature = "profiler")]
4880 pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
4881 self.window_profiler.input_latency_snapshot()
4882 }
4883
4884 #[cfg(feature = "profiler")]
4886 pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
4887 self.window_profiler.frame_duration_snapshot()
4888 }
4889
4890 #[cfg(feature = "profiler")]
4892 pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
4893 self.debug_frame_overlay.mode()
4894 }
4895
4896 #[cfg(feature = "profiler")]
4898 pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
4899 self.debug_frame_overlay.set_mode(mode);
4900 self.refresh();
4901 }
4902
4903 #[cfg(feature = "profiler")]
4906 pub fn cycle_debug_frame_overlay_mode(&mut self) {
4907 self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
4908 }
4909
4910 #[cfg(feature = "profiler")]
4913 pub fn reset_debug_frame_overlay_stats(&mut self) {
4914 self.debug_frame_overlay.reset_stats();
4915 self.refresh();
4916 }
4917
4918 fn draw_roots(&mut self, cx: &mut App) {
4919 self.invalidator.set_phase(DrawPhase::Prepaint);
4920 self.tooltip_bounds.take();
4921
4922 self.a11y.sync_active_flag();
4923 if self.a11y.is_active() {
4924 self.a11y.begin_frame();
4925 }
4926
4927 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
4928 let root_size = {
4929 #[cfg(any(feature = "inspector", debug_assertions))]
4930 {
4931 if self.inspector.is_some() {
4932 let mut size = self.viewport_size;
4933 size.width = (size.width - _inspector_width).max(px(0.0));
4934 size
4935 } else {
4936 self.viewport_size
4937 }
4938 }
4939 #[cfg(not(any(feature = "inspector", debug_assertions)))]
4940 {
4941 self.viewport_size
4942 }
4943 };
4944
4945 let scale_factor = self.scale_factor();
4949 #[cfg(feature = "profiler")]
4950 let request_layout_start = Instant::now();
4951 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
4952 let root_layout_id = root_element.request_layout(self, cx);
4953 #[cfg(feature = "profiler")]
4954 let prepaint_start = Instant::now();
4955 self.layout_engine
4956 .as_mut()
4957 .unwrap()
4958 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
4959 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
4960
4961 #[cfg(any(feature = "inspector", debug_assertions))]
4962 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
4963
4964 let deferred_hitboxes_start = self.next_frame.hitboxes.len();
4965 let deferred_tagged_start = self.next_frame.vn_tagged_hitboxes.len();
4966 self.prepaint_deferred_draws(cx);
4967 let deferred_hitboxes = deferred_hitboxes_start..self.next_frame.hitboxes.len();
4968 self.next_frame.vn_deferred_tagged =
4969 deferred_tagged_start..self.next_frame.vn_tagged_hitboxes.len();
4970
4971 let mut prompt_element = None;
4972 let mut active_drag_element = None;
4973 let mut tooltip_element = None;
4974 if let Some(prompt) = self.prompt.take() {
4975 let mut element = prompt.view.any_view().into_any_element();
4976 let prompt_layout_id = element.request_layout(self, cx);
4977 self.layout_engine
4978 .as_mut()
4979 .unwrap()
4980 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
4981 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
4982 prompt_element = Some(element);
4983 self.prompt = Some(prompt);
4984 } else if let Some(active_drag) = cx.active_drag.take() {
4985 let mut element = active_drag.view.clone().into_any_element();
4986 let offset = self.mouse_position() - active_drag.cursor_offset;
4987 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
4988 active_drag_element = Some(element);
4989 cx.active_drag = Some(active_drag);
4990 } else {
4991 tooltip_element = self.prepaint_tooltip(cx);
4992 }
4993
4994 self.compute_hit_order(deferred_hitboxes);
4995 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position, self.scale_factor);
4996
4997 #[cfg(feature = "profiler")]
4999 let paint_start = Instant::now();
5000 self.invalidator.set_phase(DrawPhase::Paint);
5001 root_element.paint(self, cx);
5002
5003 #[cfg(any(feature = "inspector", debug_assertions))]
5004 self.paint_inspector(inspector_element, cx);
5005
5006 self.paint_deferred_draws(cx);
5007
5008 if let Some(mut prompt_element) = prompt_element {
5009 prompt_element.paint(self, cx);
5010 } else if let Some(mut drag_element) = active_drag_element {
5011 drag_element.paint(self, cx);
5012 } else if let Some(mut tooltip_element) = tooltip_element {
5013 tooltip_element.paint(self, cx);
5014 }
5015
5016 #[cfg(any(feature = "inspector", debug_assertions))]
5017 self.paint_inspector_hitbox(cx);
5018
5019 #[cfg(feature = "profiler")]
5020 self.window_profiler
5021 .record_draw_phases(profiler::DrawPhases {
5022 request_layout: prepaint_start.duration_since(request_layout_start),
5023 prepaint: paint_start.duration_since(prepaint_start),
5024 paint: Instant::now().duration_since(paint_start),
5025 });
5026
5027 let _profile = crate::native_profiling::current_span("native", "GPUI postpaint accessibility");
5028 let a11y_active_start_of_frame = self.a11y.is_active();
5030 self.a11y.sync_active_flag();
5031 let a11y_active_end_of_frame = self.a11y.is_active();
5032
5033 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
5034
5035 if a11y_active_start_of_frame {
5036 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
5039 viewport_size: self.viewport_size,
5040 scale_factor: self.scale_factor,
5041 tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
5042 };
5043 let tree_update = self.a11y.end_frame(frame_info);
5045
5046 if should_send_a11y_update {
5047 log::debug!(
5048 "Sending a11y tree update: {} nodes",
5049 tree_update.nodes.len()
5050 );
5051 self.platform_window.a11y_tree_update(tree_update);
5052 }
5053 }
5054 }
5055
5056 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
5057 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
5059 let Some(Some(tooltip_request)) = self
5060 .next_frame
5061 .tooltip_requests
5062 .get(tooltip_request_index)
5063 .cloned()
5064 else {
5065 log::error!("Unexpectedly absent TooltipRequest");
5066 continue;
5067 };
5068 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
5069 let mouse_position = tooltip_request.tooltip.mouse_position;
5070 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
5071
5072 let mut tooltip_bounds =
5073 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
5074 let window_bounds = Bounds {
5075 origin: Point::default(),
5076 size: self.viewport_size(),
5077 };
5078
5079 if tooltip_bounds.right() > window_bounds.right() {
5080 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
5081 if new_x >= Pixels::ZERO {
5082 tooltip_bounds.origin.x = new_x;
5083 } else {
5084 tooltip_bounds.origin.x = cmp::max(
5085 Pixels::ZERO,
5086 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
5087 );
5088 }
5089 }
5090
5091 if tooltip_bounds.bottom() > window_bounds.bottom() {
5092 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
5093 if new_y >= Pixels::ZERO {
5094 tooltip_bounds.origin.y = new_y;
5095 } else {
5096 tooltip_bounds.origin.y = cmp::max(
5097 Pixels::ZERO,
5098 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
5099 );
5100 }
5101 }
5102
5103 let is_visible =
5107 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
5108 if !is_visible {
5109 continue;
5110 }
5111
5112 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
5113 element.prepaint(window, cx)
5114 });
5115
5116 self.tooltip_bounds = Some(TooltipBounds {
5117 id: tooltip_request.id,
5118 bounds: tooltip_bounds,
5119 });
5120 return Some(element);
5121 }
5122 None
5123 }
5124
5125 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
5126 assert_eq!(self.element_id_stack.len(), 0);
5127
5128 let mut round_start = 0;
5139 let mut depth = 0;
5140 loop {
5141 let round_end = self.next_frame.deferred_draws.len();
5142 if round_start == round_end {
5143 break;
5144 }
5145 assert!(depth < 64, "Exceeded maximum (64) deferred depth");
5152 depth += 1;
5153
5154 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
5156 {
5157 let draws = &self.next_frame.deferred_draws;
5158 traversal_order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5159 }
5160
5161 for deferred_draw_ix in traversal_order {
5162 let (
5163 element,
5164 parent_node,
5165 current_view,
5166 rem_size,
5167 absolute_offset,
5168 element_transform,
5169 element_opacity,
5170 content_mask,
5171 vn_clip,
5172 vn_scope,
5173 prepaint_range,
5174 ) = {
5175 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
5176 self.element_id_stack
5177 .clone_from(&deferred_draw.element_id_stack);
5178 self.text_style_stack
5179 .clone_from(&deferred_draw.text_style_stack);
5180 (
5181 deferred_draw.element.take(),
5182 deferred_draw.parent_node,
5183 deferred_draw.current_view,
5184 deferred_draw.rem_size,
5185 deferred_draw.absolute_offset,
5186 deferred_draw.element_transform,
5187 deferred_draw.element_opacity,
5188 deferred_draw.content_mask,
5189 deferred_draw.vn_clip.clone(),
5190 deferred_draw.vn_scope.clone(),
5191 deferred_draw.prepaint_range.clone(),
5192 )
5193 };
5194 self.next_frame.dispatch_tree.set_active_node(parent_node);
5195 let a11y_parent = self.next_frame.deferred_draws[deferred_draw_ix]
5198 .a11y_parent
5199 .filter(|&p| p != a11y::ROOT_NODE_ID && self.a11y.is_active());
5200
5201 let prepaint_start = self.prepaint_index();
5202 if let Some(mut element) = element {
5203 if let Some(parent) = a11y_parent {
5204 self.a11y.nodes.begin_adopted(parent);
5205 }
5206 let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
5207 self.with_rendered_view(current_view, |window| {
5208 window.with_rem_size(Some(rem_size), |window| {
5209 window.with_content_mask(content_mask, |window| {
5211 window.vn_with_absolute_clip_stack(vn_clip, |window| {
5212 window.with_absolute_element_opacity(element_opacity, |window| {
5213 window.with_absolute_element_transform(element_transform, |window| {
5214 window.with_absolute_element_offset(absolute_offset, |window| {
5215 let outer = mem::replace(&mut window.vn_defer_scope, vn_scope);
5216 element.prepaint(window, cx);
5217 window.vn_defer_scope = outer;
5218 });
5219 });
5220 });
5221 });
5222 });
5223 });
5224 });
5225 });
5226 if a11y_parent.is_some() {
5227 self.a11y.nodes.end_adopted();
5228 }
5229 self.next_frame.deferred_draws[deferred_draw_ix].accessed_entities = accessed_entities;
5230 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
5231 } else {
5232 cx.entities.extend_accessed(
5233 self.next_frame.deferred_draws[deferred_draw_ix]
5234 .accessed_entities
5235 .iter()
5236 .copied(),
5237 );
5238 self.reuse_prepaint(prepaint_range);
5239 }
5240 let prepaint_end = self.prepaint_index();
5241 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
5242 prepaint_start..prepaint_end;
5243 }
5244
5245 self.element_id_stack.clear();
5246 self.text_style_stack.clear();
5247 round_start = round_end;
5248 }
5249 }
5250
5251 fn paint_deferred_draws(&mut self, cx: &mut App) {
5252 let _profile = crate::native_profiling::current_span("paint", "GPUI paint deferred draws");
5253 assert_eq!(self.element_id_stack.len(), 0);
5254
5255 if self.next_frame.deferred_draws.len() == 0 {
5258 return;
5259 }
5260
5261 let traversal_order = self.deferred_draw_traversal_order();
5264 for deferred_draw_ix in traversal_order {
5265 let draw = &self.next_frame.deferred_draws[deferred_draw_ix];
5266 if let Some(scope) = &draw.vn_scope
5268 && (self.vn_scopes_painted.contains(&scope.id) || draw.element.is_none())
5269 {
5270 continue;
5271 }
5272 self.vn_paint_deferred_draw(deferred_draw_ix, None, cx);
5273 }
5274 self.element_id_stack.clear();
5275 self.text_style_stack.clear();
5276 }
5277
5278 fn vn_paint_deferred_draw(
5282 &mut self,
5283 ix: usize,
5284 scope: Option<(f32, Option<Arc<crate::VnClipNode>>)>,
5285 cx: &mut App,
5286 ) {
5287 let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5288 self.element_id_stack
5289 .clone_from(&deferred_draw.element_id_stack);
5290 self.text_style_stack
5296 .clone_from(&deferred_draw.text_style_stack);
5297 self.next_frame
5298 .dispatch_tree
5299 .set_active_node(deferred_draw.parent_node);
5300
5301 let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5302 let content_mask = deferred_draw.content_mask;
5303 let element_transform = deferred_draw.element_transform;
5304 let (element_opacity, base) = match &scope {
5305 Some((opacity, base)) => (
5306 (deferred_draw.element_opacity / opacity).min(1.),
5307 base.as_ref(),
5308 ),
5309 None => (deferred_draw.element_opacity, None),
5310 };
5311 let vn_clip = deferred_draw.vn_clip.clone();
5312 let view = deferred_draw.current_view;
5313 let rem_size = deferred_draw.rem_size;
5314 let paint_range = deferred_draw.paint_range.clone();
5315 let mut element = deferred_draw.element.take();
5316
5317 let paint_start = self.paint_index();
5318 if let Some(element) = element.as_mut() {
5319 let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
5320 self.with_rendered_view(view, |window| {
5321 window.with_content_mask(content_mask, |window| {
5323 window.vn_reopen_clip_layers(vn_clip, base, cx, |window, cx| {
5324 window.with_absolute_element_opacity(element_opacity, |window| {
5325 window.with_absolute_element_transform(element_transform, |window| {
5326 window.with_rem_size(Some(rem_size), |window| {
5327 element.paint(window, cx);
5328 });
5329 });
5330 });
5331 });
5332 });
5333 });
5334 });
5335 self.next_frame.deferred_draws[ix]
5336 .accessed_entities
5337 .extend(accessed_entities);
5338 } else {
5339 self.reuse_paint(paint_range);
5340 }
5341 let paint_end = self.paint_index();
5342 let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5343 deferred_draw.element = element;
5344 deferred_draw.paint_range = paint_start..paint_end;
5345 }
5346
5347 fn vn_paint_scope(&mut self, id: u64, opacity: f32, cx: &mut App) {
5351 if id == 0 || !self.vn_scopes_painted.insert(id) {
5352 return;
5353 }
5354 let mut order: SmallVec<[usize; 8]> = self
5355 .next_frame
5356 .deferred_draws
5357 .iter()
5358 .enumerate()
5359 .filter(|(_, draw)| draw.vn_scope.as_ref().is_some_and(|scope| scope.id == id))
5360 .map(|(ix, _)| ix)
5361 .collect();
5362 if order.is_empty() {
5363 return;
5364 }
5365 let draws = &self.next_frame.deferred_draws;
5366 order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5367 let element_id_stack = self.element_id_stack.clone();
5368 let text_style_stack = self.text_style_stack.clone();
5369 let active_node = self.next_frame.dispatch_tree.active_node_id();
5370 for ix in order {
5371 let base = self.next_frame.deferred_draws[ix]
5372 .vn_scope
5373 .as_ref()
5374 .and_then(|scope| scope.clip.clone());
5375 self.vn_paint_deferred_draw(ix, Some((opacity, base)), cx);
5376 }
5377 self.element_id_stack = element_id_stack;
5378 self.text_style_stack = text_style_stack;
5379 if let Some(node) = active_node {
5380 self.next_frame.dispatch_tree.set_active_node(node);
5381 }
5382 }
5383
5384 pub fn vn_with_defer_scope<R>(&mut self, id: u64, f: impl FnOnce(&mut Self) -> R) -> R {
5387 if id == 0 {
5388 return f(self);
5389 }
5390 let scope = VnDeferScope {
5391 id,
5392 clip: self.vn_clip_stack.clone(),
5393 };
5394 let previous = self.vn_defer_scope.replace(scope);
5395 let result = f(self);
5396 self.vn_defer_scope = previous;
5397 result
5398 }
5399
5400 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
5401 let deferred_count = self.next_frame.deferred_draws.len();
5402 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
5403 let draws = &self.next_frame.deferred_draws;
5404 sorted_indices.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5405 sorted_indices
5406 }
5407
5408 fn compute_hit_order(&mut self, deferred_hitboxes: Range<usize>) {
5416 let frame = &mut self.next_frame;
5417 frame.vn_hit_order.clear();
5418 if deferred_hitboxes.is_empty() {
5419 return;
5420 }
5421 let mut order: Vec<u32> = Vec::with_capacity(frame.hitboxes.len());
5422 order.extend(0..deferred_hitboxes.start as u32);
5423 let mut traversal = (0..frame.deferred_draws.len()).collect::<Vec<_>>();
5424 let draws = &frame.deferred_draws;
5425 traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5426 for ix in traversal {
5427 let range = &draws[ix].prepaint_range;
5428 let (start, end) = (range.start.hitboxes_index, range.end.hitboxes_index);
5429 if start >= deferred_hitboxes.start && end <= deferred_hitboxes.end && start < end {
5432 order.extend(start as u32..end as u32);
5433 }
5434 }
5435 order.extend(deferred_hitboxes.end as u32..frame.hitboxes.len() as u32);
5436 if order.len() != frame.hitboxes.len() {
5439 return;
5440 }
5441 frame.vn_hit_order = order;
5442 }
5443
5444 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
5445 PrepaintStateIndex {
5446 hitboxes_index: self.next_frame.hitboxes.len(),
5447 vn_tagged_hitboxes_index: self.next_frame.vn_tagged_hitboxes.len(),
5449 tooltips_index: self.next_frame.tooltip_requests.len(),
5450 deferred_draws_index: self.next_frame.deferred_draws.len(),
5451 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
5452 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
5453 line_layout_index: self.text_system.layout_index(),
5454 }
5455 }
5456
5457 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
5458 self.next_frame.hitboxes.extend(
5459 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
5460 .iter()
5461 .cloned(),
5462 );
5463 self.next_frame.vn_tagged_hitboxes.extend(
5469 self.rendered_frame.vn_tagged_hitboxes
5470 [range.start.vn_tagged_hitboxes_index..range.end.vn_tagged_hitboxes_index]
5471 .iter()
5472 .cloned(),
5473 );
5474 self.next_frame.tooltip_requests.extend(
5475 self.rendered_frame.tooltip_requests
5476 [range.start.tooltips_index..range.end.tooltips_index]
5477 .iter_mut()
5478 .map(|request| request.take()),
5479 );
5480 self.next_frame.accessed_element_states.extend(
5481 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
5482 ..range.end.accessed_element_states_index]
5483 .iter()
5484 .map(|(id, type_id)| (id.clone(), *type_id)),
5485 );
5486 self.text_system
5487 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
5488
5489 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
5490 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
5491 &mut self.rendered_frame.dispatch_tree,
5492 self.focus,
5493 );
5494
5495 if reused_subtree.contains_focus() {
5496 self.next_frame.focus = self.focus;
5497 }
5498
5499 self.next_frame.deferred_draws.extend(
5500 self.rendered_frame.deferred_draws
5501 [range.start.deferred_draws_index..range.end.deferred_draws_index]
5502 .iter()
5503 .map(|deferred_draw| DeferredDraw {
5504 current_view: deferred_draw.current_view,
5505 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
5506 element_id_stack: deferred_draw.element_id_stack.clone(),
5507 text_style_stack: deferred_draw.text_style_stack.clone(),
5508 content_mask: deferred_draw.content_mask,
5509 rem_size: deferred_draw.rem_size,
5510 priority: deferred_draw.priority,
5511 element: None,
5512 absolute_offset: deferred_draw.absolute_offset,
5513 element_transform: deferred_draw.element_transform,
5514 a11y_parent: deferred_draw.a11y_parent,
5515 vn_stack: deferred_draw.vn_stack.clone(),
5516 element_opacity: deferred_draw.element_opacity,
5517 vn_clip: deferred_draw.vn_clip.clone(),
5518 vn_scope: deferred_draw.vn_scope.clone(),
5519 prepaint_range: deferred_draw.prepaint_range.clone(),
5520 paint_range: deferred_draw.paint_range.clone(),
5521 accessed_entities: deferred_draw.accessed_entities.clone(),
5522 }),
5523 );
5524 }
5525
5526 pub(crate) fn paint_index(&self) -> PaintIndex {
5527 PaintIndex {
5528 scene_index: self.next_frame.scene.len(),
5529 #[cfg(any(test, feature = "test-support"))]
5530 debug_bounds_index: self.next_frame.debug_bounds_records.len(),
5531 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
5532 input_handlers_index: self.next_frame.input_handlers.len(),
5533 cursor_styles_index: self.next_frame.cursor_styles.len(),
5534 window_control_hitboxes_index: self.next_frame.window_control_hitboxes.len(),
5535 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
5536 tab_handle_index: self.next_frame.tab_stops.paint_index(),
5537 line_layout_index: self.text_system.layout_index(),
5538 }
5539 }
5540
5541 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
5542 #[cfg(any(test, feature = "test-support"))]
5544 for (selector, bounds) in &self.rendered_frame.debug_bounds_records
5545 [range.start.debug_bounds_index..range.end.debug_bounds_index]
5546 {
5547 self.next_frame
5548 .record_debug_bounds(selector.clone(), *bounds);
5549 }
5550 self.next_frame.window_control_hitboxes.extend(
5554 self.rendered_frame.window_control_hitboxes
5555 [range.start.window_control_hitboxes_index..range.end.window_control_hitboxes_index]
5556 .iter()
5557 .cloned(),
5558 );
5559 self.next_frame.cursor_styles.extend(
5560 self.rendered_frame.cursor_styles
5561 [range.start.cursor_styles_index..range.end.cursor_styles_index]
5562 .iter()
5563 .cloned(),
5564 );
5565 self.next_frame.input_handlers.extend(
5566 self.rendered_frame.input_handlers
5567 [range.start.input_handlers_index..range.end.input_handlers_index]
5568 .iter_mut()
5569 .map(|handler| handler.take()),
5570 );
5571 self.next_frame.mouse_listeners.extend(
5572 self.rendered_frame.mouse_listeners
5573 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
5574 .iter_mut()
5575 .map(|listener| listener.take()),
5576 );
5577 self.next_frame.accessed_element_states.extend(
5578 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
5579 ..range.end.accessed_element_states_index]
5580 .iter()
5581 .map(|(id, type_id)| (id.clone(), *type_id)),
5582 );
5583 self.next_frame.tab_stops.replay(
5584 &self.rendered_frame.tab_stops.insertion_history
5585 [range.start.tab_handle_index..range.end.tab_handle_index],
5586 );
5587
5588 self.text_system
5589 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
5590 self.next_frame.scene.replay(
5591 range.start.scene_index..range.end.scene_index,
5592 &self.rendered_frame.scene,
5593 );
5594 }
5595
5596 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
5600 where
5601 F: FnOnce(&mut Self) -> R,
5602 {
5603 self.invalidator.debug_assert_paint_or_prepaint();
5604 if let Some(style) = style {
5605 self.text_style_stack.push(style);
5606 let result = f(self);
5607 self.text_style_stack.pop();
5608 result
5609 } else {
5610 f(self)
5611 }
5612 }
5613
5614 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
5617 self.invalidator.debug_assert_paint();
5618 self.next_frame.cursor_styles.push(CursorStyleRequest {
5619 hitbox_id: Some(hitbox.id),
5620 style,
5621 });
5622 }
5623
5624 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
5629 self.invalidator.debug_assert_paint();
5630 self.next_frame.cursor_styles.push(CursorStyleRequest {
5631 hitbox_id: None,
5632 style,
5633 })
5634 }
5635
5636 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
5639 self.invalidator.debug_assert_prepaint();
5640 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
5641 self.next_frame
5642 .tooltip_requests
5643 .push(Some(TooltipRequest { id, tooltip }));
5644 id
5645 }
5646
5647 #[inline]
5652 pub fn with_content_mask<R>(
5653 &mut self,
5654 mask: Option<ContentMask<Pixels>>,
5655 f: impl FnOnce(&mut Self) -> R,
5656 ) -> R {
5657 self.invalidator.debug_assert_paint_or_prepaint();
5658 if let Some(mask) = mask {
5659 let mask = transform_mask(self.element_transform, mask, self.scale_factor);
5676 let mask = mask.intersect(&self.content_mask());
5677 self.content_mask_stack.push(mask);
5678 let result = f(self);
5679 self.content_mask_stack.pop();
5680 result
5681 } else {
5682 f(self)
5683 }
5684 }
5685
5686 pub fn vn_with_clip_shape<R>(
5695 &mut self,
5696 outline: Option<&crate::VnClipOutline>,
5697 f: impl FnOnce(&mut Self) -> R,
5698 ) -> R {
5699 let Some(outline) = outline else {
5700 return f(self);
5701 };
5702 let geometry = Arc::new(crate::VnClipGeometry::new(
5703 outline,
5704 self.scale_factor,
5705 self.element_transform,
5706 ));
5707 let node = Arc::new(crate::VnClipNode {
5708 geometry,
5709 color_matrix: None,
5710 capture: None,
5711 mask: None,
5712 parent: self.vn_clip_stack.clone(),
5713 });
5714 let previous = self.vn_clip_stack.replace(node.clone());
5715 let result = self.vn_with_clip_layer(&node, f);
5716 self.vn_clip_stack = previous;
5717 result
5718 }
5719
5720 pub fn vn_with_color_matrix<R>(
5723 &mut self,
5724 matrix: Option<crate::VnColorMatrix>,
5725 f: impl FnOnce(&mut Self) -> R,
5726 ) -> R {
5727 let Some(matrix) = matrix else { return f(self) };
5728 let bounds = self.snapped_content_mask().bounds;
5729 let left = bounds.origin.x.0;
5730 let top = bounds.origin.y.0;
5731 let right = left + bounds.size.width.0;
5732 let bottom = top + bounds.size.height.0;
5733 let geometry = Arc::new(crate::VnClipGeometry {
5734 fill_rule: crate::VnFillRule::NonZero,
5735 segments: vec![
5736 [left, top, right, top], [right, top, right, bottom],
5737 [right, bottom, left, bottom], [left, bottom, left, top],
5738 ],
5739 bounds,
5740 });
5741 let node = Arc::new(crate::VnClipNode {
5742 geometry,
5743 color_matrix: Some(matrix),
5744 capture: None,
5745 mask: None,
5746 parent: self.vn_clip_stack.clone(),
5747 });
5748 let previous = self.vn_clip_stack.replace(node.clone());
5749 let result = self.vn_with_clip_layer(&node, f);
5750 self.vn_clip_stack = previous;
5751 result
5752 }
5753
5754 pub fn vn_text_paint(&self, fill: crate::VnTextFill, bounds: Bounds<Pixels>) -> Arc<crate::VnTextPaint> {
5756 let x = bounds.origin.x.0; let y = bounds.origin.y.0;
5757 let right = x + bounds.size.width.0; let bottom = y + bounds.size.height.0;
5758 let outline = crate::VnClipOutline {
5759 fill_rule: crate::VnFillRule::NonZero,
5760 verbs: vec![crate::VnPathVerb::MoveTo([x,y]), crate::VnPathVerb::LineTo([right,y]),
5761 crate::VnPathVerb::LineTo([right,bottom]), crate::VnPathVerb::LineTo([x,bottom]), crate::VnPathVerb::Close],
5762 };
5763 let m = self.element_transform.inverse().unwrap_or_else(TransformationMatrix::unit);
5764 Arc::new(crate::VnTextPaint {
5765 fill, bounds: [x, y, bounds.size.width.0, bounds.size.height.0],
5766 inverse: [m.rotation_scale[0][0], m.rotation_scale[0][1], m.rotation_scale[1][0], m.rotation_scale[1][1], m.translation[0], m.translation[1]],
5767 scale_factor: self.scale_factor,
5768 geometry: Arc::new(crate::VnClipGeometry::new(&outline, self.scale_factor, self.element_transform)),
5769 content_mask: self.snapped_content_mask(),
5770 })
5771 }
5772
5773 pub fn vn_with_text_mask<R>(&mut self, paint: Arc<crate::VnTextPaint>, f: impl FnOnce(&mut Self) -> R) -> R {
5776 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5777 geometry: paint.geometry.clone(), color_matrix: None,
5778 content_mask: paint.content_mask, text_paint: Some(paint), capture: None,
5779 });
5780 let result = f(self);
5781 self.next_frame.scene.vn_pop_isolation();
5782 result
5783 }
5784
5785 pub fn vn_with_mask<R>(
5791 &mut self,
5792 mask: Option<&crate::VnMask>,
5793 bounds: Bounds<Pixels>,
5794 cx: &mut App,
5795 f: impl FnOnce(&mut Self, &mut App) -> R,
5796 ) -> R {
5797 let Some(mask) = mask.filter(|mask| mask.paint.is_some()) else {
5798 return f(self, cx);
5799 };
5800 let node = Arc::new(crate::VnClipNode {
5801 geometry: self.vn_box_geometry(bounds),
5802 color_matrix: None,
5803 capture: None,
5804 mask: Some(crate::VnClipMask {
5805 mask: mask.clone(),
5806 bounds,
5807 transform: self.element_transform,
5808 }),
5809 parent: self.vn_clip_stack.clone(),
5810 });
5811 let previous = self.vn_clip_stack.replace(node.clone());
5812 let result = if self.invalidator.is_painting() {
5813 let content_mask = self.snapped_content_mask();
5814 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5815 geometry: node.geometry.clone(),
5816 color_matrix: None,
5817 text_paint: None,
5818 content_mask,
5819 capture: None,
5820 });
5821 let result = f(self, cx);
5822 self.vn_paint_mask(&node, cx);
5823 self.next_frame.scene.vn_pop_isolation();
5824 result
5825 } else {
5826 f(self, cx)
5827 };
5828 self.vn_clip_stack = previous;
5829 result
5830 }
5831
5832 fn vn_paint_mask(&mut self, node: &crate::VnClipNode, cx: &mut App) {
5834 let Some(clip) = &node.mask else { return };
5835 let Some(paint) = clip.mask.paint.clone() else { return };
5836 self.next_frame.scene.vn_begin_mask(clip.mask.luminance);
5837 let opacity = mem::replace(&mut self.element_opacity, 1.);
5840 let tint = mem::replace(&mut self.element_image_tint, Hsla::transparent_black());
5841 let transform = mem::replace(&mut self.element_transform, clip.transform);
5842 paint(clip.bounds, None, self, cx);
5843 self.element_opacity = opacity;
5844 self.element_image_tint = tint;
5845 self.element_transform = transform;
5846 }
5847
5848 fn vn_box_geometry(&self, bounds: Bounds<Pixels>) -> Arc<crate::VnClipGeometry> {
5850 let (x, y) = (bounds.origin.x.0, bounds.origin.y.0);
5851 let (right, bottom) = (x + bounds.size.width.0, y + bounds.size.height.0);
5852 let outline = crate::VnClipOutline {
5853 fill_rule: crate::VnFillRule::NonZero,
5854 verbs: vec![
5855 crate::VnPathVerb::MoveTo([x, y]),
5856 crate::VnPathVerb::LineTo([right, y]),
5857 crate::VnPathVerb::LineTo([right, bottom]),
5858 crate::VnPathVerb::LineTo([x, bottom]),
5859 crate::VnPathVerb::Close,
5860 ],
5861 };
5862 Arc::new(crate::VnClipGeometry::new(
5863 &outline,
5864 self.scale_factor,
5865 self.element_transform,
5866 ))
5867 }
5868
5869 fn vn_with_clip_layer<R>(
5872 &mut self,
5873 node: &Arc<crate::VnClipNode>,
5874 f: impl FnOnce(&mut Self) -> R,
5875 ) -> R {
5876 if !self.invalidator.is_painting() {
5877 return f(self);
5878 }
5879 let content_mask = self.snapped_content_mask();
5880 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5881 geometry: node.geometry.clone(),
5882 color_matrix: node.color_matrix,
5883 text_paint: None,
5884 content_mask,
5885 capture: node.capture,
5886 });
5887 let result = f(self);
5888 self.next_frame.scene.vn_pop_isolation();
5889 result
5890 }
5891
5892 fn vn_with_absolute_clip_stack<R>(
5895 &mut self,
5896 clip: Option<Arc<crate::VnClipNode>>,
5897 f: impl FnOnce(&mut Self) -> R,
5898 ) -> R {
5899 let previous = mem::replace(&mut self.vn_clip_stack, clip);
5900 let result = f(self);
5901 self.vn_clip_stack = previous;
5902 result
5903 }
5904
5905 fn vn_reopen_clip_layers<R>(
5911 &mut self,
5912 clip: Option<Arc<crate::VnClipNode>>,
5913 base: Option<&Arc<crate::VnClipNode>>,
5914 cx: &mut App,
5915 f: impl FnOnce(&mut Self, &mut App) -> R,
5916 ) -> R {
5917 let Some(innermost) = clip.clone() else {
5918 return self.vn_with_absolute_clip_stack(None, |window| f(window, cx));
5919 };
5920 let chain = crate::VnClipNode::inside_of(&innermost, base);
5921 self.vn_with_absolute_clip_stack(clip, |window| {
5922 for node in &chain {
5923 let content_mask = window.snapped_content_mask();
5924 window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5925 geometry: node.geometry.clone(),
5926 color_matrix: node.color_matrix,
5927 text_paint: None,
5928 content_mask,
5929 capture: node.capture,
5930 });
5931 }
5932 let result = f(window, cx);
5933 for node in chain.iter().rev() {
5934 window.vn_paint_mask(node, cx);
5935 window.next_frame.scene.vn_pop_isolation();
5936 }
5937 result
5938 })
5939 }
5940
5941 pub fn vn_with_capture<R>(
5947 &mut self,
5948 id: Option<u64>,
5949 bounds: Bounds<Pixels>,
5950 own: TransformationMatrix,
5951 f: impl FnOnce(&mut Self) -> R,
5952 ) -> R {
5953 let Some(id) = id else { return f(self) };
5954 let scale_factor = self.scale_factor();
5955 let viewport = Bounds { origin: Point::default(), size: self.viewport_size };
5956 let device = viewport.scale(scale_factor);
5957 let info = crate::VnCaptureInfo {
5958 id,
5959 border_box: bounds.scale(scale_factor),
5960 transform: self.element_transform.compose(own),
5961 };
5962 let node = Arc::new(crate::VnClipNode {
5963 geometry: Arc::new(crate::VnClipGeometry::rect(device)),
5964 color_matrix: None,
5965 capture: Some(info),
5966 mask: None,
5967 parent: None,
5968 });
5969 let previous_clip = self.vn_clip_stack.replace(node.clone());
5970 self.content_mask_stack.push(ContentMask::rect(viewport));
5971 let result = self.with_absolute_element_transform(TransformationMatrix::unit(), |window| {
5972 window.with_absolute_element_opacity(1., |window| {
5973 if !window.invalidator.is_painting() {
5974 return f(window);
5975 }
5976 window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5977 geometry: node.geometry.clone(),
5978 color_matrix: None,
5979 text_paint: None,
5980 content_mask: ContentMask { bounds: device, corner_radii: Default::default() },
5981 capture: Some(info),
5982 });
5983 let result = f(window);
5984 window.next_frame.scene.vn_pop_isolation();
5985 result
5986 })
5987 });
5988 self.content_mask_stack.pop();
5989 self.vn_clip_stack = previous_clip;
5990 result
5991 }
5992
5993 pub fn vn_with_isolation<R>(&mut self, isolate: bool, f: impl FnOnce(&mut Self) -> R) -> R {
5996 if !isolate || !self.invalidator.is_painting() {
5997 return f(self);
5998 }
5999 let device = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6000 let content_mask = self.snapped_content_mask();
6001 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
6002 geometry: Arc::new(crate::VnClipGeometry::rect(device)),
6003 color_matrix: None,
6004 text_paint: None,
6005 content_mask,
6006 capture: None,
6007 });
6008 let result = f(self);
6009 self.next_frame.scene.vn_pop_isolation();
6010 result
6011 }
6012
6013 pub fn vn_paint_snapshot(&mut self, id: u64, bounds: Bounds<Pixels>, plus_lighter: bool) {
6018 self.invalidator.debug_assert_paint();
6019 let scale_factor = self.scale_factor();
6020 let device = bounds.scale(scale_factor);
6021 if device.size.width.0 <= 0. || device.size.height.0 <= 0. {
6022 return;
6023 }
6024 let Some(inverse) = self.element_transform.inverse() else { return };
6025 let (w, h) = (device.size.width.0, device.size.height.0);
6026 let [[a, b], [c, d]] = inverse.rotation_scale;
6027 let [tx, ty] = inverse.translation;
6028 let (x, y) = (device.origin.x.0, device.origin.y.0);
6029 let to_unit = [a / w, b / w, (tx - x) / w, c / h, d / h, (ty - y) / h];
6030 let covered = crate::scene::transformed_bounds(device, self.element_transform);
6031 let covered = Bounds::from_corners(
6032 point(ScaledPixels(covered.origin.x.0.floor()), ScaledPixels(covered.origin.y.0.floor())),
6033 point(
6034 ScaledPixels((covered.origin.x.0 + covered.size.width.0).ceil()),
6035 ScaledPixels((covered.origin.y.0 + covered.size.height.0).ceil()),
6036 ),
6037 );
6038 let opacity = self.element_opacity;
6039 let content_mask = self.snapped_content_mask();
6040 self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
6041 id,
6042 to_unit,
6043 bounds: covered,
6044 content_mask,
6045 opacity,
6046 plus_lighter,
6047 in_place: false,
6048 });
6049 }
6050
6051 pub fn vn_paint_snapshot_in_place(&mut self, id: u64) {
6054 self.invalidator.debug_assert_paint();
6055 let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6056 let opacity = self.element_opacity;
6057 let content_mask = self.snapped_content_mask();
6058 self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
6059 id,
6060 to_unit: [0.; 6],
6061 bounds: viewport,
6062 content_mask,
6063 opacity,
6064 plus_lighter: false,
6065 in_place: true,
6066 });
6067 }
6068
6069 pub fn vn_capture(&self, id: u64) -> Option<crate::VnCaptureInfo> {
6072 self.vn_capture_records.get(&id).map(|(info, _)| *info)
6073 }
6074
6075 pub fn vn_forget_captures(&mut self, ids: &[u64]) {
6078 for id in ids {
6079 self.vn_capture_records.remove(id);
6080 }
6081 }
6082
6083 pub fn vn_supports_snapshots(&self) -> bool {
6086 self.platform_window.vn_supports_snapshots()
6087 }
6088
6089 fn vn_settle_captures(&mut self) {
6090 let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6091 let scene = &mut self.next_frame.scene;
6092 for capture in &mut scene.vn_captures {
6093 capture.ink = capture.ink.intersect(&viewport);
6094 self.vn_capture_records.insert(capture.info.id, (capture.info, capture.ink));
6095 }
6096 let records = &self.vn_capture_records;
6097 scene.vn_resolve_snapshots(|id| records.get(&id).copied());
6098 }
6099
6100 pub fn with_element_offset<R>(
6103 &mut self,
6104 offset: Point<Pixels>,
6105 f: impl FnOnce(&mut Self) -> R,
6106 ) -> R {
6107 self.invalidator.debug_assert_prepaint();
6108
6109 if offset.is_zero() {
6110 return f(self);
6111 };
6112
6113 let abs_offset = self.element_offset() + offset;
6114 self.with_absolute_element_offset(abs_offset, f)
6115 }
6116
6117 pub fn with_absolute_element_offset<R>(
6121 &mut self,
6122 offset: Point<Pixels>,
6123 f: impl FnOnce(&mut Self) -> R,
6124 ) -> R {
6125 self.invalidator.debug_assert_prepaint();
6126 self.element_offset_stack.push(offset);
6127 let result = f(self);
6128 self.element_offset_stack.pop();
6129 result
6130 }
6131
6132 pub(crate) fn with_element_opacity<R>(
6133 &mut self,
6134 opacity: Option<f32>,
6135 f: impl FnOnce(&mut Self) -> R,
6136 ) -> R {
6137 self.invalidator.debug_assert_paint_or_prepaint();
6138
6139 let Some(opacity) = opacity else {
6140 return f(self);
6141 };
6142
6143 let previous_opacity = self.element_opacity;
6144 self.element_opacity = previous_opacity * opacity;
6145 let result = f(self);
6146 self.element_opacity = previous_opacity;
6147 result
6148 }
6149
6150 pub fn with_image_tint<R>(&mut self, tint: Hsla, f: impl FnOnce(&mut Self) -> R) -> R {
6161 self.invalidator.debug_assert_paint_or_prepaint();
6162 let previous = std::mem::replace(&mut self.element_image_tint, tint);
6163 let result = f(self);
6164 self.element_image_tint = previous;
6165 result
6166 }
6167
6168 pub fn with_absolute_element_transform<R>(
6191 &mut self,
6192 transformation: TransformationMatrix,
6193 f: impl FnOnce(&mut Self) -> R,
6194 ) -> R {
6195 let previous = mem::replace(&mut self.element_transform, transformation);
6196 let result = f(self);
6197 self.element_transform = previous;
6198 result
6199 }
6200
6201 fn with_absolute_element_opacity<R>(
6204 &mut self,
6205 opacity: f32,
6206 f: impl FnOnce(&mut Self) -> R,
6207 ) -> R {
6208 let previous = mem::replace(&mut self.element_opacity, opacity);
6209 let result = f(self);
6210 self.element_opacity = previous;
6211 result
6212 }
6213
6214 pub fn with_element_transform<R>(
6218 &mut self,
6219 transformation: TransformationMatrix,
6220 f: impl FnOnce(&mut Self) -> R,
6221 ) -> R {
6222 if transformation.is_unit() {
6223 return f(self);
6224 }
6225 let previous = self.element_transform;
6226 self.element_transform = previous.compose(transformation);
6229 let result = f(self);
6230 self.element_transform = previous;
6231 result
6232 }
6233
6234 pub fn content_mask_in_element_space(&self) -> ContentMask<Pixels> {
6246 let mask = self.content_mask();
6247 if self.element_transform.is_unit() {
6248 return mask;
6249 }
6250 match self.element_transform.inverse() {
6251 Some(inverse) => transform_mask(inverse, mask, self.scale_factor),
6252 None => ContentMask::rect(Bounds::default()),
6253 }
6254 }
6255
6256 #[inline]
6259 pub fn element_transform(&self) -> TransformationMatrix {
6260 self.element_transform
6261 }
6262
6263 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
6269 self.invalidator.debug_assert_prepaint();
6270 let index = self.prepaint_index();
6271 let result = f(self);
6272 if result.is_err() {
6273 self.next_frame.hitboxes.truncate(index.hitboxes_index);
6274 self.next_frame
6277 .vn_tagged_hitboxes
6278 .truncate(index.vn_tagged_hitboxes_index);
6279 self.next_frame
6280 .tooltip_requests
6281 .truncate(index.tooltips_index);
6282 self.next_frame
6283 .deferred_draws
6284 .truncate(index.deferred_draws_index);
6285 self.next_frame
6286 .dispatch_tree
6287 .truncate(index.dispatch_tree_index);
6288 self.next_frame
6289 .accessed_element_states
6290 .truncate(index.accessed_element_states_index);
6291 self.text_system.truncate_layouts(index.line_layout_index);
6292 }
6293 result
6294 }
6295
6296 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
6302 self.invalidator.debug_assert_prepaint();
6303 self.requested_autoscroll = Some(bounds);
6304 }
6305
6306 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
6309 self.invalidator.debug_assert_prepaint();
6310 self.requested_autoscroll.take()
6311 }
6312
6313 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
6319 cx.asset_entry::<A>(source).use_by(self.current_view())
6320 }
6321
6322 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
6328 cx.fetch_asset::<A>(source)
6329 }
6330 pub fn element_offset(&self) -> Point<Pixels> {
6333 self.invalidator.debug_assert_prepaint();
6334 self.element_offset_stack
6335 .last()
6336 .copied()
6337 .unwrap_or_default()
6338 }
6339
6340 #[inline]
6343 pub(crate) fn element_opacity(&self) -> f32 {
6344 self.invalidator.debug_assert_paint_or_prepaint();
6345 self.element_opacity
6346 }
6347
6348 pub fn content_mask(&self) -> ContentMask<Pixels> {
6350 self.invalidator.debug_assert_paint_or_prepaint();
6351 self.content_mask_stack
6352 .last()
6353 .cloned()
6354 .unwrap_or_else(|| {
6355 ContentMask::rect(Bounds {
6356 origin: Point::default(),
6357 size: self.viewport_size,
6358 })
6359 })
6360 }
6361
6362 pub fn with_element_namespace<R>(
6365 &mut self,
6366 element_id: impl Into<ElementId>,
6367 f: impl FnOnce(&mut Self) -> R,
6368 ) -> R {
6369 self.element_id_stack.push(element_id.into());
6370 let result = f(self);
6371 self.element_id_stack.pop();
6372 result
6373 }
6374
6375 pub fn use_keyed_state<S: 'static>(
6377 &mut self,
6378 key: impl Into<ElementId>,
6379 cx: &mut App,
6380 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
6381 ) -> Entity<S> {
6382 let current_view = self.current_view();
6383 self.with_global_id(key.into(), |global_id, window| {
6384 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
6385 if let Some(state) = state {
6386 (state.clone(), state)
6387 } else {
6388 let new_state = cx.new(|cx| init(window, cx));
6389 Self::observe_keyed_state(&new_state, current_view, cx);
6390 (new_state.clone(), new_state)
6391 }
6392 })
6393 })
6394 }
6395
6396 #[track_caller]
6402 pub fn use_state<S: 'static>(
6403 &mut self,
6404 cx: &mut App,
6405 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
6406 ) -> Entity<S> {
6407 self.use_keyed_state(
6408 ElementId::CodeLocation(*core::panic::Location::caller()),
6409 cx,
6410 init,
6411 )
6412 }
6413
6414 #[inline(always)]
6419 pub fn with_element_state<S, R>(
6420 &mut self,
6421 global_id: &GlobalElementId,
6422 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
6423 ) -> R
6424 where
6425 S: 'static,
6426 {
6427 self.invalidator.debug_assert_paint_or_prepaint();
6428
6429 let (key, state) = self.take_element_state(global_id, TypeId::of::<S>());
6430
6431 if let Some(any) = state {
6432 let ElementStateBox {
6433 inner,
6434 #[cfg(debug_assertions)]
6435 type_name,
6436 } = any;
6437 let mut state_box = inner
6439 .downcast::<Option<S>>()
6440 .map_err(|_| {
6441 #[cfg(debug_assertions)]
6442 {
6443 anyhow::anyhow!(
6444 "invalid element state type for id, requested {:?}, actual: {:?}",
6445 std::any::type_name::<S>(),
6446 type_name
6447 )
6448 }
6449
6450 #[cfg(not(debug_assertions))]
6451 {
6452 anyhow::anyhow!(
6453 "invalid element state type for id, requested {:?}",
6454 std::any::type_name::<S>(),
6455 )
6456 }
6457 })
6458 .unwrap();
6459
6460 let state = state_box.take().expect(
6461 "reentrant call to with_element_state for the same state type and element id",
6462 );
6463 let (result, state) = f(Some(state), self);
6464 state_box.replace(state);
6465 self.insert_element_state(
6466 key,
6467 ElementStateBox {
6468 inner: state_box,
6469 #[cfg(debug_assertions)]
6470 type_name,
6471 },
6472 );
6473 result
6474 } else {
6475 let (result, state) = f(None, self);
6476 self.insert_element_state(
6477 key,
6478 ElementStateBox {
6479 inner: Box::new(Some(state)),
6480 #[cfg(debug_assertions)]
6481 type_name: std::any::type_name::<S>(),
6482 },
6483 );
6484 result
6485 }
6486 }
6487
6488 pub fn with_optional_element_state<S, R>(
6495 &mut self,
6496 global_id: Option<&GlobalElementId>,
6497 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
6498 ) -> R
6499 where
6500 S: 'static,
6501 {
6502 self.invalidator.debug_assert_paint_or_prepaint();
6503
6504 if let Some(global_id) = global_id {
6505 self.with_element_state(global_id, |state, cx| {
6506 let (result, state) = f(Some(state), cx);
6507 let state =
6508 state.expect("you must return some state when you pass some element id");
6509 (result, state)
6510 })
6511 } else {
6512 let (result, state) = f(None, self);
6513 debug_assert!(
6514 state.is_none(),
6515 "you must not return an element state when passing None for the global id"
6516 );
6517 result
6518 }
6519 }
6520
6521 #[inline]
6523 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
6524 if let Some(index) = index {
6525 self.next_frame.tab_stops.begin_group(index);
6526 let result = f(self);
6527 self.next_frame.tab_stops.end_group();
6528 result
6529 } else {
6530 f(self)
6531 }
6532 }
6533
6534 pub fn defer_draw(
6543 &mut self,
6544 element: AnyElement,
6545 absolute_offset: Point<Pixels>,
6546 priority: usize,
6547 content_mask: Option<ContentMask<Pixels>>,
6548 ) {
6549 self.defer_draw_with_stack_key(element, absolute_offset, priority, content_mask, None)
6550 }
6551
6552 pub fn defer_draw_with_stack_key(
6555 &mut self,
6556 element: AnyElement,
6557 absolute_offset: Point<Pixels>,
6558 priority: usize,
6559 content_mask: Option<ContentMask<Pixels>>,
6560 stack_key: Option<Rc<[u128]>>,
6561 ) {
6562 self.invalidator.debug_assert_prepaint();
6563 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
6564 self.next_frame.deferred_draws.push(DeferredDraw {
6565 current_view: self.current_view(),
6566 parent_node,
6567 element_id_stack: self.element_id_stack.clone(),
6568 text_style_stack: self.text_style_stack.clone(),
6569 content_mask,
6570 rem_size: self.rem_size(),
6571 priority,
6572 element: Some(element),
6573 absolute_offset,
6574 element_transform: self.element_transform,
6575 a11y_parent: self
6576 .a11y
6577 .is_active()
6578 .then(|| self.a11y.nodes.current_id()),
6579 vn_stack: stack_key,
6580 element_opacity: self.element_opacity,
6581 vn_clip: if content_mask.is_some() {
6582 self.vn_clip_stack.clone()
6583 } else {
6584 crate::VnClipNode::color_filters(&self.vn_clip_stack)
6585 },
6586 vn_scope: self.vn_defer_scope.clone(),
6587 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
6588 paint_range: PaintIndex::default()..PaintIndex::default(),
6589 accessed_entities: FxHashSet::default(),
6590 });
6591 }
6592
6593 pub fn paint_layer<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
6602 self.invalidator.debug_assert_paint();
6603
6604 self.next_frame.scene.push_layer();
6605 let result = f(self);
6606 self.next_frame.scene.pop_layer();
6607 result
6608 }
6609
6610 pub fn paint_drop_shadows(
6621 &mut self,
6622 bounds: Bounds<Pixels>,
6623 corner_radii: Corners<Pixels>,
6624 shadows: &[BoxShadow],
6625 ) {
6626 self.paint_outer_shadows(bounds, corner_radii, shadows, SHADOW_OUTSIDE_BOX);
6627 }
6628
6629 pub fn paint_drop_shadows_under_box(
6633 &mut self,
6634 bounds: Bounds<Pixels>,
6635 corner_radii: Corners<Pixels>,
6636 shadows: &[BoxShadow],
6637 ) {
6638 self.paint_outer_shadows(bounds, corner_radii, shadows, SHADOW_UNDER_BOX);
6639 }
6640
6641 fn paint_outer_shadows(
6642 &mut self,
6643 bounds: Bounds<Pixels>,
6644 corner_radii: Corners<Pixels>,
6645 shadows: &[BoxShadow],
6646 kind: u32,
6647 ) {
6648 self.invalidator.debug_assert_paint();
6649
6650 let scale_factor = self.scale_factor();
6651 let content_mask = self.snapped_content_mask();
6652 let opacity = self.element_opacity();
6653 let element_bounds = self.cover_bounds(bounds);
6654 let element_corner_radii = corner_radii.scale(scale_factor);
6655 for shadow in shadows {
6656 if shadow.inset {
6657 continue;
6658 }
6659 let shape_bounds =
6660 self.cover_bounds((bounds + shadow.offset).dilate(shadow.spread_radius));
6661 if shape_bounds.is_empty() {
6662 continue;
6663 }
6664 let blur_radius = shadow.blur_radius.scale(scale_factor);
6665 let spread = shadow.spread_radius;
6666 let shadow_radius = |r: Pixels| spread_shadow_radius(r, spread);
6667 let shadow_corner_radii = Corners {
6668 top_left: shadow_radius(corner_radii.top_left),
6669 top_right: shadow_radius(corner_radii.top_right),
6670 bottom_right: shadow_radius(corner_radii.bottom_right),
6671 bottom_left: shadow_radius(corner_radii.bottom_left),
6672 };
6673 self.next_frame.scene.insert_primitive(Shadow {
6674 order: 0,
6675 blur_radius,
6676 bounds: shape_bounds.dilate(blur_radius * 3.),
6678 content_mask,
6679 corner_radii: element_corner_radii,
6680 color: shadow.color.opacity(opacity),
6681 shape_bounds,
6682 shape_corner_radii: shadow_corner_radii.scale(scale_factor),
6683 inset: kind,
6684 pad: 0,
6685 transformation: self.element_transform,
6686 element_bounds,
6687 });
6688 }
6689 }
6690
6691 pub fn paint_inset_shadows(
6695 &mut self,
6696 bounds: Bounds<Pixels>,
6697 corner_radii: Corners<Pixels>,
6698 shadows: &[BoxShadow],
6699 ) {
6700 self.invalidator.debug_assert_paint();
6701
6702 let scale_factor = self.scale_factor();
6703 let content_mask = self.snapped_content_mask();
6704 let opacity = self.element_opacity();
6705 let element_bounds = self.cover_bounds(bounds);
6706 let element_corner_radii = corner_radii.scale(scale_factor);
6707 for shadow in shadows {
6708 if !shadow.inset {
6709 continue;
6710 }
6711 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
6712 let zero = Pixels::ZERO;
6715 let hole_corner_radii = Corners {
6716 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
6717 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
6718 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
6719 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
6720 };
6721 self.next_frame.scene.insert_primitive(Shadow {
6722 order: 0,
6723 blur_radius: shadow.blur_radius.scale(scale_factor),
6724 bounds: element_bounds,
6725 content_mask,
6726 corner_radii: element_corner_radii,
6727 color: shadow.color.opacity(opacity),
6728 shape_bounds: self.cover_bounds(hole),
6729 shape_corner_radii: hole_corner_radii.scale(scale_factor),
6730 inset: SHADOW_INSET,
6731 pad: 0,
6732 transformation: self.element_transform,
6733 element_bounds,
6734 });
6735 }
6736 }
6737
6738 fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
6739 let size = quad.bounds.size;
6740 let diagonal = (size.width.0 * size.width.0 + size.height.0 * size.height.0).sqrt();
6741 if diagonal == 0. {
6742 return Bounds::default();
6743 }
6744 let cos = size.height.0 / diagonal;
6748 let sin = size.width.0 / diagonal;
6749
6750 let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| {
6753 point(
6754 width_x.max(radius - (radius - width_x) * cos),
6755 width_y.max(radius - (radius - width_y) * sin),
6756 )
6757 };
6758
6759 let radii = &quad.corner_radii;
6760 let widths = &quad.border_widths;
6761 let top_left = corner_inset(radii.top_left, widths.left, widths.top);
6762 let top_right = corner_inset(radii.top_right, widths.right, widths.top);
6763 let bottom_right = corner_inset(radii.bottom_right, widths.right, widths.bottom);
6764 let bottom_left = corner_inset(radii.bottom_left, widths.left, widths.bottom);
6765
6766 let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
6767 Bounds::from_corners(
6768 quad.bounds.origin
6769 + point(top_left.x.max(bottom_left.x), top_left.y.max(top_right.y))
6770 + antialias_inset,
6771 quad.bounds.bottom_right()
6772 - point(
6773 top_right.x.max(bottom_right.x),
6774 bottom_left.y.max(bottom_right.y),
6775 )
6776 - antialias_inset,
6777 )
6778 }
6779
6780 pub fn paint_quad(&mut self, quad: PaintQuad) {
6790 self.invalidator.debug_assert_paint();
6791
6792 let opacity = self.element_opacity();
6793 let snapped_bounds = self.snap_bounds(quad.bounds);
6794 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
6795 let quad = Quad {
6796 order: 0,
6797 bounds: snapped_bounds,
6798 content_mask: self.snapped_content_mask(),
6799 background: quad.background.opacity(opacity),
6800 border_color: quad.border_color.opacity(opacity),
6801 corner_radii: quad.corner_radii.scale(self.scale_factor()),
6802 border_widths: snapped_border_widths,
6803 border_style: quad.border_style,
6804 transformation: self.element_transform,
6805 };
6806 self.insert_quad(quad);
6807 }
6808
6809 fn insert_quad(&mut self, quad: Quad) {
6810 let has_background = !quad.background.is_transparent();
6811 let has_border =
6812 quad.border_widths != Edges::default() && !quad.border_color.is_transparent();
6813 if !has_background && !has_border {
6814 return;
6815 }
6816
6817 let is_rectangle =
6818 quad.border_widths == Edges::default() && quad.corner_radii == Corners::default();
6819 if has_background && is_rectangle {
6820 self.next_frame.scene.insert_primitive(quad);
6821 return;
6822 }
6823
6824 if !quad.transformation.is_unit() || quad.content_mask.is_rounded() {
6831 self.next_frame.scene.insert_primitive(quad);
6832 return;
6833 }
6834
6835 let plain_border = quad.corner_radii == Corners::default()
6836 && quad.border_style == BorderStyle::Solid
6837 && (!has_background || quad.border_color.is_opaque());
6838
6839 let outer_bounds = quad.bounds;
6842 let inner_bounds = if plain_border {
6843 quad.bounds.extend(quad.border_widths.map(|width| -*width))
6844 } else {
6845 Self::largest_border_interior(&quad)
6846 };
6847
6848 let strip_quad = if plain_border {
6852 Quad {
6853 background: quad.border_color.into(),
6854 border_widths: Edges::default(),
6855 ..quad
6856 }
6857 } else {
6858 quad
6859 };
6860
6861 if inner_bounds.is_empty() {
6862 self.next_frame.scene.insert_primitive(strip_quad);
6863 return;
6864 }
6865
6866 if has_background && !quad.background.is_ring() {
6868 self.next_frame.scene.insert_primitive(Quad {
6869 content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&inner_bounds)),
6870 border_widths: Edges::default(),
6871 corner_radii: Corners::default(),
6872 ..quad
6873 });
6874 }
6875
6876 let strips = [
6877 Bounds::from_corners(
6879 outer_bounds.origin,
6880 point(outer_bounds.right(), inner_bounds.top()),
6881 ),
6882 Bounds::from_corners(
6884 point(outer_bounds.left(), inner_bounds.bottom()),
6885 outer_bounds.bottom_right(),
6886 ),
6887 Bounds::from_corners(
6889 point(outer_bounds.left(), inner_bounds.top()),
6890 inner_bounds.bottom_left(),
6891 ),
6892 Bounds::from_corners(
6894 inner_bounds.top_right(),
6895 point(outer_bounds.right(), inner_bounds.bottom()),
6896 ),
6897 ];
6898
6899 for strip in strips {
6900 self.next_frame.scene.insert_primitive(Quad {
6901 content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&strip)),
6902 ..strip_quad
6903 });
6904 }
6905 }
6906
6907 pub fn paint_backdrop_blur_rect(
6922 &mut self,
6923 bounds: Bounds<Pixels>,
6924 corner_radii: Corners<Pixels>,
6925 effect: BackdropBlurEffect,
6926 ) {
6927 self.invalidator.debug_assert_paint();
6928
6929 let opacity = self.element_opacity();
6930 if opacity <= 0. {
6931 return;
6932 }
6933
6934 let scale_factor = self.scale_factor();
6935 let blur_radius = effect.radius.scale(scale_factor);
6936 if blur_radius.0 <= 0. {
6937 let tint = effect.tint.opacity(opacity);
6938 if tint.a > 0. {
6939 self.paint_quad(fill(bounds, tint).corner_radii(corner_radii));
6940 }
6941 return;
6942 }
6943
6944 let Some((bounds, k)) =
6950 crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
6951 else {
6952 return;
6953 };
6954 self.next_frame.scene.insert_primitive(BackdropBlurRect {
6955 order: 0,
6956 pad: 0,
6957 bounds,
6958 content_mask: self.snapped_content_mask(),
6959 corner_radii: corner_radii.scale(scale_factor * k),
6960 blur_radius,
6961 opacity,
6962 tint: effect.tint,
6963 });
6964 }
6965
6966 pub fn paint_effect_quad(
6987 &mut self,
6988 bounds: Bounds<Pixels>,
6989 corner_radii: Corners<Pixels>,
6990 spec: EffectSpec,
6991 ) {
6992 self.vn_paint_effect(bounds, corner_radii, spec, 0);
6993 }
6994
6995 pub fn vn_paint_effect(
6998 &mut self,
6999 bounds: Bounds<Pixels>,
7000 corner_radii: Corners<Pixels>,
7001 spec: EffectSpec,
7002 element: u64,
7003 ) {
7004 self.vn_paint_effect_with(bounds, corner_radii, spec, element, None);
7005 }
7006
7007 pub fn vn_paint_textured_effect(
7010 &mut self,
7011 bounds: Bounds<Pixels>,
7012 corner_radii: Corners<Pixels>,
7013 spec: EffectSpec,
7014 element: u64,
7015 cx: &mut App,
7016 ) {
7017 let textures = crate::resolve_effect_textures(&spec, self, cx);
7018 self.vn_paint_effect_with(bounds, corner_radii, spec, element, textures);
7019 }
7020
7021 fn vn_paint_effect_with(
7022 &mut self,
7023 bounds: Bounds<Pixels>,
7024 corner_radii: Corners<Pixels>,
7025 spec: EffectSpec,
7026 element: u64,
7027 textures: Option<Arc<crate::EffectTextureSet>>,
7028 ) {
7029 self.invalidator.debug_assert_paint();
7030 let opacity = self.element_opacity();
7031 let Some(mut quad) =
7032 self.vn_effect_quad(bounds, corner_radii, spec, element, opacity, textures.as_deref())
7033 else {
7034 return;
7035 };
7036 quad.flags &= !crate::EFFECT_FLAG_NEEDS_CONTENT;
7037 let history = vn_history_key(element, &spec);
7038 if history == 0 {
7039 quad.flags &= !crate::EFFECT_FLAG_HISTORY;
7040 self.next_frame
7041 .scene
7042 .insert_primitive(crate::Primitive::EffectQuad(quad, textures));
7043 return;
7044 }
7045 let content_mask = quad.content_mask;
7046 self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
7047 draws: vec![crate::VnEffectDraw {
7048 quad,
7049 history,
7050 textures,
7051 }],
7052 content: false,
7053 content_mask,
7054 });
7055 self.next_frame.scene.vn_pop_isolation();
7056 }
7057
7058 pub fn vn_set_effect_element(&mut self, id: Option<&GlobalElementId>) {
7061 self.vn_effect_element = vn_element_key(id);
7062 }
7063
7064 pub fn vn_take_effect_element(&mut self) -> u64 {
7067 mem::take(&mut self.vn_effect_element)
7068 }
7069
7070 pub fn vn_with_effect_content<R>(
7074 &mut self,
7075 bounds: Bounds<Pixels>,
7076 corner_radii: Corners<Pixels>,
7077 effects: &[(EffectSpec, f32, Option<Arc<crate::EffectTextureSet>>)],
7078 element: u64,
7079 cx: &mut App,
7080 f: impl FnOnce(&mut Self, &mut App) -> R,
7081 ) -> R {
7082 let opacity = self.element_opacity();
7083 if !self.invalidator.is_painting() || opacity <= 0. {
7084 return f(self, cx);
7085 }
7086 let mut draws = Vec::new();
7087 let mut plain = 1.;
7088 for (spec, weight, textures) in effects {
7089 if spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT == 0 || *weight <= 0. {
7090 continue;
7091 }
7092 let Some(mut quad) = self.vn_effect_quad(
7093 bounds,
7094 corner_radii,
7095 *spec,
7096 element,
7097 opacity * weight,
7098 textures.as_deref(),
7099 ) else {
7100 continue;
7101 };
7102 let history = vn_history_key(element, spec);
7103 if history == 0 {
7104 quad.flags &= !crate::EFFECT_FLAG_HISTORY;
7105 }
7106 plain -= weight;
7107 draws.push(crate::VnEffectDraw {
7108 quad,
7109 history,
7110 textures: textures.clone(),
7111 });
7112 }
7113 let content_mask = self.snapped_content_mask();
7114 if plain > 1e-3 {
7115 draws.insert(
7116 0,
7117 crate::VnEffectDraw {
7118 quad: EffectQuad {
7119 effect_id: crate::effect_id::CONTENT,
7120 bounds: content_mask.bounds,
7121 content_mask,
7122 opacity: opacity * plain.min(1.),
7123 scale: self.scale_factor(),
7124 flags: crate::EFFECT_FLAG_NEEDS_CONTENT,
7125 ..Default::default()
7126 },
7127 history: 0,
7128 textures: None,
7129 },
7130 );
7131 }
7132 self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
7133 draws,
7134 content: true,
7135 content_mask,
7136 });
7137 let outer = mem::replace(&mut self.element_opacity, 1.);
7138 let result = f(self, cx);
7139 self.vn_paint_scope(element, opacity, cx);
7140 self.element_opacity = outer;
7141 self.next_frame.scene.vn_pop_isolation();
7142 result
7143 }
7144
7145 fn vn_effect_quad(
7148 &mut self,
7149 bounds: Bounds<Pixels>,
7150 corner_radii: Corners<Pixels>,
7151 spec: EffectSpec,
7152 element: u64,
7153 opacity: f32,
7154 textures: Option<&crate::EffectTextureSet>,
7155 ) -> Option<EffectQuad> {
7156 if !spec.is_some() || opacity <= 0. {
7157 return None;
7158 }
7159
7160 let scale_factor = self.scale_factor();
7161 let bleed = px(spec.bleed());
7162 let draw_bounds = bounds.dilate(bleed);
7167 let draw_radii = Corners {
7168 top_left: corner_radii.top_left + bleed,
7169 top_right: corner_radii.top_right + bleed,
7170 bottom_right: corner_radii.bottom_right + bleed,
7171 bottom_left: corner_radii.bottom_left + bleed,
7172 };
7173
7174 let mut params = spec.params;
7175 for (index, param) in params.iter_mut().enumerate() {
7176 if spec.length_mask & (1 << index) != 0 {
7177 *param *= scale_factor;
7178 }
7179 }
7180 crate::write_effect_texture_sizes(&spec, textures, &mut params);
7181
7182 let Some((draw_bounds, k)) = crate::scene::axis_aligned_through(
7186 self.snap_bounds(draw_bounds),
7187 self.element_transform,
7188 ) else {
7189 return None;
7190 };
7191 let bleed = bleed.scale(scale_factor);
7192 let now = crate::effect_clock_seconds();
7193
7194 if let Some(slot) = spec.pointer_param.map(usize::from)
7195 && slot + 2 <= params.len()
7196 {
7197 let origin = draw_bounds.origin.map(|c| c.0 + bleed.0);
7199 let size = draw_bounds.size.map(|c| (c.0 - 2. * bleed.0).max(1.));
7200 let pointer = self.mouse_position.map(|c| c.0 * scale_factor);
7201 params[slot] = (pointer.x - origin.x) / size.width;
7202 params[slot + 1] = (pointer.y - origin.y) / size.height;
7203 }
7204 if let Some(slot) = spec.pointer_times_param.map(usize::from)
7205 && slot + 3 <= params.len()
7206 {
7207 let times = &self.vn_effect_pointer;
7208 params[slot..slot + 3].copy_from_slice(&[times.moved, times.entered, times.left]);
7209 }
7210 if spec.follows_pointer() {
7211 let view = self.current_view();
7212 self.vn_effect_pointer.views.insert(view);
7213 }
7214 if let Some(slot) = spec.animated_param.map(usize::from)
7215 && slot < params.len()
7216 && element != 0
7217 {
7218 let key = vn_phase_key(element, &spec);
7219 let previous = self.vn_effect_phases.get(&key).copied();
7220 let phase = VnEffectPhase::advance(previous, params[slot], now);
7221 self.vn_effect_phases.insert(key, phase);
7222 if let Some(speed) = phase.speed(now) {
7223 params[slot] = speed;
7224 }
7225 }
7226
7227 let mut clocked = spec;
7228 clocked.params = params;
7229 if spec.animated || clocked.clock_running(now) {
7230 self.request_animation_frame();
7232 }
7233
7234 Some(EffectQuad {
7235 order: 0,
7236 effect_id: spec.id,
7237 bounds: draw_bounds,
7238 content_mask: self.snapped_content_mask(),
7239 corner_radii: draw_radii.scale(scale_factor * k),
7240 params,
7241 opacity,
7242 time: now,
7243 bleed,
7244 backdrop_blur_radius: px(spec.backdrop_blur_radius()).scale(scale_factor),
7245 scale: scale_factor,
7246 flags: spec.flags,
7247 })
7248 }
7249
7250 pub fn vn_paint_punch(&mut self, bounds: Bounds<Pixels>, corner_radii: Corners<Pixels>) {
7259 self.invalidator.debug_assert_paint();
7260 let opacity = self.element_opacity();
7261 if opacity <= 0. {
7262 return;
7263 }
7264 let scale_factor = self.scale_factor();
7265 let Some((draw_bounds, k)) =
7268 crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
7269 else {
7270 return;
7271 };
7272 self.next_frame.scene.insert_primitive(EffectQuad {
7273 order: 0,
7274 effect_id: crate::effect_id::PUNCH,
7275 bounds: draw_bounds,
7276 content_mask: self.snapped_content_mask(),
7277 corner_radii: corner_radii.scale(scale_factor * k),
7278 params: [0.; crate::EFFECT_PARAM_SLOTS],
7279 opacity,
7280 time: 0.,
7281 bleed: ScaledPixels(0.),
7282 backdrop_blur_radius: ScaledPixels(0.),
7283 scale: scale_factor,
7284 flags: 0,
7285 });
7286 }
7287
7288 pub fn paint_path(&mut self, path: Path, color: impl Into<Background>) {
7292 self.invalidator.debug_assert_paint();
7293
7294 let scale_factor = self.scale_factor();
7295 let content_mask = self.content_mask();
7296 let opacity = self.element_opacity();
7297 let color: Background = color.into();
7298 let path = if self.element_transform.is_unit() {
7303 path
7304 } else {
7305 path.transformed(self.element_transform, scale_factor)
7306 };
7307 self.next_frame.scene.insert_primitive(PaintedPath::new(
7308 path,
7309 scale_factor,
7310 content_mask,
7311 color.opacity(opacity),
7312 ));
7313 }
7314
7315 pub fn paint_underline(
7319 &mut self,
7320 origin: Point<Pixels>,
7321 width: Pixels,
7322 style: &UnderlineStyle,
7323 ) {
7324 self.invalidator.debug_assert_paint();
7325 let underline = self.underline(origin, width, style);
7327 self.next_frame.scene.insert_primitive(underline);
7328 }
7329
7330 pub fn paint_strikethrough(
7334 &mut self,
7335 origin: Point<Pixels>,
7336 width: Pixels,
7337 style: &StrikethroughStyle,
7338 ) {
7339 self.invalidator.debug_assert_paint();
7340
7341 let scale_factor = self.scale_factor();
7342 let height = style.thickness;
7343 let bounds = Bounds {
7344 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
7345 size: size(self.snap_stroke(width), self.snap_stroke(height)),
7346 };
7347 let opacity = self.element_opacity();
7348
7349 self.next_frame.scene.insert_primitive(Underline {
7350 order: 0,
7351 pad: 0,
7352 bounds,
7353 content_mask: self.snapped_content_mask(),
7354 thickness: self.snap_stroke(style.thickness),
7355 color: style.color.unwrap_or_default().opacity(opacity),
7356 wavy: false.into(),
7357 transformation: self.element_transform,
7358 });
7359 }
7360
7361 pub fn paint_glyph(
7370 &mut self,
7371 origin: Point<Pixels>,
7372 font_id: FontId,
7373 glyph_id: GlyphId,
7374 font_size: Pixels,
7375 color: Hsla,
7376 ) -> Result<()> {
7377 self.invalidator.debug_assert_paint();
7378
7379 let element_opacity = self.element_opacity();
7380 let scale_factor = self.scale_factor();
7381 let glyph_origin = origin.scale(scale_factor);
7382
7383 let quantized_origin = Point::new(
7384 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
7385 / SUBPIXEL_VARIANTS_X as f32,
7386 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
7387 / SUBPIXEL_VARIANTS_Y as f32,
7388 );
7389 let subpixel_variant = Point::new(
7390 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
7391 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
7392 );
7393 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
7394 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
7395 let dilation = self.text_system().glyph_dilation_for_color(color);
7396 let params = RenderGlyphParams {
7397 font_id,
7398 glyph_id,
7399 font_size,
7400 subpixel_variant,
7401 scale_factor,
7402 is_emoji: false,
7403 subpixel_rendering,
7404 dilation,
7405 };
7406
7407 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
7408 if !raster_bounds.is_zero() {
7409 let tile = self
7410 .sprite_atlas
7411 .get_or_insert_with(params.clone().into(), &mut || {
7412 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
7413 Ok(Some((size, Cow::Owned(bytes))))
7414 })?
7415 .expect("Callback above only errors or returns Some");
7416 let bounds = Bounds {
7417 origin: integer_origin + raster_bounds.origin.map(Into::into),
7418 size: tile.bounds.size.map(Into::into),
7419 };
7420 let content_mask = self.snapped_content_mask();
7421
7422 if subpixel_rendering {
7423 self.next_frame.scene.insert_primitive(SubpixelSprite {
7424 order: 0,
7425 pad: 0,
7426 bounds,
7427 content_mask,
7428 color: color.opacity(element_opacity),
7429 tile,
7430 transformation: self.element_transform,
7431 });
7432 } else {
7433 self.next_frame.scene.insert_primitive(MonochromeSprite {
7434 order: 0,
7435 raw_coverage: false.into(),
7436 animation: SpriteAnimationId::NONE,
7437 pad: 0,
7438 bounds,
7439 content_mask,
7440 color: color.opacity(element_opacity),
7441 tile,
7442 transformation: self.element_transform,
7443 });
7444 }
7445 }
7446 Ok(())
7447 }
7448
7449 pub fn paint_glyph_shadow(
7452 &mut self,
7453 origin: Point<Pixels>,
7454 font_id: FontId,
7455 glyph_id: GlyphId,
7456 font_size: Pixels,
7457 is_emoji: bool,
7458 color: Hsla,
7459 blur_radius: Pixels,
7460 ) -> Result<()> {
7461 self.invalidator.debug_assert_paint();
7462 if blur_radius <= px(0.) && !is_emoji {
7463 return self.paint_glyph(origin, font_id, glyph_id, font_size, color);
7464 }
7465
7466 let scale_factor = self.scale_factor();
7467 let glyph_origin = origin.scale(scale_factor);
7468 let (integer_origin, subpixel_variant) = if is_emoji {
7469 (
7470 glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0))),
7471 Point::default(),
7472 )
7473 } else {
7474 let quantized_origin = Point::new(
7475 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
7476 / SUBPIXEL_VARIANTS_X as f32,
7477 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
7478 / SUBPIXEL_VARIANTS_Y as f32,
7479 );
7480 (
7481 quantized_origin.map(|c| ScaledPixels(c.trunc())),
7482 Point::new(
7483 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
7484 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
7485 ),
7486 )
7487 };
7488 let glyph = RenderGlyphParams {
7489 font_id,
7490 glyph_id,
7491 font_size,
7492 subpixel_variant,
7493 scale_factor,
7494 is_emoji,
7495 subpixel_rendering: false,
7496 dilation: if is_emoji {
7497 0
7498 } else {
7499 self.text_system().glyph_dilation_for_color(color)
7500 },
7501 };
7502 let raster_bounds = self.text_system().raster_bounds(&glyph)?;
7503 if raster_bounds.is_zero() {
7504 return Ok(());
7505 }
7506 let params = GlyphShadowParams {
7507 sigma_quarters: GlyphShadowParams::quantize_sigma(blur_radius.0 / 2. * scale_factor),
7508 glyph,
7509 };
7510 let padding = params.padding();
7511 let sigma = params.sigma();
7512 let Some(tile) = self.sprite_atlas.get_or_insert_with(
7513 AtlasKey::GlyphShadow(params.clone()),
7514 &mut || {
7515 let (size, coverage) = self.text_system().rasterize_glyph(¶ms.glyph)?;
7516 let (size, blurred) = blur_glyph_coverage(size, &coverage, sigma);
7517 Ok(Some((size, Cow::Owned(blurred))))
7518 },
7519 )?
7520 else {
7521 return Ok(());
7522 };
7523 let bounds = Bounds {
7524 origin: integer_origin
7525 + raster_bounds.origin.map(Into::into)
7526 - point(ScaledPixels(padding as f32), ScaledPixels(padding as f32)),
7527 size: tile.bounds.size.map(Into::into),
7528 };
7529 let content_mask = self.snapped_content_mask();
7530 self.next_frame.scene.insert_primitive(MonochromeSprite {
7531 order: 0,
7532 raw_coverage: true.into(),
7533 animation: SpriteAnimationId::NONE,
7534 pad: 0,
7535 bounds,
7536 content_mask,
7537 color: color.opacity(self.element_opacity()),
7538 tile,
7539 transformation: self.element_transform,
7540 });
7541 Ok(())
7542 }
7543
7544 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
7545 if !self.platform_window.is_subpixel_rendering_supported() {
7548 return false;
7549 }
7550 if self.next_frame.scene.vn_is_isolating() {
7554 return false;
7555 }
7556
7557 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
7558 return false;
7559 }
7560
7561 let mode = match self.text_rendering_mode.get() {
7562 TextRenderingMode::PlatformDefault => self
7563 .text_system()
7564 .recommended_rendering_mode(font_id, font_size),
7565 mode => mode,
7566 };
7567
7568 mode == TextRenderingMode::Subpixel
7569 }
7570
7571 pub fn paint_emoji(
7580 &mut self,
7581 origin: Point<Pixels>,
7582 font_id: FontId,
7583 glyph_id: GlyphId,
7584 font_size: Pixels,
7585 ) -> Result<()> {
7586 self.invalidator.debug_assert_paint();
7587
7588 let scale_factor = self.scale_factor();
7589 let glyph_origin = origin.scale(scale_factor);
7590 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
7591 let params = RenderGlyphParams {
7592 font_id,
7593 glyph_id,
7594 font_size,
7595 subpixel_variant: Default::default(),
7596 scale_factor,
7597 is_emoji: true,
7598 subpixel_rendering: false,
7599 dilation: 0,
7600 };
7601
7602 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
7603 if !raster_bounds.is_zero() {
7604 let tile = self
7605 .sprite_atlas
7606 .get_or_insert_with(params.clone().into(), &mut || {
7607 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
7608 Ok(Some((size, Cow::Owned(bytes))))
7609 })?
7610 .expect("Callback above only errors or returns Some");
7611
7612 let bounds = Bounds {
7613 origin: integer_origin + raster_bounds.origin.map(Into::into),
7614 size: tile.bounds.size.map(Into::into),
7615 };
7616 let content_mask = self.snapped_content_mask();
7617 let opacity = self.element_opacity();
7618
7619 self.next_frame.scene.insert_primitive(PolychromeSprite {
7620 order: 0,
7621 pad: 0,
7622 grayscale: false.into(),
7623 bounds,
7624 corner_radii: Default::default(),
7625 content_mask,
7626 tile,
7627 opacity,
7628 transformation: self.element_transform,
7629 tint: Hsla::transparent_black(),
7630 });
7631 }
7632 Ok(())
7633 }
7634
7635 pub fn paint_svg(
7639 &mut self,
7640 bounds: Bounds<Pixels>,
7641 path: SharedString,
7642 data: Option<&[u8]>,
7643 transformation: TransformationMatrix,
7644 color: Hsla,
7645 cx: &App,
7646 ) -> Result<()> {
7647 self.paint_animated_svg(bounds, path, data, transformation, None, color, cx)
7648 }
7649
7650 pub(crate) fn paint_animated_svg(
7653 &mut self,
7654 bounds: Bounds<Pixels>,
7655 path: SharedString,
7656 data: Option<&[u8]>,
7657 transformation: TransformationMatrix,
7658 animation: Option<SpriteAnimation>,
7659 color: Hsla,
7660 cx: &App,
7661 ) -> Result<()> {
7662 self.invalidator.debug_assert_paint();
7663
7664 let element_opacity = self.element_opacity();
7665 let bounds = self.snap_bounds(bounds);
7666
7667 let params = RenderSvgParams {
7668 path,
7669 size: bounds.size.map(|pixels| {
7670 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
7671 }),
7672 };
7673
7674 let Some(tile) =
7675 self.sprite_atlas
7676 .get_or_insert_with(params.clone().into(), &mut || {
7677 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
7678 else {
7679 return Ok(None);
7680 };
7681 Ok(Some((size, Cow::Owned(bytes))))
7682 })?
7683 else {
7684 return Ok(());
7685 };
7686 let content_mask = self.snapped_content_mask();
7687 let svg_bounds = Bounds {
7688 origin: bounds.center()
7689 - Point::new(
7690 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
7691 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
7692 ),
7693 size: tile
7694 .bounds
7695 .size
7696 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
7697 };
7698 let final_bounds = svg_bounds
7699 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
7700 .map_size(|size| size.ceil());
7701
7702 let sprite = MonochromeSprite {
7703 order: 0,
7704 raw_coverage: false.into(),
7705 animation: SpriteAnimationId::NONE,
7706 pad: 0,
7707 bounds: final_bounds,
7708 content_mask,
7709 color: color.opacity(element_opacity),
7710 tile,
7711 transformation: self.element_transform.compose(transformation),
7714 };
7715 match animation {
7716 Some(animation) => self.next_frame.scene.insert_animated_sprite(
7717 sprite,
7718 animation.under(self.element_transform),
7719 ),
7720 None => self.next_frame.scene.insert_primitive(sprite),
7721 }
7722
7723 Ok(())
7724 }
7725
7726 pub fn paint_image(
7738 &mut self,
7739 bounds: Bounds<Pixels>,
7740 image_bounds: Bounds<Pixels>,
7741 corner_radii: Corners<Pixels>,
7742 data: Arc<RenderImage>,
7743 frame_index: usize,
7744 grayscale: bool,
7745 ) -> Result<()> {
7746 self.invalidator.debug_assert_paint();
7747
7748 let visible_bounds = bounds.intersect(&image_bounds);
7749 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
7750 return Ok(());
7751 }
7752 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
7753 return Ok(());
7754 }
7755
7756 let (data, frame_index) = match IMAGE_RESAMPLER.get() {
7759 Some(resample) if !data.is_dynamic() => {
7760 let scale = self.scale_factor();
7761 let device = size(
7762 DevicePixels((image_bounds.size.width.0 * scale).round() as i32),
7763 DevicePixels((image_bounds.size.height.0 * scale).round() as i32),
7764 );
7765 match resample(&data, frame_index, device) {
7766 Some(smaller) => (smaller, 0),
7767 None => (data, frame_index),
7768 }
7769 }
7770 _ => (data, frame_index),
7771 };
7772
7773 let params = RenderImageParams {
7774 image_id: data.id,
7775 frame_index,
7776 };
7777
7778 let tile = self.sprite_atlas.get_or_insert_with(params.into(), &mut || {
7779 Ok(data.as_bytes(frame_index).map(|bytes| (data.size(frame_index), Cow::Borrowed(bytes))))
7780 })?;
7781 let Some(tile) = tile else { return Ok(()); };
7782
7783 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
7784
7785 let sub_tile = if visible_bounds == image_bounds {
7786 tile
7787 } else {
7788 let x_offset_ratio =
7789 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
7790 let y_offset_ratio =
7791 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
7792 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
7793 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
7794
7795 let tile_origin_x = tile.bounds.origin.x.0;
7796 let tile_origin_y = tile.bounds.origin.y.0;
7797 let tile_width = tile.bounds.size.width.0;
7798 let tile_height = tile.bounds.size.height.0;
7799
7800 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
7801 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
7802 let sub_width = (width_ratio * tile_width as f32).round() as i32;
7803 let sub_height = (height_ratio * tile_height as f32).round() as i32;
7804
7805 let max_x = tile_origin_x + tile_width;
7806 let max_y = tile_origin_y + tile_height;
7807
7808 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
7809 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
7810 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
7811 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
7812
7813 AtlasTile {
7814 bounds: Bounds {
7815 origin: point(
7816 DevicePixels(clamped_origin_x),
7817 DevicePixels(clamped_origin_y),
7818 ),
7819 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
7820 },
7821 ..tile
7822 }
7823 };
7824
7825 let content_mask = self.snapped_content_mask();
7826 let corner_radii = corner_radii
7827 .clamp_radii_for_quad_size(visible_bounds.size)
7828 .scale(self.scale_factor());
7829 let opacity = self.element_opacity();
7830
7831 self.next_frame.scene.insert_primitive(PolychromeSprite {
7832 order: 0,
7833 pad: 0,
7834 grayscale: grayscale.into(),
7835 bounds: visible_bounds_snapped,
7836 content_mask,
7837 corner_radii,
7838 tile: sub_tile,
7839 opacity,
7840 transformation: self.element_transform,
7841 tint: self.element_image_tint,
7842 });
7843 Ok(())
7844 }
7845
7846 #[cfg(any(target_os = "macos", target_os = "ios"))]
7850 pub fn paint_surface(
7851 &mut self,
7852 bounds: Bounds<Pixels>,
7853 image_buffer: CFRetained<CVPixelBuffer>,
7854 ) {
7855 use crate::PaintSurface;
7856
7857 self.invalidator.debug_assert_paint();
7858
7859 let bounds = self.snap_bounds(bounds);
7860 let content_mask = self.snapped_content_mask();
7861 self.next_frame.scene.insert_primitive(PaintSurface {
7862 order: 0,
7863 bounds,
7864 content_mask,
7865 image_buffer,
7866 });
7867 }
7868
7869 pub fn upload_image_from_gpu(
7890 &mut self,
7891 data: &RenderImage,
7892 frame_index: usize,
7893 texture: GpuTextureHandle,
7894 ) -> Result<bool> {
7895 Ok(self.write_image_tile(data, frame_index, TileSource::Gpu(texture))? != TileWrite::Refused)
7896 }
7897
7898 pub fn write_image_tile(
7916 &mut self,
7917 image: &RenderImage,
7918 frame_index: usize,
7919 source: TileSource,
7920 ) -> Result<TileWrite> {
7921 let key: AtlasKey = RenderImageParams {
7922 image_id: image.id,
7923 frame_index,
7924 }
7925 .into();
7926 let size = image.size(frame_index);
7927 let before = self.sprite_atlas.tile(&key);
7928 let after = match source {
7929 TileSource::Gpu(texture) => {
7930 match self.sprite_atlas.upload_from_gpu(&key, size, texture)? {
7931 Some(tile) => tile,
7932 None => return Ok(TileWrite::Refused),
7933 }
7934 }
7935 TileSource::Bytes => {
7936 let bytes = image
7937 .as_bytes(frame_index)
7938 .ok_or_else(|| anyhow!("write_image_tile: no frame {frame_index}"))?;
7939 match self.sprite_atlas.write_bytes(&key, size, bytes)? {
7940 Some(tile) => tile,
7941 None => {
7942 self.sprite_atlas.remove(&key);
7943 self.sprite_atlas
7944 .get_or_insert_with(key, &mut || {
7945 Ok(Some((size, Cow::Borrowed(bytes))))
7946 })?
7947 .ok_or_else(|| anyhow!("write_image_tile: the atlas took no tile"))?;
7948 return Ok(TileWrite::Placed);
7949 }
7950 }
7951 }
7952 };
7953 Ok(match before {
7954 Some(tile) if tile == after => TileWrite::InPlace,
7955 _ => TileWrite::Placed,
7956 })
7957 }
7958
7959 pub fn write_image_tile_d3d12(
7962 &mut self,
7963 image: &RenderImage,
7964 frame_index: usize,
7965 texture: crate::D3D12TextureHandle,
7966 owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
7967 ) -> Result<TileWrite> {
7968 let key: AtlasKey = RenderImageParams {
7969 image_id: image.id,
7970 frame_index,
7971 }
7972 .into();
7973 let before = self.sprite_atlas.tile(&key);
7974 let Some(after) = self.sprite_atlas.upload_from_d3d12(
7975 &key,
7976 image.size(frame_index),
7977 texture,
7978 owner,
7979 )? else {
7980 return Ok(TileWrite::Refused);
7981 };
7982 Ok(match before {
7983 Some(tile) if tile == after => TileWrite::InPlace,
7984 _ => TileWrite::Placed,
7985 })
7986 }
7987
7988 pub fn request_present(&self) {
7995 self.needs_present.set(true);
7996 self.invalidator.wake_platform();
7997 }
7998
7999 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
8001 for frame_index in 0..data.frame_count() {
8002 let params = RenderImageParams {
8003 image_id: data.id,
8004 frame_index,
8005 };
8006
8007 self.sprite_atlas.remove(¶ms.into());
8008 }
8009
8010 Ok(())
8011 }
8012
8013 pub fn sprite_atlas_stats(&self) -> Option<AtlasStats> {
8017 self.sprite_atlas.stats()
8018 }
8019
8020 pub fn has_image_atlas_tile(&self, data: &RenderImage, frame_index: usize) -> bool {
8022 self.sprite_atlas.tile(&RenderImageParams {image_id:data.id,frame_index}.into()).is_some()
8023 }
8024
8025 #[cfg(any(test, feature = "test-support"))]
8027 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
8028 data.frame_count() > 0
8029 && (0..data.frame_count()).all(|frame_index| {
8030 self.sprite_atlas.contains(
8031 &RenderImageParams {
8032 image_id: data.id,
8033 frame_index,
8034 }
8035 .into(),
8036 )
8037 })
8038 }
8039
8040 pub fn vn_enable_retained_layout(&mut self) {
8043 self.layout_engine.as_mut().unwrap().enable_retention();
8044 }
8045
8046 pub fn vn_profile_retained_layout(&mut self, enabled: bool) {
8048 self.layout_engine
8049 .as_mut()
8050 .unwrap()
8051 .profile_retention(enabled);
8052 }
8053
8054 pub fn vn_take_retained_layout_stats(&mut self) -> Option<crate::VnRetainedLayoutStats> {
8056 self.layout_engine.as_mut().unwrap().take_retention_stats()
8057 }
8058
8059 #[must_use]
8065 pub fn request_layout(
8066 &mut self,
8067 style: Style,
8068 children: impl IntoIterator<Item = LayoutId>,
8069 cx: &mut App,
8070 ) -> LayoutId {
8071 self.invalidator.debug_assert_prepaint();
8072
8073 cx.layout_id_buffer.clear();
8074 cx.layout_id_buffer.extend(children);
8075 let rem_size = self.rem_size();
8076 let scale_factor = self.scale_factor();
8077
8078 let scope = self
8079 .layout_engine
8080 .as_ref()
8081 .unwrap()
8082 .retention_enabled()
8083 .then(|| self.element_id_stack.global_id());
8084 let engine = self.layout_engine.as_mut().unwrap();
8085 if let Some(scope) = scope {
8086 engine.request_layout_in_scope(
8087 Some(scope),
8088 style,
8089 rem_size,
8090 scale_factor,
8091 &cx.layout_id_buffer,
8092 )
8093 } else {
8094 engine.request_layout(style, rem_size, scale_factor, &cx.layout_id_buffer)
8095 }
8096 }
8097
8098 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
8107 where
8108 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
8109 + 'static,
8110 {
8111 self.invalidator.debug_assert_prepaint();
8112
8113 let rem_size = self.rem_size();
8114 let scale_factor = self.scale_factor();
8115 let scope = self
8116 .layout_engine
8117 .as_ref()
8118 .unwrap()
8119 .retention_enabled()
8120 .then(|| self.element_id_stack.global_id());
8121 let engine = self.layout_engine.as_mut().unwrap();
8122 if let Some(scope) = scope {
8123 engine.request_measured_layout_in_scope(
8124 Some(scope),
8125 style,
8126 rem_size,
8127 scale_factor,
8128 measure,
8129 )
8130 } else {
8131 engine.request_measured_layout(style, rem_size, scale_factor, measure)
8132 }
8133 }
8134
8135 pub fn compute_layout(
8141 &mut self,
8142 layout_id: LayoutId,
8143 available_space: Size<AvailableSpace>,
8144 cx: &mut App,
8145 ) {
8146 self.invalidator.debug_assert_prepaint();
8147
8148 let mut layout_engine = self.layout_engine.take().unwrap();
8149 layout_engine.compute_layout(layout_id, available_space, self, cx);
8150 self.layout_engine = Some(layout_engine);
8151 }
8152
8153 pub fn layout_is_absolute(&self, layout_id: LayoutId) -> bool {
8156 self.layout_engine
8157 .as_ref()
8158 .is_some_and(|engine| engine.is_absolute(layout_id))
8159 }
8160
8161 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
8166 self.invalidator.debug_assert_prepaint();
8167
8168 let scale_factor = self.scale_factor();
8169 let mut bounds = self
8170 .layout_engine
8171 .as_mut()
8172 .unwrap()
8173 .layout_bounds(layout_id, scale_factor)
8174 .map(Into::into);
8175 let snapped_offset = self.pixel_snap_point(self.element_offset());
8176 bounds.origin += snapped_offset;
8177 bounds
8178 }
8179
8180 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
8186 self.invalidator.debug_assert_prepaint();
8187
8188 let content_mask = self.content_mask();
8189 let id = self.next_hitbox_id;
8190 self.next_hitbox_id = self.next_hitbox_id.next();
8191 let hitbox = Hitbox {
8192 id,
8193 bounds,
8194 content_mask,
8195 behavior,
8196 transformation: self.element_transform,
8200 vn_clip: self.vn_clip_stack.clone(),
8201 };
8202 self.next_frame.hitboxes.push(hitbox.clone());
8203 if self.vn_hitbox_tag != 0 {
8205 self.next_frame
8206 .vn_tagged_hitboxes
8207 .push((self.vn_hitbox_tag, hitbox.clone()));
8208 }
8209 hitbox
8210 }
8211
8212 pub fn set_hitbox_tag(&mut self, tag: u32) -> u32 {
8219 mem::replace(&mut self.vn_hitbox_tag, tag)
8220 }
8221
8222 pub fn with_hitbox_tag<R>(
8233 &mut self,
8234 tag: u32,
8235 f: impl FnOnce(&mut Self) -> R,
8236 ) -> (R, Option<TransformationMatrix>) {
8237 let tag = mem::replace(&mut self.vn_hitbox_tag, tag);
8238 let fresh = mem::replace(&mut self.vn_tag_fresh, true);
8239 let noted = self.vn_tag_transform.take();
8240 let result = f(self);
8241 let own = mem::replace(&mut self.vn_tag_transform, noted);
8242 self.vn_tag_fresh = fresh;
8243 self.vn_hitbox_tag = tag;
8244 (result, own)
8245 }
8246
8247 pub(crate) fn note_tagged_transform(&mut self, own_is_unit: bool) {
8251 if self.vn_tag_fresh {
8252 self.vn_tag_fresh = false;
8253 if !own_is_unit {
8254 self.vn_tag_transform = Some(self.element_transform);
8255 }
8256 }
8257 }
8258
8259 pub fn transformed_bounds(
8264 &self,
8265 matrix: TransformationMatrix,
8266 bounds: Bounds<Pixels>,
8267 ) -> Bounds<Pixels> {
8268 transform_bounds(matrix, bounds, self.scale_factor)
8269 }
8270
8271 pub fn set_tag_every_hitbox(&mut self, on: bool) {
8277 self.vn_tag_every_hitbox = on;
8278 }
8279
8280 pub fn tags_every_hitbox(&self) -> bool {
8282 self.vn_tag_every_hitbox
8283 }
8284
8285 pub fn tagged_hitbox(&self, tag: u32) -> Option<&Hitbox> {
8293 self.rendered_frame
8294 .vn_tagged_hitboxes
8295 .iter()
8296 .find(|(t, hitbox)| *t == tag && hitbox.id != HitboxId::VN_PICK)
8297 .map(|(_, hitbox)| hitbox)
8298 }
8299
8300 pub fn vn_tags_at(&self, position: Point<Pixels>) -> Vec<u32> {
8322 let frame = &self.rendered_frame;
8323 let tagged = &frame.vn_tagged_hitboxes;
8324 let mut out = Vec::new();
8325 let mut visit = |(tag, hitbox): &(u32, Hitbox)| {
8326 if tag & VN_TAG_PASSIVE != 0 || !Frame::box_contains(hitbox, position, self.scale_factor) {
8327 return true;
8328 }
8329 out.push(*tag);
8330 hitbox.behavior != HitboxBehavior::BlockMouse
8331 };
8332 match frame.vn_tagged_paint_order() {
8333 Some(order) => {
8334 for &ix in order.iter().rev() {
8335 if !visit(&tagged[ix as usize]) {
8336 break;
8337 }
8338 }
8339 }
8340 None => {
8341 for entry in tagged.iter().rev() {
8342 if !visit(entry) {
8343 break;
8344 }
8345 }
8346 }
8347 }
8348 out
8349 }
8350
8351 pub fn set_vn_pick_every_box(&mut self, on: bool) {
8359 self.vn_pick_every_box = on;
8360 }
8361
8362 pub fn vn_picks_every_box(&self) -> bool {
8364 self.vn_pick_every_box
8365 }
8366
8367 pub fn vn_insert_pick(&mut self, bounds: Bounds<Pixels>) {
8372 self.invalidator.debug_assert_prepaint();
8373 if self.vn_hitbox_tag == 0 {
8374 return;
8375 }
8376 let hitbox = Hitbox {
8377 id: HitboxId::VN_PICK,
8378 bounds,
8379 content_mask: self.content_mask(),
8380 behavior: HitboxBehavior::Normal,
8381 transformation: self.element_transform,
8382 vn_clip: self.vn_clip_stack.clone(),
8383 };
8384 self.next_frame
8385 .vn_tagged_hitboxes
8386 .push((self.vn_hitbox_tag, hitbox));
8387 }
8388
8389 pub fn set_vn_hit_refiner(&mut self, refiner: Option<VnHitRefiner>) {
8399 self.vn_hit_refiner = refiner;
8400 }
8401
8402 pub fn has_vn_hit_refiner(&self) -> bool {
8404 self.vn_hit_refiner.is_some()
8405 }
8406
8407 pub fn vn_key_event_seq(&self) -> u64 {
8421 self.vn_key_event_seq
8422 }
8423
8424 pub fn vn_pointer_inside(&self) -> bool {
8431 self.pointer_inside
8432 }
8433
8434 pub fn vn_lock_pointer(&mut self, how: VnPointerLock) -> Result<(), crate::PointerLockError> {
8438 let anchor = match self.vn_pointer_lock.take() {
8439 Some((previous, anchor)) => {
8440 if matches!(previous, VnPointerLock::System { .. }) {
8441 self.platform_window.unlock_pointer();
8442 }
8443 anchor
8444 }
8445 None => self.mouse_position,
8446 };
8447 if let VnPointerLock::System { unadjusted } = how {
8448 self.platform_window.lock_pointer(unadjusted)?;
8449 }
8450 self.vn_pointer_lock = Some((how, anchor));
8451 self.vn_raw_mouse_position = None;
8452 Ok(())
8453 }
8454
8455 pub fn vn_unlock_pointer(&mut self) {
8457 if let Some((VnPointerLock::System { .. }, _)) = self.vn_pointer_lock.take() {
8458 self.platform_window.unlock_pointer();
8459 }
8460 self.vn_raw_mouse_position = None;
8461 }
8462
8463 pub fn vn_pointer_locked(&self) -> bool {
8466 match self.vn_pointer_lock {
8467 Some((VnPointerLock::System { .. }, _)) => self.platform_window.is_pointer_locked(),
8468 Some((VnPointerLock::Simulated, _)) => true,
8469 None => false,
8470 }
8471 }
8472
8473 pub fn vn_mouse_movement(&self) -> Point<Pixels> {
8477 self.vn_mouse_movement
8478 }
8479
8480 fn vn_pin_to_pointer_lock(&mut self, mut event: PlatformInput) -> PlatformInput {
8481 let system = matches!(
8482 self.vn_pointer_lock,
8483 Some((VnPointerLock::System { .. }, _))
8484 );
8485 if system && !self.platform_window.is_pointer_locked() {
8486 self.vn_pointer_lock = None;
8487 self.vn_raw_mouse_position = None;
8488 }
8489 if let PlatformInput::MouseMove(mouse_move) = &event {
8490 let previous = self.vn_raw_mouse_position.replace(mouse_move.position);
8491 let motion = system.then(|| self.platform_window.take_pointer_motion());
8492 self.vn_mouse_movement = motion.flatten().unwrap_or_else(|| {
8493 previous.map_or_else(Point::default, |previous| mouse_move.position - previous)
8494 });
8495 }
8496 let Some((_, anchor)) = self.vn_pointer_lock else {
8497 return event;
8498 };
8499 match &mut event {
8500 PlatformInput::MouseMove(e) => e.position = anchor,
8501 PlatformInput::MouseDown(e) => e.position = anchor,
8502 PlatformInput::MouseUp(e) => e.position = anchor,
8503 PlatformInput::Scroll(e) => e.position = anchor,
8504 PlatformInput::MouseExited(e) => e.position = anchor,
8505 _ => {}
8506 }
8507 event
8508 }
8509
8510 pub fn vn_is_dirty(&self) -> bool {
8517 self.invalidator.is_dirty()
8518 }
8519
8520 pub fn vn_restrict_mouse_hit(&mut self, keep: &dyn Fn(u32) -> bool, add: bool) {
8529 let frame = &self.rendered_frame;
8530 let mut tag_of: FxHashMap<HitboxId, u32> = FxHashMap::default();
8531 for (tag, hitbox) in &frame.vn_tagged_hitboxes {
8533 if hitbox.id != HitboxId::VN_PICK {
8534 tag_of.entry(hitbox.id).or_insert(tag & !VN_TAG_PASSIVE);
8535 }
8536 }
8537 let old = mem::take(&mut self.mouse_hit_test);
8538 let mut ids: SmallVec<[HitboxId; 8]> = SmallVec::new();
8539 let mut hover = 0;
8540 for (ix, id) in old.ids.iter().enumerate() {
8541 if tag_of.get(id).is_none_or(|tag| keep(*tag)) {
8542 ids.push(*id);
8543 if ix < old.hover_hitbox_count {
8544 hover += 1;
8545 }
8546 }
8547 }
8548 let all_hovered = old.hover_hitbox_count == old.ids.len();
8551 if add {
8552 for (tag, hitbox) in &frame.vn_tagged_hitboxes {
8553 if hitbox.id != HitboxId::VN_PICK
8554 && keep(tag & !VN_TAG_PASSIVE)
8555 && !ids.contains(&hitbox.id)
8556 {
8557 ids.push(hitbox.id);
8558 }
8559 }
8560 }
8561 if all_hovered {
8562 hover = ids.len();
8563 }
8564 self.mouse_hit_test = HitTest {
8565 ids,
8566 hover_hitbox_count: hover,
8567 };
8568 }
8569
8570 pub fn window_control_area_at(&self, position: Point<Pixels>) -> Option<WindowControlArea> {
8573 for hitbox in self.rendered_frame.topmost_hitboxes() {
8574 if !Frame::box_contains(hitbox, position, self.scale_factor) {
8575 continue;
8576 }
8577 if let Some((area, _)) = self.rendered_frame.window_control_hitboxes.iter()
8578 .find(|(_, control)| control.id == hitbox.id)
8579 {
8580 return Some(*area);
8581 }
8582 if hitbox.behavior == HitboxBehavior::BlockMouse {
8583 break;
8584 }
8585 }
8586 None
8587 }
8588
8589 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
8593 self.invalidator.debug_assert_paint();
8594 self.next_frame.window_control_hitboxes.push((area, hitbox));
8595 }
8596
8597 pub fn set_key_context(&mut self, context: KeyContext) {
8602 self.invalidator.debug_assert_paint();
8603 self.next_frame.dispatch_tree.set_key_context(context);
8604 }
8605
8606 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
8611 self.invalidator.debug_assert_prepaint();
8612 if focus_handle.is_focused(self) {
8613 self.next_frame.focus = Some(focus_handle.id);
8614 }
8615 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
8616 }
8617
8618 pub fn set_view_id(&mut self, view_id: EntityId) {
8624 self.invalidator.debug_assert_prepaint();
8625 self.next_frame.dispatch_tree.set_view_id(view_id);
8626 }
8627
8628 pub fn current_view(&self) -> EntityId {
8630 self.invalidator.debug_assert_paint_or_prepaint();
8631 self.rendered_entity_stack.last().copied().unwrap()
8632 }
8633
8634 #[inline]
8635 pub(crate) fn with_rendered_view<R>(
8636 &mut self,
8637 id: EntityId,
8638 f: impl FnOnce(&mut Self) -> R,
8639 ) -> R {
8640 self.rendered_entity_stack.push(id);
8641 let result = f(self);
8642 self.rendered_entity_stack.pop();
8643 result
8644 }
8645
8646 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
8648 where
8649 F: FnOnce(&mut Self) -> R,
8650 {
8651 if let Some(image_cache) = image_cache {
8652 self.image_cache_stack.push(image_cache);
8653 let result = f(self);
8654 self.image_cache_stack.pop();
8655 result
8656 } else {
8657 f(self)
8658 }
8659 }
8660
8661 pub fn handle_input(
8670 &mut self,
8671 focus_handle: &FocusHandle,
8672 input_handler: impl InputHandler,
8673 cx: &App,
8674 ) {
8675 self.invalidator.debug_assert_paint();
8676
8677 if focus_handle.is_focused(self) {
8678 let cx = self.to_async(cx);
8679 self.next_frame.input_handlers.push(Some(
8680 PlatformInputHandler::new(cx, Box::new(input_handler)).with_focus(focus_handle.id),
8681 ));
8682 }
8683 }
8684
8685 pub fn notify_text_input_changed(&self, focus_handle: &FocusHandle) {
8690 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
8691 self.platform_window
8692 .text_input_state_changed(TextInputStateChange::ContentChanged);
8693 }
8694 }
8695
8696 pub fn notify_text_selection_changed(&self, focus_handle: &FocusHandle) {
8701 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
8702 self.platform_window
8703 .text_input_state_changed(TextInputStateChange::SelectionChanged);
8704 }
8705 }
8706
8707 fn apply_text_input_configuration(&mut self, cx: &mut App) {
8712 let configuration = match self.platform_window.take_input_handler() {
8713 Some(mut input_handler) => {
8714 let configuration = input_handler.text_input_configuration(self, cx);
8715 self.platform_window.set_input_handler(input_handler);
8716 configuration
8717 }
8718 None => TextInputConfiguration::default(),
8719 };
8720 if self.last_text_input_configuration.as_ref() != Some(&configuration) {
8721 self.platform_window
8722 .set_text_input_configuration(configuration.clone());
8723 self.last_text_input_configuration = Some(configuration);
8724 }
8725 }
8726
8727 pub fn on_mouse_event<Event: MouseEvent>(
8733 &mut self,
8734 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
8735 ) {
8736 self.invalidator.debug_assert_paint();
8737
8738 self.next_frame.mouse_listeners.push(Some(Box::new(
8739 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
8740 if let Some(event) = event.downcast_ref() {
8741 listener(event, phase, window, cx)
8742 }
8743 },
8744 )));
8745 }
8746
8747 pub fn on_key_event<Event: KeyEvent>(
8756 &mut self,
8757 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
8758 ) {
8759 self.invalidator.debug_assert_paint();
8760
8761 self.next_frame.dispatch_tree.on_key_event(Rc::new(
8762 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
8763 if let Some(event) = event.downcast_ref::<Event>() {
8764 listener(event, phase, window, cx)
8765 }
8766 },
8767 ));
8768 }
8769
8770 pub fn on_modifiers_changed(
8777 &mut self,
8778 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
8779 ) {
8780 self.invalidator.debug_assert_paint();
8781
8782 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
8783 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
8784 listener(event, window, cx)
8785 },
8786 ));
8787 }
8788
8789 pub fn on_focus_in(
8793 &mut self,
8794 handle: &FocusHandle,
8795 cx: &mut App,
8796 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
8797 ) -> Subscription {
8798 let focus_id = handle.id;
8799 let (subscription, activate) =
8800 self.new_focus_listener(Box::new(move |event, window, cx| {
8801 if event.is_focus_in(focus_id) {
8802 listener(window, cx);
8803 }
8804 true
8805 }));
8806 cx.defer(move |_| activate());
8807 subscription
8808 }
8809
8810 pub fn on_focus_out(
8813 &mut self,
8814 handle: &FocusHandle,
8815 cx: &mut App,
8816 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
8817 ) -> Subscription {
8818 let focus_id = handle.id;
8819 let (subscription, activate) =
8820 self.new_focus_listener(Box::new(move |event, window, cx| {
8821 if let Some(blurred_id) = event.previous_focus_path.last().copied()
8822 && event.is_focus_out(focus_id)
8823 {
8824 let event = FocusOutEvent {
8825 blurred: WeakFocusHandle {
8826 id: blurred_id,
8827 handles: Arc::downgrade(&cx.focus_handles),
8828 },
8829 };
8830 listener(event, window, cx)
8831 }
8832 true
8833 }));
8834 cx.defer(move |_| activate());
8835 subscription
8836 }
8837
8838 fn reset_cursor_style(&self, cx: &mut App) {
8839 if self.is_window_hovered() {
8841 let style = cx
8843 .active_drag_cursor_style()
8844 .or_else(|| self.rendered_frame.cursor_style(self))
8845 .unwrap_or(CursorStyle::Arrow);
8846 cx.platform.set_cursor_style(style);
8847 }
8848 }
8849
8850 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
8853 let keystroke = keystroke.with_simulated_ime();
8854 let result = self.dispatch_event(
8855 PlatformInput::KeyDown(KeyDownEvent {
8856 keystroke: keystroke.clone(),
8857 is_held: false,
8858 prefer_character_input: false,
8859 }),
8860 cx,
8861 );
8862 if !result.propagate {
8863 return true;
8864 }
8865
8866 if let Some(input) = keystroke.key_char
8867 && let Some(mut input_handler) = self.platform_window.take_input_handler()
8868 {
8869 input_handler.dispatch_input(&input, self, cx);
8870 self.platform_window.set_input_handler(input_handler);
8871 return true;
8872 }
8873
8874 false
8875 }
8876
8877 pub fn keystroke_text_for(&self, action: &dyn Action, cx: &App) -> String {
8880 self.highest_precedence_binding_for_action(action)
8881 .map(|binding| {
8882 binding
8883 .keystrokes()
8884 .iter()
8885 .map(|keystroke| keystroke.display(cx.platform_info().os).to_string())
8886 .collect::<Vec<_>>()
8887 .join(" ")
8888 })
8889 .unwrap_or_else(|| action.name().to_string())
8890 }
8891
8892 pub fn set_input_interceptor(
8896 &mut self,
8897 interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
8898 ) {
8899 self.input_interceptor = interceptor;
8900 }
8901
8902 #[profiling::function]
8904 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
8905 if let Some(intercept) = self.input_interceptor.clone() {
8909 if intercept(&event, self, cx) {
8910 return DispatchEventResult { propagate: false, default_prevented: true };
8911 }
8912 }
8913 #[cfg(feature = "profiler")]
8914 self.window_profiler.begin_input(event.kind_name());
8915 let update_count_before = self.invalidator.update_count();
8916 let old_modality = self.last_input_modality;
8920 self.last_input_modality = match &event {
8921 PlatformInput::KeyDown(_) => InputModality::Keyboard,
8922 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
8923 PlatformInput::Touch(_) => InputModality::Touch,
8924 _ => self.last_input_modality,
8925 };
8926 if self.last_input_modality != old_modality {
8927 self.refresh();
8928 }
8929 let was_inside = self.pointer_inside;
8930 let pointer_moved = matches!(event, PlatformInput::MouseMove(_));
8931 let pointer_leaves = match &event {
8936 PlatformInput::MouseMove(_)
8937 | PlatformInput::MouseDown(_)
8938 | PlatformInput::MouseUp(_)
8939 | PlatformInput::MousePressure(_)
8940 | PlatformInput::Scroll(_)
8941 | PlatformInput::Pinch(_)
8942 | PlatformInput::LongPress(_)
8943 | PlatformInput::TouchDrag(_)
8944 | PlatformInput::BackGesture(_)
8945 | PlatformInput::Touch(_) => {
8946 self.pointer_inside = true;
8947 false
8948 }
8949 PlatformInput::FileDrop(FileDropEvent::Exited) | PlatformInput::MouseExited(_) => true,
8950 PlatformInput::FileDrop(_) => {
8951 self.pointer_inside = true;
8952 false
8953 }
8954 PlatformInput::KeyDown(_)
8955 | PlatformInput::KeyUp(_)
8956 | PlatformInput::ModifiersChanged(_) => false,
8957 };
8958
8959 cx.propagate_event = true;
8961 self.default_prevented = false;
8963
8964 let event = self.vn_pin_to_pointer_lock(event);
8965 let event = match event {
8966 PlatformInput::MouseMove(mouse_move) => {
8969 self.mouse_position = mouse_move.position;
8970 self.modifiers = mouse_move.modifiers;
8971 PlatformInput::MouseMove(mouse_move)
8972 }
8973 PlatformInput::MouseDown(mouse_down) => {
8974 self.mouse_position = mouse_down.position;
8975 self.modifiers = mouse_down.modifiers;
8976 PlatformInput::MouseDown(mouse_down)
8977 }
8978 PlatformInput::MouseUp(mouse_up) => {
8979 self.mouse_position = mouse_up.position;
8980 self.modifiers = mouse_up.modifiers;
8981 PlatformInput::MouseUp(mouse_up)
8982 }
8983 PlatformInput::MousePressure(mouse_pressure) => {
8984 PlatformInput::MousePressure(mouse_pressure)
8985 }
8986 PlatformInput::MouseExited(mouse_exited) => {
8987 self.modifiers = mouse_exited.modifiers;
8988 PlatformInput::MouseExited(mouse_exited)
8989 }
8990 PlatformInput::ModifiersChanged(modifiers_changed) => {
8991 self.modifiers = modifiers_changed.modifiers;
8992 self.capslock = modifiers_changed.capslock;
8993 PlatformInput::ModifiersChanged(modifiers_changed)
8994 }
8995 PlatformInput::Scroll(scroll_wheel) => {
8996 self.mouse_position = scroll_wheel.position;
8997 self.modifiers = scroll_wheel.modifiers;
8998 PlatformInput::Scroll(scroll_wheel)
8999 }
9000 PlatformInput::Pinch(pinch) => {
9001 self.mouse_position = pinch.position;
9002 self.modifiers = pinch.modifiers;
9003 PlatformInput::Pinch(pinch)
9004 }
9005 PlatformInput::FileDrop(file_drop) => match file_drop {
9008 FileDropEvent::Entered { position, paths } => {
9009 self.mouse_position = position;
9010 let source_window = self.handle.window_id();
9011 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
9012 cx.active_drag = Some(AnyDrag {
9013 value: Arc::new(paths.clone()),
9014 view: cx.new(|_| paths).into(),
9015 cursor_offset: position,
9016 cursor_style: None,
9017 external_payload_source: None,
9018 });
9019 }
9020 PlatformInput::MouseMove(MouseMoveEvent {
9021 position,
9022 pressed_button: Some(MouseButton::Left),
9023 modifiers: Modifiers::default(),
9024 })
9025 }
9026 FileDropEvent::Pending { position } => {
9027 self.mouse_position = position;
9028 PlatformInput::MouseMove(MouseMoveEvent {
9029 position,
9030 pressed_button: Some(MouseButton::Left),
9031 modifiers: Modifiers::default(),
9032 })
9033 }
9034 FileDropEvent::Submit { position } => {
9035 cx.activate(true);
9036 self.mouse_position = position;
9037 PlatformInput::MouseUp(MouseUpEvent {
9038 button: MouseButton::Left,
9039 position,
9040 modifiers: Modifiers::default(),
9041 click_count: 1,
9042 })
9043 }
9044 FileDropEvent::Exited => {
9045 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
9046 cx.active_drag.take();
9047 }
9048 self.refresh();
9049 PlatformInput::FileDrop(FileDropEvent::Exited)
9050 }
9051 FileDropEvent::Ended => {
9052 cx.end_platform_drag(self.handle.window_id());
9053 self.refresh();
9054 PlatformInput::FileDrop(FileDropEvent::Ended)
9055 }
9056 },
9057 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
9058 PlatformInput::LongPress(long_press) => {
9059 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
9060 long_press.start_position
9061 } else {
9062 long_press.position
9063 };
9064 if long_press.phase == crate::TouchPhase::Started {
9065 self.long_press_capture = None;
9066 }
9067 PlatformInput::LongPress(long_press)
9068 }
9069 PlatformInput::TouchDrag(touch_drag) => {
9070 self.mouse_position = touch_drag.start_position;
9071 PlatformInput::TouchDrag(touch_drag)
9072 }
9073 PlatformInput::BackGesture(back) => {
9074 self.mouse_position = back.start_position;
9075 PlatformInput::BackGesture(back)
9076 }
9077 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
9078 };
9079
9080 if let Some(any_mouse_event) = event.mouse_event() {
9081 self.dispatch_mouse_event(any_mouse_event, cx);
9082 } else if let Some(any_key_event) = event.keyboard_event() {
9083 self.dispatch_key_event(any_key_event, cx);
9084 } else if let Some(touch_event) = event.touch_event() {
9085 self.dispatch_touch_event(touch_event, cx);
9086 }
9087 if let PlatformInput::LongPress(long_press) = &event {
9088 match long_press.phase {
9089 crate::TouchPhase::Started if !self.default_prevented => {
9090 self.long_press_capture = None;
9091 }
9092 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
9093 self.long_press_capture = None;
9094 }
9095 crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
9096 }
9097 }
9098
9099 self.promote_external_drag_to_platform(&event, cx);
9102
9103 if pointer_leaves && std::mem::replace(&mut self.pointer_inside, false) {
9106 self.refresh();
9107 }
9108 self.vn_effect_pointer
9109 .update(was_inside, self.pointer_inside, pointer_moved, cx);
9110
9111 let caused_invalidation = self.invalidator.update_count() > update_count_before;
9112 if caused_invalidation {
9113 self.input_rate_tracker.borrow_mut().record_input();
9114 }
9115 #[cfg(feature = "profiler")]
9116 self.window_profiler.end_input(caused_invalidation);
9117
9118 DispatchEventResult {
9119 propagate: cx.propagate_event,
9120 default_prevented: self.default_prevented,
9121 }
9122 }
9123
9124 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
9125 let PlatformInput::MouseMove(mouse_move) = event else {
9126 return;
9127 };
9128 if mouse_move.pressed_button != Some(MouseButton::Left) {
9129 return;
9130 }
9131 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
9132 return;
9133 }
9134 if !self.platform_window.can_start_external_drag() {
9135 return;
9136 }
9137 let Some(payload_source) = cx
9138 .active_drag
9139 .as_mut()
9140 .and_then(|drag| drag.external_payload_source.take())
9141 else {
9142 return;
9143 };
9144 let Some(payload) = payload_source(self, cx) else {
9145 return;
9146 };
9147 if self.platform_window.start_external_drag(&payload)
9148 && cx.hand_active_drag_to_platform(self.handle.window_id())
9149 {
9150 self.refresh();
9151 }
9152 }
9153
9154 pub fn touch_prediction_enabled(&self) -> bool {
9158 self.touch_prediction_enabled
9159 }
9160
9161 pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
9165 self.touch_prediction_enabled = enabled;
9166 }
9167
9168 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
9172 let mut event = event.clone();
9173 if !self.touch_prediction_enabled {
9174 event.predicted_position = None;
9175 }
9176 let recognized_gestures = self.touch_gestures.handle_event(&event);
9177 if event.phase == crate::TouchPhase::Started
9178 && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
9179 {
9180 self.dispatch_recognized_touch_gesture(touch_drag, cx);
9181 }
9182 if event.phase == crate::TouchPhase::Started
9183 && self.touch_gestures.pending_long_press().is_some()
9184 {
9185 self.long_press_capture = None;
9186 }
9187 let mut tapped = false;
9188 for gesture in recognized_gestures {
9189 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
9190 self.dispatch_recognized_touch_gesture(gesture, cx);
9191 }
9192 if event.phase == crate::TouchPhase::Started {
9193 self.schedule_long_press_timer(cx);
9194 } else if self.touch_gestures.pending_long_press().is_none() {
9195 self.long_press_timer.take();
9196 }
9197 if tapped && self.invalidator.is_dirty() {
9203 self.draw(cx).clear(cx);
9204 }
9205 if self.touch_gestures.has_momentum() {
9206 self.schedule_touch_momentum_tick();
9207 }
9208 }
9209
9210 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
9211 match gesture {
9212 RecognizedTouchGesture::Scroll(scroll_wheel) => {
9213 self.mouse_position = scroll_wheel.position;
9214 cx.propagate_event = true;
9215 self.dispatch_mouse_event(&scroll_wheel, cx);
9216 }
9217 RecognizedTouchGesture::Tap { down, up } => {
9218 self.mouse_position = up.position;
9219 cx.propagate_event = true;
9220 self.dispatch_mouse_event(&down, cx);
9221 cx.propagate_event = true;
9222 self.dispatch_mouse_event(&up, cx);
9223 }
9224 RecognizedTouchGesture::TouchDrag(touch_drag) => {
9225 self.mouse_position = touch_drag.start_position;
9226 cx.propagate_event = true;
9227 self.default_prevented = false;
9228 let started = touch_drag.phase == crate::TouchPhase::Started;
9229 self.dispatch_mouse_event(&touch_drag, cx);
9230 if started {
9231 self.touch_gestures
9232 .resolve_touch_drag(self.default_prevented);
9233 }
9234 }
9235 RecognizedTouchGesture::LongPress(long_press) => {
9236 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
9237 long_press.start_position
9238 } else {
9239 long_press.position
9240 };
9241 cx.propagate_event = true;
9242 self.default_prevented = false;
9243 let started = long_press.phase == crate::TouchPhase::Started;
9244 let ended = matches!(
9245 long_press.phase,
9246 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
9247 );
9248 self.dispatch_mouse_event(&long_press, cx);
9249 if started {
9250 let claimed = self.default_prevented;
9251 self.touch_gestures.resolve_long_press(claimed);
9252 if !claimed {
9253 self.long_press_capture = None;
9254 }
9255 }
9256 if ended {
9257 self.long_press_capture = None;
9258 }
9259 }
9260 }
9261 }
9262
9263 fn schedule_long_press_timer(&mut self, cx: &mut App) {
9264 self.long_press_timer.take();
9265 let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
9266 return;
9267 };
9268 self.long_press_timer = Some(self.spawn(cx, async move |cx| {
9269 cx.background_executor.timer(duration).await;
9270 cx.update(move |window, cx| {
9271 window.long_press_timer.take();
9272 if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
9273 window.dispatch_recognized_touch_gesture(gesture, cx);
9274 }
9275 })
9276 .with_context(|| {
9277 format!(
9278 "handling long-press timer for window {:?}",
9279 cx.window_handle().window_id()
9280 )
9281 })
9282 .log_err();
9283 }));
9284 }
9285
9286 fn schedule_touch_momentum_tick(&mut self) {
9287 self.on_next_frame(|window, cx| {
9288 if let Some(gesture) = window.touch_gestures.tick_momentum() {
9289 window.dispatch_recognized_touch_gesture(gesture, cx);
9290 }
9291 if window.touch_gestures.has_momentum() {
9292 window.schedule_touch_momentum_tick();
9293 }
9294 });
9295 }
9296
9297 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
9298 self.mouse_hit_test = self.rendered_frame.hit_test(self.mouse_position(), self.scale_factor);
9299
9300 if let Some(refiner) = self.vn_hit_refiner.clone() {
9303 let kind = if event.is::<crate::MouseDownEvent>() {
9304 Some(VnHitKind::Down)
9305 } else if event.is::<MouseUpEvent>() {
9306 Some(VnHitKind::Up)
9307 } else if event.is::<crate::ScrollEvent>() {
9308 Some(VnHitKind::Scroll)
9309 } else {
9310 None
9311 };
9312 if let Some(kind) = kind {
9313 let position = self.mouse_position();
9314 refiner(kind, position, self, cx);
9315 }
9316 }
9317
9318 #[cfg(any(feature = "inspector", debug_assertions))]
9319 if self.is_inspector_picking(cx) {
9320 self.reset_cursor_style(cx);
9321 self.handle_inspector_mouse_event(event, cx);
9322 return;
9324 }
9325
9326 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
9327
9328 for listener in &mut mouse_listeners {
9331 let listener = listener.as_mut().unwrap();
9332 listener(event, DispatchPhase::Capture, self, cx);
9333 if !cx.propagate_event {
9334 break;
9335 }
9336 }
9337
9338 if cx.propagate_event {
9340 for listener in mouse_listeners.iter_mut().rev() {
9341 let listener = listener.as_mut().unwrap();
9342 listener(event, DispatchPhase::Bubble, self, cx);
9343 if !cx.propagate_event {
9344 break;
9345 }
9346 }
9347 }
9348
9349 self.rendered_frame.mouse_listeners = mouse_listeners;
9350
9351 if cx.has_active_drag() {
9352 if event.is::<MouseMoveEvent>() {
9353 self.refresh();
9356 } else if event.is::<MouseUpEvent>() {
9357 cx.active_drag = None;
9360 self.refresh();
9361 }
9362 }
9363
9364 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
9366 self.captured_hitbox = None;
9367 }
9368
9369 self.reset_cursor_style(cx);
9372 }
9373
9374 fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
9377 let prefer_character_input = event
9378 .downcast_ref::<KeyDownEvent>()
9379 .is_some_and(|key_down_event| key_down_event.prefer_character_input);
9380 if !prefer_character_input {
9381 return InputPreference::KeyBindings;
9382 }
9383 let Some(mut input_handler) = self.platform_window.take_input_handler() else {
9384 return InputPreference::KeyBindings;
9385 };
9386 let accepts_text_input = input_handler.accepts_text_input(self, cx);
9387 self.platform_window.set_input_handler(input_handler);
9388 if accepts_text_input {
9389 InputPreference::CharacterInput
9390 } else {
9391 InputPreference::KeyBindings
9392 }
9393 }
9394
9395 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
9396 if self.invalidator.is_dirty() {
9397 self.draw(cx).clear(cx);
9398 }
9399 self.vn_key_event_seq = self.vn_key_event_seq.wrapping_add(1);
9401
9402 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
9403 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
9404
9405 let mut keystroke: Option<Keystroke> = None;
9406
9407 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
9408 if event.modifiers.number_of_modifiers() == 0
9409 && self.pending_modifier.modifiers.number_of_modifiers() == 1
9410 && !self.pending_modifier.saw_other_input
9411 {
9412 let key = match self.pending_modifier.modifiers {
9413 modifiers if modifiers.shift => Some("shift"),
9414 modifiers if modifiers.control => Some("control"),
9415 modifiers if modifiers.alt => Some("alt"),
9416 modifiers if modifiers.platform => Some("platform"),
9417 modifiers if modifiers.function => Some("function"),
9418 _ => None,
9419 };
9420 if let Some(key) = key {
9421 keystroke = Some(Keystroke {
9422 key: key.to_string(),
9423 key_char: None,
9424 modifiers: Modifiers::default(),
9425 });
9426 }
9427 }
9428
9429 if self.pending_modifier.modifiers.number_of_modifiers() == 0
9430 && event.modifiers.number_of_modifiers() == 1
9431 {
9432 self.pending_modifier.saw_other_input = false
9433 } else if event.modifiers.number_of_modifiers() > 1 {
9434 self.pending_modifier.saw_other_input = true
9435 }
9436 self.pending_modifier.modifiers = event.modifiers
9437 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
9438 self.pending_modifier.saw_other_input = true;
9439 keystroke = Some(key_down_event.keystroke.clone());
9440 if key_down_event.keystroke.key_char.is_some()
9441 && matches!(
9442 cx.cursor_hide_mode,
9443 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
9444 )
9445 {
9446 cx.platform.hide_cursor_until_mouse_moves();
9447 }
9448 }
9449
9450 let Some(keystroke) = keystroke else {
9451 self.finish_dispatch_key_event(
9452 event,
9453 None,
9454 InputPreference::KeyBindings,
9455 dispatch_path,
9456 self.context_stack(),
9457 cx,
9458 );
9459 return;
9460 };
9461
9462 let input_preference = self.input_preference(event, cx);
9463
9464 cx.propagate_event = true;
9465 self.dispatch_keystroke_interceptors(
9466 &keystroke,
9467 input_preference,
9468 self.context_stack(),
9469 cx,
9470 );
9471 if !cx.propagate_event {
9472 self.finish_dispatch_key_event(
9473 event,
9474 Some(&keystroke),
9475 input_preference,
9476 dispatch_path,
9477 self.context_stack(),
9478 cx,
9479 );
9480 return;
9481 }
9482
9483 let mut currently_pending = self.pending_input.take().unwrap_or_default();
9484 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
9485 currently_pending = PendingInput::default();
9486 }
9487
9488 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
9489 currently_pending.keystrokes,
9490 keystroke.clone(),
9491 &dispatch_path,
9492 );
9493
9494 if !match_result.to_replay.is_empty() {
9495 self.replay_pending_input(match_result.to_replay, cx);
9496 cx.propagate_event = true;
9497 }
9498
9499 if !match_result.pending.is_empty() {
9500 let previous_timeout = currently_pending.timeout.take();
9501 currently_pending.keystrokes = match_result.pending;
9502 currently_pending.focus = self.focus;
9503
9504 let text_input_requires_timeout = event
9505 .downcast_ref::<KeyDownEvent>()
9506 .filter(|key_down| key_down.keystroke.key_char.is_some())
9507 .and_then(|_| self.platform_window.take_input_handler())
9508 .map_or(false, |mut input_handler| {
9509 let accepts = input_handler.accepts_text_input(self, cx);
9510 self.platform_window.set_input_handler(input_handler);
9511 accepts
9512 });
9513
9514 let standalone_modifier = matches!(currently_pending.keystrokes.as_slice(), [keystroke] if keystroke.is_modifier_key());
9515 let needs_timeout = previous_timeout.is_some()
9516 || match_result.pending_has_binding
9517 || text_input_requires_timeout
9518 || standalone_modifier;
9519 currently_pending.timeout = if needs_timeout {
9520 match previous_timeout {
9521 Some(mut timeout) if timeout.is_paused() => {
9522 timeout.reset_duration(PENDING_INPUT_TIMEOUT);
9523 Some(timeout)
9524 }
9525 previous_timeout => {
9526 drop(previous_timeout);
9527 Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
9528 }
9529 }
9530 } else {
9531 None
9532 };
9533 self.pending_input = Some(currently_pending);
9534 self.pending_input_changed(cx);
9535 cx.propagate_event = false;
9536 return;
9537 }
9538
9539 let input_preference = self.input_preference(event, cx);
9541 if input_preference == InputPreference::KeyBindings {
9542 for binding in match_result.bindings {
9543 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
9544 if !cx.propagate_event {
9545 self.dispatch_keystroke_observers(
9546 &keystroke,
9547 input_preference,
9548 Some(binding.action.as_ref()),
9549 match_result.context_stack,
9550 cx,
9551 );
9552 self.pending_input_changed(cx);
9553 return;
9554 }
9555 }
9556 }
9557
9558 self.finish_dispatch_key_event(
9559 event,
9560 Some(&keystroke),
9561 input_preference,
9562 dispatch_path,
9563 match_result.context_stack,
9564 cx,
9565 );
9566 self.pending_input_changed(cx);
9567 }
9568
9569 fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
9570 let (started_at, task) = self.start_pending_input_timeout(duration, cx);
9571 PendingInputTimeout {
9572 duration,
9573 remaining: duration,
9574 state: PendingInputTimeoutState::Running { started_at, task },
9575 }
9576 }
9577
9578 fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
9579 let started_at = cx.background_executor().now();
9580 let task = self.spawn(cx, async move |cx| {
9581 cx.background_executor.timer(remaining).await;
9582 cx.update(move |window, cx| {
9583 let Some(currently_pending) = window
9584 .pending_input
9585 .take()
9586 .filter(|pending| pending.focus == window.focus)
9587 else {
9588 return;
9589 };
9590
9591 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
9592 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
9593
9594 let to_replay = window
9595 .rendered_frame
9596 .dispatch_tree
9597 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
9598
9599 window.pending_input_changed(cx);
9600 window.replay_pending_input(to_replay, cx)
9601 })
9602 .with_context(|| {
9603 format!(
9604 "handling pending input timeout for window {:?}",
9605 cx.window_handle().window_id()
9606 )
9607 })
9608 .log_err();
9609 });
9610 (started_at, task)
9611 }
9612
9613 fn finish_dispatch_key_event(
9614 &mut self,
9615 event: &dyn Any,
9616 recognized_keystroke: Option<&Keystroke>,
9617 input_preference: InputPreference,
9618 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
9619 context_stack: Vec<KeyContext>,
9620 cx: &mut App,
9621 ) {
9622 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
9623 if !cx.propagate_event {
9624 return;
9625 }
9626
9627 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
9628 if !cx.propagate_event {
9629 return;
9630 }
9631
9632 if let Some(keystroke) = recognized_keystroke {
9633 self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
9634 }
9635 }
9636
9637 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
9638 self.pending_input_observers
9639 .clone()
9640 .retain(|callback| callback(self, cx));
9641 }
9642
9643 fn defer_pending_input_changed(&self, cx: &mut App) {
9644 let window_handle = self.handle;
9647 cx.defer(move |cx| {
9648 window_handle
9649 .update(cx, |_, window, cx| {
9650 window.pending_input_changed(cx);
9651 })
9652 .ok();
9653 });
9654 }
9655
9656 fn dispatch_key_down_up_event(
9657 &mut self,
9658 event: &dyn Any,
9659 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
9660 cx: &mut App,
9661 ) {
9662 for node_id in dispatch_path {
9664 let node = self.rendered_frame.dispatch_tree.node(*node_id);
9665
9666 for key_listener in node.key_listeners.clone() {
9667 key_listener(event, DispatchPhase::Capture, self, cx);
9668 if !cx.propagate_event {
9669 return;
9670 }
9671 }
9672 }
9673
9674 for node_id in dispatch_path.iter().rev() {
9676 let node = self.rendered_frame.dispatch_tree.node(*node_id);
9678 for key_listener in node.key_listeners.clone() {
9679 key_listener(event, DispatchPhase::Bubble, self, cx);
9680 if !cx.propagate_event {
9681 return;
9682 }
9683 }
9684 }
9685 }
9686
9687 fn dispatch_modifiers_changed_event(
9688 &mut self,
9689 event: &dyn Any,
9690 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
9691 cx: &mut App,
9692 ) {
9693 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
9694 return;
9695 };
9696 for node_id in dispatch_path.iter().rev() {
9697 let node = self.rendered_frame.dispatch_tree.node(*node_id);
9698 for listener in node.modifiers_changed_listeners.clone() {
9699 listener(event, self, cx);
9700 if !cx.propagate_event {
9701 return;
9702 }
9703 }
9704 }
9705 }
9706
9707 pub fn has_pending_keystrokes(&self) -> bool {
9709 self.pending_input().is_some()
9710 }
9711
9712 #[cfg(test)]
9713 pub(crate) fn pending_input_is_none(&self) -> bool {
9714 self.pending_input.is_none()
9715 }
9716
9717 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
9718 if self.pending_input.take().is_some() {
9719 self.defer_pending_input_changed(cx);
9720 }
9721 }
9722
9723 pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
9726 self.pending_input
9727 .as_ref()
9728 .filter(|pending_input| pending_input.focus == self.focus)
9729 .map(|pending_input| PendingInputStatus {
9730 keystrokes: pending_input.keystrokes.as_slice(),
9731 timeout: pending_input
9732 .timeout
9733 .as_ref()
9734 .map(PendingInputTimeout::status),
9735 })
9736 }
9737
9738 pub fn set_pending_input_timeout_paused<T: 'static>(
9743 &mut self,
9744 owner: &Entity<T>,
9745 paused: bool,
9746 cx: &mut App,
9747 ) -> bool {
9748 let owner_id = owner.entity_id();
9749 if !paused {
9750 return self.resume_pending_input_timeout(owner_id, cx);
9751 }
9752
9753 let timeout = self
9754 .pending_input
9755 .as_ref()
9756 .filter(|pending_input| pending_input.focus == self.focus)
9757 .and_then(|pending_input| pending_input.timeout.as_ref());
9758 let Some(timeout) = timeout else {
9759 return false;
9760 };
9761 if timeout.is_paused() {
9762 return false;
9763 }
9764
9765 let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
9766 window.resume_pending_input_timeout(owner_id, cx);
9767 });
9768 let now = cx.background_executor().now();
9769 let changed = self
9770 .pending_input
9771 .as_mut()
9772 .filter(|pending_input| pending_input.focus == self.focus)
9773 .and_then(|pending_input| pending_input.timeout.as_mut())
9774 .is_some_and(|timeout| {
9775 timeout.pause(
9776 PendingInputTimeoutPause {
9777 owner_id,
9778 _release_subscription: release_subscription,
9779 },
9780 now,
9781 )
9782 });
9783
9784 if changed {
9785 self.defer_pending_input_changed(cx);
9786 }
9787 changed
9788 }
9789
9790 fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
9791 let Some(remaining) = self
9792 .pending_input
9793 .as_ref()
9794 .and_then(|pending_input| pending_input.timeout.as_ref())
9795 .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
9796 .map(|timeout| timeout.remaining)
9797 else {
9798 return false;
9799 };
9800
9801 let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
9802 let changed = self
9803 .pending_input
9804 .as_mut()
9805 .and_then(|pending_input| pending_input.timeout.as_mut())
9806 .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
9807
9808 if changed {
9809 self.defer_pending_input_changed(cx);
9810 }
9811 changed
9812 }
9813
9814 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
9816 self.pending_input()
9817 .map(|pending_input| pending_input.keystrokes())
9818 }
9819
9820 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
9821 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
9822 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
9823
9824 'replay: for replay in replays {
9825 let event = KeyDownEvent {
9826 keystroke: replay.keystroke.clone(),
9827 is_held: false,
9828 prefer_character_input: true,
9829 };
9830
9831 cx.propagate_event = true;
9832 for binding in replay.bindings {
9833 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
9834 if !cx.propagate_event {
9835 self.dispatch_keystroke_observers(
9836 &replay.keystroke,
9837 InputPreference::KeyBindings,
9838 Some(binding.action.as_ref()),
9839 Vec::default(),
9840 cx,
9841 );
9842 continue 'replay;
9843 }
9844 }
9845
9846 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
9847 if !cx.propagate_event {
9848 continue 'replay;
9849 }
9850 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
9851 && let Some(mut input_handler) = self.platform_window.take_input_handler()
9852 {
9853 input_handler.dispatch_input(&input, self, cx);
9854 self.platform_window.set_input_handler(input_handler)
9855 }
9856 }
9857 }
9858
9859 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
9860 focus_id
9861 .and_then(|focus_id| {
9862 self.rendered_frame
9863 .dispatch_tree
9864 .focusable_node_id(focus_id)
9865 })
9866 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
9867 }
9868
9869 fn dispatch_action_on_node(
9870 &mut self,
9871 node_id: DispatchNodeId,
9872 action: &dyn Action,
9873 cx: &mut App,
9874 ) {
9875 self.dispatch_action_on_node_inner(node_id, action, cx);
9876
9877 if !cx.propagate_event
9878 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
9879 && self.last_input_was_keyboard()
9880 {
9881 cx.platform.hide_cursor_until_mouse_moves();
9882 }
9883 }
9884
9885 fn dispatch_action_on_node_inner(
9886 &mut self,
9887 node_id: DispatchNodeId,
9888 action: &dyn Action,
9889 cx: &mut App,
9890 ) {
9891 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
9892
9893 cx.propagate_event = true;
9895 if let Some(mut global_listeners) = cx
9896 .global_action_listeners
9897 .remove(&action.as_any().type_id())
9898 {
9899 for listener in &global_listeners {
9900 #[cfg(feature = "profiler")]
9901 self.window_profiler.begin_action_handler(action, cx);
9902 listener(action.as_any(), DispatchPhase::Capture, cx);
9903 #[cfg(feature = "profiler")]
9904 self.window_profiler.end_action_handler();
9905 if !cx.propagate_event {
9906 break;
9907 }
9908 }
9909
9910 global_listeners.extend(
9911 cx.global_action_listeners
9912 .remove(&action.as_any().type_id())
9913 .unwrap_or_default(),
9914 );
9915
9916 cx.global_action_listeners
9917 .insert(action.as_any().type_id(), global_listeners);
9918 }
9919
9920 if !cx.propagate_event {
9921 return;
9922 }
9923
9924 for node_id in &dispatch_path {
9926 let node = self.rendered_frame.dispatch_tree.node(*node_id);
9927 for DispatchActionListener {
9928 action_type,
9929 listener,
9930 } in node.action_listeners.clone()
9931 {
9932 let any_action = action.as_any();
9933 if action_type == any_action.type_id() {
9934 #[cfg(feature = "profiler")]
9935 self.window_profiler.begin_action_handler(action, cx);
9936 listener(any_action, DispatchPhase::Capture, self, cx);
9937 #[cfg(feature = "profiler")]
9938 self.window_profiler.end_action_handler();
9939
9940 if !cx.propagate_event {
9941 return;
9942 }
9943 }
9944 }
9945 }
9946
9947 for node_id in dispatch_path.iter().rev() {
9949 let node = self.rendered_frame.dispatch_tree.node(*node_id);
9950 for DispatchActionListener {
9951 action_type,
9952 listener,
9953 } in node.action_listeners.clone()
9954 {
9955 let any_action = action.as_any();
9956 if action_type == any_action.type_id() {
9957 cx.propagate_event = false; #[cfg(feature = "profiler")]
9959 self.window_profiler.begin_action_handler(action, cx);
9960 listener(any_action, DispatchPhase::Bubble, self, cx);
9961 #[cfg(feature = "profiler")]
9962 self.window_profiler.end_action_handler();
9963
9964 if !cx.propagate_event {
9965 return;
9966 }
9967 }
9968 }
9969 }
9970
9971 if let Some(mut global_listeners) = cx
9973 .global_action_listeners
9974 .remove(&action.as_any().type_id())
9975 {
9976 for listener in global_listeners.iter().rev() {
9977 cx.propagate_event = false; #[cfg(feature = "profiler")]
9980 self.window_profiler.begin_action_handler(action, cx);
9981 listener(action.as_any(), DispatchPhase::Bubble, cx);
9982 #[cfg(feature = "profiler")]
9983 self.window_profiler.end_action_handler();
9984 if !cx.propagate_event {
9985 break;
9986 }
9987 }
9988
9989 global_listeners.extend(
9990 cx.global_action_listeners
9991 .remove(&action.as_any().type_id())
9992 .unwrap_or_default(),
9993 );
9994
9995 cx.global_action_listeners
9996 .insert(action.as_any().type_id(), global_listeners);
9997 }
9998 }
9999
10000 pub fn observe_global<G: Global>(
10003 &mut self,
10004 cx: &mut App,
10005 f: impl Fn(&mut Window, &mut App) + 'static,
10006 ) -> Subscription {
10007 let window_handle = self.handle;
10008 let (subscription, activate) = cx.global_observers.insert_pending(
10009 TypeId::of::<G>(),
10010 Box::new(move |cx| {
10011 window_handle
10012 .update(cx, |_, window, cx| f(window, cx))
10013 .is_ok()
10014 }),
10015 );
10016 cx.defer(move |_| activate());
10017 subscription
10018 }
10019
10020 pub fn activate_window(&self) {
10022 self.platform_window.activate();
10023 }
10024
10025 pub fn show_window(
10028 &self,
10029 activate: bool,
10030 should_show: impl FnOnce() -> bool + 'static,
10031 completed: impl FnOnce(bool) + 'static,
10032 ) -> bool {
10033 self.platform_window.show_window(activate, Box::new(should_show), Box::new(completed))
10034 }
10035
10036 pub fn request_attention(&self) {
10038 self.platform_window.request_attention();
10039 }
10040
10041 pub fn minimize_window(&self) {
10043 self.platform_window.minimize();
10044 }
10045
10046 pub fn toggle_fullscreen(&self) {
10048 self.platform_window.toggle_fullscreen();
10049 }
10050
10051 pub fn toggle_simple_fullscreen(&self) {
10056 self.platform_window.toggle_simple_fullscreen();
10057 }
10058
10059 pub fn invalidate_character_coordinates(&self) {
10061 self.on_next_frame(|window, cx| {
10062 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
10063 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
10064 window.platform_window.update_ime_position(bounds);
10065 }
10066 window.platform_window.set_input_handler(input_handler);
10067 }
10068 });
10069 }
10070
10071 pub fn prompt<T>(
10075 &mut self,
10076 level: PromptLevel,
10077 message: &str,
10078 detail: Option<&str>,
10079 answers: &[T],
10080 cx: &mut App,
10081 ) -> oneshot::Receiver<usize>
10082 where
10083 T: Clone + Into<PromptButton>,
10084 {
10085 let prompt_builder = cx.prompt_builder.take();
10086 let Some(prompt_builder) = prompt_builder else {
10087 unreachable!("Re-entrant window prompting is not supported by GPUI");
10088 };
10089
10090 let answers = answers
10091 .iter()
10092 .map(|answer| answer.clone().into())
10093 .collect::<Vec<_>>();
10094
10095 let receiver = match &prompt_builder {
10096 PromptBuilder::Default => self
10097 .platform_window
10098 .prompt(level, message, detail, &answers)
10099 .unwrap_or_else(|| {
10100 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
10101 }),
10102 PromptBuilder::Custom(_) => {
10103 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
10104 }
10105 };
10106
10107 cx.prompt_builder = Some(prompt_builder);
10108
10109 receiver
10110 }
10111
10112 fn build_custom_prompt(
10113 &mut self,
10114 prompt_builder: &PromptBuilder,
10115 level: PromptLevel,
10116 message: &str,
10117 detail: Option<&str>,
10118 answers: &[PromptButton],
10119 cx: &mut App,
10120 ) -> oneshot::Receiver<usize> {
10121 let (sender, receiver) = oneshot::channel();
10122 let handle = PromptHandle::new(sender);
10123 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
10124 self.prompt = Some(handle);
10125 receiver
10126 }
10127
10128 pub fn has_active_prompt(&self) -> bool {
10133 self.prompt.is_some()
10134 }
10135
10136 pub fn context_stack(&self) -> Vec<KeyContext> {
10138 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10139 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10140 dispatch_tree
10141 .dispatch_path(node_id)
10142 .iter()
10143 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
10144 .collect()
10145 }
10146
10147 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
10149 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10150 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
10151 for action_type in cx.global_action_listeners.keys() {
10152 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
10153 let action = cx.actions.build_action_type(action_type).ok();
10154 if let Some(action) = action {
10155 actions.insert(ix, action);
10156 }
10157 }
10158 }
10159 actions
10160 }
10161
10162 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
10165 self.rendered_frame
10166 .dispatch_tree
10167 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
10168 }
10169
10170 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
10173 self.rendered_frame
10174 .dispatch_tree
10175 .highest_precedence_binding_for_action(
10176 action,
10177 &self.rendered_frame.dispatch_tree.context_stack,
10178 )
10179 }
10180
10181 pub fn bindings_for_action_in_context(
10183 &self,
10184 action: &dyn Action,
10185 context: KeyContext,
10186 ) -> Vec<KeyBinding> {
10187 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10188 dispatch_tree.bindings_for_action(action, &[context])
10189 }
10190
10191 pub fn highest_precedence_binding_for_action_in_context(
10194 &self,
10195 action: &dyn Action,
10196 context: KeyContext,
10197 ) -> Option<KeyBinding> {
10198 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10199 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
10200 }
10201
10202 pub fn bindings_for_action_in(
10206 &self,
10207 action: &dyn Action,
10208 focus_handle: &FocusHandle,
10209 ) -> Vec<KeyBinding> {
10210 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10211 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
10212 return vec![];
10213 };
10214 dispatch_tree.bindings_for_action(action, &context_stack)
10215 }
10216
10217 pub fn highest_precedence_binding_for_action_in(
10221 &self,
10222 action: &dyn Action,
10223 focus_handle: &FocusHandle,
10224 ) -> Option<KeyBinding> {
10225 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10226 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
10227 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
10228 }
10229
10230 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
10232 self.rendered_frame
10233 .dispatch_tree
10234 .possible_next_bindings_for_input(input, &self.context_stack())
10235 }
10236
10237 fn context_stack_for_focus_handle(
10238 &self,
10239 focus_handle: &FocusHandle,
10240 ) -> Option<Vec<KeyContext>> {
10241 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10242 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
10243 let context_stack: Vec<_> = dispatch_tree
10244 .dispatch_path(node_id)
10245 .into_iter()
10246 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
10247 .collect();
10248 Some(context_stack)
10249 }
10250
10251 pub fn listener_for<T: 'static, E>(
10253 &self,
10254 view: &Entity<T>,
10255 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
10256 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
10257 let view = view.downgrade();
10258 move |e: &E, window: &mut Window, cx: &mut App| {
10259 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
10260 }
10261 }
10262
10263 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
10265 &self,
10266 entity: &Entity<E>,
10267 f: Callback,
10268 ) -> impl Fn(&mut Window, &mut App) + 'static {
10269 let entity = entity.downgrade();
10270 move |window: &mut Window, cx: &mut App| {
10271 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
10272 }
10273 }
10274
10275 pub fn on_window_should_close(
10278 &self,
10279 cx: &App,
10280 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
10281 ) {
10282 let mut cx = self.to_async(cx);
10283 self.platform_window.on_should_close(Box::new(move || {
10284 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
10285 }))
10286 }
10287
10288 pub fn on_action(
10297 &mut self,
10298 action_type: TypeId,
10299 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
10300 ) {
10301 self.invalidator.debug_assert_paint();
10302
10303 self.next_frame
10304 .dispatch_tree
10305 .on_action(action_type, Rc::new(listener));
10306 }
10307
10308 pub fn on_action_when(
10317 &mut self,
10318 condition: bool,
10319 action_type: TypeId,
10320 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
10321 ) {
10322 self.invalidator.debug_assert_paint();
10323
10324 if condition {
10325 self.next_frame
10326 .dispatch_tree
10327 .on_action(action_type, Rc::new(listener));
10328 }
10329 }
10330
10331 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
10334 self.platform_window.gpu_specs()
10335 }
10336
10337 pub fn titlebar_double_click(&self) {
10340 self.platform_window
10341 .titlebar_double_click(self.is_resizable, self.is_minimizable);
10342 }
10343
10344 pub fn window_title(&self) -> String {
10347 self.platform_window.get_title()
10348 }
10349
10350 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
10353 self.platform_window.tabbed_windows()
10354 }
10355
10356 pub fn tab_bar_visible(&self) -> bool {
10359 self.platform_window.tab_bar_visible()
10360 }
10361
10362 pub fn merge_all_windows(&self) {
10365 self.platform_window.merge_all_windows()
10366 }
10367
10368 pub fn move_tab_to_new_window(&self) {
10371 self.platform_window.move_tab_to_new_window()
10372 }
10373
10374 pub fn toggle_window_tab_overview(&self) {
10377 self.platform_window.toggle_window_tab_overview()
10378 }
10379
10380 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
10383 self.platform_window
10384 .set_tabbing_identifier(tabbing_identifier)
10385 }
10386
10387 pub fn play_system_bell(&self) {
10390 self.platform_window.play_system_bell()
10391 }
10392
10393 pub fn is_a11y_enabled(&self) -> bool {
10400 self.a11y.is_enabled()
10401 }
10402
10403 pub fn is_a11y_active(&self) -> bool {
10414 self.a11y.is_active()
10415 }
10416
10417 pub fn debug_a11y_tree_json(&self) -> Option<String> {
10419 self.a11y.debug_tree_json()
10420 }
10421
10422 pub fn on_a11y_action(
10428 &mut self,
10429 node_id: accesskit::NodeId,
10430 action: accesskit::Action,
10431 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
10432 ) {
10433 self.a11y
10434 .action_listeners
10435 .entry(node_id)
10436 .or_default()
10437 .push((action, Box::new(listener)));
10438 }
10439
10440 #[cfg(not(target_family = "wasm"))]
10441 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
10442 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
10445 let extra_data = request.data.as_ref();
10446 let mut matched = false;
10447 for (action, listener) in &mut listeners {
10448 if *action == request.action {
10449 listener(extra_data, self, cx);
10450 matched = true;
10451 }
10452 }
10453 self.a11y
10454 .action_listeners
10455 .insert(request.target_node, listeners);
10456 if matched {
10457 return;
10458 }
10459 }
10460
10461 match request.action {
10463 accesskit::Action::Click => {
10464 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
10465 let center = bounds.center();
10466 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
10467 button: MouseButton::Left,
10468 position: center,
10469 modifiers: Modifiers::default(),
10470 click_count: 1,
10471 first_mouse: false,
10472 });
10473 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
10474 button: MouseButton::Left,
10475 position: center,
10476 modifiers: Modifiers::default(),
10477 click_count: 1,
10478 });
10479 self.dispatch_event(mouse_down, cx);
10480 self.dispatch_event(mouse_up, cx);
10481 }
10482 }
10483 accesskit::Action::Focus => {
10484 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
10485 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
10486 {
10487 self.focus(&handle, cx);
10488 }
10489 }
10490 accesskit::Action::Blur => {
10491 self.blur(cx);
10492 }
10493 _ => {
10494 log::debug!(
10495 "Unhandled a11y action: {:?} on {:?}",
10496 request.action,
10497 request.target_node
10498 );
10499 }
10500 }
10501 }
10502
10503 #[cfg(any(feature = "inspector", debug_assertions))]
10505 pub fn toggle_inspector(&mut self, cx: &mut App) {
10506 self.inspector = match self.inspector {
10507 None => Some(cx.new(|_| Inspector::new())),
10508 Some(_) => {
10509 self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
10510 self.rendered_frame.inspector_hitboxes = FxHashMap::default();
10511 self.next_frame.next_inspector_instance_ids = FxHashMap::default();
10512 self.next_frame.inspector_hitboxes = FxHashMap::default();
10513 None
10514 }
10515 };
10516 self.refresh();
10517 }
10518
10519 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
10521 #[cfg(any(feature = "inspector", debug_assertions))]
10522 {
10523 if let Some(inspector) = &self.inspector {
10524 return inspector.read(_cx).is_picking();
10525 }
10526 }
10527 false
10528 }
10529
10530 #[cfg(any(feature = "inspector", debug_assertions))]
10532 pub fn with_inspector_state<T: 'static, R>(
10533 &mut self,
10534 inspector_id: Option<&crate::InspectorElementId>,
10535 cx: &mut App,
10536 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
10537 ) -> Option<R> {
10538 let inspector_id = inspector_id?;
10539 let inspector = self.inspector.as_ref()?;
10540 if inspector.read(cx).active_element_id() != Some(inspector_id) {
10541 return None;
10542 }
10543 let inspector = inspector.clone();
10544 Some(inspector.update(cx, |inspector, _cx| {
10545 inspector.with_active_element_state(self, f)
10546 }))
10547 }
10548
10549 #[cfg(any(feature = "inspector", debug_assertions))]
10550 pub(crate) fn inspector_enabled(&self) -> bool {
10551 self.inspector.is_some()
10552 }
10553
10554 #[cfg(any(feature = "inspector", debug_assertions))]
10555 pub(crate) fn build_inspector_element_id(
10556 &mut self,
10557 path: crate::InspectorElementPath,
10558 ) -> crate::InspectorElementId {
10559 self.invalidator.debug_assert_paint_or_prepaint();
10560 let path = Rc::new(path);
10561 let next_instance_id = self
10562 .next_frame
10563 .next_inspector_instance_ids
10564 .entry(path.clone())
10565 .or_insert(0);
10566 let instance_id = *next_instance_id;
10567 *next_instance_id += 1;
10568 crate::InspectorElementId { path, instance_id }
10569 }
10570
10571 #[cfg(any(feature = "inspector", debug_assertions))]
10572 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
10573 if let Some(inspector) = self.inspector.take() {
10574 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
10575 inspector_element.prepaint_as_root(
10576 point(self.viewport_size.width - inspector_width, px(0.0)),
10577 size(inspector_width, self.viewport_size.height).into(),
10578 self,
10579 cx,
10580 );
10581 self.inspector = Some(inspector);
10582 Some(inspector_element)
10583 } else {
10584 None
10585 }
10586 }
10587
10588 #[cfg(any(feature = "inspector", debug_assertions))]
10589 fn paint_inspector(&mut self, inspector_element: Option<AnyElement>, cx: &mut App) {
10590 if let Some(mut inspector_element) = inspector_element {
10591 inspector_element.paint(self, cx);
10592 };
10593 }
10594
10595 #[cfg(any(feature = "inspector", debug_assertions))]
10598 pub fn insert_inspector_hitbox(
10599 &mut self,
10600 hitbox_id: HitboxId,
10601 inspector_id: Option<&crate::InspectorElementId>,
10602 cx: &App,
10603 ) {
10604 self.invalidator.debug_assert_paint_or_prepaint();
10605 if !self.is_inspector_picking(cx) {
10606 return;
10607 }
10608 if let Some(inspector_id) = inspector_id {
10609 self.next_frame
10610 .inspector_hitboxes
10611 .insert(hitbox_id, inspector_id.clone());
10612 }
10613 }
10614
10615 #[cfg(any(feature = "inspector", debug_assertions))]
10616 fn paint_inspector_hitbox(&mut self, cx: &App) {
10617 if let Some(inspector) = self.inspector.as_ref() {
10618 let inspector = inspector.read(cx);
10619 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
10620 && let Some(hitbox) = self
10621 .next_frame
10622 .hitboxes
10623 .iter()
10624 .find(|hitbox| hitbox.id == hitbox_id)
10625 {
10626 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
10627 }
10628 }
10629 }
10630
10631 #[cfg(any(feature = "inspector", debug_assertions))]
10632 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
10633 let Some(inspector) = self.inspector.clone() else {
10634 return;
10635 };
10636 if event.downcast_ref::<MouseMoveEvent>().is_some() {
10637 inspector.update(cx, |inspector, _cx| {
10638 if let Some((_, inspector_id)) =
10639 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10640 {
10641 inspector.hover(inspector_id, self);
10642 }
10643 });
10644 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
10645 inspector.update(cx, |inspector, _cx| {
10646 if let Some((_, inspector_id)) =
10647 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10648 {
10649 inspector.select(inspector_id, self);
10650 }
10651 });
10652 } else if let Some(event) = event.downcast_ref::<crate::ScrollEvent>() {
10653 const SCROLL_LINES: f32 = 3.0;
10655 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
10656 let delta_y = event
10657 .delta
10658 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
10659 .y;
10660 if let Some(inspector) = self.inspector.clone() {
10661 inspector.update(cx, |inspector, _cx| {
10662 if let Some(depth) = inspector.pick_depth.as_mut() {
10663 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
10664 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
10665 if *depth < 0.0 {
10666 *depth = 0.0;
10667 } else if *depth > max_depth {
10668 *depth = max_depth;
10669 }
10670 if let Some((_, inspector_id)) =
10671 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10672 {
10673 inspector.set_active_element_id(inspector_id, self);
10674 }
10675 }
10676 });
10677 }
10678 }
10679 }
10680
10681 #[cfg(any(feature = "inspector", debug_assertions))]
10682 fn hovered_inspector_hitbox(
10683 &self,
10684 inspector: &Inspector,
10685 frame: &Frame,
10686 ) -> Option<(HitboxId, crate::InspectorElementId)> {
10687 if let Some(pick_depth) = inspector.pick_depth {
10688 let depth = (pick_depth as i64).try_into().unwrap_or(0);
10689 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
10690 let skip_count = (depth as usize).min(max_skipped);
10691 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
10692 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
10693 return Some((*hitbox_id, inspector_id.clone()));
10694 }
10695 }
10696 }
10697 None
10698 }
10699
10700 #[cfg(any(test, feature = "test-support"))]
10703 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
10704 self.modifiers = modifiers;
10705 }
10706
10707 #[cfg(any(test, feature = "test-support"))]
10711 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
10712 let event = PlatformInput::MouseMove(MouseMoveEvent {
10713 position,
10714 modifiers: self.modifiers,
10715 pressed_button: None,
10716 });
10717 let _ = self.dispatch_event(event, cx);
10718 }
10719
10720 #[inline(never)]
10721 fn take_element_state(
10722 &mut self,
10723 global_id: &GlobalElementId,
10724 state_type: TypeId,
10725 ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
10726 let key = (global_id.clone(), state_type);
10727 self.next_frame.accessed_element_states.push(key.clone());
10728 let state = self
10729 .next_frame
10730 .element_states
10731 .remove(&key)
10732 .or_else(|| self.rendered_frame.element_states.remove(&key));
10733 (key, state)
10734 }
10735
10736 #[inline(never)]
10737 fn insert_element_state(
10738 &mut self,
10739 key: (GlobalElementId, TypeId),
10740 state: ElementStateBox,
10741 ) -> Option<ElementStateBox> {
10742 self.next_frame.element_states.insert(key, state)
10743 }
10744
10745 #[inline(never)]
10746 fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
10747 cx.observe(state, move |_, cx| {
10748 cx.notify(current_view);
10749 })
10750 .detach();
10751 }
10752}
10753
10754slotmap::new_key_type! {
10756 pub struct WindowId;
10758}
10759
10760impl WindowId {
10761 pub fn as_u64(&self) -> u64 {
10763 self.0.as_ffi()
10764 }
10765}
10766
10767impl From<u64> for WindowId {
10768 fn from(value: u64) -> Self {
10769 WindowId(slotmap::KeyData::from_ffi(value))
10770 }
10771}
10772
10773pub struct WindowHandle<V> {
10776 pub(crate) any_handle: AnyWindowHandle,
10777 state_type: PhantomData<fn(V) -> V>,
10778}
10779
10780impl_deref!([V] WindowHandle<V> => mut any_handle: AnyWindowHandle);
10781
10782impl<V> Debug for WindowHandle<V> {
10783 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10784 f.debug_struct("WindowHandle")
10785 .field("any_handle", &self.any_handle.id.as_u64())
10786 .finish()
10787 }
10788}
10789
10790impl<V: 'static + Render> WindowHandle<V> {
10791 pub fn new(id: WindowId) -> Self {
10794 WindowHandle {
10795 any_handle: AnyWindowHandle {
10796 id,
10797 state_type: TypeId::of::<V>(),
10798 root_entity_type_name: std::any::type_name::<V>(),
10799 },
10800 state_type: PhantomData,
10801 }
10802 }
10803
10804 #[cfg(any(test, feature = "test-support"))]
10808 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
10809 where
10810 C: AppContext,
10811 {
10812 cx.update_window(self.any_handle, |root_view, _, _| {
10813 root_view
10814 .downcast::<V>()
10815 .map_err(|_| anyhow!("the type of the window's root view has changed"))
10816 })?
10817 }
10818
10819 #[track_caller]
10823 pub fn update<C, R>(
10824 &self,
10825 cx: &mut C,
10826 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
10827 ) -> Result<R>
10828 where
10829 C: AppContext,
10830 {
10831 cx.update_window(self.any_handle, |root_view, window, cx| {
10832 let view = root_view
10833 .downcast::<V>()
10834 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
10835
10836 Ok(view.update(cx, |view, cx| update(view, window, cx)))
10837 })?
10838 }
10839
10840 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
10844 let x = cx
10845 .windows
10846 .get(self.id)
10847 .and_then(|window| {
10848 window
10849 .as_deref()
10850 .and_then(|window| window.root.clone())
10851 .map(|root_view| root_view.downcast::<V>())
10852 })
10853 .context("window not found")?
10854 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
10855
10856 Ok(x.read(cx))
10857 }
10858
10859 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
10863 where
10864 C: AppContext,
10865 {
10866 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
10867 }
10868
10869 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
10873 where
10874 C: AppContext,
10875 {
10876 cx.read_window(self, |root_view, _cx| root_view)
10877 }
10878
10879 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
10884 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
10885 .ok()
10886 }
10887}
10888
10889impl<V> Copy for WindowHandle<V> {}
10890
10891impl<V> Clone for WindowHandle<V> {
10892 fn clone(&self) -> Self {
10893 *self
10894 }
10895}
10896
10897impl<V> PartialEq for WindowHandle<V> {
10898 fn eq(&self, other: &Self) -> bool {
10899 self.any_handle == other.any_handle
10900 }
10901}
10902
10903impl<V> Eq for WindowHandle<V> {}
10904
10905impl<V> Hash for WindowHandle<V> {
10906 fn hash<H: Hasher>(&self, state: &mut H) {
10907 self.any_handle.hash(state);
10908 }
10909}
10910
10911impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
10912 fn from(val: WindowHandle<V>) -> Self {
10913 val.any_handle
10914 }
10915}
10916
10917#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
10919pub struct AnyWindowHandle {
10920 pub(crate) id: WindowId,
10921 state_type: TypeId,
10922 root_entity_type_name: &'static str,
10923}
10924
10925impl AnyWindowHandle {
10926 pub fn window_id(&self) -> WindowId {
10928 self.id
10929 }
10930
10931 pub fn root_entity_type_name(&self) -> &'static str {
10933 self.root_entity_type_name
10934 }
10935
10936 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
10939 if TypeId::of::<T>() == self.state_type {
10940 Some(WindowHandle {
10941 any_handle: *self,
10942 state_type: PhantomData,
10943 })
10944 } else {
10945 None
10946 }
10947 }
10948
10949 #[track_caller]
10953 pub fn update<C, R>(
10954 self,
10955 cx: &mut C,
10956 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
10957 ) -> Result<R>
10958 where
10959 C: AppContext,
10960 {
10961 cx.update_window(self, update)
10962 }
10963
10964 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
10968 where
10969 C: AppContext,
10970 T: 'static,
10971 {
10972 let view = self
10973 .downcast::<T>()
10974 .context("the type of the window's root view has changed")?;
10975
10976 cx.read_window(&view, read)
10977 }
10978}
10979
10980impl HasWindowHandle for Window {
10981 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
10982 self.platform_window.window_handle()
10983 }
10984}
10985
10986impl HasDisplayHandle for Window {
10987 fn display_handle(
10988 &self,
10989 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
10990 self.platform_window.display_handle()
10991 }
10992}
10993
10994#[derive(Clone, Debug, Eq, PartialEq, Hash)]
10999pub enum ElementId {
11000 View(EntityId),
11002 Integer(u64),
11004 Name(SharedString),
11006 Uuid(Uuid),
11008 FocusHandle(FocusId),
11010 NamedInteger(SharedString, u64),
11012 Path(Arc<std::path::Path>),
11014 CodeLocation(core::panic::Location<'static>),
11016 NamedChild(Arc<ElementId>, SharedString),
11018 OpaqueId([u8; 20]),
11020}
11021
11022impl ElementId {
11023 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
11025 Self::NamedInteger(name.into(), integer as u64)
11026 }
11027}
11028
11029impl Display for ElementId {
11030 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11031 match self {
11032 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
11033 ElementId::Integer(ix) => write!(f, "{}", ix)?,
11034 ElementId::Name(name) => write!(f, "{}", name)?,
11035 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
11036 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
11037 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
11038 ElementId::Path(path) => write!(f, "{}", path.display())?,
11039 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
11040 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
11041 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
11042 }
11043
11044 Ok(())
11045 }
11046}
11047
11048impl TryInto<SharedString> for ElementId {
11049 type Error = anyhow::Error;
11050
11051 fn try_into(self) -> anyhow::Result<SharedString> {
11052 if let ElementId::Name(name) = self {
11053 Ok(name)
11054 } else {
11055 anyhow::bail!("element id is not string")
11056 }
11057 }
11058}
11059
11060impl From<u64> for ElementId {
11061 fn from(id: u64) -> Self {
11062 ElementId::Integer(id)
11063 }
11064}
11065
11066impl From<usize> for ElementId {
11067 fn from(id: usize) -> Self {
11068 ElementId::Integer(id as u64)
11069 }
11070}
11071
11072impl From<i32> for ElementId {
11073 fn from(id: i32) -> Self {
11074 Self::Integer(id as u64)
11075 }
11076}
11077
11078impl From<SharedString> for ElementId {
11079 fn from(name: SharedString) -> Self {
11080 ElementId::Name(name)
11081 }
11082}
11083
11084impl From<String> for ElementId {
11085 fn from(name: String) -> Self {
11086 ElementId::Name(name.into())
11087 }
11088}
11089
11090impl From<Arc<str>> for ElementId {
11091 fn from(name: Arc<str>) -> Self {
11092 ElementId::Name(name.into())
11093 }
11094}
11095
11096impl From<Arc<std::path::Path>> for ElementId {
11097 fn from(path: Arc<std::path::Path>) -> Self {
11098 ElementId::Path(path)
11099 }
11100}
11101
11102impl From<&'static str> for ElementId {
11103 fn from(name: &'static str) -> Self {
11104 ElementId::Name(SharedString::new_static(name))
11105 }
11106}
11107
11108impl<'a> From<&'a FocusHandle> for ElementId {
11109 fn from(handle: &'a FocusHandle) -> Self {
11110 ElementId::FocusHandle(handle.id)
11111 }
11112}
11113
11114impl From<(&'static str, EntityId)> for ElementId {
11115 fn from((name, id): (&'static str, EntityId)) -> Self {
11116 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
11117 }
11118}
11119
11120impl From<(&'static str, usize)> for ElementId {
11121 fn from((name, id): (&'static str, usize)) -> Self {
11122 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
11123 }
11124}
11125
11126impl From<(SharedString, usize)> for ElementId {
11127 fn from((name, id): (SharedString, usize)) -> Self {
11128 ElementId::NamedInteger(name, id as u64)
11129 }
11130}
11131
11132impl From<(&'static str, u64)> for ElementId {
11133 fn from((name, id): (&'static str, u64)) -> Self {
11134 ElementId::NamedInteger(SharedString::new_static(name), id)
11135 }
11136}
11137
11138impl From<Uuid> for ElementId {
11139 fn from(value: Uuid) -> Self {
11140 Self::Uuid(value)
11141 }
11142}
11143
11144impl From<(&'static str, u32)> for ElementId {
11145 fn from((name, id): (&'static str, u32)) -> Self {
11146 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
11147 }
11148}
11149
11150impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
11151 fn from((id, name): (ElementId, T)) -> Self {
11152 ElementId::NamedChild(Arc::new(id), name.into())
11153 }
11154}
11155
11156impl From<&'static core::panic::Location<'static>> for ElementId {
11157 fn from(location: &'static core::panic::Location<'static>) -> Self {
11158 ElementId::CodeLocation(*location)
11159 }
11160}
11161
11162impl From<[u8; 20]> for ElementId {
11163 fn from(opaque_id: [u8; 20]) -> Self {
11164 ElementId::OpaqueId(opaque_id)
11165 }
11166}
11167
11168#[derive(Clone)]
11171pub struct PaintQuad {
11172 pub bounds: Bounds<Pixels>,
11174 pub corner_radii: Corners<Pixels>,
11176 pub background: Background,
11178 pub border_widths: Edges<Pixels>,
11180 pub border_color: Hsla,
11182 pub border_style: BorderStyle,
11184}
11185
11186#[derive(Clone, Copy, Debug)]
11188pub struct BackdropBlurEffect {
11189 pub radius: Pixels,
11195 pub tint: Hsla,
11201}
11202
11203impl BackdropBlurEffect {
11204 pub fn new(radius: Pixels) -> Self {
11208 Self {
11209 radius,
11210 ..Self::default()
11211 }
11212 }
11213
11214 pub fn tint(mut self, tint: impl Into<Hsla>) -> Self {
11216 self.tint = tint.into();
11217 self
11218 }
11219}
11220
11221impl Default for BackdropBlurEffect {
11222 fn default() -> Self {
11223 Self {
11224 radius: px(20.),
11225 tint: transparent_black(),
11226 }
11227 }
11228}
11229
11230impl PaintQuad {
11231 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
11233 PaintQuad {
11234 corner_radii: corner_radii.into(),
11235 ..self
11236 }
11237 }
11238
11239 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
11241 PaintQuad {
11242 border_widths: border_widths.into(),
11243 ..self
11244 }
11245 }
11246
11247 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
11249 PaintQuad {
11250 border_color: border_color.into(),
11251 ..self
11252 }
11253 }
11254
11255 pub fn background(self, background: impl Into<Background>) -> Self {
11257 PaintQuad {
11258 background: background.into(),
11259 ..self
11260 }
11261 }
11262}
11263
11264pub type ImageResampler =
11275 fn(&Arc<RenderImage>, usize, Size<DevicePixels>) -> Option<Arc<RenderImage>>;
11276
11277static IMAGE_RESAMPLER: std::sync::OnceLock<ImageResampler> = std::sync::OnceLock::new();
11278
11279pub fn set_image_resampler(resampler: ImageResampler) {
11282 let _ = IMAGE_RESAMPLER.set(resampler);
11283}
11284
11285pub fn quad(
11287 bounds: Bounds<Pixels>,
11288 corner_radii: impl Into<Corners<Pixels>>,
11289 background: impl Into<Background>,
11290 border_widths: impl Into<Edges<Pixels>>,
11291 border_color: impl Into<Hsla>,
11292 border_style: BorderStyle,
11293) -> PaintQuad {
11294 PaintQuad {
11295 bounds,
11296 corner_radii: corner_radii.into(),
11297 background: background.into(),
11298 border_widths: border_widths.into(),
11299 border_color: border_color.into(),
11300 border_style,
11301 }
11302}
11303
11304pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
11306 PaintQuad {
11307 bounds: bounds.into(),
11308 corner_radii: (0.).into(),
11309 background: background.into(),
11310 border_widths: (0.).into(),
11311 border_color: transparent_black(),
11312 border_style: BorderStyle::default(),
11313 }
11314}
11315
11316pub fn outline(
11318 bounds: impl Into<Bounds<Pixels>>,
11319 border_color: impl Into<Hsla>,
11320 border_style: BorderStyle,
11321) -> PaintQuad {
11322 PaintQuad {
11323 bounds: bounds.into(),
11324 corner_radii: (0.).into(),
11325 background: transparent_black().into(),
11326 border_widths: (1.).into(),
11327 border_color: border_color.into(),
11328 border_style,
11329 }
11330}
11331
11332pub(crate) const SHADOW_OUTSIDE_BOX: u32 = 0;
11335pub(crate) const SHADOW_INSET: u32 = 1;
11337pub(crate) const SHADOW_UNDER_BOX: u32 = 2;
11340
11341fn spread_shadow_radius(radius: Pixels, spread: Pixels) -> Pixels {
11347 if spread <= Pixels::ZERO {
11348 return (radius + spread).max(Pixels::ZERO);
11349 }
11350 let ratio = radius / spread;
11351 if ratio >= 1.0 {
11352 radius + spread
11353 } else {
11354 radius + spread * (1.0 + (ratio - 1.0).powi(3))
11355 }
11356}
11357
11358#[inline(never)]
11359fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
11360 if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
11361 let arena_cell = unsafe { &*arena_pointer };
11364 callback(&mut arena_cell.borrow_mut());
11365 Ok(())
11366 } else {
11367 ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
11368 }
11369}
11370
11371#[cfg(test)]
11372mod tests {
11373 use std::{
11374 cell::{Cell, RefCell},
11375 path::PathBuf,
11376 rc::Rc,
11377 time::Duration,
11378 };
11379
11380 use crate::{
11381 AnyWindowHandle, AppContext as _, BackGestureEvent, BackGesturePhase, Bounds, ContentMask,
11382 Context, CursorStyle, DispatchPhase, DragMoveEvent, Empty, ExternalDragPayload,
11383 ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle, InputEvent as _,
11384 InteractiveElement as _, IntoElement, KeyDownEvent, Keystroke, LongPressEvent, MouseButton,
11385 MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, PlatformInput, Point,
11386 Render, RequestFrameOptions, ScaledPixels, StatefulInteractiveElement as _, Styled,
11387 TestAppContext, ThermalState, TouchDragEvent, TouchEvent, TouchId, TouchPhase, Underline,
11388 UnderlineStyle, Window, WindowAppearance, WindowOptions, canvas, div, hsla, point, px,
11389 size,
11390 };
11391
11392 #[gpui::test]
11393 async fn test_focus_handle_release(cx: &mut TestAppContext) {
11394 let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
11395 let handle_id = handle.id;
11396 let weak_handle = handle.downgrade();
11397 let retained = handle.clone();
11398 drop(handle);
11399
11400 cx.update(|_| {});
11401 cx.read(|cx| {
11402 let handles = cx.focus_handles.read();
11403 assert_eq!(handles.handles.len(), 2);
11404 assert!(handles.dropped_handles.is_empty());
11405 });
11406 assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));
11407
11408 cx.background_spawn(async move { drop(retained) }).await;
11409 assert_eq!(weak_handle.upgrade(), None);
11410 cx.read(|cx| {
11411 assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);
11412 });
11413 cx.update(|_| {});
11414 cx.read(|cx| {
11415 let handles = cx.focus_handles.read();
11416 assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);
11417 assert!(handles.dropped_handles.is_empty());
11418 });
11419
11420 let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);
11421 assert_eq!(weak_handle.upgrade(), None);
11422 cx.update(|cx| {
11423 drop(replacements);
11424 cx.defer(move |_| drop(survivor));
11425 });
11426 cx.read(|cx| {
11427 let handles = cx.focus_handles.read();
11428 assert_eq!(handles.handles.len(), 0);
11429 assert!(handles.dropped_handles.is_empty());
11430 });
11431 }
11432
11433 #[gpui::test]
11434 fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {
11435 let windows = [
11436 cx.add_window(|_, _| EmptyView),
11437 cx.add_window(|_, _| EmptyView),
11438 cx.add_window(|_, _| EmptyView),
11439 cx.add_window(|_, _| EmptyView),
11440 cx.add_window(|_, _| EmptyView),
11441 ];
11442 let (handle, other_handle, survivor) =
11443 cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));
11444 for window in &windows[..2] {
11445 window
11446 .update(cx, |_, window, cx| window.focus(&handle, cx))
11447 .expect("window exists");
11448 }
11449 windows[2]
11450 .update(cx, |_, window, cx| window.focus(&other_handle, cx))
11451 .expect("window exists");
11452 windows[3]
11453 .update(cx, |_, window, cx| window.focus(&survivor, cx))
11454 .expect("window exists");
11455
11456 cx.update(|cx| {
11457 for _ in 0..1_000 {
11458 drop(cx.focus_handle());
11459 }
11460 drop((handle, other_handle));
11461 });
11462 for window in &windows[..3] {
11463 window
11464 .update(cx, |_, window, _| assert_eq!(window.focus, None))
11465 .expect("window exists");
11466 }
11467 windows[3]
11468 .update(cx, |_, window, cx| {
11469 assert_eq!(window.focused(cx).as_ref(), Some(&survivor));
11470 assert_eq!(window.focus_generation, 1);
11471 })
11472 .expect("window exists");
11473 windows[4]
11474 .update(cx, |_, window, _| {
11475 assert_eq!(window.focus, None);
11476 assert_eq!(window.focus_generation, 0);
11477 })
11478 .expect("window exists");
11479 }
11480
11481 #[gpui::test]
11482 fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
11483 let window = cx.add_window(|_, _| EmptyView);
11484 let platform_window = cx.test_window(window.into());
11485 {
11486 let app = cx.app.borrow_mut();
11487 platform_window.simulate_close();
11488 assert!(app.windows.contains_key(window.window_id()));
11489 }
11490 cx.run_until_parked();
11491 assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
11492 }
11493
11494 #[cfg(feature = "profiler")]
11495 #[gpui::test]
11496 fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
11497 use crate::FrameRequestSource;
11498 use crate::profiler::journal::{
11499 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
11500 };
11501 use scheduler::Instant;
11502
11503 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
11504 let window = cx.add_window(|_, _| EmptyView);
11505 let platform_window = cx.test_window(window.into());
11506 platform_window.simulate_frame_request(RequestFrameOptions::default());
11507 let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
11508 let mut collector = journal.collector();
11509
11510 for (signal_at, source) in [
11511 (Some(Instant::now()), FrameRequestSource::NativeCallback),
11512 (Some(Instant::now()), FrameRequestSource::LocalSchedule),
11513 (None, FrameRequestSource::NativeCallback),
11514 ] {
11515 platform_window.simulate_frame_request(RequestFrameOptions {
11516 signal_at,
11517 signal_source: source,
11518 require_presentation: true,
11519 ..Default::default()
11520 });
11521 let entries = collector.collect_unseen().entries;
11522 let signal_index = entries
11523 .iter()
11524 .position(|entry| {
11525 matches!(
11526 entry,
11527 ForegroundJournalEntry::PlatformSignal(signal)
11528 if signal.window_id == window.window_id()
11529 && signal.signal_at == signal_at
11530 && signal.source == source
11531 && signal_at.is_none_or(|at| signal.handled_at >= at)
11532 )
11533 })
11534 .expect("frame request metadata");
11535 let skip_index = entries
11536 .iter()
11537 .position(|entry| {
11538 matches!(
11539 entry,
11540 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
11541 if skipped.window_id == window.window_id()
11542 && skipped.reason == FrameSkipReason::NoRenderNeeded
11543 )
11544 })
11545 .expect("completed no-render boundary");
11546 assert!(signal_index < skip_index);
11547 }
11548 }
11549
11550 #[cfg(feature = "profiler")]
11551 #[gpui::test]
11552 fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
11553 use crate::profiler::journal::{
11554 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
11555 };
11556 use scheduler::Instant;
11557
11558 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
11560 let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
11561 let mut collector = journal.collector();
11562 for (initially_dirty, schedule_callback) in [(true, false), (false, true)] {
11563 let window = cx
11565 .app
11566 .borrow_mut()
11567 .open_window(
11568 WindowOptions {
11569 inactive_frame_interval: Some(Duration::from_secs(3600)),
11570 ..Default::default()
11571 },
11572 |_, cx| cx.new(|_| EmptyView),
11573 )
11574 .expect("open inactive test window");
11575 let platform_window = cx.test_window(window.into());
11576 platform_window.simulate_active_status_change(false);
11577 platform_window.simulate_frame_request(RequestFrameOptions::default());
11578 let callback_ran = Rc::new(Cell::new(false));
11579 let draws_before = window
11580 .update(cx, |_, window, _| {
11581 let draws_before = window
11582 .frame_duration_snapshot()
11583 .draw_duration_histogram
11584 .len();
11585 if initially_dirty {
11586 window.refresh();
11587 }
11588 if schedule_callback {
11589 window.on_next_frame({
11590 let callback_ran = callback_ran.clone();
11591 move |window, _| {
11592 callback_ran.set(true);
11593 window.refresh();
11594 }
11595 });
11596 }
11597 draws_before
11598 })
11599 .expect("schedule throttled frame");
11600 let input_at = Instant::now();
11602 journal::record_input(journal::InputTiming {
11603 kind: "test",
11604 start: input_at,
11605 end: input_at,
11606 caused_invalidation: false,
11607 });
11608 collector.collect_unseen();
11609 let wakes_before = platform_window.frame_wake_count();
11610 platform_window.simulate_frame_request(RequestFrameOptions {
11611 signal_at: Some(Instant::now()),
11612 ..Default::default()
11613 });
11614 window
11615 .update(cx, |_, window, _| {
11616 assert_eq!(
11617 window
11618 .frame_duration_snapshot()
11619 .draw_duration_histogram
11620 .len(),
11621 draws_before,
11622 );
11623 })
11624 .expect("inspect deferred frame");
11625 assert!(!callback_ran.get());
11626 assert!(platform_window.frame_scheduled());
11627 assert!(platform_window.frame_wake_count() > wakes_before);
11628 assert!(collector.collect_unseen().entries.iter().any(|entry| {
11629 matches!(
11630 entry,
11631 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
11632 if skipped.window_id == window.window_id()
11633 && skipped.reason == FrameSkipReason::InactiveFrameRateLimit
11634 )
11635 }));
11636 platform_window.simulate_frame_request(RequestFrameOptions {
11637 signal_at: Some(Instant::now()),
11638 require_presentation: true,
11639 ..Default::default()
11640 });
11641 window
11642 .update(cx, |_, window, _| {
11643 assert_eq!(
11644 window
11645 .frame_duration_snapshot()
11646 .draw_duration_histogram
11647 .len(),
11648 draws_before + 1,
11649 );
11650 })
11651 .expect("inspect presented frame");
11652 assert_eq!(callback_ran.get(), schedule_callback);
11653 }
11654 }
11655
11656 #[gpui::test]
11659 fn test_debug_state_reports_cached_and_platform_values(cx: &mut TestAppContext) {
11660 use crate::WindowVisibility;
11661
11662 let window = cx.add_window(|_, _| EmptyView);
11663 let window_id = window.window_id().as_u64();
11664 let window_state = |cx: &mut TestAppContext| {
11665 let state = cx.update(|cx| cx.debug_state());
11666 state["windows"]
11667 .as_array()
11668 .and_then(|windows| windows.iter().find(|window| window["id"] == window_id))
11669 .cloned()
11670 .expect("the open window is listed")
11671 };
11672
11673 let state = window_state(cx);
11674 assert_eq!(state["visibility"]["cached"], "Visible");
11675 assert_eq!(state["visibility"]["platform"], "Visible");
11676
11677 cx.test_window(window.into())
11678 .simulate_visibility_change(WindowVisibility::Hidden);
11679 let state = window_state(cx);
11680 assert_eq!(state["visibility"]["cached"], "Hidden");
11681 assert_eq!(state["visibility"]["platform"], "Hidden");
11682 }
11683
11684 #[gpui::test]
11688 fn test_window_visibility(cx: &mut TestAppContext) {
11689 use crate::WindowVisibility;
11690
11691 let window = cx.add_window(|_, _| EmptyView);
11692 let observed = Rc::new(RefCell::new(Vec::new()));
11693 let _subscription = window
11694 .update(cx, {
11695 let observed = observed.clone();
11696 move |_, window, _| {
11697 assert_eq!(window.visibility(), WindowVisibility::Visible);
11698 assert!(window.is_visible());
11699 window.observe_window_visibility(move |visibility, window, _| {
11700 assert_eq!(window.visibility(), visibility);
11701 observed.borrow_mut().push(visibility);
11702 })
11703 }
11704 })
11705 .unwrap();
11706 let test_window = cx.test_window(window.into());
11707 let frame_wake_count = test_window.frame_wake_count();
11708
11709 test_window.simulate_visibility_change(WindowVisibility::Hidden);
11710 assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
11711 window
11712 .update(cx, |_, window, _| assert!(!window.is_visible()))
11713 .unwrap();
11714
11715 test_window.simulate_visibility_change(WindowVisibility::Hidden);
11717 assert_eq!(observed.borrow().len(), 1);
11718
11719 test_window.simulate_visibility_change(WindowVisibility::Visible);
11720 assert_eq!(
11721 *observed.borrow(),
11722 [WindowVisibility::Hidden, WindowVisibility::Visible]
11723 );
11724 window
11725 .update(cx, |_, window, _| assert!(window.is_visible()))
11726 .unwrap();
11727 assert_eq!(test_window.frame_wake_count(), frame_wake_count);
11728 }
11729
11730 #[gpui::test]
11733 fn test_display_tracking(cx: &mut TestAppContext) {
11734 use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
11735
11736 let sixty_hertz = Duration::from_secs(1) / 60;
11737 let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
11738 let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
11739
11740 let display_events = Rc::new(RefCell::new(Vec::new()));
11741 let _display_subscription = cx.update({
11742 let display_events = display_events.clone();
11743 move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
11744 });
11745
11746 let window = cx.add_window(|window, cx| DisplayTracker {
11747 refresh_intervals: Vec::new(),
11748 _subscription: cx.observe_window_display(
11749 window,
11750 |tracker: &mut DisplayTracker, window, cx| {
11751 tracker.refresh_intervals.push(window.refresh_interval(cx));
11752 },
11753 ),
11754 });
11755 let window_notifications = Rc::new(RefCell::new(Vec::new()));
11756 let _window_subscription = window
11757 .update(cx, {
11758 let window_notifications = window_notifications.clone();
11759 move |_, window, cx| {
11760 assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
11761 window.observe_window_display(move |window, cx| {
11762 window_notifications
11763 .borrow_mut()
11764 .push((window.display_id, window.refresh_interval(cx)));
11765 })
11766 }
11767 })
11768 .unwrap();
11769 let test_window = cx.test_window(window.into());
11770
11771 cx.test_platform()
11776 .connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
11777 test_window.simulate_move_to_display(DisplayId(2));
11778 assert_eq!(
11779 window_notifications.take(),
11780 [(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
11781 );
11782 assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
11783 cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
11784 assert!(window_notifications.borrow().is_empty());
11785
11786 test_window.simulate_move_to_display(DisplayId(2));
11788 assert!(window_notifications.borrow().is_empty());
11789
11790 cx.simulate_display_refresh_interval_change(
11791 DisplayId(2),
11792 Some(one_hundred_forty_four_hertz),
11793 );
11794 assert_eq!(
11795 window_notifications.take(),
11796 [(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
11797 );
11798
11799 cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
11801 cx.simulate_display_removed(DisplayId(1));
11802 assert!(window_notifications.borrow().is_empty());
11803
11804 assert_eq!(
11805 display_events.take(),
11806 [
11807 DisplayEvent::Changed {
11808 id: DisplayId(2),
11809 changes: DisplayChanges::REFRESH_INTERVAL,
11810 },
11811 DisplayEvent::Changed {
11812 id: DisplayId(1),
11813 changes: DisplayChanges::REFRESH_INTERVAL,
11814 },
11815 DisplayEvent::Removed(DisplayId(1)),
11816 ]
11817 );
11818 window
11819 .update(cx, |tracker, _, _| {
11820 assert_eq!(
11821 tracker.refresh_intervals,
11822 [
11823 Some(one_hundred_twenty_hertz),
11824 Some(one_hundred_forty_four_hertz)
11825 ]
11826 );
11827 })
11828 .unwrap();
11829
11830 struct DisplayTracker {
11831 refresh_intervals: Vec<Option<Duration>>,
11832 _subscription: Subscription,
11833 }
11834
11835 impl Render for DisplayTracker {
11836 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
11837 Empty
11838 }
11839 }
11840 }
11841
11842 #[gpui::test]
11843 fn test_window_opened_from_bounds_observer_uses_new_bounds(cx: &mut TestAppContext) {
11844 use crate::Subscription;
11845
11846 struct BoundsObserver {
11847 _subscription: Subscription,
11848 }
11849
11850 impl Render for BoundsObserver {
11851 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
11852 Empty
11853 }
11854 }
11855
11856 let opened_window = Rc::new(Cell::new(None));
11857 let window = cx.add_window({
11858 let opened_window = opened_window.clone();
11859 move |window, cx| BoundsObserver {
11860 _subscription: cx.observe_window_bounds(window, move |_, _, cx| {
11861 let handle = cx
11862 .open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
11863 .unwrap();
11864 opened_window.set(Some(AnyWindowHandle::from(handle)));
11865 }),
11866 }
11867 });
11868 window
11869 .update(cx, |_, window, _| window.activate_window())
11870 .unwrap();
11871
11872 let new_size = size(px(400.), px(300.));
11873 cx.simulate_window_resize(window.into(), new_size);
11874
11875 let opened_window = opened_window
11876 .take()
11877 .expect("bounds observer should have opened a window");
11878 let opened_size = opened_window
11879 .update(cx, |_, window, _| window.bounds().size)
11880 .unwrap();
11881 assert_eq!(opened_size, new_size);
11882 }
11883
11884 #[gpui::test]
11885 fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
11886 let window = cx.add_window(|_, _| EmptyView);
11887 let mut platform_window = cx.test_window(window.into());
11888 platform_window.simulate_resize(size(px(400.), px(800.)));
11889 window
11890 .update(cx, |_, window, _| {
11891 assert_eq!(
11892 window.visual_viewport_bounds(),
11893 Bounds::new(Point::default(), size(px(400.), px(800.)))
11894 );
11895 assert_eq!(
11896 window.fully_visible_bounds(),
11897 window.visual_viewport_bounds()
11898 );
11899 })
11900 .unwrap();
11901
11902 platform_window.simulate_frame_request(RequestFrameOptions::default());
11903 let wakes = platform_window.frame_wake_count();
11904 let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
11905 platform_window.simulate_visual_viewport_change(visual_bounds);
11906 assert!(platform_window.frame_wake_count() > wakes);
11907 platform_window.simulate_frame_request(RequestFrameOptions::default());
11908 let wakes = platform_window.frame_wake_count();
11909 let insets = crate::WindowInsets {
11910 safe_area: crate::Edges {
11911 top: px(60.),
11912 right: px(20.),
11913 bottom: px(30.),
11914 left: px(-10.),
11915 },
11916 ime: crate::Edges {
11917 bottom: px(350.),
11918 ..Default::default()
11919 },
11920 ..Default::default()
11921 };
11922 platform_window.simulate_insets_change(insets.clone());
11923 assert!(platform_window.frame_wake_count() > wakes);
11924 window
11925 .update(cx, |_, window, cx| {
11926 let focus = cx.focus_handle();
11927 window.focus(&focus, cx);
11928 assert_eq!(window.insets(), insets);
11929 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
11930 assert_eq!(window.visual_viewport_bounds(), visual_bounds);
11931 assert_eq!(
11932 window.fully_visible_bounds(),
11933 Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
11934 );
11935 window.request_virtual_keyboard();
11936 window.dismiss_virtual_keyboard();
11937 assert!(focus.is_focused(window));
11938 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
11939 })
11940 .unwrap();
11941 assert_eq!(platform_window.virtual_keyboard_requests(), 1);
11942 assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
11943
11944 platform_window.simulate_insets_change(crate::WindowInsets {
11945 safe_area: crate::Edges {
11946 top: px(900.),
11947 left: px(500.),
11948 ..Default::default()
11949 },
11950 ..Default::default()
11951 });
11952 window
11953 .update(cx, |_, window, _| {
11954 assert_eq!(
11955 window.fully_visible_bounds().size,
11956 size(Pixels::ZERO, Pixels::ZERO)
11957 );
11958 })
11959 .unwrap();
11960
11961 use crate::PlatformWindow as _;
11963 platform_window.on_insets_changed(Box::new(|_| {}));
11964 platform_window.simulate_insets_change(crate::WindowInsets::default());
11965 window
11966 .update(cx, |_, window, _| {
11967 assert_eq!(window.insets(), crate::WindowInsets::default());
11968 })
11969 .unwrap();
11970 }
11971
11972 #[test]
11973 fn frame_throttle_tracks_display_refreshes() {
11974 let start = super::Instant::now();
11975 for (elapsed, interval) in [
11976 (Duration::from_micros(16_666), Duration::from_micros(16_667)),
11977 (Duration::from_micros(33_332), Duration::from_micros(33_333)),
11978 ] {
11979 let mut pacer = super::FramePacer::default();
11980 assert!(!pacer.should_defer(start, Some(interval)));
11981 assert!(pacer.should_defer(start + elapsed / 2, Some(interval)));
11982 assert!(!pacer.should_defer(start + elapsed, Some(interval)));
11983 }
11984 }
11985
11986 #[test]
11987 fn frame_throttle_preserves_cadence_without_catching_up_after_stalls() {
11988 let start = super::Instant::now();
11989 let interval = Duration::from_micros(33_333);
11990 let mut pacer = super::FramePacer::default();
11991 assert!(!pacer.should_defer(start, Some(interval)));
11992 let delayed_frame = start + interval + Duration::from_millis(5);
11993 assert!(!pacer.should_defer(delayed_frame, Some(interval)));
11994 assert!(pacer.should_defer(start + interval + interval / 2, Some(interval)));
11995 assert!(!pacer.should_defer(start + interval * 2, Some(interval)));
11996
11997 let after_stall = start + interval * 4 - Duration::from_millis(1);
11999 assert!(!pacer.should_defer(after_stall, Some(interval)));
12000 assert!(pacer.should_defer(after_stall + interval / 2, Some(interval)));
12001 assert!(!pacer.should_defer(after_stall + interval, Some(interval)));
12002 let mandatory_frame = after_stall + interval + Duration::from_millis(2);
12004 assert!(!pacer.should_defer(mandatory_frame, None));
12005 assert!(pacer.should_defer(mandatory_frame + interval / 2, Some(interval)));
12006 }
12007
12008 #[test]
12009 fn power_modes_preserve_frame_limits() {
12010 let options = WindowOptions::default();
12011 for (power_mode, active_interval, thermal_interval) in [
12012 (
12013 crate::PowerMode::LowPower,
12014 Some(Duration::from_micros(33_333)),
12015 Duration::from_micros(33_333),
12016 ),
12017 (
12018 crate::PowerMode::Unknown,
12019 None,
12020 Duration::from_micros(16_667),
12021 ),
12022 (
12023 crate::PowerMode::Balanced,
12024 None,
12025 Duration::from_micros(16_667),
12026 ),
12027 (
12028 crate::PowerMode::HighPower,
12029 None,
12030 Duration::from_micros(16_667),
12031 ),
12032 ] {
12033 assert_eq!(
12034 super::minimum_frame_interval(
12035 true,
12036 false,
12037 options.inactive_frame_interval,
12038 options.low_power_frame_interval,
12039 options.thermal_frame_interval,
12040 ThermalState::Nominal,
12041 power_mode,
12042 ),
12043 active_interval,
12044 );
12045 assert_eq!(
12046 super::minimum_frame_interval(
12047 true,
12048 false,
12049 options.inactive_frame_interval,
12050 options.low_power_frame_interval,
12051 options.thermal_frame_interval,
12052 ThermalState::Serious,
12053 power_mode,
12054 ),
12055 Some(thermal_interval),
12056 );
12057 }
12058 }
12059
12060 #[test]
12061 fn frame_limits_combine_enabled_intervals() {
12062 let short = Some(Duration::from_millis(10));
12063 let long = Some(Duration::from_millis(100));
12064 for (inactive, low_power, thermal, expected) in [
12065 (long, short, short, long),
12066 (short, long, short, long),
12067 (short, short, long, long),
12068 (long, None, None, long),
12069 (None, long, None, long),
12070 (None, None, long, long),
12071 (None, None, None, None),
12072 ] {
12073 assert_eq!(
12074 super::minimum_frame_interval(
12075 true,
12076 true,
12077 inactive,
12078 low_power,
12079 thermal,
12080 ThermalState::Critical,
12081 crate::PowerMode::LowPower,
12082 ),
12083 expected,
12084 );
12085 }
12086 assert_eq!(
12087 super::minimum_frame_interval(
12088 false,
12089 true,
12090 long,
12091 long,
12092 long,
12093 ThermalState::Critical,
12094 crate::PowerMode::LowPower,
12095 ),
12096 None,
12097 );
12098 }
12099
12100 struct EmptyView;
12101
12102 impl Render for EmptyView {
12103 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
12104 div()
12105 }
12106 }
12107
12108 struct OpensWindowOnPaint {
12109 opened: Rc<Cell<bool>>,
12110 }
12111
12112 impl Render for OpensWindowOnPaint {
12113 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
12114 let opened = self.opened.clone();
12115 div()
12116 .size_full()
12117 .child(canvas(
12118 |_, _, _| {},
12119 move |_, _, _window, cx| {
12120 if !opened.replace(true) {
12121 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
12122 .unwrap();
12123 }
12124 },
12125 ))
12126 .child(div().child("after"))
12130 }
12131 }
12132
12133 #[test]
12139 fn test_window_opened_during_draw_defers_arena_clear() {
12140 let mut cx = TestAppContext::single();
12141
12142 let opened = Rc::new(Cell::new(false));
12143 let window = cx.add_window({
12145 let opened = opened.clone();
12146 move |_, _| OpensWindowOnPaint { opened }
12147 });
12148
12149 assert!(opened.get());
12150 assert_eq!(cx.windows().len(), 2);
12151
12152 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
12155 .unwrap();
12156 }
12157
12158 #[test]
12159 fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
12160 let mut cx = TestAppContext::single();
12161 let window = cx.add_window(|_, _| EmptyView);
12162 let handle: AnyWindowHandle = window.into();
12163 let window_state = |cx: &mut TestAppContext| {
12164 cx.update_window(handle, |_, window, _| {
12165 (
12166 window.scale_factor(),
12167 window.bounds(),
12168 window.viewport_size(),
12169 )
12170 })
12171 .unwrap()
12172 };
12173
12174 let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
12175 assert_eq!(scale_factor, 2.0);
12176
12177 for (scale_factor, resized_size) in [
12178 (1.0, size(px(800.), px(600.))),
12179 (1.25, size(px(640.), px(480.))),
12180 (2.0, size(px(1024.), px(768.))),
12181 ] {
12182 cx.simulate_window_scale_factor_change(handle, scale_factor);
12183 assert_eq!(
12184 window_state(&mut cx),
12185 (scale_factor, expected_bounds, expected_bounds.size)
12186 );
12187
12188 cx.simulate_window_resize(handle, resized_size);
12189 expected_bounds.size = resized_size;
12190 assert_eq!(
12191 window_state(&mut cx),
12192 (scale_factor, expected_bounds, resized_size)
12193 );
12194 }
12195 }
12196
12197 #[gpui::test]
12198 fn test_fullscreen_toggle_reports_current_bounds(cx: &mut TestAppContext) {
12199 let window = cx.add_window(|_, _| EmptyView);
12200 let handle = AnyWindowHandle::from(window);
12201 let notifications = Rc::new(Cell::new(0));
12202 window
12203 .update(cx, {
12204 let notifications = notifications.clone();
12205 |_, window, cx| {
12206 cx.observe_window_bounds(window, move |_, _, _| {
12207 notifications.set(notifications.get() + 1)
12208 })
12209 .detach();
12210 }
12211 })
12212 .unwrap();
12213 let window_state = |cx: &mut TestAppContext| {
12214 cx.update_window(handle, |_, window, _| {
12215 (
12216 window.is_fullscreen(),
12217 window.bounds().size,
12218 window.viewport_size(),
12219 )
12220 })
12221 .unwrap()
12222 };
12223 let initial_size = window_state(cx).1;
12224
12225 window
12226 .update(cx, |_, window, _| window.toggle_fullscreen())
12227 .unwrap();
12228 cx.run_until_parked();
12229 assert_eq!(window_state(cx), (true, initial_size, initial_size));
12230 assert_eq!(notifications.get(), 1);
12231
12232 let resized_size = size(px(800.), px(600.));
12233 window
12234 .update(cx, |_, window, _| window.toggle_fullscreen())
12235 .unwrap();
12236 cx.simulate_window_resize(handle, resized_size);
12237 cx.run_until_parked();
12238 assert_eq!(window_state(cx), (false, resized_size, resized_size));
12239 }
12240
12241 #[gpui::test]
12246 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
12247 let window = cx.add_window(|_, _| EmptyView);
12248 let test_window = cx.test_window(window.into());
12249 test_window.simulate_active_status_change(true);
12251
12252 assert!(
12256 test_window.frame_wake_count() >= 1,
12257 "opening a window must wake the frame source for the initial frame"
12258 );
12259
12260 test_window.simulate_frame_request(RequestFrameOptions::default());
12262
12263 let baseline = test_window.frame_wake_count();
12266 test_window.simulate_frame_request(RequestFrameOptions::default());
12267 window.update(cx, |_, _, _| {}).unwrap();
12268 assert_eq!(
12269 test_window.frame_wake_count(),
12270 baseline,
12271 "clean frames and non-notifying updates must not wake the frame source"
12272 );
12273
12274 window.update(cx, |_, _, cx| cx.notify()).unwrap();
12276 assert!(
12277 test_window.frame_wake_count() > baseline,
12278 "notifying a view in an idle window must wake the frame source"
12279 );
12280
12281 test_window.simulate_frame_request(RequestFrameOptions::default());
12283 let baseline = test_window.frame_wake_count();
12284 test_window.simulate_frame_request(RequestFrameOptions::default());
12285 assert_eq!(
12286 test_window.frame_wake_count(),
12287 baseline,
12288 "serving demand must return the window to idle"
12289 );
12290
12291 window
12293 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
12294 .unwrap();
12295 assert!(
12296 test_window.frame_wake_count() > baseline,
12297 "scheduling a next-frame callback in an idle window must wake the frame source"
12298 );
12299 }
12300
12301 #[gpui::test]
12304 fn test_passive_next_frame_callbacks_are_not_demand(cx: &mut TestAppContext) {
12305 fn rearm(window: &mut Window, runs: Rc<Cell<usize>>) {
12306 runs.set(runs.get() + 1);
12307 window.on_next_frame_passive(move |window, _| rearm(window, runs));
12308 }
12309 let window = cx.add_window(|_, _| EmptyView);
12310 let test_window = cx.test_window(window.into());
12311 test_window.simulate_frame_request(RequestFrameOptions::default());
12312
12313 let runs = Rc::new(Cell::new(0));
12314 let baseline = test_window.frame_wake_count();
12315 window
12316 .update(cx, {
12317 let runs = runs.clone();
12318 move |_, window, _| window.on_next_frame_passive(move |window, _| rearm(window, runs))
12319 })
12320 .unwrap();
12321 assert_eq!(test_window.frame_wake_count(), baseline, "queueing a passive callback is not demand");
12322
12323 test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
12324 test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
12325 assert_eq!(runs.get(), 2, "a passive callback runs with every delivered frame");
12326 assert_eq!(test_window.frame_wake_count(), baseline, "a re-arming passive pump never wakes the frame source");
12327
12328 window.update(cx, |_, window, _| window.on_next_frame(|_, _| {})).unwrap();
12330 assert!(test_window.frame_wake_count() > baseline);
12331 }
12332
12333 #[gpui::test]
12338 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
12339 let window = cx.add_window(|_, _| EmptyView);
12340 let test_window = cx.test_window(window.into());
12341 test_window.simulate_frame_request(RequestFrameOptions::default());
12344
12345 let callback_ran = Rc::new(Cell::new(false));
12346 window
12347 .update(cx, {
12348 let callback_ran = callback_ran.clone();
12349 move |_, window, _| {
12350 window.on_next_frame(move |_, _| callback_ran.set(true));
12351 }
12352 })
12353 .unwrap();
12354
12355 let baseline = test_window.frame_wake_count();
12356 test_window.simulate_frame_request(RequestFrameOptions::default());
12357 assert!(
12364 test_window.frame_wake_count() > baseline || callback_ran.get(),
12365 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
12366 );
12367 }
12368
12369 #[gpui::test]
12370 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
12371 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
12372
12373 let window = cx.add_window(|_, _| EmptyView);
12374 window
12375 .update(cx, |_, window, _| {
12376 assert!(matches!(
12377 window.window_handle(),
12378 Err(HandleError::NotSupported)
12379 ));
12380 assert!(matches!(
12381 window.display_handle(),
12382 Err(HandleError::NotSupported)
12383 ));
12384 })
12385 .unwrap();
12386 }
12387
12388 #[gpui::test]
12389 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
12390 let window = cx.add_window(|_, _| EmptyView);
12391 let observed_appearance = Rc::new(Cell::new(None));
12392 let _subscription = window
12393 .update(cx, {
12394 let observed_appearance = observed_appearance.clone();
12395 move |_, window, _| {
12396 window.observe_window_appearance(move |window, _| {
12397 observed_appearance.set(Some(window.appearance()));
12398 })
12399 }
12400 })
12401 .unwrap();
12402 let test_window = cx.test_window(window.into());
12403
12404 cx.update(|_| {
12405 test_window.simulate_appearance_change(WindowAppearance::Dark);
12406 assert_eq!(observed_appearance.get(), None);
12407 });
12408 cx.run_until_parked();
12409
12410 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
12411 }
12412
12413 #[gpui::test]
12414 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
12415 let window = cx.add_window(|_, _| Empty);
12416 let test_window = cx.test_window(window.into());
12417
12418 assert!(test_window.simulate_scheduled_frame());
12419 assert!(test_window.simulate_scheduled_frame());
12420 assert!(!test_window.frame_scheduled());
12421
12422 cx.update_window(window.into(), |_, window, _| {
12423 window.active.set(true);
12424 window.on_next_frame(|_, _| {});
12425 })
12426 .unwrap();
12427 assert!(
12428 test_window.frame_scheduled(),
12429 "queuing work on a parked window must wake the render loop"
12430 );
12431
12432 assert!(test_window.simulate_scheduled_frame());
12433 assert!(
12434 test_window.frame_scheduled(),
12435 "presenting the frame must await one compositor callback"
12436 );
12437 assert!(test_window.simulate_scheduled_frame());
12438 assert!(!test_window.frame_scheduled());
12439 }
12440
12441 #[gpui::test]
12442 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
12443 let window = cx.add_window(|_, _| Empty);
12444 let test_window = cx.test_window(window.into());
12445
12446 assert!(test_window.simulate_scheduled_frame());
12447 assert!(test_window.simulate_scheduled_frame());
12448 assert!(!test_window.frame_scheduled());
12449
12450 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
12451 .unwrap();
12452
12453 assert!(
12454 test_window.frame_scheduled(),
12455 "a rendered scene awaiting presentation must wake the render loop"
12456 );
12457 }
12458
12459 #[gpui::test]
12460 fn reentrant_frame_request_preserves_pending_callbacks(cx: &mut TestAppContext) {
12461 let window = cx.add_window(|_, _| Empty);
12462 let test_window = cx.test_window(window.into());
12463 let callback_count = Rc::new(Cell::new(0));
12464
12465 cx.update_window(window.into(), |_, window, _| {
12466 window.active.set(true);
12467 let callback_count = callback_count.clone();
12468 window.on_next_frame(move |window, _| {
12469 callback_count.set(callback_count.get() + 1);
12470 window.on_next_frame(move |_, _| {
12471 callback_count.set(callback_count.get() + 1);
12472 });
12473 });
12474 })
12475 .unwrap();
12476
12477 let wake_count = test_window.frame_wake_count();
12480 cx.update(|_| {
12481 test_window.simulate_frame_request(RequestFrameOptions::default());
12482 });
12483 assert_eq!(callback_count.get(), 0);
12484 cx.update_window(window.into(), |_, window, _| {
12485 assert_eq!(window.next_frame_callbacks.borrow().len(), 1);
12486 })
12487 .unwrap();
12488 assert!(
12489 test_window.frame_wake_count() > wake_count,
12490 "a deferred frame callback must wake the frame source for a retry"
12491 );
12492
12493 test_window.simulate_frame_request(RequestFrameOptions::default());
12494 assert_eq!(callback_count.get(), 1);
12495 test_window.simulate_frame_request(RequestFrameOptions::default());
12496 assert_eq!(callback_count.get(), 2);
12497 test_window.simulate_frame_request(RequestFrameOptions::default());
12498 assert_eq!(callback_count.get(), 2);
12499 }
12500
12501 #[gpui::test]
12502 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
12503 let window = cx.add_window(|_, _| Empty);
12504 let test_window = cx.test_window(window.into());
12505
12506 let callback_ran = Rc::new(Cell::new(false));
12507 cx.update_window(window.into(), |_, window, _| {
12508 window.active.set(true);
12511 let callback_ran = callback_ran.clone();
12512 window.on_next_frame(move |window, _| {
12513 window.on_next_frame(move |_, _| callback_ran.set(true));
12514 });
12515 })
12516 .unwrap();
12517
12518 assert!(test_window.simulate_scheduled_frame());
12519 assert!(!callback_ran.get());
12520 assert!(
12521 test_window.frame_scheduled(),
12522 "a callback queued mid-frame must schedule a follow-up before the loop parks"
12523 );
12524
12525 assert!(test_window.simulate_scheduled_frame());
12526 assert!(callback_ran.get());
12527 }
12528
12529 struct RootView {
12530 explicit_size: bool,
12531 child_bounds: Rc<Cell<Bounds<Pixels>>>,
12532 }
12533
12534 impl Render for RootView {
12535 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12536 let child_bounds = self.child_bounds.clone();
12537 let root = div().flex().flex_col().child(
12538 canvas(
12539 move |bounds, _, _| child_bounds.set(bounds),
12540 |_, _, _, _| {},
12541 )
12542 .size_full(),
12543 );
12544 if self.explicit_size {
12545 root.w(px(300.)).h(px(200.))
12546 } else {
12547 root
12548 }
12549 }
12550 }
12551
12552 #[test]
12553 fn auto_sized_window_root_fills_the_window() {
12554 let mut cx = TestAppContext::single();
12555 let child_bounds = Rc::new(Cell::new(Bounds::default()));
12556 let window = cx.add_window({
12557 let child_bounds = child_bounds.clone();
12558 move |_, _| RootView {
12559 explicit_size: false,
12560 child_bounds,
12561 }
12562 });
12563
12564 let viewport_size = cx
12565 .update_window(window.into(), |_, window, cx| {
12566 window.draw(cx).clear(cx);
12567 window.viewport_size()
12568 })
12569 .unwrap();
12570
12571 assert_eq!(child_bounds.get().size, viewport_size);
12572 }
12573
12574 #[test]
12575 fn explicitly_sized_window_root_keeps_its_size() {
12576 let mut cx = TestAppContext::single();
12577 let child_bounds = Rc::new(Cell::new(Bounds::default()));
12578 let window = cx.add_window({
12579 let child_bounds = child_bounds.clone();
12580 move |_, _| RootView {
12581 explicit_size: true,
12582 child_bounds,
12583 }
12584 });
12585
12586 cx.update_window(window.into(), |_, window, cx| {
12587 window.draw(cx).clear(cx);
12588 })
12589 .unwrap();
12590
12591 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
12592 }
12593
12594 struct FileDragView {
12595 path: PathBuf,
12596 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
12597 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
12598 }
12599
12600 struct FileDropExitView(Rc<Cell<usize>>);
12601
12602 impl Render for FileDropExitView {
12603 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12604 div().size_full().on_file_drop_exit({
12605 let observed_file_drop_exit = self.0.clone();
12606 move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
12607 })
12608 }
12609 }
12610
12611 impl Render for FileDragView {
12612 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12613 div()
12614 .id("file-drag")
12615 .size_full()
12616 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
12617 .external_drag_payload(|path: &PathBuf, _, _| {
12618 Some(ExternalDragPayload::Files(FileDragPaths::new([(
12619 path.clone(),
12620 true,
12621 )])))
12622 })
12623 .on_drag_move({
12624 let observed_drag_moves = self.observed_drag_moves.clone();
12625 move |event: &DragMoveEvent<PathBuf>, _, _| {
12626 observed_drag_moves.borrow_mut().push(event.event.position);
12627 }
12628 })
12629 .on_drop({
12630 let observed_drops = self.observed_drops.clone();
12631 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
12632 })
12633 }
12634 }
12635
12636 #[gpui::test]
12637 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
12638 struct Drag {
12639 window: AnyWindowHandle,
12640 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
12641 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
12642 }
12643
12644 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
12645 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
12646 let observed_drops = Rc::new(RefCell::new(Vec::new()));
12647 let window: AnyWindowHandle = cx
12648 .add_window({
12649 let observed_drag_moves = observed_drag_moves.clone();
12650 let observed_drops = observed_drops.clone();
12651 move |_, _| FileDragView {
12652 path,
12653 observed_drag_moves,
12654 observed_drops,
12655 }
12656 })
12657 .into();
12658 cx.test_window(window)
12659 .set_start_external_drag_result(platform_result);
12660
12661 let update_result = cx.update_window(window, |_, window, cx| {
12662 window.draw(cx).clear(cx);
12663 window.dispatch_event(
12664 MouseDownEvent {
12665 position: point(px(10.), px(10.)),
12666 button: MouseButton::Left,
12667 modifiers: Default::default(),
12668 click_count: 1,
12669 first_mouse: false,
12670 }
12671 .to_platform_input(),
12672 cx,
12673 );
12674 window.dispatch_event(
12675 MouseMoveEvent {
12676 position: point(px(20.), px(20.)),
12677 pressed_button: Some(MouseButton::Left),
12678 modifiers: Default::default(),
12679 }
12680 .to_platform_input(),
12681 cx,
12682 );
12683 assert!(cx.active_drag.is_some());
12684 });
12685 assert!(
12686 update_result.is_ok(),
12687 "failed to start drag: {update_result:?}"
12688 );
12689
12690 assert!(cx.test_window(window).external_drag_files().is_empty());
12691 Drag {
12692 window,
12693 observed_drag_moves,
12694 observed_drops,
12695 }
12696 }
12697
12698 let successful_path = PathBuf::from("/tmp/successful-drag");
12699 let successful = start_drag(cx, successful_path.clone(), true);
12700 let outside_position = point(px(-1.), px(20.));
12701 let update_result = cx.update_window(successful.window, |_, window, cx| {
12702 window.dispatch_event(
12703 MouseMoveEvent {
12704 position: outside_position,
12705 pressed_button: Some(MouseButton::Left),
12706 modifiers: Default::default(),
12707 }
12708 .to_platform_input(),
12709 cx,
12710 );
12711 assert!(cx.active_drag.is_none());
12712 });
12713 assert!(
12714 update_result.is_ok(),
12715 "failed to promote drag: {update_result:?}"
12716 );
12717 assert_eq!(
12718 cx.test_window(successful.window).external_drag_files(),
12719 [(successful_path.clone(), true)]
12720 );
12721 assert_eq!(
12724 successful.observed_drag_moves.borrow().last(),
12725 Some(&outside_position)
12726 );
12727
12728 let first_destination_exit_count = Rc::new(Cell::new(0));
12729 let first_destination: AnyWindowHandle = cx
12730 .add_window({
12731 let first_destination_exit_count = first_destination_exit_count.clone();
12732 move |_, _| FileDropExitView(first_destination_exit_count)
12733 })
12734 .into();
12735 let second_destination_exit_count = Rc::new(Cell::new(0));
12736 let second_destination: AnyWindowHandle = cx
12737 .add_window({
12738 let second_destination_exit_count = second_destination_exit_count.clone();
12739 move |_, _| FileDropExitView(second_destination_exit_count)
12740 })
12741 .into();
12742 let reentry_position = point(px(30.), px(30.));
12743 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
12744 let update_result = cx.update_window(first_destination, |_, window, cx| {
12745 window.draw(cx).clear(cx);
12746 window.dispatch_event(
12747 FileDropEvent::Entered {
12748 position: reentry_position,
12749 paths: external_paths(),
12750 }
12751 .to_platform_input(),
12752 cx,
12753 );
12754 assert!(
12755 cx.active_drag
12756 .as_ref()
12757 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
12758 );
12759 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12760 assert!(cx.active_drag.is_none());
12761 assert_eq!(first_destination_exit_count.get(), 1);
12762 assert_eq!(second_destination_exit_count.get(), 0);
12763 });
12764 assert!(
12765 update_result.is_ok(),
12766 "failed to handle drag in first destination window: {update_result:?}"
12767 );
12768
12769 let update_result = cx.update_window(second_destination, |_, window, cx| {
12770 window.draw(cx).clear(cx);
12771 window.dispatch_event(
12772 PlatformInput::KeyDown(KeyDownEvent {
12773 keystroke: Keystroke::parse("down").expect("valid keystroke"),
12774 is_held: false,
12775 prefer_character_input: false,
12776 }),
12777 cx,
12778 );
12779 window.dispatch_event(
12780 FileDropEvent::Entered {
12781 position: reentry_position,
12782 paths: external_paths(),
12783 }
12784 .to_platform_input(),
12785 cx,
12786 );
12787 assert!(
12788 cx.active_drag
12789 .as_ref()
12790 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
12791 );
12792 assert_eq!(first_destination_exit_count.get(), 1);
12793 assert_eq!(second_destination_exit_count.get(), 0);
12794
12795 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12796 assert!(cx.active_drag.is_none());
12797 assert_eq!(first_destination_exit_count.get(), 1);
12798 assert_eq!(second_destination_exit_count.get(), 1);
12799 });
12800 assert!(
12801 update_result.is_ok(),
12802 "failed to handle drag in second destination window: {update_result:?}"
12803 );
12804
12805 let update_result = cx.update_window(successful.window, |_, window, cx| {
12806 window.dispatch_event(
12807 FileDropEvent::Entered {
12808 position: reentry_position,
12809 paths: external_paths(),
12810 }
12811 .to_platform_input(),
12812 cx,
12813 );
12814 assert!(
12815 cx.active_drag
12816 .as_ref()
12817 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
12818 );
12819 assert_eq!(
12820 successful.observed_drag_moves.borrow().last(),
12821 Some(&reentry_position)
12822 );
12823
12824 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12825 assert!(cx.active_drag.is_none());
12826
12827 window.dispatch_event(
12828 FileDropEvent::Entered {
12829 position: reentry_position,
12830 paths: external_paths(),
12831 }
12832 .to_platform_input(),
12833 cx,
12834 );
12835 assert!(
12836 cx.active_drag
12837 .as_ref()
12838 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
12839 );
12840
12841 window.dispatch_event(
12842 FileDropEvent::Submit {
12843 position: reentry_position,
12844 }
12845 .to_platform_input(),
12846 cx,
12847 );
12848 assert_eq!(
12849 successful.observed_drops.borrow().as_slice(),
12850 std::slice::from_ref(&successful_path)
12851 );
12852 assert!(cx.active_drag.is_none());
12853
12854 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12855 assert!(cx.active_drag.is_none());
12856 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
12857 assert!(cx.active_drag.is_none());
12858
12859 window.dispatch_event(
12860 FileDropEvent::Entered {
12861 position: reentry_position,
12862 paths: external_paths(),
12863 }
12864 .to_platform_input(),
12865 cx,
12866 );
12867 assert!(
12868 cx.active_drag
12869 .as_ref()
12870 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
12871 );
12872 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12873 });
12874 assert!(
12875 update_result.is_ok(),
12876 "failed to restore drag in source window: {update_result:?}"
12877 );
12878
12879 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
12880 let cancelled = start_drag(cx, cancelled_path.clone(), true);
12881 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
12882 window.dispatch_event(
12883 MouseMoveEvent {
12884 position: outside_position,
12885 pressed_button: Some(MouseButton::Left),
12886 modifiers: Default::default(),
12887 }
12888 .to_platform_input(),
12889 cx,
12890 );
12891 assert!(cx.active_drag.is_none());
12892
12893 window.dispatch_event(
12894 FileDropEvent::Entered {
12895 position: reentry_position,
12896 paths: ExternalPaths([cancelled_path].into_iter().collect()),
12897 }
12898 .to_platform_input(),
12899 cx,
12900 );
12901 assert!(
12902 cx.active_drag
12903 .as_ref()
12904 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
12905 );
12906 assert!(cx.stop_active_drag(window));
12907 assert!(cx.active_drag.is_none());
12908 });
12909 assert!(
12910 update_result.is_ok(),
12911 "failed to cancel restored drag: {update_result:?}"
12912 );
12913 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
12914
12915 let removed_path = PathBuf::from("/tmp/removed-window-drag");
12916 let removed = start_drag(cx, removed_path, true);
12917 let removed_window_id = removed.window.window_id();
12918 let update_result = cx.update_window(removed.window, |_, window, cx| {
12919 window.dispatch_event(
12920 MouseMoveEvent {
12921 position: outside_position,
12922 pressed_button: Some(MouseButton::Left),
12923 modifiers: Default::default(),
12924 }
12925 .to_platform_input(),
12926 cx,
12927 );
12928 assert!(cx.active_drag.is_none());
12929 window.remove_window();
12930 });
12931 assert!(
12932 update_result.is_ok(),
12933 "failed to remove drag source window: {update_result:?}"
12934 );
12935 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
12936
12937 let failed_path = PathBuf::from("/tmp/failed-drag");
12938 let failed = start_drag(cx, failed_path.clone(), false);
12939 let update_result = cx.update_window(failed.window, |_, window, cx| {
12940 for x_position in [-1., -2.] {
12941 window.dispatch_event(
12942 MouseMoveEvent {
12943 position: point(px(x_position), px(20.)),
12944 pressed_button: Some(MouseButton::Left),
12945 modifiers: Default::default(),
12946 }
12947 .to_platform_input(),
12948 cx,
12949 );
12950 }
12951 assert!(cx.active_drag.is_some());
12952 });
12953 assert!(
12954 update_result.is_ok(),
12955 "failed to retain drag after platform failure: {update_result:?}"
12956 );
12957 assert_eq!(
12958 cx.test_window(failed.window).external_drag_files(),
12959 [(failed_path, true)]
12960 );
12961 }
12962
12963 struct FocusForwarder {
12964 a: FocusHandle,
12965 b: FocusHandle,
12966 }
12967
12968 impl Render for FocusForwarder {
12969 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12970 div()
12971 .size_full()
12972 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
12973 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
12974 }
12975 }
12976
12977 #[gpui::test]
12981 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
12982 let b_focus_count = Rc::new(Cell::new(0));
12983 let window = cx.add_window({
12984 let b_focus_count = b_focus_count.clone();
12985 move |window, cx| {
12986 let a = cx.focus_handle();
12987 let b = cx.focus_handle();
12988 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
12989 let b = this.b.clone();
12990 window.focus(&b, cx);
12991 })
12992 .detach();
12993 cx.on_focus(&b, window, move |_, _, _| {
12994 b_focus_count.set(b_focus_count.get() + 1);
12995 })
12996 .detach();
12997 FocusForwarder { a, b }
12998 }
12999 });
13000
13001 window
13002 .update(cx, |_, window, _| window.activate_window())
13003 .unwrap();
13004 cx.executor().run_until_parked();
13005
13006 window
13007 .update(cx, |this, window, cx| {
13008 let a = this.a.clone();
13009 window.focus(&a, cx);
13010 })
13011 .unwrap();
13012 cx.executor().run_until_parked();
13013
13014 window
13015 .update(cx, |this, window, _| {
13016 assert!(this.b.is_focused(window));
13017 })
13018 .unwrap();
13019 assert_eq!(b_focus_count.get(), 1);
13020 }
13021
13022 #[gpui::test]
13023 fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
13024 let events = Rc::new(RefCell::new(Vec::new()));
13025 let window = cx.add_window({
13026 let events = events.clone();
13027 move |_, _| TouchDragListener { events }
13028 });
13029 let touch = TouchId(1);
13030
13031 dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
13032 dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
13033 dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
13034
13035 assert_eq!(
13036 events.borrow().as_slice(),
13037 [
13038 (TouchPhase::Started, px(10.)),
13039 (TouchPhase::Moved, px(30.)),
13040 (TouchPhase::Ended, px(40.)),
13041 ]
13042 );
13043 }
13044
13045 #[gpui::test]
13046 fn back_gesture_is_claimed_by_the_innermost_listener(cx: &mut TestAppContext) {
13047 let claims = Rc::new(RefCell::new(Vec::new()));
13048 let window = cx.add_window({
13049 let claims = claims.clone();
13050 move |_, _| BackListeners { claims }
13051 });
13052 let dispatch_back = |cx: &mut TestAppContext, x: f32| {
13053 window
13054 .update(cx, |_, window, cx| {
13055 window
13056 .dispatch_event(
13057 BackGestureEvent {
13058 phase: BackGesturePhase::Started,
13059 start_position: point(px(x), px(10.)),
13060 progress: 0.,
13061 }
13062 .to_platform_input(),
13063 cx,
13064 )
13065 .default_prevented
13066 })
13067 .unwrap()
13068 };
13069 assert!(dispatch_back(cx, 10.));
13070 assert!(dispatch_back(cx, 80.));
13071 assert!(!dispatch_back(cx, 150.));
13072 assert_eq!(claims.borrow().as_slice(), ["inner", "outer"]);
13073 }
13074
13075 struct BackListeners {
13076 claims: Rc<RefCell<Vec<&'static str>>>,
13077 }
13078
13079 impl Render for BackListeners {
13080 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
13081 let claim = |name: &'static str| {
13082 let claims = self.claims.clone();
13083 move |_: &BackGestureEvent, _: &mut Window, _: &mut crate::App| {
13084 claims.borrow_mut().push(name)
13085 }
13086 };
13087 div().size_full().child(
13088 div()
13089 .w(px(100.))
13090 .h_full()
13091 .on_back_gesture(claim("outer"))
13092 .child(div().w(px(50.)).h_full().on_back_gesture(claim("inner"))),
13093 )
13094 }
13095 }
13096
13097 struct TouchDragListener {
13098 events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
13099 }
13100
13101 impl Render for TouchDragListener {
13102 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
13103 let events = self.events.clone();
13104 canvas(
13105 |_, _, _| {},
13106 move |_, _, window, _| {
13107 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
13108 if phase != DispatchPhase::Bubble {
13109 return;
13110 }
13111 events.borrow_mut().push((event.phase, event.position.x));
13112 if event.phase == TouchPhase::Started {
13113 window.prevent_default();
13114 }
13115 });
13116 },
13117 )
13118 }
13119 }
13120
13121 #[gpui::test]
13122 fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
13123 for response in [
13124 LongPressResponse::PreventDefault,
13125 LongPressResponse::StopPropagation,
13126 LongPressResponse::None,
13127 ] {
13128 let phases = Rc::new(RefCell::new(Vec::new()));
13129 let window = cx.add_window({
13130 let phases = phases.clone();
13131 move |_, _| LongPressListener { phases, response }
13132 });
13133 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13134 cx.executor().advance_clock(Duration::from_millis(501));
13135 cx.executor().run_until_parked();
13136 window
13137 .update(cx, |_, window, _| {
13138 assert_eq!(
13139 window.long_press_capture.is_some(),
13140 response == LongPressResponse::PreventDefault
13141 );
13142 })
13143 .unwrap();
13144 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
13145 dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
13146 window
13147 .update(cx, |_, window, _| {
13148 assert!(window.long_press_capture.is_none());
13149 })
13150 .unwrap();
13151
13152 let phases = phases.borrow();
13153 if response == LongPressResponse::PreventDefault {
13154 assert_eq!(
13155 phases.as_slice(),
13156 [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
13157 );
13158 } else {
13159 assert_eq!(phases.as_slice(), [TouchPhase::Started]);
13160 }
13161 }
13162 }
13163
13164 #[gpui::test]
13165 fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
13166 let phases = Rc::new(RefCell::new(Vec::new()));
13167 let window = cx.add_window({
13168 let phases = phases.clone();
13169 move |_, _| LongPressListener {
13170 phases,
13171 response: LongPressResponse::None,
13172 }
13173 });
13174 window
13175 .update(cx, |_, window, _| {
13176 window.prevent_default();
13177 })
13178 .unwrap();
13179
13180 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13181 cx.executor().advance_clock(Duration::from_millis(501));
13182 cx.executor().run_until_parked();
13183 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
13184
13185 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
13186 }
13187
13188 #[gpui::test]
13189 fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
13190 for (phase, position) in [
13191 (TouchPhase::Ended, 0.),
13192 (TouchPhase::Cancelled, 0.),
13193 (TouchPhase::Moved, 20.),
13194 ] {
13195 let phases = Rc::new(RefCell::new(Vec::new()));
13196 let window = cx.add_window({
13197 let phases = phases.clone();
13198 move |_, _| LongPressListener {
13199 phases,
13200 response: LongPressResponse::PreventDefault,
13201 }
13202 });
13203 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13204 dispatch_touch(window, cx, TouchId(1), phase, position);
13205 cx.executor().advance_clock(Duration::from_millis(501));
13206 cx.executor().run_until_parked();
13207
13208 assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
13209 }
13210 }
13211
13212 #[gpui::test]
13213 fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
13214 let phases = Rc::new(RefCell::new(Vec::new()));
13215 let window = cx.add_window({
13216 let phases = phases.clone();
13217 move |_, _| LongPressListener {
13218 phases,
13219 response: LongPressResponse::PreventDefault,
13220 }
13221 });
13222 let first_touch = TouchId(1);
13223 dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
13224 cx.executor().advance_clock(Duration::from_millis(250));
13225 dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
13226 dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
13227
13228 cx.executor().advance_clock(Duration::from_millis(251));
13229 cx.executor().run_until_parked();
13230 assert!(phases.borrow().is_empty());
13231
13232 cx.executor().advance_clock(Duration::from_millis(250));
13233 cx.executor().run_until_parked();
13234 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
13235 }
13236
13237 #[gpui::test]
13238 fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
13239 test_underline_paint_at_scales(cx, |window| {
13240 let (numerator, denominator) = match window.scale_factor() {
13241 1.0 => (1, 1),
13242 1.25 => (5, 4),
13243 1.5 => (3, 2),
13244 2.0 => (2, 1),
13245 3.0 => (3, 1),
13246 scale => panic!("unexpected scale {scale}"),
13247 };
13248 let snap = |quarters: i32| {
13249 let scaled = quarters * numerator;
13250 let divisor = 4 * denominator;
13251 let rounded =
13252 scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
13253 ScaledPixels((scaled.signum() * rounded) as f32)
13254 };
13255 let stroke = |quarters| {
13256 if quarters == 0 {
13257 ScaledPixels(0.)
13258 } else {
13259 snap(quarters).max(ScaledPixels(1.))
13260 }
13261 };
13262
13263 for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
13264 for width in [0, 1, 3, 84] {
13265 for thickness in [0, 1, 4, 7] {
13266 for wavy in [false, true] {
13267 let style = UnderlineStyle {
13268 thickness: px(thickness as f32 / 4.),
13269 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
13270 wavy,
13271 offset: px(0.),
13272 };
13273 let bounds = Bounds::new(
13274 point(snap(origin), snap(-origin)),
13275 size(
13276 stroke(width),
13277 stroke(thickness) * if wavy { 3. } else { 1. },
13278 ),
13279 );
13280 let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
13281 let width = px(width as f32 / 4.);
13282 assert_eq!(window.underline_bounds(origin, width, &style), bounds);
13283 let original = paint_test_underlines(window, |window| {
13284 window.paint_underline(origin, width, &style);
13285 })
13286 .to_vec();
13287 assert_eq!(original.len(), usize::from(!bounds.is_empty()));
13288 if let Some(underline) = original.first() {
13289 assert_eq!(underline.bounds, bounds);
13290 assert_eq!(underline.thickness, stroke(thickness));
13291 assert_eq!(underline.wavy, wavy.into());
13292 assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
13293 }
13294
13295 let underlines = paint_test_underlines(window, |window| {
13296 window.paint_underline_with_exclusions(origin, width, &style, &[]);
13297 });
13298 assert_eq!(underlines.len(), original.len());
13299 for (actual, original) in underlines.iter().zip(&original) {
13300 assert_same_underline_geometry(actual, original);
13301 assert_eq!(actual.content_mask, original.content_mask);
13302 }
13303
13304 let left = bounds.left().0 as i32;
13305 let right = bounds.right().0 as i32;
13306 let exclusions = [
13307 (15, 25),
13308 (3, 7),
13309 (5, 10),
13310 (10, 12),
13311 (0, 0),
13312 (4, 2),
13313 (-50, -1),
13314 (70, 100),
13315 ]
13316 .map(|(start, end)| {
13317 ScaledPixels((left + start) as f32)
13318 ..ScaledPixels((left + end) as f32)
13319 });
13320 let underlines = paint_test_underlines(window, |window| {
13321 window.paint_underline_with_exclusions(
13322 origin,
13323 width,
13324 &style,
13325 &exclusions,
13326 );
13327 });
13328 let expected = (left..right)
13329 .filter(|column| {
13330 !bounds.is_empty()
13331 && !exclusions.iter().any(|span| {
13332 span.contains(&ScaledPixels(*column as f32))
13333 })
13334 })
13335 .collect::<Vec<_>>();
13336 assert_eq!(underline_device_columns(underlines), expected);
13337 for underline in underlines {
13338 assert_same_underline_geometry(underline, &original[0]);
13339 }
13340 }
13341 }
13342 }
13343 }
13344 });
13345 }
13346
13347 #[gpui::test]
13348 fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
13349 test_underline_paint_at_scales(cx, |window| {
13350 if window.scale_factor() != 2.0 {
13351 return;
13352 }
13353 let style = UnderlineStyle {
13354 thickness: px(1.),
13355 color: None,
13356 wavy: true,
13357 offset: px(0.),
13358 };
13359 let origin = point(px(2.888_183_8), px(15.357_917));
13360 let width = px(23.848_145) - origin.x;
13361 let original = paint_test_underlines(window, |window| {
13362 window.paint_underline(origin, width, &style);
13363 })[0];
13364 assert_eq!(original.bounds.left(), ScaledPixels(6.));
13365 assert_eq!(original.bounds.right(), ScaledPixels(48.));
13366 let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
13367 assert_eq!(point_bounds.left(), ScaledPixels(6.));
13368 assert_eq!(point_bounds.right(), ScaledPixels(28.));
13369
13370 let underlines = paint_test_underlines(window, |window| {
13371 window.paint_underline_with_exclusions(
13372 origin,
13373 width,
13374 &style,
13375 &[point_bounds.left()..point_bounds.right()],
13376 );
13377 });
13378 assert_eq!(underlines.len(), 1);
13379 assert_same_underline_geometry(&underlines[0], &original);
13380 assert_eq!(
13381 underline_device_columns(underlines),
13382 (28..48).collect::<Vec<_>>()
13383 );
13384 });
13385 }
13386
13387 #[gpui::test]
13388 fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
13389 test_underline_paint_at_scales(cx, |window| {
13390 let scale = window.scale_factor();
13391 let original_mask = window.content_mask();
13392 let original_opacity = window.element_opacity();
13393 let mask = ContentMask {
13394 bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
13395 corner_radii: crate::Corners::default(),
13396 };
13397 let style = UnderlineStyle {
13398 thickness: px(2.),
13399 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
13400 wavy: true,
13401 offset: px(0.),
13402 };
13403 let origin = point(px(-1.25), px(9.25));
13404 let width = px(24.);
13405 window.with_content_mask(Some(mask), |window| {
13406 window.with_element_opacity(Some(0.5), |window| {
13407 window.with_element_opacity(Some(0.5), |window| {
13408 let original = paint_test_underlines(window, |window| {
13409 window.paint_underline(origin, width, &style);
13410 })[0];
13411 assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
13412 let underlines = paint_test_underlines(window, |window| {
13413 window.paint_underline_with_exclusions(
13414 origin,
13415 width,
13416 &style,
13417 &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
13418 );
13419 });
13420 assert_eq!(underlines.len(), 2);
13421 let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
13422 |(left, right)| {
13423 Bounds::from_corners(
13424 point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
13425 point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
13426 )
13427 },
13428 );
13429 assert_eq!(
13430 underlines
13431 .iter()
13432 .map(|underline| underline.content_mask.bounds)
13433 .collect::<Vec<_>>(),
13434 expected
13435 );
13436 for underline in underlines {
13437 assert_same_underline_geometry(underline, &original);
13438 }
13439 });
13440 });
13441 });
13442 assert_eq!(window.content_mask(), original_mask);
13443 assert_eq!(window.element_opacity(), original_opacity);
13444 });
13445 }
13446
13447 #[gpui::test]
13448 fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
13449 test_underline_paint_at_scales(cx, |window| {
13450 let style = UnderlineStyle {
13451 thickness: px(1.),
13452 color: None,
13453 wavy: true,
13454 offset: px(0.),
13455 };
13456 let origin = point(px(-4.), px(-1.));
13457 let width = px(8.);
13458 let left = (-4. * window.scale_factor()) as i32;
13459 let right = (4. * window.scale_factor()) as i32;
13460 let endpoints = [-16, -8, -1, 0, 1, 8, 16];
13461 for first_start in endpoints {
13462 for first_end in endpoints {
13463 for second_start in endpoints {
13464 for second_end in endpoints {
13465 let exclusions = [first_start..first_end, second_start..second_end];
13466 let expected = (left..right)
13467 .filter(|column| {
13468 !exclusions.iter().any(|span| span.contains(column))
13469 })
13470 .collect::<Vec<_>>();
13471 let exclusions = exclusions.map(|span| {
13472 ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
13473 });
13474 let underlines = paint_test_underlines(window, |window| {
13475 window.paint_underline_with_exclusions(
13476 origin,
13477 width,
13478 &style,
13479 &exclusions,
13480 );
13481 });
13482 assert_eq!(
13483 underline_device_columns(underlines),
13484 expected,
13485 "{exclusions:?}"
13486 );
13487 }
13488 }
13489 }
13490 }
13491 });
13492 }
13493
13494 #[derive(Clone, Copy, PartialEq)]
13495 enum LongPressResponse {
13496 PreventDefault,
13497 StopPropagation,
13498 None,
13499 }
13500
13501 struct LongPressListener {
13502 phases: Rc<RefCell<Vec<TouchPhase>>>,
13503 response: LongPressResponse,
13504 }
13505
13506 impl Render for LongPressListener {
13507 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
13508 let entity = cx.entity();
13509 let phases = self.phases.clone();
13510 let response = self.response;
13511 canvas(
13512 |_, _, _| {},
13513 move |_, _, window, _| {
13514 window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
13515 if phase != DispatchPhase::Bubble {
13516 return;
13517 }
13518 phases.borrow_mut().push(event.phase);
13519 match response {
13520 LongPressResponse::PreventDefault => {
13521 window.capture_long_press(&entity);
13522 window.prevent_default();
13523 }
13524 LongPressResponse::StopPropagation => cx.stop_propagation(),
13525 LongPressResponse::None => {}
13526 }
13527 });
13528 },
13529 )
13530 }
13531 }
13532
13533 struct UnderlineTestView(Rc<dyn Fn(&mut Window)>);
13534
13535 impl Render for UnderlineTestView {
13536 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13537 let paint = self.0.clone();
13538 canvas(
13539 |_, _, _| {},
13540 move |_, _, window, _| {
13541 window.content_mask_stack.push(ContentMask::rect(Bounds::from_corners(
13542 point(px(-1000.), px(-1000.)),
13543 point(px(1000.), px(1000.)),
13544 )));
13545 paint(window);
13546 window.content_mask_stack.pop();
13547 },
13548 )
13549 .size_full()
13550 }
13551 }
13552
13553 fn test_underline_paint_at_scales(
13554 cx: &mut TestAppContext,
13555 paint: impl Fn(&mut Window) + 'static,
13556 ) {
13557 let window = cx.add_window(move |_, _| UnderlineTestView(Rc::new(paint)));
13558 for scale in [1., 1.25, 1.5, 2., 3.] {
13559 cx.simulate_window_scale_factor_change(window.into(), scale);
13560 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
13561 .unwrap();
13562 }
13563 }
13564
13565 fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
13566 window.next_frame.scene.clear();
13567 paint(window);
13568 &window.next_frame.scene.underlines
13569 }
13570
13571 fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
13572 assert_eq!(actual.bounds, expected.bounds);
13573 assert_eq!(actual.thickness, expected.thickness);
13574 assert_eq!(actual.wavy, expected.wavy);
13575 assert_eq!(actual.color, expected.color);
13576 assert_eq!(actual.pad, expected.pad);
13577 }
13578
13579 fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
13580 underlines
13581 .iter()
13582 .flat_map(|underline| {
13583 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
13584 bounds.left().0 as i32..bounds.right().0 as i32
13585 })
13586 .collect()
13587 }
13588
13589 actions!(window_test, [StandaloneModifierAction]);
13590
13591 struct StandaloneModifierView {
13592 focus_handle: FocusHandle,
13593 action_count: usize,
13594 }
13595
13596 impl Render for StandaloneModifierView {
13597 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
13598 div()
13599 .key_context("StandaloneModifier")
13600 .track_focus(&self.focus_handle)
13601 .on_action(cx.listener(|this, _: &StandaloneModifierAction, _, _| {
13602 this.action_count += 1;
13603 }))
13604 }
13605 }
13606
13607 #[gpui::test]
13608 fn test_standalone_modifier_sequence_timeout_and_recovery(cx: &mut TestAppContext) {
13609 use crate::{KeyBinding, Modifiers};
13610
13611 cx.update(|cx| {
13612 cx.bind_keys([KeyBinding::new(
13613 "shift shift",
13614 StandaloneModifierAction,
13615 Some("StandaloneModifier"),
13616 )]);
13617 });
13618 let (view, cx) = cx.add_window_view(|window, cx| {
13619 let focus_handle = cx.focus_handle();
13620 window.focus(&focus_handle, cx);
13621 StandaloneModifierView {
13622 focus_handle,
13623 action_count: 0,
13624 }
13625 });
13626 let shift = Modifiers {
13627 shift: true,
13628 ..Modifiers::default()
13629 };
13630 cx.simulate_modifiers_change(shift);
13631 cx.simulate_modifiers_change(Modifiers::default());
13632 cx.update(|window, _| {
13633 assert_eq!(
13634 window.pending_input_keystrokes(),
13635 Some([Keystroke::parse("shift").expect("valid keystroke")].as_slice())
13636 );
13637 });
13638 cx.background_executor.advance_clock(Duration::from_secs(2));
13639 cx.run_until_parked();
13640 cx.update(|window, cx| {
13641 assert!(!window.has_pending_keystrokes());
13642 assert_eq!(view.read(cx).action_count, 0);
13643 });
13644
13645 cx.simulate_modifiers_change(shift);
13646 cx.simulate_modifiers_change(Modifiers::default());
13647 cx.update(|window, cx| {
13648 assert!(window.has_pending_keystrokes());
13649 assert_eq!(view.read(cx).action_count, 0);
13650 });
13651
13652 cx.simulate_modifiers_change(shift);
13653 cx.simulate_modifiers_change(Modifiers::default());
13654 cx.update(|window, cx| {
13655 assert!(!window.has_pending_keystrokes());
13656 assert_eq!(view.read(cx).action_count, 1);
13657 });
13658 }
13659
13660 #[gpui::test]
13661 fn test_standalone_modifier_sequence_dispatches_before_timeout(cx: &mut TestAppContext) {
13662 use crate::{KeyBinding, Modifiers};
13663
13664 cx.update(|cx| {
13665 cx.bind_keys([KeyBinding::new(
13666 "shift shift",
13667 StandaloneModifierAction,
13668 Some("StandaloneModifier"),
13669 )]);
13670 });
13671 let (view, cx) = cx.add_window_view(|window, cx| {
13672 let focus_handle = cx.focus_handle();
13673 window.focus(&focus_handle, cx);
13674 StandaloneModifierView {
13675 focus_handle,
13676 action_count: 0,
13677 }
13678 });
13679 let shift = Modifiers {
13680 shift: true,
13681 ..Modifiers::default()
13682 };
13683 cx.simulate_modifiers_change(shift);
13684 cx.simulate_modifiers_change(Modifiers::default());
13685 cx.background_executor
13686 .advance_clock(Duration::from_millis(500));
13687 cx.update(|window, cx| {
13688 assert!(window.has_pending_keystrokes());
13689 assert_eq!(view.read(cx).action_count, 0);
13690 });
13691 cx.simulate_modifiers_change(shift);
13692 cx.simulate_modifiers_change(Modifiers::default());
13693 cx.update(|window, cx| {
13694 assert!(!window.has_pending_keystrokes());
13695 assert_eq!(view.read(cx).action_count, 1);
13696 });
13697 cx.background_executor.advance_clock(Duration::from_secs(2));
13698 cx.run_until_parked();
13699 cx.update(|window, cx| {
13700 assert!(!window.has_pending_keystrokes());
13701 assert_eq!(view.read(cx).action_count, 1);
13702 });
13703 }
13704
13705 fn dispatch_touch<T: 'static>(
13706 window: crate::WindowHandle<T>,
13707 cx: &mut TestAppContext,
13708 id: TouchId,
13709 phase: TouchPhase,
13710 x: f32,
13711 ) {
13712 window
13713 .update(cx, |_, window, cx| {
13714 window.dispatch_event(
13715 TouchEvent {
13716 id,
13717 phase,
13718 position: point(px(x), px(0.)),
13719 predicted_position: None,
13720 force: None,
13721 }
13722 .to_platform_input(),
13723 cx,
13724 );
13725 })
13726 .unwrap();
13727 }
13728
13729 #[gpui::test]
13730 fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
13731 struct Child {
13732 renders: usize,
13733 }
13734
13735 impl Render for Child {
13736 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13737 self.renders += 1;
13738 div().size_full().bg(crate::rgb(0xff0000))
13739 }
13740 }
13741
13742 struct Root {
13743 opacity: f32,
13744 width: Pixels,
13745 child: crate::Entity<Child>,
13746 }
13747
13748 impl Render for Root {
13749 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13750 div()
13751 .w(self.width)
13752 .h(px(200.))
13753 .opacity(self.opacity)
13754 .hover(|style| style.opacity(1.))
13755 .child(
13756 self.child
13757 .clone()
13758 .cached(crate::StyleRefinement::default().size(px(100.))),
13759 )
13760 }
13761 }
13762
13763 fn update_and_draw(
13766 window: crate::WindowHandle<Root>,
13767 child: &crate::Entity<Child>,
13768 cx: &mut TestAppContext,
13769 update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
13770 ) -> (f32, usize) {
13771 window
13772 .update(cx, |root, window, cx| {
13773 update(root, window, cx);
13774 cx.notify();
13775 })
13776 .expect("update root");
13777 for _ in 0..3 {
13778 let (alpha, renders, requested_frames) = cx
13779 .update_window(window.into(), |_, window, cx| {
13780 window.draw(cx).clear(cx);
13781 let quads = &window.rendered_frame.scene.quads;
13782 assert_eq!(quads.len(), 1);
13783 let alpha = quads.first().expect("child quad").background.solid.a;
13784 (
13785 alpha,
13786 child.read(cx).renders,
13787 window.simulate_next_frame(cx),
13788 )
13789 })
13790 .expect("draw window");
13791 if requested_frames == 0 {
13792 return (alpha, renders);
13793 }
13794 }
13795 panic!("cached child kept requesting frames");
13796 }
13797
13798 let child = cx.new(|_| Child { renders: 0 });
13799 let window = cx.add_window(|_, _| Root {
13800 opacity: 1.,
13801 width: px(200.),
13802 child: child.clone(),
13803 });
13804 let outside = point(px(500.), px(500.));
13805 let inside = point(px(50.), px(50.));
13806 let beside = point(px(250.), px(50.));
13807
13808 let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
13810 window.simulate_mouse_move(outside, cx)
13811 };
13812 assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
13813 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
13814 let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
13815 assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
13816 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
13817
13818 let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
13820 window.simulate_mouse_move(inside, cx)
13821 };
13822 assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
13823 let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
13824 window.simulate_mouse_move(beside, cx)
13825 };
13826 assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
13827
13828 let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
13831 assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
13832 }
13833
13834 #[gpui::test]
13835 fn test_drag_cursor_applies_before_next_paint(cx: &mut TestAppContext) {
13836 struct ResizeHandle;
13837
13838 impl Render for ResizeHandle {
13839 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13840 div().size_full().cursor_text().child(
13841 div()
13842 .id("resize-handle")
13843 .w(px(4.))
13844 .h_full()
13845 .cursor_col_resize()
13846 .on_drag((), |_, _, _, cx| cx.new(|_| Empty)),
13847 )
13848 }
13849 }
13850
13851 let window = cx.add_window(|_, _| ResizeHandle);
13852 let handle_position = point(px(1.), px(10.));
13853 let drag_position = point(px(20.), px(10.));
13854 let cursor_observer = cx.clone();
13855
13856 let update_result = cx.update_window(window.into(), |_, window, cx| {
13857 window.hovered.set(true);
13858 window.active.set(true);
13859 window.draw(cx).clear(cx);
13860 window.dispatch_event(
13861 MouseMoveEvent {
13862 position: handle_position,
13863 ..Default::default()
13864 }
13865 .to_platform_input(),
13866 cx,
13867 );
13868 window.dispatch_event(
13869 MouseDownEvent {
13870 position: handle_position,
13871 button: MouseButton::Left,
13872 ..Default::default()
13873 }
13874 .to_platform_input(),
13875 cx,
13876 );
13877 window.dispatch_event(
13878 MouseMoveEvent {
13879 position: drag_position,
13880 pressed_button: Some(MouseButton::Left),
13881 ..Default::default()
13882 }
13883 .to_platform_input(),
13884 cx,
13885 );
13886 assert!(cx.has_active_drag());
13887 assert_eq!(
13889 cursor_observer.test_platform().cursor_style(),
13890 CursorStyle::ResizeColumn
13891 );
13892
13893 window.draw(cx).clear(cx);
13894 window.dispatch_event(
13895 MouseUpEvent {
13896 position: drag_position,
13897 button: MouseButton::Left,
13898 ..Default::default()
13899 }
13900 .to_platform_input(),
13901 cx,
13902 );
13903 window.draw(cx).clear(cx);
13904 });
13905 assert!(
13906 update_result.is_ok(),
13907 "failed to run drag: {update_result:?}"
13908 );
13909 assert_eq!(
13910 cursor_observer.test_platform().cursor_style(),
13911 CursorStyle::IBeam
13912 );
13913 }
13914}
13915
13916#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
13917mod inspector_tests {
13918 use super::*;
13919 use crate::{
13920 DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
13921 };
13922
13923 #[gpui::test]
13924 fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
13925 let windows = [
13926 cx.add_window(|_, cx| InspectorTestRoot {
13927 child: cx.new(|_| InspectorTestView::default()),
13928 }),
13929 cx.add_window(|_, cx| InspectorTestRoot {
13930 child: cx.new(|_| InspectorTestView::default()),
13931 }),
13932 ];
13933 for window in windows {
13934 assert_closed_inspector(window.into(), cx);
13935 }
13936 for _ in 0..2 {
13937 cx.update_window(windows[0].into(), |root, window, cx| {
13938 let root = root.downcast::<InspectorTestRoot>().expect("test root");
13939 let child_widths = root.read(cx).child.read(cx).child_widths.clone();
13940 window.toggle_inspector(cx);
13941 window.draw(cx).clear(cx);
13942 assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
13943 let path = window
13944 .rendered_frame
13945 .next_inspector_instance_ids
13946 .iter()
13947 .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
13948 .expect("anonymous siblings share an inspector path");
13949 let selected_id = InspectorElementId {
13950 path,
13951 instance_id: 1,
13952 };
13953 let position = window
13954 .rendered_frame
13955 .hitboxes
13956 .iter()
13957 .find(|hitbox| {
13958 window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
13959 == Some(&selected_id)
13960 })
13961 .expect("middle sibling is pickable")
13962 .bounds
13963 .center();
13964 window.simulate_mouse_move(position, cx);
13965 window.dispatch_event(
13966 PlatformInput::MouseDown(MouseDownEvent {
13967 position,
13968 button: MouseButton::Left,
13969 modifiers: Modifiers::default(),
13970 click_count: 1,
13971 first_mouse: false,
13972 }),
13973 cx,
13974 );
13975 window.dispatch_event(
13976 PlatformInput::MouseUp(MouseUpEvent {
13977 position,
13978 button: MouseButton::Left,
13979 modifiers: Modifiers::default(),
13980 click_count: 1,
13981 }),
13982 cx,
13983 );
13984 assert!(!window.is_inspector_picking(cx));
13985 assert_eq!(
13986 window
13987 .inspector
13988 .as_ref()
13989 .expect("open inspector")
13990 .read(cx)
13991 .active_element_id(),
13992 Some(&selected_id)
13993 );
13994 window.draw(cx).clear(cx);
13995 window.with_inspector_state::<DivInspectorState, _>(
13996 Some(&selected_id),
13997 cx,
13998 |state, _| {
13999 let state = state.as_mut().expect("selected div has style state");
14000 assert_eq!(
14001 state.base_style.size.width,
14002 Some(crate::Length::from(px(10.)))
14003 );
14004 state.base_style.size.width = Some(crate::Length::from(px(25.)));
14005 },
14006 );
14007 window.refresh();
14008 window.draw(cx).clear(cx);
14009 assert_eq!(
14010 child_widths.borrow().as_slice(),
14011 &[px(10.), px(25.), px(10.)]
14012 );
14013 })
14014 .expect("pick and edit a cached child");
14015 assert_closed_inspector(windows[1].into(), cx);
14016 windows[0]
14017 .update(cx, |_, window, cx| window.toggle_inspector(cx))
14018 .expect("close inspector");
14019 assert_closed_inspector(windows[0].into(), cx);
14020 }
14021 }
14022
14023 struct InspectorTestRoot {
14024 child: Entity<InspectorTestView>,
14025 }
14026
14027 impl Render for InspectorTestRoot {
14028 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14029 self.child
14030 .clone()
14031 .cached(StyleRefinement::default().size(px(100.)))
14032 }
14033 }
14034
14035 #[derive(Default)]
14036 struct InspectorTestView {
14037 child_widths: Rc<RefCell<Vec<Pixels>>>,
14038 }
14039
14040 impl Render for InspectorTestView {
14041 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14042 let child_widths = self.child_widths.clone();
14043 div()
14044 .on_children_prepainted(move |bounds, _, _| {
14045 *child_widths.borrow_mut() =
14046 bounds.iter().map(|bounds| bounds.size.width).collect();
14047 })
14048 .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
14049 .id("inspector-root")
14050 .flex()
14051 .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
14052 }
14053 }
14054
14055 fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
14056 cx.update_window(window, |root, window, cx| {
14057 window.draw(cx).clear(cx);
14058 window.draw(cx).clear(cx);
14059 let root = root.downcast::<InspectorTestRoot>().expect("test root");
14060 assert_eq!(
14061 root.read(cx)
14062 .child
14063 .read(cx)
14064 .child_widths
14065 .borrow()
14066 .as_slice(),
14067 &[px(10.); 3]
14068 );
14069 for frame in [&window.rendered_frame, &window.next_frame] {
14070 assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
14071 assert_eq!(frame.inspector_hitboxes.capacity(), 0);
14072 }
14073 })
14074 .expect("closed inspector has no bookkeeping and no style overrides");
14075 }
14076}
14077
14078#[cfg(test)]
14080mod vn_assume_active_tests {
14081 use crate::{
14082 Context, FocusHandle, Render, Subscription, TestAppContext, Window, div, prelude::*, px,
14083 size,
14084 };
14085 use std::{cell::Cell, rc::Rc};
14086
14087 struct Focusable {
14088 handle: FocusHandle,
14089 _on_focus: Subscription,
14090 }
14091
14092 impl Render for Focusable {
14093 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14094 div().size_full().track_focus(&self.handle)
14095 }
14096 }
14097
14098 #[gpui::test]
14099 fn an_assumed_active_window_runs_focus_and_ignores_the_os(cx: &mut TestAppContext) {
14100 let focused = Rc::new(Cell::new(0u32));
14101 let counter = focused.clone();
14102 let window = cx.open_window(size(px(200.), px(200.)), move |window, cx| {
14103 let handle = cx.focus_handle();
14104 let on_focus = cx.on_focus(&handle, window, move |_, _, _| counter.set(counter.get() + 1));
14105 Focusable { handle, _on_focus: on_focus }
14106 });
14107 let platform = cx.test_window(window.into());
14108 platform.simulate_active_status_change(false);
14109 cx.run_until_parked();
14110
14111 window
14114 .update(cx, |view, window, cx| window.focus(&view.handle, cx))
14115 .unwrap();
14116 cx.run_until_parked();
14117 assert_eq!(focused.get(), 0, "no focus event without activation");
14118
14119 window
14121 .update(cx, |_, window, _| window.set_assume_active(true))
14122 .unwrap();
14123 cx.run_until_parked();
14124 assert_eq!(focused.get(), 1, "the focus event carries the path");
14125 let active = |cx: &mut TestAppContext| {
14126 window
14127 .update(cx, |_, window, _| window.is_window_active())
14128 .unwrap()
14129 };
14130 assert!(active(cx));
14131
14132 platform.simulate_active_status_change(false);
14134 cx.run_until_parked();
14135 assert!(active(cx), "still active after the OS says otherwise");
14136
14137 window
14139 .update(cx, |_, window, _| window.set_assume_active(false))
14140 .unwrap();
14141 assert!(!active(cx));
14142 }
14143}
14144
14145#[cfg(test)]
14150mod vn_shadow_tests {
14151 use super::{SHADOW_INSET, SHADOW_OUTSIDE_BOX, SHADOW_UNDER_BOX, spread_shadow_radius};
14152 use crate::{
14153 BoxShadow, Context, Hsla, TestAppContext, Window, div, point, prelude::*, px, size,
14154 };
14155
14156 #[test]
14157 fn a_spread_grows_a_rounded_corner_and_keeps_a_square_one_square() {
14158 assert_eq!(spread_shadow_radius(px(6.), px(3.)), px(9.));
14160 assert_eq!(spread_shadow_radius(px(0.), px(3.)), px(0.));
14161 assert_eq!(spread_shadow_radius(px(1.5), px(3.)), px(1.5 + 3. * 0.875));
14163 assert_eq!(spread_shadow_radius(px(6.), px(0.)), px(6.));
14164 assert_eq!(spread_shadow_radius(px(6.), px(-2.)), px(4.));
14165 assert_eq!(spread_shadow_radius(px(1.), px(-2.)), px(0.));
14166 }
14167
14168 struct Ring {
14169 under_box: bool,
14170 }
14171
14172 impl Render for Ring {
14173 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14174 let shadow = |inset: bool| BoxShadow {
14175 color: Hsla::white().opacity(0.5),
14176 offset: point(px(0.), px(0.)),
14177 blur_radius: px(0.),
14178 spread_radius: px(3.),
14179 inset,
14180 };
14181 let mut d = div()
14182 .w(px(100.))
14183 .h(px(36.))
14184 .rounded_md()
14185 .shadow(vec![shadow(false), shadow(true)]);
14186 d.style().vn_shadow_under_box = Some(self.under_box);
14187 d
14188 }
14189 }
14190
14191 fn paint(under_box: bool, cx: &mut TestAppContext) -> (Vec<(u32, f32, f32)>, f32) {
14193 let window = cx.open_window(size(px(300.), px(300.)), move |_, _| Ring { under_box });
14194 cx.run_until_parked();
14195 window
14196 .update(cx, |_, window, _| {
14197 let shadows = window
14198 .rendered_frame
14199 .scene
14200 .shadows
14201 .iter()
14202 .map(|s| (s.inset, s.shape_corner_radii.top_left.0, s.corner_radii.top_left.0))
14203 .collect();
14204 (shadows, window.scale_factor())
14205 })
14206 .unwrap()
14207 }
14208
14209 #[gpui::test]
14210 fn an_outer_shadow_is_cut_out_of_the_border_box_unless_it_stands_in_for_the_box(
14211 cx: &mut TestAppContext,
14212 ) {
14213 let (shadows, scale) = paint(false, cx);
14214 let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
14215 assert_eq!(outer.0, SHADOW_OUTSIDE_BOX, "the shaders cut the border box out of it");
14216 assert_eq!(outer.1, 9. * scale, "6px corner + 3px spread");
14217 assert_eq!(outer.2, 6. * scale, "the cut-out is the border box itself");
14218 assert!(shadows.iter().any(|s| s.0 == SHADOW_INSET), "the inset shadow is unchanged");
14219
14220 let (shadows, _) = paint(true, cx);
14221 let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
14222 assert_eq!(outer.0, SHADOW_UNDER_BOX);
14223 }
14224}
14225
14226#[cfg(test)]
14227mod vn_rounded_mask_tests {
14228 use super::transform_mask;
14229 use crate::{Bounds, ContentMask, Corners, TransformationMatrix, point, px, size};
14230
14231 fn mask(x: f32, y: f32, w: f32, h: f32, radius: f32) -> ContentMask<crate::Pixels> {
14232 ContentMask {
14233 bounds: Bounds::new(point(px(x), px(y)), size(px(w), px(h))),
14234 corner_radii: Corners::all(px(radius)),
14235 }
14236 }
14237
14238 #[test]
14239 fn rectangles_intersect_exactly_and_stay_square() {
14240 let a = mask(0., 0., 100., 100., 0.);
14241 let b = mask(50., 20., 100., 30., 0.);
14242 let both = a.intersect(&b);
14243 assert_eq!(both.bounds, Bounds::new(point(px(50.), px(20.)), size(px(50.), px(30.))));
14244 assert!(!both.is_rounded());
14245 }
14246
14247 #[test]
14248 fn a_corner_keeps_the_radius_of_the_mask_it_belongs_to() {
14249 let card = mask(10., 10., 200., 160., 24.);
14251 let scroller = mask(10., 10., 200., 160., 0.);
14252 assert_eq!(scroller.intersect(&card).corner_radii, Corners::all(px(24.)));
14253 assert_eq!(card.intersect(&scroller).corner_radii, Corners::all(px(24.)));
14254
14255 let header = mask(10., 10., 200., 60., 0.);
14258 let clipped = header.intersect(&card);
14259 assert_eq!(clipped.corner_radii.top_left, px(24.));
14260 assert_eq!(clipped.corner_radii.top_right, px(24.));
14261 assert_eq!(clipped.corner_radii.bottom_left, px(0.));
14262 assert_eq!(clipped.corner_radii.bottom_right, px(0.));
14263
14264 let inner = mask(10., 10., 200., 160., 8.);
14267 assert_eq!(inner.intersect(&card).corner_radii, Corners::all(px(24.)));
14268
14269 let row = mask(40., 60., 100., 20., 0.);
14271 assert!(!row.intersect(&card).is_rounded());
14272
14273 let sliver = mask(10., 10., 200., 10., 0.);
14275 let clipped = sliver.intersect(&card);
14276 assert_eq!(clipped.corner_radii.top_left, px(5.));
14277 }
14278
14279 #[test]
14280 fn contains_follows_the_curve() {
14281 let avatar = mask(0., 0., 64., 64., 32.);
14282 assert!(avatar.contains(&point(px(32.), px(32.))));
14283 assert!(avatar.contains(&point(px(32.), px(1.))), "the top edge's middle");
14284 assert!(!avatar.contains(&point(px(2.), px(2.))), "outside the curve");
14285 assert!(!avatar.contains(&point(px(62.), px(62.))));
14286 assert!(avatar.contains(&point(px(10.), px(10.))), "inside the curve");
14287 assert!(!avatar.contains(&point(px(70.), px(32.))), "outside the rect");
14288 assert!(mask(0., 0., 64., 64., 0.).contains(&point(px(1.), px(1.))));
14289 }
14290
14291 #[test]
14292 fn a_transform_keeps_the_radii_only_while_corners_stay_round() {
14293 let card = mask(0., 0., 100., 100., 10.);
14294 let moved = TransformationMatrix {
14295 rotation_scale: [[1., 0.], [0., 1.]],
14296 translation: [5., 7.],
14297 };
14298 assert_eq!(transform_mask(moved, card, 1.).corner_radii, Corners::all(px(10.)));
14299
14300 let scaled = TransformationMatrix {
14301 rotation_scale: [[2., 0.], [0., 3.]],
14302 translation: [0., 0.],
14303 };
14304 assert_eq!(
14305 transform_mask(scaled, card, 1.).corner_radii,
14306 Corners::all(px(20.)),
14307 "the smaller factor"
14308 );
14309
14310 let rotated = TransformationMatrix {
14311 rotation_scale: [[0., 1.], [-1., 0.]],
14312 translation: [0., 0.],
14313 };
14314 assert!(!transform_mask(rotated, card, 1.).is_rounded());
14315 }
14316}
14317
14318#[cfg(test)]
14320mod vn_pointer_inside_tests {
14321 use crate::{
14322 Context, Modifiers, MouseExitEvent, MouseMoveEvent, PlatformInput, Render,
14323 TestAppContext, Window, div, point, prelude::*, px, size,
14324 };
14325 use std::{cell::Cell, rc::Rc};
14326
14327 struct Hoverable {
14328 hovered: Rc<Cell<bool>>,
14329 }
14330
14331 impl Render for Hoverable {
14332 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14333 let hovered = self.hovered.clone();
14334 div()
14335 .id("box")
14336 .size_full()
14337 .on_hover(move |is_hovered, _, _| hovered.set(*is_hovered))
14338 }
14339 }
14340
14341 #[gpui::test]
14342 fn a_pointer_outside_the_window_hovers_nothing(cx: &mut TestAppContext) {
14343 let hovered = Rc::new(Cell::new(false));
14344 let state = hovered.clone();
14345 let window = cx.open_window(size(px(200.), px(200.)), move |_, _| Hoverable {
14346 hovered: state,
14347 });
14348 let mut platform = cx.test_window(window.into());
14349 let draw = |cx: &mut TestAppContext| {
14350 window.update(cx, |_, window, _| window.refresh()).unwrap();
14351 cx.run_until_parked();
14352 };
14353 let at = |x: f32, y: f32| point(px(x), px(y));
14354 let moved = |x: f32, y: f32| {
14355 PlatformInput::MouseMove(MouseMoveEvent {
14356 position: at(x, y),
14357 pressed_button: None,
14358 modifiers: Modifiers::default(),
14359 })
14360 };
14361
14362 draw(cx);
14366 assert!(!hovered.get(), "a cursor that never entered hovers nothing");
14367
14368 platform.simulate_input(moved(50., 50.));
14369 draw(cx);
14370 assert!(hovered.get(), "a move into the box hovers it");
14371
14372 platform.simulate_hover_status_change(false);
14376 draw(cx);
14377 assert!(!hovered.get(), "a pointer that left hovers nothing");
14378
14379 platform.simulate_input(moved(60., 60.));
14380 draw(cx);
14381 assert!(hovered.get(), "back in");
14382
14383 platform.simulate_input(PlatformInput::MouseExited(MouseExitEvent {
14384 position: at(60., 60.),
14385 pressed_button: None,
14386 modifiers: Modifiers::default(),
14387 }));
14388 draw(cx);
14389 assert!(!hovered.get(), "MouseExited");
14390 }
14391
14392 struct Shaded {
14393 effect: bool,
14394 renders: Rc<Cell<usize>>,
14395 }
14396
14397 impl Render for Shaded {
14398 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14399 self.renders.set(self.renders.get() + 1);
14400 let mut element = div().size_full();
14401 if self.effect {
14402 let mut spec = crate::EffectSpec::NONE;
14403 spec.id = 0;
14404 spec.pointer_param = Some(4);
14405 element.style().vn_effect = Some(spec);
14406 }
14407 element
14408 }
14409 }
14410
14411 #[gpui::test]
14412 fn only_a_pointer_effect_repaints_when_the_pointer_moves(cx: &mut TestAppContext) {
14413 let open = |cx: &mut TestAppContext, effect: bool| {
14414 let renders = Rc::new(Cell::new(0));
14415 let counted = renders.clone();
14416 let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Shaded {
14417 effect,
14418 renders: counted,
14419 });
14420 cx.run_until_parked();
14421 (window, cx.test_window(window.into()), renders)
14422 };
14423 let moved = |x: f32, y: f32| {
14424 PlatformInput::MouseMove(MouseMoveEvent {
14425 position: point(px(x), px(y)),
14426 pressed_button: None,
14427 modifiers: Modifiers::default(),
14428 })
14429 };
14430
14431 let (_, mut platform, renders) = open(cx, false);
14432 platform.simulate_input(moved(10., 10.));
14433 cx.run_until_parked();
14434 let before = renders.get();
14435 platform.simulate_input(moved(20., 20.));
14436 cx.run_until_parked();
14437 assert_eq!(renders.get(), before, "no pointer effect, no repaint");
14438
14439 let (shaded, mut platform, renders) = open(cx, true);
14440 platform.simulate_input(moved(10., 10.));
14441 cx.run_until_parked();
14442 let before = renders.get();
14443 platform.simulate_input(moved(150., 25.));
14444 cx.run_until_parked();
14445 assert!(renders.get() > before, "a pointer effect repaints");
14446 let params = shaded
14447 .update(cx, |_, window, _| {
14448 window.rendered_frame.scene.effect_quads[0].params
14449 })
14450 .unwrap();
14451 assert!((params[4] - 0.75).abs() < 1e-4 && (params[5] - 0.25).abs() < 1e-4);
14452 }
14453
14454 struct Spinning {
14455 speed: Rc<Cell<f32>>,
14456 }
14457
14458 impl Render for Spinning {
14459 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14460 let mut spec = crate::EffectSpec::NONE;
14461 spec.id = 0;
14462 spec.animated_param = Some(0);
14463 spec.params[0] = self.speed.get();
14464 let mut element = div().id("spinning").size_full();
14465 element.style().vn_effect = Some(spec);
14466 element
14467 }
14468 }
14469
14470 #[gpui::test]
14471 fn a_speed_change_continues_the_phase_instead_of_rescaling_the_clock(
14472 cx: &mut TestAppContext,
14473 ) {
14474 let speed = Rc::new(Cell::new(1.));
14475 let shared = speed.clone();
14476 let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Spinning {
14477 speed: shared,
14478 });
14479 cx.run_until_parked();
14480 let repaint = |cx: &mut TestAppContext| {
14481 window.update(cx, |_, window, _| window.refresh()).unwrap();
14482 cx.run_until_parked();
14483 window
14484 .update(cx, |_, window, _| {
14485 let quad = window.rendered_frame.scene.effect_quads[0];
14486 (quad.params[0] * quad.time, quad.time)
14487 })
14488 .unwrap()
14489 };
14490 std::thread::sleep(std::time::Duration::from_millis(200));
14492 let (before, then) = repaint(cx);
14493 assert!((before - then).abs() < 1e-3, "an unchanged speed is `speed * time`");
14494
14495 speed.set(8.);
14496 let (after, now) = repaint(cx);
14497 let advanced = after - before;
14498 assert!(
14499 advanced >= -1e-3 && advanced <= 8. * (now - then) + 1e-3,
14500 "the phase moved by {advanced} in {}s",
14501 now - then
14502 );
14503 }
14504}
14505
14506#[cfg(test)]
14507mod vn_tagged_transform_tests {
14508 use crate::{
14509 AnyElement, App, Bounds, Context, Element, GlobalElementId, InspectorElementId,
14510 IntoElement, LayoutId, Pixels, Render, TestAppContext, TransformLength, TransformSpec,
14511 Window, div, prelude::*, px, size,
14512 };
14513 use std::{cell::RefCell, rc::Rc};
14514
14515 type Seen = Rc<RefCell<Vec<(u32, Bounds<Pixels>, Bounds<Pixels>)>>>;
14516
14517 struct Probe {
14520 tag: u32,
14521 inner: AnyElement,
14522 seen: Seen,
14523 }
14524
14525 impl Element for Probe {
14526 type RequestLayoutState = ();
14527 type PrepaintState = ();
14528 fn id(&self) -> Option<crate::ElementId> {
14529 None
14530 }
14531 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
14532 None
14533 }
14534 fn request_layout(
14535 &mut self,
14536 _: Option<&GlobalElementId>,
14537 _: Option<&InspectorElementId>,
14538 window: &mut Window,
14539 cx: &mut App,
14540 ) -> (LayoutId, ()) {
14541 (self.inner.request_layout(window, cx), ())
14542 }
14543 fn prepaint(
14544 &mut self,
14545 _: Option<&GlobalElementId>,
14546 _: Option<&InspectorElementId>,
14547 bounds: Bounds<Pixels>,
14548 _: &mut (),
14549 window: &mut Window,
14550 cx: &mut App,
14551 ) {
14552 let ancestors = window.element_transform();
14553 let (_, own) =
14554 window.with_hitbox_tag(self.tag, |window| self.inner.prepaint(window, cx));
14555 let seen = window.transformed_bounds(own.unwrap_or(ancestors), bounds);
14556 self.seen.borrow_mut().push((self.tag, bounds, seen));
14557 }
14558 fn paint(
14559 &mut self,
14560 _: Option<&GlobalElementId>,
14561 _: Option<&InspectorElementId>,
14562 _: Bounds<Pixels>,
14563 _: &mut (),
14564 _: &mut (),
14565 window: &mut Window,
14566 cx: &mut App,
14567 ) {
14568 self.inner.paint(window, cx);
14569 }
14570 }
14571
14572 fn moved(x: TransformLength, y: TransformLength, scale: f32) -> TransformSpec {
14573 TransformSpec { translate: (x, y), scale: (scale, scale), ..TransformSpec::IDENTITY }
14574 }
14575
14576 struct Popper {
14579 seen: Seen,
14580 }
14581
14582 impl Render for Popper {
14583 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
14584 let probe = |tag, inner: AnyElement| Probe { tag, inner, seen: self.seen.clone() };
14585 let mut wrapper = div().w(px(100.)).h(px(80.));
14586 wrapper.style().vn_transform =
14587 Some(moved(TransformLength::Pixels(300.), TransformLength::Pixels(200.), 1.0));
14588 let mut scaled = div().w(px(20.)).h(px(10.));
14589 scaled.style().vn_transform =
14590 Some(moved(TransformLength::ZERO, TransformLength::ZERO, 2.0));
14591 let mut pseudo = div().w(px(4.)).h(px(4.));
14594 pseudo.style().vn_transform =
14595 Some(moved(TransformLength::Pixels(50.), TransformLength::ZERO, 1.0));
14596 let button = div()
14597 .ml(px(10.))
14598 .w(px(30.))
14599 .h(px(20.))
14600 .child(probe(3, scaled.into_any_element()))
14601 .child(pseudo);
14602 div().size_full().child(probe(
14603 1,
14604 wrapper.child(probe(2, button.into_any_element())).into_any_element(),
14605 ))
14606 }
14607 }
14608
14609 #[gpui::test]
14610 fn a_probe_sees_its_node_where_the_transforms_put_it(cx: &mut TestAppContext) {
14611 let seen: Seen = Rc::default();
14612 let state = seen.clone();
14613 let window =
14614 cx.open_window(size(px(800.), px(600.)), move |_, _| Popper { seen: state });
14615 window.update(cx, |_, window, _| window.refresh()).unwrap();
14616 cx.run_until_parked();
14617 let seen = seen.borrow();
14618 let at = |tag: u32| *seen.iter().rev().find(|s| s.0 == tag).expect("probed");
14619 let b = |x: f32, y: f32, w: f32, h: f32| {
14620 Bounds::new(crate::point(px(x), px(y)), size(px(w), px(h)))
14621 };
14622 assert_eq!(at(1).1, b(0., 0., 100., 80.));
14624 assert_eq!(at(1).2, b(300., 200., 100., 80.));
14625 assert_eq!(at(2).1, b(10., 0., 30., 20.));
14628 assert_eq!(at(2).2, b(310., 200., 30., 20.));
14629 assert_eq!(at(3).1, b(10., 0., 20., 10.));
14631 assert_eq!(at(3).2, b(300., 195., 40., 20.));
14632 }
14633}