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, AtlasTextureKind, AtlasTile, AvailableSpace, BackdropBlurRect, Background, BorderStyle,
12 EffectQuad, EffectSpec,
13 Bounds, BoxShadow,
14 Capslock, Context, CornerShape, CornerShapes, 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, HdrOutput,
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
369fn window_closed(cx: &crate::AsyncApp, id: WindowId) -> bool {
371 cx.app
372 .upgrade()
373 .is_some_and(|app| !app.is_borrowed() && !app.borrow().windows.contains_key(id))
374}
375
376#[derive(Clone, Copy, Debug, PartialEq, Eq)]
378pub enum FrameOutcome {
379 Drew,
381 NoDraw,
383 Throttled,
385}
386
387#[derive(Clone, Copy, Debug)]
389pub struct FrameWork {
390 pub window_id: WindowId,
392 pub started: Instant,
394 pub ended: Instant,
396 pub outcome: FrameOutcome,
398}
399
400static FRAME_OBSERVER: std::sync::OnceLock<fn(FrameWork)> = std::sync::OnceLock::new();
401
402pub fn observe_frames(observer: fn(FrameWork)) {
405 let _ = FRAME_OBSERVER.set(observer);
406}
407
408fn report_frame(window_id: WindowId, started: Instant, outcome: FrameOutcome) {
409 if let Some(observer) = FRAME_OBSERVER.get() {
410 observer(FrameWork { window_id, started, ended: Instant::now(), outcome });
411 }
412}
413
414#[inline(always)]
417pub(crate) fn with_element_arena<R>(callback: impl FnOnce(&mut Arena) -> R) -> R {
418 let mut callback = Some(callback);
419 let mut result = None;
420 let access = with_element_arena_erased(&mut |arena| {
421 result = Some(callback.take().expect("arena callback runs once")(arena));
422 });
423 drop(callback);
424 access.expect("cannot access a Thread Local Storage value during or after destruction");
425 result.expect("arena callback produces a result")
426}
427
428pub(crate) struct ElementArenaScope {
443 entered: *const RefCell<Arena>,
446 previous: Option<*const RefCell<Arena>>,
447 exited: bool,
448}
449
450impl ElementArenaScope {
451 pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
453 arena.borrow_mut().begin_scope();
454 let previous = CURRENT_ELEMENT_ARENA.with(|current| {
455 let prev = current.get();
456 current.set(Some(arena as *const RefCell<Arena>));
457 prev
458 });
459 Self {
460 entered: arena as *const RefCell<Arena>,
461 previous,
462 exited: false,
463 }
464 }
465
466 pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
475 assert!(
476 std::ptr::eq(self.entered, arena),
477 "ElementArenaScope::exit called with a different arena than was entered"
478 );
479 self.exited = true;
480 ArenaClearNeeded::new(arena)
485 }
486}
487
488impl Drop for ElementArenaScope {
489 fn drop(&mut self) {
490 CURRENT_ELEMENT_ARENA.with(|current| {
497 current.set(self.previous);
498 });
499 unsafe { &*self.entered }.borrow_mut().end_scope();
503 if !self.exited && !std::thread::panicking() {
504 debug_assert!(false, "ElementArenaScope dropped without calling exit()");
505 log::error!(
506 "ElementArenaScope dropped without calling exit(); \
507 the arena clear for this draw was never requested"
508 );
509 }
510 }
511}
512
513#[must_use]
515pub struct ArenaClearNeeded {
516 arena: *const RefCell<Arena>,
519}
520
521impl ArenaClearNeeded {
522 fn new(arena: &RefCell<Arena>) -> Self {
525 Self {
526 arena: arena as *const RefCell<Arena>,
527 }
528 }
529
530 pub fn clear(self, cx: &mut App) {
539 assert!(
540 std::ptr::eq(self.arena, &*cx.element_arena),
541 "ArenaClearNeeded::clear called with a different App than the draw ran against"
542 );
543 RefCell::borrow_mut(&cx.element_arena).clear();
544 }
545}
546
547#[derive(Default)]
548pub(crate) struct FocusMap {
549 pub(crate) handles: SlotMap<FocusId, FocusRef>,
550 pub(crate) dropped_handles: Vec<FocusId>,
551}
552
553pub(crate) struct FocusRef {
554 pub(crate) ref_count: AtomicUsize,
555 pub(crate) tab_index: isize,
556 pub(crate) tab_stop: bool,
557}
558
559impl FocusId {
560 pub fn is_focused(&self, window: &Window) -> bool {
562 window.focus == Some(*self)
563 }
564
565 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
568 window
569 .focused(cx)
570 .is_some_and(|focused| self.contains(focused.id, window))
571 }
572
573 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
576 let focused = window.focused(cx);
577 focused.is_some_and(|focused| focused.id.contains(*self, window))
578 }
579
580 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
582 window
583 .rendered_frame
584 .dispatch_tree
585 .focus_contains(*self, other)
586 }
587}
588
589pub struct FocusHandle {
591 pub(crate) id: FocusId,
592 handles: Arc<RwLock<FocusMap>>,
593 pub tab_index: isize,
595 pub tab_stop: bool,
597}
598
599impl std::fmt::Debug for FocusHandle {
600 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
601 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
602 }
603}
604
605impl FocusHandle {
606 pub(crate) fn new(handles: &Arc<RwLock<FocusMap>>) -> Self {
607 let id = handles.write().handles.insert(FocusRef {
608 ref_count: AtomicUsize::new(1),
609 tab_index: 0,
610 tab_stop: false,
611 });
612
613 Self {
614 id,
615 tab_index: 0,
616 tab_stop: false,
617 handles: handles.clone(),
618 }
619 }
620
621 pub(crate) fn for_id(id: FocusId, handles: &Arc<RwLock<FocusMap>>) -> Option<Self> {
622 let lock = handles.read();
623 let focus = lock.handles.get(id)?;
624 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
625 return None;
626 }
627 Some(Self {
628 id,
629 tab_index: focus.tab_index,
630 tab_stop: focus.tab_stop,
631 handles: handles.clone(),
632 })
633 }
634
635 pub fn tab_index(mut self, index: isize) -> Self {
637 self.tab_index = index;
638 if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
639 focus.tab_index = index;
640 }
641 self
642 }
643
644 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
648 self.tab_stop = tab_stop;
649 if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
650 focus.tab_stop = tab_stop;
651 }
652 self
653 }
654
655 pub fn downgrade(&self) -> WeakFocusHandle {
657 WeakFocusHandle {
658 id: self.id,
659 handles: Arc::downgrade(&self.handles),
660 }
661 }
662
663 pub fn focus(&self, window: &mut Window, cx: &mut App) {
665 window.focus(self, cx)
666 }
667
668 pub fn is_focused(&self, window: &Window) -> bool {
670 self.id.is_focused(window)
671 }
672
673 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
676 self.id.contains_focused(window, cx)
677 }
678
679 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
682 self.id.within_focused(window, cx)
683 }
684
685 pub fn contains(&self, other: &Self, window: &Window) -> bool {
687 self.id.contains(other.id, window)
688 }
689
690 pub fn is_rendered(&self, window: &Window) -> bool {
692 window
693 .rendered_frame
694 .dispatch_tree
695 .focusable_node_id(self.id)
696 .is_some()
697 }
698
699 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
701 if let Some(node_id) = window
702 .rendered_frame
703 .dispatch_tree
704 .focusable_node_id(self.id)
705 {
706 window.dispatch_action_on_node(node_id, action, cx)
707 }
708 }
709}
710
711impl Clone for FocusHandle {
712 fn clone(&self) -> Self {
713 Self::for_id(self.id, &self.handles).unwrap()
714 }
715}
716
717impl PartialEq for FocusHandle {
718 fn eq(&self, other: &Self) -> bool {
719 self.id == other.id
720 }
721}
722
723impl Eq for FocusHandle {}
724
725impl Drop for FocusHandle {
726 fn drop(&mut self) {
727 let handles = self.handles.upgradable_read();
728 let focus = handles.handles.get(self.id).expect("focus handle missing");
729 let previous_count = focus.ref_count.fetch_sub(1, SeqCst);
730 assert_ne!(previous_count, 0, "over-released focus handle");
731 if previous_count == 1 {
732 RwLockUpgradableReadGuard::upgrade(handles)
733 .dropped_handles
734 .push(self.id);
735 }
736 }
737}
738
739#[derive(Clone, Debug)]
741pub struct WeakFocusHandle {
742 pub(crate) id: FocusId,
743 pub(crate) handles: Weak<RwLock<FocusMap>>,
744}
745
746impl WeakFocusHandle {
747 pub fn upgrade(&self) -> Option<FocusHandle> {
749 let handles = self.handles.upgrade()?;
750 FocusHandle::for_id(self.id, &handles)
751 }
752}
753
754impl PartialEq for WeakFocusHandle {
755 fn eq(&self, other: &WeakFocusHandle) -> bool {
756 self.id == other.id
757 }
758}
759
760impl Eq for WeakFocusHandle {}
761
762impl PartialEq<FocusHandle> for WeakFocusHandle {
763 fn eq(&self, other: &FocusHandle) -> bool {
764 self.id == other.id
765 }
766}
767
768impl PartialEq<WeakFocusHandle> for FocusHandle {
769 fn eq(&self, other: &WeakFocusHandle) -> bool {
770 self.id == other.id
771 }
772}
773
774pub trait Focusable: 'static {
777 fn focus_handle(&self, cx: &App) -> FocusHandle;
779}
780
781impl<V: Focusable> Focusable for Entity<V> {
782 fn focus_handle(&self, cx: &App) -> FocusHandle {
783 self.read(cx).focus_handle(cx)
784 }
785}
786
787pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
790
791impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
792
793pub struct DismissEvent;
795
796type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
797
798pub(crate) type AnyMouseListener =
799 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
800
801#[derive(Clone)]
802pub(crate) struct CursorStyleRequest {
803 pub(crate) hitbox_id: Option<HitboxId>,
804 pub(crate) style: CursorStyle,
805}
806
807#[derive(Default, Eq, PartialEq)]
808pub(crate) struct HitTest {
809 pub(crate) ids: SmallVec<[HitboxId; 8]>,
810 pub(crate) hover_hitbox_count: usize,
811}
812
813#[derive(Clone, Copy, Debug, Eq, PartialEq)]
815pub enum WindowControlArea {
816 Drag,
818 Close,
820 Max,
822 Min,
824 NoDrag,
833}
834
835#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
837pub struct HitboxId(u64);
838
839#[cfg(feature = "test-support")]
840impl HitboxId {
841 pub const fn placeholder() -> Self {
846 Self(0)
847 }
848}
849
850impl HitboxId {
851 pub const VN_PICK: HitboxId = HitboxId(u64::MAX);
855
856 pub fn is_hovered(self, window: &Window) -> bool {
863 if window.captured_hitbox == Some(self) {
865 return true;
866 }
867 if window.last_input_was_keyboard() {
868 return false;
869 }
870 self.hit_test(window)
871 }
872
873 pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
878 if window.captured_hitbox == Some(self) {
880 return true;
881 }
882 self.hit_test(window)
883 }
884
885 fn hit_test(self, window: &Window) -> bool {
886 if !window.pointer_inside {
891 return false;
892 }
893 let hit_test = &window.mouse_hit_test;
894 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
895 if self == *id {
896 return true;
897 }
898 }
899 false
900 }
901
902 pub fn should_handle_scroll(self, window: &Window) -> bool {
907 window.mouse_hit_test.ids.contains(&self)
908 }
909
910 fn next(self) -> HitboxId {
911 HitboxId(self.0.wrapping_add(1))
912 }
913}
914
915#[inline]
923fn transform_bounds(
924 matrix: TransformationMatrix,
925 bounds: Bounds<Pixels>,
926 scale_factor: f32,
927) -> Bounds<Pixels> {
928 if matrix.is_unit() {
929 return bounds;
930 }
931 let map = |p: Point<Pixels>| {
935 let d = matrix.apply(Point::new(px(p.x.0 * scale_factor), px(p.y.0 * scale_factor)));
936 Point::new(px(d.x.0 / scale_factor), px(d.y.0 / scale_factor))
937 };
938 let corners = [
939 map(bounds.origin),
940 map(bounds.top_right()),
941 map(bounds.bottom_left()),
942 map(bounds.bottom_right()),
943 ];
944 let min_x = corners.iter().map(|p| p.x).fold(Pixels::MAX, Pixels::min);
945 let max_x = corners.iter().map(|p| p.x).fold(Pixels::MIN, Pixels::max);
946 let min_y = corners.iter().map(|p| p.y).fold(Pixels::MAX, Pixels::min);
947 let max_y = corners.iter().map(|p| p.y).fold(Pixels::MIN, Pixels::max);
948 Bounds::from_corners(Point::new(min_x, min_y), Point::new(max_x, max_y))
949}
950
951fn vn_history_key(element: u64, spec: &EffectSpec) -> u64 {
958 use std::hash::{Hash, Hasher};
959 if element == 0 || spec.flags & crate::EFFECT_FLAG_HISTORY == 0 {
960 return 0;
961 }
962 let mut hasher = collections::FxHasher::default();
963 (element, spec.id).hash(&mut hasher);
964 hasher.finish().max(1)
965}
966
967#[derive(Clone, Copy, Debug, PartialEq)]
972struct VnEffectPhase {
973 at: f32,
974 phase: f64,
975}
976
977impl VnEffectPhase {
978 const KEEP: f32 = 10.;
980
981 fn advance(previous: Option<Self>, speed: f32, now: f32) -> Self {
982 match previous {
983 None => Self {
984 at: now,
985 phase: f64::from(speed) * f64::from(now),
986 },
987 Some(previous) if now > previous.at => Self {
988 at: now,
989 phase: previous.phase + f64::from(speed) * f64::from(now - previous.at),
990 },
991 Some(previous) => previous,
992 }
993 }
994
995 fn speed(&self, now: f32) -> Option<f32> {
998 (now > 1e-3).then(|| (self.phase / f64::from(now)) as f32)
999 }
1000}
1001
1002fn vn_phase_key(element: u64, spec: &EffectSpec) -> u64 {
1003 use std::hash::{Hash, Hasher};
1004 let mut hasher = collections::FxHasher::default();
1005 (element, spec.id, "phase").hash(&mut hasher);
1006 hasher.finish()
1007}
1008
1009fn transform_mask(
1010 matrix: TransformationMatrix,
1011 mask: ContentMask<Pixels>,
1012 scale_factor: f32,
1013) -> ContentMask<Pixels> {
1014 let bounds = transform_bounds(matrix, mask.bounds, scale_factor);
1015 if !mask.is_rounded() || matrix.is_unit() {
1016 return ContentMask {
1017 bounds,
1018 corner_radii: mask.corner_radii,
1019 corner_shapes: mask.corner_shapes,
1020 };
1021 }
1022 let [[a, b], [c, d]] = matrix.rotation_scale;
1023 let (corner_radii, corner_shapes) = if b == 0. && c == 0. && a > 0. && d > 0. {
1024 let factor = a.min(d);
1025 let radii = mask.corner_radii
1026 .map(|radius| *radius * factor)
1027 .clamp_radii_for_quad_size(bounds.size);
1028 (radii, mask.corner_shapes.scale(factor))
1029 } else {
1030 (Corners::default(), CornerShapes::default())
1031 };
1032 ContentMask {
1033 bounds,
1034 corner_radii,
1035 corner_shapes,
1036 }
1037}
1038
1039#[derive(Clone, Debug)]
1042pub struct Hitbox {
1043 pub id: HitboxId,
1045 pub bounds: Bounds<Pixels>,
1047 pub content_mask: ContentMask<Pixels>,
1049 pub behavior: HitboxBehavior,
1051 pub transformation: TransformationMatrix,
1060 pub vn_clip: Option<Arc<crate::VnClipNode>>,
1064}
1065
1066impl_deref!([] Hitbox => bounds: Bounds<Pixels>);
1067
1068impl Hitbox {
1069 pub fn is_hovered(&self, window: &Window) -> bool {
1086 self.id.is_hovered(window)
1087 }
1088
1089 pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
1092 let hit_test = window
1095 .rendered_frame
1096 .hit_test(position, window.scale_factor);
1097 hit_test
1098 .ids
1099 .iter()
1100 .take(hit_test.hover_hitbox_count)
1101 .any(|id| self.id == *id)
1102 }
1103
1104 pub fn should_handle_scroll(&self, window: &Window) -> bool {
1111 self.id.should_handle_scroll(window)
1112 }
1113}
1114
1115pub const VN_TAG_PASSIVE: u32 = 1 << 31;
1121
1122#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1124pub enum VnHitKind {
1125 Down,
1127 Up,
1129 Scroll,
1131}
1132
1133pub type VnHitRefiner = Rc<dyn Fn(VnHitKind, Point<Pixels>, &mut Window, &mut App)>;
1137
1138#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1140pub enum VnPointerLock {
1141 System {
1143 unadjusted: bool,
1145 },
1146 Simulated,
1149}
1150
1151#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1153pub enum HitboxBehavior {
1154 #[default]
1156 Normal,
1157
1158 BlockMouse,
1180
1181 BlockMouseExceptScroll,
1208}
1209
1210#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
1212pub struct TooltipId(usize);
1213
1214impl TooltipId {
1215 pub fn is_hovered(&self, window: &Window) -> bool {
1217 window
1218 .tooltip_bounds
1219 .as_ref()
1220 .is_some_and(|tooltip_bounds| {
1221 tooltip_bounds.id == *self
1222 && tooltip_bounds.bounds.contains(&window.mouse_position())
1223 })
1224 }
1225}
1226
1227pub(crate) struct TooltipBounds {
1228 id: TooltipId,
1229 bounds: Bounds<Pixels>,
1230}
1231
1232#[derive(Clone)]
1233pub(crate) struct TooltipRequest {
1234 id: TooltipId,
1235 tooltip: AnyTooltip,
1236}
1237
1238#[derive(Clone, Default)]
1244pub(crate) struct ElementIdStack {
1245 ids: SmallVec<[ElementId; 32]>,
1246 hashes: SmallVec<[u64; 32]>,
1247}
1248
1249impl ElementIdStack {
1250 pub(crate) fn push(&mut self, id: ElementId) {
1251 self.hashes.push(crate::extend_path_hash(self.hash(), &id));
1252 self.ids.push(id);
1253 }
1254
1255 pub(crate) fn pop(&mut self) -> Option<ElementId> {
1256 self.hashes.pop();
1257 self.ids.pop()
1258 }
1259
1260 pub(crate) fn clear(&mut self) {
1261 self.ids.clear();
1262 self.hashes.clear();
1263 }
1264
1265 fn hash(&self) -> u64 {
1267 self.hashes
1268 .last()
1269 .copied()
1270 .unwrap_or(crate::EMPTY_PATH_HASH)
1271 }
1272
1273 pub(crate) fn global_id(&self) -> GlobalElementId {
1274 GlobalElementId::with_hash(&self.ids, self.hash())
1275 }
1276}
1277
1278impl std::ops::Deref for ElementIdStack {
1279 type Target = [ElementId];
1280
1281 fn deref(&self) -> &Self::Target {
1282 &self.ids
1283 }
1284}
1285
1286pub(crate) struct DeferredDraw {
1287 current_view: EntityId,
1288 priority: usize,
1289 parent_node: DispatchNodeId,
1290 element_id_stack: ElementIdStack,
1291 text_style_stack: Vec<TextStyleRefinement>,
1292 content_mask: Option<ContentMask<Pixels>>,
1293 rem_size: Pixels,
1294 element: Option<AnyElement>,
1295 absolute_offset: Point<Pixels>,
1296 element_transform: TransformationMatrix,
1305 a11y_parent: Option<accesskit::NodeId>,
1309 vn_stack: Option<Rc<[u128]>>,
1313 element_opacity: f32,
1318 vn_clip: Option<Arc<crate::VnClipNode>>,
1323 vn_scope: Option<VnDeferScope>,
1326 prepaint_range: Range<PrepaintStateIndex>,
1327 paint_range: Range<PaintIndex>,
1328 accessed_entities: FxHashSet<EntityId>,
1331}
1332
1333#[derive(Clone, Debug)]
1340pub(crate) struct VnDeferScope {
1341 id: u64,
1342 clip: Option<Arc<crate::VnClipNode>>,
1343}
1344
1345pub(crate) fn vn_element_key(id: Option<&GlobalElementId>) -> u64 {
1349 use std::hash::{Hash, Hasher};
1350 id.map_or(0, |id| {
1351 let mut hasher = collections::FxHasher::default();
1352 for id in id.iter() {
1353 if !matches!(id, ElementId::View(_)) {
1354 id.hash(&mut hasher);
1355 }
1356 }
1357 hasher.finish().max(1)
1358 })
1359}
1360
1361impl DeferredDraw {
1362 fn order(&self) -> (usize, Option<&[u128]>) {
1364 (self.priority, self.vn_stack.as_deref())
1365 }
1366}
1367
1368pub(crate) struct Frame {
1369 pub(crate) focus: Option<FocusId>,
1370 pub(crate) window_active: bool,
1371 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
1372 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
1373 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
1374 pub(crate) dispatch_tree: DispatchTree,
1375 pub(crate) scene: Scene,
1376 pub(crate) hitboxes: Vec<Hitbox>,
1377 pub(crate) vn_tagged_hitboxes: Vec<(u32, Hitbox)>,
1387 pub(crate) vn_hit_order: Vec<u32>,
1396 pub(crate) vn_deferred_tagged: Range<usize>,
1401 vn_tagged_order: std::cell::OnceCell<Option<Vec<u32>>>,
1404 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
1405 pub(crate) deferred_draws: Vec<DeferredDraw>,
1406 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
1407 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
1408 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
1409 #[cfg(any(test, feature = "test-support"))]
1410 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
1411 #[cfg(any(test, feature = "test-support"))]
1412 debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
1413 #[cfg(any(feature = "inspector", debug_assertions))]
1414 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
1415 #[cfg(any(feature = "inspector", debug_assertions))]
1416 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
1417 pub(crate) tab_stops: TabStopMap,
1418}
1419
1420#[derive(Clone, Default)]
1421pub(crate) struct PrepaintStateIndex {
1422 hitboxes_index: usize,
1423 vn_tagged_hitboxes_index: usize,
1427 tooltips_index: usize,
1428 deferred_draws_index: usize,
1429 dispatch_tree_index: usize,
1430 accessed_element_states_index: usize,
1431 line_layout_index: LineLayoutIndex,
1432}
1433
1434#[derive(Clone, Default)]
1435pub(crate) struct PaintIndex {
1436 scene_index: usize,
1437 #[cfg(any(test, feature = "test-support"))]
1438 debug_bounds_index: usize,
1439 mouse_listeners_index: usize,
1440 input_handlers_index: usize,
1441 cursor_styles_index: usize,
1442 window_control_hitboxes_index: usize,
1443 accessed_element_states_index: usize,
1444 tab_handle_index: usize,
1445 line_layout_index: LineLayoutIndex,
1446}
1447
1448impl Frame {
1449 #[cfg(any(test, feature = "test-support"))]
1450 pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) {
1451 self.debug_bounds.insert(selector.clone(), bounds);
1452 self.debug_bounds_records.push((selector, bounds));
1453 }
1454
1455 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
1456 Frame {
1457 focus: None,
1458 window_active: false,
1459 element_states: FxHashMap::default(),
1460 accessed_element_states: Vec::new(),
1461 mouse_listeners: Vec::new(),
1462 dispatch_tree,
1463 scene: Scene::default(),
1464 hitboxes: Vec::new(),
1465 vn_tagged_hitboxes: Vec::new(),
1466 vn_hit_order: Vec::new(),
1467 vn_deferred_tagged: 0..0,
1468 vn_tagged_order: std::cell::OnceCell::new(),
1469 window_control_hitboxes: Vec::new(),
1470 deferred_draws: Vec::new(),
1471 input_handlers: Vec::new(),
1472 tooltip_requests: Vec::new(),
1473 cursor_styles: Vec::new(),
1474
1475 #[cfg(any(test, feature = "test-support"))]
1476 debug_bounds: FxHashMap::default(),
1477 #[cfg(any(test, feature = "test-support"))]
1478 debug_bounds_records: Vec::new(),
1479
1480 #[cfg(any(feature = "inspector", debug_assertions))]
1481 next_inspector_instance_ids: FxHashMap::default(),
1482
1483 #[cfg(any(feature = "inspector", debug_assertions))]
1484 inspector_hitboxes: FxHashMap::default(),
1485 tab_stops: TabStopMap::default(),
1486 }
1487 }
1488
1489 pub(crate) fn clear(&mut self) {
1490 self.element_states.clear();
1491 self.accessed_element_states.clear();
1492 self.mouse_listeners.clear();
1493 self.dispatch_tree.clear();
1494 self.scene.clear();
1495 self.input_handlers.clear();
1496 self.tooltip_requests.clear();
1497 self.cursor_styles.clear();
1498 self.hitboxes.clear();
1499 self.vn_tagged_hitboxes.clear();
1500 self.vn_hit_order.clear();
1501 self.vn_deferred_tagged = 0..0;
1502 self.vn_tagged_order = std::cell::OnceCell::new();
1503 self.window_control_hitboxes.clear();
1504 self.deferred_draws.clear();
1505 self.tab_stops.clear();
1506 self.focus = None;
1507
1508 #[cfg(any(test, feature = "test-support"))]
1509 {
1510 self.debug_bounds.clear();
1511 self.debug_bounds_records.clear();
1512 }
1513
1514 #[cfg(any(feature = "inspector", debug_assertions))]
1515 {
1516 self.next_inspector_instance_ids.clear();
1517 self.inspector_hitboxes.clear();
1518 }
1519 }
1520
1521 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1522 self.cursor_styles
1523 .iter()
1524 .rev()
1525 .fold_while(None, |style, request| match request.hitbox_id {
1526 None => Done(Some(request.style)),
1527 Some(hitbox_id) => Continue(style.or_else(|| {
1528 hitbox_id
1529 .is_hovered_ignoring_last_input(window)
1530 .then_some(request.style)
1531 })),
1532 })
1533 .into_inner()
1534 }
1535
1536 fn box_contains(hitbox: &Hitbox, position: Point<Pixels>, scale_factor: f32) -> bool {
1538 let local = if hitbox.transformation.is_unit() {
1552 position
1553 } else {
1554 match hitbox.transformation.inverse() {
1555 Some(inverse) => {
1556 let d = inverse.apply(Point::new(
1557 px(position.x.0 * scale_factor),
1558 px(position.y.0 * scale_factor),
1559 ));
1560 Point::new(px(d.x.0 / scale_factor), px(d.y.0 / scale_factor))
1561 }
1562 None => return false,
1563 }
1564 };
1565 hitbox.content_mask.contains(&position)
1574 && hitbox.bounds.contains(&local)
1575 && hitbox.vn_clip.as_ref().is_none_or(|clip| {
1578 clip.contains([position.x.0 * scale_factor, position.y.0 * scale_factor])
1579 })
1580 }
1581
1582 fn vn_tagged_paint_order(&self) -> Option<&[u32]> {
1589 self.vn_tagged_order
1590 .get_or_init(|| {
1591 let deferred = self.vn_deferred_tagged.clone();
1592 if deferred.is_empty() {
1593 return None;
1594 }
1595 let len = self.vn_tagged_hitboxes.len();
1596 let mut order: Vec<u32> = Vec::with_capacity(len);
1597 order.extend(0..deferred.start as u32);
1598 let draws = &self.deferred_draws;
1599 let mut traversal = (0..draws.len()).collect::<Vec<_>>();
1600 traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
1601 for ix in traversal {
1602 let range = &draws[ix].prepaint_range;
1603 let (start, end) = (
1604 range.start.vn_tagged_hitboxes_index,
1605 range.end.vn_tagged_hitboxes_index,
1606 );
1607 if start >= deferred.start && end <= deferred.end && start < end {
1608 order.extend(start as u32..end as u32);
1609 }
1610 }
1611 order.extend(deferred.end as u32..len as u32);
1612 (order.len() == len).then_some(order)
1615 })
1616 .as_deref()
1617 }
1618
1619 fn topmost_hitboxes(&self) -> impl Iterator<Item = &Hitbox> {
1622 let in_paint_order = self.vn_hit_order.len() == self.hitboxes.len();
1623 (0..self.hitboxes.len()).rev().map(move |index| {
1624 let index = if in_paint_order { self.vn_hit_order[index] as usize } else { index };
1625 &self.hitboxes[index]
1626 })
1627 }
1628
1629 pub(crate) fn hit_test(&self, position: Point<Pixels>, scale_factor: f32) -> HitTest {
1630 let mut set_hover_hitbox_count = false;
1631 let mut hit_test = HitTest::default();
1632 for hitbox in self.topmost_hitboxes() {
1633 if Self::box_contains(hitbox, position, scale_factor) {
1634 hit_test.ids.push(hitbox.id);
1635 if !set_hover_hitbox_count
1636 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1637 {
1638 hit_test.hover_hitbox_count = hit_test.ids.len();
1639 set_hover_hitbox_count = true;
1640 }
1641 if hitbox.behavior == HitboxBehavior::BlockMouse {
1642 break;
1643 }
1644 }
1645 }
1646 if !set_hover_hitbox_count {
1647 hit_test.hover_hitbox_count = hit_test.ids.len();
1648 }
1649 hit_test
1650 }
1651
1652 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1653 self.focus
1654 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1655 .unwrap_or_default()
1656 }
1657
1658 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1659 for element_state_key in &self.accessed_element_states {
1660 if let Some((element_state_key, element_state)) =
1661 prev_frame.element_states.remove_entry(element_state_key)
1662 {
1663 self.element_states.insert(element_state_key, element_state);
1664 }
1665 }
1666
1667 self.scene.finish();
1668 }
1669}
1670
1671#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1672enum InputModality {
1673 Mouse,
1674 Keyboard,
1675 Touch,
1676}
1677
1678struct VnEffectPointer {
1681 moved: f32,
1684 entered: f32,
1685 left: f32,
1686 views: FxHashSet<EntityId>,
1688}
1689
1690impl VnEffectPointer {
1691 const NEVER: f32 = -1.0e4;
1693
1694 fn new(inside: bool) -> Self {
1695 let (entered, left) = if inside {
1696 (Self::NEVER, Self::NEVER - 1.)
1697 } else {
1698 (Self::NEVER - 1., Self::NEVER)
1699 };
1700 Self {
1701 moved: Self::NEVER,
1702 entered,
1703 left,
1704 views: FxHashSet::default(),
1705 }
1706 }
1707
1708 fn update(&mut self, was_inside: bool, inside: bool, moved: bool, cx: &mut App) {
1709 if was_inside == inside && !moved {
1710 return;
1711 }
1712 let now = crate::effect_clock_seconds();
1713 if moved {
1714 self.moved = now;
1715 }
1716 if inside && !was_inside {
1717 self.entered = now;
1718 } else if was_inside && !inside {
1719 self.left = now;
1720 }
1721 for view in self.views.drain() {
1722 cx.notify(view);
1723 }
1724 }
1725}
1726
1727pub struct Window {
1729 pub(crate) handle: AnyWindowHandle,
1730 pub(crate) invalidator: WindowInvalidator,
1731 pub(crate) removed: bool,
1732 pub(crate) platform_window: Box<dyn PlatformWindow>,
1733 pub(crate) display_id: Option<DisplayId>,
1734 pub(crate) display_observers: SingleSubscriberSet<AnyObserver>,
1735 is_resizable: bool,
1736 is_minimizable: bool,
1737 last_window_bounds: WindowBounds,
1738 sprite_atlas: Arc<dyn PlatformAtlas>,
1739 text_system: Rc<WindowTextSystem>,
1740 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1741 rem_size: Pixels,
1742 rem_size_override_stack: SmallVec<[Pixels; 8]>,
1747 pub(crate) viewport_size: Size<Pixels>,
1748 layout_engine: Option<TaffyLayoutEngine>,
1749 pub(crate) root: Option<AnyView>,
1750 pub(crate) element_id_stack: ElementIdStack,
1751 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1752 pub(crate) rendered_entity_stack: Vec<EntityId>,
1753 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1754 pub(crate) element_opacity: f32,
1755 element_image_tint: Hsla,
1758 element_image_headroom: f32,
1761 pub(crate) element_transform: TransformationMatrix,
1769 vn_hitbox_tag: u32,
1773 vn_tag_fresh: bool,
1777 vn_tag_transform: Option<TransformationMatrix>,
1780 vn_tag_every_hitbox: bool,
1785 vn_pick_every_box: bool,
1788 vn_hit_refiner: Option<VnHitRefiner>,
1790 input_interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
1792 vn_key_event_seq: u64,
1794 vn_pointer_lock: Option<(VnPointerLock, Point<Pixels>)>,
1796 vn_raw_mouse_position: Option<Point<Pixels>>,
1798 vn_mouse_movement: Point<Pixels>,
1800 vn_pen: Option<crate::PenInput>,
1802 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1803 pub(crate) vn_clip_stack: Option<Arc<crate::VnClipNode>>,
1807 vn_capture_records: FxHashMap<u64, (crate::VnCaptureInfo, Bounds<ScaledPixels>)>,
1810 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1811 last_text_input_configuration: Option<TextInputConfiguration>,
1815 focused_text_input: Option<FocusId>,
1816 pub(crate) image_cache_stack: Vec<AnyImageCache>,
1817 pub(crate) rendered_frame: Frame,
1818 pub(crate) next_frame: Frame,
1819 next_hitbox_id: HitboxId,
1820 pub(crate) next_tooltip_id: TooltipId,
1821 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1822 pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1823 pub(crate) next_frame_wanted: Rc<Cell<bool>>,
1826 pub(crate) dirty_views: FxHashSet<EntityId>,
1827 focus_listeners: SingleSubscriberSet<AnyWindowFocusListener>,
1828 pub(crate) focus_lost_listeners: SingleSubscriberSet<AnyObserver>,
1829 focus_lost_path: SmallVec<[FocusId; 8]>,
1830 default_prevented: bool,
1831 mouse_position: Point<Pixels>,
1832 mouse_hit_test: HitTest,
1833 modifiers: Modifiers,
1834 capslock: Capslock,
1835 scale_factor: f32,
1836 pub(crate) bounds_observers: SingleSubscriberSet<AnyObserver>,
1837 appearance: WindowAppearance,
1838 pub(crate) appearance_observers: SingleSubscriberSet<AnyObserver>,
1839 pub(crate) button_layout_observers: SingleSubscriberSet<AnyObserver>,
1840 active: Rc<Cell<bool>>,
1841 assume_active: bool,
1843 visibility: WindowVisibility,
1844 pub(crate) visibility_observers:
1845 SingleSubscriberSet<Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
1846 hovered: Rc<Cell<bool>>,
1847 pointer_inside: bool,
1861 vn_effect_pointer: VnEffectPointer,
1862 vn_effect_element: u64,
1865 vn_effect_phases: FxHashMap<u64, VnEffectPhase>,
1868 vn_defer_scope: Option<VnDeferScope>,
1871 vn_scopes_painted: FxHashSet<u64>,
1874 pub(crate) needs_present: Rc<Cell<bool>>,
1875 scene_animation_interval: Rc<Cell<Option<Duration>>>,
1878 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1881 #[cfg(feature = "profiler")]
1882 pub(crate) window_profiler: profiler::WindowProfiler,
1883 last_input_modality: InputModality,
1884 touch_gestures: TouchGestureRecognizer,
1885 touch_prediction_enabled: bool,
1886 long_press_timer: Option<Task<()>>,
1887 long_press_capture: Option<EntityId>,
1888 pub(crate) refreshing: bool,
1889 pub(crate) activation_observers: SingleSubscriberSet<AnyObserver>,
1890 pub(crate) focus: Option<FocusId>,
1891 focus_enabled: bool,
1892 pub(crate) focus_generation: u64,
1895 pending_input: Option<PendingInput>,
1896 pending_modifier: ModifierState,
1897 pub(crate) pending_input_observers: SingleSubscriberSet<AnyObserver>,
1898 prompt: Option<RenderablePromptHandle>,
1899 pub(crate) client_inset: Option<Pixels>,
1900 captured_hitbox: Option<HitboxId>,
1903 #[cfg(any(feature = "inspector", debug_assertions))]
1904 inspector: Option<Entity<Inspector>>,
1905 #[cfg(feature = "profiler")]
1906 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1907 pub(crate) a11y: A11y,
1908}
1909
1910#[derive(Clone, Debug, Default)]
1911struct ModifierState {
1912 modifiers: Modifiers,
1913 saw_other_input: bool,
1914}
1915
1916#[derive(Clone, Debug)]
1919pub(crate) struct InputRateTracker {
1920 timestamps: Vec<Instant>,
1921 window: Duration,
1922 inputs_per_second: u32,
1923 sustain_until: Instant,
1924 sustain_duration: Duration,
1925}
1926
1927const FRAME_INTERVAL_TOLERANCE: Duration = Duration::from_millis(1);
1928
1929#[derive(Default)]
1931struct FramePacer {
1932 last_frame: Option<Instant>,
1933}
1934
1935impl FramePacer {
1936 fn should_defer(&mut self, now: Instant, minimum_interval: Option<Duration>) -> bool {
1937 if let Some(interval) = minimum_interval
1938 && let Some(last_frame) = self.last_frame
1939 {
1940 let deadline = last_frame + interval;
1941 if now + FRAME_INTERVAL_TOLERANCE < deadline {
1942 return true;
1943 }
1944 self.last_frame = Some(if now.saturating_duration_since(deadline) <= interval / 4 {
1948 deadline
1949 } else {
1950 now
1951 });
1952 } else {
1953 self.last_frame = Some(now);
1954 }
1955 false
1956 }
1957}
1958
1959fn minimum_frame_interval(
1960 should_throttle: bool,
1961 inactive_without_high_rate_input: bool,
1962 inactive_frame_interval: Option<Duration>,
1963 low_power_frame_interval: Option<Duration>,
1964 thermal_frame_interval: Option<Duration>,
1965 thermal_state: ThermalState,
1966 power_mode: crate::PowerMode,
1967) -> Option<Duration> {
1968 if !should_throttle {
1969 return None;
1970 }
1971
1972 [
1973 inactive_frame_interval.filter(|_| inactive_without_high_rate_input),
1974 low_power_frame_interval.filter(|_| power_mode == crate::PowerMode::LowPower),
1975 thermal_frame_interval.filter(|_| {
1976 matches!(
1977 thermal_state,
1978 ThermalState::Critical | ThermalState::Serious
1979 )
1980 }),
1981 ]
1982 .into_iter()
1983 .flatten()
1984 .max()
1985}
1986
1987impl Default for InputRateTracker {
1988 fn default() -> Self {
1989 Self {
1990 timestamps: Vec::new(),
1991 window: Duration::from_millis(100),
1992 inputs_per_second: 60,
1993 sustain_until: Instant::now(),
1994 sustain_duration: Duration::from_secs(1),
1995 }
1996 }
1997}
1998
1999impl InputRateTracker {
2000 pub fn record_input(&mut self) {
2001 let now = Instant::now();
2002 self.timestamps.push(now);
2003 self.prune_old_timestamps(now);
2004
2005 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
2006 if self.timestamps.len() as u128 >= min_events {
2007 self.sustain_until = now + self.sustain_duration;
2008 }
2009 }
2010
2011 pub fn is_high_rate(&self) -> bool {
2012 Instant::now() < self.sustain_until
2013 }
2014
2015 fn prune_old_timestamps(&mut self, now: Instant) {
2016 self.timestamps
2017 .retain(|&t| now.duration_since(t) <= self.window);
2018 }
2019}
2020
2021#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2022pub(crate) enum DrawPhase {
2023 None,
2024 Prepaint,
2025 Paint,
2026 Focus,
2027}
2028
2029pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
2030
2031pub struct PendingInputStatus<'a> {
2033 keystrokes: &'a [Keystroke],
2034 timeout: Option<PendingInputTimeoutStatus>,
2035}
2036
2037impl<'a> PendingInputStatus<'a> {
2038 pub fn keystrokes(&self) -> &'a [Keystroke] {
2040 self.keystrokes
2041 }
2042
2043 pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
2045 self.timeout
2046 }
2047}
2048
2049#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2051pub struct PendingInputTimeoutStatus {
2052 duration: Duration,
2053 remaining: Duration,
2054 started_at: Option<Instant>,
2055 paused: bool,
2056}
2057
2058impl PendingInputTimeoutStatus {
2059 pub fn duration(&self) -> Duration {
2061 self.duration
2062 }
2063
2064 pub fn remaining(&self, cx: &App) -> Duration {
2066 self.started_at
2067 .map(|started_at| {
2068 self.remaining
2069 .saturating_sub(cx.background_executor().now() - started_at)
2070 })
2071 .unwrap_or(self.remaining)
2072 }
2073
2074 pub fn is_paused(&self) -> bool {
2076 self.paused
2077 }
2078}
2079
2080#[derive(Debug)]
2081struct PendingInputTimeout {
2082 duration: Duration,
2083 remaining: Duration,
2084 state: PendingInputTimeoutState,
2085}
2086
2087#[derive(Debug)]
2088enum PendingInputTimeoutState {
2089 Running { started_at: Instant, task: Task<()> },
2090 Paused { pause: PendingInputTimeoutPause },
2091}
2092
2093#[derive(Debug)]
2094struct PendingInputTimeoutPause {
2095 owner_id: EntityId,
2096 _release_subscription: Subscription,
2097}
2098
2099impl PendingInputTimeout {
2100 fn is_paused(&self) -> bool {
2101 matches!(&self.state, PendingInputTimeoutState::Paused { .. })
2102 }
2103
2104 fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
2105 match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
2106 PendingInputTimeoutState::Running { started_at, task } => {
2107 self.remaining = self.remaining.saturating_sub(now - started_at);
2108 drop(task);
2109 true
2110 }
2111 previous_state @ PendingInputTimeoutState::Paused { .. } => {
2112 self.state = previous_state;
2113 false
2114 }
2115 }
2116 }
2117
2118 fn pause_owner_id(&self) -> Option<EntityId> {
2119 match &self.state {
2120 PendingInputTimeoutState::Running { .. } => None,
2121 PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
2122 }
2123 }
2124
2125 fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
2126 match std::mem::replace(
2127 &mut self.state,
2128 PendingInputTimeoutState::Running { started_at, task },
2129 ) {
2130 PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
2131 previous_state => {
2132 self.state = previous_state;
2133 false
2134 }
2135 }
2136 }
2137
2138 fn reset_duration(&mut self, duration: Duration) {
2139 self.duration = duration;
2140 self.remaining = duration;
2141 }
2142
2143 fn status(&self) -> PendingInputTimeoutStatus {
2144 let (started_at, paused) = match &self.state {
2145 PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
2146 PendingInputTimeoutState::Paused { .. } => (None, true),
2147 };
2148 PendingInputTimeoutStatus {
2149 duration: self.duration,
2150 remaining: self.remaining,
2151 started_at,
2152 paused,
2153 }
2154 }
2155}
2156
2157#[derive(Default, Debug)]
2158struct PendingInput {
2159 keystrokes: SmallVec<[Keystroke; 1]>,
2160 focus: Option<FocusId>,
2161 timeout: Option<PendingInputTimeout>,
2162}
2163
2164pub(crate) struct ElementStateBox {
2165 pub(crate) inner: Box<dyn Any>,
2166 #[cfg(debug_assertions)]
2167 pub(crate) type_name: &'static str,
2168}
2169
2170fn default_bounds(
2171 active_window_bounds: Option<WindowBounds>,
2172 display: Option<&dyn PlatformDisplay>,
2173) -> WindowBounds {
2174 const CASCADE_OFFSET: f32 = 25.0;
2175
2176 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
2177
2178 let display_bounds = display
2180 .map(|d| d.visible_bounds())
2181 .unwrap_or_else(default_placement);
2182
2183 let (
2184 Bounds {
2185 origin: base_origin,
2186 size: base_size,
2187 },
2188 window_bounds_ctor,
2189 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
2190 Some(bounds) => match bounds {
2191 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
2192 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
2193 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
2194 },
2195 None => (
2196 display
2197 .map(|d| d.default_bounds())
2198 .unwrap_or_else(default_placement),
2199 WindowBounds::Windowed,
2200 ),
2201 };
2202
2203 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
2204 let proposed_origin = base_origin + cascade_offset;
2205 let proposed_bounds = Bounds::new(proposed_origin, base_size);
2206
2207 let display_right = display_bounds.origin.x + display_bounds.size.width;
2208 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
2209 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
2210 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
2211
2212 let fits_horizontally = window_right <= display_right;
2213 let fits_vertically = window_bottom <= display_bottom;
2214
2215 let final_origin = match (fits_horizontally, fits_vertically) {
2216 (true, true) => proposed_origin,
2217 (false, true) => point(display_bounds.origin.x, base_origin.y),
2218 (true, false) => point(base_origin.x, display_bounds.origin.y),
2219 (false, false) => display_bounds.origin,
2220 };
2221 window_bounds_ctor(Bounds::new(final_origin, base_size))
2222}
2223
2224fn report_bounds_changed(
2228 handle: AnyWindowHandle,
2229 cx: &mut crate::AsyncApp,
2230 deferred: &Rc<Cell<bool>>,
2231 what: &'static str,
2232) {
2233 let borrowed = cx.app.upgrade().is_some_and(|app| app.is_borrowed());
2234 if !borrowed {
2235 handle
2236 .update(cx, |_, window, cx| window.bounds_changed(cx))
2237 .with_context(|| format!("handling {what} for window {:?}", handle.window_id()))
2238 .log_err();
2239 return;
2240 }
2241 if deferred.replace(true) {
2242 return;
2243 }
2244 let deferred = deferred.clone();
2245 let mut cx = cx.clone();
2246 cx.foreground_executor()
2247 .clone()
2248 .spawn(async move {
2249 deferred.set(false);
2250 handle
2252 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2253 .ok();
2254 })
2255 .detach();
2256}
2257
2258impl Window {
2259 pub(crate) fn new(
2260 handle: AnyWindowHandle,
2261 options: WindowOptions,
2262 cx: &mut App,
2263 ) -> Result<Self> {
2264 let WindowOptions {
2265 window_bounds,
2266 titlebar,
2267 focus,
2268 show,
2269 kind,
2270 is_movable,
2271 app_owns_titlebar_drag,
2272 inactive_frame_interval,
2273 low_power_frame_interval,
2274 thermal_frame_interval,
2275 is_resizable,
2276 is_minimizable,
2277 display_id,
2278 window_background,
2279 app_id,
2280 window_min_size,
2281 window_decorations,
2282 #[cfg_attr(
2283 not(any(target_os = "linux", target_os = "freebsd")),
2284 allow(unused_variables)
2285 )]
2286 icon,
2287 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
2288 tabbing_identifier,
2289 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
2290 use_display_p3,
2291 } = options;
2292
2293 let initial_window_title = titlebar
2294 .as_ref()
2295 .and_then(|titlebar| titlebar.title.clone());
2296
2297 let active_window_placement = cx.active_window_placement();
2298 let target_display_id = display_id.or_else(|| {
2300 active_window_placement
2301 .filter(|_| window_bounds.is_none())
2302 .and_then(|(display_id, _)| display_id)
2303 });
2304 let display = target_display_id
2305 .and_then(|display_id| cx.find_display(display_id))
2306 .or_else(|| cx.primary_display());
2307 let display_id = display
2308 .as_ref()
2309 .map(|display| display.id())
2310 .or(target_display_id);
2311 let active_window_bounds = active_window_placement
2312 .filter(|(active_display_id, _)| *active_display_id == display_id)
2313 .map(|(_, bounds)| bounds);
2314 let window_bounds = window_bounds
2315 .unwrap_or_else(|| default_bounds(active_window_bounds, display.as_deref()));
2316 let mut platform_window = cx.platform.open_window(
2317 handle,
2318 WindowParams {
2319 bounds: window_bounds.get_bounds(),
2320 titlebar,
2321 kind,
2322 is_movable,
2323 app_owns_titlebar_drag,
2324 is_resizable,
2325 is_minimizable,
2326 focus,
2327 show,
2328 display_id,
2329 window_min_size,
2330 app_id: app_id.clone(),
2331 icon,
2332 #[cfg(target_os = "macos")]
2333 tabbing_identifier,
2334 #[cfg(target_os = "macos")]
2335 use_display_p3,
2336 },
2337 )?;
2338
2339 let tab_bar_visible = platform_window.tab_bar_visible();
2340 SystemWindowTabController::init_visible(cx, tab_bar_visible);
2341 if let Some(tabs) = platform_window.tabbed_windows() {
2342 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
2343 }
2344
2345 let display_id = platform_window.display().map(|display| display.id());
2346 let sprite_atlas = platform_window.sprite_atlas();
2347 let mouse_position = platform_window.mouse_position();
2348 let modifiers = platform_window.modifiers();
2349 let capslock = platform_window.capslock();
2350 let content_size = platform_window.content_size();
2351 let scale_factor = platform_window.scale_factor();
2352 let appearance = platform_window.appearance();
2353 let text_system = Rc::new(WindowTextSystem::new(cx.text_system().clone()));
2354 let invalidator = WindowInvalidator::new(handle.window_id());
2355 let active = Rc::new(Cell::new(platform_window.is_active()));
2356 let visibility = platform_window.visibility();
2357 #[cfg(feature = "profiler")]
2358 profiler::journal::record_window_visibility(handle.window_id(), visibility);
2359 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
2360 let needs_present = Rc::new(Cell::new(false));
2361 let scene_animation_interval = Rc::new(Cell::new(None::<Duration>));
2362 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
2363 let next_frame_wanted: Rc<Cell<bool>> = Default::default();
2364 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
2365
2366 platform_window
2367 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
2368 platform_window.set_background_appearance(window_background);
2369
2370 match window_bounds {
2371 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
2372 WindowBounds::Maximized(_) => platform_window.zoom(),
2373 WindowBounds::Windowed(_) => {}
2374 }
2375
2376 let accessibility_force_disabled = cx.accessibility_force_disabled;
2377 let a11y_active_flag = Arc::new(AtomicBool::new(false));
2378
2379 #[cfg(not(target_family = "wasm"))]
2380 if !accessibility_force_disabled {
2381 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
2382 if let Some(title) = &initial_window_title {
2383 initial_root_node.set_label(title.to_string());
2384 }
2385 let initial_tree = accesskit::TreeUpdate {
2386 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
2387 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
2388 tree_id: accesskit::TreeId::ROOT,
2389 focus: ROOT_NODE_ID,
2390 };
2391 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
2392 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
2393 let (action_sender, action_receiver) =
2394 async_channel::unbounded::<accesskit::ActionRequest>();
2395
2396 platform_window.a11y_init(crate::A11yCallbacks {
2397 activation: {
2398 let active_flag = a11y_active_flag.clone();
2399 Box::new(move || {
2400 log::info!("Accessibility activated");
2401 active_flag.store(true, SeqCst);
2402 activation_sender
2403 .send_blocking(())
2404 .with_context(|| {
2405 format!(
2406 "queuing accessibility activation for window {:?}",
2407 handle.window_id()
2408 )
2409 })
2410 .log_err();
2411 Some(initial_tree.clone())
2412 })
2413 },
2414 action: Box::new(move |request| {
2415 action_sender
2416 .send_blocking(request)
2417 .with_context(|| {
2418 format!(
2419 "queuing accessibility action for window {:?}",
2420 handle.window_id()
2421 )
2422 })
2423 .log_err();
2424 }),
2425 deactivation: {
2426 let active_flag = a11y_active_flag.clone();
2427 Box::new(move || {
2428 log::info!("Accessibility deactivated");
2429 active_flag.store(false, SeqCst);
2430 deactivation_sender
2431 .send_blocking(())
2432 .with_context(|| {
2433 format!(
2434 "queuing accessibility deactivation for window {:?}",
2435 handle.window_id()
2436 )
2437 })
2438 .log_err();
2439 })
2440 },
2441 });
2442
2443 let mut async_cx = cx.to_async();
2449 cx.foreground_executor()
2450 .spawn(async move {
2451 while activation_receiver.recv().await.is_ok() {
2452 handle
2453 .update(&mut async_cx, |_, window, _| window.refresh())
2454 .with_context(|| {
2455 format!(
2456 "handling accessibility activation for window {:?}",
2457 handle.window_id()
2458 )
2459 })
2460 .log_err();
2461 }
2462 })
2463 .detach();
2464
2465 let mut async_cx = cx.to_async();
2466 cx.foreground_executor()
2467 .spawn(async move {
2468 while deactivation_receiver.recv().await.is_ok() {
2469 handle
2470 .update(&mut async_cx, |_, window, _| window.refresh())
2471 .with_context(|| {
2472 format!(
2473 "handling accessibility deactivation for window {:?}",
2474 handle.window_id()
2475 )
2476 })
2477 .log_err();
2478 }
2479 })
2480 .detach();
2481
2482 let mut async_cx = cx.to_async();
2483 cx.foreground_executor()
2484 .spawn(async move {
2485 while let Ok(request) = action_receiver.recv().await {
2486 handle
2487 .update(&mut async_cx, |_, window, cx| {
2488 window.handle_a11y_action(request, cx);
2489 })
2490 .with_context(|| {
2491 format!(
2492 "handling accessibility action for window {:?}",
2493 handle.window_id()
2494 )
2495 })
2496 .log_err();
2497 }
2498 })
2499 .detach();
2500 }
2501
2502 platform_window.on_close(Box::new({
2503 let window_id = handle.window_id();
2504 let cx = cx.to_async();
2505 move || {
2506 cx.spawn(async move |cx| {
2509 cx.update(|cx| {
2510 if cx.windows.contains_key(window_id) {
2512 handle
2513 .update(cx, |_, window, _| window.remove_window())
2514 .with_context(|| format!("handling close for window {window_id:?}"))
2515 .log_err();
2516 }
2517 SystemWindowTabController::remove_tab(cx, window_id);
2518 });
2519 })
2520 .detach();
2521 }
2522 }));
2523 platform_window.on_request_frame(Box::new({
2524 let mut cx = cx.to_async();
2525 let invalidator = invalidator.clone();
2526 let active = active.clone();
2527 let needs_present = needs_present.clone();
2528 let scene_animation_interval = scene_animation_interval.clone();
2529 let next_frame_callbacks = next_frame_callbacks.clone();
2530 let next_frame_wanted = next_frame_wanted.clone();
2531 let input_rate_tracker = input_rate_tracker.clone();
2532 let mut deferred_force_render = false;
2533 let mut frame_pacer = FramePacer::default();
2534 move |request_frame_options| {
2535 #[cfg(feature = "profiler")]
2536 let (_foreground_turn, window_id) = {
2537 let foreground_turn = profiler::journal::foreground_turn();
2538 let window_id = handle.window_id();
2539 profiler::journal::record_platform_signal(profiler::journal::PlatformSignal {
2540 window_id,
2541 signal_at: request_frame_options.signal_at,
2542 handled_at: Instant::now(),
2543 source: request_frame_options.signal_source,
2544 });
2545 (foreground_turn, window_id)
2546 };
2547 if draw_in_progress() {
2563 log::debug!("deferring re-entrant window draw request");
2564 deferred_force_render |= request_frame_options.force_render;
2565 #[cfg(feature = "profiler")]
2566 profiler::journal::record_reentrant_frame_skipped(window_id, Instant::now());
2567 return;
2568 }
2569 let force_render =
2573 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
2574
2575 let power_state = handle
2576 .update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode()))
2577 .with_context(|| {
2578 format!(
2579 "reading power state for frame request for window {:?}",
2580 handle.window_id()
2581 )
2582 })
2583 .log_err();
2584
2585 let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate();
2588 let present_for_high_rate_input = cfg!(target_os = "macos") && high_rate_input;
2592 let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty();
2593 let wants_frame_besides_animation = invalidator.is_dirty()
2598 || force_render
2599 || next_frame_wanted.get()
2600 || request_frame_options.require_presentation
2601 || needs_present.get()
2602 || present_for_high_rate_input;
2603 let has_demand_besides_animation =
2604 wants_frame_besides_animation || has_next_frame_callbacks;
2605 let wants_frame =
2606 wants_frame_besides_animation || scene_animation_interval.get().is_some();
2607 let has_frame_demand = wants_frame || has_next_frame_callbacks;
2608
2609 let should_throttle = !request_frame_options.require_presentation;
2610 let inactive_without_high_rate_input =
2611 should_throttle && !active.get() && !high_rate_input;
2612 let (thermal_state, power_mode) =
2613 power_state.unwrap_or((ThermalState::Nominal, crate::PowerMode::Unknown));
2614 let min_frame_interval = minimum_frame_interval(
2615 should_throttle,
2616 inactive_without_high_rate_input,
2617 inactive_frame_interval,
2618 low_power_frame_interval,
2619 thermal_frame_interval,
2620 thermal_state,
2621 power_mode,
2622 );
2623 let animation_frame_interval = scene_animation_interval
2624 .get()
2625 .filter(|interval| !has_demand_besides_animation && !interval.is_zero());
2626 let min_frame_interval = min_frame_interval.max(animation_frame_interval);
2627
2628 let now = Instant::now();
2629 if has_frame_demand && frame_pacer.should_defer(now, min_frame_interval) {
2632 deferred_force_render |= force_render;
2634 if wants_frame {
2636 handle
2638 .update(&mut cx, |_, window, _| {
2639 window.platform_window.schedule_frame();
2640 })
2641 .with_context(|| {
2642 format!(
2643 "rescheduling throttled frame for window {:?}",
2644 handle.window_id()
2645 )
2646 })
2647 .log_err();
2648 invalidator.wake_platform();
2651 }
2652 #[cfg(feature = "profiler")]
2653 profiler::journal::record_frame_skipped(
2654 window_id,
2655 Instant::now(),
2656 if animation_frame_interval.is_some()
2657 && animation_frame_interval == min_frame_interval
2658 {
2659 profiler::journal::FrameSkipReason::AnimationFrameRateLimit
2660 } else if inactive_without_high_rate_input
2661 && inactive_frame_interval == min_frame_interval
2662 {
2663 profiler::journal::FrameSkipReason::InactiveFrameRateLimit
2664 } else if power_mode == crate::PowerMode::LowPower
2665 && low_power_frame_interval == min_frame_interval
2666 {
2667 profiler::journal::FrameSkipReason::LowPowerFrameRateLimit
2668 } else {
2669 profiler::journal::FrameSkipReason::ThermalFrameRateLimit
2670 },
2671 );
2672 report_frame(handle.window_id(), now, FrameOutcome::Throttled);
2673 return;
2674 }
2675
2676 if !next_frame_callbacks.borrow().is_empty() {
2677 handle
2678 .update(&mut cx, |_, window, cx| {
2679 window.next_frame_wanted.set(false);
2683 for callback in next_frame_callbacks.take() {
2684 callback(window, cx);
2685 }
2686 })
2687 .with_context(|| {
2688 format!(
2689 "running next-frame callbacks for window {:?}",
2690 handle.window_id()
2691 )
2692 })
2693 .log_err();
2694 if window_closed(&cx, handle.window_id()) {
2695 return;
2696 }
2697 }
2698
2699 let should_draw = invalidator.is_dirty() || force_render;
2700 let needs_present = request_frame_options.require_presentation
2701 || needs_present.get()
2702 || scene_animation_interval.get().is_some()
2703 || present_for_high_rate_input;
2704 if should_draw {
2705 measure("frame duration", || {
2706 handle
2707 .update(&mut cx, |_, window, cx| {
2708 #[cfg(feature = "profiler")]
2709 window
2710 .window_profiler
2711 .record_frame_signal(request_frame_options.signal_at);
2712 if force_render {
2713 window.refresh();
2716 }
2717 let arena_clear_needed = window.draw(cx);
2718 window.advance_scene_animations(cx);
2719 window.present();
2720 arena_clear_needed.clear(cx);
2721 })
2722 .with_context(|| {
2723 format!(
2724 "drawing and presenting frame for window {:?}",
2725 handle.window_id()
2726 )
2727 })
2728 .log_err();
2729 })
2730 } else if needs_present {
2731 handle
2732 .update(&mut cx, |_, window, cx| {
2733 window.advance_scene_animations(cx);
2734 window.present();
2735 })
2736 .with_context(|| {
2737 format!("presenting frame for window {:?}", handle.window_id())
2738 })
2739 .log_err();
2740 }
2741 if window_closed(&cx, handle.window_id()) {
2742 return;
2743 }
2744
2745 handle
2746 .update(&mut cx, |_, window, _| {
2747 if window.invalidator.is_dirty()
2748 || window.next_frame_wanted.get()
2749 || window.scene_animation_interval.get().is_some()
2750 {
2751 window.platform_window.schedule_frame();
2752 }
2753 })
2754 .with_context(|| {
2755 format!(
2756 "scheduling follow-up frame for window {:?}",
2757 handle.window_id()
2758 )
2759 })
2760 .log_err();
2761
2762 if invalidator.is_dirty()
2768 || next_frame_wanted.get()
2769 || scene_animation_interval.get().is_some()
2770 {
2771 invalidator.wake_platform();
2772 }
2773 #[cfg(feature = "profiler")]
2774 if !should_draw {
2775 profiler::journal::record_frame_skipped(
2776 window_id,
2777 Instant::now(),
2778 profiler::journal::FrameSkipReason::NoRenderNeeded,
2779 );
2780 }
2781 if should_draw {
2782 report_frame(handle.window_id(), now, FrameOutcome::Drew);
2783 } else if has_next_frame_callbacks || needs_present {
2784 report_frame(handle.window_id(), now, FrameOutcome::NoDraw);
2785 }
2786 }
2787 }));
2788 invalidator.set_platform_waker(platform_window.frame_waker());
2789 platform_window.on_visual_viewport_changed(Box::new({
2790 let mut cx = cx.to_async();
2791 move || {
2792 handle
2793 .update(&mut cx, |_, window, _| window.refresh())
2794 .with_context(|| {
2795 format!(
2796 "handling visual viewport change for window {:?}",
2797 handle.window_id()
2798 )
2799 })
2800 .log_err();
2801 }
2802 }));
2803 platform_window.on_insets_changed(Box::new({
2804 let mut cx = cx.to_async();
2805 move |_| {
2806 handle
2807 .update(&mut cx, |_, window, _| window.refresh())
2808 .with_context(|| {
2809 format!("handling insets change for window {:?}", handle.window_id())
2810 })
2811 .log_err();
2812 }
2813 }));
2814 let bounds_deferred = Rc::new(Cell::new(false));
2816 platform_window.on_resize(Box::new({
2817 let mut cx = cx.to_async();
2818 let deferred = bounds_deferred.clone();
2819 move |_, _| report_bounds_changed(handle, &mut cx, &deferred, "resize")
2820 }));
2821 platform_window.on_moved(Box::new({
2822 let mut cx = cx.to_async();
2823 let deferred = bounds_deferred;
2824 move || report_bounds_changed(handle, &mut cx, &deferred, "move")
2825 }));
2826 platform_window.on_display_changed(Box::new({
2827 let cx = cx.to_async();
2828 move || cx.update(|cx| Window::display_changed(handle, cx))
2829 }));
2830 platform_window.on_appearance_changed(Box::new({
2831 let cx = cx.to_async();
2832 let foreground_executor = cx.foreground_executor().clone();
2833 move || {
2834 let mut cx = cx.clone();
2835 foreground_executor
2838 .spawn(async move {
2839 handle
2840 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
2841 .with_context(|| {
2842 format!(
2843 "handling appearance change for window {:?}",
2844 handle.window_id()
2845 )
2846 })
2847 .log_err();
2848 })
2849 .detach();
2850 }
2851 }));
2852 platform_window.on_button_layout_changed(Box::new({
2853 let mut cx = cx.to_async();
2854 move || {
2855 handle
2856 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
2857 .with_context(|| {
2858 format!(
2859 "handling button layout change for window {:?}",
2860 handle.window_id()
2861 )
2862 })
2863 .log_err();
2864 }
2865 }));
2866 platform_window.on_active_status_change(Box::new({
2867 let mut cx = cx.to_async();
2868 move |active| {
2869 handle
2870 .update(&mut cx, |_, window, cx| {
2871 if window.assume_active {
2875 return;
2876 }
2877 window.active.set(active);
2878 window.modifiers = window.platform_window.modifiers();
2879 window.capslock = window.platform_window.capslock();
2880 window
2881 .activation_observers
2882 .clone()
2883 .retain(|callback| callback(window, cx));
2884
2885 window.bounds_changed(cx);
2886 window.refresh();
2887
2888 SystemWindowTabController::update_last_active(cx, window.handle.id);
2889 })
2890 .with_context(|| {
2891 format!(
2892 "handling active status change for window {:?}",
2893 handle.window_id()
2894 )
2895 })
2896 .log_err();
2897 }
2898 }));
2899 platform_window.on_visibility_change(Box::new({
2900 let mut cx = cx.to_async();
2901 move |_| {
2902 handle
2903 .update(&mut cx, |_, window, cx| {
2904 window.refresh_visibility(cx);
2905 })
2906 .with_context(|| {
2907 format!(
2908 "handling visibility change for window {:?}",
2909 handle.window_id()
2910 )
2911 })
2912 .log_err();
2913 }
2914 }));
2915 platform_window.on_hover_status_change(Box::new({
2916 let mut cx = cx.to_async();
2917 move |active| {
2918 handle
2919 .update(&mut cx, |_, window, cx| {
2920 window.hovered.set(active);
2921 let was_inside = std::mem::replace(&mut window.pointer_inside, active);
2922 window
2923 .vn_effect_pointer
2924 .update(was_inside, active, false, cx);
2925 window.refresh();
2926 })
2927 .with_context(|| {
2928 format!(
2929 "handling hover status change for window {:?}",
2930 handle.window_id()
2931 )
2932 })
2933 .log_err();
2934 }
2935 }));
2936 platform_window.on_input({
2937 let mut cx = cx.to_async();
2938 Box::new(move |event| {
2939 handle
2940 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
2941 .with_context(|| {
2942 format!("dispatching input for window {:?}", handle.window_id())
2943 })
2944 .log_err()
2945 .unwrap_or(DispatchEventResult::default())
2946 })
2947 });
2948 platform_window.on_hit_test_window_control_at({
2949 let mut cx = cx.to_async();
2950 Box::new(move |position| {
2951 handle
2952 .update(&mut cx, |_, window, _cx| {
2953 let position = position.unwrap_or_else(|| window.platform_window.mouse_position());
2958 window.window_control_area_at(position)
2959 })
2960 .with_context(|| {
2961 format!(
2962 "hit-testing window controls for window {:?}",
2963 handle.window_id()
2964 )
2965 })
2966 .log_err()
2967 .unwrap_or(None)
2968 })
2969 });
2970 platform_window.on_move_tab_to_new_window({
2971 let mut cx = cx.to_async();
2972 Box::new(move || {
2973 handle
2974 .update(&mut cx, |_, _window, cx| {
2975 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
2976 })
2977 .with_context(|| {
2978 format!(
2979 "moving tab to new window from window {:?}",
2980 handle.window_id()
2981 )
2982 })
2983 .log_err();
2984 })
2985 });
2986 platform_window.on_merge_all_windows({
2987 let mut cx = cx.to_async();
2988 Box::new(move || {
2989 handle
2990 .update(&mut cx, |_, _window, cx| {
2991 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
2992 })
2993 .with_context(|| {
2994 format!("merging all windows into window {:?}", handle.window_id())
2995 })
2996 .log_err();
2997 })
2998 });
2999 platform_window.on_select_next_tab({
3000 let mut cx = cx.to_async();
3001 Box::new(move || {
3002 handle
3003 .update(&mut cx, |_, _window, cx| {
3004 SystemWindowTabController::select_next_tab(cx, handle.window_id());
3005 })
3006 .with_context(|| {
3007 format!("selecting next tab for window {:?}", handle.window_id())
3008 })
3009 .log_err();
3010 })
3011 });
3012 platform_window.on_select_previous_tab({
3013 let mut cx = cx.to_async();
3014 Box::new(move || {
3015 handle
3016 .update(&mut cx, |_, _window, cx| {
3017 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
3018 })
3019 .with_context(|| {
3020 format!("selecting previous tab for window {:?}", handle.window_id())
3021 })
3022 .log_err();
3023 })
3024 });
3025 platform_window.on_toggle_tab_bar({
3026 let mut cx = cx.to_async();
3027 Box::new(move || {
3028 handle
3029 .update(&mut cx, |_, window, cx| {
3030 let tab_bar_visible = window.platform_window.tab_bar_visible();
3031 SystemWindowTabController::set_visible(cx, tab_bar_visible);
3032 })
3033 .with_context(|| {
3034 format!("toggling tab bar for window {:?}", handle.window_id())
3035 })
3036 .log_err();
3037 })
3038 });
3039
3040 if let Some(app_id) = app_id {
3041 platform_window.set_app_id(&app_id);
3042 }
3043
3044 platform_window.map_window().unwrap();
3045
3046 Ok(Window {
3047 handle,
3048 invalidator,
3049 removed: false,
3050 platform_window,
3051 display_id,
3052 display_observers: SingleSubscriberSet::new(),
3053 is_resizable,
3054 is_minimizable,
3055 last_window_bounds: window_bounds,
3056 sprite_atlas,
3057 text_system,
3058 text_rendering_mode: cx.text_rendering_mode.clone(),
3059 rem_size: px(16.),
3060 rem_size_override_stack: SmallVec::new(),
3061 viewport_size: content_size,
3062 layout_engine: Some(TaffyLayoutEngine::new()),
3063 root: None,
3064 element_id_stack: ElementIdStack::default(),
3065 text_style_stack: Vec::new(),
3066 rendered_entity_stack: Vec::new(),
3067 element_offset_stack: Vec::new(),
3068 content_mask_stack: Vec::new(),
3069 vn_clip_stack: None,
3070 vn_capture_records: FxHashMap::default(),
3071 element_opacity: 1.0,
3072 element_image_tint: Hsla::transparent_black(),
3073 element_image_headroom: 1.0,
3074 element_transform: TransformationMatrix::unit(),
3075 vn_hitbox_tag: 0,
3076 vn_tag_fresh: false,
3077 vn_tag_transform: None,
3078 vn_tag_every_hitbox: false,
3079 vn_pick_every_box: false,
3080 vn_hit_refiner: None,
3081 input_interceptor: None,
3082 vn_key_event_seq: 0,
3083 vn_pointer_lock: None,
3084 vn_raw_mouse_position: None,
3085 vn_mouse_movement: Point::default(),
3086 vn_pen: None,
3087 requested_autoscroll: None,
3088 last_text_input_configuration: None,
3089 focused_text_input: None,
3090 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
3091 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
3092 next_frame_callbacks,
3093 next_frame_wanted,
3094 next_hitbox_id: HitboxId(0),
3095 next_tooltip_id: TooltipId::default(),
3096 tooltip_bounds: None,
3097 dirty_views: FxHashSet::default(),
3098 focus_listeners: SingleSubscriberSet::new(),
3099 focus_lost_listeners: SingleSubscriberSet::new(),
3100 focus_lost_path: SmallVec::new(),
3101 default_prevented: true,
3102 mouse_position,
3103 mouse_hit_test: HitTest::default(),
3104 modifiers,
3105 capslock,
3106 scale_factor,
3107 bounds_observers: SingleSubscriberSet::new(),
3108 appearance,
3109 appearance_observers: SingleSubscriberSet::new(),
3110 button_layout_observers: SingleSubscriberSet::new(),
3111 active,
3112 assume_active: false,
3113 visibility,
3114 visibility_observers: SingleSubscriberSet::new(),
3115 vn_effect_pointer: VnEffectPointer::new(hovered.get()),
3116 vn_effect_element: 0,
3117 vn_effect_phases: FxHashMap::default(),
3118 vn_defer_scope: None,
3119 vn_scopes_painted: FxHashSet::default(),
3120 pointer_inside: hovered.get(),
3121 hovered,
3122 needs_present,
3123 scene_animation_interval,
3124 input_rate_tracker,
3125 #[cfg(feature = "profiler")]
3126 window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
3127 last_input_modality: InputModality::Mouse,
3128 touch_gestures: TouchGestureRecognizer::new(
3129 cx.platform
3130 .gestures()
3131 .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
3132 ),
3133 touch_prediction_enabled: true,
3134 long_press_timer: None,
3135 long_press_capture: None,
3136 refreshing: false,
3137 activation_observers: SingleSubscriberSet::new(),
3138 focus: None,
3139 focus_enabled: true,
3140 focus_generation: 0,
3141 pending_input: None,
3142 pending_modifier: ModifierState::default(),
3143 pending_input_observers: SingleSubscriberSet::new(),
3144 prompt: None,
3145 client_inset: None,
3146 image_cache_stack: Vec::new(),
3147 captured_hitbox: None,
3148 #[cfg(any(feature = "inspector", debug_assertions))]
3149 inspector: None,
3150 #[cfg(feature = "profiler")]
3151 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
3152 a11y: A11y::new(
3153 a11y_active_flag,
3154 accessibility_force_disabled,
3155 initial_window_title,
3156 ),
3157 })
3158 }
3159
3160 pub(crate) fn new_focus_listener(
3161 &self,
3162 value: AnyWindowFocusListener,
3163 ) -> (Subscription, impl FnOnce() + use<>) {
3164 self.focus_listeners.insert_pending(value)
3165 }
3166}
3167
3168#[derive(Clone, Debug, Default, PartialEq, Eq)]
3169#[expect(missing_docs)]
3170pub struct DispatchEventResult {
3171 pub propagate: bool,
3172 pub default_prevented: bool,
3173}
3174
3175#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3185#[repr(C)]
3186pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
3187 pub bounds: Bounds<P>,
3189 pub corner_radii: Corners<P>,
3192 pub corner_shapes: CornerShapes,
3195}
3196
3197impl<P: Clone + Debug + Default + PartialEq> ContentMask<P> {
3198 pub fn rect(bounds: Bounds<P>) -> Self {
3200 ContentMask {
3201 bounds,
3202 corner_radii: Corners::default(),
3203 corner_shapes: CornerShapes::default(),
3204 }
3205 }
3206
3207 pub fn is_rounded(&self) -> bool {
3209 self.corner_radii != Corners::default()
3210 }
3211}
3212
3213impl ContentMask<Pixels> {
3214 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
3216 ContentMask {
3217 bounds: self.bounds.scale(factor),
3218 corner_radii: self.corner_radii.scale(factor),
3219 corner_shapes: self.corner_shapes.scale(factor),
3220 }
3221 }
3222}
3223
3224impl<P> ContentMask<P>
3225where
3226 P: Copy
3227 + Ord
3228 + Debug
3229 + Default
3230 + Add<P, Output = P>
3231 + Sub<P, Output = P>
3232 + Div<f32, Output = P>
3233 + Into<f64>,
3234{
3235 pub fn intersect(&self, other: &Self) -> Self {
3251 let bounds = self.bounds.intersect(&other.bounds);
3252 if !self.is_rounded() && !other.is_rounded() {
3253 return ContentMask::rect(bounds);
3254 }
3255 let at = |mask: &Self, left: bool, top: bool| {
3256 let x = if left { mask.bounds.left() } else { mask.bounds.right() };
3257 let y = if top { mask.bounds.top() } else { mask.bounds.bottom() };
3258 (x, y)
3259 };
3260 let radius = |left: bool, top: bool, mine: (P, u32), theirs: (P, u32)| {
3261 let here = at(&ContentMask::rect(bounds), left, top);
3262 let mine = if at(self, left, top) == here { mine } else { (P::default(), 0) };
3263 let theirs = if at(other, left, top) == here { theirs } else { (P::default(), 0) };
3264 if theirs.0 > mine.0 { theirs } else { mine }
3265 };
3266 let (a, b) = (&self.corner_radii, &other.corner_radii);
3267 let (sa, sb) = (self.corner_shapes.corners(), other.corner_shapes.corners());
3268 let top_left = radius(true, true, (a.top_left, sa.top_left), (b.top_left, sb.top_left));
3269 let top_right = radius(false, true, (a.top_right, sa.top_right), (b.top_right, sb.top_right));
3270 let bottom_right = radius(
3271 false,
3272 false,
3273 (a.bottom_right, sa.bottom_right),
3274 (b.bottom_right, sb.bottom_right),
3275 );
3276 let bottom_left =
3277 radius(true, false, (a.bottom_left, sa.bottom_left), (b.bottom_left, sb.bottom_left));
3278 let corner_radii = Corners {
3279 top_left: top_left.0,
3280 top_right: top_right.0,
3281 bottom_right: bottom_right.0,
3282 bottom_left: bottom_left.0,
3283 }
3284 .clamp_radii_for_quad_size(bounds.size);
3285 ContentMask {
3286 bounds,
3287 corner_radii,
3288 corner_shapes: CornerShapes {
3289 top_left: top_left.1,
3290 top_right: top_right.1,
3291 bottom_right: bottom_right.1,
3292 bottom_left: bottom_left.1,
3293 },
3294 }
3295 }
3296
3297 pub fn contains(&self, point: &Point<P>) -> bool {
3301 if !self.bounds.contains(point) {
3302 return false;
3303 }
3304 if !self.is_rounded() {
3305 return true;
3306 }
3307 if !self.corner_shapes.is_round() {
3308 return crate::corner_shape::shaped_rect_sdf(
3309 *point,
3310 &self.bounds,
3311 &self.corner_radii,
3312 &self.corner_shapes,
3313 ) <= 0.;
3314 }
3315 let b = &self.bounds;
3316 let r = &self.corner_radii;
3317 for (radius, cx, cy, left, top) in [
3318 (r.top_left, b.left() + r.top_left, b.top() + r.top_left, true, true),
3319 (r.top_right, b.right() - r.top_right, b.top() + r.top_right, false, true),
3320 (r.bottom_right, b.right() - r.bottom_right, b.bottom() - r.bottom_right, false, false),
3321 (r.bottom_left, b.left() + r.bottom_left, b.bottom() - r.bottom_left, true, false),
3322 ] {
3323 let in_x = if left { point.x < cx } else { point.x > cx };
3324 let in_y = if top { point.y < cy } else { point.y > cy };
3325 if radius > P::default() && in_x && in_y {
3326 let (dx, dy): (f64, f64) = ((point.x - cx).into(), (point.y - cy).into());
3327 let radius: f64 = radius.into();
3328 return dx * dx + dy * dy <= radius * radius;
3329 }
3330 }
3331 true
3332 }
3333}
3334
3335impl Window {
3336 fn mark_view_dirty(&mut self, view_id: EntityId) {
3337 for view_id in self
3340 .rendered_frame
3341 .dispatch_tree
3342 .view_path_reversed(view_id)
3343 {
3344 if !self.dirty_views.insert(view_id) {
3345 break;
3346 }
3347 }
3348 }
3349
3350 pub(crate) fn refresh_visibility(&mut self, cx: &mut App) {
3351 let visibility = self.platform_window.visibility();
3352 if self.visibility != visibility {
3353 self.visibility = visibility;
3354 #[cfg(feature = "profiler")]
3355 profiler::journal::record_window_visibility(self.handle.window_id(), visibility);
3356 self.visibility_observers
3357 .clone()
3358 .retain(|callback| callback(visibility, self, cx));
3359 }
3360 #[cfg(feature = "profiler")]
3361 if self.invalidator.is_dirty() || self.needs_present.get() {
3362 profiler::journal::record_frame_pending(self.handle.window_id(), Instant::now());
3363 }
3364 }
3365
3366 pub(crate) fn debug_state(&self) -> serde_json::Value {
3371 let platform_window = &self.platform_window;
3372 serde_json::json!({
3373 "id": self.handle.window_id().as_u64(),
3374 "title": platform_window.get_title(),
3375 "bounds": platform_window.bounds(),
3376 "window_bounds": format!("{:?}", platform_window.window_bounds()),
3377 "content_size": platform_window.content_size(),
3378 "viewport_size": self.viewport_size,
3379 "scale_factor": {
3380 "cached": self.scale_factor,
3381 "platform": platform_window.scale_factor(),
3382 },
3383 "display_id": {
3384 "cached": self.display_id.map(u64::from),
3385 "platform": platform_window.display().map(|display| u64::from(display.id())),
3386 },
3387 "active": {
3388 "cached": self.active.get(),
3389 "platform": platform_window.is_active(),
3390 },
3391 "hovered": {
3392 "cached": self.hovered.get(),
3393 "platform": platform_window.is_hovered(),
3394 },
3395 "visibility": {
3396 "cached": format!("{:?}", self.visibility),
3397 "platform": format!("{:?}", platform_window.visibility()),
3398 },
3399 "appearance": {
3400 "cached": format!("{:?}", self.appearance),
3401 "platform": format!("{:?}", platform_window.appearance()),
3402 },
3403 "is_fullscreen": platform_window.is_fullscreen(),
3404 "is_maximized": platform_window.is_maximized(),
3405 "mouse_position": {
3406 "cached": self.mouse_position,
3407 "platform": platform_window.mouse_position(),
3408 },
3409 "modifiers": {
3410 "cached": self.modifiers,
3411 "platform": platform_window.modifiers(),
3412 },
3413 "cursor_style": self.rendered_frame.cursor_style(self),
3414 "frame": {
3415 "dirty": self.invalidator.is_dirty(),
3416 "needs_present": self.needs_present.get(),
3417 "refreshing": self.refreshing,
3418 "next_frame_callbacks": self.next_frame_callbacks.borrow().len(),
3419 },
3420 "gpu": platform_window.gpu_specs(),
3421 "platform": platform_window.debug_state(),
3422 })
3423 }
3424
3425 pub fn visibility(&self) -> WindowVisibility {
3428 self.visibility
3429 }
3430
3431 pub fn is_visible(&self) -> bool {
3437 self.visibility.is_visible()
3438 }
3439
3440 pub fn observe_window_visibility(
3442 &self,
3443 mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
3444 ) -> Subscription {
3445 self.visibility_observers
3446 .insert(Box::new(move |visibility, window, cx| {
3447 callback(visibility, window, cx);
3448 true
3449 }))
3450 }
3451
3452 pub fn observe_window_activation(
3455 &self,
3456 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3457 ) -> Subscription {
3458 self.activation_observers
3459 .insert(Box::new(move |window, cx| {
3460 callback(window, cx);
3461 true
3462 }))
3463 }
3464
3465 pub fn observe_window_appearance(
3467 &self,
3468 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3469 ) -> Subscription {
3470 self.appearance_observers
3471 .insert(Box::new(move |window, cx| {
3472 callback(window, cx);
3473 true
3474 }))
3475 }
3476
3477 pub fn observe_button_layout_changed(
3479 &self,
3480 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3481 ) -> Subscription {
3482 self.button_layout_observers
3483 .insert(Box::new(move |window, cx| {
3484 callback(window, cx);
3485 true
3486 }))
3487 }
3488
3489 pub fn replace_root<E>(
3491 &mut self,
3492 cx: &mut App,
3493 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
3494 ) -> Entity<E>
3495 where
3496 E: 'static + Render,
3497 {
3498 let view = cx.new(|cx| build_view(self, cx));
3499 self.root = Some(view.clone().into());
3500 self.refresh();
3501 view
3502 }
3503
3504 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
3506 where
3507 E: 'static + Render,
3508 {
3509 self.root
3510 .as_ref()
3511 .map(|view| view.clone().downcast::<E>().ok())
3512 }
3513
3514 pub fn window_handle(&self) -> AnyWindowHandle {
3516 self.handle
3517 }
3518
3519 pub fn refresh(&mut self) {
3521 if self.invalidator.not_drawing() {
3522 self.refreshing = true;
3523 self.invalidator.set_dirty(true);
3524 }
3525 }
3526
3527 pub fn remove_window(&mut self) {
3529 self.removed = true;
3530 }
3531
3532 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
3534 self.focus
3535 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
3536 }
3537
3538 pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
3542 let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
3543 ancestors.iter().rev().find_map(|id| {
3544 self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
3545 FocusHandle::for_id(*id, &cx.focus_handles)
3546 })
3547 }
3548
3549 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
3551 if !self.focus_enabled || self.focus == Some(handle.id) {
3552 return;
3553 }
3554
3555 self.focus = Some(handle.id);
3556 self.focus_generation = self.focus_generation.wrapping_add(1);
3557 self.clear_pending_keystrokes(cx);
3558
3559 self.refresh();
3560 }
3561
3562 pub fn blur(&mut self, cx: &mut App) {
3564 self.clear_pending_keystrokes(cx);
3565
3566 if !self.focus_enabled {
3567 return;
3568 }
3569
3570 if self.focus.is_some() {
3571 self.focus_generation = self.focus_generation.wrapping_add(1);
3572 }
3573 self.focus = None;
3574 self.refresh();
3575 }
3576
3577 pub fn disable_focus(&mut self, cx: &mut App) {
3579 self.blur(cx);
3580 self.focus_enabled = false;
3581 }
3582
3583 pub fn focus_next(&mut self, cx: &mut App) {
3585 if !self.focus_enabled {
3586 return;
3587 }
3588
3589 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
3590 self.focus(&handle, cx)
3591 }
3592 }
3593
3594 pub fn focus_prev(&mut self, cx: &mut App) {
3596 if !self.focus_enabled {
3597 return;
3598 }
3599
3600 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
3601 self.focus(&handle, cx)
3602 }
3603 }
3604
3605 pub fn text_system(&self) -> &Rc<WindowTextSystem> {
3607 &self.text_system
3608 }
3609
3610 pub fn text_style(&self) -> TextStyle {
3612 let mut style = TextStyle::default();
3613 for refinement in &self.text_style_stack {
3614 style.refine(refinement);
3615 }
3616 style
3617 }
3618
3619 pub fn is_maximized(&self) -> bool {
3623 self.platform_window.is_maximized()
3624 }
3625
3626 pub fn request_decorations(&self, decorations: WindowDecorations) {
3628 self.platform_window.request_decorations(decorations);
3629 }
3630
3631 pub fn set_exclusive_zone(&self, zone: Pixels) {
3637 self.platform_window.set_exclusive_zone(zone);
3638 }
3639
3640 #[cfg(all(target_os = "linux", feature = "wayland"))]
3645 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
3646 self.platform_window.set_exclusive_edge(edge);
3647 }
3648
3649 pub fn start_window_resize(&self, edge: ResizeEdge) {
3651 if self.is_resizable {
3652 self.platform_window.start_window_resize(edge);
3653 }
3654 }
3655
3656 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
3663 self.platform_window.set_input_region(region);
3664 }
3665
3666 pub fn window_bounds(&self) -> WindowBounds {
3669 self.platform_window.window_bounds()
3670 }
3671
3672 pub(crate) fn last_window_bounds(&self) -> WindowBounds {
3673 self.last_window_bounds
3674 }
3675
3676 pub(crate) fn display_id(&self) -> Option<DisplayId> {
3677 self.display_id
3678 }
3679
3680 pub fn inner_window_bounds(&self) -> WindowBounds {
3682 self.platform_window.inner_window_bounds()
3683 }
3684
3685 pub fn vn_composition_underlay(&self) -> Option<(usize, usize)> {
3689 self.platform_window.vn_composition_underlay()
3690 }
3691
3692 pub fn vn_set_maximized(&self, maximized: bool) {
3694 self.platform_window.vn_set_maximized(maximized)
3695 }
3696
3697 pub fn vn_is_zoomed(&self) -> bool {
3699 self.platform_window.vn_is_zoomed()
3700 }
3701
3702 pub fn vn_is_minimized(&self) -> bool {
3704 self.platform_window.vn_is_minimized()
3705 }
3706
3707 pub fn vn_unminimize(&self) {
3709 self.platform_window.vn_unminimize()
3710 }
3711
3712 pub fn vn_hide(&self) -> bool {
3714 self.platform_window.vn_hide()
3715 }
3716
3717 pub fn vn_is_shown(&self) -> bool {
3719 self.platform_window.vn_is_shown()
3720 }
3721
3722 pub fn vn_set_frame(&self, origin: Option<Point<Pixels>>, size: Option<Size<Pixels>>) -> bool {
3725 self.platform_window.vn_set_frame(origin, size)
3726 }
3727
3728 pub fn vn_set_always_on_top(&self, on: bool) -> bool {
3730 self.platform_window.vn_set_always_on_top(on)
3731 }
3732
3733 pub fn vn_set_maximizable(&self, maximizable: bool) {
3735 self.platform_window.vn_set_maximizable(maximizable)
3736 }
3737
3738 pub fn vn_set_ignore_mouse(&self, ignore: bool) -> bool {
3740 self.platform_window.vn_set_ignore_mouse(ignore)
3741 }
3742
3743 pub fn vn_set_content_protection(&self, on: bool) -> bool {
3745 self.platform_window.vn_set_content_protection(on)
3746 }
3747
3748 pub fn vn_request_close(&self) {
3750 self.platform_window.vn_request_close()
3751 }
3752
3753 pub fn native_window_state(&self) -> Option<Vec<u8>> {
3756 self.platform_window.native_window_state()
3757 }
3758
3759 pub fn restore_native_window_state(&self, state: &[u8]) {
3762 self.platform_window.restore_native_window_state(state);
3763 }
3764
3765 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
3767 let focus_id = self.focused(cx).map(|handle| handle.id);
3768
3769 let window = self.handle;
3770 cx.defer(move |cx| {
3771 window
3772 .update(cx, |_, window, cx| {
3773 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
3774 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
3775 })
3776 .with_context(|| format!("dispatching action for window {:?}", window.window_id()))
3777 .log_err();
3778 })
3779 }
3780
3781 pub(crate) fn dispatch_keystroke_observers(
3782 &mut self,
3783 keystroke: &Keystroke,
3784 input_preference: InputPreference,
3785 action: Option<&dyn Action>,
3786 context_stack: Vec<KeyContext>,
3787 cx: &mut App,
3788 ) {
3789 cx.keystroke_observers.clone().retain(move |callback| {
3790 (callback)(
3791 &KeystrokeEvent {
3792 keystroke: keystroke.clone(),
3793 input_preference,
3794 action: action.map(|action| action.boxed_clone()),
3795 context_stack: context_stack.clone(),
3796 },
3797 self,
3798 cx,
3799 )
3800 });
3801 }
3802
3803 pub(crate) fn dispatch_keystroke_interceptors(
3804 &mut self,
3805 keystroke: &Keystroke,
3806 input_preference: InputPreference,
3807 context_stack: Vec<KeyContext>,
3808 cx: &mut App,
3809 ) {
3810 cx.keystroke_interceptors.clone().retain(move |callback| {
3811 (callback)(
3812 &KeystrokeEvent {
3813 keystroke: keystroke.clone(),
3814 input_preference,
3815 action: None,
3816 context_stack: context_stack.clone(),
3817 },
3818 self,
3819 cx,
3820 )
3821 });
3822 }
3823
3824 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
3827 let handle = self.handle;
3828 cx.defer(move |cx| {
3829 handle.update(cx, |_, window, cx| f(window, cx)).ok();
3830 });
3831 }
3832
3833 pub fn observe<T: 'static>(
3837 &mut self,
3838 observed: &Entity<T>,
3839 cx: &mut App,
3840 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
3841 ) -> Subscription {
3842 let entity_id = observed.entity_id();
3843 let observed = observed.downgrade();
3844 let window_handle = self.handle;
3845 cx.new_observer(
3846 entity_id,
3847 Box::new(move |cx| {
3848 window_handle
3849 .update(cx, |_, window, cx| {
3850 if let Some(handle) = observed.upgrade() {
3851 on_notify(handle, window, cx);
3852 true
3853 } else {
3854 false
3855 }
3856 })
3857 .unwrap_or(false)
3858 }),
3859 )
3860 }
3861
3862 pub fn subscribe<Emitter, Evt>(
3866 &mut self,
3867 entity: &Entity<Emitter>,
3868 cx: &mut App,
3869 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
3870 ) -> Subscription
3871 where
3872 Emitter: EventEmitter<Evt>,
3873 Evt: 'static,
3874 {
3875 let entity_id = entity.entity_id();
3876 let handle = entity.downgrade();
3877 let window_handle = self.handle;
3878 cx.new_subscription(
3879 entity_id,
3880 (
3881 TypeId::of::<Evt>(),
3882 Box::new(move |event, cx| {
3883 window_handle
3884 .update(cx, |_, window, cx| {
3885 if let Some(entity) = handle.upgrade() {
3886 let event = event.downcast_ref().expect("invalid event type");
3887 on_event(entity, event, window, cx);
3888 true
3889 } else {
3890 false
3891 }
3892 })
3893 .unwrap_or(false)
3894 }),
3895 ),
3896 )
3897 }
3898
3899 pub fn observe_release<T>(
3901 &self,
3902 entity: &Entity<T>,
3903 cx: &mut App,
3904 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
3905 ) -> Subscription
3906 where
3907 T: 'static,
3908 {
3909 let entity_id = entity.entity_id();
3910 let window_handle = self.handle;
3911 cx.release_listeners.insert(
3912 entity_id,
3913 Box::new(move |entity, cx| {
3914 let entity = entity.downcast_mut().expect("invalid entity type");
3915 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
3916 }),
3917 )
3918 }
3919
3920 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
3923 AsyncWindowContext::new_context(cx.to_async(), self.handle)
3924 }
3925
3926 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
3928 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
3929 self.next_frame_wanted.set(true);
3930 self.platform_window.schedule_frame();
3931 self.invalidator.wake_platform();
3934 }
3935
3936 pub fn on_next_frame_passive(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
3942 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
3943 }
3944
3945 pub fn request_animation_frame(&self) {
3958 let entity = self.current_view();
3959 self.on_next_frame(move |_, cx| cx.notify(entity));
3960 }
3961
3962 pub(crate) fn advance_scene_animations(&mut self, cx: &App) {
3963 let elapsed = cx.background_executor().now() - cx.synced_animation_epoch;
3964 self.rendered_frame.scene.advance_animations(elapsed);
3965 }
3966
3967 #[cfg(any(test, feature = "test-support"))]
3972 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
3973 let callbacks = self.next_frame_callbacks.take();
3974 self.next_frame_wanted.set(false);
3975 let count = callbacks.len();
3976 for callback in callbacks {
3977 callback(self, cx);
3978 }
3979 count
3980 }
3981
3982 #[track_caller]
3986 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
3987 where
3988 R: 'static,
3989 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3990 {
3991 let handle = self.handle;
3992 cx.spawn(async move |app| {
3993 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3994 f(&mut async_window_cx).await
3995 })
3996 }
3997
3998 #[track_caller]
4002 pub fn spawn_with_priority<AsyncFn, R>(
4003 &self,
4004 priority: Priority,
4005 cx: &App,
4006 f: AsyncFn,
4007 ) -> Task<R>
4008 where
4009 R: 'static,
4010 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
4011 {
4012 let handle = self.handle;
4013 cx.spawn_with_priority(priority, async move |app| {
4014 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
4015 f(&mut async_window_cx).await
4016 })
4017 }
4018
4019 pub fn bounds_changed(&mut self, cx: &mut App) {
4025 self.scale_factor = self.platform_window.scale_factor();
4026 self.viewport_size = self.platform_window.content_size();
4027 self.last_window_bounds = self.platform_window.window_bounds();
4028 cx.sync_window_update_entry(self);
4029 self.mouse_position = self.platform_window.mouse_position();
4030
4031 self.refresh();
4032
4033 self.bounds_observers
4034 .clone()
4035 .retain(|callback| callback(self, cx));
4036 }
4037
4038 fn display_changed(handle: AnyWindowHandle, cx: &mut App) {
4039 let moved_to = handle
4040 .update(cx, |_, window, _| {
4041 let display_id = window.platform_window.display().map(|display| display.id());
4042 let moved = display_id != window.display_id;
4043 window.display_id = display_id;
4044 moved.then_some(display_id)
4045 })
4046 .with_context(|| {
4047 format!(
4048 "handling display change for window {:?}",
4049 handle.window_id()
4050 )
4051 })
4052 .log_err()
4053 .flatten();
4054 let Some(display_id) = moved_to else {
4055 return;
4056 };
4057 if let Some(display_id) = display_id
4061 && !cx.knows_display(display_id)
4062 {
4063 cx.displays_changed();
4064 }
4065 handle
4066 .update(cx, |_, window, cx| window.notify_display_observers(cx))
4067 .with_context(|| {
4068 format!(
4069 "notifying display observers for window {:?}",
4070 handle.window_id()
4071 )
4072 })
4073 .log_err();
4074 }
4075
4076 pub(crate) fn notify_display_observers(&mut self, cx: &mut App) {
4077 self.display_observers
4078 .clone()
4079 .retain(|callback| callback(self, cx));
4080 }
4081
4082 pub fn refresh_interval(&self, cx: &App) -> Option<Duration> {
4087 cx.display_refresh_interval(self.display_id?)
4088 }
4089
4090 pub fn observe_window_display(
4095 &self,
4096 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
4097 ) -> Subscription {
4098 self.display_observers.insert(Box::new(move |window, cx| {
4099 callback(window, cx);
4100 true
4101 }))
4102 }
4103
4104 pub fn bounds(&self) -> Bounds<Pixels> {
4106 self.platform_window.bounds()
4107 }
4108
4109 pub fn insets(&self) -> WindowInsets {
4111 self.platform_window.insets()
4112 }
4113
4114 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
4128 self.platform_window
4129 .render_to_image(&self.rendered_frame.scene)
4130 }
4131
4132 #[cfg(feature = "bench-support")]
4135 pub fn rendered_scene(&self) -> &Scene {
4136 &self.rendered_frame.scene
4137 }
4138
4139 #[cfg(any(test, feature = "test-support"))]
4144 pub fn painted_quads(&self) -> Vec<Quad> {
4145 self.rendered_frame.scene.quads.clone()
4146 }
4147
4148 #[cfg(any(test, feature = "test-support"))]
4150 pub fn painted_underlines(&self) -> Vec<Underline> {
4151 self.rendered_frame.scene.underlines.clone()
4152 }
4153
4154 pub fn resize(&mut self, size: Size<Pixels>) {
4156 self.platform_window.resize(size);
4157 }
4158
4159 pub fn is_fullscreen(&self) -> bool {
4161 self.platform_window.is_fullscreen()
4162 }
4163
4164 pub fn is_simple_fullscreen(&self) -> bool {
4168 self.platform_window.is_simple_fullscreen()
4169 }
4170
4171 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
4172 self.appearance = self.platform_window.appearance();
4173
4174 self.appearance_observers
4175 .clone()
4176 .retain(|callback| callback(self, cx));
4177 }
4178
4179 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
4180 self.button_layout_observers
4181 .clone()
4182 .retain(|callback| callback(self, cx));
4183 }
4184
4185 pub fn appearance(&self) -> WindowAppearance {
4187 self.appearance
4188 }
4189
4190 pub fn viewport_size(&self) -> Size<Pixels> {
4192 self.viewport_size
4193 }
4194
4195 pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
4201 self.platform_window.visual_viewport_bounds()
4202 }
4203
4204 pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
4209 let insets = self.platform_window.insets().effective();
4210 let viewport = self.viewport_size();
4211 let left = insets.left.max(Pixels::ZERO).min(viewport.width);
4212 let top = insets.top.max(Pixels::ZERO).min(viewport.height);
4213 let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
4214 let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
4215 let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
4216 let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
4217 visible.size.width = visible.size.width.max(Pixels::ZERO);
4218 visible.size.height = visible.size.height.max(Pixels::ZERO);
4219 visible
4220 }
4221
4222 pub fn request_virtual_keyboard(&self) {
4227 self.platform_window.show_soft_keyboard();
4228 }
4229
4230 pub fn dismiss_virtual_keyboard(&self) {
4232 self.platform_window.hide_soft_keyboard();
4233 }
4234
4235 pub fn is_window_active(&self) -> bool {
4237 self.active.get()
4238 }
4239
4240 pub fn set_assume_active(&mut self, on: bool) {
4253 self.assume_active = on;
4254 let active = on || self.platform_window.is_active();
4255 if self.active.replace(active) != active {
4256 self.refresh();
4257 }
4258 }
4259
4260 pub fn set_draws_while_occluded(&self, on: bool) {
4263 self.platform_window.set_draws_while_occluded(on);
4264 }
4265
4266 pub fn set_hdr_output(&self, output: Option<HdrOutput>) -> bool {
4269 self.platform_window.set_hdr_output(output)
4270 }
4271
4272 pub fn is_window_hovered(&self) -> bool {
4276 if cfg!(any(
4277 target_os = "windows",
4278 target_os = "linux",
4279 target_os = "freebsd"
4280 )) {
4281 self.hovered.get()
4282 } else {
4283 self.is_window_active()
4284 }
4285 }
4286
4287 pub fn zoom_window(&self) {
4289 self.platform_window.zoom();
4290 }
4291
4292 pub fn show_window_menu(&self, position: Point<Pixels>) {
4294 self.platform_window.show_window_menu(position)
4295 }
4296
4297 pub fn start_window_move(&self) {
4302 self.platform_window.start_window_move()
4303 }
4304
4305 pub fn set_client_inset(&mut self, inset: Pixels) {
4307 self.client_inset = Some(inset);
4308 self.platform_window.set_client_inset(inset);
4309 }
4310
4311 pub fn set_client_corner_radii(&mut self, radii: Corners<Pixels>) {
4313 self.platform_window.set_client_corner_radii(radii);
4314 }
4315
4316 pub fn client_inset(&self) -> Option<Pixels> {
4318 self.client_inset
4319 }
4320
4321 pub fn window_decorations(&self) -> Decorations {
4323 self.platform_window.window_decorations()
4324 }
4325
4326 pub fn is_resizable(&self) -> bool {
4328 self.is_resizable
4329 }
4330
4331 pub fn is_minimizable(&self) -> bool {
4333 self.is_minimizable
4334 }
4335
4336 pub fn window_controls(&self) -> WindowControls {
4338 self.platform_window.window_controls()
4339 }
4340
4341 pub fn set_window_title(&mut self, title: &str) {
4343 self.platform_window.set_title(title);
4344 self.a11y.set_window_title(title.to_string());
4345 }
4346
4347 #[cfg(target_os = "macos")]
4349 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
4350 self.platform_window.set_traffic_light_position(position);
4351 }
4352
4353 #[cfg(target_os = "macos")]
4355 pub fn set_native_titlebar_visibility(&self, visible: bool) {
4356 self.platform_window.set_native_titlebar_visibility(visible);
4357 }
4358
4359 pub fn set_app_id(&mut self, app_id: &str) {
4361 self.platform_window.set_app_id(app_id);
4362 }
4363
4364 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
4366 self.platform_window
4367 .set_background_appearance(background_appearance);
4368 }
4369
4370 pub fn is_background_appearance_drawn(&self) -> bool {
4376 self.platform_window.is_background_appearance_drawn()
4377 }
4378
4379 pub fn set_window_edited(&mut self, edited: bool) {
4381 self.platform_window.set_edited(edited);
4382 }
4383
4384 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
4387 self.platform_window.set_document_path(path);
4388 }
4389
4390 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
4392 cx.platform
4393 .displays()
4394 .into_iter()
4395 .find(|display| Some(display.id()) == self.display_id)
4396 }
4397
4398 pub fn show_character_palette(&self) {
4400 self.platform_window.show_character_palette();
4401 }
4402
4403 pub fn scale_factor(&self) -> f32 {
4407 self.scale_factor
4408 }
4409
4410 #[cfg(any(test, feature = "test-support"))]
4412 pub fn set_scale_factor(&mut self, scale_factor: f32) {
4413 self.scale_factor = scale_factor;
4414 self.refresh();
4415 }
4416
4417 pub fn rem_size(&self) -> Pixels {
4420 self.rem_size_override_stack
4421 .last()
4422 .copied()
4423 .unwrap_or(self.rem_size)
4424 }
4425
4426 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
4429 self.rem_size = rem_size.into();
4430 }
4431
4432 pub fn with_global_id<R>(
4435 &mut self,
4436 element_id: ElementId,
4437 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
4438 ) -> R {
4439 self.with_id(element_id, |this| {
4440 let global_id = this.element_id_stack.global_id();
4441
4442 f(&global_id, this)
4443 })
4444 }
4445
4446 #[inline]
4448 pub fn with_id<R>(
4449 &mut self,
4450 element_id: impl Into<ElementId>,
4451 f: impl FnOnce(&mut Self) -> R,
4452 ) -> R {
4453 self.element_id_stack.push(element_id.into());
4454 let result = f(self);
4455 self.element_id_stack.pop();
4456 result
4457 }
4458
4459 #[inline]
4465 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
4466 where
4467 F: FnOnce(&mut Self) -> R,
4468 {
4469 self.invalidator.debug_assert_paint_or_prepaint();
4470
4471 if let Some(rem_size) = rem_size {
4472 self.rem_size_override_stack.push(rem_size.into());
4473 let result = f(self);
4474 self.rem_size_override_stack.pop();
4475 result
4476 } else {
4477 f(self)
4478 }
4479 }
4480
4481 pub fn line_height(&self) -> Pixels {
4483 self.text_style().line_height_in_pixels(self.rem_size())
4484 }
4485
4486 #[inline]
4488 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
4489 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
4490 }
4491
4492 #[inline]
4494 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
4495 let scale_factor = f64::from(self.scale_factor());
4496 round_half_toward_zero_f64(value * scale_factor) / scale_factor
4497 }
4498
4499 #[inline]
4501 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
4502 bounds.map(|c| self.pixel_snap(c))
4503 }
4504
4505 #[inline]
4507 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
4508 position.map(|c| self.pixel_snap(c))
4509 }
4510
4511 pub fn underline_bounds(
4513 &self,
4514 origin: Point<Pixels>,
4515 width: Pixels,
4516 style: &UnderlineStyle,
4517 ) -> Bounds<ScaledPixels> {
4518 let scale_factor = self.scale_factor();
4519 let thickness = self.snap_stroke(style.thickness);
4520 let height = if style.wavy {
4521 ScaledPixels(thickness.0 * 3.)
4522 } else {
4523 thickness
4524 };
4525 Bounds {
4526 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4527 size: size(self.snap_stroke(width), height),
4528 }
4529 }
4530
4531 pub fn paint_underline_with_exclusions(
4533 &mut self,
4534 origin: Point<Pixels>,
4535 width: Pixels,
4536 style: &UnderlineStyle,
4537 exclusions: &[Range<ScaledPixels>],
4538 ) {
4539 self.invalidator.debug_assert_paint();
4540 let underline = self.underline(origin, width, style);
4541 if exclusions.is_empty() {
4542 self.next_frame.scene.insert_primitive(underline);
4543 return;
4544 }
4545
4546 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
4547 if bounds.is_empty() {
4548 return;
4549 }
4550
4551 let mut exclusions = exclusions
4552 .iter()
4553 .filter_map(|span| {
4554 let start = span.start.max(bounds.left());
4555 let end = span.end.min(bounds.right());
4556 (start < end).then_some(start..end)
4557 })
4558 .collect::<SmallVec<[_; 4]>>();
4559 if exclusions.is_empty() {
4560 self.next_frame.scene.insert_primitive(underline);
4561 return;
4562 }
4563 exclusions.sort_unstable_by_key(|span| span.start);
4564
4565 let mut paint_span = |start, end| {
4566 let span = ContentMask::rect(Bounds::from_corners(
4569 point(start, bounds.top()),
4570 point(end, bounds.bottom()),
4571 ));
4572 self.next_frame.scene.insert_primitive(Underline {
4573 content_mask: underline.content_mask.intersect(&span),
4574 ..underline
4575 });
4576 };
4577 let mut start = bounds.left();
4578 for exclusion in exclusions {
4579 if start < exclusion.start {
4580 paint_span(start, exclusion.start);
4581 }
4582 start = start.max(exclusion.end);
4583 }
4584 if start < bounds.right() {
4585 paint_span(start, bounds.right());
4586 }
4587 }
4588
4589 fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline {
4590 Underline {
4591 order: 0,
4592 pad: 0,
4593 bounds: self.underline_bounds(origin, width, style),
4594 content_mask: self.snapped_content_mask(),
4595 color: style
4596 .color
4597 .unwrap_or_default()
4598 .opacity(self.element_opacity()),
4599 thickness: self.snap_stroke(style.thickness),
4600 wavy: style.wavy.into(),
4601 transformation: self.element_transform,
4604 }
4605 }
4606
4607 #[inline]
4608 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
4609 let scale_factor = self.scale_factor();
4610 let left = round_to_device_pixel(bounds.left().0, scale_factor);
4611 let top = round_to_device_pixel(bounds.top().0, scale_factor);
4612 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
4613 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
4614 Bounds::from_corners(
4615 point(ScaledPixels(left), ScaledPixels(top)),
4616 point(ScaledPixels(right), ScaledPixels(bottom)),
4617 )
4618 }
4619
4620 #[inline]
4622 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
4623 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
4624 }
4625
4626 #[inline]
4627 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
4628 edges.map(|e| self.snap_stroke(*e))
4629 }
4630
4631 #[inline]
4633 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
4634 let scale_factor = self.scale_factor();
4635 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
4636 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
4637 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
4638 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
4639 Bounds::from_corners(
4640 point(ScaledPixels(left), ScaledPixels(top)),
4641 point(ScaledPixels(right), ScaledPixels(bottom)),
4642 )
4643 }
4644
4645 #[inline]
4646 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
4647 let mask = self.content_mask();
4648 ContentMask {
4649 bounds: self.cover_bounds(mask.bounds),
4650 corner_radii: mask.corner_radii.scale(self.scale_factor()),
4654 corner_shapes: mask.corner_shapes.scale(self.scale_factor()),
4655 }
4656 }
4657
4658 pub fn prevent_default(&mut self) {
4661 self.default_prevented = true;
4662 }
4663
4664 pub fn default_prevented(&self) -> bool {
4666 self.default_prevented
4667 }
4668
4669 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
4671 let node_id =
4672 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
4673 self.rendered_frame
4674 .dispatch_tree
4675 .is_action_available(action, node_id)
4676 }
4677
4678 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
4680 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
4681 self.rendered_frame
4682 .dispatch_tree
4683 .is_action_available(action, node_id)
4684 }
4685
4686 pub fn mouse_position(&self) -> Point<Pixels> {
4688 self.mouse_position
4689 }
4690
4691 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
4698 self.captured_hitbox = Some(hitbox_id);
4699 }
4700
4701 pub fn release_pointer(&mut self) {
4703 self.captured_hitbox = None;
4704 }
4705
4706 pub fn captured_hitbox(&self) -> Option<HitboxId> {
4708 self.captured_hitbox
4709 }
4710
4711 pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
4717 self.long_press_capture = Some(entity.entity_id());
4718 }
4719
4720 pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
4722 self.long_press_capture == Some(entity.entity_id())
4723 }
4724
4725 pub fn modifiers(&self) -> Modifiers {
4727 self.modifiers
4728 }
4729
4730 pub fn last_input_was_keyboard(&self) -> bool {
4733 self.last_input_modality == InputModality::Keyboard
4734 }
4735
4736 pub fn last_input_was_touch(&self) -> bool {
4738 self.last_input_modality == InputModality::Touch
4739 }
4740
4741 pub fn capslock(&self) -> Capslock {
4743 self.capslock
4744 }
4745
4746 #[profiling::function]
4749 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
4750 let _profile_window = crate::native_profiling::window_scope(self.platform_window.as_ref());
4751 let _profile = crate::native_profiling::current_span("native", "GPUI draw");
4752 #[cfg(feature = "profiler")]
4755 let frame_dirty = self.invalidator.take_frame_dirty();
4756 #[cfg(feature = "profiler")]
4757 self.window_profiler.begin_draw();
4758
4759 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
4762
4763 if self.platform_window.prepare_frame() {
4764 self.refresh();
4765 }
4766 self.invalidate_entities();
4767 cx.entities.clear_accessed();
4768 debug_assert!(self.rendered_entity_stack.is_empty());
4769 self.invalidator.set_dirty(false);
4770 self.requested_autoscroll = None;
4771
4772 if let Some(input_handler) = self.platform_window.take_input_handler() {
4777 if let Some(slot) = self
4778 .rendered_frame
4779 .input_handlers
4780 .iter_mut()
4781 .rev()
4782 .find(|h| h.is_none())
4783 {
4784 *slot = Some(input_handler);
4785 } else {
4786 self.rendered_frame.input_handlers.push(Some(input_handler));
4787 }
4788 }
4789 if !cx.mode.skip_drawing() {
4790 self.vn_scopes_painted.clear();
4791 self.draw_roots(cx);
4792 let now = crate::effect_clock_seconds();
4793 self.vn_effect_phases
4794 .retain(|_, phase| now - phase.at < VnEffectPhase::KEEP);
4795 #[cfg(feature = "profiler")]
4796 {
4797 let viewport_size = self.viewport_size;
4798 let scale_factor = self.scale_factor();
4799 self.debug_frame_overlay.paint(
4800 &mut self.next_frame.scene,
4801 viewport_size,
4802 scale_factor,
4803 );
4804 }
4805 }
4806 let _finalize = crate::native_profiling::current_span("native", "GPUI finalize frame");
4807 self.dirty_views.clear();
4808 self.next_frame.window_active = self.active.get();
4809
4810 let focused_text_input = if let Some(mut input_handler) = self
4816 .next_frame
4817 .input_handlers
4818 .iter_mut()
4819 .rev()
4820 .find_map(|h| h.take())
4821 {
4822 let accepts_text_input = input_handler.accepts_text_input(self, cx);
4823 self.platform_window.set_input_handler(input_handler);
4824 self.focus.filter(|_| accepts_text_input)
4825 } else {
4826 None
4827 };
4828 self.apply_text_input_configuration(cx);
4829 let previous = mem::replace(&mut self.focused_text_input, focused_text_input);
4830 if previous.is_some() != focused_text_input.is_some() {
4831 self.platform_window
4832 .text_input_state_changed(if focused_text_input.is_some() {
4833 TextInputStateChange::FocusGained
4834 } else {
4835 TextInputStateChange::FocusLost
4836 });
4837 }
4838
4839 {
4840 let _profile = crate::native_profiling::current_span("native", "GPUI finish layout and text");
4841 self.layout_engine.as_mut().unwrap().clear();
4842 self.text_system().finish_frame();
4843 }
4844 {
4845 let _profile = crate::native_profiling::current_span("native", "GPUI finish scene");
4846 self.next_frame.finish(&mut self.rendered_frame);
4847 self.vn_settle_captures();
4848 }
4849
4850 self.invalidator.set_phase(DrawPhase::Focus);
4851 let previous_focus_path = self.rendered_frame.focus_path();
4852 let previous_window_active = self.rendered_frame.window_active;
4853 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
4854 self.scene_animation_interval
4855 .set(self.rendered_frame.scene.animation_frame_interval());
4856 {
4857 let _profile = crate::native_profiling::current_span("native", "GPUI clear previous frame");
4858 self.next_frame.clear();
4859 }
4860 let current_focus_path = self.rendered_frame.focus_path();
4861 let current_window_active = self.rendered_frame.window_active;
4862 let mut focus_before_listeners = self.focus;
4863
4864 if previous_focus_path != current_focus_path
4865 || previous_window_active != current_window_active
4866 {
4867 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
4868 self.focus_lost_path = previous_focus_path.clone();
4869 self.focus_lost_listeners
4870 .clone()
4871 .retain(|listener| listener(self, cx));
4872 self.focus_lost_path = SmallVec::new();
4873 focus_before_listeners = self.focus;
4878 }
4879
4880 let event = WindowFocusEvent {
4881 previous_focus_path: if previous_window_active {
4882 previous_focus_path
4883 } else {
4884 Default::default()
4885 },
4886 current_focus_path: if current_window_active {
4887 current_focus_path
4888 } else {
4889 Default::default()
4890 },
4891 };
4892 self.focus_listeners
4893 .clone()
4894 .retain(|listener| listener(&event, self, cx));
4895 }
4896
4897 debug_assert!(self.rendered_entity_stack.is_empty());
4898 self.record_entities_accessed(cx);
4899 self.reset_cursor_style(cx);
4900 self.refreshing = false;
4901 self.invalidator.set_phase(DrawPhase::None);
4902 if self.focus != focus_before_listeners {
4907 self.refresh();
4908 }
4909 self.needs_present.set(true);
4910
4911 #[cfg(feature = "profiler")]
4912 {
4913 self.window_profiler
4914 .set_refresh_interval(self.refresh_interval(cx));
4915 let draw_duration = self
4916 .window_profiler
4917 .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
4918 self.debug_frame_overlay.record_frame(draw_duration);
4919 }
4920
4921 arena_scope.exit(&cx.element_arena)
4924 }
4925
4926 fn record_entities_accessed(&mut self, cx: &mut App) {
4927 let entities = cx.entities.take_accessed();
4928 let handle = self.handle;
4929 cx.record_entities_accessed(
4930 handle,
4931 self.invalidator.clone(),
4933 &entities,
4934 );
4935 cx.entities.restore_accessed(entities);
4936 }
4937
4938 fn invalidate_entities(&mut self) {
4939 let mut views = self.invalidator.take_views();
4940 for entity in views.drain() {
4941 self.mark_view_dirty(entity);
4942 }
4943 self.invalidator.replace_views(views);
4944 }
4945
4946 #[profiling::function]
4947 fn present(&mut self) {
4948 #[cfg(feature = "profiler")]
4949 let _foreground_turn = profiler::journal::foreground_turn();
4950 #[cfg(feature = "profiler")]
4951 let present_start = Instant::now();
4952 self.platform_window.draw(&self.rendered_frame.scene);
4953 #[cfg(feature = "profiler")]
4954 self.window_profiler.record_present(
4955 present_start,
4956 Instant::now(),
4957 self.active.get(),
4958 !self.next_frame_callbacks.borrow().is_empty(),
4959 );
4960 self.needs_present.set(false);
4961 profiling::finish_frame!();
4962 }
4963
4964 #[cfg(all(test, feature = "profiler"))]
4966 pub fn present_if_needed(&mut self) {
4967 if self.needs_present.get() {
4968 self.present();
4969 }
4970 }
4971
4972 #[cfg(feature = "profiler")]
4974 pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
4975 self.window_profiler.input_latency_snapshot()
4976 }
4977
4978 #[cfg(feature = "profiler")]
4980 pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
4981 self.window_profiler.frame_duration_snapshot()
4982 }
4983
4984 #[cfg(feature = "profiler")]
4986 pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
4987 self.debug_frame_overlay.mode()
4988 }
4989
4990 #[cfg(feature = "profiler")]
4992 pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
4993 self.debug_frame_overlay.set_mode(mode);
4994 self.refresh();
4995 }
4996
4997 #[cfg(feature = "profiler")]
5000 pub fn cycle_debug_frame_overlay_mode(&mut self) {
5001 self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
5002 }
5003
5004 #[cfg(feature = "profiler")]
5007 pub fn reset_debug_frame_overlay_stats(&mut self) {
5008 self.debug_frame_overlay.reset_stats();
5009 self.refresh();
5010 }
5011
5012 fn draw_roots(&mut self, cx: &mut App) {
5013 self.invalidator.set_phase(DrawPhase::Prepaint);
5014 self.tooltip_bounds.take();
5015
5016 self.a11y.sync_active_flag();
5017 if self.a11y.is_active() {
5018 self.a11y.begin_frame();
5019 }
5020
5021 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
5022 let root_size = {
5023 #[cfg(any(feature = "inspector", debug_assertions))]
5024 {
5025 if self.inspector.is_some() {
5026 let mut size = self.viewport_size;
5027 size.width = (size.width - _inspector_width).max(px(0.0));
5028 size
5029 } else {
5030 self.viewport_size
5031 }
5032 }
5033 #[cfg(not(any(feature = "inspector", debug_assertions)))]
5034 {
5035 self.viewport_size
5036 }
5037 };
5038
5039 let scale_factor = self.scale_factor();
5043 #[cfg(feature = "profiler")]
5044 let request_layout_start = Instant::now();
5045 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
5046 let root_layout_id = root_element.request_layout(self, cx);
5047 #[cfg(feature = "profiler")]
5048 let prepaint_start = Instant::now();
5049 self.layout_engine
5050 .as_mut()
5051 .unwrap()
5052 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
5053 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
5054
5055 #[cfg(any(feature = "inspector", debug_assertions))]
5056 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
5057
5058 let deferred_hitboxes_start = self.next_frame.hitboxes.len();
5059 let deferred_tagged_start = self.next_frame.vn_tagged_hitboxes.len();
5060 self.prepaint_deferred_draws(cx);
5061 let deferred_hitboxes = deferred_hitboxes_start..self.next_frame.hitboxes.len();
5062 self.next_frame.vn_deferred_tagged =
5063 deferred_tagged_start..self.next_frame.vn_tagged_hitboxes.len();
5064
5065 let mut prompt_element = None;
5066 let mut active_drag_element = None;
5067 let mut tooltip_element = None;
5068 if let Some(prompt) = self.prompt.take() {
5069 let mut element = prompt.view.any_view().into_any_element();
5070 let prompt_layout_id = element.request_layout(self, cx);
5071 self.layout_engine
5072 .as_mut()
5073 .unwrap()
5074 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
5075 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
5076 prompt_element = Some(element);
5077 self.prompt = Some(prompt);
5078 } else if let Some(active_drag) = cx.active_drag.take() {
5079 let mut element = active_drag.view.clone().into_any_element();
5080 let offset = self.mouse_position() - active_drag.cursor_offset;
5081 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
5082 active_drag_element = Some(element);
5083 cx.active_drag = Some(active_drag);
5084 } else {
5085 tooltip_element = self.prepaint_tooltip(cx);
5086 }
5087
5088 self.compute_hit_order(deferred_hitboxes);
5089 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position, self.scale_factor);
5090
5091 #[cfg(feature = "profiler")]
5093 let paint_start = Instant::now();
5094 self.invalidator.set_phase(DrawPhase::Paint);
5095 root_element.paint(self, cx);
5096
5097 #[cfg(any(feature = "inspector", debug_assertions))]
5098 self.paint_inspector(inspector_element, cx);
5099
5100 self.paint_deferred_draws(cx);
5101
5102 if let Some(mut prompt_element) = prompt_element {
5103 prompt_element.paint(self, cx);
5104 } else if let Some(mut drag_element) = active_drag_element {
5105 drag_element.paint(self, cx);
5106 } else if let Some(mut tooltip_element) = tooltip_element {
5107 tooltip_element.paint(self, cx);
5108 }
5109
5110 #[cfg(any(feature = "inspector", debug_assertions))]
5111 self.paint_inspector_hitbox(cx);
5112
5113 #[cfg(feature = "profiler")]
5114 self.window_profiler
5115 .record_draw_phases(profiler::DrawPhases {
5116 request_layout: prepaint_start.duration_since(request_layout_start),
5117 prepaint: paint_start.duration_since(prepaint_start),
5118 paint: Instant::now().duration_since(paint_start),
5119 });
5120
5121 let _profile = crate::native_profiling::current_span("native", "GPUI postpaint accessibility");
5122 let a11y_active_start_of_frame = self.a11y.is_active();
5124 self.a11y.sync_active_flag();
5125 let a11y_active_end_of_frame = self.a11y.is_active();
5126
5127 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
5128
5129 if a11y_active_start_of_frame {
5130 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
5133 viewport_size: self.viewport_size,
5134 scale_factor: self.scale_factor,
5135 tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
5136 };
5137 let tree_update = self.a11y.end_frame(frame_info);
5139
5140 if should_send_a11y_update {
5141 log::debug!(
5142 "Sending a11y tree update: {} nodes",
5143 tree_update.nodes.len()
5144 );
5145 self.platform_window.a11y_tree_update(tree_update);
5146 }
5147 }
5148 }
5149
5150 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
5151 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
5153 let Some(Some(tooltip_request)) = self
5154 .next_frame
5155 .tooltip_requests
5156 .get(tooltip_request_index)
5157 .cloned()
5158 else {
5159 log::error!("Unexpectedly absent TooltipRequest");
5160 continue;
5161 };
5162 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
5163 let mouse_position = tooltip_request.tooltip.mouse_position;
5164 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
5165
5166 let mut tooltip_bounds =
5167 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
5168 let window_bounds = Bounds {
5169 origin: Point::default(),
5170 size: self.viewport_size(),
5171 };
5172
5173 if tooltip_bounds.right() > window_bounds.right() {
5174 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
5175 if new_x >= Pixels::ZERO {
5176 tooltip_bounds.origin.x = new_x;
5177 } else {
5178 tooltip_bounds.origin.x = cmp::max(
5179 Pixels::ZERO,
5180 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
5181 );
5182 }
5183 }
5184
5185 if tooltip_bounds.bottom() > window_bounds.bottom() {
5186 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
5187 if new_y >= Pixels::ZERO {
5188 tooltip_bounds.origin.y = new_y;
5189 } else {
5190 tooltip_bounds.origin.y = cmp::max(
5191 Pixels::ZERO,
5192 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
5193 );
5194 }
5195 }
5196
5197 let is_visible =
5201 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
5202 if !is_visible {
5203 continue;
5204 }
5205
5206 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
5207 element.prepaint(window, cx)
5208 });
5209
5210 self.tooltip_bounds = Some(TooltipBounds {
5211 id: tooltip_request.id,
5212 bounds: tooltip_bounds,
5213 });
5214 return Some(element);
5215 }
5216 None
5217 }
5218
5219 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
5220 assert_eq!(self.element_id_stack.len(), 0);
5221
5222 let mut round_start = 0;
5233 let mut depth = 0;
5234 loop {
5235 let round_end = self.next_frame.deferred_draws.len();
5236 if round_start == round_end {
5237 break;
5238 }
5239 assert!(depth < 64, "Exceeded maximum (64) deferred depth");
5246 depth += 1;
5247
5248 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
5250 {
5251 let draws = &self.next_frame.deferred_draws;
5252 traversal_order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5253 }
5254
5255 for deferred_draw_ix in traversal_order {
5256 let (
5257 element,
5258 parent_node,
5259 current_view,
5260 rem_size,
5261 absolute_offset,
5262 element_transform,
5263 element_opacity,
5264 content_mask,
5265 vn_clip,
5266 vn_scope,
5267 prepaint_range,
5268 ) = {
5269 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
5270 self.element_id_stack
5271 .clone_from(&deferred_draw.element_id_stack);
5272 self.text_style_stack
5273 .clone_from(&deferred_draw.text_style_stack);
5274 (
5275 deferred_draw.element.take(),
5276 deferred_draw.parent_node,
5277 deferred_draw.current_view,
5278 deferred_draw.rem_size,
5279 deferred_draw.absolute_offset,
5280 deferred_draw.element_transform,
5281 deferred_draw.element_opacity,
5282 deferred_draw.content_mask,
5283 deferred_draw.vn_clip.clone(),
5284 deferred_draw.vn_scope.clone(),
5285 deferred_draw.prepaint_range.clone(),
5286 )
5287 };
5288 self.next_frame.dispatch_tree.set_active_node(parent_node);
5289 let a11y_parent = self.next_frame.deferred_draws[deferred_draw_ix]
5292 .a11y_parent
5293 .filter(|&p| p != a11y::ROOT_NODE_ID && self.a11y.is_active());
5294
5295 let prepaint_start = self.prepaint_index();
5296 if let Some(mut element) = element {
5297 if let Some(parent) = a11y_parent {
5298 self.a11y.nodes.begin_adopted(parent);
5299 }
5300 let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
5301 self.with_rendered_view(current_view, |window| {
5302 window.with_rem_size(Some(rem_size), |window| {
5303 window.with_content_mask(content_mask, |window| {
5305 window.vn_with_absolute_clip_stack(vn_clip, |window| {
5306 window.with_absolute_element_opacity(element_opacity, |window| {
5307 window.with_absolute_element_transform(element_transform, |window| {
5308 window.with_absolute_element_offset(absolute_offset, |window| {
5309 let outer = mem::replace(&mut window.vn_defer_scope, vn_scope);
5310 element.prepaint(window, cx);
5311 window.vn_defer_scope = outer;
5312 });
5313 });
5314 });
5315 });
5316 });
5317 });
5318 });
5319 });
5320 if a11y_parent.is_some() {
5321 self.a11y.nodes.end_adopted();
5322 }
5323 self.next_frame.deferred_draws[deferred_draw_ix].accessed_entities = accessed_entities;
5324 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
5325 } else {
5326 cx.entities.extend_accessed(
5327 self.next_frame.deferred_draws[deferred_draw_ix]
5328 .accessed_entities
5329 .iter()
5330 .copied(),
5331 );
5332 self.reuse_prepaint(prepaint_range);
5333 }
5334 let prepaint_end = self.prepaint_index();
5335 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
5336 prepaint_start..prepaint_end;
5337 }
5338
5339 self.element_id_stack.clear();
5340 self.text_style_stack.clear();
5341 round_start = round_end;
5342 }
5343 }
5344
5345 fn paint_deferred_draws(&mut self, cx: &mut App) {
5346 let _profile = crate::native_profiling::current_span("paint", "GPUI paint deferred draws");
5347 assert_eq!(self.element_id_stack.len(), 0);
5348
5349 if self.next_frame.deferred_draws.len() == 0 {
5352 return;
5353 }
5354
5355 let traversal_order = self.deferred_draw_traversal_order();
5358 for deferred_draw_ix in traversal_order {
5359 let draw = &self.next_frame.deferred_draws[deferred_draw_ix];
5360 if let Some(scope) = &draw.vn_scope
5362 && (self.vn_scopes_painted.contains(&scope.id) || draw.element.is_none())
5363 {
5364 continue;
5365 }
5366 self.vn_paint_deferred_draw(deferred_draw_ix, None, cx);
5367 }
5368 self.element_id_stack.clear();
5369 self.text_style_stack.clear();
5370 }
5371
5372 fn vn_paint_deferred_draw(
5376 &mut self,
5377 ix: usize,
5378 scope: Option<(f32, Option<Arc<crate::VnClipNode>>)>,
5379 cx: &mut App,
5380 ) {
5381 let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5382 self.element_id_stack
5383 .clone_from(&deferred_draw.element_id_stack);
5384 self.text_style_stack
5390 .clone_from(&deferred_draw.text_style_stack);
5391 self.next_frame
5392 .dispatch_tree
5393 .set_active_node(deferred_draw.parent_node);
5394
5395 let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5396 let content_mask = deferred_draw.content_mask;
5397 let element_transform = deferred_draw.element_transform;
5398 let (element_opacity, base) = match &scope {
5399 Some((opacity, base)) => (
5400 (deferred_draw.element_opacity / opacity).min(1.),
5401 base.as_ref(),
5402 ),
5403 None => (deferred_draw.element_opacity, None),
5404 };
5405 let vn_clip = deferred_draw.vn_clip.clone();
5406 let view = deferred_draw.current_view;
5407 let rem_size = deferred_draw.rem_size;
5408 let paint_range = deferred_draw.paint_range.clone();
5409 let mut element = deferred_draw.element.take();
5410
5411 let paint_start = self.paint_index();
5412 if let Some(element) = element.as_mut() {
5413 let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
5414 self.with_rendered_view(view, |window| {
5415 window.with_content_mask(content_mask, |window| {
5417 window.vn_reopen_clip_layers(vn_clip, base, cx, |window, cx| {
5418 window.with_absolute_element_opacity(element_opacity, |window| {
5419 window.with_absolute_element_transform(element_transform, |window| {
5420 window.with_rem_size(Some(rem_size), |window| {
5421 element.paint(window, cx);
5422 });
5423 });
5424 });
5425 });
5426 });
5427 });
5428 });
5429 self.next_frame.deferred_draws[ix]
5430 .accessed_entities
5431 .extend(accessed_entities);
5432 } else {
5433 self.reuse_paint(paint_range);
5434 }
5435 let paint_end = self.paint_index();
5436 let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5437 deferred_draw.element = element;
5438 deferred_draw.paint_range = paint_start..paint_end;
5439 }
5440
5441 fn vn_paint_scope(&mut self, id: u64, opacity: f32, cx: &mut App) {
5445 if id == 0 || !self.vn_scopes_painted.insert(id) {
5446 return;
5447 }
5448 let mut order: SmallVec<[usize; 8]> = self
5449 .next_frame
5450 .deferred_draws
5451 .iter()
5452 .enumerate()
5453 .filter(|(_, draw)| draw.vn_scope.as_ref().is_some_and(|scope| scope.id == id))
5454 .map(|(ix, _)| ix)
5455 .collect();
5456 if order.is_empty() {
5457 return;
5458 }
5459 let draws = &self.next_frame.deferred_draws;
5460 order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5461 let element_id_stack = self.element_id_stack.clone();
5462 let text_style_stack = self.text_style_stack.clone();
5463 let active_node = self.next_frame.dispatch_tree.active_node_id();
5464 for ix in order {
5465 let base = self.next_frame.deferred_draws[ix]
5466 .vn_scope
5467 .as_ref()
5468 .and_then(|scope| scope.clip.clone());
5469 self.vn_paint_deferred_draw(ix, Some((opacity, base)), cx);
5470 }
5471 self.element_id_stack = element_id_stack;
5472 self.text_style_stack = text_style_stack;
5473 if let Some(node) = active_node {
5474 self.next_frame.dispatch_tree.set_active_node(node);
5475 }
5476 }
5477
5478 pub fn vn_with_defer_scope<R>(&mut self, id: u64, f: impl FnOnce(&mut Self) -> R) -> R {
5481 if id == 0 {
5482 return f(self);
5483 }
5484 let scope = VnDeferScope {
5485 id,
5486 clip: self.vn_clip_stack.clone(),
5487 };
5488 let previous = self.vn_defer_scope.replace(scope);
5489 let result = f(self);
5490 self.vn_defer_scope = previous;
5491 result
5492 }
5493
5494 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
5495 let deferred_count = self.next_frame.deferred_draws.len();
5496 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
5497 let draws = &self.next_frame.deferred_draws;
5498 sorted_indices.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5499 sorted_indices
5500 }
5501
5502 fn compute_hit_order(&mut self, deferred_hitboxes: Range<usize>) {
5510 let frame = &mut self.next_frame;
5511 frame.vn_hit_order.clear();
5512 if deferred_hitboxes.is_empty() {
5513 return;
5514 }
5515 let mut order: Vec<u32> = Vec::with_capacity(frame.hitboxes.len());
5516 order.extend(0..deferred_hitboxes.start as u32);
5517 let mut traversal = (0..frame.deferred_draws.len()).collect::<Vec<_>>();
5518 let draws = &frame.deferred_draws;
5519 traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5520 for ix in traversal {
5521 let range = &draws[ix].prepaint_range;
5522 let (start, end) = (range.start.hitboxes_index, range.end.hitboxes_index);
5523 if start >= deferred_hitboxes.start && end <= deferred_hitboxes.end && start < end {
5526 order.extend(start as u32..end as u32);
5527 }
5528 }
5529 order.extend(deferred_hitboxes.end as u32..frame.hitboxes.len() as u32);
5530 if order.len() != frame.hitboxes.len() {
5533 return;
5534 }
5535 frame.vn_hit_order = order;
5536 }
5537
5538 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
5539 PrepaintStateIndex {
5540 hitboxes_index: self.next_frame.hitboxes.len(),
5541 vn_tagged_hitboxes_index: self.next_frame.vn_tagged_hitboxes.len(),
5543 tooltips_index: self.next_frame.tooltip_requests.len(),
5544 deferred_draws_index: self.next_frame.deferred_draws.len(),
5545 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
5546 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
5547 line_layout_index: self.text_system.layout_index(),
5548 }
5549 }
5550
5551 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
5552 self.next_frame.hitboxes.extend(
5553 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
5554 .iter()
5555 .cloned(),
5556 );
5557 self.next_frame.vn_tagged_hitboxes.extend(
5563 self.rendered_frame.vn_tagged_hitboxes
5564 [range.start.vn_tagged_hitboxes_index..range.end.vn_tagged_hitboxes_index]
5565 .iter()
5566 .cloned(),
5567 );
5568 self.next_frame.tooltip_requests.extend(
5569 self.rendered_frame.tooltip_requests
5570 [range.start.tooltips_index..range.end.tooltips_index]
5571 .iter_mut()
5572 .map(|request| request.take()),
5573 );
5574 self.next_frame.accessed_element_states.extend(
5575 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
5576 ..range.end.accessed_element_states_index]
5577 .iter()
5578 .map(|(id, type_id)| (id.clone(), *type_id)),
5579 );
5580 self.text_system
5581 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
5582
5583 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
5584 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
5585 &mut self.rendered_frame.dispatch_tree,
5586 self.focus,
5587 );
5588
5589 if reused_subtree.contains_focus() {
5590 self.next_frame.focus = self.focus;
5591 }
5592
5593 self.next_frame.deferred_draws.extend(
5594 self.rendered_frame.deferred_draws
5595 [range.start.deferred_draws_index..range.end.deferred_draws_index]
5596 .iter()
5597 .map(|deferred_draw| DeferredDraw {
5598 current_view: deferred_draw.current_view,
5599 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
5600 element_id_stack: deferred_draw.element_id_stack.clone(),
5601 text_style_stack: deferred_draw.text_style_stack.clone(),
5602 content_mask: deferred_draw.content_mask,
5603 rem_size: deferred_draw.rem_size,
5604 priority: deferred_draw.priority,
5605 element: None,
5606 absolute_offset: deferred_draw.absolute_offset,
5607 element_transform: deferred_draw.element_transform,
5608 a11y_parent: deferred_draw.a11y_parent,
5609 vn_stack: deferred_draw.vn_stack.clone(),
5610 element_opacity: deferred_draw.element_opacity,
5611 vn_clip: deferred_draw.vn_clip.clone(),
5612 vn_scope: deferred_draw.vn_scope.clone(),
5613 prepaint_range: deferred_draw.prepaint_range.clone(),
5614 paint_range: deferred_draw.paint_range.clone(),
5615 accessed_entities: deferred_draw.accessed_entities.clone(),
5616 }),
5617 );
5618 }
5619
5620 pub(crate) fn paint_index(&self) -> PaintIndex {
5621 PaintIndex {
5622 scene_index: self.next_frame.scene.len(),
5623 #[cfg(any(test, feature = "test-support"))]
5624 debug_bounds_index: self.next_frame.debug_bounds_records.len(),
5625 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
5626 input_handlers_index: self.next_frame.input_handlers.len(),
5627 cursor_styles_index: self.next_frame.cursor_styles.len(),
5628 window_control_hitboxes_index: self.next_frame.window_control_hitboxes.len(),
5629 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
5630 tab_handle_index: self.next_frame.tab_stops.paint_index(),
5631 line_layout_index: self.text_system.layout_index(),
5632 }
5633 }
5634
5635 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
5636 #[cfg(any(test, feature = "test-support"))]
5638 for (selector, bounds) in &self.rendered_frame.debug_bounds_records
5639 [range.start.debug_bounds_index..range.end.debug_bounds_index]
5640 {
5641 self.next_frame
5642 .record_debug_bounds(selector.clone(), *bounds);
5643 }
5644 self.next_frame.window_control_hitboxes.extend(
5648 self.rendered_frame.window_control_hitboxes
5649 [range.start.window_control_hitboxes_index..range.end.window_control_hitboxes_index]
5650 .iter()
5651 .cloned(),
5652 );
5653 self.next_frame.cursor_styles.extend(
5654 self.rendered_frame.cursor_styles
5655 [range.start.cursor_styles_index..range.end.cursor_styles_index]
5656 .iter()
5657 .cloned(),
5658 );
5659 self.next_frame.input_handlers.extend(
5660 self.rendered_frame.input_handlers
5661 [range.start.input_handlers_index..range.end.input_handlers_index]
5662 .iter_mut()
5663 .map(|handler| handler.take()),
5664 );
5665 self.next_frame.mouse_listeners.extend(
5666 self.rendered_frame.mouse_listeners
5667 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
5668 .iter_mut()
5669 .map(|listener| listener.take()),
5670 );
5671 self.next_frame.accessed_element_states.extend(
5672 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
5673 ..range.end.accessed_element_states_index]
5674 .iter()
5675 .map(|(id, type_id)| (id.clone(), *type_id)),
5676 );
5677 self.next_frame.tab_stops.replay(
5678 &self.rendered_frame.tab_stops.insertion_history
5679 [range.start.tab_handle_index..range.end.tab_handle_index],
5680 );
5681
5682 self.text_system
5683 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
5684 self.next_frame.scene.replay(
5685 range.start.scene_index..range.end.scene_index,
5686 &self.rendered_frame.scene,
5687 );
5688 }
5689
5690 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
5694 where
5695 F: FnOnce(&mut Self) -> R,
5696 {
5697 self.invalidator.debug_assert_paint_or_prepaint();
5698 if let Some(style) = style {
5699 self.text_style_stack.push(style);
5700 let result = f(self);
5701 self.text_style_stack.pop();
5702 result
5703 } else {
5704 f(self)
5705 }
5706 }
5707
5708 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
5711 self.invalidator.debug_assert_paint();
5712 self.next_frame.cursor_styles.push(CursorStyleRequest {
5713 hitbox_id: Some(hitbox.id),
5714 style,
5715 });
5716 }
5717
5718 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
5723 self.invalidator.debug_assert_paint();
5724 self.next_frame.cursor_styles.push(CursorStyleRequest {
5725 hitbox_id: None,
5726 style,
5727 })
5728 }
5729
5730 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
5733 self.invalidator.debug_assert_prepaint();
5734 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
5735 self.next_frame
5736 .tooltip_requests
5737 .push(Some(TooltipRequest { id, tooltip }));
5738 id
5739 }
5740
5741 #[inline]
5746 pub fn with_content_mask<R>(
5747 &mut self,
5748 mask: Option<ContentMask<Pixels>>,
5749 f: impl FnOnce(&mut Self) -> R,
5750 ) -> R {
5751 self.invalidator.debug_assert_paint_or_prepaint();
5752 if let Some(mask) = mask {
5753 let mask = transform_mask(self.element_transform, mask, self.scale_factor);
5770 let mask = mask.intersect(&self.content_mask());
5771 self.content_mask_stack.push(mask);
5772 let result = f(self);
5773 self.content_mask_stack.pop();
5774 result
5775 } else {
5776 f(self)
5777 }
5778 }
5779
5780 pub fn vn_with_clip_shape<R>(
5789 &mut self,
5790 outline: Option<&crate::VnClipOutline>,
5791 f: impl FnOnce(&mut Self) -> R,
5792 ) -> R {
5793 let Some(outline) = outline else {
5794 return f(self);
5795 };
5796 let geometry = Arc::new(crate::VnClipGeometry::new(
5797 outline,
5798 self.scale_factor,
5799 self.element_transform,
5800 ));
5801 let node = Arc::new(crate::VnClipNode {
5802 geometry,
5803 color_matrix: None,
5804 capture: None,
5805 mask: None,
5806 parent: self.vn_clip_stack.clone(),
5807 });
5808 let previous = self.vn_clip_stack.replace(node.clone());
5809 let result = self.vn_with_clip_layer(&node, f);
5810 self.vn_clip_stack = previous;
5811 result
5812 }
5813
5814 pub fn vn_with_color_matrix<R>(
5817 &mut self,
5818 matrix: Option<crate::VnColorMatrix>,
5819 f: impl FnOnce(&mut Self) -> R,
5820 ) -> R {
5821 let Some(matrix) = matrix else { return f(self) };
5822 let bounds = self.snapped_content_mask().bounds;
5823 let left = bounds.origin.x.0;
5824 let top = bounds.origin.y.0;
5825 let right = left + bounds.size.width.0;
5826 let bottom = top + bounds.size.height.0;
5827 let geometry = Arc::new(crate::VnClipGeometry {
5828 fill_rule: crate::VnFillRule::NonZero,
5829 segments: vec![
5830 [left, top, right, top], [right, top, right, bottom],
5831 [right, bottom, left, bottom], [left, bottom, left, top],
5832 ],
5833 bounds,
5834 });
5835 let node = Arc::new(crate::VnClipNode {
5836 geometry,
5837 color_matrix: Some(matrix),
5838 capture: None,
5839 mask: None,
5840 parent: self.vn_clip_stack.clone(),
5841 });
5842 let previous = self.vn_clip_stack.replace(node.clone());
5843 let result = self.vn_with_clip_layer(&node, f);
5844 self.vn_clip_stack = previous;
5845 result
5846 }
5847
5848 pub fn vn_text_paint(&self, fill: crate::VnTextFill, bounds: Bounds<Pixels>) -> Arc<crate::VnTextPaint> {
5850 let x = bounds.origin.x.0; let y = bounds.origin.y.0;
5851 let right = x + bounds.size.width.0; let bottom = y + bounds.size.height.0;
5852 let outline = crate::VnClipOutline {
5853 fill_rule: crate::VnFillRule::NonZero,
5854 verbs: vec![crate::VnPathVerb::MoveTo([x,y]), crate::VnPathVerb::LineTo([right,y]),
5855 crate::VnPathVerb::LineTo([right,bottom]), crate::VnPathVerb::LineTo([x,bottom]), crate::VnPathVerb::Close],
5856 };
5857 let m = self.element_transform.inverse().unwrap_or_else(TransformationMatrix::unit);
5858 Arc::new(crate::VnTextPaint {
5859 fill, bounds: [x, y, bounds.size.width.0, bounds.size.height.0],
5860 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]],
5861 scale_factor: self.scale_factor,
5862 geometry: Arc::new(crate::VnClipGeometry::new(&outline, self.scale_factor, self.element_transform)),
5863 content_mask: self.snapped_content_mask(),
5864 })
5865 }
5866
5867 pub fn vn_with_text_mask<R>(&mut self, paint: Arc<crate::VnTextPaint>, f: impl FnOnce(&mut Self) -> R) -> R {
5870 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5871 geometry: paint.geometry.clone(), color_matrix: None,
5872 content_mask: paint.content_mask, text_paint: Some(paint), capture: None,
5873 });
5874 let result = f(self);
5875 self.next_frame.scene.vn_pop_isolation();
5876 result
5877 }
5878
5879 pub fn vn_with_mask<R>(
5885 &mut self,
5886 mask: Option<&crate::VnMask>,
5887 bounds: Bounds<Pixels>,
5888 cx: &mut App,
5889 f: impl FnOnce(&mut Self, &mut App) -> R,
5890 ) -> R {
5891 let Some(mask) = mask.filter(|mask| mask.paint.is_some()) else {
5892 return f(self, cx);
5893 };
5894 let node = Arc::new(crate::VnClipNode {
5895 geometry: self.vn_box_geometry(bounds),
5896 color_matrix: None,
5897 capture: None,
5898 mask: Some(crate::VnClipMask {
5899 mask: mask.clone(),
5900 bounds,
5901 transform: self.element_transform,
5902 }),
5903 parent: self.vn_clip_stack.clone(),
5904 });
5905 let previous = self.vn_clip_stack.replace(node.clone());
5906 let result = if self.invalidator.is_painting() {
5907 let content_mask = self.snapped_content_mask();
5908 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5909 geometry: node.geometry.clone(),
5910 color_matrix: None,
5911 text_paint: None,
5912 content_mask,
5913 capture: None,
5914 });
5915 let result = f(self, cx);
5916 self.vn_paint_mask(&node, cx);
5917 self.next_frame.scene.vn_pop_isolation();
5918 result
5919 } else {
5920 f(self, cx)
5921 };
5922 self.vn_clip_stack = previous;
5923 result
5924 }
5925
5926 fn vn_paint_mask(&mut self, node: &crate::VnClipNode, cx: &mut App) {
5928 let Some(clip) = &node.mask else { return };
5929 let Some(paint) = clip.mask.paint.clone() else { return };
5930 self.next_frame.scene.vn_begin_mask(clip.mask.luminance);
5931 let opacity = mem::replace(&mut self.element_opacity, 1.);
5934 let tint = mem::replace(&mut self.element_image_tint, Hsla::transparent_black());
5935 let transform = mem::replace(&mut self.element_transform, clip.transform);
5936 paint(clip.bounds, None, self, cx);
5937 self.element_opacity = opacity;
5938 self.element_image_tint = tint;
5939 self.element_transform = transform;
5940 }
5941
5942 fn vn_box_geometry(&self, bounds: Bounds<Pixels>) -> Arc<crate::VnClipGeometry> {
5944 let (x, y) = (bounds.origin.x.0, bounds.origin.y.0);
5945 let (right, bottom) = (x + bounds.size.width.0, y + bounds.size.height.0);
5946 let outline = crate::VnClipOutline {
5947 fill_rule: crate::VnFillRule::NonZero,
5948 verbs: vec![
5949 crate::VnPathVerb::MoveTo([x, y]),
5950 crate::VnPathVerb::LineTo([right, y]),
5951 crate::VnPathVerb::LineTo([right, bottom]),
5952 crate::VnPathVerb::LineTo([x, bottom]),
5953 crate::VnPathVerb::Close,
5954 ],
5955 };
5956 Arc::new(crate::VnClipGeometry::new(
5957 &outline,
5958 self.scale_factor,
5959 self.element_transform,
5960 ))
5961 }
5962
5963 fn vn_with_clip_layer<R>(
5966 &mut self,
5967 node: &Arc<crate::VnClipNode>,
5968 f: impl FnOnce(&mut Self) -> R,
5969 ) -> R {
5970 if !self.invalidator.is_painting() {
5971 return f(self);
5972 }
5973 let content_mask = self.snapped_content_mask();
5974 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5975 geometry: node.geometry.clone(),
5976 color_matrix: node.color_matrix,
5977 text_paint: None,
5978 content_mask,
5979 capture: node.capture,
5980 });
5981 let result = f(self);
5982 self.next_frame.scene.vn_pop_isolation();
5983 result
5984 }
5985
5986 fn vn_with_absolute_clip_stack<R>(
5989 &mut self,
5990 clip: Option<Arc<crate::VnClipNode>>,
5991 f: impl FnOnce(&mut Self) -> R,
5992 ) -> R {
5993 let previous = mem::replace(&mut self.vn_clip_stack, clip);
5994 let result = f(self);
5995 self.vn_clip_stack = previous;
5996 result
5997 }
5998
5999 fn vn_reopen_clip_layers<R>(
6005 &mut self,
6006 clip: Option<Arc<crate::VnClipNode>>,
6007 base: Option<&Arc<crate::VnClipNode>>,
6008 cx: &mut App,
6009 f: impl FnOnce(&mut Self, &mut App) -> R,
6010 ) -> R {
6011 let Some(innermost) = clip.clone() else {
6012 return self.vn_with_absolute_clip_stack(None, |window| f(window, cx));
6013 };
6014 let chain = crate::VnClipNode::inside_of(&innermost, base);
6015 self.vn_with_absolute_clip_stack(clip, |window| {
6016 for node in &chain {
6017 let content_mask = window.snapped_content_mask();
6018 window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
6019 geometry: node.geometry.clone(),
6020 color_matrix: node.color_matrix,
6021 text_paint: None,
6022 content_mask,
6023 capture: node.capture,
6024 });
6025 }
6026 let result = f(window, cx);
6027 for node in chain.iter().rev() {
6028 window.vn_paint_mask(node, cx);
6029 window.next_frame.scene.vn_pop_isolation();
6030 }
6031 result
6032 })
6033 }
6034
6035 pub fn vn_with_capture<R>(
6041 &mut self,
6042 id: Option<u64>,
6043 bounds: Bounds<Pixels>,
6044 own: TransformationMatrix,
6045 f: impl FnOnce(&mut Self) -> R,
6046 ) -> R {
6047 let Some(id) = id else { return f(self) };
6048 let scale_factor = self.scale_factor();
6049 let viewport = Bounds { origin: Point::default(), size: self.viewport_size };
6050 let device = viewport.scale(scale_factor);
6051 let info = crate::VnCaptureInfo {
6052 id,
6053 border_box: bounds.scale(scale_factor),
6054 transform: self.element_transform.compose(own),
6055 };
6056 let node = Arc::new(crate::VnClipNode {
6057 geometry: Arc::new(crate::VnClipGeometry::rect(device)),
6058 color_matrix: None,
6059 capture: Some(info),
6060 mask: None,
6061 parent: None,
6062 });
6063 let previous_clip = self.vn_clip_stack.replace(node.clone());
6064 self.content_mask_stack.push(ContentMask::rect(viewport));
6065 let result = self.with_absolute_element_transform(TransformationMatrix::unit(), |window| {
6066 window.with_absolute_element_opacity(1., |window| {
6067 if !window.invalidator.is_painting() {
6068 return f(window);
6069 }
6070 window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
6071 geometry: node.geometry.clone(),
6072 color_matrix: None,
6073 text_paint: None,
6074 content_mask: ContentMask::rect(device),
6075 capture: Some(info),
6076 });
6077 let result = f(window);
6078 window.next_frame.scene.vn_pop_isolation();
6079 result
6080 })
6081 });
6082 self.content_mask_stack.pop();
6083 self.vn_clip_stack = previous_clip;
6084 result
6085 }
6086
6087 pub fn vn_with_isolation<R>(&mut self, isolate: bool, f: impl FnOnce(&mut Self) -> R) -> R {
6090 if !isolate || !self.invalidator.is_painting() {
6091 return f(self);
6092 }
6093 let device = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6094 let content_mask = self.snapped_content_mask();
6095 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
6096 geometry: Arc::new(crate::VnClipGeometry::rect(device)),
6097 color_matrix: None,
6098 text_paint: None,
6099 content_mask,
6100 capture: None,
6101 });
6102 let result = f(self);
6103 self.next_frame.scene.vn_pop_isolation();
6104 result
6105 }
6106
6107 pub fn vn_paint_snapshot(&mut self, id: u64, bounds: Bounds<Pixels>, plus_lighter: bool) {
6112 self.invalidator.debug_assert_paint();
6113 let scale_factor = self.scale_factor();
6114 let device = bounds.scale(scale_factor);
6115 if device.size.width.0 <= 0. || device.size.height.0 <= 0. {
6116 return;
6117 }
6118 let Some(inverse) = self.element_transform.inverse() else { return };
6119 let (w, h) = (device.size.width.0, device.size.height.0);
6120 let [[a, b], [c, d]] = inverse.rotation_scale;
6121 let [tx, ty] = inverse.translation;
6122 let (x, y) = (device.origin.x.0, device.origin.y.0);
6123 let to_unit = [a / w, b / w, (tx - x) / w, c / h, d / h, (ty - y) / h];
6124 let covered = crate::scene::transformed_bounds(device, self.element_transform);
6125 let covered = Bounds::from_corners(
6126 point(ScaledPixels(covered.origin.x.0.floor()), ScaledPixels(covered.origin.y.0.floor())),
6127 point(
6128 ScaledPixels((covered.origin.x.0 + covered.size.width.0).ceil()),
6129 ScaledPixels((covered.origin.y.0 + covered.size.height.0).ceil()),
6130 ),
6131 );
6132 let opacity = self.element_opacity;
6133 let content_mask = self.snapped_content_mask();
6134 self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
6135 id,
6136 to_unit,
6137 bounds: covered,
6138 content_mask,
6139 opacity,
6140 plus_lighter,
6141 in_place: false,
6142 });
6143 }
6144
6145 pub fn vn_paint_snapshot_in_place(&mut self, id: u64) {
6148 self.invalidator.debug_assert_paint();
6149 let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6150 let opacity = self.element_opacity;
6151 let content_mask = self.snapped_content_mask();
6152 self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
6153 id,
6154 to_unit: [0.; 6],
6155 bounds: viewport,
6156 content_mask,
6157 opacity,
6158 plus_lighter: false,
6159 in_place: true,
6160 });
6161 }
6162
6163 pub fn vn_capture(&self, id: u64) -> Option<crate::VnCaptureInfo> {
6166 self.vn_capture_records.get(&id).map(|(info, _)| *info)
6167 }
6168
6169 pub fn vn_forget_captures(&mut self, ids: &[u64]) {
6172 for id in ids {
6173 self.vn_capture_records.remove(id);
6174 }
6175 }
6176
6177 pub fn vn_supports_snapshots(&self) -> bool {
6180 self.platform_window.vn_supports_snapshots()
6181 }
6182
6183 fn vn_settle_captures(&mut self) {
6184 let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6185 let scene = &mut self.next_frame.scene;
6186 for capture in &mut scene.vn_captures {
6187 capture.ink = capture.ink.intersect(&viewport);
6188 self.vn_capture_records.insert(capture.info.id, (capture.info, capture.ink));
6189 }
6190 let records = &self.vn_capture_records;
6191 scene.vn_resolve_snapshots(|id| records.get(&id).copied());
6192 }
6193
6194 pub fn with_element_offset<R>(
6197 &mut self,
6198 offset: Point<Pixels>,
6199 f: impl FnOnce(&mut Self) -> R,
6200 ) -> R {
6201 self.invalidator.debug_assert_prepaint();
6202
6203 if offset.is_zero() {
6204 return f(self);
6205 };
6206
6207 let abs_offset = self.element_offset() + offset;
6208 self.with_absolute_element_offset(abs_offset, f)
6209 }
6210
6211 pub fn with_absolute_element_offset<R>(
6215 &mut self,
6216 offset: Point<Pixels>,
6217 f: impl FnOnce(&mut Self) -> R,
6218 ) -> R {
6219 self.invalidator.debug_assert_prepaint();
6220 self.element_offset_stack.push(offset);
6221 let result = f(self);
6222 self.element_offset_stack.pop();
6223 result
6224 }
6225
6226 pub(crate) fn with_element_opacity<R>(
6227 &mut self,
6228 opacity: Option<f32>,
6229 f: impl FnOnce(&mut Self) -> R,
6230 ) -> R {
6231 self.invalidator.debug_assert_paint_or_prepaint();
6232
6233 let Some(opacity) = opacity else {
6234 return f(self);
6235 };
6236
6237 let previous_opacity = self.element_opacity;
6238 self.element_opacity = previous_opacity * opacity;
6239 let result = f(self);
6240 self.element_opacity = previous_opacity;
6241 result
6242 }
6243
6244 pub fn with_image_tint<R>(&mut self, tint: Hsla, f: impl FnOnce(&mut Self) -> R) -> R {
6255 self.invalidator.debug_assert_paint_or_prepaint();
6256 let previous = std::mem::replace(&mut self.element_image_tint, tint);
6257 let result = f(self);
6258 self.element_image_tint = previous;
6259 result
6260 }
6261
6262 pub fn with_image_headroom<R>(&mut self, headroom: f32, f: impl FnOnce(&mut Self) -> R) -> R {
6266 self.invalidator.debug_assert_paint_or_prepaint();
6267 let headroom = if headroom.is_finite() {
6268 headroom.max(1.0)
6269 } else {
6270 1.0
6271 };
6272 let previous = std::mem::replace(&mut self.element_image_headroom, headroom);
6273 let result = f(self);
6274 self.element_image_headroom = previous;
6275 result
6276 }
6277
6278 pub fn with_absolute_element_transform<R>(
6301 &mut self,
6302 transformation: TransformationMatrix,
6303 f: impl FnOnce(&mut Self) -> R,
6304 ) -> R {
6305 let previous = mem::replace(&mut self.element_transform, transformation);
6306 let result = f(self);
6307 self.element_transform = previous;
6308 result
6309 }
6310
6311 fn with_absolute_element_opacity<R>(
6314 &mut self,
6315 opacity: f32,
6316 f: impl FnOnce(&mut Self) -> R,
6317 ) -> R {
6318 let previous = mem::replace(&mut self.element_opacity, opacity);
6319 let result = f(self);
6320 self.element_opacity = previous;
6321 result
6322 }
6323
6324 pub fn with_element_transform<R>(
6328 &mut self,
6329 transformation: TransformationMatrix,
6330 f: impl FnOnce(&mut Self) -> R,
6331 ) -> R {
6332 if transformation.is_unit() {
6333 return f(self);
6334 }
6335 let previous = self.element_transform;
6336 self.element_transform = previous.compose(transformation);
6339 let result = f(self);
6340 self.element_transform = previous;
6341 result
6342 }
6343
6344 pub fn content_mask_in_element_space(&self) -> ContentMask<Pixels> {
6356 let mask = self.content_mask();
6357 if self.element_transform.is_unit() {
6358 return mask;
6359 }
6360 match self.element_transform.inverse() {
6361 Some(inverse) => transform_mask(inverse, mask, self.scale_factor),
6362 None => ContentMask::rect(Bounds::default()),
6363 }
6364 }
6365
6366 #[inline]
6369 pub fn element_transform(&self) -> TransformationMatrix {
6370 self.element_transform
6371 }
6372
6373 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
6379 self.invalidator.debug_assert_prepaint();
6380 let index = self.prepaint_index();
6381 let result = f(self);
6382 if result.is_err() {
6383 self.next_frame.hitboxes.truncate(index.hitboxes_index);
6384 self.next_frame
6387 .vn_tagged_hitboxes
6388 .truncate(index.vn_tagged_hitboxes_index);
6389 self.next_frame
6390 .tooltip_requests
6391 .truncate(index.tooltips_index);
6392 self.next_frame
6393 .deferred_draws
6394 .truncate(index.deferred_draws_index);
6395 self.next_frame
6396 .dispatch_tree
6397 .truncate(index.dispatch_tree_index);
6398 self.next_frame
6399 .accessed_element_states
6400 .truncate(index.accessed_element_states_index);
6401 self.text_system.truncate_layouts(index.line_layout_index);
6402 }
6403 result
6404 }
6405
6406 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
6412 self.invalidator.debug_assert_prepaint();
6413 self.requested_autoscroll = Some(bounds);
6414 }
6415
6416 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
6419 self.invalidator.debug_assert_prepaint();
6420 self.requested_autoscroll.take()
6421 }
6422
6423 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
6429 cx.asset_entry::<A>(source).use_by(self.current_view())
6430 }
6431
6432 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
6438 cx.fetch_asset::<A>(source)
6439 }
6440 pub fn element_offset(&self) -> Point<Pixels> {
6443 self.invalidator.debug_assert_prepaint();
6444 self.element_offset_stack
6445 .last()
6446 .copied()
6447 .unwrap_or_default()
6448 }
6449
6450 #[inline]
6453 pub(crate) fn element_opacity(&self) -> f32 {
6454 self.invalidator.debug_assert_paint_or_prepaint();
6455 self.element_opacity
6456 }
6457
6458 pub fn content_mask(&self) -> ContentMask<Pixels> {
6460 self.invalidator.debug_assert_paint_or_prepaint();
6461 self.content_mask_stack
6462 .last()
6463 .cloned()
6464 .unwrap_or_else(|| {
6465 ContentMask::rect(Bounds {
6466 origin: Point::default(),
6467 size: self.viewport_size,
6468 })
6469 })
6470 }
6471
6472 pub fn with_element_namespace<R>(
6475 &mut self,
6476 element_id: impl Into<ElementId>,
6477 f: impl FnOnce(&mut Self) -> R,
6478 ) -> R {
6479 self.element_id_stack.push(element_id.into());
6480 let result = f(self);
6481 self.element_id_stack.pop();
6482 result
6483 }
6484
6485 pub fn use_keyed_state<S: 'static>(
6487 &mut self,
6488 key: impl Into<ElementId>,
6489 cx: &mut App,
6490 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
6491 ) -> Entity<S> {
6492 let current_view = self.current_view();
6493 self.with_global_id(key.into(), |global_id, window| {
6494 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
6495 if let Some(state) = state {
6496 (state.clone(), state)
6497 } else {
6498 let new_state = cx.new(|cx| init(window, cx));
6499 Self::observe_keyed_state(&new_state, current_view, cx);
6500 (new_state.clone(), new_state)
6501 }
6502 })
6503 })
6504 }
6505
6506 #[track_caller]
6512 pub fn use_state<S: 'static>(
6513 &mut self,
6514 cx: &mut App,
6515 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
6516 ) -> Entity<S> {
6517 self.use_keyed_state(
6518 ElementId::CodeLocation(*core::panic::Location::caller()),
6519 cx,
6520 init,
6521 )
6522 }
6523
6524 #[inline(always)]
6529 pub fn with_element_state<S, R>(
6530 &mut self,
6531 global_id: &GlobalElementId,
6532 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
6533 ) -> R
6534 where
6535 S: 'static,
6536 {
6537 self.invalidator.debug_assert_paint_or_prepaint();
6538
6539 let (key, state) = self.take_element_state(global_id, TypeId::of::<S>());
6540
6541 if let Some(any) = state {
6542 let ElementStateBox {
6543 inner,
6544 #[cfg(debug_assertions)]
6545 type_name,
6546 } = any;
6547 let mut state_box = inner
6549 .downcast::<Option<S>>()
6550 .map_err(|_| {
6551 #[cfg(debug_assertions)]
6552 {
6553 anyhow::anyhow!(
6554 "invalid element state type for id, requested {:?}, actual: {:?}",
6555 std::any::type_name::<S>(),
6556 type_name
6557 )
6558 }
6559
6560 #[cfg(not(debug_assertions))]
6561 {
6562 anyhow::anyhow!(
6563 "invalid element state type for id, requested {:?}",
6564 std::any::type_name::<S>(),
6565 )
6566 }
6567 })
6568 .unwrap();
6569
6570 let state = state_box.take().expect(
6571 "reentrant call to with_element_state for the same state type and element id",
6572 );
6573 let (result, state) = f(Some(state), self);
6574 state_box.replace(state);
6575 self.insert_element_state(
6576 key,
6577 ElementStateBox {
6578 inner: state_box,
6579 #[cfg(debug_assertions)]
6580 type_name,
6581 },
6582 );
6583 result
6584 } else {
6585 let (result, state) = f(None, self);
6586 self.insert_element_state(
6587 key,
6588 ElementStateBox {
6589 inner: Box::new(Some(state)),
6590 #[cfg(debug_assertions)]
6591 type_name: std::any::type_name::<S>(),
6592 },
6593 );
6594 result
6595 }
6596 }
6597
6598 pub fn with_optional_element_state<S, R>(
6605 &mut self,
6606 global_id: Option<&GlobalElementId>,
6607 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
6608 ) -> R
6609 where
6610 S: 'static,
6611 {
6612 self.invalidator.debug_assert_paint_or_prepaint();
6613
6614 if let Some(global_id) = global_id {
6615 self.with_element_state(global_id, |state, cx| {
6616 let (result, state) = f(Some(state), cx);
6617 let state =
6618 state.expect("you must return some state when you pass some element id");
6619 (result, state)
6620 })
6621 } else {
6622 let (result, state) = f(None, self);
6623 debug_assert!(
6624 state.is_none(),
6625 "you must not return an element state when passing None for the global id"
6626 );
6627 result
6628 }
6629 }
6630
6631 #[inline]
6633 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
6634 if let Some(index) = index {
6635 self.next_frame.tab_stops.begin_group(index);
6636 let result = f(self);
6637 self.next_frame.tab_stops.end_group();
6638 result
6639 } else {
6640 f(self)
6641 }
6642 }
6643
6644 pub fn defer_draw(
6653 &mut self,
6654 element: AnyElement,
6655 absolute_offset: Point<Pixels>,
6656 priority: usize,
6657 content_mask: Option<ContentMask<Pixels>>,
6658 ) {
6659 self.defer_draw_with_stack_key(element, absolute_offset, priority, content_mask, None)
6660 }
6661
6662 pub fn defer_draw_with_stack_key(
6665 &mut self,
6666 element: AnyElement,
6667 absolute_offset: Point<Pixels>,
6668 priority: usize,
6669 content_mask: Option<ContentMask<Pixels>>,
6670 stack_key: Option<Rc<[u128]>>,
6671 ) {
6672 self.invalidator.debug_assert_prepaint();
6673 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
6674 self.next_frame.deferred_draws.push(DeferredDraw {
6675 current_view: self.current_view(),
6676 parent_node,
6677 element_id_stack: self.element_id_stack.clone(),
6678 text_style_stack: self.text_style_stack.clone(),
6679 content_mask,
6680 rem_size: self.rem_size(),
6681 priority,
6682 element: Some(element),
6683 absolute_offset,
6684 element_transform: self.element_transform,
6685 a11y_parent: self
6686 .a11y
6687 .is_active()
6688 .then(|| self.a11y.nodes.current_id()),
6689 vn_stack: stack_key,
6690 element_opacity: self.element_opacity,
6691 vn_clip: if content_mask.is_some() {
6692 self.vn_clip_stack.clone()
6693 } else {
6694 crate::VnClipNode::color_filters(&self.vn_clip_stack)
6695 },
6696 vn_scope: self.vn_defer_scope.clone(),
6697 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
6698 paint_range: PaintIndex::default()..PaintIndex::default(),
6699 accessed_entities: FxHashSet::default(),
6700 });
6701 }
6702
6703 pub fn paint_layer<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
6712 self.invalidator.debug_assert_paint();
6713
6714 self.next_frame.scene.push_layer();
6715 let result = f(self);
6716 self.next_frame.scene.pop_layer();
6717 result
6718 }
6719
6720 pub fn paint_drop_shadows(
6731 &mut self,
6732 bounds: Bounds<Pixels>,
6733 corner_radii: Corners<Pixels>,
6734 shadows: &[BoxShadow],
6735 ) {
6736 self.paint_outer_shadows(bounds, corner_radii, Corners::default(), shadows, SHADOW_OUTSIDE_BOX);
6737 }
6738
6739 pub fn paint_drop_shadows_under_box(
6743 &mut self,
6744 bounds: Bounds<Pixels>,
6745 corner_radii: Corners<Pixels>,
6746 shadows: &[BoxShadow],
6747 ) {
6748 self.paint_outer_shadows(bounds, corner_radii, Corners::default(), shadows, SHADOW_UNDER_BOX);
6749 }
6750
6751 pub fn vn_paint_drop_shadows(
6754 &mut self,
6755 bounds: Bounds<Pixels>,
6756 corner_radii: Corners<Pixels>,
6757 corner_shapes: Corners<CornerShape>,
6758 shadows: &[BoxShadow],
6759 under_box: bool,
6760 ) {
6761 let kind = if under_box { SHADOW_UNDER_BOX } else { SHADOW_OUTSIDE_BOX };
6762 self.paint_outer_shadows(bounds, corner_radii, corner_shapes, shadows, kind);
6763 }
6764
6765 fn paint_outer_shadows(
6766 &mut self,
6767 bounds: Bounds<Pixels>,
6768 corner_radii: Corners<Pixels>,
6769 corner_shapes: Corners<CornerShape>,
6770 shadows: &[BoxShadow],
6771 kind: u32,
6772 ) {
6773 self.invalidator.debug_assert_paint();
6774
6775 let scale_factor = self.scale_factor();
6776 let content_mask = self.snapped_content_mask();
6777 let opacity = self.element_opacity();
6778 let element_bounds = self.cover_bounds(bounds);
6779 let element_corner_radii = corner_radii.scale(scale_factor);
6780 for shadow in shadows {
6781 if shadow.inset {
6782 continue;
6783 }
6784 let shape_bounds =
6785 self.cover_bounds((bounds + shadow.offset).dilate(shadow.spread_radius));
6786 if shape_bounds.is_empty() {
6787 continue;
6788 }
6789 let blur_radius = shadow.blur_radius.scale(scale_factor);
6790 let spread = shadow.spread_radius;
6791 let shadow_radius = |r: Pixels| spread_shadow_radius(r, spread);
6792 let shadow_corner_radii = Corners {
6793 top_left: shadow_radius(corner_radii.top_left),
6794 top_right: shadow_radius(corner_radii.top_right),
6795 bottom_right: shadow_radius(corner_radii.bottom_right),
6796 bottom_left: shadow_radius(corner_radii.bottom_left),
6797 };
6798 self.next_frame.scene.insert_primitive(Shadow {
6799 order: 0,
6800 blur_radius,
6801 bounds: shape_bounds.dilate(blur_radius * 3.),
6803 content_mask,
6804 corner_radii: element_corner_radii,
6805 color: shadow.color.opacity(opacity),
6806 shape_bounds,
6807 shape_corner_radii: shadow_corner_radii.scale(scale_factor),
6808 inset: kind,
6809 pad: 0,
6810 transformation: self.element_transform,
6811 element_bounds,
6812 corner_shapes: CornerShapes::new(&corner_shapes),
6813 });
6814 }
6815 }
6816
6817 pub fn paint_inset_shadows(
6821 &mut self,
6822 bounds: Bounds<Pixels>,
6823 corner_radii: Corners<Pixels>,
6824 shadows: &[BoxShadow],
6825 ) {
6826 self.vn_paint_inset_shadows(bounds, corner_radii, Corners::default(), shadows);
6827 }
6828
6829 pub fn vn_paint_inset_shadows(
6833 &mut self,
6834 bounds: Bounds<Pixels>,
6835 corner_radii: Corners<Pixels>,
6836 corner_shapes: Corners<CornerShape>,
6837 shadows: &[BoxShadow],
6838 ) {
6839 self.invalidator.debug_assert_paint();
6840
6841 let scale_factor = self.scale_factor();
6842 let content_mask = self.snapped_content_mask();
6843 let opacity = self.element_opacity();
6844 let element_bounds = self.cover_bounds(bounds);
6845 let element_corner_radii = corner_radii.scale(scale_factor);
6846 for shadow in shadows {
6847 if !shadow.inset {
6848 continue;
6849 }
6850 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
6851 let zero = Pixels::ZERO;
6854 let spread = shadow.spread_radius;
6855 let hole_radius = |radius: Pixels, shape: CornerShape| {
6856 if shape.is_round() || spread <= zero { (radius - spread).max(zero) } else { radius }
6857 };
6858 let hole_corner_radii = Corners {
6859 top_left: hole_radius(corner_radii.top_left, corner_shapes.top_left),
6860 top_right: hole_radius(corner_radii.top_right, corner_shapes.top_right),
6861 bottom_right: hole_radius(corner_radii.bottom_right, corner_shapes.bottom_right),
6862 bottom_left: hole_radius(corner_radii.bottom_left, corner_shapes.bottom_left),
6863 };
6864 let inset = f32::from(spread.max(zero)) * scale_factor;
6865 self.next_frame.scene.insert_primitive(Shadow {
6866 order: 0,
6867 blur_radius: shadow.blur_radius.scale(scale_factor),
6868 bounds: element_bounds,
6869 content_mask,
6870 corner_radii: element_corner_radii,
6871 color: shadow.color.opacity(opacity),
6872 shape_bounds: self.cover_bounds(hole),
6873 shape_corner_radii: hole_corner_radii.scale(scale_factor),
6874 inset: SHADOW_INSET,
6875 pad: 0,
6876 transformation: self.element_transform,
6877 element_bounds,
6878 corner_shapes: CornerShapes::new(&corner_shapes)
6879 .with_insets(Corners {
6880 top_left: (inset, inset),
6881 top_right: (inset, inset),
6882 bottom_right: (inset, inset),
6883 bottom_left: (inset, inset),
6884 }),
6885 });
6886 }
6887 }
6888
6889 fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
6890 let size = quad.bounds.size;
6891 let diagonal = (size.width.0 * size.width.0 + size.height.0 * size.height.0).sqrt();
6892 if diagonal == 0. {
6893 return Bounds::default();
6894 }
6895 let cos = size.height.0 / diagonal;
6899 let sin = size.width.0 / diagonal;
6900
6901 let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| {
6904 point(
6905 width_x.max(radius - (radius - width_x) * cos),
6906 width_y.max(radius - (radius - width_y) * sin),
6907 )
6908 };
6909
6910 let radii = &quad.corner_radii;
6911 let widths = &quad.border_widths;
6912 let top_left = corner_inset(radii.top_left, widths.left, widths.top);
6913 let top_right = corner_inset(radii.top_right, widths.right, widths.top);
6914 let bottom_right = corner_inset(radii.bottom_right, widths.right, widths.bottom);
6915 let bottom_left = corner_inset(radii.bottom_left, widths.left, widths.bottom);
6916
6917 let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
6918 Bounds::from_corners(
6919 quad.bounds.origin
6920 + point(top_left.x.max(bottom_left.x), top_left.y.max(top_right.y))
6921 + antialias_inset,
6922 quad.bounds.bottom_right()
6923 - point(
6924 top_right.x.max(bottom_right.x),
6925 bottom_left.y.max(bottom_right.y),
6926 )
6927 - antialias_inset,
6928 )
6929 }
6930
6931 pub fn paint_quad(&mut self, quad: PaintQuad) {
6941 self.invalidator.debug_assert_paint();
6942
6943 let opacity = self.element_opacity();
6944 let snapped_bounds = self.snap_bounds(quad.bounds);
6945 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
6946 let quad = Quad {
6947 order: 0,
6948 bounds: snapped_bounds,
6949 content_mask: self.snapped_content_mask(),
6950 background: quad.background.opacity(opacity),
6951 border_color: quad.border_color.opacity(opacity),
6952 corner_radii: quad.corner_radii.scale(self.scale_factor()),
6953 border_widths: snapped_border_widths,
6954 border_style: quad.border_style,
6955 transformation: self.element_transform,
6956 corner_shapes: CornerShapes::new(&quad.corner_shapes),
6957 };
6958 self.insert_quad(quad);
6959 }
6960
6961 fn insert_quad(&mut self, quad: Quad) {
6962 let has_background = !quad.background.is_transparent();
6963 let has_border =
6964 quad.border_widths != Edges::default() && !quad.border_color.is_transparent();
6965 if !has_background && !has_border {
6966 return;
6967 }
6968
6969 let is_rectangle =
6970 quad.border_widths == Edges::default() && quad.corner_radii == Corners::default();
6971 if has_background && is_rectangle {
6972 self.next_frame.scene.insert_primitive(quad);
6973 return;
6974 }
6975
6976 if !quad.transformation.is_unit()
6984 || quad.content_mask.is_rounded()
6985 || !quad.corner_shapes.is_round()
6986 {
6987 self.next_frame.scene.insert_primitive(quad);
6988 return;
6989 }
6990
6991 let plain_border = quad.corner_radii == Corners::default()
6992 && quad.border_style == BorderStyle::Solid
6993 && (!has_background || quad.border_color.is_opaque());
6994
6995 let outer_bounds = quad.bounds;
6998 let inner_bounds = if plain_border {
6999 quad.bounds.extend(quad.border_widths.map(|width| -*width))
7000 } else {
7001 Self::largest_border_interior(&quad)
7002 };
7003
7004 let strip_quad = if plain_border {
7008 Quad {
7009 background: quad.border_color.into(),
7010 border_widths: Edges::default(),
7011 ..quad
7012 }
7013 } else {
7014 quad
7015 };
7016
7017 if inner_bounds.is_empty() {
7018 self.next_frame.scene.insert_primitive(strip_quad);
7019 return;
7020 }
7021
7022 if has_background && !quad.background.is_ring() {
7024 self.next_frame.scene.insert_primitive(Quad {
7025 content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&inner_bounds)),
7026 border_widths: Edges::default(),
7027 corner_radii: Corners::default(),
7028 ..quad
7029 });
7030 }
7031
7032 let strips = [
7033 Bounds::from_corners(
7035 outer_bounds.origin,
7036 point(outer_bounds.right(), inner_bounds.top()),
7037 ),
7038 Bounds::from_corners(
7040 point(outer_bounds.left(), inner_bounds.bottom()),
7041 outer_bounds.bottom_right(),
7042 ),
7043 Bounds::from_corners(
7045 point(outer_bounds.left(), inner_bounds.top()),
7046 inner_bounds.bottom_left(),
7047 ),
7048 Bounds::from_corners(
7050 inner_bounds.top_right(),
7051 point(outer_bounds.right(), inner_bounds.bottom()),
7052 ),
7053 ];
7054
7055 for strip in strips {
7056 self.next_frame.scene.insert_primitive(Quad {
7057 content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&strip)),
7058 ..strip_quad
7059 });
7060 }
7061 }
7062
7063 pub fn paint_backdrop_blur_rect(
7078 &mut self,
7079 bounds: Bounds<Pixels>,
7080 corner_radii: Corners<Pixels>,
7081 effect: BackdropBlurEffect,
7082 ) {
7083 self.vn_paint_backdrop_blur_rect(bounds, corner_radii, Corners::default(), effect);
7084 }
7085
7086 pub fn vn_paint_backdrop_blur_rect(
7088 &mut self,
7089 bounds: Bounds<Pixels>,
7090 corner_radii: Corners<Pixels>,
7091 corner_shapes: Corners<CornerShape>,
7092 effect: BackdropBlurEffect,
7093 ) {
7094 self.invalidator.debug_assert_paint();
7095
7096 let opacity = self.element_opacity();
7097 if opacity <= 0. {
7098 return;
7099 }
7100
7101 let scale_factor = self.scale_factor();
7102 let blur_radius = effect.radius.scale(scale_factor);
7103 if blur_radius.0 <= 0. {
7104 let tint = effect.tint.opacity(opacity);
7105 if tint.a > 0. {
7106 self.paint_quad(
7107 fill(bounds, tint).corner_radii(corner_radii).corner_shapes(corner_shapes),
7108 );
7109 }
7110 return;
7111 }
7112
7113 let Some((bounds, k)) =
7119 crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
7120 else {
7121 return;
7122 };
7123 self.next_frame.scene.insert_primitive(BackdropBlurRect {
7124 order: 0,
7125 pad: 0,
7126 bounds,
7127 content_mask: self.snapped_content_mask(),
7128 corner_radii: corner_radii.scale(scale_factor * k),
7129 blur_radius,
7130 opacity,
7131 tint: effect.tint,
7132 corner_shapes: CornerShapes::new(&corner_shapes),
7133 });
7134 }
7135
7136 pub fn paint_effect_quad(
7157 &mut self,
7158 bounds: Bounds<Pixels>,
7159 corner_radii: Corners<Pixels>,
7160 spec: EffectSpec,
7161 ) {
7162 self.vn_paint_effect(bounds, corner_radii, spec, 0);
7163 }
7164
7165 pub fn vn_paint_effect(
7168 &mut self,
7169 bounds: Bounds<Pixels>,
7170 corner_radii: Corners<Pixels>,
7171 spec: EffectSpec,
7172 element: u64,
7173 ) {
7174 self.vn_paint_effect_with(bounds, corner_radii, Corners::default(), spec, element, None);
7175 }
7176
7177 pub fn vn_paint_textured_effect(
7180 &mut self,
7181 bounds: Bounds<Pixels>,
7182 corner_radii: Corners<Pixels>,
7183 corner_shapes: Corners<CornerShape>,
7184 spec: EffectSpec,
7185 element: u64,
7186 cx: &mut App,
7187 ) {
7188 let textures = crate::resolve_effect_textures(&spec, self, cx);
7189 self.vn_paint_effect_with(bounds, corner_radii, corner_shapes, spec, element, textures);
7190 }
7191
7192 fn vn_paint_effect_with(
7193 &mut self,
7194 bounds: Bounds<Pixels>,
7195 corner_radii: Corners<Pixels>,
7196 corner_shapes: Corners<CornerShape>,
7197 spec: EffectSpec,
7198 element: u64,
7199 textures: Option<Arc<crate::EffectTextureSet>>,
7200 ) {
7201 self.invalidator.debug_assert_paint();
7202 let opacity = self.element_opacity();
7203 let Some(mut quad) =
7204 self.vn_effect_quad(bounds, corner_radii, corner_shapes, spec, element, opacity, textures.as_deref())
7205 else {
7206 return;
7207 };
7208 quad.flags &= !crate::EFFECT_FLAG_NEEDS_CONTENT;
7209 let history = vn_history_key(element, &spec);
7210 if history == 0 {
7211 quad.flags &= !crate::EFFECT_FLAG_HISTORY;
7212 self.next_frame
7213 .scene
7214 .insert_primitive(crate::Primitive::EffectQuad(quad, textures));
7215 return;
7216 }
7217 let content_mask = quad.content_mask;
7218 self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
7219 draws: vec![crate::VnEffectDraw {
7220 quad,
7221 history,
7222 textures,
7223 }],
7224 content: false,
7225 content_mask,
7226 });
7227 self.next_frame.scene.vn_pop_isolation();
7228 }
7229
7230 pub fn vn_set_effect_element(&mut self, id: Option<&GlobalElementId>) {
7233 self.vn_effect_element = vn_element_key(id);
7234 }
7235
7236 pub fn vn_take_effect_element(&mut self) -> u64 {
7239 mem::take(&mut self.vn_effect_element)
7240 }
7241
7242 #[allow(clippy::too_many_arguments)]
7246 pub fn vn_with_effect_content<R>(
7247 &mut self,
7248 bounds: Bounds<Pixels>,
7249 corner_radii: Corners<Pixels>,
7250 corner_shapes: Corners<CornerShape>,
7251 effects: &[(EffectSpec, f32, Option<Arc<crate::EffectTextureSet>>)],
7252 element: u64,
7253 cx: &mut App,
7254 f: impl FnOnce(&mut Self, &mut App) -> R,
7255 ) -> R {
7256 let opacity = self.element_opacity();
7257 if !self.invalidator.is_painting() || opacity <= 0. {
7258 return f(self, cx);
7259 }
7260 let mut draws = Vec::new();
7261 let mut plain = 1.;
7262 for (spec, weight, textures) in effects {
7263 if spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT == 0 || *weight <= 0. {
7264 continue;
7265 }
7266 let Some(mut quad) = self.vn_effect_quad(
7267 bounds,
7268 corner_radii,
7269 corner_shapes,
7270 *spec,
7271 element,
7272 opacity * weight,
7273 textures.as_deref(),
7274 ) else {
7275 continue;
7276 };
7277 let history = vn_history_key(element, spec);
7278 if history == 0 {
7279 quad.flags &= !crate::EFFECT_FLAG_HISTORY;
7280 }
7281 plain -= weight;
7282 draws.push(crate::VnEffectDraw {
7283 quad,
7284 history,
7285 textures: textures.clone(),
7286 });
7287 }
7288 let content_mask = self.snapped_content_mask();
7289 if plain > 1e-3 {
7290 draws.insert(
7291 0,
7292 crate::VnEffectDraw {
7293 quad: EffectQuad {
7294 effect_id: crate::effect_id::CONTENT,
7295 bounds: content_mask.bounds,
7296 content_mask,
7297 opacity: opacity * plain.min(1.),
7298 scale: self.scale_factor(),
7299 flags: crate::EFFECT_FLAG_NEEDS_CONTENT,
7300 ..Default::default()
7301 },
7302 history: 0,
7303 textures: None,
7304 },
7305 );
7306 }
7307 self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
7308 draws,
7309 content: true,
7310 content_mask,
7311 });
7312 let outer = mem::replace(&mut self.element_opacity, 1.);
7313 let result = f(self, cx);
7314 self.vn_paint_scope(element, opacity, cx);
7315 self.element_opacity = outer;
7316 self.next_frame.scene.vn_pop_isolation();
7317 result
7318 }
7319
7320 #[allow(clippy::too_many_arguments)]
7323 fn vn_effect_quad(
7324 &mut self,
7325 bounds: Bounds<Pixels>,
7326 corner_radii: Corners<Pixels>,
7327 corner_shapes: Corners<CornerShape>,
7328 spec: EffectSpec,
7329 element: u64,
7330 opacity: f32,
7331 textures: Option<&crate::EffectTextureSet>,
7332 ) -> Option<EffectQuad> {
7333 if !spec.is_some() || opacity <= 0. {
7334 return None;
7335 }
7336
7337 let scale_factor = self.scale_factor();
7338 let bleed = px(spec.bleed());
7339 let draw_bounds = bounds.dilate(bleed);
7344 let draw_radii = Corners {
7345 top_left: corner_radii.top_left + bleed,
7346 top_right: corner_radii.top_right + bleed,
7347 bottom_right: corner_radii.bottom_right + bleed,
7348 bottom_left: corner_radii.bottom_left + bleed,
7349 };
7350
7351 let mut params = spec.params;
7352 for (index, param) in params.iter_mut().enumerate() {
7353 if spec.length_mask & (1 << index) != 0 {
7354 *param *= scale_factor;
7355 }
7356 }
7357 crate::write_effect_texture_sizes(&spec, textures, &mut params);
7358
7359 let Some((draw_bounds, k)) = crate::scene::axis_aligned_through(
7363 self.snap_bounds(draw_bounds),
7364 self.element_transform,
7365 ) else {
7366 return None;
7367 };
7368 let bleed = bleed.scale(scale_factor);
7369 let now = crate::effect_clock_seconds();
7370
7371 if let Some(slot) = spec.pointer_param.map(usize::from)
7372 && slot + 2 <= params.len()
7373 {
7374 let origin = draw_bounds.origin.map(|c| c.0 + bleed.0);
7376 let size = draw_bounds.size.map(|c| (c.0 - 2. * bleed.0).max(1.));
7377 let pointer = self.mouse_position.map(|c| c.0 * scale_factor);
7378 params[slot] = (pointer.x - origin.x) / size.width;
7379 params[slot + 1] = (pointer.y - origin.y) / size.height;
7380 }
7381 if let Some(slot) = spec.pointer_times_param.map(usize::from)
7382 && slot + 3 <= params.len()
7383 {
7384 let times = &self.vn_effect_pointer;
7385 params[slot..slot + 3].copy_from_slice(&[times.moved, times.entered, times.left]);
7386 }
7387 if spec.follows_pointer() {
7388 let view = self.current_view();
7389 self.vn_effect_pointer.views.insert(view);
7390 }
7391 if let Some(slot) = spec.animated_param.map(usize::from)
7392 && slot < params.len()
7393 && element != 0
7394 {
7395 let key = vn_phase_key(element, &spec);
7396 let previous = self.vn_effect_phases.get(&key).copied();
7397 let phase = VnEffectPhase::advance(previous, params[slot], now);
7398 self.vn_effect_phases.insert(key, phase);
7399 if let Some(speed) = phase.speed(now) {
7400 params[slot] = speed;
7401 }
7402 }
7403
7404 let mut clocked = spec;
7405 clocked.params = params;
7406 if spec.animated || clocked.clock_running(now) {
7407 self.request_animation_frame();
7409 }
7410
7411 Some(EffectQuad {
7412 order: 0,
7413 effect_id: spec.id,
7414 bounds: draw_bounds,
7415 content_mask: self.snapped_content_mask(),
7416 corner_radii: draw_radii.scale(scale_factor * k),
7417 params,
7418 opacity,
7419 time: now,
7420 bleed,
7421 backdrop_blur_radius: px(spec.backdrop_blur_radius()).scale(scale_factor),
7422 scale: scale_factor,
7423 flags: spec.flags,
7424 corner_shapes: CornerShapes::new(&corner_shapes),
7425 })
7426 }
7427
7428 pub fn vn_paint_punch(&mut self, bounds: Bounds<Pixels>, corner_radii: Corners<Pixels>) {
7437 self.invalidator.debug_assert_paint();
7438 let opacity = self.element_opacity();
7439 if opacity <= 0. {
7440 return;
7441 }
7442 let scale_factor = self.scale_factor();
7443 let Some((draw_bounds, k)) =
7446 crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
7447 else {
7448 return;
7449 };
7450 self.next_frame.scene.insert_primitive(EffectQuad {
7451 order: 0,
7452 effect_id: crate::effect_id::PUNCH,
7453 bounds: draw_bounds,
7454 content_mask: self.snapped_content_mask(),
7455 corner_radii: corner_radii.scale(scale_factor * k),
7456 params: [0.; crate::EFFECT_PARAM_SLOTS],
7457 opacity,
7458 time: 0.,
7459 bleed: ScaledPixels(0.),
7460 backdrop_blur_radius: ScaledPixels(0.),
7461 scale: scale_factor,
7462 flags: 0,
7463 corner_shapes: CornerShapes::default(),
7464 });
7465 }
7466
7467 pub fn paint_path(&mut self, path: Path, color: impl Into<Background>) {
7471 self.invalidator.debug_assert_paint();
7472
7473 let scale_factor = self.scale_factor();
7474 let content_mask = self.content_mask();
7475 let opacity = self.element_opacity();
7476 let color: Background = color.into();
7477 let path = if self.element_transform.is_unit() {
7482 path
7483 } else {
7484 path.transformed(self.element_transform, scale_factor)
7485 };
7486 self.next_frame.scene.insert_primitive(PaintedPath::new(
7487 path,
7488 scale_factor,
7489 content_mask,
7490 color.opacity(opacity),
7491 ));
7492 }
7493
7494 pub fn paint_underline(
7498 &mut self,
7499 origin: Point<Pixels>,
7500 width: Pixels,
7501 style: &UnderlineStyle,
7502 ) {
7503 self.invalidator.debug_assert_paint();
7504 let underline = self.underline(origin, width, style);
7506 self.next_frame.scene.insert_primitive(underline);
7507 }
7508
7509 pub fn paint_strikethrough(
7513 &mut self,
7514 origin: Point<Pixels>,
7515 width: Pixels,
7516 style: &StrikethroughStyle,
7517 ) {
7518 self.invalidator.debug_assert_paint();
7519
7520 let scale_factor = self.scale_factor();
7521 let height = style.thickness;
7522 let bounds = Bounds {
7523 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
7524 size: size(self.snap_stroke(width), self.snap_stroke(height)),
7525 };
7526 let opacity = self.element_opacity();
7527
7528 self.next_frame.scene.insert_primitive(Underline {
7529 order: 0,
7530 pad: 0,
7531 bounds,
7532 content_mask: self.snapped_content_mask(),
7533 thickness: self.snap_stroke(style.thickness),
7534 color: style.color.unwrap_or_default().opacity(opacity),
7535 wavy: false.into(),
7536 transformation: self.element_transform,
7537 });
7538 }
7539
7540 pub fn paint_glyph(
7549 &mut self,
7550 origin: Point<Pixels>,
7551 font_id: FontId,
7552 glyph_id: GlyphId,
7553 font_size: Pixels,
7554 color: Hsla,
7555 ) -> Result<()> {
7556 self.invalidator.debug_assert_paint();
7557
7558 let element_opacity = self.element_opacity();
7559 let scale_factor = self.scale_factor();
7560 let (glyph_origin, transformation) = self.glyph_placement(origin);
7561
7562 let quantized_origin = Point::new(
7563 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
7564 / SUBPIXEL_VARIANTS_X as f32,
7565 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
7566 / SUBPIXEL_VARIANTS_Y as f32,
7567 );
7568 let subpixel_variant = Point::new(
7569 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
7570 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
7571 );
7572 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
7573 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
7574 let dilation = self.text_system().glyph_dilation_for_color(color);
7575 let params = RenderGlyphParams {
7576 font_id,
7577 glyph_id,
7578 font_size,
7579 subpixel_variant,
7580 scale_factor,
7581 is_emoji: false,
7582 subpixel_rendering,
7583 dilation,
7584 };
7585
7586 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
7587 if !raster_bounds.is_zero() {
7588 let tile = self
7589 .sprite_atlas
7590 .get_or_insert_with(params.clone().into(), &mut || {
7591 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
7592 Ok(Some((size, Cow::Owned(bytes))))
7593 })?
7594 .expect("Callback above only errors or returns Some");
7595 let bounds = Bounds {
7596 origin: integer_origin + raster_bounds.origin.map(Into::into),
7597 size: tile.bounds.size.map(Into::into),
7598 };
7599 let content_mask = self.snapped_content_mask();
7600
7601 if subpixel_rendering {
7602 self.next_frame.scene.insert_primitive(SubpixelSprite {
7603 order: 0,
7604 pad: 0,
7605 bounds,
7606 content_mask,
7607 color: color.opacity(element_opacity),
7608 tile,
7609 transformation,
7610 });
7611 } else {
7612 self.next_frame.scene.insert_primitive(MonochromeSprite {
7613 order: 0,
7614 raw_coverage: false.into(),
7615 animation: SpriteAnimationId::NONE,
7616 pad: 0,
7617 bounds,
7618 content_mask,
7619 color: color.opacity(element_opacity),
7620 tile,
7621 transformation,
7622 });
7623 }
7624 }
7625 Ok(())
7626 }
7627
7628 fn glyph_placement(
7632 &self,
7633 origin: Point<Pixels>,
7634 ) -> (Point<ScaledPixels>, TransformationMatrix) {
7635 let origin = origin.scale(self.scale_factor());
7636 let transform = self.element_transform;
7637 if transform.rotation_scale != TransformationMatrix::unit().rotation_scale {
7638 return (origin, transform);
7639 }
7640 let [x, y] = transform.translation;
7641 (
7642 point(origin.x + ScaledPixels(x), origin.y + ScaledPixels(y)),
7643 TransformationMatrix::unit(),
7644 )
7645 }
7646
7647 pub fn paint_glyph_shadow(
7650 &mut self,
7651 origin: Point<Pixels>,
7652 font_id: FontId,
7653 glyph_id: GlyphId,
7654 font_size: Pixels,
7655 is_emoji: bool,
7656 color: Hsla,
7657 blur_radius: Pixels,
7658 ) -> Result<()> {
7659 self.invalidator.debug_assert_paint();
7660 if blur_radius <= px(0.) && !is_emoji {
7661 return self.paint_glyph(origin, font_id, glyph_id, font_size, color);
7662 }
7663
7664 let scale_factor = self.scale_factor();
7665 let (glyph_origin, transformation) = self.glyph_placement(origin);
7666 let (integer_origin, subpixel_variant) = if is_emoji {
7667 (
7668 glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0))),
7669 Point::default(),
7670 )
7671 } else {
7672 let quantized_origin = Point::new(
7673 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
7674 / SUBPIXEL_VARIANTS_X as f32,
7675 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
7676 / SUBPIXEL_VARIANTS_Y as f32,
7677 );
7678 (
7679 quantized_origin.map(|c| ScaledPixels(c.trunc())),
7680 Point::new(
7681 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
7682 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
7683 ),
7684 )
7685 };
7686 let glyph = RenderGlyphParams {
7687 font_id,
7688 glyph_id,
7689 font_size,
7690 subpixel_variant,
7691 scale_factor,
7692 is_emoji,
7693 subpixel_rendering: false,
7694 dilation: if is_emoji {
7695 0
7696 } else {
7697 self.text_system().glyph_dilation_for_color(color)
7698 },
7699 };
7700 let raster_bounds = self.text_system().raster_bounds(&glyph)?;
7701 if raster_bounds.is_zero() {
7702 return Ok(());
7703 }
7704 let params = GlyphShadowParams {
7705 sigma_quarters: GlyphShadowParams::quantize_sigma(blur_radius.0 / 2. * scale_factor),
7706 glyph,
7707 };
7708 let padding = params.padding();
7709 let sigma = params.sigma();
7710 let Some(tile) = self.sprite_atlas.get_or_insert_with(
7711 AtlasKey::GlyphShadow(params.clone()),
7712 &mut || {
7713 let (size, coverage) = self.text_system().rasterize_glyph(¶ms.glyph)?;
7714 let (size, blurred) = blur_glyph_coverage(size, &coverage, sigma);
7715 Ok(Some((size, Cow::Owned(blurred))))
7716 },
7717 )?
7718 else {
7719 return Ok(());
7720 };
7721 let bounds = Bounds {
7722 origin: integer_origin
7723 + raster_bounds.origin.map(Into::into)
7724 - point(ScaledPixels(padding as f32), ScaledPixels(padding as f32)),
7725 size: tile.bounds.size.map(Into::into),
7726 };
7727 let content_mask = self.snapped_content_mask();
7728 self.next_frame.scene.insert_primitive(MonochromeSprite {
7729 order: 0,
7730 raw_coverage: true.into(),
7731 animation: SpriteAnimationId::NONE,
7732 pad: 0,
7733 bounds,
7734 content_mask,
7735 color: color.opacity(self.element_opacity()),
7736 tile,
7737 transformation,
7738 });
7739 Ok(())
7740 }
7741
7742 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
7743 if !self.platform_window.is_subpixel_rendering_supported() {
7746 return false;
7747 }
7748 if self.next_frame.scene.vn_is_isolating() {
7752 return false;
7753 }
7754
7755 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
7756 return false;
7757 }
7758
7759 let mode = match self.text_rendering_mode.get() {
7760 TextRenderingMode::PlatformDefault => self
7761 .text_system()
7762 .recommended_rendering_mode(font_id, font_size),
7763 mode => mode,
7764 };
7765
7766 mode == TextRenderingMode::Subpixel
7767 }
7768
7769 pub fn paint_emoji(
7778 &mut self,
7779 origin: Point<Pixels>,
7780 font_id: FontId,
7781 glyph_id: GlyphId,
7782 font_size: Pixels,
7783 ) -> Result<()> {
7784 self.invalidator.debug_assert_paint();
7785
7786 let scale_factor = self.scale_factor();
7787 let (glyph_origin, transformation) = self.glyph_placement(origin);
7788 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
7789 let params = RenderGlyphParams {
7790 font_id,
7791 glyph_id,
7792 font_size,
7793 subpixel_variant: Default::default(),
7794 scale_factor,
7795 is_emoji: true,
7796 subpixel_rendering: false,
7797 dilation: 0,
7798 };
7799
7800 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
7801 if !raster_bounds.is_zero() {
7802 let tile = self
7803 .sprite_atlas
7804 .get_or_insert_with(params.clone().into(), &mut || {
7805 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
7806 Ok(Some((size, Cow::Owned(bytes))))
7807 })?
7808 .expect("Callback above only errors or returns Some");
7809
7810 let bounds = Bounds {
7811 origin: integer_origin + raster_bounds.origin.map(Into::into),
7812 size: tile.bounds.size.map(Into::into),
7813 };
7814 let content_mask = self.snapped_content_mask();
7815 let opacity = self.element_opacity();
7816
7817 self.next_frame.scene.insert_primitive(PolychromeSprite {
7818 order: 0,
7819 pad: 0,
7820 grayscale: false.into(),
7821 bounds,
7822 corner_radii: Default::default(),
7823 content_mask,
7824 tile,
7825 opacity,
7826 transformation,
7827 tint: Hsla::transparent_black(),
7828 corner_shapes: CornerShapes::default(),
7829 });
7830 }
7831 Ok(())
7832 }
7833
7834 pub fn paint_svg(
7838 &mut self,
7839 bounds: Bounds<Pixels>,
7840 path: SharedString,
7841 data: Option<&[u8]>,
7842 transformation: TransformationMatrix,
7843 color: Hsla,
7844 cx: &App,
7845 ) -> Result<()> {
7846 self.paint_animated_svg(bounds, path, data, transformation, None, color, cx)
7847 }
7848
7849 pub(crate) fn paint_animated_svg(
7852 &mut self,
7853 bounds: Bounds<Pixels>,
7854 path: SharedString,
7855 data: Option<&[u8]>,
7856 transformation: TransformationMatrix,
7857 animation: Option<SpriteAnimation>,
7858 color: Hsla,
7859 cx: &App,
7860 ) -> Result<()> {
7861 self.invalidator.debug_assert_paint();
7862
7863 let element_opacity = self.element_opacity();
7864 let bounds = self.snap_bounds(bounds);
7865
7866 let params = RenderSvgParams {
7867 path,
7868 size: bounds.size.map(|pixels| {
7869 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
7870 }),
7871 };
7872
7873 let Some(tile) =
7874 self.sprite_atlas
7875 .get_or_insert_with(params.clone().into(), &mut || {
7876 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
7877 else {
7878 return Ok(None);
7879 };
7880 Ok(Some((size, Cow::Owned(bytes))))
7881 })?
7882 else {
7883 return Ok(());
7884 };
7885 let content_mask = self.snapped_content_mask();
7886 let svg_bounds = Bounds {
7887 origin: bounds.center()
7888 - Point::new(
7889 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
7890 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
7891 ),
7892 size: tile
7893 .bounds
7894 .size
7895 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
7896 };
7897 let final_bounds = svg_bounds
7898 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
7899 .map_size(|size| size.ceil());
7900
7901 let sprite = MonochromeSprite {
7902 order: 0,
7903 raw_coverage: false.into(),
7904 animation: SpriteAnimationId::NONE,
7905 pad: 0,
7906 bounds: final_bounds,
7907 content_mask,
7908 color: color.opacity(element_opacity),
7909 tile,
7910 transformation: self.element_transform.compose(transformation),
7913 };
7914 match animation {
7915 Some(animation) => self.next_frame.scene.insert_animated_sprite(
7916 sprite,
7917 animation.under(self.element_transform),
7918 ),
7919 None => self.next_frame.scene.insert_primitive(sprite),
7920 }
7921
7922 Ok(())
7923 }
7924
7925 pub fn paint_image(
7937 &mut self,
7938 bounds: Bounds<Pixels>,
7939 image_bounds: Bounds<Pixels>,
7940 corner_radii: Corners<Pixels>,
7941 data: Arc<RenderImage>,
7942 frame_index: usize,
7943 grayscale: bool,
7944 ) -> Result<()> {
7945 self.invalidator.debug_assert_paint();
7946
7947 let visible_bounds = bounds.intersect(&image_bounds);
7948 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
7949 return Ok(());
7950 }
7951 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
7952 return Ok(());
7953 }
7954
7955 let (data, frame_index) = match IMAGE_RESAMPLER.get() {
7958 Some(resample) if !data.is_dynamic() => {
7959 let scale = self.scale_factor();
7960 let device = size(
7961 DevicePixels((image_bounds.size.width.0 * scale).round() as i32),
7962 DevicePixels((image_bounds.size.height.0 * scale).round() as i32),
7963 );
7964 match resample(&data, frame_index, device) {
7965 Some(smaller) => (smaller, 0),
7966 None => (data, frame_index),
7967 }
7968 }
7969 _ => (data, frame_index),
7970 };
7971
7972 let params = RenderImageParams {
7973 image_id: data.id,
7974 frame_index,
7975 };
7976
7977 let tile = self.sprite_atlas.get_or_insert_with(params.into(), &mut || {
7978 Ok(data.as_bytes(frame_index).map(|bytes| (data.size(frame_index), Cow::Borrowed(bytes))))
7979 })?;
7980 let Some(tile) = tile else { return Ok(()); };
7981
7982 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
7983
7984 let sub_tile = if visible_bounds == image_bounds {
7985 tile
7986 } else {
7987 let x_offset_ratio =
7988 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
7989 let y_offset_ratio =
7990 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
7991 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
7992 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
7993
7994 let tile_origin_x = tile.bounds.origin.x.0;
7995 let tile_origin_y = tile.bounds.origin.y.0;
7996 let tile_width = tile.bounds.size.width.0;
7997 let tile_height = tile.bounds.size.height.0;
7998
7999 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
8000 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
8001 let sub_width = (width_ratio * tile_width as f32).round() as i32;
8002 let sub_height = (height_ratio * tile_height as f32).round() as i32;
8003
8004 let max_x = tile_origin_x + tile_width;
8005 let max_y = tile_origin_y + tile_height;
8006
8007 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
8008 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
8009 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
8010 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
8011
8012 AtlasTile {
8013 bounds: Bounds {
8014 origin: point(
8015 DevicePixels(clamped_origin_x),
8016 DevicePixels(clamped_origin_y),
8017 ),
8018 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
8019 },
8020 ..tile
8021 }
8022 };
8023
8024 let content_mask = self.snapped_content_mask();
8025 let corner_radii = corner_radii
8026 .clamp_radii_for_quad_size(visible_bounds.size)
8027 .scale(self.scale_factor());
8028 let opacity = self.element_opacity();
8029
8030 let pad = if sub_tile.texture_id.kind == AtlasTextureKind::PolychromeHdr {
8033 self.element_image_headroom.to_bits()
8034 } else {
8035 0
8036 };
8037 self.next_frame.scene.insert_primitive(PolychromeSprite {
8038 order: 0,
8039 pad,
8040 grayscale: grayscale.into(),
8041 bounds: visible_bounds_snapped,
8042 content_mask,
8043 corner_radii,
8044 tile: sub_tile,
8045 opacity,
8046 transformation: self.element_transform,
8047 tint: self.element_image_tint,
8048 corner_shapes: CornerShapes::default(),
8049 });
8050 Ok(())
8051 }
8052
8053 #[cfg(any(target_os = "macos", target_os = "ios"))]
8057 pub fn paint_surface(
8058 &mut self,
8059 bounds: Bounds<Pixels>,
8060 image_buffer: CFRetained<CVPixelBuffer>,
8061 ) {
8062 use crate::PaintSurface;
8063
8064 self.invalidator.debug_assert_paint();
8065
8066 let bounds = self.snap_bounds(bounds);
8067 let content_mask = self.snapped_content_mask();
8068 self.next_frame.scene.insert_primitive(PaintSurface {
8069 order: 0,
8070 bounds,
8071 content_mask,
8072 image_buffer,
8073 });
8074 }
8075
8076 pub fn upload_image_from_gpu(
8097 &mut self,
8098 data: &RenderImage,
8099 frame_index: usize,
8100 texture: GpuTextureHandle,
8101 ) -> Result<bool> {
8102 Ok(self.write_image_tile(data, frame_index, TileSource::Gpu(texture))? != TileWrite::Refused)
8103 }
8104
8105 pub fn write_image_tile(
8123 &mut self,
8124 image: &RenderImage,
8125 frame_index: usize,
8126 source: TileSource,
8127 ) -> Result<TileWrite> {
8128 let key: AtlasKey = RenderImageParams {
8129 image_id: image.id,
8130 frame_index,
8131 }
8132 .into();
8133 let size = image.size(frame_index);
8134 let before = self.sprite_atlas.tile(&key);
8135 let after = match source {
8136 TileSource::Gpu(texture) => {
8137 match self.sprite_atlas.upload_from_gpu(&key, size, texture)? {
8138 Some(tile) => tile,
8139 None => return Ok(TileWrite::Refused),
8140 }
8141 }
8142 TileSource::Bytes => {
8143 let bytes = image
8144 .as_bytes(frame_index)
8145 .ok_or_else(|| anyhow!("write_image_tile: no frame {frame_index}"))?;
8146 match self.sprite_atlas.write_bytes(&key, size, bytes)? {
8147 Some(tile) => tile,
8148 None => {
8149 self.sprite_atlas.remove(&key);
8150 self.sprite_atlas
8151 .get_or_insert_with(key, &mut || {
8152 Ok(Some((size, Cow::Borrowed(bytes))))
8153 })?
8154 .ok_or_else(|| anyhow!("write_image_tile: the atlas took no tile"))?;
8155 return Ok(TileWrite::Placed);
8156 }
8157 }
8158 }
8159 };
8160 Ok(match before {
8161 Some(tile) if tile == after => TileWrite::InPlace,
8162 _ => TileWrite::Placed,
8163 })
8164 }
8165
8166 pub fn write_image_tile_rgba16f(
8170 &mut self,
8171 image: &RenderImage,
8172 frame_index: usize,
8173 halves: &[u16],
8174 ) -> Result<TileWrite> {
8175 let key: AtlasKey = RenderImageParams {
8176 image_id: image.id,
8177 frame_index,
8178 }
8179 .into();
8180 let before = self.sprite_atlas.tile(&key);
8181 let bytes = unsafe {
8183 std::slice::from_raw_parts(halves.as_ptr().cast::<u8>(), std::mem::size_of_val(halves))
8184 };
8185 let Some(after) =
8186 self.sprite_atlas
8187 .write_hdr_bytes(&key, image.size(frame_index), bytes)?
8188 else {
8189 return Ok(TileWrite::Refused);
8190 };
8191 Ok(match before {
8192 Some(tile) if tile == after => TileWrite::InPlace,
8193 _ => TileWrite::Placed,
8194 })
8195 }
8196
8197 pub fn write_image_tile_d3d12(
8200 &mut self,
8201 image: &RenderImage,
8202 frame_index: usize,
8203 texture: crate::D3D12TextureHandle,
8204 owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
8205 ) -> Result<TileWrite> {
8206 let key: AtlasKey = RenderImageParams {
8207 image_id: image.id,
8208 frame_index,
8209 }
8210 .into();
8211 let before = self.sprite_atlas.tile(&key);
8212 let Some(after) = self.sprite_atlas.upload_from_d3d12(
8213 &key,
8214 image.size(frame_index),
8215 texture,
8216 owner,
8217 )? else {
8218 return Ok(TileWrite::Refused);
8219 };
8220 Ok(match before {
8221 Some(tile) if tile == after => TileWrite::InPlace,
8222 _ => TileWrite::Placed,
8223 })
8224 }
8225
8226 pub fn write_image_tile_metal(
8229 &mut self,
8230 image: &RenderImage,
8231 frame_index: usize,
8232 texture: GpuTextureHandle,
8233 ready: Option<(*mut std::ffi::c_void, u64)>,
8234 owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
8235 ) -> Result<TileWrite> {
8236 let key: AtlasKey = RenderImageParams {
8237 image_id: image.id,
8238 frame_index,
8239 }
8240 .into();
8241 let before = self.sprite_atlas.tile(&key);
8242 let Some(after) =
8243 self.sprite_atlas
8244 .upload_from_metal(&key, image.size(frame_index), texture, ready, owner)?
8245 else {
8246 return Ok(TileWrite::Refused);
8247 };
8248 Ok(match before {
8249 Some(tile) if tile == after => TileWrite::InPlace,
8250 _ => TileWrite::Placed,
8251 })
8252 }
8253
8254 pub fn request_present(&self) {
8261 self.needs_present.set(true);
8262 self.invalidator.wake_platform();
8263 }
8264
8265 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
8267 for frame_index in 0..data.frame_count() {
8268 let params = RenderImageParams {
8269 image_id: data.id,
8270 frame_index,
8271 };
8272
8273 self.sprite_atlas.remove(¶ms.into());
8274 }
8275
8276 Ok(())
8277 }
8278
8279 pub fn sprite_atlas_stats(&self) -> Option<AtlasStats> {
8283 self.sprite_atlas.stats()
8284 }
8285
8286 pub fn has_image_atlas_tile(&self, data: &RenderImage, frame_index: usize) -> bool {
8288 self.sprite_atlas.tile(&RenderImageParams {image_id:data.id,frame_index}.into()).is_some()
8289 }
8290
8291 #[cfg(any(test, feature = "test-support"))]
8293 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
8294 data.frame_count() > 0
8295 && (0..data.frame_count()).all(|frame_index| {
8296 self.sprite_atlas.contains(
8297 &RenderImageParams {
8298 image_id: data.id,
8299 frame_index,
8300 }
8301 .into(),
8302 )
8303 })
8304 }
8305
8306 pub fn vn_enable_retained_layout(&mut self) {
8309 self.layout_engine.as_mut().unwrap().enable_retention();
8310 }
8311
8312 pub fn vn_profile_retained_layout(&mut self, enabled: bool) {
8314 self.layout_engine
8315 .as_mut()
8316 .unwrap()
8317 .profile_retention(enabled);
8318 }
8319
8320 pub fn vn_take_retained_layout_stats(&mut self) -> Option<crate::VnRetainedLayoutStats> {
8322 self.layout_engine.as_mut().unwrap().take_retention_stats()
8323 }
8324
8325 #[must_use]
8331 pub fn request_layout(
8332 &mut self,
8333 style: Style,
8334 children: impl IntoIterator<Item = LayoutId>,
8335 cx: &mut App,
8336 ) -> LayoutId {
8337 self.invalidator.debug_assert_prepaint();
8338
8339 cx.layout_id_buffer.clear();
8340 cx.layout_id_buffer.extend(children);
8341 let rem_size = self.rem_size();
8342 let scale_factor = self.scale_factor();
8343
8344 let scope = self
8345 .layout_engine
8346 .as_ref()
8347 .unwrap()
8348 .retention_enabled()
8349 .then(|| self.element_id_stack.global_id());
8350 let engine = self.layout_engine.as_mut().unwrap();
8351 if let Some(scope) = scope {
8352 engine.request_layout_in_scope(
8353 Some(scope),
8354 style,
8355 rem_size,
8356 scale_factor,
8357 &cx.layout_id_buffer,
8358 )
8359 } else {
8360 engine.request_layout(style, rem_size, scale_factor, &cx.layout_id_buffer)
8361 }
8362 }
8363
8364 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
8373 where
8374 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
8375 + 'static,
8376 {
8377 self.invalidator.debug_assert_prepaint();
8378
8379 let rem_size = self.rem_size();
8380 let scale_factor = self.scale_factor();
8381 let scope = self
8382 .layout_engine
8383 .as_ref()
8384 .unwrap()
8385 .retention_enabled()
8386 .then(|| self.element_id_stack.global_id());
8387 let engine = self.layout_engine.as_mut().unwrap();
8388 if let Some(scope) = scope {
8389 engine.request_measured_layout_in_scope(
8390 Some(scope),
8391 style,
8392 rem_size,
8393 scale_factor,
8394 measure,
8395 )
8396 } else {
8397 engine.request_measured_layout(style, rem_size, scale_factor, measure)
8398 }
8399 }
8400
8401 pub fn compute_layout(
8407 &mut self,
8408 layout_id: LayoutId,
8409 available_space: Size<AvailableSpace>,
8410 cx: &mut App,
8411 ) {
8412 self.invalidator.debug_assert_prepaint();
8413
8414 let mut layout_engine = self.layout_engine.take().unwrap();
8415 layout_engine.compute_layout(layout_id, available_space, self, cx);
8416 self.layout_engine = Some(layout_engine);
8417 }
8418
8419 pub fn layout_is_absolute(&self, layout_id: LayoutId) -> bool {
8422 self.layout_engine
8423 .as_ref()
8424 .is_some_and(|engine| engine.is_absolute(layout_id))
8425 }
8426
8427 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
8432 self.invalidator.debug_assert_prepaint();
8433
8434 let scale_factor = self.scale_factor();
8435 let mut bounds = self
8436 .layout_engine
8437 .as_mut()
8438 .unwrap()
8439 .layout_bounds(layout_id, scale_factor)
8440 .map(Into::into);
8441 let snapped_offset = self.pixel_snap_point(self.element_offset());
8442 bounds.origin += snapped_offset;
8443 bounds
8444 }
8445
8446 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
8452 self.invalidator.debug_assert_prepaint();
8453
8454 let content_mask = self.content_mask();
8455 let id = self.next_hitbox_id;
8456 self.next_hitbox_id = self.next_hitbox_id.next();
8457 let hitbox = Hitbox {
8458 id,
8459 bounds,
8460 content_mask,
8461 behavior,
8462 transformation: self.element_transform,
8466 vn_clip: self.vn_clip_stack.clone(),
8467 };
8468 self.next_frame.hitboxes.push(hitbox.clone());
8469 if self.vn_hitbox_tag != 0 {
8471 self.next_frame
8472 .vn_tagged_hitboxes
8473 .push((self.vn_hitbox_tag, hitbox.clone()));
8474 }
8475 hitbox
8476 }
8477
8478 pub fn set_hitbox_tag(&mut self, tag: u32) -> u32 {
8485 mem::replace(&mut self.vn_hitbox_tag, tag)
8486 }
8487
8488 pub fn with_hitbox_tag<R>(
8499 &mut self,
8500 tag: u32,
8501 f: impl FnOnce(&mut Self) -> R,
8502 ) -> (R, Option<TransformationMatrix>) {
8503 let tag = mem::replace(&mut self.vn_hitbox_tag, tag);
8504 let fresh = mem::replace(&mut self.vn_tag_fresh, true);
8505 let noted = self.vn_tag_transform.take();
8506 let result = f(self);
8507 let own = mem::replace(&mut self.vn_tag_transform, noted);
8508 self.vn_tag_fresh = fresh;
8509 self.vn_hitbox_tag = tag;
8510 (result, own)
8511 }
8512
8513 pub(crate) fn note_tagged_transform(&mut self, own_is_unit: bool) {
8517 if self.vn_tag_fresh {
8518 self.vn_tag_fresh = false;
8519 if !own_is_unit {
8520 self.vn_tag_transform = Some(self.element_transform);
8521 }
8522 }
8523 }
8524
8525 pub fn transformed_bounds(
8530 &self,
8531 matrix: TransformationMatrix,
8532 bounds: Bounds<Pixels>,
8533 ) -> Bounds<Pixels> {
8534 transform_bounds(matrix, bounds, self.scale_factor)
8535 }
8536
8537 pub fn set_tag_every_hitbox(&mut self, on: bool) {
8543 self.vn_tag_every_hitbox = on;
8544 }
8545
8546 pub fn tags_every_hitbox(&self) -> bool {
8548 self.vn_tag_every_hitbox
8549 }
8550
8551 pub fn tagged_hitbox(&self, tag: u32) -> Option<&Hitbox> {
8559 self.rendered_frame
8560 .vn_tagged_hitboxes
8561 .iter()
8562 .find(|(t, hitbox)| *t == tag && hitbox.id != HitboxId::VN_PICK)
8563 .map(|(_, hitbox)| hitbox)
8564 }
8565
8566 pub fn vn_tags_at(&self, position: Point<Pixels>) -> Vec<u32> {
8588 let frame = &self.rendered_frame;
8589 let tagged = &frame.vn_tagged_hitboxes;
8590 let mut out = Vec::new();
8591 let mut visit = |(tag, hitbox): &(u32, Hitbox)| {
8592 if tag & VN_TAG_PASSIVE != 0 || !Frame::box_contains(hitbox, position, self.scale_factor) {
8593 return true;
8594 }
8595 out.push(*tag);
8596 hitbox.behavior != HitboxBehavior::BlockMouse
8597 };
8598 match frame.vn_tagged_paint_order() {
8599 Some(order) => {
8600 for &ix in order.iter().rev() {
8601 if !visit(&tagged[ix as usize]) {
8602 break;
8603 }
8604 }
8605 }
8606 None => {
8607 for entry in tagged.iter().rev() {
8608 if !visit(entry) {
8609 break;
8610 }
8611 }
8612 }
8613 }
8614 out
8615 }
8616
8617 pub fn set_vn_pick_every_box(&mut self, on: bool) {
8625 self.vn_pick_every_box = on;
8626 }
8627
8628 pub fn vn_picks_every_box(&self) -> bool {
8630 self.vn_pick_every_box
8631 }
8632
8633 pub fn vn_insert_pick(&mut self, bounds: Bounds<Pixels>) {
8638 self.invalidator.debug_assert_prepaint();
8639 if self.vn_hitbox_tag == 0 {
8640 return;
8641 }
8642 let hitbox = Hitbox {
8643 id: HitboxId::VN_PICK,
8644 bounds,
8645 content_mask: self.content_mask(),
8646 behavior: HitboxBehavior::Normal,
8647 transformation: self.element_transform,
8648 vn_clip: self.vn_clip_stack.clone(),
8649 };
8650 self.next_frame
8651 .vn_tagged_hitboxes
8652 .push((self.vn_hitbox_tag, hitbox));
8653 }
8654
8655 pub fn set_vn_hit_refiner(&mut self, refiner: Option<VnHitRefiner>) {
8665 self.vn_hit_refiner = refiner;
8666 }
8667
8668 pub fn has_vn_hit_refiner(&self) -> bool {
8670 self.vn_hit_refiner.is_some()
8671 }
8672
8673 pub fn vn_key_event_seq(&self) -> u64 {
8687 self.vn_key_event_seq
8688 }
8689
8690 pub fn vn_pointer_inside(&self) -> bool {
8697 self.pointer_inside
8698 }
8699
8700 pub fn vn_lock_pointer(&mut self, how: VnPointerLock) -> Result<(), crate::PointerLockError> {
8704 let anchor = match self.vn_pointer_lock.take() {
8705 Some((previous, anchor)) => {
8706 if matches!(previous, VnPointerLock::System { .. }) {
8707 self.platform_window.unlock_pointer();
8708 }
8709 anchor
8710 }
8711 None => self.mouse_position,
8712 };
8713 if let VnPointerLock::System { unadjusted } = how {
8714 self.platform_window.lock_pointer(unadjusted)?;
8715 }
8716 self.vn_pointer_lock = Some((how, anchor));
8717 self.vn_raw_mouse_position = None;
8718 Ok(())
8719 }
8720
8721 pub fn vn_unlock_pointer(&mut self) {
8723 if let Some((VnPointerLock::System { .. }, _)) = self.vn_pointer_lock.take() {
8724 self.platform_window.unlock_pointer();
8725 }
8726 self.vn_raw_mouse_position = None;
8727 }
8728
8729 pub fn vn_pointer_locked(&self) -> bool {
8732 match self.vn_pointer_lock {
8733 Some((VnPointerLock::System { .. }, _)) => self.platform_window.is_pointer_locked(),
8734 Some((VnPointerLock::Simulated, _)) => true,
8735 None => false,
8736 }
8737 }
8738
8739 pub fn vn_mouse_movement(&self) -> Point<Pixels> {
8743 self.vn_mouse_movement
8744 }
8745
8746 pub fn vn_pen(&self) -> Option<&crate::PenInput> {
8750 self.vn_pen.as_ref()
8751 }
8752
8753 fn vn_pin_to_pointer_lock(&mut self, mut event: PlatformInput) -> PlatformInput {
8754 let system = matches!(
8755 self.vn_pointer_lock,
8756 Some((VnPointerLock::System { .. }, _))
8757 );
8758 if system && !self.platform_window.is_pointer_locked() {
8759 self.vn_pointer_lock = None;
8760 self.vn_raw_mouse_position = None;
8761 }
8762 if let PlatformInput::MouseMove(mouse_move) = &event {
8763 let previous = self.vn_raw_mouse_position.replace(mouse_move.position);
8764 let motion = system.then(|| self.platform_window.take_pointer_motion());
8765 self.vn_mouse_movement = motion.flatten().unwrap_or_else(|| {
8766 previous.map_or_else(Point::default, |previous| mouse_move.position - previous)
8767 });
8768 }
8769 let Some((_, anchor)) = self.vn_pointer_lock else {
8770 return event;
8771 };
8772 match &mut event {
8773 PlatformInput::MouseMove(e) => e.position = anchor,
8774 PlatformInput::MouseDown(e) => e.position = anchor,
8775 PlatformInput::MouseUp(e) => e.position = anchor,
8776 PlatformInput::Scroll(e) => e.position = anchor,
8777 PlatformInput::MouseExited(e) => e.position = anchor,
8778 _ => {}
8779 }
8780 event
8781 }
8782
8783 pub fn vn_is_dirty(&self) -> bool {
8790 self.invalidator.is_dirty()
8791 }
8792
8793 pub fn vn_restrict_mouse_hit(&mut self, keep: &dyn Fn(u32) -> bool, add: bool) {
8802 let frame = &self.rendered_frame;
8803 let mut tag_of: FxHashMap<HitboxId, u32> = FxHashMap::default();
8804 for (tag, hitbox) in &frame.vn_tagged_hitboxes {
8806 if hitbox.id != HitboxId::VN_PICK {
8807 tag_of.entry(hitbox.id).or_insert(tag & !VN_TAG_PASSIVE);
8808 }
8809 }
8810 let old = mem::take(&mut self.mouse_hit_test);
8811 let mut ids: SmallVec<[HitboxId; 8]> = SmallVec::new();
8812 let mut hover = 0;
8813 for (ix, id) in old.ids.iter().enumerate() {
8814 if tag_of.get(id).is_none_or(|tag| keep(*tag)) {
8815 ids.push(*id);
8816 if ix < old.hover_hitbox_count {
8817 hover += 1;
8818 }
8819 }
8820 }
8821 let all_hovered = old.hover_hitbox_count == old.ids.len();
8824 if add {
8825 for (tag, hitbox) in &frame.vn_tagged_hitboxes {
8826 if hitbox.id != HitboxId::VN_PICK
8827 && keep(tag & !VN_TAG_PASSIVE)
8828 && !ids.contains(&hitbox.id)
8829 {
8830 ids.push(hitbox.id);
8831 }
8832 }
8833 }
8834 if all_hovered {
8835 hover = ids.len();
8836 }
8837 self.mouse_hit_test = HitTest {
8838 ids,
8839 hover_hitbox_count: hover,
8840 };
8841 }
8842
8843 pub fn window_control_area_at(&self, position: Point<Pixels>) -> Option<WindowControlArea> {
8846 for hitbox in self.rendered_frame.topmost_hitboxes() {
8847 if !Frame::box_contains(hitbox, position, self.scale_factor) {
8848 continue;
8849 }
8850 if let Some((area, _)) = self.rendered_frame.window_control_hitboxes.iter()
8851 .find(|(_, control)| control.id == hitbox.id)
8852 {
8853 return Some(*area);
8854 }
8855 if hitbox.behavior == HitboxBehavior::BlockMouse {
8856 break;
8857 }
8858 }
8859 None
8860 }
8861
8862 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
8866 self.invalidator.debug_assert_paint();
8867 self.next_frame.window_control_hitboxes.push((area, hitbox));
8868 }
8869
8870 pub fn set_key_context(&mut self, context: KeyContext) {
8875 self.invalidator.debug_assert_paint();
8876 self.next_frame.dispatch_tree.set_key_context(context);
8877 }
8878
8879 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
8884 self.invalidator.debug_assert_prepaint();
8885 if focus_handle.is_focused(self) {
8886 self.next_frame.focus = Some(focus_handle.id);
8887 }
8888 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
8889 }
8890
8891 pub fn set_view_id(&mut self, view_id: EntityId) {
8897 self.invalidator.debug_assert_prepaint();
8898 self.next_frame.dispatch_tree.set_view_id(view_id);
8899 }
8900
8901 pub fn current_view(&self) -> EntityId {
8903 self.invalidator.debug_assert_paint_or_prepaint();
8904 self.rendered_entity_stack.last().copied().unwrap()
8905 }
8906
8907 #[inline]
8908 pub(crate) fn with_rendered_view<R>(
8909 &mut self,
8910 id: EntityId,
8911 f: impl FnOnce(&mut Self) -> R,
8912 ) -> R {
8913 self.rendered_entity_stack.push(id);
8914 let result = f(self);
8915 self.rendered_entity_stack.pop();
8916 result
8917 }
8918
8919 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
8921 where
8922 F: FnOnce(&mut Self) -> R,
8923 {
8924 if let Some(image_cache) = image_cache {
8925 self.image_cache_stack.push(image_cache);
8926 let result = f(self);
8927 self.image_cache_stack.pop();
8928 result
8929 } else {
8930 f(self)
8931 }
8932 }
8933
8934 pub fn handle_input(
8943 &mut self,
8944 focus_handle: &FocusHandle,
8945 input_handler: impl InputHandler,
8946 cx: &App,
8947 ) {
8948 self.invalidator.debug_assert_paint();
8949
8950 if focus_handle.is_focused(self) {
8951 let cx = self.to_async(cx);
8952 self.next_frame.input_handlers.push(Some(
8953 PlatformInputHandler::new(cx, Box::new(input_handler)).with_focus(focus_handle.id),
8954 ));
8955 }
8956 }
8957
8958 pub fn notify_text_input_changed(&self, focus_handle: &FocusHandle) {
8963 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
8964 self.platform_window
8965 .text_input_state_changed(TextInputStateChange::ContentChanged);
8966 }
8967 }
8968
8969 pub fn notify_text_selection_changed(&self, focus_handle: &FocusHandle) {
8974 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
8975 self.platform_window
8976 .text_input_state_changed(TextInputStateChange::SelectionChanged);
8977 }
8978 }
8979
8980 fn apply_text_input_configuration(&mut self, cx: &mut App) {
8985 let configuration = match self.platform_window.take_input_handler() {
8986 Some(mut input_handler) => {
8987 let configuration = input_handler.text_input_configuration(self, cx);
8988 self.platform_window.set_input_handler(input_handler);
8989 configuration
8990 }
8991 None => TextInputConfiguration::default(),
8992 };
8993 if self.last_text_input_configuration.as_ref() != Some(&configuration) {
8994 self.platform_window
8995 .set_text_input_configuration(configuration.clone());
8996 self.last_text_input_configuration = Some(configuration);
8997 }
8998 }
8999
9000 pub fn on_mouse_event<Event: MouseEvent>(
9006 &mut self,
9007 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
9008 ) {
9009 self.invalidator.debug_assert_paint();
9010
9011 self.next_frame.mouse_listeners.push(Some(Box::new(
9012 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
9013 if let Some(event) = event.downcast_ref() {
9014 listener(event, phase, window, cx)
9015 }
9016 },
9017 )));
9018 }
9019
9020 pub fn on_key_event<Event: KeyEvent>(
9029 &mut self,
9030 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
9031 ) {
9032 self.invalidator.debug_assert_paint();
9033
9034 self.next_frame.dispatch_tree.on_key_event(Rc::new(
9035 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
9036 if let Some(event) = event.downcast_ref::<Event>() {
9037 listener(event, phase, window, cx)
9038 }
9039 },
9040 ));
9041 }
9042
9043 pub fn on_modifiers_changed(
9050 &mut self,
9051 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
9052 ) {
9053 self.invalidator.debug_assert_paint();
9054
9055 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
9056 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
9057 listener(event, window, cx)
9058 },
9059 ));
9060 }
9061
9062 pub fn on_focus_in(
9066 &mut self,
9067 handle: &FocusHandle,
9068 cx: &mut App,
9069 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
9070 ) -> Subscription {
9071 let focus_id = handle.id;
9072 let (subscription, activate) =
9073 self.new_focus_listener(Box::new(move |event, window, cx| {
9074 if event.is_focus_in(focus_id) {
9075 listener(window, cx);
9076 }
9077 true
9078 }));
9079 cx.defer(move |_| activate());
9080 subscription
9081 }
9082
9083 pub fn on_focus_out(
9086 &mut self,
9087 handle: &FocusHandle,
9088 cx: &mut App,
9089 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
9090 ) -> Subscription {
9091 let focus_id = handle.id;
9092 let (subscription, activate) =
9093 self.new_focus_listener(Box::new(move |event, window, cx| {
9094 if let Some(blurred_id) = event.previous_focus_path.last().copied()
9095 && event.is_focus_out(focus_id)
9096 {
9097 let event = FocusOutEvent {
9098 blurred: WeakFocusHandle {
9099 id: blurred_id,
9100 handles: Arc::downgrade(&cx.focus_handles),
9101 },
9102 };
9103 listener(event, window, cx)
9104 }
9105 true
9106 }));
9107 cx.defer(move |_| activate());
9108 subscription
9109 }
9110
9111 fn reset_cursor_style(&self, cx: &mut App) {
9112 if self.is_window_hovered() {
9114 let style = cx
9116 .active_drag_cursor_style()
9117 .or_else(|| self.rendered_frame.cursor_style(self))
9118 .unwrap_or(CursorStyle::Arrow);
9119 cx.platform.set_cursor_style(style);
9120 }
9121 }
9122
9123 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
9126 let keystroke = keystroke.with_simulated_ime();
9127 let result = self.dispatch_event(
9128 PlatformInput::KeyDown(KeyDownEvent {
9129 keystroke: keystroke.clone(),
9130 is_held: false,
9131 prefer_character_input: false,
9132 }),
9133 cx,
9134 );
9135 if !result.propagate {
9136 return true;
9137 }
9138
9139 if let Some(input) = keystroke.key_char
9140 && let Some(mut input_handler) = self.platform_window.take_input_handler()
9141 {
9142 input_handler.dispatch_input(&input, self, cx);
9143 self.platform_window.set_input_handler(input_handler);
9144 return true;
9145 }
9146
9147 false
9148 }
9149
9150 pub fn keystroke_text_for(&self, action: &dyn Action, cx: &App) -> String {
9153 self.highest_precedence_binding_for_action(action)
9154 .map(|binding| {
9155 binding
9156 .keystrokes()
9157 .iter()
9158 .map(|keystroke| keystroke.display(cx.platform_info().os).to_string())
9159 .collect::<Vec<_>>()
9160 .join(" ")
9161 })
9162 .unwrap_or_else(|| action.name().to_string())
9163 }
9164
9165 pub fn set_input_interceptor(
9169 &mut self,
9170 interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
9171 ) {
9172 self.input_interceptor = interceptor;
9173 }
9174
9175 #[profiling::function]
9177 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
9178 let event = match event {
9179 PlatformInput::Pen(pen) => {
9180 let (mouse, pen) = pen.into_mouse();
9181 self.vn_pen = Some(pen);
9182 mouse
9183 }
9184 PlatformInput::MouseMove(_)
9185 | PlatformInput::MouseDown(_)
9186 | PlatformInput::MouseUp(_)
9187 | PlatformInput::Scroll(_) => {
9188 self.vn_pen = None;
9189 event
9190 }
9191 event => event,
9192 };
9193 if let Some(intercept) = self.input_interceptor.clone() {
9197 if intercept(&event, self, cx) {
9198 return DispatchEventResult { propagate: false, default_prevented: true };
9199 }
9200 }
9201 #[cfg(feature = "profiler")]
9202 self.window_profiler.begin_input(event.kind_name());
9203 let update_count_before = self.invalidator.update_count();
9204 let old_modality = self.last_input_modality;
9208 self.last_input_modality = match &event {
9209 PlatformInput::KeyDown(_) => InputModality::Keyboard,
9210 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
9211 PlatformInput::Touch(_) => InputModality::Touch,
9212 _ => self.last_input_modality,
9213 };
9214 if self.last_input_modality != old_modality {
9215 self.refresh();
9216 }
9217 let was_inside = self.pointer_inside;
9218 let pointer_moved = matches!(event, PlatformInput::MouseMove(_));
9219 let pointer_leaves = match &event {
9224 PlatformInput::MouseMove(_)
9225 | PlatformInput::MouseDown(_)
9226 | PlatformInput::MouseUp(_)
9227 | PlatformInput::MousePressure(_)
9228 | PlatformInput::Scroll(_)
9229 | PlatformInput::Pinch(_)
9230 | PlatformInput::LongPress(_)
9231 | PlatformInput::TouchDrag(_)
9232 | PlatformInput::BackGesture(_)
9233 | PlatformInput::Touch(_)
9234 | PlatformInput::Pen(_) => {
9235 self.pointer_inside = true;
9236 false
9237 }
9238 PlatformInput::FileDrop(FileDropEvent::Exited) | PlatformInput::MouseExited(_) => true,
9239 PlatformInput::FileDrop(_) => {
9240 self.pointer_inside = true;
9241 false
9242 }
9243 PlatformInput::KeyDown(_)
9244 | PlatformInput::KeyUp(_)
9245 | PlatformInput::ModifiersChanged(_) => false,
9246 };
9247
9248 cx.propagate_event = true;
9250 self.default_prevented = false;
9252
9253 let event = self.vn_pin_to_pointer_lock(event);
9254 let event = match event {
9255 PlatformInput::MouseMove(mouse_move) => {
9258 self.mouse_position = mouse_move.position;
9259 self.modifiers = mouse_move.modifiers;
9260 PlatformInput::MouseMove(mouse_move)
9261 }
9262 PlatformInput::MouseDown(mouse_down) => {
9263 self.mouse_position = mouse_down.position;
9264 self.modifiers = mouse_down.modifiers;
9265 PlatformInput::MouseDown(mouse_down)
9266 }
9267 PlatformInput::MouseUp(mouse_up) => {
9268 self.mouse_position = mouse_up.position;
9269 self.modifiers = mouse_up.modifiers;
9270 PlatformInput::MouseUp(mouse_up)
9271 }
9272 PlatformInput::MousePressure(mouse_pressure) => {
9273 PlatformInput::MousePressure(mouse_pressure)
9274 }
9275 PlatformInput::MouseExited(mouse_exited) => {
9276 self.modifiers = mouse_exited.modifiers;
9277 PlatformInput::MouseExited(mouse_exited)
9278 }
9279 PlatformInput::ModifiersChanged(modifiers_changed) => {
9280 self.modifiers = modifiers_changed.modifiers;
9281 self.capslock = modifiers_changed.capslock;
9282 PlatformInput::ModifiersChanged(modifiers_changed)
9283 }
9284 PlatformInput::Scroll(scroll_wheel) => {
9285 self.mouse_position = scroll_wheel.position;
9286 self.modifiers = scroll_wheel.modifiers;
9287 PlatformInput::Scroll(scroll_wheel)
9288 }
9289 PlatformInput::Pinch(pinch) => {
9290 self.mouse_position = pinch.position;
9291 self.modifiers = pinch.modifiers;
9292 PlatformInput::Pinch(pinch)
9293 }
9294 PlatformInput::FileDrop(file_drop) => match file_drop {
9297 FileDropEvent::Entered { position, paths } => {
9298 self.mouse_position = position;
9299 let source_window = self.handle.window_id();
9300 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
9301 cx.active_drag = Some(AnyDrag {
9302 value: Arc::new(paths.clone()),
9303 view: cx.new(|_| paths).into(),
9304 cursor_offset: position,
9305 cursor_style: None,
9306 external_payload_source: None,
9307 });
9308 }
9309 PlatformInput::MouseMove(MouseMoveEvent {
9310 position,
9311 pressed_button: Some(MouseButton::Left),
9312 modifiers: Modifiers::default(),
9313 })
9314 }
9315 FileDropEvent::Pending { position } => {
9316 self.mouse_position = position;
9317 PlatformInput::MouseMove(MouseMoveEvent {
9318 position,
9319 pressed_button: Some(MouseButton::Left),
9320 modifiers: Modifiers::default(),
9321 })
9322 }
9323 FileDropEvent::Submit { position } => {
9324 cx.activate(true);
9325 self.mouse_position = position;
9326 PlatformInput::MouseUp(MouseUpEvent {
9327 button: MouseButton::Left,
9328 position,
9329 modifiers: Modifiers::default(),
9330 click_count: 1,
9331 })
9332 }
9333 FileDropEvent::Exited => {
9334 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
9335 cx.active_drag.take();
9336 }
9337 self.refresh();
9338 PlatformInput::FileDrop(FileDropEvent::Exited)
9339 }
9340 FileDropEvent::Ended => {
9341 cx.end_platform_drag(self.handle.window_id());
9342 self.refresh();
9343 PlatformInput::FileDrop(FileDropEvent::Ended)
9344 }
9345 },
9346 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
9347 PlatformInput::Pen(pen) => PlatformInput::Pen(pen),
9348 PlatformInput::LongPress(long_press) => {
9349 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
9350 long_press.start_position
9351 } else {
9352 long_press.position
9353 };
9354 if long_press.phase == crate::TouchPhase::Started {
9355 self.long_press_capture = None;
9356 }
9357 PlatformInput::LongPress(long_press)
9358 }
9359 PlatformInput::TouchDrag(touch_drag) => {
9360 self.mouse_position = touch_drag.start_position;
9361 PlatformInput::TouchDrag(touch_drag)
9362 }
9363 PlatformInput::BackGesture(back) => {
9364 self.mouse_position = back.start_position;
9365 PlatformInput::BackGesture(back)
9366 }
9367 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
9368 };
9369
9370 if let Some(any_mouse_event) = event.mouse_event() {
9371 self.dispatch_mouse_event(any_mouse_event, cx);
9372 } else if let Some(any_key_event) = event.keyboard_event() {
9373 self.dispatch_key_event(any_key_event, cx);
9374 } else if let Some(touch_event) = event.touch_event() {
9375 self.dispatch_touch_event(touch_event, cx);
9376 }
9377 if let PlatformInput::LongPress(long_press) = &event {
9378 match long_press.phase {
9379 crate::TouchPhase::Started if !self.default_prevented => {
9380 self.long_press_capture = None;
9381 }
9382 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
9383 self.long_press_capture = None;
9384 }
9385 crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
9386 }
9387 }
9388
9389 self.promote_external_drag_to_platform(&event, cx);
9392
9393 if pointer_leaves && std::mem::replace(&mut self.pointer_inside, false) {
9396 self.refresh();
9397 }
9398 self.vn_effect_pointer
9399 .update(was_inside, self.pointer_inside, pointer_moved, cx);
9400
9401 let caused_invalidation = self.invalidator.update_count() > update_count_before;
9402 if caused_invalidation {
9403 self.input_rate_tracker.borrow_mut().record_input();
9404 }
9405 #[cfg(feature = "profiler")]
9406 self.window_profiler.end_input(caused_invalidation);
9407
9408 DispatchEventResult {
9409 propagate: cx.propagate_event,
9410 default_prevented: self.default_prevented,
9411 }
9412 }
9413
9414 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
9415 let PlatformInput::MouseMove(mouse_move) = event else {
9416 return;
9417 };
9418 if mouse_move.pressed_button != Some(MouseButton::Left) {
9419 return;
9420 }
9421 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
9422 return;
9423 }
9424 if !self.platform_window.can_start_external_drag() {
9425 return;
9426 }
9427 let Some(payload_source) = cx
9428 .active_drag
9429 .as_mut()
9430 .and_then(|drag| drag.external_payload_source.take())
9431 else {
9432 return;
9433 };
9434 let Some(payload) = payload_source(self, cx) else {
9435 return;
9436 };
9437 if self.platform_window.start_external_drag(&payload)
9438 && cx.hand_active_drag_to_platform(self.handle.window_id())
9439 {
9440 self.refresh();
9441 }
9442 }
9443
9444 pub fn touch_prediction_enabled(&self) -> bool {
9448 self.touch_prediction_enabled
9449 }
9450
9451 pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
9455 self.touch_prediction_enabled = enabled;
9456 }
9457
9458 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
9462 let mut event = event.clone();
9463 if !self.touch_prediction_enabled {
9464 event.predicted_position = None;
9465 }
9466 let recognized_gestures = self.touch_gestures.handle_event(&event);
9467 if event.phase == crate::TouchPhase::Started
9468 && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
9469 {
9470 self.dispatch_recognized_touch_gesture(touch_drag, cx);
9471 }
9472 if event.phase == crate::TouchPhase::Started
9473 && self.touch_gestures.pending_long_press().is_some()
9474 {
9475 self.long_press_capture = None;
9476 }
9477 let mut tapped = false;
9478 for gesture in recognized_gestures {
9479 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
9480 self.dispatch_recognized_touch_gesture(gesture, cx);
9481 }
9482 if event.phase == crate::TouchPhase::Started {
9483 self.schedule_long_press_timer(cx);
9484 } else if self.touch_gestures.pending_long_press().is_none() {
9485 self.long_press_timer.take();
9486 }
9487 if tapped && self.invalidator.is_dirty() {
9493 self.draw(cx).clear(cx);
9494 }
9495 if self.touch_gestures.has_momentum() {
9496 self.schedule_touch_momentum_tick();
9497 }
9498 }
9499
9500 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
9501 match gesture {
9502 RecognizedTouchGesture::Scroll(scroll_wheel) => {
9503 self.mouse_position = scroll_wheel.position;
9504 cx.propagate_event = true;
9505 self.dispatch_mouse_event(&scroll_wheel, cx);
9506 }
9507 RecognizedTouchGesture::Tap { down, up } => {
9508 self.mouse_position = up.position;
9509 cx.propagate_event = true;
9510 self.dispatch_mouse_event(&down, cx);
9511 cx.propagate_event = true;
9512 self.dispatch_mouse_event(&up, cx);
9513 }
9514 RecognizedTouchGesture::TouchDrag(touch_drag) => {
9515 self.mouse_position = touch_drag.start_position;
9516 cx.propagate_event = true;
9517 self.default_prevented = false;
9518 let started = touch_drag.phase == crate::TouchPhase::Started;
9519 self.dispatch_mouse_event(&touch_drag, cx);
9520 if started {
9521 self.touch_gestures
9522 .resolve_touch_drag(self.default_prevented);
9523 }
9524 }
9525 RecognizedTouchGesture::LongPress(long_press) => {
9526 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
9527 long_press.start_position
9528 } else {
9529 long_press.position
9530 };
9531 cx.propagate_event = true;
9532 self.default_prevented = false;
9533 let started = long_press.phase == crate::TouchPhase::Started;
9534 let ended = matches!(
9535 long_press.phase,
9536 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
9537 );
9538 self.dispatch_mouse_event(&long_press, cx);
9539 if started {
9540 let claimed = self.default_prevented;
9541 self.touch_gestures.resolve_long_press(claimed);
9542 if !claimed {
9543 self.long_press_capture = None;
9544 }
9545 }
9546 if ended {
9547 self.long_press_capture = None;
9548 }
9549 }
9550 }
9551 }
9552
9553 fn schedule_long_press_timer(&mut self, cx: &mut App) {
9554 self.long_press_timer.take();
9555 let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
9556 return;
9557 };
9558 self.long_press_timer = Some(self.spawn(cx, async move |cx| {
9559 cx.background_executor.timer(duration).await;
9560 cx.update(move |window, cx| {
9561 window.long_press_timer.take();
9562 if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
9563 window.dispatch_recognized_touch_gesture(gesture, cx);
9564 }
9565 })
9566 .with_context(|| {
9567 format!(
9568 "handling long-press timer for window {:?}",
9569 cx.window_handle().window_id()
9570 )
9571 })
9572 .log_err();
9573 }));
9574 }
9575
9576 fn schedule_touch_momentum_tick(&mut self) {
9577 self.on_next_frame(|window, cx| {
9578 if let Some(gesture) = window.touch_gestures.tick_momentum() {
9579 window.dispatch_recognized_touch_gesture(gesture, cx);
9580 }
9581 if window.touch_gestures.has_momentum() {
9582 window.schedule_touch_momentum_tick();
9583 }
9584 });
9585 }
9586
9587 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
9588 self.mouse_hit_test = self.rendered_frame.hit_test(self.mouse_position(), self.scale_factor);
9589
9590 if let Some(refiner) = self.vn_hit_refiner.clone() {
9593 let kind = if event.is::<crate::MouseDownEvent>() {
9594 Some(VnHitKind::Down)
9595 } else if event.is::<MouseUpEvent>() {
9596 Some(VnHitKind::Up)
9597 } else if event.is::<crate::ScrollEvent>() {
9598 Some(VnHitKind::Scroll)
9599 } else {
9600 None
9601 };
9602 if let Some(kind) = kind {
9603 let position = self.mouse_position();
9604 refiner(kind, position, self, cx);
9605 }
9606 }
9607
9608 #[cfg(any(feature = "inspector", debug_assertions))]
9609 if self.is_inspector_picking(cx) {
9610 self.reset_cursor_style(cx);
9611 self.handle_inspector_mouse_event(event, cx);
9612 return;
9614 }
9615
9616 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
9617
9618 for listener in &mut mouse_listeners {
9621 let listener = listener.as_mut().unwrap();
9622 listener(event, DispatchPhase::Capture, self, cx);
9623 if !cx.propagate_event {
9624 break;
9625 }
9626 }
9627
9628 if cx.propagate_event {
9630 for listener in mouse_listeners.iter_mut().rev() {
9631 let listener = listener.as_mut().unwrap();
9632 listener(event, DispatchPhase::Bubble, self, cx);
9633 if !cx.propagate_event {
9634 break;
9635 }
9636 }
9637 }
9638
9639 self.rendered_frame.mouse_listeners = mouse_listeners;
9640
9641 if cx.has_active_drag() {
9642 if event.is::<MouseMoveEvent>() {
9643 self.refresh();
9646 } else if event.is::<MouseUpEvent>() {
9647 cx.active_drag = None;
9650 self.refresh();
9651 }
9652 }
9653
9654 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
9656 self.captured_hitbox = None;
9657 }
9658
9659 self.reset_cursor_style(cx);
9662 }
9663
9664 fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
9667 let prefer_character_input = event
9668 .downcast_ref::<KeyDownEvent>()
9669 .is_some_and(|key_down_event| key_down_event.prefer_character_input);
9670 if !prefer_character_input {
9671 return InputPreference::KeyBindings;
9672 }
9673 let Some(mut input_handler) = self.platform_window.take_input_handler() else {
9674 return InputPreference::KeyBindings;
9675 };
9676 let accepts_text_input = input_handler.accepts_text_input(self, cx);
9677 self.platform_window.set_input_handler(input_handler);
9678 if accepts_text_input {
9679 InputPreference::CharacterInput
9680 } else {
9681 InputPreference::KeyBindings
9682 }
9683 }
9684
9685 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
9686 if self.invalidator.is_dirty() {
9687 self.draw(cx).clear(cx);
9688 }
9689 self.vn_key_event_seq = self.vn_key_event_seq.wrapping_add(1);
9691
9692 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
9693 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
9694
9695 let mut keystroke: Option<Keystroke> = None;
9696
9697 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
9698 if event.modifiers.number_of_modifiers() == 0
9699 && self.pending_modifier.modifiers.number_of_modifiers() == 1
9700 && !self.pending_modifier.saw_other_input
9701 {
9702 let key = match self.pending_modifier.modifiers {
9703 modifiers if modifiers.shift => Some("shift"),
9704 modifiers if modifiers.control => Some("control"),
9705 modifiers if modifiers.alt => Some("alt"),
9706 modifiers if modifiers.platform => Some("platform"),
9707 modifiers if modifiers.function => Some("function"),
9708 _ => None,
9709 };
9710 if let Some(key) = key {
9711 keystroke = Some(Keystroke {
9712 key: key.to_string(),
9713 key_char: None,
9714 modifiers: Modifiers::default(),
9715 });
9716 }
9717 }
9718
9719 if self.pending_modifier.modifiers.number_of_modifiers() == 0
9720 && event.modifiers.number_of_modifiers() == 1
9721 {
9722 self.pending_modifier.saw_other_input = false
9723 } else if event.modifiers.number_of_modifiers() > 1 {
9724 self.pending_modifier.saw_other_input = true
9725 }
9726 self.pending_modifier.modifiers = event.modifiers
9727 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
9728 self.pending_modifier.saw_other_input = true;
9729 keystroke = Some(key_down_event.keystroke.clone());
9730 if key_down_event.keystroke.key_char.is_some()
9731 && matches!(
9732 cx.cursor_hide_mode,
9733 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
9734 )
9735 {
9736 cx.platform.hide_cursor_until_mouse_moves();
9737 }
9738 }
9739
9740 let Some(keystroke) = keystroke else {
9741 self.finish_dispatch_key_event(
9742 event,
9743 None,
9744 InputPreference::KeyBindings,
9745 dispatch_path,
9746 self.context_stack(),
9747 cx,
9748 );
9749 return;
9750 };
9751
9752 let input_preference = self.input_preference(event, cx);
9753
9754 cx.propagate_event = true;
9755 self.dispatch_keystroke_interceptors(
9756 &keystroke,
9757 input_preference,
9758 self.context_stack(),
9759 cx,
9760 );
9761 if !cx.propagate_event {
9762 self.finish_dispatch_key_event(
9763 event,
9764 Some(&keystroke),
9765 input_preference,
9766 dispatch_path,
9767 self.context_stack(),
9768 cx,
9769 );
9770 return;
9771 }
9772
9773 let mut currently_pending = self.pending_input.take().unwrap_or_default();
9774 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
9775 currently_pending = PendingInput::default();
9776 }
9777
9778 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
9779 currently_pending.keystrokes,
9780 keystroke.clone(),
9781 &dispatch_path,
9782 );
9783
9784 if !match_result.to_replay.is_empty() {
9785 self.replay_pending_input(match_result.to_replay, cx);
9786 cx.propagate_event = true;
9787 }
9788
9789 if !match_result.pending.is_empty() {
9790 let previous_timeout = currently_pending.timeout.take();
9791 currently_pending.keystrokes = match_result.pending;
9792 currently_pending.focus = self.focus;
9793
9794 let text_input_requires_timeout = event
9795 .downcast_ref::<KeyDownEvent>()
9796 .filter(|key_down| key_down.keystroke.key_char.is_some())
9797 .and_then(|_| self.platform_window.take_input_handler())
9798 .map_or(false, |mut input_handler| {
9799 let accepts = input_handler.accepts_text_input(self, cx);
9800 self.platform_window.set_input_handler(input_handler);
9801 accepts
9802 });
9803
9804 let standalone_modifier = matches!(currently_pending.keystrokes.as_slice(), [keystroke] if keystroke.is_modifier_key());
9805 let needs_timeout = previous_timeout.is_some()
9806 || match_result.pending_has_binding
9807 || text_input_requires_timeout
9808 || standalone_modifier;
9809 currently_pending.timeout = if needs_timeout {
9810 match previous_timeout {
9811 Some(mut timeout) if timeout.is_paused() => {
9812 timeout.reset_duration(PENDING_INPUT_TIMEOUT);
9813 Some(timeout)
9814 }
9815 previous_timeout => {
9816 drop(previous_timeout);
9817 Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
9818 }
9819 }
9820 } else {
9821 None
9822 };
9823 self.pending_input = Some(currently_pending);
9824 self.pending_input_changed(cx);
9825 cx.propagate_event = false;
9826 return;
9827 }
9828
9829 let input_preference = self.input_preference(event, cx);
9831 if input_preference == InputPreference::KeyBindings {
9832 for binding in match_result.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 &keystroke,
9837 input_preference,
9838 Some(binding.action.as_ref()),
9839 match_result.context_stack,
9840 cx,
9841 );
9842 self.pending_input_changed(cx);
9843 return;
9844 }
9845 }
9846 }
9847
9848 self.finish_dispatch_key_event(
9849 event,
9850 Some(&keystroke),
9851 input_preference,
9852 dispatch_path,
9853 match_result.context_stack,
9854 cx,
9855 );
9856 self.pending_input_changed(cx);
9857 }
9858
9859 fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
9860 let (started_at, task) = self.start_pending_input_timeout(duration, cx);
9861 PendingInputTimeout {
9862 duration,
9863 remaining: duration,
9864 state: PendingInputTimeoutState::Running { started_at, task },
9865 }
9866 }
9867
9868 fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
9869 let started_at = cx.background_executor().now();
9870 let task = self.spawn(cx, async move |cx| {
9871 cx.background_executor.timer(remaining).await;
9872 cx.update(move |window, cx| {
9873 let Some(currently_pending) = window
9874 .pending_input
9875 .take()
9876 .filter(|pending| pending.focus == window.focus)
9877 else {
9878 return;
9879 };
9880
9881 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
9882 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
9883
9884 let to_replay = window
9885 .rendered_frame
9886 .dispatch_tree
9887 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
9888
9889 window.pending_input_changed(cx);
9890 window.replay_pending_input(to_replay, cx)
9891 })
9892 .with_context(|| {
9893 format!(
9894 "handling pending input timeout for window {:?}",
9895 cx.window_handle().window_id()
9896 )
9897 })
9898 .log_err();
9899 });
9900 (started_at, task)
9901 }
9902
9903 fn finish_dispatch_key_event(
9904 &mut self,
9905 event: &dyn Any,
9906 recognized_keystroke: Option<&Keystroke>,
9907 input_preference: InputPreference,
9908 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
9909 context_stack: Vec<KeyContext>,
9910 cx: &mut App,
9911 ) {
9912 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
9913 if !cx.propagate_event {
9914 return;
9915 }
9916
9917 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
9918 if !cx.propagate_event {
9919 return;
9920 }
9921
9922 if let Some(keystroke) = recognized_keystroke {
9923 self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
9924 }
9925 }
9926
9927 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
9928 self.pending_input_observers
9929 .clone()
9930 .retain(|callback| callback(self, cx));
9931 }
9932
9933 fn defer_pending_input_changed(&self, cx: &mut App) {
9934 let window_handle = self.handle;
9937 cx.defer(move |cx| {
9938 window_handle
9939 .update(cx, |_, window, cx| {
9940 window.pending_input_changed(cx);
9941 })
9942 .ok();
9943 });
9944 }
9945
9946 fn dispatch_key_down_up_event(
9947 &mut self,
9948 event: &dyn Any,
9949 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
9950 cx: &mut App,
9951 ) {
9952 for node_id in dispatch_path {
9954 let node = self.rendered_frame.dispatch_tree.node(*node_id);
9955
9956 for key_listener in node.key_listeners.clone() {
9957 key_listener(event, DispatchPhase::Capture, self, cx);
9958 if !cx.propagate_event {
9959 return;
9960 }
9961 }
9962 }
9963
9964 for node_id in dispatch_path.iter().rev() {
9966 let node = self.rendered_frame.dispatch_tree.node(*node_id);
9968 for key_listener in node.key_listeners.clone() {
9969 key_listener(event, DispatchPhase::Bubble, self, cx);
9970 if !cx.propagate_event {
9971 return;
9972 }
9973 }
9974 }
9975 }
9976
9977 fn dispatch_modifiers_changed_event(
9978 &mut self,
9979 event: &dyn Any,
9980 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
9981 cx: &mut App,
9982 ) {
9983 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
9984 return;
9985 };
9986 for node_id in dispatch_path.iter().rev() {
9987 let node = self.rendered_frame.dispatch_tree.node(*node_id);
9988 for listener in node.modifiers_changed_listeners.clone() {
9989 listener(event, self, cx);
9990 if !cx.propagate_event {
9991 return;
9992 }
9993 }
9994 }
9995 }
9996
9997 pub fn has_pending_keystrokes(&self) -> bool {
9999 self.pending_input().is_some()
10000 }
10001
10002 #[cfg(test)]
10003 pub(crate) fn pending_input_is_none(&self) -> bool {
10004 self.pending_input.is_none()
10005 }
10006
10007 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
10008 if self.pending_input.take().is_some() {
10009 self.defer_pending_input_changed(cx);
10010 }
10011 }
10012
10013 pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
10016 self.pending_input
10017 .as_ref()
10018 .filter(|pending_input| pending_input.focus == self.focus)
10019 .map(|pending_input| PendingInputStatus {
10020 keystrokes: pending_input.keystrokes.as_slice(),
10021 timeout: pending_input
10022 .timeout
10023 .as_ref()
10024 .map(PendingInputTimeout::status),
10025 })
10026 }
10027
10028 pub fn set_pending_input_timeout_paused<T: 'static>(
10033 &mut self,
10034 owner: &Entity<T>,
10035 paused: bool,
10036 cx: &mut App,
10037 ) -> bool {
10038 let owner_id = owner.entity_id();
10039 if !paused {
10040 return self.resume_pending_input_timeout(owner_id, cx);
10041 }
10042
10043 let timeout = self
10044 .pending_input
10045 .as_ref()
10046 .filter(|pending_input| pending_input.focus == self.focus)
10047 .and_then(|pending_input| pending_input.timeout.as_ref());
10048 let Some(timeout) = timeout else {
10049 return false;
10050 };
10051 if timeout.is_paused() {
10052 return false;
10053 }
10054
10055 let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
10056 window.resume_pending_input_timeout(owner_id, cx);
10057 });
10058 let now = cx.background_executor().now();
10059 let changed = self
10060 .pending_input
10061 .as_mut()
10062 .filter(|pending_input| pending_input.focus == self.focus)
10063 .and_then(|pending_input| pending_input.timeout.as_mut())
10064 .is_some_and(|timeout| {
10065 timeout.pause(
10066 PendingInputTimeoutPause {
10067 owner_id,
10068 _release_subscription: release_subscription,
10069 },
10070 now,
10071 )
10072 });
10073
10074 if changed {
10075 self.defer_pending_input_changed(cx);
10076 }
10077 changed
10078 }
10079
10080 fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
10081 let Some(remaining) = self
10082 .pending_input
10083 .as_ref()
10084 .and_then(|pending_input| pending_input.timeout.as_ref())
10085 .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
10086 .map(|timeout| timeout.remaining)
10087 else {
10088 return false;
10089 };
10090
10091 let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
10092 let changed = self
10093 .pending_input
10094 .as_mut()
10095 .and_then(|pending_input| pending_input.timeout.as_mut())
10096 .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
10097
10098 if changed {
10099 self.defer_pending_input_changed(cx);
10100 }
10101 changed
10102 }
10103
10104 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
10106 self.pending_input()
10107 .map(|pending_input| pending_input.keystrokes())
10108 }
10109
10110 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
10111 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10112 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
10113
10114 'replay: for replay in replays {
10115 let event = KeyDownEvent {
10116 keystroke: replay.keystroke.clone(),
10117 is_held: false,
10118 prefer_character_input: true,
10119 };
10120
10121 cx.propagate_event = true;
10122 for binding in replay.bindings {
10123 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
10124 if !cx.propagate_event {
10125 self.dispatch_keystroke_observers(
10126 &replay.keystroke,
10127 InputPreference::KeyBindings,
10128 Some(binding.action.as_ref()),
10129 Vec::default(),
10130 cx,
10131 );
10132 continue 'replay;
10133 }
10134 }
10135
10136 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
10137 if !cx.propagate_event {
10138 continue 'replay;
10139 }
10140 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
10141 && let Some(mut input_handler) = self.platform_window.take_input_handler()
10142 {
10143 input_handler.dispatch_input(&input, self, cx);
10144 self.platform_window.set_input_handler(input_handler)
10145 }
10146 }
10147 }
10148
10149 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
10150 focus_id
10151 .and_then(|focus_id| {
10152 self.rendered_frame
10153 .dispatch_tree
10154 .focusable_node_id(focus_id)
10155 })
10156 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
10157 }
10158
10159 fn dispatch_action_on_node(
10160 &mut self,
10161 node_id: DispatchNodeId,
10162 action: &dyn Action,
10163 cx: &mut App,
10164 ) {
10165 self.dispatch_action_on_node_inner(node_id, action, cx);
10166
10167 if !cx.propagate_event
10168 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
10169 && self.last_input_was_keyboard()
10170 {
10171 cx.platform.hide_cursor_until_mouse_moves();
10172 }
10173 }
10174
10175 fn dispatch_action_on_node_inner(
10176 &mut self,
10177 node_id: DispatchNodeId,
10178 action: &dyn Action,
10179 cx: &mut App,
10180 ) {
10181 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
10182
10183 cx.propagate_event = true;
10185 if let Some(mut global_listeners) = cx
10186 .global_action_listeners
10187 .remove(&action.as_any().type_id())
10188 {
10189 for listener in &global_listeners {
10190 #[cfg(feature = "profiler")]
10191 self.window_profiler.begin_action_handler(action, cx);
10192 listener(action.as_any(), DispatchPhase::Capture, cx);
10193 #[cfg(feature = "profiler")]
10194 self.window_profiler.end_action_handler();
10195 if !cx.propagate_event {
10196 break;
10197 }
10198 }
10199
10200 global_listeners.extend(
10201 cx.global_action_listeners
10202 .remove(&action.as_any().type_id())
10203 .unwrap_or_default(),
10204 );
10205
10206 cx.global_action_listeners
10207 .insert(action.as_any().type_id(), global_listeners);
10208 }
10209
10210 if !cx.propagate_event {
10211 return;
10212 }
10213
10214 for node_id in &dispatch_path {
10216 let node = self.rendered_frame.dispatch_tree.node(*node_id);
10217 for DispatchActionListener {
10218 action_type,
10219 listener,
10220 } in node.action_listeners.clone()
10221 {
10222 let any_action = action.as_any();
10223 if action_type == any_action.type_id() {
10224 #[cfg(feature = "profiler")]
10225 self.window_profiler.begin_action_handler(action, cx);
10226 listener(any_action, DispatchPhase::Capture, self, cx);
10227 #[cfg(feature = "profiler")]
10228 self.window_profiler.end_action_handler();
10229
10230 if !cx.propagate_event {
10231 return;
10232 }
10233 }
10234 }
10235 }
10236
10237 for node_id in dispatch_path.iter().rev() {
10239 let node = self.rendered_frame.dispatch_tree.node(*node_id);
10240 for DispatchActionListener {
10241 action_type,
10242 listener,
10243 } in node.action_listeners.clone()
10244 {
10245 let any_action = action.as_any();
10246 if action_type == any_action.type_id() {
10247 cx.propagate_event = false; #[cfg(feature = "profiler")]
10249 self.window_profiler.begin_action_handler(action, cx);
10250 listener(any_action, DispatchPhase::Bubble, self, cx);
10251 #[cfg(feature = "profiler")]
10252 self.window_profiler.end_action_handler();
10253
10254 if !cx.propagate_event {
10255 return;
10256 }
10257 }
10258 }
10259 }
10260
10261 if let Some(mut global_listeners) = cx
10263 .global_action_listeners
10264 .remove(&action.as_any().type_id())
10265 {
10266 for listener in global_listeners.iter().rev() {
10267 cx.propagate_event = false; #[cfg(feature = "profiler")]
10270 self.window_profiler.begin_action_handler(action, cx);
10271 listener(action.as_any(), DispatchPhase::Bubble, cx);
10272 #[cfg(feature = "profiler")]
10273 self.window_profiler.end_action_handler();
10274 if !cx.propagate_event {
10275 break;
10276 }
10277 }
10278
10279 global_listeners.extend(
10280 cx.global_action_listeners
10281 .remove(&action.as_any().type_id())
10282 .unwrap_or_default(),
10283 );
10284
10285 cx.global_action_listeners
10286 .insert(action.as_any().type_id(), global_listeners);
10287 }
10288 }
10289
10290 pub fn observe_global<G: Global>(
10293 &mut self,
10294 cx: &mut App,
10295 f: impl Fn(&mut Window, &mut App) + 'static,
10296 ) -> Subscription {
10297 let window_handle = self.handle;
10298 let (subscription, activate) = cx.global_observers.insert_pending(
10299 TypeId::of::<G>(),
10300 Box::new(move |cx| {
10301 window_handle
10302 .update(cx, |_, window, cx| f(window, cx))
10303 .is_ok()
10304 }),
10305 );
10306 cx.defer(move |_| activate());
10307 subscription
10308 }
10309
10310 pub fn activate_window(&self) {
10312 self.platform_window.activate();
10313 }
10314
10315 pub fn show_window(
10318 &self,
10319 activate: bool,
10320 should_show: impl FnOnce() -> bool + 'static,
10321 completed: impl FnOnce(bool) + 'static,
10322 ) -> bool {
10323 self.platform_window.show_window(activate, Box::new(should_show), Box::new(completed))
10324 }
10325
10326 pub fn request_attention(&self) {
10328 self.platform_window.request_attention();
10329 }
10330
10331 pub fn minimize_window(&self) {
10333 self.platform_window.minimize();
10334 }
10335
10336 pub fn toggle_fullscreen(&self) {
10338 self.platform_window.toggle_fullscreen();
10339 }
10340
10341 pub fn toggle_simple_fullscreen(&self) {
10346 self.platform_window.toggle_simple_fullscreen();
10347 }
10348
10349 pub fn invalidate_character_coordinates(&self) {
10351 self.on_next_frame(|window, cx| {
10352 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
10353 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
10354 window.platform_window.update_ime_position(bounds);
10355 }
10356 window.platform_window.set_input_handler(input_handler);
10357 }
10358 });
10359 }
10360
10361 pub fn prompt<T>(
10365 &mut self,
10366 level: PromptLevel,
10367 message: &str,
10368 detail: Option<&str>,
10369 answers: &[T],
10370 cx: &mut App,
10371 ) -> oneshot::Receiver<usize>
10372 where
10373 T: Clone + Into<PromptButton>,
10374 {
10375 let prompt_builder = cx.prompt_builder.take();
10376 let Some(prompt_builder) = prompt_builder else {
10377 unreachable!("Re-entrant window prompting is not supported by GPUI");
10378 };
10379
10380 let answers = answers
10381 .iter()
10382 .map(|answer| answer.clone().into())
10383 .collect::<Vec<_>>();
10384
10385 let receiver = match &prompt_builder {
10386 PromptBuilder::Default => self
10387 .platform_window
10388 .prompt(level, message, detail, &answers)
10389 .unwrap_or_else(|| {
10390 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
10391 }),
10392 PromptBuilder::Custom(_) => {
10393 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
10394 }
10395 };
10396
10397 cx.prompt_builder = Some(prompt_builder);
10398
10399 receiver
10400 }
10401
10402 fn build_custom_prompt(
10403 &mut self,
10404 prompt_builder: &PromptBuilder,
10405 level: PromptLevel,
10406 message: &str,
10407 detail: Option<&str>,
10408 answers: &[PromptButton],
10409 cx: &mut App,
10410 ) -> oneshot::Receiver<usize> {
10411 let (sender, receiver) = oneshot::channel();
10412 let handle = PromptHandle::new(sender);
10413 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
10414 self.prompt = Some(handle);
10415 receiver
10416 }
10417
10418 pub fn has_active_prompt(&self) -> bool {
10423 self.prompt.is_some()
10424 }
10425
10426 pub fn context_stack(&self) -> Vec<KeyContext> {
10428 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10429 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10430 dispatch_tree
10431 .dispatch_path(node_id)
10432 .iter()
10433 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
10434 .collect()
10435 }
10436
10437 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
10439 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10440 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
10441 for action_type in cx.global_action_listeners.keys() {
10442 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
10443 let action = cx.actions.build_action_type(action_type).ok();
10444 if let Some(action) = action {
10445 actions.insert(ix, action);
10446 }
10447 }
10448 }
10449 actions
10450 }
10451
10452 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
10455 self.rendered_frame
10456 .dispatch_tree
10457 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
10458 }
10459
10460 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
10463 self.rendered_frame
10464 .dispatch_tree
10465 .highest_precedence_binding_for_action(
10466 action,
10467 &self.rendered_frame.dispatch_tree.context_stack,
10468 )
10469 }
10470
10471 pub fn bindings_for_action_in_context(
10473 &self,
10474 action: &dyn Action,
10475 context: KeyContext,
10476 ) -> Vec<KeyBinding> {
10477 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10478 dispatch_tree.bindings_for_action(action, &[context])
10479 }
10480
10481 pub fn highest_precedence_binding_for_action_in_context(
10484 &self,
10485 action: &dyn Action,
10486 context: KeyContext,
10487 ) -> Option<KeyBinding> {
10488 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10489 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
10490 }
10491
10492 pub fn bindings_for_action_in(
10496 &self,
10497 action: &dyn Action,
10498 focus_handle: &FocusHandle,
10499 ) -> Vec<KeyBinding> {
10500 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10501 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
10502 return vec![];
10503 };
10504 dispatch_tree.bindings_for_action(action, &context_stack)
10505 }
10506
10507 pub fn highest_precedence_binding_for_action_in(
10511 &self,
10512 action: &dyn Action,
10513 focus_handle: &FocusHandle,
10514 ) -> Option<KeyBinding> {
10515 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10516 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
10517 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
10518 }
10519
10520 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
10522 self.rendered_frame
10523 .dispatch_tree
10524 .possible_next_bindings_for_input(input, &self.context_stack())
10525 }
10526
10527 fn context_stack_for_focus_handle(
10528 &self,
10529 focus_handle: &FocusHandle,
10530 ) -> Option<Vec<KeyContext>> {
10531 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10532 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
10533 let context_stack: Vec<_> = dispatch_tree
10534 .dispatch_path(node_id)
10535 .into_iter()
10536 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
10537 .collect();
10538 Some(context_stack)
10539 }
10540
10541 pub fn listener_for<T: 'static, E>(
10543 &self,
10544 view: &Entity<T>,
10545 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
10546 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
10547 let view = view.downgrade();
10548 move |e: &E, window: &mut Window, cx: &mut App| {
10549 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
10550 }
10551 }
10552
10553 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
10555 &self,
10556 entity: &Entity<E>,
10557 f: Callback,
10558 ) -> impl Fn(&mut Window, &mut App) + 'static {
10559 let entity = entity.downgrade();
10560 move |window: &mut Window, cx: &mut App| {
10561 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
10562 }
10563 }
10564
10565 pub fn on_window_should_close(
10568 &self,
10569 cx: &App,
10570 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
10571 ) {
10572 let mut cx = self.to_async(cx);
10573 self.platform_window.on_should_close(Box::new(move || {
10574 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
10575 }))
10576 }
10577
10578 pub fn on_action(
10587 &mut self,
10588 action_type: TypeId,
10589 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
10590 ) {
10591 self.invalidator.debug_assert_paint();
10592
10593 self.next_frame
10594 .dispatch_tree
10595 .on_action(action_type, Rc::new(listener));
10596 }
10597
10598 pub fn on_action_when(
10607 &mut self,
10608 condition: bool,
10609 action_type: TypeId,
10610 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
10611 ) {
10612 self.invalidator.debug_assert_paint();
10613
10614 if condition {
10615 self.next_frame
10616 .dispatch_tree
10617 .on_action(action_type, Rc::new(listener));
10618 }
10619 }
10620
10621 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
10624 self.platform_window.gpu_specs()
10625 }
10626
10627 pub fn titlebar_double_click(&self) {
10630 self.platform_window
10631 .titlebar_double_click(self.is_resizable, self.is_minimizable);
10632 }
10633
10634 pub fn window_title(&self) -> String {
10637 self.platform_window.get_title()
10638 }
10639
10640 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
10643 self.platform_window.tabbed_windows()
10644 }
10645
10646 pub fn tab_bar_visible(&self) -> bool {
10649 self.platform_window.tab_bar_visible()
10650 }
10651
10652 pub fn merge_all_windows(&self) {
10655 self.platform_window.merge_all_windows()
10656 }
10657
10658 pub fn move_tab_to_new_window(&self) {
10661 self.platform_window.move_tab_to_new_window()
10662 }
10663
10664 pub fn toggle_window_tab_overview(&self) {
10667 self.platform_window.toggle_window_tab_overview()
10668 }
10669
10670 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
10673 self.platform_window
10674 .set_tabbing_identifier(tabbing_identifier)
10675 }
10676
10677 pub fn play_system_bell(&self) {
10680 self.platform_window.play_system_bell()
10681 }
10682
10683 pub fn is_a11y_enabled(&self) -> bool {
10690 self.a11y.is_enabled()
10691 }
10692
10693 pub fn is_a11y_active(&self) -> bool {
10704 self.a11y.is_active()
10705 }
10706
10707 pub fn debug_a11y_tree_json(&self) -> Option<String> {
10709 self.a11y.debug_tree_json()
10710 }
10711
10712 pub fn on_a11y_action(
10718 &mut self,
10719 node_id: accesskit::NodeId,
10720 action: accesskit::Action,
10721 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
10722 ) {
10723 self.a11y
10724 .action_listeners
10725 .entry(node_id)
10726 .or_default()
10727 .push((action, Box::new(listener)));
10728 }
10729
10730 #[cfg(not(target_family = "wasm"))]
10731 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
10732 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
10735 let extra_data = request.data.as_ref();
10736 let mut matched = false;
10737 for (action, listener) in &mut listeners {
10738 if *action == request.action {
10739 listener(extra_data, self, cx);
10740 matched = true;
10741 }
10742 }
10743 self.a11y
10744 .action_listeners
10745 .insert(request.target_node, listeners);
10746 if matched {
10747 return;
10748 }
10749 }
10750
10751 match request.action {
10753 accesskit::Action::Click => {
10754 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
10755 let center = bounds.center();
10756 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
10757 button: MouseButton::Left,
10758 position: center,
10759 modifiers: Modifiers::default(),
10760 click_count: 1,
10761 first_mouse: false,
10762 });
10763 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
10764 button: MouseButton::Left,
10765 position: center,
10766 modifiers: Modifiers::default(),
10767 click_count: 1,
10768 });
10769 self.dispatch_event(mouse_down, cx);
10770 self.dispatch_event(mouse_up, cx);
10771 }
10772 }
10773 accesskit::Action::Focus => {
10774 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
10775 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
10776 {
10777 self.focus(&handle, cx);
10778 }
10779 }
10780 accesskit::Action::Blur => {
10781 self.blur(cx);
10782 }
10783 _ => {
10784 log::debug!(
10785 "Unhandled a11y action: {:?} on {:?}",
10786 request.action,
10787 request.target_node
10788 );
10789 }
10790 }
10791 }
10792
10793 #[cfg(any(feature = "inspector", debug_assertions))]
10795 pub fn toggle_inspector(&mut self, cx: &mut App) {
10796 self.inspector = match self.inspector {
10797 None => Some(cx.new(|_| Inspector::new())),
10798 Some(_) => {
10799 self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
10800 self.rendered_frame.inspector_hitboxes = FxHashMap::default();
10801 self.next_frame.next_inspector_instance_ids = FxHashMap::default();
10802 self.next_frame.inspector_hitboxes = FxHashMap::default();
10803 None
10804 }
10805 };
10806 self.refresh();
10807 }
10808
10809 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
10811 #[cfg(any(feature = "inspector", debug_assertions))]
10812 {
10813 if let Some(inspector) = &self.inspector {
10814 return inspector.read(_cx).is_picking();
10815 }
10816 }
10817 false
10818 }
10819
10820 #[cfg(any(feature = "inspector", debug_assertions))]
10822 pub fn with_inspector_state<T: 'static, R>(
10823 &mut self,
10824 inspector_id: Option<&crate::InspectorElementId>,
10825 cx: &mut App,
10826 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
10827 ) -> Option<R> {
10828 let inspector_id = inspector_id?;
10829 let inspector = self.inspector.as_ref()?;
10830 if inspector.read(cx).active_element_id() != Some(inspector_id) {
10831 return None;
10832 }
10833 let inspector = inspector.clone();
10834 Some(inspector.update(cx, |inspector, _cx| {
10835 inspector.with_active_element_state(self, f)
10836 }))
10837 }
10838
10839 #[cfg(any(feature = "inspector", debug_assertions))]
10840 pub(crate) fn inspector_enabled(&self) -> bool {
10841 self.inspector.is_some()
10842 }
10843
10844 #[cfg(any(feature = "inspector", debug_assertions))]
10845 pub(crate) fn build_inspector_element_id(
10846 &mut self,
10847 path: crate::InspectorElementPath,
10848 ) -> crate::InspectorElementId {
10849 self.invalidator.debug_assert_paint_or_prepaint();
10850 let path = Rc::new(path);
10851 let next_instance_id = self
10852 .next_frame
10853 .next_inspector_instance_ids
10854 .entry(path.clone())
10855 .or_insert(0);
10856 let instance_id = *next_instance_id;
10857 *next_instance_id += 1;
10858 crate::InspectorElementId { path, instance_id }
10859 }
10860
10861 #[cfg(any(feature = "inspector", debug_assertions))]
10862 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
10863 if let Some(inspector) = self.inspector.take() {
10864 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
10865 inspector_element.prepaint_as_root(
10866 point(self.viewport_size.width - inspector_width, px(0.0)),
10867 size(inspector_width, self.viewport_size.height).into(),
10868 self,
10869 cx,
10870 );
10871 self.inspector = Some(inspector);
10872 Some(inspector_element)
10873 } else {
10874 None
10875 }
10876 }
10877
10878 #[cfg(any(feature = "inspector", debug_assertions))]
10879 fn paint_inspector(&mut self, inspector_element: Option<AnyElement>, cx: &mut App) {
10880 if let Some(mut inspector_element) = inspector_element {
10881 inspector_element.paint(self, cx);
10882 };
10883 }
10884
10885 #[cfg(any(feature = "inspector", debug_assertions))]
10888 pub fn insert_inspector_hitbox(
10889 &mut self,
10890 hitbox_id: HitboxId,
10891 inspector_id: Option<&crate::InspectorElementId>,
10892 cx: &App,
10893 ) {
10894 self.invalidator.debug_assert_paint_or_prepaint();
10895 if !self.is_inspector_picking(cx) {
10896 return;
10897 }
10898 if let Some(inspector_id) = inspector_id {
10899 self.next_frame
10900 .inspector_hitboxes
10901 .insert(hitbox_id, inspector_id.clone());
10902 }
10903 }
10904
10905 #[cfg(any(feature = "inspector", debug_assertions))]
10906 fn paint_inspector_hitbox(&mut self, cx: &App) {
10907 if let Some(inspector) = self.inspector.as_ref() {
10908 let inspector = inspector.read(cx);
10909 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
10910 && let Some(hitbox) = self
10911 .next_frame
10912 .hitboxes
10913 .iter()
10914 .find(|hitbox| hitbox.id == hitbox_id)
10915 {
10916 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
10917 }
10918 }
10919 }
10920
10921 #[cfg(any(feature = "inspector", debug_assertions))]
10922 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
10923 let Some(inspector) = self.inspector.clone() else {
10924 return;
10925 };
10926 if event.downcast_ref::<MouseMoveEvent>().is_some() {
10927 inspector.update(cx, |inspector, _cx| {
10928 if let Some((_, inspector_id)) =
10929 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10930 {
10931 inspector.hover(inspector_id, self);
10932 }
10933 });
10934 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
10935 inspector.update(cx, |inspector, _cx| {
10936 if let Some((_, inspector_id)) =
10937 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10938 {
10939 inspector.select(inspector_id, self);
10940 }
10941 });
10942 } else if let Some(event) = event.downcast_ref::<crate::ScrollEvent>() {
10943 const SCROLL_LINES: f32 = 3.0;
10945 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
10946 let delta_y = event
10947 .delta
10948 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
10949 .y;
10950 if let Some(inspector) = self.inspector.clone() {
10951 inspector.update(cx, |inspector, _cx| {
10952 if let Some(depth) = inspector.pick_depth.as_mut() {
10953 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
10954 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
10955 if *depth < 0.0 {
10956 *depth = 0.0;
10957 } else if *depth > max_depth {
10958 *depth = max_depth;
10959 }
10960 if let Some((_, inspector_id)) =
10961 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10962 {
10963 inspector.set_active_element_id(inspector_id, self);
10964 }
10965 }
10966 });
10967 }
10968 }
10969 }
10970
10971 #[cfg(any(feature = "inspector", debug_assertions))]
10972 fn hovered_inspector_hitbox(
10973 &self,
10974 inspector: &Inspector,
10975 frame: &Frame,
10976 ) -> Option<(HitboxId, crate::InspectorElementId)> {
10977 if let Some(pick_depth) = inspector.pick_depth {
10978 let depth = (pick_depth as i64).try_into().unwrap_or(0);
10979 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
10980 let skip_count = (depth as usize).min(max_skipped);
10981 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
10982 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
10983 return Some((*hitbox_id, inspector_id.clone()));
10984 }
10985 }
10986 }
10987 None
10988 }
10989
10990 #[cfg(any(test, feature = "test-support"))]
10993 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
10994 self.modifiers = modifiers;
10995 }
10996
10997 #[cfg(any(test, feature = "test-support"))]
11001 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
11002 let event = PlatformInput::MouseMove(MouseMoveEvent {
11003 position,
11004 modifiers: self.modifiers,
11005 pressed_button: None,
11006 });
11007 let _ = self.dispatch_event(event, cx);
11008 }
11009
11010 #[inline(never)]
11011 fn take_element_state(
11012 &mut self,
11013 global_id: &GlobalElementId,
11014 state_type: TypeId,
11015 ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
11016 let key = (global_id.clone(), state_type);
11017 self.next_frame.accessed_element_states.push(key.clone());
11018 let state = self
11019 .next_frame
11020 .element_states
11021 .remove(&key)
11022 .or_else(|| self.rendered_frame.element_states.remove(&key));
11023 (key, state)
11024 }
11025
11026 #[inline(never)]
11027 fn insert_element_state(
11028 &mut self,
11029 key: (GlobalElementId, TypeId),
11030 state: ElementStateBox,
11031 ) -> Option<ElementStateBox> {
11032 self.next_frame.element_states.insert(key, state)
11033 }
11034
11035 #[inline(never)]
11036 fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
11037 cx.observe(state, move |_, cx| {
11038 cx.notify(current_view);
11039 })
11040 .detach();
11041 }
11042}
11043
11044slotmap::new_key_type! {
11046 pub struct WindowId;
11048}
11049
11050impl WindowId {
11051 pub fn as_u64(&self) -> u64 {
11053 self.0.as_ffi()
11054 }
11055}
11056
11057impl From<u64> for WindowId {
11058 fn from(value: u64) -> Self {
11059 WindowId(slotmap::KeyData::from_ffi(value))
11060 }
11061}
11062
11063pub struct WindowHandle<V> {
11066 pub(crate) any_handle: AnyWindowHandle,
11067 state_type: PhantomData<fn(V) -> V>,
11068}
11069
11070impl_deref!([V] WindowHandle<V> => mut any_handle: AnyWindowHandle);
11071
11072impl<V> Debug for WindowHandle<V> {
11073 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11074 f.debug_struct("WindowHandle")
11075 .field("any_handle", &self.any_handle.id.as_u64())
11076 .finish()
11077 }
11078}
11079
11080impl<V: 'static + Render> WindowHandle<V> {
11081 pub fn new(id: WindowId) -> Self {
11084 WindowHandle {
11085 any_handle: AnyWindowHandle {
11086 id,
11087 state_type: TypeId::of::<V>(),
11088 root_entity_type_name: std::any::type_name::<V>(),
11089 },
11090 state_type: PhantomData,
11091 }
11092 }
11093
11094 #[cfg(any(test, feature = "test-support"))]
11098 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
11099 where
11100 C: AppContext,
11101 {
11102 cx.update_window(self.any_handle, |root_view, _, _| {
11103 root_view
11104 .downcast::<V>()
11105 .map_err(|_| anyhow!("the type of the window's root view has changed"))
11106 })?
11107 }
11108
11109 #[track_caller]
11113 pub fn update<C, R>(
11114 &self,
11115 cx: &mut C,
11116 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
11117 ) -> Result<R>
11118 where
11119 C: AppContext,
11120 {
11121 cx.update_window(self.any_handle, |root_view, window, cx| {
11122 let view = root_view
11123 .downcast::<V>()
11124 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
11125
11126 Ok(view.update(cx, |view, cx| update(view, window, cx)))
11127 })?
11128 }
11129
11130 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
11134 let x = cx
11135 .windows
11136 .get(self.id)
11137 .and_then(|window| {
11138 window
11139 .as_deref()
11140 .and_then(|window| window.root.clone())
11141 .map(|root_view| root_view.downcast::<V>())
11142 })
11143 .context("window not found")?
11144 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
11145
11146 Ok(x.read(cx))
11147 }
11148
11149 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
11153 where
11154 C: AppContext,
11155 {
11156 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
11157 }
11158
11159 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
11163 where
11164 C: AppContext,
11165 {
11166 cx.read_window(self, |root_view, _cx| root_view)
11167 }
11168
11169 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
11174 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
11175 .ok()
11176 }
11177}
11178
11179impl<V> Copy for WindowHandle<V> {}
11180
11181impl<V> Clone for WindowHandle<V> {
11182 fn clone(&self) -> Self {
11183 *self
11184 }
11185}
11186
11187impl<V> PartialEq for WindowHandle<V> {
11188 fn eq(&self, other: &Self) -> bool {
11189 self.any_handle == other.any_handle
11190 }
11191}
11192
11193impl<V> Eq for WindowHandle<V> {}
11194
11195impl<V> Hash for WindowHandle<V> {
11196 fn hash<H: Hasher>(&self, state: &mut H) {
11197 self.any_handle.hash(state);
11198 }
11199}
11200
11201impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
11202 fn from(val: WindowHandle<V>) -> Self {
11203 val.any_handle
11204 }
11205}
11206
11207#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
11209pub struct AnyWindowHandle {
11210 pub(crate) id: WindowId,
11211 state_type: TypeId,
11212 root_entity_type_name: &'static str,
11213}
11214
11215impl AnyWindowHandle {
11216 pub fn window_id(&self) -> WindowId {
11218 self.id
11219 }
11220
11221 pub fn root_entity_type_name(&self) -> &'static str {
11223 self.root_entity_type_name
11224 }
11225
11226 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
11229 if TypeId::of::<T>() == self.state_type {
11230 Some(WindowHandle {
11231 any_handle: *self,
11232 state_type: PhantomData,
11233 })
11234 } else {
11235 None
11236 }
11237 }
11238
11239 #[track_caller]
11243 pub fn update<C, R>(
11244 self,
11245 cx: &mut C,
11246 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
11247 ) -> Result<R>
11248 where
11249 C: AppContext,
11250 {
11251 cx.update_window(self, update)
11252 }
11253
11254 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
11258 where
11259 C: AppContext,
11260 T: 'static,
11261 {
11262 let view = self
11263 .downcast::<T>()
11264 .context("the type of the window's root view has changed")?;
11265
11266 cx.read_window(&view, read)
11267 }
11268}
11269
11270impl HasWindowHandle for Window {
11271 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
11272 self.platform_window.window_handle()
11273 }
11274}
11275
11276impl HasDisplayHandle for Window {
11277 fn display_handle(
11278 &self,
11279 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
11280 self.platform_window.display_handle()
11281 }
11282}
11283
11284#[derive(Clone, Debug, Eq, PartialEq, Hash)]
11289pub enum ElementId {
11290 View(EntityId),
11292 Integer(u64),
11294 Name(SharedString),
11296 Uuid(Uuid),
11298 FocusHandle(FocusId),
11300 NamedInteger(SharedString, u64),
11302 Path(Arc<std::path::Path>),
11304 CodeLocation(core::panic::Location<'static>),
11306 NamedChild(Arc<ElementId>, SharedString),
11308 OpaqueId([u8; 20]),
11310}
11311
11312impl ElementId {
11313 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
11315 Self::NamedInteger(name.into(), integer as u64)
11316 }
11317}
11318
11319impl Display for ElementId {
11320 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11321 match self {
11322 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
11323 ElementId::Integer(ix) => write!(f, "{}", ix)?,
11324 ElementId::Name(name) => write!(f, "{}", name)?,
11325 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
11326 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
11327 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
11328 ElementId::Path(path) => write!(f, "{}", path.display())?,
11329 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
11330 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
11331 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
11332 }
11333
11334 Ok(())
11335 }
11336}
11337
11338impl TryInto<SharedString> for ElementId {
11339 type Error = anyhow::Error;
11340
11341 fn try_into(self) -> anyhow::Result<SharedString> {
11342 if let ElementId::Name(name) = self {
11343 Ok(name)
11344 } else {
11345 anyhow::bail!("element id is not string")
11346 }
11347 }
11348}
11349
11350impl From<u64> for ElementId {
11351 fn from(id: u64) -> Self {
11352 ElementId::Integer(id)
11353 }
11354}
11355
11356impl From<usize> for ElementId {
11357 fn from(id: usize) -> Self {
11358 ElementId::Integer(id as u64)
11359 }
11360}
11361
11362impl From<i32> for ElementId {
11363 fn from(id: i32) -> Self {
11364 Self::Integer(id as u64)
11365 }
11366}
11367
11368impl From<SharedString> for ElementId {
11369 fn from(name: SharedString) -> Self {
11370 ElementId::Name(name)
11371 }
11372}
11373
11374impl From<String> for ElementId {
11375 fn from(name: String) -> Self {
11376 ElementId::Name(name.into())
11377 }
11378}
11379
11380impl From<Arc<str>> for ElementId {
11381 fn from(name: Arc<str>) -> Self {
11382 ElementId::Name(name.into())
11383 }
11384}
11385
11386impl From<Arc<std::path::Path>> for ElementId {
11387 fn from(path: Arc<std::path::Path>) -> Self {
11388 ElementId::Path(path)
11389 }
11390}
11391
11392impl From<&'static str> for ElementId {
11393 fn from(name: &'static str) -> Self {
11394 ElementId::Name(SharedString::new_static(name))
11395 }
11396}
11397
11398impl<'a> From<&'a FocusHandle> for ElementId {
11399 fn from(handle: &'a FocusHandle) -> Self {
11400 ElementId::FocusHandle(handle.id)
11401 }
11402}
11403
11404impl From<(&'static str, EntityId)> for ElementId {
11405 fn from((name, id): (&'static str, EntityId)) -> Self {
11406 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
11407 }
11408}
11409
11410impl From<(&'static str, usize)> for ElementId {
11411 fn from((name, id): (&'static str, usize)) -> Self {
11412 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
11413 }
11414}
11415
11416impl From<(SharedString, usize)> for ElementId {
11417 fn from((name, id): (SharedString, usize)) -> Self {
11418 ElementId::NamedInteger(name, id as u64)
11419 }
11420}
11421
11422impl From<(&'static str, u64)> for ElementId {
11423 fn from((name, id): (&'static str, u64)) -> Self {
11424 ElementId::NamedInteger(SharedString::new_static(name), id)
11425 }
11426}
11427
11428impl From<Uuid> for ElementId {
11429 fn from(value: Uuid) -> Self {
11430 Self::Uuid(value)
11431 }
11432}
11433
11434impl From<(&'static str, u32)> for ElementId {
11435 fn from((name, id): (&'static str, u32)) -> Self {
11436 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
11437 }
11438}
11439
11440impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
11441 fn from((id, name): (ElementId, T)) -> Self {
11442 ElementId::NamedChild(Arc::new(id), name.into())
11443 }
11444}
11445
11446impl From<&'static core::panic::Location<'static>> for ElementId {
11447 fn from(location: &'static core::panic::Location<'static>) -> Self {
11448 ElementId::CodeLocation(*location)
11449 }
11450}
11451
11452impl From<[u8; 20]> for ElementId {
11453 fn from(opaque_id: [u8; 20]) -> Self {
11454 ElementId::OpaqueId(opaque_id)
11455 }
11456}
11457
11458#[derive(Clone)]
11461pub struct PaintQuad {
11462 pub bounds: Bounds<Pixels>,
11464 pub corner_radii: Corners<Pixels>,
11466 pub background: Background,
11468 pub border_widths: Edges<Pixels>,
11470 pub border_color: Hsla,
11472 pub border_style: BorderStyle,
11474 pub corner_shapes: Corners<CornerShape>,
11476}
11477
11478#[derive(Clone, Copy, Debug)]
11480pub struct BackdropBlurEffect {
11481 pub radius: Pixels,
11487 pub tint: Hsla,
11493}
11494
11495impl BackdropBlurEffect {
11496 pub fn new(radius: Pixels) -> Self {
11500 Self {
11501 radius,
11502 ..Self::default()
11503 }
11504 }
11505
11506 pub fn tint(mut self, tint: impl Into<Hsla>) -> Self {
11508 self.tint = tint.into();
11509 self
11510 }
11511}
11512
11513impl Default for BackdropBlurEffect {
11514 fn default() -> Self {
11515 Self {
11516 radius: px(20.),
11517 tint: transparent_black(),
11518 }
11519 }
11520}
11521
11522impl PaintQuad {
11523 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
11525 PaintQuad {
11526 corner_radii: corner_radii.into(),
11527 ..self
11528 }
11529 }
11530
11531 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
11533 PaintQuad {
11534 border_widths: border_widths.into(),
11535 ..self
11536 }
11537 }
11538
11539 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
11541 PaintQuad {
11542 border_color: border_color.into(),
11543 ..self
11544 }
11545 }
11546
11547 pub fn background(self, background: impl Into<Background>) -> Self {
11549 PaintQuad {
11550 background: background.into(),
11551 ..self
11552 }
11553 }
11554
11555 pub fn corner_shapes(self, corner_shapes: Corners<CornerShape>) -> Self {
11557 PaintQuad {
11558 corner_shapes,
11559 ..self
11560 }
11561 }
11562}
11563
11564pub type ImageResampler =
11575 fn(&Arc<RenderImage>, usize, Size<DevicePixels>) -> Option<Arc<RenderImage>>;
11576
11577static IMAGE_RESAMPLER: std::sync::OnceLock<ImageResampler> = std::sync::OnceLock::new();
11578
11579pub fn set_image_resampler(resampler: ImageResampler) {
11582 let _ = IMAGE_RESAMPLER.set(resampler);
11583}
11584
11585pub fn quad(
11587 bounds: Bounds<Pixels>,
11588 corner_radii: impl Into<Corners<Pixels>>,
11589 background: impl Into<Background>,
11590 border_widths: impl Into<Edges<Pixels>>,
11591 border_color: impl Into<Hsla>,
11592 border_style: BorderStyle,
11593) -> PaintQuad {
11594 PaintQuad {
11595 bounds,
11596 corner_radii: corner_radii.into(),
11597 background: background.into(),
11598 border_widths: border_widths.into(),
11599 border_color: border_color.into(),
11600 border_style,
11601 corner_shapes: Corners::default(),
11602 }
11603}
11604
11605pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
11607 PaintQuad {
11608 bounds: bounds.into(),
11609 corner_radii: (0.).into(),
11610 background: background.into(),
11611 border_widths: (0.).into(),
11612 border_color: transparent_black(),
11613 border_style: BorderStyle::default(),
11614 corner_shapes: Corners::default(),
11615 }
11616}
11617
11618pub fn outline(
11620 bounds: impl Into<Bounds<Pixels>>,
11621 border_color: impl Into<Hsla>,
11622 border_style: BorderStyle,
11623) -> PaintQuad {
11624 PaintQuad {
11625 bounds: bounds.into(),
11626 corner_radii: (0.).into(),
11627 background: transparent_black().into(),
11628 border_widths: (1.).into(),
11629 border_color: border_color.into(),
11630 border_style,
11631 corner_shapes: Corners::default(),
11632 }
11633}
11634
11635pub(crate) const SHADOW_OUTSIDE_BOX: u32 = 0;
11638pub(crate) const SHADOW_INSET: u32 = 1;
11640pub(crate) const SHADOW_UNDER_BOX: u32 = 2;
11643
11644fn spread_shadow_radius(radius: Pixels, spread: Pixels) -> Pixels {
11650 if spread <= Pixels::ZERO {
11651 return (radius + spread).max(Pixels::ZERO);
11652 }
11653 let ratio = radius / spread;
11654 if ratio >= 1.0 {
11655 radius + spread
11656 } else {
11657 radius + spread * (1.0 + (ratio - 1.0).powi(3))
11658 }
11659}
11660
11661#[inline(never)]
11662fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
11663 if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
11664 let arena_cell = unsafe { &*arena_pointer };
11667 callback(&mut arena_cell.borrow_mut());
11668 Ok(())
11669 } else {
11670 ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
11671 }
11672}
11673
11674#[cfg(test)]
11675mod tests {
11676 use std::{
11677 cell::{Cell, RefCell},
11678 path::PathBuf,
11679 rc::Rc,
11680 time::Duration,
11681 };
11682
11683 use crate::{
11684 AnyWindowHandle, AppContext as _, BackGestureEvent, BackGesturePhase, Bounds, ContentMask,
11685 Context, CursorStyle, DispatchPhase, DragMoveEvent, Empty, ExternalDragPayload,
11686 ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle, InputEvent as _,
11687 InteractiveElement as _, IntoElement, KeyDownEvent, Keystroke, LongPressEvent, MouseButton,
11688 MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, PlatformInput, Point,
11689 Render, RequestFrameOptions, ScaledPixels, StatefulInteractiveElement as _, Styled,
11690 TestAppContext, ThermalState, TouchDragEvent, TouchEvent, TouchId, TouchPhase, Underline,
11691 UnderlineStyle, Window, WindowAppearance, WindowOptions, canvas, div, hsla, point, px,
11692 size,
11693 };
11694
11695 #[gpui::test]
11696 async fn test_focus_handle_release(cx: &mut TestAppContext) {
11697 let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
11698 let handle_id = handle.id;
11699 let weak_handle = handle.downgrade();
11700 let retained = handle.clone();
11701 drop(handle);
11702
11703 cx.update(|_| {});
11704 cx.read(|cx| {
11705 let handles = cx.focus_handles.read();
11706 assert_eq!(handles.handles.len(), 2);
11707 assert!(handles.dropped_handles.is_empty());
11708 });
11709 assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));
11710
11711 cx.background_spawn(async move { drop(retained) }).await;
11712 assert_eq!(weak_handle.upgrade(), None);
11713 cx.read(|cx| {
11714 assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);
11715 });
11716 cx.update(|_| {});
11717 cx.read(|cx| {
11718 let handles = cx.focus_handles.read();
11719 assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);
11720 assert!(handles.dropped_handles.is_empty());
11721 });
11722
11723 let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);
11724 assert_eq!(weak_handle.upgrade(), None);
11725 cx.update(|cx| {
11726 drop(replacements);
11727 cx.defer(move |_| drop(survivor));
11728 });
11729 cx.read(|cx| {
11730 let handles = cx.focus_handles.read();
11731 assert_eq!(handles.handles.len(), 0);
11732 assert!(handles.dropped_handles.is_empty());
11733 });
11734 }
11735
11736 #[gpui::test]
11737 fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {
11738 let windows = [
11739 cx.add_window(|_, _| EmptyView),
11740 cx.add_window(|_, _| EmptyView),
11741 cx.add_window(|_, _| EmptyView),
11742 cx.add_window(|_, _| EmptyView),
11743 cx.add_window(|_, _| EmptyView),
11744 ];
11745 let (handle, other_handle, survivor) =
11746 cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));
11747 for window in &windows[..2] {
11748 window
11749 .update(cx, |_, window, cx| window.focus(&handle, cx))
11750 .expect("window exists");
11751 }
11752 windows[2]
11753 .update(cx, |_, window, cx| window.focus(&other_handle, cx))
11754 .expect("window exists");
11755 windows[3]
11756 .update(cx, |_, window, cx| window.focus(&survivor, cx))
11757 .expect("window exists");
11758
11759 cx.update(|cx| {
11760 for _ in 0..1_000 {
11761 drop(cx.focus_handle());
11762 }
11763 drop((handle, other_handle));
11764 });
11765 for window in &windows[..3] {
11766 window
11767 .update(cx, |_, window, _| assert_eq!(window.focus, None))
11768 .expect("window exists");
11769 }
11770 windows[3]
11771 .update(cx, |_, window, cx| {
11772 assert_eq!(window.focused(cx).as_ref(), Some(&survivor));
11773 assert_eq!(window.focus_generation, 1);
11774 })
11775 .expect("window exists");
11776 windows[4]
11777 .update(cx, |_, window, _| {
11778 assert_eq!(window.focus, None);
11779 assert_eq!(window.focus_generation, 0);
11780 })
11781 .expect("window exists");
11782 }
11783
11784 #[gpui::test]
11785 fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
11786 let window = cx.add_window(|_, _| EmptyView);
11787 let platform_window = cx.test_window(window.into());
11788 {
11789 let app = cx.app.borrow_mut();
11790 platform_window.simulate_close();
11791 assert!(app.windows.contains_key(window.window_id()));
11792 }
11793 cx.run_until_parked();
11794 assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
11795 }
11796
11797 #[gpui::test]
11798 fn test_a_window_closed_by_its_own_frame_logs_no_error(cx: &mut TestAppContext) {
11799 struct Errors;
11800 thread_local!(static ERRORS: Cell<usize> = const { Cell::new(0) });
11801 impl log::Log for Errors {
11802 fn enabled(&self, metadata: &log::Metadata) -> bool {
11803 metadata.level() == log::Level::Error
11804 }
11805 fn log(&self, record: &log::Record) {
11806 if self.enabled(record.metadata()) {
11807 ERRORS.with(|errors| errors.set(errors.get() + 1));
11808 }
11809 }
11810 fn flush(&self) {}
11811 }
11812 if log::set_logger(&Errors).is_ok() {
11813 log::set_max_level(log::LevelFilter::Error);
11814 }
11815
11816 let window = cx.add_window(|_, _| EmptyView);
11817 let platform_window = cx.test_window(window.into());
11818 window
11819 .update(cx, |_, window, _| {
11820 window.refresh();
11821 window.on_next_frame(|window, _| window.remove_window());
11822 })
11823 .expect("window exists");
11824 let before = ERRORS.with(Cell::get);
11825 platform_window.simulate_frame_request(RequestFrameOptions {
11826 require_presentation: true,
11827 ..Default::default()
11828 });
11829 assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
11830 assert_eq!(ERRORS.with(Cell::get), before);
11831 }
11832
11833 #[cfg(feature = "profiler")]
11834 #[gpui::test]
11835 fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
11836 use crate::FrameRequestSource;
11837 use crate::profiler::journal::{
11838 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
11839 };
11840 use scheduler::Instant;
11841
11842 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
11843 let window = cx.add_window(|_, _| EmptyView);
11844 let platform_window = cx.test_window(window.into());
11845 platform_window.simulate_frame_request(RequestFrameOptions::default());
11846 let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
11847 let mut collector = journal.collector();
11848
11849 for (signal_at, source) in [
11850 (Some(Instant::now()), FrameRequestSource::NativeCallback),
11851 (Some(Instant::now()), FrameRequestSource::LocalSchedule),
11852 (None, FrameRequestSource::NativeCallback),
11853 ] {
11854 platform_window.simulate_frame_request(RequestFrameOptions {
11855 signal_at,
11856 signal_source: source,
11857 require_presentation: true,
11858 ..Default::default()
11859 });
11860 let entries = collector.collect_unseen().entries;
11861 let signal_index = entries
11862 .iter()
11863 .position(|entry| {
11864 matches!(
11865 entry,
11866 ForegroundJournalEntry::PlatformSignal(signal)
11867 if signal.window_id == window.window_id()
11868 && signal.signal_at == signal_at
11869 && signal.source == source
11870 && signal_at.is_none_or(|at| signal.handled_at >= at)
11871 )
11872 })
11873 .expect("frame request metadata");
11874 let skip_index = entries
11875 .iter()
11876 .position(|entry| {
11877 matches!(
11878 entry,
11879 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
11880 if skipped.window_id == window.window_id()
11881 && skipped.reason == FrameSkipReason::NoRenderNeeded
11882 )
11883 })
11884 .expect("completed no-render boundary");
11885 assert!(signal_index < skip_index);
11886 }
11887 }
11888
11889 #[cfg(feature = "profiler")]
11890 #[gpui::test]
11891 fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
11892 use crate::profiler::journal::{
11893 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
11894 };
11895 use scheduler::Instant;
11896
11897 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
11899 let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
11900 let mut collector = journal.collector();
11901 for (initially_dirty, schedule_callback) in [(true, false), (false, true)] {
11902 let window = cx
11904 .app
11905 .borrow_mut()
11906 .open_window(
11907 WindowOptions {
11908 inactive_frame_interval: Some(Duration::from_secs(3600)),
11909 ..Default::default()
11910 },
11911 |_, cx| cx.new(|_| EmptyView),
11912 )
11913 .expect("open inactive test window");
11914 let platform_window = cx.test_window(window.into());
11915 platform_window.simulate_active_status_change(false);
11916 platform_window.simulate_frame_request(RequestFrameOptions::default());
11917 let callback_ran = Rc::new(Cell::new(false));
11918 let draws_before = window
11919 .update(cx, |_, window, _| {
11920 let draws_before = window
11921 .frame_duration_snapshot()
11922 .draw_duration_histogram
11923 .len();
11924 if initially_dirty {
11925 window.refresh();
11926 }
11927 if schedule_callback {
11928 window.on_next_frame({
11929 let callback_ran = callback_ran.clone();
11930 move |window, _| {
11931 callback_ran.set(true);
11932 window.refresh();
11933 }
11934 });
11935 }
11936 draws_before
11937 })
11938 .expect("schedule throttled frame");
11939 let input_at = Instant::now();
11941 journal::record_input(journal::InputTiming {
11942 kind: "test",
11943 start: input_at,
11944 end: input_at,
11945 caused_invalidation: false,
11946 });
11947 collector.collect_unseen();
11948 let wakes_before = platform_window.frame_wake_count();
11949 platform_window.simulate_frame_request(RequestFrameOptions {
11950 signal_at: Some(Instant::now()),
11951 ..Default::default()
11952 });
11953 window
11954 .update(cx, |_, window, _| {
11955 assert_eq!(
11956 window
11957 .frame_duration_snapshot()
11958 .draw_duration_histogram
11959 .len(),
11960 draws_before,
11961 );
11962 })
11963 .expect("inspect deferred frame");
11964 assert!(!callback_ran.get());
11965 assert!(platform_window.frame_scheduled());
11966 assert!(platform_window.frame_wake_count() > wakes_before);
11967 assert!(collector.collect_unseen().entries.iter().any(|entry| {
11968 matches!(
11969 entry,
11970 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
11971 if skipped.window_id == window.window_id()
11972 && skipped.reason == FrameSkipReason::InactiveFrameRateLimit
11973 )
11974 }));
11975 platform_window.simulate_frame_request(RequestFrameOptions {
11976 signal_at: Some(Instant::now()),
11977 require_presentation: true,
11978 ..Default::default()
11979 });
11980 window
11981 .update(cx, |_, window, _| {
11982 assert_eq!(
11983 window
11984 .frame_duration_snapshot()
11985 .draw_duration_histogram
11986 .len(),
11987 draws_before + 1,
11988 );
11989 })
11990 .expect("inspect presented frame");
11991 assert_eq!(callback_ran.get(), schedule_callback);
11992 }
11993 }
11994
11995 #[gpui::test]
11998 fn test_debug_state_reports_cached_and_platform_values(cx: &mut TestAppContext) {
11999 use crate::WindowVisibility;
12000
12001 let window = cx.add_window(|_, _| EmptyView);
12002 let window_id = window.window_id().as_u64();
12003 let window_state = |cx: &mut TestAppContext| {
12004 let state = cx.update(|cx| cx.debug_state());
12005 state["windows"]
12006 .as_array()
12007 .and_then(|windows| windows.iter().find(|window| window["id"] == window_id))
12008 .cloned()
12009 .expect("the open window is listed")
12010 };
12011
12012 let state = window_state(cx);
12013 assert_eq!(state["visibility"]["cached"], "Visible");
12014 assert_eq!(state["visibility"]["platform"], "Visible");
12015
12016 cx.test_window(window.into())
12017 .simulate_visibility_change(WindowVisibility::Hidden);
12018 let state = window_state(cx);
12019 assert_eq!(state["visibility"]["cached"], "Hidden");
12020 assert_eq!(state["visibility"]["platform"], "Hidden");
12021 }
12022
12023 #[gpui::test]
12027 fn test_window_visibility(cx: &mut TestAppContext) {
12028 use crate::WindowVisibility;
12029
12030 let window = cx.add_window(|_, _| EmptyView);
12031 let observed = Rc::new(RefCell::new(Vec::new()));
12032 let _subscription = window
12033 .update(cx, {
12034 let observed = observed.clone();
12035 move |_, window, _| {
12036 assert_eq!(window.visibility(), WindowVisibility::Visible);
12037 assert!(window.is_visible());
12038 window.observe_window_visibility(move |visibility, window, _| {
12039 assert_eq!(window.visibility(), visibility);
12040 observed.borrow_mut().push(visibility);
12041 })
12042 }
12043 })
12044 .unwrap();
12045 let test_window = cx.test_window(window.into());
12046 let frame_wake_count = test_window.frame_wake_count();
12047
12048 test_window.simulate_visibility_change(WindowVisibility::Hidden);
12049 assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
12050 window
12051 .update(cx, |_, window, _| assert!(!window.is_visible()))
12052 .unwrap();
12053
12054 test_window.simulate_visibility_change(WindowVisibility::Hidden);
12056 assert_eq!(observed.borrow().len(), 1);
12057
12058 test_window.simulate_visibility_change(WindowVisibility::Visible);
12059 assert_eq!(
12060 *observed.borrow(),
12061 [WindowVisibility::Hidden, WindowVisibility::Visible]
12062 );
12063 window
12064 .update(cx, |_, window, _| assert!(window.is_visible()))
12065 .unwrap();
12066 assert_eq!(test_window.frame_wake_count(), frame_wake_count);
12067 }
12068
12069 #[gpui::test]
12072 fn test_display_tracking(cx: &mut TestAppContext) {
12073 use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
12074
12075 let sixty_hertz = Duration::from_secs(1) / 60;
12076 let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
12077 let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
12078
12079 let display_events = Rc::new(RefCell::new(Vec::new()));
12080 let _display_subscription = cx.update({
12081 let display_events = display_events.clone();
12082 move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
12083 });
12084
12085 let window = cx.add_window(|window, cx| DisplayTracker {
12086 refresh_intervals: Vec::new(),
12087 _subscription: cx.observe_window_display(
12088 window,
12089 |tracker: &mut DisplayTracker, window, cx| {
12090 tracker.refresh_intervals.push(window.refresh_interval(cx));
12091 },
12092 ),
12093 });
12094 let window_notifications = Rc::new(RefCell::new(Vec::new()));
12095 let _window_subscription = window
12096 .update(cx, {
12097 let window_notifications = window_notifications.clone();
12098 move |_, window, cx| {
12099 assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
12100 window.observe_window_display(move |window, cx| {
12101 window_notifications
12102 .borrow_mut()
12103 .push((window.display_id, window.refresh_interval(cx)));
12104 })
12105 }
12106 })
12107 .unwrap();
12108 let test_window = cx.test_window(window.into());
12109
12110 cx.test_platform()
12115 .connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
12116 test_window.simulate_move_to_display(DisplayId(2));
12117 assert_eq!(
12118 window_notifications.take(),
12119 [(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
12120 );
12121 assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
12122 cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
12123 assert!(window_notifications.borrow().is_empty());
12124
12125 test_window.simulate_move_to_display(DisplayId(2));
12127 assert!(window_notifications.borrow().is_empty());
12128
12129 cx.simulate_display_refresh_interval_change(
12130 DisplayId(2),
12131 Some(one_hundred_forty_four_hertz),
12132 );
12133 assert_eq!(
12134 window_notifications.take(),
12135 [(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
12136 );
12137
12138 cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
12140 cx.simulate_display_removed(DisplayId(1));
12141 assert!(window_notifications.borrow().is_empty());
12142
12143 assert_eq!(
12144 display_events.take(),
12145 [
12146 DisplayEvent::Changed {
12147 id: DisplayId(2),
12148 changes: DisplayChanges::REFRESH_INTERVAL,
12149 },
12150 DisplayEvent::Changed {
12151 id: DisplayId(1),
12152 changes: DisplayChanges::REFRESH_INTERVAL,
12153 },
12154 DisplayEvent::Removed(DisplayId(1)),
12155 ]
12156 );
12157 window
12158 .update(cx, |tracker, _, _| {
12159 assert_eq!(
12160 tracker.refresh_intervals,
12161 [
12162 Some(one_hundred_twenty_hertz),
12163 Some(one_hundred_forty_four_hertz)
12164 ]
12165 );
12166 })
12167 .unwrap();
12168
12169 struct DisplayTracker {
12170 refresh_intervals: Vec<Option<Duration>>,
12171 _subscription: Subscription,
12172 }
12173
12174 impl Render for DisplayTracker {
12175 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12176 Empty
12177 }
12178 }
12179 }
12180
12181 #[gpui::test]
12182 fn test_window_opened_from_bounds_observer_uses_new_bounds(cx: &mut TestAppContext) {
12183 use crate::Subscription;
12184
12185 struct BoundsObserver {
12186 _subscription: Subscription,
12187 }
12188
12189 impl Render for BoundsObserver {
12190 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12191 Empty
12192 }
12193 }
12194
12195 let opened_window = Rc::new(Cell::new(None));
12196 let window = cx.add_window({
12197 let opened_window = opened_window.clone();
12198 move |window, cx| BoundsObserver {
12199 _subscription: cx.observe_window_bounds(window, move |_, _, cx| {
12200 let handle = cx
12201 .open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
12202 .unwrap();
12203 opened_window.set(Some(AnyWindowHandle::from(handle)));
12204 }),
12205 }
12206 });
12207 window
12208 .update(cx, |_, window, _| window.activate_window())
12209 .unwrap();
12210
12211 let new_size = size(px(400.), px(300.));
12212 cx.simulate_window_resize(window.into(), new_size);
12213
12214 let opened_window = opened_window
12215 .take()
12216 .expect("bounds observer should have opened a window");
12217 let opened_size = opened_window
12218 .update(cx, |_, window, _| window.bounds().size)
12219 .unwrap();
12220 assert_eq!(opened_size, new_size);
12221 }
12222
12223 #[gpui::test]
12224 fn test_resize_reported_while_app_is_borrowed_runs_later(cx: &mut TestAppContext) {
12225 use crate::Subscription;
12226
12227 struct BoundsObserver {
12228 _subscription: Subscription,
12229 }
12230
12231 impl Render for BoundsObserver {
12232 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12233 Empty
12234 }
12235 }
12236
12237 let observed = Rc::new(Cell::new(None));
12238 let window = cx.add_window({
12239 let observed = observed.clone();
12240 move |window, cx| BoundsObserver {
12241 _subscription: cx.observe_window_bounds(window, move |_, window, _| {
12242 observed.set(Some(window.bounds().size));
12243 }),
12244 }
12245 });
12246 let mut platform_window = cx.test_window(window.into());
12247
12248 let new_size = size(px(420.), px(310.));
12249 cx.update(|_| platform_window.simulate_resize(new_size));
12250 cx.run_until_parked();
12251
12252 assert_eq!(observed.get(), Some(new_size));
12253 }
12254
12255 #[gpui::test]
12256 fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
12257 let window = cx.add_window(|_, _| EmptyView);
12258 let mut platform_window = cx.test_window(window.into());
12259 platform_window.simulate_resize(size(px(400.), px(800.)));
12260 window
12261 .update(cx, |_, window, _| {
12262 assert_eq!(
12263 window.visual_viewport_bounds(),
12264 Bounds::new(Point::default(), size(px(400.), px(800.)))
12265 );
12266 assert_eq!(
12267 window.fully_visible_bounds(),
12268 window.visual_viewport_bounds()
12269 );
12270 })
12271 .unwrap();
12272
12273 platform_window.simulate_frame_request(RequestFrameOptions::default());
12274 let wakes = platform_window.frame_wake_count();
12275 let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
12276 platform_window.simulate_visual_viewport_change(visual_bounds);
12277 assert!(platform_window.frame_wake_count() > wakes);
12278 platform_window.simulate_frame_request(RequestFrameOptions::default());
12279 let wakes = platform_window.frame_wake_count();
12280 let insets = crate::WindowInsets {
12281 safe_area: crate::Edges {
12282 top: px(60.),
12283 right: px(20.),
12284 bottom: px(30.),
12285 left: px(-10.),
12286 },
12287 ime: crate::Edges {
12288 bottom: px(350.),
12289 ..Default::default()
12290 },
12291 ..Default::default()
12292 };
12293 platform_window.simulate_insets_change(insets.clone());
12294 assert!(platform_window.frame_wake_count() > wakes);
12295 window
12296 .update(cx, |_, window, cx| {
12297 let focus = cx.focus_handle();
12298 window.focus(&focus, cx);
12299 assert_eq!(window.insets(), insets);
12300 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
12301 assert_eq!(window.visual_viewport_bounds(), visual_bounds);
12302 assert_eq!(
12303 window.fully_visible_bounds(),
12304 Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
12305 );
12306 window.request_virtual_keyboard();
12307 window.dismiss_virtual_keyboard();
12308 assert!(focus.is_focused(window));
12309 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
12310 })
12311 .unwrap();
12312 assert_eq!(platform_window.virtual_keyboard_requests(), 1);
12313 assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
12314
12315 platform_window.simulate_insets_change(crate::WindowInsets {
12316 safe_area: crate::Edges {
12317 top: px(900.),
12318 left: px(500.),
12319 ..Default::default()
12320 },
12321 ..Default::default()
12322 });
12323 window
12324 .update(cx, |_, window, _| {
12325 assert_eq!(
12326 window.fully_visible_bounds().size,
12327 size(Pixels::ZERO, Pixels::ZERO)
12328 );
12329 })
12330 .unwrap();
12331
12332 use crate::PlatformWindow as _;
12334 platform_window.on_insets_changed(Box::new(|_| {}));
12335 platform_window.simulate_insets_change(crate::WindowInsets::default());
12336 window
12337 .update(cx, |_, window, _| {
12338 assert_eq!(window.insets(), crate::WindowInsets::default());
12339 })
12340 .unwrap();
12341 }
12342
12343 #[test]
12344 fn frame_throttle_tracks_display_refreshes() {
12345 let start = super::Instant::now();
12346 for (elapsed, interval) in [
12347 (Duration::from_micros(16_666), Duration::from_micros(16_667)),
12348 (Duration::from_micros(33_332), Duration::from_micros(33_333)),
12349 ] {
12350 let mut pacer = super::FramePacer::default();
12351 assert!(!pacer.should_defer(start, Some(interval)));
12352 assert!(pacer.should_defer(start + elapsed / 2, Some(interval)));
12353 assert!(!pacer.should_defer(start + elapsed, Some(interval)));
12354 }
12355 }
12356
12357 #[test]
12358 fn frame_throttle_preserves_cadence_without_catching_up_after_stalls() {
12359 let start = super::Instant::now();
12360 let interval = Duration::from_micros(33_333);
12361 let mut pacer = super::FramePacer::default();
12362 assert!(!pacer.should_defer(start, Some(interval)));
12363 let delayed_frame = start + interval + Duration::from_millis(5);
12364 assert!(!pacer.should_defer(delayed_frame, Some(interval)));
12365 assert!(pacer.should_defer(start + interval + interval / 2, Some(interval)));
12366 assert!(!pacer.should_defer(start + interval * 2, Some(interval)));
12367
12368 let after_stall = start + interval * 4 - Duration::from_millis(1);
12370 assert!(!pacer.should_defer(after_stall, Some(interval)));
12371 assert!(pacer.should_defer(after_stall + interval / 2, Some(interval)));
12372 assert!(!pacer.should_defer(after_stall + interval, Some(interval)));
12373 let mandatory_frame = after_stall + interval + Duration::from_millis(2);
12375 assert!(!pacer.should_defer(mandatory_frame, None));
12376 assert!(pacer.should_defer(mandatory_frame + interval / 2, Some(interval)));
12377 }
12378
12379 #[test]
12380 fn power_modes_preserve_frame_limits() {
12381 let options = WindowOptions::default();
12382 for (power_mode, active_interval, thermal_interval) in [
12383 (
12384 crate::PowerMode::LowPower,
12385 Some(Duration::from_micros(33_333)),
12386 Duration::from_micros(33_333),
12387 ),
12388 (
12389 crate::PowerMode::Unknown,
12390 None,
12391 Duration::from_micros(16_667),
12392 ),
12393 (
12394 crate::PowerMode::Balanced,
12395 None,
12396 Duration::from_micros(16_667),
12397 ),
12398 (
12399 crate::PowerMode::HighPower,
12400 None,
12401 Duration::from_micros(16_667),
12402 ),
12403 ] {
12404 assert_eq!(
12405 super::minimum_frame_interval(
12406 true,
12407 false,
12408 options.inactive_frame_interval,
12409 options.low_power_frame_interval,
12410 options.thermal_frame_interval,
12411 ThermalState::Nominal,
12412 power_mode,
12413 ),
12414 active_interval,
12415 );
12416 assert_eq!(
12417 super::minimum_frame_interval(
12418 true,
12419 false,
12420 options.inactive_frame_interval,
12421 options.low_power_frame_interval,
12422 options.thermal_frame_interval,
12423 ThermalState::Serious,
12424 power_mode,
12425 ),
12426 Some(thermal_interval),
12427 );
12428 }
12429 }
12430
12431 #[test]
12432 fn frame_limits_combine_enabled_intervals() {
12433 let short = Some(Duration::from_millis(10));
12434 let long = Some(Duration::from_millis(100));
12435 for (inactive, low_power, thermal, expected) in [
12436 (long, short, short, long),
12437 (short, long, short, long),
12438 (short, short, long, long),
12439 (long, None, None, long),
12440 (None, long, None, long),
12441 (None, None, long, long),
12442 (None, None, None, None),
12443 ] {
12444 assert_eq!(
12445 super::minimum_frame_interval(
12446 true,
12447 true,
12448 inactive,
12449 low_power,
12450 thermal,
12451 ThermalState::Critical,
12452 crate::PowerMode::LowPower,
12453 ),
12454 expected,
12455 );
12456 }
12457 assert_eq!(
12458 super::minimum_frame_interval(
12459 false,
12460 true,
12461 long,
12462 long,
12463 long,
12464 ThermalState::Critical,
12465 crate::PowerMode::LowPower,
12466 ),
12467 None,
12468 );
12469 }
12470
12471 struct EmptyView;
12472
12473 impl Render for EmptyView {
12474 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
12475 div()
12476 }
12477 }
12478
12479 struct OpensWindowOnPaint {
12480 opened: Rc<Cell<bool>>,
12481 }
12482
12483 impl Render for OpensWindowOnPaint {
12484 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
12485 let opened = self.opened.clone();
12486 div()
12487 .size_full()
12488 .child(canvas(
12489 |_, _, _| {},
12490 move |_, _, _window, cx| {
12491 if !opened.replace(true) {
12492 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
12493 .unwrap();
12494 }
12495 },
12496 ))
12497 .child(div().child("after"))
12501 }
12502 }
12503
12504 #[test]
12510 fn test_window_opened_during_draw_defers_arena_clear() {
12511 let mut cx = TestAppContext::single();
12512
12513 let opened = Rc::new(Cell::new(false));
12514 let window = cx.add_window({
12516 let opened = opened.clone();
12517 move |_, _| OpensWindowOnPaint { opened }
12518 });
12519
12520 assert!(opened.get());
12521 assert_eq!(cx.windows().len(), 2);
12522
12523 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
12526 .unwrap();
12527 }
12528
12529 #[test]
12530 fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
12531 let mut cx = TestAppContext::single();
12532 let window = cx.add_window(|_, _| EmptyView);
12533 let handle: AnyWindowHandle = window.into();
12534 let window_state = |cx: &mut TestAppContext| {
12535 cx.update_window(handle, |_, window, _| {
12536 (
12537 window.scale_factor(),
12538 window.bounds(),
12539 window.viewport_size(),
12540 )
12541 })
12542 .unwrap()
12543 };
12544
12545 let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
12546 assert_eq!(scale_factor, 2.0);
12547
12548 for (scale_factor, resized_size) in [
12549 (1.0, size(px(800.), px(600.))),
12550 (1.25, size(px(640.), px(480.))),
12551 (2.0, size(px(1024.), px(768.))),
12552 ] {
12553 cx.simulate_window_scale_factor_change(handle, scale_factor);
12554 assert_eq!(
12555 window_state(&mut cx),
12556 (scale_factor, expected_bounds, expected_bounds.size)
12557 );
12558
12559 cx.simulate_window_resize(handle, resized_size);
12560 expected_bounds.size = resized_size;
12561 assert_eq!(
12562 window_state(&mut cx),
12563 (scale_factor, expected_bounds, resized_size)
12564 );
12565 }
12566 }
12567
12568 #[gpui::test]
12569 fn test_fullscreen_toggle_reports_current_bounds(cx: &mut TestAppContext) {
12570 let window = cx.add_window(|_, _| EmptyView);
12571 let handle = AnyWindowHandle::from(window);
12572 let notifications = Rc::new(Cell::new(0));
12573 window
12574 .update(cx, {
12575 let notifications = notifications.clone();
12576 |_, window, cx| {
12577 cx.observe_window_bounds(window, move |_, _, _| {
12578 notifications.set(notifications.get() + 1)
12579 })
12580 .detach();
12581 }
12582 })
12583 .unwrap();
12584 let window_state = |cx: &mut TestAppContext| {
12585 cx.update_window(handle, |_, window, _| {
12586 (
12587 window.is_fullscreen(),
12588 window.bounds().size,
12589 window.viewport_size(),
12590 )
12591 })
12592 .unwrap()
12593 };
12594 let initial_size = window_state(cx).1;
12595
12596 window
12597 .update(cx, |_, window, _| window.toggle_fullscreen())
12598 .unwrap();
12599 cx.run_until_parked();
12600 assert_eq!(window_state(cx), (true, initial_size, initial_size));
12601 assert_eq!(notifications.get(), 1);
12602
12603 let resized_size = size(px(800.), px(600.));
12604 window
12605 .update(cx, |_, window, _| window.toggle_fullscreen())
12606 .unwrap();
12607 cx.simulate_window_resize(handle, resized_size);
12608 cx.run_until_parked();
12609 assert_eq!(window_state(cx), (false, resized_size, resized_size));
12610 }
12611
12612 #[gpui::test]
12617 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
12618 let window = cx.add_window(|_, _| EmptyView);
12619 let test_window = cx.test_window(window.into());
12620 test_window.simulate_active_status_change(true);
12622
12623 assert!(
12627 test_window.frame_wake_count() >= 1,
12628 "opening a window must wake the frame source for the initial frame"
12629 );
12630
12631 test_window.simulate_frame_request(RequestFrameOptions::default());
12633
12634 let baseline = test_window.frame_wake_count();
12637 test_window.simulate_frame_request(RequestFrameOptions::default());
12638 window.update(cx, |_, _, _| {}).unwrap();
12639 assert_eq!(
12640 test_window.frame_wake_count(),
12641 baseline,
12642 "clean frames and non-notifying updates must not wake the frame source"
12643 );
12644
12645 window.update(cx, |_, _, cx| cx.notify()).unwrap();
12647 assert!(
12648 test_window.frame_wake_count() > baseline,
12649 "notifying a view in an idle window must wake the frame source"
12650 );
12651
12652 test_window.simulate_frame_request(RequestFrameOptions::default());
12654 let baseline = test_window.frame_wake_count();
12655 test_window.simulate_frame_request(RequestFrameOptions::default());
12656 assert_eq!(
12657 test_window.frame_wake_count(),
12658 baseline,
12659 "serving demand must return the window to idle"
12660 );
12661
12662 window
12664 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
12665 .unwrap();
12666 assert!(
12667 test_window.frame_wake_count() > baseline,
12668 "scheduling a next-frame callback in an idle window must wake the frame source"
12669 );
12670 }
12671
12672 #[gpui::test]
12675 fn test_passive_next_frame_callbacks_are_not_demand(cx: &mut TestAppContext) {
12676 fn rearm(window: &mut Window, runs: Rc<Cell<usize>>) {
12677 runs.set(runs.get() + 1);
12678 window.on_next_frame_passive(move |window, _| rearm(window, runs));
12679 }
12680 let window = cx.add_window(|_, _| EmptyView);
12681 let test_window = cx.test_window(window.into());
12682 test_window.simulate_frame_request(RequestFrameOptions::default());
12683
12684 let runs = Rc::new(Cell::new(0));
12685 let baseline = test_window.frame_wake_count();
12686 window
12687 .update(cx, {
12688 let runs = runs.clone();
12689 move |_, window, _| window.on_next_frame_passive(move |window, _| rearm(window, runs))
12690 })
12691 .unwrap();
12692 assert_eq!(test_window.frame_wake_count(), baseline, "queueing a passive callback is not demand");
12693
12694 test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
12695 test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
12696 assert_eq!(runs.get(), 2, "a passive callback runs with every delivered frame");
12697 assert_eq!(test_window.frame_wake_count(), baseline, "a re-arming passive pump never wakes the frame source");
12698
12699 window.update(cx, |_, window, _| window.on_next_frame(|_, _| {})).unwrap();
12701 assert!(test_window.frame_wake_count() > baseline);
12702 }
12703
12704 #[gpui::test]
12709 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
12710 let window = cx.add_window(|_, _| EmptyView);
12711 let test_window = cx.test_window(window.into());
12712 test_window.simulate_frame_request(RequestFrameOptions::default());
12715
12716 let callback_ran = Rc::new(Cell::new(false));
12717 window
12718 .update(cx, {
12719 let callback_ran = callback_ran.clone();
12720 move |_, window, _| {
12721 window.on_next_frame(move |_, _| callback_ran.set(true));
12722 }
12723 })
12724 .unwrap();
12725
12726 let baseline = test_window.frame_wake_count();
12727 test_window.simulate_frame_request(RequestFrameOptions::default());
12728 assert!(
12735 test_window.frame_wake_count() > baseline || callback_ran.get(),
12736 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
12737 );
12738 }
12739
12740 #[gpui::test]
12741 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
12742 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
12743
12744 let window = cx.add_window(|_, _| EmptyView);
12745 window
12746 .update(cx, |_, window, _| {
12747 assert!(matches!(
12748 window.window_handle(),
12749 Err(HandleError::NotSupported)
12750 ));
12751 assert!(matches!(
12752 window.display_handle(),
12753 Err(HandleError::NotSupported)
12754 ));
12755 })
12756 .unwrap();
12757 }
12758
12759 #[gpui::test]
12760 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
12761 let window = cx.add_window(|_, _| EmptyView);
12762 let observed_appearance = Rc::new(Cell::new(None));
12763 let _subscription = window
12764 .update(cx, {
12765 let observed_appearance = observed_appearance.clone();
12766 move |_, window, _| {
12767 window.observe_window_appearance(move |window, _| {
12768 observed_appearance.set(Some(window.appearance()));
12769 })
12770 }
12771 })
12772 .unwrap();
12773 let test_window = cx.test_window(window.into());
12774
12775 cx.update(|_| {
12776 test_window.simulate_appearance_change(WindowAppearance::Dark);
12777 assert_eq!(observed_appearance.get(), None);
12778 });
12779 cx.run_until_parked();
12780
12781 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
12782 }
12783
12784 #[gpui::test]
12785 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
12786 let window = cx.add_window(|_, _| Empty);
12787 let test_window = cx.test_window(window.into());
12788
12789 assert!(test_window.simulate_scheduled_frame());
12790 assert!(test_window.simulate_scheduled_frame());
12791 assert!(!test_window.frame_scheduled());
12792
12793 cx.update_window(window.into(), |_, window, _| {
12794 window.active.set(true);
12795 window.on_next_frame(|_, _| {});
12796 })
12797 .unwrap();
12798 assert!(
12799 test_window.frame_scheduled(),
12800 "queuing work on a parked window must wake the render loop"
12801 );
12802
12803 assert!(test_window.simulate_scheduled_frame());
12804 assert!(
12805 test_window.frame_scheduled(),
12806 "presenting the frame must await one compositor callback"
12807 );
12808 assert!(test_window.simulate_scheduled_frame());
12809 assert!(!test_window.frame_scheduled());
12810 }
12811
12812 #[gpui::test]
12813 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
12814 let window = cx.add_window(|_, _| Empty);
12815 let test_window = cx.test_window(window.into());
12816
12817 assert!(test_window.simulate_scheduled_frame());
12818 assert!(test_window.simulate_scheduled_frame());
12819 assert!(!test_window.frame_scheduled());
12820
12821 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
12822 .unwrap();
12823
12824 assert!(
12825 test_window.frame_scheduled(),
12826 "a rendered scene awaiting presentation must wake the render loop"
12827 );
12828 }
12829
12830 #[gpui::test]
12831 fn reentrant_frame_request_preserves_pending_callbacks(cx: &mut TestAppContext) {
12832 let window = cx.add_window(|_, _| Empty);
12833 let test_window = cx.test_window(window.into());
12834 let callback_count = Rc::new(Cell::new(0));
12835
12836 cx.update_window(window.into(), |_, window, _| {
12837 window.active.set(true);
12838 let callback_count = callback_count.clone();
12839 window.on_next_frame(move |window, _| {
12840 callback_count.set(callback_count.get() + 1);
12841 window.on_next_frame(move |_, _| {
12842 callback_count.set(callback_count.get() + 1);
12843 });
12844 });
12845 })
12846 .unwrap();
12847
12848 let wake_count = test_window.frame_wake_count();
12851 cx.update(|_| {
12852 test_window.simulate_frame_request(RequestFrameOptions::default());
12853 });
12854 assert_eq!(callback_count.get(), 0);
12855 cx.update_window(window.into(), |_, window, _| {
12856 assert_eq!(window.next_frame_callbacks.borrow().len(), 1);
12857 })
12858 .unwrap();
12859 assert!(
12860 test_window.frame_wake_count() > wake_count,
12861 "a deferred frame callback must wake the frame source for a retry"
12862 );
12863
12864 test_window.simulate_frame_request(RequestFrameOptions::default());
12865 assert_eq!(callback_count.get(), 1);
12866 test_window.simulate_frame_request(RequestFrameOptions::default());
12867 assert_eq!(callback_count.get(), 2);
12868 test_window.simulate_frame_request(RequestFrameOptions::default());
12869 assert_eq!(callback_count.get(), 2);
12870 }
12871
12872 #[gpui::test]
12873 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
12874 let window = cx.add_window(|_, _| Empty);
12875 let test_window = cx.test_window(window.into());
12876
12877 let callback_ran = Rc::new(Cell::new(false));
12878 cx.update_window(window.into(), |_, window, _| {
12879 window.active.set(true);
12882 let callback_ran = callback_ran.clone();
12883 window.on_next_frame(move |window, _| {
12884 window.on_next_frame(move |_, _| callback_ran.set(true));
12885 });
12886 })
12887 .unwrap();
12888
12889 assert!(test_window.simulate_scheduled_frame());
12890 assert!(!callback_ran.get());
12891 assert!(
12892 test_window.frame_scheduled(),
12893 "a callback queued mid-frame must schedule a follow-up before the loop parks"
12894 );
12895
12896 assert!(test_window.simulate_scheduled_frame());
12897 assert!(callback_ran.get());
12898 }
12899
12900 struct RootView {
12901 explicit_size: bool,
12902 child_bounds: Rc<Cell<Bounds<Pixels>>>,
12903 }
12904
12905 impl Render for RootView {
12906 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12907 let child_bounds = self.child_bounds.clone();
12908 let root = div().flex().flex_col().child(
12909 canvas(
12910 move |bounds, _, _| child_bounds.set(bounds),
12911 |_, _, _, _| {},
12912 )
12913 .size_full(),
12914 );
12915 if self.explicit_size {
12916 root.w(px(300.)).h(px(200.))
12917 } else {
12918 root
12919 }
12920 }
12921 }
12922
12923 #[test]
12924 fn auto_sized_window_root_fills_the_window() {
12925 let mut cx = TestAppContext::single();
12926 let child_bounds = Rc::new(Cell::new(Bounds::default()));
12927 let window = cx.add_window({
12928 let child_bounds = child_bounds.clone();
12929 move |_, _| RootView {
12930 explicit_size: false,
12931 child_bounds,
12932 }
12933 });
12934
12935 let viewport_size = cx
12936 .update_window(window.into(), |_, window, cx| {
12937 window.draw(cx).clear(cx);
12938 window.viewport_size()
12939 })
12940 .unwrap();
12941
12942 assert_eq!(child_bounds.get().size, viewport_size);
12943 }
12944
12945 #[test]
12946 fn explicitly_sized_window_root_keeps_its_size() {
12947 let mut cx = TestAppContext::single();
12948 let child_bounds = Rc::new(Cell::new(Bounds::default()));
12949 let window = cx.add_window({
12950 let child_bounds = child_bounds.clone();
12951 move |_, _| RootView {
12952 explicit_size: true,
12953 child_bounds,
12954 }
12955 });
12956
12957 cx.update_window(window.into(), |_, window, cx| {
12958 window.draw(cx).clear(cx);
12959 })
12960 .unwrap();
12961
12962 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
12963 }
12964
12965 struct FileDragView {
12966 path: PathBuf,
12967 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
12968 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
12969 }
12970
12971 struct FileDropExitView(Rc<Cell<usize>>);
12972
12973 impl Render for FileDropExitView {
12974 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12975 div().size_full().on_file_drop_exit({
12976 let observed_file_drop_exit = self.0.clone();
12977 move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
12978 })
12979 }
12980 }
12981
12982 impl Render for FileDragView {
12983 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12984 div()
12985 .id("file-drag")
12986 .size_full()
12987 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
12988 .external_drag_payload(|path: &PathBuf, _, _| {
12989 Some(ExternalDragPayload::Files(FileDragPaths::new([(
12990 path.clone(),
12991 true,
12992 )])))
12993 })
12994 .on_drag_move({
12995 let observed_drag_moves = self.observed_drag_moves.clone();
12996 move |event: &DragMoveEvent<PathBuf>, _, _| {
12997 observed_drag_moves.borrow_mut().push(event.event.position);
12998 }
12999 })
13000 .on_drop({
13001 let observed_drops = self.observed_drops.clone();
13002 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
13003 })
13004 }
13005 }
13006
13007 #[gpui::test]
13008 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
13009 struct Drag {
13010 window: AnyWindowHandle,
13011 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
13012 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
13013 }
13014
13015 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
13016 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
13017 let observed_drops = Rc::new(RefCell::new(Vec::new()));
13018 let window: AnyWindowHandle = cx
13019 .add_window({
13020 let observed_drag_moves = observed_drag_moves.clone();
13021 let observed_drops = observed_drops.clone();
13022 move |_, _| FileDragView {
13023 path,
13024 observed_drag_moves,
13025 observed_drops,
13026 }
13027 })
13028 .into();
13029 cx.test_window(window)
13030 .set_start_external_drag_result(platform_result);
13031
13032 let update_result = cx.update_window(window, |_, window, cx| {
13033 window.draw(cx).clear(cx);
13034 window.dispatch_event(
13035 MouseDownEvent {
13036 position: point(px(10.), px(10.)),
13037 button: MouseButton::Left,
13038 modifiers: Default::default(),
13039 click_count: 1,
13040 first_mouse: false,
13041 }
13042 .to_platform_input(),
13043 cx,
13044 );
13045 window.dispatch_event(
13046 MouseMoveEvent {
13047 position: point(px(20.), px(20.)),
13048 pressed_button: Some(MouseButton::Left),
13049 modifiers: Default::default(),
13050 }
13051 .to_platform_input(),
13052 cx,
13053 );
13054 assert!(cx.active_drag.is_some());
13055 });
13056 assert!(
13057 update_result.is_ok(),
13058 "failed to start drag: {update_result:?}"
13059 );
13060
13061 assert!(cx.test_window(window).external_drag_files().is_empty());
13062 Drag {
13063 window,
13064 observed_drag_moves,
13065 observed_drops,
13066 }
13067 }
13068
13069 let successful_path = PathBuf::from("/tmp/successful-drag");
13070 let successful = start_drag(cx, successful_path.clone(), true);
13071 let outside_position = point(px(-1.), px(20.));
13072 let update_result = cx.update_window(successful.window, |_, window, cx| {
13073 window.dispatch_event(
13074 MouseMoveEvent {
13075 position: outside_position,
13076 pressed_button: Some(MouseButton::Left),
13077 modifiers: Default::default(),
13078 }
13079 .to_platform_input(),
13080 cx,
13081 );
13082 assert!(cx.active_drag.is_none());
13083 });
13084 assert!(
13085 update_result.is_ok(),
13086 "failed to promote drag: {update_result:?}"
13087 );
13088 assert_eq!(
13089 cx.test_window(successful.window).external_drag_files(),
13090 [(successful_path.clone(), true)]
13091 );
13092 assert_eq!(
13095 successful.observed_drag_moves.borrow().last(),
13096 Some(&outside_position)
13097 );
13098
13099 let first_destination_exit_count = Rc::new(Cell::new(0));
13100 let first_destination: AnyWindowHandle = cx
13101 .add_window({
13102 let first_destination_exit_count = first_destination_exit_count.clone();
13103 move |_, _| FileDropExitView(first_destination_exit_count)
13104 })
13105 .into();
13106 let second_destination_exit_count = Rc::new(Cell::new(0));
13107 let second_destination: AnyWindowHandle = cx
13108 .add_window({
13109 let second_destination_exit_count = second_destination_exit_count.clone();
13110 move |_, _| FileDropExitView(second_destination_exit_count)
13111 })
13112 .into();
13113 let reentry_position = point(px(30.), px(30.));
13114 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
13115 let update_result = cx.update_window(first_destination, |_, window, cx| {
13116 window.draw(cx).clear(cx);
13117 window.dispatch_event(
13118 FileDropEvent::Entered {
13119 position: reentry_position,
13120 paths: external_paths(),
13121 }
13122 .to_platform_input(),
13123 cx,
13124 );
13125 assert!(
13126 cx.active_drag
13127 .as_ref()
13128 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
13129 );
13130 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13131 assert!(cx.active_drag.is_none());
13132 assert_eq!(first_destination_exit_count.get(), 1);
13133 assert_eq!(second_destination_exit_count.get(), 0);
13134 });
13135 assert!(
13136 update_result.is_ok(),
13137 "failed to handle drag in first destination window: {update_result:?}"
13138 );
13139
13140 let update_result = cx.update_window(second_destination, |_, window, cx| {
13141 window.draw(cx).clear(cx);
13142 window.dispatch_event(
13143 PlatformInput::KeyDown(KeyDownEvent {
13144 keystroke: Keystroke::parse("down").expect("valid keystroke"),
13145 is_held: false,
13146 prefer_character_input: false,
13147 }),
13148 cx,
13149 );
13150 window.dispatch_event(
13151 FileDropEvent::Entered {
13152 position: reentry_position,
13153 paths: external_paths(),
13154 }
13155 .to_platform_input(),
13156 cx,
13157 );
13158 assert!(
13159 cx.active_drag
13160 .as_ref()
13161 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
13162 );
13163 assert_eq!(first_destination_exit_count.get(), 1);
13164 assert_eq!(second_destination_exit_count.get(), 0);
13165
13166 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13167 assert!(cx.active_drag.is_none());
13168 assert_eq!(first_destination_exit_count.get(), 1);
13169 assert_eq!(second_destination_exit_count.get(), 1);
13170 });
13171 assert!(
13172 update_result.is_ok(),
13173 "failed to handle drag in second destination window: {update_result:?}"
13174 );
13175
13176 let update_result = cx.update_window(successful.window, |_, window, cx| {
13177 window.dispatch_event(
13178 FileDropEvent::Entered {
13179 position: reentry_position,
13180 paths: external_paths(),
13181 }
13182 .to_platform_input(),
13183 cx,
13184 );
13185 assert!(
13186 cx.active_drag
13187 .as_ref()
13188 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
13189 );
13190 assert_eq!(
13191 successful.observed_drag_moves.borrow().last(),
13192 Some(&reentry_position)
13193 );
13194
13195 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13196 assert!(cx.active_drag.is_none());
13197
13198 window.dispatch_event(
13199 FileDropEvent::Entered {
13200 position: reentry_position,
13201 paths: external_paths(),
13202 }
13203 .to_platform_input(),
13204 cx,
13205 );
13206 assert!(
13207 cx.active_drag
13208 .as_ref()
13209 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
13210 );
13211
13212 window.dispatch_event(
13213 FileDropEvent::Submit {
13214 position: reentry_position,
13215 }
13216 .to_platform_input(),
13217 cx,
13218 );
13219 assert_eq!(
13220 successful.observed_drops.borrow().as_slice(),
13221 std::slice::from_ref(&successful_path)
13222 );
13223 assert!(cx.active_drag.is_none());
13224
13225 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13226 assert!(cx.active_drag.is_none());
13227 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
13228 assert!(cx.active_drag.is_none());
13229
13230 window.dispatch_event(
13231 FileDropEvent::Entered {
13232 position: reentry_position,
13233 paths: external_paths(),
13234 }
13235 .to_platform_input(),
13236 cx,
13237 );
13238 assert!(
13239 cx.active_drag
13240 .as_ref()
13241 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
13242 );
13243 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13244 });
13245 assert!(
13246 update_result.is_ok(),
13247 "failed to restore drag in source window: {update_result:?}"
13248 );
13249
13250 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
13251 let cancelled = start_drag(cx, cancelled_path.clone(), true);
13252 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
13253 window.dispatch_event(
13254 MouseMoveEvent {
13255 position: outside_position,
13256 pressed_button: Some(MouseButton::Left),
13257 modifiers: Default::default(),
13258 }
13259 .to_platform_input(),
13260 cx,
13261 );
13262 assert!(cx.active_drag.is_none());
13263
13264 window.dispatch_event(
13265 FileDropEvent::Entered {
13266 position: reentry_position,
13267 paths: ExternalPaths([cancelled_path].into_iter().collect()),
13268 }
13269 .to_platform_input(),
13270 cx,
13271 );
13272 assert!(
13273 cx.active_drag
13274 .as_ref()
13275 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
13276 );
13277 assert!(cx.stop_active_drag(window));
13278 assert!(cx.active_drag.is_none());
13279 });
13280 assert!(
13281 update_result.is_ok(),
13282 "failed to cancel restored drag: {update_result:?}"
13283 );
13284 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
13285
13286 let removed_path = PathBuf::from("/tmp/removed-window-drag");
13287 let removed = start_drag(cx, removed_path, true);
13288 let removed_window_id = removed.window.window_id();
13289 let update_result = cx.update_window(removed.window, |_, window, cx| {
13290 window.dispatch_event(
13291 MouseMoveEvent {
13292 position: outside_position,
13293 pressed_button: Some(MouseButton::Left),
13294 modifiers: Default::default(),
13295 }
13296 .to_platform_input(),
13297 cx,
13298 );
13299 assert!(cx.active_drag.is_none());
13300 window.remove_window();
13301 });
13302 assert!(
13303 update_result.is_ok(),
13304 "failed to remove drag source window: {update_result:?}"
13305 );
13306 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
13307
13308 let failed_path = PathBuf::from("/tmp/failed-drag");
13309 let failed = start_drag(cx, failed_path.clone(), false);
13310 let update_result = cx.update_window(failed.window, |_, window, cx| {
13311 for x_position in [-1., -2.] {
13312 window.dispatch_event(
13313 MouseMoveEvent {
13314 position: point(px(x_position), px(20.)),
13315 pressed_button: Some(MouseButton::Left),
13316 modifiers: Default::default(),
13317 }
13318 .to_platform_input(),
13319 cx,
13320 );
13321 }
13322 assert!(cx.active_drag.is_some());
13323 });
13324 assert!(
13325 update_result.is_ok(),
13326 "failed to retain drag after platform failure: {update_result:?}"
13327 );
13328 assert_eq!(
13329 cx.test_window(failed.window).external_drag_files(),
13330 [(failed_path, true)]
13331 );
13332 }
13333
13334 struct FocusForwarder {
13335 a: FocusHandle,
13336 b: FocusHandle,
13337 }
13338
13339 impl Render for FocusForwarder {
13340 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13341 div()
13342 .size_full()
13343 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
13344 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
13345 }
13346 }
13347
13348 #[gpui::test]
13352 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
13353 let b_focus_count = Rc::new(Cell::new(0));
13354 let window = cx.add_window({
13355 let b_focus_count = b_focus_count.clone();
13356 move |window, cx| {
13357 let a = cx.focus_handle();
13358 let b = cx.focus_handle();
13359 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
13360 let b = this.b.clone();
13361 window.focus(&b, cx);
13362 })
13363 .detach();
13364 cx.on_focus(&b, window, move |_, _, _| {
13365 b_focus_count.set(b_focus_count.get() + 1);
13366 })
13367 .detach();
13368 FocusForwarder { a, b }
13369 }
13370 });
13371
13372 window
13373 .update(cx, |_, window, _| window.activate_window())
13374 .unwrap();
13375 cx.executor().run_until_parked();
13376
13377 window
13378 .update(cx, |this, window, cx| {
13379 let a = this.a.clone();
13380 window.focus(&a, cx);
13381 })
13382 .unwrap();
13383 cx.executor().run_until_parked();
13384
13385 window
13386 .update(cx, |this, window, _| {
13387 assert!(this.b.is_focused(window));
13388 })
13389 .unwrap();
13390 assert_eq!(b_focus_count.get(), 1);
13391 }
13392
13393 #[gpui::test]
13394 fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
13395 let events = Rc::new(RefCell::new(Vec::new()));
13396 let window = cx.add_window({
13397 let events = events.clone();
13398 move |_, _| TouchDragListener { events }
13399 });
13400 let touch = TouchId(1);
13401
13402 dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
13403 dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
13404 dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
13405
13406 assert_eq!(
13407 events.borrow().as_slice(),
13408 [
13409 (TouchPhase::Started, px(10.)),
13410 (TouchPhase::Moved, px(30.)),
13411 (TouchPhase::Ended, px(40.)),
13412 ]
13413 );
13414 }
13415
13416 #[gpui::test]
13417 fn back_gesture_is_claimed_by_the_innermost_listener(cx: &mut TestAppContext) {
13418 let claims = Rc::new(RefCell::new(Vec::new()));
13419 let window = cx.add_window({
13420 let claims = claims.clone();
13421 move |_, _| BackListeners { claims }
13422 });
13423 let dispatch_back = |cx: &mut TestAppContext, x: f32| {
13424 window
13425 .update(cx, |_, window, cx| {
13426 window
13427 .dispatch_event(
13428 BackGestureEvent {
13429 phase: BackGesturePhase::Started,
13430 start_position: point(px(x), px(10.)),
13431 progress: 0.,
13432 }
13433 .to_platform_input(),
13434 cx,
13435 )
13436 .default_prevented
13437 })
13438 .unwrap()
13439 };
13440 assert!(dispatch_back(cx, 10.));
13441 assert!(dispatch_back(cx, 80.));
13442 assert!(!dispatch_back(cx, 150.));
13443 assert_eq!(claims.borrow().as_slice(), ["inner", "outer"]);
13444 }
13445
13446 struct BackListeners {
13447 claims: Rc<RefCell<Vec<&'static str>>>,
13448 }
13449
13450 impl Render for BackListeners {
13451 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
13452 let claim = |name: &'static str| {
13453 let claims = self.claims.clone();
13454 move |_: &BackGestureEvent, _: &mut Window, _: &mut crate::App| {
13455 claims.borrow_mut().push(name)
13456 }
13457 };
13458 div().size_full().child(
13459 div()
13460 .w(px(100.))
13461 .h_full()
13462 .on_back_gesture(claim("outer"))
13463 .child(div().w(px(50.)).h_full().on_back_gesture(claim("inner"))),
13464 )
13465 }
13466 }
13467
13468 struct TouchDragListener {
13469 events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
13470 }
13471
13472 impl Render for TouchDragListener {
13473 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
13474 let events = self.events.clone();
13475 canvas(
13476 |_, _, _| {},
13477 move |_, _, window, _| {
13478 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
13479 if phase != DispatchPhase::Bubble {
13480 return;
13481 }
13482 events.borrow_mut().push((event.phase, event.position.x));
13483 if event.phase == TouchPhase::Started {
13484 window.prevent_default();
13485 }
13486 });
13487 },
13488 )
13489 }
13490 }
13491
13492 #[gpui::test]
13493 fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
13494 for response in [
13495 LongPressResponse::PreventDefault,
13496 LongPressResponse::StopPropagation,
13497 LongPressResponse::None,
13498 ] {
13499 let phases = Rc::new(RefCell::new(Vec::new()));
13500 let window = cx.add_window({
13501 let phases = phases.clone();
13502 move |_, _| LongPressListener { phases, response }
13503 });
13504 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13505 cx.executor().advance_clock(Duration::from_millis(501));
13506 cx.executor().run_until_parked();
13507 window
13508 .update(cx, |_, window, _| {
13509 assert_eq!(
13510 window.long_press_capture.is_some(),
13511 response == LongPressResponse::PreventDefault
13512 );
13513 })
13514 .unwrap();
13515 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
13516 dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
13517 window
13518 .update(cx, |_, window, _| {
13519 assert!(window.long_press_capture.is_none());
13520 })
13521 .unwrap();
13522
13523 let phases = phases.borrow();
13524 if response == LongPressResponse::PreventDefault {
13525 assert_eq!(
13526 phases.as_slice(),
13527 [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
13528 );
13529 } else {
13530 assert_eq!(phases.as_slice(), [TouchPhase::Started]);
13531 }
13532 }
13533 }
13534
13535 #[gpui::test]
13536 fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
13537 let phases = Rc::new(RefCell::new(Vec::new()));
13538 let window = cx.add_window({
13539 let phases = phases.clone();
13540 move |_, _| LongPressListener {
13541 phases,
13542 response: LongPressResponse::None,
13543 }
13544 });
13545 window
13546 .update(cx, |_, window, _| {
13547 window.prevent_default();
13548 })
13549 .unwrap();
13550
13551 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13552 cx.executor().advance_clock(Duration::from_millis(501));
13553 cx.executor().run_until_parked();
13554 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
13555
13556 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
13557 }
13558
13559 #[gpui::test]
13560 fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
13561 for (phase, position) in [
13562 (TouchPhase::Ended, 0.),
13563 (TouchPhase::Cancelled, 0.),
13564 (TouchPhase::Moved, 20.),
13565 ] {
13566 let phases = Rc::new(RefCell::new(Vec::new()));
13567 let window = cx.add_window({
13568 let phases = phases.clone();
13569 move |_, _| LongPressListener {
13570 phases,
13571 response: LongPressResponse::PreventDefault,
13572 }
13573 });
13574 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13575 dispatch_touch(window, cx, TouchId(1), phase, position);
13576 cx.executor().advance_clock(Duration::from_millis(501));
13577 cx.executor().run_until_parked();
13578
13579 assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
13580 }
13581 }
13582
13583 #[gpui::test]
13584 fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
13585 let phases = Rc::new(RefCell::new(Vec::new()));
13586 let window = cx.add_window({
13587 let phases = phases.clone();
13588 move |_, _| LongPressListener {
13589 phases,
13590 response: LongPressResponse::PreventDefault,
13591 }
13592 });
13593 let first_touch = TouchId(1);
13594 dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
13595 cx.executor().advance_clock(Duration::from_millis(250));
13596 dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
13597 dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
13598
13599 cx.executor().advance_clock(Duration::from_millis(251));
13600 cx.executor().run_until_parked();
13601 assert!(phases.borrow().is_empty());
13602
13603 cx.executor().advance_clock(Duration::from_millis(250));
13604 cx.executor().run_until_parked();
13605 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
13606 }
13607
13608 #[gpui::test]
13609 fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
13610 test_underline_paint_at_scales(cx, |window| {
13611 let (numerator, denominator) = match window.scale_factor() {
13612 1.0 => (1, 1),
13613 1.25 => (5, 4),
13614 1.5 => (3, 2),
13615 2.0 => (2, 1),
13616 3.0 => (3, 1),
13617 scale => panic!("unexpected scale {scale}"),
13618 };
13619 let snap = |quarters: i32| {
13620 let scaled = quarters * numerator;
13621 let divisor = 4 * denominator;
13622 let rounded =
13623 scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
13624 ScaledPixels((scaled.signum() * rounded) as f32)
13625 };
13626 let stroke = |quarters| {
13627 if quarters == 0 {
13628 ScaledPixels(0.)
13629 } else {
13630 snap(quarters).max(ScaledPixels(1.))
13631 }
13632 };
13633
13634 for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
13635 for width in [0, 1, 3, 84] {
13636 for thickness in [0, 1, 4, 7] {
13637 for wavy in [false, true] {
13638 let style = UnderlineStyle {
13639 thickness: px(thickness as f32 / 4.),
13640 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
13641 wavy,
13642 offset: px(0.),
13643 };
13644 let bounds = Bounds::new(
13645 point(snap(origin), snap(-origin)),
13646 size(
13647 stroke(width),
13648 stroke(thickness) * if wavy { 3. } else { 1. },
13649 ),
13650 );
13651 let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
13652 let width = px(width as f32 / 4.);
13653 assert_eq!(window.underline_bounds(origin, width, &style), bounds);
13654 let original = paint_test_underlines(window, |window| {
13655 window.paint_underline(origin, width, &style);
13656 })
13657 .to_vec();
13658 assert_eq!(original.len(), usize::from(!bounds.is_empty()));
13659 if let Some(underline) = original.first() {
13660 assert_eq!(underline.bounds, bounds);
13661 assert_eq!(underline.thickness, stroke(thickness));
13662 assert_eq!(underline.wavy, wavy.into());
13663 assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
13664 }
13665
13666 let underlines = paint_test_underlines(window, |window| {
13667 window.paint_underline_with_exclusions(origin, width, &style, &[]);
13668 });
13669 assert_eq!(underlines.len(), original.len());
13670 for (actual, original) in underlines.iter().zip(&original) {
13671 assert_same_underline_geometry(actual, original);
13672 assert_eq!(actual.content_mask, original.content_mask);
13673 }
13674
13675 let left = bounds.left().0 as i32;
13676 let right = bounds.right().0 as i32;
13677 let exclusions = [
13678 (15, 25),
13679 (3, 7),
13680 (5, 10),
13681 (10, 12),
13682 (0, 0),
13683 (4, 2),
13684 (-50, -1),
13685 (70, 100),
13686 ]
13687 .map(|(start, end)| {
13688 ScaledPixels((left + start) as f32)
13689 ..ScaledPixels((left + end) as f32)
13690 });
13691 let underlines = paint_test_underlines(window, |window| {
13692 window.paint_underline_with_exclusions(
13693 origin,
13694 width,
13695 &style,
13696 &exclusions,
13697 );
13698 });
13699 let expected = (left..right)
13700 .filter(|column| {
13701 !bounds.is_empty()
13702 && !exclusions.iter().any(|span| {
13703 span.contains(&ScaledPixels(*column as f32))
13704 })
13705 })
13706 .collect::<Vec<_>>();
13707 assert_eq!(underline_device_columns(underlines), expected);
13708 for underline in underlines {
13709 assert_same_underline_geometry(underline, &original[0]);
13710 }
13711 }
13712 }
13713 }
13714 }
13715 });
13716 }
13717
13718 #[gpui::test]
13719 fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
13720 test_underline_paint_at_scales(cx, |window| {
13721 if window.scale_factor() != 2.0 {
13722 return;
13723 }
13724 let style = UnderlineStyle {
13725 thickness: px(1.),
13726 color: None,
13727 wavy: true,
13728 offset: px(0.),
13729 };
13730 let origin = point(px(2.888_183_8), px(15.357_917));
13731 let width = px(23.848_145) - origin.x;
13732 let original = paint_test_underlines(window, |window| {
13733 window.paint_underline(origin, width, &style);
13734 })[0];
13735 assert_eq!(original.bounds.left(), ScaledPixels(6.));
13736 assert_eq!(original.bounds.right(), ScaledPixels(48.));
13737 let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
13738 assert_eq!(point_bounds.left(), ScaledPixels(6.));
13739 assert_eq!(point_bounds.right(), ScaledPixels(28.));
13740
13741 let underlines = paint_test_underlines(window, |window| {
13742 window.paint_underline_with_exclusions(
13743 origin,
13744 width,
13745 &style,
13746 &[point_bounds.left()..point_bounds.right()],
13747 );
13748 });
13749 assert_eq!(underlines.len(), 1);
13750 assert_same_underline_geometry(&underlines[0], &original);
13751 assert_eq!(
13752 underline_device_columns(underlines),
13753 (28..48).collect::<Vec<_>>()
13754 );
13755 });
13756 }
13757
13758 #[gpui::test]
13759 fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
13760 test_underline_paint_at_scales(cx, |window| {
13761 let scale = window.scale_factor();
13762 let original_mask = window.content_mask();
13763 let original_opacity = window.element_opacity();
13764 let mask = ContentMask {
13765 bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
13766 ..Default::default()
13767 };
13768 let style = UnderlineStyle {
13769 thickness: px(2.),
13770 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
13771 wavy: true,
13772 offset: px(0.),
13773 };
13774 let origin = point(px(-1.25), px(9.25));
13775 let width = px(24.);
13776 window.with_content_mask(Some(mask), |window| {
13777 window.with_element_opacity(Some(0.5), |window| {
13778 window.with_element_opacity(Some(0.5), |window| {
13779 let original = paint_test_underlines(window, |window| {
13780 window.paint_underline(origin, width, &style);
13781 })[0];
13782 assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
13783 let underlines = paint_test_underlines(window, |window| {
13784 window.paint_underline_with_exclusions(
13785 origin,
13786 width,
13787 &style,
13788 &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
13789 );
13790 });
13791 assert_eq!(underlines.len(), 2);
13792 let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
13793 |(left, right)| {
13794 Bounds::from_corners(
13795 point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
13796 point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
13797 )
13798 },
13799 );
13800 assert_eq!(
13801 underlines
13802 .iter()
13803 .map(|underline| underline.content_mask.bounds)
13804 .collect::<Vec<_>>(),
13805 expected
13806 );
13807 for underline in underlines {
13808 assert_same_underline_geometry(underline, &original);
13809 }
13810 });
13811 });
13812 });
13813 assert_eq!(window.content_mask(), original_mask);
13814 assert_eq!(window.element_opacity(), original_opacity);
13815 });
13816 }
13817
13818 #[gpui::test]
13819 fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
13820 test_underline_paint_at_scales(cx, |window| {
13821 let style = UnderlineStyle {
13822 thickness: px(1.),
13823 color: None,
13824 wavy: true,
13825 offset: px(0.),
13826 };
13827 let origin = point(px(-4.), px(-1.));
13828 let width = px(8.);
13829 let left = (-4. * window.scale_factor()) as i32;
13830 let right = (4. * window.scale_factor()) as i32;
13831 let endpoints = [-16, -8, -1, 0, 1, 8, 16];
13832 for first_start in endpoints {
13833 for first_end in endpoints {
13834 for second_start in endpoints {
13835 for second_end in endpoints {
13836 let exclusions = [first_start..first_end, second_start..second_end];
13837 let expected = (left..right)
13838 .filter(|column| {
13839 !exclusions.iter().any(|span| span.contains(column))
13840 })
13841 .collect::<Vec<_>>();
13842 let exclusions = exclusions.map(|span| {
13843 ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
13844 });
13845 let underlines = paint_test_underlines(window, |window| {
13846 window.paint_underline_with_exclusions(
13847 origin,
13848 width,
13849 &style,
13850 &exclusions,
13851 );
13852 });
13853 assert_eq!(
13854 underline_device_columns(underlines),
13855 expected,
13856 "{exclusions:?}"
13857 );
13858 }
13859 }
13860 }
13861 }
13862 });
13863 }
13864
13865 #[derive(Clone, Copy, PartialEq)]
13866 enum LongPressResponse {
13867 PreventDefault,
13868 StopPropagation,
13869 None,
13870 }
13871
13872 struct LongPressListener {
13873 phases: Rc<RefCell<Vec<TouchPhase>>>,
13874 response: LongPressResponse,
13875 }
13876
13877 impl Render for LongPressListener {
13878 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
13879 let entity = cx.entity();
13880 let phases = self.phases.clone();
13881 let response = self.response;
13882 canvas(
13883 |_, _, _| {},
13884 move |_, _, window, _| {
13885 window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
13886 if phase != DispatchPhase::Bubble {
13887 return;
13888 }
13889 phases.borrow_mut().push(event.phase);
13890 match response {
13891 LongPressResponse::PreventDefault => {
13892 window.capture_long_press(&entity);
13893 window.prevent_default();
13894 }
13895 LongPressResponse::StopPropagation => cx.stop_propagation(),
13896 LongPressResponse::None => {}
13897 }
13898 });
13899 },
13900 )
13901 }
13902 }
13903
13904 struct UnderlineTestView(Rc<dyn Fn(&mut Window)>);
13905
13906 impl Render for UnderlineTestView {
13907 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13908 let paint = self.0.clone();
13909 canvas(
13910 |_, _, _| {},
13911 move |_, _, window, _| {
13912 window.content_mask_stack.push(ContentMask::rect(Bounds::from_corners(
13913 point(px(-1000.), px(-1000.)),
13914 point(px(1000.), px(1000.)),
13915 )));
13916 paint(window);
13917 window.content_mask_stack.pop();
13918 },
13919 )
13920 .size_full()
13921 }
13922 }
13923
13924 fn test_underline_paint_at_scales(
13925 cx: &mut TestAppContext,
13926 paint: impl Fn(&mut Window) + 'static,
13927 ) {
13928 let window = cx.add_window(move |_, _| UnderlineTestView(Rc::new(paint)));
13929 for scale in [1., 1.25, 1.5, 2., 3.] {
13930 cx.simulate_window_scale_factor_change(window.into(), scale);
13931 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
13932 .unwrap();
13933 }
13934 }
13935
13936 fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
13937 window.next_frame.scene.clear();
13938 paint(window);
13939 &window.next_frame.scene.underlines
13940 }
13941
13942 fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
13943 assert_eq!(actual.bounds, expected.bounds);
13944 assert_eq!(actual.thickness, expected.thickness);
13945 assert_eq!(actual.wavy, expected.wavy);
13946 assert_eq!(actual.color, expected.color);
13947 assert_eq!(actual.pad, expected.pad);
13948 }
13949
13950 fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
13951 underlines
13952 .iter()
13953 .flat_map(|underline| {
13954 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
13955 bounds.left().0 as i32..bounds.right().0 as i32
13956 })
13957 .collect()
13958 }
13959
13960 actions!(window_test, [StandaloneModifierAction]);
13961
13962 struct StandaloneModifierView {
13963 focus_handle: FocusHandle,
13964 action_count: usize,
13965 }
13966
13967 impl Render for StandaloneModifierView {
13968 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
13969 div()
13970 .key_context("StandaloneModifier")
13971 .track_focus(&self.focus_handle)
13972 .on_action(cx.listener(|this, _: &StandaloneModifierAction, _, _| {
13973 this.action_count += 1;
13974 }))
13975 }
13976 }
13977
13978 #[gpui::test]
13979 fn test_standalone_modifier_sequence_timeout_and_recovery(cx: &mut TestAppContext) {
13980 use crate::{KeyBinding, Modifiers};
13981
13982 cx.update(|cx| {
13983 cx.bind_keys([KeyBinding::new(
13984 "shift shift",
13985 StandaloneModifierAction,
13986 Some("StandaloneModifier"),
13987 )]);
13988 });
13989 let (view, cx) = cx.add_window_view(|window, cx| {
13990 let focus_handle = cx.focus_handle();
13991 window.focus(&focus_handle, cx);
13992 StandaloneModifierView {
13993 focus_handle,
13994 action_count: 0,
13995 }
13996 });
13997 let shift = Modifiers {
13998 shift: true,
13999 ..Modifiers::default()
14000 };
14001 cx.simulate_modifiers_change(shift);
14002 cx.simulate_modifiers_change(Modifiers::default());
14003 cx.update(|window, _| {
14004 assert_eq!(
14005 window.pending_input_keystrokes(),
14006 Some([Keystroke::parse("shift").expect("valid keystroke")].as_slice())
14007 );
14008 });
14009 cx.background_executor.advance_clock(Duration::from_secs(2));
14010 cx.run_until_parked();
14011 cx.update(|window, cx| {
14012 assert!(!window.has_pending_keystrokes());
14013 assert_eq!(view.read(cx).action_count, 0);
14014 });
14015
14016 cx.simulate_modifiers_change(shift);
14017 cx.simulate_modifiers_change(Modifiers::default());
14018 cx.update(|window, cx| {
14019 assert!(window.has_pending_keystrokes());
14020 assert_eq!(view.read(cx).action_count, 0);
14021 });
14022
14023 cx.simulate_modifiers_change(shift);
14024 cx.simulate_modifiers_change(Modifiers::default());
14025 cx.update(|window, cx| {
14026 assert!(!window.has_pending_keystrokes());
14027 assert_eq!(view.read(cx).action_count, 1);
14028 });
14029 }
14030
14031 #[gpui::test]
14032 fn test_standalone_modifier_sequence_dispatches_before_timeout(cx: &mut TestAppContext) {
14033 use crate::{KeyBinding, Modifiers};
14034
14035 cx.update(|cx| {
14036 cx.bind_keys([KeyBinding::new(
14037 "shift shift",
14038 StandaloneModifierAction,
14039 Some("StandaloneModifier"),
14040 )]);
14041 });
14042 let (view, cx) = cx.add_window_view(|window, cx| {
14043 let focus_handle = cx.focus_handle();
14044 window.focus(&focus_handle, cx);
14045 StandaloneModifierView {
14046 focus_handle,
14047 action_count: 0,
14048 }
14049 });
14050 let shift = Modifiers {
14051 shift: true,
14052 ..Modifiers::default()
14053 };
14054 cx.simulate_modifiers_change(shift);
14055 cx.simulate_modifiers_change(Modifiers::default());
14056 cx.background_executor
14057 .advance_clock(Duration::from_millis(500));
14058 cx.update(|window, cx| {
14059 assert!(window.has_pending_keystrokes());
14060 assert_eq!(view.read(cx).action_count, 0);
14061 });
14062 cx.simulate_modifiers_change(shift);
14063 cx.simulate_modifiers_change(Modifiers::default());
14064 cx.update(|window, cx| {
14065 assert!(!window.has_pending_keystrokes());
14066 assert_eq!(view.read(cx).action_count, 1);
14067 });
14068 cx.background_executor.advance_clock(Duration::from_secs(2));
14069 cx.run_until_parked();
14070 cx.update(|window, cx| {
14071 assert!(!window.has_pending_keystrokes());
14072 assert_eq!(view.read(cx).action_count, 1);
14073 });
14074 }
14075
14076 fn dispatch_touch<T: 'static>(
14077 window: crate::WindowHandle<T>,
14078 cx: &mut TestAppContext,
14079 id: TouchId,
14080 phase: TouchPhase,
14081 x: f32,
14082 ) {
14083 window
14084 .update(cx, |_, window, cx| {
14085 window.dispatch_event(
14086 TouchEvent {
14087 id,
14088 phase,
14089 position: point(px(x), px(0.)),
14090 predicted_position: None,
14091 force: None,
14092 }
14093 .to_platform_input(),
14094 cx,
14095 );
14096 })
14097 .unwrap();
14098 }
14099
14100 #[gpui::test]
14101 fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
14102 struct Child {
14103 renders: usize,
14104 }
14105
14106 impl Render for Child {
14107 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
14108 self.renders += 1;
14109 div().size_full().bg(crate::rgb(0xff0000))
14110 }
14111 }
14112
14113 struct Root {
14114 opacity: f32,
14115 width: Pixels,
14116 child: crate::Entity<Child>,
14117 }
14118
14119 impl Render for Root {
14120 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
14121 div()
14122 .w(self.width)
14123 .h(px(200.))
14124 .opacity(self.opacity)
14125 .hover(|style| style.opacity(1.))
14126 .child(
14127 self.child
14128 .clone()
14129 .cached(crate::StyleRefinement::default().size(px(100.))),
14130 )
14131 }
14132 }
14133
14134 fn update_and_draw(
14137 window: crate::WindowHandle<Root>,
14138 child: &crate::Entity<Child>,
14139 cx: &mut TestAppContext,
14140 update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
14141 ) -> (f32, usize) {
14142 window
14143 .update(cx, |root, window, cx| {
14144 update(root, window, cx);
14145 cx.notify();
14146 })
14147 .expect("update root");
14148 for _ in 0..3 {
14149 let (alpha, renders, requested_frames) = cx
14150 .update_window(window.into(), |_, window, cx| {
14151 window.draw(cx).clear(cx);
14152 let quads = &window.rendered_frame.scene.quads;
14153 assert_eq!(quads.len(), 1);
14154 let alpha = quads.first().expect("child quad").background.solid.a;
14155 (
14156 alpha,
14157 child.read(cx).renders,
14158 window.simulate_next_frame(cx),
14159 )
14160 })
14161 .expect("draw window");
14162 if requested_frames == 0 {
14163 return (alpha, renders);
14164 }
14165 }
14166 panic!("cached child kept requesting frames");
14167 }
14168
14169 let child = cx.new(|_| Child { renders: 0 });
14170 let window = cx.add_window(|_, _| Root {
14171 opacity: 1.,
14172 width: px(200.),
14173 child: child.clone(),
14174 });
14175 let outside = point(px(500.), px(500.));
14176 let inside = point(px(50.), px(50.));
14177 let beside = point(px(250.), px(50.));
14178
14179 let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
14181 window.simulate_mouse_move(outside, cx)
14182 };
14183 assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
14184 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
14185 let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
14186 assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
14187 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
14188
14189 let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
14191 window.simulate_mouse_move(inside, cx)
14192 };
14193 assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
14194 let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
14195 window.simulate_mouse_move(beside, cx)
14196 };
14197 assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
14198
14199 let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
14202 assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
14203 }
14204
14205 #[gpui::test]
14206 fn test_drag_cursor_applies_before_next_paint(cx: &mut TestAppContext) {
14207 struct ResizeHandle;
14208
14209 impl Render for ResizeHandle {
14210 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
14211 div().size_full().cursor_text().child(
14212 div()
14213 .id("resize-handle")
14214 .w(px(4.))
14215 .h_full()
14216 .cursor_col_resize()
14217 .on_drag((), |_, _, _, cx| cx.new(|_| Empty)),
14218 )
14219 }
14220 }
14221
14222 let window = cx.add_window(|_, _| ResizeHandle);
14223 let handle_position = point(px(1.), px(10.));
14224 let drag_position = point(px(20.), px(10.));
14225 let cursor_observer = cx.clone();
14226
14227 let update_result = cx.update_window(window.into(), |_, window, cx| {
14228 window.hovered.set(true);
14229 window.active.set(true);
14230 window.draw(cx).clear(cx);
14231 window.dispatch_event(
14232 MouseMoveEvent {
14233 position: handle_position,
14234 ..Default::default()
14235 }
14236 .to_platform_input(),
14237 cx,
14238 );
14239 window.dispatch_event(
14240 MouseDownEvent {
14241 position: handle_position,
14242 button: MouseButton::Left,
14243 ..Default::default()
14244 }
14245 .to_platform_input(),
14246 cx,
14247 );
14248 window.dispatch_event(
14249 MouseMoveEvent {
14250 position: drag_position,
14251 pressed_button: Some(MouseButton::Left),
14252 ..Default::default()
14253 }
14254 .to_platform_input(),
14255 cx,
14256 );
14257 assert!(cx.has_active_drag());
14258 assert_eq!(
14260 cursor_observer.test_platform().cursor_style(),
14261 CursorStyle::ResizeColumn
14262 );
14263
14264 window.draw(cx).clear(cx);
14265 window.dispatch_event(
14266 MouseUpEvent {
14267 position: drag_position,
14268 button: MouseButton::Left,
14269 ..Default::default()
14270 }
14271 .to_platform_input(),
14272 cx,
14273 );
14274 window.draw(cx).clear(cx);
14275 });
14276 assert!(
14277 update_result.is_ok(),
14278 "failed to run drag: {update_result:?}"
14279 );
14280 assert_eq!(
14281 cursor_observer.test_platform().cursor_style(),
14282 CursorStyle::IBeam
14283 );
14284 }
14285}
14286
14287#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
14288mod inspector_tests {
14289 use super::*;
14290 use crate::{
14291 DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
14292 };
14293
14294 #[gpui::test]
14295 fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
14296 let windows = [
14297 cx.add_window(|_, cx| InspectorTestRoot {
14298 child: cx.new(|_| InspectorTestView::default()),
14299 }),
14300 cx.add_window(|_, cx| InspectorTestRoot {
14301 child: cx.new(|_| InspectorTestView::default()),
14302 }),
14303 ];
14304 for window in windows {
14305 assert_closed_inspector(window.into(), cx);
14306 }
14307 for _ in 0..2 {
14308 cx.update_window(windows[0].into(), |root, window, cx| {
14309 let root = root.downcast::<InspectorTestRoot>().expect("test root");
14310 let child_widths = root.read(cx).child.read(cx).child_widths.clone();
14311 window.toggle_inspector(cx);
14312 window.draw(cx).clear(cx);
14313 assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
14314 let path = window
14315 .rendered_frame
14316 .next_inspector_instance_ids
14317 .iter()
14318 .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
14319 .expect("anonymous siblings share an inspector path");
14320 let selected_id = InspectorElementId {
14321 path,
14322 instance_id: 1,
14323 };
14324 let position = window
14325 .rendered_frame
14326 .hitboxes
14327 .iter()
14328 .find(|hitbox| {
14329 window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
14330 == Some(&selected_id)
14331 })
14332 .expect("middle sibling is pickable")
14333 .bounds
14334 .center();
14335 window.simulate_mouse_move(position, cx);
14336 window.dispatch_event(
14337 PlatformInput::MouseDown(MouseDownEvent {
14338 position,
14339 button: MouseButton::Left,
14340 modifiers: Modifiers::default(),
14341 click_count: 1,
14342 first_mouse: false,
14343 }),
14344 cx,
14345 );
14346 window.dispatch_event(
14347 PlatformInput::MouseUp(MouseUpEvent {
14348 position,
14349 button: MouseButton::Left,
14350 modifiers: Modifiers::default(),
14351 click_count: 1,
14352 }),
14353 cx,
14354 );
14355 assert!(!window.is_inspector_picking(cx));
14356 assert_eq!(
14357 window
14358 .inspector
14359 .as_ref()
14360 .expect("open inspector")
14361 .read(cx)
14362 .active_element_id(),
14363 Some(&selected_id)
14364 );
14365 window.draw(cx).clear(cx);
14366 window.with_inspector_state::<DivInspectorState, _>(
14367 Some(&selected_id),
14368 cx,
14369 |state, _| {
14370 let state = state.as_mut().expect("selected div has style state");
14371 assert_eq!(
14372 state.base_style.size.width,
14373 Some(crate::Length::from(px(10.)))
14374 );
14375 state.base_style.size.width = Some(crate::Length::from(px(25.)));
14376 },
14377 );
14378 window.refresh();
14379 window.draw(cx).clear(cx);
14380 assert_eq!(
14381 child_widths.borrow().as_slice(),
14382 &[px(10.), px(25.), px(10.)]
14383 );
14384 })
14385 .expect("pick and edit a cached child");
14386 assert_closed_inspector(windows[1].into(), cx);
14387 windows[0]
14388 .update(cx, |_, window, cx| window.toggle_inspector(cx))
14389 .expect("close inspector");
14390 assert_closed_inspector(windows[0].into(), cx);
14391 }
14392 }
14393
14394 struct InspectorTestRoot {
14395 child: Entity<InspectorTestView>,
14396 }
14397
14398 impl Render for InspectorTestRoot {
14399 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14400 self.child
14401 .clone()
14402 .cached(StyleRefinement::default().size(px(100.)))
14403 }
14404 }
14405
14406 #[derive(Default)]
14407 struct InspectorTestView {
14408 child_widths: Rc<RefCell<Vec<Pixels>>>,
14409 }
14410
14411 impl Render for InspectorTestView {
14412 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14413 let child_widths = self.child_widths.clone();
14414 div()
14415 .on_children_prepainted(move |bounds, _, _| {
14416 *child_widths.borrow_mut() =
14417 bounds.iter().map(|bounds| bounds.size.width).collect();
14418 })
14419 .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
14420 .id("inspector-root")
14421 .flex()
14422 .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
14423 }
14424 }
14425
14426 fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
14427 cx.update_window(window, |root, window, cx| {
14428 window.draw(cx).clear(cx);
14429 window.draw(cx).clear(cx);
14430 let root = root.downcast::<InspectorTestRoot>().expect("test root");
14431 assert_eq!(
14432 root.read(cx)
14433 .child
14434 .read(cx)
14435 .child_widths
14436 .borrow()
14437 .as_slice(),
14438 &[px(10.); 3]
14439 );
14440 for frame in [&window.rendered_frame, &window.next_frame] {
14441 assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
14442 assert_eq!(frame.inspector_hitboxes.capacity(), 0);
14443 }
14444 })
14445 .expect("closed inspector has no bookkeeping and no style overrides");
14446 }
14447}
14448
14449#[cfg(test)]
14451mod vn_assume_active_tests {
14452 use crate::{
14453 Context, FocusHandle, Render, Subscription, TestAppContext, Window, div, prelude::*, px,
14454 size,
14455 };
14456 use std::{cell::Cell, rc::Rc};
14457
14458 struct Focusable {
14459 handle: FocusHandle,
14460 _on_focus: Subscription,
14461 }
14462
14463 impl Render for Focusable {
14464 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14465 div().size_full().track_focus(&self.handle)
14466 }
14467 }
14468
14469 #[gpui::test]
14470 fn an_assumed_active_window_runs_focus_and_ignores_the_os(cx: &mut TestAppContext) {
14471 let focused = Rc::new(Cell::new(0u32));
14472 let counter = focused.clone();
14473 let window = cx.open_window(size(px(200.), px(200.)), move |window, cx| {
14474 let handle = cx.focus_handle();
14475 let on_focus = cx.on_focus(&handle, window, move |_, _, _| counter.set(counter.get() + 1));
14476 Focusable { handle, _on_focus: on_focus }
14477 });
14478 let platform = cx.test_window(window.into());
14479 platform.simulate_active_status_change(false);
14480 cx.run_until_parked();
14481
14482 window
14485 .update(cx, |view, window, cx| window.focus(&view.handle, cx))
14486 .unwrap();
14487 cx.run_until_parked();
14488 assert_eq!(focused.get(), 0, "no focus event without activation");
14489
14490 window
14492 .update(cx, |_, window, _| window.set_assume_active(true))
14493 .unwrap();
14494 cx.run_until_parked();
14495 assert_eq!(focused.get(), 1, "the focus event carries the path");
14496 let active = |cx: &mut TestAppContext| {
14497 window
14498 .update(cx, |_, window, _| window.is_window_active())
14499 .unwrap()
14500 };
14501 assert!(active(cx));
14502
14503 platform.simulate_active_status_change(false);
14505 cx.run_until_parked();
14506 assert!(active(cx), "still active after the OS says otherwise");
14507
14508 window
14510 .update(cx, |_, window, _| window.set_assume_active(false))
14511 .unwrap();
14512 assert!(!active(cx));
14513 }
14514}
14515
14516#[cfg(test)]
14521mod vn_shadow_tests {
14522 use super::{SHADOW_INSET, SHADOW_OUTSIDE_BOX, SHADOW_UNDER_BOX, spread_shadow_radius};
14523 use crate::{
14524 BoxShadow, Context, Hsla, TestAppContext, Window, div, point, prelude::*, px, size,
14525 };
14526
14527 #[test]
14528 fn a_spread_grows_a_rounded_corner_and_keeps_a_square_one_square() {
14529 assert_eq!(spread_shadow_radius(px(6.), px(3.)), px(9.));
14531 assert_eq!(spread_shadow_radius(px(0.), px(3.)), px(0.));
14532 assert_eq!(spread_shadow_radius(px(1.5), px(3.)), px(1.5 + 3. * 0.875));
14534 assert_eq!(spread_shadow_radius(px(6.), px(0.)), px(6.));
14535 assert_eq!(spread_shadow_radius(px(6.), px(-2.)), px(4.));
14536 assert_eq!(spread_shadow_radius(px(1.), px(-2.)), px(0.));
14537 }
14538
14539 struct Ring {
14540 under_box: bool,
14541 }
14542
14543 impl Render for Ring {
14544 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14545 let shadow = |inset: bool| BoxShadow {
14546 color: Hsla::white().opacity(0.5),
14547 offset: point(px(0.), px(0.)),
14548 blur_radius: px(0.),
14549 spread_radius: px(3.),
14550 inset,
14551 };
14552 let mut d = div()
14553 .w(px(100.))
14554 .h(px(36.))
14555 .rounded_md()
14556 .shadow(vec![shadow(false), shadow(true)]);
14557 d.style().vn_shadow_under_box = Some(self.under_box);
14558 d
14559 }
14560 }
14561
14562 fn paint(under_box: bool, cx: &mut TestAppContext) -> (Vec<(u32, f32, f32)>, f32) {
14564 let window = cx.open_window(size(px(300.), px(300.)), move |_, _| Ring { under_box });
14565 cx.run_until_parked();
14566 window
14567 .update(cx, |_, window, _| {
14568 let shadows = window
14569 .rendered_frame
14570 .scene
14571 .shadows
14572 .iter()
14573 .map(|s| (s.inset, s.shape_corner_radii.top_left.0, s.corner_radii.top_left.0))
14574 .collect();
14575 (shadows, window.scale_factor())
14576 })
14577 .unwrap()
14578 }
14579
14580 #[gpui::test]
14581 fn an_outer_shadow_is_cut_out_of_the_border_box_unless_it_stands_in_for_the_box(
14582 cx: &mut TestAppContext,
14583 ) {
14584 let (shadows, scale) = paint(false, cx);
14585 let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
14586 assert_eq!(outer.0, SHADOW_OUTSIDE_BOX, "the shaders cut the border box out of it");
14587 assert_eq!(outer.1, 9. * scale, "6px corner + 3px spread");
14588 assert_eq!(outer.2, 6. * scale, "the cut-out is the border box itself");
14589 assert!(shadows.iter().any(|s| s.0 == SHADOW_INSET), "the inset shadow is unchanged");
14590
14591 let (shadows, _) = paint(true, cx);
14592 let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
14593 assert_eq!(outer.0, SHADOW_UNDER_BOX);
14594 }
14595}
14596
14597#[cfg(test)]
14598mod vn_rounded_mask_tests {
14599 use super::transform_mask;
14600 use crate::{Bounds, ContentMask, Corners, TransformationMatrix, point, px, size};
14601
14602 fn mask(x: f32, y: f32, w: f32, h: f32, radius: f32) -> ContentMask<crate::Pixels> {
14603 ContentMask {
14604 bounds: Bounds::new(point(px(x), px(y)), size(px(w), px(h))),
14605 corner_radii: Corners::all(px(radius)),
14606 ..Default::default()
14607 }
14608 }
14609
14610 #[test]
14611 fn rectangles_intersect_exactly_and_stay_square() {
14612 let a = mask(0., 0., 100., 100., 0.);
14613 let b = mask(50., 20., 100., 30., 0.);
14614 let both = a.intersect(&b);
14615 assert_eq!(both.bounds, Bounds::new(point(px(50.), px(20.)), size(px(50.), px(30.))));
14616 assert!(!both.is_rounded());
14617 }
14618
14619 #[test]
14620 fn a_corner_keeps_the_radius_of_the_mask_it_belongs_to() {
14621 let card = mask(10., 10., 200., 160., 24.);
14623 let scroller = mask(10., 10., 200., 160., 0.);
14624 assert_eq!(scroller.intersect(&card).corner_radii, Corners::all(px(24.)));
14625 assert_eq!(card.intersect(&scroller).corner_radii, Corners::all(px(24.)));
14626
14627 let header = mask(10., 10., 200., 60., 0.);
14630 let clipped = header.intersect(&card);
14631 assert_eq!(clipped.corner_radii.top_left, px(24.));
14632 assert_eq!(clipped.corner_radii.top_right, px(24.));
14633 assert_eq!(clipped.corner_radii.bottom_left, px(0.));
14634 assert_eq!(clipped.corner_radii.bottom_right, px(0.));
14635
14636 let inner = mask(10., 10., 200., 160., 8.);
14639 assert_eq!(inner.intersect(&card).corner_radii, Corners::all(px(24.)));
14640
14641 let row = mask(40., 60., 100., 20., 0.);
14643 assert!(!row.intersect(&card).is_rounded());
14644
14645 let sliver = mask(10., 10., 200., 10., 0.);
14647 let clipped = sliver.intersect(&card);
14648 assert_eq!(clipped.corner_radii.top_left, px(5.));
14649 }
14650
14651 #[test]
14652 fn contains_follows_the_curve() {
14653 let avatar = mask(0., 0., 64., 64., 32.);
14654 assert!(avatar.contains(&point(px(32.), px(32.))));
14655 assert!(avatar.contains(&point(px(32.), px(1.))), "the top edge's middle");
14656 assert!(!avatar.contains(&point(px(2.), px(2.))), "outside the curve");
14657 assert!(!avatar.contains(&point(px(62.), px(62.))));
14658 assert!(avatar.contains(&point(px(10.), px(10.))), "inside the curve");
14659 assert!(!avatar.contains(&point(px(70.), px(32.))), "outside the rect");
14660 assert!(mask(0., 0., 64., 64., 0.).contains(&point(px(1.), px(1.))));
14661 }
14662
14663 #[test]
14664 fn a_transform_keeps_the_radii_only_while_corners_stay_round() {
14665 let card = mask(0., 0., 100., 100., 10.);
14666 let moved = TransformationMatrix {
14667 rotation_scale: [[1., 0.], [0., 1.]],
14668 translation: [5., 7.],
14669 };
14670 assert_eq!(transform_mask(moved, card, 1.).corner_radii, Corners::all(px(10.)));
14671
14672 let scaled = TransformationMatrix {
14673 rotation_scale: [[2., 0.], [0., 3.]],
14674 translation: [0., 0.],
14675 };
14676 assert_eq!(
14677 transform_mask(scaled, card, 1.).corner_radii,
14678 Corners::all(px(20.)),
14679 "the smaller factor"
14680 );
14681
14682 let rotated = TransformationMatrix {
14683 rotation_scale: [[0., 1.], [-1., 0.]],
14684 translation: [0., 0.],
14685 };
14686 assert!(!transform_mask(rotated, card, 1.).is_rounded());
14687 }
14688}
14689
14690#[cfg(test)]
14692mod vn_pointer_inside_tests {
14693 use crate::{
14694 Context, Modifiers, MouseExitEvent, MouseMoveEvent, PlatformInput, Render,
14695 TestAppContext, Window, div, point, prelude::*, px, size,
14696 };
14697 use std::{cell::Cell, rc::Rc};
14698
14699 struct Hoverable {
14700 hovered: Rc<Cell<bool>>,
14701 }
14702
14703 impl Render for Hoverable {
14704 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14705 let hovered = self.hovered.clone();
14706 div()
14707 .id("box")
14708 .size_full()
14709 .on_hover(move |is_hovered, _, _| hovered.set(*is_hovered))
14710 }
14711 }
14712
14713 #[gpui::test]
14714 fn a_pointer_outside_the_window_hovers_nothing(cx: &mut TestAppContext) {
14715 let hovered = Rc::new(Cell::new(false));
14716 let state = hovered.clone();
14717 let window = cx.open_window(size(px(200.), px(200.)), move |_, _| Hoverable {
14718 hovered: state,
14719 });
14720 let mut platform = cx.test_window(window.into());
14721 let draw = |cx: &mut TestAppContext| {
14722 window.update(cx, |_, window, _| window.refresh()).unwrap();
14723 cx.run_until_parked();
14724 };
14725 let at = |x: f32, y: f32| point(px(x), px(y));
14726 let moved = |x: f32, y: f32| {
14727 PlatformInput::MouseMove(MouseMoveEvent {
14728 position: at(x, y),
14729 pressed_button: None,
14730 modifiers: Modifiers::default(),
14731 })
14732 };
14733
14734 draw(cx);
14738 assert!(!hovered.get(), "a cursor that never entered hovers nothing");
14739
14740 platform.simulate_input(moved(50., 50.));
14741 draw(cx);
14742 assert!(hovered.get(), "a move into the box hovers it");
14743
14744 platform.simulate_hover_status_change(false);
14748 draw(cx);
14749 assert!(!hovered.get(), "a pointer that left hovers nothing");
14750
14751 platform.simulate_input(moved(60., 60.));
14752 draw(cx);
14753 assert!(hovered.get(), "back in");
14754
14755 platform.simulate_input(PlatformInput::MouseExited(MouseExitEvent {
14756 position: at(60., 60.),
14757 pressed_button: None,
14758 modifiers: Modifiers::default(),
14759 }));
14760 draw(cx);
14761 assert!(!hovered.get(), "MouseExited");
14762 }
14763
14764 struct Shaded {
14765 effect: bool,
14766 renders: Rc<Cell<usize>>,
14767 }
14768
14769 impl Render for Shaded {
14770 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14771 self.renders.set(self.renders.get() + 1);
14772 let mut element = div().size_full();
14773 if self.effect {
14774 let mut spec = crate::EffectSpec::NONE;
14775 spec.id = 0;
14776 spec.pointer_param = Some(4);
14777 element.style().vn_effect = Some(spec);
14778 }
14779 element
14780 }
14781 }
14782
14783 #[gpui::test]
14784 fn only_a_pointer_effect_repaints_when_the_pointer_moves(cx: &mut TestAppContext) {
14785 let open = |cx: &mut TestAppContext, effect: bool| {
14786 let renders = Rc::new(Cell::new(0));
14787 let counted = renders.clone();
14788 let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Shaded {
14789 effect,
14790 renders: counted,
14791 });
14792 cx.run_until_parked();
14793 (window, cx.test_window(window.into()), renders)
14794 };
14795 let moved = |x: f32, y: f32| {
14796 PlatformInput::MouseMove(MouseMoveEvent {
14797 position: point(px(x), px(y)),
14798 pressed_button: None,
14799 modifiers: Modifiers::default(),
14800 })
14801 };
14802
14803 let (_, mut platform, renders) = open(cx, false);
14804 platform.simulate_input(moved(10., 10.));
14805 cx.run_until_parked();
14806 let before = renders.get();
14807 platform.simulate_input(moved(20., 20.));
14808 cx.run_until_parked();
14809 assert_eq!(renders.get(), before, "no pointer effect, no repaint");
14810
14811 let (shaded, mut platform, renders) = open(cx, true);
14812 platform.simulate_input(moved(10., 10.));
14813 cx.run_until_parked();
14814 let before = renders.get();
14815 platform.simulate_input(moved(150., 25.));
14816 cx.run_until_parked();
14817 assert!(renders.get() > before, "a pointer effect repaints");
14818 let params = shaded
14819 .update(cx, |_, window, _| {
14820 window.rendered_frame.scene.effect_quads[0].params
14821 })
14822 .unwrap();
14823 assert!((params[4] - 0.75).abs() < 1e-4 && (params[5] - 0.25).abs() < 1e-4);
14824 }
14825
14826 struct Spinning {
14827 speed: Rc<Cell<f32>>,
14828 }
14829
14830 impl Render for Spinning {
14831 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14832 let mut spec = crate::EffectSpec::NONE;
14833 spec.id = 0;
14834 spec.animated_param = Some(0);
14835 spec.params[0] = self.speed.get();
14836 let mut element = div().id("spinning").size_full();
14837 element.style().vn_effect = Some(spec);
14838 element
14839 }
14840 }
14841
14842 #[gpui::test]
14843 fn a_speed_change_continues_the_phase_instead_of_rescaling_the_clock(
14844 cx: &mut TestAppContext,
14845 ) {
14846 let speed = Rc::new(Cell::new(1.));
14847 let shared = speed.clone();
14848 let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Spinning {
14849 speed: shared,
14850 });
14851 cx.run_until_parked();
14852 let repaint = |cx: &mut TestAppContext| {
14853 window.update(cx, |_, window, _| window.refresh()).unwrap();
14854 cx.run_until_parked();
14855 window
14856 .update(cx, |_, window, _| {
14857 let quad = window.rendered_frame.scene.effect_quads[0];
14858 (quad.params[0] * quad.time, quad.time)
14859 })
14860 .unwrap()
14861 };
14862 std::thread::sleep(std::time::Duration::from_millis(200));
14864 let (before, then) = repaint(cx);
14865 assert!((before - then).abs() < 1e-3, "an unchanged speed is `speed * time`");
14866
14867 speed.set(8.);
14868 let (after, now) = repaint(cx);
14869 let advanced = after - before;
14870 assert!(
14871 advanced >= -1e-3 && advanced <= 8. * (now - then) + 1e-3,
14872 "the phase moved by {advanced} in {}s",
14873 now - then
14874 );
14875 }
14876}
14877
14878#[cfg(test)]
14879mod vn_tagged_transform_tests {
14880 use crate::{
14881 AnyElement, App, Bounds, Context, Element, GlobalElementId, InspectorElementId,
14882 IntoElement, LayoutId, Pixels, Render, TestAppContext, TransformLength, TransformSpec,
14883 Window, div, prelude::*, px, size,
14884 };
14885 use std::{cell::RefCell, rc::Rc};
14886
14887 type Seen = Rc<RefCell<Vec<(u32, Bounds<Pixels>, Bounds<Pixels>)>>>;
14888
14889 struct Probe {
14892 tag: u32,
14893 inner: AnyElement,
14894 seen: Seen,
14895 }
14896
14897 impl Element for Probe {
14898 type RequestLayoutState = ();
14899 type PrepaintState = ();
14900 fn id(&self) -> Option<crate::ElementId> {
14901 None
14902 }
14903 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
14904 None
14905 }
14906 fn request_layout(
14907 &mut self,
14908 _: Option<&GlobalElementId>,
14909 _: Option<&InspectorElementId>,
14910 window: &mut Window,
14911 cx: &mut App,
14912 ) -> (LayoutId, ()) {
14913 (self.inner.request_layout(window, cx), ())
14914 }
14915 fn prepaint(
14916 &mut self,
14917 _: Option<&GlobalElementId>,
14918 _: Option<&InspectorElementId>,
14919 bounds: Bounds<Pixels>,
14920 _: &mut (),
14921 window: &mut Window,
14922 cx: &mut App,
14923 ) {
14924 let ancestors = window.element_transform();
14925 let (_, own) =
14926 window.with_hitbox_tag(self.tag, |window| self.inner.prepaint(window, cx));
14927 let seen = window.transformed_bounds(own.unwrap_or(ancestors), bounds);
14928 self.seen.borrow_mut().push((self.tag, bounds, seen));
14929 }
14930 fn paint(
14931 &mut self,
14932 _: Option<&GlobalElementId>,
14933 _: Option<&InspectorElementId>,
14934 _: Bounds<Pixels>,
14935 _: &mut (),
14936 _: &mut (),
14937 window: &mut Window,
14938 cx: &mut App,
14939 ) {
14940 self.inner.paint(window, cx);
14941 }
14942 }
14943
14944 fn moved(x: TransformLength, y: TransformLength, scale: f32) -> TransformSpec {
14945 TransformSpec { translate: (x, y), scale: (scale, scale), ..TransformSpec::IDENTITY }
14946 }
14947
14948 struct Popper {
14951 seen: Seen,
14952 }
14953
14954 impl Render for Popper {
14955 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
14956 let probe = |tag, inner: AnyElement| Probe { tag, inner, seen: self.seen.clone() };
14957 let mut wrapper = div().w(px(100.)).h(px(80.));
14958 wrapper.style().vn_transform =
14959 Some(moved(TransformLength::Pixels(300.), TransformLength::Pixels(200.), 1.0));
14960 let mut scaled = div().w(px(20.)).h(px(10.));
14961 scaled.style().vn_transform =
14962 Some(moved(TransformLength::ZERO, TransformLength::ZERO, 2.0));
14963 let mut pseudo = div().w(px(4.)).h(px(4.));
14966 pseudo.style().vn_transform =
14967 Some(moved(TransformLength::Pixels(50.), TransformLength::ZERO, 1.0));
14968 let button = div()
14969 .ml(px(10.))
14970 .w(px(30.))
14971 .h(px(20.))
14972 .child(probe(3, scaled.into_any_element()))
14973 .child(pseudo);
14974 div().size_full().child(probe(
14975 1,
14976 wrapper.child(probe(2, button.into_any_element())).into_any_element(),
14977 ))
14978 }
14979 }
14980
14981 #[gpui::test]
14982 fn a_probe_sees_its_node_where_the_transforms_put_it(cx: &mut TestAppContext) {
14983 let seen: Seen = Rc::default();
14984 let state = seen.clone();
14985 let window =
14986 cx.open_window(size(px(800.), px(600.)), move |_, _| Popper { seen: state });
14987 window.update(cx, |_, window, _| window.refresh()).unwrap();
14988 cx.run_until_parked();
14989 let seen = seen.borrow();
14990 let at = |tag: u32| *seen.iter().rev().find(|s| s.0 == tag).expect("probed");
14991 let b = |x: f32, y: f32, w: f32, h: f32| {
14992 Bounds::new(crate::point(px(x), px(y)), size(px(w), px(h)))
14993 };
14994 assert_eq!(at(1).1, b(0., 0., 100., 80.));
14996 assert_eq!(at(1).2, b(300., 200., 100., 80.));
14997 assert_eq!(at(2).1, b(10., 0., 30., 20.));
15000 assert_eq!(at(2).2, b(310., 200., 30., 20.));
15001 assert_eq!(at(3).1, b(10., 0., 20., 10.));
15003 assert_eq!(at(3).2, b(300., 195., 40., 20.));
15004 }
15005}