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::{
8 Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
9 AsyncWindowContext, AtlasTile, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow,
10 Capslock, Context, Corners, CursorHideMode, CursorStyle, Decorations, DevicePixels,
11 DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
12 EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
13 Hsla, InputHandler, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke,
14 KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite,
15 MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas,
16 PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite,
17 Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage,
18 RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
19 SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,
20 StrikethroughStyle, Style, SubpixelSprite, SubscriberSet, Subscription, SystemWindowTab,
21 SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextInputConfiguration,
22 TextInputStateChange, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState,
23 TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance,
24 WindowBounds, WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem,
25 point, prelude::*, px, rems, size, transparent_black,
26};
27
28use crate::gestures::{GestureTuning, RecognizedTouchGesture, TouchGestureRecognizer};
29use crate::interactive::TouchEvent;
30use anyhow::{Context as _, Result, anyhow};
31use collections::{FxHashMap, FxHashSet};
32#[cfg(target_os = "macos")]
33use core_video::pixel_buffer::CVPixelBuffer;
34use derive_more::{Deref, DerefMut};
35use futures::FutureExt;
36use futures::channel::oneshot;
37use gpui_util::post_inc;
38use gpui_util::{ResultExt, measure};
39use itertools::FoldWhile::{Continue, Done};
40use itertools::Itertools;
41use parking_lot::RwLock;
42use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
43use refineable::Refineable;
44use scheduler::Instant;
45use slotmap::SlotMap;
46use smallvec::SmallVec;
47use std::{
48 any::{Any, TypeId},
49 borrow::Cow,
50 cell::{Cell, RefCell},
51 cmp,
52 fmt::{Debug, Display},
53 hash::{Hash, Hasher},
54 marker::PhantomData,
55 mem,
56 ops::{DerefMut, Range},
57 rc::Rc,
58 sync::{
59 Arc, Weak,
60 atomic::{AtomicBool, AtomicUsize, Ordering::SeqCst},
61 },
62 time::Duration,
63};
64use uuid::Uuid;
65
66pub(crate) mod a11y;
67mod prompts;
68
69pub use a11y::A11ySubtreeBuilder;
70
71use self::a11y::A11y;
72#[cfg(not(target_family = "wasm"))]
73use self::a11y::ROOT_NODE_ID;
74use crate::util::{
75 atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
76 round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
77};
78pub use prompts::*;
79
80pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
82
83pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
86 width: Pixels(900.),
87 height: Pixels(750.),
88};
89
90#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
92pub enum DispatchPhase {
93 #[default]
98 Bubble,
99 Capture,
105}
106
107impl DispatchPhase {
108 #[inline]
110 pub fn bubble(self) -> bool {
111 self == DispatchPhase::Bubble
112 }
113
114 #[inline]
116 pub fn capture(self) -> bool {
117 self == DispatchPhase::Capture
118 }
119}
120
121struct WindowInvalidatorInner {
122 #[cfg(feature = "profiler")]
123 pub window_id: WindowId,
124 pub dirty: bool,
125 pub draw_phase: DrawPhase,
126 pub dirty_views: FxHashSet<EntityId>,
127 pub update_count: usize,
128 #[cfg(feature = "profiler")]
129 pub frame_dirty: FrameDirtyAccumulator,
130 pub platform_waker: Option<Rc<dyn Fn()>>,
131}
132
133#[cfg(feature = "profiler")]
139#[derive(Default)]
140struct FrameDirtyAccumulator {
141 dirty_at: Option<Instant>,
142 invalidations: u64,
143}
144
145#[derive(Clone)]
146pub(crate) struct WindowInvalidator {
147 inner: Rc<RefCell<WindowInvalidatorInner>>,
148}
149
150impl WindowInvalidator {
151 pub fn new(#[allow(unused_variables)] window_id: WindowId) -> Self {
152 WindowInvalidator {
153 inner: Rc::new(RefCell::new(WindowInvalidatorInner {
154 #[cfg(feature = "profiler")]
155 window_id,
156 dirty: true,
157 draw_phase: DrawPhase::None,
158 dirty_views: FxHashSet::default(),
159 update_count: 0,
160 #[cfg(feature = "profiler")]
161 frame_dirty: FrameDirtyAccumulator::default(),
162 platform_waker: None,
163 })),
164 }
165 }
166
167 pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
168 let mut inner = self.inner.borrow_mut();
169 inner.update_count += 1;
170 inner.dirty_views.insert(entity);
171 if inner.draw_phase == DrawPhase::None {
172 #[cfg(feature = "profiler")]
173 let dirty_at = Self::record_frame_dirty(&mut inner);
174 let became_dirty = !inner.dirty;
175 inner.dirty = true;
176 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
177 #[cfg(feature = "profiler")]
178 let window_id = inner.window_id;
179 drop(inner);
180 #[cfg(feature = "profiler")]
181 if became_dirty {
182 profiler::journal::record_frame_pending(window_id, dirty_at);
183 }
184 cx.push_effect(Effect::Notify { emitter: entity });
185 if let Some(waker) = waker {
186 waker();
187 }
188 true
189 } else {
190 false
191 }
192 }
193
194 pub fn is_dirty(&self) -> bool {
195 self.inner.borrow().dirty
196 }
197
198 pub fn set_dirty(&self, dirty: bool) {
199 let mut inner = self.inner.borrow_mut();
200 let became_dirty = dirty && !inner.dirty;
201 inner.dirty = dirty;
202 if dirty {
203 inner.update_count += 1;
204 }
205 #[cfg(feature = "profiler")]
206 let dirty_at = dirty.then(|| Self::record_frame_dirty(&mut inner));
207 let waker = became_dirty.then(|| inner.platform_waker.clone()).flatten();
208 #[cfg(feature = "profiler")]
209 let window_id = inner.window_id;
210 drop(inner);
211 #[cfg(feature = "profiler")]
212 if became_dirty && let Some(dirty_at) = dirty_at {
213 profiler::journal::record_frame_pending(window_id, dirty_at);
214 }
215 if let Some(waker) = waker {
216 waker();
217 }
218 }
219
220 pub fn set_platform_waker(&self, waker: Option<Rc<dyn Fn()>>) {
221 let mut inner = self.inner.borrow_mut();
222 inner.platform_waker = waker;
223 let waker = inner.dirty.then(|| inner.platform_waker.clone()).flatten();
224 drop(inner);
225 if let Some(waker) = waker {
226 waker();
227 }
228 }
229
230 pub fn wake_platform(&self) {
234 let waker = self.inner.borrow().platform_waker.clone();
235 if let Some(waker) = waker {
236 waker();
237 }
238 }
239
240 pub fn set_phase(&self, phase: DrawPhase) {
241 self.inner.borrow_mut().draw_phase = phase
242 }
243
244 pub fn update_count(&self) -> usize {
245 self.inner.borrow().update_count
246 }
247
248 #[cfg(feature = "profiler")]
249 fn record_frame_dirty(inner: &mut WindowInvalidatorInner) -> Instant {
250 let dirty_at = *inner.frame_dirty.dirty_at.get_or_insert_with(Instant::now);
251 inner.frame_dirty.invalidations += 1;
252 dirty_at
253 }
254
255 #[cfg(feature = "profiler")]
256 fn take_frame_dirty(&self) -> FrameDirtyAccumulator {
257 mem::take(&mut self.inner.borrow_mut().frame_dirty)
258 }
259
260 pub fn take_views(&self) -> FxHashSet<EntityId> {
261 mem::take(&mut self.inner.borrow_mut().dirty_views)
262 }
263
264 pub fn replace_views(&self, views: FxHashSet<EntityId>) {
265 self.inner.borrow_mut().dirty_views = views;
266 }
267
268 pub fn not_drawing(&self) -> bool {
269 self.inner.borrow().draw_phase == DrawPhase::None
270 }
271
272 #[track_caller]
273 pub fn debug_assert_paint(&self) {
274 debug_assert!(
275 matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
276 "this method can only be called during paint"
277 );
278 }
279
280 #[track_caller]
281 pub fn debug_assert_prepaint(&self) {
282 debug_assert!(
283 matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
284 "this method can only be called during request_layout, or prepaint"
285 );
286 }
287
288 #[track_caller]
289 pub fn debug_assert_paint_or_prepaint(&self) {
290 debug_assert!(
291 matches!(
292 self.inner.borrow().draw_phase,
293 DrawPhase::Paint | DrawPhase::Prepaint
294 ),
295 "this method can only be called during request_layout, prepaint, or paint"
296 );
297 }
298}
299
300type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
301
302pub(crate) type AnyWindowFocusListener =
303 Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
304
305pub(crate) struct WindowFocusEvent {
306 pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
307 pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
308}
309
310impl WindowFocusEvent {
311 pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
312 !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
313 }
314
315 pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
316 self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
317 }
318}
319
320pub struct FocusOutEvent {
322 pub blurred: WeakFocusHandle,
324}
325
326slotmap::new_key_type! {
327 pub struct FocusId;
329}
330
331thread_local! {
332 pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
335
336 static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
340}
341
342fn draw_in_progress() -> bool {
353 CURRENT_ELEMENT_ARENA.with(|current| current.get().is_some())
354}
355
356pub(crate) fn with_element_arena<R>(f: impl FnOnce(&mut Arena) -> R) -> R {
359 CURRENT_ELEMENT_ARENA.with(|current| {
360 if let Some(arena_ptr) = current.get() {
361 let arena_cell = unsafe { &*arena_ptr };
364 f(&mut arena_cell.borrow_mut())
365 } else {
366 ELEMENT_ARENA.with_borrow_mut(f)
367 }
368 })
369}
370
371pub(crate) struct ElementArenaScope {
386 entered: *const RefCell<Arena>,
389 previous: Option<*const RefCell<Arena>>,
390 exited: bool,
391}
392
393impl ElementArenaScope {
394 pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
396 arena.borrow_mut().begin_scope();
397 let previous = CURRENT_ELEMENT_ARENA.with(|current| {
398 let prev = current.get();
399 current.set(Some(arena as *const RefCell<Arena>));
400 prev
401 });
402 Self {
403 entered: arena as *const RefCell<Arena>,
404 previous,
405 exited: false,
406 }
407 }
408
409 pub(crate) fn exit(mut self, arena: &RefCell<Arena>) -> ArenaClearNeeded {
418 assert!(
419 std::ptr::eq(self.entered, arena),
420 "ElementArenaScope::exit called with a different arena than was entered"
421 );
422 self.exited = true;
423 ArenaClearNeeded::new(arena)
428 }
429}
430
431impl Drop for ElementArenaScope {
432 fn drop(&mut self) {
433 CURRENT_ELEMENT_ARENA.with(|current| {
440 current.set(self.previous);
441 });
442 unsafe { &*self.entered }.borrow_mut().end_scope();
446 if !self.exited && !std::thread::panicking() {
447 debug_assert!(false, "ElementArenaScope dropped without calling exit()");
448 log::error!(
449 "ElementArenaScope dropped without calling exit(); \
450 the arena clear for this draw was never requested"
451 );
452 }
453 }
454}
455
456#[must_use]
458pub struct ArenaClearNeeded {
459 arena: *const RefCell<Arena>,
462}
463
464impl ArenaClearNeeded {
465 fn new(arena: &RefCell<Arena>) -> Self {
468 Self {
469 arena: arena as *const RefCell<Arena>,
470 }
471 }
472
473 pub fn clear(self, cx: &mut App) {
482 assert!(
483 std::ptr::eq(self.arena, &cx.element_arena),
484 "ArenaClearNeeded::clear called with a different App than the draw ran against"
485 );
486 cx.element_arena.borrow_mut().clear();
487 }
488}
489
490pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;
491pub(crate) struct FocusRef {
492 pub(crate) ref_count: AtomicUsize,
493 pub(crate) tab_index: isize,
494 pub(crate) tab_stop: bool,
495}
496
497impl FocusId {
498 pub fn is_focused(&self, window: &Window) -> bool {
500 window.focus == Some(*self)
501 }
502
503 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
506 window
507 .focused(cx)
508 .is_some_and(|focused| self.contains(focused.id, window))
509 }
510
511 pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
514 let focused = window.focused(cx);
515 focused.is_some_and(|focused| focused.id.contains(*self, window))
516 }
517
518 pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
520 window
521 .rendered_frame
522 .dispatch_tree
523 .focus_contains(*self, other)
524 }
525}
526
527pub struct FocusHandle {
529 pub(crate) id: FocusId,
530 handles: Arc<FocusMap>,
531 pub tab_index: isize,
533 pub tab_stop: bool,
535}
536
537impl std::fmt::Debug for FocusHandle {
538 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
539 f.write_fmt(format_args!("FocusHandle({:?})", self.id))
540 }
541}
542
543impl FocusHandle {
544 pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
545 let id = handles.write().insert(FocusRef {
546 ref_count: AtomicUsize::new(1),
547 tab_index: 0,
548 tab_stop: false,
549 });
550
551 Self {
552 id,
553 tab_index: 0,
554 tab_stop: false,
555 handles: handles.clone(),
556 }
557 }
558
559 pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
560 let lock = handles.read();
561 let focus = lock.get(id)?;
562 if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
563 return None;
564 }
565 Some(Self {
566 id,
567 tab_index: focus.tab_index,
568 tab_stop: focus.tab_stop,
569 handles: handles.clone(),
570 })
571 }
572
573 pub fn tab_index(mut self, index: isize) -> Self {
575 self.tab_index = index;
576 if let Some(focus) = self.handles.write().get_mut(self.id) {
577 focus.tab_index = index;
578 }
579 self
580 }
581
582 pub fn tab_stop(mut self, tab_stop: bool) -> Self {
586 self.tab_stop = tab_stop;
587 if let Some(focus) = self.handles.write().get_mut(self.id) {
588 focus.tab_stop = tab_stop;
589 }
590 self
591 }
592
593 pub fn downgrade(&self) -> WeakFocusHandle {
595 WeakFocusHandle {
596 id: self.id,
597 handles: Arc::downgrade(&self.handles),
598 }
599 }
600
601 pub fn focus(&self, window: &mut Window, cx: &mut App) {
603 window.focus(self, cx)
604 }
605
606 pub fn is_focused(&self, window: &Window) -> bool {
608 self.id.is_focused(window)
609 }
610
611 pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
614 self.id.contains_focused(window, cx)
615 }
616
617 pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
620 self.id.within_focused(window, cx)
621 }
622
623 pub fn contains(&self, other: &Self, window: &Window) -> bool {
625 self.id.contains(other.id, window)
626 }
627
628 pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
630 if let Some(node_id) = window
631 .rendered_frame
632 .dispatch_tree
633 .focusable_node_id(self.id)
634 {
635 window.dispatch_action_on_node(node_id, action, cx)
636 }
637 }
638}
639
640impl Clone for FocusHandle {
641 fn clone(&self) -> Self {
642 Self::for_id(self.id, &self.handles).unwrap()
643 }
644}
645
646impl PartialEq for FocusHandle {
647 fn eq(&self, other: &Self) -> bool {
648 self.id == other.id
649 }
650}
651
652impl Eq for FocusHandle {}
653
654impl Drop for FocusHandle {
655 fn drop(&mut self) {
656 self.handles
657 .read()
658 .get(self.id)
659 .unwrap()
660 .ref_count
661 .fetch_sub(1, SeqCst);
662 }
663}
664
665#[derive(Clone, Debug)]
667pub struct WeakFocusHandle {
668 pub(crate) id: FocusId,
669 pub(crate) handles: Weak<FocusMap>,
670}
671
672impl WeakFocusHandle {
673 pub fn upgrade(&self) -> Option<FocusHandle> {
675 let handles = self.handles.upgrade()?;
676 FocusHandle::for_id(self.id, &handles)
677 }
678}
679
680impl PartialEq for WeakFocusHandle {
681 fn eq(&self, other: &WeakFocusHandle) -> bool {
682 self.id == other.id
683 }
684}
685
686impl Eq for WeakFocusHandle {}
687
688impl PartialEq<FocusHandle> for WeakFocusHandle {
689 fn eq(&self, other: &FocusHandle) -> bool {
690 self.id == other.id
691 }
692}
693
694impl PartialEq<WeakFocusHandle> for FocusHandle {
695 fn eq(&self, other: &WeakFocusHandle) -> bool {
696 self.id == other.id
697 }
698}
699
700pub trait Focusable: 'static {
703 fn focus_handle(&self, cx: &App) -> FocusHandle;
705}
706
707impl<V: Focusable> Focusable for Entity<V> {
708 fn focus_handle(&self, cx: &App) -> FocusHandle {
709 self.read(cx).focus_handle(cx)
710 }
711}
712
713pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
716
717impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
718
719pub struct DismissEvent;
721
722type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
723
724pub(crate) type AnyMouseListener =
725 Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
726
727#[derive(Clone)]
728pub(crate) struct CursorStyleRequest {
729 pub(crate) hitbox_id: Option<HitboxId>,
730 pub(crate) style: CursorStyle,
731}
732
733#[derive(Default, Eq, PartialEq)]
734pub(crate) struct HitTest {
735 pub(crate) ids: SmallVec<[HitboxId; 8]>,
736 pub(crate) hover_hitbox_count: usize,
737}
738
739#[derive(Clone, Copy, Debug, Eq, PartialEq)]
741pub enum WindowControlArea {
742 Drag,
744 Close,
746 Max,
748 Min,
750}
751
752#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
754pub struct HitboxId(u64);
755
756#[cfg(feature = "test-support")]
757impl HitboxId {
758 pub const fn placeholder() -> Self {
763 Self(0)
764 }
765}
766
767impl HitboxId {
768 pub fn is_hovered(self, window: &Window) -> bool {
775 if window.captured_hitbox == Some(self) {
777 return true;
778 }
779 if window.last_input_was_keyboard() {
780 return false;
781 }
782 self.hit_test(window)
783 }
784
785 pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
790 if window.captured_hitbox == Some(self) {
792 return true;
793 }
794 self.hit_test(window)
795 }
796
797 fn hit_test(self, window: &Window) -> bool {
798 let hit_test = &window.mouse_hit_test;
799 for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
800 if self == *id {
801 return true;
802 }
803 }
804 false
805 }
806
807 pub fn should_handle_scroll(self, window: &Window) -> bool {
812 window.mouse_hit_test.ids.contains(&self)
813 }
814
815 fn next(mut self) -> HitboxId {
816 HitboxId(self.0.wrapping_add(1))
817 }
818}
819
820#[derive(Clone, Debug, Deref)]
823pub struct Hitbox {
824 pub id: HitboxId,
826 #[deref]
828 pub bounds: Bounds<Pixels>,
829 pub content_mask: ContentMask<Pixels>,
831 pub behavior: HitboxBehavior,
833}
834
835impl Hitbox {
836 pub fn is_hovered(&self, window: &Window) -> bool {
853 self.id.is_hovered(window)
854 }
855
856 pub fn should_handle_scroll(&self, window: &Window) -> bool {
863 self.id.should_handle_scroll(window)
864 }
865}
866
867#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
869pub enum HitboxBehavior {
870 #[default]
872 Normal,
873
874 BlockMouse,
896
897 BlockMouseExceptScroll,
924}
925
926#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
928pub struct TooltipId(usize);
929
930impl TooltipId {
931 pub fn is_hovered(&self, window: &Window) -> bool {
933 window
934 .tooltip_bounds
935 .as_ref()
936 .is_some_and(|tooltip_bounds| {
937 tooltip_bounds.id == *self
938 && tooltip_bounds.bounds.contains(&window.mouse_position())
939 })
940 }
941}
942
943pub(crate) struct TooltipBounds {
944 id: TooltipId,
945 bounds: Bounds<Pixels>,
946}
947
948#[derive(Clone)]
949pub(crate) struct TooltipRequest {
950 id: TooltipId,
951 tooltip: AnyTooltip,
952}
953
954pub(crate) struct DeferredDraw {
955 current_view: EntityId,
956 priority: usize,
957 parent_node: DispatchNodeId,
958 element_id_stack: SmallVec<[ElementId; 32]>,
959 text_style_stack: Vec<TextStyleRefinement>,
960 content_mask: Option<ContentMask<Pixels>>,
961 rem_size: Pixels,
962 element: Option<AnyElement>,
963 absolute_offset: Point<Pixels>,
964 prepaint_range: Range<PrepaintStateIndex>,
965 paint_range: Range<PaintIndex>,
966}
967
968pub(crate) struct Frame {
969 pub(crate) focus: Option<FocusId>,
970 pub(crate) window_active: bool,
971 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
972 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
973 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
974 pub(crate) dispatch_tree: DispatchTree,
975 pub(crate) scene: Scene,
976 pub(crate) hitboxes: Vec<Hitbox>,
977 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
978 pub(crate) deferred_draws: Vec<DeferredDraw>,
979 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
980 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
981 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
982 #[cfg(any(test, feature = "test-support"))]
983 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
984 #[cfg(any(feature = "inspector", debug_assertions))]
985 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
986 #[cfg(any(feature = "inspector", debug_assertions))]
987 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
988 pub(crate) tab_stops: TabStopMap,
989}
990
991#[derive(Clone, Default)]
992pub(crate) struct PrepaintStateIndex {
993 hitboxes_index: usize,
994 tooltips_index: usize,
995 deferred_draws_index: usize,
996 dispatch_tree_index: usize,
997 accessed_element_states_index: usize,
998 line_layout_index: LineLayoutIndex,
999}
1000
1001#[derive(Clone, Default)]
1002pub(crate) struct PaintIndex {
1003 scene_index: usize,
1004 mouse_listeners_index: usize,
1005 input_handlers_index: usize,
1006 cursor_styles_index: usize,
1007 accessed_element_states_index: usize,
1008 tab_handle_index: usize,
1009 line_layout_index: LineLayoutIndex,
1010}
1011
1012impl Frame {
1013 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
1014 Frame {
1015 focus: None,
1016 window_active: false,
1017 element_states: FxHashMap::default(),
1018 accessed_element_states: Vec::new(),
1019 mouse_listeners: Vec::new(),
1020 dispatch_tree,
1021 scene: Scene::default(),
1022 hitboxes: Vec::new(),
1023 window_control_hitboxes: Vec::new(),
1024 deferred_draws: Vec::new(),
1025 input_handlers: Vec::new(),
1026 tooltip_requests: Vec::new(),
1027 cursor_styles: Vec::new(),
1028
1029 #[cfg(any(test, feature = "test-support"))]
1030 debug_bounds: FxHashMap::default(),
1031
1032 #[cfg(any(feature = "inspector", debug_assertions))]
1033 next_inspector_instance_ids: FxHashMap::default(),
1034
1035 #[cfg(any(feature = "inspector", debug_assertions))]
1036 inspector_hitboxes: FxHashMap::default(),
1037 tab_stops: TabStopMap::default(),
1038 }
1039 }
1040
1041 pub(crate) fn clear(&mut self) {
1042 self.element_states.clear();
1043 self.accessed_element_states.clear();
1044 self.mouse_listeners.clear();
1045 self.dispatch_tree.clear();
1046 self.scene.clear();
1047 self.input_handlers.clear();
1048 self.tooltip_requests.clear();
1049 self.cursor_styles.clear();
1050 self.hitboxes.clear();
1051 self.window_control_hitboxes.clear();
1052 self.deferred_draws.clear();
1053 self.tab_stops.clear();
1054 self.focus = None;
1055
1056 #[cfg(any(test, feature = "test-support"))]
1057 {
1058 self.debug_bounds.clear();
1059 }
1060
1061 #[cfg(any(feature = "inspector", debug_assertions))]
1062 {
1063 self.next_inspector_instance_ids.clear();
1064 self.inspector_hitboxes.clear();
1065 }
1066 }
1067
1068 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1069 self.cursor_styles
1070 .iter()
1071 .rev()
1072 .fold_while(None, |style, request| match request.hitbox_id {
1073 None => Done(Some(request.style)),
1074 Some(hitbox_id) => Continue(style.or_else(|| {
1075 hitbox_id
1076 .is_hovered_ignoring_last_input(window)
1077 .then_some(request.style)
1078 })),
1079 })
1080 .into_inner()
1081 }
1082
1083 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
1084 let mut set_hover_hitbox_count = false;
1085 let mut hit_test = HitTest::default();
1086 for hitbox in self.hitboxes.iter().rev() {
1087 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
1088 if bounds.contains(&position) {
1089 hit_test.ids.push(hitbox.id);
1090 if !set_hover_hitbox_count
1091 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1092 {
1093 hit_test.hover_hitbox_count = hit_test.ids.len();
1094 set_hover_hitbox_count = true;
1095 }
1096 if hitbox.behavior == HitboxBehavior::BlockMouse {
1097 break;
1098 }
1099 }
1100 }
1101 if !set_hover_hitbox_count {
1102 hit_test.hover_hitbox_count = hit_test.ids.len();
1103 }
1104 hit_test
1105 }
1106
1107 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1108 self.focus
1109 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1110 .unwrap_or_default()
1111 }
1112
1113 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1114 for element_state_key in &self.accessed_element_states {
1115 if let Some((element_state_key, element_state)) =
1116 prev_frame.element_states.remove_entry(element_state_key)
1117 {
1118 self.element_states.insert(element_state_key, element_state);
1119 }
1120 }
1121
1122 self.scene.finish();
1123 }
1124}
1125
1126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1127enum InputModality {
1128 Mouse,
1129 Keyboard,
1130 Touch,
1131}
1132
1133pub struct Window {
1135 pub(crate) handle: AnyWindowHandle,
1136 pub(crate) invalidator: WindowInvalidator,
1137 pub(crate) removed: bool,
1138 pub(crate) platform_window: Box<dyn PlatformWindow>,
1139 display_id: Option<DisplayId>,
1140 is_resizable: bool,
1141 is_minimizable: bool,
1142 sprite_atlas: Arc<dyn PlatformAtlas>,
1143 text_system: Arc<WindowTextSystem>,
1144 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1145 rem_size: Pixels,
1146 rem_size_override_stack: SmallVec<[Pixels; 8]>,
1151 pub(crate) viewport_size: Size<Pixels>,
1152 layout_engine: Option<TaffyLayoutEngine>,
1153 pub(crate) root: Option<AnyView>,
1154 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
1155 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1156 pub(crate) rendered_entity_stack: Vec<EntityId>,
1157 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1158 pub(crate) element_opacity: f32,
1159 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1160 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1161 last_text_input_configuration: Option<TextInputConfiguration>,
1165 focused_text_input_active: bool,
1166 pub(crate) image_cache_stack: Vec<AnyImageCache>,
1167 pub(crate) rendered_frame: Frame,
1168 pub(crate) next_frame: Frame,
1169 next_hitbox_id: HitboxId,
1170 pub(crate) next_tooltip_id: TooltipId,
1171 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1172 pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1173 pub(crate) dirty_views: FxHashSet<EntityId>,
1174 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
1175 pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
1176 focus_lost_path: SmallVec<[FocusId; 8]>,
1177 default_prevented: bool,
1178 mouse_position: Point<Pixels>,
1179 mouse_hit_test: HitTest,
1180 modifiers: Modifiers,
1181 capslock: Capslock,
1182 scale_factor: f32,
1183 pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
1184 appearance: WindowAppearance,
1185 pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
1186 pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>,
1187 active: Rc<Cell<bool>>,
1188 hovered: Rc<Cell<bool>>,
1189 pub(crate) needs_present: Rc<Cell<bool>>,
1190 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1193 #[cfg(feature = "profiler")]
1194 window_profiler: profiler::WindowProfiler,
1195 last_input_modality: InputModality,
1196 touch_gestures: TouchGestureRecognizer,
1197 touch_prediction_enabled: bool,
1198 long_press_timer: Option<Task<()>>,
1199 long_press_capture: Option<EntityId>,
1200 pub(crate) refreshing: bool,
1201 pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
1202 pub(crate) focus: Option<FocusId>,
1203 focus_enabled: bool,
1204 pub(crate) focus_generation: u64,
1207 pending_input: Option<PendingInput>,
1208 pending_modifier: ModifierState,
1209 pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
1210 prompt: Option<RenderablePromptHandle>,
1211 pub(crate) client_inset: Option<Pixels>,
1212 captured_hitbox: Option<HitboxId>,
1215 #[cfg(any(feature = "inspector", debug_assertions))]
1216 inspector: Option<Entity<Inspector>>,
1217 #[cfg(feature = "profiler")]
1218 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1219 pub(crate) a11y: A11y,
1220}
1221
1222#[derive(Clone, Debug, Default)]
1223struct ModifierState {
1224 modifiers: Modifiers,
1225 saw_other_input: bool,
1226}
1227
1228#[derive(Clone, Debug)]
1231pub(crate) struct InputRateTracker {
1232 timestamps: Vec<Instant>,
1233 window: Duration,
1234 inputs_per_second: u32,
1235 sustain_until: Instant,
1236 sustain_duration: Duration,
1237}
1238
1239impl Default for InputRateTracker {
1240 fn default() -> Self {
1241 Self {
1242 timestamps: Vec::new(),
1243 window: Duration::from_millis(100),
1244 inputs_per_second: 60,
1245 sustain_until: Instant::now(),
1246 sustain_duration: Duration::from_secs(1),
1247 }
1248 }
1249}
1250
1251impl InputRateTracker {
1252 pub fn record_input(&mut self) {
1253 let now = Instant::now();
1254 self.timestamps.push(now);
1255 self.prune_old_timestamps(now);
1256
1257 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1258 if self.timestamps.len() as u128 >= min_events {
1259 self.sustain_until = now + self.sustain_duration;
1260 }
1261 }
1262
1263 pub fn is_high_rate(&self) -> bool {
1264 Instant::now() < self.sustain_until
1265 }
1266
1267 fn prune_old_timestamps(&mut self, now: Instant) {
1268 self.timestamps
1269 .retain(|&t| now.duration_since(t) <= self.window);
1270 }
1271}
1272
1273#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1274pub(crate) enum DrawPhase {
1275 None,
1276 Prepaint,
1277 Paint,
1278 Focus,
1279}
1280
1281pub(crate) const PENDING_INPUT_TIMEOUT: Duration = Duration::from_secs(1);
1282
1283pub struct PendingInputStatus<'a> {
1285 keystrokes: &'a [Keystroke],
1286 timeout: Option<PendingInputTimeoutStatus>,
1287}
1288
1289impl<'a> PendingInputStatus<'a> {
1290 pub fn keystrokes(&self) -> &'a [Keystroke] {
1292 self.keystrokes
1293 }
1294
1295 pub fn timeout(&self) -> Option<PendingInputTimeoutStatus> {
1297 self.timeout
1298 }
1299}
1300
1301#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1303pub struct PendingInputTimeoutStatus {
1304 duration: Duration,
1305 remaining: Duration,
1306 started_at: Option<Instant>,
1307 paused: bool,
1308}
1309
1310impl PendingInputTimeoutStatus {
1311 pub fn duration(&self) -> Duration {
1313 self.duration
1314 }
1315
1316 pub fn remaining(&self, cx: &App) -> Duration {
1318 self.started_at
1319 .map(|started_at| {
1320 self.remaining
1321 .saturating_sub(cx.background_executor().now() - started_at)
1322 })
1323 .unwrap_or(self.remaining)
1324 }
1325
1326 pub fn is_paused(&self) -> bool {
1328 self.paused
1329 }
1330}
1331
1332#[derive(Debug)]
1333struct PendingInputTimeout {
1334 duration: Duration,
1335 remaining: Duration,
1336 state: PendingInputTimeoutState,
1337}
1338
1339#[derive(Debug)]
1340enum PendingInputTimeoutState {
1341 Running { started_at: Instant, task: Task<()> },
1342 Paused { pause: PendingInputTimeoutPause },
1343}
1344
1345#[derive(Debug)]
1346struct PendingInputTimeoutPause {
1347 owner_id: EntityId,
1348 _release_subscription: Subscription,
1349}
1350
1351impl PendingInputTimeout {
1352 fn is_paused(&self) -> bool {
1353 matches!(&self.state, PendingInputTimeoutState::Paused { .. })
1354 }
1355
1356 fn pause(&mut self, pause: PendingInputTimeoutPause, now: Instant) -> bool {
1357 match std::mem::replace(&mut self.state, PendingInputTimeoutState::Paused { pause }) {
1358 PendingInputTimeoutState::Running { started_at, task } => {
1359 self.remaining = self.remaining.saturating_sub(now - started_at);
1360 drop(task);
1361 true
1362 }
1363 previous_state @ PendingInputTimeoutState::Paused { .. } => {
1364 self.state = previous_state;
1365 false
1366 }
1367 }
1368 }
1369
1370 fn pause_owner_id(&self) -> Option<EntityId> {
1371 match &self.state {
1372 PendingInputTimeoutState::Running { .. } => None,
1373 PendingInputTimeoutState::Paused { pause } => Some(pause.owner_id),
1374 }
1375 }
1376
1377 fn resume(&mut self, owner_id: EntityId, started_at: Instant, task: Task<()>) -> bool {
1378 match std::mem::replace(
1379 &mut self.state,
1380 PendingInputTimeoutState::Running { started_at, task },
1381 ) {
1382 PendingInputTimeoutState::Paused { pause } if pause.owner_id == owner_id => true,
1383 previous_state => {
1384 self.state = previous_state;
1385 false
1386 }
1387 }
1388 }
1389
1390 fn reset_duration(&mut self, duration: Duration) {
1391 self.duration = duration;
1392 self.remaining = duration;
1393 }
1394
1395 fn status(&self) -> PendingInputTimeoutStatus {
1396 let (started_at, paused) = match &self.state {
1397 PendingInputTimeoutState::Running { started_at, .. } => (Some(*started_at), false),
1398 PendingInputTimeoutState::Paused { .. } => (None, true),
1399 };
1400 PendingInputTimeoutStatus {
1401 duration: self.duration,
1402 remaining: self.remaining,
1403 started_at,
1404 paused,
1405 }
1406 }
1407}
1408
1409#[derive(Default, Debug)]
1410struct PendingInput {
1411 keystrokes: SmallVec<[Keystroke; 1]>,
1412 focus: Option<FocusId>,
1413 timeout: Option<PendingInputTimeout>,
1414}
1415
1416pub(crate) struct ElementStateBox {
1417 pub(crate) inner: Box<dyn Any>,
1418 #[cfg(debug_assertions)]
1419 pub(crate) type_name: &'static str,
1420}
1421
1422fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1423 let active_window_bounds = cx
1428 .active_window()
1429 .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1430
1431 const CASCADE_OFFSET: f32 = 25.0;
1432
1433 let display = display_id
1434 .map(|id| cx.find_display(id))
1435 .unwrap_or_else(|| cx.primary_display());
1436
1437 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1438
1439 let display_bounds = display
1441 .as_ref()
1442 .map(|d| d.visible_bounds())
1443 .unwrap_or_else(default_placement);
1444
1445 let (
1446 Bounds {
1447 origin: base_origin,
1448 size: base_size,
1449 },
1450 window_bounds_ctor,
1451 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1452 Some(bounds) => match bounds {
1453 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1454 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1455 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1456 },
1457 None => (
1458 display
1459 .as_ref()
1460 .map(|d| d.default_bounds())
1461 .unwrap_or_else(default_placement),
1462 WindowBounds::Windowed,
1463 ),
1464 };
1465
1466 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1467 let proposed_origin = base_origin + cascade_offset;
1468 let proposed_bounds = Bounds::new(proposed_origin, base_size);
1469
1470 let display_right = display_bounds.origin.x + display_bounds.size.width;
1471 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1472 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1473 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1474
1475 let fits_horizontally = window_right <= display_right;
1476 let fits_vertically = window_bottom <= display_bottom;
1477
1478 let final_origin = match (fits_horizontally, fits_vertically) {
1479 (true, true) => proposed_origin,
1480 (false, true) => point(display_bounds.origin.x, base_origin.y),
1481 (true, false) => point(base_origin.x, display_bounds.origin.y),
1482 (false, false) => display_bounds.origin,
1483 };
1484 window_bounds_ctor(Bounds::new(final_origin, base_size))
1485}
1486
1487impl Window {
1488 pub(crate) fn new(
1489 handle: AnyWindowHandle,
1490 options: WindowOptions,
1491 cx: &mut App,
1492 ) -> Result<Self> {
1493 let WindowOptions {
1494 window_bounds,
1495 titlebar,
1496 focus,
1497 show,
1498 kind,
1499 is_movable,
1500 app_owns_titlebar_drag,
1501 inactive_frame_interval,
1502 is_resizable,
1503 is_minimizable,
1504 display_id,
1505 window_background,
1506 app_id,
1507 window_min_size,
1508 window_decorations,
1509 #[cfg_attr(
1510 not(any(target_os = "linux", target_os = "freebsd")),
1511 allow(unused_variables)
1512 )]
1513 icon,
1514 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1515 tabbing_identifier,
1516 } = options;
1517
1518 let initial_window_title = titlebar
1519 .as_ref()
1520 .and_then(|titlebar| titlebar.title.clone());
1521
1522 let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1523 let mut platform_window = cx.platform.open_window(
1524 handle,
1525 WindowParams {
1526 bounds: window_bounds.get_bounds(),
1527 titlebar,
1528 kind,
1529 is_movable,
1530 app_owns_titlebar_drag,
1531 is_resizable,
1532 is_minimizable,
1533 focus,
1534 show,
1535 display_id,
1536 window_min_size,
1537 app_id: app_id.clone(),
1538 icon,
1539 #[cfg(target_os = "macos")]
1540 tabbing_identifier,
1541 },
1542 )?;
1543
1544 let tab_bar_visible = platform_window.tab_bar_visible();
1545 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1546 if let Some(tabs) = platform_window.tabbed_windows() {
1547 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1548 }
1549
1550 let display_id = platform_window.display().map(|display| display.id());
1551 let sprite_atlas = platform_window.sprite_atlas();
1552 let mouse_position = platform_window.mouse_position();
1553 let modifiers = platform_window.modifiers();
1554 let capslock = platform_window.capslock();
1555 let content_size = platform_window.content_size();
1556 let scale_factor = platform_window.scale_factor();
1557 let appearance = platform_window.appearance();
1558 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1559 let invalidator = WindowInvalidator::new(handle.window_id());
1560 let active = Rc::new(Cell::new(platform_window.is_active()));
1561 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1562 let needs_present = Rc::new(Cell::new(false));
1563 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1564 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1565 let last_frame_time = Rc::new(Cell::new(None));
1566
1567 platform_window
1568 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1569 platform_window.set_background_appearance(window_background);
1570
1571 match window_bounds {
1572 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1573 WindowBounds::Maximized(_) => platform_window.zoom(),
1574 WindowBounds::Windowed(_) => {}
1575 }
1576
1577 let accessibility_force_disabled = cx.accessibility_force_disabled;
1578 let a11y_active_flag = Arc::new(AtomicBool::new(false));
1579
1580 #[cfg(not(target_family = "wasm"))]
1581 if !accessibility_force_disabled {
1582 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
1583 if let Some(title) = &initial_window_title {
1584 initial_root_node.set_label(title.to_string());
1585 }
1586 let initial_tree = accesskit::TreeUpdate {
1587 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
1588 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
1589 tree_id: accesskit::TreeId::ROOT,
1590 focus: ROOT_NODE_ID,
1591 };
1592 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
1593 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
1594 let (action_sender, action_receiver) =
1595 async_channel::unbounded::<accesskit::ActionRequest>();
1596
1597 platform_window.a11y_init(crate::A11yCallbacks {
1598 activation: {
1599 let active_flag = a11y_active_flag.clone();
1600 Box::new(move || {
1601 log::info!("Accessibility activated");
1602 active_flag.store(true, SeqCst);
1603 activation_sender.send_blocking(()).log_err();
1604 Some(initial_tree.clone())
1605 })
1606 },
1607 action: Box::new(move |request| {
1608 action_sender.send_blocking(request).log_err();
1609 }),
1610 deactivation: {
1611 let active_flag = a11y_active_flag.clone();
1612 Box::new(move || {
1613 log::info!("Accessibility deactivated");
1614 active_flag.store(false, SeqCst);
1615 deactivation_sender.send_blocking(()).log_err();
1616 })
1617 },
1618 });
1619
1620 let mut async_cx = cx.to_async();
1626 cx.foreground_executor()
1627 .spawn(async move {
1628 while activation_receiver.recv().await.is_ok() {
1629 handle
1630 .update(&mut async_cx, |_, window, _| window.refresh())
1631 .log_err();
1632 }
1633 })
1634 .detach();
1635
1636 let mut async_cx = cx.to_async();
1637 cx.foreground_executor()
1638 .spawn(async move {
1639 while deactivation_receiver.recv().await.is_ok() {
1640 handle
1641 .update(&mut async_cx, |_, window, _| window.refresh())
1642 .log_err();
1643 }
1644 })
1645 .detach();
1646
1647 let mut async_cx = cx.to_async();
1648 cx.foreground_executor()
1649 .spawn(async move {
1650 while let Ok(request) = action_receiver.recv().await {
1651 handle
1652 .update(&mut async_cx, |_, window, cx| {
1653 window.handle_a11y_action(request, cx);
1654 })
1655 .log_err();
1656 }
1657 })
1658 .detach();
1659 }
1660
1661 platform_window.on_close(Box::new({
1662 let window_id = handle.window_id();
1663 let mut cx = cx.to_async();
1664 move || {
1665 let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
1666 let _ = cx.update(|cx| {
1667 SystemWindowTabController::remove_tab(cx, window_id);
1668 });
1669 }
1670 }));
1671 platform_window.on_request_frame(Box::new({
1672 let mut cx = cx.to_async();
1673 let invalidator = invalidator.clone();
1674 let active = active.clone();
1675 let needs_present = needs_present.clone();
1676 let next_frame_callbacks = next_frame_callbacks.clone();
1677 let input_rate_tracker = input_rate_tracker.clone();
1678 let mut deferred_force_render = false;
1679 move |request_frame_options| {
1680 #[cfg(feature = "profiler")]
1681 let _foreground_turn = profiler::journal::foreground_turn();
1682 if draw_in_progress() {
1698 log::debug!("deferring re-entrant window draw request");
1699 deferred_force_render |= request_frame_options.force_render;
1700 return;
1701 }
1702 let force_render =
1706 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
1707
1708 let thermal_state = handle
1709 .update(&mut cx, |_, _, cx| cx.thermal_state())
1710 .log_err();
1711
1712 let min_frame_interval = if request_frame_options.require_presentation
1716 || (!request_frame_options.force_render
1717 && next_frame_callbacks.borrow().is_empty())
1718 {
1719 None
1720 } else if !active.get() && !input_rate_tracker.borrow_mut().is_high_rate() {
1721 inactive_frame_interval
1722 } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
1723 Some(Duration::from_micros(16667))
1724 } else {
1725 None
1726 };
1727
1728 let now = Instant::now();
1729 if let Some(min_interval) = min_frame_interval {
1730 if let Some(last_frame) = last_frame_time.get()
1731 && now.duration_since(last_frame) < min_interval
1732 {
1733 deferred_force_render |= force_render;
1735 handle
1737 .update(&mut cx, |_, window, _| {
1738 window.platform_window.schedule_frame();
1739 })
1740 .log_err();
1741 invalidator.wake_platform();
1746 return;
1747 }
1748 }
1749 last_frame_time.set(Some(now));
1750
1751 let pending_next_frame_callbacks = next_frame_callbacks.take();
1752 if !pending_next_frame_callbacks.is_empty() {
1753 handle
1754 .update(&mut cx, |_, window, cx| {
1755 for callback in pending_next_frame_callbacks {
1756 callback(window, cx);
1757 }
1758 })
1759 .log_err();
1760 }
1761
1762 let needs_present = request_frame_options.require_presentation
1766 || needs_present.get()
1767 || input_rate_tracker.borrow_mut().is_high_rate();
1768
1769 if invalidator.is_dirty() || force_render {
1770 measure("frame duration", || {
1771 handle
1772 .update(&mut cx, |_, window, cx| {
1773 if force_render {
1774 window.refresh();
1777 }
1778 let arena_clear_needed = window.draw(cx);
1779 window.present();
1780 arena_clear_needed.clear(cx);
1781 })
1782 .log_err();
1783 })
1784 } else if needs_present {
1785 handle
1786 .update(&mut cx, |_, window, _| window.present())
1787 .log_err();
1788 }
1789
1790 handle
1791 .update(&mut cx, |_, window, _| {
1792 if window.invalidator.is_dirty()
1793 || !window.next_frame_callbacks.borrow().is_empty()
1794 {
1795 window.platform_window.schedule_frame();
1796 }
1797 })
1798 .log_err();
1799
1800 if invalidator.is_dirty() || !next_frame_callbacks.borrow().is_empty() {
1806 invalidator.wake_platform();
1807 }
1808 }
1809 }));
1810 invalidator.set_platform_waker(platform_window.frame_waker());
1811 platform_window.on_resize(Box::new({
1812 let mut cx = cx.to_async();
1813 move |_, _| {
1814 handle
1815 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1816 .log_err();
1817 }
1818 }));
1819 platform_window.on_moved(Box::new({
1820 let mut cx = cx.to_async();
1821 move || {
1822 handle
1823 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1824 .log_err();
1825 }
1826 }));
1827 platform_window.on_appearance_changed(Box::new({
1828 let cx = cx.to_async();
1829 let foreground_executor = cx.foreground_executor().clone();
1830 move || {
1831 let mut cx = cx.clone();
1832 foreground_executor
1835 .spawn(async move {
1836 handle
1837 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1838 .log_err();
1839 })
1840 .detach();
1841 }
1842 }));
1843 platform_window.on_button_layout_changed(Box::new({
1844 let mut cx = cx.to_async();
1845 move || {
1846 handle
1847 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
1848 .log_err();
1849 }
1850 }));
1851 platform_window.on_active_status_change(Box::new({
1852 let mut cx = cx.to_async();
1853 move |active| {
1854 handle
1855 .update(&mut cx, |_, window, cx| {
1856 window.active.set(active);
1857 window.modifiers = window.platform_window.modifiers();
1858 window.capslock = window.platform_window.capslock();
1859 window
1860 .activation_observers
1861 .clone()
1862 .retain(&(), |callback| callback(window, cx));
1863
1864 window.bounds_changed(cx);
1865 window.refresh();
1866
1867 SystemWindowTabController::update_last_active(cx, window.handle.id);
1868 })
1869 .log_err();
1870 }
1871 }));
1872 platform_window.on_hover_status_change(Box::new({
1873 let mut cx = cx.to_async();
1874 move |active| {
1875 handle
1876 .update(&mut cx, |_, window, _| {
1877 window.hovered.set(active);
1878 window.refresh();
1879 })
1880 .log_err();
1881 }
1882 }));
1883 platform_window.on_input({
1884 let mut cx = cx.to_async();
1885 Box::new(move |event| {
1886 handle
1887 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1888 .log_err()
1889 .unwrap_or(DispatchEventResult::default())
1890 })
1891 });
1892 platform_window.on_hit_test_window_control({
1893 let mut cx = cx.to_async();
1894 Box::new(move || {
1895 handle
1896 .update(&mut cx, |_, window, _cx| {
1897 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1898 if window.mouse_hit_test.ids.contains(&hitbox.id) {
1899 return Some(*area);
1900 }
1901 }
1902 None
1903 })
1904 .log_err()
1905 .unwrap_or(None)
1906 })
1907 });
1908 platform_window.on_move_tab_to_new_window({
1909 let mut cx = cx.to_async();
1910 Box::new(move || {
1911 handle
1912 .update(&mut cx, |_, _window, cx| {
1913 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1914 })
1915 .log_err();
1916 })
1917 });
1918 platform_window.on_merge_all_windows({
1919 let mut cx = cx.to_async();
1920 Box::new(move || {
1921 handle
1922 .update(&mut cx, |_, _window, cx| {
1923 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1924 })
1925 .log_err();
1926 })
1927 });
1928 platform_window.on_select_next_tab({
1929 let mut cx = cx.to_async();
1930 Box::new(move || {
1931 handle
1932 .update(&mut cx, |_, _window, cx| {
1933 SystemWindowTabController::select_next_tab(cx, handle.window_id());
1934 })
1935 .log_err();
1936 })
1937 });
1938 platform_window.on_select_previous_tab({
1939 let mut cx = cx.to_async();
1940 Box::new(move || {
1941 handle
1942 .update(&mut cx, |_, _window, cx| {
1943 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1944 })
1945 .log_err();
1946 })
1947 });
1948 platform_window.on_toggle_tab_bar({
1949 let mut cx = cx.to_async();
1950 Box::new(move || {
1951 handle
1952 .update(&mut cx, |_, window, cx| {
1953 let tab_bar_visible = window.platform_window.tab_bar_visible();
1954 SystemWindowTabController::set_visible(cx, tab_bar_visible);
1955 })
1956 .log_err();
1957 })
1958 });
1959
1960 if let Some(app_id) = app_id {
1961 platform_window.set_app_id(&app_id);
1962 }
1963
1964 platform_window.map_window().unwrap();
1965
1966 Ok(Window {
1967 handle,
1968 invalidator,
1969 removed: false,
1970 platform_window,
1971 display_id,
1972 is_resizable,
1973 is_minimizable,
1974 sprite_atlas,
1975 text_system,
1976 text_rendering_mode: cx.text_rendering_mode.clone(),
1977 rem_size: px(16.),
1978 rem_size_override_stack: SmallVec::new(),
1979 viewport_size: content_size,
1980 layout_engine: Some(TaffyLayoutEngine::new()),
1981 root: None,
1982 element_id_stack: SmallVec::default(),
1983 text_style_stack: Vec::new(),
1984 rendered_entity_stack: Vec::new(),
1985 element_offset_stack: Vec::new(),
1986 content_mask_stack: Vec::new(),
1987 element_opacity: 1.0,
1988 requested_autoscroll: None,
1989 last_text_input_configuration: None,
1990 focused_text_input_active: false,
1991 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1992 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1993 next_frame_callbacks,
1994 next_hitbox_id: HitboxId(0),
1995 next_tooltip_id: TooltipId::default(),
1996 tooltip_bounds: None,
1997 dirty_views: FxHashSet::default(),
1998 focus_listeners: SubscriberSet::new(),
1999 focus_lost_listeners: SubscriberSet::new(),
2000 focus_lost_path: SmallVec::new(),
2001 default_prevented: true,
2002 mouse_position,
2003 mouse_hit_test: HitTest::default(),
2004 modifiers,
2005 capslock,
2006 scale_factor,
2007 bounds_observers: SubscriberSet::new(),
2008 appearance,
2009 appearance_observers: SubscriberSet::new(),
2010 button_layout_observers: SubscriberSet::new(),
2011 active,
2012 hovered,
2013 needs_present,
2014 input_rate_tracker,
2015 #[cfg(feature = "profiler")]
2016 window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
2017 last_input_modality: InputModality::Mouse,
2018 touch_gestures: TouchGestureRecognizer::new(
2019 cx.platform
2020 .gestures()
2021 .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
2022 ),
2023 touch_prediction_enabled: true,
2024 long_press_timer: None,
2025 long_press_capture: None,
2026 refreshing: false,
2027 activation_observers: SubscriberSet::new(),
2028 focus: None,
2029 focus_enabled: true,
2030 focus_generation: 0,
2031 pending_input: None,
2032 pending_modifier: ModifierState::default(),
2033 pending_input_observers: SubscriberSet::new(),
2034 prompt: None,
2035 client_inset: None,
2036 image_cache_stack: Vec::new(),
2037 captured_hitbox: None,
2038 #[cfg(any(feature = "inspector", debug_assertions))]
2039 inspector: None,
2040 #[cfg(feature = "profiler")]
2041 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
2042 a11y: A11y::new(
2043 a11y_active_flag,
2044 accessibility_force_disabled,
2045 initial_window_title,
2046 ),
2047 })
2048 }
2049
2050 pub(crate) fn new_focus_listener(
2051 &self,
2052 value: AnyWindowFocusListener,
2053 ) -> (Subscription, impl FnOnce() + use<>) {
2054 self.focus_listeners.insert((), value)
2055 }
2056}
2057
2058#[derive(Clone, Debug, Default, PartialEq, Eq)]
2059#[expect(missing_docs)]
2060pub struct DispatchEventResult {
2061 pub propagate: bool,
2062 pub default_prevented: bool,
2063}
2064
2065#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
2069#[repr(C)]
2070pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
2071 pub bounds: Bounds<P>,
2073}
2074
2075impl ContentMask<Pixels> {
2076 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
2078 ContentMask {
2079 bounds: self.bounds.scale(factor),
2080 }
2081 }
2082
2083 pub fn intersect(&self, other: &Self) -> Self {
2085 let bounds = self.bounds.intersect(&other.bounds);
2086 ContentMask { bounds }
2087 }
2088}
2089
2090impl Window {
2091 fn mark_view_dirty(&mut self, view_id: EntityId) {
2092 for view_id in self
2095 .rendered_frame
2096 .dispatch_tree
2097 .view_path_reversed(view_id)
2098 {
2099 if !self.dirty_views.insert(view_id) {
2100 break;
2101 }
2102 }
2103 }
2104
2105 pub fn observe_window_appearance(
2107 &self,
2108 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2109 ) -> Subscription {
2110 let (subscription, activate) = self.appearance_observers.insert(
2111 (),
2112 Box::new(move |window, cx| {
2113 callback(window, cx);
2114 true
2115 }),
2116 );
2117 activate();
2118 subscription
2119 }
2120
2121 pub fn observe_button_layout_changed(
2123 &self,
2124 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2125 ) -> Subscription {
2126 let (subscription, activate) = self.button_layout_observers.insert(
2127 (),
2128 Box::new(move |window, cx| {
2129 callback(window, cx);
2130 true
2131 }),
2132 );
2133 activate();
2134 subscription
2135 }
2136
2137 pub fn replace_root<E>(
2139 &mut self,
2140 cx: &mut App,
2141 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
2142 ) -> Entity<E>
2143 where
2144 E: 'static + Render,
2145 {
2146 let view = cx.new(|cx| build_view(self, cx));
2147 self.root = Some(view.clone().into());
2148 self.refresh();
2149 view
2150 }
2151
2152 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
2154 where
2155 E: 'static + Render,
2156 {
2157 self.root
2158 .as_ref()
2159 .map(|view| view.clone().downcast::<E>().ok())
2160 }
2161
2162 pub fn window_handle(&self) -> AnyWindowHandle {
2164 self.handle
2165 }
2166
2167 pub fn refresh(&mut self) {
2169 if self.invalidator.not_drawing() {
2170 self.refreshing = true;
2171 self.invalidator.set_dirty(true);
2172 }
2173 }
2174
2175 pub fn remove_window(&mut self) {
2177 self.removed = true;
2178 }
2179
2180 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
2182 self.focus
2183 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
2184 }
2185
2186 pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
2190 let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
2191 ancestors.iter().rev().find_map(|id| {
2192 self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
2193 FocusHandle::for_id(*id, &cx.focus_handles)
2194 })
2195 }
2196
2197 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
2199 if !self.focus_enabled || self.focus == Some(handle.id) {
2200 return;
2201 }
2202
2203 self.focus = Some(handle.id);
2204 self.focus_generation = self.focus_generation.wrapping_add(1);
2205 self.clear_pending_keystrokes(cx);
2206
2207 self.refresh();
2208 }
2209
2210 pub fn blur(&mut self, cx: &mut App) {
2212 self.clear_pending_keystrokes(cx);
2213
2214 if !self.focus_enabled {
2215 return;
2216 }
2217
2218 if self.focus.is_some() {
2219 self.focus_generation = self.focus_generation.wrapping_add(1);
2220 }
2221 self.focus = None;
2222 self.refresh();
2223 }
2224
2225 pub fn disable_focus(&mut self, cx: &mut App) {
2227 self.blur(cx);
2228 self.focus_enabled = false;
2229 }
2230
2231 pub fn focus_next(&mut self, cx: &mut App) {
2233 if !self.focus_enabled {
2234 return;
2235 }
2236
2237 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
2238 self.focus(&handle, cx)
2239 }
2240 }
2241
2242 pub fn focus_prev(&mut self, cx: &mut App) {
2244 if !self.focus_enabled {
2245 return;
2246 }
2247
2248 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
2249 self.focus(&handle, cx)
2250 }
2251 }
2252
2253 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
2255 &self.text_system
2256 }
2257
2258 pub fn text_style(&self) -> TextStyle {
2260 let mut style = TextStyle::default();
2261 for refinement in &self.text_style_stack {
2262 style.refine(refinement);
2263 }
2264 style
2265 }
2266
2267 pub fn is_maximized(&self) -> bool {
2271 self.platform_window.is_maximized()
2272 }
2273
2274 pub fn request_decorations(&self, decorations: WindowDecorations) {
2276 self.platform_window.request_decorations(decorations);
2277 }
2278
2279 pub fn set_exclusive_zone(&self, zone: Pixels) {
2285 self.platform_window.set_exclusive_zone(zone);
2286 }
2287
2288 #[cfg(all(target_os = "linux", feature = "wayland"))]
2293 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
2294 self.platform_window.set_exclusive_edge(edge);
2295 }
2296
2297 pub fn start_window_resize(&self, edge: ResizeEdge) {
2299 if self.is_resizable {
2300 self.platform_window.start_window_resize(edge);
2301 }
2302 }
2303
2304 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
2311 self.platform_window.set_input_region(region);
2312 }
2313
2314 pub fn window_bounds(&self) -> WindowBounds {
2317 self.platform_window.window_bounds()
2318 }
2319
2320 pub fn inner_window_bounds(&self) -> WindowBounds {
2322 self.platform_window.inner_window_bounds()
2323 }
2324
2325 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
2327 let focus_id = self.focused(cx).map(|handle| handle.id);
2328
2329 let window = self.handle;
2330 cx.defer(move |cx| {
2331 window
2332 .update(cx, |_, window, cx| {
2333 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
2334 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
2335 })
2336 .log_err();
2337 })
2338 }
2339
2340 pub(crate) fn dispatch_keystroke_observers(
2341 &mut self,
2342 event: &dyn Any,
2343 action: Option<Box<dyn Action>>,
2344 context_stack: Vec<KeyContext>,
2345 cx: &mut App,
2346 ) {
2347 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2348 return;
2349 };
2350
2351 cx.keystroke_observers.clone().retain(&(), move |callback| {
2352 (callback)(
2353 &KeystrokeEvent {
2354 keystroke: key_down_event.keystroke.clone(),
2355 action: action.as_ref().map(|action| action.boxed_clone()),
2356 context_stack: context_stack.clone(),
2357 },
2358 self,
2359 cx,
2360 )
2361 });
2362 }
2363
2364 pub(crate) fn dispatch_keystroke_interceptors(
2365 &mut self,
2366 event: &dyn Any,
2367 context_stack: Vec<KeyContext>,
2368 cx: &mut App,
2369 ) {
2370 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2371 return;
2372 };
2373
2374 cx.keystroke_interceptors
2375 .clone()
2376 .retain(&(), move |callback| {
2377 (callback)(
2378 &KeystrokeEvent {
2379 keystroke: key_down_event.keystroke.clone(),
2380 action: None,
2381 context_stack: context_stack.clone(),
2382 },
2383 self,
2384 cx,
2385 )
2386 });
2387 }
2388
2389 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2392 let handle = self.handle;
2393 cx.defer(move |cx| {
2394 handle.update(cx, |_, window, cx| f(window, cx)).ok();
2395 });
2396 }
2397
2398 pub fn observe<T: 'static>(
2402 &mut self,
2403 observed: &Entity<T>,
2404 cx: &mut App,
2405 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2406 ) -> Subscription {
2407 let entity_id = observed.entity_id();
2408 let observed = observed.downgrade();
2409 let window_handle = self.handle;
2410 cx.new_observer(
2411 entity_id,
2412 Box::new(move |cx| {
2413 window_handle
2414 .update(cx, |_, window, cx| {
2415 if let Some(handle) = observed.upgrade() {
2416 on_notify(handle, window, cx);
2417 true
2418 } else {
2419 false
2420 }
2421 })
2422 .unwrap_or(false)
2423 }),
2424 )
2425 }
2426
2427 pub fn subscribe<Emitter, Evt>(
2431 &mut self,
2432 entity: &Entity<Emitter>,
2433 cx: &mut App,
2434 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
2435 ) -> Subscription
2436 where
2437 Emitter: EventEmitter<Evt>,
2438 Evt: 'static,
2439 {
2440 let entity_id = entity.entity_id();
2441 let handle = entity.downgrade();
2442 let window_handle = self.handle;
2443 cx.new_subscription(
2444 entity_id,
2445 (
2446 TypeId::of::<Evt>(),
2447 Box::new(move |event, cx| {
2448 window_handle
2449 .update(cx, |_, window, cx| {
2450 if let Some(entity) = handle.upgrade() {
2451 let event = event.downcast_ref().expect("invalid event type");
2452 on_event(entity, event, window, cx);
2453 true
2454 } else {
2455 false
2456 }
2457 })
2458 .unwrap_or(false)
2459 }),
2460 ),
2461 )
2462 }
2463
2464 pub fn observe_release<T>(
2466 &self,
2467 entity: &Entity<T>,
2468 cx: &mut App,
2469 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2470 ) -> Subscription
2471 where
2472 T: 'static,
2473 {
2474 let entity_id = entity.entity_id();
2475 let window_handle = self.handle;
2476 let (subscription, activate) = cx.release_listeners.insert(
2477 entity_id,
2478 Box::new(move |entity, cx| {
2479 let entity = entity.downcast_mut().expect("invalid entity type");
2480 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2481 }),
2482 );
2483 activate();
2484 subscription
2485 }
2486
2487 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2490 AsyncWindowContext::new_context(cx.to_async(), self.handle)
2491 }
2492
2493 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2495 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2496 self.platform_window.schedule_frame();
2497 self.invalidator.wake_platform();
2500 }
2501
2502 pub fn request_animation_frame(&self) {
2515 let entity = self.current_view();
2516 self.on_next_frame(move |_, cx| cx.notify(entity));
2517 }
2518
2519 #[cfg(any(test, feature = "test-support"))]
2524 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
2525 let callbacks = self.next_frame_callbacks.take();
2526 let count = callbacks.len();
2527 for callback in callbacks {
2528 callback(self, cx);
2529 }
2530 count
2531 }
2532
2533 #[track_caller]
2537 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2538 where
2539 R: 'static,
2540 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2541 {
2542 let handle = self.handle;
2543 cx.spawn(async move |app| {
2544 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2545 f(&mut async_window_cx).await
2546 })
2547 }
2548
2549 #[track_caller]
2553 pub fn spawn_with_priority<AsyncFn, R>(
2554 &self,
2555 priority: Priority,
2556 cx: &App,
2557 f: AsyncFn,
2558 ) -> Task<R>
2559 where
2560 R: 'static,
2561 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2562 {
2563 let handle = self.handle;
2564 cx.spawn_with_priority(priority, async move |app| {
2565 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2566 f(&mut async_window_cx).await
2567 })
2568 }
2569
2570 pub fn bounds_changed(&mut self, cx: &mut App) {
2576 self.scale_factor = self.platform_window.scale_factor();
2577 self.viewport_size = self.platform_window.content_size();
2578 self.display_id = self.platform_window.display().map(|display| display.id());
2579 self.mouse_position = self.platform_window.mouse_position();
2580
2581 self.refresh();
2582
2583 self.bounds_observers
2584 .clone()
2585 .retain(&(), |callback| callback(self, cx));
2586 }
2587
2588 pub fn bounds(&self) -> Bounds<Pixels> {
2590 self.platform_window.bounds()
2591 }
2592
2593 #[cfg(any(test, feature = "test-support"))]
2597 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
2598 self.platform_window
2599 .render_to_image(&self.rendered_frame.scene)
2600 }
2601
2602 #[cfg(any(test, feature = "test-support"))]
2607 pub fn painted_quads(&self) -> Vec<Quad> {
2608 self.rendered_frame.scene.quads.clone()
2609 }
2610
2611 pub fn resize(&mut self, size: Size<Pixels>) {
2613 self.platform_window.resize(size);
2614 }
2615
2616 pub fn is_fullscreen(&self) -> bool {
2618 self.platform_window.is_fullscreen()
2619 }
2620
2621 pub fn is_simple_fullscreen(&self) -> bool {
2625 self.platform_window.is_simple_fullscreen()
2626 }
2627
2628 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
2629 self.appearance = self.platform_window.appearance();
2630
2631 self.appearance_observers
2632 .clone()
2633 .retain(&(), |callback| callback(self, cx));
2634 }
2635
2636 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2637 self.button_layout_observers
2638 .clone()
2639 .retain(&(), |callback| callback(self, cx));
2640 }
2641
2642 pub fn appearance(&self) -> WindowAppearance {
2644 self.appearance
2645 }
2646
2647 pub fn viewport_size(&self) -> Size<Pixels> {
2649 self.viewport_size
2650 }
2651
2652 pub fn is_window_active(&self) -> bool {
2654 self.active.get()
2655 }
2656
2657 pub fn is_window_hovered(&self) -> bool {
2661 if cfg!(any(
2662 target_os = "windows",
2663 target_os = "linux",
2664 target_os = "freebsd"
2665 )) {
2666 self.hovered.get()
2667 } else {
2668 self.is_window_active()
2669 }
2670 }
2671
2672 pub fn zoom_window(&self) {
2674 self.platform_window.zoom();
2675 }
2676
2677 pub fn show_window_menu(&self, position: Point<Pixels>) {
2679 self.platform_window.show_window_menu(position)
2680 }
2681
2682 pub fn start_window_move(&self) {
2687 self.platform_window.start_window_move()
2688 }
2689
2690 pub fn set_client_inset(&mut self, inset: Pixels) {
2692 self.client_inset = Some(inset);
2693 self.platform_window.set_client_inset(inset);
2694 }
2695
2696 pub fn client_inset(&self) -> Option<Pixels> {
2698 self.client_inset
2699 }
2700
2701 pub fn window_decorations(&self) -> Decorations {
2703 self.platform_window.window_decorations()
2704 }
2705
2706 pub fn is_resizable(&self) -> bool {
2708 self.is_resizable
2709 }
2710
2711 pub fn is_minimizable(&self) -> bool {
2713 self.is_minimizable
2714 }
2715
2716 pub fn window_controls(&self) -> WindowControls {
2718 self.platform_window.window_controls()
2719 }
2720
2721 pub fn set_window_title(&mut self, title: &str) {
2723 self.platform_window.set_title(title);
2724 self.a11y.set_window_title(title.to_string());
2725 }
2726
2727 #[cfg(target_os = "macos")]
2729 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
2730 self.platform_window.set_traffic_light_position(position);
2731 }
2732
2733 pub fn set_app_id(&mut self, app_id: &str) {
2735 self.platform_window.set_app_id(app_id);
2736 }
2737
2738 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2740 self.platform_window
2741 .set_background_appearance(background_appearance);
2742 }
2743
2744 pub fn set_window_edited(&mut self, edited: bool) {
2746 self.platform_window.set_edited(edited);
2747 }
2748
2749 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
2752 self.platform_window.set_document_path(path);
2753 }
2754
2755 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2757 cx.platform
2758 .displays()
2759 .into_iter()
2760 .find(|display| Some(display.id()) == self.display_id)
2761 }
2762
2763 pub fn show_character_palette(&self) {
2765 self.platform_window.show_character_palette();
2766 }
2767
2768 pub fn scale_factor(&self) -> f32 {
2772 self.scale_factor
2773 }
2774
2775 #[cfg(any(test, feature = "test-support"))]
2777 pub fn set_scale_factor(&mut self, scale_factor: f32) {
2778 self.scale_factor = scale_factor;
2779 self.refresh();
2780 }
2781
2782 pub fn rem_size(&self) -> Pixels {
2785 self.rem_size_override_stack
2786 .last()
2787 .copied()
2788 .unwrap_or(self.rem_size)
2789 }
2790
2791 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2794 self.rem_size = rem_size.into();
2795 }
2796
2797 pub fn with_global_id<R>(
2800 &mut self,
2801 element_id: ElementId,
2802 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2803 ) -> R {
2804 self.with_id(element_id, |this| {
2805 let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2806
2807 f(&global_id, this)
2808 })
2809 }
2810
2811 #[inline]
2813 pub fn with_id<R>(
2814 &mut self,
2815 element_id: impl Into<ElementId>,
2816 f: impl FnOnce(&mut Self) -> R,
2817 ) -> R {
2818 self.element_id_stack.push(element_id.into());
2819 let result = f(self);
2820 self.element_id_stack.pop();
2821 result
2822 }
2823
2824 #[inline]
2830 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2831 where
2832 F: FnOnce(&mut Self) -> R,
2833 {
2834 self.invalidator.debug_assert_paint_or_prepaint();
2835
2836 if let Some(rem_size) = rem_size {
2837 self.rem_size_override_stack.push(rem_size.into());
2838 let result = f(self);
2839 self.rem_size_override_stack.pop();
2840 result
2841 } else {
2842 f(self)
2843 }
2844 }
2845
2846 pub fn line_height(&self) -> Pixels {
2848 self.text_style().line_height_in_pixels(self.rem_size())
2849 }
2850
2851 #[inline]
2853 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
2854 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
2855 }
2856
2857 #[inline]
2859 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
2860 let scale_factor = f64::from(self.scale_factor());
2861 round_half_toward_zero_f64(value * scale_factor) / scale_factor
2862 }
2863
2864 #[inline]
2866 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
2867 bounds.map(|c| self.pixel_snap(c))
2868 }
2869
2870 #[inline]
2872 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
2873 position.map(|c| self.pixel_snap(c))
2874 }
2875
2876 #[inline]
2877 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2878 let scale_factor = self.scale_factor();
2879 let left = round_to_device_pixel(bounds.left().0, scale_factor);
2880 let top = round_to_device_pixel(bounds.top().0, scale_factor);
2881 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
2882 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2883 Bounds::from_corners(
2884 point(ScaledPixels(left), ScaledPixels(top)),
2885 point(ScaledPixels(right), ScaledPixels(bottom)),
2886 )
2887 }
2888
2889 #[inline]
2891 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
2892 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
2893 }
2894
2895 #[inline]
2896 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
2897 edges.map(|e| self.snap_stroke(*e))
2898 }
2899
2900 #[inline]
2902 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2903 let scale_factor = self.scale_factor();
2904 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
2905 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
2906 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
2907 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2908 Bounds::from_corners(
2909 point(ScaledPixels(left), ScaledPixels(top)),
2910 point(ScaledPixels(right), ScaledPixels(bottom)),
2911 )
2912 }
2913
2914 #[inline]
2915 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
2916 ContentMask {
2917 bounds: self.cover_bounds(self.content_mask().bounds),
2918 }
2919 }
2920
2921 pub fn prevent_default(&mut self) {
2924 self.default_prevented = true;
2925 }
2926
2927 pub fn default_prevented(&self) -> bool {
2929 self.default_prevented
2930 }
2931
2932 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2934 let node_id =
2935 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2936 self.rendered_frame
2937 .dispatch_tree
2938 .is_action_available(action, node_id)
2939 }
2940
2941 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2943 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2944 self.rendered_frame
2945 .dispatch_tree
2946 .is_action_available(action, node_id)
2947 }
2948
2949 pub fn mouse_position(&self) -> Point<Pixels> {
2951 self.mouse_position
2952 }
2953
2954 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
2961 self.captured_hitbox = Some(hitbox_id);
2962 }
2963
2964 pub fn release_pointer(&mut self) {
2966 self.captured_hitbox = None;
2967 }
2968
2969 pub fn captured_hitbox(&self) -> Option<HitboxId> {
2971 self.captured_hitbox
2972 }
2973
2974 pub fn capture_long_press<T: 'static>(&mut self, entity: &Entity<T>) {
2980 self.long_press_capture = Some(entity.entity_id());
2981 }
2982
2983 pub fn has_long_press_capture<T: 'static>(&self, entity: &Entity<T>) -> bool {
2985 self.long_press_capture == Some(entity.entity_id())
2986 }
2987
2988 pub fn modifiers(&self) -> Modifiers {
2990 self.modifiers
2991 }
2992
2993 pub fn last_input_was_keyboard(&self) -> bool {
2996 self.last_input_modality == InputModality::Keyboard
2997 }
2998
2999 pub(crate) fn last_input_was_touch(&self) -> bool {
3000 self.last_input_modality == InputModality::Touch
3001 }
3002
3003 pub fn capslock(&self) -> Capslock {
3005 self.capslock
3006 }
3007
3008 #[profiling::function]
3011 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
3012 #[cfg(feature = "profiler")]
3015 let frame_dirty = self.invalidator.take_frame_dirty();
3016 #[cfg(feature = "profiler")]
3017 self.window_profiler.begin_draw();
3018
3019 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
3022
3023 self.invalidate_entities();
3024 cx.entities.clear_accessed();
3025 debug_assert!(self.rendered_entity_stack.is_empty());
3026 self.invalidator.set_dirty(false);
3027 self.requested_autoscroll = None;
3028
3029 if let Some(input_handler) = self.platform_window.take_input_handler() {
3034 if let Some(slot) = self
3035 .rendered_frame
3036 .input_handlers
3037 .iter_mut()
3038 .rev()
3039 .find(|h| h.is_none())
3040 {
3041 *slot = Some(input_handler);
3042 } else {
3043 self.rendered_frame.input_handlers.push(Some(input_handler));
3044 }
3045 }
3046 if !cx.mode.skip_drawing() {
3047 self.draw_roots(cx);
3048 #[cfg(feature = "profiler")]
3049 {
3050 let viewport_size = self.viewport_size;
3051 let scale_factor = self.scale_factor();
3052 self.debug_frame_overlay.paint(
3053 &mut self.next_frame.scene,
3054 viewport_size,
3055 scale_factor,
3056 );
3057 }
3058 }
3059 self.dirty_views.clear();
3060 self.next_frame.window_active = self.active.get();
3061
3062 let focused_text_input_active = if let Some(mut input_handler) = self
3068 .next_frame
3069 .input_handlers
3070 .iter_mut()
3071 .rev()
3072 .find_map(|h| h.take())
3073 {
3074 let accepts_text_input = input_handler.accepts_text_input(self, cx);
3075 self.platform_window.set_input_handler(input_handler);
3076 accepts_text_input
3077 } else {
3078 false
3079 };
3080 self.apply_text_input_configuration(cx);
3081 if focused_text_input_active != self.focused_text_input_active {
3082 self.focused_text_input_active = focused_text_input_active;
3083 self.platform_window
3084 .text_input_state_changed(if focused_text_input_active {
3085 TextInputStateChange::FocusGained
3086 } else {
3087 TextInputStateChange::FocusLost
3088 });
3089 }
3090
3091 self.layout_engine.as_mut().unwrap().clear();
3092 self.text_system().finish_frame();
3093 self.next_frame.finish(&mut self.rendered_frame);
3094
3095 self.invalidator.set_phase(DrawPhase::Focus);
3096 let previous_focus_path = self.rendered_frame.focus_path();
3097 let previous_window_active = self.rendered_frame.window_active;
3098 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
3099 self.next_frame.clear();
3100 let current_focus_path = self.rendered_frame.focus_path();
3101 let current_window_active = self.rendered_frame.window_active;
3102 let mut focus_before_listeners = self.focus;
3103
3104 if previous_focus_path != current_focus_path
3105 || previous_window_active != current_window_active
3106 {
3107 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
3108 self.focus_lost_path = previous_focus_path.clone();
3109 self.focus_lost_listeners
3110 .clone()
3111 .retain(&(), |listener| listener(self, cx));
3112 self.focus_lost_path = SmallVec::new();
3113 focus_before_listeners = self.focus;
3118 }
3119
3120 let event = WindowFocusEvent {
3121 previous_focus_path: if previous_window_active {
3122 previous_focus_path
3123 } else {
3124 Default::default()
3125 },
3126 current_focus_path: if current_window_active {
3127 current_focus_path
3128 } else {
3129 Default::default()
3130 },
3131 };
3132 self.focus_listeners
3133 .clone()
3134 .retain(&(), |listener| listener(&event, self, cx));
3135 }
3136
3137 debug_assert!(self.rendered_entity_stack.is_empty());
3138 self.record_entities_accessed(cx);
3139 self.reset_cursor_style(cx);
3140 self.refreshing = false;
3141 self.invalidator.set_phase(DrawPhase::None);
3142 if self.focus != focus_before_listeners {
3147 self.refresh();
3148 }
3149 self.needs_present.set(true);
3150
3151 #[cfg(feature = "profiler")]
3152 {
3153 let draw_duration = self
3154 .window_profiler
3155 .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
3156 self.debug_frame_overlay.record_frame(draw_duration);
3157 }
3158
3159 arena_scope.exit(&cx.element_arena)
3162 }
3163
3164 fn record_entities_accessed(&mut self, cx: &mut App) {
3165 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3166 let mut entities = mem::take(entities_ref.deref_mut());
3167 let handle = self.handle;
3168 cx.record_entities_accessed(
3169 handle,
3170 self.invalidator.clone(),
3172 &entities,
3173 );
3174 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3175 mem::swap(&mut entities, entities_ref.deref_mut());
3176 }
3177
3178 fn invalidate_entities(&mut self) {
3179 let mut views = self.invalidator.take_views();
3180 for entity in views.drain() {
3181 self.mark_view_dirty(entity);
3182 }
3183 self.invalidator.replace_views(views);
3184 }
3185
3186 #[profiling::function]
3187 fn present(&mut self) {
3188 #[cfg(feature = "profiler")]
3189 let _foreground_turn = profiler::journal::foreground_turn();
3190 #[cfg(feature = "profiler")]
3191 let present_start = Instant::now();
3192 self.platform_window.draw(&self.rendered_frame.scene);
3193 #[cfg(feature = "profiler")]
3194 self.window_profiler.record_present(
3195 present_start,
3196 Instant::now(),
3197 self.active.get(),
3198 !self.next_frame_callbacks.borrow().is_empty(),
3199 );
3200 self.needs_present.set(false);
3201 profiling::finish_frame!();
3202 }
3203
3204 #[cfg(any(feature = "bench-support", all(test, feature = "profiler")))]
3210 pub fn present_if_needed(&mut self) {
3211 if self.needs_present.get() {
3212 self.present();
3213 }
3214 }
3215
3216 #[cfg(feature = "profiler")]
3218 pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
3219 self.window_profiler.input_latency_snapshot()
3220 }
3221
3222 #[cfg(feature = "profiler")]
3224 pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
3225 self.window_profiler.frame_duration_snapshot()
3226 }
3227
3228 #[cfg(feature = "profiler")]
3230 pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
3231 self.debug_frame_overlay.mode()
3232 }
3233
3234 #[cfg(feature = "profiler")]
3236 pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
3237 self.debug_frame_overlay.set_mode(mode);
3238 self.refresh();
3239 }
3240
3241 #[cfg(feature = "profiler")]
3244 pub fn cycle_debug_frame_overlay_mode(&mut self) {
3245 self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
3246 }
3247
3248 #[cfg(feature = "profiler")]
3251 pub fn reset_debug_frame_overlay_stats(&mut self) {
3252 self.debug_frame_overlay.reset_stats();
3253 self.refresh();
3254 }
3255
3256 fn draw_roots(&mut self, cx: &mut App) {
3257 self.invalidator.set_phase(DrawPhase::Prepaint);
3258 self.tooltip_bounds.take();
3259
3260 self.a11y.sync_active_flag();
3261 if self.a11y.is_active() {
3262 self.a11y.begin_frame();
3263 }
3264
3265 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
3266 let root_size = {
3267 #[cfg(any(feature = "inspector", debug_assertions))]
3268 {
3269 if self.inspector.is_some() {
3270 let mut size = self.viewport_size;
3271 size.width = (size.width - _inspector_width).max(px(0.0));
3272 size
3273 } else {
3274 self.viewport_size
3275 }
3276 }
3277 #[cfg(not(any(feature = "inspector", debug_assertions)))]
3278 {
3279 self.viewport_size
3280 }
3281 };
3282
3283 let scale_factor = self.scale_factor();
3287 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
3288 let root_layout_id = root_element.request_layout(self, cx);
3289 self.layout_engine
3290 .as_mut()
3291 .unwrap()
3292 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
3293 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3294
3295 #[cfg(any(feature = "inspector", debug_assertions))]
3296 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
3297
3298 self.prepaint_deferred_draws(cx);
3299
3300 let mut prompt_element = None;
3301 let mut active_drag_element = None;
3302 let mut tooltip_element = None;
3303 if let Some(prompt) = self.prompt.take() {
3304 let mut element = prompt.view.any_view().into_any_element();
3305 let prompt_layout_id = element.request_layout(self, cx);
3306 self.layout_engine
3307 .as_mut()
3308 .unwrap()
3309 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
3310 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3311 prompt_element = Some(element);
3312 self.prompt = Some(prompt);
3313 } else if let Some(active_drag) = cx.active_drag.take() {
3314 let mut element = active_drag.view.clone().into_any_element();
3315 let offset = self.mouse_position() - active_drag.cursor_offset;
3316 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
3317 active_drag_element = Some(element);
3318 cx.active_drag = Some(active_drag);
3319 } else {
3320 tooltip_element = self.prepaint_tooltip(cx);
3321 }
3322
3323 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
3324
3325 self.invalidator.set_phase(DrawPhase::Paint);
3327 root_element.paint(self, cx);
3328
3329 #[cfg(any(feature = "inspector", debug_assertions))]
3330 self.paint_inspector(inspector_element, cx);
3331
3332 self.paint_deferred_draws(cx);
3333
3334 if let Some(mut prompt_element) = prompt_element {
3335 prompt_element.paint(self, cx);
3336 } else if let Some(mut drag_element) = active_drag_element {
3337 drag_element.paint(self, cx);
3338 } else if let Some(mut tooltip_element) = tooltip_element {
3339 tooltip_element.paint(self, cx);
3340 }
3341
3342 #[cfg(any(feature = "inspector", debug_assertions))]
3343 self.paint_inspector_hitbox(cx);
3344
3345 let a11y_active_start_of_frame = self.a11y.is_active();
3347 self.a11y.sync_active_flag();
3348 let a11y_active_end_of_frame = self.a11y.is_active();
3349
3350 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
3351
3352 if a11y_active_start_of_frame {
3353 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
3356 viewport_size: self.viewport_size,
3357 scale_factor: self.scale_factor,
3358 tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
3359 };
3360 let tree_update = self.a11y.end_frame(frame_info);
3362
3363 if should_send_a11y_update {
3364 log::debug!(
3365 "Sending a11y tree update: {} nodes",
3366 tree_update.nodes.len()
3367 );
3368 self.platform_window.a11y_tree_update(tree_update);
3369 }
3370 }
3371 }
3372
3373 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
3374 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
3376 let Some(Some(tooltip_request)) = self
3377 .next_frame
3378 .tooltip_requests
3379 .get(tooltip_request_index)
3380 .cloned()
3381 else {
3382 log::error!("Unexpectedly absent TooltipRequest");
3383 continue;
3384 };
3385 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
3386 let mouse_position = tooltip_request.tooltip.mouse_position;
3387 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
3388
3389 let mut tooltip_bounds =
3390 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
3391 let window_bounds = Bounds {
3392 origin: Point::default(),
3393 size: self.viewport_size(),
3394 };
3395
3396 if tooltip_bounds.right() > window_bounds.right() {
3397 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
3398 if new_x >= Pixels::ZERO {
3399 tooltip_bounds.origin.x = new_x;
3400 } else {
3401 tooltip_bounds.origin.x = cmp::max(
3402 Pixels::ZERO,
3403 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
3404 );
3405 }
3406 }
3407
3408 if tooltip_bounds.bottom() > window_bounds.bottom() {
3409 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
3410 if new_y >= Pixels::ZERO {
3411 tooltip_bounds.origin.y = new_y;
3412 } else {
3413 tooltip_bounds.origin.y = cmp::max(
3414 Pixels::ZERO,
3415 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
3416 );
3417 }
3418 }
3419
3420 let is_visible =
3424 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
3425 if !is_visible {
3426 continue;
3427 }
3428
3429 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
3430 element.prepaint(window, cx)
3431 });
3432
3433 self.tooltip_bounds = Some(TooltipBounds {
3434 id: tooltip_request.id,
3435 bounds: tooltip_bounds,
3436 });
3437 return Some(element);
3438 }
3439 None
3440 }
3441
3442 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
3443 assert_eq!(self.element_id_stack.len(), 0);
3444
3445 let mut round_start = 0;
3456 let mut depth = 0;
3457 loop {
3458 let round_end = self.next_frame.deferred_draws.len();
3459 if round_start == round_end {
3460 break;
3461 }
3462 assert!(depth < 10, "Exceeded maximum (10) deferred depth");
3464 depth += 1;
3465
3466 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
3468 traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3469
3470 for deferred_draw_ix in traversal_order {
3471 let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
3472 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
3473 self.element_id_stack
3474 .clone_from(&deferred_draw.element_id_stack);
3475 self.text_style_stack
3476 .clone_from(&deferred_draw.text_style_stack);
3477 (
3478 deferred_draw.element.take(),
3479 deferred_draw.parent_node,
3480 deferred_draw.current_view,
3481 deferred_draw.rem_size,
3482 deferred_draw.absolute_offset,
3483 deferred_draw.prepaint_range.clone(),
3484 )
3485 };
3486 self.next_frame.dispatch_tree.set_active_node(parent_node);
3487
3488 let prepaint_start = self.prepaint_index();
3489 if let Some(mut element) = element {
3490 self.with_rendered_view(current_view, |window| {
3491 window.with_rem_size(Some(rem_size), |window| {
3492 window.with_absolute_element_offset(absolute_offset, |window| {
3493 element.prepaint(window, cx);
3494 });
3495 });
3496 });
3497 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
3498 } else {
3499 self.reuse_prepaint(prepaint_range);
3500 }
3501 let prepaint_end = self.prepaint_index();
3502 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
3503 prepaint_start..prepaint_end;
3504 }
3505
3506 self.element_id_stack.clear();
3507 self.text_style_stack.clear();
3508 round_start = round_end;
3509 }
3510 }
3511
3512 fn paint_deferred_draws(&mut self, cx: &mut App) {
3513 assert_eq!(self.element_id_stack.len(), 0);
3514
3515 if self.next_frame.deferred_draws.len() == 0 {
3518 return;
3519 }
3520
3521 let traversal_order = self.deferred_draw_traversal_order();
3522 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
3523 for deferred_draw_ix in traversal_order {
3524 let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
3525 self.element_id_stack
3526 .clone_from(&deferred_draw.element_id_stack);
3527 self.next_frame
3528 .dispatch_tree
3529 .set_active_node(deferred_draw.parent_node);
3530
3531 let paint_start = self.paint_index();
3532 let content_mask = deferred_draw.content_mask;
3533 if let Some(element) = deferred_draw.element.as_mut() {
3534 self.with_rendered_view(deferred_draw.current_view, |window| {
3535 window.with_content_mask(content_mask, |window| {
3536 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
3537 element.paint(window, cx);
3538 });
3539 })
3540 })
3541 } else {
3542 self.reuse_paint(deferred_draw.paint_range.clone());
3543 }
3544 let paint_end = self.paint_index();
3545 deferred_draw.paint_range = paint_start..paint_end;
3546 }
3547 self.next_frame.deferred_draws = deferred_draws;
3548 self.element_id_stack.clear();
3549 }
3550
3551 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
3552 let deferred_count = self.next_frame.deferred_draws.len();
3553 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
3554 sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3555 sorted_indices
3556 }
3557
3558 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
3559 PrepaintStateIndex {
3560 hitboxes_index: self.next_frame.hitboxes.len(),
3561 tooltips_index: self.next_frame.tooltip_requests.len(),
3562 deferred_draws_index: self.next_frame.deferred_draws.len(),
3563 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
3564 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3565 line_layout_index: self.text_system.layout_index(),
3566 }
3567 }
3568
3569 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
3570 self.next_frame.hitboxes.extend(
3571 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
3572 .iter()
3573 .cloned(),
3574 );
3575 self.next_frame.tooltip_requests.extend(
3576 self.rendered_frame.tooltip_requests
3577 [range.start.tooltips_index..range.end.tooltips_index]
3578 .iter_mut()
3579 .map(|request| request.take()),
3580 );
3581 self.next_frame.accessed_element_states.extend(
3582 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3583 ..range.end.accessed_element_states_index]
3584 .iter()
3585 .map(|(id, type_id)| (id.clone(), *type_id)),
3586 );
3587 self.text_system
3588 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3589
3590 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
3591 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
3592 &mut self.rendered_frame.dispatch_tree,
3593 self.focus,
3594 );
3595
3596 if reused_subtree.contains_focus() {
3597 self.next_frame.focus = self.focus;
3598 }
3599
3600 self.next_frame.deferred_draws.extend(
3601 self.rendered_frame.deferred_draws
3602 [range.start.deferred_draws_index..range.end.deferred_draws_index]
3603 .iter()
3604 .map(|deferred_draw| DeferredDraw {
3605 current_view: deferred_draw.current_view,
3606 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
3607 element_id_stack: deferred_draw.element_id_stack.clone(),
3608 text_style_stack: deferred_draw.text_style_stack.clone(),
3609 content_mask: deferred_draw.content_mask,
3610 rem_size: deferred_draw.rem_size,
3611 priority: deferred_draw.priority,
3612 element: None,
3613 absolute_offset: deferred_draw.absolute_offset,
3614 prepaint_range: deferred_draw.prepaint_range.clone(),
3615 paint_range: deferred_draw.paint_range.clone(),
3616 }),
3617 );
3618 }
3619
3620 pub(crate) fn paint_index(&self) -> PaintIndex {
3621 PaintIndex {
3622 scene_index: self.next_frame.scene.len(),
3623 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
3624 input_handlers_index: self.next_frame.input_handlers.len(),
3625 cursor_styles_index: self.next_frame.cursor_styles.len(),
3626 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3627 tab_handle_index: self.next_frame.tab_stops.paint_index(),
3628 line_layout_index: self.text_system.layout_index(),
3629 }
3630 }
3631
3632 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
3633 self.next_frame.cursor_styles.extend(
3634 self.rendered_frame.cursor_styles
3635 [range.start.cursor_styles_index..range.end.cursor_styles_index]
3636 .iter()
3637 .cloned(),
3638 );
3639 self.next_frame.input_handlers.extend(
3640 self.rendered_frame.input_handlers
3641 [range.start.input_handlers_index..range.end.input_handlers_index]
3642 .iter_mut()
3643 .map(|handler| handler.take()),
3644 );
3645 self.next_frame.mouse_listeners.extend(
3646 self.rendered_frame.mouse_listeners
3647 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
3648 .iter_mut()
3649 .map(|listener| listener.take()),
3650 );
3651 self.next_frame.accessed_element_states.extend(
3652 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3653 ..range.end.accessed_element_states_index]
3654 .iter()
3655 .map(|(id, type_id)| (id.clone(), *type_id)),
3656 );
3657 self.next_frame.tab_stops.replay(
3658 &self.rendered_frame.tab_stops.insertion_history
3659 [range.start.tab_handle_index..range.end.tab_handle_index],
3660 );
3661
3662 self.text_system
3663 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3664 self.next_frame.scene.replay(
3665 range.start.scene_index..range.end.scene_index,
3666 &self.rendered_frame.scene,
3667 );
3668 }
3669
3670 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
3674 where
3675 F: FnOnce(&mut Self) -> R,
3676 {
3677 self.invalidator.debug_assert_paint_or_prepaint();
3678 if let Some(style) = style {
3679 self.text_style_stack.push(style);
3680 let result = f(self);
3681 self.text_style_stack.pop();
3682 result
3683 } else {
3684 f(self)
3685 }
3686 }
3687
3688 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
3691 self.invalidator.debug_assert_paint();
3692 self.next_frame.cursor_styles.push(CursorStyleRequest {
3693 hitbox_id: Some(hitbox.id),
3694 style,
3695 });
3696 }
3697
3698 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
3703 self.invalidator.debug_assert_paint();
3704 self.next_frame.cursor_styles.push(CursorStyleRequest {
3705 hitbox_id: None,
3706 style,
3707 })
3708 }
3709
3710 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
3713 self.invalidator.debug_assert_prepaint();
3714 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
3715 self.next_frame
3716 .tooltip_requests
3717 .push(Some(TooltipRequest { id, tooltip }));
3718 id
3719 }
3720
3721 #[inline]
3726 pub fn with_content_mask<R>(
3727 &mut self,
3728 mask: Option<ContentMask<Pixels>>,
3729 f: impl FnOnce(&mut Self) -> R,
3730 ) -> R {
3731 self.invalidator.debug_assert_paint_or_prepaint();
3732 if let Some(mask) = mask {
3733 let mask = mask.intersect(&self.content_mask());
3734 self.content_mask_stack.push(mask);
3735 let result = f(self);
3736 self.content_mask_stack.pop();
3737 result
3738 } else {
3739 f(self)
3740 }
3741 }
3742
3743 pub fn with_element_offset<R>(
3746 &mut self,
3747 offset: Point<Pixels>,
3748 f: impl FnOnce(&mut Self) -> R,
3749 ) -> R {
3750 self.invalidator.debug_assert_prepaint();
3751
3752 if offset.is_zero() {
3753 return f(self);
3754 };
3755
3756 let abs_offset = self.element_offset() + offset;
3757 self.with_absolute_element_offset(abs_offset, f)
3758 }
3759
3760 pub fn with_absolute_element_offset<R>(
3764 &mut self,
3765 offset: Point<Pixels>,
3766 f: impl FnOnce(&mut Self) -> R,
3767 ) -> R {
3768 self.invalidator.debug_assert_prepaint();
3769 self.element_offset_stack.push(offset);
3770 let result = f(self);
3771 self.element_offset_stack.pop();
3772 result
3773 }
3774
3775 pub(crate) fn with_element_opacity<R>(
3776 &mut self,
3777 opacity: Option<f32>,
3778 f: impl FnOnce(&mut Self) -> R,
3779 ) -> R {
3780 self.invalidator.debug_assert_paint_or_prepaint();
3781
3782 let Some(opacity) = opacity else {
3783 return f(self);
3784 };
3785
3786 let previous_opacity = self.element_opacity;
3787 self.element_opacity = previous_opacity * opacity;
3788 let result = f(self);
3789 self.element_opacity = previous_opacity;
3790 result
3791 }
3792
3793 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
3799 self.invalidator.debug_assert_prepaint();
3800 let index = self.prepaint_index();
3801 let result = f(self);
3802 if result.is_err() {
3803 self.next_frame.hitboxes.truncate(index.hitboxes_index);
3804 self.next_frame
3805 .tooltip_requests
3806 .truncate(index.tooltips_index);
3807 self.next_frame
3808 .deferred_draws
3809 .truncate(index.deferred_draws_index);
3810 self.next_frame
3811 .dispatch_tree
3812 .truncate(index.dispatch_tree_index);
3813 self.next_frame
3814 .accessed_element_states
3815 .truncate(index.accessed_element_states_index);
3816 self.text_system.truncate_layouts(index.line_layout_index);
3817 }
3818 result
3819 }
3820
3821 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
3827 self.invalidator.debug_assert_prepaint();
3828 self.requested_autoscroll = Some(bounds);
3829 }
3830
3831 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
3834 self.invalidator.debug_assert_prepaint();
3835 self.requested_autoscroll.take()
3836 }
3837
3838 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3844 let (task, is_first) = cx.fetch_asset::<A>(source);
3845 task.clone().now_or_never().or_else(|| {
3846 if is_first {
3847 let entity_id = self.current_view();
3848 self.spawn(cx, {
3849 let task = task.clone();
3850 async move |cx| {
3851 task.await;
3852
3853 cx.on_next_frame(move |_, cx| {
3854 cx.notify(entity_id);
3855 });
3856 }
3857 })
3858 .detach();
3859 }
3860
3861 None
3862 })
3863 }
3864
3865 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3871 let (task, _) = cx.fetch_asset::<A>(source);
3872 task.now_or_never()
3873 }
3874 pub fn element_offset(&self) -> Point<Pixels> {
3877 self.invalidator.debug_assert_prepaint();
3878 self.element_offset_stack
3879 .last()
3880 .copied()
3881 .unwrap_or_default()
3882 }
3883
3884 #[inline]
3887 pub(crate) fn element_opacity(&self) -> f32 {
3888 self.invalidator.debug_assert_paint_or_prepaint();
3889 self.element_opacity
3890 }
3891
3892 pub fn content_mask(&self) -> ContentMask<Pixels> {
3894 self.invalidator.debug_assert_paint_or_prepaint();
3895 self.content_mask_stack
3896 .last()
3897 .cloned()
3898 .unwrap_or_else(|| ContentMask {
3899 bounds: Bounds {
3900 origin: Point::default(),
3901 size: self.viewport_size,
3902 },
3903 })
3904 }
3905
3906 pub fn with_element_namespace<R>(
3909 &mut self,
3910 element_id: impl Into<ElementId>,
3911 f: impl FnOnce(&mut Self) -> R,
3912 ) -> R {
3913 self.element_id_stack.push(element_id.into());
3914 let result = f(self);
3915 self.element_id_stack.pop();
3916 result
3917 }
3918
3919 pub fn use_keyed_state<S: 'static>(
3921 &mut self,
3922 key: impl Into<ElementId>,
3923 cx: &mut App,
3924 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3925 ) -> Entity<S> {
3926 let current_view = self.current_view();
3927 self.with_global_id(key.into(), |global_id, window| {
3928 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
3929 if let Some(state) = state {
3930 (state.clone(), state)
3931 } else {
3932 let new_state = cx.new(|cx| init(window, cx));
3933 cx.observe(&new_state, move |_, cx| {
3934 cx.notify(current_view);
3935 })
3936 .detach();
3937 (new_state.clone(), new_state)
3938 }
3939 })
3940 })
3941 }
3942
3943 #[track_caller]
3949 pub fn use_state<S: 'static>(
3950 &mut self,
3951 cx: &mut App,
3952 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3953 ) -> Entity<S> {
3954 self.use_keyed_state(
3955 ElementId::CodeLocation(*core::panic::Location::caller()),
3956 cx,
3957 init,
3958 )
3959 }
3960
3961 pub fn with_element_state<S, R>(
3966 &mut self,
3967 global_id: &GlobalElementId,
3968 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
3969 ) -> R
3970 where
3971 S: 'static,
3972 {
3973 self.invalidator.debug_assert_paint_or_prepaint();
3974
3975 let key = (global_id.clone(), TypeId::of::<S>());
3976 self.next_frame.accessed_element_states.push(key.clone());
3977
3978 if let Some(any) = self
3979 .next_frame
3980 .element_states
3981 .remove(&key)
3982 .or_else(|| self.rendered_frame.element_states.remove(&key))
3983 {
3984 let ElementStateBox {
3985 inner,
3986 #[cfg(debug_assertions)]
3987 type_name,
3988 } = any;
3989 let mut state_box = inner
3991 .downcast::<Option<S>>()
3992 .map_err(|_| {
3993 #[cfg(debug_assertions)]
3994 {
3995 anyhow::anyhow!(
3996 "invalid element state type for id, requested {:?}, actual: {:?}",
3997 std::any::type_name::<S>(),
3998 type_name
3999 )
4000 }
4001
4002 #[cfg(not(debug_assertions))]
4003 {
4004 anyhow::anyhow!(
4005 "invalid element state type for id, requested {:?}",
4006 std::any::type_name::<S>(),
4007 )
4008 }
4009 })
4010 .unwrap();
4011
4012 let state = state_box.take().expect(
4013 "reentrant call to with_element_state for the same state type and element id",
4014 );
4015 let (result, state) = f(Some(state), self);
4016 state_box.replace(state);
4017 self.next_frame.element_states.insert(
4018 key,
4019 ElementStateBox {
4020 inner: state_box,
4021 #[cfg(debug_assertions)]
4022 type_name,
4023 },
4024 );
4025 result
4026 } else {
4027 let (result, state) = f(None, self);
4028 self.next_frame.element_states.insert(
4029 key,
4030 ElementStateBox {
4031 inner: Box::new(Some(state)),
4032 #[cfg(debug_assertions)]
4033 type_name: std::any::type_name::<S>(),
4034 },
4035 );
4036 result
4037 }
4038 }
4039
4040 pub fn with_optional_element_state<S, R>(
4047 &mut self,
4048 global_id: Option<&GlobalElementId>,
4049 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
4050 ) -> R
4051 where
4052 S: 'static,
4053 {
4054 self.invalidator.debug_assert_paint_or_prepaint();
4055
4056 if let Some(global_id) = global_id {
4057 self.with_element_state(global_id, |state, cx| {
4058 let (result, state) = f(Some(state), cx);
4059 let state =
4060 state.expect("you must return some state when you pass some element id");
4061 (result, state)
4062 })
4063 } else {
4064 let (result, state) = f(None, self);
4065 debug_assert!(
4066 state.is_none(),
4067 "you must not return an element state when passing None for the global id"
4068 );
4069 result
4070 }
4071 }
4072
4073 #[inline]
4075 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
4076 if let Some(index) = index {
4077 self.next_frame.tab_stops.begin_group(index);
4078 let result = f(self);
4079 self.next_frame.tab_stops.end_group();
4080 result
4081 } else {
4082 f(self)
4083 }
4084 }
4085
4086 pub fn defer_draw(
4095 &mut self,
4096 element: AnyElement,
4097 absolute_offset: Point<Pixels>,
4098 priority: usize,
4099 content_mask: Option<ContentMask<Pixels>>,
4100 ) {
4101 self.invalidator.debug_assert_prepaint();
4102 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
4103 self.next_frame.deferred_draws.push(DeferredDraw {
4104 current_view: self.current_view(),
4105 parent_node,
4106 element_id_stack: self.element_id_stack.clone(),
4107 text_style_stack: self.text_style_stack.clone(),
4108 content_mask,
4109 rem_size: self.rem_size(),
4110 priority,
4111 element: Some(element),
4112 absolute_offset,
4113 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
4114 paint_range: PaintIndex::default()..PaintIndex::default(),
4115 });
4116 }
4117
4118 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
4124 self.invalidator.debug_assert_paint();
4125
4126 let content_mask = self.content_mask();
4127 let clipped_bounds = bounds.intersect(&content_mask.bounds);
4128 if !clipped_bounds.is_empty() {
4129 self.next_frame
4130 .scene
4131 .push_layer(self.cover_bounds(clipped_bounds));
4132 }
4133
4134 let result = f(self);
4135
4136 if !clipped_bounds.is_empty() {
4137 self.next_frame.scene.pop_layer();
4138 }
4139
4140 result
4141 }
4142
4143 pub fn paint_drop_shadows(
4149 &mut self,
4150 bounds: Bounds<Pixels>,
4151 corner_radii: Corners<Pixels>,
4152 shadows: &[BoxShadow],
4153 ) {
4154 self.invalidator.debug_assert_paint();
4155
4156 let scale_factor = self.scale_factor();
4157 let content_mask = self.snapped_content_mask();
4158 let opacity = self.element_opacity();
4159 let element_bounds = self.cover_bounds(bounds);
4160 let element_corner_radii = corner_radii.scale(scale_factor);
4161 for shadow in shadows {
4162 if shadow.inset {
4163 continue;
4164 }
4165 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
4166 self.next_frame.scene.insert_primitive(Shadow {
4167 order: 0,
4168 blur_radius: shadow.blur_radius.scale(scale_factor),
4169 bounds: self.cover_bounds(shadow_bounds),
4170 content_mask,
4171 corner_radii: corner_radii.scale(scale_factor),
4172 color: shadow.color.opacity(opacity),
4173 element_bounds,
4174 element_corner_radii,
4175 inset: 0,
4176 pad: 0,
4177 });
4178 }
4179 }
4180
4181 pub fn paint_inset_shadows(
4185 &mut self,
4186 bounds: Bounds<Pixels>,
4187 corner_radii: Corners<Pixels>,
4188 shadows: &[BoxShadow],
4189 ) {
4190 self.invalidator.debug_assert_paint();
4191
4192 let scale_factor = self.scale_factor();
4193 let content_mask = self.snapped_content_mask();
4194 let opacity = self.element_opacity();
4195 let element_bounds = self.cover_bounds(bounds);
4196 let element_corner_radii = corner_radii.scale(scale_factor);
4197 for shadow in shadows {
4198 if !shadow.inset {
4199 continue;
4200 }
4201 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
4202 let zero = Pixels::ZERO;
4205 let hole_corner_radii = Corners {
4206 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
4207 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
4208 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
4209 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
4210 };
4211 self.next_frame.scene.insert_primitive(Shadow {
4212 order: 0,
4213 blur_radius: shadow.blur_radius.scale(scale_factor),
4214 bounds: self.cover_bounds(hole),
4215 content_mask,
4216 corner_radii: hole_corner_radii.scale(scale_factor),
4217 color: shadow.color.opacity(opacity),
4218 element_bounds,
4219 element_corner_radii,
4220 inset: 1,
4221 pad: 0,
4222 });
4223 }
4224 }
4225
4226 fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
4227 let radii = &quad.corner_radii;
4228 let widths = &quad.border_widths;
4229 let edge_radii = Edges {
4230 top: radii.top_left.max(radii.top_right),
4231 right: radii.top_right.max(radii.bottom_right),
4232 bottom: radii.bottom_left.max(radii.bottom_right),
4233 left: radii.top_left.max(radii.bottom_left),
4234 };
4235
4236 let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
4237 let inset_bounds = |top_left_inset, bottom_right_inset| {
4238 Bounds::from_corners(
4239 quad.bounds.origin + top_left_inset + antialias_inset,
4240 quad.bounds.bottom_right() - bottom_right_inset - antialias_inset,
4241 )
4242 };
4243
4244 let horizontal_band = inset_bounds(
4247 point(widths.left, widths.top.max(edge_radii.top)),
4248 point(widths.right, widths.bottom.max(edge_radii.bottom)),
4249 );
4250 let vertical_band = inset_bounds(
4251 point(widths.left.max(edge_radii.left), widths.top),
4252 point(widths.right.max(edge_radii.right), widths.bottom),
4253 );
4254
4255 let area = |bounds: &Bounds<ScaledPixels>| {
4256 bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.)
4257 };
4258 if area(&horizontal_band) >= area(&vertical_band) {
4259 horizontal_band
4260 } else {
4261 vertical_band
4262 }
4263 }
4264
4265 pub fn paint_quad(&mut self, quad: PaintQuad) {
4275 self.invalidator.debug_assert_paint();
4276
4277 let opacity = self.element_opacity();
4278 let snapped_bounds = self.snap_bounds(quad.bounds);
4279 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
4280 let quad = Quad {
4281 order: 0,
4282 bounds: snapped_bounds,
4283 content_mask: self.snapped_content_mask(),
4284 background: quad.background.opacity(opacity),
4285 border_color: quad.border_color.opacity(opacity),
4286 corner_radii: quad.corner_radii.scale(self.scale_factor()),
4287 border_widths: snapped_border_widths,
4288 border_style: quad.border_style,
4289 };
4290
4291 if !quad.background.is_transparent() {
4292 self.next_frame.scene.insert_primitive(quad);
4293 return;
4294 }
4295
4296 let outer_bounds = quad.bounds;
4299 let inner_bounds = Self::largest_border_interior(&quad);
4300
4301 if inner_bounds.is_empty() {
4302 self.next_frame.scene.insert_primitive(quad);
4303 return;
4304 }
4305
4306 let strips = [
4307 Bounds::from_corners(
4309 outer_bounds.origin,
4310 point(outer_bounds.right(), inner_bounds.top()),
4311 ),
4312 Bounds::from_corners(
4314 point(outer_bounds.left(), inner_bounds.bottom()),
4315 outer_bounds.bottom_right(),
4316 ),
4317 Bounds::from_corners(
4319 point(outer_bounds.left(), inner_bounds.top()),
4320 inner_bounds.bottom_left(),
4321 ),
4322 Bounds::from_corners(
4324 inner_bounds.top_right(),
4325 point(outer_bounds.right(), inner_bounds.bottom()),
4326 ),
4327 ];
4328
4329 for strip in strips {
4330 let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
4331 if !content_mask_bounds.is_empty() {
4332 self.next_frame.scene.insert_primitive(Quad {
4333 content_mask: ContentMask {
4334 bounds: content_mask_bounds,
4335 },
4336 ..quad
4337 });
4338 }
4339 }
4340 }
4341
4342 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
4346 self.invalidator.debug_assert_paint();
4347
4348 let scale_factor = self.scale_factor();
4349 let content_mask = self.content_mask();
4350 let opacity = self.element_opacity();
4351 path.content_mask = content_mask;
4352 let color: Background = color.into();
4353 path.color = color.opacity(opacity);
4354 self.next_frame
4355 .scene
4356 .insert_primitive(path.scale(scale_factor));
4357 }
4358
4359 pub fn paint_underline(
4363 &mut self,
4364 origin: Point<Pixels>,
4365 width: Pixels,
4366 style: &UnderlineStyle,
4367 ) {
4368 self.invalidator.debug_assert_paint();
4369
4370 let scale_factor = self.scale_factor();
4371 let thickness = self.snap_stroke(style.thickness);
4372 let height = if style.wavy {
4373 ScaledPixels(thickness.0 * 3.)
4374 } else {
4375 thickness
4376 };
4377 let bounds = Bounds {
4378 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4379 size: size(self.snap_stroke(width), height),
4380 };
4381 let element_opacity = self.element_opacity();
4382
4383 self.next_frame.scene.insert_primitive(Underline {
4384 order: 0,
4385 pad: 0,
4386 bounds,
4387 content_mask: self.snapped_content_mask(),
4388 color: style.color.unwrap_or_default().opacity(element_opacity),
4389 thickness,
4390 wavy: style.wavy.into(),
4391 });
4392 }
4393
4394 pub fn paint_strikethrough(
4398 &mut self,
4399 origin: Point<Pixels>,
4400 width: Pixels,
4401 style: &StrikethroughStyle,
4402 ) {
4403 self.invalidator.debug_assert_paint();
4404
4405 let scale_factor = self.scale_factor();
4406 let height = style.thickness;
4407 let bounds = Bounds {
4408 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4409 size: size(self.snap_stroke(width), self.snap_stroke(height)),
4410 };
4411 let opacity = self.element_opacity();
4412
4413 self.next_frame.scene.insert_primitive(Underline {
4414 order: 0,
4415 pad: 0,
4416 bounds,
4417 content_mask: self.snapped_content_mask(),
4418 thickness: self.snap_stroke(style.thickness),
4419 color: style.color.unwrap_or_default().opacity(opacity),
4420 wavy: false.into(),
4421 });
4422 }
4423
4424 pub fn paint_glyph(
4433 &mut self,
4434 origin: Point<Pixels>,
4435 font_id: FontId,
4436 glyph_id: GlyphId,
4437 font_size: Pixels,
4438 color: Hsla,
4439 ) -> Result<()> {
4440 self.invalidator.debug_assert_paint();
4441
4442 let element_opacity = self.element_opacity();
4443 let scale_factor = self.scale_factor();
4444 let glyph_origin = origin.scale(scale_factor);
4445
4446 let quantized_origin = Point::new(
4447 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
4448 / SUBPIXEL_VARIANTS_X as f32,
4449 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
4450 / SUBPIXEL_VARIANTS_Y as f32,
4451 );
4452 let subpixel_variant = Point::new(
4453 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
4454 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
4455 );
4456 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
4457 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
4458 let dilation = self.text_system().glyph_dilation_for_color(color);
4459 let params = RenderGlyphParams {
4460 font_id,
4461 glyph_id,
4462 font_size,
4463 subpixel_variant,
4464 scale_factor,
4465 is_emoji: false,
4466 subpixel_rendering,
4467 dilation,
4468 };
4469
4470 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4471 if !raster_bounds.is_zero() {
4472 let tile = self
4473 .sprite_atlas
4474 .get_or_insert_with(¶ms.clone().into(), &mut || {
4475 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4476 Ok(Some((size, Cow::Owned(bytes))))
4477 })?
4478 .expect("Callback above only errors or returns Some");
4479 let bounds = Bounds {
4480 origin: integer_origin + raster_bounds.origin.map(Into::into),
4481 size: tile.bounds.size.map(Into::into),
4482 };
4483 let content_mask = self.snapped_content_mask();
4484
4485 if subpixel_rendering {
4486 self.next_frame.scene.insert_primitive(SubpixelSprite {
4487 order: 0,
4488 pad: 0,
4489 bounds,
4490 content_mask,
4491 color: color.opacity(element_opacity),
4492 tile,
4493 transformation: TransformationMatrix::unit(),
4494 });
4495 } else {
4496 self.next_frame.scene.insert_primitive(MonochromeSprite {
4497 order: 0,
4498 pad: 0,
4499 bounds,
4500 content_mask,
4501 color: color.opacity(element_opacity),
4502 tile,
4503 transformation: TransformationMatrix::unit(),
4504 });
4505 }
4506 }
4507 Ok(())
4508 }
4509
4510 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
4511 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
4512 return false;
4513 }
4514
4515 if !self.platform_window.is_subpixel_rendering_supported() {
4516 return false;
4517 }
4518
4519 let mode = match self.text_rendering_mode.get() {
4520 TextRenderingMode::PlatformDefault => self
4521 .text_system()
4522 .recommended_rendering_mode(font_id, font_size),
4523 mode => mode,
4524 };
4525
4526 mode == TextRenderingMode::Subpixel
4527 }
4528
4529 pub fn paint_emoji(
4538 &mut self,
4539 origin: Point<Pixels>,
4540 font_id: FontId,
4541 glyph_id: GlyphId,
4542 font_size: Pixels,
4543 ) -> Result<()> {
4544 self.invalidator.debug_assert_paint();
4545
4546 let scale_factor = self.scale_factor();
4547 let glyph_origin = origin.scale(scale_factor);
4548 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
4549 let params = RenderGlyphParams {
4550 font_id,
4551 glyph_id,
4552 font_size,
4553 subpixel_variant: Default::default(),
4554 scale_factor,
4555 is_emoji: true,
4556 subpixel_rendering: false,
4557 dilation: 0,
4558 };
4559
4560 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4561 if !raster_bounds.is_zero() {
4562 let tile = self
4563 .sprite_atlas
4564 .get_or_insert_with(¶ms.clone().into(), &mut || {
4565 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4566 Ok(Some((size, Cow::Owned(bytes))))
4567 })?
4568 .expect("Callback above only errors or returns Some");
4569
4570 let bounds = Bounds {
4571 origin: integer_origin + raster_bounds.origin.map(Into::into),
4572 size: tile.bounds.size.map(Into::into),
4573 };
4574 let content_mask = self.snapped_content_mask();
4575 let opacity = self.element_opacity();
4576
4577 self.next_frame.scene.insert_primitive(PolychromeSprite {
4578 order: 0,
4579 pad: 0,
4580 grayscale: false.into(),
4581 bounds,
4582 corner_radii: Default::default(),
4583 content_mask,
4584 tile,
4585 opacity,
4586 });
4587 }
4588 Ok(())
4589 }
4590
4591 pub fn paint_svg(
4595 &mut self,
4596 bounds: Bounds<Pixels>,
4597 path: SharedString,
4598 mut data: Option<&[u8]>,
4599 transformation: TransformationMatrix,
4600 color: Hsla,
4601 cx: &App,
4602 ) -> Result<()> {
4603 self.invalidator.debug_assert_paint();
4604
4605 let element_opacity = self.element_opacity();
4606 let bounds = self.snap_bounds(bounds);
4607
4608 let params = RenderSvgParams {
4609 path,
4610 size: bounds.size.map(|pixels| {
4611 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
4612 }),
4613 };
4614
4615 let Some(tile) =
4616 self.sprite_atlas
4617 .get_or_insert_with(¶ms.clone().into(), &mut || {
4618 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
4619 else {
4620 return Ok(None);
4621 };
4622 Ok(Some((size, Cow::Owned(bytes))))
4623 })?
4624 else {
4625 return Ok(());
4626 };
4627 let content_mask = self.snapped_content_mask();
4628 let svg_bounds = Bounds {
4629 origin: bounds.center()
4630 - Point::new(
4631 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4632 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4633 ),
4634 size: tile
4635 .bounds
4636 .size
4637 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
4638 };
4639 let final_bounds = svg_bounds
4640 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
4641 .map_size(|size| size.ceil());
4642
4643 self.next_frame.scene.insert_primitive(MonochromeSprite {
4644 order: 0,
4645 pad: 0,
4646 bounds: final_bounds,
4647 content_mask,
4648 color: color.opacity(element_opacity),
4649 tile,
4650 transformation,
4651 });
4652
4653 Ok(())
4654 }
4655
4656 pub fn paint_image(
4665 &mut self,
4666 bounds: Bounds<Pixels>,
4667 image_bounds: Bounds<Pixels>,
4668 corner_radii: Corners<Pixels>,
4669 data: Arc<RenderImage>,
4670 frame_index: usize,
4671 grayscale: bool,
4672 ) -> Result<()> {
4673 self.invalidator.debug_assert_paint();
4674
4675 let visible_bounds = bounds.intersect(&image_bounds);
4676 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
4677 return Ok(());
4678 }
4679 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
4680 return Ok(());
4681 }
4682
4683 let params = RenderImageParams {
4684 image_id: data.id,
4685 frame_index,
4686 };
4687
4688 let tile = self
4689 .sprite_atlas
4690 .get_or_insert_with(¶ms.into(), &mut || {
4691 Ok(Some((
4692 data.size(frame_index),
4693 Cow::Borrowed(
4694 data.as_bytes(frame_index)
4695 .expect("It's the caller's job to pass a valid frame index"),
4696 ),
4697 )))
4698 })?
4699 .expect("Callback above only returns Some");
4700
4701 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
4702
4703 let sub_tile = if visible_bounds == image_bounds {
4704 tile
4705 } else {
4706 let x_offset_ratio =
4707 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
4708 let y_offset_ratio =
4709 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
4710 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
4711 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
4712
4713 let tile_origin_x = tile.bounds.origin.x.0;
4714 let tile_origin_y = tile.bounds.origin.y.0;
4715 let tile_width = tile.bounds.size.width.0;
4716 let tile_height = tile.bounds.size.height.0;
4717
4718 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
4719 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
4720 let sub_width = (width_ratio * tile_width as f32).round() as i32;
4721 let sub_height = (height_ratio * tile_height as f32).round() as i32;
4722
4723 let max_x = tile_origin_x + tile_width;
4724 let max_y = tile_origin_y + tile_height;
4725
4726 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
4727 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
4728 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
4729 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
4730
4731 AtlasTile {
4732 bounds: Bounds {
4733 origin: point(
4734 DevicePixels(clamped_origin_x),
4735 DevicePixels(clamped_origin_y),
4736 ),
4737 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
4738 },
4739 ..tile
4740 }
4741 };
4742
4743 let content_mask = self.snapped_content_mask();
4744 let corner_radii = corner_radii
4745 .clamp_radii_for_quad_size(visible_bounds.size)
4746 .scale(self.scale_factor());
4747 let opacity = self.element_opacity();
4748
4749 self.next_frame.scene.insert_primitive(PolychromeSprite {
4750 order: 0,
4751 pad: 0,
4752 grayscale: grayscale.into(),
4753 bounds: visible_bounds_snapped,
4754 content_mask,
4755 corner_radii,
4756 tile: sub_tile,
4757 opacity,
4758 });
4759 Ok(())
4760 }
4761
4762 #[cfg(target_os = "macos")]
4766 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
4767 use crate::PaintSurface;
4768
4769 self.invalidator.debug_assert_paint();
4770
4771 let bounds = self.snap_bounds(bounds);
4772 let content_mask = self.snapped_content_mask();
4773 self.next_frame.scene.insert_primitive(PaintSurface {
4774 order: 0,
4775 bounds,
4776 content_mask,
4777 image_buffer,
4778 });
4779 }
4780
4781 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
4783 for frame_index in 0..data.frame_count() {
4784 let params = RenderImageParams {
4785 image_id: data.id,
4786 frame_index,
4787 };
4788
4789 self.sprite_atlas.remove(¶ms.clone().into());
4790 }
4791
4792 Ok(())
4793 }
4794
4795 #[cfg(any(test, feature = "test-support"))]
4797 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
4798 data.frame_count() > 0
4799 && (0..data.frame_count()).all(|frame_index| {
4800 self.sprite_atlas.contains(
4801 &RenderImageParams {
4802 image_id: data.id,
4803 frame_index,
4804 }
4805 .into(),
4806 )
4807 })
4808 }
4809
4810 #[must_use]
4816 pub fn request_layout(
4817 &mut self,
4818 style: Style,
4819 children: impl IntoIterator<Item = LayoutId>,
4820 cx: &mut App,
4821 ) -> LayoutId {
4822 self.invalidator.debug_assert_prepaint();
4823
4824 cx.layout_id_buffer.clear();
4825 cx.layout_id_buffer.extend(children);
4826 let rem_size = self.rem_size();
4827 let scale_factor = self.scale_factor();
4828
4829 self.layout_engine.as_mut().unwrap().request_layout(
4830 style,
4831 rem_size,
4832 scale_factor,
4833 &cx.layout_id_buffer,
4834 )
4835 }
4836
4837 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
4846 where
4847 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
4848 + 'static,
4849 {
4850 self.invalidator.debug_assert_prepaint();
4851
4852 let rem_size = self.rem_size();
4853 let scale_factor = self.scale_factor();
4854 self.layout_engine
4855 .as_mut()
4856 .unwrap()
4857 .request_measured_layout(style, rem_size, scale_factor, measure)
4858 }
4859
4860 pub fn compute_layout(
4866 &mut self,
4867 layout_id: LayoutId,
4868 available_space: Size<AvailableSpace>,
4869 cx: &mut App,
4870 ) {
4871 self.invalidator.debug_assert_prepaint();
4872
4873 let mut layout_engine = self.layout_engine.take().unwrap();
4874 layout_engine.compute_layout(layout_id, available_space, self, cx);
4875 self.layout_engine = Some(layout_engine);
4876 }
4877
4878 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
4883 self.invalidator.debug_assert_prepaint();
4884
4885 let scale_factor = self.scale_factor();
4886 let mut bounds = self
4887 .layout_engine
4888 .as_mut()
4889 .unwrap()
4890 .layout_bounds(layout_id, scale_factor)
4891 .map(Into::into);
4892 let snapped_offset = self.pixel_snap_point(self.element_offset());
4893 bounds.origin += snapped_offset;
4894 bounds
4895 }
4896
4897 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
4903 self.invalidator.debug_assert_prepaint();
4904
4905 let content_mask = self.content_mask();
4906 let mut id = self.next_hitbox_id;
4907 self.next_hitbox_id = self.next_hitbox_id.next();
4908 let hitbox = Hitbox {
4909 id,
4910 bounds,
4911 content_mask,
4912 behavior,
4913 };
4914 self.next_frame.hitboxes.push(hitbox.clone());
4915 hitbox
4916 }
4917
4918 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
4922 self.invalidator.debug_assert_paint();
4923 self.next_frame.window_control_hitboxes.push((area, hitbox));
4924 }
4925
4926 pub fn set_key_context(&mut self, context: KeyContext) {
4931 self.invalidator.debug_assert_paint();
4932 self.next_frame.dispatch_tree.set_key_context(context);
4933 }
4934
4935 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
4940 self.invalidator.debug_assert_prepaint();
4941 if focus_handle.is_focused(self) {
4942 self.next_frame.focus = Some(focus_handle.id);
4943 }
4944 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
4945 }
4946
4947 pub fn set_view_id(&mut self, view_id: EntityId) {
4953 self.invalidator.debug_assert_prepaint();
4954 self.next_frame.dispatch_tree.set_view_id(view_id);
4955 }
4956
4957 pub fn current_view(&self) -> EntityId {
4959 self.invalidator.debug_assert_paint_or_prepaint();
4960 self.rendered_entity_stack.last().copied().unwrap()
4961 }
4962
4963 #[inline]
4964 pub(crate) fn with_rendered_view<R>(
4965 &mut self,
4966 id: EntityId,
4967 f: impl FnOnce(&mut Self) -> R,
4968 ) -> R {
4969 self.rendered_entity_stack.push(id);
4970 let result = f(self);
4971 self.rendered_entity_stack.pop();
4972 result
4973 }
4974
4975 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
4977 where
4978 F: FnOnce(&mut Self) -> R,
4979 {
4980 if let Some(image_cache) = image_cache {
4981 self.image_cache_stack.push(image_cache);
4982 let result = f(self);
4983 self.image_cache_stack.pop();
4984 result
4985 } else {
4986 f(self)
4987 }
4988 }
4989
4990 pub fn handle_input(
4999 &mut self,
5000 focus_handle: &FocusHandle,
5001 input_handler: impl InputHandler,
5002 cx: &App,
5003 ) {
5004 self.invalidator.debug_assert_paint();
5005
5006 if focus_handle.is_focused(self) {
5007 let cx = self.to_async(cx);
5008 self.next_frame
5009 .input_handlers
5010 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
5011 }
5012 }
5013
5014 fn apply_text_input_configuration(&mut self, cx: &mut App) {
5019 let configuration = match self.platform_window.take_input_handler() {
5020 Some(mut input_handler) => {
5021 let configuration = input_handler.text_input_configuration(self, cx);
5022 self.platform_window.set_input_handler(input_handler);
5023 configuration
5024 }
5025 None => TextInputConfiguration::default(),
5026 };
5027 if self.last_text_input_configuration.as_ref() != Some(&configuration) {
5028 self.platform_window
5029 .set_text_input_configuration(configuration.clone());
5030 self.last_text_input_configuration = Some(configuration);
5031 }
5032 }
5033
5034 pub fn on_mouse_event<Event: MouseEvent>(
5040 &mut self,
5041 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5042 ) {
5043 self.invalidator.debug_assert_paint();
5044
5045 self.next_frame.mouse_listeners.push(Some(Box::new(
5046 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
5047 if let Some(event) = event.downcast_ref() {
5048 listener(event, phase, window, cx)
5049 }
5050 },
5051 )));
5052 }
5053
5054 pub fn on_key_event<Event: KeyEvent>(
5063 &mut self,
5064 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5065 ) {
5066 self.invalidator.debug_assert_paint();
5067
5068 self.next_frame.dispatch_tree.on_key_event(Rc::new(
5069 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
5070 if let Some(event) = event.downcast_ref::<Event>() {
5071 listener(event, phase, window, cx)
5072 }
5073 },
5074 ));
5075 }
5076
5077 pub fn on_modifiers_changed(
5084 &mut self,
5085 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
5086 ) {
5087 self.invalidator.debug_assert_paint();
5088
5089 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
5090 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
5091 listener(event, window, cx)
5092 },
5093 ));
5094 }
5095
5096 pub fn on_focus_in(
5100 &mut self,
5101 handle: &FocusHandle,
5102 cx: &mut App,
5103 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
5104 ) -> Subscription {
5105 let focus_id = handle.id;
5106 let (subscription, activate) =
5107 self.new_focus_listener(Box::new(move |event, window, cx| {
5108 if event.is_focus_in(focus_id) {
5109 listener(window, cx);
5110 }
5111 true
5112 }));
5113 cx.defer(move |_| activate());
5114 subscription
5115 }
5116
5117 pub fn on_focus_out(
5120 &mut self,
5121 handle: &FocusHandle,
5122 cx: &mut App,
5123 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
5124 ) -> Subscription {
5125 let focus_id = handle.id;
5126 let (subscription, activate) =
5127 self.new_focus_listener(Box::new(move |event, window, cx| {
5128 if let Some(blurred_id) = event.previous_focus_path.last().copied()
5129 && event.is_focus_out(focus_id)
5130 {
5131 let event = FocusOutEvent {
5132 blurred: WeakFocusHandle {
5133 id: blurred_id,
5134 handles: Arc::downgrade(&cx.focus_handles),
5135 },
5136 };
5137 listener(event, window, cx)
5138 }
5139 true
5140 }));
5141 cx.defer(move |_| activate());
5142 subscription
5143 }
5144
5145 fn reset_cursor_style(&self, cx: &mut App) {
5146 if self.is_window_hovered() {
5148 let style = self
5149 .rendered_frame
5150 .cursor_style(self)
5151 .unwrap_or(CursorStyle::Arrow);
5152 cx.platform.set_cursor_style(style);
5153 }
5154 }
5155
5156 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
5159 let keystroke = keystroke.with_simulated_ime();
5160 let result = self.dispatch_event(
5161 PlatformInput::KeyDown(KeyDownEvent {
5162 keystroke: keystroke.clone(),
5163 is_held: false,
5164 prefer_character_input: false,
5165 }),
5166 cx,
5167 );
5168 if !result.propagate {
5169 return true;
5170 }
5171
5172 if let Some(input) = keystroke.key_char
5173 && let Some(mut input_handler) = self.platform_window.take_input_handler()
5174 {
5175 input_handler.dispatch_input(&input, self, cx);
5176 self.platform_window.set_input_handler(input_handler);
5177 return true;
5178 }
5179
5180 false
5181 }
5182
5183 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
5186 self.highest_precedence_binding_for_action(action)
5187 .map(|binding| {
5188 binding
5189 .keystrokes()
5190 .iter()
5191 .map(ToString::to_string)
5192 .collect::<Vec<_>>()
5193 .join(" ")
5194 })
5195 .unwrap_or_else(|| action.name().to_string())
5196 }
5197
5198 #[profiling::function]
5200 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
5201 #[cfg(feature = "profiler")]
5202 self.window_profiler.begin_input(event.kind_name());
5203 let update_count_before = self.invalidator.update_count();
5204 let old_modality = self.last_input_modality;
5208 self.last_input_modality = match &event {
5209 PlatformInput::KeyDown(_) => InputModality::Keyboard,
5210 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
5211 PlatformInput::Touch(_) => InputModality::Touch,
5212 _ => self.last_input_modality,
5213 };
5214 if self.last_input_modality != old_modality {
5215 self.refresh();
5216 }
5217
5218 cx.propagate_event = true;
5220 self.default_prevented = false;
5222
5223 let event = match event {
5224 PlatformInput::MouseMove(mouse_move) => {
5227 self.mouse_position = mouse_move.position;
5228 self.modifiers = mouse_move.modifiers;
5229 PlatformInput::MouseMove(mouse_move)
5230 }
5231 PlatformInput::MouseDown(mouse_down) => {
5232 self.mouse_position = mouse_down.position;
5233 self.modifiers = mouse_down.modifiers;
5234 PlatformInput::MouseDown(mouse_down)
5235 }
5236 PlatformInput::MouseUp(mouse_up) => {
5237 self.mouse_position = mouse_up.position;
5238 self.modifiers = mouse_up.modifiers;
5239 PlatformInput::MouseUp(mouse_up)
5240 }
5241 PlatformInput::MousePressure(mouse_pressure) => {
5242 PlatformInput::MousePressure(mouse_pressure)
5243 }
5244 PlatformInput::MouseExited(mouse_exited) => {
5245 self.modifiers = mouse_exited.modifiers;
5246 PlatformInput::MouseExited(mouse_exited)
5247 }
5248 PlatformInput::ModifiersChanged(modifiers_changed) => {
5249 self.modifiers = modifiers_changed.modifiers;
5250 self.capslock = modifiers_changed.capslock;
5251 PlatformInput::ModifiersChanged(modifiers_changed)
5252 }
5253 PlatformInput::ScrollWheel(scroll_wheel) => {
5254 self.mouse_position = scroll_wheel.position;
5255 self.modifiers = scroll_wheel.modifiers;
5256 PlatformInput::ScrollWheel(scroll_wheel)
5257 }
5258 PlatformInput::Pinch(pinch) => {
5259 self.mouse_position = pinch.position;
5260 self.modifiers = pinch.modifiers;
5261 PlatformInput::Pinch(pinch)
5262 }
5263 PlatformInput::FileDrop(file_drop) => match file_drop {
5266 FileDropEvent::Entered { position, paths } => {
5267 self.mouse_position = position;
5268 let source_window = self.handle.window_id();
5269 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
5270 cx.active_drag = Some(AnyDrag {
5271 value: Arc::new(paths.clone()),
5272 view: cx.new(|_| paths).into(),
5273 cursor_offset: position,
5274 cursor_style: None,
5275 external_payload_source: None,
5276 });
5277 }
5278 PlatformInput::MouseMove(MouseMoveEvent {
5279 position,
5280 pressed_button: Some(MouseButton::Left),
5281 modifiers: Modifiers::default(),
5282 })
5283 }
5284 FileDropEvent::Pending { position } => {
5285 self.mouse_position = position;
5286 PlatformInput::MouseMove(MouseMoveEvent {
5287 position,
5288 pressed_button: Some(MouseButton::Left),
5289 modifiers: Modifiers::default(),
5290 })
5291 }
5292 FileDropEvent::Submit { position } => {
5293 cx.activate(true);
5294 self.mouse_position = position;
5295 PlatformInput::MouseUp(MouseUpEvent {
5296 button: MouseButton::Left,
5297 position,
5298 modifiers: Modifiers::default(),
5299 click_count: 1,
5300 })
5301 }
5302 FileDropEvent::Exited => {
5303 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
5304 cx.active_drag.take();
5305 }
5306 self.refresh();
5307 PlatformInput::FileDrop(FileDropEvent::Exited)
5308 }
5309 FileDropEvent::Ended => {
5310 cx.end_platform_drag(self.handle.window_id());
5311 self.refresh();
5312 PlatformInput::FileDrop(FileDropEvent::Ended)
5313 }
5314 },
5315 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
5316 PlatformInput::LongPress(long_press) => {
5317 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
5318 long_press.start_position
5319 } else {
5320 long_press.position
5321 };
5322 if long_press.phase == crate::TouchPhase::Started {
5323 self.long_press_capture = None;
5324 }
5325 PlatformInput::LongPress(long_press)
5326 }
5327 PlatformInput::TouchDrag(touch_drag) => {
5328 self.mouse_position = touch_drag.start_position;
5329 PlatformInput::TouchDrag(touch_drag)
5330 }
5331 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
5332 };
5333
5334 if let Some(any_mouse_event) = event.mouse_event() {
5335 self.dispatch_mouse_event(any_mouse_event, cx);
5336 } else if let Some(any_key_event) = event.keyboard_event() {
5337 self.dispatch_key_event(any_key_event, cx);
5338 } else if let Some(touch_event) = event.touch_event() {
5339 self.dispatch_touch_event(touch_event, cx);
5340 }
5341 if let PlatformInput::LongPress(long_press) = &event {
5342 match long_press.phase {
5343 crate::TouchPhase::Started if !self.default_prevented => {
5344 self.long_press_capture = None;
5345 }
5346 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled => {
5347 self.long_press_capture = None;
5348 }
5349 crate::TouchPhase::Started | crate::TouchPhase::Moved => {}
5350 }
5351 }
5352
5353 self.promote_external_drag_to_platform(&event, cx);
5356
5357 let caused_invalidation = self.invalidator.update_count() > update_count_before;
5358 if caused_invalidation {
5359 self.input_rate_tracker.borrow_mut().record_input();
5360 }
5361 #[cfg(feature = "profiler")]
5362 self.window_profiler.end_input(caused_invalidation);
5363
5364 DispatchEventResult {
5365 propagate: cx.propagate_event,
5366 default_prevented: self.default_prevented,
5367 }
5368 }
5369
5370 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
5371 let PlatformInput::MouseMove(mouse_move) = event else {
5372 return;
5373 };
5374 if mouse_move.pressed_button != Some(MouseButton::Left) {
5375 return;
5376 }
5377 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
5378 return;
5379 }
5380 if !self.platform_window.can_start_external_drag() {
5381 return;
5382 }
5383 let Some(payload_source) = cx
5384 .active_drag
5385 .as_mut()
5386 .and_then(|drag| drag.external_payload_source.take())
5387 else {
5388 return;
5389 };
5390 let Some(payload) = payload_source(self, cx) else {
5391 return;
5392 };
5393 if self.platform_window.start_external_drag(&payload)
5394 && cx.hand_active_drag_to_platform(self.handle.window_id())
5395 {
5396 self.refresh();
5397 }
5398 }
5399
5400 pub fn touch_prediction_enabled(&self) -> bool {
5404 self.touch_prediction_enabled
5405 }
5406
5407 pub fn set_touch_prediction_enabled(&mut self, enabled: bool) {
5411 self.touch_prediction_enabled = enabled;
5412 }
5413
5414 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
5418 let mut event = event.clone();
5419 if !self.touch_prediction_enabled {
5420 event.predicted_position = None;
5421 }
5422 let recognized_gestures = self.touch_gestures.handle_event(&event);
5423 if event.phase == crate::TouchPhase::Started
5424 && let Some(touch_drag) = self.touch_gestures.offer_touch_drag(event.id)
5425 {
5426 self.dispatch_recognized_touch_gesture(touch_drag, cx);
5427 }
5428 if event.phase == crate::TouchPhase::Started
5429 && self.touch_gestures.pending_long_press().is_some()
5430 {
5431 self.long_press_capture = None;
5432 }
5433 let mut tapped = false;
5434 for gesture in recognized_gestures {
5435 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
5436 self.dispatch_recognized_touch_gesture(gesture, cx);
5437 }
5438 if event.phase == crate::TouchPhase::Started {
5439 self.schedule_long_press_timer(cx);
5440 } else if self.touch_gestures.pending_long_press().is_none() {
5441 self.long_press_timer.take();
5442 }
5443 if tapped && self.invalidator.is_dirty() {
5449 self.draw(cx).clear(cx);
5450 }
5451 if self.touch_gestures.has_momentum() {
5452 self.schedule_touch_momentum_tick();
5453 }
5454 }
5455
5456 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
5457 match gesture {
5458 RecognizedTouchGesture::Scroll(scroll_wheel) => {
5459 self.mouse_position = scroll_wheel.position;
5460 cx.propagate_event = true;
5461 self.dispatch_mouse_event(&scroll_wheel, cx);
5462 }
5463 RecognizedTouchGesture::Tap { down, up } => {
5464 self.mouse_position = up.position;
5465 cx.propagate_event = true;
5466 self.dispatch_mouse_event(&down, cx);
5467 cx.propagate_event = true;
5468 self.dispatch_mouse_event(&up, cx);
5469 }
5470 RecognizedTouchGesture::TouchDrag(touch_drag) => {
5471 self.mouse_position = touch_drag.start_position;
5472 cx.propagate_event = true;
5473 self.default_prevented = false;
5474 let started = touch_drag.phase == crate::TouchPhase::Started;
5475 self.dispatch_mouse_event(&touch_drag, cx);
5476 if started {
5477 self.touch_gestures
5478 .resolve_touch_drag(self.default_prevented);
5479 }
5480 }
5481 RecognizedTouchGesture::LongPress(long_press) => {
5482 self.mouse_position = if long_press.phase == crate::TouchPhase::Started {
5483 long_press.start_position
5484 } else {
5485 long_press.position
5486 };
5487 cx.propagate_event = true;
5488 self.default_prevented = false;
5489 let started = long_press.phase == crate::TouchPhase::Started;
5490 let ended = matches!(
5491 long_press.phase,
5492 crate::TouchPhase::Ended | crate::TouchPhase::Cancelled
5493 );
5494 self.dispatch_mouse_event(&long_press, cx);
5495 if started {
5496 let claimed = self.default_prevented;
5497 self.touch_gestures.resolve_long_press(claimed);
5498 if !claimed {
5499 self.long_press_capture = None;
5500 }
5501 }
5502 if ended {
5503 self.long_press_capture = None;
5504 }
5505 }
5506 }
5507 }
5508
5509 fn schedule_long_press_timer(&mut self, cx: &mut App) {
5510 self.long_press_timer.take();
5511 let Some((touch_id, duration)) = self.touch_gestures.pending_long_press() else {
5512 return;
5513 };
5514 self.long_press_timer = Some(self.spawn(cx, async move |cx| {
5515 cx.background_executor.timer(duration).await;
5516 cx.update(move |window, cx| {
5517 window.long_press_timer.take();
5518 if let Some(gesture) = window.touch_gestures.offer_long_press(touch_id) {
5519 window.dispatch_recognized_touch_gesture(gesture, cx);
5520 }
5521 })
5522 .log_err();
5523 }));
5524 }
5525
5526 fn schedule_touch_momentum_tick(&mut self) {
5527 self.on_next_frame(|window, cx| {
5528 if let Some(gesture) = window.touch_gestures.tick_momentum() {
5529 window.dispatch_recognized_touch_gesture(gesture, cx);
5530 }
5531 if window.touch_gestures.has_momentum() {
5532 window.schedule_touch_momentum_tick();
5533 }
5534 });
5535 }
5536
5537 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5538 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
5539 if hit_test != self.mouse_hit_test {
5540 self.mouse_hit_test = hit_test;
5541 self.reset_cursor_style(cx);
5542 }
5543
5544 #[cfg(any(feature = "inspector", debug_assertions))]
5545 if self.is_inspector_picking(cx) {
5546 self.handle_inspector_mouse_event(event, cx);
5547 return;
5549 }
5550
5551 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
5552
5553 for listener in &mut mouse_listeners {
5556 let listener = listener.as_mut().unwrap();
5557 listener(event, DispatchPhase::Capture, self, cx);
5558 if !cx.propagate_event {
5559 break;
5560 }
5561 }
5562
5563 if cx.propagate_event {
5565 for listener in mouse_listeners.iter_mut().rev() {
5566 let listener = listener.as_mut().unwrap();
5567 listener(event, DispatchPhase::Bubble, self, cx);
5568 if !cx.propagate_event {
5569 break;
5570 }
5571 }
5572 }
5573
5574 self.rendered_frame.mouse_listeners = mouse_listeners;
5575
5576 if cx.has_active_drag() {
5577 if event.is::<MouseMoveEvent>() {
5578 self.refresh();
5581 } else if event.is::<MouseUpEvent>() {
5582 cx.active_drag = None;
5585 self.refresh();
5586 }
5587 }
5588
5589 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
5591 self.captured_hitbox = None;
5592 }
5593 }
5594
5595 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
5596 if self.invalidator.is_dirty() {
5597 self.draw(cx).clear(cx);
5598 }
5599
5600 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5601 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5602
5603 let mut keystroke: Option<Keystroke> = None;
5604
5605 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
5606 if event.modifiers.number_of_modifiers() == 0
5607 && self.pending_modifier.modifiers.number_of_modifiers() == 1
5608 && !self.pending_modifier.saw_other_input
5609 {
5610 let key = match self.pending_modifier.modifiers {
5611 modifiers if modifiers.shift => Some("shift"),
5612 modifiers if modifiers.control => Some("control"),
5613 modifiers if modifiers.alt => Some("alt"),
5614 modifiers if modifiers.platform => Some("platform"),
5615 modifiers if modifiers.function => Some("function"),
5616 _ => None,
5617 };
5618 if let Some(key) = key {
5619 keystroke = Some(Keystroke {
5620 key: key.to_string(),
5621 key_char: None,
5622 modifiers: Modifiers::default(),
5623 });
5624 }
5625 }
5626
5627 if self.pending_modifier.modifiers.number_of_modifiers() == 0
5628 && event.modifiers.number_of_modifiers() == 1
5629 {
5630 self.pending_modifier.saw_other_input = false
5631 } else if event.modifiers.number_of_modifiers() > 1 {
5632 self.pending_modifier.saw_other_input = true
5633 }
5634 self.pending_modifier.modifiers = event.modifiers
5635 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
5636 self.pending_modifier.saw_other_input = true;
5637 keystroke = Some(key_down_event.keystroke.clone());
5638 if key_down_event.keystroke.key_char.is_some()
5639 && matches!(
5640 cx.cursor_hide_mode,
5641 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
5642 )
5643 {
5644 cx.platform.hide_cursor_until_mouse_moves();
5645 }
5646 }
5647
5648 let Some(keystroke) = keystroke else {
5649 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5650 return;
5651 };
5652
5653 cx.propagate_event = true;
5654 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
5655 if !cx.propagate_event {
5656 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5657 return;
5658 }
5659
5660 let mut currently_pending = self.pending_input.take().unwrap_or_default();
5661 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
5662 currently_pending = PendingInput::default();
5663 }
5664
5665 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
5666 currently_pending.keystrokes,
5667 keystroke,
5668 &dispatch_path,
5669 );
5670
5671 if !match_result.to_replay.is_empty() {
5672 self.replay_pending_input(match_result.to_replay, cx);
5673 cx.propagate_event = true;
5674 }
5675
5676 if !match_result.pending.is_empty() {
5677 let previous_timeout = currently_pending.timeout.take();
5678 currently_pending.keystrokes = match_result.pending;
5679 currently_pending.focus = self.focus;
5680
5681 let text_input_requires_timeout = event
5682 .downcast_ref::<KeyDownEvent>()
5683 .filter(|key_down| key_down.keystroke.key_char.is_some())
5684 .and_then(|_| self.platform_window.take_input_handler())
5685 .map_or(false, |mut input_handler| {
5686 let accepts = input_handler.accepts_text_input(self, cx);
5687 self.platform_window.set_input_handler(input_handler);
5688 accepts
5689 });
5690
5691 let needs_timeout = previous_timeout.is_some()
5692 || match_result.pending_has_binding
5693 || text_input_requires_timeout;
5694 currently_pending.timeout = if needs_timeout {
5695 match previous_timeout {
5696 Some(mut timeout) if timeout.is_paused() => {
5697 timeout.reset_duration(PENDING_INPUT_TIMEOUT);
5698 Some(timeout)
5699 }
5700 previous_timeout => {
5701 drop(previous_timeout);
5702 Some(self.new_pending_input_timeout(PENDING_INPUT_TIMEOUT, cx))
5703 }
5704 }
5705 } else {
5706 None
5707 };
5708 self.pending_input = Some(currently_pending);
5709 self.pending_input_changed(cx);
5710 cx.propagate_event = false;
5711 return;
5712 }
5713
5714 let skip_bindings = event
5715 .downcast_ref::<KeyDownEvent>()
5716 .filter(|key_down_event| key_down_event.prefer_character_input)
5717 .map(|_| {
5718 self.platform_window
5719 .take_input_handler()
5720 .map_or(false, |mut input_handler| {
5721 let accepts = input_handler.accepts_text_input(self, cx);
5722 self.platform_window.set_input_handler(input_handler);
5723 accepts
5726 })
5727 })
5728 .unwrap_or(false);
5729
5730 if !skip_bindings {
5731 for binding in match_result.bindings {
5732 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5733 if !cx.propagate_event {
5734 self.dispatch_keystroke_observers(
5735 event,
5736 Some(binding.action),
5737 match_result.context_stack,
5738 cx,
5739 );
5740 self.pending_input_changed(cx);
5741 return;
5742 }
5743 }
5744 }
5745
5746 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
5747 self.pending_input_changed(cx);
5748 }
5749
5750 fn new_pending_input_timeout(&self, duration: Duration, cx: &App) -> PendingInputTimeout {
5751 let (started_at, task) = self.start_pending_input_timeout(duration, cx);
5752 PendingInputTimeout {
5753 duration,
5754 remaining: duration,
5755 state: PendingInputTimeoutState::Running { started_at, task },
5756 }
5757 }
5758
5759 fn start_pending_input_timeout(&self, remaining: Duration, cx: &App) -> (Instant, Task<()>) {
5760 let started_at = cx.background_executor().now();
5761 let task = self.spawn(cx, async move |cx| {
5762 cx.background_executor.timer(remaining).await;
5763 cx.update(move |window, cx| {
5764 let Some(currently_pending) = window
5765 .pending_input
5766 .take()
5767 .filter(|pending| pending.focus == window.focus)
5768 else {
5769 return;
5770 };
5771
5772 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
5773 let dispatch_path = window.rendered_frame.dispatch_tree.dispatch_path(node_id);
5774
5775 let to_replay = window
5776 .rendered_frame
5777 .dispatch_tree
5778 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
5779
5780 window.pending_input_changed(cx);
5781 window.replay_pending_input(to_replay, cx)
5782 })
5783 .log_err();
5784 });
5785 (started_at, task)
5786 }
5787
5788 fn finish_dispatch_key_event(
5789 &mut self,
5790 event: &dyn Any,
5791 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
5792 context_stack: Vec<KeyContext>,
5793 cx: &mut App,
5794 ) {
5795 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
5796 if !cx.propagate_event {
5797 return;
5798 }
5799
5800 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
5801 if !cx.propagate_event {
5802 return;
5803 }
5804
5805 self.dispatch_keystroke_observers(event, None, context_stack, cx);
5806 }
5807
5808 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
5809 self.pending_input_observers
5810 .clone()
5811 .retain(&(), |callback| callback(self, cx));
5812 }
5813
5814 fn defer_pending_input_changed(&self, cx: &mut App) {
5815 let window_handle = self.handle;
5818 cx.defer(move |cx| {
5819 window_handle
5820 .update(cx, |_, window, cx| {
5821 window.pending_input_changed(cx);
5822 })
5823 .ok();
5824 });
5825 }
5826
5827 fn dispatch_key_down_up_event(
5828 &mut self,
5829 event: &dyn Any,
5830 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5831 cx: &mut App,
5832 ) {
5833 for node_id in dispatch_path {
5835 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5836
5837 for key_listener in node.key_listeners.clone() {
5838 key_listener(event, DispatchPhase::Capture, self, cx);
5839 if !cx.propagate_event {
5840 return;
5841 }
5842 }
5843 }
5844
5845 for node_id in dispatch_path.iter().rev() {
5847 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5849 for key_listener in node.key_listeners.clone() {
5850 key_listener(event, DispatchPhase::Bubble, self, cx);
5851 if !cx.propagate_event {
5852 return;
5853 }
5854 }
5855 }
5856 }
5857
5858 fn dispatch_modifiers_changed_event(
5859 &mut self,
5860 event: &dyn Any,
5861 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5862 cx: &mut App,
5863 ) {
5864 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
5865 return;
5866 };
5867 for node_id in dispatch_path.iter().rev() {
5868 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5869 for listener in node.modifiers_changed_listeners.clone() {
5870 listener(event, self, cx);
5871 if !cx.propagate_event {
5872 return;
5873 }
5874 }
5875 }
5876 }
5877
5878 pub fn has_pending_keystrokes(&self) -> bool {
5880 self.pending_input().is_some()
5881 }
5882
5883 #[cfg(test)]
5884 pub(crate) fn pending_input_is_none(&self) -> bool {
5885 self.pending_input.is_none()
5886 }
5887
5888 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
5889 if self.pending_input.take().is_some() {
5890 self.defer_pending_input_changed(cx);
5891 }
5892 }
5893
5894 pub fn pending_input(&self) -> Option<PendingInputStatus<'_>> {
5897 self.pending_input
5898 .as_ref()
5899 .filter(|pending_input| pending_input.focus == self.focus)
5900 .map(|pending_input| PendingInputStatus {
5901 keystrokes: pending_input.keystrokes.as_slice(),
5902 timeout: pending_input
5903 .timeout
5904 .as_ref()
5905 .map(PendingInputTimeout::status),
5906 })
5907 }
5908
5909 pub fn set_pending_input_timeout_paused<T: 'static>(
5914 &mut self,
5915 owner: &Entity<T>,
5916 paused: bool,
5917 cx: &mut App,
5918 ) -> bool {
5919 let owner_id = owner.entity_id();
5920 if !paused {
5921 return self.resume_pending_input_timeout(owner_id, cx);
5922 }
5923
5924 let timeout = self
5925 .pending_input
5926 .as_ref()
5927 .filter(|pending_input| pending_input.focus == self.focus)
5928 .and_then(|pending_input| pending_input.timeout.as_ref());
5929 let Some(timeout) = timeout else {
5930 return false;
5931 };
5932 if timeout.is_paused() {
5933 return false;
5934 }
5935
5936 let release_subscription = self.observe_release(owner, cx, move |_, window, cx| {
5937 window.resume_pending_input_timeout(owner_id, cx);
5938 });
5939 let now = cx.background_executor().now();
5940 let changed = self
5941 .pending_input
5942 .as_mut()
5943 .filter(|pending_input| pending_input.focus == self.focus)
5944 .and_then(|pending_input| pending_input.timeout.as_mut())
5945 .is_some_and(|timeout| {
5946 timeout.pause(
5947 PendingInputTimeoutPause {
5948 owner_id,
5949 _release_subscription: release_subscription,
5950 },
5951 now,
5952 )
5953 });
5954
5955 if changed {
5956 self.defer_pending_input_changed(cx);
5957 }
5958 changed
5959 }
5960
5961 fn resume_pending_input_timeout(&mut self, owner_id: EntityId, cx: &mut App) -> bool {
5962 let Some(remaining) = self
5963 .pending_input
5964 .as_ref()
5965 .and_then(|pending_input| pending_input.timeout.as_ref())
5966 .filter(|timeout| timeout.pause_owner_id() == Some(owner_id))
5967 .map(|timeout| timeout.remaining)
5968 else {
5969 return false;
5970 };
5971
5972 let (started_at, task) = self.start_pending_input_timeout(remaining, cx);
5973 let changed = self
5974 .pending_input
5975 .as_mut()
5976 .and_then(|pending_input| pending_input.timeout.as_mut())
5977 .is_some_and(|timeout| timeout.resume(owner_id, started_at, task));
5978
5979 if changed {
5980 self.defer_pending_input_changed(cx);
5981 }
5982 changed
5983 }
5984
5985 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
5987 self.pending_input()
5988 .map(|pending_input| pending_input.keystrokes())
5989 }
5990
5991 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
5992 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5993 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5994
5995 'replay: for replay in replays {
5996 let event = KeyDownEvent {
5997 keystroke: replay.keystroke.clone(),
5998 is_held: false,
5999 prefer_character_input: true,
6000 };
6001
6002 cx.propagate_event = true;
6003 for binding in replay.bindings {
6004 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
6005 if !cx.propagate_event {
6006 self.dispatch_keystroke_observers(
6007 &event,
6008 Some(binding.action),
6009 Vec::default(),
6010 cx,
6011 );
6012 continue 'replay;
6013 }
6014 }
6015
6016 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
6017 if !cx.propagate_event {
6018 continue 'replay;
6019 }
6020 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
6021 && let Some(mut input_handler) = self.platform_window.take_input_handler()
6022 {
6023 input_handler.dispatch_input(&input, self, cx);
6024 self.platform_window.set_input_handler(input_handler)
6025 }
6026 }
6027 }
6028
6029 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
6030 focus_id
6031 .and_then(|focus_id| {
6032 self.rendered_frame
6033 .dispatch_tree
6034 .focusable_node_id(focus_id)
6035 })
6036 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
6037 }
6038
6039 fn dispatch_action_on_node(
6040 &mut self,
6041 node_id: DispatchNodeId,
6042 action: &dyn Action,
6043 cx: &mut App,
6044 ) {
6045 self.dispatch_action_on_node_inner(node_id, action, cx);
6046
6047 if !cx.propagate_event
6048 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
6049 && self.last_input_was_keyboard()
6050 {
6051 cx.platform.hide_cursor_until_mouse_moves();
6052 }
6053 }
6054
6055 fn dispatch_action_on_node_inner(
6056 &mut self,
6057 node_id: DispatchNodeId,
6058 action: &dyn Action,
6059 cx: &mut App,
6060 ) {
6061 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6062
6063 cx.propagate_event = true;
6065 if let Some(mut global_listeners) = cx
6066 .global_action_listeners
6067 .remove(&action.as_any().type_id())
6068 {
6069 for listener in &global_listeners {
6070 #[cfg(feature = "profiler")]
6071 self.window_profiler.begin_action_handler(action, cx);
6072 listener(action.as_any(), DispatchPhase::Capture, cx);
6073 #[cfg(feature = "profiler")]
6074 self.window_profiler.end_action_handler();
6075 if !cx.propagate_event {
6076 break;
6077 }
6078 }
6079
6080 global_listeners.extend(
6081 cx.global_action_listeners
6082 .remove(&action.as_any().type_id())
6083 .unwrap_or_default(),
6084 );
6085
6086 cx.global_action_listeners
6087 .insert(action.as_any().type_id(), global_listeners);
6088 }
6089
6090 if !cx.propagate_event {
6091 return;
6092 }
6093
6094 for node_id in &dispatch_path {
6096 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6097 for DispatchActionListener {
6098 action_type,
6099 listener,
6100 } in node.action_listeners.clone()
6101 {
6102 let any_action = action.as_any();
6103 if action_type == any_action.type_id() {
6104 #[cfg(feature = "profiler")]
6105 self.window_profiler.begin_action_handler(action, cx);
6106 listener(any_action, DispatchPhase::Capture, self, cx);
6107 #[cfg(feature = "profiler")]
6108 self.window_profiler.end_action_handler();
6109
6110 if !cx.propagate_event {
6111 return;
6112 }
6113 }
6114 }
6115 }
6116
6117 for node_id in dispatch_path.iter().rev() {
6119 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6120 for DispatchActionListener {
6121 action_type,
6122 listener,
6123 } in node.action_listeners.clone()
6124 {
6125 let any_action = action.as_any();
6126 if action_type == any_action.type_id() {
6127 cx.propagate_event = false; #[cfg(feature = "profiler")]
6129 self.window_profiler.begin_action_handler(action, cx);
6130 listener(any_action, DispatchPhase::Bubble, self, cx);
6131 #[cfg(feature = "profiler")]
6132 self.window_profiler.end_action_handler();
6133
6134 if !cx.propagate_event {
6135 return;
6136 }
6137 }
6138 }
6139 }
6140
6141 if let Some(mut global_listeners) = cx
6143 .global_action_listeners
6144 .remove(&action.as_any().type_id())
6145 {
6146 for listener in global_listeners.iter().rev() {
6147 cx.propagate_event = false; #[cfg(feature = "profiler")]
6150 self.window_profiler.begin_action_handler(action, cx);
6151 listener(action.as_any(), DispatchPhase::Bubble, cx);
6152 #[cfg(feature = "profiler")]
6153 self.window_profiler.end_action_handler();
6154 if !cx.propagate_event {
6155 break;
6156 }
6157 }
6158
6159 global_listeners.extend(
6160 cx.global_action_listeners
6161 .remove(&action.as_any().type_id())
6162 .unwrap_or_default(),
6163 );
6164
6165 cx.global_action_listeners
6166 .insert(action.as_any().type_id(), global_listeners);
6167 }
6168 }
6169
6170 pub fn observe_global<G: Global>(
6173 &mut self,
6174 cx: &mut App,
6175 f: impl Fn(&mut Window, &mut App) + 'static,
6176 ) -> Subscription {
6177 let window_handle = self.handle;
6178 let (subscription, activate) = cx.global_observers.insert(
6179 TypeId::of::<G>(),
6180 Box::new(move |cx| {
6181 window_handle
6182 .update(cx, |_, window, cx| f(window, cx))
6183 .is_ok()
6184 }),
6185 );
6186 cx.defer(move |_| activate());
6187 subscription
6188 }
6189
6190 pub fn activate_window(&self) {
6192 self.platform_window.activate();
6193 }
6194
6195 pub fn request_attention(&self) {
6197 self.platform_window.request_attention();
6198 }
6199
6200 pub fn minimize_window(&self) {
6202 self.platform_window.minimize();
6203 }
6204
6205 pub fn toggle_fullscreen(&self) {
6207 self.platform_window.toggle_fullscreen();
6208 }
6209
6210 pub fn toggle_simple_fullscreen(&self) {
6215 self.platform_window.toggle_simple_fullscreen();
6216 }
6217
6218 pub fn invalidate_character_coordinates(&self) {
6220 self.on_next_frame(|window, cx| {
6221 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
6222 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
6223 window.platform_window.update_ime_position(bounds);
6224 }
6225 window.platform_window.set_input_handler(input_handler);
6226 }
6227 });
6228 }
6229
6230 pub fn prompt<T>(
6234 &mut self,
6235 level: PromptLevel,
6236 message: &str,
6237 detail: Option<&str>,
6238 answers: &[T],
6239 cx: &mut App,
6240 ) -> oneshot::Receiver<usize>
6241 where
6242 T: Clone + Into<PromptButton>,
6243 {
6244 let prompt_builder = cx.prompt_builder.take();
6245 let Some(prompt_builder) = prompt_builder else {
6246 unreachable!("Re-entrant window prompting is not supported by GPUI");
6247 };
6248
6249 let answers = answers
6250 .iter()
6251 .map(|answer| answer.clone().into())
6252 .collect::<Vec<_>>();
6253
6254 let receiver = match &prompt_builder {
6255 PromptBuilder::Default => self
6256 .platform_window
6257 .prompt(level, message, detail, &answers)
6258 .unwrap_or_else(|| {
6259 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6260 }),
6261 PromptBuilder::Custom(_) => {
6262 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6263 }
6264 };
6265
6266 cx.prompt_builder = Some(prompt_builder);
6267
6268 receiver
6269 }
6270
6271 fn build_custom_prompt(
6272 &mut self,
6273 prompt_builder: &PromptBuilder,
6274 level: PromptLevel,
6275 message: &str,
6276 detail: Option<&str>,
6277 answers: &[PromptButton],
6278 cx: &mut App,
6279 ) -> oneshot::Receiver<usize> {
6280 let (sender, receiver) = oneshot::channel();
6281 let handle = PromptHandle::new(sender);
6282 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
6283 self.prompt = Some(handle);
6284 receiver
6285 }
6286
6287 pub fn has_active_prompt(&self) -> bool {
6292 self.prompt.is_some()
6293 }
6294
6295 pub fn context_stack(&self) -> Vec<KeyContext> {
6297 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6298 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6299 dispatch_tree
6300 .dispatch_path(node_id)
6301 .iter()
6302 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
6303 .collect()
6304 }
6305
6306 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
6308 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6309 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
6310 for action_type in cx.global_action_listeners.keys() {
6311 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
6312 let action = cx.actions.build_action_type(action_type).ok();
6313 if let Some(action) = action {
6314 actions.insert(ix, action);
6315 }
6316 }
6317 }
6318 actions
6319 }
6320
6321 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
6324 self.rendered_frame
6325 .dispatch_tree
6326 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
6327 }
6328
6329 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
6332 self.rendered_frame
6333 .dispatch_tree
6334 .highest_precedence_binding_for_action(
6335 action,
6336 &self.rendered_frame.dispatch_tree.context_stack,
6337 )
6338 }
6339
6340 pub fn bindings_for_action_in_context(
6342 &self,
6343 action: &dyn Action,
6344 context: KeyContext,
6345 ) -> Vec<KeyBinding> {
6346 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6347 dispatch_tree.bindings_for_action(action, &[context])
6348 }
6349
6350 pub fn highest_precedence_binding_for_action_in_context(
6353 &self,
6354 action: &dyn Action,
6355 context: KeyContext,
6356 ) -> Option<KeyBinding> {
6357 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6358 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
6359 }
6360
6361 pub fn bindings_for_action_in(
6365 &self,
6366 action: &dyn Action,
6367 focus_handle: &FocusHandle,
6368 ) -> Vec<KeyBinding> {
6369 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6370 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
6371 return vec![];
6372 };
6373 dispatch_tree.bindings_for_action(action, &context_stack)
6374 }
6375
6376 pub fn highest_precedence_binding_for_action_in(
6380 &self,
6381 action: &dyn Action,
6382 focus_handle: &FocusHandle,
6383 ) -> Option<KeyBinding> {
6384 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6385 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
6386 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
6387 }
6388
6389 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
6391 self.rendered_frame
6392 .dispatch_tree
6393 .possible_next_bindings_for_input(input, &self.context_stack())
6394 }
6395
6396 fn context_stack_for_focus_handle(
6397 &self,
6398 focus_handle: &FocusHandle,
6399 ) -> Option<Vec<KeyContext>> {
6400 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6401 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
6402 let context_stack: Vec<_> = dispatch_tree
6403 .dispatch_path(node_id)
6404 .into_iter()
6405 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
6406 .collect();
6407 Some(context_stack)
6408 }
6409
6410 pub fn listener_for<T: 'static, E>(
6412 &self,
6413 view: &Entity<T>,
6414 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
6415 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
6416 let view = view.downgrade();
6417 move |e: &E, window: &mut Window, cx: &mut App| {
6418 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
6419 }
6420 }
6421
6422 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
6424 &self,
6425 entity: &Entity<E>,
6426 f: Callback,
6427 ) -> impl Fn(&mut Window, &mut App) + 'static {
6428 let entity = entity.downgrade();
6429 move |window: &mut Window, cx: &mut App| {
6430 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
6431 }
6432 }
6433
6434 pub fn on_window_should_close(
6437 &self,
6438 cx: &App,
6439 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
6440 ) {
6441 let mut cx = self.to_async(cx);
6442 self.platform_window.on_should_close(Box::new(move || {
6443 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
6444 }))
6445 }
6446
6447 pub fn on_action(
6456 &mut self,
6457 action_type: TypeId,
6458 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
6459 ) {
6460 self.invalidator.debug_assert_paint();
6461
6462 self.next_frame
6463 .dispatch_tree
6464 .on_action(action_type, Rc::new(listener));
6465 }
6466
6467 pub fn on_action_when(
6476 &mut self,
6477 condition: bool,
6478 action_type: TypeId,
6479 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
6480 ) {
6481 self.invalidator.debug_assert_paint();
6482
6483 if condition {
6484 self.next_frame
6485 .dispatch_tree
6486 .on_action(action_type, Rc::new(listener));
6487 }
6488 }
6489
6490 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
6493 self.platform_window.gpu_specs()
6494 }
6495
6496 pub fn titlebar_double_click(&self) {
6499 self.platform_window
6500 .titlebar_double_click(self.is_resizable, self.is_minimizable);
6501 }
6502
6503 pub fn window_title(&self) -> String {
6506 self.platform_window.get_title()
6507 }
6508
6509 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
6512 self.platform_window.tabbed_windows()
6513 }
6514
6515 pub fn tab_bar_visible(&self) -> bool {
6518 self.platform_window.tab_bar_visible()
6519 }
6520
6521 pub fn merge_all_windows(&self) {
6524 self.platform_window.merge_all_windows()
6525 }
6526
6527 pub fn move_tab_to_new_window(&self) {
6530 self.platform_window.move_tab_to_new_window()
6531 }
6532
6533 pub fn toggle_window_tab_overview(&self) {
6536 self.platform_window.toggle_window_tab_overview()
6537 }
6538
6539 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
6542 self.platform_window
6543 .set_tabbing_identifier(tabbing_identifier)
6544 }
6545
6546 pub fn play_system_bell(&self) {
6549 self.platform_window.play_system_bell()
6550 }
6551
6552 pub fn is_a11y_active(&self) -> bool {
6563 self.a11y.is_active()
6564 }
6565
6566 pub fn debug_a11y_tree_json(&self) -> Option<String> {
6568 self.a11y.debug_tree_json()
6569 }
6570
6571 pub fn on_a11y_action(
6577 &mut self,
6578 node_id: accesskit::NodeId,
6579 action: accesskit::Action,
6580 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
6581 ) {
6582 self.a11y
6583 .action_listeners
6584 .entry(node_id)
6585 .or_default()
6586 .push((action, Box::new(listener)));
6587 }
6588
6589 #[cfg(not(target_family = "wasm"))]
6590 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
6591 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
6594 let extra_data = request.data.as_ref();
6595 let mut matched = false;
6596 for (action, listener) in &mut listeners {
6597 if *action == request.action {
6598 listener(extra_data, self, cx);
6599 matched = true;
6600 }
6601 }
6602 self.a11y
6603 .action_listeners
6604 .insert(request.target_node, listeners);
6605 if matched {
6606 return;
6607 }
6608 }
6609
6610 match request.action {
6612 accesskit::Action::Click => {
6613 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
6614 let center = bounds.center();
6615 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
6616 button: MouseButton::Left,
6617 position: center,
6618 modifiers: Modifiers::default(),
6619 click_count: 1,
6620 first_mouse: false,
6621 });
6622 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
6623 button: MouseButton::Left,
6624 position: center,
6625 modifiers: Modifiers::default(),
6626 click_count: 1,
6627 });
6628 self.dispatch_event(mouse_down, cx);
6629 self.dispatch_event(mouse_up, cx);
6630 }
6631 }
6632 accesskit::Action::Focus => {
6633 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
6634 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
6635 {
6636 self.focus(&handle, cx);
6637 }
6638 }
6639 accesskit::Action::Blur => {
6640 self.blur(cx);
6641 }
6642 _ => {
6643 log::debug!(
6644 "Unhandled a11y action: {:?} on {:?}",
6645 request.action,
6646 request.target_node
6647 );
6648 }
6649 }
6650 }
6651
6652 #[cfg(any(feature = "inspector", debug_assertions))]
6654 pub fn toggle_inspector(&mut self, cx: &mut App) {
6655 self.inspector = match self.inspector {
6656 None => Some(cx.new(|_| Inspector::new())),
6657 Some(_) => None,
6658 };
6659 self.refresh();
6660 }
6661
6662 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
6664 #[cfg(any(feature = "inspector", debug_assertions))]
6665 {
6666 if let Some(inspector) = &self.inspector {
6667 return inspector.read(_cx).is_picking();
6668 }
6669 }
6670 false
6671 }
6672
6673 #[cfg(any(feature = "inspector", debug_assertions))]
6675 pub fn with_inspector_state<T: 'static, R>(
6676 &mut self,
6677 _inspector_id: Option<&crate::InspectorElementId>,
6678 cx: &mut App,
6679 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
6680 ) -> R {
6681 if let Some(inspector_id) = _inspector_id
6682 && let Some(inspector) = &self.inspector
6683 {
6684 let inspector = inspector.clone();
6685 let active_element_id = inspector.read(cx).active_element_id();
6686 if Some(inspector_id) == active_element_id {
6687 return inspector.update(cx, |inspector, _cx| {
6688 inspector.with_active_element_state(self, f)
6689 });
6690 }
6691 }
6692 f(&mut None, self)
6693 }
6694
6695 #[cfg(any(feature = "inspector", debug_assertions))]
6696 pub(crate) fn build_inspector_element_id(
6697 &mut self,
6698 path: crate::InspectorElementPath,
6699 ) -> crate::InspectorElementId {
6700 self.invalidator.debug_assert_paint_or_prepaint();
6701 let path = Rc::new(path);
6702 let next_instance_id = self
6703 .next_frame
6704 .next_inspector_instance_ids
6705 .entry(path.clone())
6706 .or_insert(0);
6707 let instance_id = *next_instance_id;
6708 *next_instance_id += 1;
6709 crate::InspectorElementId { path, instance_id }
6710 }
6711
6712 #[cfg(any(feature = "inspector", debug_assertions))]
6713 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
6714 if let Some(inspector) = self.inspector.take() {
6715 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
6716 inspector_element.prepaint_as_root(
6717 point(self.viewport_size.width - inspector_width, px(0.0)),
6718 size(inspector_width, self.viewport_size.height).into(),
6719 self,
6720 cx,
6721 );
6722 self.inspector = Some(inspector);
6723 Some(inspector_element)
6724 } else {
6725 None
6726 }
6727 }
6728
6729 #[cfg(any(feature = "inspector", debug_assertions))]
6730 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
6731 if let Some(mut inspector_element) = inspector_element {
6732 inspector_element.paint(self, cx);
6733 };
6734 }
6735
6736 #[cfg(any(feature = "inspector", debug_assertions))]
6739 pub fn insert_inspector_hitbox(
6740 &mut self,
6741 hitbox_id: HitboxId,
6742 inspector_id: Option<&crate::InspectorElementId>,
6743 cx: &App,
6744 ) {
6745 self.invalidator.debug_assert_paint_or_prepaint();
6746 if !self.is_inspector_picking(cx) {
6747 return;
6748 }
6749 if let Some(inspector_id) = inspector_id {
6750 self.next_frame
6751 .inspector_hitboxes
6752 .insert(hitbox_id, inspector_id.clone());
6753 }
6754 }
6755
6756 #[cfg(any(feature = "inspector", debug_assertions))]
6757 fn paint_inspector_hitbox(&mut self, cx: &App) {
6758 if let Some(inspector) = self.inspector.as_ref() {
6759 let inspector = inspector.read(cx);
6760 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
6761 && let Some(hitbox) = self
6762 .next_frame
6763 .hitboxes
6764 .iter()
6765 .find(|hitbox| hitbox.id == hitbox_id)
6766 {
6767 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
6768 }
6769 }
6770 }
6771
6772 #[cfg(any(feature = "inspector", debug_assertions))]
6773 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6774 let Some(inspector) = self.inspector.clone() else {
6775 return;
6776 };
6777 if event.downcast_ref::<MouseMoveEvent>().is_some() {
6778 inspector.update(cx, |inspector, _cx| {
6779 if let Some((_, inspector_id)) =
6780 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6781 {
6782 inspector.hover(inspector_id, self);
6783 }
6784 });
6785 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
6786 inspector.update(cx, |inspector, _cx| {
6787 if let Some((_, inspector_id)) =
6788 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6789 {
6790 inspector.select(inspector_id, self);
6791 }
6792 });
6793 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
6794 const SCROLL_LINES: f32 = 3.0;
6796 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
6797 let delta_y = event
6798 .delta
6799 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
6800 .y;
6801 if let Some(inspector) = self.inspector.clone() {
6802 inspector.update(cx, |inspector, _cx| {
6803 if let Some(depth) = inspector.pick_depth.as_mut() {
6804 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
6805 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
6806 if *depth < 0.0 {
6807 *depth = 0.0;
6808 } else if *depth > max_depth {
6809 *depth = max_depth;
6810 }
6811 if let Some((_, inspector_id)) =
6812 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6813 {
6814 inspector.set_active_element_id(inspector_id, self);
6815 }
6816 }
6817 });
6818 }
6819 }
6820 }
6821
6822 #[cfg(any(feature = "inspector", debug_assertions))]
6823 fn hovered_inspector_hitbox(
6824 &self,
6825 inspector: &Inspector,
6826 frame: &Frame,
6827 ) -> Option<(HitboxId, crate::InspectorElementId)> {
6828 if let Some(pick_depth) = inspector.pick_depth {
6829 let depth = (pick_depth as i64).try_into().unwrap_or(0);
6830 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
6831 let skip_count = (depth as usize).min(max_skipped);
6832 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
6833 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
6834 return Some((*hitbox_id, inspector_id.clone()));
6835 }
6836 }
6837 }
6838 None
6839 }
6840
6841 #[cfg(any(test, feature = "test-support"))]
6844 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
6845 self.modifiers = modifiers;
6846 }
6847
6848 #[cfg(any(test, feature = "test-support"))]
6852 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
6853 let event = PlatformInput::MouseMove(MouseMoveEvent {
6854 position,
6855 modifiers: self.modifiers,
6856 pressed_button: None,
6857 });
6858 let _ = self.dispatch_event(event, cx);
6859 }
6860}
6861
6862slotmap::new_key_type! {
6864 pub struct WindowId;
6866}
6867
6868impl WindowId {
6869 pub fn as_u64(&self) -> u64 {
6871 self.0.as_ffi()
6872 }
6873}
6874
6875impl From<u64> for WindowId {
6876 fn from(value: u64) -> Self {
6877 WindowId(slotmap::KeyData::from_ffi(value))
6878 }
6879}
6880
6881#[derive(Deref, DerefMut)]
6884pub struct WindowHandle<V> {
6885 #[deref]
6886 #[deref_mut]
6887 pub(crate) any_handle: AnyWindowHandle,
6888 state_type: PhantomData<fn(V) -> V>,
6889}
6890
6891impl<V> Debug for WindowHandle<V> {
6892 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6893 f.debug_struct("WindowHandle")
6894 .field("any_handle", &self.any_handle.id.as_u64())
6895 .finish()
6896 }
6897}
6898
6899impl<V: 'static + Render> WindowHandle<V> {
6900 pub fn new(id: WindowId) -> Self {
6903 WindowHandle {
6904 any_handle: AnyWindowHandle {
6905 id,
6906 state_type: TypeId::of::<V>(),
6907 root_entity_type_name: std::any::type_name::<V>(),
6908 },
6909 state_type: PhantomData,
6910 }
6911 }
6912
6913 #[cfg(any(test, feature = "test-support"))]
6917 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
6918 where
6919 C: AppContext,
6920 {
6921 cx.update_window(self.any_handle, |root_view, _, _| {
6922 root_view
6923 .downcast::<V>()
6924 .map_err(|_| anyhow!("the type of the window's root view has changed"))
6925 })?
6926 }
6927
6928 pub fn update<C, R>(
6932 &self,
6933 cx: &mut C,
6934 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
6935 ) -> Result<R>
6936 where
6937 C: AppContext,
6938 {
6939 cx.update_window(self.any_handle, |root_view, window, cx| {
6940 let view = root_view
6941 .downcast::<V>()
6942 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6943
6944 Ok(view.update(cx, |view, cx| update(view, window, cx)))
6945 })?
6946 }
6947
6948 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
6952 let x = cx
6953 .windows
6954 .get(self.id)
6955 .and_then(|window| {
6956 window
6957 .as_deref()
6958 .and_then(|window| window.root.clone())
6959 .map(|root_view| root_view.downcast::<V>())
6960 })
6961 .context("window not found")?
6962 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6963
6964 Ok(x.read(cx))
6965 }
6966
6967 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
6971 where
6972 C: AppContext,
6973 {
6974 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
6975 }
6976
6977 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
6981 where
6982 C: AppContext,
6983 {
6984 cx.read_window(self, |root_view, _cx| root_view)
6985 }
6986
6987 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
6992 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
6993 .ok()
6994 }
6995}
6996
6997impl<V> Copy for WindowHandle<V> {}
6998
6999impl<V> Clone for WindowHandle<V> {
7000 fn clone(&self) -> Self {
7001 *self
7002 }
7003}
7004
7005impl<V> PartialEq for WindowHandle<V> {
7006 fn eq(&self, other: &Self) -> bool {
7007 self.any_handle == other.any_handle
7008 }
7009}
7010
7011impl<V> Eq for WindowHandle<V> {}
7012
7013impl<V> Hash for WindowHandle<V> {
7014 fn hash<H: Hasher>(&self, state: &mut H) {
7015 self.any_handle.hash(state);
7016 }
7017}
7018
7019impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
7020 fn from(val: WindowHandle<V>) -> Self {
7021 val.any_handle
7022 }
7023}
7024
7025#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
7027pub struct AnyWindowHandle {
7028 pub(crate) id: WindowId,
7029 state_type: TypeId,
7030 root_entity_type_name: &'static str,
7031}
7032
7033impl AnyWindowHandle {
7034 pub fn window_id(&self) -> WindowId {
7036 self.id
7037 }
7038
7039 pub fn root_entity_type_name(&self) -> &'static str {
7041 self.root_entity_type_name
7042 }
7043
7044 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
7047 if TypeId::of::<T>() == self.state_type {
7048 Some(WindowHandle {
7049 any_handle: *self,
7050 state_type: PhantomData,
7051 })
7052 } else {
7053 None
7054 }
7055 }
7056
7057 pub fn update<C, R>(
7061 self,
7062 cx: &mut C,
7063 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
7064 ) -> Result<R>
7065 where
7066 C: AppContext,
7067 {
7068 cx.update_window(self, update)
7069 }
7070
7071 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
7075 where
7076 C: AppContext,
7077 T: 'static,
7078 {
7079 let view = self
7080 .downcast::<T>()
7081 .context("the type of the window's root view has changed")?;
7082
7083 cx.read_window(&view, read)
7084 }
7085}
7086
7087impl HasWindowHandle for Window {
7088 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
7089 self.platform_window.window_handle()
7090 }
7091}
7092
7093impl HasDisplayHandle for Window {
7094 fn display_handle(
7095 &self,
7096 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
7097 self.platform_window.display_handle()
7098 }
7099}
7100
7101#[derive(Clone, Debug, Eq, PartialEq, Hash)]
7106pub enum ElementId {
7107 View(EntityId),
7109 Integer(u64),
7111 Name(SharedString),
7113 Uuid(Uuid),
7115 FocusHandle(FocusId),
7117 NamedInteger(SharedString, u64),
7119 Path(Arc<std::path::Path>),
7121 CodeLocation(core::panic::Location<'static>),
7123 NamedChild(Arc<ElementId>, SharedString),
7125 OpaqueId([u8; 20]),
7127}
7128
7129impl ElementId {
7130 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
7132 Self::NamedInteger(name.into(), integer as u64)
7133 }
7134}
7135
7136impl Display for ElementId {
7137 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7138 match self {
7139 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
7140 ElementId::Integer(ix) => write!(f, "{}", ix)?,
7141 ElementId::Name(name) => write!(f, "{}", name)?,
7142 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
7143 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
7144 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
7145 ElementId::Path(path) => write!(f, "{}", path.display())?,
7146 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
7147 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
7148 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
7149 }
7150
7151 Ok(())
7152 }
7153}
7154
7155impl TryInto<SharedString> for ElementId {
7156 type Error = anyhow::Error;
7157
7158 fn try_into(self) -> anyhow::Result<SharedString> {
7159 if let ElementId::Name(name) = self {
7160 Ok(name)
7161 } else {
7162 anyhow::bail!("element id is not string")
7163 }
7164 }
7165}
7166
7167impl From<usize> for ElementId {
7168 fn from(id: usize) -> Self {
7169 ElementId::Integer(id as u64)
7170 }
7171}
7172
7173impl From<i32> for ElementId {
7174 fn from(id: i32) -> Self {
7175 Self::Integer(id as u64)
7176 }
7177}
7178
7179impl From<SharedString> for ElementId {
7180 fn from(name: SharedString) -> Self {
7181 ElementId::Name(name)
7182 }
7183}
7184
7185impl From<String> for ElementId {
7186 fn from(name: String) -> Self {
7187 ElementId::Name(name.into())
7188 }
7189}
7190
7191impl From<Arc<str>> for ElementId {
7192 fn from(name: Arc<str>) -> Self {
7193 ElementId::Name(name.into())
7194 }
7195}
7196
7197impl From<Arc<std::path::Path>> for ElementId {
7198 fn from(path: Arc<std::path::Path>) -> Self {
7199 ElementId::Path(path)
7200 }
7201}
7202
7203impl From<&'static str> for ElementId {
7204 fn from(name: &'static str) -> Self {
7205 ElementId::Name(SharedString::new_static(name))
7206 }
7207}
7208
7209impl<'a> From<&'a FocusHandle> for ElementId {
7210 fn from(handle: &'a FocusHandle) -> Self {
7211 ElementId::FocusHandle(handle.id)
7212 }
7213}
7214
7215impl From<(&'static str, EntityId)> for ElementId {
7216 fn from((name, id): (&'static str, EntityId)) -> Self {
7217 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
7218 }
7219}
7220
7221impl From<(&'static str, usize)> for ElementId {
7222 fn from((name, id): (&'static str, usize)) -> Self {
7223 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
7224 }
7225}
7226
7227impl From<(SharedString, usize)> for ElementId {
7228 fn from((name, id): (SharedString, usize)) -> Self {
7229 ElementId::NamedInteger(name, id as u64)
7230 }
7231}
7232
7233impl From<(&'static str, u64)> for ElementId {
7234 fn from((name, id): (&'static str, u64)) -> Self {
7235 ElementId::NamedInteger(SharedString::new_static(name), id)
7236 }
7237}
7238
7239impl From<Uuid> for ElementId {
7240 fn from(value: Uuid) -> Self {
7241 Self::Uuid(value)
7242 }
7243}
7244
7245impl From<(&'static str, u32)> for ElementId {
7246 fn from((name, id): (&'static str, u32)) -> Self {
7247 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
7248 }
7249}
7250
7251impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
7252 fn from((id, name): (ElementId, T)) -> Self {
7253 ElementId::NamedChild(Arc::new(id), name.into())
7254 }
7255}
7256
7257impl From<&'static core::panic::Location<'static>> for ElementId {
7258 fn from(location: &'static core::panic::Location<'static>) -> Self {
7259 ElementId::CodeLocation(*location)
7260 }
7261}
7262
7263impl From<[u8; 20]> for ElementId {
7264 fn from(opaque_id: [u8; 20]) -> Self {
7265 ElementId::OpaqueId(opaque_id)
7266 }
7267}
7268
7269#[derive(Clone)]
7272pub struct PaintQuad {
7273 pub bounds: Bounds<Pixels>,
7275 pub corner_radii: Corners<Pixels>,
7277 pub background: Background,
7279 pub border_widths: Edges<Pixels>,
7281 pub border_color: Hsla,
7283 pub border_style: BorderStyle,
7285}
7286
7287impl PaintQuad {
7288 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
7290 PaintQuad {
7291 corner_radii: corner_radii.into(),
7292 ..self
7293 }
7294 }
7295
7296 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
7298 PaintQuad {
7299 border_widths: border_widths.into(),
7300 ..self
7301 }
7302 }
7303
7304 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
7306 PaintQuad {
7307 border_color: border_color.into(),
7308 ..self
7309 }
7310 }
7311
7312 pub fn background(self, background: impl Into<Background>) -> Self {
7314 PaintQuad {
7315 background: background.into(),
7316 ..self
7317 }
7318 }
7319}
7320
7321pub fn quad(
7323 bounds: Bounds<Pixels>,
7324 corner_radii: impl Into<Corners<Pixels>>,
7325 background: impl Into<Background>,
7326 border_widths: impl Into<Edges<Pixels>>,
7327 border_color: impl Into<Hsla>,
7328 border_style: BorderStyle,
7329) -> PaintQuad {
7330 PaintQuad {
7331 bounds,
7332 corner_radii: corner_radii.into(),
7333 background: background.into(),
7334 border_widths: border_widths.into(),
7335 border_color: border_color.into(),
7336 border_style,
7337 }
7338}
7339
7340pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
7342 PaintQuad {
7343 bounds: bounds.into(),
7344 corner_radii: (0.).into(),
7345 background: background.into(),
7346 border_widths: (0.).into(),
7347 border_color: transparent_black(),
7348 border_style: BorderStyle::default(),
7349 }
7350}
7351
7352pub fn outline(
7354 bounds: impl Into<Bounds<Pixels>>,
7355 border_color: impl Into<Hsla>,
7356 border_style: BorderStyle,
7357) -> PaintQuad {
7358 PaintQuad {
7359 bounds: bounds.into(),
7360 corner_radii: (0.).into(),
7361 background: transparent_black().into(),
7362 border_widths: (1.).into(),
7363 border_color: border_color.into(),
7364 border_style,
7365 }
7366}
7367
7368#[cfg(test)]
7369mod tests {
7370 use std::{
7371 cell::{Cell, RefCell},
7372 path::PathBuf,
7373 rc::Rc,
7374 time::Duration,
7375 };
7376
7377 use crate::{
7378 AnyWindowHandle, AppContext as _, Bounds, Context, DispatchPhase, DragMoveEvent, Empty,
7379 ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle,
7380 InputEvent as _, InteractiveElement as _, IntoElement, LongPressEvent, MouseButton,
7381 MouseDownEvent, MouseMoveEvent, ParentElement, Pixels, Point, Render, RequestFrameOptions,
7382 StatefulInteractiveElement as _, Styled, TestAppContext, TouchDragEvent, TouchEvent,
7383 TouchId, TouchPhase, Window, WindowAppearance, WindowOptions, canvas, div, point, px, size,
7384 };
7385
7386 struct EmptyView;
7387
7388 impl Render for EmptyView {
7389 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7390 div()
7391 }
7392 }
7393
7394 struct OpensWindowOnPaint {
7395 opened: Rc<Cell<bool>>,
7396 }
7397
7398 impl Render for OpensWindowOnPaint {
7399 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7400 let opened = self.opened.clone();
7401 div()
7402 .size_full()
7403 .child(canvas(
7404 |_, _, _| {},
7405 move |_, _, _window, cx| {
7406 if !opened.replace(true) {
7407 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
7408 .unwrap();
7409 }
7410 },
7411 ))
7412 .child(div().child("after"))
7416 }
7417 }
7418
7419 #[test]
7425 fn test_window_opened_during_draw_defers_arena_clear() {
7426 let mut cx = TestAppContext::single();
7427
7428 let opened = Rc::new(Cell::new(false));
7429 let window = cx.add_window({
7431 let opened = opened.clone();
7432 move |_, _| OpensWindowOnPaint { opened }
7433 });
7434
7435 assert!(opened.get());
7436 assert_eq!(cx.windows().len(), 2);
7437
7438 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
7441 .unwrap();
7442 }
7443
7444 #[gpui::test]
7449 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
7450 let window = cx.add_window(|_, _| EmptyView);
7451 let test_window = cx.test_window(window.into());
7452
7453 assert!(
7457 test_window.frame_wake_count() >= 1,
7458 "opening a window must wake the frame source for the initial frame"
7459 );
7460
7461 test_window.simulate_frame_request(RequestFrameOptions::default());
7463
7464 let baseline = test_window.frame_wake_count();
7467 test_window.simulate_frame_request(RequestFrameOptions::default());
7468 window.update(cx, |_, _, _| {}).unwrap();
7469 assert_eq!(
7470 test_window.frame_wake_count(),
7471 baseline,
7472 "clean frames and non-notifying updates must not wake the frame source"
7473 );
7474
7475 window.update(cx, |_, _, cx| cx.notify()).unwrap();
7477 assert!(
7478 test_window.frame_wake_count() > baseline,
7479 "notifying a view in an idle window must wake the frame source"
7480 );
7481
7482 test_window.simulate_frame_request(RequestFrameOptions::default());
7484 let baseline = test_window.frame_wake_count();
7485 test_window.simulate_frame_request(RequestFrameOptions::default());
7486 assert_eq!(
7487 test_window.frame_wake_count(),
7488 baseline,
7489 "serving demand must return the window to idle"
7490 );
7491
7492 window
7494 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
7495 .unwrap();
7496 assert!(
7497 test_window.frame_wake_count() > baseline,
7498 "scheduling a next-frame callback in an idle window must wake the frame source"
7499 );
7500 }
7501
7502 #[gpui::test]
7507 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
7508 let window = cx.add_window(|_, _| EmptyView);
7509 let test_window = cx.test_window(window.into());
7510 test_window.simulate_frame_request(RequestFrameOptions::default());
7513
7514 let callback_ran = Rc::new(Cell::new(false));
7515 window
7516 .update(cx, {
7517 let callback_ran = callback_ran.clone();
7518 move |_, window, _| {
7519 window.on_next_frame(move |_, _| callback_ran.set(true));
7520 }
7521 })
7522 .unwrap();
7523
7524 let baseline = test_window.frame_wake_count();
7525 test_window.simulate_frame_request(RequestFrameOptions::default());
7526 assert!(
7533 test_window.frame_wake_count() > baseline || callback_ran.get(),
7534 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
7535 );
7536 }
7537
7538 #[gpui::test]
7539 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
7540 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
7541
7542 let window = cx.add_window(|_, _| EmptyView);
7543 window
7544 .update(cx, |_, window, _| {
7545 assert!(matches!(
7546 window.window_handle(),
7547 Err(HandleError::NotSupported)
7548 ));
7549 assert!(matches!(
7550 window.display_handle(),
7551 Err(HandleError::NotSupported)
7552 ));
7553 })
7554 .unwrap();
7555 }
7556
7557 #[gpui::test]
7558 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
7559 let window = cx.add_window(|_, _| EmptyView);
7560 let observed_appearance = Rc::new(Cell::new(None));
7561 let _subscription = window
7562 .update(cx, {
7563 let observed_appearance = observed_appearance.clone();
7564 move |_, window, _| {
7565 window.observe_window_appearance(move |window, _| {
7566 observed_appearance.set(Some(window.appearance()));
7567 })
7568 }
7569 })
7570 .unwrap();
7571 let test_window = cx.test_window(window.into());
7572
7573 cx.update(|_| {
7574 test_window.simulate_appearance_change(WindowAppearance::Dark);
7575 assert_eq!(observed_appearance.get(), None);
7576 });
7577 cx.run_until_parked();
7578
7579 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
7580 }
7581
7582 #[gpui::test]
7583 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
7584 let window = cx.add_window(|_, _| Empty);
7585 let test_window = cx.test_window(window.into());
7586
7587 assert!(test_window.simulate_scheduled_frame());
7588 assert!(test_window.simulate_scheduled_frame());
7589 assert!(!test_window.frame_scheduled());
7590
7591 cx.update_window(window.into(), |_, window, _| {
7592 window.active.set(true);
7593 window.on_next_frame(|_, _| {});
7594 })
7595 .unwrap();
7596 assert!(
7597 test_window.frame_scheduled(),
7598 "queuing work on a parked window must wake the render loop"
7599 );
7600
7601 assert!(test_window.simulate_scheduled_frame());
7602 assert!(
7603 test_window.frame_scheduled(),
7604 "presenting the frame must await one compositor callback"
7605 );
7606 assert!(test_window.simulate_scheduled_frame());
7607 assert!(!test_window.frame_scheduled());
7608 }
7609
7610 #[gpui::test]
7611 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
7612 let window = cx.add_window(|_, _| Empty);
7613 let test_window = cx.test_window(window.into());
7614
7615 assert!(test_window.simulate_scheduled_frame());
7616 assert!(test_window.simulate_scheduled_frame());
7617 assert!(!test_window.frame_scheduled());
7618
7619 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
7620 .unwrap();
7621
7622 assert!(
7623 test_window.frame_scheduled(),
7624 "a rendered scene awaiting presentation must wake the render loop"
7625 );
7626 }
7627
7628 #[gpui::test]
7629 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
7630 let window = cx.add_window(|_, _| Empty);
7631 let test_window = cx.test_window(window.into());
7632
7633 let callback_ran = Rc::new(Cell::new(false));
7634 cx.update_window(window.into(), |_, window, _| {
7635 window.active.set(true);
7638 let callback_ran = callback_ran.clone();
7639 window.on_next_frame(move |window, _| {
7640 window.on_next_frame(move |_, _| callback_ran.set(true));
7641 });
7642 })
7643 .unwrap();
7644
7645 assert!(test_window.simulate_scheduled_frame());
7646 assert!(!callback_ran.get());
7647 assert!(
7648 test_window.frame_scheduled(),
7649 "a callback queued mid-frame must schedule a follow-up before the loop parks"
7650 );
7651
7652 assert!(test_window.simulate_scheduled_frame());
7653 assert!(callback_ran.get());
7654 }
7655
7656 struct RootView {
7657 explicit_size: bool,
7658 child_bounds: Rc<Cell<Bounds<Pixels>>>,
7659 }
7660
7661 impl Render for RootView {
7662 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7663 let child_bounds = self.child_bounds.clone();
7664 let root = div().flex().flex_col().child(
7665 canvas(
7666 move |bounds, _, _| child_bounds.set(bounds),
7667 |_, _, _, _| {},
7668 )
7669 .size_full(),
7670 );
7671 if self.explicit_size {
7672 root.w(px(300.)).h(px(200.))
7673 } else {
7674 root
7675 }
7676 }
7677 }
7678
7679 #[test]
7680 fn auto_sized_window_root_fills_the_window() {
7681 let mut cx = TestAppContext::single();
7682 let child_bounds = Rc::new(Cell::new(Bounds::default()));
7683 let window = cx.add_window({
7684 let child_bounds = child_bounds.clone();
7685 move |_, _| RootView {
7686 explicit_size: false,
7687 child_bounds,
7688 }
7689 });
7690
7691 let viewport_size = cx
7692 .update_window(window.into(), |_, window, cx| {
7693 window.draw(cx).clear(cx);
7694 window.viewport_size()
7695 })
7696 .unwrap();
7697
7698 assert_eq!(child_bounds.get().size, viewport_size);
7699 }
7700
7701 #[test]
7702 fn explicitly_sized_window_root_keeps_its_size() {
7703 let mut cx = TestAppContext::single();
7704 let child_bounds = Rc::new(Cell::new(Bounds::default()));
7705 let window = cx.add_window({
7706 let child_bounds = child_bounds.clone();
7707 move |_, _| RootView {
7708 explicit_size: true,
7709 child_bounds,
7710 }
7711 });
7712
7713 cx.update_window(window.into(), |_, window, cx| {
7714 window.draw(cx).clear(cx);
7715 })
7716 .unwrap();
7717
7718 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
7719 }
7720
7721 struct FileDragView {
7722 path: PathBuf,
7723 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7724 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7725 }
7726
7727 impl Render for FileDragView {
7728 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7729 div()
7730 .id("file-drag")
7731 .size_full()
7732 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
7733 .external_drag_payload(|path: &PathBuf, _, _| {
7734 Some(ExternalDragPayload::Files(FileDragPaths::new([(
7735 path.clone(),
7736 true,
7737 )])))
7738 })
7739 .on_drag_move({
7740 let observed_drag_moves = self.observed_drag_moves.clone();
7741 move |event: &DragMoveEvent<PathBuf>, _, _| {
7742 observed_drag_moves.borrow_mut().push(event.event.position);
7743 }
7744 })
7745 .on_drop({
7746 let observed_drops = self.observed_drops.clone();
7747 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
7748 })
7749 }
7750 }
7751
7752 #[gpui::test]
7753 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
7754 struct Drag {
7755 window: AnyWindowHandle,
7756 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7757 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7758 }
7759
7760 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
7761 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
7762 let observed_drops = Rc::new(RefCell::new(Vec::new()));
7763 let window: AnyWindowHandle = cx
7764 .add_window({
7765 let observed_drag_moves = observed_drag_moves.clone();
7766 let observed_drops = observed_drops.clone();
7767 move |_, _| FileDragView {
7768 path,
7769 observed_drag_moves,
7770 observed_drops,
7771 }
7772 })
7773 .into();
7774 cx.test_window(window)
7775 .set_start_external_drag_result(platform_result);
7776
7777 let update_result = cx.update_window(window, |_, window, cx| {
7778 window.draw(cx).clear(cx);
7779 window.dispatch_event(
7780 MouseDownEvent {
7781 position: point(px(10.), px(10.)),
7782 button: MouseButton::Left,
7783 modifiers: Default::default(),
7784 click_count: 1,
7785 first_mouse: false,
7786 }
7787 .to_platform_input(),
7788 cx,
7789 );
7790 window.dispatch_event(
7791 MouseMoveEvent {
7792 position: point(px(20.), px(20.)),
7793 pressed_button: Some(MouseButton::Left),
7794 modifiers: Default::default(),
7795 }
7796 .to_platform_input(),
7797 cx,
7798 );
7799 assert!(cx.active_drag.is_some());
7800 });
7801 assert!(
7802 update_result.is_ok(),
7803 "failed to start drag: {update_result:?}"
7804 );
7805
7806 assert!(cx.test_window(window).external_drag_files().is_empty());
7807 Drag {
7808 window,
7809 observed_drag_moves,
7810 observed_drops,
7811 }
7812 }
7813
7814 let successful_path = PathBuf::from("/tmp/successful-drag");
7815 let successful = start_drag(cx, successful_path.clone(), true);
7816 let outside_position = point(px(-1.), px(20.));
7817 let update_result = cx.update_window(successful.window, |_, window, cx| {
7818 window.dispatch_event(
7819 MouseMoveEvent {
7820 position: outside_position,
7821 pressed_button: Some(MouseButton::Left),
7822 modifiers: Default::default(),
7823 }
7824 .to_platform_input(),
7825 cx,
7826 );
7827 assert!(cx.active_drag.is_none());
7828 });
7829 assert!(
7830 update_result.is_ok(),
7831 "failed to promote drag: {update_result:?}"
7832 );
7833 assert_eq!(
7834 cx.test_window(successful.window).external_drag_files(),
7835 [(successful_path.clone(), true)]
7836 );
7837 assert_eq!(
7840 successful.observed_drag_moves.borrow().last(),
7841 Some(&outside_position)
7842 );
7843
7844 let destination: AnyWindowHandle = cx.add_window(|_, _| EmptyView).into();
7845 let reentry_position = point(px(30.), px(30.));
7846 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
7847 let update_result = cx.update_window(destination, |_, window, cx| {
7848 window.dispatch_event(
7849 FileDropEvent::Entered {
7850 position: reentry_position,
7851 paths: external_paths(),
7852 }
7853 .to_platform_input(),
7854 cx,
7855 );
7856 assert!(
7857 cx.active_drag
7858 .as_ref()
7859 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7860 );
7861 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7862 assert!(cx.active_drag.is_none());
7863 });
7864 assert!(
7865 update_result.is_ok(),
7866 "failed to handle drag in destination window: {update_result:?}"
7867 );
7868
7869 let update_result = cx.update_window(successful.window, |_, window, cx| {
7870 window.dispatch_event(
7871 FileDropEvent::Entered {
7872 position: reentry_position,
7873 paths: external_paths(),
7874 }
7875 .to_platform_input(),
7876 cx,
7877 );
7878 assert!(
7879 cx.active_drag
7880 .as_ref()
7881 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7882 );
7883 assert_eq!(
7884 successful.observed_drag_moves.borrow().last(),
7885 Some(&reentry_position)
7886 );
7887
7888 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7889 assert!(cx.active_drag.is_none());
7890
7891 window.dispatch_event(
7892 FileDropEvent::Entered {
7893 position: reentry_position,
7894 paths: external_paths(),
7895 }
7896 .to_platform_input(),
7897 cx,
7898 );
7899 assert!(
7900 cx.active_drag
7901 .as_ref()
7902 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7903 );
7904
7905 window.dispatch_event(
7906 FileDropEvent::Submit {
7907 position: reentry_position,
7908 }
7909 .to_platform_input(),
7910 cx,
7911 );
7912 assert_eq!(
7913 successful.observed_drops.borrow().as_slice(),
7914 std::slice::from_ref(&successful_path)
7915 );
7916 assert!(cx.active_drag.is_none());
7917
7918 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7919 assert!(cx.active_drag.is_none());
7920 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
7921 assert!(cx.active_drag.is_none());
7922
7923 window.dispatch_event(
7924 FileDropEvent::Entered {
7925 position: reentry_position,
7926 paths: external_paths(),
7927 }
7928 .to_platform_input(),
7929 cx,
7930 );
7931 assert!(
7932 cx.active_drag
7933 .as_ref()
7934 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7935 );
7936 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7937 });
7938 assert!(
7939 update_result.is_ok(),
7940 "failed to restore drag in source window: {update_result:?}"
7941 );
7942
7943 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
7944 let cancelled = start_drag(cx, cancelled_path.clone(), true);
7945 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
7946 window.dispatch_event(
7947 MouseMoveEvent {
7948 position: outside_position,
7949 pressed_button: Some(MouseButton::Left),
7950 modifiers: Default::default(),
7951 }
7952 .to_platform_input(),
7953 cx,
7954 );
7955 assert!(cx.active_drag.is_none());
7956
7957 window.dispatch_event(
7958 FileDropEvent::Entered {
7959 position: reentry_position,
7960 paths: ExternalPaths([cancelled_path].into_iter().collect()),
7961 }
7962 .to_platform_input(),
7963 cx,
7964 );
7965 assert!(
7966 cx.active_drag
7967 .as_ref()
7968 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7969 );
7970 assert!(cx.stop_active_drag(window));
7971 assert!(cx.active_drag.is_none());
7972 });
7973 assert!(
7974 update_result.is_ok(),
7975 "failed to cancel restored drag: {update_result:?}"
7976 );
7977 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
7978
7979 let removed_path = PathBuf::from("/tmp/removed-window-drag");
7980 let removed = start_drag(cx, removed_path, true);
7981 let removed_window_id = removed.window.window_id();
7982 let update_result = cx.update_window(removed.window, |_, window, cx| {
7983 window.dispatch_event(
7984 MouseMoveEvent {
7985 position: outside_position,
7986 pressed_button: Some(MouseButton::Left),
7987 modifiers: Default::default(),
7988 }
7989 .to_platform_input(),
7990 cx,
7991 );
7992 assert!(cx.active_drag.is_none());
7993 window.remove_window();
7994 });
7995 assert!(
7996 update_result.is_ok(),
7997 "failed to remove drag source window: {update_result:?}"
7998 );
7999 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
8000
8001 let failed_path = PathBuf::from("/tmp/failed-drag");
8002 let failed = start_drag(cx, failed_path.clone(), false);
8003 let update_result = cx.update_window(failed.window, |_, window, cx| {
8004 for x_position in [-1., -2.] {
8005 window.dispatch_event(
8006 MouseMoveEvent {
8007 position: point(px(x_position), px(20.)),
8008 pressed_button: Some(MouseButton::Left),
8009 modifiers: Default::default(),
8010 }
8011 .to_platform_input(),
8012 cx,
8013 );
8014 }
8015 assert!(cx.active_drag.is_some());
8016 });
8017 assert!(
8018 update_result.is_ok(),
8019 "failed to retain drag after platform failure: {update_result:?}"
8020 );
8021 assert_eq!(
8022 cx.test_window(failed.window).external_drag_files(),
8023 [(failed_path, true)]
8024 );
8025 }
8026
8027 struct FocusForwarder {
8028 a: FocusHandle,
8029 b: FocusHandle,
8030 }
8031
8032 impl Render for FocusForwarder {
8033 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
8034 div()
8035 .size_full()
8036 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
8037 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
8038 }
8039 }
8040
8041 #[gpui::test]
8045 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
8046 let b_focus_count = Rc::new(Cell::new(0));
8047 let window = cx.add_window({
8048 let b_focus_count = b_focus_count.clone();
8049 move |window, cx| {
8050 let a = cx.focus_handle();
8051 let b = cx.focus_handle();
8052 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
8053 let b = this.b.clone();
8054 window.focus(&b, cx);
8055 })
8056 .detach();
8057 cx.on_focus(&b, window, move |_, _, _| {
8058 b_focus_count.set(b_focus_count.get() + 1);
8059 })
8060 .detach();
8061 FocusForwarder { a, b }
8062 }
8063 });
8064
8065 window
8066 .update(cx, |_, window, _| window.activate_window())
8067 .unwrap();
8068 cx.executor().run_until_parked();
8069
8070 window
8071 .update(cx, |this, window, cx| {
8072 let a = this.a.clone();
8073 window.focus(&a, cx);
8074 })
8075 .unwrap();
8076 cx.executor().run_until_parked();
8077
8078 window
8079 .update(cx, |this, window, _| {
8080 assert!(this.b.is_focused(window));
8081 })
8082 .unwrap();
8083 assert_eq!(b_focus_count.get(), 1);
8084 }
8085
8086 #[gpui::test]
8087 fn claimed_touch_drag_receives_movement_and_release(cx: &mut TestAppContext) {
8088 let events = Rc::new(RefCell::new(Vec::new()));
8089 let window = cx.add_window({
8090 let events = events.clone();
8091 move |_, _| TouchDragListener { events }
8092 });
8093 let touch = TouchId(1);
8094
8095 dispatch_touch(window, cx, touch, TouchPhase::Started, 10.);
8096 dispatch_touch(window, cx, touch, TouchPhase::Moved, 30.);
8097 dispatch_touch(window, cx, touch, TouchPhase::Ended, 40.);
8098
8099 assert_eq!(
8100 events.borrow().as_slice(),
8101 [
8102 (TouchPhase::Started, px(10.)),
8103 (TouchPhase::Moved, px(30.)),
8104 (TouchPhase::Ended, px(40.)),
8105 ]
8106 );
8107 }
8108
8109 struct TouchDragListener {
8110 events: Rc<RefCell<Vec<(TouchPhase, Pixels)>>>,
8111 }
8112
8113 impl Render for TouchDragListener {
8114 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
8115 let events = self.events.clone();
8116 canvas(
8117 |_, _, _| {},
8118 move |_, _, window, _| {
8119 window.on_mouse_event(move |event: &TouchDragEvent, phase, window, _cx| {
8120 if phase != DispatchPhase::Bubble {
8121 return;
8122 }
8123 events.borrow_mut().push((event.phase, event.position.x));
8124 if event.phase == TouchPhase::Started {
8125 window.prevent_default();
8126 }
8127 });
8128 },
8129 )
8130 }
8131 }
8132
8133 #[gpui::test]
8134 fn long_press_is_claimed_only_when_started_prevents_default(cx: &mut TestAppContext) {
8135 for response in [
8136 LongPressResponse::PreventDefault,
8137 LongPressResponse::StopPropagation,
8138 LongPressResponse::None,
8139 ] {
8140 let phases = Rc::new(RefCell::new(Vec::new()));
8141 let window = cx.add_window({
8142 let phases = phases.clone();
8143 move |_, _| LongPressListener { phases, response }
8144 });
8145 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
8146 cx.executor().advance_clock(Duration::from_millis(501));
8147 cx.executor().run_until_parked();
8148 window
8149 .update(cx, |_, window, _| {
8150 assert_eq!(
8151 window.long_press_capture.is_some(),
8152 response == LongPressResponse::PreventDefault
8153 );
8154 })
8155 .unwrap();
8156 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
8157 dispatch_touch(window, cx, TouchId(1), TouchPhase::Ended, 2.);
8158 window
8159 .update(cx, |_, window, _| {
8160 assert!(window.long_press_capture.is_none());
8161 })
8162 .unwrap();
8163
8164 let phases = phases.borrow();
8165 if response == LongPressResponse::PreventDefault {
8166 assert_eq!(
8167 phases.as_slice(),
8168 [TouchPhase::Started, TouchPhase::Moved, TouchPhase::Ended]
8169 );
8170 } else {
8171 assert_eq!(phases.as_slice(), [TouchPhase::Started]);
8172 }
8173 }
8174 }
8175
8176 #[gpui::test]
8177 fn stale_default_prevention_does_not_claim_long_press(cx: &mut TestAppContext) {
8178 let phases = Rc::new(RefCell::new(Vec::new()));
8179 let window = cx.add_window({
8180 let phases = phases.clone();
8181 move |_, _| LongPressListener {
8182 phases,
8183 response: LongPressResponse::None,
8184 }
8185 });
8186 window
8187 .update(cx, |_, window, _| {
8188 window.prevent_default();
8189 })
8190 .unwrap();
8191
8192 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
8193 cx.executor().advance_clock(Duration::from_millis(501));
8194 cx.executor().run_until_parked();
8195 dispatch_touch(window, cx, TouchId(1), TouchPhase::Moved, 2.);
8196
8197 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
8198 }
8199
8200 #[gpui::test]
8201 fn resolved_touch_cancels_scheduled_long_press(cx: &mut TestAppContext) {
8202 for (phase, position) in [
8203 (TouchPhase::Ended, 0.),
8204 (TouchPhase::Cancelled, 0.),
8205 (TouchPhase::Moved, 20.),
8206 ] {
8207 let phases = Rc::new(RefCell::new(Vec::new()));
8208 let window = cx.add_window({
8209 let phases = phases.clone();
8210 move |_, _| LongPressListener {
8211 phases,
8212 response: LongPressResponse::PreventDefault,
8213 }
8214 });
8215 dispatch_touch(window, cx, TouchId(1), TouchPhase::Started, 0.);
8216 dispatch_touch(window, cx, TouchId(1), phase, position);
8217 cx.executor().advance_clock(Duration::from_millis(501));
8218 cx.executor().run_until_parked();
8219
8220 assert!(phases.borrow().is_empty(), "{phase:?} allowed long press");
8221 }
8222 }
8223
8224 #[gpui::test]
8225 fn stale_long_press_timer_cannot_affect_replacement_touch(cx: &mut TestAppContext) {
8226 let phases = Rc::new(RefCell::new(Vec::new()));
8227 let window = cx.add_window({
8228 let phases = phases.clone();
8229 move |_, _| LongPressListener {
8230 phases,
8231 response: LongPressResponse::PreventDefault,
8232 }
8233 });
8234 let first_touch = TouchId(1);
8235 dispatch_touch(window, cx, first_touch, TouchPhase::Started, 0.);
8236 cx.executor().advance_clock(Duration::from_millis(250));
8237 dispatch_touch(window, cx, first_touch, TouchPhase::Cancelled, 0.);
8238 dispatch_touch(window, cx, TouchId(2), TouchPhase::Started, 10.);
8239
8240 cx.executor().advance_clock(Duration::from_millis(251));
8241 cx.executor().run_until_parked();
8242 assert!(phases.borrow().is_empty());
8243
8244 cx.executor().advance_clock(Duration::from_millis(250));
8245 cx.executor().run_until_parked();
8246 assert_eq!(phases.borrow().as_slice(), [TouchPhase::Started]);
8247 }
8248
8249 #[derive(Clone, Copy, PartialEq)]
8250 enum LongPressResponse {
8251 PreventDefault,
8252 StopPropagation,
8253 None,
8254 }
8255
8256 struct LongPressListener {
8257 phases: Rc<RefCell<Vec<TouchPhase>>>,
8258 response: LongPressResponse,
8259 }
8260
8261 impl Render for LongPressListener {
8262 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
8263 let entity = cx.entity();
8264 let phases = self.phases.clone();
8265 let response = self.response;
8266 canvas(
8267 |_, _, _| {},
8268 move |_, _, window, _| {
8269 window.on_mouse_event(move |event: &LongPressEvent, phase, window, cx| {
8270 if phase != DispatchPhase::Bubble {
8271 return;
8272 }
8273 phases.borrow_mut().push(event.phase);
8274 match response {
8275 LongPressResponse::PreventDefault => {
8276 window.capture_long_press(&entity);
8277 window.prevent_default();
8278 }
8279 LongPressResponse::StopPropagation => cx.stop_propagation(),
8280 LongPressResponse::None => {}
8281 }
8282 });
8283 },
8284 )
8285 }
8286 }
8287
8288 fn dispatch_touch<T: 'static>(
8289 window: crate::WindowHandle<T>,
8290 cx: &mut TestAppContext,
8291 id: TouchId,
8292 phase: TouchPhase,
8293 x: f32,
8294 ) {
8295 window
8296 .update(cx, |_, window, cx| {
8297 window.dispatch_event(
8298 TouchEvent {
8299 id,
8300 phase,
8301 position: point(px(x), px(0.)),
8302 predicted_position: None,
8303 force: None,
8304 }
8305 .to_platform_input(),
8306 cx,
8307 );
8308 })
8309 .unwrap();
8310 }
8311}