1#[cfg(feature = "profiler")]
2use crate::DebugFrameOverlayMode;
3#[cfg(any(feature = "inspector", debug_assertions))]
4use crate::Inspector;
5#[cfg(feature = "profiler")]
6use crate::profiler;
7use crate::subscription::SingleSubscriberSet;
8use crate::taffy::TaffyLayoutEngine;
9use crate::{
10 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
11 AsyncWindowContext, AtlasKey, AtlasStats, AtlasTile, AvailableSpace, BackdropBlurRect, Background, BorderStyle,
12 EffectQuad, EffectSpec,
13 Bounds, BoxShadow,
14 Capslock, Context, 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,
18 Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent,
19 Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent,
20 MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, PaintedPath, Path,
21 Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow,
22 Point, PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams,
23 RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
24 SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,
25 SpriteAnimation, SpriteAnimationId, StrikethroughStyle, Style, SubpixelSprite, Subscription,
26 SystemWindowTab, SystemWindowTabController, TabStopMap, Task, TextInputConfiguration,
27 TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState,
28 TileSource, TileWrite, TransformationMatrix, Underline, UnderlineStyle, WindowAppearance,
29 WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations, WindowInsets,
30 WindowOptions, WindowParams, WindowTextSystem, WindowVisibility, blur_glyph_coverage, point,
31 prelude::*, px, rems, size, transparent_black,
32};
33
34use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
35use crate::interactive::TouchEvent;
36use crate::util::impl_deref;
37use anyhow::{Context as _, Result, anyhow};
38use collections::{FxHashMap, FxHashSet};
39use futures::channel::oneshot;
40use gpui_util::post_inc;
41use gpui_util::{ResultExt, measure};
42use itertools::FoldWhile::{Continue, Done};
43use itertools::Itertools;
44#[cfg(any(target_os = "macos", target_os = "ios"))]
45use objc2_core_foundation::CFRetained;
46#[cfg(any(target_os = "macos", target_os = "ios"))]
47use objc2_core_video::CVPixelBuffer;
48use parking_lot::{RwLock, RwLockUpgradableReadGuard};
49use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
50use refineable::Refineable;
51use scheduler::Instant;
52use slotmap::SlotMap;
53use smallvec::SmallVec;
54use std::{
55 any::{Any, TypeId},
56 borrow::Cow,
57 cell::{Cell, RefCell},
58 cmp,
59 fmt::{Debug, Display},
60 hash::{Hash, Hasher},
61 marker::PhantomData,
62 mem,
63 ops::{Add, Div, Range, Sub},
64 rc::Rc,
65 sync::{
66 Arc, Weak,
67 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
68 },
69 thread::AccessError,
70 time::Duration,
71};
72use uuid::Uuid;
73
74pub(crate) mod a11y;
75mod prompts;
76
77pub use a11y::A11ySubtreeBuilder;
78
79use self::a11y::A11y;
80#[cfg(not(target_family = "wasm"))]
81use self::a11y::ROOT_NODE_ID;
82use crate::util::{
83 atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
84 round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
85};
86pub use prompts::*;
87
88pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
90
91pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
94 width: Pixels(900.),
95 height: Pixels(750.),
96};
97
98#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
100pub enum DispatchPhase {
101 #[default]
106 Bubble,
107 Capture,
113}
114
115impl DispatchPhase {
116 #[inline]
118 pub fn bubble(self) -> bool {
119 self == DispatchPhase::Bubble
120 }
121
122 #[inline]
124 pub fn capture(self) -> bool {
125 self == DispatchPhase::Capture
126 }
127}
128
129struct WindowInvalidatorInner {
130 #[cfg(feature = "profiler")]
131 pub window_id: WindowId,
132 pub dirty: bool,
133 pub draw_phase: DrawPhase,
134 pub dirty_views: FxHashSet<EntityId>,
135 pub update_count: usize,
136 #[cfg(feature = "profiler")]
137 pub frame_dirty: FrameDirtyAccumulator,
138 pub platform_waker: Option<Rc<dyn Fn()>>,
139}
140
141#[cfg(feature = "profiler")]
147#[derive(Default)]
148struct FrameDirtyAccumulator {
149 dirty_at: Option<Instant>,
150 invalidations: u64,
151}
152
153#[derive(Clone)]
154pub(crate) struct WindowInvalidator {
155 inner: Rc<RefCell<WindowInvalidatorInner>>,
156}
157
158impl WindowInvalidator {
159 pub fn new(#[allow(unused_variables)] window_id: WindowId) -> Self {
160 WindowInvalidator {
161 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
162 #[cfg(feature = "profiler")]
163 window_id,
164 dirty: true,
165 draw_phase: DrawPhase::None,
166 dirty_views: FxHashSet::default(),
167 update_count: 0,
168 #[cfg(feature = "profiler")]
169 frame_dirty: FrameDirtyAccumulator::default(),
170 platform_waker: None,
171 })),
172 }
173 }
174
175 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
176 let mut inner = self.inner.borrow_mut();
177 inner.update_count += 1;
178 inner.dirty_views.insert(entity);
179 if inner.draw_phase == DrawPhase::None {
180 #[cfg(feature = "profiler")]
181 let dirty_at = Self::record_frame_dirty(&mut inner);
182 let became_dirty = !inner.dirty;
183 inner.dirty = true;
184 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
185 #[cfg(feature = "profiler")]
186 let window_id = inner.window_id;
187 drop(inner);
188 #[cfg(feature = "profiler")]
189 if became_dirty {
190 profiler::journal::record_frame_pending(window_id, dirty_at);
191 }
192 cx.push_effect(Effect::Notify { emitter: entity });
193 if let Some(waker) = waker {
194 waker();
195 }
196 true
197 } else {
198 false
199 }
200 }
201
202 pub fn is_dirty(&self) -> bool {
203 self.inner.borrow().dirty
204 }
205
206 pub fn set_dirty(&self, dirty: bool) {
207 let mut inner = self.inner.borrow_mut();
208 let became_dirty = dirty && !inner.dirty;
209 inner.dirty = dirty;
210 if dirty {
211 inner.update_count += 1;
212 }
213 #[cfg(feature = "profiler")]
214 let dirty_at = dirty.then(|| Self::record_frame_dirty(&mut inner));
215 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
216 #[cfg(feature = "profiler")]
217 let window_id = inner.window_id;
218 drop(inner);
219 #[cfg(feature = "profiler")]
220 if became_dirty && let Some(dirty_at) = dirty_at {
221 profiler::journal::record_frame_pending(window_id, dirty_at);
222 }
223 if let Some(waker) = waker {
224 waker();
225 }
226 }
227
228 pub fn set_platform_waker(&self, waker: Option<Rc<dyn Fn()>>) {
229 let mut inner = self.inner.borrow_mut();
230 inner.platform_waker = waker;
231 let waker = inner.dirty.then(|| inner.platform_waker.clone()).flatten();
232 drop(inner);
233 if let Some(waker) = waker {
234 waker();
235 }
236 }
237
238 pub fn wake_platform(&self) {
242 let waker = self.inner.borrow().platform_waker.clone();
243 if let Some(waker) = waker {
244 waker();
245 }
246 }
247
248 pub fn set_phase(&self, phase: DrawPhase) {
249 self.inner.borrow_mut().draw_phase = phase
250 }
251
252 pub fn update_count(&self) -> usize {
253 self.inner.borrow().update_count
254 }
255
256 #[cfg(feature = "profiler")]
257 fn record_frame_dirty(inner: &mut WindowInvalidatorInner) -> Instant {
258 let dirty_at = *inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
259 inner.frame_dirty.invalidations += 1;
260 dirty_at
261 }
262
263 #[cfg(feature = "profiler")]
264 fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
265 mem::take(&mut self.inner.borrow_mut().frame_dirty)
266 }
267
268 pub fn take_views(&self) -> FxHashSet<EntityId> {
269 mem::take(&mut self.inner.borrow_mut().dirty_views)
270 }
271
272 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
273 self.inner.borrow_mut().dirty_views = views;
274 }
275
276 pub fn not_drawing(&self) -> bool {
277 self.inner.borrow().draw_phase == DrawPhase::None
278 }
279
280 pub fn is_painting(&self) -> bool {
282 self.inner.borrow().draw_phase == DrawPhase::Paint
283 }
284
285 #[track_caller]
286 pub fn debug_assert_paint(&self) {
287 debug_assert!(
288 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
289 "this method can only be called during paint"
290 );
291 }
292
293 #[track_caller]
294 pub fn debug_assert_prepaint(&self) {
295 debug_assert!(
296 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
297 "this method can only be called during request_layout, or prepaint"
298 );
299 }
300
301 #[track_caller]
302 pub fn debug_assert_paint_or_prepaint(&self) {
303 debug_assert!(
304 matches!(
305 self.inner.borrow().draw_phase,
306 DrawPhase::Paint | DrawPhase::Prepaint
307 ),
308 "this method can only be called during request_layout, prepaint, or paint"
309 );
310 }
311}
312
313type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
314
315pub(crate) type AnyWindowFocusListener =
316 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
317
318pub(crate) struct WindowFocusEvent {
319 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
320 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
321}
322
323impl WindowFocusEvent {
324 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
325 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
326 }
327
328 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
329 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
330 }
331}
332
333pub struct FocusOutEvent {
335 pub blurred: WeakFocusHandle,
337}
338
339slotmap::new_key_type! {
340 pub struct FocusId;
342}
343
344thread_local! {
345 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
348
349 static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
353}
354
355pub(crate) fn draw_in_progress() -> bool {
366 CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some())
367}
368
369#[derive(Clone, Copy, Debug, PartialEq, Eq)]
371pub enum FrameOutcome {
372 Drew,
374 NoDraw,
376 Throttled,
378}
379
380#[derive(Clone, Copy, Debug)]
382pub struct FrameWork {
383 pub window_id: WindowId,
385 pub started: Instant,
387 pub ended: Instant,
389 pub outcome: FrameOutcome,
391}
392
393static FRAME_OBSERVER: std::sync::OnceLock<fn(FrameWork)> = std::sync::OnceLock::new();
394
395pub fn observe_frames(observer: fn(FrameWork)) {
398 let _ = FRAME_OBSERVER.set(observer);
399}
400
401fn report_frame(window_id: WindowId, started: Instant, outcome: FrameOutcome) {
402 if let Some(observer) = FRAME_OBSERVER.get() {
403 observer(FrameWork { window_id, started, ended: Instant::now(), outcome });
404 }
405}
406
407#[inline(always)]
410pub(crate) fn with_element_arena<R>(callback: impl FnOnce(&mut Arena) -> R) -> R {
411 let mut callback = Some(callback);
412 let mut result = None;
413 let access = with_element_arena_erased(&mut |arena| {
414 result = Some(callback.take().expect("arena callback runs once")(arena));
415 });
416 drop(callback);
417 access.expect("cannot access a Thread Local Storage value during or after destruction");
418 result.expect("arena callback produces a result")
419}
420
421pub(crate) struct ElementArenaScope {
436 entered: *const RefCell<Arena>,
439 previous: Option<*const RefCell<Arena>>,
440 exited: bool,
441}
442
443impl ElementArenaScope {
444 pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
446 arena.borrow_mut().begin_scope();
447 let previous = CURRENT_ELEMENT_ARENA.with(|current| {
448 let prev = current.get();
449 current.set(Some(arena as *const RefCell<Arena>));
450 prev
451 });
452 Self {
453 entered: arena as *const RefCell<Arena>,
454 previous,
455 exited: false,
456 }
457 }
458
459 pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
468 assert!(
469 std::ptr::eq(self.entered, arena),
470 "ElementArenaScope::exit called with a different arena than was entered"
471 );
472 self.exited = true;
473 ArenaClearNeeded::new(arena)
478 }
479}
480
481impl Drop for ElementArenaScope {
482 fn drop(&mut self) {
483 CURRENT_ELEMENT_ARENA.with(|current| {
490 current.set(self.previous);
491 });
492 unsafe { &*self.entered }.borrow_mut().end_scope();
496 if !self.exited && !std::thread::panicking() {
497 debug_assert!(false, "ElementArenaScope dropped without calling exit()");
498 log::error!(
499 "ElementArenaScope dropped without calling exit(); \
500 the arena clear for this draw was never requested"
501 );
502 }
503 }
504}
505
506#[must_use]
508pub struct ArenaClearNeeded {
509 arena: *const RefCell<Arena>,
512}
513
514impl ArenaClearNeeded {
515 fn new(arena: &RefCell<Arena>) -> Self {
518 Self {
519 arena: arena as *const RefCell<Arena>,
520 }
521 }
522
523 pub fn clear(self, cx: &mut App) {
532 assert!(
533 std::ptr::eq(self.arena, &*cx.element_arena),
534 "ArenaClearNeeded::clear called with a different App than the draw ran against"
535 );
536 RefCell::borrow_mut(&cx.element_arena).clear();
537 }
538}
539
540#[derive(Default)]
541pub(crate) struct FocusMap {
542 pub(crate) handles: SlotMap<FocusId, FocusRef>,
543 pub(crate) dropped_handles: Vec<FocusId>,
544}
545
546pub(crate) struct FocusRef {
547 pub(crate) ref_count: AtomicUsize,
548 pub(crate) tab_index: isize,
549 pub(crate) tab_stop: bool,
550}
551
552impl FocusId {
553 pub fn is_focused(&self, window: &Window) -> bool {
555 window.focus == Some(*self)
556 }
557
558 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
561 window
562 .focused(cx)
563 .is_some_and(|focused| self.contains(focused.id, window))
564 }
565
566 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
569 let focused = window.focused(cx);
570 focused.is_some_and(|focused| focused.id.contains(*self, window))
571 }
572
573 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
575 window
576 .rendered_frame
577 .dispatch_tree
578 .focus_contains(*self, other)
579 }
580}
581
582pub struct FocusHandle {
584 pub(crate) id: FocusId,
585 handles: Arc<RwLock<FocusMap>>,
586 pub tab_index: isize,
588 pub tab_stop: bool,
590}
591
592impl std::fmt::Debug for FocusHandle {
593 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
594 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
595 }
596}
597
598impl FocusHandle {
599 pub(crate) fn new(handles: &Arc<RwLock<FocusMap>>) -> Self {
600 let id = handles.write().handles.insert(FocusRef {
601 ref_count: AtomicUsize::new(1),
602 tab_index: 0,
603 tab_stop: false,
604 });
605
606 Self {
607 id,
608 tab_index: 0,
609 tab_stop: false,
610 handles: handles.clone(),
611 }
612 }
613
614 pub(crate) fn for_id(id: FocusId, handles: &Arc<RwLock<FocusMap>>) -> Option<Self> {
615 let lock = handles.read();
616 let focus = lock.handles.get(id)?;
617 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
618 return None;
619 }
620 Some(Self {
621 id,
622 tab_index: focus.tab_index,
623 tab_stop: focus.tab_stop,
624 handles: handles.clone(),
625 })
626 }
627
628 pub fn tab_index(mut self, index: isize) -> Self {
630 self.tab_index = index;
631 if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
632 focus.tab_index = index;
633 }
634 self
635 }
636
637 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
641 self.tab_stop = tab_stop;
642 if let Some(focus) = self.handles.write().handles.get_mut(self.id) {
643 focus.tab_stop = tab_stop;
644 }
645 self
646 }
647
648 pub fn downgrade(&self) -> WeakFocusHandle {
650 WeakFocusHandle {
651 id: self.id,
652 handles: Arc::downgrade(&self.handles),
653 }
654 }
655
656 pub fn focus(&self, window: &mut Window, cx: &mut App) {
658 window.focus(self, cx)
659 }
660
661 pub fn is_focused(&self, window: &Window) -> bool {
663 self.id.is_focused(window)
664 }
665
666 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
669 self.id.contains_focused(window, cx)
670 }
671
672 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
675 self.id.within_focused(window, cx)
676 }
677
678 pub fn contains(&self, other: &Self, window: &Window) -> bool {
680 self.id.contains(other.id, window)
681 }
682
683 pub fn is_rendered(&self, window: &Window) -> bool {
685 window
686 .rendered_frame
687 .dispatch_tree
688 .focusable_node_id(self.id)
689 .is_some()
690 }
691
692 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
694 if let Some(node_id) = window
695 .rendered_frame
696 .dispatch_tree
697 .focusable_node_id(self.id)
698 {
699 window.dispatch_action_on_node(node_id, action, cx)
700 }
701 }
702}
703
704impl Clone for FocusHandle {
705 fn clone(&self) -> Self {
706 Self::for_id(self.id, &self.handles).unwrap()
707 }
708}
709
710impl PartialEq for FocusHandle {
711 fn eq(&self, other: &Self) -> bool {
712 self.id == other.id
713 }
714}
715
716impl Eq for FocusHandle {}
717
718impl Drop for FocusHandle {
719 fn drop(&mut self) {
720 let handles = self.handles.upgradable_read();
721 let focus = handles.handles.get(self.id).expect("focus handle missing");
722 let previous_count = focus.ref_count.fetch_sub(1, SeqCst);
723 assert_ne!(previous_count, 0, "over-released focus handle");
724 if previous_count == 1 {
725 RwLockUpgradableReadGuard::upgrade(handles)
726 .dropped_handles
727 .push(self.id);
728 }
729 }
730}
731
732#[derive(Clone, Debug)]
734pub struct WeakFocusHandle {
735 pub(crate) id: FocusId,
736 pub(crate) handles: Weak<RwLock<FocusMap>>,
737}
738
739impl WeakFocusHandle {
740 pub fn upgrade(&self) -> Option<FocusHandle> {
742 let handles = self.handles.upgrade()?;
743 FocusHandle::for_id(self.id, &handles)
744 }
745}
746
747impl PartialEq for WeakFocusHandle {
748 fn eq(&self, other: &WeakFocusHandle) -> bool {
749 self.id == other.id
750 }
751}
752
753impl Eq for WeakFocusHandle {}
754
755impl PartialEq<FocusHandle> for WeakFocusHandle {
756 fn eq(&self, other: &FocusHandle) -> bool {
757 self.id == other.id
758 }
759}
760
761impl PartialEq<WeakFocusHandle> for FocusHandle {
762 fn eq(&self, other: &WeakFocusHandle) -> bool {
763 self.id == other.id
764 }
765}
766
767pub trait Focusable: 'static {
770 fn focus_handle(&self, cx: &App) -> FocusHandle;
772}
773
774impl<V: Focusable> Focusable for Entity<V> {
775 fn focus_handle(&self, cx: &App) -> FocusHandle {
776 self.read(cx).focus_handle(cx)
777 }
778}
779
780pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
783
784impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
785
786pub struct DismissEvent;
788
789type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
790
791pub(crate) type AnyMouseListener =
792 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
793
794#[derive(Clone)]
795pub(crate) struct CursorStyleRequest {
796 pub(crate) hitbox_id: Option<HitboxId>,
797 pub(crate) style: CursorStyle,
798}
799
800#[derive(Default, Eq, PartialEq)]
801pub(crate) struct HitTest {
802 pub(crate) ids: SmallVec<[HitboxId; 8]>,
803 pub(crate) hover_hitbox_count: usize,
804}
805
806#[derive(Clone, Copy, Debug, Eq, PartialEq)]
808pub enum WindowControlArea {
809 Drag,
811 Close,
813 Max,
815 Min,
817 NoDrag,
826}
827
828#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
830pub struct HitboxId(u64);
831
832#[cfg(feature = "test-support")]
833impl HitboxId {
834 pub const fn placeholder() -> Self {
839 Self(0)
840 }
841}
842
843impl HitboxId {
844 pub const VN_PICK: HitboxId = HitboxId(u64::MAX);
848
849 pub fn is_hovered(self, window: &Window) -> bool {
856 if window.captured_hitbox == Some(self) {
858 return true;
859 }
860 if window.last_input_was_keyboard() {
861 return false;
862 }
863 self.hit_test(window)
864 }
865
866 pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
871 if window.captured_hitbox == Some(self) {
873 return true;
874 }
875 self.hit_test(window)
876 }
877
878 fn hit_test(self, window: &Window) -> bool {
879 if !window.pointer_inside {
884 return false;
885 }
886 let hit_test = &window.mouse_hit_test;
887 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
888 if self == *id {
889 return true;
890 }
891 }
892 false
893 }
894
895 pub fn should_handle_scroll(self, window: &Window) -> bool {
900 window.mouse_hit_test.ids.contains(&self)
901 }
902
903 fn next(self) -> HitboxId {
904 HitboxId(self.0.wrapping_add(1))
905 }
906}
907
908#[inline]
916fn transform_bounds(
917 matrix: TransformationMatrix,
918 bounds: Bounds<Pixels>,
919 scale_factor: f32,
920) -> Bounds<Pixels> {
921 if matrix.is_unit() {
922 return bounds;
923 }
924 let map = |p: Point<Pixels>| {
928 let d = matrix.apply(Point::new(px(p.x.0 * scale_factor), px(p.y.0 * scale_factor)));
929 Point::new(px(d.x.0 / scale_factor), px(d.y.0 / scale_factor))
930 };
931 let corners = [
932 map(bounds.origin),
933 map(bounds.top_right()),
934 map(bounds.bottom_left()),
935 map(bounds.bottom_right()),
936 ];
937 let min_x = corners.iter().map(|p| p.x).fold(Pixels::MAX, Pixels::min);
938 let max_x = corners.iter().map(|p| p.x).fold(Pixels::MIN, Pixels::max);
939 let min_y = corners.iter().map(|p| p.y).fold(Pixels::MAX, Pixels::min);
940 let max_y = corners.iter().map(|p| p.y).fold(Pixels::MIN, Pixels::max);
941 Bounds::from_corners(Point::new(min_x, min_y), Point::new(max_x, max_y))
942}
943
944fn vn_history_key(element: u64, spec: &EffectSpec) -> u64 {
951 use std::hash::{Hash, Hasher};
952 if element == 0 || spec.flags & crate::EFFECT_FLAG_HISTORY == 0 {
953 return 0;
954 }
955 let mut hasher = collections::FxHasher::default();
956 (element, spec.id).hash(&mut hasher);
957 hasher.finish().max(1)
958}
959
960#[derive(Clone, Copy, Debug, PartialEq)]
965struct VnEffectPhase {
966 at: f32,
967 phase: f64,
968}
969
970impl VnEffectPhase {
971 const KEEP: f32 = 10.;
973
974 fn advance(previous: Option<Self>, speed: f32, now: f32) -> Self {
975 match previous {
976 None => Self {
977 at: now,
978 phase: f64::from(speed) * f64::from(now),
979 },
980 Some(previous) if now > previous.at => Self {
981 at: now,
982 phase: previous.phase + f64::from(speed) * f64::from(now - previous.at),
983 },
984 Some(previous) => previous,
985 }
986 }
987
988 fn speed(&self, now: f32) -> Option<f32> {
991 (now > 1e-3).then(|| (self.phase / f64::from(now)) as f32)
992 }
993}
994
995fn vn_phase_key(element: u64, spec: &EffectSpec) -> u64 {
996 use std::hash::{Hash, Hasher};
997 let mut hasher = collections::FxHasher::default();
998 (element, spec.id, "phase").hash(&mut hasher);
999 hasher.finish()
1000}
1001
1002fn transform_mask(
1003 matrix: TransformationMatrix,
1004 mask: ContentMask<Pixels>,
1005 scale_factor: f32,
1006) -> ContentMask<Pixels> {
1007 let bounds = transform_bounds(matrix, mask.bounds, scale_factor);
1008 if !mask.is_rounded() || matrix.is_unit() {
1009 return ContentMask {
1010 bounds,
1011 corner_radii: mask.corner_radii,
1012 corner_shapes: mask.corner_shapes,
1013 };
1014 }
1015 let [[a, b], [c, d]] = matrix.rotation_scale;
1016 let (corner_radii, corner_shapes) = if b == 0. && c == 0. && a > 0. && d > 0. {
1017 let factor = a.min(d);
1018 let radii = mask.corner_radii
1019 .map(|radius| *radius * factor)
1020 .clamp_radii_for_quad_size(bounds.size);
1021 (radii, mask.corner_shapes.scale(factor))
1022 } else {
1023 (Corners::default(), CornerShapes::default())
1024 };
1025 ContentMask {
1026 bounds,
1027 corner_radii,
1028 corner_shapes,
1029 }
1030}
1031
1032#[derive(Clone, Debug)]
1035pub struct Hitbox {
1036 pub id: HitboxId,
1038 pub bounds: Bounds<Pixels>,
1040 pub content_mask: ContentMask<Pixels>,
1042 pub behavior: HitboxBehavior,
1044 pub transformation: TransformationMatrix,
1053 pub vn_clip: Option<Arc<crate::VnClipNode>>,
1057}
1058
1059impl_deref!([] Hitbox => bounds: Bounds<Pixels>);
1060
1061impl Hitbox {
1062 pub fn is_hovered(&self, window: &Window) -> bool {
1079 self.id.is_hovered(window)
1080 }
1081
1082 pub fn is_hovered_at(&self, position: Point<Pixels>, window: &Window) -> bool {
1085 let hit_test = window
1088 .rendered_frame
1089 .hit_test(position, window.scale_factor);
1090 hit_test
1091 .ids
1092 .iter()
1093 .take(hit_test.hover_hitbox_count)
1094 .any(|id| self.id == *id)
1095 }
1096
1097 pub fn should_handle_scroll(&self, window: &Window) -> bool {
1104 self.id.should_handle_scroll(window)
1105 }
1106}
1107
1108pub const VN_TAG_PASSIVE: u32 = 1 << 31;
1114
1115#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1117pub enum VnHitKind {
1118 Down,
1120 Up,
1122 Scroll,
1124}
1125
1126pub type VnHitRefiner = Rc<dyn Fn(VnHitKind, Point<Pixels>, &mut Window, &mut App)>;
1130
1131#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1133pub enum VnPointerLock {
1134 System {
1136 unadjusted: bool,
1138 },
1139 Simulated,
1142}
1143
1144#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1146pub enum HitboxBehavior {
1147 #[default]
1149 Normal,
1150
1151 BlockMouse,
1173
1174 BlockMouseExceptScroll,
1201}
1202
1203#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
1205pub struct TooltipId(usize);
1206
1207impl TooltipId {
1208 pub fn is_hovered(&self, window: &Window) -> bool {
1210 window
1211 .tooltip_bounds
1212 .as_ref()
1213 .is_some_and(|tooltip_bounds| {
1214 tooltip_bounds.id == *self
1215 && tooltip_bounds.bounds.contains(&window.mouse_position())
1216 })
1217 }
1218}
1219
1220pub(crate) struct TooltipBounds {
1221 id: TooltipId,
1222 bounds: Bounds<Pixels>,
1223}
1224
1225#[derive(Clone)]
1226pub(crate) struct TooltipRequest {
1227 id: TooltipId,
1228 tooltip: AnyTooltip,
1229}
1230
1231#[derive(Clone, Default)]
1237pub(crate) struct ElementIdStack {
1238 ids: SmallVec<[ElementId; 32]>,
1239 hashes: SmallVec<[u64; 32]>,
1240}
1241
1242impl ElementIdStack {
1243 pub(crate) fn push(&mut self, id: ElementId) {
1244 self.hashes.push(crate::extend_path_hash(self.hash(), &id));
1245 self.ids.push(id);
1246 }
1247
1248 pub(crate) fn pop(&mut self) -> Option<ElementId> {
1249 self.hashes.pop();
1250 self.ids.pop()
1251 }
1252
1253 pub(crate) fn clear(&mut self) {
1254 self.ids.clear();
1255 self.hashes.clear();
1256 }
1257
1258 fn hash(&self) -> u64 {
1260 self.hashes
1261 .last()
1262 .copied()
1263 .unwrap_or(crate::EMPTY_PATH_HASH)
1264 }
1265
1266 pub(crate) fn global_id(&self) -> GlobalElementId {
1267 GlobalElementId::with_hash(&self.ids, self.hash())
1268 }
1269}
1270
1271impl std::ops::Deref for ElementIdStack {
1272 type Target = [ElementId];
1273
1274 fn deref(&self) -> &Self::Target {
1275 &self.ids
1276 }
1277}
1278
1279pub(crate) struct DeferredDraw {
1280 current_view: EntityId,
1281 priority: usize,
1282 parent_node: DispatchNodeId,
1283 element_id_stack: ElementIdStack,
1284 text_style_stack: Vec<TextStyleRefinement>,
1285 content_mask: Option<ContentMask<Pixels>>,
1286 rem_size: Pixels,
1287 element: Option<AnyElement>,
1288 absolute_offset: Point<Pixels>,
1289 element_transform: TransformationMatrix,
1298 a11y_parent: Option<accesskit::NodeId>,
1302 vn_stack: Option<Rc<[u128]>>,
1306 element_opacity: f32,
1311 vn_clip: Option<Arc<crate::VnClipNode>>,
1316 vn_scope: Option<VnDeferScope>,
1319 prepaint_range: Range<PrepaintStateIndex>,
1320 paint_range: Range<PaintIndex>,
1321 accessed_entities: FxHashSet<EntityId>,
1324}
1325
1326#[derive(Clone, Debug)]
1333pub(crate) struct VnDeferScope {
1334 id: u64,
1335 clip: Option<Arc<crate::VnClipNode>>,
1336}
1337
1338pub(crate) fn vn_element_key(id: Option<&GlobalElementId>) -> u64 {
1342 use std::hash::{Hash, Hasher};
1343 id.map_or(0, |id| {
1344 let mut hasher = collections::FxHasher::default();
1345 for id in id.iter() {
1346 if !matches!(id, ElementId::View(_)) {
1347 id.hash(&mut hasher);
1348 }
1349 }
1350 hasher.finish().max(1)
1351 })
1352}
1353
1354impl DeferredDraw {
1355 fn order(&self) -> (usize, Option<&[u128]>) {
1357 (self.priority, self.vn_stack.as_deref())
1358 }
1359}
1360
1361pub(crate) struct Frame {
1362 pub(crate) focus: Option<FocusId>,
1363 pub(crate) window_active: bool,
1364 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
1365 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
1366 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
1367 pub(crate) dispatch_tree: DispatchTree,
1368 pub(crate) scene: Scene,
1369 pub(crate) hitboxes: Vec<Hitbox>,
1370 pub(crate) vn_tagged_hitboxes: Vec<(u32, Hitbox)>,
1380 pub(crate) vn_hit_order: Vec<u32>,
1389 pub(crate) vn_deferred_tagged: Range<usize>,
1394 vn_tagged_order: std::cell::OnceCell<Option<Vec<u32>>>,
1397 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
1398 pub(crate) deferred_draws: Vec<DeferredDraw>,
1399 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
1400 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
1401 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
1402 #[cfg(any(test, feature = "test-support"))]
1403 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
1404 #[cfg(any(test, feature = "test-support"))]
1405 debug_bounds_records: Vec<(String, Bounds<Pixels>)>,
1406 #[cfg(any(feature = "inspector", debug_assertions))]
1407 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
1408 #[cfg(any(feature = "inspector", debug_assertions))]
1409 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
1410 pub(crate) tab_stops: TabStopMap,
1411}
1412
1413#[derive(Clone, Default)]
1414pub(crate) struct PrepaintStateIndex {
1415 hitboxes_index: usize,
1416 vn_tagged_hitboxes_index: usize,
1420 tooltips_index: usize,
1421 deferred_draws_index: usize,
1422 dispatch_tree_index: usize,
1423 accessed_element_states_index: usize,
1424 line_layout_index: LineLayoutIndex,
1425}
1426
1427#[derive(Clone, Default)]
1428pub(crate) struct PaintIndex {
1429 scene_index: usize,
1430 #[cfg(any(test, feature = "test-support"))]
1431 debug_bounds_index: usize,
1432 mouse_listeners_index: usize,
1433 input_handlers_index: usize,
1434 cursor_styles_index: usize,
1435 window_control_hitboxes_index: usize,
1436 accessed_element_states_index: usize,
1437 tab_handle_index: usize,
1438 line_layout_index: LineLayoutIndex,
1439}
1440
1441impl Frame {
1442 #[cfg(any(test, feature = "test-support"))]
1443 pub(crate) fn record_debug_bounds(&mut self, selector: String, bounds: Bounds<Pixels>) {
1444 self.debug_bounds.insert(selector.clone(), bounds);
1445 self.debug_bounds_records.push((selector, bounds));
1446 }
1447
1448 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
1449 Frame {
1450 focus: None,
1451 window_active: false,
1452 element_states: FxHashMap::default(),
1453 accessed_element_states: Vec::new(),
1454 mouse_listeners: Vec::new(),
1455 dispatch_tree,
1456 scene: Scene::default(),
1457 hitboxes: Vec::new(),
1458 vn_tagged_hitboxes: Vec::new(),
1459 vn_hit_order: Vec::new(),
1460 vn_deferred_tagged: 0..0,
1461 vn_tagged_order: std::cell::OnceCell::new(),
1462 window_control_hitboxes: Vec::new(),
1463 deferred_draws: Vec::new(),
1464 input_handlers: Vec::new(),
1465 tooltip_requests: Vec::new(),
1466 cursor_styles: Vec::new(),
1467
1468 #[cfg(any(test, feature = "test-support"))]
1469 debug_bounds: FxHashMap::default(),
1470 #[cfg(any(test, feature = "test-support"))]
1471 debug_bounds_records: Vec::new(),
1472
1473 #[cfg(any(feature = "inspector", debug_assertions))]
1474 next_inspector_instance_ids: FxHashMap::default(),
1475
1476 #[cfg(any(feature = "inspector", debug_assertions))]
1477 inspector_hitboxes: FxHashMap::default(),
1478 tab_stops: TabStopMap::default(),
1479 }
1480 }
1481
1482 pub(crate) fn clear(&mut self) {
1483 self.element_states.clear();
1484 self.accessed_element_states.clear();
1485 self.mouse_listeners.clear();
1486 self.dispatch_tree.clear();
1487 self.scene.clear();
1488 self.input_handlers.clear();
1489 self.tooltip_requests.clear();
1490 self.cursor_styles.clear();
1491 self.hitboxes.clear();
1492 self.vn_tagged_hitboxes.clear();
1493 self.vn_hit_order.clear();
1494 self.vn_deferred_tagged = 0..0;
1495 self.vn_tagged_order = std::cell::OnceCell::new();
1496 self.window_control_hitboxes.clear();
1497 self.deferred_draws.clear();
1498 self.tab_stops.clear();
1499 self.focus = None;
1500
1501 #[cfg(any(test, feature = "test-support"))]
1502 {
1503 self.debug_bounds.clear();
1504 self.debug_bounds_records.clear();
1505 }
1506
1507 #[cfg(any(feature = "inspector", debug_assertions))]
1508 {
1509 self.next_inspector_instance_ids.clear();
1510 self.inspector_hitboxes.clear();
1511 }
1512 }
1513
1514 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1515 self.cursor_styles
1516 .iter()
1517 .rev()
1518 .fold_while(None, |style, request| match request.hitbox_id {
1519 None => Done(Some(request.style)),
1520 Some(hitbox_id) => Continue(style.or_else(|| {
1521 hitbox_id
1522 .is_hovered_ignoring_last_input(window)
1523 .then_some(request.style)
1524 })),
1525 })
1526 .into_inner()
1527 }
1528
1529 fn box_contains(hitbox: &Hitbox, position: Point<Pixels>, scale_factor: f32) -> bool {
1531 let local = if hitbox.transformation.is_unit() {
1545 position
1546 } else {
1547 match hitbox.transformation.inverse() {
1548 Some(inverse) => {
1549 let d = inverse.apply(Point::new(
1550 px(position.x.0 * scale_factor),
1551 px(position.y.0 * scale_factor),
1552 ));
1553 Point::new(px(d.x.0 / scale_factor), px(d.y.0 / scale_factor))
1554 }
1555 None => return false,
1556 }
1557 };
1558 hitbox.content_mask.contains(&position)
1567 && hitbox.bounds.contains(&local)
1568 && hitbox.vn_clip.as_ref().is_none_or(|clip| {
1571 clip.contains([position.x.0 * scale_factor, position.y.0 * scale_factor])
1572 })
1573 }
1574
1575 fn vn_tagged_paint_order(&self) -> Option<&[u32]> {
1582 self.vn_tagged_order
1583 .get_or_init(|| {
1584 let deferred = self.vn_deferred_tagged.clone();
1585 if deferred.is_empty() {
1586 return None;
1587 }
1588 let len = self.vn_tagged_hitboxes.len();
1589 let mut order: Vec<u32> = Vec::with_capacity(len);
1590 order.extend(0..deferred.start as u32);
1591 let draws = &self.deferred_draws;
1592 let mut traversal = (0..draws.len()).collect::<Vec<_>>();
1593 traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
1594 for ix in traversal {
1595 let range = &draws[ix].prepaint_range;
1596 let (start, end) = (
1597 range.start.vn_tagged_hitboxes_index,
1598 range.end.vn_tagged_hitboxes_index,
1599 );
1600 if start >= deferred.start && end <= deferred.end && start < end {
1601 order.extend(start as u32..end as u32);
1602 }
1603 }
1604 order.extend(deferred.end as u32..len as u32);
1605 (order.len() == len).then_some(order)
1608 })
1609 .as_deref()
1610 }
1611
1612 fn topmost_hitboxes(&self) -> impl Iterator<Item = &Hitbox> {
1615 let in_paint_order = self.vn_hit_order.len() == self.hitboxes.len();
1616 (0..self.hitboxes.len()).rev().map(move |index| {
1617 let index = if in_paint_order { self.vn_hit_order[index] as usize } else { index };
1618 &self.hitboxes[index]
1619 })
1620 }
1621
1622 pub(crate) fn hit_test(&self, position: Point<Pixels>, scale_factor: f32) -> HitTest {
1623 let mut set_hover_hitbox_count = false;
1624 let mut hit_test = HitTest::default();
1625 for hitbox in self.topmost_hitboxes() {
1626 if Self::box_contains(hitbox, position, scale_factor) {
1627 hit_test.ids.push(hitbox.id);
1628 if !set_hover_hitbox_count
1629 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1630 {
1631 hit_test.hover_hitbox_count = hit_test.ids.len();
1632 set_hover_hitbox_count = true;
1633 }
1634 if hitbox.behavior == HitboxBehavior::BlockMouse {
1635 break;
1636 }
1637 }
1638 }
1639 if !set_hover_hitbox_count {
1640 hit_test.hover_hitbox_count = hit_test.ids.len();
1641 }
1642 hit_test
1643 }
1644
1645 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1646 self.focus
1647 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1648 .unwrap_or_default()
1649 }
1650
1651 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1652 for element_state_key in &self.accessed_element_states {
1653 if let Some((element_state_key, element_state)) =
1654 prev_frame.element_states.remove_entry(element_state_key)
1655 {
1656 self.element_states.insert(element_state_key, element_state);
1657 }
1658 }
1659
1660 self.scene.finish();
1661 }
1662}
1663
1664#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1665enum InputModality {
1666 Mouse,
1667 Keyboard,
1668 Touch,
1669}
1670
1671struct VnEffectPointer {
1674 moved: f32,
1677 entered: f32,
1678 left: f32,
1679 views: FxHashSet<EntityId>,
1681}
1682
1683impl VnEffectPointer {
1684 const NEVER: f32 = -1.0e4;
1686
1687 fn new(inside: bool) -> Self {
1688 let (entered, left) = if inside {
1689 (Self::NEVER, Self::NEVER - 1.)
1690 } else {
1691 (Self::NEVER - 1., Self::NEVER)
1692 };
1693 Self {
1694 moved: Self::NEVER,
1695 entered,
1696 left,
1697 views: FxHashSet::default(),
1698 }
1699 }
1700
1701 fn update(&mut self, was_inside: bool, inside: bool, moved: bool, cx: &mut App) {
1702 if was_inside == inside && !moved {
1703 return;
1704 }
1705 let now = crate::effect_clock_seconds();
1706 if moved {
1707 self.moved = now;
1708 }
1709 if inside && !was_inside {
1710 self.entered = now;
1711 } else if was_inside && !inside {
1712 self.left = now;
1713 }
1714 for view in self.views.drain() {
1715 cx.notify(view);
1716 }
1717 }
1718}
1719
1720pub struct Window {
1722 pub(crate) handle: AnyWindowHandle,
1723 pub(crate) invalidator: WindowInvalidator,
1724 pub(crate) removed: bool,
1725 pub(crate) platform_window: Box<dyn PlatformWindow>,
1726 pub(crate) display_id: Option<DisplayId>,
1727 pub(crate) display_observers: SingleSubscriberSet<AnyObserver>,
1728 is_resizable: bool,
1729 is_minimizable: bool,
1730 last_window_bounds: WindowBounds,
1731 sprite_atlas: Arc<dyn PlatformAtlas>,
1732 text_system: Rc<WindowTextSystem>,
1733 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1734 rem_size: Pixels,
1735 rem_size_override_stack: SmallVec<[Pixels; 8]>,
1740 pub(crate) viewport_size: Size<Pixels>,
1741 layout_engine: Option<TaffyLayoutEngine>,
1742 pub(crate) root: Option<AnyView>,
1743 pub(crate) element_id_stack: ElementIdStack,
1744 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1745 pub(crate) rendered_entity_stack: Vec<EntityId>,
1746 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1747 pub(crate) element_opacity: f32,
1748 element_image_tint: Hsla,
1751 pub(crate) element_transform: TransformationMatrix,
1759 vn_hitbox_tag: u32,
1763 vn_tag_fresh: bool,
1767 vn_tag_transform: Option<TransformationMatrix>,
1770 vn_tag_every_hitbox: bool,
1775 vn_pick_every_box: bool,
1778 vn_hit_refiner: Option<VnHitRefiner>,
1780 input_interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
1782 vn_key_event_seq: u64,
1784 vn_pointer_lock: Option<(VnPointerLock, Point<Pixels>)>,
1786 vn_raw_mouse_position: Option<Point<Pixels>>,
1788 vn_mouse_movement: Point<Pixels>,
1790 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1791 pub(crate) vn_clip_stack: Option<Arc<crate::VnClipNode>>,
1795 vn_capture_records: FxHashMap<u64, (crate::VnCaptureInfo, Bounds<ScaledPixels>)>,
1798 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1799 last_text_input_configuration: Option<TextInputConfiguration>,
1803 focused_text_input: Option<FocusId>,
1804 pub(crate) image_cache_stack: Vec<AnyImageCache>,
1805 pub(crate) rendered_frame: Frame,
1806 pub(crate) next_frame: Frame,
1807 next_hitbox_id: HitboxId,
1808 pub(crate) next_tooltip_id: TooltipId,
1809 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1810 pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1811 pub(crate) next_frame_wanted: Rc<Cell<bool>>,
1814 pub(crate) dirty_views: FxHashSet<EntityId>,
1815 focus_listeners: SingleSubscriberSet<AnyWindowFocusListener>,
1816 pub(crate) focus_lost_listeners: SingleSubscriberSet<AnyObserver>,
1817 focus_lost_path: SmallVec<[FocusId; 8]>,
1818 default_prevented: bool,
1819 mouse_position: Point<Pixels>,
1820 mouse_hit_test: HitTest,
1821 modifiers: Modifiers,
1822 capslock: Capslock,
1823 scale_factor: f32,
1824 pub(crate) bounds_observers: SingleSubscriberSet<AnyObserver>,
1825 appearance: WindowAppearance,
1826 pub(crate) appearance_observers: SingleSubscriberSet<AnyObserver>,
1827 pub(crate) button_layout_observers: SingleSubscriberSet<AnyObserver>,
1828 active: Rc<Cell<bool>>,
1829 assume_active: bool,
1831 visibility: WindowVisibility,
1832 pub(crate) visibility_observers:
1833 SingleSubscriberSet<Box<dyn FnMut(WindowVisibility, &mut Window, &mut App) -> bool>>,
1834 hovered: Rc<Cell<bool>>,
1835 pointer_inside: bool,
1849 vn_effect_pointer: VnEffectPointer,
1850 vn_effect_element: u64,
1853 vn_effect_phases: FxHashMap<u64, VnEffectPhase>,
1856 vn_defer_scope: Option<VnDeferScope>,
1859 vn_scopes_painted: FxHashSet<u64>,
1862 pub(crate) needs_present: Rc<Cell<bool>>,
1863 scene_animation_interval: Rc<Cell<Option<Duration>>>,
1866 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1869 #[cfg(feature = "profiler")]
1870 pub(crate) window_profiler: profiler::WindowProfiler,
1871 last_input_modality: InputModality,
1872 touch_gestures: TouchGestureRecognizer,
1873 touch_prediction_enabled: bool,
1874 long_press_timer: Option<Task<()>>,
1875 long_press_capture: Option<EntityId>,
1876 pub(crate) refreshing: bool,
1877 pub(crate) activation_observers: SingleSubscriberSet<AnyObserver>,
1878 pub(crate) focus: Option<FocusId>,
1879 focus_enabled: bool,
1880 pub(crate) focus_generation: u64,
1883 pending_input: Option<PendingInput>,
1884 pending_modifier: ModifierState,
1885 pub(crate) pending_input_observers: SingleSubscriberSet<AnyObserver>,
1886 prompt: Option<RenderablePromptHandle>,
1887 pub(crate) client_inset: Option<Pixels>,
1888 captured_hitbox: Option<HitboxId>,
1891 #[cfg(any(feature = "inspector", debug_assertions))]
1892 inspector: Option<Entity<Inspector>>,
1893 #[cfg(feature = "profiler")]
1894 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1895 pub(crate) a11y: A11y,
1896}
1897
1898#[derive(Clone, Debug, Default)]
1899struct ModifierState {
1900 modifiers: Modifiers,
1901 saw_other_input: bool,
1902}
1903
1904#[derive(Clone, Debug)]
1907pub(crate) struct InputRateTracker {
1908 timestamps: Vec<Instant>,
1909 window: Duration,
1910 inputs_per_second: u32,
1911 sustain_until: Instant,
1912 sustain_duration: Duration,
1913}
1914
1915const FRAME_INTERVAL_TOLERANCE: Duration = Duration::from_millis(1);
1916
1917#[derive(Default)]
1919struct FramePacer {
1920 last_frame: Option<Instant>,
1921}
1922
1923impl FramePacer {
1924 fn should_defer(&mut self, now: Instant, minimum_interval: Option<Duration>) -> bool {
1925 if let Some(interval) = minimum_interval
1926 && let Some(last_frame) = self.last_frame
1927 {
1928 let deadline = last_frame + interval;
1929 if now + FRAME_INTERVAL_TOLERANCE < deadline {
1930 return true;
1931 }
1932 self.last_frame = Some(if now.saturating_duration_since(deadline) <= interval / 4 {
1936 deadline
1937 } else {
1938 now
1939 });
1940 } else {
1941 self.last_frame = Some(now);
1942 }
1943 false
1944 }
1945}
1946
1947fn minimum_frame_interval(
1948 should_throttle: bool,
1949 inactive_without_high_rate_input: bool,
1950 inactive_frame_interval: Option<Duration>,
1951 low_power_frame_interval: Option<Duration>,
1952 thermal_frame_interval: Option<Duration>,
1953 thermal_state: ThermalState,
1954 power_mode: crate::PowerMode,
1955) -> Option<Duration> {
1956 if !should_throttle {
1957 return None;
1958 }
1959
1960 [
1961 inactive_frame_interval.filter(|_| inactive_without_high_rate_input),
1962 low_power_frame_interval.filter(|_| power_mode == crate::PowerMode::LowPower),
1963 thermal_frame_interval.filter(|_| {
1964 matches!(
1965 thermal_state,
1966 ThermalState::Critical | ThermalState::Serious
1967 )
1968 }),
1969 ]
1970 .into_iter()
1971 .flatten()
1972 .max()
1973}
1974
1975impl Default for InputRateTracker {
1976 fn default() -> Self {
1977 Self {
1978 timestamps: Vec::new(),
1979 window: Duration::from_millis(100),
1980 inputs_per_second: 60,
1981 sustain_until: Instant::now(),
1982 sustain_duration: Duration::from_secs(1),
1983 }
1984 }
1985}
1986
1987impl InputRateTracker {
1988 pub fn record_input(&mut self) {
1989 let now = Instant::now();
1990 self.timestamps.push(now);
1991 self.prune_old_timestamps(now);
1992
1993 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1994 if self.timestamps.len() as u128 >= min_events {
1995 self.sustain_until = now + self.sustain_duration;
1996 }
1997 }
1998
1999 pub fn is_high_rate(&self) -> bool {
2000 Instant::now() < self.sustain_until
2001 }
2002
2003 fn prune_old_timestamps(&mut self, now: Instant) {
2004 self.timestamps
2005 .retain(|&t| now.duration_since(t) <= self.window);
2006 }
2007}
2008
2009#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2010pub(crate) enum DrawPhase {
2011 None,
2012 Prepaint,
2013 Paint,
2014 Focus,
2015}
2016
2017pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
2018
2019pub struct PendingInputStatus<'a> {
2021 keystrokes: &'a [Keystroke],
2022 timeout: Option<PendingInputTimeoutStatus>,
2023}
2024
2025impl<'a> PendingInputStatus<'a> {
2026 pub fn keystrokes(&self) -> &'a [Keystroke] {
2028 self.keystrokes
2029 }
2030
2031 pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
2033 self.timeout
2034 }
2035}
2036
2037#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2039pub struct PendingInputTimeoutStatus {
2040 duration: Duration,
2041 remaining: Duration,
2042 started_at: Option<Instant>,
2043 paused: bool,
2044}
2045
2046impl PendingInputTimeoutStatus {
2047 pub fn duration(&self) -> Duration {
2049 self.duration
2050 }
2051
2052 pub fn remaining(&self, cx: &App) -> Duration {
2054 self.started_at
2055 .map(|started_at| {
2056 self.remaining
2057 .saturating_sub(cx.background_executor().now() - started_at)
2058 })
2059 .unwrap_or(self.remaining)
2060 }
2061
2062 pub fn is_paused(&self) -> bool {
2064 self.paused
2065 }
2066}
2067
2068#[derive(Debug)]
2069struct PendingInputTimeout {
2070 duration: Duration,
2071 remaining: Duration,
2072 state: PendingInputTimeoutState,
2073}
2074
2075#[derive(Debug)]
2076enum PendingInputTimeoutState {
2077 Running { started_at: Instant, task: Task<()> },
2078 Paused { pause: PendingInputTimeoutPause },
2079}
2080
2081#[derive(Debug)]
2082struct PendingInputTimeoutPause {
2083 owner_id: EntityId,
2084 _release_subscription: Subscription,
2085}
2086
2087impl PendingInputTimeout {
2088 fn is_paused(&self) -> bool {
2089 matches!(&self.state, PendingInputTimeoutState::Paused { .. })
2090 }
2091
2092 fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
2093 match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
2094 PendingInputTimeoutState::Running { started_at, task } => {
2095 self.remaining = self.remaining.saturating_sub(now - started_at);
2096 drop(task);
2097 true
2098 }
2099 previous_state @ PendingInputTimeoutState::Paused { .. } => {
2100 self.state = previous_state;
2101 false
2102 }
2103 }
2104 }
2105
2106 fn pause_owner_id(&self) -> Option<EntityId> {
2107 match &self.state {
2108 PendingInputTimeoutState::Running { .. } => None,
2109 PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
2110 }
2111 }
2112
2113 fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
2114 match std::mem::replace(
2115 &mut self.state,
2116 PendingInputTimeoutState::Running { started_at, task },
2117 ) {
2118 PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
2119 previous_state => {
2120 self.state = previous_state;
2121 false
2122 }
2123 }
2124 }
2125
2126 fn reset_duration(&mut self, duration: Duration) {
2127 self.duration = duration;
2128 self.remaining = duration;
2129 }
2130
2131 fn status(&self) -> PendingInputTimeoutStatus {
2132 let (started_at, paused) = match &self.state {
2133 PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
2134 PendingInputTimeoutState::Paused { .. } => (None, true),
2135 };
2136 PendingInputTimeoutStatus {
2137 duration: self.duration,
2138 remaining: self.remaining,
2139 started_at,
2140 paused,
2141 }
2142 }
2143}
2144
2145#[derive(Default, Debug)]
2146struct PendingInput {
2147 keystrokes: SmallVec<[Keystroke; 1]>,
2148 focus: Option<FocusId>,
2149 timeout: Option<PendingInputTimeout>,
2150}
2151
2152pub(crate) struct ElementStateBox {
2153 pub(crate) inner: Box<dyn Any>,
2154 #[cfg(debug_assertions)]
2155 pub(crate) type_name: &'static str,
2156}
2157
2158fn default_bounds(
2159 active_window_bounds: Option<WindowBounds>,
2160 display: Option<&dyn PlatformDisplay>,
2161) -> WindowBounds {
2162 const CASCADE_OFFSET: f32 = 25.0;
2163
2164 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
2165
2166 let display_bounds = display
2168 .map(|d| d.visible_bounds())
2169 .unwrap_or_else(default_placement);
2170
2171 let (
2172 Bounds {
2173 origin: base_origin,
2174 size: base_size,
2175 },
2176 window_bounds_ctor,
2177 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
2178 Some(bounds) => match bounds {
2179 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
2180 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
2181 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
2182 },
2183 None => (
2184 display
2185 .map(|d| d.default_bounds())
2186 .unwrap_or_else(default_placement),
2187 WindowBounds::Windowed,
2188 ),
2189 };
2190
2191 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
2192 let proposed_origin = base_origin + cascade_offset;
2193 let proposed_bounds = Bounds::new(proposed_origin, base_size);
2194
2195 let display_right = display_bounds.origin.x + display_bounds.size.width;
2196 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
2197 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
2198 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
2199
2200 let fits_horizontally = window_right <= display_right;
2201 let fits_vertically = window_bottom <= display_bottom;
2202
2203 let final_origin = match (fits_horizontally, fits_vertically) {
2204 (true, true) => proposed_origin,
2205 (false, true) => point(display_bounds.origin.x, base_origin.y),
2206 (true, false) => point(base_origin.x, display_bounds.origin.y),
2207 (false, false) => display_bounds.origin,
2208 };
2209 window_bounds_ctor(Bounds::new(final_origin, base_size))
2210}
2211
2212impl Window {
2213 pub(crate) fn new(
2214 handle: AnyWindowHandle,
2215 options: WindowOptions,
2216 cx: &mut App,
2217 ) -> Result<Self> {
2218 let WindowOptions {
2219 window_bounds,
2220 titlebar,
2221 focus,
2222 show,
2223 kind,
2224 is_movable,
2225 app_owns_titlebar_drag,
2226 inactive_frame_interval,
2227 low_power_frame_interval,
2228 thermal_frame_interval,
2229 is_resizable,
2230 is_minimizable,
2231 display_id,
2232 window_background,
2233 app_id,
2234 window_min_size,
2235 window_decorations,
2236 #[cfg_attr(
2237 not(any(target_os = "linux", target_os = "freebsd")),
2238 allow(unused_variables)
2239 )]
2240 icon,
2241 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
2242 tabbing_identifier,
2243 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
2244 use_display_p3,
2245 } = options;
2246
2247 let initial_window_title = titlebar
2248 .as_ref()
2249 .and_then(|titlebar| titlebar.title.clone());
2250
2251 let active_window_placement = cx.active_window_placement();
2252 let target_display_id = display_id.or_else(|| {
2254 active_window_placement
2255 .filter(|_| window_bounds.is_none())
2256 .and_then(|(display_id, _)| display_id)
2257 });
2258 let display = target_display_id
2259 .and_then(|display_id| cx.find_display(display_id))
2260 .or_else(|| cx.primary_display());
2261 let display_id = display
2262 .as_ref()
2263 .map(|display| display.id())
2264 .or(target_display_id);
2265 let active_window_bounds = active_window_placement
2266 .filter(|(active_display_id, _)| *active_display_id == display_id)
2267 .map(|(_, bounds)| bounds);
2268 let window_bounds = window_bounds
2269 .unwrap_or_else(|| default_bounds(active_window_bounds, display.as_deref()));
2270 let mut platform_window = cx.platform.open_window(
2271 handle,
2272 WindowParams {
2273 bounds: window_bounds.get_bounds(),
2274 titlebar,
2275 kind,
2276 is_movable,
2277 app_owns_titlebar_drag,
2278 is_resizable,
2279 is_minimizable,
2280 focus,
2281 show,
2282 display_id,
2283 window_min_size,
2284 app_id: app_id.clone(),
2285 icon,
2286 #[cfg(target_os = "macos")]
2287 tabbing_identifier,
2288 #[cfg(target_os = "macos")]
2289 use_display_p3,
2290 },
2291 )?;
2292
2293 let tab_bar_visible = platform_window.tab_bar_visible();
2294 SystemWindowTabController::init_visible(cx, tab_bar_visible);
2295 if let Some(tabs) = platform_window.tabbed_windows() {
2296 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
2297 }
2298
2299 let display_id = platform_window.display().map(|display| display.id());
2300 let sprite_atlas = platform_window.sprite_atlas();
2301 let mouse_position = platform_window.mouse_position();
2302 let modifiers = platform_window.modifiers();
2303 let capslock = platform_window.capslock();
2304 let content_size = platform_window.content_size();
2305 let scale_factor = platform_window.scale_factor();
2306 let appearance = platform_window.appearance();
2307 let text_system = Rc::new(WindowTextSystem::new(cx.text_system().clone()));
2308 let invalidator = WindowInvalidator::new(handle.window_id());
2309 let active = Rc::new(Cell::new(platform_window.is_active()));
2310 let visibility = platform_window.visibility();
2311 #[cfg(feature = "profiler")]
2312 profiler::journal::record_window_visibility(handle.window_id(), visibility);
2313 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
2314 let needs_present = Rc::new(Cell::new(false));
2315 let scene_animation_interval = Rc::new(Cell::new(None::<Duration>));
2316 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
2317 let next_frame_wanted: Rc<Cell<bool>> = Default::default();
2318 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
2319
2320 platform_window
2321 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
2322 platform_window.set_background_appearance(window_background);
2323
2324 match window_bounds {
2325 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
2326 WindowBounds::Maximized(_) => platform_window.zoom(),
2327 WindowBounds::Windowed(_) => {}
2328 }
2329
2330 let accessibility_force_disabled = cx.accessibility_force_disabled;
2331 let a11y_active_flag = Arc::new(AtomicBool::new(false));
2332
2333 #[cfg(not(target_family = "wasm"))]
2334 if !accessibility_force_disabled {
2335 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
2336 if let Some(title) = &initial_window_title {
2337 initial_root_node.set_label(title.to_string());
2338 }
2339 let initial_tree = accesskit::TreeUpdate {
2340 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
2341 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
2342 tree_id: accesskit::TreeId::ROOT,
2343 focus: ROOT_NODE_ID,
2344 };
2345 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
2346 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
2347 let (action_sender, action_receiver) =
2348 async_channel::unbounded::<accesskit::ActionRequest>();
2349
2350 platform_window.a11y_init(crate::A11yCallbacks {
2351 activation: {
2352 let active_flag = a11y_active_flag.clone();
2353 Box::new(move || {
2354 log::info!("Accessibility activated");
2355 active_flag.store(true, SeqCst);
2356 activation_sender
2357 .send_blocking(())
2358 .with_context(|| {
2359 format!(
2360 "queuing accessibility activation for window {:?}",
2361 handle.window_id()
2362 )
2363 })
2364 .log_err();
2365 Some(initial_tree.clone())
2366 })
2367 },
2368 action: Box::new(move |request| {
2369 action_sender
2370 .send_blocking(request)
2371 .with_context(|| {
2372 format!(
2373 "queuing accessibility action for window {:?}",
2374 handle.window_id()
2375 )
2376 })
2377 .log_err();
2378 }),
2379 deactivation: {
2380 let active_flag = a11y_active_flag.clone();
2381 Box::new(move || {
2382 log::info!("Accessibility deactivated");
2383 active_flag.store(false, SeqCst);
2384 deactivation_sender
2385 .send_blocking(())
2386 .with_context(|| {
2387 format!(
2388 "queuing accessibility deactivation for window {:?}",
2389 handle.window_id()
2390 )
2391 })
2392 .log_err();
2393 })
2394 },
2395 });
2396
2397 let mut async_cx = cx.to_async();
2403 cx.foreground_executor()
2404 .spawn(async move {
2405 while activation_receiver.recv().await.is_ok() {
2406 handle
2407 .update(&mut async_cx, |_, window, _| window.refresh())
2408 .with_context(|| {
2409 format!(
2410 "handling accessibility activation for window {:?}",
2411 handle.window_id()
2412 )
2413 })
2414 .log_err();
2415 }
2416 })
2417 .detach();
2418
2419 let mut async_cx = cx.to_async();
2420 cx.foreground_executor()
2421 .spawn(async move {
2422 while deactivation_receiver.recv().await.is_ok() {
2423 handle
2424 .update(&mut async_cx, |_, window, _| window.refresh())
2425 .with_context(|| {
2426 format!(
2427 "handling accessibility deactivation for window {:?}",
2428 handle.window_id()
2429 )
2430 })
2431 .log_err();
2432 }
2433 })
2434 .detach();
2435
2436 let mut async_cx = cx.to_async();
2437 cx.foreground_executor()
2438 .spawn(async move {
2439 while let Ok(request) = action_receiver.recv().await {
2440 handle
2441 .update(&mut async_cx, |_, window, cx| {
2442 window.handle_a11y_action(request, cx);
2443 })
2444 .with_context(|| {
2445 format!(
2446 "handling accessibility action for window {:?}",
2447 handle.window_id()
2448 )
2449 })
2450 .log_err();
2451 }
2452 })
2453 .detach();
2454 }
2455
2456 platform_window.on_close(Box::new({
2457 let window_id = handle.window_id();
2458 let cx = cx.to_async();
2459 move || {
2460 cx.spawn(async move |cx| {
2463 cx.update(|cx| {
2464 if cx.windows.contains_key(window_id) {
2466 handle
2467 .update(cx, |_, window, _| window.remove_window())
2468 .with_context(|| format!("handling close for window {window_id:?}"))
2469 .log_err();
2470 }
2471 SystemWindowTabController::remove_tab(cx, window_id);
2472 });
2473 })
2474 .detach();
2475 }
2476 }));
2477 platform_window.on_request_frame(Box::new({
2478 let mut cx = cx.to_async();
2479 let invalidator = invalidator.clone();
2480 let active = active.clone();
2481 let needs_present = needs_present.clone();
2482 let scene_animation_interval = scene_animation_interval.clone();
2483 let next_frame_callbacks = next_frame_callbacks.clone();
2484 let next_frame_wanted = next_frame_wanted.clone();
2485 let input_rate_tracker = input_rate_tracker.clone();
2486 let mut deferred_force_render = false;
2487 let mut frame_pacer = FramePacer::default();
2488 move |request_frame_options| {
2489 #[cfg(feature = "profiler")]
2490 let (_foreground_turn, window_id) = {
2491 let foreground_turn = profiler::journal::foreground_turn();
2492 let window_id = handle.window_id();
2493 profiler::journal::record_platform_signal(profiler::journal::PlatformSignal {
2494 window_id,
2495 signal_at: request_frame_options.signal_at,
2496 handled_at: Instant::now(),
2497 source: request_frame_options.signal_source,
2498 });
2499 (foreground_turn, window_id)
2500 };
2501 if draw_in_progress() {
2517 log::debug!("deferring re-entrant window draw request");
2518 deferred_force_render |= request_frame_options.force_render;
2519 #[cfg(feature = "profiler")]
2520 profiler::journal::record_reentrant_frame_skipped(window_id, Instant::now());
2521 return;
2522 }
2523 let force_render =
2527 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
2528
2529 let power_state = handle
2530 .update(&mut cx, |_, _, cx| (cx.thermal_state(), cx.power_mode()))
2531 .with_context(|| {
2532 format!(
2533 "reading power state for frame request for window {:?}",
2534 handle.window_id()
2535 )
2536 })
2537 .log_err();
2538
2539 let high_rate_input = input_rate_tracker.borrow_mut().is_high_rate();
2542 let present_for_high_rate_input = cfg!(target_os = "macos") && high_rate_input;
2546 let has_next_frame_callbacks = !next_frame_callbacks.borrow().is_empty();
2547 let wants_frame_besides_animation = invalidator.is_dirty()
2552 || force_render
2553 || next_frame_wanted.get()
2554 || request_frame_options.require_presentation
2555 || needs_present.get()
2556 || present_for_high_rate_input;
2557 let has_demand_besides_animation =
2558 wants_frame_besides_animation || has_next_frame_callbacks;
2559 let wants_frame =
2560 wants_frame_besides_animation || scene_animation_interval.get().is_some();
2561 let has_frame_demand = wants_frame || has_next_frame_callbacks;
2562
2563 let should_throttle = !request_frame_options.require_presentation;
2564 let inactive_without_high_rate_input =
2565 should_throttle && !active.get() && !high_rate_input;
2566 let (thermal_state, power_mode) =
2567 power_state.unwrap_or((ThermalState::Nominal, crate::PowerMode::Unknown));
2568 let min_frame_interval = minimum_frame_interval(
2569 should_throttle,
2570 inactive_without_high_rate_input,
2571 inactive_frame_interval,
2572 low_power_frame_interval,
2573 thermal_frame_interval,
2574 thermal_state,
2575 power_mode,
2576 );
2577 let animation_frame_interval = scene_animation_interval
2578 .get()
2579 .filter(|interval| !has_demand_besides_animation && !interval.is_zero());
2580 let min_frame_interval = min_frame_interval.max(animation_frame_interval);
2581
2582 let now = Instant::now();
2583 if has_frame_demand && frame_pacer.should_defer(now, min_frame_interval) {
2586 deferred_force_render |= force_render;
2588 if wants_frame {
2590 handle
2592 .update(&mut cx, |_, window, _| {
2593 window.platform_window.schedule_frame();
2594 })
2595 .with_context(|| {
2596 format!(
2597 "rescheduling throttled frame for window {:?}",
2598 handle.window_id()
2599 )
2600 })
2601 .log_err();
2602 invalidator.wake_platform();
2605 }
2606 #[cfg(feature = "profiler")]
2607 profiler::journal::record_frame_skipped(
2608 window_id,
2609 Instant::now(),
2610 if animation_frame_interval.is_some()
2611 && animation_frame_interval == min_frame_interval
2612 {
2613 profiler::journal::FrameSkipReason::AnimationFrameRateLimit
2614 } else if inactive_without_high_rate_input
2615 && inactive_frame_interval == min_frame_interval
2616 {
2617 profiler::journal::FrameSkipReason::InactiveFrameRateLimit
2618 } else if power_mode == crate::PowerMode::LowPower
2619 && low_power_frame_interval == min_frame_interval
2620 {
2621 profiler::journal::FrameSkipReason::LowPowerFrameRateLimit
2622 } else {
2623 profiler::journal::FrameSkipReason::ThermalFrameRateLimit
2624 },
2625 );
2626 report_frame(handle.window_id(), now, FrameOutcome::Throttled);
2627 return;
2628 }
2629
2630 if !next_frame_callbacks.borrow().is_empty() {
2631 handle
2632 .update(&mut cx, |_, window, cx| {
2633 window.next_frame_wanted.set(false);
2637 for callback in next_frame_callbacks.take() {
2638 callback(window, cx);
2639 }
2640 })
2641 .with_context(|| {
2642 format!(
2643 "running next-frame callbacks for window {:?}",
2644 handle.window_id()
2645 )
2646 })
2647 .log_err();
2648 }
2649
2650 let should_draw = invalidator.is_dirty() || force_render;
2651 let needs_present = request_frame_options.require_presentation
2652 || needs_present.get()
2653 || scene_animation_interval.get().is_some()
2654 || present_for_high_rate_input;
2655 if should_draw {
2656 measure("frame duration", || {
2657 handle
2658 .update(&mut cx, |_, window, cx| {
2659 #[cfg(feature = "profiler")]
2660 window
2661 .window_profiler
2662 .record_frame_signal(request_frame_options.signal_at);
2663 if force_render {
2664 window.refresh();
2667 }
2668 let arena_clear_needed = window.draw(cx);
2669 window.advance_scene_animations(cx);
2670 window.present();
2671 arena_clear_needed.clear(cx);
2672 })
2673 .with_context(|| {
2674 format!(
2675 "drawing and presenting frame for window {:?}",
2676 handle.window_id()
2677 )
2678 })
2679 .log_err();
2680 })
2681 } else if needs_present {
2682 handle
2683 .update(&mut cx, |_, window, cx| {
2684 window.advance_scene_animations(cx);
2685 window.present();
2686 })
2687 .with_context(|| {
2688 format!("presenting frame for window {:?}", handle.window_id())
2689 })
2690 .log_err();
2691 }
2692
2693 handle
2694 .update(&mut cx, |_, window, _| {
2695 if window.invalidator.is_dirty()
2696 || window.next_frame_wanted.get()
2697 || window.scene_animation_interval.get().is_some()
2698 {
2699 window.platform_window.schedule_frame();
2700 }
2701 })
2702 .with_context(|| {
2703 format!(
2704 "scheduling follow-up frame for window {:?}",
2705 handle.window_id()
2706 )
2707 })
2708 .log_err();
2709
2710 if invalidator.is_dirty()
2716 || next_frame_wanted.get()
2717 || scene_animation_interval.get().is_some()
2718 {
2719 invalidator.wake_platform();
2720 }
2721 #[cfg(feature = "profiler")]
2722 if !should_draw {
2723 profiler::journal::record_frame_skipped(
2724 window_id,
2725 Instant::now(),
2726 profiler::journal::FrameSkipReason::NoRenderNeeded,
2727 );
2728 }
2729 if should_draw {
2730 report_frame(handle.window_id(), now, FrameOutcome::Drew);
2731 } else if has_next_frame_callbacks || needs_present {
2732 report_frame(handle.window_id(), now, FrameOutcome::NoDraw);
2733 }
2734 }
2735 }));
2736 invalidator.set_platform_waker(platform_window.frame_waker());
2737 platform_window.on_visual_viewport_changed(Box::new({
2738 let mut cx = cx.to_async();
2739 move || {
2740 handle
2741 .update(&mut cx, |_, window, _| window.refresh())
2742 .with_context(|| {
2743 format!(
2744 "handling visual viewport change for window {:?}",
2745 handle.window_id()
2746 )
2747 })
2748 .log_err();
2749 }
2750 }));
2751 platform_window.on_insets_changed(Box::new({
2752 let mut cx = cx.to_async();
2753 move |_| {
2754 handle
2755 .update(&mut cx, |_, window, _| window.refresh())
2756 .with_context(|| {
2757 format!("handling insets change for window {:?}", handle.window_id())
2758 })
2759 .log_err();
2760 }
2761 }));
2762 platform_window.on_resize(Box::new({
2763 let mut cx = cx.to_async();
2764 move |_, _| {
2765 handle
2766 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2767 .with_context(|| format!("handling resize for window {:?}", handle.window_id()))
2768 .log_err();
2769 }
2770 }));
2771 platform_window.on_moved(Box::new({
2772 let mut cx = cx.to_async();
2773 move || {
2774 handle
2775 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
2776 .with_context(|| format!("handling move for window {:?}", handle.window_id()))
2777 .log_err();
2778 }
2779 }));
2780 platform_window.on_display_changed(Box::new({
2781 let cx = cx.to_async();
2782 move || cx.update(|cx| Window::display_changed(handle, cx))
2783 }));
2784 platform_window.on_appearance_changed(Box::new({
2785 let cx = cx.to_async();
2786 let foreground_executor = cx.foreground_executor().clone();
2787 move || {
2788 let mut cx = cx.clone();
2789 foreground_executor
2792 .spawn(async move {
2793 handle
2794 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
2795 .with_context(|| {
2796 format!(
2797 "handling appearance change for window {:?}",
2798 handle.window_id()
2799 )
2800 })
2801 .log_err();
2802 })
2803 .detach();
2804 }
2805 }));
2806 platform_window.on_button_layout_changed(Box::new({
2807 let mut cx = cx.to_async();
2808 move || {
2809 handle
2810 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
2811 .with_context(|| {
2812 format!(
2813 "handling button layout change for window {:?}",
2814 handle.window_id()
2815 )
2816 })
2817 .log_err();
2818 }
2819 }));
2820 platform_window.on_active_status_change(Box::new({
2821 let mut cx = cx.to_async();
2822 move |active| {
2823 handle
2824 .update(&mut cx, |_, window, cx| {
2825 if window.assume_active {
2829 return;
2830 }
2831 window.active.set(active);
2832 window.modifiers = window.platform_window.modifiers();
2833 window.capslock = window.platform_window.capslock();
2834 window
2835 .activation_observers
2836 .clone()
2837 .retain(|callback| callback(window, cx));
2838
2839 window.bounds_changed(cx);
2840 window.refresh();
2841
2842 SystemWindowTabController::update_last_active(cx, window.handle.id);
2843 })
2844 .with_context(|| {
2845 format!(
2846 "handling active status change for window {:?}",
2847 handle.window_id()
2848 )
2849 })
2850 .log_err();
2851 }
2852 }));
2853 platform_window.on_visibility_change(Box::new({
2854 let mut cx = cx.to_async();
2855 move |_| {
2856 handle
2857 .update(&mut cx, |_, window, cx| {
2858 window.refresh_visibility(cx);
2859 })
2860 .with_context(|| {
2861 format!(
2862 "handling visibility change for window {:?}",
2863 handle.window_id()
2864 )
2865 })
2866 .log_err();
2867 }
2868 }));
2869 platform_window.on_hover_status_change(Box::new({
2870 let mut cx = cx.to_async();
2871 move |active| {
2872 handle
2873 .update(&mut cx, |_, window, cx| {
2874 window.hovered.set(active);
2875 let was_inside = std::mem::replace(&mut window.pointer_inside, active);
2876 window
2877 .vn_effect_pointer
2878 .update(was_inside, active, false, cx);
2879 window.refresh();
2880 })
2881 .with_context(|| {
2882 format!(
2883 "handling hover status change for window {:?}",
2884 handle.window_id()
2885 )
2886 })
2887 .log_err();
2888 }
2889 }));
2890 platform_window.on_input({
2891 let mut cx = cx.to_async();
2892 Box::new(move |event| {
2893 handle
2894 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
2895 .with_context(|| {
2896 format!("dispatching input for window {:?}", handle.window_id())
2897 })
2898 .log_err()
2899 .unwrap_or(DispatchEventResult::default())
2900 })
2901 });
2902 platform_window.on_hit_test_window_control_at({
2903 let mut cx = cx.to_async();
2904 Box::new(move |position| {
2905 handle
2906 .update(&mut cx, |_, window, _cx| {
2907 let position = position.unwrap_or_else(|| window.platform_window.mouse_position());
2912 window.window_control_area_at(position)
2913 })
2914 .with_context(|| {
2915 format!(
2916 "hit-testing window controls for window {:?}",
2917 handle.window_id()
2918 )
2919 })
2920 .log_err()
2921 .unwrap_or(None)
2922 })
2923 });
2924 platform_window.on_move_tab_to_new_window({
2925 let mut cx = cx.to_async();
2926 Box::new(move || {
2927 handle
2928 .update(&mut cx, |_, _window, cx| {
2929 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
2930 })
2931 .with_context(|| {
2932 format!(
2933 "moving tab to new window from window {:?}",
2934 handle.window_id()
2935 )
2936 })
2937 .log_err();
2938 })
2939 });
2940 platform_window.on_merge_all_windows({
2941 let mut cx = cx.to_async();
2942 Box::new(move || {
2943 handle
2944 .update(&mut cx, |_, _window, cx| {
2945 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
2946 })
2947 .with_context(|| {
2948 format!("merging all windows into window {:?}", handle.window_id())
2949 })
2950 .log_err();
2951 })
2952 });
2953 platform_window.on_select_next_tab({
2954 let mut cx = cx.to_async();
2955 Box::new(move || {
2956 handle
2957 .update(&mut cx, |_, _window, cx| {
2958 SystemWindowTabController::select_next_tab(cx, handle.window_id());
2959 })
2960 .with_context(|| {
2961 format!("selecting next tab for window {:?}", handle.window_id())
2962 })
2963 .log_err();
2964 })
2965 });
2966 platform_window.on_select_previous_tab({
2967 let mut cx = cx.to_async();
2968 Box::new(move || {
2969 handle
2970 .update(&mut cx, |_, _window, cx| {
2971 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
2972 })
2973 .with_context(|| {
2974 format!("selecting previous tab for window {:?}", handle.window_id())
2975 })
2976 .log_err();
2977 })
2978 });
2979 platform_window.on_toggle_tab_bar({
2980 let mut cx = cx.to_async();
2981 Box::new(move || {
2982 handle
2983 .update(&mut cx, |_, window, cx| {
2984 let tab_bar_visible = window.platform_window.tab_bar_visible();
2985 SystemWindowTabController::set_visible(cx, tab_bar_visible);
2986 })
2987 .with_context(|| {
2988 format!("toggling tab bar for window {:?}", handle.window_id())
2989 })
2990 .log_err();
2991 })
2992 });
2993
2994 if let Some(app_id) = app_id {
2995 platform_window.set_app_id(&app_id);
2996 }
2997
2998 platform_window.map_window().unwrap();
2999
3000 Ok(Window {
3001 handle,
3002 invalidator,
3003 removed: false,
3004 platform_window,
3005 display_id,
3006 display_observers: SingleSubscriberSet::new(),
3007 is_resizable,
3008 is_minimizable,
3009 last_window_bounds: window_bounds,
3010 sprite_atlas,
3011 text_system,
3012 text_rendering_mode: cx.text_rendering_mode.clone(),
3013 rem_size: px(16.),
3014 rem_size_override_stack: SmallVec::new(),
3015 viewport_size: content_size,
3016 layout_engine: Some(TaffyLayoutEngine::new()),
3017 root: None,
3018 element_id_stack: ElementIdStack::default(),
3019 text_style_stack: Vec::new(),
3020 rendered_entity_stack: Vec::new(),
3021 element_offset_stack: Vec::new(),
3022 content_mask_stack: Vec::new(),
3023 vn_clip_stack: None,
3024 vn_capture_records: FxHashMap::default(),
3025 element_opacity: 1.0,
3026 element_image_tint: Hsla::transparent_black(),
3027 element_transform: TransformationMatrix::unit(),
3028 vn_hitbox_tag: 0,
3029 vn_tag_fresh: false,
3030 vn_tag_transform: None,
3031 vn_tag_every_hitbox: false,
3032 vn_pick_every_box: false,
3033 vn_hit_refiner: None,
3034 input_interceptor: None,
3035 vn_key_event_seq: 0,
3036 vn_pointer_lock: None,
3037 vn_raw_mouse_position: None,
3038 vn_mouse_movement: Point::default(),
3039 requested_autoscroll: None,
3040 last_text_input_configuration: None,
3041 focused_text_input: None,
3042 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
3043 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
3044 next_frame_callbacks,
3045 next_frame_wanted,
3046 next_hitbox_id: HitboxId(0),
3047 next_tooltip_id: TooltipId::default(),
3048 tooltip_bounds: None,
3049 dirty_views: FxHashSet::default(),
3050 focus_listeners: SingleSubscriberSet::new(),
3051 focus_lost_listeners: SingleSubscriberSet::new(),
3052 focus_lost_path: SmallVec::new(),
3053 default_prevented: true,
3054 mouse_position,
3055 mouse_hit_test: HitTest::default(),
3056 modifiers,
3057 capslock,
3058 scale_factor,
3059 bounds_observers: SingleSubscriberSet::new(),
3060 appearance,
3061 appearance_observers: SingleSubscriberSet::new(),
3062 button_layout_observers: SingleSubscriberSet::new(),
3063 active,
3064 assume_active: false,
3065 visibility,
3066 visibility_observers: SingleSubscriberSet::new(),
3067 vn_effect_pointer: VnEffectPointer::new(hovered.get()),
3068 vn_effect_element: 0,
3069 vn_effect_phases: FxHashMap::default(),
3070 vn_defer_scope: None,
3071 vn_scopes_painted: FxHashSet::default(),
3072 pointer_inside: hovered.get(),
3073 hovered,
3074 needs_present,
3075 scene_animation_interval,
3076 input_rate_tracker,
3077 #[cfg(feature = "profiler")]
3078 window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
3079 last_input_modality: InputModality::Mouse,
3080 touch_gestures: TouchGestureRecognizer::new(
3081 cx.platform
3082 .gestures()
3083 .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
3084 ),
3085 touch_prediction_enabled: true,
3086 long_press_timer: None,
3087 long_press_capture: None,
3088 refreshing: false,
3089 activation_observers: SingleSubscriberSet::new(),
3090 focus: None,
3091 focus_enabled: true,
3092 focus_generation: 0,
3093 pending_input: None,
3094 pending_modifier: ModifierState::default(),
3095 pending_input_observers: SingleSubscriberSet::new(),
3096 prompt: None,
3097 client_inset: None,
3098 image_cache_stack: Vec::new(),
3099 captured_hitbox: None,
3100 #[cfg(any(feature = "inspector", debug_assertions))]
3101 inspector: None,
3102 #[cfg(feature = "profiler")]
3103 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
3104 a11y: A11y::new(
3105 a11y_active_flag,
3106 accessibility_force_disabled,
3107 initial_window_title,
3108 ),
3109 })
3110 }
3111
3112 pub(crate) fn new_focus_listener(
3113 &self,
3114 value: AnyWindowFocusListener,
3115 ) -> (Subscription, impl FnOnce() + use<>) {
3116 self.focus_listeners.insert_pending(value)
3117 }
3118}
3119
3120#[derive(Clone, Debug, Default, PartialEq, Eq)]
3121#[expect(missing_docs)]
3122pub struct DispatchEventResult {
3123 pub propagate: bool,
3124 pub default_prevented: bool,
3125}
3126
3127#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
3137#[repr(C)]
3138pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
3139 pub bounds: Bounds<P>,
3141 pub corner_radii: Corners<P>,
3144 pub corner_shapes: CornerShapes,
3147}
3148
3149impl<P: Clone + Debug + Default + PartialEq> ContentMask<P> {
3150 pub fn rect(bounds: Bounds<P>) -> Self {
3152 ContentMask {
3153 bounds,
3154 corner_radii: Corners::default(),
3155 corner_shapes: CornerShapes::default(),
3156 }
3157 }
3158
3159 pub fn is_rounded(&self) -> bool {
3161 self.corner_radii != Corners::default()
3162 }
3163}
3164
3165impl ContentMask<Pixels> {
3166 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
3168 ContentMask {
3169 bounds: self.bounds.scale(factor),
3170 corner_radii: self.corner_radii.scale(factor),
3171 corner_shapes: self.corner_shapes.scale(factor),
3172 }
3173 }
3174}
3175
3176impl<P> ContentMask<P>
3177where
3178 P: Copy
3179 + Ord
3180 + Debug
3181 + Default
3182 + Add<P, Output = P>
3183 + Sub<P, Output = P>
3184 + Div<f32, Output = P>
3185 + Into<f64>,
3186{
3187 pub fn intersect(&self, other: &Self) -> Self {
3203 let bounds = self.bounds.intersect(&other.bounds);
3204 if !self.is_rounded() && !other.is_rounded() {
3205 return ContentMask::rect(bounds);
3206 }
3207 let at = |mask: &Self, left: bool, top: bool| {
3208 let x = if left { mask.bounds.left() } else { mask.bounds.right() };
3209 let y = if top { mask.bounds.top() } else { mask.bounds.bottom() };
3210 (x, y)
3211 };
3212 let radius = |left: bool, top: bool, mine: (P, u32), theirs: (P, u32)| {
3213 let here = at(&ContentMask::rect(bounds), left, top);
3214 let mine = if at(self, left, top) == here { mine } else { (P::default(), 0) };
3215 let theirs = if at(other, left, top) == here { theirs } else { (P::default(), 0) };
3216 if theirs.0 > mine.0 { theirs } else { mine }
3217 };
3218 let (a, b) = (&self.corner_radii, &other.corner_radii);
3219 let (sa, sb) = (self.corner_shapes.corners(), other.corner_shapes.corners());
3220 let top_left = radius(true, true, (a.top_left, sa.top_left), (b.top_left, sb.top_left));
3221 let top_right = radius(false, true, (a.top_right, sa.top_right), (b.top_right, sb.top_right));
3222 let bottom_right = radius(
3223 false,
3224 false,
3225 (a.bottom_right, sa.bottom_right),
3226 (b.bottom_right, sb.bottom_right),
3227 );
3228 let bottom_left =
3229 radius(true, false, (a.bottom_left, sa.bottom_left), (b.bottom_left, sb.bottom_left));
3230 let corner_radii = Corners {
3231 top_left: top_left.0,
3232 top_right: top_right.0,
3233 bottom_right: bottom_right.0,
3234 bottom_left: bottom_left.0,
3235 }
3236 .clamp_radii_for_quad_size(bounds.size);
3237 ContentMask {
3238 bounds,
3239 corner_radii,
3240 corner_shapes: CornerShapes {
3241 top_left: top_left.1,
3242 top_right: top_right.1,
3243 bottom_right: bottom_right.1,
3244 bottom_left: bottom_left.1,
3245 },
3246 }
3247 }
3248
3249 pub fn contains(&self, point: &Point<P>) -> bool {
3253 if !self.bounds.contains(point) {
3254 return false;
3255 }
3256 if !self.is_rounded() {
3257 return true;
3258 }
3259 if !self.corner_shapes.is_round() {
3260 return crate::corner_shape::shaped_rect_sdf(
3261 *point,
3262 &self.bounds,
3263 &self.corner_radii,
3264 &self.corner_shapes,
3265 ) <= 0.;
3266 }
3267 let b = &self.bounds;
3268 let r = &self.corner_radii;
3269 for (radius, cx, cy, left, top) in [
3270 (r.top_left, b.left() + r.top_left, b.top() + r.top_left, true, true),
3271 (r.top_right, b.right() - r.top_right, b.top() + r.top_right, false, true),
3272 (r.bottom_right, b.right() - r.bottom_right, b.bottom() - r.bottom_right, false, false),
3273 (r.bottom_left, b.left() + r.bottom_left, b.bottom() - r.bottom_left, true, false),
3274 ] {
3275 let in_x = if left { point.x < cx } else { point.x > cx };
3276 let in_y = if top { point.y < cy } else { point.y > cy };
3277 if radius > P::default() && in_x && in_y {
3278 let (dx, dy): (f64, f64) = ((point.x - cx).into(), (point.y - cy).into());
3279 let radius: f64 = radius.into();
3280 return dx * dx + dy * dy <= radius * radius;
3281 }
3282 }
3283 true
3284 }
3285}
3286
3287impl Window {
3288 fn mark_view_dirty(&mut self, view_id: EntityId) {
3289 for view_id in self
3292 .rendered_frame
3293 .dispatch_tree
3294 .view_path_reversed(view_id)
3295 {
3296 if !self.dirty_views.insert(view_id) {
3297 break;
3298 }
3299 }
3300 }
3301
3302 pub(crate) fn refresh_visibility(&mut self, cx: &mut App) {
3303 let visibility = self.platform_window.visibility();
3304 if self.visibility != visibility {
3305 self.visibility = visibility;
3306 #[cfg(feature = "profiler")]
3307 profiler::journal::record_window_visibility(self.handle.window_id(), visibility);
3308 self.visibility_observers
3309 .clone()
3310 .retain(|callback| callback(visibility, self, cx));
3311 }
3312 #[cfg(feature = "profiler")]
3313 if self.invalidator.is_dirty() || self.needs_present.get() {
3314 profiler::journal::record_frame_pending(self.handle.window_id(), Instant::now());
3315 }
3316 }
3317
3318 pub(crate) fn debug_state(&self) -> serde_json::Value {
3323 let platform_window = &self.platform_window;
3324 serde_json::json!({
3325 "id": self.handle.window_id().as_u64(),
3326 "title": platform_window.get_title(),
3327 "bounds": platform_window.bounds(),
3328 "window_bounds": format!("{:?}", platform_window.window_bounds()),
3329 "content_size": platform_window.content_size(),
3330 "viewport_size": self.viewport_size,
3331 "scale_factor": {
3332 "cached": self.scale_factor,
3333 "platform": platform_window.scale_factor(),
3334 },
3335 "display_id": {
3336 "cached": self.display_id.map(u64::from),
3337 "platform": platform_window.display().map(|display| u64::from(display.id())),
3338 },
3339 "active": {
3340 "cached": self.active.get(),
3341 "platform": platform_window.is_active(),
3342 },
3343 "hovered": {
3344 "cached": self.hovered.get(),
3345 "platform": platform_window.is_hovered(),
3346 },
3347 "visibility": {
3348 "cached": format!("{:?}", self.visibility),
3349 "platform": format!("{:?}", platform_window.visibility()),
3350 },
3351 "appearance": {
3352 "cached": format!("{:?}", self.appearance),
3353 "platform": format!("{:?}", platform_window.appearance()),
3354 },
3355 "is_fullscreen": platform_window.is_fullscreen(),
3356 "is_maximized": platform_window.is_maximized(),
3357 "mouse_position": {
3358 "cached": self.mouse_position,
3359 "platform": platform_window.mouse_position(),
3360 },
3361 "modifiers": {
3362 "cached": self.modifiers,
3363 "platform": platform_window.modifiers(),
3364 },
3365 "cursor_style": self.rendered_frame.cursor_style(self),
3366 "frame": {
3367 "dirty": self.invalidator.is_dirty(),
3368 "needs_present": self.needs_present.get(),
3369 "refreshing": self.refreshing,
3370 "next_frame_callbacks": self.next_frame_callbacks.borrow().len(),
3371 },
3372 "gpu": platform_window.gpu_specs(),
3373 "platform": platform_window.debug_state(),
3374 })
3375 }
3376
3377 pub fn visibility(&self) -> WindowVisibility {
3380 self.visibility
3381 }
3382
3383 pub fn is_visible(&self) -> bool {
3389 self.visibility.is_visible()
3390 }
3391
3392 pub fn observe_window_visibility(
3394 &self,
3395 mut callback: impl FnMut(WindowVisibility, &mut Window, &mut App) + 'static,
3396 ) -> Subscription {
3397 self.visibility_observers
3398 .insert(Box::new(move |visibility, window, cx| {
3399 callback(visibility, window, cx);
3400 true
3401 }))
3402 }
3403
3404 pub fn observe_window_activation(
3407 &self,
3408 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3409 ) -> Subscription {
3410 self.activation_observers
3411 .insert(Box::new(move |window, cx| {
3412 callback(window, cx);
3413 true
3414 }))
3415 }
3416
3417 pub fn observe_window_appearance(
3419 &self,
3420 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3421 ) -> Subscription {
3422 self.appearance_observers
3423 .insert(Box::new(move |window, cx| {
3424 callback(window, cx);
3425 true
3426 }))
3427 }
3428
3429 pub fn observe_button_layout_changed(
3431 &self,
3432 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
3433 ) -> Subscription {
3434 self.button_layout_observers
3435 .insert(Box::new(move |window, cx| {
3436 callback(window, cx);
3437 true
3438 }))
3439 }
3440
3441 pub fn replace_root<E>(
3443 &mut self,
3444 cx: &mut App,
3445 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
3446 ) -> Entity<E>
3447 where
3448 E: 'static + Render,
3449 {
3450 let view = cx.new(|cx| build_view(self, cx));
3451 self.root = Some(view.clone().into());
3452 self.refresh();
3453 view
3454 }
3455
3456 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
3458 where
3459 E: 'static + Render,
3460 {
3461 self.root
3462 .as_ref()
3463 .map(|view| view.clone().downcast::<E>().ok())
3464 }
3465
3466 pub fn window_handle(&self) -> AnyWindowHandle {
3468 self.handle
3469 }
3470
3471 pub fn refresh(&mut self) {
3473 if self.invalidator.not_drawing() {
3474 self.refreshing = true;
3475 self.invalidator.set_dirty(true);
3476 }
3477 }
3478
3479 pub fn remove_window(&mut self) {
3481 self.removed = true;
3482 }
3483
3484 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
3486 self.focus
3487 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
3488 }
3489
3490 pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
3494 let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
3495 ancestors.iter().rev().find_map(|id| {
3496 self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
3497 FocusHandle::for_id(*id, &cx.focus_handles)
3498 })
3499 }
3500
3501 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
3503 if !self.focus_enabled || self.focus == Some(handle.id) {
3504 return;
3505 }
3506
3507 self.focus = Some(handle.id);
3508 self.focus_generation = self.focus_generation.wrapping_add(1);
3509 self.clear_pending_keystrokes(cx);
3510
3511 self.refresh();
3512 }
3513
3514 pub fn blur(&mut self, cx: &mut App) {
3516 self.clear_pending_keystrokes(cx);
3517
3518 if !self.focus_enabled {
3519 return;
3520 }
3521
3522 if self.focus.is_some() {
3523 self.focus_generation = self.focus_generation.wrapping_add(1);
3524 }
3525 self.focus = None;
3526 self.refresh();
3527 }
3528
3529 pub fn disable_focus(&mut self, cx: &mut App) {
3531 self.blur(cx);
3532 self.focus_enabled = false;
3533 }
3534
3535 pub fn focus_next(&mut self, cx: &mut App) {
3537 if !self.focus_enabled {
3538 return;
3539 }
3540
3541 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
3542 self.focus(&handle, cx)
3543 }
3544 }
3545
3546 pub fn focus_prev(&mut self, cx: &mut App) {
3548 if !self.focus_enabled {
3549 return;
3550 }
3551
3552 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
3553 self.focus(&handle, cx)
3554 }
3555 }
3556
3557 pub fn text_system(&self) -> &Rc<WindowTextSystem> {
3559 &self.text_system
3560 }
3561
3562 pub fn text_style(&self) -> TextStyle {
3564 let mut style = TextStyle::default();
3565 for refinement in &self.text_style_stack {
3566 style.refine(refinement);
3567 }
3568 style
3569 }
3570
3571 pub fn is_maximized(&self) -> bool {
3575 self.platform_window.is_maximized()
3576 }
3577
3578 pub fn request_decorations(&self, decorations: WindowDecorations) {
3580 self.platform_window.request_decorations(decorations);
3581 }
3582
3583 pub fn set_exclusive_zone(&self, zone: Pixels) {
3589 self.platform_window.set_exclusive_zone(zone);
3590 }
3591
3592 #[cfg(all(target_os = "linux", feature = "wayland"))]
3597 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
3598 self.platform_window.set_exclusive_edge(edge);
3599 }
3600
3601 pub fn start_window_resize(&self, edge: ResizeEdge) {
3603 if self.is_resizable {
3604 self.platform_window.start_window_resize(edge);
3605 }
3606 }
3607
3608 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
3615 self.platform_window.set_input_region(region);
3616 }
3617
3618 pub fn window_bounds(&self) -> WindowBounds {
3621 self.platform_window.window_bounds()
3622 }
3623
3624 pub(crate) fn last_window_bounds(&self) -> WindowBounds {
3625 self.last_window_bounds
3626 }
3627
3628 pub(crate) fn display_id(&self) -> Option<DisplayId> {
3629 self.display_id
3630 }
3631
3632 pub fn inner_window_bounds(&self) -> WindowBounds {
3634 self.platform_window.inner_window_bounds()
3635 }
3636
3637 pub fn vn_composition_underlay(&self) -> Option<(usize, usize)> {
3641 self.platform_window.vn_composition_underlay()
3642 }
3643
3644 pub fn vn_set_maximized(&self, maximized: bool) {
3646 self.platform_window.vn_set_maximized(maximized)
3647 }
3648
3649 pub fn vn_is_zoomed(&self) -> bool {
3651 self.platform_window.vn_is_zoomed()
3652 }
3653
3654 pub fn vn_is_minimized(&self) -> bool {
3656 self.platform_window.vn_is_minimized()
3657 }
3658
3659 pub fn vn_unminimize(&self) {
3661 self.platform_window.vn_unminimize()
3662 }
3663
3664 pub fn vn_hide(&self) -> bool {
3666 self.platform_window.vn_hide()
3667 }
3668
3669 pub fn vn_is_shown(&self) -> bool {
3671 self.platform_window.vn_is_shown()
3672 }
3673
3674 pub fn vn_set_frame(&self, origin: Option<Point<Pixels>>, size: Option<Size<Pixels>>) -> bool {
3677 self.platform_window.vn_set_frame(origin, size)
3678 }
3679
3680 pub fn vn_set_always_on_top(&self, on: bool) -> bool {
3682 self.platform_window.vn_set_always_on_top(on)
3683 }
3684
3685 pub fn vn_set_maximizable(&self, maximizable: bool) {
3687 self.platform_window.vn_set_maximizable(maximizable)
3688 }
3689
3690 pub fn vn_set_ignore_mouse(&self, ignore: bool) -> bool {
3692 self.platform_window.vn_set_ignore_mouse(ignore)
3693 }
3694
3695 pub fn vn_set_content_protection(&self, on: bool) -> bool {
3697 self.platform_window.vn_set_content_protection(on)
3698 }
3699
3700 pub fn vn_request_close(&self) {
3702 self.platform_window.vn_request_close()
3703 }
3704
3705 pub fn native_window_state(&self) -> Option<Vec<u8>> {
3708 self.platform_window.native_window_state()
3709 }
3710
3711 pub fn restore_native_window_state(&self, state: &[u8]) {
3714 self.platform_window.restore_native_window_state(state);
3715 }
3716
3717 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
3719 let focus_id = self.focused(cx).map(|handle| handle.id);
3720
3721 let window = self.handle;
3722 cx.defer(move |cx| {
3723 window
3724 .update(cx, |_, window, cx| {
3725 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
3726 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
3727 })
3728 .with_context(|| format!("dispatching action for window {:?}", window.window_id()))
3729 .log_err();
3730 })
3731 }
3732
3733 pub(crate) fn dispatch_keystroke_observers(
3734 &mut self,
3735 keystroke: &Keystroke,
3736 input_preference: InputPreference,
3737 action: Option<&dyn Action>,
3738 context_stack: Vec<KeyContext>,
3739 cx: &mut App,
3740 ) {
3741 cx.keystroke_observers.clone().retain(move |callback| {
3742 (callback)(
3743 &KeystrokeEvent {
3744 keystroke: keystroke.clone(),
3745 input_preference,
3746 action: action.map(|action| action.boxed_clone()),
3747 context_stack: context_stack.clone(),
3748 },
3749 self,
3750 cx,
3751 )
3752 });
3753 }
3754
3755 pub(crate) fn dispatch_keystroke_interceptors(
3756 &mut self,
3757 keystroke: &Keystroke,
3758 input_preference: InputPreference,
3759 context_stack: Vec<KeyContext>,
3760 cx: &mut App,
3761 ) {
3762 cx.keystroke_interceptors.clone().retain(move |callback| {
3763 (callback)(
3764 &KeystrokeEvent {
3765 keystroke: keystroke.clone(),
3766 input_preference,
3767 action: None,
3768 context_stack: context_stack.clone(),
3769 },
3770 self,
3771 cx,
3772 )
3773 });
3774 }
3775
3776 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
3779 let handle = self.handle;
3780 cx.defer(move |cx| {
3781 handle.update(cx, |_, window, cx| f(window, cx)).ok();
3782 });
3783 }
3784
3785 pub fn observe<T: 'static>(
3789 &mut self,
3790 observed: &Entity<T>,
3791 cx: &mut App,
3792 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
3793 ) -> Subscription {
3794 let entity_id = observed.entity_id();
3795 let observed = observed.downgrade();
3796 let window_handle = self.handle;
3797 cx.new_observer(
3798 entity_id,
3799 Box::new(move |cx| {
3800 window_handle
3801 .update(cx, |_, window, cx| {
3802 if let Some(handle) = observed.upgrade() {
3803 on_notify(handle, window, cx);
3804 true
3805 } else {
3806 false
3807 }
3808 })
3809 .unwrap_or(false)
3810 }),
3811 )
3812 }
3813
3814 pub fn subscribe<Emitter, Evt>(
3818 &mut self,
3819 entity: &Entity<Emitter>,
3820 cx: &mut App,
3821 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
3822 ) -> Subscription
3823 where
3824 Emitter: EventEmitter<Evt>,
3825 Evt: 'static,
3826 {
3827 let entity_id = entity.entity_id();
3828 let handle = entity.downgrade();
3829 let window_handle = self.handle;
3830 cx.new_subscription(
3831 entity_id,
3832 (
3833 TypeId::of::<Evt>(),
3834 Box::new(move |event, cx| {
3835 window_handle
3836 .update(cx, |_, window, cx| {
3837 if let Some(entity) = handle.upgrade() {
3838 let event = event.downcast_ref().expect("invalid event type");
3839 on_event(entity, event, window, cx);
3840 true
3841 } else {
3842 false
3843 }
3844 })
3845 .unwrap_or(false)
3846 }),
3847 ),
3848 )
3849 }
3850
3851 pub fn observe_release<T>(
3853 &self,
3854 entity: &Entity<T>,
3855 cx: &mut App,
3856 on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
3857 ) -> Subscription
3858 where
3859 T: 'static,
3860 {
3861 let entity_id = entity.entity_id();
3862 let window_handle = self.handle;
3863 cx.release_listeners.insert(
3864 entity_id,
3865 Box::new(move |entity, cx| {
3866 let entity = entity.downcast_mut().expect("invalid entity type");
3867 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
3868 }),
3869 )
3870 }
3871
3872 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
3875 AsyncWindowContext::new_context(cx.to_async(), self.handle)
3876 }
3877
3878 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
3880 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
3881 self.next_frame_wanted.set(true);
3882 self.platform_window.schedule_frame();
3883 self.invalidator.wake_platform();
3886 }
3887
3888 pub fn on_next_frame_passive(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
3894 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
3895 }
3896
3897 pub fn request_animation_frame(&self) {
3910 let entity = self.current_view();
3911 self.on_next_frame(move |_, cx| cx.notify(entity));
3912 }
3913
3914 pub(crate) fn advance_scene_animations(&mut self, cx: &App) {
3915 let elapsed = cx.background_executor().now() - cx.synced_animation_epoch;
3916 self.rendered_frame.scene.advance_animations(elapsed);
3917 }
3918
3919 #[cfg(any(test, feature = "test-support"))]
3924 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
3925 let callbacks = self.next_frame_callbacks.take();
3926 self.next_frame_wanted.set(false);
3927 let count = callbacks.len();
3928 for callback in callbacks {
3929 callback(self, cx);
3930 }
3931 count
3932 }
3933
3934 #[track_caller]
3938 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
3939 where
3940 R: 'static,
3941 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3942 {
3943 let handle = self.handle;
3944 cx.spawn(async move |app| {
3945 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3946 f(&mut async_window_cx).await
3947 })
3948 }
3949
3950 #[track_caller]
3954 pub fn spawn_with_priority<AsyncFn, R>(
3955 &self,
3956 priority: Priority,
3957 cx: &App,
3958 f: AsyncFn,
3959 ) -> Task<R>
3960 where
3961 R: 'static,
3962 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
3963 {
3964 let handle = self.handle;
3965 cx.spawn_with_priority(priority, async move |app| {
3966 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
3967 f(&mut async_window_cx).await
3968 })
3969 }
3970
3971 pub fn bounds_changed(&mut self, cx: &mut App) {
3977 self.scale_factor = self.platform_window.scale_factor();
3978 self.viewport_size = self.platform_window.content_size();
3979 self.last_window_bounds = self.platform_window.window_bounds();
3980 cx.sync_window_update_entry(self);
3981 self.mouse_position = self.platform_window.mouse_position();
3982
3983 self.refresh();
3984
3985 self.bounds_observers
3986 .clone()
3987 .retain(|callback| callback(self, cx));
3988 }
3989
3990 fn display_changed(handle: AnyWindowHandle, cx: &mut App) {
3991 let moved_to = handle
3992 .update(cx, |_, window, _| {
3993 let display_id = window.platform_window.display().map(|display| display.id());
3994 let moved = display_id != window.display_id;
3995 window.display_id = display_id;
3996 moved.then_some(display_id)
3997 })
3998 .with_context(|| {
3999 format!(
4000 "handling display change for window {:?}",
4001 handle.window_id()
4002 )
4003 })
4004 .log_err()
4005 .flatten();
4006 let Some(display_id) = moved_to else {
4007 return;
4008 };
4009 if let Some(display_id) = display_id
4013 && !cx.knows_display(display_id)
4014 {
4015 cx.displays_changed();
4016 }
4017 handle
4018 .update(cx, |_, window, cx| window.notify_display_observers(cx))
4019 .with_context(|| {
4020 format!(
4021 "notifying display observers for window {:?}",
4022 handle.window_id()
4023 )
4024 })
4025 .log_err();
4026 }
4027
4028 pub(crate) fn notify_display_observers(&mut self, cx: &mut App) {
4029 self.display_observers
4030 .clone()
4031 .retain(|callback| callback(self, cx));
4032 }
4033
4034 pub fn refresh_interval(&self, cx: &App) -> Option<Duration> {
4039 cx.display_refresh_interval(self.display_id?)
4040 }
4041
4042 pub fn observe_window_display(
4047 &self,
4048 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
4049 ) -> Subscription {
4050 self.display_observers.insert(Box::new(move |window, cx| {
4051 callback(window, cx);
4052 true
4053 }))
4054 }
4055
4056 pub fn bounds(&self) -> Bounds<Pixels> {
4058 self.platform_window.bounds()
4059 }
4060
4061 pub fn insets(&self) -> WindowInsets {
4063 self.platform_window.insets()
4064 }
4065
4066 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
4080 self.platform_window
4081 .render_to_image(&self.rendered_frame.scene)
4082 }
4083
4084 #[cfg(feature = "bench-support")]
4087 pub fn rendered_scene(&self) -> &Scene {
4088 &self.rendered_frame.scene
4089 }
4090
4091 #[cfg(any(test, feature = "test-support"))]
4096 pub fn painted_quads(&self) -> Vec<Quad> {
4097 self.rendered_frame.scene.quads.clone()
4098 }
4099
4100 #[cfg(any(test, feature = "test-support"))]
4102 pub fn painted_underlines(&self) -> Vec<Underline> {
4103 self.rendered_frame.scene.underlines.clone()
4104 }
4105
4106 pub fn resize(&mut self, size: Size<Pixels>) {
4108 self.platform_window.resize(size);
4109 }
4110
4111 pub fn is_fullscreen(&self) -> bool {
4113 self.platform_window.is_fullscreen()
4114 }
4115
4116 pub fn is_simple_fullscreen(&self) -> bool {
4120 self.platform_window.is_simple_fullscreen()
4121 }
4122
4123 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
4124 self.appearance = self.platform_window.appearance();
4125
4126 self.appearance_observers
4127 .clone()
4128 .retain(|callback| callback(self, cx));
4129 }
4130
4131 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
4132 self.button_layout_observers
4133 .clone()
4134 .retain(|callback| callback(self, cx));
4135 }
4136
4137 pub fn appearance(&self) -> WindowAppearance {
4139 self.appearance
4140 }
4141
4142 pub fn viewport_size(&self) -> Size<Pixels> {
4144 self.viewport_size
4145 }
4146
4147 pub fn visual_viewport_bounds(&self) -> Bounds<Pixels> {
4153 self.platform_window.visual_viewport_bounds()
4154 }
4155
4156 pub fn fully_visible_bounds(&self) -> Bounds<Pixels> {
4161 let insets = self.platform_window.insets().effective();
4162 let viewport = self.viewport_size();
4163 let left = insets.left.max(Pixels::ZERO).min(viewport.width);
4164 let top = insets.top.max(Pixels::ZERO).min(viewport.height);
4165 let right = (viewport.width - insets.right.max(Pixels::ZERO)).max(left);
4166 let bottom = (viewport.height - insets.bottom.max(Pixels::ZERO)).max(top);
4167 let safe_bounds = Bounds::from_corners(point(left, top), point(right, bottom));
4168 let mut visible = safe_bounds.intersect(&self.visual_viewport_bounds());
4169 visible.size.width = visible.size.width.max(Pixels::ZERO);
4170 visible.size.height = visible.size.height.max(Pixels::ZERO);
4171 visible
4172 }
4173
4174 pub fn request_virtual_keyboard(&self) {
4179 self.platform_window.show_soft_keyboard();
4180 }
4181
4182 pub fn dismiss_virtual_keyboard(&self) {
4184 self.platform_window.hide_soft_keyboard();
4185 }
4186
4187 pub fn is_window_active(&self) -> bool {
4189 self.active.get()
4190 }
4191
4192 pub fn set_assume_active(&mut self, on: bool) {
4205 self.assume_active = on;
4206 let active = on || self.platform_window.is_active();
4207 if self.active.replace(active) != active {
4208 self.refresh();
4209 }
4210 }
4211
4212 pub fn set_draws_while_occluded(&self, on: bool) {
4215 self.platform_window.set_draws_while_occluded(on);
4216 }
4217
4218 pub fn is_window_hovered(&self) -> bool {
4222 if cfg!(any(
4223 target_os = "windows",
4224 target_os = "linux",
4225 target_os = "freebsd"
4226 )) {
4227 self.hovered.get()
4228 } else {
4229 self.is_window_active()
4230 }
4231 }
4232
4233 pub fn zoom_window(&self) {
4235 self.platform_window.zoom();
4236 }
4237
4238 pub fn show_window_menu(&self, position: Point<Pixels>) {
4240 self.platform_window.show_window_menu(position)
4241 }
4242
4243 pub fn start_window_move(&self) {
4248 self.platform_window.start_window_move()
4249 }
4250
4251 pub fn set_client_inset(&mut self, inset: Pixels) {
4253 self.client_inset = Some(inset);
4254 self.platform_window.set_client_inset(inset);
4255 }
4256
4257 pub fn set_client_corner_radii(&mut self, radii: Corners<Pixels>) {
4259 self.platform_window.set_client_corner_radii(radii);
4260 }
4261
4262 pub fn client_inset(&self) -> Option<Pixels> {
4264 self.client_inset
4265 }
4266
4267 pub fn window_decorations(&self) -> Decorations {
4269 self.platform_window.window_decorations()
4270 }
4271
4272 pub fn is_resizable(&self) -> bool {
4274 self.is_resizable
4275 }
4276
4277 pub fn is_minimizable(&self) -> bool {
4279 self.is_minimizable
4280 }
4281
4282 pub fn window_controls(&self) -> WindowControls {
4284 self.platform_window.window_controls()
4285 }
4286
4287 pub fn set_window_title(&mut self, title: &str) {
4289 self.platform_window.set_title(title);
4290 self.a11y.set_window_title(title.to_string());
4291 }
4292
4293 #[cfg(target_os = "macos")]
4295 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
4296 self.platform_window.set_traffic_light_position(position);
4297 }
4298
4299 #[cfg(target_os = "macos")]
4301 pub fn set_native_titlebar_visibility(&self, visible: bool) {
4302 self.platform_window.set_native_titlebar_visibility(visible);
4303 }
4304
4305 pub fn set_app_id(&mut self, app_id: &str) {
4307 self.platform_window.set_app_id(app_id);
4308 }
4309
4310 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
4312 self.platform_window
4313 .set_background_appearance(background_appearance);
4314 }
4315
4316 pub fn is_background_appearance_drawn(&self) -> bool {
4322 self.platform_window.is_background_appearance_drawn()
4323 }
4324
4325 pub fn set_window_edited(&mut self, edited: bool) {
4327 self.platform_window.set_edited(edited);
4328 }
4329
4330 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
4333 self.platform_window.set_document_path(path);
4334 }
4335
4336 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
4338 cx.platform
4339 .displays()
4340 .into_iter()
4341 .find(|display| Some(display.id()) == self.display_id)
4342 }
4343
4344 pub fn show_character_palette(&self) {
4346 self.platform_window.show_character_palette();
4347 }
4348
4349 pub fn scale_factor(&self) -> f32 {
4353 self.scale_factor
4354 }
4355
4356 #[cfg(any(test, feature = "test-support"))]
4358 pub fn set_scale_factor(&mut self, scale_factor: f32) {
4359 self.scale_factor = scale_factor;
4360 self.refresh();
4361 }
4362
4363 pub fn rem_size(&self) -> Pixels {
4366 self.rem_size_override_stack
4367 .last()
4368 .copied()
4369 .unwrap_or(self.rem_size)
4370 }
4371
4372 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
4375 self.rem_size = rem_size.into();
4376 }
4377
4378 pub fn with_global_id<R>(
4381 &mut self,
4382 element_id: ElementId,
4383 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
4384 ) -> R {
4385 self.with_id(element_id, |this| {
4386 let global_id = this.element_id_stack.global_id();
4387
4388 f(&global_id, this)
4389 })
4390 }
4391
4392 #[inline]
4394 pub fn with_id<R>(
4395 &mut self,
4396 element_id: impl Into<ElementId>,
4397 f: impl FnOnce(&mut Self) -> R,
4398 ) -> R {
4399 self.element_id_stack.push(element_id.into());
4400 let result = f(self);
4401 self.element_id_stack.pop();
4402 result
4403 }
4404
4405 #[inline]
4411 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
4412 where
4413 F: FnOnce(&mut Self) -> R,
4414 {
4415 self.invalidator.debug_assert_paint_or_prepaint();
4416
4417 if let Some(rem_size) = rem_size {
4418 self.rem_size_override_stack.push(rem_size.into());
4419 let result = f(self);
4420 self.rem_size_override_stack.pop();
4421 result
4422 } else {
4423 f(self)
4424 }
4425 }
4426
4427 pub fn line_height(&self) -> Pixels {
4429 self.text_style().line_height_in_pixels(self.rem_size())
4430 }
4431
4432 #[inline]
4434 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
4435 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
4436 }
4437
4438 #[inline]
4440 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
4441 let scale_factor = f64::from(self.scale_factor());
4442 round_half_toward_zero_f64(value * scale_factor) / scale_factor
4443 }
4444
4445 #[inline]
4447 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
4448 bounds.map(|c| self.pixel_snap(c))
4449 }
4450
4451 #[inline]
4453 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
4454 position.map(|c| self.pixel_snap(c))
4455 }
4456
4457 pub fn underline_bounds(
4459 &self,
4460 origin: Point<Pixels>,
4461 width: Pixels,
4462 style: &UnderlineStyle,
4463 ) -> Bounds<ScaledPixels> {
4464 let scale_factor = self.scale_factor();
4465 let thickness = self.snap_stroke(style.thickness);
4466 let height = if style.wavy {
4467 ScaledPixels(thickness.0 * 3.)
4468 } else {
4469 thickness
4470 };
4471 Bounds {
4472 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4473 size: size(self.snap_stroke(width), height),
4474 }
4475 }
4476
4477 pub fn paint_underline_with_exclusions(
4479 &mut self,
4480 origin: Point<Pixels>,
4481 width: Pixels,
4482 style: &UnderlineStyle,
4483 exclusions: &[Range<ScaledPixels>],
4484 ) {
4485 self.invalidator.debug_assert_paint();
4486 let underline = self.underline(origin, width, style);
4487 if exclusions.is_empty() {
4488 self.next_frame.scene.insert_primitive(underline);
4489 return;
4490 }
4491
4492 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
4493 if bounds.is_empty() {
4494 return;
4495 }
4496
4497 let mut exclusions = exclusions
4498 .iter()
4499 .filter_map(|span| {
4500 let start = span.start.max(bounds.left());
4501 let end = span.end.min(bounds.right());
4502 (start < end).then_some(start..end)
4503 })
4504 .collect::<SmallVec<[_; 4]>>();
4505 if exclusions.is_empty() {
4506 self.next_frame.scene.insert_primitive(underline);
4507 return;
4508 }
4509 exclusions.sort_unstable_by_key(|span| span.start);
4510
4511 let mut paint_span = |start, end| {
4512 let span = ContentMask::rect(Bounds::from_corners(
4515 point(start, bounds.top()),
4516 point(end, bounds.bottom()),
4517 ));
4518 self.next_frame.scene.insert_primitive(Underline {
4519 content_mask: underline.content_mask.intersect(&span),
4520 ..underline
4521 });
4522 };
4523 let mut start = bounds.left();
4524 for exclusion in exclusions {
4525 if start < exclusion.start {
4526 paint_span(start, exclusion.start);
4527 }
4528 start = start.max(exclusion.end);
4529 }
4530 if start < bounds.right() {
4531 paint_span(start, bounds.right());
4532 }
4533 }
4534
4535 fn underline(&self, origin: Point<Pixels>, width: Pixels, style: &UnderlineStyle) -> Underline {
4536 Underline {
4537 order: 0,
4538 pad: 0,
4539 bounds: self.underline_bounds(origin, width, style),
4540 content_mask: self.snapped_content_mask(),
4541 color: style
4542 .color
4543 .unwrap_or_default()
4544 .opacity(self.element_opacity()),
4545 thickness: self.snap_stroke(style.thickness),
4546 wavy: style.wavy.into(),
4547 transformation: self.element_transform,
4550 }
4551 }
4552
4553 #[inline]
4554 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
4555 let scale_factor = self.scale_factor();
4556 let left = round_to_device_pixel(bounds.left().0, scale_factor);
4557 let top = round_to_device_pixel(bounds.top().0, scale_factor);
4558 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
4559 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
4560 Bounds::from_corners(
4561 point(ScaledPixels(left), ScaledPixels(top)),
4562 point(ScaledPixels(right), ScaledPixels(bottom)),
4563 )
4564 }
4565
4566 #[inline]
4568 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
4569 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
4570 }
4571
4572 #[inline]
4573 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
4574 edges.map(|e| self.snap_stroke(*e))
4575 }
4576
4577 #[inline]
4579 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
4580 let scale_factor = self.scale_factor();
4581 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
4582 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
4583 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
4584 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
4585 Bounds::from_corners(
4586 point(ScaledPixels(left), ScaledPixels(top)),
4587 point(ScaledPixels(right), ScaledPixels(bottom)),
4588 )
4589 }
4590
4591 #[inline]
4592 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
4593 let mask = self.content_mask();
4594 ContentMask {
4595 bounds: self.cover_bounds(mask.bounds),
4596 corner_radii: mask.corner_radii.scale(self.scale_factor()),
4600 corner_shapes: mask.corner_shapes.scale(self.scale_factor()),
4601 }
4602 }
4603
4604 pub fn prevent_default(&mut self) {
4607 self.default_prevented = true;
4608 }
4609
4610 pub fn default_prevented(&self) -> bool {
4612 self.default_prevented
4613 }
4614
4615 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
4617 let node_id =
4618 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
4619 self.rendered_frame
4620 .dispatch_tree
4621 .is_action_available(action, node_id)
4622 }
4623
4624 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
4626 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
4627 self.rendered_frame
4628 .dispatch_tree
4629 .is_action_available(action, node_id)
4630 }
4631
4632 pub fn mouse_position(&self) -> Point<Pixels> {
4634 self.mouse_position
4635 }
4636
4637 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
4644 self.captured_hitbox = Some(hitbox_id);
4645 }
4646
4647 pub fn release_pointer(&mut self) {
4649 self.captured_hitbox = None;
4650 }
4651
4652 pub fn captured_hitbox(&self) -> Option<HitboxId> {
4654 self.captured_hitbox
4655 }
4656
4657 pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
4663 self.long_press_capture = Some(entity.entity_id());
4664 }
4665
4666 pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
4668 self.long_press_capture == Some(entity.entity_id())
4669 }
4670
4671 pub fn modifiers(&self) -> Modifiers {
4673 self.modifiers
4674 }
4675
4676 pub fn last_input_was_keyboard(&self) -> bool {
4679 self.last_input_modality == InputModality::Keyboard
4680 }
4681
4682 pub fn last_input_was_touch(&self) -> bool {
4684 self.last_input_modality == InputModality::Touch
4685 }
4686
4687 pub fn capslock(&self) -> Capslock {
4689 self.capslock
4690 }
4691
4692 #[profiling::function]
4695 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
4696 let _profile_window = crate::native_profiling::window_scope(self.platform_window.as_ref());
4697 let _profile = crate::native_profiling::current_span("native", "GPUI draw");
4698 #[cfg(feature = "profiler")]
4701 let frame_dirty = self.invalidator.take_frame_dirty();
4702 #[cfg(feature = "profiler")]
4703 self.window_profiler.begin_draw();
4704
4705 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
4708
4709 if self.platform_window.prepare_frame() {
4710 self.refresh();
4711 }
4712 self.invalidate_entities();
4713 cx.entities.clear_accessed();
4714 debug_assert!(self.rendered_entity_stack.is_empty());
4715 self.invalidator.set_dirty(false);
4716 self.requested_autoscroll = None;
4717
4718 if let Some(input_handler) = self.platform_window.take_input_handler() {
4723 if let Some(slot) = self
4724 .rendered_frame
4725 .input_handlers
4726 .iter_mut()
4727 .rev()
4728 .find(|h| h.is_none())
4729 {
4730 *slot = Some(input_handler);
4731 } else {
4732 self.rendered_frame.input_handlers.push(Some(input_handler));
4733 }
4734 }
4735 if !cx.mode.skip_drawing() {
4736 self.vn_scopes_painted.clear();
4737 self.draw_roots(cx);
4738 let now = crate::effect_clock_seconds();
4739 self.vn_effect_phases
4740 .retain(|_, phase| now - phase.at < VnEffectPhase::KEEP);
4741 #[cfg(feature = "profiler")]
4742 {
4743 let viewport_size = self.viewport_size;
4744 let scale_factor = self.scale_factor();
4745 self.debug_frame_overlay.paint(
4746 &mut self.next_frame.scene,
4747 viewport_size,
4748 scale_factor,
4749 );
4750 }
4751 }
4752 let _finalize = crate::native_profiling::current_span("native", "GPUI finalize frame");
4753 self.dirty_views.clear();
4754 self.next_frame.window_active = self.active.get();
4755
4756 let focused_text_input = if let Some(mut input_handler) = self
4762 .next_frame
4763 .input_handlers
4764 .iter_mut()
4765 .rev()
4766 .find_map(|h| h.take())
4767 {
4768 let accepts_text_input = input_handler.accepts_text_input(self, cx);
4769 self.platform_window.set_input_handler(input_handler);
4770 self.focus.filter(|_| accepts_text_input)
4771 } else {
4772 None
4773 };
4774 self.apply_text_input_configuration(cx);
4775 let previous = mem::replace(&mut self.focused_text_input, focused_text_input);
4776 if previous.is_some() != focused_text_input.is_some() {
4777 self.platform_window
4778 .text_input_state_changed(if focused_text_input.is_some() {
4779 TextInputStateChange::FocusGained
4780 } else {
4781 TextInputStateChange::FocusLost
4782 });
4783 }
4784
4785 {
4786 let _profile = crate::native_profiling::current_span("native", "GPUI finish layout and text");
4787 self.layout_engine.as_mut().unwrap().clear();
4788 self.text_system().finish_frame();
4789 }
4790 {
4791 let _profile = crate::native_profiling::current_span("native", "GPUI finish scene");
4792 self.next_frame.finish(&mut self.rendered_frame);
4793 self.vn_settle_captures();
4794 }
4795
4796 self.invalidator.set_phase(DrawPhase::Focus);
4797 let previous_focus_path = self.rendered_frame.focus_path();
4798 let previous_window_active = self.rendered_frame.window_active;
4799 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
4800 self.scene_animation_interval
4801 .set(self.rendered_frame.scene.animation_frame_interval());
4802 {
4803 let _profile = crate::native_profiling::current_span("native", "GPUI clear previous frame");
4804 self.next_frame.clear();
4805 }
4806 let current_focus_path = self.rendered_frame.focus_path();
4807 let current_window_active = self.rendered_frame.window_active;
4808 let mut focus_before_listeners = self.focus;
4809
4810 if previous_focus_path != current_focus_path
4811 || previous_window_active != current_window_active
4812 {
4813 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
4814 self.focus_lost_path = previous_focus_path.clone();
4815 self.focus_lost_listeners
4816 .clone()
4817 .retain(|listener| listener(self, cx));
4818 self.focus_lost_path = SmallVec::new();
4819 focus_before_listeners = self.focus;
4824 }
4825
4826 let event = WindowFocusEvent {
4827 previous_focus_path: if previous_window_active {
4828 previous_focus_path
4829 } else {
4830 Default::default()
4831 },
4832 current_focus_path: if current_window_active {
4833 current_focus_path
4834 } else {
4835 Default::default()
4836 },
4837 };
4838 self.focus_listeners
4839 .clone()
4840 .retain(|listener| listener(&event, self, cx));
4841 }
4842
4843 debug_assert!(self.rendered_entity_stack.is_empty());
4844 self.record_entities_accessed(cx);
4845 self.reset_cursor_style(cx);
4846 self.refreshing = false;
4847 self.invalidator.set_phase(DrawPhase::None);
4848 if self.focus != focus_before_listeners {
4853 self.refresh();
4854 }
4855 self.needs_present.set(true);
4856
4857 #[cfg(feature = "profiler")]
4858 {
4859 self.window_profiler
4860 .set_refresh_interval(self.refresh_interval(cx));
4861 let draw_duration = self
4862 .window_profiler
4863 .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
4864 self.debug_frame_overlay.record_frame(draw_duration);
4865 }
4866
4867 arena_scope.exit(&cx.element_arena)
4870 }
4871
4872 fn record_entities_accessed(&mut self, cx: &mut App) {
4873 let entities = cx.entities.take_accessed();
4874 let handle = self.handle;
4875 cx.record_entities_accessed(
4876 handle,
4877 self.invalidator.clone(),
4879 &entities,
4880 );
4881 cx.entities.restore_accessed(entities);
4882 }
4883
4884 fn invalidate_entities(&mut self) {
4885 let mut views = self.invalidator.take_views();
4886 for entity in views.drain() {
4887 self.mark_view_dirty(entity);
4888 }
4889 self.invalidator.replace_views(views);
4890 }
4891
4892 #[profiling::function]
4893 fn present(&mut self) {
4894 #[cfg(feature = "profiler")]
4895 let _foreground_turn = profiler::journal::foreground_turn();
4896 #[cfg(feature = "profiler")]
4897 let present_start = Instant::now();
4898 self.platform_window.draw(&self.rendered_frame.scene);
4899 #[cfg(feature = "profiler")]
4900 self.window_profiler.record_present(
4901 present_start,
4902 Instant::now(),
4903 self.active.get(),
4904 !self.next_frame_callbacks.borrow().is_empty(),
4905 );
4906 self.needs_present.set(false);
4907 profiling::finish_frame!();
4908 }
4909
4910 #[cfg(all(test, feature = "profiler"))]
4912 pub fn present_if_needed(&mut self) {
4913 if self.needs_present.get() {
4914 self.present();
4915 }
4916 }
4917
4918 #[cfg(feature = "profiler")]
4920 pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
4921 self.window_profiler.input_latency_snapshot()
4922 }
4923
4924 #[cfg(feature = "profiler")]
4926 pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
4927 self.window_profiler.frame_duration_snapshot()
4928 }
4929
4930 #[cfg(feature = "profiler")]
4932 pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
4933 self.debug_frame_overlay.mode()
4934 }
4935
4936 #[cfg(feature = "profiler")]
4938 pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
4939 self.debug_frame_overlay.set_mode(mode);
4940 self.refresh();
4941 }
4942
4943 #[cfg(feature = "profiler")]
4946 pub fn cycle_debug_frame_overlay_mode(&mut self) {
4947 self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
4948 }
4949
4950 #[cfg(feature = "profiler")]
4953 pub fn reset_debug_frame_overlay_stats(&mut self) {
4954 self.debug_frame_overlay.reset_stats();
4955 self.refresh();
4956 }
4957
4958 fn draw_roots(&mut self, cx: &mut App) {
4959 self.invalidator.set_phase(DrawPhase::Prepaint);
4960 self.tooltip_bounds.take();
4961
4962 self.a11y.sync_active_flag();
4963 if self.a11y.is_active() {
4964 self.a11y.begin_frame();
4965 }
4966
4967 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
4968 let root_size = {
4969 #[cfg(any(feature = "inspector", debug_assertions))]
4970 {
4971 if self.inspector.is_some() {
4972 let mut size = self.viewport_size;
4973 size.width = (size.width - _inspector_width).max(px(0.0));
4974 size
4975 } else {
4976 self.viewport_size
4977 }
4978 }
4979 #[cfg(not(any(feature = "inspector", debug_assertions)))]
4980 {
4981 self.viewport_size
4982 }
4983 };
4984
4985 let scale_factor = self.scale_factor();
4989 #[cfg(feature = "profiler")]
4990 let request_layout_start = Instant::now();
4991 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
4992 let root_layout_id = root_element.request_layout(self, cx);
4993 #[cfg(feature = "profiler")]
4994 let prepaint_start = Instant::now();
4995 self.layout_engine
4996 .as_mut()
4997 .unwrap()
4998 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
4999 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
5000
5001 #[cfg(any(feature = "inspector", debug_assertions))]
5002 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
5003
5004 let deferred_hitboxes_start = self.next_frame.hitboxes.len();
5005 let deferred_tagged_start = self.next_frame.vn_tagged_hitboxes.len();
5006 self.prepaint_deferred_draws(cx);
5007 let deferred_hitboxes = deferred_hitboxes_start..self.next_frame.hitboxes.len();
5008 self.next_frame.vn_deferred_tagged =
5009 deferred_tagged_start..self.next_frame.vn_tagged_hitboxes.len();
5010
5011 let mut prompt_element = None;
5012 let mut active_drag_element = None;
5013 let mut tooltip_element = None;
5014 if let Some(prompt) = self.prompt.take() {
5015 let mut element = prompt.view.any_view().into_any_element();
5016 let prompt_layout_id = element.request_layout(self, cx);
5017 self.layout_engine
5018 .as_mut()
5019 .unwrap()
5020 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
5021 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
5022 prompt_element = Some(element);
5023 self.prompt = Some(prompt);
5024 } else if let Some(active_drag) = cx.active_drag.take() {
5025 let mut element = active_drag.view.clone().into_any_element();
5026 let offset = self.mouse_position() - active_drag.cursor_offset;
5027 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
5028 active_drag_element = Some(element);
5029 cx.active_drag = Some(active_drag);
5030 } else {
5031 tooltip_element = self.prepaint_tooltip(cx);
5032 }
5033
5034 self.compute_hit_order(deferred_hitboxes);
5035 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position, self.scale_factor);
5036
5037 #[cfg(feature = "profiler")]
5039 let paint_start = Instant::now();
5040 self.invalidator.set_phase(DrawPhase::Paint);
5041 root_element.paint(self, cx);
5042
5043 #[cfg(any(feature = "inspector", debug_assertions))]
5044 self.paint_inspector(inspector_element, cx);
5045
5046 self.paint_deferred_draws(cx);
5047
5048 if let Some(mut prompt_element) = prompt_element {
5049 prompt_element.paint(self, cx);
5050 } else if let Some(mut drag_element) = active_drag_element {
5051 drag_element.paint(self, cx);
5052 } else if let Some(mut tooltip_element) = tooltip_element {
5053 tooltip_element.paint(self, cx);
5054 }
5055
5056 #[cfg(any(feature = "inspector", debug_assertions))]
5057 self.paint_inspector_hitbox(cx);
5058
5059 #[cfg(feature = "profiler")]
5060 self.window_profiler
5061 .record_draw_phases(profiler::DrawPhases {
5062 request_layout: prepaint_start.duration_since(request_layout_start),
5063 prepaint: paint_start.duration_since(prepaint_start),
5064 paint: Instant::now().duration_since(paint_start),
5065 });
5066
5067 let _profile = crate::native_profiling::current_span("native", "GPUI postpaint accessibility");
5068 let a11y_active_start_of_frame = self.a11y.is_active();
5070 self.a11y.sync_active_flag();
5071 let a11y_active_end_of_frame = self.a11y.is_active();
5072
5073 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
5074
5075 if a11y_active_start_of_frame {
5076 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
5079 viewport_size: self.viewport_size,
5080 scale_factor: self.scale_factor,
5081 tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
5082 };
5083 let tree_update = self.a11y.end_frame(frame_info);
5085
5086 if should_send_a11y_update {
5087 log::debug!(
5088 "Sending a11y tree update: {} nodes",
5089 tree_update.nodes.len()
5090 );
5091 self.platform_window.a11y_tree_update(tree_update);
5092 }
5093 }
5094 }
5095
5096 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
5097 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
5099 let Some(Some(tooltip_request)) = self
5100 .next_frame
5101 .tooltip_requests
5102 .get(tooltip_request_index)
5103 .cloned()
5104 else {
5105 log::error!("Unexpectedly absent TooltipRequest");
5106 continue;
5107 };
5108 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
5109 let mouse_position = tooltip_request.tooltip.mouse_position;
5110 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
5111
5112 let mut tooltip_bounds =
5113 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
5114 let window_bounds = Bounds {
5115 origin: Point::default(),
5116 size: self.viewport_size(),
5117 };
5118
5119 if tooltip_bounds.right() > window_bounds.right() {
5120 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
5121 if new_x >= Pixels::ZERO {
5122 tooltip_bounds.origin.x = new_x;
5123 } else {
5124 tooltip_bounds.origin.x = cmp::max(
5125 Pixels::ZERO,
5126 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
5127 );
5128 }
5129 }
5130
5131 if tooltip_bounds.bottom() > window_bounds.bottom() {
5132 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
5133 if new_y >= Pixels::ZERO {
5134 tooltip_bounds.origin.y = new_y;
5135 } else {
5136 tooltip_bounds.origin.y = cmp::max(
5137 Pixels::ZERO,
5138 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
5139 );
5140 }
5141 }
5142
5143 let is_visible =
5147 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
5148 if !is_visible {
5149 continue;
5150 }
5151
5152 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
5153 element.prepaint(window, cx)
5154 });
5155
5156 self.tooltip_bounds = Some(TooltipBounds {
5157 id: tooltip_request.id,
5158 bounds: tooltip_bounds,
5159 });
5160 return Some(element);
5161 }
5162 None
5163 }
5164
5165 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
5166 assert_eq!(self.element_id_stack.len(), 0);
5167
5168 let mut round_start = 0;
5179 let mut depth = 0;
5180 loop {
5181 let round_end = self.next_frame.deferred_draws.len();
5182 if round_start == round_end {
5183 break;
5184 }
5185 assert!(depth < 64, "Exceeded maximum (64) deferred depth");
5192 depth += 1;
5193
5194 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
5196 {
5197 let draws = &self.next_frame.deferred_draws;
5198 traversal_order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5199 }
5200
5201 for deferred_draw_ix in traversal_order {
5202 let (
5203 element,
5204 parent_node,
5205 current_view,
5206 rem_size,
5207 absolute_offset,
5208 element_transform,
5209 element_opacity,
5210 content_mask,
5211 vn_clip,
5212 vn_scope,
5213 prepaint_range,
5214 ) = {
5215 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
5216 self.element_id_stack
5217 .clone_from(&deferred_draw.element_id_stack);
5218 self.text_style_stack
5219 .clone_from(&deferred_draw.text_style_stack);
5220 (
5221 deferred_draw.element.take(),
5222 deferred_draw.parent_node,
5223 deferred_draw.current_view,
5224 deferred_draw.rem_size,
5225 deferred_draw.absolute_offset,
5226 deferred_draw.element_transform,
5227 deferred_draw.element_opacity,
5228 deferred_draw.content_mask,
5229 deferred_draw.vn_clip.clone(),
5230 deferred_draw.vn_scope.clone(),
5231 deferred_draw.prepaint_range.clone(),
5232 )
5233 };
5234 self.next_frame.dispatch_tree.set_active_node(parent_node);
5235 let a11y_parent = self.next_frame.deferred_draws[deferred_draw_ix]
5238 .a11y_parent
5239 .filter(|&p| p != a11y::ROOT_NODE_ID && self.a11y.is_active());
5240
5241 let prepaint_start = self.prepaint_index();
5242 if let Some(mut element) = element {
5243 if let Some(parent) = a11y_parent {
5244 self.a11y.nodes.begin_adopted(parent);
5245 }
5246 let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
5247 self.with_rendered_view(current_view, |window| {
5248 window.with_rem_size(Some(rem_size), |window| {
5249 window.with_content_mask(content_mask, |window| {
5251 window.vn_with_absolute_clip_stack(vn_clip, |window| {
5252 window.with_absolute_element_opacity(element_opacity, |window| {
5253 window.with_absolute_element_transform(element_transform, |window| {
5254 window.with_absolute_element_offset(absolute_offset, |window| {
5255 let outer = mem::replace(&mut window.vn_defer_scope, vn_scope);
5256 element.prepaint(window, cx);
5257 window.vn_defer_scope = outer;
5258 });
5259 });
5260 });
5261 });
5262 });
5263 });
5264 });
5265 });
5266 if a11y_parent.is_some() {
5267 self.a11y.nodes.end_adopted();
5268 }
5269 self.next_frame.deferred_draws[deferred_draw_ix].accessed_entities = accessed_entities;
5270 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
5271 } else {
5272 cx.entities.extend_accessed(
5273 self.next_frame.deferred_draws[deferred_draw_ix]
5274 .accessed_entities
5275 .iter()
5276 .copied(),
5277 );
5278 self.reuse_prepaint(prepaint_range);
5279 }
5280 let prepaint_end = self.prepaint_index();
5281 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
5282 prepaint_start..prepaint_end;
5283 }
5284
5285 self.element_id_stack.clear();
5286 self.text_style_stack.clear();
5287 round_start = round_end;
5288 }
5289 }
5290
5291 fn paint_deferred_draws(&mut self, cx: &mut App) {
5292 let _profile = crate::native_profiling::current_span("paint", "GPUI paint deferred draws");
5293 assert_eq!(self.element_id_stack.len(), 0);
5294
5295 if self.next_frame.deferred_draws.len() == 0 {
5298 return;
5299 }
5300
5301 let traversal_order = self.deferred_draw_traversal_order();
5304 for deferred_draw_ix in traversal_order {
5305 let draw = &self.next_frame.deferred_draws[deferred_draw_ix];
5306 if let Some(scope) = &draw.vn_scope
5308 && (self.vn_scopes_painted.contains(&scope.id) || draw.element.is_none())
5309 {
5310 continue;
5311 }
5312 self.vn_paint_deferred_draw(deferred_draw_ix, None, cx);
5313 }
5314 self.element_id_stack.clear();
5315 self.text_style_stack.clear();
5316 }
5317
5318 fn vn_paint_deferred_draw(
5322 &mut self,
5323 ix: usize,
5324 scope: Option<(f32, Option<Arc<crate::VnClipNode>>)>,
5325 cx: &mut App,
5326 ) {
5327 let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5328 self.element_id_stack
5329 .clone_from(&deferred_draw.element_id_stack);
5330 self.text_style_stack
5336 .clone_from(&deferred_draw.text_style_stack);
5337 self.next_frame
5338 .dispatch_tree
5339 .set_active_node(deferred_draw.parent_node);
5340
5341 let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5342 let content_mask = deferred_draw.content_mask;
5343 let element_transform = deferred_draw.element_transform;
5344 let (element_opacity, base) = match &scope {
5345 Some((opacity, base)) => (
5346 (deferred_draw.element_opacity / opacity).min(1.),
5347 base.as_ref(),
5348 ),
5349 None => (deferred_draw.element_opacity, None),
5350 };
5351 let vn_clip = deferred_draw.vn_clip.clone();
5352 let view = deferred_draw.current_view;
5353 let rem_size = deferred_draw.rem_size;
5354 let paint_range = deferred_draw.paint_range.clone();
5355 let mut element = deferred_draw.element.take();
5356
5357 let paint_start = self.paint_index();
5358 if let Some(element) = element.as_mut() {
5359 let ((), accessed_entities) = cx.detect_accessed_entities(|cx| {
5360 self.with_rendered_view(view, |window| {
5361 window.with_content_mask(content_mask, |window| {
5363 window.vn_reopen_clip_layers(vn_clip, base, cx, |window, cx| {
5364 window.with_absolute_element_opacity(element_opacity, |window| {
5365 window.with_absolute_element_transform(element_transform, |window| {
5366 window.with_rem_size(Some(rem_size), |window| {
5367 element.paint(window, cx);
5368 });
5369 });
5370 });
5371 });
5372 });
5373 });
5374 });
5375 self.next_frame.deferred_draws[ix]
5376 .accessed_entities
5377 .extend(accessed_entities);
5378 } else {
5379 self.reuse_paint(paint_range);
5380 }
5381 let paint_end = self.paint_index();
5382 let deferred_draw = &mut self.next_frame.deferred_draws[ix];
5383 deferred_draw.element = element;
5384 deferred_draw.paint_range = paint_start..paint_end;
5385 }
5386
5387 fn vn_paint_scope(&mut self, id: u64, opacity: f32, cx: &mut App) {
5391 if id == 0 || !self.vn_scopes_painted.insert(id) {
5392 return;
5393 }
5394 let mut order: SmallVec<[usize; 8]> = self
5395 .next_frame
5396 .deferred_draws
5397 .iter()
5398 .enumerate()
5399 .filter(|(_, draw)| draw.vn_scope.as_ref().is_some_and(|scope| scope.id == id))
5400 .map(|(ix, _)| ix)
5401 .collect();
5402 if order.is_empty() {
5403 return;
5404 }
5405 let draws = &self.next_frame.deferred_draws;
5406 order.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5407 let element_id_stack = self.element_id_stack.clone();
5408 let text_style_stack = self.text_style_stack.clone();
5409 let active_node = self.next_frame.dispatch_tree.active_node_id();
5410 for ix in order {
5411 let base = self.next_frame.deferred_draws[ix]
5412 .vn_scope
5413 .as_ref()
5414 .and_then(|scope| scope.clip.clone());
5415 self.vn_paint_deferred_draw(ix, Some((opacity, base)), cx);
5416 }
5417 self.element_id_stack = element_id_stack;
5418 self.text_style_stack = text_style_stack;
5419 if let Some(node) = active_node {
5420 self.next_frame.dispatch_tree.set_active_node(node);
5421 }
5422 }
5423
5424 pub fn vn_with_defer_scope<R>(&mut self, id: u64, f: impl FnOnce(&mut Self) -> R) -> R {
5427 if id == 0 {
5428 return f(self);
5429 }
5430 let scope = VnDeferScope {
5431 id,
5432 clip: self.vn_clip_stack.clone(),
5433 };
5434 let previous = self.vn_defer_scope.replace(scope);
5435 let result = f(self);
5436 self.vn_defer_scope = previous;
5437 result
5438 }
5439
5440 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
5441 let deferred_count = self.next_frame.deferred_draws.len();
5442 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
5443 let draws = &self.next_frame.deferred_draws;
5444 sorted_indices.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5445 sorted_indices
5446 }
5447
5448 fn compute_hit_order(&mut self, deferred_hitboxes: Range<usize>) {
5456 let frame = &mut self.next_frame;
5457 frame.vn_hit_order.clear();
5458 if deferred_hitboxes.is_empty() {
5459 return;
5460 }
5461 let mut order: Vec<u32> = Vec::with_capacity(frame.hitboxes.len());
5462 order.extend(0..deferred_hitboxes.start as u32);
5463 let mut traversal = (0..frame.deferred_draws.len()).collect::<Vec<_>>();
5464 let draws = &frame.deferred_draws;
5465 traversal.sort_by(|a, b| draws[*a].order().cmp(&draws[*b].order()));
5466 for ix in traversal {
5467 let range = &draws[ix].prepaint_range;
5468 let (start, end) = (range.start.hitboxes_index, range.end.hitboxes_index);
5469 if start >= deferred_hitboxes.start && end <= deferred_hitboxes.end && start < end {
5472 order.extend(start as u32..end as u32);
5473 }
5474 }
5475 order.extend(deferred_hitboxes.end as u32..frame.hitboxes.len() as u32);
5476 if order.len() != frame.hitboxes.len() {
5479 return;
5480 }
5481 frame.vn_hit_order = order;
5482 }
5483
5484 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
5485 PrepaintStateIndex {
5486 hitboxes_index: self.next_frame.hitboxes.len(),
5487 vn_tagged_hitboxes_index: self.next_frame.vn_tagged_hitboxes.len(),
5489 tooltips_index: self.next_frame.tooltip_requests.len(),
5490 deferred_draws_index: self.next_frame.deferred_draws.len(),
5491 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
5492 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
5493 line_layout_index: self.text_system.layout_index(),
5494 }
5495 }
5496
5497 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
5498 self.next_frame.hitboxes.extend(
5499 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
5500 .iter()
5501 .cloned(),
5502 );
5503 self.next_frame.vn_tagged_hitboxes.extend(
5509 self.rendered_frame.vn_tagged_hitboxes
5510 [range.start.vn_tagged_hitboxes_index..range.end.vn_tagged_hitboxes_index]
5511 .iter()
5512 .cloned(),
5513 );
5514 self.next_frame.tooltip_requests.extend(
5515 self.rendered_frame.tooltip_requests
5516 [range.start.tooltips_index..range.end.tooltips_index]
5517 .iter_mut()
5518 .map(|request| request.take()),
5519 );
5520 self.next_frame.accessed_element_states.extend(
5521 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
5522 ..range.end.accessed_element_states_index]
5523 .iter()
5524 .map(|(id, type_id)| (id.clone(), *type_id)),
5525 );
5526 self.text_system
5527 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
5528
5529 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
5530 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
5531 &mut self.rendered_frame.dispatch_tree,
5532 self.focus,
5533 );
5534
5535 if reused_subtree.contains_focus() {
5536 self.next_frame.focus = self.focus;
5537 }
5538
5539 self.next_frame.deferred_draws.extend(
5540 self.rendered_frame.deferred_draws
5541 [range.start.deferred_draws_index..range.end.deferred_draws_index]
5542 .iter()
5543 .map(|deferred_draw| DeferredDraw {
5544 current_view: deferred_draw.current_view,
5545 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
5546 element_id_stack: deferred_draw.element_id_stack.clone(),
5547 text_style_stack: deferred_draw.text_style_stack.clone(),
5548 content_mask: deferred_draw.content_mask,
5549 rem_size: deferred_draw.rem_size,
5550 priority: deferred_draw.priority,
5551 element: None,
5552 absolute_offset: deferred_draw.absolute_offset,
5553 element_transform: deferred_draw.element_transform,
5554 a11y_parent: deferred_draw.a11y_parent,
5555 vn_stack: deferred_draw.vn_stack.clone(),
5556 element_opacity: deferred_draw.element_opacity,
5557 vn_clip: deferred_draw.vn_clip.clone(),
5558 vn_scope: deferred_draw.vn_scope.clone(),
5559 prepaint_range: deferred_draw.prepaint_range.clone(),
5560 paint_range: deferred_draw.paint_range.clone(),
5561 accessed_entities: deferred_draw.accessed_entities.clone(),
5562 }),
5563 );
5564 }
5565
5566 pub(crate) fn paint_index(&self) -> PaintIndex {
5567 PaintIndex {
5568 scene_index: self.next_frame.scene.len(),
5569 #[cfg(any(test, feature = "test-support"))]
5570 debug_bounds_index: self.next_frame.debug_bounds_records.len(),
5571 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
5572 input_handlers_index: self.next_frame.input_handlers.len(),
5573 cursor_styles_index: self.next_frame.cursor_styles.len(),
5574 window_control_hitboxes_index: self.next_frame.window_control_hitboxes.len(),
5575 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
5576 tab_handle_index: self.next_frame.tab_stops.paint_index(),
5577 line_layout_index: self.text_system.layout_index(),
5578 }
5579 }
5580
5581 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
5582 #[cfg(any(test, feature = "test-support"))]
5584 for (selector, bounds) in &self.rendered_frame.debug_bounds_records
5585 [range.start.debug_bounds_index..range.end.debug_bounds_index]
5586 {
5587 self.next_frame
5588 .record_debug_bounds(selector.clone(), *bounds);
5589 }
5590 self.next_frame.window_control_hitboxes.extend(
5594 self.rendered_frame.window_control_hitboxes
5595 [range.start.window_control_hitboxes_index..range.end.window_control_hitboxes_index]
5596 .iter()
5597 .cloned(),
5598 );
5599 self.next_frame.cursor_styles.extend(
5600 self.rendered_frame.cursor_styles
5601 [range.start.cursor_styles_index..range.end.cursor_styles_index]
5602 .iter()
5603 .cloned(),
5604 );
5605 self.next_frame.input_handlers.extend(
5606 self.rendered_frame.input_handlers
5607 [range.start.input_handlers_index..range.end.input_handlers_index]
5608 .iter_mut()
5609 .map(|handler| handler.take()),
5610 );
5611 self.next_frame.mouse_listeners.extend(
5612 self.rendered_frame.mouse_listeners
5613 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
5614 .iter_mut()
5615 .map(|listener| listener.take()),
5616 );
5617 self.next_frame.accessed_element_states.extend(
5618 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
5619 ..range.end.accessed_element_states_index]
5620 .iter()
5621 .map(|(id, type_id)| (id.clone(), *type_id)),
5622 );
5623 self.next_frame.tab_stops.replay(
5624 &self.rendered_frame.tab_stops.insertion_history
5625 [range.start.tab_handle_index..range.end.tab_handle_index],
5626 );
5627
5628 self.text_system
5629 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
5630 self.next_frame.scene.replay(
5631 range.start.scene_index..range.end.scene_index,
5632 &self.rendered_frame.scene,
5633 );
5634 }
5635
5636 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
5640 where
5641 F: FnOnce(&mut Self) -> R,
5642 {
5643 self.invalidator.debug_assert_paint_or_prepaint();
5644 if let Some(style) = style {
5645 self.text_style_stack.push(style);
5646 let result = f(self);
5647 self.text_style_stack.pop();
5648 result
5649 } else {
5650 f(self)
5651 }
5652 }
5653
5654 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
5657 self.invalidator.debug_assert_paint();
5658 self.next_frame.cursor_styles.push(CursorStyleRequest {
5659 hitbox_id: Some(hitbox.id),
5660 style,
5661 });
5662 }
5663
5664 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
5669 self.invalidator.debug_assert_paint();
5670 self.next_frame.cursor_styles.push(CursorStyleRequest {
5671 hitbox_id: None,
5672 style,
5673 })
5674 }
5675
5676 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
5679 self.invalidator.debug_assert_prepaint();
5680 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
5681 self.next_frame
5682 .tooltip_requests
5683 .push(Some(TooltipRequest { id, tooltip }));
5684 id
5685 }
5686
5687 #[inline]
5692 pub fn with_content_mask<R>(
5693 &mut self,
5694 mask: Option<ContentMask<Pixels>>,
5695 f: impl FnOnce(&mut Self) -> R,
5696 ) -> R {
5697 self.invalidator.debug_assert_paint_or_prepaint();
5698 if let Some(mask) = mask {
5699 let mask = transform_mask(self.element_transform, mask, self.scale_factor);
5716 let mask = mask.intersect(&self.content_mask());
5717 self.content_mask_stack.push(mask);
5718 let result = f(self);
5719 self.content_mask_stack.pop();
5720 result
5721 } else {
5722 f(self)
5723 }
5724 }
5725
5726 pub fn vn_with_clip_shape<R>(
5735 &mut self,
5736 outline: Option<&crate::VnClipOutline>,
5737 f: impl FnOnce(&mut Self) -> R,
5738 ) -> R {
5739 let Some(outline) = outline else {
5740 return f(self);
5741 };
5742 let geometry = Arc::new(crate::VnClipGeometry::new(
5743 outline,
5744 self.scale_factor,
5745 self.element_transform,
5746 ));
5747 let node = Arc::new(crate::VnClipNode {
5748 geometry,
5749 color_matrix: None,
5750 capture: None,
5751 mask: None,
5752 parent: self.vn_clip_stack.clone(),
5753 });
5754 let previous = self.vn_clip_stack.replace(node.clone());
5755 let result = self.vn_with_clip_layer(&node, f);
5756 self.vn_clip_stack = previous;
5757 result
5758 }
5759
5760 pub fn vn_with_color_matrix<R>(
5763 &mut self,
5764 matrix: Option<crate::VnColorMatrix>,
5765 f: impl FnOnce(&mut Self) -> R,
5766 ) -> R {
5767 let Some(matrix) = matrix else { return f(self) };
5768 let bounds = self.snapped_content_mask().bounds;
5769 let left = bounds.origin.x.0;
5770 let top = bounds.origin.y.0;
5771 let right = left + bounds.size.width.0;
5772 let bottom = top + bounds.size.height.0;
5773 let geometry = Arc::new(crate::VnClipGeometry {
5774 fill_rule: crate::VnFillRule::NonZero,
5775 segments: vec![
5776 [left, top, right, top], [right, top, right, bottom],
5777 [right, bottom, left, bottom], [left, bottom, left, top],
5778 ],
5779 bounds,
5780 });
5781 let node = Arc::new(crate::VnClipNode {
5782 geometry,
5783 color_matrix: Some(matrix),
5784 capture: None,
5785 mask: None,
5786 parent: self.vn_clip_stack.clone(),
5787 });
5788 let previous = self.vn_clip_stack.replace(node.clone());
5789 let result = self.vn_with_clip_layer(&node, f);
5790 self.vn_clip_stack = previous;
5791 result
5792 }
5793
5794 pub fn vn_text_paint(&self, fill: crate::VnTextFill, bounds: Bounds<Pixels>) -> Arc<crate::VnTextPaint> {
5796 let x = bounds.origin.x.0; let y = bounds.origin.y.0;
5797 let right = x + bounds.size.width.0; let bottom = y + bounds.size.height.0;
5798 let outline = crate::VnClipOutline {
5799 fill_rule: crate::VnFillRule::NonZero,
5800 verbs: vec![crate::VnPathVerb::MoveTo([x,y]), crate::VnPathVerb::LineTo([right,y]),
5801 crate::VnPathVerb::LineTo([right,bottom]), crate::VnPathVerb::LineTo([x,bottom]), crate::VnPathVerb::Close],
5802 };
5803 let m = self.element_transform.inverse().unwrap_or_else(TransformationMatrix::unit);
5804 Arc::new(crate::VnTextPaint {
5805 fill, bounds: [x, y, bounds.size.width.0, bounds.size.height.0],
5806 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]],
5807 scale_factor: self.scale_factor,
5808 geometry: Arc::new(crate::VnClipGeometry::new(&outline, self.scale_factor, self.element_transform)),
5809 content_mask: self.snapped_content_mask(),
5810 })
5811 }
5812
5813 pub fn vn_with_text_mask<R>(&mut self, paint: Arc<crate::VnTextPaint>, f: impl FnOnce(&mut Self) -> R) -> R {
5816 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5817 geometry: paint.geometry.clone(), color_matrix: None,
5818 content_mask: paint.content_mask, text_paint: Some(paint), capture: None,
5819 });
5820 let result = f(self);
5821 self.next_frame.scene.vn_pop_isolation();
5822 result
5823 }
5824
5825 pub fn vn_with_mask<R>(
5831 &mut self,
5832 mask: Option<&crate::VnMask>,
5833 bounds: Bounds<Pixels>,
5834 cx: &mut App,
5835 f: impl FnOnce(&mut Self, &mut App) -> R,
5836 ) -> R {
5837 let Some(mask) = mask.filter(|mask| mask.paint.is_some()) else {
5838 return f(self, cx);
5839 };
5840 let node = Arc::new(crate::VnClipNode {
5841 geometry: self.vn_box_geometry(bounds),
5842 color_matrix: None,
5843 capture: None,
5844 mask: Some(crate::VnClipMask {
5845 mask: mask.clone(),
5846 bounds,
5847 transform: self.element_transform,
5848 }),
5849 parent: self.vn_clip_stack.clone(),
5850 });
5851 let previous = self.vn_clip_stack.replace(node.clone());
5852 let result = if self.invalidator.is_painting() {
5853 let content_mask = self.snapped_content_mask();
5854 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5855 geometry: node.geometry.clone(),
5856 color_matrix: None,
5857 text_paint: None,
5858 content_mask,
5859 capture: None,
5860 });
5861 let result = f(self, cx);
5862 self.vn_paint_mask(&node, cx);
5863 self.next_frame.scene.vn_pop_isolation();
5864 result
5865 } else {
5866 f(self, cx)
5867 };
5868 self.vn_clip_stack = previous;
5869 result
5870 }
5871
5872 fn vn_paint_mask(&mut self, node: &crate::VnClipNode, cx: &mut App) {
5874 let Some(clip) = &node.mask else { return };
5875 let Some(paint) = clip.mask.paint.clone() else { return };
5876 self.next_frame.scene.vn_begin_mask(clip.mask.luminance);
5877 let opacity = mem::replace(&mut self.element_opacity, 1.);
5880 let tint = mem::replace(&mut self.element_image_tint, Hsla::transparent_black());
5881 let transform = mem::replace(&mut self.element_transform, clip.transform);
5882 paint(clip.bounds, None, self, cx);
5883 self.element_opacity = opacity;
5884 self.element_image_tint = tint;
5885 self.element_transform = transform;
5886 }
5887
5888 fn vn_box_geometry(&self, bounds: Bounds<Pixels>) -> Arc<crate::VnClipGeometry> {
5890 let (x, y) = (bounds.origin.x.0, bounds.origin.y.0);
5891 let (right, bottom) = (x + bounds.size.width.0, y + bounds.size.height.0);
5892 let outline = crate::VnClipOutline {
5893 fill_rule: crate::VnFillRule::NonZero,
5894 verbs: vec![
5895 crate::VnPathVerb::MoveTo([x, y]),
5896 crate::VnPathVerb::LineTo([right, y]),
5897 crate::VnPathVerb::LineTo([right, bottom]),
5898 crate::VnPathVerb::LineTo([x, bottom]),
5899 crate::VnPathVerb::Close,
5900 ],
5901 };
5902 Arc::new(crate::VnClipGeometry::new(
5903 &outline,
5904 self.scale_factor,
5905 self.element_transform,
5906 ))
5907 }
5908
5909 fn vn_with_clip_layer<R>(
5912 &mut self,
5913 node: &Arc<crate::VnClipNode>,
5914 f: impl FnOnce(&mut Self) -> R,
5915 ) -> R {
5916 if !self.invalidator.is_painting() {
5917 return f(self);
5918 }
5919 let content_mask = self.snapped_content_mask();
5920 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5921 geometry: node.geometry.clone(),
5922 color_matrix: node.color_matrix,
5923 text_paint: None,
5924 content_mask,
5925 capture: node.capture,
5926 });
5927 let result = f(self);
5928 self.next_frame.scene.vn_pop_isolation();
5929 result
5930 }
5931
5932 fn vn_with_absolute_clip_stack<R>(
5935 &mut self,
5936 clip: Option<Arc<crate::VnClipNode>>,
5937 f: impl FnOnce(&mut Self) -> R,
5938 ) -> R {
5939 let previous = mem::replace(&mut self.vn_clip_stack, clip);
5940 let result = f(self);
5941 self.vn_clip_stack = previous;
5942 result
5943 }
5944
5945 fn vn_reopen_clip_layers<R>(
5951 &mut self,
5952 clip: Option<Arc<crate::VnClipNode>>,
5953 base: Option<&Arc<crate::VnClipNode>>,
5954 cx: &mut App,
5955 f: impl FnOnce(&mut Self, &mut App) -> R,
5956 ) -> R {
5957 let Some(innermost) = clip.clone() else {
5958 return self.vn_with_absolute_clip_stack(None, |window| f(window, cx));
5959 };
5960 let chain = crate::VnClipNode::inside_of(&innermost, base);
5961 self.vn_with_absolute_clip_stack(clip, |window| {
5962 for node in &chain {
5963 let content_mask = window.snapped_content_mask();
5964 window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
5965 geometry: node.geometry.clone(),
5966 color_matrix: node.color_matrix,
5967 text_paint: None,
5968 content_mask,
5969 capture: node.capture,
5970 });
5971 }
5972 let result = f(window, cx);
5973 for node in chain.iter().rev() {
5974 window.vn_paint_mask(node, cx);
5975 window.next_frame.scene.vn_pop_isolation();
5976 }
5977 result
5978 })
5979 }
5980
5981 pub fn vn_with_capture<R>(
5987 &mut self,
5988 id: Option<u64>,
5989 bounds: Bounds<Pixels>,
5990 own: TransformationMatrix,
5991 f: impl FnOnce(&mut Self) -> R,
5992 ) -> R {
5993 let Some(id) = id else { return f(self) };
5994 let scale_factor = self.scale_factor();
5995 let viewport = Bounds { origin: Point::default(), size: self.viewport_size };
5996 let device = viewport.scale(scale_factor);
5997 let info = crate::VnCaptureInfo {
5998 id,
5999 border_box: bounds.scale(scale_factor),
6000 transform: self.element_transform.compose(own),
6001 };
6002 let node = Arc::new(crate::VnClipNode {
6003 geometry: Arc::new(crate::VnClipGeometry::rect(device)),
6004 color_matrix: None,
6005 capture: Some(info),
6006 mask: None,
6007 parent: None,
6008 });
6009 let previous_clip = self.vn_clip_stack.replace(node.clone());
6010 self.content_mask_stack.push(ContentMask::rect(viewport));
6011 let result = self.with_absolute_element_transform(TransformationMatrix::unit(), |window| {
6012 window.with_absolute_element_opacity(1., |window| {
6013 if !window.invalidator.is_painting() {
6014 return f(window);
6015 }
6016 window.next_frame.scene.vn_push_isolation(crate::VnIsolation {
6017 geometry: node.geometry.clone(),
6018 color_matrix: None,
6019 text_paint: None,
6020 content_mask: ContentMask::rect(device),
6021 capture: Some(info),
6022 });
6023 let result = f(window);
6024 window.next_frame.scene.vn_pop_isolation();
6025 result
6026 })
6027 });
6028 self.content_mask_stack.pop();
6029 self.vn_clip_stack = previous_clip;
6030 result
6031 }
6032
6033 pub fn vn_with_isolation<R>(&mut self, isolate: bool, f: impl FnOnce(&mut Self) -> R) -> R {
6036 if !isolate || !self.invalidator.is_painting() {
6037 return f(self);
6038 }
6039 let device = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6040 let content_mask = self.snapped_content_mask();
6041 self.next_frame.scene.vn_push_isolation(crate::VnIsolation {
6042 geometry: Arc::new(crate::VnClipGeometry::rect(device)),
6043 color_matrix: None,
6044 text_paint: None,
6045 content_mask,
6046 capture: None,
6047 });
6048 let result = f(self);
6049 self.next_frame.scene.vn_pop_isolation();
6050 result
6051 }
6052
6053 pub fn vn_paint_snapshot(&mut self, id: u64, bounds: Bounds<Pixels>, plus_lighter: bool) {
6058 self.invalidator.debug_assert_paint();
6059 let scale_factor = self.scale_factor();
6060 let device = bounds.scale(scale_factor);
6061 if device.size.width.0 <= 0. || device.size.height.0 <= 0. {
6062 return;
6063 }
6064 let Some(inverse) = self.element_transform.inverse() else { return };
6065 let (w, h) = (device.size.width.0, device.size.height.0);
6066 let [[a, b], [c, d]] = inverse.rotation_scale;
6067 let [tx, ty] = inverse.translation;
6068 let (x, y) = (device.origin.x.0, device.origin.y.0);
6069 let to_unit = [a / w, b / w, (tx - x) / w, c / h, d / h, (ty - y) / h];
6070 let covered = crate::scene::transformed_bounds(device, self.element_transform);
6071 let covered = Bounds::from_corners(
6072 point(ScaledPixels(covered.origin.x.0.floor()), ScaledPixels(covered.origin.y.0.floor())),
6073 point(
6074 ScaledPixels((covered.origin.x.0 + covered.size.width.0).ceil()),
6075 ScaledPixels((covered.origin.y.0 + covered.size.height.0).ceil()),
6076 ),
6077 );
6078 let opacity = self.element_opacity;
6079 let content_mask = self.snapped_content_mask();
6080 self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
6081 id,
6082 to_unit,
6083 bounds: covered,
6084 content_mask,
6085 opacity,
6086 plus_lighter,
6087 in_place: false,
6088 });
6089 }
6090
6091 pub fn vn_paint_snapshot_in_place(&mut self, id: u64) {
6094 self.invalidator.debug_assert_paint();
6095 let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6096 let opacity = self.element_opacity;
6097 let content_mask = self.snapped_content_mask();
6098 self.next_frame.scene.vn_insert_snapshot(crate::VnSnapshotPaint {
6099 id,
6100 to_unit: [0.; 6],
6101 bounds: viewport,
6102 content_mask,
6103 opacity,
6104 plus_lighter: false,
6105 in_place: true,
6106 });
6107 }
6108
6109 pub fn vn_capture(&self, id: u64) -> Option<crate::VnCaptureInfo> {
6112 self.vn_capture_records.get(&id).map(|(info, _)| *info)
6113 }
6114
6115 pub fn vn_forget_captures(&mut self, ids: &[u64]) {
6118 for id in ids {
6119 self.vn_capture_records.remove(id);
6120 }
6121 }
6122
6123 pub fn vn_supports_snapshots(&self) -> bool {
6126 self.platform_window.vn_supports_snapshots()
6127 }
6128
6129 fn vn_settle_captures(&mut self) {
6130 let viewport = Bounds { origin: Point::default(), size: self.viewport_size }.scale(self.scale_factor());
6131 let scene = &mut self.next_frame.scene;
6132 for capture in &mut scene.vn_captures {
6133 capture.ink = capture.ink.intersect(&viewport);
6134 self.vn_capture_records.insert(capture.info.id, (capture.info, capture.ink));
6135 }
6136 let records = &self.vn_capture_records;
6137 scene.vn_resolve_snapshots(|id| records.get(&id).copied());
6138 }
6139
6140 pub fn with_element_offset<R>(
6143 &mut self,
6144 offset: Point<Pixels>,
6145 f: impl FnOnce(&mut Self) -> R,
6146 ) -> R {
6147 self.invalidator.debug_assert_prepaint();
6148
6149 if offset.is_zero() {
6150 return f(self);
6151 };
6152
6153 let abs_offset = self.element_offset() + offset;
6154 self.with_absolute_element_offset(abs_offset, f)
6155 }
6156
6157 pub fn with_absolute_element_offset<R>(
6161 &mut self,
6162 offset: Point<Pixels>,
6163 f: impl FnOnce(&mut Self) -> R,
6164 ) -> R {
6165 self.invalidator.debug_assert_prepaint();
6166 self.element_offset_stack.push(offset);
6167 let result = f(self);
6168 self.element_offset_stack.pop();
6169 result
6170 }
6171
6172 pub(crate) fn with_element_opacity<R>(
6173 &mut self,
6174 opacity: Option<f32>,
6175 f: impl FnOnce(&mut Self) -> R,
6176 ) -> R {
6177 self.invalidator.debug_assert_paint_or_prepaint();
6178
6179 let Some(opacity) = opacity else {
6180 return f(self);
6181 };
6182
6183 let previous_opacity = self.element_opacity;
6184 self.element_opacity = previous_opacity * opacity;
6185 let result = f(self);
6186 self.element_opacity = previous_opacity;
6187 result
6188 }
6189
6190 pub fn with_image_tint<R>(&mut self, tint: Hsla, f: impl FnOnce(&mut Self) -> R) -> R {
6201 self.invalidator.debug_assert_paint_or_prepaint();
6202 let previous = std::mem::replace(&mut self.element_image_tint, tint);
6203 let result = f(self);
6204 self.element_image_tint = previous;
6205 result
6206 }
6207
6208 pub fn with_absolute_element_transform<R>(
6231 &mut self,
6232 transformation: TransformationMatrix,
6233 f: impl FnOnce(&mut Self) -> R,
6234 ) -> R {
6235 let previous = mem::replace(&mut self.element_transform, transformation);
6236 let result = f(self);
6237 self.element_transform = previous;
6238 result
6239 }
6240
6241 fn with_absolute_element_opacity<R>(
6244 &mut self,
6245 opacity: f32,
6246 f: impl FnOnce(&mut Self) -> R,
6247 ) -> R {
6248 let previous = mem::replace(&mut self.element_opacity, opacity);
6249 let result = f(self);
6250 self.element_opacity = previous;
6251 result
6252 }
6253
6254 pub fn with_element_transform<R>(
6258 &mut self,
6259 transformation: TransformationMatrix,
6260 f: impl FnOnce(&mut Self) -> R,
6261 ) -> R {
6262 if transformation.is_unit() {
6263 return f(self);
6264 }
6265 let previous = self.element_transform;
6266 self.element_transform = previous.compose(transformation);
6269 let result = f(self);
6270 self.element_transform = previous;
6271 result
6272 }
6273
6274 pub fn content_mask_in_element_space(&self) -> ContentMask<Pixels> {
6286 let mask = self.content_mask();
6287 if self.element_transform.is_unit() {
6288 return mask;
6289 }
6290 match self.element_transform.inverse() {
6291 Some(inverse) => transform_mask(inverse, mask, self.scale_factor),
6292 None => ContentMask::rect(Bounds::default()),
6293 }
6294 }
6295
6296 #[inline]
6299 pub fn element_transform(&self) -> TransformationMatrix {
6300 self.element_transform
6301 }
6302
6303 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
6309 self.invalidator.debug_assert_prepaint();
6310 let index = self.prepaint_index();
6311 let result = f(self);
6312 if result.is_err() {
6313 self.next_frame.hitboxes.truncate(index.hitboxes_index);
6314 self.next_frame
6317 .vn_tagged_hitboxes
6318 .truncate(index.vn_tagged_hitboxes_index);
6319 self.next_frame
6320 .tooltip_requests
6321 .truncate(index.tooltips_index);
6322 self.next_frame
6323 .deferred_draws
6324 .truncate(index.deferred_draws_index);
6325 self.next_frame
6326 .dispatch_tree
6327 .truncate(index.dispatch_tree_index);
6328 self.next_frame
6329 .accessed_element_states
6330 .truncate(index.accessed_element_states_index);
6331 self.text_system.truncate_layouts(index.line_layout_index);
6332 }
6333 result
6334 }
6335
6336 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
6342 self.invalidator.debug_assert_prepaint();
6343 self.requested_autoscroll = Some(bounds);
6344 }
6345
6346 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
6349 self.invalidator.debug_assert_prepaint();
6350 self.requested_autoscroll.take()
6351 }
6352
6353 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
6359 cx.asset_entry::<A>(source).use_by(self.current_view())
6360 }
6361
6362 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
6368 cx.fetch_asset::<A>(source)
6369 }
6370 pub fn element_offset(&self) -> Point<Pixels> {
6373 self.invalidator.debug_assert_prepaint();
6374 self.element_offset_stack
6375 .last()
6376 .copied()
6377 .unwrap_or_default()
6378 }
6379
6380 #[inline]
6383 pub(crate) fn element_opacity(&self) -> f32 {
6384 self.invalidator.debug_assert_paint_or_prepaint();
6385 self.element_opacity
6386 }
6387
6388 pub fn content_mask(&self) -> ContentMask<Pixels> {
6390 self.invalidator.debug_assert_paint_or_prepaint();
6391 self.content_mask_stack
6392 .last()
6393 .cloned()
6394 .unwrap_or_else(|| {
6395 ContentMask::rect(Bounds {
6396 origin: Point::default(),
6397 size: self.viewport_size,
6398 })
6399 })
6400 }
6401
6402 pub fn with_element_namespace<R>(
6405 &mut self,
6406 element_id: impl Into<ElementId>,
6407 f: impl FnOnce(&mut Self) -> R,
6408 ) -> R {
6409 self.element_id_stack.push(element_id.into());
6410 let result = f(self);
6411 self.element_id_stack.pop();
6412 result
6413 }
6414
6415 pub fn use_keyed_state<S: 'static>(
6417 &mut self,
6418 key: impl Into<ElementId>,
6419 cx: &mut App,
6420 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
6421 ) -> Entity<S> {
6422 let current_view = self.current_view();
6423 self.with_global_id(key.into(), |global_id, window| {
6424 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
6425 if let Some(state) = state {
6426 (state.clone(), state)
6427 } else {
6428 let new_state = cx.new(|cx| init(window, cx));
6429 Self::observe_keyed_state(&new_state, current_view, cx);
6430 (new_state.clone(), new_state)
6431 }
6432 })
6433 })
6434 }
6435
6436 #[track_caller]
6442 pub fn use_state<S: 'static>(
6443 &mut self,
6444 cx: &mut App,
6445 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
6446 ) -> Entity<S> {
6447 self.use_keyed_state(
6448 ElementId::CodeLocation(*core::panic::Location::caller()),
6449 cx,
6450 init,
6451 )
6452 }
6453
6454 #[inline(always)]
6459 pub fn with_element_state<S, R>(
6460 &mut self,
6461 global_id: &GlobalElementId,
6462 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
6463 ) -> R
6464 where
6465 S: 'static,
6466 {
6467 self.invalidator.debug_assert_paint_or_prepaint();
6468
6469 let (key, state) = self.take_element_state(global_id, TypeId::of::<S>());
6470
6471 if let Some(any) = state {
6472 let ElementStateBox {
6473 inner,
6474 #[cfg(debug_assertions)]
6475 type_name,
6476 } = any;
6477 let mut state_box = inner
6479 .downcast::<Option<S>>()
6480 .map_err(|_| {
6481 #[cfg(debug_assertions)]
6482 {
6483 anyhow::anyhow!(
6484 "invalid element state type for id, requested {:?}, actual: {:?}",
6485 std::any::type_name::<S>(),
6486 type_name
6487 )
6488 }
6489
6490 #[cfg(not(debug_assertions))]
6491 {
6492 anyhow::anyhow!(
6493 "invalid element state type for id, requested {:?}",
6494 std::any::type_name::<S>(),
6495 )
6496 }
6497 })
6498 .unwrap();
6499
6500 let state = state_box.take().expect(
6501 "reentrant call to with_element_state for the same state type and element id",
6502 );
6503 let (result, state) = f(Some(state), self);
6504 state_box.replace(state);
6505 self.insert_element_state(
6506 key,
6507 ElementStateBox {
6508 inner: state_box,
6509 #[cfg(debug_assertions)]
6510 type_name,
6511 },
6512 );
6513 result
6514 } else {
6515 let (result, state) = f(None, self);
6516 self.insert_element_state(
6517 key,
6518 ElementStateBox {
6519 inner: Box::new(Some(state)),
6520 #[cfg(debug_assertions)]
6521 type_name: std::any::type_name::<S>(),
6522 },
6523 );
6524 result
6525 }
6526 }
6527
6528 pub fn with_optional_element_state<S, R>(
6535 &mut self,
6536 global_id: Option<&GlobalElementId>,
6537 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
6538 ) -> R
6539 where
6540 S: 'static,
6541 {
6542 self.invalidator.debug_assert_paint_or_prepaint();
6543
6544 if let Some(global_id) = global_id {
6545 self.with_element_state(global_id, |state, cx| {
6546 let (result, state) = f(Some(state), cx);
6547 let state =
6548 state.expect("you must return some state when you pass some element id");
6549 (result, state)
6550 })
6551 } else {
6552 let (result, state) = f(None, self);
6553 debug_assert!(
6554 state.is_none(),
6555 "you must not return an element state when passing None for the global id"
6556 );
6557 result
6558 }
6559 }
6560
6561 #[inline]
6563 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
6564 if let Some(index) = index {
6565 self.next_frame.tab_stops.begin_group(index);
6566 let result = f(self);
6567 self.next_frame.tab_stops.end_group();
6568 result
6569 } else {
6570 f(self)
6571 }
6572 }
6573
6574 pub fn defer_draw(
6583 &mut self,
6584 element: AnyElement,
6585 absolute_offset: Point<Pixels>,
6586 priority: usize,
6587 content_mask: Option<ContentMask<Pixels>>,
6588 ) {
6589 self.defer_draw_with_stack_key(element, absolute_offset, priority, content_mask, None)
6590 }
6591
6592 pub fn defer_draw_with_stack_key(
6595 &mut self,
6596 element: AnyElement,
6597 absolute_offset: Point<Pixels>,
6598 priority: usize,
6599 content_mask: Option<ContentMask<Pixels>>,
6600 stack_key: Option<Rc<[u128]>>,
6601 ) {
6602 self.invalidator.debug_assert_prepaint();
6603 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
6604 self.next_frame.deferred_draws.push(DeferredDraw {
6605 current_view: self.current_view(),
6606 parent_node,
6607 element_id_stack: self.element_id_stack.clone(),
6608 text_style_stack: self.text_style_stack.clone(),
6609 content_mask,
6610 rem_size: self.rem_size(),
6611 priority,
6612 element: Some(element),
6613 absolute_offset,
6614 element_transform: self.element_transform,
6615 a11y_parent: self
6616 .a11y
6617 .is_active()
6618 .then(|| self.a11y.nodes.current_id()),
6619 vn_stack: stack_key,
6620 element_opacity: self.element_opacity,
6621 vn_clip: if content_mask.is_some() {
6622 self.vn_clip_stack.clone()
6623 } else {
6624 crate::VnClipNode::color_filters(&self.vn_clip_stack)
6625 },
6626 vn_scope: self.vn_defer_scope.clone(),
6627 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
6628 paint_range: PaintIndex::default()..PaintIndex::default(),
6629 accessed_entities: FxHashSet::default(),
6630 });
6631 }
6632
6633 pub fn paint_layer<R>(&mut self, f: impl FnOnce(&mut Self) -> R) -> R {
6642 self.invalidator.debug_assert_paint();
6643
6644 self.next_frame.scene.push_layer();
6645 let result = f(self);
6646 self.next_frame.scene.pop_layer();
6647 result
6648 }
6649
6650 pub fn paint_drop_shadows(
6661 &mut self,
6662 bounds: Bounds<Pixels>,
6663 corner_radii: Corners<Pixels>,
6664 shadows: &[BoxShadow],
6665 ) {
6666 self.paint_outer_shadows(bounds, corner_radii, Corners::default(), shadows, SHADOW_OUTSIDE_BOX);
6667 }
6668
6669 pub fn paint_drop_shadows_under_box(
6673 &mut self,
6674 bounds: Bounds<Pixels>,
6675 corner_radii: Corners<Pixels>,
6676 shadows: &[BoxShadow],
6677 ) {
6678 self.paint_outer_shadows(bounds, corner_radii, Corners::default(), shadows, SHADOW_UNDER_BOX);
6679 }
6680
6681 pub fn vn_paint_drop_shadows(
6684 &mut self,
6685 bounds: Bounds<Pixels>,
6686 corner_radii: Corners<Pixels>,
6687 corner_shapes: Corners<CornerShape>,
6688 shadows: &[BoxShadow],
6689 under_box: bool,
6690 ) {
6691 let kind = if under_box { SHADOW_UNDER_BOX } else { SHADOW_OUTSIDE_BOX };
6692 self.paint_outer_shadows(bounds, corner_radii, corner_shapes, shadows, kind);
6693 }
6694
6695 fn paint_outer_shadows(
6696 &mut self,
6697 bounds: Bounds<Pixels>,
6698 corner_radii: Corners<Pixels>,
6699 corner_shapes: Corners<CornerShape>,
6700 shadows: &[BoxShadow],
6701 kind: u32,
6702 ) {
6703 self.invalidator.debug_assert_paint();
6704
6705 let scale_factor = self.scale_factor();
6706 let content_mask = self.snapped_content_mask();
6707 let opacity = self.element_opacity();
6708 let element_bounds = self.cover_bounds(bounds);
6709 let element_corner_radii = corner_radii.scale(scale_factor);
6710 for shadow in shadows {
6711 if shadow.inset {
6712 continue;
6713 }
6714 let shape_bounds =
6715 self.cover_bounds((bounds + shadow.offset).dilate(shadow.spread_radius));
6716 if shape_bounds.is_empty() {
6717 continue;
6718 }
6719 let blur_radius = shadow.blur_radius.scale(scale_factor);
6720 let spread = shadow.spread_radius;
6721 let shadow_radius = |r: Pixels| spread_shadow_radius(r, spread);
6722 let shadow_corner_radii = Corners {
6723 top_left: shadow_radius(corner_radii.top_left),
6724 top_right: shadow_radius(corner_radii.top_right),
6725 bottom_right: shadow_radius(corner_radii.bottom_right),
6726 bottom_left: shadow_radius(corner_radii.bottom_left),
6727 };
6728 self.next_frame.scene.insert_primitive(Shadow {
6729 order: 0,
6730 blur_radius,
6731 bounds: shape_bounds.dilate(blur_radius * 3.),
6733 content_mask,
6734 corner_radii: element_corner_radii,
6735 color: shadow.color.opacity(opacity),
6736 shape_bounds,
6737 shape_corner_radii: shadow_corner_radii.scale(scale_factor),
6738 inset: kind,
6739 pad: 0,
6740 transformation: self.element_transform,
6741 element_bounds,
6742 corner_shapes: CornerShapes::new(&corner_shapes),
6743 });
6744 }
6745 }
6746
6747 pub fn paint_inset_shadows(
6751 &mut self,
6752 bounds: Bounds<Pixels>,
6753 corner_radii: Corners<Pixels>,
6754 shadows: &[BoxShadow],
6755 ) {
6756 self.vn_paint_inset_shadows(bounds, corner_radii, Corners::default(), shadows);
6757 }
6758
6759 pub fn vn_paint_inset_shadows(
6763 &mut self,
6764 bounds: Bounds<Pixels>,
6765 corner_radii: Corners<Pixels>,
6766 corner_shapes: Corners<CornerShape>,
6767 shadows: &[BoxShadow],
6768 ) {
6769 self.invalidator.debug_assert_paint();
6770
6771 let scale_factor = self.scale_factor();
6772 let content_mask = self.snapped_content_mask();
6773 let opacity = self.element_opacity();
6774 let element_bounds = self.cover_bounds(bounds);
6775 let element_corner_radii = corner_radii.scale(scale_factor);
6776 for shadow in shadows {
6777 if !shadow.inset {
6778 continue;
6779 }
6780 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
6781 let zero = Pixels::ZERO;
6784 let spread = shadow.spread_radius;
6785 let hole_radius = |radius: Pixels, shape: CornerShape| {
6786 if shape.is_round() || spread <= zero { (radius - spread).max(zero) } else { radius }
6787 };
6788 let hole_corner_radii = Corners {
6789 top_left: hole_radius(corner_radii.top_left, corner_shapes.top_left),
6790 top_right: hole_radius(corner_radii.top_right, corner_shapes.top_right),
6791 bottom_right: hole_radius(corner_radii.bottom_right, corner_shapes.bottom_right),
6792 bottom_left: hole_radius(corner_radii.bottom_left, corner_shapes.bottom_left),
6793 };
6794 let inset = f32::from(spread.max(zero)) * scale_factor;
6795 self.next_frame.scene.insert_primitive(Shadow {
6796 order: 0,
6797 blur_radius: shadow.blur_radius.scale(scale_factor),
6798 bounds: element_bounds,
6799 content_mask,
6800 corner_radii: element_corner_radii,
6801 color: shadow.color.opacity(opacity),
6802 shape_bounds: self.cover_bounds(hole),
6803 shape_corner_radii: hole_corner_radii.scale(scale_factor),
6804 inset: SHADOW_INSET,
6805 pad: 0,
6806 transformation: self.element_transform,
6807 element_bounds,
6808 corner_shapes: CornerShapes::new(&corner_shapes)
6809 .with_insets(Corners {
6810 top_left: (inset, inset),
6811 top_right: (inset, inset),
6812 bottom_right: (inset, inset),
6813 bottom_left: (inset, inset),
6814 }),
6815 });
6816 }
6817 }
6818
6819 fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
6820 let size = quad.bounds.size;
6821 let diagonal = (size.width.0 * size.width.0 + size.height.0 * size.height.0).sqrt();
6822 if diagonal == 0. {
6823 return Bounds::default();
6824 }
6825 let cos = size.height.0 / diagonal;
6829 let sin = size.width.0 / diagonal;
6830
6831 let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| {
6834 point(
6835 width_x.max(radius - (radius - width_x) * cos),
6836 width_y.max(radius - (radius - width_y) * sin),
6837 )
6838 };
6839
6840 let radii = &quad.corner_radii;
6841 let widths = &quad.border_widths;
6842 let top_left = corner_inset(radii.top_left, widths.left, widths.top);
6843 let top_right = corner_inset(radii.top_right, widths.right, widths.top);
6844 let bottom_right = corner_inset(radii.bottom_right, widths.right, widths.bottom);
6845 let bottom_left = corner_inset(radii.bottom_left, widths.left, widths.bottom);
6846
6847 let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
6848 Bounds::from_corners(
6849 quad.bounds.origin
6850 + point(top_left.x.max(bottom_left.x), top_left.y.max(top_right.y))
6851 + antialias_inset,
6852 quad.bounds.bottom_right()
6853 - point(
6854 top_right.x.max(bottom_right.x),
6855 bottom_left.y.max(bottom_right.y),
6856 )
6857 - antialias_inset,
6858 )
6859 }
6860
6861 pub fn paint_quad(&mut self, quad: PaintQuad) {
6871 self.invalidator.debug_assert_paint();
6872
6873 let opacity = self.element_opacity();
6874 let snapped_bounds = self.snap_bounds(quad.bounds);
6875 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
6876 let quad = Quad {
6877 order: 0,
6878 bounds: snapped_bounds,
6879 content_mask: self.snapped_content_mask(),
6880 background: quad.background.opacity(opacity),
6881 border_color: quad.border_color.opacity(opacity),
6882 corner_radii: quad.corner_radii.scale(self.scale_factor()),
6883 border_widths: snapped_border_widths,
6884 border_style: quad.border_style,
6885 transformation: self.element_transform,
6886 corner_shapes: CornerShapes::new(&quad.corner_shapes),
6887 };
6888 self.insert_quad(quad);
6889 }
6890
6891 fn insert_quad(&mut self, quad: Quad) {
6892 let has_background = !quad.background.is_transparent();
6893 let has_border =
6894 quad.border_widths != Edges::default() && !quad.border_color.is_transparent();
6895 if !has_background && !has_border {
6896 return;
6897 }
6898
6899 let is_rectangle =
6900 quad.border_widths == Edges::default() && quad.corner_radii == Corners::default();
6901 if has_background && is_rectangle {
6902 self.next_frame.scene.insert_primitive(quad);
6903 return;
6904 }
6905
6906 if !quad.transformation.is_unit()
6914 || quad.content_mask.is_rounded()
6915 || !quad.corner_shapes.is_round()
6916 {
6917 self.next_frame.scene.insert_primitive(quad);
6918 return;
6919 }
6920
6921 let plain_border = quad.corner_radii == Corners::default()
6922 && quad.border_style == BorderStyle::Solid
6923 && (!has_background || quad.border_color.is_opaque());
6924
6925 let outer_bounds = quad.bounds;
6928 let inner_bounds = if plain_border {
6929 quad.bounds.extend(quad.border_widths.map(|width| -*width))
6930 } else {
6931 Self::largest_border_interior(&quad)
6932 };
6933
6934 let strip_quad = if plain_border {
6938 Quad {
6939 background: quad.border_color.into(),
6940 border_widths: Edges::default(),
6941 ..quad
6942 }
6943 } else {
6944 quad
6945 };
6946
6947 if inner_bounds.is_empty() {
6948 self.next_frame.scene.insert_primitive(strip_quad);
6949 return;
6950 }
6951
6952 if has_background && !quad.background.is_ring() {
6954 self.next_frame.scene.insert_primitive(Quad {
6955 content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&inner_bounds)),
6956 border_widths: Edges::default(),
6957 corner_radii: Corners::default(),
6958 ..quad
6959 });
6960 }
6961
6962 let strips = [
6963 Bounds::from_corners(
6965 outer_bounds.origin,
6966 point(outer_bounds.right(), inner_bounds.top()),
6967 ),
6968 Bounds::from_corners(
6970 point(outer_bounds.left(), inner_bounds.bottom()),
6971 outer_bounds.bottom_right(),
6972 ),
6973 Bounds::from_corners(
6975 point(outer_bounds.left(), inner_bounds.top()),
6976 inner_bounds.bottom_left(),
6977 ),
6978 Bounds::from_corners(
6980 inner_bounds.top_right(),
6981 point(outer_bounds.right(), inner_bounds.bottom()),
6982 ),
6983 ];
6984
6985 for strip in strips {
6986 self.next_frame.scene.insert_primitive(Quad {
6987 content_mask: ContentMask::rect(quad.content_mask.bounds.intersect(&strip)),
6988 ..strip_quad
6989 });
6990 }
6991 }
6992
6993 pub fn paint_backdrop_blur_rect(
7008 &mut self,
7009 bounds: Bounds<Pixels>,
7010 corner_radii: Corners<Pixels>,
7011 effect: BackdropBlurEffect,
7012 ) {
7013 self.vn_paint_backdrop_blur_rect(bounds, corner_radii, Corners::default(), effect);
7014 }
7015
7016 pub fn vn_paint_backdrop_blur_rect(
7018 &mut self,
7019 bounds: Bounds<Pixels>,
7020 corner_radii: Corners<Pixels>,
7021 corner_shapes: Corners<CornerShape>,
7022 effect: BackdropBlurEffect,
7023 ) {
7024 self.invalidator.debug_assert_paint();
7025
7026 let opacity = self.element_opacity();
7027 if opacity <= 0. {
7028 return;
7029 }
7030
7031 let scale_factor = self.scale_factor();
7032 let blur_radius = effect.radius.scale(scale_factor);
7033 if blur_radius.0 <= 0. {
7034 let tint = effect.tint.opacity(opacity);
7035 if tint.a > 0. {
7036 self.paint_quad(
7037 fill(bounds, tint).corner_radii(corner_radii).corner_shapes(corner_shapes),
7038 );
7039 }
7040 return;
7041 }
7042
7043 let Some((bounds, k)) =
7049 crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
7050 else {
7051 return;
7052 };
7053 self.next_frame.scene.insert_primitive(BackdropBlurRect {
7054 order: 0,
7055 pad: 0,
7056 bounds,
7057 content_mask: self.snapped_content_mask(),
7058 corner_radii: corner_radii.scale(scale_factor * k),
7059 blur_radius,
7060 opacity,
7061 tint: effect.tint,
7062 corner_shapes: CornerShapes::new(&corner_shapes),
7063 });
7064 }
7065
7066 pub fn paint_effect_quad(
7087 &mut self,
7088 bounds: Bounds<Pixels>,
7089 corner_radii: Corners<Pixels>,
7090 spec: EffectSpec,
7091 ) {
7092 self.vn_paint_effect(bounds, corner_radii, spec, 0);
7093 }
7094
7095 pub fn vn_paint_effect(
7098 &mut self,
7099 bounds: Bounds<Pixels>,
7100 corner_radii: Corners<Pixels>,
7101 spec: EffectSpec,
7102 element: u64,
7103 ) {
7104 self.vn_paint_effect_with(bounds, corner_radii, Corners::default(), spec, element, None);
7105 }
7106
7107 pub fn vn_paint_textured_effect(
7110 &mut self,
7111 bounds: Bounds<Pixels>,
7112 corner_radii: Corners<Pixels>,
7113 corner_shapes: Corners<CornerShape>,
7114 spec: EffectSpec,
7115 element: u64,
7116 cx: &mut App,
7117 ) {
7118 let textures = crate::resolve_effect_textures(&spec, self, cx);
7119 self.vn_paint_effect_with(bounds, corner_radii, corner_shapes, spec, element, textures);
7120 }
7121
7122 fn vn_paint_effect_with(
7123 &mut self,
7124 bounds: Bounds<Pixels>,
7125 corner_radii: Corners<Pixels>,
7126 corner_shapes: Corners<CornerShape>,
7127 spec: EffectSpec,
7128 element: u64,
7129 textures: Option<Arc<crate::EffectTextureSet>>,
7130 ) {
7131 self.invalidator.debug_assert_paint();
7132 let opacity = self.element_opacity();
7133 let Some(mut quad) =
7134 self.vn_effect_quad(bounds, corner_radii, corner_shapes, spec, element, opacity, textures.as_deref())
7135 else {
7136 return;
7137 };
7138 quad.flags &= !crate::EFFECT_FLAG_NEEDS_CONTENT;
7139 let history = vn_history_key(element, &spec);
7140 if history == 0 {
7141 quad.flags &= !crate::EFFECT_FLAG_HISTORY;
7142 self.next_frame
7143 .scene
7144 .insert_primitive(crate::Primitive::EffectQuad(quad, textures));
7145 return;
7146 }
7147 let content_mask = quad.content_mask;
7148 self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
7149 draws: vec![crate::VnEffectDraw {
7150 quad,
7151 history,
7152 textures,
7153 }],
7154 content: false,
7155 content_mask,
7156 });
7157 self.next_frame.scene.vn_pop_isolation();
7158 }
7159
7160 pub fn vn_set_effect_element(&mut self, id: Option<&GlobalElementId>) {
7163 self.vn_effect_element = vn_element_key(id);
7164 }
7165
7166 pub fn vn_take_effect_element(&mut self) -> u64 {
7169 mem::take(&mut self.vn_effect_element)
7170 }
7171
7172 #[allow(clippy::too_many_arguments)]
7176 pub fn vn_with_effect_content<R>(
7177 &mut self,
7178 bounds: Bounds<Pixels>,
7179 corner_radii: Corners<Pixels>,
7180 corner_shapes: Corners<CornerShape>,
7181 effects: &[(EffectSpec, f32, Option<Arc<crate::EffectTextureSet>>)],
7182 element: u64,
7183 cx: &mut App,
7184 f: impl FnOnce(&mut Self, &mut App) -> R,
7185 ) -> R {
7186 let opacity = self.element_opacity();
7187 if !self.invalidator.is_painting() || opacity <= 0. {
7188 return f(self, cx);
7189 }
7190 let mut draws = Vec::new();
7191 let mut plain = 1.;
7192 for (spec, weight, textures) in effects {
7193 if spec.flags & crate::EFFECT_FLAG_NEEDS_CONTENT == 0 || *weight <= 0. {
7194 continue;
7195 }
7196 let Some(mut quad) = self.vn_effect_quad(
7197 bounds,
7198 corner_radii,
7199 corner_shapes,
7200 *spec,
7201 element,
7202 opacity * weight,
7203 textures.as_deref(),
7204 ) else {
7205 continue;
7206 };
7207 let history = vn_history_key(element, spec);
7208 if history == 0 {
7209 quad.flags &= !crate::EFFECT_FLAG_HISTORY;
7210 }
7211 plain -= weight;
7212 draws.push(crate::VnEffectDraw {
7213 quad,
7214 history,
7215 textures: textures.clone(),
7216 });
7217 }
7218 let content_mask = self.snapped_content_mask();
7219 if plain > 1e-3 {
7220 draws.insert(
7221 0,
7222 crate::VnEffectDraw {
7223 quad: EffectQuad {
7224 effect_id: crate::effect_id::CONTENT,
7225 bounds: content_mask.bounds,
7226 content_mask,
7227 opacity: opacity * plain.min(1.),
7228 scale: self.scale_factor(),
7229 flags: crate::EFFECT_FLAG_NEEDS_CONTENT,
7230 ..Default::default()
7231 },
7232 history: 0,
7233 textures: None,
7234 },
7235 );
7236 }
7237 self.next_frame.scene.vn_push_effect(crate::VnEffectPaint {
7238 draws,
7239 content: true,
7240 content_mask,
7241 });
7242 let outer = mem::replace(&mut self.element_opacity, 1.);
7243 let result = f(self, cx);
7244 self.vn_paint_scope(element, opacity, cx);
7245 self.element_opacity = outer;
7246 self.next_frame.scene.vn_pop_isolation();
7247 result
7248 }
7249
7250 #[allow(clippy::too_many_arguments)]
7253 fn vn_effect_quad(
7254 &mut self,
7255 bounds: Bounds<Pixels>,
7256 corner_radii: Corners<Pixels>,
7257 corner_shapes: Corners<CornerShape>,
7258 spec: EffectSpec,
7259 element: u64,
7260 opacity: f32,
7261 textures: Option<&crate::EffectTextureSet>,
7262 ) -> Option<EffectQuad> {
7263 if !spec.is_some() || opacity <= 0. {
7264 return None;
7265 }
7266
7267 let scale_factor = self.scale_factor();
7268 let bleed = px(spec.bleed());
7269 let draw_bounds = bounds.dilate(bleed);
7274 let draw_radii = Corners {
7275 top_left: corner_radii.top_left + bleed,
7276 top_right: corner_radii.top_right + bleed,
7277 bottom_right: corner_radii.bottom_right + bleed,
7278 bottom_left: corner_radii.bottom_left + bleed,
7279 };
7280
7281 let mut params = spec.params;
7282 for (index, param) in params.iter_mut().enumerate() {
7283 if spec.length_mask & (1 << index) != 0 {
7284 *param *= scale_factor;
7285 }
7286 }
7287 crate::write_effect_texture_sizes(&spec, textures, &mut params);
7288
7289 let Some((draw_bounds, k)) = crate::scene::axis_aligned_through(
7293 self.snap_bounds(draw_bounds),
7294 self.element_transform,
7295 ) else {
7296 return None;
7297 };
7298 let bleed = bleed.scale(scale_factor);
7299 let now = crate::effect_clock_seconds();
7300
7301 if let Some(slot) = spec.pointer_param.map(usize::from)
7302 && slot + 2 <= params.len()
7303 {
7304 let origin = draw_bounds.origin.map(|c| c.0 + bleed.0);
7306 let size = draw_bounds.size.map(|c| (c.0 - 2. * bleed.0).max(1.));
7307 let pointer = self.mouse_position.map(|c| c.0 * scale_factor);
7308 params[slot] = (pointer.x - origin.x) / size.width;
7309 params[slot + 1] = (pointer.y - origin.y) / size.height;
7310 }
7311 if let Some(slot) = spec.pointer_times_param.map(usize::from)
7312 && slot + 3 <= params.len()
7313 {
7314 let times = &self.vn_effect_pointer;
7315 params[slot..slot + 3].copy_from_slice(&[times.moved, times.entered, times.left]);
7316 }
7317 if spec.follows_pointer() {
7318 let view = self.current_view();
7319 self.vn_effect_pointer.views.insert(view);
7320 }
7321 if let Some(slot) = spec.animated_param.map(usize::from)
7322 && slot < params.len()
7323 && element != 0
7324 {
7325 let key = vn_phase_key(element, &spec);
7326 let previous = self.vn_effect_phases.get(&key).copied();
7327 let phase = VnEffectPhase::advance(previous, params[slot], now);
7328 self.vn_effect_phases.insert(key, phase);
7329 if let Some(speed) = phase.speed(now) {
7330 params[slot] = speed;
7331 }
7332 }
7333
7334 let mut clocked = spec;
7335 clocked.params = params;
7336 if spec.animated || clocked.clock_running(now) {
7337 self.request_animation_frame();
7339 }
7340
7341 Some(EffectQuad {
7342 order: 0,
7343 effect_id: spec.id,
7344 bounds: draw_bounds,
7345 content_mask: self.snapped_content_mask(),
7346 corner_radii: draw_radii.scale(scale_factor * k),
7347 params,
7348 opacity,
7349 time: now,
7350 bleed,
7351 backdrop_blur_radius: px(spec.backdrop_blur_radius()).scale(scale_factor),
7352 scale: scale_factor,
7353 flags: spec.flags,
7354 corner_shapes: CornerShapes::new(&corner_shapes),
7355 })
7356 }
7357
7358 pub fn vn_paint_punch(&mut self, bounds: Bounds<Pixels>, corner_radii: Corners<Pixels>) {
7367 self.invalidator.debug_assert_paint();
7368 let opacity = self.element_opacity();
7369 if opacity <= 0. {
7370 return;
7371 }
7372 let scale_factor = self.scale_factor();
7373 let Some((draw_bounds, k)) =
7376 crate::scene::axis_aligned_through(self.snap_bounds(bounds), self.element_transform)
7377 else {
7378 return;
7379 };
7380 self.next_frame.scene.insert_primitive(EffectQuad {
7381 order: 0,
7382 effect_id: crate::effect_id::PUNCH,
7383 bounds: draw_bounds,
7384 content_mask: self.snapped_content_mask(),
7385 corner_radii: corner_radii.scale(scale_factor * k),
7386 params: [0.; crate::EFFECT_PARAM_SLOTS],
7387 opacity,
7388 time: 0.,
7389 bleed: ScaledPixels(0.),
7390 backdrop_blur_radius: ScaledPixels(0.),
7391 scale: scale_factor,
7392 flags: 0,
7393 corner_shapes: CornerShapes::default(),
7394 });
7395 }
7396
7397 pub fn paint_path(&mut self, path: Path, color: impl Into<Background>) {
7401 self.invalidator.debug_assert_paint();
7402
7403 let scale_factor = self.scale_factor();
7404 let content_mask = self.content_mask();
7405 let opacity = self.element_opacity();
7406 let color: Background = color.into();
7407 let path = if self.element_transform.is_unit() {
7412 path
7413 } else {
7414 path.transformed(self.element_transform, scale_factor)
7415 };
7416 self.next_frame.scene.insert_primitive(PaintedPath::new(
7417 path,
7418 scale_factor,
7419 content_mask,
7420 color.opacity(opacity),
7421 ));
7422 }
7423
7424 pub fn paint_underline(
7428 &mut self,
7429 origin: Point<Pixels>,
7430 width: Pixels,
7431 style: &UnderlineStyle,
7432 ) {
7433 self.invalidator.debug_assert_paint();
7434 let underline = self.underline(origin, width, style);
7436 self.next_frame.scene.insert_primitive(underline);
7437 }
7438
7439 pub fn paint_strikethrough(
7443 &mut self,
7444 origin: Point<Pixels>,
7445 width: Pixels,
7446 style: &StrikethroughStyle,
7447 ) {
7448 self.invalidator.debug_assert_paint();
7449
7450 let scale_factor = self.scale_factor();
7451 let height = style.thickness;
7452 let bounds = Bounds {
7453 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
7454 size: size(self.snap_stroke(width), self.snap_stroke(height)),
7455 };
7456 let opacity = self.element_opacity();
7457
7458 self.next_frame.scene.insert_primitive(Underline {
7459 order: 0,
7460 pad: 0,
7461 bounds,
7462 content_mask: self.snapped_content_mask(),
7463 thickness: self.snap_stroke(style.thickness),
7464 color: style.color.unwrap_or_default().opacity(opacity),
7465 wavy: false.into(),
7466 transformation: self.element_transform,
7467 });
7468 }
7469
7470 pub fn paint_glyph(
7479 &mut self,
7480 origin: Point<Pixels>,
7481 font_id: FontId,
7482 glyph_id: GlyphId,
7483 font_size: Pixels,
7484 color: Hsla,
7485 ) -> Result<()> {
7486 self.invalidator.debug_assert_paint();
7487
7488 let element_opacity = self.element_opacity();
7489 let scale_factor = self.scale_factor();
7490 let glyph_origin = origin.scale(scale_factor);
7491
7492 let quantized_origin = Point::new(
7493 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
7494 / SUBPIXEL_VARIANTS_X as f32,
7495 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
7496 / SUBPIXEL_VARIANTS_Y as f32,
7497 );
7498 let subpixel_variant = Point::new(
7499 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
7500 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
7501 );
7502 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
7503 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
7504 let dilation = self.text_system().glyph_dilation_for_color(color);
7505 let params = RenderGlyphParams {
7506 font_id,
7507 glyph_id,
7508 font_size,
7509 subpixel_variant,
7510 scale_factor,
7511 is_emoji: false,
7512 subpixel_rendering,
7513 dilation,
7514 };
7515
7516 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
7517 if !raster_bounds.is_zero() {
7518 let tile = self
7519 .sprite_atlas
7520 .get_or_insert_with(params.clone().into(), &mut || {
7521 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
7522 Ok(Some((size, Cow::Owned(bytes))))
7523 })?
7524 .expect("Callback above only errors or returns Some");
7525 let bounds = Bounds {
7526 origin: integer_origin + raster_bounds.origin.map(Into::into),
7527 size: tile.bounds.size.map(Into::into),
7528 };
7529 let content_mask = self.snapped_content_mask();
7530
7531 if subpixel_rendering {
7532 self.next_frame.scene.insert_primitive(SubpixelSprite {
7533 order: 0,
7534 pad: 0,
7535 bounds,
7536 content_mask,
7537 color: color.opacity(element_opacity),
7538 tile,
7539 transformation: self.element_transform,
7540 });
7541 } else {
7542 self.next_frame.scene.insert_primitive(MonochromeSprite {
7543 order: 0,
7544 raw_coverage: false.into(),
7545 animation: SpriteAnimationId::NONE,
7546 pad: 0,
7547 bounds,
7548 content_mask,
7549 color: color.opacity(element_opacity),
7550 tile,
7551 transformation: self.element_transform,
7552 });
7553 }
7554 }
7555 Ok(())
7556 }
7557
7558 pub fn paint_glyph_shadow(
7561 &mut self,
7562 origin: Point<Pixels>,
7563 font_id: FontId,
7564 glyph_id: GlyphId,
7565 font_size: Pixels,
7566 is_emoji: bool,
7567 color: Hsla,
7568 blur_radius: Pixels,
7569 ) -> Result<()> {
7570 self.invalidator.debug_assert_paint();
7571 if blur_radius <= px(0.) && !is_emoji {
7572 return self.paint_glyph(origin, font_id, glyph_id, font_size, color);
7573 }
7574
7575 let scale_factor = self.scale_factor();
7576 let glyph_origin = origin.scale(scale_factor);
7577 let (integer_origin, subpixel_variant) = if is_emoji {
7578 (
7579 glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0))),
7580 Point::default(),
7581 )
7582 } else {
7583 let quantized_origin = Point::new(
7584 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
7585 / SUBPIXEL_VARIANTS_X as f32,
7586 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
7587 / SUBPIXEL_VARIANTS_Y as f32,
7588 );
7589 (
7590 quantized_origin.map(|c| ScaledPixels(c.trunc())),
7591 Point::new(
7592 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
7593 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
7594 ),
7595 )
7596 };
7597 let glyph = RenderGlyphParams {
7598 font_id,
7599 glyph_id,
7600 font_size,
7601 subpixel_variant,
7602 scale_factor,
7603 is_emoji,
7604 subpixel_rendering: false,
7605 dilation: if is_emoji {
7606 0
7607 } else {
7608 self.text_system().glyph_dilation_for_color(color)
7609 },
7610 };
7611 let raster_bounds = self.text_system().raster_bounds(&glyph)?;
7612 if raster_bounds.is_zero() {
7613 return Ok(());
7614 }
7615 let params = GlyphShadowParams {
7616 sigma_quarters: GlyphShadowParams::quantize_sigma(blur_radius.0 / 2. * scale_factor),
7617 glyph,
7618 };
7619 let padding = params.padding();
7620 let sigma = params.sigma();
7621 let Some(tile) = self.sprite_atlas.get_or_insert_with(
7622 AtlasKey::GlyphShadow(params.clone()),
7623 &mut || {
7624 let (size, coverage) = self.text_system().rasterize_glyph(¶ms.glyph)?;
7625 let (size, blurred) = blur_glyph_coverage(size, &coverage, sigma);
7626 Ok(Some((size, Cow::Owned(blurred))))
7627 },
7628 )?
7629 else {
7630 return Ok(());
7631 };
7632 let bounds = Bounds {
7633 origin: integer_origin
7634 + raster_bounds.origin.map(Into::into)
7635 - point(ScaledPixels(padding as f32), ScaledPixels(padding as f32)),
7636 size: tile.bounds.size.map(Into::into),
7637 };
7638 let content_mask = self.snapped_content_mask();
7639 self.next_frame.scene.insert_primitive(MonochromeSprite {
7640 order: 0,
7641 raw_coverage: true.into(),
7642 animation: SpriteAnimationId::NONE,
7643 pad: 0,
7644 bounds,
7645 content_mask,
7646 color: color.opacity(self.element_opacity()),
7647 tile,
7648 transformation: self.element_transform,
7649 });
7650 Ok(())
7651 }
7652
7653 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
7654 if !self.platform_window.is_subpixel_rendering_supported() {
7657 return false;
7658 }
7659 if self.next_frame.scene.vn_is_isolating() {
7663 return false;
7664 }
7665
7666 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
7667 return false;
7668 }
7669
7670 let mode = match self.text_rendering_mode.get() {
7671 TextRenderingMode::PlatformDefault => self
7672 .text_system()
7673 .recommended_rendering_mode(font_id, font_size),
7674 mode => mode,
7675 };
7676
7677 mode == TextRenderingMode::Subpixel
7678 }
7679
7680 pub fn paint_emoji(
7689 &mut self,
7690 origin: Point<Pixels>,
7691 font_id: FontId,
7692 glyph_id: GlyphId,
7693 font_size: Pixels,
7694 ) -> Result<()> {
7695 self.invalidator.debug_assert_paint();
7696
7697 let scale_factor = self.scale_factor();
7698 let glyph_origin = origin.scale(scale_factor);
7699 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
7700 let params = RenderGlyphParams {
7701 font_id,
7702 glyph_id,
7703 font_size,
7704 subpixel_variant: Default::default(),
7705 scale_factor,
7706 is_emoji: true,
7707 subpixel_rendering: false,
7708 dilation: 0,
7709 };
7710
7711 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
7712 if !raster_bounds.is_zero() {
7713 let tile = self
7714 .sprite_atlas
7715 .get_or_insert_with(params.clone().into(), &mut || {
7716 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
7717 Ok(Some((size, Cow::Owned(bytes))))
7718 })?
7719 .expect("Callback above only errors or returns Some");
7720
7721 let bounds = Bounds {
7722 origin: integer_origin + raster_bounds.origin.map(Into::into),
7723 size: tile.bounds.size.map(Into::into),
7724 };
7725 let content_mask = self.snapped_content_mask();
7726 let opacity = self.element_opacity();
7727
7728 self.next_frame.scene.insert_primitive(PolychromeSprite {
7729 order: 0,
7730 pad: 0,
7731 grayscale: false.into(),
7732 bounds,
7733 corner_radii: Default::default(),
7734 content_mask,
7735 tile,
7736 opacity,
7737 transformation: self.element_transform,
7738 tint: Hsla::transparent_black(),
7739 corner_shapes: CornerShapes::default(),
7740 });
7741 }
7742 Ok(())
7743 }
7744
7745 pub fn paint_svg(
7749 &mut self,
7750 bounds: Bounds<Pixels>,
7751 path: SharedString,
7752 data: Option<&[u8]>,
7753 transformation: TransformationMatrix,
7754 color: Hsla,
7755 cx: &App,
7756 ) -> Result<()> {
7757 self.paint_animated_svg(bounds, path, data, transformation, None, color, cx)
7758 }
7759
7760 pub(crate) fn paint_animated_svg(
7763 &mut self,
7764 bounds: Bounds<Pixels>,
7765 path: SharedString,
7766 data: Option<&[u8]>,
7767 transformation: TransformationMatrix,
7768 animation: Option<SpriteAnimation>,
7769 color: Hsla,
7770 cx: &App,
7771 ) -> Result<()> {
7772 self.invalidator.debug_assert_paint();
7773
7774 let element_opacity = self.element_opacity();
7775 let bounds = self.snap_bounds(bounds);
7776
7777 let params = RenderSvgParams {
7778 path,
7779 size: bounds.size.map(|pixels| {
7780 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
7781 }),
7782 };
7783
7784 let Some(tile) =
7785 self.sprite_atlas
7786 .get_or_insert_with(params.clone().into(), &mut || {
7787 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
7788 else {
7789 return Ok(None);
7790 };
7791 Ok(Some((size, Cow::Owned(bytes))))
7792 })?
7793 else {
7794 return Ok(());
7795 };
7796 let content_mask = self.snapped_content_mask();
7797 let svg_bounds = Bounds {
7798 origin: bounds.center()
7799 - Point::new(
7800 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
7801 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
7802 ),
7803 size: tile
7804 .bounds
7805 .size
7806 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
7807 };
7808 let final_bounds = svg_bounds
7809 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
7810 .map_size(|size| size.ceil());
7811
7812 let sprite = MonochromeSprite {
7813 order: 0,
7814 raw_coverage: false.into(),
7815 animation: SpriteAnimationId::NONE,
7816 pad: 0,
7817 bounds: final_bounds,
7818 content_mask,
7819 color: color.opacity(element_opacity),
7820 tile,
7821 transformation: self.element_transform.compose(transformation),
7824 };
7825 match animation {
7826 Some(animation) => self.next_frame.scene.insert_animated_sprite(
7827 sprite,
7828 animation.under(self.element_transform),
7829 ),
7830 None => self.next_frame.scene.insert_primitive(sprite),
7831 }
7832
7833 Ok(())
7834 }
7835
7836 pub fn paint_image(
7848 &mut self,
7849 bounds: Bounds<Pixels>,
7850 image_bounds: Bounds<Pixels>,
7851 corner_radii: Corners<Pixels>,
7852 data: Arc<RenderImage>,
7853 frame_index: usize,
7854 grayscale: bool,
7855 ) -> Result<()> {
7856 self.invalidator.debug_assert_paint();
7857
7858 let visible_bounds = bounds.intersect(&image_bounds);
7859 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
7860 return Ok(());
7861 }
7862 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
7863 return Ok(());
7864 }
7865
7866 let (data, frame_index) = match IMAGE_RESAMPLER.get() {
7869 Some(resample) if !data.is_dynamic() => {
7870 let scale = self.scale_factor();
7871 let device = size(
7872 DevicePixels((image_bounds.size.width.0 * scale).round() as i32),
7873 DevicePixels((image_bounds.size.height.0 * scale).round() as i32),
7874 );
7875 match resample(&data, frame_index, device) {
7876 Some(smaller) => (smaller, 0),
7877 None => (data, frame_index),
7878 }
7879 }
7880 _ => (data, frame_index),
7881 };
7882
7883 let params = RenderImageParams {
7884 image_id: data.id,
7885 frame_index,
7886 };
7887
7888 let tile = self.sprite_atlas.get_or_insert_with(params.into(), &mut || {
7889 Ok(data.as_bytes(frame_index).map(|bytes| (data.size(frame_index), Cow::Borrowed(bytes))))
7890 })?;
7891 let Some(tile) = tile else { return Ok(()); };
7892
7893 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
7894
7895 let sub_tile = if visible_bounds == image_bounds {
7896 tile
7897 } else {
7898 let x_offset_ratio =
7899 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
7900 let y_offset_ratio =
7901 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
7902 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
7903 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
7904
7905 let tile_origin_x = tile.bounds.origin.x.0;
7906 let tile_origin_y = tile.bounds.origin.y.0;
7907 let tile_width = tile.bounds.size.width.0;
7908 let tile_height = tile.bounds.size.height.0;
7909
7910 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
7911 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
7912 let sub_width = (width_ratio * tile_width as f32).round() as i32;
7913 let sub_height = (height_ratio * tile_height as f32).round() as i32;
7914
7915 let max_x = tile_origin_x + tile_width;
7916 let max_y = tile_origin_y + tile_height;
7917
7918 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
7919 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
7920 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
7921 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
7922
7923 AtlasTile {
7924 bounds: Bounds {
7925 origin: point(
7926 DevicePixels(clamped_origin_x),
7927 DevicePixels(clamped_origin_y),
7928 ),
7929 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
7930 },
7931 ..tile
7932 }
7933 };
7934
7935 let content_mask = self.snapped_content_mask();
7936 let corner_radii = corner_radii
7937 .clamp_radii_for_quad_size(visible_bounds.size)
7938 .scale(self.scale_factor());
7939 let opacity = self.element_opacity();
7940
7941 self.next_frame.scene.insert_primitive(PolychromeSprite {
7942 order: 0,
7943 pad: 0,
7944 grayscale: grayscale.into(),
7945 bounds: visible_bounds_snapped,
7946 content_mask,
7947 corner_radii,
7948 tile: sub_tile,
7949 opacity,
7950 transformation: self.element_transform,
7951 tint: self.element_image_tint,
7952 corner_shapes: CornerShapes::default(),
7953 });
7954 Ok(())
7955 }
7956
7957 #[cfg(any(target_os = "macos", target_os = "ios"))]
7961 pub fn paint_surface(
7962 &mut self,
7963 bounds: Bounds<Pixels>,
7964 image_buffer: CFRetained<CVPixelBuffer>,
7965 ) {
7966 use crate::PaintSurface;
7967
7968 self.invalidator.debug_assert_paint();
7969
7970 let bounds = self.snap_bounds(bounds);
7971 let content_mask = self.snapped_content_mask();
7972 self.next_frame.scene.insert_primitive(PaintSurface {
7973 order: 0,
7974 bounds,
7975 content_mask,
7976 image_buffer,
7977 });
7978 }
7979
7980 pub fn upload_image_from_gpu(
8001 &mut self,
8002 data: &RenderImage,
8003 frame_index: usize,
8004 texture: GpuTextureHandle,
8005 ) -> Result<bool> {
8006 Ok(self.write_image_tile(data, frame_index, TileSource::Gpu(texture))? != TileWrite::Refused)
8007 }
8008
8009 pub fn write_image_tile(
8027 &mut self,
8028 image: &RenderImage,
8029 frame_index: usize,
8030 source: TileSource,
8031 ) -> Result<TileWrite> {
8032 let key: AtlasKey = RenderImageParams {
8033 image_id: image.id,
8034 frame_index,
8035 }
8036 .into();
8037 let size = image.size(frame_index);
8038 let before = self.sprite_atlas.tile(&key);
8039 let after = match source {
8040 TileSource::Gpu(texture) => {
8041 match self.sprite_atlas.upload_from_gpu(&key, size, texture)? {
8042 Some(tile) => tile,
8043 None => return Ok(TileWrite::Refused),
8044 }
8045 }
8046 TileSource::Bytes => {
8047 let bytes = image
8048 .as_bytes(frame_index)
8049 .ok_or_else(|| anyhow!("write_image_tile: no frame {frame_index}"))?;
8050 match self.sprite_atlas.write_bytes(&key, size, bytes)? {
8051 Some(tile) => tile,
8052 None => {
8053 self.sprite_atlas.remove(&key);
8054 self.sprite_atlas
8055 .get_or_insert_with(key, &mut || {
8056 Ok(Some((size, Cow::Borrowed(bytes))))
8057 })?
8058 .ok_or_else(|| anyhow!("write_image_tile: the atlas took no tile"))?;
8059 return Ok(TileWrite::Placed);
8060 }
8061 }
8062 }
8063 };
8064 Ok(match before {
8065 Some(tile) if tile == after => TileWrite::InPlace,
8066 _ => TileWrite::Placed,
8067 })
8068 }
8069
8070 pub fn write_image_tile_d3d12(
8073 &mut self,
8074 image: &RenderImage,
8075 frame_index: usize,
8076 texture: crate::D3D12TextureHandle,
8077 owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
8078 ) -> Result<TileWrite> {
8079 let key: AtlasKey = RenderImageParams {
8080 image_id: image.id,
8081 frame_index,
8082 }
8083 .into();
8084 let before = self.sprite_atlas.tile(&key);
8085 let Some(after) = self.sprite_atlas.upload_from_d3d12(
8086 &key,
8087 image.size(frame_index),
8088 texture,
8089 owner,
8090 )? else {
8091 return Ok(TileWrite::Refused);
8092 };
8093 Ok(match before {
8094 Some(tile) if tile == after => TileWrite::InPlace,
8095 _ => TileWrite::Placed,
8096 })
8097 }
8098
8099 pub fn write_image_tile_metal(
8102 &mut self,
8103 image: &RenderImage,
8104 frame_index: usize,
8105 texture: GpuTextureHandle,
8106 ready: Option<(*mut std::ffi::c_void, u64)>,
8107 owner: std::sync::Arc<dyn std::any::Any + Send + Sync>,
8108 ) -> Result<TileWrite> {
8109 let key: AtlasKey = RenderImageParams {
8110 image_id: image.id,
8111 frame_index,
8112 }
8113 .into();
8114 let before = self.sprite_atlas.tile(&key);
8115 let Some(after) =
8116 self.sprite_atlas
8117 .upload_from_metal(&key, image.size(frame_index), texture, ready, owner)?
8118 else {
8119 return Ok(TileWrite::Refused);
8120 };
8121 Ok(match before {
8122 Some(tile) if tile == after => TileWrite::InPlace,
8123 _ => TileWrite::Placed,
8124 })
8125 }
8126
8127 pub fn request_present(&self) {
8134 self.needs_present.set(true);
8135 self.invalidator.wake_platform();
8136 }
8137
8138 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
8140 for frame_index in 0..data.frame_count() {
8141 let params = RenderImageParams {
8142 image_id: data.id,
8143 frame_index,
8144 };
8145
8146 self.sprite_atlas.remove(¶ms.into());
8147 }
8148
8149 Ok(())
8150 }
8151
8152 pub fn sprite_atlas_stats(&self) -> Option<AtlasStats> {
8156 self.sprite_atlas.stats()
8157 }
8158
8159 pub fn has_image_atlas_tile(&self, data: &RenderImage, frame_index: usize) -> bool {
8161 self.sprite_atlas.tile(&RenderImageParams {image_id:data.id,frame_index}.into()).is_some()
8162 }
8163
8164 #[cfg(any(test, feature = "test-support"))]
8166 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
8167 data.frame_count() > 0
8168 && (0..data.frame_count()).all(|frame_index| {
8169 self.sprite_atlas.contains(
8170 &RenderImageParams {
8171 image_id: data.id,
8172 frame_index,
8173 }
8174 .into(),
8175 )
8176 })
8177 }
8178
8179 pub fn vn_enable_retained_layout(&mut self) {
8182 self.layout_engine.as_mut().unwrap().enable_retention();
8183 }
8184
8185 pub fn vn_profile_retained_layout(&mut self, enabled: bool) {
8187 self.layout_engine
8188 .as_mut()
8189 .unwrap()
8190 .profile_retention(enabled);
8191 }
8192
8193 pub fn vn_take_retained_layout_stats(&mut self) -> Option<crate::VnRetainedLayoutStats> {
8195 self.layout_engine.as_mut().unwrap().take_retention_stats()
8196 }
8197
8198 #[must_use]
8204 pub fn request_layout(
8205 &mut self,
8206 style: Style,
8207 children: impl IntoIterator<Item = LayoutId>,
8208 cx: &mut App,
8209 ) -> LayoutId {
8210 self.invalidator.debug_assert_prepaint();
8211
8212 cx.layout_id_buffer.clear();
8213 cx.layout_id_buffer.extend(children);
8214 let rem_size = self.rem_size();
8215 let scale_factor = self.scale_factor();
8216
8217 let scope = self
8218 .layout_engine
8219 .as_ref()
8220 .unwrap()
8221 .retention_enabled()
8222 .then(|| self.element_id_stack.global_id());
8223 let engine = self.layout_engine.as_mut().unwrap();
8224 if let Some(scope) = scope {
8225 engine.request_layout_in_scope(
8226 Some(scope),
8227 style,
8228 rem_size,
8229 scale_factor,
8230 &cx.layout_id_buffer,
8231 )
8232 } else {
8233 engine.request_layout(style, rem_size, scale_factor, &cx.layout_id_buffer)
8234 }
8235 }
8236
8237 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
8246 where
8247 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
8248 + 'static,
8249 {
8250 self.invalidator.debug_assert_prepaint();
8251
8252 let rem_size = self.rem_size();
8253 let scale_factor = self.scale_factor();
8254 let scope = self
8255 .layout_engine
8256 .as_ref()
8257 .unwrap()
8258 .retention_enabled()
8259 .then(|| self.element_id_stack.global_id());
8260 let engine = self.layout_engine.as_mut().unwrap();
8261 if let Some(scope) = scope {
8262 engine.request_measured_layout_in_scope(
8263 Some(scope),
8264 style,
8265 rem_size,
8266 scale_factor,
8267 measure,
8268 )
8269 } else {
8270 engine.request_measured_layout(style, rem_size, scale_factor, measure)
8271 }
8272 }
8273
8274 pub fn compute_layout(
8280 &mut self,
8281 layout_id: LayoutId,
8282 available_space: Size<AvailableSpace>,
8283 cx: &mut App,
8284 ) {
8285 self.invalidator.debug_assert_prepaint();
8286
8287 let mut layout_engine = self.layout_engine.take().unwrap();
8288 layout_engine.compute_layout(layout_id, available_space, self, cx);
8289 self.layout_engine = Some(layout_engine);
8290 }
8291
8292 pub fn layout_is_absolute(&self, layout_id: LayoutId) -> bool {
8295 self.layout_engine
8296 .as_ref()
8297 .is_some_and(|engine| engine.is_absolute(layout_id))
8298 }
8299
8300 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
8305 self.invalidator.debug_assert_prepaint();
8306
8307 let scale_factor = self.scale_factor();
8308 let mut bounds = self
8309 .layout_engine
8310 .as_mut()
8311 .unwrap()
8312 .layout_bounds(layout_id, scale_factor)
8313 .map(Into::into);
8314 let snapped_offset = self.pixel_snap_point(self.element_offset());
8315 bounds.origin += snapped_offset;
8316 bounds
8317 }
8318
8319 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
8325 self.invalidator.debug_assert_prepaint();
8326
8327 let content_mask = self.content_mask();
8328 let id = self.next_hitbox_id;
8329 self.next_hitbox_id = self.next_hitbox_id.next();
8330 let hitbox = Hitbox {
8331 id,
8332 bounds,
8333 content_mask,
8334 behavior,
8335 transformation: self.element_transform,
8339 vn_clip: self.vn_clip_stack.clone(),
8340 };
8341 self.next_frame.hitboxes.push(hitbox.clone());
8342 if self.vn_hitbox_tag != 0 {
8344 self.next_frame
8345 .vn_tagged_hitboxes
8346 .push((self.vn_hitbox_tag, hitbox.clone()));
8347 }
8348 hitbox
8349 }
8350
8351 pub fn set_hitbox_tag(&mut self, tag: u32) -> u32 {
8358 mem::replace(&mut self.vn_hitbox_tag, tag)
8359 }
8360
8361 pub fn with_hitbox_tag<R>(
8372 &mut self,
8373 tag: u32,
8374 f: impl FnOnce(&mut Self) -> R,
8375 ) -> (R, Option<TransformationMatrix>) {
8376 let tag = mem::replace(&mut self.vn_hitbox_tag, tag);
8377 let fresh = mem::replace(&mut self.vn_tag_fresh, true);
8378 let noted = self.vn_tag_transform.take();
8379 let result = f(self);
8380 let own = mem::replace(&mut self.vn_tag_transform, noted);
8381 self.vn_tag_fresh = fresh;
8382 self.vn_hitbox_tag = tag;
8383 (result, own)
8384 }
8385
8386 pub(crate) fn note_tagged_transform(&mut self, own_is_unit: bool) {
8390 if self.vn_tag_fresh {
8391 self.vn_tag_fresh = false;
8392 if !own_is_unit {
8393 self.vn_tag_transform = Some(self.element_transform);
8394 }
8395 }
8396 }
8397
8398 pub fn transformed_bounds(
8403 &self,
8404 matrix: TransformationMatrix,
8405 bounds: Bounds<Pixels>,
8406 ) -> Bounds<Pixels> {
8407 transform_bounds(matrix, bounds, self.scale_factor)
8408 }
8409
8410 pub fn set_tag_every_hitbox(&mut self, on: bool) {
8416 self.vn_tag_every_hitbox = on;
8417 }
8418
8419 pub fn tags_every_hitbox(&self) -> bool {
8421 self.vn_tag_every_hitbox
8422 }
8423
8424 pub fn tagged_hitbox(&self, tag: u32) -> Option<&Hitbox> {
8432 self.rendered_frame
8433 .vn_tagged_hitboxes
8434 .iter()
8435 .find(|(t, hitbox)| *t == tag && hitbox.id != HitboxId::VN_PICK)
8436 .map(|(_, hitbox)| hitbox)
8437 }
8438
8439 pub fn vn_tags_at(&self, position: Point<Pixels>) -> Vec<u32> {
8461 let frame = &self.rendered_frame;
8462 let tagged = &frame.vn_tagged_hitboxes;
8463 let mut out = Vec::new();
8464 let mut visit = |(tag, hitbox): &(u32, Hitbox)| {
8465 if tag & VN_TAG_PASSIVE != 0 || !Frame::box_contains(hitbox, position, self.scale_factor) {
8466 return true;
8467 }
8468 out.push(*tag);
8469 hitbox.behavior != HitboxBehavior::BlockMouse
8470 };
8471 match frame.vn_tagged_paint_order() {
8472 Some(order) => {
8473 for &ix in order.iter().rev() {
8474 if !visit(&tagged[ix as usize]) {
8475 break;
8476 }
8477 }
8478 }
8479 None => {
8480 for entry in tagged.iter().rev() {
8481 if !visit(entry) {
8482 break;
8483 }
8484 }
8485 }
8486 }
8487 out
8488 }
8489
8490 pub fn set_vn_pick_every_box(&mut self, on: bool) {
8498 self.vn_pick_every_box = on;
8499 }
8500
8501 pub fn vn_picks_every_box(&self) -> bool {
8503 self.vn_pick_every_box
8504 }
8505
8506 pub fn vn_insert_pick(&mut self, bounds: Bounds<Pixels>) {
8511 self.invalidator.debug_assert_prepaint();
8512 if self.vn_hitbox_tag == 0 {
8513 return;
8514 }
8515 let hitbox = Hitbox {
8516 id: HitboxId::VN_PICK,
8517 bounds,
8518 content_mask: self.content_mask(),
8519 behavior: HitboxBehavior::Normal,
8520 transformation: self.element_transform,
8521 vn_clip: self.vn_clip_stack.clone(),
8522 };
8523 self.next_frame
8524 .vn_tagged_hitboxes
8525 .push((self.vn_hitbox_tag, hitbox));
8526 }
8527
8528 pub fn set_vn_hit_refiner(&mut self, refiner: Option<VnHitRefiner>) {
8538 self.vn_hit_refiner = refiner;
8539 }
8540
8541 pub fn has_vn_hit_refiner(&self) -> bool {
8543 self.vn_hit_refiner.is_some()
8544 }
8545
8546 pub fn vn_key_event_seq(&self) -> u64 {
8560 self.vn_key_event_seq
8561 }
8562
8563 pub fn vn_pointer_inside(&self) -> bool {
8570 self.pointer_inside
8571 }
8572
8573 pub fn vn_lock_pointer(&mut self, how: VnPointerLock) -> Result<(), crate::PointerLockError> {
8577 let anchor = match self.vn_pointer_lock.take() {
8578 Some((previous, anchor)) => {
8579 if matches!(previous, VnPointerLock::System { .. }) {
8580 self.platform_window.unlock_pointer();
8581 }
8582 anchor
8583 }
8584 None => self.mouse_position,
8585 };
8586 if let VnPointerLock::System { unadjusted } = how {
8587 self.platform_window.lock_pointer(unadjusted)?;
8588 }
8589 self.vn_pointer_lock = Some((how, anchor));
8590 self.vn_raw_mouse_position = None;
8591 Ok(())
8592 }
8593
8594 pub fn vn_unlock_pointer(&mut self) {
8596 if let Some((VnPointerLock::System { .. }, _)) = self.vn_pointer_lock.take() {
8597 self.platform_window.unlock_pointer();
8598 }
8599 self.vn_raw_mouse_position = None;
8600 }
8601
8602 pub fn vn_pointer_locked(&self) -> bool {
8605 match self.vn_pointer_lock {
8606 Some((VnPointerLock::System { .. }, _)) => self.platform_window.is_pointer_locked(),
8607 Some((VnPointerLock::Simulated, _)) => true,
8608 None => false,
8609 }
8610 }
8611
8612 pub fn vn_mouse_movement(&self) -> Point<Pixels> {
8616 self.vn_mouse_movement
8617 }
8618
8619 fn vn_pin_to_pointer_lock(&mut self, mut event: PlatformInput) -> PlatformInput {
8620 let system = matches!(
8621 self.vn_pointer_lock,
8622 Some((VnPointerLock::System { .. }, _))
8623 );
8624 if system && !self.platform_window.is_pointer_locked() {
8625 self.vn_pointer_lock = None;
8626 self.vn_raw_mouse_position = None;
8627 }
8628 if let PlatformInput::MouseMove(mouse_move) = &event {
8629 let previous = self.vn_raw_mouse_position.replace(mouse_move.position);
8630 let motion = system.then(|| self.platform_window.take_pointer_motion());
8631 self.vn_mouse_movement = motion.flatten().unwrap_or_else(|| {
8632 previous.map_or_else(Point::default, |previous| mouse_move.position - previous)
8633 });
8634 }
8635 let Some((_, anchor)) = self.vn_pointer_lock else {
8636 return event;
8637 };
8638 match &mut event {
8639 PlatformInput::MouseMove(e) => e.position = anchor,
8640 PlatformInput::MouseDown(e) => e.position = anchor,
8641 PlatformInput::MouseUp(e) => e.position = anchor,
8642 PlatformInput::Scroll(e) => e.position = anchor,
8643 PlatformInput::MouseExited(e) => e.position = anchor,
8644 _ => {}
8645 }
8646 event
8647 }
8648
8649 pub fn vn_is_dirty(&self) -> bool {
8656 self.invalidator.is_dirty()
8657 }
8658
8659 pub fn vn_restrict_mouse_hit(&mut self, keep: &dyn Fn(u32) -> bool, add: bool) {
8668 let frame = &self.rendered_frame;
8669 let mut tag_of: FxHashMap<HitboxId, u32> = FxHashMap::default();
8670 for (tag, hitbox) in &frame.vn_tagged_hitboxes {
8672 if hitbox.id != HitboxId::VN_PICK {
8673 tag_of.entry(hitbox.id).or_insert(tag & !VN_TAG_PASSIVE);
8674 }
8675 }
8676 let old = mem::take(&mut self.mouse_hit_test);
8677 let mut ids: SmallVec<[HitboxId; 8]> = SmallVec::new();
8678 let mut hover = 0;
8679 for (ix, id) in old.ids.iter().enumerate() {
8680 if tag_of.get(id).is_none_or(|tag| keep(*tag)) {
8681 ids.push(*id);
8682 if ix < old.hover_hitbox_count {
8683 hover += 1;
8684 }
8685 }
8686 }
8687 let all_hovered = old.hover_hitbox_count == old.ids.len();
8690 if add {
8691 for (tag, hitbox) in &frame.vn_tagged_hitboxes {
8692 if hitbox.id != HitboxId::VN_PICK
8693 && keep(tag & !VN_TAG_PASSIVE)
8694 && !ids.contains(&hitbox.id)
8695 {
8696 ids.push(hitbox.id);
8697 }
8698 }
8699 }
8700 if all_hovered {
8701 hover = ids.len();
8702 }
8703 self.mouse_hit_test = HitTest {
8704 ids,
8705 hover_hitbox_count: hover,
8706 };
8707 }
8708
8709 pub fn window_control_area_at(&self, position: Point<Pixels>) -> Option<WindowControlArea> {
8712 for hitbox in self.rendered_frame.topmost_hitboxes() {
8713 if !Frame::box_contains(hitbox, position, self.scale_factor) {
8714 continue;
8715 }
8716 if let Some((area, _)) = self.rendered_frame.window_control_hitboxes.iter()
8717 .find(|(_, control)| control.id == hitbox.id)
8718 {
8719 return Some(*area);
8720 }
8721 if hitbox.behavior == HitboxBehavior::BlockMouse {
8722 break;
8723 }
8724 }
8725 None
8726 }
8727
8728 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
8732 self.invalidator.debug_assert_paint();
8733 self.next_frame.window_control_hitboxes.push((area, hitbox));
8734 }
8735
8736 pub fn set_key_context(&mut self, context: KeyContext) {
8741 self.invalidator.debug_assert_paint();
8742 self.next_frame.dispatch_tree.set_key_context(context);
8743 }
8744
8745 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
8750 self.invalidator.debug_assert_prepaint();
8751 if focus_handle.is_focused(self) {
8752 self.next_frame.focus = Some(focus_handle.id);
8753 }
8754 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
8755 }
8756
8757 pub fn set_view_id(&mut self, view_id: EntityId) {
8763 self.invalidator.debug_assert_prepaint();
8764 self.next_frame.dispatch_tree.set_view_id(view_id);
8765 }
8766
8767 pub fn current_view(&self) -> EntityId {
8769 self.invalidator.debug_assert_paint_or_prepaint();
8770 self.rendered_entity_stack.last().copied().unwrap()
8771 }
8772
8773 #[inline]
8774 pub(crate) fn with_rendered_view<R>(
8775 &mut self,
8776 id: EntityId,
8777 f: impl FnOnce(&mut Self) -> R,
8778 ) -> R {
8779 self.rendered_entity_stack.push(id);
8780 let result = f(self);
8781 self.rendered_entity_stack.pop();
8782 result
8783 }
8784
8785 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
8787 where
8788 F: FnOnce(&mut Self) -> R,
8789 {
8790 if let Some(image_cache) = image_cache {
8791 self.image_cache_stack.push(image_cache);
8792 let result = f(self);
8793 self.image_cache_stack.pop();
8794 result
8795 } else {
8796 f(self)
8797 }
8798 }
8799
8800 pub fn handle_input(
8809 &mut self,
8810 focus_handle: &FocusHandle,
8811 input_handler: impl InputHandler,
8812 cx: &App,
8813 ) {
8814 self.invalidator.debug_assert_paint();
8815
8816 if focus_handle.is_focused(self) {
8817 let cx = self.to_async(cx);
8818 self.next_frame.input_handlers.push(Some(
8819 PlatformInputHandler::new(cx, Box::new(input_handler)).with_focus(focus_handle.id),
8820 ));
8821 }
8822 }
8823
8824 pub fn notify_text_input_changed(&self, focus_handle: &FocusHandle) {
8829 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
8830 self.platform_window
8831 .text_input_state_changed(TextInputStateChange::ContentChanged);
8832 }
8833 }
8834
8835 pub fn notify_text_selection_changed(&self, focus_handle: &FocusHandle) {
8840 if self.focused_text_input == Some(focus_handle.id) && focus_handle.is_focused(self) {
8841 self.platform_window
8842 .text_input_state_changed(TextInputStateChange::SelectionChanged);
8843 }
8844 }
8845
8846 fn apply_text_input_configuration(&mut self, cx: &mut App) {
8851 let configuration = match self.platform_window.take_input_handler() {
8852 Some(mut input_handler) => {
8853 let configuration = input_handler.text_input_configuration(self, cx);
8854 self.platform_window.set_input_handler(input_handler);
8855 configuration
8856 }
8857 None => TextInputConfiguration::default(),
8858 };
8859 if self.last_text_input_configuration.as_ref() != Some(&configuration) {
8860 self.platform_window
8861 .set_text_input_configuration(configuration.clone());
8862 self.last_text_input_configuration = Some(configuration);
8863 }
8864 }
8865
8866 pub fn on_mouse_event<Event: MouseEvent>(
8872 &mut self,
8873 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
8874 ) {
8875 self.invalidator.debug_assert_paint();
8876
8877 self.next_frame.mouse_listeners.push(Some(Box::new(
8878 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
8879 if let Some(event) = event.downcast_ref() {
8880 listener(event, phase, window, cx)
8881 }
8882 },
8883 )));
8884 }
8885
8886 pub fn on_key_event<Event: KeyEvent>(
8895 &mut self,
8896 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
8897 ) {
8898 self.invalidator.debug_assert_paint();
8899
8900 self.next_frame.dispatch_tree.on_key_event(Rc::new(
8901 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
8902 if let Some(event) = event.downcast_ref::<Event>() {
8903 listener(event, phase, window, cx)
8904 }
8905 },
8906 ));
8907 }
8908
8909 pub fn on_modifiers_changed(
8916 &mut self,
8917 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
8918 ) {
8919 self.invalidator.debug_assert_paint();
8920
8921 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
8922 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
8923 listener(event, window, cx)
8924 },
8925 ));
8926 }
8927
8928 pub fn on_focus_in(
8932 &mut self,
8933 handle: &FocusHandle,
8934 cx: &mut App,
8935 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
8936 ) -> Subscription {
8937 let focus_id = handle.id;
8938 let (subscription, activate) =
8939 self.new_focus_listener(Box::new(move |event, window, cx| {
8940 if event.is_focus_in(focus_id) {
8941 listener(window, cx);
8942 }
8943 true
8944 }));
8945 cx.defer(move |_| activate());
8946 subscription
8947 }
8948
8949 pub fn on_focus_out(
8952 &mut self,
8953 handle: &FocusHandle,
8954 cx: &mut App,
8955 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
8956 ) -> Subscription {
8957 let focus_id = handle.id;
8958 let (subscription, activate) =
8959 self.new_focus_listener(Box::new(move |event, window, cx| {
8960 if let Some(blurred_id) = event.previous_focus_path.last().copied()
8961 && event.is_focus_out(focus_id)
8962 {
8963 let event = FocusOutEvent {
8964 blurred: WeakFocusHandle {
8965 id: blurred_id,
8966 handles: Arc::downgrade(&cx.focus_handles),
8967 },
8968 };
8969 listener(event, window, cx)
8970 }
8971 true
8972 }));
8973 cx.defer(move |_| activate());
8974 subscription
8975 }
8976
8977 fn reset_cursor_style(&self, cx: &mut App) {
8978 if self.is_window_hovered() {
8980 let style = cx
8982 .active_drag_cursor_style()
8983 .or_else(|| self.rendered_frame.cursor_style(self))
8984 .unwrap_or(CursorStyle::Arrow);
8985 cx.platform.set_cursor_style(style);
8986 }
8987 }
8988
8989 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
8992 let keystroke = keystroke.with_simulated_ime();
8993 let result = self.dispatch_event(
8994 PlatformInput::KeyDown(KeyDownEvent {
8995 keystroke: keystroke.clone(),
8996 is_held: false,
8997 prefer_character_input: false,
8998 }),
8999 cx,
9000 );
9001 if !result.propagate {
9002 return true;
9003 }
9004
9005 if let Some(input) = keystroke.key_char
9006 && let Some(mut input_handler) = self.platform_window.take_input_handler()
9007 {
9008 input_handler.dispatch_input(&input, self, cx);
9009 self.platform_window.set_input_handler(input_handler);
9010 return true;
9011 }
9012
9013 false
9014 }
9015
9016 pub fn keystroke_text_for(&self, action: &dyn Action, cx: &App) -> String {
9019 self.highest_precedence_binding_for_action(action)
9020 .map(|binding| {
9021 binding
9022 .keystrokes()
9023 .iter()
9024 .map(|keystroke| keystroke.display(cx.platform_info().os).to_string())
9025 .collect::<Vec<_>>()
9026 .join(" ")
9027 })
9028 .unwrap_or_else(|| action.name().to_string())
9029 }
9030
9031 pub fn set_input_interceptor(
9035 &mut self,
9036 interceptor: Option<Rc<dyn Fn(&PlatformInput, &mut Window, &mut App) -> bool>>,
9037 ) {
9038 self.input_interceptor = interceptor;
9039 }
9040
9041 #[profiling::function]
9043 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
9044 if let Some(intercept) = self.input_interceptor.clone() {
9048 if intercept(&event, self, cx) {
9049 return DispatchEventResult { propagate: false, default_prevented: true };
9050 }
9051 }
9052 #[cfg(feature = "profiler")]
9053 self.window_profiler.begin_input(event.kind_name());
9054 let update_count_before = self.invalidator.update_count();
9055 let old_modality = self.last_input_modality;
9059 self.last_input_modality = match &event {
9060 PlatformInput::KeyDown(_) => InputModality::Keyboard,
9061 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
9062 PlatformInput::Touch(_) => InputModality::Touch,
9063 _ => self.last_input_modality,
9064 };
9065 if self.last_input_modality != old_modality {
9066 self.refresh();
9067 }
9068 let was_inside = self.pointer_inside;
9069 let pointer_moved = matches!(event, PlatformInput::MouseMove(_));
9070 let pointer_leaves = match &event {
9075 PlatformInput::MouseMove(_)
9076 | PlatformInput::MouseDown(_)
9077 | PlatformInput::MouseUp(_)
9078 | PlatformInput::MousePressure(_)
9079 | PlatformInput::Scroll(_)
9080 | PlatformInput::Pinch(_)
9081 | PlatformInput::LongPress(_)
9082 | PlatformInput::TouchDrag(_)
9083 | PlatformInput::BackGesture(_)
9084 | PlatformInput::Touch(_) => {
9085 self.pointer_inside = true;
9086 false
9087 }
9088 PlatformInput::FileDrop(FileDropEvent::Exited) | PlatformInput::MouseExited(_) => true,
9089 PlatformInput::FileDrop(_) => {
9090 self.pointer_inside = true;
9091 false
9092 }
9093 PlatformInput::KeyDown(_)
9094 | PlatformInput::KeyUp(_)
9095 | PlatformInput::ModifiersChanged(_) => false,
9096 };
9097
9098 cx.propagate_event = true;
9100 self.default_prevented = false;
9102
9103 let event = self.vn_pin_to_pointer_lock(event);
9104 let event = match event {
9105 PlatformInput::MouseMove(mouse_move) => {
9108 self.mouse_position = mouse_move.position;
9109 self.modifiers = mouse_move.modifiers;
9110 PlatformInput::MouseMove(mouse_move)
9111 }
9112 PlatformInput::MouseDown(mouse_down) => {
9113 self.mouse_position = mouse_down.position;
9114 self.modifiers = mouse_down.modifiers;
9115 PlatformInput::MouseDown(mouse_down)
9116 }
9117 PlatformInput::MouseUp(mouse_up) => {
9118 self.mouse_position = mouse_up.position;
9119 self.modifiers = mouse_up.modifiers;
9120 PlatformInput::MouseUp(mouse_up)
9121 }
9122 PlatformInput::MousePressure(mouse_pressure) => {
9123 PlatformInput::MousePressure(mouse_pressure)
9124 }
9125 PlatformInput::MouseExited(mouse_exited) => {
9126 self.modifiers = mouse_exited.modifiers;
9127 PlatformInput::MouseExited(mouse_exited)
9128 }
9129 PlatformInput::ModifiersChanged(modifiers_changed) => {
9130 self.modifiers = modifiers_changed.modifiers;
9131 self.capslock = modifiers_changed.capslock;
9132 PlatformInput::ModifiersChanged(modifiers_changed)
9133 }
9134 PlatformInput::Scroll(scroll_wheel) => {
9135 self.mouse_position = scroll_wheel.position;
9136 self.modifiers = scroll_wheel.modifiers;
9137 PlatformInput::Scroll(scroll_wheel)
9138 }
9139 PlatformInput::Pinch(pinch) => {
9140 self.mouse_position = pinch.position;
9141 self.modifiers = pinch.modifiers;
9142 PlatformInput::Pinch(pinch)
9143 }
9144 PlatformInput::FileDrop(file_drop) => match file_drop {
9147 FileDropEvent::Entered { position, paths } => {
9148 self.mouse_position = position;
9149 let source_window = self.handle.window_id();
9150 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
9151 cx.active_drag = Some(AnyDrag {
9152 value: Arc::new(paths.clone()),
9153 view: cx.new(|_| paths).into(),
9154 cursor_offset: position,
9155 cursor_style: None,
9156 external_payload_source: None,
9157 });
9158 }
9159 PlatformInput::MouseMove(MouseMoveEvent {
9160 position,
9161 pressed_button: Some(MouseButton::Left),
9162 modifiers: Modifiers::default(),
9163 })
9164 }
9165 FileDropEvent::Pending { position } => {
9166 self.mouse_position = position;
9167 PlatformInput::MouseMove(MouseMoveEvent {
9168 position,
9169 pressed_button: Some(MouseButton::Left),
9170 modifiers: Modifiers::default(),
9171 })
9172 }
9173 FileDropEvent::Submit { position } => {
9174 cx.activate(true);
9175 self.mouse_position = position;
9176 PlatformInput::MouseUp(MouseUpEvent {
9177 button: MouseButton::Left,
9178 position,
9179 modifiers: Modifiers::default(),
9180 click_count: 1,
9181 })
9182 }
9183 FileDropEvent::Exited => {
9184 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
9185 cx.active_drag.take();
9186 }
9187 self.refresh();
9188 PlatformInput::FileDrop(FileDropEvent::Exited)
9189 }
9190 FileDropEvent::Ended => {
9191 cx.end_platform_drag(self.handle.window_id());
9192 self.refresh();
9193 PlatformInput::FileDrop(FileDropEvent::Ended)
9194 }
9195 },
9196 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
9197 PlatformInput::LongPress(long_press) => {
9198 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
9199 long_press.start_position
9200 } else {
9201 long_press.position
9202 };
9203 if long_press.phase == crate::TouchPhase::Started {
9204 self.long_press_capture = None;
9205 }
9206 PlatformInput::LongPress(long_press)
9207 }
9208 PlatformInput::TouchDrag(touch_drag) => {
9209 self.mouse_position = touch_drag.start_position;
9210 PlatformInput::TouchDrag(touch_drag)
9211 }
9212 PlatformInput::BackGesture(back) => {
9213 self.mouse_position = back.start_position;
9214 PlatformInput::BackGesture(back)
9215 }
9216 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
9217 };
9218
9219 if let Some(any_mouse_event) = event.mouse_event() {
9220 self.dispatch_mouse_event(any_mouse_event, cx);
9221 } else if let Some(any_key_event) = event.keyboard_event() {
9222 self.dispatch_key_event(any_key_event, cx);
9223 } else if let Some(touch_event) = event.touch_event() {
9224 self.dispatch_touch_event(touch_event, cx);
9225 }
9226 if let PlatformInput::LongPress(long_press) = &event {
9227 match long_press.phase {
9228 crate::TouchPhase::Started if !self.default_prevented => {
9229 self.long_press_capture = None;
9230 }
9231 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
9232 self.long_press_capture = None;
9233 }
9234 crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
9235 }
9236 }
9237
9238 self.promote_external_drag_to_platform(&event, cx);
9241
9242 if pointer_leaves && std::mem::replace(&mut self.pointer_inside, false) {
9245 self.refresh();
9246 }
9247 self.vn_effect_pointer
9248 .update(was_inside, self.pointer_inside, pointer_moved, cx);
9249
9250 let caused_invalidation = self.invalidator.update_count() > update_count_before;
9251 if caused_invalidation {
9252 self.input_rate_tracker.borrow_mut().record_input();
9253 }
9254 #[cfg(feature = "profiler")]
9255 self.window_profiler.end_input(caused_invalidation);
9256
9257 DispatchEventResult {
9258 propagate: cx.propagate_event,
9259 default_prevented: self.default_prevented,
9260 }
9261 }
9262
9263 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
9264 let PlatformInput::MouseMove(mouse_move) = event else {
9265 return;
9266 };
9267 if mouse_move.pressed_button != Some(MouseButton::Left) {
9268 return;
9269 }
9270 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
9271 return;
9272 }
9273 if !self.platform_window.can_start_external_drag() {
9274 return;
9275 }
9276 let Some(payload_source) = cx
9277 .active_drag
9278 .as_mut()
9279 .and_then(|drag| drag.external_payload_source.take())
9280 else {
9281 return;
9282 };
9283 let Some(payload) = payload_source(self, cx) else {
9284 return;
9285 };
9286 if self.platform_window.start_external_drag(&payload)
9287 && cx.hand_active_drag_to_platform(self.handle.window_id())
9288 {
9289 self.refresh();
9290 }
9291 }
9292
9293 pub fn touch_prediction_enabled(&self) -> bool {
9297 self.touch_prediction_enabled
9298 }
9299
9300 pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
9304 self.touch_prediction_enabled = enabled;
9305 }
9306
9307 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
9311 let mut event = event.clone();
9312 if !self.touch_prediction_enabled {
9313 event.predicted_position = None;
9314 }
9315 let recognized_gestures = self.touch_gestures.handle_event(&event);
9316 if event.phase == crate::TouchPhase::Started
9317 && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
9318 {
9319 self.dispatch_recognized_touch_gesture(touch_drag, cx);
9320 }
9321 if event.phase == crate::TouchPhase::Started
9322 && self.touch_gestures.pending_long_press().is_some()
9323 {
9324 self.long_press_capture = None;
9325 }
9326 let mut tapped = false;
9327 for gesture in recognized_gestures {
9328 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
9329 self.dispatch_recognized_touch_gesture(gesture, cx);
9330 }
9331 if event.phase == crate::TouchPhase::Started {
9332 self.schedule_long_press_timer(cx);
9333 } else if self.touch_gestures.pending_long_press().is_none() {
9334 self.long_press_timer.take();
9335 }
9336 if tapped && self.invalidator.is_dirty() {
9342 self.draw(cx).clear(cx);
9343 }
9344 if self.touch_gestures.has_momentum() {
9345 self.schedule_touch_momentum_tick();
9346 }
9347 }
9348
9349 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
9350 match gesture {
9351 RecognizedTouchGesture::Scroll(scroll_wheel) => {
9352 self.mouse_position = scroll_wheel.position;
9353 cx.propagate_event = true;
9354 self.dispatch_mouse_event(&scroll_wheel, cx);
9355 }
9356 RecognizedTouchGesture::Tap { down, up } => {
9357 self.mouse_position = up.position;
9358 cx.propagate_event = true;
9359 self.dispatch_mouse_event(&down, cx);
9360 cx.propagate_event = true;
9361 self.dispatch_mouse_event(&up, cx);
9362 }
9363 RecognizedTouchGesture::TouchDrag(touch_drag) => {
9364 self.mouse_position = touch_drag.start_position;
9365 cx.propagate_event = true;
9366 self.default_prevented = false;
9367 let started = touch_drag.phase == crate::TouchPhase::Started;
9368 self.dispatch_mouse_event(&touch_drag, cx);
9369 if started {
9370 self.touch_gestures
9371 .resolve_touch_drag(self.default_prevented);
9372 }
9373 }
9374 RecognizedTouchGesture::LongPress(long_press) => {
9375 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
9376 long_press.start_position
9377 } else {
9378 long_press.position
9379 };
9380 cx.propagate_event = true;
9381 self.default_prevented = false;
9382 let started = long_press.phase == crate::TouchPhase::Started;
9383 let ended = matches!(
9384 long_press.phase,
9385 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
9386 );
9387 self.dispatch_mouse_event(&long_press, cx);
9388 if started {
9389 let claimed = self.default_prevented;
9390 self.touch_gestures.resolve_long_press(claimed);
9391 if !claimed {
9392 self.long_press_capture = None;
9393 }
9394 }
9395 if ended {
9396 self.long_press_capture = None;
9397 }
9398 }
9399 }
9400 }
9401
9402 fn schedule_long_press_timer(&mut self, cx: &mut App) {
9403 self.long_press_timer.take();
9404 let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
9405 return;
9406 };
9407 self.long_press_timer = Some(self.spawn(cx, async move |cx| {
9408 cx.background_executor.timer(duration).await;
9409 cx.update(move |window, cx| {
9410 window.long_press_timer.take();
9411 if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
9412 window.dispatch_recognized_touch_gesture(gesture, cx);
9413 }
9414 })
9415 .with_context(|| {
9416 format!(
9417 "handling long-press timer for window {:?}",
9418 cx.window_handle().window_id()
9419 )
9420 })
9421 .log_err();
9422 }));
9423 }
9424
9425 fn schedule_touch_momentum_tick(&mut self) {
9426 self.on_next_frame(|window, cx| {
9427 if let Some(gesture) = window.touch_gestures.tick_momentum() {
9428 window.dispatch_recognized_touch_gesture(gesture, cx);
9429 }
9430 if window.touch_gestures.has_momentum() {
9431 window.schedule_touch_momentum_tick();
9432 }
9433 });
9434 }
9435
9436 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
9437 self.mouse_hit_test = self.rendered_frame.hit_test(self.mouse_position(), self.scale_factor);
9438
9439 if let Some(refiner) = self.vn_hit_refiner.clone() {
9442 let kind = if event.is::<crate::MouseDownEvent>() {
9443 Some(VnHitKind::Down)
9444 } else if event.is::<MouseUpEvent>() {
9445 Some(VnHitKind::Up)
9446 } else if event.is::<crate::ScrollEvent>() {
9447 Some(VnHitKind::Scroll)
9448 } else {
9449 None
9450 };
9451 if let Some(kind) = kind {
9452 let position = self.mouse_position();
9453 refiner(kind, position, self, cx);
9454 }
9455 }
9456
9457 #[cfg(any(feature = "inspector", debug_assertions))]
9458 if self.is_inspector_picking(cx) {
9459 self.reset_cursor_style(cx);
9460 self.handle_inspector_mouse_event(event, cx);
9461 return;
9463 }
9464
9465 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
9466
9467 for listener in &mut mouse_listeners {
9470 let listener = listener.as_mut().unwrap();
9471 listener(event, DispatchPhase::Capture, self, cx);
9472 if !cx.propagate_event {
9473 break;
9474 }
9475 }
9476
9477 if cx.propagate_event {
9479 for listener in mouse_listeners.iter_mut().rev() {
9480 let listener = listener.as_mut().unwrap();
9481 listener(event, DispatchPhase::Bubble, self, cx);
9482 if !cx.propagate_event {
9483 break;
9484 }
9485 }
9486 }
9487
9488 self.rendered_frame.mouse_listeners = mouse_listeners;
9489
9490 if cx.has_active_drag() {
9491 if event.is::<MouseMoveEvent>() {
9492 self.refresh();
9495 } else if event.is::<MouseUpEvent>() {
9496 cx.active_drag = None;
9499 self.refresh();
9500 }
9501 }
9502
9503 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
9505 self.captured_hitbox = None;
9506 }
9507
9508 self.reset_cursor_style(cx);
9511 }
9512
9513 fn input_preference(&mut self, event: &dyn Any, cx: &mut App) -> InputPreference {
9516 let prefer_character_input = event
9517 .downcast_ref::<KeyDownEvent>()
9518 .is_some_and(|key_down_event| key_down_event.prefer_character_input);
9519 if !prefer_character_input {
9520 return InputPreference::KeyBindings;
9521 }
9522 let Some(mut input_handler) = self.platform_window.take_input_handler() else {
9523 return InputPreference::KeyBindings;
9524 };
9525 let accepts_text_input = input_handler.accepts_text_input(self, cx);
9526 self.platform_window.set_input_handler(input_handler);
9527 if accepts_text_input {
9528 InputPreference::CharacterInput
9529 } else {
9530 InputPreference::KeyBindings
9531 }
9532 }
9533
9534 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
9535 if self.invalidator.is_dirty() {
9536 self.draw(cx).clear(cx);
9537 }
9538 self.vn_key_event_seq = self.vn_key_event_seq.wrapping_add(1);
9540
9541 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
9542 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
9543
9544 let mut keystroke: Option<Keystroke> = None;
9545
9546 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
9547 if event.modifiers.number_of_modifiers() == 0
9548 && self.pending_modifier.modifiers.number_of_modifiers() == 1
9549 && !self.pending_modifier.saw_other_input
9550 {
9551 let key = match self.pending_modifier.modifiers {
9552 modifiers if modifiers.shift => Some("shift"),
9553 modifiers if modifiers.control => Some("control"),
9554 modifiers if modifiers.alt => Some("alt"),
9555 modifiers if modifiers.platform => Some("platform"),
9556 modifiers if modifiers.function => Some("function"),
9557 _ => None,
9558 };
9559 if let Some(key) = key {
9560 keystroke = Some(Keystroke {
9561 key: key.to_string(),
9562 key_char: None,
9563 modifiers: Modifiers::default(),
9564 });
9565 }
9566 }
9567
9568 if self.pending_modifier.modifiers.number_of_modifiers() == 0
9569 && event.modifiers.number_of_modifiers() == 1
9570 {
9571 self.pending_modifier.saw_other_input = false
9572 } else if event.modifiers.number_of_modifiers() > 1 {
9573 self.pending_modifier.saw_other_input = true
9574 }
9575 self.pending_modifier.modifiers = event.modifiers
9576 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
9577 self.pending_modifier.saw_other_input = true;
9578 keystroke = Some(key_down_event.keystroke.clone());
9579 if key_down_event.keystroke.key_char.is_some()
9580 && matches!(
9581 cx.cursor_hide_mode,
9582 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
9583 )
9584 {
9585 cx.platform.hide_cursor_until_mouse_moves();
9586 }
9587 }
9588
9589 let Some(keystroke) = keystroke else {
9590 self.finish_dispatch_key_event(
9591 event,
9592 None,
9593 InputPreference::KeyBindings,
9594 dispatch_path,
9595 self.context_stack(),
9596 cx,
9597 );
9598 return;
9599 };
9600
9601 let input_preference = self.input_preference(event, cx);
9602
9603 cx.propagate_event = true;
9604 self.dispatch_keystroke_interceptors(
9605 &keystroke,
9606 input_preference,
9607 self.context_stack(),
9608 cx,
9609 );
9610 if !cx.propagate_event {
9611 self.finish_dispatch_key_event(
9612 event,
9613 Some(&keystroke),
9614 input_preference,
9615 dispatch_path,
9616 self.context_stack(),
9617 cx,
9618 );
9619 return;
9620 }
9621
9622 let mut currently_pending = self.pending_input.take().unwrap_or_default();
9623 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
9624 currently_pending = PendingInput::default();
9625 }
9626
9627 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
9628 currently_pending.keystrokes,
9629 keystroke.clone(),
9630 &dispatch_path,
9631 );
9632
9633 if !match_result.to_replay.is_empty() {
9634 self.replay_pending_input(match_result.to_replay, cx);
9635 cx.propagate_event = true;
9636 }
9637
9638 if !match_result.pending.is_empty() {
9639 let previous_timeout = currently_pending.timeout.take();
9640 currently_pending.keystrokes = match_result.pending;
9641 currently_pending.focus = self.focus;
9642
9643 let text_input_requires_timeout = event
9644 .downcast_ref::<KeyDownEvent>()
9645 .filter(|key_down| key_down.keystroke.key_char.is_some())
9646 .and_then(|_| self.platform_window.take_input_handler())
9647 .map_or(false, |mut input_handler| {
9648 let accepts = input_handler.accepts_text_input(self, cx);
9649 self.platform_window.set_input_handler(input_handler);
9650 accepts
9651 });
9652
9653 let standalone_modifier = matches!(currently_pending.keystrokes.as_slice(), [keystroke] if keystroke.is_modifier_key());
9654 let needs_timeout = previous_timeout.is_some()
9655 || match_result.pending_has_binding
9656 || text_input_requires_timeout
9657 || standalone_modifier;
9658 currently_pending.timeout = if needs_timeout {
9659 match previous_timeout {
9660 Some(mut timeout) if timeout.is_paused() => {
9661 timeout.reset_duration(PENDING_INPUT_TIMEOUT);
9662 Some(timeout)
9663 }
9664 previous_timeout => {
9665 drop(previous_timeout);
9666 Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
9667 }
9668 }
9669 } else {
9670 None
9671 };
9672 self.pending_input = Some(currently_pending);
9673 self.pending_input_changed(cx);
9674 cx.propagate_event = false;
9675 return;
9676 }
9677
9678 let input_preference = self.input_preference(event, cx);
9680 if input_preference == InputPreference::KeyBindings {
9681 for binding in match_result.bindings {
9682 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
9683 if !cx.propagate_event {
9684 self.dispatch_keystroke_observers(
9685 &keystroke,
9686 input_preference,
9687 Some(binding.action.as_ref()),
9688 match_result.context_stack,
9689 cx,
9690 );
9691 self.pending_input_changed(cx);
9692 return;
9693 }
9694 }
9695 }
9696
9697 self.finish_dispatch_key_event(
9698 event,
9699 Some(&keystroke),
9700 input_preference,
9701 dispatch_path,
9702 match_result.context_stack,
9703 cx,
9704 );
9705 self.pending_input_changed(cx);
9706 }
9707
9708 fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
9709 let (started_at, task) = self.start_pending_input_timeout(duration, cx);
9710 PendingInputTimeout {
9711 duration,
9712 remaining: duration,
9713 state: PendingInputTimeoutState::Running { started_at, task },
9714 }
9715 }
9716
9717 fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
9718 let started_at = cx.background_executor().now();
9719 let task = self.spawn(cx, async move |cx| {
9720 cx.background_executor.timer(remaining).await;
9721 cx.update(move |window, cx| {
9722 let Some(currently_pending) = window
9723 .pending_input
9724 .take()
9725 .filter(|pending| pending.focus == window.focus)
9726 else {
9727 return;
9728 };
9729
9730 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
9731 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
9732
9733 let to_replay = window
9734 .rendered_frame
9735 .dispatch_tree
9736 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
9737
9738 window.pending_input_changed(cx);
9739 window.replay_pending_input(to_replay, cx)
9740 })
9741 .with_context(|| {
9742 format!(
9743 "handling pending input timeout for window {:?}",
9744 cx.window_handle().window_id()
9745 )
9746 })
9747 .log_err();
9748 });
9749 (started_at, task)
9750 }
9751
9752 fn finish_dispatch_key_event(
9753 &mut self,
9754 event: &dyn Any,
9755 recognized_keystroke: Option<&Keystroke>,
9756 input_preference: InputPreference,
9757 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
9758 context_stack: Vec<KeyContext>,
9759 cx: &mut App,
9760 ) {
9761 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
9762 if !cx.propagate_event {
9763 return;
9764 }
9765
9766 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
9767 if !cx.propagate_event {
9768 return;
9769 }
9770
9771 if let Some(keystroke) = recognized_keystroke {
9772 self.dispatch_keystroke_observers(keystroke, input_preference, None, context_stack, cx);
9773 }
9774 }
9775
9776 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
9777 self.pending_input_observers
9778 .clone()
9779 .retain(|callback| callback(self, cx));
9780 }
9781
9782 fn defer_pending_input_changed(&self, cx: &mut App) {
9783 let window_handle = self.handle;
9786 cx.defer(move |cx| {
9787 window_handle
9788 .update(cx, |_, window, cx| {
9789 window.pending_input_changed(cx);
9790 })
9791 .ok();
9792 });
9793 }
9794
9795 fn dispatch_key_down_up_event(
9796 &mut self,
9797 event: &dyn Any,
9798 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
9799 cx: &mut App,
9800 ) {
9801 for node_id in dispatch_path {
9803 let node = self.rendered_frame.dispatch_tree.node(*node_id);
9804
9805 for key_listener in node.key_listeners.clone() {
9806 key_listener(event, DispatchPhase::Capture, self, cx);
9807 if !cx.propagate_event {
9808 return;
9809 }
9810 }
9811 }
9812
9813 for node_id in dispatch_path.iter().rev() {
9815 let node = self.rendered_frame.dispatch_tree.node(*node_id);
9817 for key_listener in node.key_listeners.clone() {
9818 key_listener(event, DispatchPhase::Bubble, self, cx);
9819 if !cx.propagate_event {
9820 return;
9821 }
9822 }
9823 }
9824 }
9825
9826 fn dispatch_modifiers_changed_event(
9827 &mut self,
9828 event: &dyn Any,
9829 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
9830 cx: &mut App,
9831 ) {
9832 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
9833 return;
9834 };
9835 for node_id in dispatch_path.iter().rev() {
9836 let node = self.rendered_frame.dispatch_tree.node(*node_id);
9837 for listener in node.modifiers_changed_listeners.clone() {
9838 listener(event, self, cx);
9839 if !cx.propagate_event {
9840 return;
9841 }
9842 }
9843 }
9844 }
9845
9846 pub fn has_pending_keystrokes(&self) -> bool {
9848 self.pending_input().is_some()
9849 }
9850
9851 #[cfg(test)]
9852 pub(crate) fn pending_input_is_none(&self) -> bool {
9853 self.pending_input.is_none()
9854 }
9855
9856 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
9857 if self.pending_input.take().is_some() {
9858 self.defer_pending_input_changed(cx);
9859 }
9860 }
9861
9862 pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
9865 self.pending_input
9866 .as_ref()
9867 .filter(|pending_input| pending_input.focus == self.focus)
9868 .map(|pending_input| PendingInputStatus {
9869 keystrokes: pending_input.keystrokes.as_slice(),
9870 timeout: pending_input
9871 .timeout
9872 .as_ref()
9873 .map(PendingInputTimeout::status),
9874 })
9875 }
9876
9877 pub fn set_pending_input_timeout_paused<T: 'static>(
9882 &mut self,
9883 owner: &Entity<T>,
9884 paused: bool,
9885 cx: &mut App,
9886 ) -> bool {
9887 let owner_id = owner.entity_id();
9888 if !paused {
9889 return self.resume_pending_input_timeout(owner_id, cx);
9890 }
9891
9892 let timeout = self
9893 .pending_input
9894 .as_ref()
9895 .filter(|pending_input| pending_input.focus == self.focus)
9896 .and_then(|pending_input| pending_input.timeout.as_ref());
9897 let Some(timeout) = timeout else {
9898 return false;
9899 };
9900 if timeout.is_paused() {
9901 return false;
9902 }
9903
9904 let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
9905 window.resume_pending_input_timeout(owner_id, cx);
9906 });
9907 let now = cx.background_executor().now();
9908 let changed = self
9909 .pending_input
9910 .as_mut()
9911 .filter(|pending_input| pending_input.focus == self.focus)
9912 .and_then(|pending_input| pending_input.timeout.as_mut())
9913 .is_some_and(|timeout| {
9914 timeout.pause(
9915 PendingInputTimeoutPause {
9916 owner_id,
9917 _release_subscription: release_subscription,
9918 },
9919 now,
9920 )
9921 });
9922
9923 if changed {
9924 self.defer_pending_input_changed(cx);
9925 }
9926 changed
9927 }
9928
9929 fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
9930 let Some(remaining) = self
9931 .pending_input
9932 .as_ref()
9933 .and_then(|pending_input| pending_input.timeout.as_ref())
9934 .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
9935 .map(|timeout| timeout.remaining)
9936 else {
9937 return false;
9938 };
9939
9940 let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
9941 let changed = self
9942 .pending_input
9943 .as_mut()
9944 .and_then(|pending_input| pending_input.timeout.as_mut())
9945 .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
9946
9947 if changed {
9948 self.defer_pending_input_changed(cx);
9949 }
9950 changed
9951 }
9952
9953 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
9955 self.pending_input()
9956 .map(|pending_input| pending_input.keystrokes())
9957 }
9958
9959 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
9960 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
9961 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
9962
9963 'replay: for replay in replays {
9964 let event = KeyDownEvent {
9965 keystroke: replay.keystroke.clone(),
9966 is_held: false,
9967 prefer_character_input: true,
9968 };
9969
9970 cx.propagate_event = true;
9971 for binding in replay.bindings {
9972 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
9973 if !cx.propagate_event {
9974 self.dispatch_keystroke_observers(
9975 &replay.keystroke,
9976 InputPreference::KeyBindings,
9977 Some(binding.action.as_ref()),
9978 Vec::default(),
9979 cx,
9980 );
9981 continue 'replay;
9982 }
9983 }
9984
9985 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
9986 if !cx.propagate_event {
9987 continue 'replay;
9988 }
9989 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
9990 && let Some(mut input_handler) = self.platform_window.take_input_handler()
9991 {
9992 input_handler.dispatch_input(&input, self, cx);
9993 self.platform_window.set_input_handler(input_handler)
9994 }
9995 }
9996 }
9997
9998 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
9999 focus_id
10000 .and_then(|focus_id| {
10001 self.rendered_frame
10002 .dispatch_tree
10003 .focusable_node_id(focus_id)
10004 })
10005 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
10006 }
10007
10008 fn dispatch_action_on_node(
10009 &mut self,
10010 node_id: DispatchNodeId,
10011 action: &dyn Action,
10012 cx: &mut App,
10013 ) {
10014 self.dispatch_action_on_node_inner(node_id, action, cx);
10015
10016 if !cx.propagate_event
10017 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
10018 && self.last_input_was_keyboard()
10019 {
10020 cx.platform.hide_cursor_until_mouse_moves();
10021 }
10022 }
10023
10024 fn dispatch_action_on_node_inner(
10025 &mut self,
10026 node_id: DispatchNodeId,
10027 action: &dyn Action,
10028 cx: &mut App,
10029 ) {
10030 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
10031
10032 cx.propagate_event = true;
10034 if let Some(mut global_listeners) = cx
10035 .global_action_listeners
10036 .remove(&action.as_any().type_id())
10037 {
10038 for listener in &global_listeners {
10039 #[cfg(feature = "profiler")]
10040 self.window_profiler.begin_action_handler(action, cx);
10041 listener(action.as_any(), DispatchPhase::Capture, cx);
10042 #[cfg(feature = "profiler")]
10043 self.window_profiler.end_action_handler();
10044 if !cx.propagate_event {
10045 break;
10046 }
10047 }
10048
10049 global_listeners.extend(
10050 cx.global_action_listeners
10051 .remove(&action.as_any().type_id())
10052 .unwrap_or_default(),
10053 );
10054
10055 cx.global_action_listeners
10056 .insert(action.as_any().type_id(), global_listeners);
10057 }
10058
10059 if !cx.propagate_event {
10060 return;
10061 }
10062
10063 for node_id in &dispatch_path {
10065 let node = self.rendered_frame.dispatch_tree.node(*node_id);
10066 for DispatchActionListener {
10067 action_type,
10068 listener,
10069 } in node.action_listeners.clone()
10070 {
10071 let any_action = action.as_any();
10072 if action_type == any_action.type_id() {
10073 #[cfg(feature = "profiler")]
10074 self.window_profiler.begin_action_handler(action, cx);
10075 listener(any_action, DispatchPhase::Capture, self, cx);
10076 #[cfg(feature = "profiler")]
10077 self.window_profiler.end_action_handler();
10078
10079 if !cx.propagate_event {
10080 return;
10081 }
10082 }
10083 }
10084 }
10085
10086 for node_id in dispatch_path.iter().rev() {
10088 let node = self.rendered_frame.dispatch_tree.node(*node_id);
10089 for DispatchActionListener {
10090 action_type,
10091 listener,
10092 } in node.action_listeners.clone()
10093 {
10094 let any_action = action.as_any();
10095 if action_type == any_action.type_id() {
10096 cx.propagate_event = false; #[cfg(feature = "profiler")]
10098 self.window_profiler.begin_action_handler(action, cx);
10099 listener(any_action, DispatchPhase::Bubble, self, cx);
10100 #[cfg(feature = "profiler")]
10101 self.window_profiler.end_action_handler();
10102
10103 if !cx.propagate_event {
10104 return;
10105 }
10106 }
10107 }
10108 }
10109
10110 if let Some(mut global_listeners) = cx
10112 .global_action_listeners
10113 .remove(&action.as_any().type_id())
10114 {
10115 for listener in global_listeners.iter().rev() {
10116 cx.propagate_event = false; #[cfg(feature = "profiler")]
10119 self.window_profiler.begin_action_handler(action, cx);
10120 listener(action.as_any(), DispatchPhase::Bubble, cx);
10121 #[cfg(feature = "profiler")]
10122 self.window_profiler.end_action_handler();
10123 if !cx.propagate_event {
10124 break;
10125 }
10126 }
10127
10128 global_listeners.extend(
10129 cx.global_action_listeners
10130 .remove(&action.as_any().type_id())
10131 .unwrap_or_default(),
10132 );
10133
10134 cx.global_action_listeners
10135 .insert(action.as_any().type_id(), global_listeners);
10136 }
10137 }
10138
10139 pub fn observe_global<G: Global>(
10142 &mut self,
10143 cx: &mut App,
10144 f: impl Fn(&mut Window, &mut App) + 'static,
10145 ) -> Subscription {
10146 let window_handle = self.handle;
10147 let (subscription, activate) = cx.global_observers.insert_pending(
10148 TypeId::of::<G>(),
10149 Box::new(move |cx| {
10150 window_handle
10151 .update(cx, |_, window, cx| f(window, cx))
10152 .is_ok()
10153 }),
10154 );
10155 cx.defer(move |_| activate());
10156 subscription
10157 }
10158
10159 pub fn activate_window(&self) {
10161 self.platform_window.activate();
10162 }
10163
10164 pub fn show_window(
10167 &self,
10168 activate: bool,
10169 should_show: impl FnOnce() -> bool + 'static,
10170 completed: impl FnOnce(bool) + 'static,
10171 ) -> bool {
10172 self.platform_window.show_window(activate, Box::new(should_show), Box::new(completed))
10173 }
10174
10175 pub fn request_attention(&self) {
10177 self.platform_window.request_attention();
10178 }
10179
10180 pub fn minimize_window(&self) {
10182 self.platform_window.minimize();
10183 }
10184
10185 pub fn toggle_fullscreen(&self) {
10187 self.platform_window.toggle_fullscreen();
10188 }
10189
10190 pub fn toggle_simple_fullscreen(&self) {
10195 self.platform_window.toggle_simple_fullscreen();
10196 }
10197
10198 pub fn invalidate_character_coordinates(&self) {
10200 self.on_next_frame(|window, cx| {
10201 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
10202 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
10203 window.platform_window.update_ime_position(bounds);
10204 }
10205 window.platform_window.set_input_handler(input_handler);
10206 }
10207 });
10208 }
10209
10210 pub fn prompt<T>(
10214 &mut self,
10215 level: PromptLevel,
10216 message: &str,
10217 detail: Option<&str>,
10218 answers: &[T],
10219 cx: &mut App,
10220 ) -> oneshot::Receiver<usize>
10221 where
10222 T: Clone + Into<PromptButton>,
10223 {
10224 let prompt_builder = cx.prompt_builder.take();
10225 let Some(prompt_builder) = prompt_builder else {
10226 unreachable!("Re-entrant window prompting is not supported by GPUI");
10227 };
10228
10229 let answers = answers
10230 .iter()
10231 .map(|answer| answer.clone().into())
10232 .collect::<Vec<_>>();
10233
10234 let receiver = match &prompt_builder {
10235 PromptBuilder::Default => self
10236 .platform_window
10237 .prompt(level, message, detail, &answers)
10238 .unwrap_or_else(|| {
10239 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
10240 }),
10241 PromptBuilder::Custom(_) => {
10242 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
10243 }
10244 };
10245
10246 cx.prompt_builder = Some(prompt_builder);
10247
10248 receiver
10249 }
10250
10251 fn build_custom_prompt(
10252 &mut self,
10253 prompt_builder: &PromptBuilder,
10254 level: PromptLevel,
10255 message: &str,
10256 detail: Option<&str>,
10257 answers: &[PromptButton],
10258 cx: &mut App,
10259 ) -> oneshot::Receiver<usize> {
10260 let (sender, receiver) = oneshot::channel();
10261 let handle = PromptHandle::new(sender);
10262 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
10263 self.prompt = Some(handle);
10264 receiver
10265 }
10266
10267 pub fn has_active_prompt(&self) -> bool {
10272 self.prompt.is_some()
10273 }
10274
10275 pub fn context_stack(&self) -> Vec<KeyContext> {
10277 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10278 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10279 dispatch_tree
10280 .dispatch_path(node_id)
10281 .iter()
10282 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
10283 .collect()
10284 }
10285
10286 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
10288 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
10289 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
10290 for action_type in cx.global_action_listeners.keys() {
10291 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
10292 let action = cx.actions.build_action_type(action_type).ok();
10293 if let Some(action) = action {
10294 actions.insert(ix, action);
10295 }
10296 }
10297 }
10298 actions
10299 }
10300
10301 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
10304 self.rendered_frame
10305 .dispatch_tree
10306 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
10307 }
10308
10309 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
10312 self.rendered_frame
10313 .dispatch_tree
10314 .highest_precedence_binding_for_action(
10315 action,
10316 &self.rendered_frame.dispatch_tree.context_stack,
10317 )
10318 }
10319
10320 pub fn bindings_for_action_in_context(
10322 &self,
10323 action: &dyn Action,
10324 context: KeyContext,
10325 ) -> Vec<KeyBinding> {
10326 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10327 dispatch_tree.bindings_for_action(action, &[context])
10328 }
10329
10330 pub fn highest_precedence_binding_for_action_in_context(
10333 &self,
10334 action: &dyn Action,
10335 context: KeyContext,
10336 ) -> Option<KeyBinding> {
10337 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10338 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
10339 }
10340
10341 pub fn bindings_for_action_in(
10345 &self,
10346 action: &dyn Action,
10347 focus_handle: &FocusHandle,
10348 ) -> Vec<KeyBinding> {
10349 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10350 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
10351 return vec![];
10352 };
10353 dispatch_tree.bindings_for_action(action, &context_stack)
10354 }
10355
10356 pub fn highest_precedence_binding_for_action_in(
10360 &self,
10361 action: &dyn Action,
10362 focus_handle: &FocusHandle,
10363 ) -> Option<KeyBinding> {
10364 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10365 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
10366 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
10367 }
10368
10369 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
10371 self.rendered_frame
10372 .dispatch_tree
10373 .possible_next_bindings_for_input(input, &self.context_stack())
10374 }
10375
10376 fn context_stack_for_focus_handle(
10377 &self,
10378 focus_handle: &FocusHandle,
10379 ) -> Option<Vec<KeyContext>> {
10380 let dispatch_tree = &self.rendered_frame.dispatch_tree;
10381 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
10382 let context_stack: Vec<_> = dispatch_tree
10383 .dispatch_path(node_id)
10384 .into_iter()
10385 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
10386 .collect();
10387 Some(context_stack)
10388 }
10389
10390 pub fn listener_for<T: 'static, E>(
10392 &self,
10393 view: &Entity<T>,
10394 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
10395 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
10396 let view = view.downgrade();
10397 move |e: &E, window: &mut Window, cx: &mut App| {
10398 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
10399 }
10400 }
10401
10402 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
10404 &self,
10405 entity: &Entity<E>,
10406 f: Callback,
10407 ) -> impl Fn(&mut Window, &mut App) + 'static {
10408 let entity = entity.downgrade();
10409 move |window: &mut Window, cx: &mut App| {
10410 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
10411 }
10412 }
10413
10414 pub fn on_window_should_close(
10417 &self,
10418 cx: &App,
10419 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
10420 ) {
10421 let mut cx = self.to_async(cx);
10422 self.platform_window.on_should_close(Box::new(move || {
10423 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
10424 }))
10425 }
10426
10427 pub fn on_action(
10436 &mut self,
10437 action_type: TypeId,
10438 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
10439 ) {
10440 self.invalidator.debug_assert_paint();
10441
10442 self.next_frame
10443 .dispatch_tree
10444 .on_action(action_type, Rc::new(listener));
10445 }
10446
10447 pub fn on_action_when(
10456 &mut self,
10457 condition: bool,
10458 action_type: TypeId,
10459 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
10460 ) {
10461 self.invalidator.debug_assert_paint();
10462
10463 if condition {
10464 self.next_frame
10465 .dispatch_tree
10466 .on_action(action_type, Rc::new(listener));
10467 }
10468 }
10469
10470 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
10473 self.platform_window.gpu_specs()
10474 }
10475
10476 pub fn titlebar_double_click(&self) {
10479 self.platform_window
10480 .titlebar_double_click(self.is_resizable, self.is_minimizable);
10481 }
10482
10483 pub fn window_title(&self) -> String {
10486 self.platform_window.get_title()
10487 }
10488
10489 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
10492 self.platform_window.tabbed_windows()
10493 }
10494
10495 pub fn tab_bar_visible(&self) -> bool {
10498 self.platform_window.tab_bar_visible()
10499 }
10500
10501 pub fn merge_all_windows(&self) {
10504 self.platform_window.merge_all_windows()
10505 }
10506
10507 pub fn move_tab_to_new_window(&self) {
10510 self.platform_window.move_tab_to_new_window()
10511 }
10512
10513 pub fn toggle_window_tab_overview(&self) {
10516 self.platform_window.toggle_window_tab_overview()
10517 }
10518
10519 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
10522 self.platform_window
10523 .set_tabbing_identifier(tabbing_identifier)
10524 }
10525
10526 pub fn play_system_bell(&self) {
10529 self.platform_window.play_system_bell()
10530 }
10531
10532 pub fn is_a11y_enabled(&self) -> bool {
10539 self.a11y.is_enabled()
10540 }
10541
10542 pub fn is_a11y_active(&self) -> bool {
10553 self.a11y.is_active()
10554 }
10555
10556 pub fn debug_a11y_tree_json(&self) -> Option<String> {
10558 self.a11y.debug_tree_json()
10559 }
10560
10561 pub fn on_a11y_action(
10567 &mut self,
10568 node_id: accesskit::NodeId,
10569 action: accesskit::Action,
10570 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
10571 ) {
10572 self.a11y
10573 .action_listeners
10574 .entry(node_id)
10575 .or_default()
10576 .push((action, Box::new(listener)));
10577 }
10578
10579 #[cfg(not(target_family = "wasm"))]
10580 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
10581 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
10584 let extra_data = request.data.as_ref();
10585 let mut matched = false;
10586 for (action, listener) in &mut listeners {
10587 if *action == request.action {
10588 listener(extra_data, self, cx);
10589 matched = true;
10590 }
10591 }
10592 self.a11y
10593 .action_listeners
10594 .insert(request.target_node, listeners);
10595 if matched {
10596 return;
10597 }
10598 }
10599
10600 match request.action {
10602 accesskit::Action::Click => {
10603 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
10604 let center = bounds.center();
10605 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
10606 button: MouseButton::Left,
10607 position: center,
10608 modifiers: Modifiers::default(),
10609 click_count: 1,
10610 first_mouse: false,
10611 });
10612 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
10613 button: MouseButton::Left,
10614 position: center,
10615 modifiers: Modifiers::default(),
10616 click_count: 1,
10617 });
10618 self.dispatch_event(mouse_down, cx);
10619 self.dispatch_event(mouse_up, cx);
10620 }
10621 }
10622 accesskit::Action::Focus => {
10623 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
10624 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
10625 {
10626 self.focus(&handle, cx);
10627 }
10628 }
10629 accesskit::Action::Blur => {
10630 self.blur(cx);
10631 }
10632 _ => {
10633 log::debug!(
10634 "Unhandled a11y action: {:?} on {:?}",
10635 request.action,
10636 request.target_node
10637 );
10638 }
10639 }
10640 }
10641
10642 #[cfg(any(feature = "inspector", debug_assertions))]
10644 pub fn toggle_inspector(&mut self, cx: &mut App) {
10645 self.inspector = match self.inspector {
10646 None => Some(cx.new(|_| Inspector::new())),
10647 Some(_) => {
10648 self.rendered_frame.next_inspector_instance_ids = FxHashMap::default();
10649 self.rendered_frame.inspector_hitboxes = FxHashMap::default();
10650 self.next_frame.next_inspector_instance_ids = FxHashMap::default();
10651 self.next_frame.inspector_hitboxes = FxHashMap::default();
10652 None
10653 }
10654 };
10655 self.refresh();
10656 }
10657
10658 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
10660 #[cfg(any(feature = "inspector", debug_assertions))]
10661 {
10662 if let Some(inspector) = &self.inspector {
10663 return inspector.read(_cx).is_picking();
10664 }
10665 }
10666 false
10667 }
10668
10669 #[cfg(any(feature = "inspector", debug_assertions))]
10671 pub fn with_inspector_state<T: 'static, R>(
10672 &mut self,
10673 inspector_id: Option<&crate::InspectorElementId>,
10674 cx: &mut App,
10675 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
10676 ) -> Option<R> {
10677 let inspector_id = inspector_id?;
10678 let inspector = self.inspector.as_ref()?;
10679 if inspector.read(cx).active_element_id() != Some(inspector_id) {
10680 return None;
10681 }
10682 let inspector = inspector.clone();
10683 Some(inspector.update(cx, |inspector, _cx| {
10684 inspector.with_active_element_state(self, f)
10685 }))
10686 }
10687
10688 #[cfg(any(feature = "inspector", debug_assertions))]
10689 pub(crate) fn inspector_enabled(&self) -> bool {
10690 self.inspector.is_some()
10691 }
10692
10693 #[cfg(any(feature = "inspector", debug_assertions))]
10694 pub(crate) fn build_inspector_element_id(
10695 &mut self,
10696 path: crate::InspectorElementPath,
10697 ) -> crate::InspectorElementId {
10698 self.invalidator.debug_assert_paint_or_prepaint();
10699 let path = Rc::new(path);
10700 let next_instance_id = self
10701 .next_frame
10702 .next_inspector_instance_ids
10703 .entry(path.clone())
10704 .or_insert(0);
10705 let instance_id = *next_instance_id;
10706 *next_instance_id += 1;
10707 crate::InspectorElementId { path, instance_id }
10708 }
10709
10710 #[cfg(any(feature = "inspector", debug_assertions))]
10711 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
10712 if let Some(inspector) = self.inspector.take() {
10713 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
10714 inspector_element.prepaint_as_root(
10715 point(self.viewport_size.width - inspector_width, px(0.0)),
10716 size(inspector_width, self.viewport_size.height).into(),
10717 self,
10718 cx,
10719 );
10720 self.inspector = Some(inspector);
10721 Some(inspector_element)
10722 } else {
10723 None
10724 }
10725 }
10726
10727 #[cfg(any(feature = "inspector", debug_assertions))]
10728 fn paint_inspector(&mut self, inspector_element: Option<AnyElement>, cx: &mut App) {
10729 if let Some(mut inspector_element) = inspector_element {
10730 inspector_element.paint(self, cx);
10731 };
10732 }
10733
10734 #[cfg(any(feature = "inspector", debug_assertions))]
10737 pub fn insert_inspector_hitbox(
10738 &mut self,
10739 hitbox_id: HitboxId,
10740 inspector_id: Option<&crate::InspectorElementId>,
10741 cx: &App,
10742 ) {
10743 self.invalidator.debug_assert_paint_or_prepaint();
10744 if !self.is_inspector_picking(cx) {
10745 return;
10746 }
10747 if let Some(inspector_id) = inspector_id {
10748 self.next_frame
10749 .inspector_hitboxes
10750 .insert(hitbox_id, inspector_id.clone());
10751 }
10752 }
10753
10754 #[cfg(any(feature = "inspector", debug_assertions))]
10755 fn paint_inspector_hitbox(&mut self, cx: &App) {
10756 if let Some(inspector) = self.inspector.as_ref() {
10757 let inspector = inspector.read(cx);
10758 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
10759 && let Some(hitbox) = self
10760 .next_frame
10761 .hitboxes
10762 .iter()
10763 .find(|hitbox| hitbox.id == hitbox_id)
10764 {
10765 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
10766 }
10767 }
10768 }
10769
10770 #[cfg(any(feature = "inspector", debug_assertions))]
10771 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
10772 let Some(inspector) = self.inspector.clone() else {
10773 return;
10774 };
10775 if event.downcast_ref::<MouseMoveEvent>().is_some() {
10776 inspector.update(cx, |inspector, _cx| {
10777 if let Some((_, inspector_id)) =
10778 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10779 {
10780 inspector.hover(inspector_id, self);
10781 }
10782 });
10783 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
10784 inspector.update(cx, |inspector, _cx| {
10785 if let Some((_, inspector_id)) =
10786 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10787 {
10788 inspector.select(inspector_id, self);
10789 }
10790 });
10791 } else if let Some(event) = event.downcast_ref::<crate::ScrollEvent>() {
10792 const SCROLL_LINES: f32 = 3.0;
10794 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
10795 let delta_y = event
10796 .delta
10797 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
10798 .y;
10799 if let Some(inspector) = self.inspector.clone() {
10800 inspector.update(cx, |inspector, _cx| {
10801 if let Some(depth) = inspector.pick_depth.as_mut() {
10802 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
10803 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
10804 if *depth < 0.0 {
10805 *depth = 0.0;
10806 } else if *depth > max_depth {
10807 *depth = max_depth;
10808 }
10809 if let Some((_, inspector_id)) =
10810 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
10811 {
10812 inspector.set_active_element_id(inspector_id, self);
10813 }
10814 }
10815 });
10816 }
10817 }
10818 }
10819
10820 #[cfg(any(feature = "inspector", debug_assertions))]
10821 fn hovered_inspector_hitbox(
10822 &self,
10823 inspector: &Inspector,
10824 frame: &Frame,
10825 ) -> Option<(HitboxId, crate::InspectorElementId)> {
10826 if let Some(pick_depth) = inspector.pick_depth {
10827 let depth = (pick_depth as i64).try_into().unwrap_or(0);
10828 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
10829 let skip_count = (depth as usize).min(max_skipped);
10830 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
10831 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
10832 return Some((*hitbox_id, inspector_id.clone()));
10833 }
10834 }
10835 }
10836 None
10837 }
10838
10839 #[cfg(any(test, feature = "test-support"))]
10842 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
10843 self.modifiers = modifiers;
10844 }
10845
10846 #[cfg(any(test, feature = "test-support"))]
10850 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
10851 let event = PlatformInput::MouseMove(MouseMoveEvent {
10852 position,
10853 modifiers: self.modifiers,
10854 pressed_button: None,
10855 });
10856 let _ = self.dispatch_event(event, cx);
10857 }
10858
10859 #[inline(never)]
10860 fn take_element_state(
10861 &mut self,
10862 global_id: &GlobalElementId,
10863 state_type: TypeId,
10864 ) -> ((GlobalElementId, TypeId), Option<ElementStateBox>) {
10865 let key = (global_id.clone(), state_type);
10866 self.next_frame.accessed_element_states.push(key.clone());
10867 let state = self
10868 .next_frame
10869 .element_states
10870 .remove(&key)
10871 .or_else(|| self.rendered_frame.element_states.remove(&key));
10872 (key, state)
10873 }
10874
10875 #[inline(never)]
10876 fn insert_element_state(
10877 &mut self,
10878 key: (GlobalElementId, TypeId),
10879 state: ElementStateBox,
10880 ) -> Option<ElementStateBox> {
10881 self.next_frame.element_states.insert(key, state)
10882 }
10883
10884 #[inline(never)]
10885 fn observe_keyed_state<S: 'static>(state: &Entity<S>, current_view: EntityId, cx: &mut App) {
10886 cx.observe(state, move |_, cx| {
10887 cx.notify(current_view);
10888 })
10889 .detach();
10890 }
10891}
10892
10893slotmap::new_key_type! {
10895 pub struct WindowId;
10897}
10898
10899impl WindowId {
10900 pub fn as_u64(&self) -> u64 {
10902 self.0.as_ffi()
10903 }
10904}
10905
10906impl From<u64> for WindowId {
10907 fn from(value: u64) -> Self {
10908 WindowId(slotmap::KeyData::from_ffi(value))
10909 }
10910}
10911
10912pub struct WindowHandle<V> {
10915 pub(crate) any_handle: AnyWindowHandle,
10916 state_type: PhantomData<fn(V) -> V>,
10917}
10918
10919impl_deref!([V] WindowHandle<V> => mut any_handle: AnyWindowHandle);
10920
10921impl<V> Debug for WindowHandle<V> {
10922 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
10923 f.debug_struct("WindowHandle")
10924 .field("any_handle", &self.any_handle.id.as_u64())
10925 .finish()
10926 }
10927}
10928
10929impl<V: 'static + Render> WindowHandle<V> {
10930 pub fn new(id: WindowId) -> Self {
10933 WindowHandle {
10934 any_handle: AnyWindowHandle {
10935 id,
10936 state_type: TypeId::of::<V>(),
10937 root_entity_type_name: std::any::type_name::<V>(),
10938 },
10939 state_type: PhantomData,
10940 }
10941 }
10942
10943 #[cfg(any(test, feature = "test-support"))]
10947 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
10948 where
10949 C: AppContext,
10950 {
10951 cx.update_window(self.any_handle, |root_view, _, _| {
10952 root_view
10953 .downcast::<V>()
10954 .map_err(|_| anyhow!("the type of the window's root view has changed"))
10955 })?
10956 }
10957
10958 #[track_caller]
10962 pub fn update<C, R>(
10963 &self,
10964 cx: &mut C,
10965 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
10966 ) -> Result<R>
10967 where
10968 C: AppContext,
10969 {
10970 cx.update_window(self.any_handle, |root_view, window, cx| {
10971 let view = root_view
10972 .downcast::<V>()
10973 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
10974
10975 Ok(view.update(cx, |view, cx| update(view, window, cx)))
10976 })?
10977 }
10978
10979 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
10983 let x = cx
10984 .windows
10985 .get(self.id)
10986 .and_then(|window| {
10987 window
10988 .as_deref()
10989 .and_then(|window| window.root.clone())
10990 .map(|root_view| root_view.downcast::<V>())
10991 })
10992 .context("window not found")?
10993 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
10994
10995 Ok(x.read(cx))
10996 }
10997
10998 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
11002 where
11003 C: AppContext,
11004 {
11005 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
11006 }
11007
11008 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
11012 where
11013 C: AppContext,
11014 {
11015 cx.read_window(self, |root_view, _cx| root_view)
11016 }
11017
11018 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
11023 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
11024 .ok()
11025 }
11026}
11027
11028impl<V> Copy for WindowHandle<V> {}
11029
11030impl<V> Clone for WindowHandle<V> {
11031 fn clone(&self) -> Self {
11032 *self
11033 }
11034}
11035
11036impl<V> PartialEq for WindowHandle<V> {
11037 fn eq(&self, other: &Self) -> bool {
11038 self.any_handle == other.any_handle
11039 }
11040}
11041
11042impl<V> Eq for WindowHandle<V> {}
11043
11044impl<V> Hash for WindowHandle<V> {
11045 fn hash<H: Hasher>(&self, state: &mut H) {
11046 self.any_handle.hash(state);
11047 }
11048}
11049
11050impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
11051 fn from(val: WindowHandle<V>) -> Self {
11052 val.any_handle
11053 }
11054}
11055
11056#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
11058pub struct AnyWindowHandle {
11059 pub(crate) id: WindowId,
11060 state_type: TypeId,
11061 root_entity_type_name: &'static str,
11062}
11063
11064impl AnyWindowHandle {
11065 pub fn window_id(&self) -> WindowId {
11067 self.id
11068 }
11069
11070 pub fn root_entity_type_name(&self) -> &'static str {
11072 self.root_entity_type_name
11073 }
11074
11075 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
11078 if TypeId::of::<T>() == self.state_type {
11079 Some(WindowHandle {
11080 any_handle: *self,
11081 state_type: PhantomData,
11082 })
11083 } else {
11084 None
11085 }
11086 }
11087
11088 #[track_caller]
11092 pub fn update<C, R>(
11093 self,
11094 cx: &mut C,
11095 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
11096 ) -> Result<R>
11097 where
11098 C: AppContext,
11099 {
11100 cx.update_window(self, update)
11101 }
11102
11103 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
11107 where
11108 C: AppContext,
11109 T: 'static,
11110 {
11111 let view = self
11112 .downcast::<T>()
11113 .context("the type of the window's root view has changed")?;
11114
11115 cx.read_window(&view, read)
11116 }
11117}
11118
11119impl HasWindowHandle for Window {
11120 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
11121 self.platform_window.window_handle()
11122 }
11123}
11124
11125impl HasDisplayHandle for Window {
11126 fn display_handle(
11127 &self,
11128 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
11129 self.platform_window.display_handle()
11130 }
11131}
11132
11133#[derive(Clone, Debug, Eq, PartialEq, Hash)]
11138pub enum ElementId {
11139 View(EntityId),
11141 Integer(u64),
11143 Name(SharedString),
11145 Uuid(Uuid),
11147 FocusHandle(FocusId),
11149 NamedInteger(SharedString, u64),
11151 Path(Arc<std::path::Path>),
11153 CodeLocation(core::panic::Location<'static>),
11155 NamedChild(Arc<ElementId>, SharedString),
11157 OpaqueId([u8; 20]),
11159}
11160
11161impl ElementId {
11162 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
11164 Self::NamedInteger(name.into(), integer as u64)
11165 }
11166}
11167
11168impl Display for ElementId {
11169 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
11170 match self {
11171 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
11172 ElementId::Integer(ix) => write!(f, "{}", ix)?,
11173 ElementId::Name(name) => write!(f, "{}", name)?,
11174 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
11175 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
11176 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
11177 ElementId::Path(path) => write!(f, "{}", path.display())?,
11178 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
11179 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
11180 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
11181 }
11182
11183 Ok(())
11184 }
11185}
11186
11187impl TryInto<SharedString> for ElementId {
11188 type Error = anyhow::Error;
11189
11190 fn try_into(self) -> anyhow::Result<SharedString> {
11191 if let ElementId::Name(name) = self {
11192 Ok(name)
11193 } else {
11194 anyhow::bail!("element id is not string")
11195 }
11196 }
11197}
11198
11199impl From<u64> for ElementId {
11200 fn from(id: u64) -> Self {
11201 ElementId::Integer(id)
11202 }
11203}
11204
11205impl From<usize> for ElementId {
11206 fn from(id: usize) -> Self {
11207 ElementId::Integer(id as u64)
11208 }
11209}
11210
11211impl From<i32> for ElementId {
11212 fn from(id: i32) -> Self {
11213 Self::Integer(id as u64)
11214 }
11215}
11216
11217impl From<SharedString> for ElementId {
11218 fn from(name: SharedString) -> Self {
11219 ElementId::Name(name)
11220 }
11221}
11222
11223impl From<String> for ElementId {
11224 fn from(name: String) -> Self {
11225 ElementId::Name(name.into())
11226 }
11227}
11228
11229impl From<Arc<str>> for ElementId {
11230 fn from(name: Arc<str>) -> Self {
11231 ElementId::Name(name.into())
11232 }
11233}
11234
11235impl From<Arc<std::path::Path>> for ElementId {
11236 fn from(path: Arc<std::path::Path>) -> Self {
11237 ElementId::Path(path)
11238 }
11239}
11240
11241impl From<&'static str> for ElementId {
11242 fn from(name: &'static str) -> Self {
11243 ElementId::Name(SharedString::new_static(name))
11244 }
11245}
11246
11247impl<'a> From<&'a FocusHandle> for ElementId {
11248 fn from(handle: &'a FocusHandle) -> Self {
11249 ElementId::FocusHandle(handle.id)
11250 }
11251}
11252
11253impl From<(&'static str, EntityId)> for ElementId {
11254 fn from((name, id): (&'static str, EntityId)) -> Self {
11255 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
11256 }
11257}
11258
11259impl From<(&'static str, usize)> for ElementId {
11260 fn from((name, id): (&'static str, usize)) -> Self {
11261 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
11262 }
11263}
11264
11265impl From<(SharedString, usize)> for ElementId {
11266 fn from((name, id): (SharedString, usize)) -> Self {
11267 ElementId::NamedInteger(name, id as u64)
11268 }
11269}
11270
11271impl From<(&'static str, u64)> for ElementId {
11272 fn from((name, id): (&'static str, u64)) -> Self {
11273 ElementId::NamedInteger(SharedString::new_static(name), id)
11274 }
11275}
11276
11277impl From<Uuid> for ElementId {
11278 fn from(value: Uuid) -> Self {
11279 Self::Uuid(value)
11280 }
11281}
11282
11283impl From<(&'static str, u32)> for ElementId {
11284 fn from((name, id): (&'static str, u32)) -> Self {
11285 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
11286 }
11287}
11288
11289impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
11290 fn from((id, name): (ElementId, T)) -> Self {
11291 ElementId::NamedChild(Arc::new(id), name.into())
11292 }
11293}
11294
11295impl From<&'static core::panic::Location<'static>> for ElementId {
11296 fn from(location: &'static core::panic::Location<'static>) -> Self {
11297 ElementId::CodeLocation(*location)
11298 }
11299}
11300
11301impl From<[u8; 20]> for ElementId {
11302 fn from(opaque_id: [u8; 20]) -> Self {
11303 ElementId::OpaqueId(opaque_id)
11304 }
11305}
11306
11307#[derive(Clone)]
11310pub struct PaintQuad {
11311 pub bounds: Bounds<Pixels>,
11313 pub corner_radii: Corners<Pixels>,
11315 pub background: Background,
11317 pub border_widths: Edges<Pixels>,
11319 pub border_color: Hsla,
11321 pub border_style: BorderStyle,
11323 pub corner_shapes: Corners<CornerShape>,
11325}
11326
11327#[derive(Clone, Copy, Debug)]
11329pub struct BackdropBlurEffect {
11330 pub radius: Pixels,
11336 pub tint: Hsla,
11342}
11343
11344impl BackdropBlurEffect {
11345 pub fn new(radius: Pixels) -> Self {
11349 Self {
11350 radius,
11351 ..Self::default()
11352 }
11353 }
11354
11355 pub fn tint(mut self, tint: impl Into<Hsla>) -> Self {
11357 self.tint = tint.into();
11358 self
11359 }
11360}
11361
11362impl Default for BackdropBlurEffect {
11363 fn default() -> Self {
11364 Self {
11365 radius: px(20.),
11366 tint: transparent_black(),
11367 }
11368 }
11369}
11370
11371impl PaintQuad {
11372 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
11374 PaintQuad {
11375 corner_radii: corner_radii.into(),
11376 ..self
11377 }
11378 }
11379
11380 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
11382 PaintQuad {
11383 border_widths: border_widths.into(),
11384 ..self
11385 }
11386 }
11387
11388 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
11390 PaintQuad {
11391 border_color: border_color.into(),
11392 ..self
11393 }
11394 }
11395
11396 pub fn background(self, background: impl Into<Background>) -> Self {
11398 PaintQuad {
11399 background: background.into(),
11400 ..self
11401 }
11402 }
11403
11404 pub fn corner_shapes(self, corner_shapes: Corners<CornerShape>) -> Self {
11406 PaintQuad {
11407 corner_shapes,
11408 ..self
11409 }
11410 }
11411}
11412
11413pub type ImageResampler =
11424 fn(&Arc<RenderImage>, usize, Size<DevicePixels>) -> Option<Arc<RenderImage>>;
11425
11426static IMAGE_RESAMPLER: std::sync::OnceLock<ImageResampler> = std::sync::OnceLock::new();
11427
11428pub fn set_image_resampler(resampler: ImageResampler) {
11431 let _ = IMAGE_RESAMPLER.set(resampler);
11432}
11433
11434pub fn quad(
11436 bounds: Bounds<Pixels>,
11437 corner_radii: impl Into<Corners<Pixels>>,
11438 background: impl Into<Background>,
11439 border_widths: impl Into<Edges<Pixels>>,
11440 border_color: impl Into<Hsla>,
11441 border_style: BorderStyle,
11442) -> PaintQuad {
11443 PaintQuad {
11444 bounds,
11445 corner_radii: corner_radii.into(),
11446 background: background.into(),
11447 border_widths: border_widths.into(),
11448 border_color: border_color.into(),
11449 border_style,
11450 corner_shapes: Corners::default(),
11451 }
11452}
11453
11454pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
11456 PaintQuad {
11457 bounds: bounds.into(),
11458 corner_radii: (0.).into(),
11459 background: background.into(),
11460 border_widths: (0.).into(),
11461 border_color: transparent_black(),
11462 border_style: BorderStyle::default(),
11463 corner_shapes: Corners::default(),
11464 }
11465}
11466
11467pub fn outline(
11469 bounds: impl Into<Bounds<Pixels>>,
11470 border_color: impl Into<Hsla>,
11471 border_style: BorderStyle,
11472) -> PaintQuad {
11473 PaintQuad {
11474 bounds: bounds.into(),
11475 corner_radii: (0.).into(),
11476 background: transparent_black().into(),
11477 border_widths: (1.).into(),
11478 border_color: border_color.into(),
11479 border_style,
11480 corner_shapes: Corners::default(),
11481 }
11482}
11483
11484pub(crate) const SHADOW_OUTSIDE_BOX: u32 = 0;
11487pub(crate) const SHADOW_INSET: u32 = 1;
11489pub(crate) const SHADOW_UNDER_BOX: u32 = 2;
11492
11493fn spread_shadow_radius(radius: Pixels, spread: Pixels) -> Pixels {
11499 if spread <= Pixels::ZERO {
11500 return (radius + spread).max(Pixels::ZERO);
11501 }
11502 let ratio = radius / spread;
11503 if ratio >= 1.0 {
11504 radius + spread
11505 } else {
11506 radius + spread * (1.0 + (ratio - 1.0).powi(3))
11507 }
11508}
11509
11510#[inline(never)]
11511fn with_element_arena_erased(callback: &mut dyn FnMut(&mut Arena)) -> Result<(), AccessError> {
11512 if let Some(arena_pointer) = CURRENT_ELEMENT_ARENA.try_with(Cell::get)? {
11513 let arena_cell = unsafe { &*arena_pointer };
11516 callback(&mut arena_cell.borrow_mut());
11517 Ok(())
11518 } else {
11519 ELEMENT_ARENA.try_with(|arena| callback(&mut arena.borrow_mut()))
11520 }
11521}
11522
11523#[cfg(test)]
11524mod tests {
11525 use std::{
11526 cell::{Cell, RefCell},
11527 path::PathBuf,
11528 rc::Rc,
11529 time::Duration,
11530 };
11531
11532 use crate::{
11533 AnyWindowHandle, AppContext as _, BackGestureEvent, BackGesturePhase, Bounds, ContentMask,
11534 Context, CursorStyle, DispatchPhase, DragMoveEvent, Empty, ExternalDragPayload,
11535 ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle, InputEvent as _,
11536 InteractiveElement as _, IntoElement, KeyDownEvent, Keystroke, LongPressEvent, MouseButton,
11537 MouseDownEvent, MouseMoveEvent, MouseUpEvent, ParentElement, Pixels, PlatformInput, Point,
11538 Render, RequestFrameOptions, ScaledPixels, StatefulInteractiveElement as _, Styled,
11539 TestAppContext, ThermalState, TouchDragEvent, TouchEvent, TouchId, TouchPhase, Underline,
11540 UnderlineStyle, Window, WindowAppearance, WindowOptions, canvas, div, hsla, point, px,
11541 size,
11542 };
11543
11544 #[gpui::test]
11545 async fn test_focus_handle_release(cx: &mut TestAppContext) {
11546 let (handle, survivor) = cx.update(|cx| (cx.focus_handle(), cx.focus_handle()));
11547 let handle_id = handle.id;
11548 let weak_handle = handle.downgrade();
11549 let retained = handle.clone();
11550 drop(handle);
11551
11552 cx.update(|_| {});
11553 cx.read(|cx| {
11554 let handles = cx.focus_handles.read();
11555 assert_eq!(handles.handles.len(), 2);
11556 assert!(handles.dropped_handles.is_empty());
11557 });
11558 assert_eq!(weak_handle.upgrade().as_ref(), Some(&retained));
11559
11560 cx.background_spawn(async move { drop(retained) }).await;
11561 assert_eq!(weak_handle.upgrade(), None);
11562 cx.read(|cx| {
11563 assert_eq!(cx.focus_handles.read().dropped_handles, [handle_id]);
11564 });
11565 cx.update(|_| {});
11566 cx.read(|cx| {
11567 let handles = cx.focus_handles.read();
11568 assert_eq!(handles.handles.keys().collect::<Vec<_>>(), [survivor.id]);
11569 assert!(handles.dropped_handles.is_empty());
11570 });
11571
11572 let replacements = cx.update(|cx| [cx.focus_handle(), cx.focus_handle()]);
11573 assert_eq!(weak_handle.upgrade(), None);
11574 cx.update(|cx| {
11575 drop(replacements);
11576 cx.defer(move |_| drop(survivor));
11577 });
11578 cx.read(|cx| {
11579 let handles = cx.focus_handles.read();
11580 assert_eq!(handles.handles.len(), 0);
11581 assert!(handles.dropped_handles.is_empty());
11582 });
11583 }
11584
11585 #[gpui::test]
11586 fn test_dropped_focus_handle_blurs_only_its_windows(cx: &mut TestAppContext) {
11587 let windows = [
11588 cx.add_window(|_, _| EmptyView),
11589 cx.add_window(|_, _| EmptyView),
11590 cx.add_window(|_, _| EmptyView),
11591 cx.add_window(|_, _| EmptyView),
11592 cx.add_window(|_, _| EmptyView),
11593 ];
11594 let (handle, other_handle, survivor) =
11595 cx.update(|cx| (cx.focus_handle(), cx.focus_handle(), cx.focus_handle()));
11596 for window in &windows[..2] {
11597 window
11598 .update(cx, |_, window, cx| window.focus(&handle, cx))
11599 .expect("window exists");
11600 }
11601 windows[2]
11602 .update(cx, |_, window, cx| window.focus(&other_handle, cx))
11603 .expect("window exists");
11604 windows[3]
11605 .update(cx, |_, window, cx| window.focus(&survivor, cx))
11606 .expect("window exists");
11607
11608 cx.update(|cx| {
11609 for _ in 0..1_000 {
11610 drop(cx.focus_handle());
11611 }
11612 drop((handle, other_handle));
11613 });
11614 for window in &windows[..3] {
11615 window
11616 .update(cx, |_, window, _| assert_eq!(window.focus, None))
11617 .expect("window exists");
11618 }
11619 windows[3]
11620 .update(cx, |_, window, cx| {
11621 assert_eq!(window.focused(cx).as_ref(), Some(&survivor));
11622 assert_eq!(window.focus_generation, 1);
11623 })
11624 .expect("window exists");
11625 windows[4]
11626 .update(cx, |_, window, _| {
11627 assert_eq!(window.focus, None);
11628 assert_eq!(window.focus_generation, 0);
11629 })
11630 .expect("window exists");
11631 }
11632
11633 #[gpui::test]
11634 fn test_native_close_defers_app_access(cx: &mut TestAppContext) {
11635 let window = cx.add_window(|_, _| EmptyView);
11636 let platform_window = cx.test_window(window.into());
11637 {
11638 let app = cx.app.borrow_mut();
11639 platform_window.simulate_close();
11640 assert!(app.windows.contains_key(window.window_id()));
11641 }
11642 cx.run_until_parked();
11643 assert!(!cx.app.borrow().windows.contains_key(window.window_id()));
11644 }
11645
11646 #[cfg(feature = "profiler")]
11647 #[gpui::test]
11648 fn test_frame_requests_and_skips_are_journaled(cx: &mut TestAppContext) {
11649 use crate::FrameRequestSource;
11650 use crate::profiler::journal::{
11651 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
11652 };
11653 use scheduler::Instant;
11654
11655 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
11656 let window = cx.add_window(|_, _| EmptyView);
11657 let platform_window = cx.test_window(window.into());
11658 platform_window.simulate_frame_request(RequestFrameOptions::default());
11659 let (journal, _guard) = journal::install_test_foreground_journal(64, 4);
11660 let mut collector = journal.collector();
11661
11662 for (signal_at, source) in [
11663 (Some(Instant::now()), FrameRequestSource::NativeCallback),
11664 (Some(Instant::now()), FrameRequestSource::LocalSchedule),
11665 (None, FrameRequestSource::NativeCallback),
11666 ] {
11667 platform_window.simulate_frame_request(RequestFrameOptions {
11668 signal_at,
11669 signal_source: source,
11670 require_presentation: true,
11671 ..Default::default()
11672 });
11673 let entries = collector.collect_unseen().entries;
11674 let signal_index = entries
11675 .iter()
11676 .position(|entry| {
11677 matches!(
11678 entry,
11679 ForegroundJournalEntry::PlatformSignal(signal)
11680 if signal.window_id == window.window_id()
11681 && signal.signal_at == signal_at
11682 && signal.source == source
11683 && signal_at.is_none_or(|at| signal.handled_at >= at)
11684 )
11685 })
11686 .expect("frame request metadata");
11687 let skip_index = entries
11688 .iter()
11689 .position(|entry| {
11690 matches!(
11691 entry,
11692 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
11693 if skipped.window_id == window.window_id()
11694 && skipped.reason == FrameSkipReason::NoRenderNeeded
11695 )
11696 })
11697 .expect("completed no-render boundary");
11698 assert!(signal_index < skip_index);
11699 }
11700 }
11701
11702 #[cfg(feature = "profiler")]
11703 #[gpui::test]
11704 fn test_frame_demand_survives_throttling(cx: &mut TestAppContext) {
11705 use crate::profiler::journal::{
11706 self, ForegroundJournalEntry, FrameSkipReason, IntervalBoundary,
11707 };
11708 use scheduler::Instant;
11709
11710 cx.app.borrow_mut().mode = crate::app::GpuiMode::Production;
11712 let (journal, _guard) = journal::install_test_foreground_journal(256, 4);
11713 let mut collector = journal.collector();
11714 for (initially_dirty, schedule_callback) in [(true, false), (false, true)] {
11715 let window = cx
11717 .app
11718 .borrow_mut()
11719 .open_window(
11720 WindowOptions {
11721 inactive_frame_interval: Some(Duration::from_secs(3600)),
11722 ..Default::default()
11723 },
11724 |_, cx| cx.new(|_| EmptyView),
11725 )
11726 .expect("open inactive test window");
11727 let platform_window = cx.test_window(window.into());
11728 platform_window.simulate_active_status_change(false);
11729 platform_window.simulate_frame_request(RequestFrameOptions::default());
11730 let callback_ran = Rc::new(Cell::new(false));
11731 let draws_before = window
11732 .update(cx, |_, window, _| {
11733 let draws_before = window
11734 .frame_duration_snapshot()
11735 .draw_duration_histogram
11736 .len();
11737 if initially_dirty {
11738 window.refresh();
11739 }
11740 if schedule_callback {
11741 window.on_next_frame({
11742 let callback_ran = callback_ran.clone();
11743 move |window, _| {
11744 callback_ran.set(true);
11745 window.refresh();
11746 }
11747 });
11748 }
11749 draws_before
11750 })
11751 .expect("schedule throttled frame");
11752 let input_at = Instant::now();
11754 journal::record_input(journal::InputTiming {
11755 kind: "test",
11756 start: input_at,
11757 end: input_at,
11758 caused_invalidation: false,
11759 });
11760 collector.collect_unseen();
11761 let wakes_before = platform_window.frame_wake_count();
11762 platform_window.simulate_frame_request(RequestFrameOptions {
11763 signal_at: Some(Instant::now()),
11764 ..Default::default()
11765 });
11766 window
11767 .update(cx, |_, window, _| {
11768 assert_eq!(
11769 window
11770 .frame_duration_snapshot()
11771 .draw_duration_histogram
11772 .len(),
11773 draws_before,
11774 );
11775 })
11776 .expect("inspect deferred frame");
11777 assert!(!callback_ran.get());
11778 assert!(platform_window.frame_scheduled());
11779 assert!(platform_window.frame_wake_count() > wakes_before);
11780 assert!(collector.collect_unseen().entries.iter().any(|entry| {
11781 matches!(
11782 entry,
11783 ForegroundJournalEntry::Boundary(IntervalBoundary::FrameSkipped(skipped))
11784 if skipped.window_id == window.window_id()
11785 && skipped.reason == FrameSkipReason::InactiveFrameRateLimit
11786 )
11787 }));
11788 platform_window.simulate_frame_request(RequestFrameOptions {
11789 signal_at: Some(Instant::now()),
11790 require_presentation: true,
11791 ..Default::default()
11792 });
11793 window
11794 .update(cx, |_, window, _| {
11795 assert_eq!(
11796 window
11797 .frame_duration_snapshot()
11798 .draw_duration_histogram
11799 .len(),
11800 draws_before + 1,
11801 );
11802 })
11803 .expect("inspect presented frame");
11804 assert_eq!(callback_ran.get(), schedule_callback);
11805 }
11806 }
11807
11808 #[gpui::test]
11811 fn test_debug_state_reports_cached_and_platform_values(cx: &mut TestAppContext) {
11812 use crate::WindowVisibility;
11813
11814 let window = cx.add_window(|_, _| EmptyView);
11815 let window_id = window.window_id().as_u64();
11816 let window_state = |cx: &mut TestAppContext| {
11817 let state = cx.update(|cx| cx.debug_state());
11818 state["windows"]
11819 .as_array()
11820 .and_then(|windows| windows.iter().find(|window| window["id"] == window_id))
11821 .cloned()
11822 .expect("the open window is listed")
11823 };
11824
11825 let state = window_state(cx);
11826 assert_eq!(state["visibility"]["cached"], "Visible");
11827 assert_eq!(state["visibility"]["platform"], "Visible");
11828
11829 cx.test_window(window.into())
11830 .simulate_visibility_change(WindowVisibility::Hidden);
11831 let state = window_state(cx);
11832 assert_eq!(state["visibility"]["cached"], "Hidden");
11833 assert_eq!(state["visibility"]["platform"], "Hidden");
11834 }
11835
11836 #[gpui::test]
11840 fn test_window_visibility(cx: &mut TestAppContext) {
11841 use crate::WindowVisibility;
11842
11843 let window = cx.add_window(|_, _| EmptyView);
11844 let observed = Rc::new(RefCell::new(Vec::new()));
11845 let _subscription = window
11846 .update(cx, {
11847 let observed = observed.clone();
11848 move |_, window, _| {
11849 assert_eq!(window.visibility(), WindowVisibility::Visible);
11850 assert!(window.is_visible());
11851 window.observe_window_visibility(move |visibility, window, _| {
11852 assert_eq!(window.visibility(), visibility);
11853 observed.borrow_mut().push(visibility);
11854 })
11855 }
11856 })
11857 .unwrap();
11858 let test_window = cx.test_window(window.into());
11859 let frame_wake_count = test_window.frame_wake_count();
11860
11861 test_window.simulate_visibility_change(WindowVisibility::Hidden);
11862 assert_eq!(*observed.borrow(), [WindowVisibility::Hidden]);
11863 window
11864 .update(cx, |_, window, _| assert!(!window.is_visible()))
11865 .unwrap();
11866
11867 test_window.simulate_visibility_change(WindowVisibility::Hidden);
11869 assert_eq!(observed.borrow().len(), 1);
11870
11871 test_window.simulate_visibility_change(WindowVisibility::Visible);
11872 assert_eq!(
11873 *observed.borrow(),
11874 [WindowVisibility::Hidden, WindowVisibility::Visible]
11875 );
11876 window
11877 .update(cx, |_, window, _| assert!(window.is_visible()))
11878 .unwrap();
11879 assert_eq!(test_window.frame_wake_count(), frame_wake_count);
11880 }
11881
11882 #[gpui::test]
11885 fn test_display_tracking(cx: &mut TestAppContext) {
11886 use crate::{DisplayChanges, DisplayEvent, DisplayId, Subscription};
11887
11888 let sixty_hertz = Duration::from_secs(1) / 60;
11889 let one_hundred_twenty_hertz = Duration::from_secs(1) / 120;
11890 let one_hundred_forty_four_hertz = Duration::from_secs(1) / 144;
11891
11892 let display_events = Rc::new(RefCell::new(Vec::new()));
11893 let _display_subscription = cx.update({
11894 let display_events = display_events.clone();
11895 move |cx| cx.observe_displays(move |event, _| display_events.borrow_mut().push(event))
11896 });
11897
11898 let window = cx.add_window(|window, cx| DisplayTracker {
11899 refresh_intervals: Vec::new(),
11900 _subscription: cx.observe_window_display(
11901 window,
11902 |tracker: &mut DisplayTracker, window, cx| {
11903 tracker.refresh_intervals.push(window.refresh_interval(cx));
11904 },
11905 ),
11906 });
11907 let window_notifications = Rc::new(RefCell::new(Vec::new()));
11908 let _window_subscription = window
11909 .update(cx, {
11910 let window_notifications = window_notifications.clone();
11911 move |_, window, cx| {
11912 assert_eq!(window.refresh_interval(cx), Some(sixty_hertz));
11913 window.observe_window_display(move |window, cx| {
11914 window_notifications
11915 .borrow_mut()
11916 .push((window.display_id, window.refresh_interval(cx)));
11917 })
11918 }
11919 })
11920 .unwrap();
11921 let test_window = cx.test_window(window.into());
11922
11923 cx.test_platform()
11928 .connect_display(DisplayId(2), Some(one_hundred_twenty_hertz));
11929 test_window.simulate_move_to_display(DisplayId(2));
11930 assert_eq!(
11931 window_notifications.take(),
11932 [(Some(DisplayId(2)), Some(one_hundred_twenty_hertz))]
11933 );
11934 assert_eq!(display_events.take(), [DisplayEvent::Added(DisplayId(2))]);
11935 cx.simulate_display_refresh_interval_change(DisplayId(2), Some(one_hundred_twenty_hertz));
11936 assert!(window_notifications.borrow().is_empty());
11937
11938 test_window.simulate_move_to_display(DisplayId(2));
11940 assert!(window_notifications.borrow().is_empty());
11941
11942 cx.simulate_display_refresh_interval_change(
11943 DisplayId(2),
11944 Some(one_hundred_forty_four_hertz),
11945 );
11946 assert_eq!(
11947 window_notifications.take(),
11948 [(Some(DisplayId(2)), Some(one_hundred_forty_four_hertz))]
11949 );
11950
11951 cx.simulate_display_refresh_interval_change(DisplayId(1), Some(one_hundred_twenty_hertz));
11953 cx.simulate_display_removed(DisplayId(1));
11954 assert!(window_notifications.borrow().is_empty());
11955
11956 assert_eq!(
11957 display_events.take(),
11958 [
11959 DisplayEvent::Changed {
11960 id: DisplayId(2),
11961 changes: DisplayChanges::REFRESH_INTERVAL,
11962 },
11963 DisplayEvent::Changed {
11964 id: DisplayId(1),
11965 changes: DisplayChanges::REFRESH_INTERVAL,
11966 },
11967 DisplayEvent::Removed(DisplayId(1)),
11968 ]
11969 );
11970 window
11971 .update(cx, |tracker, _, _| {
11972 assert_eq!(
11973 tracker.refresh_intervals,
11974 [
11975 Some(one_hundred_twenty_hertz),
11976 Some(one_hundred_forty_four_hertz)
11977 ]
11978 );
11979 })
11980 .unwrap();
11981
11982 struct DisplayTracker {
11983 refresh_intervals: Vec<Option<Duration>>,
11984 _subscription: Subscription,
11985 }
11986
11987 impl Render for DisplayTracker {
11988 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
11989 Empty
11990 }
11991 }
11992 }
11993
11994 #[gpui::test]
11995 fn test_window_opened_from_bounds_observer_uses_new_bounds(cx: &mut TestAppContext) {
11996 use crate::Subscription;
11997
11998 struct BoundsObserver {
11999 _subscription: Subscription,
12000 }
12001
12002 impl Render for BoundsObserver {
12003 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12004 Empty
12005 }
12006 }
12007
12008 let opened_window = Rc::new(Cell::new(None));
12009 let window = cx.add_window({
12010 let opened_window = opened_window.clone();
12011 move |window, cx| BoundsObserver {
12012 _subscription: cx.observe_window_bounds(window, move |_, _, cx| {
12013 let handle = cx
12014 .open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
12015 .unwrap();
12016 opened_window.set(Some(AnyWindowHandle::from(handle)));
12017 }),
12018 }
12019 });
12020 window
12021 .update(cx, |_, window, _| window.activate_window())
12022 .unwrap();
12023
12024 let new_size = size(px(400.), px(300.));
12025 cx.simulate_window_resize(window.into(), new_size);
12026
12027 let opened_window = opened_window
12028 .take()
12029 .expect("bounds observer should have opened a window");
12030 let opened_size = opened_window
12031 .update(cx, |_, window, _| window.bounds().size)
12032 .unwrap();
12033 assert_eq!(opened_size, new_size);
12034 }
12035
12036 #[gpui::test]
12037 fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) {
12038 let window = cx.add_window(|_, _| EmptyView);
12039 let mut platform_window = cx.test_window(window.into());
12040 platform_window.simulate_resize(size(px(400.), px(800.)));
12041 window
12042 .update(cx, |_, window, _| {
12043 assert_eq!(
12044 window.visual_viewport_bounds(),
12045 Bounds::new(Point::default(), size(px(400.), px(800.)))
12046 );
12047 assert_eq!(
12048 window.fully_visible_bounds(),
12049 window.visual_viewport_bounds()
12050 );
12051 })
12052 .unwrap();
12053
12054 platform_window.simulate_frame_request(RequestFrameOptions::default());
12055 let wakes = platform_window.frame_wake_count();
12056 let visual_bounds = Bounds::new(point(px(10.), px(40.)), size(px(380.), px(460.)));
12057 platform_window.simulate_visual_viewport_change(visual_bounds);
12058 assert!(platform_window.frame_wake_count() > wakes);
12059 platform_window.simulate_frame_request(RequestFrameOptions::default());
12060 let wakes = platform_window.frame_wake_count();
12061 let insets = crate::WindowInsets {
12062 safe_area: crate::Edges {
12063 top: px(60.),
12064 right: px(20.),
12065 bottom: px(30.),
12066 left: px(-10.),
12067 },
12068 ime: crate::Edges {
12069 bottom: px(350.),
12070 ..Default::default()
12071 },
12072 ..Default::default()
12073 };
12074 platform_window.simulate_insets_change(insets.clone());
12075 assert!(platform_window.frame_wake_count() > wakes);
12076 window
12077 .update(cx, |_, window, cx| {
12078 let focus = cx.focus_handle();
12079 window.focus(&focus, cx);
12080 assert_eq!(window.insets(), insets);
12081 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
12082 assert_eq!(window.visual_viewport_bounds(), visual_bounds);
12083 assert_eq!(
12084 window.fully_visible_bounds(),
12085 Bounds::new(point(px(10.), px(60.)), size(px(370.), px(390.)))
12086 );
12087 window.request_virtual_keyboard();
12088 window.dismiss_virtual_keyboard();
12089 assert!(focus.is_focused(window));
12090 assert_eq!(window.viewport_size(), size(px(400.), px(800.)));
12091 })
12092 .unwrap();
12093 assert_eq!(platform_window.virtual_keyboard_requests(), 1);
12094 assert_eq!(platform_window.virtual_keyboard_dismissals(), 1);
12095
12096 platform_window.simulate_insets_change(crate::WindowInsets {
12097 safe_area: crate::Edges {
12098 top: px(900.),
12099 left: px(500.),
12100 ..Default::default()
12101 },
12102 ..Default::default()
12103 });
12104 window
12105 .update(cx, |_, window, _| {
12106 assert_eq!(
12107 window.fully_visible_bounds().size,
12108 size(Pixels::ZERO, Pixels::ZERO)
12109 );
12110 })
12111 .unwrap();
12112
12113 use crate::PlatformWindow as _;
12115 platform_window.on_insets_changed(Box::new(|_| {}));
12116 platform_window.simulate_insets_change(crate::WindowInsets::default());
12117 window
12118 .update(cx, |_, window, _| {
12119 assert_eq!(window.insets(), crate::WindowInsets::default());
12120 })
12121 .unwrap();
12122 }
12123
12124 #[test]
12125 fn frame_throttle_tracks_display_refreshes() {
12126 let start = super::Instant::now();
12127 for (elapsed, interval) in [
12128 (Duration::from_micros(16_666), Duration::from_micros(16_667)),
12129 (Duration::from_micros(33_332), Duration::from_micros(33_333)),
12130 ] {
12131 let mut pacer = super::FramePacer::default();
12132 assert!(!pacer.should_defer(start, Some(interval)));
12133 assert!(pacer.should_defer(start + elapsed / 2, Some(interval)));
12134 assert!(!pacer.should_defer(start + elapsed, Some(interval)));
12135 }
12136 }
12137
12138 #[test]
12139 fn frame_throttle_preserves_cadence_without_catching_up_after_stalls() {
12140 let start = super::Instant::now();
12141 let interval = Duration::from_micros(33_333);
12142 let mut pacer = super::FramePacer::default();
12143 assert!(!pacer.should_defer(start, Some(interval)));
12144 let delayed_frame = start + interval + Duration::from_millis(5);
12145 assert!(!pacer.should_defer(delayed_frame, Some(interval)));
12146 assert!(pacer.should_defer(start + interval + interval / 2, Some(interval)));
12147 assert!(!pacer.should_defer(start + interval * 2, Some(interval)));
12148
12149 let after_stall = start + interval * 4 - Duration::from_millis(1);
12151 assert!(!pacer.should_defer(after_stall, Some(interval)));
12152 assert!(pacer.should_defer(after_stall + interval / 2, Some(interval)));
12153 assert!(!pacer.should_defer(after_stall + interval, Some(interval)));
12154 let mandatory_frame = after_stall + interval + Duration::from_millis(2);
12156 assert!(!pacer.should_defer(mandatory_frame, None));
12157 assert!(pacer.should_defer(mandatory_frame + interval / 2, Some(interval)));
12158 }
12159
12160 #[test]
12161 fn power_modes_preserve_frame_limits() {
12162 let options = WindowOptions::default();
12163 for (power_mode, active_interval, thermal_interval) in [
12164 (
12165 crate::PowerMode::LowPower,
12166 Some(Duration::from_micros(33_333)),
12167 Duration::from_micros(33_333),
12168 ),
12169 (
12170 crate::PowerMode::Unknown,
12171 None,
12172 Duration::from_micros(16_667),
12173 ),
12174 (
12175 crate::PowerMode::Balanced,
12176 None,
12177 Duration::from_micros(16_667),
12178 ),
12179 (
12180 crate::PowerMode::HighPower,
12181 None,
12182 Duration::from_micros(16_667),
12183 ),
12184 ] {
12185 assert_eq!(
12186 super::minimum_frame_interval(
12187 true,
12188 false,
12189 options.inactive_frame_interval,
12190 options.low_power_frame_interval,
12191 options.thermal_frame_interval,
12192 ThermalState::Nominal,
12193 power_mode,
12194 ),
12195 active_interval,
12196 );
12197 assert_eq!(
12198 super::minimum_frame_interval(
12199 true,
12200 false,
12201 options.inactive_frame_interval,
12202 options.low_power_frame_interval,
12203 options.thermal_frame_interval,
12204 ThermalState::Serious,
12205 power_mode,
12206 ),
12207 Some(thermal_interval),
12208 );
12209 }
12210 }
12211
12212 #[test]
12213 fn frame_limits_combine_enabled_intervals() {
12214 let short = Some(Duration::from_millis(10));
12215 let long = Some(Duration::from_millis(100));
12216 for (inactive, low_power, thermal, expected) in [
12217 (long, short, short, long),
12218 (short, long, short, long),
12219 (short, short, long, long),
12220 (long, None, None, long),
12221 (None, long, None, long),
12222 (None, None, long, long),
12223 (None, None, None, None),
12224 ] {
12225 assert_eq!(
12226 super::minimum_frame_interval(
12227 true,
12228 true,
12229 inactive,
12230 low_power,
12231 thermal,
12232 ThermalState::Critical,
12233 crate::PowerMode::LowPower,
12234 ),
12235 expected,
12236 );
12237 }
12238 assert_eq!(
12239 super::minimum_frame_interval(
12240 false,
12241 true,
12242 long,
12243 long,
12244 long,
12245 ThermalState::Critical,
12246 crate::PowerMode::LowPower,
12247 ),
12248 None,
12249 );
12250 }
12251
12252 struct EmptyView;
12253
12254 impl Render for EmptyView {
12255 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
12256 div()
12257 }
12258 }
12259
12260 struct OpensWindowOnPaint {
12261 opened: Rc<Cell<bool>>,
12262 }
12263
12264 impl Render for OpensWindowOnPaint {
12265 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
12266 let opened = self.opened.clone();
12267 div()
12268 .size_full()
12269 .child(canvas(
12270 |_, _, _| {},
12271 move |_, _, _window, cx| {
12272 if !opened.replace(true) {
12273 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
12274 .unwrap();
12275 }
12276 },
12277 ))
12278 .child(div().child("after"))
12282 }
12283 }
12284
12285 #[test]
12291 fn test_window_opened_during_draw_defers_arena_clear() {
12292 let mut cx = TestAppContext::single();
12293
12294 let opened = Rc::new(Cell::new(false));
12295 let window = cx.add_window({
12297 let opened = opened.clone();
12298 move |_, _| OpensWindowOnPaint { opened }
12299 });
12300
12301 assert!(opened.get());
12302 assert_eq!(cx.windows().len(), 2);
12303
12304 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
12307 .unwrap();
12308 }
12309
12310 #[test]
12311 fn test_scale_factor_change_preserves_bounds_and_survives_resize() {
12312 let mut cx = TestAppContext::single();
12313 let window = cx.add_window(|_, _| EmptyView);
12314 let handle: AnyWindowHandle = window.into();
12315 let window_state = |cx: &mut TestAppContext| {
12316 cx.update_window(handle, |_, window, _| {
12317 (
12318 window.scale_factor(),
12319 window.bounds(),
12320 window.viewport_size(),
12321 )
12322 })
12323 .unwrap()
12324 };
12325
12326 let (scale_factor, mut expected_bounds, _) = window_state(&mut cx);
12327 assert_eq!(scale_factor, 2.0);
12328
12329 for (scale_factor, resized_size) in [
12330 (1.0, size(px(800.), px(600.))),
12331 (1.25, size(px(640.), px(480.))),
12332 (2.0, size(px(1024.), px(768.))),
12333 ] {
12334 cx.simulate_window_scale_factor_change(handle, scale_factor);
12335 assert_eq!(
12336 window_state(&mut cx),
12337 (scale_factor, expected_bounds, expected_bounds.size)
12338 );
12339
12340 cx.simulate_window_resize(handle, resized_size);
12341 expected_bounds.size = resized_size;
12342 assert_eq!(
12343 window_state(&mut cx),
12344 (scale_factor, expected_bounds, resized_size)
12345 );
12346 }
12347 }
12348
12349 #[gpui::test]
12350 fn test_fullscreen_toggle_reports_current_bounds(cx: &mut TestAppContext) {
12351 let window = cx.add_window(|_, _| EmptyView);
12352 let handle = AnyWindowHandle::from(window);
12353 let notifications = Rc::new(Cell::new(0));
12354 window
12355 .update(cx, {
12356 let notifications = notifications.clone();
12357 |_, window, cx| {
12358 cx.observe_window_bounds(window, move |_, _, _| {
12359 notifications.set(notifications.get() + 1)
12360 })
12361 .detach();
12362 }
12363 })
12364 .unwrap();
12365 let window_state = |cx: &mut TestAppContext| {
12366 cx.update_window(handle, |_, window, _| {
12367 (
12368 window.is_fullscreen(),
12369 window.bounds().size,
12370 window.viewport_size(),
12371 )
12372 })
12373 .unwrap()
12374 };
12375 let initial_size = window_state(cx).1;
12376
12377 window
12378 .update(cx, |_, window, _| window.toggle_fullscreen())
12379 .unwrap();
12380 cx.run_until_parked();
12381 assert_eq!(window_state(cx), (true, initial_size, initial_size));
12382 assert_eq!(notifications.get(), 1);
12383
12384 let resized_size = size(px(800.), px(600.));
12385 window
12386 .update(cx, |_, window, _| window.toggle_fullscreen())
12387 .unwrap();
12388 cx.simulate_window_resize(handle, resized_size);
12389 cx.run_until_parked();
12390 assert_eq!(window_state(cx), (false, resized_size, resized_size));
12391 }
12392
12393 #[gpui::test]
12398 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
12399 let window = cx.add_window(|_, _| EmptyView);
12400 let test_window = cx.test_window(window.into());
12401 test_window.simulate_active_status_change(true);
12403
12404 assert!(
12408 test_window.frame_wake_count() >= 1,
12409 "opening a window must wake the frame source for the initial frame"
12410 );
12411
12412 test_window.simulate_frame_request(RequestFrameOptions::default());
12414
12415 let baseline = test_window.frame_wake_count();
12418 test_window.simulate_frame_request(RequestFrameOptions::default());
12419 window.update(cx, |_, _, _| {}).unwrap();
12420 assert_eq!(
12421 test_window.frame_wake_count(),
12422 baseline,
12423 "clean frames and non-notifying updates must not wake the frame source"
12424 );
12425
12426 window.update(cx, |_, _, cx| cx.notify()).unwrap();
12428 assert!(
12429 test_window.frame_wake_count() > baseline,
12430 "notifying a view in an idle window must wake the frame source"
12431 );
12432
12433 test_window.simulate_frame_request(RequestFrameOptions::default());
12435 let baseline = test_window.frame_wake_count();
12436 test_window.simulate_frame_request(RequestFrameOptions::default());
12437 assert_eq!(
12438 test_window.frame_wake_count(),
12439 baseline,
12440 "serving demand must return the window to idle"
12441 );
12442
12443 window
12445 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
12446 .unwrap();
12447 assert!(
12448 test_window.frame_wake_count() > baseline,
12449 "scheduling a next-frame callback in an idle window must wake the frame source"
12450 );
12451 }
12452
12453 #[gpui::test]
12456 fn test_passive_next_frame_callbacks_are_not_demand(cx: &mut TestAppContext) {
12457 fn rearm(window: &mut Window, runs: Rc<Cell<usize>>) {
12458 runs.set(runs.get() + 1);
12459 window.on_next_frame_passive(move |window, _| rearm(window, runs));
12460 }
12461 let window = cx.add_window(|_, _| EmptyView);
12462 let test_window = cx.test_window(window.into());
12463 test_window.simulate_frame_request(RequestFrameOptions::default());
12464
12465 let runs = Rc::new(Cell::new(0));
12466 let baseline = test_window.frame_wake_count();
12467 window
12468 .update(cx, {
12469 let runs = runs.clone();
12470 move |_, window, _| window.on_next_frame_passive(move |window, _| rearm(window, runs))
12471 })
12472 .unwrap();
12473 assert_eq!(test_window.frame_wake_count(), baseline, "queueing a passive callback is not demand");
12474
12475 test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
12476 test_window.simulate_frame_request(RequestFrameOptions { require_presentation: true, ..Default::default() });
12477 assert_eq!(runs.get(), 2, "a passive callback runs with every delivered frame");
12478 assert_eq!(test_window.frame_wake_count(), baseline, "a re-arming passive pump never wakes the frame source");
12479
12480 window.update(cx, |_, window, _| window.on_next_frame(|_, _| {})).unwrap();
12482 assert!(test_window.frame_wake_count() > baseline);
12483 }
12484
12485 #[gpui::test]
12490 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
12491 let window = cx.add_window(|_, _| EmptyView);
12492 let test_window = cx.test_window(window.into());
12493 test_window.simulate_frame_request(RequestFrameOptions::default());
12496
12497 let callback_ran = Rc::new(Cell::new(false));
12498 window
12499 .update(cx, {
12500 let callback_ran = callback_ran.clone();
12501 move |_, window, _| {
12502 window.on_next_frame(move |_, _| callback_ran.set(true));
12503 }
12504 })
12505 .unwrap();
12506
12507 let baseline = test_window.frame_wake_count();
12508 test_window.simulate_frame_request(RequestFrameOptions::default());
12509 assert!(
12516 test_window.frame_wake_count() > baseline || callback_ran.get(),
12517 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
12518 );
12519 }
12520
12521 #[gpui::test]
12522 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
12523 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
12524
12525 let window = cx.add_window(|_, _| EmptyView);
12526 window
12527 .update(cx, |_, window, _| {
12528 assert!(matches!(
12529 window.window_handle(),
12530 Err(HandleError::NotSupported)
12531 ));
12532 assert!(matches!(
12533 window.display_handle(),
12534 Err(HandleError::NotSupported)
12535 ));
12536 })
12537 .unwrap();
12538 }
12539
12540 #[gpui::test]
12541 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
12542 let window = cx.add_window(|_, _| EmptyView);
12543 let observed_appearance = Rc::new(Cell::new(None));
12544 let _subscription = window
12545 .update(cx, {
12546 let observed_appearance = observed_appearance.clone();
12547 move |_, window, _| {
12548 window.observe_window_appearance(move |window, _| {
12549 observed_appearance.set(Some(window.appearance()));
12550 })
12551 }
12552 })
12553 .unwrap();
12554 let test_window = cx.test_window(window.into());
12555
12556 cx.update(|_| {
12557 test_window.simulate_appearance_change(WindowAppearance::Dark);
12558 assert_eq!(observed_appearance.get(), None);
12559 });
12560 cx.run_until_parked();
12561
12562 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
12563 }
12564
12565 #[gpui::test]
12566 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
12567 let window = cx.add_window(|_, _| Empty);
12568 let test_window = cx.test_window(window.into());
12569
12570 assert!(test_window.simulate_scheduled_frame());
12571 assert!(test_window.simulate_scheduled_frame());
12572 assert!(!test_window.frame_scheduled());
12573
12574 cx.update_window(window.into(), |_, window, _| {
12575 window.active.set(true);
12576 window.on_next_frame(|_, _| {});
12577 })
12578 .unwrap();
12579 assert!(
12580 test_window.frame_scheduled(),
12581 "queuing work on a parked window must wake the render loop"
12582 );
12583
12584 assert!(test_window.simulate_scheduled_frame());
12585 assert!(
12586 test_window.frame_scheduled(),
12587 "presenting the frame must await one compositor callback"
12588 );
12589 assert!(test_window.simulate_scheduled_frame());
12590 assert!(!test_window.frame_scheduled());
12591 }
12592
12593 #[gpui::test]
12594 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
12595 let window = cx.add_window(|_, _| Empty);
12596 let test_window = cx.test_window(window.into());
12597
12598 assert!(test_window.simulate_scheduled_frame());
12599 assert!(test_window.simulate_scheduled_frame());
12600 assert!(!test_window.frame_scheduled());
12601
12602 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
12603 .unwrap();
12604
12605 assert!(
12606 test_window.frame_scheduled(),
12607 "a rendered scene awaiting presentation must wake the render loop"
12608 );
12609 }
12610
12611 #[gpui::test]
12612 fn reentrant_frame_request_preserves_pending_callbacks(cx: &mut TestAppContext) {
12613 let window = cx.add_window(|_, _| Empty);
12614 let test_window = cx.test_window(window.into());
12615 let callback_count = Rc::new(Cell::new(0));
12616
12617 cx.update_window(window.into(), |_, window, _| {
12618 window.active.set(true);
12619 let callback_count = callback_count.clone();
12620 window.on_next_frame(move |window, _| {
12621 callback_count.set(callback_count.get() + 1);
12622 window.on_next_frame(move |_, _| {
12623 callback_count.set(callback_count.get() + 1);
12624 });
12625 });
12626 })
12627 .unwrap();
12628
12629 let wake_count = test_window.frame_wake_count();
12632 cx.update(|_| {
12633 test_window.simulate_frame_request(RequestFrameOptions::default());
12634 });
12635 assert_eq!(callback_count.get(), 0);
12636 cx.update_window(window.into(), |_, window, _| {
12637 assert_eq!(window.next_frame_callbacks.borrow().len(), 1);
12638 })
12639 .unwrap();
12640 assert!(
12641 test_window.frame_wake_count() > wake_count,
12642 "a deferred frame callback must wake the frame source for a retry"
12643 );
12644
12645 test_window.simulate_frame_request(RequestFrameOptions::default());
12646 assert_eq!(callback_count.get(), 1);
12647 test_window.simulate_frame_request(RequestFrameOptions::default());
12648 assert_eq!(callback_count.get(), 2);
12649 test_window.simulate_frame_request(RequestFrameOptions::default());
12650 assert_eq!(callback_count.get(), 2);
12651 }
12652
12653 #[gpui::test]
12654 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
12655 let window = cx.add_window(|_, _| Empty);
12656 let test_window = cx.test_window(window.into());
12657
12658 let callback_ran = Rc::new(Cell::new(false));
12659 cx.update_window(window.into(), |_, window, _| {
12660 window.active.set(true);
12663 let callback_ran = callback_ran.clone();
12664 window.on_next_frame(move |window, _| {
12665 window.on_next_frame(move |_, _| callback_ran.set(true));
12666 });
12667 })
12668 .unwrap();
12669
12670 assert!(test_window.simulate_scheduled_frame());
12671 assert!(!callback_ran.get());
12672 assert!(
12673 test_window.frame_scheduled(),
12674 "a callback queued mid-frame must schedule a follow-up before the loop parks"
12675 );
12676
12677 assert!(test_window.simulate_scheduled_frame());
12678 assert!(callback_ran.get());
12679 }
12680
12681 struct RootView {
12682 explicit_size: bool,
12683 child_bounds: Rc<Cell<Bounds<Pixels>>>,
12684 }
12685
12686 impl Render for RootView {
12687 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12688 let child_bounds = self.child_bounds.clone();
12689 let root = div().flex().flex_col().child(
12690 canvas(
12691 move |bounds, _, _| child_bounds.set(bounds),
12692 |_, _, _, _| {},
12693 )
12694 .size_full(),
12695 );
12696 if self.explicit_size {
12697 root.w(px(300.)).h(px(200.))
12698 } else {
12699 root
12700 }
12701 }
12702 }
12703
12704 #[test]
12705 fn auto_sized_window_root_fills_the_window() {
12706 let mut cx = TestAppContext::single();
12707 let child_bounds = Rc::new(Cell::new(Bounds::default()));
12708 let window = cx.add_window({
12709 let child_bounds = child_bounds.clone();
12710 move |_, _| RootView {
12711 explicit_size: false,
12712 child_bounds,
12713 }
12714 });
12715
12716 let viewport_size = cx
12717 .update_window(window.into(), |_, window, cx| {
12718 window.draw(cx).clear(cx);
12719 window.viewport_size()
12720 })
12721 .unwrap();
12722
12723 assert_eq!(child_bounds.get().size, viewport_size);
12724 }
12725
12726 #[test]
12727 fn explicitly_sized_window_root_keeps_its_size() {
12728 let mut cx = TestAppContext::single();
12729 let child_bounds = Rc::new(Cell::new(Bounds::default()));
12730 let window = cx.add_window({
12731 let child_bounds = child_bounds.clone();
12732 move |_, _| RootView {
12733 explicit_size: true,
12734 child_bounds,
12735 }
12736 });
12737
12738 cx.update_window(window.into(), |_, window, cx| {
12739 window.draw(cx).clear(cx);
12740 })
12741 .unwrap();
12742
12743 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
12744 }
12745
12746 struct FileDragView {
12747 path: PathBuf,
12748 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
12749 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
12750 }
12751
12752 struct FileDropExitView(Rc<Cell<usize>>);
12753
12754 impl Render for FileDropExitView {
12755 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12756 div().size_full().on_file_drop_exit({
12757 let observed_file_drop_exit = self.0.clone();
12758 move |_, _, _| observed_file_drop_exit.set(observed_file_drop_exit.get() + 1)
12759 })
12760 }
12761 }
12762
12763 impl Render for FileDragView {
12764 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
12765 div()
12766 .id("file-drag")
12767 .size_full()
12768 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
12769 .external_drag_payload(|path: &PathBuf, _, _| {
12770 Some(ExternalDragPayload::Files(FileDragPaths::new([(
12771 path.clone(),
12772 true,
12773 )])))
12774 })
12775 .on_drag_move({
12776 let observed_drag_moves = self.observed_drag_moves.clone();
12777 move |event: &DragMoveEvent<PathBuf>, _, _| {
12778 observed_drag_moves.borrow_mut().push(event.event.position);
12779 }
12780 })
12781 .on_drop({
12782 let observed_drops = self.observed_drops.clone();
12783 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
12784 })
12785 }
12786 }
12787
12788 #[gpui::test]
12789 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
12790 struct Drag {
12791 window: AnyWindowHandle,
12792 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
12793 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
12794 }
12795
12796 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
12797 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
12798 let observed_drops = Rc::new(RefCell::new(Vec::new()));
12799 let window: AnyWindowHandle = cx
12800 .add_window({
12801 let observed_drag_moves = observed_drag_moves.clone();
12802 let observed_drops = observed_drops.clone();
12803 move |_, _| FileDragView {
12804 path,
12805 observed_drag_moves,
12806 observed_drops,
12807 }
12808 })
12809 .into();
12810 cx.test_window(window)
12811 .set_start_external_drag_result(platform_result);
12812
12813 let update_result = cx.update_window(window, |_, window, cx| {
12814 window.draw(cx).clear(cx);
12815 window.dispatch_event(
12816 MouseDownEvent {
12817 position: point(px(10.), px(10.)),
12818 button: MouseButton::Left,
12819 modifiers: Default::default(),
12820 click_count: 1,
12821 first_mouse: false,
12822 }
12823 .to_platform_input(),
12824 cx,
12825 );
12826 window.dispatch_event(
12827 MouseMoveEvent {
12828 position: point(px(20.), px(20.)),
12829 pressed_button: Some(MouseButton::Left),
12830 modifiers: Default::default(),
12831 }
12832 .to_platform_input(),
12833 cx,
12834 );
12835 assert!(cx.active_drag.is_some());
12836 });
12837 assert!(
12838 update_result.is_ok(),
12839 "failed to start drag: {update_result:?}"
12840 );
12841
12842 assert!(cx.test_window(window).external_drag_files().is_empty());
12843 Drag {
12844 window,
12845 observed_drag_moves,
12846 observed_drops,
12847 }
12848 }
12849
12850 let successful_path = PathBuf::from("/tmp/successful-drag");
12851 let successful = start_drag(cx, successful_path.clone(), true);
12852 let outside_position = point(px(-1.), px(20.));
12853 let update_result = cx.update_window(successful.window, |_, window, cx| {
12854 window.dispatch_event(
12855 MouseMoveEvent {
12856 position: outside_position,
12857 pressed_button: Some(MouseButton::Left),
12858 modifiers: Default::default(),
12859 }
12860 .to_platform_input(),
12861 cx,
12862 );
12863 assert!(cx.active_drag.is_none());
12864 });
12865 assert!(
12866 update_result.is_ok(),
12867 "failed to promote drag: {update_result:?}"
12868 );
12869 assert_eq!(
12870 cx.test_window(successful.window).external_drag_files(),
12871 [(successful_path.clone(), true)]
12872 );
12873 assert_eq!(
12876 successful.observed_drag_moves.borrow().last(),
12877 Some(&outside_position)
12878 );
12879
12880 let first_destination_exit_count = Rc::new(Cell::new(0));
12881 let first_destination: AnyWindowHandle = cx
12882 .add_window({
12883 let first_destination_exit_count = first_destination_exit_count.clone();
12884 move |_, _| FileDropExitView(first_destination_exit_count)
12885 })
12886 .into();
12887 let second_destination_exit_count = Rc::new(Cell::new(0));
12888 let second_destination: AnyWindowHandle = cx
12889 .add_window({
12890 let second_destination_exit_count = second_destination_exit_count.clone();
12891 move |_, _| FileDropExitView(second_destination_exit_count)
12892 })
12893 .into();
12894 let reentry_position = point(px(30.), px(30.));
12895 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
12896 let update_result = cx.update_window(first_destination, |_, window, cx| {
12897 window.draw(cx).clear(cx);
12898 window.dispatch_event(
12899 FileDropEvent::Entered {
12900 position: reentry_position,
12901 paths: external_paths(),
12902 }
12903 .to_platform_input(),
12904 cx,
12905 );
12906 assert!(
12907 cx.active_drag
12908 .as_ref()
12909 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
12910 );
12911 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12912 assert!(cx.active_drag.is_none());
12913 assert_eq!(first_destination_exit_count.get(), 1);
12914 assert_eq!(second_destination_exit_count.get(), 0);
12915 });
12916 assert!(
12917 update_result.is_ok(),
12918 "failed to handle drag in first destination window: {update_result:?}"
12919 );
12920
12921 let update_result = cx.update_window(second_destination, |_, window, cx| {
12922 window.draw(cx).clear(cx);
12923 window.dispatch_event(
12924 PlatformInput::KeyDown(KeyDownEvent {
12925 keystroke: Keystroke::parse("down").expect("valid keystroke"),
12926 is_held: false,
12927 prefer_character_input: false,
12928 }),
12929 cx,
12930 );
12931 window.dispatch_event(
12932 FileDropEvent::Entered {
12933 position: reentry_position,
12934 paths: external_paths(),
12935 }
12936 .to_platform_input(),
12937 cx,
12938 );
12939 assert!(
12940 cx.active_drag
12941 .as_ref()
12942 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
12943 );
12944 assert_eq!(first_destination_exit_count.get(), 1);
12945 assert_eq!(second_destination_exit_count.get(), 0);
12946
12947 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12948 assert!(cx.active_drag.is_none());
12949 assert_eq!(first_destination_exit_count.get(), 1);
12950 assert_eq!(second_destination_exit_count.get(), 1);
12951 });
12952 assert!(
12953 update_result.is_ok(),
12954 "failed to handle drag in second destination window: {update_result:?}"
12955 );
12956
12957 let update_result = cx.update_window(successful.window, |_, window, cx| {
12958 window.dispatch_event(
12959 FileDropEvent::Entered {
12960 position: reentry_position,
12961 paths: external_paths(),
12962 }
12963 .to_platform_input(),
12964 cx,
12965 );
12966 assert!(
12967 cx.active_drag
12968 .as_ref()
12969 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
12970 );
12971 assert_eq!(
12972 successful.observed_drag_moves.borrow().last(),
12973 Some(&reentry_position)
12974 );
12975
12976 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
12977 assert!(cx.active_drag.is_none());
12978
12979 window.dispatch_event(
12980 FileDropEvent::Entered {
12981 position: reentry_position,
12982 paths: external_paths(),
12983 }
12984 .to_platform_input(),
12985 cx,
12986 );
12987 assert!(
12988 cx.active_drag
12989 .as_ref()
12990 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
12991 );
12992
12993 window.dispatch_event(
12994 FileDropEvent::Submit {
12995 position: reentry_position,
12996 }
12997 .to_platform_input(),
12998 cx,
12999 );
13000 assert_eq!(
13001 successful.observed_drops.borrow().as_slice(),
13002 std::slice::from_ref(&successful_path)
13003 );
13004 assert!(cx.active_drag.is_none());
13005
13006 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13007 assert!(cx.active_drag.is_none());
13008 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
13009 assert!(cx.active_drag.is_none());
13010
13011 window.dispatch_event(
13012 FileDropEvent::Entered {
13013 position: reentry_position,
13014 paths: external_paths(),
13015 }
13016 .to_platform_input(),
13017 cx,
13018 );
13019 assert!(
13020 cx.active_drag
13021 .as_ref()
13022 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
13023 );
13024 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
13025 });
13026 assert!(
13027 update_result.is_ok(),
13028 "failed to restore drag in source window: {update_result:?}"
13029 );
13030
13031 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
13032 let cancelled = start_drag(cx, cancelled_path.clone(), true);
13033 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
13034 window.dispatch_event(
13035 MouseMoveEvent {
13036 position: outside_position,
13037 pressed_button: Some(MouseButton::Left),
13038 modifiers: Default::default(),
13039 }
13040 .to_platform_input(),
13041 cx,
13042 );
13043 assert!(cx.active_drag.is_none());
13044
13045 window.dispatch_event(
13046 FileDropEvent::Entered {
13047 position: reentry_position,
13048 paths: ExternalPaths([cancelled_path].into_iter().collect()),
13049 }
13050 .to_platform_input(),
13051 cx,
13052 );
13053 assert!(
13054 cx.active_drag
13055 .as_ref()
13056 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
13057 );
13058 assert!(cx.stop_active_drag(window));
13059 assert!(cx.active_drag.is_none());
13060 });
13061 assert!(
13062 update_result.is_ok(),
13063 "failed to cancel restored drag: {update_result:?}"
13064 );
13065 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
13066
13067 let removed_path = PathBuf::from("/tmp/removed-window-drag");
13068 let removed = start_drag(cx, removed_path, true);
13069 let removed_window_id = removed.window.window_id();
13070 let update_result = cx.update_window(removed.window, |_, window, cx| {
13071 window.dispatch_event(
13072 MouseMoveEvent {
13073 position: outside_position,
13074 pressed_button: Some(MouseButton::Left),
13075 modifiers: Default::default(),
13076 }
13077 .to_platform_input(),
13078 cx,
13079 );
13080 assert!(cx.active_drag.is_none());
13081 window.remove_window();
13082 });
13083 assert!(
13084 update_result.is_ok(),
13085 "failed to remove drag source window: {update_result:?}"
13086 );
13087 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
13088
13089 let failed_path = PathBuf::from("/tmp/failed-drag");
13090 let failed = start_drag(cx, failed_path.clone(), false);
13091 let update_result = cx.update_window(failed.window, |_, window, cx| {
13092 for x_position in [-1., -2.] {
13093 window.dispatch_event(
13094 MouseMoveEvent {
13095 position: point(px(x_position), px(20.)),
13096 pressed_button: Some(MouseButton::Left),
13097 modifiers: Default::default(),
13098 }
13099 .to_platform_input(),
13100 cx,
13101 );
13102 }
13103 assert!(cx.active_drag.is_some());
13104 });
13105 assert!(
13106 update_result.is_ok(),
13107 "failed to retain drag after platform failure: {update_result:?}"
13108 );
13109 assert_eq!(
13110 cx.test_window(failed.window).external_drag_files(),
13111 [(failed_path, true)]
13112 );
13113 }
13114
13115 struct FocusForwarder {
13116 a: FocusHandle,
13117 b: FocusHandle,
13118 }
13119
13120 impl Render for FocusForwarder {
13121 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13122 div()
13123 .size_full()
13124 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
13125 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
13126 }
13127 }
13128
13129 #[gpui::test]
13133 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
13134 let b_focus_count = Rc::new(Cell::new(0));
13135 let window = cx.add_window({
13136 let b_focus_count = b_focus_count.clone();
13137 move |window, cx| {
13138 let a = cx.focus_handle();
13139 let b = cx.focus_handle();
13140 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
13141 let b = this.b.clone();
13142 window.focus(&b, cx);
13143 })
13144 .detach();
13145 cx.on_focus(&b, window, move |_, _, _| {
13146 b_focus_count.set(b_focus_count.get() + 1);
13147 })
13148 .detach();
13149 FocusForwarder { a, b }
13150 }
13151 });
13152
13153 window
13154 .update(cx, |_, window, _| window.activate_window())
13155 .unwrap();
13156 cx.executor().run_until_parked();
13157
13158 window
13159 .update(cx, |this, window, cx| {
13160 let a = this.a.clone();
13161 window.focus(&a, cx);
13162 })
13163 .unwrap();
13164 cx.executor().run_until_parked();
13165
13166 window
13167 .update(cx, |this, window, _| {
13168 assert!(this.b.is_focused(window));
13169 })
13170 .unwrap();
13171 assert_eq!(b_focus_count.get(), 1);
13172 }
13173
13174 #[gpui::test]
13175 fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
13176 let events = Rc::new(RefCell::new(Vec::new()));
13177 let window = cx.add_window({
13178 let events = events.clone();
13179 move |_, _| TouchDragListener { events }
13180 });
13181 let touch = TouchId(1);
13182
13183 dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
13184 dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
13185 dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
13186
13187 assert_eq!(
13188 events.borrow().as_slice(),
13189 [
13190 (TouchPhase::Started, px(10.)),
13191 (TouchPhase::Moved, px(30.)),
13192 (TouchPhase::Ended, px(40.)),
13193 ]
13194 );
13195 }
13196
13197 #[gpui::test]
13198 fn back_gesture_is_claimed_by_the_innermost_listener(cx: &mut TestAppContext) {
13199 let claims = Rc::new(RefCell::new(Vec::new()));
13200 let window = cx.add_window({
13201 let claims = claims.clone();
13202 move |_, _| BackListeners { claims }
13203 });
13204 let dispatch_back = |cx: &mut TestAppContext, x: f32| {
13205 window
13206 .update(cx, |_, window, cx| {
13207 window
13208 .dispatch_event(
13209 BackGestureEvent {
13210 phase: BackGesturePhase::Started,
13211 start_position: point(px(x), px(10.)),
13212 progress: 0.,
13213 }
13214 .to_platform_input(),
13215 cx,
13216 )
13217 .default_prevented
13218 })
13219 .unwrap()
13220 };
13221 assert!(dispatch_back(cx, 10.));
13222 assert!(dispatch_back(cx, 80.));
13223 assert!(!dispatch_back(cx, 150.));
13224 assert_eq!(claims.borrow().as_slice(), ["inner", "outer"]);
13225 }
13226
13227 struct BackListeners {
13228 claims: Rc<RefCell<Vec<&'static str>>>,
13229 }
13230
13231 impl Render for BackListeners {
13232 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
13233 let claim = |name: &'static str| {
13234 let claims = self.claims.clone();
13235 move |_: &BackGestureEvent, _: &mut Window, _: &mut crate::App| {
13236 claims.borrow_mut().push(name)
13237 }
13238 };
13239 div().size_full().child(
13240 div()
13241 .w(px(100.))
13242 .h_full()
13243 .on_back_gesture(claim("outer"))
13244 .child(div().w(px(50.)).h_full().on_back_gesture(claim("inner"))),
13245 )
13246 }
13247 }
13248
13249 struct TouchDragListener {
13250 events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
13251 }
13252
13253 impl Render for TouchDragListener {
13254 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
13255 let events = self.events.clone();
13256 canvas(
13257 |_, _, _| {},
13258 move |_, _, window, _| {
13259 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
13260 if phase != DispatchPhase::Bubble {
13261 return;
13262 }
13263 events.borrow_mut().push((event.phase, event.position.x));
13264 if event.phase == TouchPhase::Started {
13265 window.prevent_default();
13266 }
13267 });
13268 },
13269 )
13270 }
13271 }
13272
13273 #[gpui::test]
13274 fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
13275 for response in [
13276 LongPressResponse::PreventDefault,
13277 LongPressResponse::StopPropagation,
13278 LongPressResponse::None,
13279 ] {
13280 let phases = Rc::new(RefCell::new(Vec::new()));
13281 let window = cx.add_window({
13282 let phases = phases.clone();
13283 move |_, _| LongPressListener { phases, response }
13284 });
13285 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13286 cx.executor().advance_clock(Duration::from_millis(501));
13287 cx.executor().run_until_parked();
13288 window
13289 .update(cx, |_, window, _| {
13290 assert_eq!(
13291 window.long_press_capture.is_some(),
13292 response == LongPressResponse::PreventDefault
13293 );
13294 })
13295 .unwrap();
13296 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
13297 dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
13298 window
13299 .update(cx, |_, window, _| {
13300 assert!(window.long_press_capture.is_none());
13301 })
13302 .unwrap();
13303
13304 let phases = phases.borrow();
13305 if response == LongPressResponse::PreventDefault {
13306 assert_eq!(
13307 phases.as_slice(),
13308 [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
13309 );
13310 } else {
13311 assert_eq!(phases.as_slice(), [TouchPhase::Started]);
13312 }
13313 }
13314 }
13315
13316 #[gpui::test]
13317 fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
13318 let phases = Rc::new(RefCell::new(Vec::new()));
13319 let window = cx.add_window({
13320 let phases = phases.clone();
13321 move |_, _| LongPressListener {
13322 phases,
13323 response: LongPressResponse::None,
13324 }
13325 });
13326 window
13327 .update(cx, |_, window, _| {
13328 window.prevent_default();
13329 })
13330 .unwrap();
13331
13332 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13333 cx.executor().advance_clock(Duration::from_millis(501));
13334 cx.executor().run_until_parked();
13335 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
13336
13337 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
13338 }
13339
13340 #[gpui::test]
13341 fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
13342 for (phase, position) in [
13343 (TouchPhase::Ended, 0.),
13344 (TouchPhase::Cancelled, 0.),
13345 (TouchPhase::Moved, 20.),
13346 ] {
13347 let phases = Rc::new(RefCell::new(Vec::new()));
13348 let window = cx.add_window({
13349 let phases = phases.clone();
13350 move |_, _| LongPressListener {
13351 phases,
13352 response: LongPressResponse::PreventDefault,
13353 }
13354 });
13355 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
13356 dispatch_touch(window, cx, TouchId(1), phase, position);
13357 cx.executor().advance_clock(Duration::from_millis(501));
13358 cx.executor().run_until_parked();
13359
13360 assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
13361 }
13362 }
13363
13364 #[gpui::test]
13365 fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
13366 let phases = Rc::new(RefCell::new(Vec::new()));
13367 let window = cx.add_window({
13368 let phases = phases.clone();
13369 move |_, _| LongPressListener {
13370 phases,
13371 response: LongPressResponse::PreventDefault,
13372 }
13373 });
13374 let first_touch = TouchId(1);
13375 dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
13376 cx.executor().advance_clock(Duration::from_millis(250));
13377 dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
13378 dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
13379
13380 cx.executor().advance_clock(Duration::from_millis(251));
13381 cx.executor().run_until_parked();
13382 assert!(phases.borrow().is_empty());
13383
13384 cx.executor().advance_clock(Duration::from_millis(250));
13385 cx.executor().run_until_parked();
13386 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
13387 }
13388
13389 #[gpui::test]
13390 fn test_underline_exclusions_preserve_device_geometry(cx: &mut TestAppContext) {
13391 test_underline_paint_at_scales(cx, |window| {
13392 let (numerator, denominator) = match window.scale_factor() {
13393 1.0 => (1, 1),
13394 1.25 => (5, 4),
13395 1.5 => (3, 2),
13396 2.0 => (2, 1),
13397 3.0 => (3, 1),
13398 scale => panic!("unexpected scale {scale}"),
13399 };
13400 let snap = |quarters: i32| {
13401 let scaled = quarters * numerator;
13402 let divisor = 4 * denominator;
13403 let rounded =
13404 scaled.abs() / divisor + i32::from(2 * (scaled.abs() % divisor) > divisor);
13405 ScaledPixels((scaled.signum() * rounded) as f32)
13406 };
13407 let stroke = |quarters| {
13408 if quarters == 0 {
13409 ScaledPixels(0.)
13410 } else {
13411 snap(quarters).max(ScaledPixels(1.))
13412 }
13413 };
13414
13415 for origin in [-101, -3, -2, -1, 0, 1, 2, 3, 101] {
13416 for width in [0, 1, 3, 84] {
13417 for thickness in [0, 1, 4, 7] {
13418 for wavy in [false, true] {
13419 let style = UnderlineStyle {
13420 thickness: px(thickness as f32 / 4.),
13421 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
13422 wavy,
13423 offset: px(0.),
13424 };
13425 let bounds = Bounds::new(
13426 point(snap(origin), snap(-origin)),
13427 size(
13428 stroke(width),
13429 stroke(thickness) * if wavy { 3. } else { 1. },
13430 ),
13431 );
13432 let origin = point(px(origin as f32 / 4.), px(-origin as f32 / 4.));
13433 let width = px(width as f32 / 4.);
13434 assert_eq!(window.underline_bounds(origin, width, &style), bounds);
13435 let original = paint_test_underlines(window, |window| {
13436 window.paint_underline(origin, width, &style);
13437 })
13438 .to_vec();
13439 assert_eq!(original.len(), usize::from(!bounds.is_empty()));
13440 if let Some(underline) = original.first() {
13441 assert_eq!(underline.bounds, bounds);
13442 assert_eq!(underline.thickness, stroke(thickness));
13443 assert_eq!(underline.wavy, wavy.into());
13444 assert_eq!(underline.color, hsla(0.25, 0.5, 0.75, 0.5));
13445 }
13446
13447 let underlines = paint_test_underlines(window, |window| {
13448 window.paint_underline_with_exclusions(origin, width, &style, &[]);
13449 });
13450 assert_eq!(underlines.len(), original.len());
13451 for (actual, original) in underlines.iter().zip(&original) {
13452 assert_same_underline_geometry(actual, original);
13453 assert_eq!(actual.content_mask, original.content_mask);
13454 }
13455
13456 let left = bounds.left().0 as i32;
13457 let right = bounds.right().0 as i32;
13458 let exclusions = [
13459 (15, 25),
13460 (3, 7),
13461 (5, 10),
13462 (10, 12),
13463 (0, 0),
13464 (4, 2),
13465 (-50, -1),
13466 (70, 100),
13467 ]
13468 .map(|(start, end)| {
13469 ScaledPixels((left + start) as f32)
13470 ..ScaledPixels((left + end) as f32)
13471 });
13472 let underlines = paint_test_underlines(window, |window| {
13473 window.paint_underline_with_exclusions(
13474 origin,
13475 width,
13476 &style,
13477 &exclusions,
13478 );
13479 });
13480 let expected = (left..right)
13481 .filter(|column| {
13482 !bounds.is_empty()
13483 && !exclusions.iter().any(|span| {
13484 span.contains(&ScaledPixels(*column as f32))
13485 })
13486 })
13487 .collect::<Vec<_>>();
13488 assert_eq!(underline_device_columns(underlines), expected);
13489 for underline in underlines {
13490 assert_same_underline_geometry(underline, &original[0]);
13491 }
13492 }
13493 }
13494 }
13495 }
13496 });
13497 }
13498
13499 #[gpui::test]
13500 fn test_underline_exclusions_preserve_helvetica_warning_edge(cx: &mut TestAppContext) {
13501 test_underline_paint_at_scales(cx, |window| {
13502 if window.scale_factor() != 2.0 {
13503 return;
13504 }
13505 let style = UnderlineStyle {
13506 thickness: px(1.),
13507 color: None,
13508 wavy: true,
13509 offset: px(0.),
13510 };
13511 let origin = point(px(2.888_183_8), px(15.357_917));
13512 let width = px(23.848_145) - origin.x;
13513 let original = paint_test_underlines(window, |window| {
13514 window.paint_underline(origin, width, &style);
13515 })[0];
13516 assert_eq!(original.bounds.left(), ScaledPixels(6.));
13517 assert_eq!(original.bounds.right(), ScaledPixels(48.));
13518 let point_bounds = window.underline_bounds(origin, px(10.829_102), &style);
13519 assert_eq!(point_bounds.left(), ScaledPixels(6.));
13520 assert_eq!(point_bounds.right(), ScaledPixels(28.));
13521
13522 let underlines = paint_test_underlines(window, |window| {
13523 window.paint_underline_with_exclusions(
13524 origin,
13525 width,
13526 &style,
13527 &[point_bounds.left()..point_bounds.right()],
13528 );
13529 });
13530 assert_eq!(underlines.len(), 1);
13531 assert_same_underline_geometry(&underlines[0], &original);
13532 assert_eq!(
13533 underline_device_columns(underlines),
13534 (28..48).collect::<Vec<_>>()
13535 );
13536 });
13537 }
13538
13539 #[gpui::test]
13540 fn test_underline_exclusions_preserve_content_mask_and_opacity(cx: &mut TestAppContext) {
13541 test_underline_paint_at_scales(cx, |window| {
13542 let scale = window.scale_factor();
13543 let original_mask = window.content_mask();
13544 let original_opacity = window.element_opacity();
13545 let mask = ContentMask {
13546 bounds: Bounds::from_corners(point(px(4.), px(10.)), point(px(16.), px(12.))),
13547 ..Default::default()
13548 };
13549 let style = UnderlineStyle {
13550 thickness: px(2.),
13551 color: Some(hsla(0.25, 0.5, 0.75, 0.5)),
13552 wavy: true,
13553 offset: px(0.),
13554 };
13555 let origin = point(px(-1.25), px(9.25));
13556 let width = px(24.);
13557 window.with_content_mask(Some(mask), |window| {
13558 window.with_element_opacity(Some(0.5), |window| {
13559 window.with_element_opacity(Some(0.5), |window| {
13560 let original = paint_test_underlines(window, |window| {
13561 window.paint_underline(origin, width, &style);
13562 })[0];
13563 assert_eq!(original.color, hsla(0.25, 0.5, 0.75, 0.125));
13564 let underlines = paint_test_underlines(window, |window| {
13565 window.paint_underline_with_exclusions(
13566 origin,
13567 width,
13568 &style,
13569 &[ScaledPixels(6. * scale)..ScaledPixels(8. * scale)],
13570 );
13571 });
13572 assert_eq!(underlines.len(), 2);
13573 let expected = [(4. * scale, 6. * scale), (8. * scale, 16. * scale)].map(
13574 |(left, right)| {
13575 Bounds::from_corners(
13576 point(ScaledPixels(left), ScaledPixels((10. * scale).floor())),
13577 point(ScaledPixels(right), ScaledPixels((12. * scale).ceil())),
13578 )
13579 },
13580 );
13581 assert_eq!(
13582 underlines
13583 .iter()
13584 .map(|underline| underline.content_mask.bounds)
13585 .collect::<Vec<_>>(),
13586 expected
13587 );
13588 for underline in underlines {
13589 assert_same_underline_geometry(underline, &original);
13590 }
13591 });
13592 });
13593 });
13594 assert_eq!(window.content_mask(), original_mask);
13595 assert_eq!(window.element_opacity(), original_opacity);
13596 });
13597 }
13598
13599 #[gpui::test]
13600 fn test_underline_exclusions_adversarial_permutations(cx: &mut TestAppContext) {
13601 test_underline_paint_at_scales(cx, |window| {
13602 let style = UnderlineStyle {
13603 thickness: px(1.),
13604 color: None,
13605 wavy: true,
13606 offset: px(0.),
13607 };
13608 let origin = point(px(-4.), px(-1.));
13609 let width = px(8.);
13610 let left = (-4. * window.scale_factor()) as i32;
13611 let right = (4. * window.scale_factor()) as i32;
13612 let endpoints = [-16, -8, -1, 0, 1, 8, 16];
13613 for first_start in endpoints {
13614 for first_end in endpoints {
13615 for second_start in endpoints {
13616 for second_end in endpoints {
13617 let exclusions = [first_start..first_end, second_start..second_end];
13618 let expected = (left..right)
13619 .filter(|column| {
13620 !exclusions.iter().any(|span| span.contains(column))
13621 })
13622 .collect::<Vec<_>>();
13623 let exclusions = exclusions.map(|span| {
13624 ScaledPixels(span.start as f32)..ScaledPixels(span.end as f32)
13625 });
13626 let underlines = paint_test_underlines(window, |window| {
13627 window.paint_underline_with_exclusions(
13628 origin,
13629 width,
13630 &style,
13631 &exclusions,
13632 );
13633 });
13634 assert_eq!(
13635 underline_device_columns(underlines),
13636 expected,
13637 "{exclusions:?}"
13638 );
13639 }
13640 }
13641 }
13642 }
13643 });
13644 }
13645
13646 #[derive(Clone, Copy, PartialEq)]
13647 enum LongPressResponse {
13648 PreventDefault,
13649 StopPropagation,
13650 None,
13651 }
13652
13653 struct LongPressListener {
13654 phases: Rc<RefCell<Vec<TouchPhase>>>,
13655 response: LongPressResponse,
13656 }
13657
13658 impl Render for LongPressListener {
13659 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
13660 let entity = cx.entity();
13661 let phases = self.phases.clone();
13662 let response = self.response;
13663 canvas(
13664 |_, _, _| {},
13665 move |_, _, window, _| {
13666 window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
13667 if phase != DispatchPhase::Bubble {
13668 return;
13669 }
13670 phases.borrow_mut().push(event.phase);
13671 match response {
13672 LongPressResponse::PreventDefault => {
13673 window.capture_long_press(&entity);
13674 window.prevent_default();
13675 }
13676 LongPressResponse::StopPropagation => cx.stop_propagation(),
13677 LongPressResponse::None => {}
13678 }
13679 });
13680 },
13681 )
13682 }
13683 }
13684
13685 struct UnderlineTestView(Rc<dyn Fn(&mut Window)>);
13686
13687 impl Render for UnderlineTestView {
13688 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13689 let paint = self.0.clone();
13690 canvas(
13691 |_, _, _| {},
13692 move |_, _, window, _| {
13693 window.content_mask_stack.push(ContentMask::rect(Bounds::from_corners(
13694 point(px(-1000.), px(-1000.)),
13695 point(px(1000.), px(1000.)),
13696 )));
13697 paint(window);
13698 window.content_mask_stack.pop();
13699 },
13700 )
13701 .size_full()
13702 }
13703 }
13704
13705 fn test_underline_paint_at_scales(
13706 cx: &mut TestAppContext,
13707 paint: impl Fn(&mut Window) + 'static,
13708 ) {
13709 let window = cx.add_window(move |_, _| UnderlineTestView(Rc::new(paint)));
13710 for scale in [1., 1.25, 1.5, 2., 3.] {
13711 cx.simulate_window_scale_factor_change(window.into(), scale);
13712 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
13713 .unwrap();
13714 }
13715 }
13716
13717 fn paint_test_underlines(window: &mut Window, paint: impl FnOnce(&mut Window)) -> &[Underline] {
13718 window.next_frame.scene.clear();
13719 paint(window);
13720 &window.next_frame.scene.underlines
13721 }
13722
13723 fn assert_same_underline_geometry(actual: &Underline, expected: &Underline) {
13724 assert_eq!(actual.bounds, expected.bounds);
13725 assert_eq!(actual.thickness, expected.thickness);
13726 assert_eq!(actual.wavy, expected.wavy);
13727 assert_eq!(actual.color, expected.color);
13728 assert_eq!(actual.pad, expected.pad);
13729 }
13730
13731 fn underline_device_columns(underlines: &[Underline]) -> Vec<i32> {
13732 underlines
13733 .iter()
13734 .flat_map(|underline| {
13735 let bounds = underline.bounds.intersect(&underline.content_mask.bounds);
13736 bounds.left().0 as i32..bounds.right().0 as i32
13737 })
13738 .collect()
13739 }
13740
13741 actions!(window_test, [StandaloneModifierAction]);
13742
13743 struct StandaloneModifierView {
13744 focus_handle: FocusHandle,
13745 action_count: usize,
13746 }
13747
13748 impl Render for StandaloneModifierView {
13749 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
13750 div()
13751 .key_context("StandaloneModifier")
13752 .track_focus(&self.focus_handle)
13753 .on_action(cx.listener(|this, _: &StandaloneModifierAction, _, _| {
13754 this.action_count += 1;
13755 }))
13756 }
13757 }
13758
13759 #[gpui::test]
13760 fn test_standalone_modifier_sequence_timeout_and_recovery(cx: &mut TestAppContext) {
13761 use crate::{KeyBinding, Modifiers};
13762
13763 cx.update(|cx| {
13764 cx.bind_keys([KeyBinding::new(
13765 "shift shift",
13766 StandaloneModifierAction,
13767 Some("StandaloneModifier"),
13768 )]);
13769 });
13770 let (view, cx) = cx.add_window_view(|window, cx| {
13771 let focus_handle = cx.focus_handle();
13772 window.focus(&focus_handle, cx);
13773 StandaloneModifierView {
13774 focus_handle,
13775 action_count: 0,
13776 }
13777 });
13778 let shift = Modifiers {
13779 shift: true,
13780 ..Modifiers::default()
13781 };
13782 cx.simulate_modifiers_change(shift);
13783 cx.simulate_modifiers_change(Modifiers::default());
13784 cx.update(|window, _| {
13785 assert_eq!(
13786 window.pending_input_keystrokes(),
13787 Some([Keystroke::parse("shift").expect("valid keystroke")].as_slice())
13788 );
13789 });
13790 cx.background_executor.advance_clock(Duration::from_secs(2));
13791 cx.run_until_parked();
13792 cx.update(|window, cx| {
13793 assert!(!window.has_pending_keystrokes());
13794 assert_eq!(view.read(cx).action_count, 0);
13795 });
13796
13797 cx.simulate_modifiers_change(shift);
13798 cx.simulate_modifiers_change(Modifiers::default());
13799 cx.update(|window, cx| {
13800 assert!(window.has_pending_keystrokes());
13801 assert_eq!(view.read(cx).action_count, 0);
13802 });
13803
13804 cx.simulate_modifiers_change(shift);
13805 cx.simulate_modifiers_change(Modifiers::default());
13806 cx.update(|window, cx| {
13807 assert!(!window.has_pending_keystrokes());
13808 assert_eq!(view.read(cx).action_count, 1);
13809 });
13810 }
13811
13812 #[gpui::test]
13813 fn test_standalone_modifier_sequence_dispatches_before_timeout(cx: &mut TestAppContext) {
13814 use crate::{KeyBinding, Modifiers};
13815
13816 cx.update(|cx| {
13817 cx.bind_keys([KeyBinding::new(
13818 "shift shift",
13819 StandaloneModifierAction,
13820 Some("StandaloneModifier"),
13821 )]);
13822 });
13823 let (view, cx) = cx.add_window_view(|window, cx| {
13824 let focus_handle = cx.focus_handle();
13825 window.focus(&focus_handle, cx);
13826 StandaloneModifierView {
13827 focus_handle,
13828 action_count: 0,
13829 }
13830 });
13831 let shift = Modifiers {
13832 shift: true,
13833 ..Modifiers::default()
13834 };
13835 cx.simulate_modifiers_change(shift);
13836 cx.simulate_modifiers_change(Modifiers::default());
13837 cx.background_executor
13838 .advance_clock(Duration::from_millis(500));
13839 cx.update(|window, cx| {
13840 assert!(window.has_pending_keystrokes());
13841 assert_eq!(view.read(cx).action_count, 0);
13842 });
13843 cx.simulate_modifiers_change(shift);
13844 cx.simulate_modifiers_change(Modifiers::default());
13845 cx.update(|window, cx| {
13846 assert!(!window.has_pending_keystrokes());
13847 assert_eq!(view.read(cx).action_count, 1);
13848 });
13849 cx.background_executor.advance_clock(Duration::from_secs(2));
13850 cx.run_until_parked();
13851 cx.update(|window, cx| {
13852 assert!(!window.has_pending_keystrokes());
13853 assert_eq!(view.read(cx).action_count, 1);
13854 });
13855 }
13856
13857 fn dispatch_touch<T: 'static>(
13858 window: crate::WindowHandle<T>,
13859 cx: &mut TestAppContext,
13860 id: TouchId,
13861 phase: TouchPhase,
13862 x: f32,
13863 ) {
13864 window
13865 .update(cx, |_, window, cx| {
13866 window.dispatch_event(
13867 TouchEvent {
13868 id,
13869 phase,
13870 position: point(px(x), px(0.)),
13871 predicted_position: None,
13872 force: None,
13873 }
13874 .to_platform_input(),
13875 cx,
13876 );
13877 })
13878 .unwrap();
13879 }
13880
13881 #[gpui::test]
13882 fn cached_view_follows_inherited_opacity(cx: &mut TestAppContext) {
13883 struct Child {
13884 renders: usize,
13885 }
13886
13887 impl Render for Child {
13888 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13889 self.renders += 1;
13890 div().size_full().bg(crate::rgb(0xff0000))
13891 }
13892 }
13893
13894 struct Root {
13895 opacity: f32,
13896 width: Pixels,
13897 child: crate::Entity<Child>,
13898 }
13899
13900 impl Render for Root {
13901 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13902 div()
13903 .w(self.width)
13904 .h(px(200.))
13905 .opacity(self.opacity)
13906 .hover(|style| style.opacity(1.))
13907 .child(
13908 self.child
13909 .clone()
13910 .cached(crate::StyleRefinement::default().size(px(100.))),
13911 )
13912 }
13913 }
13914
13915 fn update_and_draw(
13918 window: crate::WindowHandle<Root>,
13919 child: &crate::Entity<Child>,
13920 cx: &mut TestAppContext,
13921 update: impl FnOnce(&mut Root, &mut Window, &mut Context<Root>),
13922 ) -> (f32, usize) {
13923 window
13924 .update(cx, |root, window, cx| {
13925 update(root, window, cx);
13926 cx.notify();
13927 })
13928 .expect("update root");
13929 for _ in 0..3 {
13930 let (alpha, renders, requested_frames) = cx
13931 .update_window(window.into(), |_, window, cx| {
13932 window.draw(cx).clear(cx);
13933 let quads = &window.rendered_frame.scene.quads;
13934 assert_eq!(quads.len(), 1);
13935 let alpha = quads.first().expect("child quad").background.solid.a;
13936 (
13937 alpha,
13938 child.read(cx).renders,
13939 window.simulate_next_frame(cx),
13940 )
13941 })
13942 .expect("draw window");
13943 if requested_frames == 0 {
13944 return (alpha, renders);
13945 }
13946 }
13947 panic!("cached child kept requesting frames");
13948 }
13949
13950 let child = cx.new(|_| Child { renders: 0 });
13951 let window = cx.add_window(|_, _| Root {
13952 opacity: 1.,
13953 width: px(200.),
13954 child: child.clone(),
13955 });
13956 let outside = point(px(500.), px(500.));
13957 let inside = point(px(50.), px(50.));
13958 let beside = point(px(250.), px(50.));
13959
13960 let move_outside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
13962 window.simulate_mouse_move(outside, cx)
13963 };
13964 assert_eq!(update_and_draw(window, &child, cx, move_outside), (1., 1));
13965 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (1., 1));
13966 let fade = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.opacity = 0.5;
13967 assert_eq!(update_and_draw(window, &child, cx, fade), (0.5, 2));
13968 assert_eq!(update_and_draw(window, &child, cx, |_, _, _| {}), (0.5, 2));
13969
13970 let move_inside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
13972 window.simulate_mouse_move(inside, cx)
13973 };
13974 assert_eq!(update_and_draw(window, &child, cx, move_inside).0, 1.);
13975 let move_beside = |_: &mut Root, window: &mut Window, cx: &mut Context<Root>| {
13976 window.simulate_mouse_move(beside, cx)
13977 };
13978 assert_eq!(update_and_draw(window, &child, cx, move_beside).0, 0.5);
13979
13980 let widen = |root: &mut Root, _: &mut Window, _: &mut Context<Root>| root.width = px(300.);
13983 assert_eq!(update_and_draw(window, &child, cx, widen).0, 1.);
13984 }
13985
13986 #[gpui::test]
13987 fn test_drag_cursor_applies_before_next_paint(cx: &mut TestAppContext) {
13988 struct ResizeHandle;
13989
13990 impl Render for ResizeHandle {
13991 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
13992 div().size_full().cursor_text().child(
13993 div()
13994 .id("resize-handle")
13995 .w(px(4.))
13996 .h_full()
13997 .cursor_col_resize()
13998 .on_drag((), |_, _, _, cx| cx.new(|_| Empty)),
13999 )
14000 }
14001 }
14002
14003 let window = cx.add_window(|_, _| ResizeHandle);
14004 let handle_position = point(px(1.), px(10.));
14005 let drag_position = point(px(20.), px(10.));
14006 let cursor_observer = cx.clone();
14007
14008 let update_result = cx.update_window(window.into(), |_, window, cx| {
14009 window.hovered.set(true);
14010 window.active.set(true);
14011 window.draw(cx).clear(cx);
14012 window.dispatch_event(
14013 MouseMoveEvent {
14014 position: handle_position,
14015 ..Default::default()
14016 }
14017 .to_platform_input(),
14018 cx,
14019 );
14020 window.dispatch_event(
14021 MouseDownEvent {
14022 position: handle_position,
14023 button: MouseButton::Left,
14024 ..Default::default()
14025 }
14026 .to_platform_input(),
14027 cx,
14028 );
14029 window.dispatch_event(
14030 MouseMoveEvent {
14031 position: drag_position,
14032 pressed_button: Some(MouseButton::Left),
14033 ..Default::default()
14034 }
14035 .to_platform_input(),
14036 cx,
14037 );
14038 assert!(cx.has_active_drag());
14039 assert_eq!(
14041 cursor_observer.test_platform().cursor_style(),
14042 CursorStyle::ResizeColumn
14043 );
14044
14045 window.draw(cx).clear(cx);
14046 window.dispatch_event(
14047 MouseUpEvent {
14048 position: drag_position,
14049 button: MouseButton::Left,
14050 ..Default::default()
14051 }
14052 .to_platform_input(),
14053 cx,
14054 );
14055 window.draw(cx).clear(cx);
14056 });
14057 assert!(
14058 update_result.is_ok(),
14059 "failed to run drag: {update_result:?}"
14060 );
14061 assert_eq!(
14062 cursor_observer.test_platform().cursor_style(),
14063 CursorStyle::IBeam
14064 );
14065 }
14066}
14067
14068#[cfg(all(test, any(feature = "inspector", debug_assertions)))]
14069mod inspector_tests {
14070 use super::*;
14071 use crate::{
14072 DivInspectorState, InspectorElementId, MouseDownEvent, StyleRefinement, TestAppContext, div,
14073 };
14074
14075 #[gpui::test]
14076 fn inspector_only_tracks_its_open_window(cx: &mut TestAppContext) {
14077 let windows = [
14078 cx.add_window(|_, cx| InspectorTestRoot {
14079 child: cx.new(|_| InspectorTestView::default()),
14080 }),
14081 cx.add_window(|_, cx| InspectorTestRoot {
14082 child: cx.new(|_| InspectorTestView::default()),
14083 }),
14084 ];
14085 for window in windows {
14086 assert_closed_inspector(window.into(), cx);
14087 }
14088 for _ in 0..2 {
14089 cx.update_window(windows[0].into(), |root, window, cx| {
14090 let root = root.downcast::<InspectorTestRoot>().expect("test root");
14091 let child_widths = root.read(cx).child.read(cx).child_widths.clone();
14092 window.toggle_inspector(cx);
14093 window.draw(cx).clear(cx);
14094 assert_eq!(child_widths.borrow().as_slice(), &[px(10.); 3]);
14095 let path = window
14096 .rendered_frame
14097 .next_inspector_instance_ids
14098 .iter()
14099 .find_map(|(path, count)| (*count == 3).then(|| path.clone()))
14100 .expect("anonymous siblings share an inspector path");
14101 let selected_id = InspectorElementId {
14102 path,
14103 instance_id: 1,
14104 };
14105 let position = window
14106 .rendered_frame
14107 .hitboxes
14108 .iter()
14109 .find(|hitbox| {
14110 window.rendered_frame.inspector_hitboxes.get(&hitbox.id)
14111 == Some(&selected_id)
14112 })
14113 .expect("middle sibling is pickable")
14114 .bounds
14115 .center();
14116 window.simulate_mouse_move(position, cx);
14117 window.dispatch_event(
14118 PlatformInput::MouseDown(MouseDownEvent {
14119 position,
14120 button: MouseButton::Left,
14121 modifiers: Modifiers::default(),
14122 click_count: 1,
14123 first_mouse: false,
14124 }),
14125 cx,
14126 );
14127 window.dispatch_event(
14128 PlatformInput::MouseUp(MouseUpEvent {
14129 position,
14130 button: MouseButton::Left,
14131 modifiers: Modifiers::default(),
14132 click_count: 1,
14133 }),
14134 cx,
14135 );
14136 assert!(!window.is_inspector_picking(cx));
14137 assert_eq!(
14138 window
14139 .inspector
14140 .as_ref()
14141 .expect("open inspector")
14142 .read(cx)
14143 .active_element_id(),
14144 Some(&selected_id)
14145 );
14146 window.draw(cx).clear(cx);
14147 window.with_inspector_state::<DivInspectorState, _>(
14148 Some(&selected_id),
14149 cx,
14150 |state, _| {
14151 let state = state.as_mut().expect("selected div has style state");
14152 assert_eq!(
14153 state.base_style.size.width,
14154 Some(crate::Length::from(px(10.)))
14155 );
14156 state.base_style.size.width = Some(crate::Length::from(px(25.)));
14157 },
14158 );
14159 window.refresh();
14160 window.draw(cx).clear(cx);
14161 assert_eq!(
14162 child_widths.borrow().as_slice(),
14163 &[px(10.), px(25.), px(10.)]
14164 );
14165 })
14166 .expect("pick and edit a cached child");
14167 assert_closed_inspector(windows[1].into(), cx);
14168 windows[0]
14169 .update(cx, |_, window, cx| window.toggle_inspector(cx))
14170 .expect("close inspector");
14171 assert_closed_inspector(windows[0].into(), cx);
14172 }
14173 }
14174
14175 struct InspectorTestRoot {
14176 child: Entity<InspectorTestView>,
14177 }
14178
14179 impl Render for InspectorTestRoot {
14180 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14181 self.child
14182 .clone()
14183 .cached(StyleRefinement::default().size(px(100.)))
14184 }
14185 }
14186
14187 #[derive(Default)]
14188 struct InspectorTestView {
14189 child_widths: Rc<RefCell<Vec<Pixels>>>,
14190 }
14191
14192 impl Render for InspectorTestView {
14193 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14194 let child_widths = self.child_widths.clone();
14195 div()
14196 .on_children_prepainted(move |bounds, _, _| {
14197 *child_widths.borrow_mut() =
14198 bounds.iter().map(|bounds| bounds.size.width).collect();
14199 })
14200 .with_dynamic_prepaint_order(|_, _| SmallVec::from_iter([2, 0, 1]))
14201 .id("inspector-root")
14202 .flex()
14203 .children((0..3).map(|_| div().size(px(10.)).flex_shrink_0()))
14204 }
14205 }
14206
14207 fn assert_closed_inspector(window: AnyWindowHandle, cx: &mut TestAppContext) {
14208 cx.update_window(window, |root, window, cx| {
14209 window.draw(cx).clear(cx);
14210 window.draw(cx).clear(cx);
14211 let root = root.downcast::<InspectorTestRoot>().expect("test root");
14212 assert_eq!(
14213 root.read(cx)
14214 .child
14215 .read(cx)
14216 .child_widths
14217 .borrow()
14218 .as_slice(),
14219 &[px(10.); 3]
14220 );
14221 for frame in [&window.rendered_frame, &window.next_frame] {
14222 assert_eq!(frame.next_inspector_instance_ids.capacity(), 0);
14223 assert_eq!(frame.inspector_hitboxes.capacity(), 0);
14224 }
14225 })
14226 .expect("closed inspector has no bookkeeping and no style overrides");
14227 }
14228}
14229
14230#[cfg(test)]
14232mod vn_assume_active_tests {
14233 use crate::{
14234 Context, FocusHandle, Render, Subscription, TestAppContext, Window, div, prelude::*, px,
14235 size,
14236 };
14237 use std::{cell::Cell, rc::Rc};
14238
14239 struct Focusable {
14240 handle: FocusHandle,
14241 _on_focus: Subscription,
14242 }
14243
14244 impl Render for Focusable {
14245 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14246 div().size_full().track_focus(&self.handle)
14247 }
14248 }
14249
14250 #[gpui::test]
14251 fn an_assumed_active_window_runs_focus_and_ignores_the_os(cx: &mut TestAppContext) {
14252 let focused = Rc::new(Cell::new(0u32));
14253 let counter = focused.clone();
14254 let window = cx.open_window(size(px(200.), px(200.)), move |window, cx| {
14255 let handle = cx.focus_handle();
14256 let on_focus = cx.on_focus(&handle, window, move |_, _, _| counter.set(counter.get() + 1));
14257 Focusable { handle, _on_focus: on_focus }
14258 });
14259 let platform = cx.test_window(window.into());
14260 platform.simulate_active_status_change(false);
14261 cx.run_until_parked();
14262
14263 window
14266 .update(cx, |view, window, cx| window.focus(&view.handle, cx))
14267 .unwrap();
14268 cx.run_until_parked();
14269 assert_eq!(focused.get(), 0, "no focus event without activation");
14270
14271 window
14273 .update(cx, |_, window, _| window.set_assume_active(true))
14274 .unwrap();
14275 cx.run_until_parked();
14276 assert_eq!(focused.get(), 1, "the focus event carries the path");
14277 let active = |cx: &mut TestAppContext| {
14278 window
14279 .update(cx, |_, window, _| window.is_window_active())
14280 .unwrap()
14281 };
14282 assert!(active(cx));
14283
14284 platform.simulate_active_status_change(false);
14286 cx.run_until_parked();
14287 assert!(active(cx), "still active after the OS says otherwise");
14288
14289 window
14291 .update(cx, |_, window, _| window.set_assume_active(false))
14292 .unwrap();
14293 assert!(!active(cx));
14294 }
14295}
14296
14297#[cfg(test)]
14302mod vn_shadow_tests {
14303 use super::{SHADOW_INSET, SHADOW_OUTSIDE_BOX, SHADOW_UNDER_BOX, spread_shadow_radius};
14304 use crate::{
14305 BoxShadow, Context, Hsla, TestAppContext, Window, div, point, prelude::*, px, size,
14306 };
14307
14308 #[test]
14309 fn a_spread_grows_a_rounded_corner_and_keeps_a_square_one_square() {
14310 assert_eq!(spread_shadow_radius(px(6.), px(3.)), px(9.));
14312 assert_eq!(spread_shadow_radius(px(0.), px(3.)), px(0.));
14313 assert_eq!(spread_shadow_radius(px(1.5), px(3.)), px(1.5 + 3. * 0.875));
14315 assert_eq!(spread_shadow_radius(px(6.), px(0.)), px(6.));
14316 assert_eq!(spread_shadow_radius(px(6.), px(-2.)), px(4.));
14317 assert_eq!(spread_shadow_radius(px(1.), px(-2.)), px(0.));
14318 }
14319
14320 struct Ring {
14321 under_box: bool,
14322 }
14323
14324 impl Render for Ring {
14325 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14326 let shadow = |inset: bool| BoxShadow {
14327 color: Hsla::white().opacity(0.5),
14328 offset: point(px(0.), px(0.)),
14329 blur_radius: px(0.),
14330 spread_radius: px(3.),
14331 inset,
14332 };
14333 let mut d = div()
14334 .w(px(100.))
14335 .h(px(36.))
14336 .rounded_md()
14337 .shadow(vec![shadow(false), shadow(true)]);
14338 d.style().vn_shadow_under_box = Some(self.under_box);
14339 d
14340 }
14341 }
14342
14343 fn paint(under_box: bool, cx: &mut TestAppContext) -> (Vec<(u32, f32, f32)>, f32) {
14345 let window = cx.open_window(size(px(300.), px(300.)), move |_, _| Ring { under_box });
14346 cx.run_until_parked();
14347 window
14348 .update(cx, |_, window, _| {
14349 let shadows = window
14350 .rendered_frame
14351 .scene
14352 .shadows
14353 .iter()
14354 .map(|s| (s.inset, s.shape_corner_radii.top_left.0, s.corner_radii.top_left.0))
14355 .collect();
14356 (shadows, window.scale_factor())
14357 })
14358 .unwrap()
14359 }
14360
14361 #[gpui::test]
14362 fn an_outer_shadow_is_cut_out_of_the_border_box_unless_it_stands_in_for_the_box(
14363 cx: &mut TestAppContext,
14364 ) {
14365 let (shadows, scale) = paint(false, cx);
14366 let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
14367 assert_eq!(outer.0, SHADOW_OUTSIDE_BOX, "the shaders cut the border box out of it");
14368 assert_eq!(outer.1, 9. * scale, "6px corner + 3px spread");
14369 assert_eq!(outer.2, 6. * scale, "the cut-out is the border box itself");
14370 assert!(shadows.iter().any(|s| s.0 == SHADOW_INSET), "the inset shadow is unchanged");
14371
14372 let (shadows, _) = paint(true, cx);
14373 let outer = shadows.iter().find(|s| s.0 != SHADOW_INSET).expect("the outer shadow");
14374 assert_eq!(outer.0, SHADOW_UNDER_BOX);
14375 }
14376}
14377
14378#[cfg(test)]
14379mod vn_rounded_mask_tests {
14380 use super::transform_mask;
14381 use crate::{Bounds, ContentMask, Corners, TransformationMatrix, point, px, size};
14382
14383 fn mask(x: f32, y: f32, w: f32, h: f32, radius: f32) -> ContentMask<crate::Pixels> {
14384 ContentMask {
14385 bounds: Bounds::new(point(px(x), px(y)), size(px(w), px(h))),
14386 corner_radii: Corners::all(px(radius)),
14387 ..Default::default()
14388 }
14389 }
14390
14391 #[test]
14392 fn rectangles_intersect_exactly_and_stay_square() {
14393 let a = mask(0., 0., 100., 100., 0.);
14394 let b = mask(50., 20., 100., 30., 0.);
14395 let both = a.intersect(&b);
14396 assert_eq!(both.bounds, Bounds::new(point(px(50.), px(20.)), size(px(50.), px(30.))));
14397 assert!(!both.is_rounded());
14398 }
14399
14400 #[test]
14401 fn a_corner_keeps_the_radius_of_the_mask_it_belongs_to() {
14402 let card = mask(10., 10., 200., 160., 24.);
14404 let scroller = mask(10., 10., 200., 160., 0.);
14405 assert_eq!(scroller.intersect(&card).corner_radii, Corners::all(px(24.)));
14406 assert_eq!(card.intersect(&scroller).corner_radii, Corners::all(px(24.)));
14407
14408 let header = mask(10., 10., 200., 60., 0.);
14411 let clipped = header.intersect(&card);
14412 assert_eq!(clipped.corner_radii.top_left, px(24.));
14413 assert_eq!(clipped.corner_radii.top_right, px(24.));
14414 assert_eq!(clipped.corner_radii.bottom_left, px(0.));
14415 assert_eq!(clipped.corner_radii.bottom_right, px(0.));
14416
14417 let inner = mask(10., 10., 200., 160., 8.);
14420 assert_eq!(inner.intersect(&card).corner_radii, Corners::all(px(24.)));
14421
14422 let row = mask(40., 60., 100., 20., 0.);
14424 assert!(!row.intersect(&card).is_rounded());
14425
14426 let sliver = mask(10., 10., 200., 10., 0.);
14428 let clipped = sliver.intersect(&card);
14429 assert_eq!(clipped.corner_radii.top_left, px(5.));
14430 }
14431
14432 #[test]
14433 fn contains_follows_the_curve() {
14434 let avatar = mask(0., 0., 64., 64., 32.);
14435 assert!(avatar.contains(&point(px(32.), px(32.))));
14436 assert!(avatar.contains(&point(px(32.), px(1.))), "the top edge's middle");
14437 assert!(!avatar.contains(&point(px(2.), px(2.))), "outside the curve");
14438 assert!(!avatar.contains(&point(px(62.), px(62.))));
14439 assert!(avatar.contains(&point(px(10.), px(10.))), "inside the curve");
14440 assert!(!avatar.contains(&point(px(70.), px(32.))), "outside the rect");
14441 assert!(mask(0., 0., 64., 64., 0.).contains(&point(px(1.), px(1.))));
14442 }
14443
14444 #[test]
14445 fn a_transform_keeps_the_radii_only_while_corners_stay_round() {
14446 let card = mask(0., 0., 100., 100., 10.);
14447 let moved = TransformationMatrix {
14448 rotation_scale: [[1., 0.], [0., 1.]],
14449 translation: [5., 7.],
14450 };
14451 assert_eq!(transform_mask(moved, card, 1.).corner_radii, Corners::all(px(10.)));
14452
14453 let scaled = TransformationMatrix {
14454 rotation_scale: [[2., 0.], [0., 3.]],
14455 translation: [0., 0.],
14456 };
14457 assert_eq!(
14458 transform_mask(scaled, card, 1.).corner_radii,
14459 Corners::all(px(20.)),
14460 "the smaller factor"
14461 );
14462
14463 let rotated = TransformationMatrix {
14464 rotation_scale: [[0., 1.], [-1., 0.]],
14465 translation: [0., 0.],
14466 };
14467 assert!(!transform_mask(rotated, card, 1.).is_rounded());
14468 }
14469}
14470
14471#[cfg(test)]
14473mod vn_pointer_inside_tests {
14474 use crate::{
14475 Context, Modifiers, MouseExitEvent, MouseMoveEvent, PlatformInput, Render,
14476 TestAppContext, Window, div, point, prelude::*, px, size,
14477 };
14478 use std::{cell::Cell, rc::Rc};
14479
14480 struct Hoverable {
14481 hovered: Rc<Cell<bool>>,
14482 }
14483
14484 impl Render for Hoverable {
14485 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14486 let hovered = self.hovered.clone();
14487 div()
14488 .id("box")
14489 .size_full()
14490 .on_hover(move |is_hovered, _, _| hovered.set(*is_hovered))
14491 }
14492 }
14493
14494 #[gpui::test]
14495 fn a_pointer_outside_the_window_hovers_nothing(cx: &mut TestAppContext) {
14496 let hovered = Rc::new(Cell::new(false));
14497 let state = hovered.clone();
14498 let window = cx.open_window(size(px(200.), px(200.)), move |_, _| Hoverable {
14499 hovered: state,
14500 });
14501 let mut platform = cx.test_window(window.into());
14502 let draw = |cx: &mut TestAppContext| {
14503 window.update(cx, |_, window, _| window.refresh()).unwrap();
14504 cx.run_until_parked();
14505 };
14506 let at = |x: f32, y: f32| point(px(x), px(y));
14507 let moved = |x: f32, y: f32| {
14508 PlatformInput::MouseMove(MouseMoveEvent {
14509 position: at(x, y),
14510 pressed_button: None,
14511 modifiers: Modifiers::default(),
14512 })
14513 };
14514
14515 draw(cx);
14519 assert!(!hovered.get(), "a cursor that never entered hovers nothing");
14520
14521 platform.simulate_input(moved(50., 50.));
14522 draw(cx);
14523 assert!(hovered.get(), "a move into the box hovers it");
14524
14525 platform.simulate_hover_status_change(false);
14529 draw(cx);
14530 assert!(!hovered.get(), "a pointer that left hovers nothing");
14531
14532 platform.simulate_input(moved(60., 60.));
14533 draw(cx);
14534 assert!(hovered.get(), "back in");
14535
14536 platform.simulate_input(PlatformInput::MouseExited(MouseExitEvent {
14537 position: at(60., 60.),
14538 pressed_button: None,
14539 modifiers: Modifiers::default(),
14540 }));
14541 draw(cx);
14542 assert!(!hovered.get(), "MouseExited");
14543 }
14544
14545 struct Shaded {
14546 effect: bool,
14547 renders: Rc<Cell<usize>>,
14548 }
14549
14550 impl Render for Shaded {
14551 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14552 self.renders.set(self.renders.get() + 1);
14553 let mut element = div().size_full();
14554 if self.effect {
14555 let mut spec = crate::EffectSpec::NONE;
14556 spec.id = 0;
14557 spec.pointer_param = Some(4);
14558 element.style().vn_effect = Some(spec);
14559 }
14560 element
14561 }
14562 }
14563
14564 #[gpui::test]
14565 fn only_a_pointer_effect_repaints_when_the_pointer_moves(cx: &mut TestAppContext) {
14566 let open = |cx: &mut TestAppContext, effect: bool| {
14567 let renders = Rc::new(Cell::new(0));
14568 let counted = renders.clone();
14569 let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Shaded {
14570 effect,
14571 renders: counted,
14572 });
14573 cx.run_until_parked();
14574 (window, cx.test_window(window.into()), renders)
14575 };
14576 let moved = |x: f32, y: f32| {
14577 PlatformInput::MouseMove(MouseMoveEvent {
14578 position: point(px(x), px(y)),
14579 pressed_button: None,
14580 modifiers: Modifiers::default(),
14581 })
14582 };
14583
14584 let (_, mut platform, renders) = open(cx, false);
14585 platform.simulate_input(moved(10., 10.));
14586 cx.run_until_parked();
14587 let before = renders.get();
14588 platform.simulate_input(moved(20., 20.));
14589 cx.run_until_parked();
14590 assert_eq!(renders.get(), before, "no pointer effect, no repaint");
14591
14592 let (shaded, mut platform, renders) = open(cx, true);
14593 platform.simulate_input(moved(10., 10.));
14594 cx.run_until_parked();
14595 let before = renders.get();
14596 platform.simulate_input(moved(150., 25.));
14597 cx.run_until_parked();
14598 assert!(renders.get() > before, "a pointer effect repaints");
14599 let params = shaded
14600 .update(cx, |_, window, _| {
14601 window.rendered_frame.scene.effect_quads[0].params
14602 })
14603 .unwrap();
14604 assert!((params[4] - 0.75).abs() < 1e-4 && (params[5] - 0.25).abs() < 1e-4);
14605 }
14606
14607 struct Spinning {
14608 speed: Rc<Cell<f32>>,
14609 }
14610
14611 impl Render for Spinning {
14612 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
14613 let mut spec = crate::EffectSpec::NONE;
14614 spec.id = 0;
14615 spec.animated_param = Some(0);
14616 spec.params[0] = self.speed.get();
14617 let mut element = div().id("spinning").size_full();
14618 element.style().vn_effect = Some(spec);
14619 element
14620 }
14621 }
14622
14623 #[gpui::test]
14624 fn a_speed_change_continues_the_phase_instead_of_rescaling_the_clock(
14625 cx: &mut TestAppContext,
14626 ) {
14627 let speed = Rc::new(Cell::new(1.));
14628 let shared = speed.clone();
14629 let window = cx.open_window(size(px(200.), px(100.)), move |_, _| Spinning {
14630 speed: shared,
14631 });
14632 cx.run_until_parked();
14633 let repaint = |cx: &mut TestAppContext| {
14634 window.update(cx, |_, window, _| window.refresh()).unwrap();
14635 cx.run_until_parked();
14636 window
14637 .update(cx, |_, window, _| {
14638 let quad = window.rendered_frame.scene.effect_quads[0];
14639 (quad.params[0] * quad.time, quad.time)
14640 })
14641 .unwrap()
14642 };
14643 std::thread::sleep(std::time::Duration::from_millis(200));
14645 let (before, then) = repaint(cx);
14646 assert!((before - then).abs() < 1e-3, "an unchanged speed is `speed * time`");
14647
14648 speed.set(8.);
14649 let (after, now) = repaint(cx);
14650 let advanced = after - before;
14651 assert!(
14652 advanced >= -1e-3 && advanced <= 8. * (now - then) + 1e-3,
14653 "the phase moved by {advanced} in {}s",
14654 now - then
14655 );
14656 }
14657}
14658
14659#[cfg(test)]
14660mod vn_tagged_transform_tests {
14661 use crate::{
14662 AnyElement, App, Bounds, Context, Element, GlobalElementId, InspectorElementId,
14663 IntoElement, LayoutId, Pixels, Render, TestAppContext, TransformLength, TransformSpec,
14664 Window, div, prelude::*, px, size,
14665 };
14666 use std::{cell::RefCell, rc::Rc};
14667
14668 type Seen = Rc<RefCell<Vec<(u32, Bounds<Pixels>, Bounds<Pixels>)>>>;
14669
14670 struct Probe {
14673 tag: u32,
14674 inner: AnyElement,
14675 seen: Seen,
14676 }
14677
14678 impl Element for Probe {
14679 type RequestLayoutState = ();
14680 type PrepaintState = ();
14681 fn id(&self) -> Option<crate::ElementId> {
14682 None
14683 }
14684 fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
14685 None
14686 }
14687 fn request_layout(
14688 &mut self,
14689 _: Option<&GlobalElementId>,
14690 _: Option<&InspectorElementId>,
14691 window: &mut Window,
14692 cx: &mut App,
14693 ) -> (LayoutId, ()) {
14694 (self.inner.request_layout(window, cx), ())
14695 }
14696 fn prepaint(
14697 &mut self,
14698 _: Option<&GlobalElementId>,
14699 _: Option<&InspectorElementId>,
14700 bounds: Bounds<Pixels>,
14701 _: &mut (),
14702 window: &mut Window,
14703 cx: &mut App,
14704 ) {
14705 let ancestors = window.element_transform();
14706 let (_, own) =
14707 window.with_hitbox_tag(self.tag, |window| self.inner.prepaint(window, cx));
14708 let seen = window.transformed_bounds(own.unwrap_or(ancestors), bounds);
14709 self.seen.borrow_mut().push((self.tag, bounds, seen));
14710 }
14711 fn paint(
14712 &mut self,
14713 _: Option<&GlobalElementId>,
14714 _: Option<&InspectorElementId>,
14715 _: Bounds<Pixels>,
14716 _: &mut (),
14717 _: &mut (),
14718 window: &mut Window,
14719 cx: &mut App,
14720 ) {
14721 self.inner.paint(window, cx);
14722 }
14723 }
14724
14725 fn moved(x: TransformLength, y: TransformLength, scale: f32) -> TransformSpec {
14726 TransformSpec { translate: (x, y), scale: (scale, scale), ..TransformSpec::IDENTITY }
14727 }
14728
14729 struct Popper {
14732 seen: Seen,
14733 }
14734
14735 impl Render for Popper {
14736 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
14737 let probe = |tag, inner: AnyElement| Probe { tag, inner, seen: self.seen.clone() };
14738 let mut wrapper = div().w(px(100.)).h(px(80.));
14739 wrapper.style().vn_transform =
14740 Some(moved(TransformLength::Pixels(300.), TransformLength::Pixels(200.), 1.0));
14741 let mut scaled = div().w(px(20.)).h(px(10.));
14742 scaled.style().vn_transform =
14743 Some(moved(TransformLength::ZERO, TransformLength::ZERO, 2.0));
14744 let mut pseudo = div().w(px(4.)).h(px(4.));
14747 pseudo.style().vn_transform =
14748 Some(moved(TransformLength::Pixels(50.), TransformLength::ZERO, 1.0));
14749 let button = div()
14750 .ml(px(10.))
14751 .w(px(30.))
14752 .h(px(20.))
14753 .child(probe(3, scaled.into_any_element()))
14754 .child(pseudo);
14755 div().size_full().child(probe(
14756 1,
14757 wrapper.child(probe(2, button.into_any_element())).into_any_element(),
14758 ))
14759 }
14760 }
14761
14762 #[gpui::test]
14763 fn a_probe_sees_its_node_where_the_transforms_put_it(cx: &mut TestAppContext) {
14764 let seen: Seen = Rc::default();
14765 let state = seen.clone();
14766 let window =
14767 cx.open_window(size(px(800.), px(600.)), move |_, _| Popper { seen: state });
14768 window.update(cx, |_, window, _| window.refresh()).unwrap();
14769 cx.run_until_parked();
14770 let seen = seen.borrow();
14771 let at = |tag: u32| *seen.iter().rev().find(|s| s.0 == tag).expect("probed");
14772 let b = |x: f32, y: f32, w: f32, h: f32| {
14773 Bounds::new(crate::point(px(x), px(y)), size(px(w), px(h)))
14774 };
14775 assert_eq!(at(1).1, b(0., 0., 100., 80.));
14777 assert_eq!(at(1).2, b(300., 200., 100., 80.));
14778 assert_eq!(at(2).1, b(10., 0., 30., 20.));
14781 assert_eq!(at(2).2, b(310., 200., 30., 20.));
14782 assert_eq!(at(3).1, b(10., 0., 20., 10.));
14784 assert_eq!(at(3).2, b(300., 195., 40., 20.));
14785 }
14786}