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, BackdropBlur, Background, BorderStyle, Bounds,
10 BoxShadow, 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 TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState, TransformationMatrix,
23 Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance, WindowBounds,
24 WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem, point,
25 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, Copy, Debug, PartialEq)]
827pub struct EdgeFade {
828 pub bounds: Bounds<Pixels>,
830 pub band: Pixels,
832 pub top: bool,
834 pub bottom: bool,
836 pub left: bool,
838 pub right: bool,
840}
841
842#[derive(Clone, Debug, Deref)]
845pub struct Hitbox {
846 pub id: HitboxId,
848 #[deref]
850 pub bounds: Bounds<Pixels>,
851 pub content_mask: ContentMask<Pixels>,
853 pub behavior: HitboxBehavior,
855}
856
857impl Hitbox {
858 pub fn is_hovered(&self, window: &Window) -> bool {
875 self.id.is_hovered(window)
876 }
877
878 pub fn should_handle_scroll(&self, window: &Window) -> bool {
885 self.id.should_handle_scroll(window)
886 }
887}
888
889#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
891pub enum HitboxBehavior {
892 #[default]
894 Normal,
895
896 BlockMouse,
918
919 BlockMouseExceptScroll,
946}
947
948#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
950pub struct TooltipId(usize);
951
952impl TooltipId {
953 pub fn is_hovered(&self, window: &Window) -> bool {
955 window
956 .tooltip_bounds
957 .as_ref()
958 .is_some_and(|tooltip_bounds| {
959 tooltip_bounds.id == *self
960 && tooltip_bounds.bounds.contains(&window.mouse_position())
961 })
962 }
963}
964
965pub(crate) struct TooltipBounds {
966 id: TooltipId,
967 bounds: Bounds<Pixels>,
968}
969
970#[derive(Clone)]
971pub(crate) struct TooltipRequest {
972 id: TooltipId,
973 tooltip: AnyTooltip,
974}
975
976pub(crate) struct DeferredDraw {
977 current_view: EntityId,
978 priority: usize,
979 parent_node: DispatchNodeId,
980 element_id_stack: SmallVec<[ElementId; 32]>,
981 text_style_stack: Vec<TextStyleRefinement>,
982 content_mask: Option<ContentMask<Pixels>>,
983 rem_size: Pixels,
984 element: Option<AnyElement>,
985 absolute_offset: Point<Pixels>,
986 prepaint_range: Range<PrepaintStateIndex>,
987 paint_range: Range<PaintIndex>,
988}
989
990pub(crate) struct Frame {
991 pub(crate) focus: Option<FocusId>,
992 pub(crate) window_active: bool,
993 pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
994 accessed_element_states: Vec<(GlobalElementId, TypeId)>,
995 pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
996 pub(crate) dispatch_tree: DispatchTree,
997 pub(crate) scene: Scene,
998 pub(crate) hitboxes: Vec<Hitbox>,
999 pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
1000 pub(crate) deferred_draws: Vec<DeferredDraw>,
1001 pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
1002 pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
1003 pub(crate) cursor_styles: Vec<CursorStyleRequest>,
1004 #[cfg(any(test, feature = "test-support"))]
1005 pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
1006 #[cfg(any(feature = "inspector", debug_assertions))]
1007 pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
1008 #[cfg(any(feature = "inspector", debug_assertions))]
1009 pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
1010 pub(crate) tab_stops: TabStopMap,
1011}
1012
1013#[derive(Clone, Default)]
1014pub(crate) struct PrepaintStateIndex {
1015 hitboxes_index: usize,
1016 tooltips_index: usize,
1017 deferred_draws_index: usize,
1018 dispatch_tree_index: usize,
1019 accessed_element_states_index: usize,
1020 line_layout_index: LineLayoutIndex,
1021}
1022
1023#[derive(Clone, Default)]
1024pub(crate) struct PaintIndex {
1025 scene_index: usize,
1026 mouse_listeners_index: usize,
1027 input_handlers_index: usize,
1028 cursor_styles_index: usize,
1029 accessed_element_states_index: usize,
1030 tab_handle_index: usize,
1031 line_layout_index: LineLayoutIndex,
1032}
1033
1034impl Frame {
1035 pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
1036 Frame {
1037 focus: None,
1038 window_active: false,
1039 element_states: FxHashMap::default(),
1040 accessed_element_states: Vec::new(),
1041 mouse_listeners: Vec::new(),
1042 dispatch_tree,
1043 scene: Scene::default(),
1044 hitboxes: Vec::new(),
1045 window_control_hitboxes: Vec::new(),
1046 deferred_draws: Vec::new(),
1047 input_handlers: Vec::new(),
1048 tooltip_requests: Vec::new(),
1049 cursor_styles: Vec::new(),
1050
1051 #[cfg(any(test, feature = "test-support"))]
1052 debug_bounds: FxHashMap::default(),
1053
1054 #[cfg(any(feature = "inspector", debug_assertions))]
1055 next_inspector_instance_ids: FxHashMap::default(),
1056
1057 #[cfg(any(feature = "inspector", debug_assertions))]
1058 inspector_hitboxes: FxHashMap::default(),
1059 tab_stops: TabStopMap::default(),
1060 }
1061 }
1062
1063 pub(crate) fn clear(&mut self) {
1064 self.element_states.clear();
1065 self.accessed_element_states.clear();
1066 self.mouse_listeners.clear();
1067 self.dispatch_tree.clear();
1068 self.scene.clear();
1069 self.input_handlers.clear();
1070 self.tooltip_requests.clear();
1071 self.cursor_styles.clear();
1072 self.hitboxes.clear();
1073 self.window_control_hitboxes.clear();
1074 self.deferred_draws.clear();
1075 self.tab_stops.clear();
1076 self.focus = None;
1077
1078 #[cfg(any(test, feature = "test-support"))]
1079 {
1080 self.debug_bounds.clear();
1081 }
1082
1083 #[cfg(any(feature = "inspector", debug_assertions))]
1084 {
1085 self.next_inspector_instance_ids.clear();
1086 self.inspector_hitboxes.clear();
1087 }
1088 }
1089
1090 pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
1091 self.cursor_styles
1092 .iter()
1093 .rev()
1094 .fold_while(None, |style, request| match request.hitbox_id {
1095 None => Done(Some(request.style)),
1096 Some(hitbox_id) => Continue(style.or_else(|| {
1097 hitbox_id
1098 .is_hovered_ignoring_last_input(window)
1099 .then_some(request.style)
1100 })),
1101 })
1102 .into_inner()
1103 }
1104
1105 pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
1106 let mut set_hover_hitbox_count = false;
1107 let mut hit_test = HitTest::default();
1108 for hitbox in self.hitboxes.iter().rev() {
1109 let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
1110 if bounds.contains(&position) {
1111 hit_test.ids.push(hitbox.id);
1112 if !set_hover_hitbox_count
1113 && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
1114 {
1115 hit_test.hover_hitbox_count = hit_test.ids.len();
1116 set_hover_hitbox_count = true;
1117 }
1118 if hitbox.behavior == HitboxBehavior::BlockMouse {
1119 break;
1120 }
1121 }
1122 }
1123 if !set_hover_hitbox_count {
1124 hit_test.hover_hitbox_count = hit_test.ids.len();
1125 }
1126 hit_test
1127 }
1128
1129 pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
1130 self.focus
1131 .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
1132 .unwrap_or_default()
1133 }
1134
1135 pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
1136 for element_state_key in &self.accessed_element_states {
1137 if let Some((element_state_key, element_state)) =
1138 prev_frame.element_states.remove_entry(element_state_key)
1139 {
1140 self.element_states.insert(element_state_key, element_state);
1141 }
1142 }
1143
1144 self.scene.finish();
1145 }
1146}
1147
1148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
1149enum InputModality {
1150 Mouse,
1151 Keyboard,
1152 Touch,
1153}
1154
1155pub struct Window {
1157 pub(crate) handle: AnyWindowHandle,
1158 pub(crate) invalidator: WindowInvalidator,
1159 pub(crate) removed: bool,
1160 pub(crate) platform_window: Box<dyn PlatformWindow>,
1161 display_id: Option<DisplayId>,
1162 is_resizable: bool,
1163 is_minimizable: bool,
1164 sprite_atlas: Arc<dyn PlatformAtlas>,
1165 text_system: Arc<WindowTextSystem>,
1166 text_rendering_mode: Rc<Cell<TextRenderingMode>>,
1167 rem_size: Pixels,
1168 rem_size_override_stack: SmallVec<[Pixels; 8]>,
1173 pub(crate) viewport_size: Size<Pixels>,
1174 layout_engine: Option<TaffyLayoutEngine>,
1175 pub(crate) root: Option<AnyView>,
1176 pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
1177 pub(crate) text_style_stack: Vec<TextStyleRefinement>,
1178 pub(crate) rendered_entity_stack: Vec<EntityId>,
1179 pub(crate) element_offset_stack: Vec<Point<Pixels>>,
1180 pub(crate) element_opacity: f32,
1181 pub(crate) edge_fade: Option<EdgeFade>,
1182 pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
1183 pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
1184 last_text_input_configuration: Option<TextInputConfiguration>,
1188 pub(crate) image_cache_stack: Vec<AnyImageCache>,
1189 pub(crate) rendered_frame: Frame,
1190 pub(crate) next_frame: Frame,
1191 next_hitbox_id: HitboxId,
1192 pub(crate) next_tooltip_id: TooltipId,
1193 pub(crate) tooltip_bounds: Option<TooltipBounds>,
1194 pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
1195 pub(crate) dirty_views: FxHashSet<EntityId>,
1196 focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
1197 pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
1198 focus_lost_path: SmallVec<[FocusId; 8]>,
1199 default_prevented: bool,
1200 mouse_position: Point<Pixels>,
1201 mouse_hit_test: HitTest,
1202 modifiers: Modifiers,
1203 capslock: Capslock,
1204 scale_factor: f32,
1205 pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
1206 appearance: WindowAppearance,
1207 pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
1208 pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>,
1209 active: Rc<Cell<bool>>,
1210 hovered: Rc<Cell<bool>>,
1211 pub(crate) needs_present: Rc<Cell<bool>>,
1212 pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1215 #[cfg(feature = "profiler")]
1216 window_profiler: profiler::WindowProfiler,
1217 last_input_modality: InputModality,
1218 touch_gestures: TouchGestureRecognizer,
1219 pub(crate) refreshing: bool,
1220 pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
1221 pub(crate) focus: Option<FocusId>,
1222 focus_enabled: bool,
1223 pub(crate) focus_generation: u64,
1226 pending_input: Option<PendingInput>,
1227 pending_modifier: ModifierState,
1228 pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
1229 prompt: Option<RenderablePromptHandle>,
1230 pub(crate) client_inset: Option<Pixels>,
1231 captured_hitbox: Option<HitboxId>,
1234 #[cfg(any(feature = "inspector", debug_assertions))]
1235 inspector: Option<Entity<Inspector>>,
1236 #[cfg(feature = "profiler")]
1237 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay,
1238 pub(crate) a11y: A11y,
1239}
1240
1241#[derive(Clone, Debug, Default)]
1242struct ModifierState {
1243 modifiers: Modifiers,
1244 saw_other_input: bool,
1245}
1246
1247#[derive(Clone, Debug)]
1250pub(crate) struct InputRateTracker {
1251 timestamps: Vec<Instant>,
1252 window: Duration,
1253 inputs_per_second: u32,
1254 sustain_until: Instant,
1255 sustain_duration: Duration,
1256}
1257
1258impl Default for InputRateTracker {
1259 fn default() -> Self {
1260 Self {
1261 timestamps: Vec::new(),
1262 window: Duration::from_millis(100),
1263 inputs_per_second: 60,
1264 sustain_until: Instant::now(),
1265 sustain_duration: Duration::from_secs(1),
1266 }
1267 }
1268}
1269
1270impl InputRateTracker {
1271 pub fn record_input(&mut self) {
1272 let now = Instant::now();
1273 self.timestamps.push(now);
1274 self.prune_old_timestamps(now);
1275
1276 let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1277 if self.timestamps.len() as u128 >= min_events {
1278 self.sustain_until = now + self.sustain_duration;
1279 }
1280 }
1281
1282 pub fn is_high_rate(&self) -> bool {
1283 Instant::now() < self.sustain_until
1284 }
1285
1286 fn prune_old_timestamps(&mut self, now: Instant) {
1287 self.timestamps
1288 .retain(|&t| now.duration_since(t) <= self.window);
1289 }
1290}
1291
1292#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1293pub(crate) enum DrawPhase {
1294 None,
1295 Prepaint,
1296 Paint,
1297 Focus,
1298}
1299
1300#[derive(Default, Debug)]
1301struct PendingInput {
1302 keystrokes: SmallVec<[Keystroke; 1]>,
1303 focus: Option<FocusId>,
1304 timer: Option<Task<()>>,
1305 needs_timeout: bool,
1306}
1307
1308pub(crate) struct ElementStateBox {
1309 pub(crate) inner: Box<dyn Any>,
1310 #[cfg(debug_assertions)]
1311 pub(crate) type_name: &'static str,
1312}
1313
1314fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1315 let active_window_bounds = cx
1320 .active_window()
1321 .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1322
1323 const CASCADE_OFFSET: f32 = 25.0;
1324
1325 let display = display_id
1326 .map(|id| cx.find_display(id))
1327 .unwrap_or_else(|| cx.primary_display());
1328
1329 let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1330
1331 let display_bounds = display
1333 .as_ref()
1334 .map(|d| d.visible_bounds())
1335 .unwrap_or_else(default_placement);
1336
1337 let (
1338 Bounds {
1339 origin: base_origin,
1340 size: base_size,
1341 },
1342 window_bounds_ctor,
1343 ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1344 Some(bounds) => match bounds {
1345 WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1346 WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1347 WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1348 },
1349 None => (
1350 display
1351 .as_ref()
1352 .map(|d| d.default_bounds())
1353 .unwrap_or_else(default_placement),
1354 WindowBounds::Windowed,
1355 ),
1356 };
1357
1358 let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1359 let proposed_origin = base_origin + cascade_offset;
1360 let proposed_bounds = Bounds::new(proposed_origin, base_size);
1361
1362 let display_right = display_bounds.origin.x + display_bounds.size.width;
1363 let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1364 let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1365 let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1366
1367 let fits_horizontally = window_right <= display_right;
1368 let fits_vertically = window_bottom <= display_bottom;
1369
1370 let final_origin = match (fits_horizontally, fits_vertically) {
1371 (true, true) => proposed_origin,
1372 (false, true) => point(display_bounds.origin.x, base_origin.y),
1373 (true, false) => point(base_origin.x, display_bounds.origin.y),
1374 (false, false) => display_bounds.origin,
1375 };
1376 window_bounds_ctor(Bounds::new(final_origin, base_size))
1377}
1378
1379#[derive(Debug, Clone, Copy)]
1382pub struct GlassEffect {
1383 pub blur_radius: Pixels,
1385 pub lens: Pixels,
1387 pub reach: Pixels,
1390 pub magnify: f32,
1392 pub dispersion: f32,
1394 pub gain: f32,
1396 pub saturation: f32,
1399 pub tint: Hsla,
1401 pub edge: f32,
1403 pub edge_width: Pixels,
1405 pub edge_aa: Pixels,
1407}
1408
1409impl Window {
1410 pub(crate) fn new(
1411 handle: AnyWindowHandle,
1412 options: WindowOptions,
1413 cx: &mut App,
1414 ) -> Result<Self> {
1415 let WindowOptions {
1416 window_bounds,
1417 titlebar,
1418 focus,
1419 show,
1420 kind,
1421 is_movable,
1422 app_owns_titlebar_drag,
1423 inactive_frame_interval,
1424 is_resizable,
1425 is_minimizable,
1426 display_id,
1427 window_background,
1428 app_id,
1429 window_min_size,
1430 window_decorations,
1431 #[cfg_attr(
1432 not(any(target_os = "linux", target_os = "freebsd")),
1433 allow(unused_variables)
1434 )]
1435 icon,
1436 #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1437 tabbing_identifier,
1438 } = options;
1439
1440 let initial_window_title = titlebar
1441 .as_ref()
1442 .and_then(|titlebar| titlebar.title.clone());
1443
1444 let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1445 let mut platform_window = cx.platform.open_window(
1446 handle,
1447 WindowParams {
1448 bounds: window_bounds.get_bounds(),
1449 titlebar,
1450 kind,
1451 is_movable,
1452 app_owns_titlebar_drag,
1453 is_resizable,
1454 is_minimizable,
1455 focus,
1456 show,
1457 display_id,
1458 window_min_size,
1459 app_id: app_id.clone(),
1460 icon,
1461 #[cfg(target_os = "macos")]
1462 tabbing_identifier,
1463 },
1464 )?;
1465
1466 let tab_bar_visible = platform_window.tab_bar_visible();
1467 SystemWindowTabController::init_visible(cx, tab_bar_visible);
1468 if let Some(tabs) = platform_window.tabbed_windows() {
1469 SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1470 }
1471
1472 let display_id = platform_window.display().map(|display| display.id());
1473 let sprite_atlas = platform_window.sprite_atlas();
1474 let mouse_position = platform_window.mouse_position();
1475 let modifiers = platform_window.modifiers();
1476 let capslock = platform_window.capslock();
1477 let content_size = platform_window.content_size();
1478 let scale_factor = platform_window.scale_factor();
1479 let appearance = platform_window.appearance();
1480 let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1481 let invalidator = WindowInvalidator::new(handle.window_id());
1482 let active = Rc::new(Cell::new(platform_window.is_active()));
1483 let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1484 let needs_present = Rc::new(Cell::new(false));
1485 let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1486 let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1487 let last_frame_time = Rc::new(Cell::new(None));
1488
1489 platform_window
1490 .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1491 platform_window.set_background_appearance(window_background);
1492
1493 match window_bounds {
1494 WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1495 WindowBounds::Maximized(_) => platform_window.zoom(),
1496 WindowBounds::Windowed(_) => {}
1497 }
1498
1499 let accessibility_force_disabled = cx.accessibility_force_disabled;
1500 let a11y_active_flag = Arc::new(AtomicBool::new(false));
1501
1502 #[cfg(not(target_family = "wasm"))]
1503 if !accessibility_force_disabled {
1504 let mut initial_root_node = accesskit::Node::new(accesskit::Role::Window);
1505 if let Some(title) = &initial_window_title {
1506 initial_root_node.set_label(title.to_string());
1507 }
1508 let initial_tree = accesskit::TreeUpdate {
1509 nodes: vec![(ROOT_NODE_ID, initial_root_node)],
1510 tree: Some(accesskit::Tree::new(ROOT_NODE_ID)),
1511 tree_id: accesskit::TreeId::ROOT,
1512 focus: ROOT_NODE_ID,
1513 };
1514 let (activation_sender, activation_receiver) = async_channel::unbounded::<()>();
1515 let (deactivation_sender, deactivation_receiver) = async_channel::unbounded::<()>();
1516 let (action_sender, action_receiver) =
1517 async_channel::unbounded::<accesskit::ActionRequest>();
1518
1519 platform_window.a11y_init(crate::A11yCallbacks {
1520 activation: {
1521 let active_flag = a11y_active_flag.clone();
1522 Box::new(move || {
1523 log::info!("Accessibility activated");
1524 active_flag.store(true, SeqCst);
1525 activation_sender.send_blocking(()).log_err();
1526 Some(initial_tree.clone())
1527 })
1528 },
1529 action: Box::new(move |request| {
1530 action_sender.send_blocking(request).log_err();
1531 }),
1532 deactivation: {
1533 let active_flag = a11y_active_flag.clone();
1534 Box::new(move || {
1535 log::info!("Accessibility deactivated");
1536 active_flag.store(false, SeqCst);
1537 deactivation_sender.send_blocking(()).log_err();
1538 })
1539 },
1540 });
1541
1542 let mut async_cx = cx.to_async();
1548 cx.foreground_executor()
1549 .spawn(async move {
1550 while activation_receiver.recv().await.is_ok() {
1551 handle
1552 .update(&mut async_cx, |_, window, _| window.refresh())
1553 .log_err();
1554 }
1555 })
1556 .detach();
1557
1558 let mut async_cx = cx.to_async();
1559 cx.foreground_executor()
1560 .spawn(async move {
1561 while deactivation_receiver.recv().await.is_ok() {
1562 handle
1563 .update(&mut async_cx, |_, window, _| window.refresh())
1564 .log_err();
1565 }
1566 })
1567 .detach();
1568
1569 let mut async_cx = cx.to_async();
1570 cx.foreground_executor()
1571 .spawn(async move {
1572 while let Ok(request) = action_receiver.recv().await {
1573 handle
1574 .update(&mut async_cx, |_, window, cx| {
1575 window.handle_a11y_action(request, cx);
1576 })
1577 .log_err();
1578 }
1579 })
1580 .detach();
1581 }
1582
1583 platform_window.on_close(Box::new({
1584 let window_id = handle.window_id();
1585 let mut cx = cx.to_async();
1586 move || {
1587 let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
1588 let _ = cx.update(|cx| {
1589 SystemWindowTabController::remove_tab(cx, window_id);
1590 });
1591 }
1592 }));
1593 platform_window.on_request_frame(Box::new({
1594 let mut cx = cx.to_async();
1595 let invalidator = invalidator.clone();
1596 let active = active.clone();
1597 let needs_present = needs_present.clone();
1598 let next_frame_callbacks = next_frame_callbacks.clone();
1599 let input_rate_tracker = input_rate_tracker.clone();
1600 let mut deferred_force_render = false;
1601 move |request_frame_options| {
1602 #[cfg(feature = "profiler")]
1603 let _foreground_turn = profiler::journal::foreground_turn();
1604 if draw_in_progress() {
1620 log::debug!("deferring re-entrant window draw request");
1621 deferred_force_render |= request_frame_options.force_render;
1622 return;
1623 }
1624 let force_render =
1628 mem::take(&mut deferred_force_render) || request_frame_options.force_render;
1629
1630 let thermal_state = handle
1631 .update(&mut cx, |_, _, cx| cx.thermal_state())
1632 .log_err();
1633
1634 let min_frame_interval = if request_frame_options.require_presentation
1638 || (!request_frame_options.force_render
1639 && next_frame_callbacks.borrow().is_empty())
1640 {
1641 None
1642 } else if !active.get() && !input_rate_tracker.borrow_mut().is_high_rate() {
1643 inactive_frame_interval
1644 } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
1645 Some(Duration::from_micros(16667))
1646 } else {
1647 None
1648 };
1649
1650 let now = Instant::now();
1651 if let Some(min_interval) = min_frame_interval {
1652 if let Some(last_frame) = last_frame_time.get()
1653 && now.duration_since(last_frame) < min_interval
1654 {
1655 deferred_force_render |= force_render;
1657 handle
1659 .update(&mut cx, |_, window, _| {
1660 window.platform_window.schedule_frame();
1661 })
1662 .log_err();
1663 invalidator.wake_platform();
1668 return;
1669 }
1670 }
1671 last_frame_time.set(Some(now));
1672
1673 let pending_next_frame_callbacks = next_frame_callbacks.take();
1674 if !pending_next_frame_callbacks.is_empty() {
1675 handle
1676 .update(&mut cx, |_, window, cx| {
1677 for callback in pending_next_frame_callbacks {
1678 callback(window, cx);
1679 }
1680 })
1681 .log_err();
1682 }
1683
1684 let needs_present = request_frame_options.require_presentation
1688 || needs_present.get()
1689 || input_rate_tracker.borrow_mut().is_high_rate();
1690
1691 if invalidator.is_dirty() || force_render {
1692 measure("frame duration", || {
1693 handle
1694 .update(&mut cx, |_, window, cx| {
1695 if force_render {
1696 window.refresh();
1699 }
1700 let arena_clear_needed = window.draw(cx);
1701 window.present();
1702 arena_clear_needed.clear(cx);
1703 })
1704 .log_err();
1705 })
1706 } else if needs_present {
1707 handle
1708 .update(&mut cx, |_, window, _| window.present())
1709 .log_err();
1710 }
1711
1712 handle
1713 .update(&mut cx, |_, window, _| {
1714 if window.invalidator.is_dirty()
1715 || !window.next_frame_callbacks.borrow().is_empty()
1716 {
1717 window.platform_window.schedule_frame();
1718 }
1719 })
1720 .log_err();
1721
1722 if invalidator.is_dirty() || !next_frame_callbacks.borrow().is_empty() {
1728 invalidator.wake_platform();
1729 }
1730 }
1731 }));
1732 invalidator.set_platform_waker(platform_window.frame_waker());
1733 platform_window.on_resize(Box::new({
1734 let mut cx = cx.to_async();
1735 move |_, _| {
1736 handle
1737 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1738 .log_err();
1739 }
1740 }));
1741 platform_window.on_moved(Box::new({
1742 let mut cx = cx.to_async();
1743 move || {
1744 handle
1745 .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1746 .log_err();
1747 }
1748 }));
1749 platform_window.on_appearance_changed(Box::new({
1750 let cx = cx.to_async();
1751 let foreground_executor = cx.foreground_executor().clone();
1752 move || {
1753 let mut cx = cx.clone();
1754 foreground_executor
1757 .spawn(async move {
1758 handle
1759 .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1760 .log_err();
1761 })
1762 .detach();
1763 }
1764 }));
1765 platform_window.on_button_layout_changed(Box::new({
1766 let mut cx = cx.to_async();
1767 move || {
1768 handle
1769 .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
1770 .log_err();
1771 }
1772 }));
1773 platform_window.on_active_status_change(Box::new({
1774 let mut cx = cx.to_async();
1775 move |active| {
1776 handle
1777 .update(&mut cx, |_, window, cx| {
1778 window.active.set(active);
1779 window.modifiers = window.platform_window.modifiers();
1780 window.capslock = window.platform_window.capslock();
1781 window
1782 .activation_observers
1783 .clone()
1784 .retain(&(), |callback| callback(window, cx));
1785
1786 window.bounds_changed(cx);
1787 window.refresh();
1788
1789 SystemWindowTabController::update_last_active(cx, window.handle.id);
1790 })
1791 .log_err();
1792 }
1793 }));
1794 platform_window.on_hover_status_change(Box::new({
1795 let mut cx = cx.to_async();
1796 move |active| {
1797 handle
1798 .update(&mut cx, |_, window, _| {
1799 window.hovered.set(active);
1800 window.refresh();
1801 })
1802 .log_err();
1803 }
1804 }));
1805 platform_window.on_input({
1806 let mut cx = cx.to_async();
1807 Box::new(move |event| {
1808 handle
1809 .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1810 .log_err()
1811 .unwrap_or(DispatchEventResult::default())
1812 })
1813 });
1814 platform_window.on_hit_test_window_control({
1815 let mut cx = cx.to_async();
1816 Box::new(move || {
1817 handle
1818 .update(&mut cx, |_, window, _cx| {
1819 for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1820 if window.mouse_hit_test.ids.contains(&hitbox.id) {
1821 return Some(*area);
1822 }
1823 }
1824 None
1825 })
1826 .log_err()
1827 .unwrap_or(None)
1828 })
1829 });
1830 platform_window.on_move_tab_to_new_window({
1831 let mut cx = cx.to_async();
1832 Box::new(move || {
1833 handle
1834 .update(&mut cx, |_, _window, cx| {
1835 SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1836 })
1837 .log_err();
1838 })
1839 });
1840 platform_window.on_merge_all_windows({
1841 let mut cx = cx.to_async();
1842 Box::new(move || {
1843 handle
1844 .update(&mut cx, |_, _window, cx| {
1845 SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1846 })
1847 .log_err();
1848 })
1849 });
1850 platform_window.on_select_next_tab({
1851 let mut cx = cx.to_async();
1852 Box::new(move || {
1853 handle
1854 .update(&mut cx, |_, _window, cx| {
1855 SystemWindowTabController::select_next_tab(cx, handle.window_id());
1856 })
1857 .log_err();
1858 })
1859 });
1860 platform_window.on_select_previous_tab({
1861 let mut cx = cx.to_async();
1862 Box::new(move || {
1863 handle
1864 .update(&mut cx, |_, _window, cx| {
1865 SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1866 })
1867 .log_err();
1868 })
1869 });
1870 platform_window.on_toggle_tab_bar({
1871 let mut cx = cx.to_async();
1872 Box::new(move || {
1873 handle
1874 .update(&mut cx, |_, window, cx| {
1875 let tab_bar_visible = window.platform_window.tab_bar_visible();
1876 SystemWindowTabController::set_visible(cx, tab_bar_visible);
1877 })
1878 .log_err();
1879 })
1880 });
1881
1882 if let Some(app_id) = app_id {
1883 platform_window.set_app_id(&app_id);
1884 }
1885
1886 platform_window.map_window().unwrap();
1887
1888 Ok(Window {
1889 handle,
1890 invalidator,
1891 removed: false,
1892 platform_window,
1893 display_id,
1894 is_resizable,
1895 is_minimizable,
1896 sprite_atlas,
1897 text_system,
1898 text_rendering_mode: cx.text_rendering_mode.clone(),
1899 rem_size: px(16.),
1900 rem_size_override_stack: SmallVec::new(),
1901 viewport_size: content_size,
1902 layout_engine: Some(TaffyLayoutEngine::new()),
1903 root: None,
1904 element_id_stack: SmallVec::default(),
1905 text_style_stack: Vec::new(),
1906 rendered_entity_stack: Vec::new(),
1907 element_offset_stack: Vec::new(),
1908 content_mask_stack: Vec::new(),
1909 element_opacity: 1.0,
1910 edge_fade: None,
1911 requested_autoscroll: None,
1912 last_text_input_configuration: None,
1913 rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1914 next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1915 next_frame_callbacks,
1916 next_hitbox_id: HitboxId(0),
1917 next_tooltip_id: TooltipId::default(),
1918 tooltip_bounds: None,
1919 dirty_views: FxHashSet::default(),
1920 focus_listeners: SubscriberSet::new(),
1921 focus_lost_listeners: SubscriberSet::new(),
1922 focus_lost_path: SmallVec::new(),
1923 default_prevented: true,
1924 mouse_position,
1925 mouse_hit_test: HitTest::default(),
1926 modifiers,
1927 capslock,
1928 scale_factor,
1929 bounds_observers: SubscriberSet::new(),
1930 appearance,
1931 appearance_observers: SubscriberSet::new(),
1932 button_layout_observers: SubscriberSet::new(),
1933 active,
1934 hovered,
1935 needs_present,
1936 input_rate_tracker,
1937 #[cfg(feature = "profiler")]
1938 window_profiler: profiler::WindowProfiler::new(handle.window_id())?,
1939 last_input_modality: InputModality::Mouse,
1940 touch_gestures: TouchGestureRecognizer::new(
1941 cx.platform
1942 .gestures()
1943 .map_or_else(GestureTuning::default, |gestures| gestures.tuning()),
1944 ),
1945 refreshing: false,
1946 activation_observers: SubscriberSet::new(),
1947 focus: None,
1948 focus_enabled: true,
1949 focus_generation: 0,
1950 pending_input: None,
1951 pending_modifier: ModifierState::default(),
1952 pending_input_observers: SubscriberSet::new(),
1953 prompt: None,
1954 client_inset: None,
1955 image_cache_stack: Vec::new(),
1956 captured_hitbox: None,
1957 #[cfg(any(feature = "inspector", debug_assertions))]
1958 inspector: None,
1959 #[cfg(feature = "profiler")]
1960 debug_frame_overlay: crate::debug_overlay::DebugFrameOverlay::new(),
1961 a11y: A11y::new(
1962 a11y_active_flag,
1963 accessibility_force_disabled,
1964 initial_window_title,
1965 ),
1966 })
1967 }
1968
1969 pub(crate) fn new_focus_listener(
1970 &self,
1971 value: AnyWindowFocusListener,
1972 ) -> (Subscription, impl FnOnce() + use<>) {
1973 self.focus_listeners.insert((), value)
1974 }
1975}
1976
1977#[derive(Clone, Debug, Default, PartialEq, Eq)]
1978#[expect(missing_docs)]
1979pub struct DispatchEventResult {
1980 pub propagate: bool,
1981 pub default_prevented: bool,
1982}
1983
1984#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1988#[repr(C)]
1989pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1990 pub bounds: Bounds<P>,
1992}
1993
1994impl ContentMask<Pixels> {
1995 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1997 ContentMask {
1998 bounds: self.bounds.scale(factor),
1999 }
2000 }
2001
2002 pub fn intersect(&self, other: &Self) -> Self {
2004 let bounds = self.bounds.intersect(&other.bounds);
2005 ContentMask { bounds }
2006 }
2007}
2008
2009impl Window {
2010 fn mark_view_dirty(&mut self, view_id: EntityId) {
2011 for view_id in self
2014 .rendered_frame
2015 .dispatch_tree
2016 .view_path_reversed(view_id)
2017 {
2018 if !self.dirty_views.insert(view_id) {
2019 break;
2020 }
2021 }
2022 }
2023
2024 pub fn observe_window_appearance(
2026 &self,
2027 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2028 ) -> Subscription {
2029 let (subscription, activate) = self.appearance_observers.insert(
2030 (),
2031 Box::new(move |window, cx| {
2032 callback(window, cx);
2033 true
2034 }),
2035 );
2036 activate();
2037 subscription
2038 }
2039
2040 pub fn observe_button_layout_changed(
2042 &self,
2043 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2044 ) -> Subscription {
2045 let (subscription, activate) = self.button_layout_observers.insert(
2046 (),
2047 Box::new(move |window, cx| {
2048 callback(window, cx);
2049 true
2050 }),
2051 );
2052 activate();
2053 subscription
2054 }
2055
2056 pub fn replace_root<E>(
2058 &mut self,
2059 cx: &mut App,
2060 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
2061 ) -> Entity<E>
2062 where
2063 E: 'static + Render,
2064 {
2065 let view = cx.new(|cx| build_view(self, cx));
2066 self.root = Some(view.clone().into());
2067 self.refresh();
2068 view
2069 }
2070
2071 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
2073 where
2074 E: 'static + Render,
2075 {
2076 self.root
2077 .as_ref()
2078 .map(|view| view.clone().downcast::<E>().ok())
2079 }
2080
2081 pub fn window_handle(&self) -> AnyWindowHandle {
2083 self.handle
2084 }
2085
2086 pub fn refresh(&mut self) {
2088 if self.invalidator.not_drawing() {
2089 self.refreshing = true;
2090 self.invalidator.set_dirty(true);
2091 }
2092 }
2093
2094 pub fn remove_window(&mut self) {
2096 self.removed = true;
2097 }
2098
2099 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
2101 self.focus
2102 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
2103 }
2104
2105 pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
2109 let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
2110 ancestors.iter().rev().find_map(|id| {
2111 self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
2112 FocusHandle::for_id(*id, &cx.focus_handles)
2113 })
2114 }
2115
2116 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
2118 if !self.focus_enabled || self.focus == Some(handle.id) {
2119 return;
2120 }
2121
2122 self.focus = Some(handle.id);
2123 self.focus_generation = self.focus_generation.wrapping_add(1);
2124 self.clear_pending_keystrokes(cx);
2125
2126 self.refresh();
2127 }
2128
2129 pub fn blur(&mut self, cx: &mut App) {
2131 self.clear_pending_keystrokes(cx);
2132
2133 if !self.focus_enabled {
2134 return;
2135 }
2136
2137 if self.focus.is_some() {
2138 self.focus_generation = self.focus_generation.wrapping_add(1);
2139 }
2140 self.focus = None;
2141 self.refresh();
2142 }
2143
2144 pub fn disable_focus(&mut self, cx: &mut App) {
2146 self.blur(cx);
2147 self.focus_enabled = false;
2148 }
2149
2150 pub fn focus_next(&mut self, cx: &mut App) {
2152 if !self.focus_enabled {
2153 return;
2154 }
2155
2156 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
2157 self.focus(&handle, cx)
2158 }
2159 }
2160
2161 pub fn focus_prev(&mut self, cx: &mut App) {
2163 if !self.focus_enabled {
2164 return;
2165 }
2166
2167 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
2168 self.focus(&handle, cx)
2169 }
2170 }
2171
2172 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
2174 &self.text_system
2175 }
2176
2177 pub fn text_style(&self) -> TextStyle {
2179 let mut style = TextStyle::default();
2180 for refinement in &self.text_style_stack {
2181 style.refine(refinement);
2182 }
2183 style
2184 }
2185
2186 pub fn is_maximized(&self) -> bool {
2190 self.platform_window.is_maximized()
2191 }
2192
2193 pub fn request_decorations(&self, decorations: WindowDecorations) {
2195 self.platform_window.request_decorations(decorations);
2196 }
2197
2198 pub fn set_exclusive_zone(&self, zone: Pixels) {
2204 self.platform_window.set_exclusive_zone(zone);
2205 }
2206
2207 #[cfg(all(target_os = "linux", feature = "wayland"))]
2212 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
2213 self.platform_window.set_exclusive_edge(edge);
2214 }
2215
2216 pub fn start_window_resize(&self, edge: ResizeEdge) {
2218 if self.is_resizable {
2219 self.platform_window.start_window_resize(edge);
2220 }
2221 }
2222
2223 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
2230 self.platform_window.set_input_region(region);
2231 }
2232
2233 pub fn window_bounds(&self) -> WindowBounds {
2236 self.platform_window.window_bounds()
2237 }
2238
2239 pub fn inner_window_bounds(&self) -> WindowBounds {
2241 self.platform_window.inner_window_bounds()
2242 }
2243
2244 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
2246 let focus_id = self.focused(cx).map(|handle| handle.id);
2247
2248 let window = self.handle;
2249 cx.defer(move |cx| {
2250 window
2251 .update(cx, |_, window, cx| {
2252 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
2253 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
2254 })
2255 .log_err();
2256 })
2257 }
2258
2259 pub(crate) fn dispatch_keystroke_observers(
2260 &mut self,
2261 event: &dyn Any,
2262 action: Option<Box<dyn Action>>,
2263 context_stack: Vec<KeyContext>,
2264 cx: &mut App,
2265 ) {
2266 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2267 return;
2268 };
2269
2270 cx.keystroke_observers.clone().retain(&(), move |callback| {
2271 (callback)(
2272 &KeystrokeEvent {
2273 keystroke: key_down_event.keystroke.clone(),
2274 action: action.as_ref().map(|action| action.boxed_clone()),
2275 context_stack: context_stack.clone(),
2276 },
2277 self,
2278 cx,
2279 )
2280 });
2281 }
2282
2283 pub(crate) fn dispatch_keystroke_interceptors(
2284 &mut self,
2285 event: &dyn Any,
2286 context_stack: Vec<KeyContext>,
2287 cx: &mut App,
2288 ) {
2289 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2290 return;
2291 };
2292
2293 cx.keystroke_interceptors
2294 .clone()
2295 .retain(&(), move |callback| {
2296 (callback)(
2297 &KeystrokeEvent {
2298 keystroke: key_down_event.keystroke.clone(),
2299 action: None,
2300 context_stack: context_stack.clone(),
2301 },
2302 self,
2303 cx,
2304 )
2305 });
2306 }
2307
2308 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2311 let handle = self.handle;
2312 cx.defer(move |cx| {
2313 handle.update(cx, |_, window, cx| f(window, cx)).ok();
2314 });
2315 }
2316
2317 pub fn observe<T: 'static>(
2321 &mut self,
2322 observed: &Entity<T>,
2323 cx: &mut App,
2324 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2325 ) -> Subscription {
2326 let entity_id = observed.entity_id();
2327 let observed = observed.downgrade();
2328 let window_handle = self.handle;
2329 cx.new_observer(
2330 entity_id,
2331 Box::new(move |cx| {
2332 window_handle
2333 .update(cx, |_, window, cx| {
2334 if let Some(handle) = observed.upgrade() {
2335 on_notify(handle, window, cx);
2336 true
2337 } else {
2338 false
2339 }
2340 })
2341 .unwrap_or(false)
2342 }),
2343 )
2344 }
2345
2346 pub fn subscribe<Emitter, Evt>(
2350 &mut self,
2351 entity: &Entity<Emitter>,
2352 cx: &mut App,
2353 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
2354 ) -> Subscription
2355 where
2356 Emitter: EventEmitter<Evt>,
2357 Evt: 'static,
2358 {
2359 let entity_id = entity.entity_id();
2360 let handle = entity.downgrade();
2361 let window_handle = self.handle;
2362 cx.new_subscription(
2363 entity_id,
2364 (
2365 TypeId::of::<Evt>(),
2366 Box::new(move |event, cx| {
2367 window_handle
2368 .update(cx, |_, window, cx| {
2369 if let Some(entity) = handle.upgrade() {
2370 let event = event.downcast_ref().expect("invalid event type");
2371 on_event(entity, event, window, cx);
2372 true
2373 } else {
2374 false
2375 }
2376 })
2377 .unwrap_or(false)
2378 }),
2379 ),
2380 )
2381 }
2382
2383 pub fn observe_release<T>(
2385 &self,
2386 entity: &Entity<T>,
2387 cx: &mut App,
2388 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2389 ) -> Subscription
2390 where
2391 T: 'static,
2392 {
2393 let entity_id = entity.entity_id();
2394 let window_handle = self.handle;
2395 let (subscription, activate) = cx.release_listeners.insert(
2396 entity_id,
2397 Box::new(move |entity, cx| {
2398 let entity = entity.downcast_mut().expect("invalid entity type");
2399 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2400 }),
2401 );
2402 activate();
2403 subscription
2404 }
2405
2406 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2409 AsyncWindowContext::new_context(cx.to_async(), self.handle)
2410 }
2411
2412 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2414 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2415 self.platform_window.schedule_frame();
2416 self.invalidator.wake_platform();
2419 }
2420
2421 pub fn request_animation_frame(&self) {
2434 let entity = self.current_view();
2435 self.on_next_frame(move |_, cx| cx.notify(entity));
2436 }
2437
2438 #[cfg(any(test, feature = "test-support"))]
2443 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
2444 let callbacks = self.next_frame_callbacks.take();
2445 let count = callbacks.len();
2446 for callback in callbacks {
2447 callback(self, cx);
2448 }
2449 count
2450 }
2451
2452 #[track_caller]
2456 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2457 where
2458 R: 'static,
2459 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2460 {
2461 let handle = self.handle;
2462 cx.spawn(async move |app| {
2463 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2464 f(&mut async_window_cx).await
2465 })
2466 }
2467
2468 #[track_caller]
2472 pub fn spawn_with_priority<AsyncFn, R>(
2473 &self,
2474 priority: Priority,
2475 cx: &App,
2476 f: AsyncFn,
2477 ) -> Task<R>
2478 where
2479 R: 'static,
2480 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2481 {
2482 let handle = self.handle;
2483 cx.spawn_with_priority(priority, async move |app| {
2484 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2485 f(&mut async_window_cx).await
2486 })
2487 }
2488
2489 pub fn bounds_changed(&mut self, cx: &mut App) {
2495 self.scale_factor = self.platform_window.scale_factor();
2496 self.viewport_size = self.platform_window.content_size();
2497 self.display_id = self.platform_window.display().map(|display| display.id());
2498 self.mouse_position = self.platform_window.mouse_position();
2499
2500 self.refresh();
2501
2502 self.bounds_observers
2503 .clone()
2504 .retain(&(), |callback| callback(self, cx));
2505 }
2506
2507 pub fn bounds(&self) -> Bounds<Pixels> {
2509 self.platform_window.bounds()
2510 }
2511
2512 #[cfg(any(test, feature = "test-support"))]
2516 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
2517 self.platform_window
2518 .render_to_image(&self.rendered_frame.scene)
2519 }
2520
2521 #[cfg(any(test, feature = "test-support"))]
2526 pub fn painted_quads(&self) -> Vec<Quad> {
2527 self.rendered_frame.scene.quads.clone()
2528 }
2529
2530 pub fn resize(&mut self, size: Size<Pixels>) {
2532 self.platform_window.resize(size);
2533 }
2534
2535 pub fn is_fullscreen(&self) -> bool {
2537 self.platform_window.is_fullscreen()
2538 }
2539
2540 pub fn is_simple_fullscreen(&self) -> bool {
2544 self.platform_window.is_simple_fullscreen()
2545 }
2546
2547 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
2548 self.appearance = self.platform_window.appearance();
2549
2550 self.appearance_observers
2551 .clone()
2552 .retain(&(), |callback| callback(self, cx));
2553 }
2554
2555 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2556 self.button_layout_observers
2557 .clone()
2558 .retain(&(), |callback| callback(self, cx));
2559 }
2560
2561 pub fn appearance(&self) -> WindowAppearance {
2563 self.appearance
2564 }
2565
2566 pub fn viewport_size(&self) -> Size<Pixels> {
2568 self.viewport_size
2569 }
2570
2571 pub fn is_window_active(&self) -> bool {
2573 self.active.get()
2574 }
2575
2576 pub fn is_window_hovered(&self) -> bool {
2580 if cfg!(any(
2581 target_os = "windows",
2582 target_os = "linux",
2583 target_os = "freebsd"
2584 )) {
2585 self.hovered.get()
2586 } else {
2587 self.is_window_active()
2588 }
2589 }
2590
2591 pub fn zoom_window(&self) {
2593 self.platform_window.zoom();
2594 }
2595
2596 pub fn show_window_menu(&self, position: Point<Pixels>) {
2598 self.platform_window.show_window_menu(position)
2599 }
2600
2601 pub fn start_window_move(&self) {
2606 self.platform_window.start_window_move()
2607 }
2608
2609 pub fn set_client_inset(&mut self, inset: Pixels) {
2611 self.client_inset = Some(inset);
2612 self.platform_window.set_client_inset(inset);
2613 }
2614
2615 pub fn client_inset(&self) -> Option<Pixels> {
2617 self.client_inset
2618 }
2619
2620 pub fn window_decorations(&self) -> Decorations {
2622 self.platform_window.window_decorations()
2623 }
2624
2625 pub fn is_resizable(&self) -> bool {
2627 self.is_resizable
2628 }
2629
2630 pub fn is_minimizable(&self) -> bool {
2632 self.is_minimizable
2633 }
2634
2635 pub fn window_controls(&self) -> WindowControls {
2637 self.platform_window.window_controls()
2638 }
2639
2640 pub fn set_window_title(&mut self, title: &str) {
2642 self.platform_window.set_title(title);
2643 self.a11y.set_window_title(title.to_string());
2644 }
2645
2646 #[cfg(target_os = "macos")]
2648 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
2649 self.platform_window.set_traffic_light_position(position);
2650 }
2651
2652 pub fn set_app_id(&mut self, app_id: &str) {
2654 self.platform_window.set_app_id(app_id);
2655 }
2656
2657 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2659 self.platform_window
2660 .set_background_appearance(background_appearance);
2661 }
2662
2663 pub fn set_window_edited(&mut self, edited: bool) {
2665 self.platform_window.set_edited(edited);
2666 }
2667
2668 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
2671 self.platform_window.set_document_path(path);
2672 }
2673
2674 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2676 cx.platform
2677 .displays()
2678 .into_iter()
2679 .find(|display| Some(display.id()) == self.display_id)
2680 }
2681
2682 pub fn show_character_palette(&self) {
2684 self.platform_window.show_character_palette();
2685 }
2686
2687 pub fn scale_factor(&self) -> f32 {
2691 self.scale_factor
2692 }
2693
2694 #[cfg(any(test, feature = "test-support"))]
2696 pub fn set_scale_factor(&mut self, scale_factor: f32) {
2697 self.scale_factor = scale_factor;
2698 self.refresh();
2699 }
2700
2701 pub fn rem_size(&self) -> Pixels {
2704 self.rem_size_override_stack
2705 .last()
2706 .copied()
2707 .unwrap_or(self.rem_size)
2708 }
2709
2710 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2713 self.rem_size = rem_size.into();
2714 }
2715
2716 pub fn with_global_id<R>(
2719 &mut self,
2720 element_id: ElementId,
2721 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2722 ) -> R {
2723 self.with_id(element_id, |this| {
2724 let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2725
2726 f(&global_id, this)
2727 })
2728 }
2729
2730 #[inline]
2732 pub fn with_id<R>(
2733 &mut self,
2734 element_id: impl Into<ElementId>,
2735 f: impl FnOnce(&mut Self) -> R,
2736 ) -> R {
2737 self.element_id_stack.push(element_id.into());
2738 let result = f(self);
2739 self.element_id_stack.pop();
2740 result
2741 }
2742
2743 #[inline]
2749 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2750 where
2751 F: FnOnce(&mut Self) -> R,
2752 {
2753 self.invalidator.debug_assert_paint_or_prepaint();
2754
2755 if let Some(rem_size) = rem_size {
2756 self.rem_size_override_stack.push(rem_size.into());
2757 let result = f(self);
2758 self.rem_size_override_stack.pop();
2759 result
2760 } else {
2761 f(self)
2762 }
2763 }
2764
2765 pub fn line_height(&self) -> Pixels {
2767 self.text_style().line_height_in_pixels(self.rem_size())
2768 }
2769
2770 #[inline]
2772 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
2773 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
2774 }
2775
2776 #[inline]
2778 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
2779 let scale_factor = f64::from(self.scale_factor());
2780 round_half_toward_zero_f64(value * scale_factor) / scale_factor
2781 }
2782
2783 #[inline]
2785 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
2786 bounds.map(|c| self.pixel_snap(c))
2787 }
2788
2789 #[inline]
2791 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
2792 position.map(|c| self.pixel_snap(c))
2793 }
2794
2795 #[inline]
2796 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2797 let scale_factor = self.scale_factor();
2798 let left = round_to_device_pixel(bounds.left().0, scale_factor);
2799 let top = round_to_device_pixel(bounds.top().0, scale_factor);
2800 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
2801 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2802 Bounds::from_corners(
2803 point(ScaledPixels(left), ScaledPixels(top)),
2804 point(ScaledPixels(right), ScaledPixels(bottom)),
2805 )
2806 }
2807
2808 #[inline]
2810 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
2811 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
2812 }
2813
2814 #[inline]
2815 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
2816 edges.map(|e| self.snap_stroke(*e))
2817 }
2818
2819 #[inline]
2821 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2822 let scale_factor = self.scale_factor();
2823 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
2824 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
2825 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
2826 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2827 Bounds::from_corners(
2828 point(ScaledPixels(left), ScaledPixels(top)),
2829 point(ScaledPixels(right), ScaledPixels(bottom)),
2830 )
2831 }
2832
2833 #[inline]
2834 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
2835 ContentMask {
2836 bounds: self.cover_bounds(self.content_mask().bounds),
2837 }
2838 }
2839
2840 pub fn prevent_default(&mut self) {
2843 self.default_prevented = true;
2844 }
2845
2846 pub fn default_prevented(&self) -> bool {
2848 self.default_prevented
2849 }
2850
2851 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2853 let node_id =
2854 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2855 self.rendered_frame
2856 .dispatch_tree
2857 .is_action_available(action, node_id)
2858 }
2859
2860 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2862 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2863 self.rendered_frame
2864 .dispatch_tree
2865 .is_action_available(action, node_id)
2866 }
2867
2868 pub fn mouse_position(&self) -> Point<Pixels> {
2870 self.mouse_position
2871 }
2872
2873 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
2880 self.captured_hitbox = Some(hitbox_id);
2881 }
2882
2883 pub fn release_pointer(&mut self) {
2885 self.captured_hitbox = None;
2886 }
2887
2888 pub fn captured_hitbox(&self) -> Option<HitboxId> {
2890 self.captured_hitbox
2891 }
2892
2893 pub fn modifiers(&self) -> Modifiers {
2895 self.modifiers
2896 }
2897
2898 pub fn last_input_was_keyboard(&self) -> bool {
2901 self.last_input_modality == InputModality::Keyboard
2902 }
2903
2904 pub fn capslock(&self) -> Capslock {
2906 self.capslock
2907 }
2908
2909 #[profiling::function]
2912 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2913 #[cfg(feature = "profiler")]
2916 let frame_dirty = self.invalidator.take_frame_dirty();
2917 #[cfg(feature = "profiler")]
2918 self.window_profiler.begin_draw();
2919
2920 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
2923
2924 self.invalidate_entities();
2925 cx.entities.clear_accessed();
2926 debug_assert!(self.rendered_entity_stack.is_empty());
2927 self.invalidator.set_dirty(false);
2928 self.requested_autoscroll = None;
2929
2930 if let Some(input_handler) = self.platform_window.take_input_handler() {
2935 if let Some(slot) = self
2936 .rendered_frame
2937 .input_handlers
2938 .iter_mut()
2939 .rev()
2940 .find(|h| h.is_none())
2941 {
2942 *slot = Some(input_handler);
2943 } else {
2944 self.rendered_frame.input_handlers.push(Some(input_handler));
2945 }
2946 }
2947 if !cx.mode.skip_drawing() {
2948 self.draw_roots(cx);
2949 #[cfg(feature = "profiler")]
2950 {
2951 let viewport_size = self.viewport_size;
2952 let scale_factor = self.scale_factor();
2953 self.debug_frame_overlay.paint(
2954 &mut self.next_frame.scene,
2955 viewport_size,
2956 scale_factor,
2957 );
2958 }
2959 }
2960 self.dirty_views.clear();
2961 self.next_frame.window_active = self.active.get();
2962
2963 if let Some(input_handler) = self
2969 .next_frame
2970 .input_handlers
2971 .iter_mut()
2972 .rev()
2973 .find_map(|h| h.take())
2974 {
2975 self.platform_window.set_input_handler(input_handler);
2976 }
2977 self.apply_text_input_configuration(cx);
2978
2979 self.layout_engine.as_mut().unwrap().clear();
2980 self.text_system().finish_frame();
2981 self.next_frame.finish(&mut self.rendered_frame);
2982
2983 self.invalidator.set_phase(DrawPhase::Focus);
2984 let previous_focus_path = self.rendered_frame.focus_path();
2985 let previous_window_active = self.rendered_frame.window_active;
2986 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2987 self.next_frame.clear();
2988 let current_focus_path = self.rendered_frame.focus_path();
2989 let current_window_active = self.rendered_frame.window_active;
2990 let mut focus_before_listeners = self.focus;
2991
2992 if previous_focus_path != current_focus_path
2993 || previous_window_active != current_window_active
2994 {
2995 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2996 self.focus_lost_path = previous_focus_path.clone();
2997 self.focus_lost_listeners
2998 .clone()
2999 .retain(&(), |listener| listener(self, cx));
3000 self.focus_lost_path = SmallVec::new();
3001 focus_before_listeners = self.focus;
3006 }
3007
3008 let event = WindowFocusEvent {
3009 previous_focus_path: if previous_window_active {
3010 previous_focus_path
3011 } else {
3012 Default::default()
3013 },
3014 current_focus_path: if current_window_active {
3015 current_focus_path
3016 } else {
3017 Default::default()
3018 },
3019 };
3020 self.focus_listeners
3021 .clone()
3022 .retain(&(), |listener| listener(&event, self, cx));
3023 }
3024
3025 debug_assert!(self.rendered_entity_stack.is_empty());
3026 self.record_entities_accessed(cx);
3027 self.reset_cursor_style(cx);
3028 self.refreshing = false;
3029 self.invalidator.set_phase(DrawPhase::None);
3030 if self.focus != focus_before_listeners {
3035 self.refresh();
3036 }
3037 self.needs_present.set(true);
3038
3039 #[cfg(feature = "profiler")]
3040 {
3041 let draw_duration = self
3042 .window_profiler
3043 .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
3044 self.debug_frame_overlay.record_frame(draw_duration);
3045 }
3046
3047 arena_scope.exit(&cx.element_arena)
3050 }
3051
3052 fn record_entities_accessed(&mut self, cx: &mut App) {
3053 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3054 let mut entities = mem::take(entities_ref.deref_mut());
3055 let handle = self.handle;
3056 cx.record_entities_accessed(
3057 handle,
3058 self.invalidator.clone(),
3060 &entities,
3061 );
3062 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3063 mem::swap(&mut entities, entities_ref.deref_mut());
3064 }
3065
3066 fn invalidate_entities(&mut self) {
3067 let mut views = self.invalidator.take_views();
3068 for entity in views.drain() {
3069 self.mark_view_dirty(entity);
3070 }
3071 self.invalidator.replace_views(views);
3072 }
3073
3074 #[profiling::function]
3075 fn present(&mut self) {
3076 #[cfg(feature = "profiler")]
3077 let _foreground_turn = profiler::journal::foreground_turn();
3078 #[cfg(feature = "profiler")]
3079 let present_start = Instant::now();
3080 self.platform_window.draw(&self.rendered_frame.scene);
3081 #[cfg(feature = "profiler")]
3082 self.window_profiler.record_present(
3083 present_start,
3084 Instant::now(),
3085 self.active.get(),
3086 !self.next_frame_callbacks.borrow().is_empty(),
3087 );
3088 self.needs_present.set(false);
3089 profiling::finish_frame!();
3090 }
3091
3092 #[cfg(any(feature = "bench-support", all(test, feature = "profiler")))]
3098 pub fn present_if_needed(&mut self) {
3099 if self.needs_present.get() {
3100 self.present();
3101 }
3102 }
3103
3104 #[cfg(feature = "profiler")]
3106 pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
3107 self.window_profiler.input_latency_snapshot()
3108 }
3109
3110 #[cfg(feature = "profiler")]
3112 pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
3113 self.window_profiler.frame_duration_snapshot()
3114 }
3115
3116 #[cfg(feature = "profiler")]
3118 pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
3119 self.debug_frame_overlay.mode()
3120 }
3121
3122 #[cfg(feature = "profiler")]
3124 pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
3125 self.debug_frame_overlay.set_mode(mode);
3126 self.refresh();
3127 }
3128
3129 #[cfg(feature = "profiler")]
3132 pub fn cycle_debug_frame_overlay_mode(&mut self) {
3133 self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
3134 }
3135
3136 #[cfg(feature = "profiler")]
3139 pub fn reset_debug_frame_overlay_stats(&mut self) {
3140 self.debug_frame_overlay.reset_stats();
3141 self.refresh();
3142 }
3143
3144 fn draw_roots(&mut self, cx: &mut App) {
3145 self.invalidator.set_phase(DrawPhase::Prepaint);
3146 self.tooltip_bounds.take();
3147
3148 self.a11y.sync_active_flag();
3149 if self.a11y.is_active() {
3150 self.a11y.begin_frame();
3151 }
3152
3153 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
3154 let root_size = {
3155 #[cfg(any(feature = "inspector", debug_assertions))]
3156 {
3157 if self.inspector.is_some() {
3158 let mut size = self.viewport_size;
3159 size.width = (size.width - _inspector_width).max(px(0.0));
3160 size
3161 } else {
3162 self.viewport_size
3163 }
3164 }
3165 #[cfg(not(any(feature = "inspector", debug_assertions)))]
3166 {
3167 self.viewport_size
3168 }
3169 };
3170
3171 let scale_factor = self.scale_factor();
3175 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
3176 let root_layout_id = root_element.request_layout(self, cx);
3177 self.layout_engine
3178 .as_mut()
3179 .unwrap()
3180 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
3181 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3182
3183 #[cfg(any(feature = "inspector", debug_assertions))]
3184 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
3185
3186 self.prepaint_deferred_draws(cx);
3187
3188 let mut prompt_element = None;
3189 let mut active_drag_element = None;
3190 let mut tooltip_element = None;
3191 if let Some(prompt) = self.prompt.take() {
3192 let mut element = prompt.view.any_view().into_any_element();
3193 let prompt_layout_id = element.request_layout(self, cx);
3194 self.layout_engine
3195 .as_mut()
3196 .unwrap()
3197 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
3198 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3199 prompt_element = Some(element);
3200 self.prompt = Some(prompt);
3201 } else if let Some(active_drag) = cx.active_drag.take() {
3202 let mut element = active_drag.view.clone().into_any_element();
3203 let offset = self.mouse_position() - active_drag.cursor_offset;
3204 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
3205 active_drag_element = Some(element);
3206 cx.active_drag = Some(active_drag);
3207 } else {
3208 tooltip_element = self.prepaint_tooltip(cx);
3209 }
3210
3211 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
3212
3213 self.invalidator.set_phase(DrawPhase::Paint);
3215 root_element.paint(self, cx);
3216
3217 #[cfg(any(feature = "inspector", debug_assertions))]
3218 self.paint_inspector(inspector_element, cx);
3219
3220 self.paint_deferred_draws(cx);
3221
3222 if let Some(mut prompt_element) = prompt_element {
3223 prompt_element.paint(self, cx);
3224 } else if let Some(mut drag_element) = active_drag_element {
3225 drag_element.paint(self, cx);
3226 } else if let Some(mut tooltip_element) = tooltip_element {
3227 tooltip_element.paint(self, cx);
3228 }
3229
3230 #[cfg(any(feature = "inspector", debug_assertions))]
3231 self.paint_inspector_hitbox(cx);
3232
3233 let a11y_active_start_of_frame = self.a11y.is_active();
3235 self.a11y.sync_active_flag();
3236 let a11y_active_end_of_frame = self.a11y.is_active();
3237
3238 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
3239
3240 if a11y_active_start_of_frame {
3241 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
3244 viewport_size: self.viewport_size,
3245 scale_factor: self.scale_factor,
3246 tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
3247 };
3248 let tree_update = self.a11y.end_frame(frame_info);
3250
3251 if should_send_a11y_update {
3252 log::debug!(
3253 "Sending a11y tree update: {} nodes",
3254 tree_update.nodes.len()
3255 );
3256 self.platform_window.a11y_tree_update(tree_update);
3257 }
3258 }
3259 }
3260
3261 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
3262 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
3264 let Some(Some(tooltip_request)) = self
3265 .next_frame
3266 .tooltip_requests
3267 .get(tooltip_request_index)
3268 .cloned()
3269 else {
3270 log::error!("Unexpectedly absent TooltipRequest");
3271 continue;
3272 };
3273 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
3274 let mouse_position = tooltip_request.tooltip.mouse_position;
3275 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
3276
3277 let mut tooltip_bounds =
3278 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
3279 let window_bounds = Bounds {
3280 origin: Point::default(),
3281 size: self.viewport_size(),
3282 };
3283
3284 if tooltip_bounds.right() > window_bounds.right() {
3285 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
3286 if new_x >= Pixels::ZERO {
3287 tooltip_bounds.origin.x = new_x;
3288 } else {
3289 tooltip_bounds.origin.x = cmp::max(
3290 Pixels::ZERO,
3291 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
3292 );
3293 }
3294 }
3295
3296 if tooltip_bounds.bottom() > window_bounds.bottom() {
3297 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
3298 if new_y >= Pixels::ZERO {
3299 tooltip_bounds.origin.y = new_y;
3300 } else {
3301 tooltip_bounds.origin.y = cmp::max(
3302 Pixels::ZERO,
3303 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
3304 );
3305 }
3306 }
3307
3308 let is_visible =
3312 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
3313 if !is_visible {
3314 continue;
3315 }
3316
3317 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
3318 element.prepaint(window, cx)
3319 });
3320
3321 self.tooltip_bounds = Some(TooltipBounds {
3322 id: tooltip_request.id,
3323 bounds: tooltip_bounds,
3324 });
3325 return Some(element);
3326 }
3327 None
3328 }
3329
3330 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
3331 assert_eq!(self.element_id_stack.len(), 0);
3332
3333 let mut round_start = 0;
3344 let mut depth = 0;
3345 loop {
3346 let round_end = self.next_frame.deferred_draws.len();
3347 if round_start == round_end {
3348 break;
3349 }
3350 assert!(depth < 10, "Exceeded maximum (10) deferred depth");
3352 depth += 1;
3353
3354 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
3356 traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3357
3358 for deferred_draw_ix in traversal_order {
3359 let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
3360 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
3361 self.element_id_stack
3362 .clone_from(&deferred_draw.element_id_stack);
3363 self.text_style_stack
3364 .clone_from(&deferred_draw.text_style_stack);
3365 (
3366 deferred_draw.element.take(),
3367 deferred_draw.parent_node,
3368 deferred_draw.current_view,
3369 deferred_draw.rem_size,
3370 deferred_draw.absolute_offset,
3371 deferred_draw.prepaint_range.clone(),
3372 )
3373 };
3374 self.next_frame.dispatch_tree.set_active_node(parent_node);
3375
3376 let prepaint_start = self.prepaint_index();
3377 if let Some(mut element) = element {
3378 self.with_rendered_view(current_view, |window| {
3379 window.with_rem_size(Some(rem_size), |window| {
3380 window.with_absolute_element_offset(absolute_offset, |window| {
3381 element.prepaint(window, cx);
3382 });
3383 });
3384 });
3385 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
3386 } else {
3387 self.reuse_prepaint(prepaint_range);
3388 }
3389 let prepaint_end = self.prepaint_index();
3390 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
3391 prepaint_start..prepaint_end;
3392 }
3393
3394 self.element_id_stack.clear();
3395 self.text_style_stack.clear();
3396 round_start = round_end;
3397 }
3398 }
3399
3400 fn paint_deferred_draws(&mut self, cx: &mut App) {
3401 assert_eq!(self.element_id_stack.len(), 0);
3402
3403 if self.next_frame.deferred_draws.len() == 0 {
3406 return;
3407 }
3408
3409 let traversal_order = self.deferred_draw_traversal_order();
3410 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
3411 for deferred_draw_ix in traversal_order {
3412 let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
3413 self.element_id_stack
3414 .clone_from(&deferred_draw.element_id_stack);
3415 self.next_frame
3416 .dispatch_tree
3417 .set_active_node(deferred_draw.parent_node);
3418
3419 let paint_start = self.paint_index();
3420 let content_mask = deferred_draw.content_mask;
3421 if let Some(element) = deferred_draw.element.as_mut() {
3422 self.with_rendered_view(deferred_draw.current_view, |window| {
3423 window.with_content_mask(content_mask, |window| {
3424 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
3425 element.paint(window, cx);
3426 });
3427 })
3428 })
3429 } else {
3430 self.reuse_paint(deferred_draw.paint_range.clone());
3431 }
3432 let paint_end = self.paint_index();
3433 deferred_draw.paint_range = paint_start..paint_end;
3434 }
3435 self.next_frame.deferred_draws = deferred_draws;
3436 self.element_id_stack.clear();
3437 }
3438
3439 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
3440 let deferred_count = self.next_frame.deferred_draws.len();
3441 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
3442 sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3443 sorted_indices
3444 }
3445
3446 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
3447 PrepaintStateIndex {
3448 hitboxes_index: self.next_frame.hitboxes.len(),
3449 tooltips_index: self.next_frame.tooltip_requests.len(),
3450 deferred_draws_index: self.next_frame.deferred_draws.len(),
3451 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
3452 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3453 line_layout_index: self.text_system.layout_index(),
3454 }
3455 }
3456
3457 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
3458 self.next_frame.hitboxes.extend(
3459 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
3460 .iter()
3461 .cloned(),
3462 );
3463 self.next_frame.tooltip_requests.extend(
3464 self.rendered_frame.tooltip_requests
3465 [range.start.tooltips_index..range.end.tooltips_index]
3466 .iter_mut()
3467 .map(|request| request.take()),
3468 );
3469 self.next_frame.accessed_element_states.extend(
3470 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3471 ..range.end.accessed_element_states_index]
3472 .iter()
3473 .map(|(id, type_id)| (id.clone(), *type_id)),
3474 );
3475 self.text_system
3476 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3477
3478 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
3479 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
3480 &mut self.rendered_frame.dispatch_tree,
3481 self.focus,
3482 );
3483
3484 if reused_subtree.contains_focus() {
3485 self.next_frame.focus = self.focus;
3486 }
3487
3488 self.next_frame.deferred_draws.extend(
3489 self.rendered_frame.deferred_draws
3490 [range.start.deferred_draws_index..range.end.deferred_draws_index]
3491 .iter()
3492 .map(|deferred_draw| DeferredDraw {
3493 current_view: deferred_draw.current_view,
3494 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
3495 element_id_stack: deferred_draw.element_id_stack.clone(),
3496 text_style_stack: deferred_draw.text_style_stack.clone(),
3497 content_mask: deferred_draw.content_mask,
3498 rem_size: deferred_draw.rem_size,
3499 priority: deferred_draw.priority,
3500 element: None,
3501 absolute_offset: deferred_draw.absolute_offset,
3502 prepaint_range: deferred_draw.prepaint_range.clone(),
3503 paint_range: deferred_draw.paint_range.clone(),
3504 }),
3505 );
3506 }
3507
3508 pub(crate) fn paint_index(&self) -> PaintIndex {
3509 PaintIndex {
3510 scene_index: self.next_frame.scene.len(),
3511 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
3512 input_handlers_index: self.next_frame.input_handlers.len(),
3513 cursor_styles_index: self.next_frame.cursor_styles.len(),
3514 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3515 tab_handle_index: self.next_frame.tab_stops.paint_index(),
3516 line_layout_index: self.text_system.layout_index(),
3517 }
3518 }
3519
3520 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
3521 self.next_frame.cursor_styles.extend(
3522 self.rendered_frame.cursor_styles
3523 [range.start.cursor_styles_index..range.end.cursor_styles_index]
3524 .iter()
3525 .cloned(),
3526 );
3527 self.next_frame.input_handlers.extend(
3528 self.rendered_frame.input_handlers
3529 [range.start.input_handlers_index..range.end.input_handlers_index]
3530 .iter_mut()
3531 .map(|handler| handler.take()),
3532 );
3533 self.next_frame.mouse_listeners.extend(
3534 self.rendered_frame.mouse_listeners
3535 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
3536 .iter_mut()
3537 .map(|listener| listener.take()),
3538 );
3539 self.next_frame.accessed_element_states.extend(
3540 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3541 ..range.end.accessed_element_states_index]
3542 .iter()
3543 .map(|(id, type_id)| (id.clone(), *type_id)),
3544 );
3545 self.next_frame.tab_stops.replay(
3546 &self.rendered_frame.tab_stops.insertion_history
3547 [range.start.tab_handle_index..range.end.tab_handle_index],
3548 );
3549
3550 self.text_system
3551 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3552 self.next_frame.scene.replay(
3553 range.start.scene_index..range.end.scene_index,
3554 &self.rendered_frame.scene,
3555 );
3556 }
3557
3558 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
3562 where
3563 F: FnOnce(&mut Self) -> R,
3564 {
3565 self.invalidator.debug_assert_paint_or_prepaint();
3566 if let Some(style) = style {
3567 self.text_style_stack.push(style);
3568 let result = f(self);
3569 self.text_style_stack.pop();
3570 result
3571 } else {
3572 f(self)
3573 }
3574 }
3575
3576 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
3579 self.invalidator.debug_assert_paint();
3580 self.next_frame.cursor_styles.push(CursorStyleRequest {
3581 hitbox_id: Some(hitbox.id),
3582 style,
3583 });
3584 }
3585
3586 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
3591 self.invalidator.debug_assert_paint();
3592 self.next_frame.cursor_styles.push(CursorStyleRequest {
3593 hitbox_id: None,
3594 style,
3595 })
3596 }
3597
3598 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
3601 self.invalidator.debug_assert_prepaint();
3602 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
3603 self.next_frame
3604 .tooltip_requests
3605 .push(Some(TooltipRequest { id, tooltip }));
3606 id
3607 }
3608
3609 #[inline]
3614 pub fn with_content_mask<R>(
3615 &mut self,
3616 mask: Option<ContentMask<Pixels>>,
3617 f: impl FnOnce(&mut Self) -> R,
3618 ) -> R {
3619 self.invalidator.debug_assert_paint_or_prepaint();
3620 if let Some(mask) = mask {
3621 let mask = mask.intersect(&self.content_mask());
3622 self.content_mask_stack.push(mask);
3623 let result = f(self);
3624 self.content_mask_stack.pop();
3625 result
3626 } else {
3627 f(self)
3628 }
3629 }
3630
3631 pub fn with_element_offset<R>(
3634 &mut self,
3635 offset: Point<Pixels>,
3636 f: impl FnOnce(&mut Self) -> R,
3637 ) -> R {
3638 self.invalidator.debug_assert_prepaint();
3639
3640 if offset.is_zero() {
3641 return f(self);
3642 };
3643
3644 let abs_offset = self.element_offset() + offset;
3645 self.with_absolute_element_offset(abs_offset, f)
3646 }
3647
3648 pub fn with_absolute_element_offset<R>(
3652 &mut self,
3653 offset: Point<Pixels>,
3654 f: impl FnOnce(&mut Self) -> R,
3655 ) -> R {
3656 self.invalidator.debug_assert_prepaint();
3657 self.element_offset_stack.push(offset);
3658 let result = f(self);
3659 self.element_offset_stack.pop();
3660 result
3661 }
3662
3663 pub(crate) fn with_element_opacity<R>(
3664 &mut self,
3665 opacity: Option<f32>,
3666 f: impl FnOnce(&mut Self) -> R,
3667 ) -> R {
3668 self.invalidator.debug_assert_paint_or_prepaint();
3669
3670 let Some(opacity) = opacity else {
3671 return f(self);
3672 };
3673
3674 let previous_opacity = self.element_opacity;
3675 self.element_opacity = previous_opacity * opacity;
3676 let result = f(self);
3677 self.element_opacity = previous_opacity;
3678 result
3679 }
3680
3681 pub fn with_edge_fade<R>(
3688 &mut self,
3689 fade: Option<EdgeFade>,
3690 f: impl FnOnce(&mut Self) -> R,
3691 ) -> R {
3692 let Some(fade) = fade else {
3693 return f(self);
3694 };
3695 if !(fade.top || fade.bottom || fade.left || fade.right) {
3696 return f(self);
3697 }
3698 self.invalidator.debug_assert_paint_or_prepaint();
3699 let previous = self.edge_fade.replace(fade);
3700 let result = f(self);
3701 self.edge_fade = previous;
3702 result
3703 }
3704
3705 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
3711 self.invalidator.debug_assert_prepaint();
3712 let index = self.prepaint_index();
3713 let result = f(self);
3714 if result.is_err() {
3715 self.next_frame.hitboxes.truncate(index.hitboxes_index);
3716 self.next_frame
3717 .tooltip_requests
3718 .truncate(index.tooltips_index);
3719 self.next_frame
3720 .deferred_draws
3721 .truncate(index.deferred_draws_index);
3722 self.next_frame
3723 .dispatch_tree
3724 .truncate(index.dispatch_tree_index);
3725 self.next_frame
3726 .accessed_element_states
3727 .truncate(index.accessed_element_states_index);
3728 self.text_system.truncate_layouts(index.line_layout_index);
3729 }
3730 result
3731 }
3732
3733 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
3739 self.invalidator.debug_assert_prepaint();
3740 self.requested_autoscroll = Some(bounds);
3741 }
3742
3743 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
3746 self.invalidator.debug_assert_prepaint();
3747 self.requested_autoscroll.take()
3748 }
3749
3750 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3756 let (task, is_first) = cx.fetch_asset::<A>(source);
3757 task.clone().now_or_never().or_else(|| {
3758 if is_first {
3759 let entity_id = self.current_view();
3760 self.spawn(cx, {
3761 let task = task.clone();
3762 async move |cx| {
3763 task.await;
3764
3765 cx.on_next_frame(move |_, cx| {
3766 cx.notify(entity_id);
3767 });
3768 }
3769 })
3770 .detach();
3771 }
3772
3773 None
3774 })
3775 }
3776
3777 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3783 let (task, _) = cx.fetch_asset::<A>(source);
3784 task.now_or_never()
3785 }
3786 pub fn element_offset(&self) -> Point<Pixels> {
3789 self.invalidator.debug_assert_prepaint();
3790 self.element_offset_stack
3791 .last()
3792 .copied()
3793 .unwrap_or_default()
3794 }
3795
3796 #[inline]
3799 pub(crate) fn element_opacity(&self) -> f32 {
3800 self.invalidator.debug_assert_paint_or_prepaint();
3801 self.element_opacity
3802 }
3803
3804 #[inline]
3807 pub(crate) fn element_opacity_at(&self, center: Point<Pixels>) -> f32 {
3808 let opacity = self.element_opacity();
3809 let Some(fade) = &self.edge_fade else {
3810 return opacity;
3811 };
3812 let band = fade.band.0.max(1.0);
3813 let mut ramp: f32 = 1.0;
3814 if fade.top {
3815 ramp = ramp.min(((center.y.0 - fade.bounds.top().0) / band).clamp(0.0, 1.0));
3816 }
3817 if fade.bottom {
3818 ramp = ramp.min(((fade.bounds.bottom().0 - center.y.0) / band).clamp(0.0, 1.0));
3819 }
3820 if fade.left {
3821 ramp = ramp.min(((center.x.0 - fade.bounds.left().0) / band).clamp(0.0, 1.0));
3822 }
3823 if fade.right {
3824 ramp = ramp.min(((fade.bounds.right().0 - center.x.0) / band).clamp(0.0, 1.0));
3825 }
3826 opacity * ramp
3827 }
3828
3829 #[inline]
3836 pub(crate) fn element_opacity_for_bounds(&self, bounds: &Bounds<Pixels>) -> f32 {
3837 let opacity = self.element_opacity();
3838 let Some(fade) = &self.edge_fade else {
3839 return opacity;
3840 };
3841 let band = fade.band.0.max(1.0);
3842 let mut ramp: f32 = 1.0;
3843 if fade.top {
3844 ramp = ramp.min(((bounds.top().0 - fade.bounds.top().0) / band).clamp(0.0, 1.0));
3845 }
3846 if fade.bottom {
3847 ramp = ramp.min(((fade.bounds.bottom().0 - bounds.bottom().0) / band).clamp(0.0, 1.0));
3848 }
3849 if fade.left {
3850 ramp = ramp.min(((bounds.left().0 - fade.bounds.left().0) / band).clamp(0.0, 1.0));
3851 }
3852 if fade.right {
3853 ramp = ramp.min(((fade.bounds.right().0 - bounds.right().0) / band).clamp(0.0, 1.0));
3854 }
3855 opacity * ramp
3856 }
3857
3858 fn quad_fade_gradient(
3867 &self,
3868 bounds: Bounds<Pixels>,
3869 background: &Background,
3870 ) -> Option<Background> {
3871 let fade = self.edge_fade.as_ref()?;
3872 if background.tag != crate::color::BackgroundTag::Solid {
3873 return None;
3874 }
3875 let horizontal = fade.left || fade.right;
3876 let vertical = fade.top || fade.bottom;
3877 if horizontal == vertical {
3878 return None;
3879 }
3880 let band = fade.band.0.max(1.0);
3881 let (lo, hi, edge_lo, edge_hi, fade_lo, fade_hi, angle) = if horizontal {
3882 (
3883 bounds.left().0,
3884 bounds.right().0,
3885 fade.bounds.left().0,
3886 fade.bounds.right().0,
3887 fade.left,
3888 fade.right,
3889 90.0,
3890 )
3891 } else {
3892 (
3893 bounds.top().0,
3894 bounds.bottom().0,
3895 fade.bounds.top().0,
3896 fade.bounds.bottom().0,
3897 fade.top,
3898 fade.bottom,
3899 180.0,
3900 )
3901 };
3902 let extent = (hi - lo).max(1.0);
3903 let in_lo_band = fade_lo && lo < edge_lo + band;
3904 let in_hi_band = fade_hi && hi > edge_hi - band;
3905 let base = self.element_opacity();
3906 let color = background.solid;
3907 let (v0, v1, a0, a1) = match (in_lo_band, in_hi_band) {
3913 (true, true) | (false, false) => return None,
3916 (true, false) => {
3917 let v0 = lo.max(edge_lo);
3918 let v1 = hi.min(edge_lo + band);
3919 let ramp = |v: f32| ((v - edge_lo) / band).clamp(0.0, 1.0);
3920 (v0, v1, ramp(v0), ramp(v1))
3921 }
3922 (false, true) => {
3923 let v0 = lo.max(edge_hi - band);
3924 let v1 = hi.min(edge_hi);
3925 let ramp = |v: f32| ((edge_hi - v) / band).clamp(0.0, 1.0);
3926 (v0, v1, ramp(v0), ramp(v1))
3927 }
3928 };
3929 let p0 = (v0 - lo) / extent;
3930 let p1 = (v1 - lo) / extent;
3931 if (p1 - p0) < 0.001 {
3932 return None;
3933 }
3934 Some(crate::linear_gradient(
3935 angle,
3936 crate::linear_color_stop(color.opacity(a0 * base), p0),
3937 crate::linear_color_stop(color.opacity(a1 * base), p1),
3938 ))
3939 }
3940
3941 pub fn content_mask(&self) -> ContentMask<Pixels> {
3943 self.invalidator.debug_assert_paint_or_prepaint();
3944 self.content_mask_stack
3945 .last()
3946 .cloned()
3947 .unwrap_or_else(|| ContentMask {
3948 bounds: Bounds {
3949 origin: Point::default(),
3950 size: self.viewport_size,
3951 },
3952 })
3953 }
3954
3955 pub fn with_element_namespace<R>(
3958 &mut self,
3959 element_id: impl Into<ElementId>,
3960 f: impl FnOnce(&mut Self) -> R,
3961 ) -> R {
3962 self.element_id_stack.push(element_id.into());
3963 let result = f(self);
3964 self.element_id_stack.pop();
3965 result
3966 }
3967
3968 pub fn use_keyed_state<S: 'static>(
3970 &mut self,
3971 key: impl Into<ElementId>,
3972 cx: &mut App,
3973 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3974 ) -> Entity<S> {
3975 let current_view = self.current_view();
3976 self.with_global_id(key.into(), |global_id, window| {
3977 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
3978 if let Some(state) = state {
3979 (state.clone(), state)
3980 } else {
3981 let new_state = cx.new(|cx| init(window, cx));
3982 cx.observe(&new_state, move |_, cx| {
3983 cx.notify(current_view);
3984 })
3985 .detach();
3986 (new_state.clone(), new_state)
3987 }
3988 })
3989 })
3990 }
3991
3992 #[track_caller]
3998 pub fn use_state<S: 'static>(
3999 &mut self,
4000 cx: &mut App,
4001 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4002 ) -> Entity<S> {
4003 self.use_keyed_state(
4004 ElementId::CodeLocation(*core::panic::Location::caller()),
4005 cx,
4006 init,
4007 )
4008 }
4009
4010 pub fn with_element_state<S, R>(
4015 &mut self,
4016 global_id: &GlobalElementId,
4017 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
4018 ) -> R
4019 where
4020 S: 'static,
4021 {
4022 self.invalidator.debug_assert_paint_or_prepaint();
4023
4024 let key = (global_id.clone(), TypeId::of::<S>());
4025 self.next_frame.accessed_element_states.push(key.clone());
4026
4027 if let Some(any) = self
4028 .next_frame
4029 .element_states
4030 .remove(&key)
4031 .or_else(|| self.rendered_frame.element_states.remove(&key))
4032 {
4033 let ElementStateBox {
4034 inner,
4035 #[cfg(debug_assertions)]
4036 type_name,
4037 } = any;
4038 let mut state_box = inner
4040 .downcast::<Option<S>>()
4041 .map_err(|_| {
4042 #[cfg(debug_assertions)]
4043 {
4044 anyhow::anyhow!(
4045 "invalid element state type for id, requested {:?}, actual: {:?}",
4046 std::any::type_name::<S>(),
4047 type_name
4048 )
4049 }
4050
4051 #[cfg(not(debug_assertions))]
4052 {
4053 anyhow::anyhow!(
4054 "invalid element state type for id, requested {:?}",
4055 std::any::type_name::<S>(),
4056 )
4057 }
4058 })
4059 .unwrap();
4060
4061 let state = state_box.take().expect(
4062 "reentrant call to with_element_state for the same state type and element id",
4063 );
4064 let (result, state) = f(Some(state), self);
4065 state_box.replace(state);
4066 self.next_frame.element_states.insert(
4067 key,
4068 ElementStateBox {
4069 inner: state_box,
4070 #[cfg(debug_assertions)]
4071 type_name,
4072 },
4073 );
4074 result
4075 } else {
4076 let (result, state) = f(None, self);
4077 self.next_frame.element_states.insert(
4078 key,
4079 ElementStateBox {
4080 inner: Box::new(Some(state)),
4081 #[cfg(debug_assertions)]
4082 type_name: std::any::type_name::<S>(),
4083 },
4084 );
4085 result
4086 }
4087 }
4088
4089 pub fn with_optional_element_state<S, R>(
4096 &mut self,
4097 global_id: Option<&GlobalElementId>,
4098 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
4099 ) -> R
4100 where
4101 S: 'static,
4102 {
4103 self.invalidator.debug_assert_paint_or_prepaint();
4104
4105 if let Some(global_id) = global_id {
4106 self.with_element_state(global_id, |state, cx| {
4107 let (result, state) = f(Some(state), cx);
4108 let state =
4109 state.expect("you must return some state when you pass some element id");
4110 (result, state)
4111 })
4112 } else {
4113 let (result, state) = f(None, self);
4114 debug_assert!(
4115 state.is_none(),
4116 "you must not return an element state when passing None for the global id"
4117 );
4118 result
4119 }
4120 }
4121
4122 #[inline]
4124 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
4125 if let Some(index) = index {
4126 self.next_frame.tab_stops.begin_group(index);
4127 let result = f(self);
4128 self.next_frame.tab_stops.end_group();
4129 result
4130 } else {
4131 f(self)
4132 }
4133 }
4134
4135 pub fn defer_draw(
4144 &mut self,
4145 element: AnyElement,
4146 absolute_offset: Point<Pixels>,
4147 priority: usize,
4148 content_mask: Option<ContentMask<Pixels>>,
4149 ) {
4150 self.invalidator.debug_assert_prepaint();
4151 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
4152 self.next_frame.deferred_draws.push(DeferredDraw {
4153 current_view: self.current_view(),
4154 parent_node,
4155 element_id_stack: self.element_id_stack.clone(),
4156 text_style_stack: self.text_style_stack.clone(),
4157 content_mask,
4158 rem_size: self.rem_size(),
4159 priority,
4160 element: Some(element),
4161 absolute_offset,
4162 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
4163 paint_range: PaintIndex::default()..PaintIndex::default(),
4164 });
4165 }
4166
4167 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
4173 self.invalidator.debug_assert_paint();
4174
4175 let content_mask = self.content_mask();
4176 let clipped_bounds = bounds.intersect(&content_mask.bounds);
4177 if !clipped_bounds.is_empty() {
4178 self.next_frame
4179 .scene
4180 .push_layer(self.cover_bounds(clipped_bounds));
4181 }
4182
4183 let result = f(self);
4184
4185 if !clipped_bounds.is_empty() {
4186 self.next_frame.scene.pop_layer();
4187 }
4188
4189 result
4190 }
4191
4192 pub fn paint_drop_shadows(
4198 &mut self,
4199 bounds: Bounds<Pixels>,
4200 corner_radii: Corners<Pixels>,
4201 shadows: &[BoxShadow],
4202 ) {
4203 self.drop_shadows(bounds, corner_radii, shadows, false);
4204 }
4205
4206 pub fn paint_drop_shadows_outside(
4215 &mut self,
4216 bounds: Bounds<Pixels>,
4217 corner_radii: Corners<Pixels>,
4218 shadows: &[BoxShadow],
4219 ) {
4220 self.drop_shadows(bounds, corner_radii, shadows, true);
4221 }
4222
4223 fn drop_shadows(
4224 &mut self,
4225 bounds: Bounds<Pixels>,
4226 corner_radii: Corners<Pixels>,
4227 shadows: &[BoxShadow],
4228 outside: bool,
4229 ) {
4230 self.invalidator.debug_assert_paint();
4231
4232 let scale_factor = self.scale_factor();
4233 let content_mask = self.snapped_content_mask();
4234 let opacity = self.element_opacity_for_bounds(&bounds);
4235 let element_bounds = self.cover_bounds(bounds);
4236 let element_corner_radii = corner_radii.scale(scale_factor);
4237 for shadow in shadows {
4238 if shadow.inset {
4239 continue;
4240 }
4241 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
4242 self.next_frame.scene.insert_primitive(Shadow {
4243 order: 0,
4244 blur_radius: shadow.blur_radius.scale(scale_factor),
4245 bounds: self.cover_bounds(shadow_bounds),
4246 content_mask,
4247 corner_radii: corner_radii.scale(scale_factor),
4248 color: shadow.color.opacity(opacity),
4249 element_bounds,
4250 element_corner_radii,
4251 inset: if outside { 2 } else { 0 },
4252 pad: 0,
4253 });
4254 }
4255 }
4256
4257 pub fn paint_inset_shadows(
4261 &mut self,
4262 bounds: Bounds<Pixels>,
4263 corner_radii: Corners<Pixels>,
4264 shadows: &[BoxShadow],
4265 ) {
4266 self.invalidator.debug_assert_paint();
4267
4268 let scale_factor = self.scale_factor();
4269 let content_mask = self.snapped_content_mask();
4270 let opacity = self.element_opacity_for_bounds(&bounds);
4271 let element_bounds = self.cover_bounds(bounds);
4272 let element_corner_radii = corner_radii.scale(scale_factor);
4273 for shadow in shadows {
4274 if !shadow.inset {
4275 continue;
4276 }
4277 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
4278 let zero = Pixels::ZERO;
4281 let hole_corner_radii = Corners {
4282 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
4283 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
4284 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
4285 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
4286 };
4287 self.next_frame.scene.insert_primitive(Shadow {
4288 order: 0,
4289 blur_radius: shadow.blur_radius.scale(scale_factor),
4290 bounds: self.cover_bounds(hole),
4291 content_mask,
4292 corner_radii: hole_corner_radii.scale(scale_factor),
4293 color: shadow.color.opacity(opacity),
4294 element_bounds,
4295 element_corner_radii,
4296 inset: 1,
4297 pad: 0,
4298 });
4299 }
4300 }
4301
4302 pub fn paint_backdrop_blur(
4308 &mut self,
4309 bounds: Bounds<Pixels>,
4310 corner_radii: Corners<Pixels>,
4311 glass: GlassEffect,
4312 ) {
4313 self.invalidator.debug_assert_paint();
4314 let scale_factor = self.scale_factor();
4315 let content_mask = self.content_mask().scale(scale_factor);
4316 let limit = bounds.size.width.min(bounds.size.height) / 2.;
4320 let corner_radii = Corners {
4321 top_left: corner_radii.top_left.min(limit),
4322 top_right: corner_radii.top_right.min(limit),
4323 bottom_right: corner_radii.bottom_right.min(limit),
4324 bottom_left: corner_radii.bottom_left.min(limit),
4325 };
4326 self.next_frame.scene.insert_primitive(Shadow {
4329 order: 0,
4330 blur_radius: ScaledPixels(0.),
4331 bounds: bounds.scale(scale_factor),
4332 corner_radii: corner_radii.scale(scale_factor),
4333 content_mask,
4334 color: crate::transparent_black(),
4335 element_bounds: bounds.scale(scale_factor),
4336 element_corner_radii: corner_radii.scale(scale_factor),
4337 inset: 0,
4338 pad: 0,
4339 });
4340 self.next_frame.scene.insert_backdrop_blur(BackdropBlur {
4341 order: 0,
4342 blur_radius: glass.blur_radius.scale(scale_factor),
4343 bounds: bounds.scale(scale_factor),
4344 content_mask,
4345 corner_radii: corner_radii.scale(scale_factor),
4346 lens: glass.lens.scale(scale_factor),
4347 reach: glass.reach.scale(scale_factor),
4348 magnify: glass.magnify,
4349 dispersion: glass.dispersion,
4350 gain: glass.gain,
4351 saturation: glass.saturation,
4352 tint: glass.tint,
4353 edge: glass.edge,
4354 edge_width: glass.edge_width.scale(scale_factor),
4355 edge_aa: glass.edge_aa.scale(scale_factor),
4356 opacity: self.element_opacity_for_bounds(&bounds),
4359 });
4360 }
4361
4362 fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
4363 let radii = &quad.corner_radii;
4364 let widths = &quad.border_widths;
4365 let edge_radii = Edges {
4366 top: radii.top_left.max(radii.top_right),
4367 right: radii.top_right.max(radii.bottom_right),
4368 bottom: radii.bottom_left.max(radii.bottom_right),
4369 left: radii.top_left.max(radii.bottom_left),
4370 };
4371
4372 let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
4373 let inset_bounds = |top_left_inset, bottom_right_inset| {
4374 Bounds::from_corners(
4375 quad.bounds.origin + top_left_inset + antialias_inset,
4376 quad.bounds.bottom_right() - bottom_right_inset - antialias_inset,
4377 )
4378 };
4379
4380 let horizontal_band = inset_bounds(
4383 point(widths.left, widths.top.max(edge_radii.top)),
4384 point(widths.right, widths.bottom.max(edge_radii.bottom)),
4385 );
4386 let vertical_band = inset_bounds(
4387 point(widths.left.max(edge_radii.left), widths.top),
4388 point(widths.right.max(edge_radii.right), widths.bottom),
4389 );
4390
4391 let area = |bounds: &Bounds<ScaledPixels>| {
4392 bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.)
4393 };
4394 if area(&horizontal_band) >= area(&vertical_band) {
4395 horizontal_band
4396 } else {
4397 vertical_band
4398 }
4399 }
4400
4401 pub fn paint_quad(&mut self, quad: PaintQuad) {
4411 self.invalidator.debug_assert_paint();
4412
4413 let opacity = self.element_opacity_at(quad.bounds.center());
4414 let background = self
4415 .quad_fade_gradient(quad.bounds, &quad.background)
4416 .unwrap_or_else(|| quad.background.opacity(opacity));
4417 let snapped_bounds = self.snap_bounds(quad.bounds);
4418 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
4419 let quad = Quad {
4420 order: 0,
4421 bounds: snapped_bounds,
4422 content_mask: self.snapped_content_mask(),
4423 background,
4424 border_color: quad.border_color.opacity(opacity),
4425 corner_radii: quad.corner_radii.scale(self.scale_factor()),
4426 border_widths: snapped_border_widths,
4427 border_style: quad.border_style,
4428 };
4429
4430 if !quad.background.is_transparent() {
4431 self.next_frame.scene.insert_primitive(quad);
4432 return;
4433 }
4434
4435 let outer_bounds = quad.bounds;
4438 let inner_bounds = Self::largest_border_interior(&quad);
4439
4440 if inner_bounds.is_empty() {
4441 self.next_frame.scene.insert_primitive(quad);
4442 return;
4443 }
4444
4445 let strips = [
4446 Bounds::from_corners(
4448 outer_bounds.origin,
4449 point(outer_bounds.right(), inner_bounds.top()),
4450 ),
4451 Bounds::from_corners(
4453 point(outer_bounds.left(), inner_bounds.bottom()),
4454 outer_bounds.bottom_right(),
4455 ),
4456 Bounds::from_corners(
4458 point(outer_bounds.left(), inner_bounds.top()),
4459 inner_bounds.bottom_left(),
4460 ),
4461 Bounds::from_corners(
4463 inner_bounds.top_right(),
4464 point(outer_bounds.right(), inner_bounds.bottom()),
4465 ),
4466 ];
4467
4468 for strip in strips {
4469 let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
4470 if !content_mask_bounds.is_empty() {
4471 self.next_frame.scene.insert_primitive(Quad {
4472 content_mask: ContentMask {
4473 bounds: content_mask_bounds,
4474 },
4475 ..quad
4476 });
4477 }
4478 }
4479 }
4480
4481 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
4485 self.invalidator.debug_assert_paint();
4486
4487 let scale_factor = self.scale_factor();
4488 let content_mask = self.content_mask();
4489 let opacity = self.element_opacity_for_bounds(&path.bounds);
4490 path.content_mask = content_mask;
4491 let color: Background = color.into();
4492 path.color = color.opacity(opacity);
4493 self.next_frame
4494 .scene
4495 .insert_primitive(path.scale(scale_factor));
4496 }
4497
4498 pub fn paint_underline(
4502 &mut self,
4503 origin: Point<Pixels>,
4504 width: Pixels,
4505 style: &UnderlineStyle,
4506 ) {
4507 self.invalidator.debug_assert_paint();
4508
4509 let scale_factor = self.scale_factor();
4510 let thickness = self.snap_stroke(style.thickness);
4511 let height = if style.wavy {
4512 ScaledPixels(thickness.0 * 3.)
4513 } else {
4514 thickness
4515 };
4516 let bounds = Bounds {
4517 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4518 size: size(self.snap_stroke(width), height),
4519 };
4520 let element_opacity = self.element_opacity_at(origin);
4521
4522 self.next_frame.scene.insert_primitive(Underline {
4523 order: 0,
4524 pad: 0,
4525 bounds,
4526 content_mask: self.snapped_content_mask(),
4527 color: style.color.unwrap_or_default().opacity(element_opacity),
4528 thickness,
4529 wavy: style.wavy.into(),
4530 });
4531 }
4532
4533 pub fn paint_strikethrough(
4537 &mut self,
4538 origin: Point<Pixels>,
4539 width: Pixels,
4540 style: &StrikethroughStyle,
4541 ) {
4542 self.invalidator.debug_assert_paint();
4543
4544 let scale_factor = self.scale_factor();
4545 let height = style.thickness;
4546 let bounds = Bounds {
4547 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4548 size: size(self.snap_stroke(width), self.snap_stroke(height)),
4549 };
4550 let opacity = self.element_opacity_at(origin);
4551
4552 self.next_frame.scene.insert_primitive(Underline {
4553 order: 0,
4554 pad: 0,
4555 bounds,
4556 content_mask: self.snapped_content_mask(),
4557 thickness: self.snap_stroke(style.thickness),
4558 color: style.color.unwrap_or_default().opacity(opacity),
4559 wavy: false.into(),
4560 });
4561 }
4562
4563 pub fn paint_glyph(
4572 &mut self,
4573 origin: Point<Pixels>,
4574 font_id: FontId,
4575 glyph_id: GlyphId,
4576 font_size: Pixels,
4577 color: Hsla,
4578 ) -> Result<()> {
4579 self.invalidator.debug_assert_paint();
4580
4581 let element_opacity = self.element_opacity_for_bounds(&Bounds {
4582 origin,
4583 size: size(font_size * 0.6, font_size),
4584 });
4585 let scale_factor = self.scale_factor();
4586 let glyph_origin = origin.scale(scale_factor);
4587
4588 let quantized_origin = Point::new(
4589 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
4590 / SUBPIXEL_VARIANTS_X as f32,
4591 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
4592 / SUBPIXEL_VARIANTS_Y as f32,
4593 );
4594 let subpixel_variant = Point::new(
4595 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
4596 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
4597 );
4598 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
4599 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
4600 let dilation = self.text_system().glyph_dilation_for_color(color);
4601 let params = RenderGlyphParams {
4602 font_id,
4603 glyph_id,
4604 font_size,
4605 subpixel_variant,
4606 scale_factor,
4607 is_emoji: false,
4608 subpixel_rendering,
4609 dilation,
4610 };
4611
4612 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4613 if !raster_bounds.is_zero() {
4614 let tile = self
4615 .sprite_atlas
4616 .get_or_insert_with(¶ms.clone().into(), &mut || {
4617 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4618 Ok(Some((size, Cow::Owned(bytes))))
4619 })?
4620 .expect("Callback above only errors or returns Some");
4621 let bounds = Bounds {
4622 origin: integer_origin + raster_bounds.origin.map(Into::into),
4623 size: tile.bounds.size.map(Into::into),
4624 };
4625 let content_mask = self.snapped_content_mask();
4626
4627 if subpixel_rendering {
4628 self.next_frame.scene.insert_primitive(SubpixelSprite {
4629 order: 0,
4630 pad: 0,
4631 bounds,
4632 content_mask,
4633 color: color.opacity(element_opacity),
4634 tile,
4635 transformation: TransformationMatrix::unit(),
4636 });
4637 } else {
4638 self.next_frame.scene.insert_primitive(MonochromeSprite {
4639 order: 0,
4640 pad: 0,
4641 bounds,
4642 content_mask,
4643 color: color.opacity(element_opacity),
4644 tile,
4645 transformation: TransformationMatrix::unit(),
4646 });
4647 }
4648 }
4649 Ok(())
4650 }
4651
4652 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
4653 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
4654 return false;
4655 }
4656
4657 if !self.platform_window.is_subpixel_rendering_supported() {
4658 return false;
4659 }
4660
4661 let mode = match self.text_rendering_mode.get() {
4662 TextRenderingMode::PlatformDefault => self
4663 .text_system()
4664 .recommended_rendering_mode(font_id, font_size),
4665 mode => mode,
4666 };
4667
4668 mode == TextRenderingMode::Subpixel
4669 }
4670
4671 pub fn paint_emoji(
4680 &mut self,
4681 origin: Point<Pixels>,
4682 font_id: FontId,
4683 glyph_id: GlyphId,
4684 font_size: Pixels,
4685 ) -> Result<()> {
4686 self.invalidator.debug_assert_paint();
4687
4688 let scale_factor = self.scale_factor();
4689 let glyph_origin = origin.scale(scale_factor);
4690 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
4691 let params = RenderGlyphParams {
4692 font_id,
4693 glyph_id,
4694 font_size,
4695 subpixel_variant: Default::default(),
4696 scale_factor,
4697 is_emoji: true,
4698 subpixel_rendering: false,
4699 dilation: 0,
4700 };
4701
4702 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4703 if !raster_bounds.is_zero() {
4704 let tile = self
4705 .sprite_atlas
4706 .get_or_insert_with(¶ms.clone().into(), &mut || {
4707 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4708 Ok(Some((size, Cow::Owned(bytes))))
4709 })?
4710 .expect("Callback above only errors or returns Some");
4711
4712 let bounds = Bounds {
4713 origin: integer_origin + raster_bounds.origin.map(Into::into),
4714 size: tile.bounds.size.map(Into::into),
4715 };
4716 let content_mask = self.snapped_content_mask();
4717 let opacity = self.element_opacity_for_bounds(&Bounds {
4718 origin,
4719 size: size(font_size * 0.6, font_size),
4720 });
4721
4722 self.next_frame.scene.insert_primitive(PolychromeSprite {
4723 order: 0,
4724 pad: 0,
4725 grayscale: false.into(),
4726 bounds,
4727 corner_radii: Default::default(),
4728 content_mask,
4729 tile,
4730 opacity,
4731 });
4732 }
4733 Ok(())
4734 }
4735
4736 pub fn paint_svg(
4740 &mut self,
4741 bounds: Bounds<Pixels>,
4742 path: SharedString,
4743 mut data: Option<&[u8]>,
4744 transformation: TransformationMatrix,
4745 color: Hsla,
4746 cx: &App,
4747 ) -> Result<()> {
4748 self.invalidator.debug_assert_paint();
4749
4750 let element_opacity = self.element_opacity_for_bounds(&bounds);
4751 let bounds = self.snap_bounds(bounds);
4752
4753 let params = RenderSvgParams {
4754 path,
4755 size: bounds.size.map(|pixels| {
4756 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
4757 }),
4758 };
4759
4760 let Some(tile) =
4761 self.sprite_atlas
4762 .get_or_insert_with(¶ms.clone().into(), &mut || {
4763 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
4764 else {
4765 return Ok(None);
4766 };
4767 Ok(Some((size, Cow::Owned(bytes))))
4768 })?
4769 else {
4770 return Ok(());
4771 };
4772 let content_mask = self.snapped_content_mask();
4773 let svg_bounds = Bounds {
4774 origin: bounds.center()
4775 - Point::new(
4776 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4777 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4778 ),
4779 size: tile
4780 .bounds
4781 .size
4782 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
4783 };
4784 let final_bounds = svg_bounds
4785 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
4786 .map_size(|size| size.ceil());
4787
4788 self.next_frame.scene.insert_primitive(MonochromeSprite {
4789 order: 0,
4790 pad: 0,
4791 bounds: final_bounds,
4792 content_mask,
4793 color: color.opacity(element_opacity),
4794 tile,
4795 transformation,
4796 });
4797
4798 Ok(())
4799 }
4800
4801 pub fn paint_image(
4810 &mut self,
4811 bounds: Bounds<Pixels>,
4812 image_bounds: Bounds<Pixels>,
4813 corner_radii: Corners<Pixels>,
4814 data: Arc<RenderImage>,
4815 frame_index: usize,
4816 grayscale: bool,
4817 ) -> Result<()> {
4818 self.invalidator.debug_assert_paint();
4819
4820 let fade_bounds = bounds;
4821 let visible_bounds = bounds.intersect(&image_bounds);
4822 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
4823 return Ok(());
4824 }
4825 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
4826 return Ok(());
4827 }
4828
4829 let params = RenderImageParams {
4830 image_id: data.id,
4831 frame_index,
4832 };
4833
4834 let tile = self
4835 .sprite_atlas
4836 .get_or_insert_with(¶ms.into(), &mut || {
4837 Ok(Some((
4838 data.size(frame_index),
4839 Cow::Borrowed(
4840 data.as_bytes(frame_index)
4841 .expect("It's the caller's job to pass a valid frame index"),
4842 ),
4843 )))
4844 })?
4845 .expect("Callback above only returns Some");
4846
4847 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
4848
4849 let sub_tile = if visible_bounds == image_bounds {
4850 tile
4851 } else {
4852 let x_offset_ratio =
4853 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
4854 let y_offset_ratio =
4855 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
4856 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
4857 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
4858
4859 let tile_origin_x = tile.bounds.origin.x.0;
4860 let tile_origin_y = tile.bounds.origin.y.0;
4861 let tile_width = tile.bounds.size.width.0;
4862 let tile_height = tile.bounds.size.height.0;
4863
4864 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
4865 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
4866 let sub_width = (width_ratio * tile_width as f32).round() as i32;
4867 let sub_height = (height_ratio * tile_height as f32).round() as i32;
4868
4869 let max_x = tile_origin_x + tile_width;
4870 let max_y = tile_origin_y + tile_height;
4871
4872 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
4873 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
4874 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
4875 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
4876
4877 AtlasTile {
4878 bounds: Bounds {
4879 origin: point(
4880 DevicePixels(clamped_origin_x),
4881 DevicePixels(clamped_origin_y),
4882 ),
4883 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
4884 },
4885 ..tile
4886 }
4887 };
4888
4889 let content_mask = self.snapped_content_mask();
4890 let corner_radii = corner_radii
4891 .clamp_radii_for_quad_size(visible_bounds.size)
4892 .scale(self.scale_factor());
4893 let opacity = self.element_opacity_for_bounds(&fade_bounds);
4894
4895 self.next_frame.scene.insert_primitive(PolychromeSprite {
4896 order: 0,
4897 pad: 0,
4898 grayscale: grayscale.into(),
4899 bounds: visible_bounds_snapped,
4900 content_mask,
4901 corner_radii,
4902 tile: sub_tile,
4903 opacity,
4904 });
4905 Ok(())
4906 }
4907
4908 #[cfg(target_os = "macos")]
4912 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
4913 use crate::PaintSurface;
4914
4915 self.invalidator.debug_assert_paint();
4916
4917 let bounds = self.snap_bounds(bounds);
4918 let content_mask = self.snapped_content_mask();
4919 self.next_frame.scene.insert_primitive(PaintSurface {
4920 order: 0,
4921 bounds,
4922 content_mask,
4923 image_buffer,
4924 });
4925 }
4926
4927 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
4929 for frame_index in 0..data.frame_count() {
4930 let params = RenderImageParams {
4931 image_id: data.id,
4932 frame_index,
4933 };
4934
4935 self.sprite_atlas.remove(¶ms.clone().into());
4936 }
4937
4938 Ok(())
4939 }
4940
4941 #[cfg(any(test, feature = "test-support"))]
4943 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
4944 data.frame_count() > 0
4945 && (0..data.frame_count()).all(|frame_index| {
4946 self.sprite_atlas.contains(
4947 &RenderImageParams {
4948 image_id: data.id,
4949 frame_index,
4950 }
4951 .into(),
4952 )
4953 })
4954 }
4955
4956 #[must_use]
4962 pub fn request_layout(
4963 &mut self,
4964 style: Style,
4965 children: impl IntoIterator<Item = LayoutId>,
4966 cx: &mut App,
4967 ) -> LayoutId {
4968 self.invalidator.debug_assert_prepaint();
4969
4970 cx.layout_id_buffer.clear();
4971 cx.layout_id_buffer.extend(children);
4972 let rem_size = self.rem_size();
4973 let scale_factor = self.scale_factor();
4974
4975 self.layout_engine.as_mut().unwrap().request_layout(
4976 style,
4977 rem_size,
4978 scale_factor,
4979 &cx.layout_id_buffer,
4980 )
4981 }
4982
4983 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
4992 where
4993 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
4994 + 'static,
4995 {
4996 self.invalidator.debug_assert_prepaint();
4997
4998 let rem_size = self.rem_size();
4999 let scale_factor = self.scale_factor();
5000 self.layout_engine
5001 .as_mut()
5002 .unwrap()
5003 .request_measured_layout(style, rem_size, scale_factor, measure)
5004 }
5005
5006 pub fn compute_layout(
5012 &mut self,
5013 layout_id: LayoutId,
5014 available_space: Size<AvailableSpace>,
5015 cx: &mut App,
5016 ) {
5017 self.invalidator.debug_assert_prepaint();
5018
5019 let mut layout_engine = self.layout_engine.take().unwrap();
5020 layout_engine.compute_layout(layout_id, available_space, self, cx);
5021 self.layout_engine = Some(layout_engine);
5022 }
5023
5024 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
5029 self.invalidator.debug_assert_prepaint();
5030
5031 let scale_factor = self.scale_factor();
5032 let mut bounds = self
5033 .layout_engine
5034 .as_mut()
5035 .unwrap()
5036 .layout_bounds(layout_id, scale_factor)
5037 .map(Into::into);
5038 let snapped_offset = self.pixel_snap_point(self.element_offset());
5039 bounds.origin += snapped_offset;
5040 bounds
5041 }
5042
5043 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
5049 self.invalidator.debug_assert_prepaint();
5050
5051 let content_mask = self.content_mask();
5052 let mut id = self.next_hitbox_id;
5053 self.next_hitbox_id = self.next_hitbox_id.next();
5054 let hitbox = Hitbox {
5055 id,
5056 bounds,
5057 content_mask,
5058 behavior,
5059 };
5060 self.next_frame.hitboxes.push(hitbox.clone());
5061 hitbox
5062 }
5063
5064 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
5068 self.invalidator.debug_assert_paint();
5069 self.next_frame.window_control_hitboxes.push((area, hitbox));
5070 }
5071
5072 pub fn set_key_context(&mut self, context: KeyContext) {
5077 self.invalidator.debug_assert_paint();
5078 self.next_frame.dispatch_tree.set_key_context(context);
5079 }
5080
5081 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
5086 self.invalidator.debug_assert_prepaint();
5087 if focus_handle.is_focused(self) {
5088 self.next_frame.focus = Some(focus_handle.id);
5089 }
5090 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
5091 }
5092
5093 pub fn set_view_id(&mut self, view_id: EntityId) {
5099 self.invalidator.debug_assert_prepaint();
5100 self.next_frame.dispatch_tree.set_view_id(view_id);
5101 }
5102
5103 pub fn current_view(&self) -> EntityId {
5105 self.invalidator.debug_assert_paint_or_prepaint();
5106 self.rendered_entity_stack.last().copied().unwrap()
5107 }
5108
5109 #[inline]
5110 pub(crate) fn with_rendered_view<R>(
5111 &mut self,
5112 id: EntityId,
5113 f: impl FnOnce(&mut Self) -> R,
5114 ) -> R {
5115 self.rendered_entity_stack.push(id);
5116 let result = f(self);
5117 self.rendered_entity_stack.pop();
5118 result
5119 }
5120
5121 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
5123 where
5124 F: FnOnce(&mut Self) -> R,
5125 {
5126 if let Some(image_cache) = image_cache {
5127 self.image_cache_stack.push(image_cache);
5128 let result = f(self);
5129 self.image_cache_stack.pop();
5130 result
5131 } else {
5132 f(self)
5133 }
5134 }
5135
5136 pub fn handle_input(
5145 &mut self,
5146 focus_handle: &FocusHandle,
5147 input_handler: impl InputHandler,
5148 cx: &App,
5149 ) {
5150 self.invalidator.debug_assert_paint();
5151
5152 if focus_handle.is_focused(self) {
5153 let cx = self.to_async(cx);
5154 self.next_frame
5155 .input_handlers
5156 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
5157 }
5158 }
5159
5160 fn apply_text_input_configuration(&mut self, cx: &mut App) {
5165 let configuration = match self.platform_window.take_input_handler() {
5166 Some(mut input_handler) => {
5167 let configuration = input_handler.text_input_configuration(self, cx);
5168 self.platform_window.set_input_handler(input_handler);
5169 configuration
5170 }
5171 None => TextInputConfiguration::default(),
5172 };
5173 if self.last_text_input_configuration.as_ref() != Some(&configuration) {
5174 self.platform_window
5175 .set_text_input_configuration(configuration.clone());
5176 self.last_text_input_configuration = Some(configuration);
5177 }
5178 }
5179
5180 pub fn on_mouse_event<Event: MouseEvent>(
5186 &mut self,
5187 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5188 ) {
5189 self.invalidator.debug_assert_paint();
5190
5191 self.next_frame.mouse_listeners.push(Some(Box::new(
5192 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
5193 if let Some(event) = event.downcast_ref() {
5194 listener(event, phase, window, cx)
5195 }
5196 },
5197 )));
5198 }
5199
5200 pub fn on_key_event<Event: KeyEvent>(
5209 &mut self,
5210 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5211 ) {
5212 self.invalidator.debug_assert_paint();
5213
5214 self.next_frame.dispatch_tree.on_key_event(Rc::new(
5215 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
5216 if let Some(event) = event.downcast_ref::<Event>() {
5217 listener(event, phase, window, cx)
5218 }
5219 },
5220 ));
5221 }
5222
5223 pub fn on_modifiers_changed(
5230 &mut self,
5231 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
5232 ) {
5233 self.invalidator.debug_assert_paint();
5234
5235 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
5236 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
5237 listener(event, window, cx)
5238 },
5239 ));
5240 }
5241
5242 pub fn on_focus_in(
5246 &mut self,
5247 handle: &FocusHandle,
5248 cx: &mut App,
5249 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
5250 ) -> Subscription {
5251 let focus_id = handle.id;
5252 let (subscription, activate) =
5253 self.new_focus_listener(Box::new(move |event, window, cx| {
5254 if event.is_focus_in(focus_id) {
5255 listener(window, cx);
5256 }
5257 true
5258 }));
5259 cx.defer(move |_| activate());
5260 subscription
5261 }
5262
5263 pub fn on_focus_out(
5266 &mut self,
5267 handle: &FocusHandle,
5268 cx: &mut App,
5269 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
5270 ) -> Subscription {
5271 let focus_id = handle.id;
5272 let (subscription, activate) =
5273 self.new_focus_listener(Box::new(move |event, window, cx| {
5274 if let Some(blurred_id) = event.previous_focus_path.last().copied()
5275 && event.is_focus_out(focus_id)
5276 {
5277 let event = FocusOutEvent {
5278 blurred: WeakFocusHandle {
5279 id: blurred_id,
5280 handles: Arc::downgrade(&cx.focus_handles),
5281 },
5282 };
5283 listener(event, window, cx)
5284 }
5285 true
5286 }));
5287 cx.defer(move |_| activate());
5288 subscription
5289 }
5290
5291 fn reset_cursor_style(&self, cx: &mut App) {
5292 if self.is_window_hovered() {
5294 let style = self
5295 .rendered_frame
5296 .cursor_style(self)
5297 .unwrap_or(CursorStyle::Arrow);
5298 cx.platform.set_cursor_style(style);
5299 }
5300 }
5301
5302 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
5305 let keystroke = keystroke.with_simulated_ime();
5306 let result = self.dispatch_event(
5307 PlatformInput::KeyDown(KeyDownEvent {
5308 keystroke: keystroke.clone(),
5309 is_held: false,
5310 prefer_character_input: false,
5311 }),
5312 cx,
5313 );
5314 if !result.propagate {
5315 return true;
5316 }
5317
5318 if let Some(input) = keystroke.key_char
5319 && let Some(mut input_handler) = self.platform_window.take_input_handler()
5320 {
5321 input_handler.dispatch_input(&input, self, cx);
5322 self.platform_window.set_input_handler(input_handler);
5323 return true;
5324 }
5325
5326 false
5327 }
5328
5329 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
5332 self.highest_precedence_binding_for_action(action)
5333 .map(|binding| {
5334 binding
5335 .keystrokes()
5336 .iter()
5337 .map(ToString::to_string)
5338 .collect::<Vec<_>>()
5339 .join(" ")
5340 })
5341 .unwrap_or_else(|| action.name().to_string())
5342 }
5343
5344 #[profiling::function]
5346 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
5347 #[cfg(feature = "profiler")]
5348 self.window_profiler.begin_input(event.kind_name());
5349 let update_count_before = self.invalidator.update_count();
5350 let old_modality = self.last_input_modality;
5354 self.last_input_modality = match &event {
5355 PlatformInput::KeyDown(_) => InputModality::Keyboard,
5356 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
5357 PlatformInput::Touch(_) => InputModality::Touch,
5358 _ => self.last_input_modality,
5359 };
5360 if self.last_input_modality != old_modality {
5361 self.refresh();
5362 }
5363
5364 cx.propagate_event = true;
5366 self.default_prevented = false;
5368
5369 let event = match event {
5370 PlatformInput::MouseMove(mouse_move) => {
5373 self.mouse_position = mouse_move.position;
5374 self.modifiers = mouse_move.modifiers;
5375 PlatformInput::MouseMove(mouse_move)
5376 }
5377 PlatformInput::MouseDown(mouse_down) => {
5378 self.mouse_position = mouse_down.position;
5379 self.modifiers = mouse_down.modifiers;
5380 PlatformInput::MouseDown(mouse_down)
5381 }
5382 PlatformInput::MouseUp(mouse_up) => {
5383 self.mouse_position = mouse_up.position;
5384 self.modifiers = mouse_up.modifiers;
5385 PlatformInput::MouseUp(mouse_up)
5386 }
5387 PlatformInput::MousePressure(mouse_pressure) => {
5388 PlatformInput::MousePressure(mouse_pressure)
5389 }
5390 PlatformInput::MouseExited(mouse_exited) => {
5391 self.modifiers = mouse_exited.modifiers;
5392 PlatformInput::MouseExited(mouse_exited)
5393 }
5394 PlatformInput::ModifiersChanged(modifiers_changed) => {
5395 self.modifiers = modifiers_changed.modifiers;
5396 self.capslock = modifiers_changed.capslock;
5397 PlatformInput::ModifiersChanged(modifiers_changed)
5398 }
5399 PlatformInput::ScrollWheel(scroll_wheel) => {
5400 self.mouse_position = scroll_wheel.position;
5401 self.modifiers = scroll_wheel.modifiers;
5402 PlatformInput::ScrollWheel(scroll_wheel)
5403 }
5404 PlatformInput::Pinch(pinch) => {
5405 self.mouse_position = pinch.position;
5406 self.modifiers = pinch.modifiers;
5407 PlatformInput::Pinch(pinch)
5408 }
5409 PlatformInput::FileDrop(file_drop) => match file_drop {
5412 FileDropEvent::Entered { position, paths } => {
5413 self.mouse_position = position;
5414 let source_window = self.handle.window_id();
5415 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
5416 cx.active_drag = Some(AnyDrag {
5417 value: Arc::new(paths.clone()),
5418 view: cx.new(|_| paths).into(),
5419 cursor_offset: position,
5420 cursor_style: None,
5421 external_payload_source: None,
5422 });
5423 }
5424 PlatformInput::MouseMove(MouseMoveEvent {
5425 position,
5426 pressed_button: Some(MouseButton::Left),
5427 modifiers: Modifiers::default(),
5428 })
5429 }
5430 FileDropEvent::Pending { position } => {
5431 self.mouse_position = position;
5432 PlatformInput::MouseMove(MouseMoveEvent {
5433 position,
5434 pressed_button: Some(MouseButton::Left),
5435 modifiers: Modifiers::default(),
5436 })
5437 }
5438 FileDropEvent::Submit { position } => {
5439 cx.activate(true);
5440 self.mouse_position = position;
5441 PlatformInput::MouseUp(MouseUpEvent {
5442 button: MouseButton::Left,
5443 position,
5444 modifiers: Modifiers::default(),
5445 click_count: 1,
5446 })
5447 }
5448 FileDropEvent::Exited => {
5449 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
5450 cx.active_drag.take();
5451 }
5452 self.refresh();
5453 PlatformInput::FileDrop(FileDropEvent::Exited)
5454 }
5455 FileDropEvent::Ended => {
5456 cx.end_platform_drag(self.handle.window_id());
5457 self.refresh();
5458 PlatformInput::FileDrop(FileDropEvent::Ended)
5459 }
5460 },
5461 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
5462 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
5463 };
5464
5465 if let Some(any_mouse_event) = event.mouse_event() {
5466 self.dispatch_mouse_event(any_mouse_event, cx);
5467 } else if let Some(any_key_event) = event.keyboard_event() {
5468 self.dispatch_key_event(any_key_event, cx);
5469 } else if let Some(touch_event) = event.touch_event() {
5470 self.dispatch_touch_event(touch_event, cx);
5471 }
5472
5473 self.promote_external_drag_to_platform(&event, cx);
5476
5477 let caused_invalidation = self.invalidator.update_count() > update_count_before;
5478 if caused_invalidation {
5479 self.input_rate_tracker.borrow_mut().record_input();
5480 }
5481 #[cfg(feature = "profiler")]
5482 self.window_profiler.end_input(caused_invalidation);
5483
5484 DispatchEventResult {
5485 propagate: cx.propagate_event,
5486 default_prevented: self.default_prevented,
5487 }
5488 }
5489
5490 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
5491 let PlatformInput::MouseMove(mouse_move) = event else {
5492 return;
5493 };
5494 if mouse_move.pressed_button != Some(MouseButton::Left) {
5495 return;
5496 }
5497 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
5498 return;
5499 }
5500 if !self.platform_window.can_start_external_drag() {
5501 return;
5502 }
5503 let Some(payload_source) = cx
5504 .active_drag
5505 .as_mut()
5506 .and_then(|drag| drag.external_payload_source.take())
5507 else {
5508 return;
5509 };
5510 let Some(payload) = payload_source(self, cx) else {
5511 return;
5512 };
5513 if self.platform_window.start_external_drag(&payload)
5514 && cx.hand_active_drag_to_platform(self.handle.window_id())
5515 {
5516 self.refresh();
5517 }
5518 }
5519
5520 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
5524 let recognized_gestures = self.touch_gestures.handle_event(event);
5525 let mut tapped = false;
5526 for gesture in recognized_gestures {
5527 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
5528 self.dispatch_recognized_touch_gesture(gesture, cx);
5529 }
5530 if tapped && self.invalidator.is_dirty() {
5536 self.draw(cx).clear(cx);
5537 }
5538 if self.touch_gestures.has_momentum() {
5539 self.schedule_touch_momentum_tick();
5540 }
5541 }
5542
5543 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
5544 match gesture {
5545 RecognizedTouchGesture::Scroll(scroll_wheel) => {
5546 self.mouse_position = scroll_wheel.position;
5547 cx.propagate_event = true;
5548 self.dispatch_mouse_event(&scroll_wheel, cx);
5549 }
5550 RecognizedTouchGesture::Tap { down, up } => {
5551 self.mouse_position = up.position;
5552 cx.propagate_event = true;
5553 self.dispatch_mouse_event(&down, cx);
5554 cx.propagate_event = true;
5555 self.dispatch_mouse_event(&up, cx);
5556 }
5557 }
5558 }
5559
5560 fn schedule_touch_momentum_tick(&mut self) {
5561 self.on_next_frame(|window, cx| {
5562 if let Some(gesture) = window.touch_gestures.tick_momentum() {
5563 window.dispatch_recognized_touch_gesture(gesture, cx);
5564 }
5565 if window.touch_gestures.has_momentum() {
5566 window.schedule_touch_momentum_tick();
5567 }
5568 });
5569 }
5570
5571 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5572 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
5573 if hit_test != self.mouse_hit_test {
5574 self.mouse_hit_test = hit_test;
5575 self.reset_cursor_style(cx);
5576 }
5577
5578 #[cfg(any(feature = "inspector", debug_assertions))]
5579 if self.is_inspector_picking(cx) {
5580 self.handle_inspector_mouse_event(event, cx);
5581 return;
5583 }
5584
5585 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
5586
5587 for listener in &mut mouse_listeners {
5590 let listener = listener.as_mut().unwrap();
5591 listener(event, DispatchPhase::Capture, self, cx);
5592 if !cx.propagate_event {
5593 break;
5594 }
5595 }
5596
5597 if cx.propagate_event {
5599 for listener in mouse_listeners.iter_mut().rev() {
5600 let listener = listener.as_mut().unwrap();
5601 listener(event, DispatchPhase::Bubble, self, cx);
5602 if !cx.propagate_event {
5603 break;
5604 }
5605 }
5606 }
5607
5608 self.rendered_frame.mouse_listeners = mouse_listeners;
5609
5610 if cx.has_active_drag() {
5611 if event.is::<MouseMoveEvent>() {
5612 self.refresh();
5615 } else if event.is::<MouseUpEvent>() {
5616 cx.active_drag = None;
5619 self.refresh();
5620 }
5621 }
5622
5623 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
5625 self.captured_hitbox = None;
5626 }
5627 }
5628
5629 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
5630 if self.invalidator.is_dirty() {
5631 self.draw(cx).clear(cx);
5632 }
5633
5634 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5635 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5636
5637 let mut keystroke: Option<Keystroke> = None;
5638
5639 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
5640 if event.modifiers.number_of_modifiers() == 0
5641 && self.pending_modifier.modifiers.number_of_modifiers() == 1
5642 && !self.pending_modifier.saw_other_input
5643 {
5644 let key = match self.pending_modifier.modifiers {
5645 modifiers if modifiers.shift => Some("shift"),
5646 modifiers if modifiers.control => Some("control"),
5647 modifiers if modifiers.alt => Some("alt"),
5648 modifiers if modifiers.platform => Some("platform"),
5649 modifiers if modifiers.function => Some("function"),
5650 _ => None,
5651 };
5652 if let Some(key) = key {
5653 keystroke = Some(Keystroke {
5654 key: key.to_string(),
5655 key_char: None,
5656 modifiers: Modifiers::default(),
5657 });
5658 }
5659 }
5660
5661 if self.pending_modifier.modifiers.number_of_modifiers() == 0
5662 && event.modifiers.number_of_modifiers() == 1
5663 {
5664 self.pending_modifier.saw_other_input = false
5665 } else if event.modifiers.number_of_modifiers() > 1 {
5666 self.pending_modifier.saw_other_input = true
5667 }
5668 self.pending_modifier.modifiers = event.modifiers
5669 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
5670 self.pending_modifier.saw_other_input = true;
5671 keystroke = Some(key_down_event.keystroke.clone());
5672 if key_down_event.keystroke.key_char.is_some()
5673 && matches!(
5674 cx.cursor_hide_mode,
5675 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
5676 )
5677 {
5678 cx.platform.hide_cursor_until_mouse_moves();
5679 }
5680 }
5681
5682 let Some(keystroke) = keystroke else {
5683 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5684 return;
5685 };
5686
5687 cx.propagate_event = true;
5688 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
5689 if !cx.propagate_event {
5690 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5691 return;
5692 }
5693
5694 let mut currently_pending = self.pending_input.take().unwrap_or_default();
5695 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
5696 currently_pending = PendingInput::default();
5697 }
5698
5699 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
5700 currently_pending.keystrokes,
5701 keystroke,
5702 &dispatch_path,
5703 );
5704
5705 if !match_result.to_replay.is_empty() {
5706 self.replay_pending_input(match_result.to_replay, cx);
5707 cx.propagate_event = true;
5708 }
5709
5710 if !match_result.pending.is_empty() {
5711 currently_pending.timer.take();
5712 currently_pending.keystrokes = match_result.pending;
5713 currently_pending.focus = self.focus;
5714
5715 let text_input_requires_timeout = event
5716 .downcast_ref::<KeyDownEvent>()
5717 .filter(|key_down| key_down.keystroke.key_char.is_some())
5718 .and_then(|_| self.platform_window.take_input_handler())
5719 .map_or(false, |mut input_handler| {
5720 let accepts = input_handler.accepts_text_input(self, cx);
5721 self.platform_window.set_input_handler(input_handler);
5722 accepts
5723 });
5724
5725 currently_pending.needs_timeout |=
5726 match_result.pending_has_binding || text_input_requires_timeout;
5727
5728 if currently_pending.needs_timeout {
5729 currently_pending.timer = Some(self.spawn(cx, async move |cx| {
5730 cx.background_executor.timer(Duration::from_secs(1)).await;
5731 cx.update(move |window, cx| {
5732 let Some(currently_pending) = window
5733 .pending_input
5734 .take()
5735 .filter(|pending| pending.focus == window.focus)
5736 else {
5737 return;
5738 };
5739
5740 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
5741 let dispatch_path =
5742 window.rendered_frame.dispatch_tree.dispatch_path(node_id);
5743
5744 let to_replay = window
5745 .rendered_frame
5746 .dispatch_tree
5747 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
5748
5749 window.pending_input_changed(cx);
5750 window.replay_pending_input(to_replay, cx)
5751 })
5752 .log_err();
5753 }));
5754 } else {
5755 currently_pending.timer = None;
5756 }
5757 self.pending_input = Some(currently_pending);
5758 self.pending_input_changed(cx);
5759 cx.propagate_event = false;
5760 return;
5761 }
5762
5763 let skip_bindings = event
5764 .downcast_ref::<KeyDownEvent>()
5765 .filter(|key_down_event| key_down_event.prefer_character_input)
5766 .map(|_| {
5767 self.platform_window
5768 .take_input_handler()
5769 .map_or(false, |mut input_handler| {
5770 let accepts = input_handler.accepts_text_input(self, cx);
5771 self.platform_window.set_input_handler(input_handler);
5772 accepts
5775 })
5776 })
5777 .unwrap_or(false);
5778
5779 if !skip_bindings {
5780 for binding in match_result.bindings {
5781 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5782 if !cx.propagate_event {
5783 self.dispatch_keystroke_observers(
5784 event,
5785 Some(binding.action),
5786 match_result.context_stack,
5787 cx,
5788 );
5789 self.pending_input_changed(cx);
5790 return;
5791 }
5792 }
5793 }
5794
5795 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
5796 self.pending_input_changed(cx);
5797 }
5798
5799 fn finish_dispatch_key_event(
5800 &mut self,
5801 event: &dyn Any,
5802 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
5803 context_stack: Vec<KeyContext>,
5804 cx: &mut App,
5805 ) {
5806 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
5807 if !cx.propagate_event {
5808 return;
5809 }
5810
5811 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
5812 if !cx.propagate_event {
5813 return;
5814 }
5815
5816 self.dispatch_keystroke_observers(event, None, context_stack, cx);
5817 }
5818
5819 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
5820 self.pending_input_observers
5821 .clone()
5822 .retain(&(), |callback| callback(self, cx));
5823 }
5824
5825 fn defer_pending_input_changed(&self, cx: &mut App) {
5826 let window_handle = self.handle;
5829 cx.defer(move |cx| {
5830 window_handle
5831 .update(cx, |_, window, cx| {
5832 window.pending_input_changed(cx);
5833 })
5834 .ok();
5835 });
5836 }
5837
5838 fn dispatch_key_down_up_event(
5839 &mut self,
5840 event: &dyn Any,
5841 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5842 cx: &mut App,
5843 ) {
5844 for node_id in dispatch_path {
5846 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5847
5848 for key_listener in node.key_listeners.clone() {
5849 key_listener(event, DispatchPhase::Capture, self, cx);
5850 if !cx.propagate_event {
5851 return;
5852 }
5853 }
5854 }
5855
5856 for node_id in dispatch_path.iter().rev() {
5858 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5860 for key_listener in node.key_listeners.clone() {
5861 key_listener(event, DispatchPhase::Bubble, self, cx);
5862 if !cx.propagate_event {
5863 return;
5864 }
5865 }
5866 }
5867 }
5868
5869 fn dispatch_modifiers_changed_event(
5870 &mut self,
5871 event: &dyn Any,
5872 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5873 cx: &mut App,
5874 ) {
5875 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
5876 return;
5877 };
5878 for node_id in dispatch_path.iter().rev() {
5879 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5880 for listener in node.modifiers_changed_listeners.clone() {
5881 listener(event, self, cx);
5882 if !cx.propagate_event {
5883 return;
5884 }
5885 }
5886 }
5887 }
5888
5889 fn active_pending_input(&self) -> Option<&PendingInput> {
5892 self.pending_input
5893 .as_ref()
5894 .filter(|pending_input| pending_input.focus == self.focus)
5895 }
5896
5897 pub fn has_pending_keystrokes(&self) -> bool {
5899 self.active_pending_input().is_some()
5900 }
5901
5902 #[cfg(test)]
5903 pub(crate) fn pending_input_is_none(&self) -> bool {
5904 self.pending_input.is_none()
5905 }
5906
5907 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
5908 if self.pending_input.take().is_some() {
5909 self.defer_pending_input_changed(cx);
5910 }
5911 }
5912
5913 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
5915 self.active_pending_input()
5916 .map(|pending_input| pending_input.keystrokes.as_slice())
5917 }
5918
5919 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
5920 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5921 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5922
5923 'replay: for replay in replays {
5924 let event = KeyDownEvent {
5925 keystroke: replay.keystroke.clone(),
5926 is_held: false,
5927 prefer_character_input: true,
5928 };
5929
5930 cx.propagate_event = true;
5931 for binding in replay.bindings {
5932 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5933 if !cx.propagate_event {
5934 self.dispatch_keystroke_observers(
5935 &event,
5936 Some(binding.action),
5937 Vec::default(),
5938 cx,
5939 );
5940 continue 'replay;
5941 }
5942 }
5943
5944 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
5945 if !cx.propagate_event {
5946 continue 'replay;
5947 }
5948 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
5949 && let Some(mut input_handler) = self.platform_window.take_input_handler()
5950 {
5951 input_handler.dispatch_input(&input, self, cx);
5952 self.platform_window.set_input_handler(input_handler)
5953 }
5954 }
5955 }
5956
5957 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
5958 focus_id
5959 .and_then(|focus_id| {
5960 self.rendered_frame
5961 .dispatch_tree
5962 .focusable_node_id(focus_id)
5963 })
5964 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
5965 }
5966
5967 fn dispatch_action_on_node(
5968 &mut self,
5969 node_id: DispatchNodeId,
5970 action: &dyn Action,
5971 cx: &mut App,
5972 ) {
5973 self.dispatch_action_on_node_inner(node_id, action, cx);
5974
5975 if !cx.propagate_event
5976 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
5977 && self.last_input_was_keyboard()
5978 {
5979 cx.platform.hide_cursor_until_mouse_moves();
5980 }
5981 }
5982
5983 fn dispatch_action_on_node_inner(
5984 &mut self,
5985 node_id: DispatchNodeId,
5986 action: &dyn Action,
5987 cx: &mut App,
5988 ) {
5989 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5990
5991 cx.propagate_event = true;
5993 if let Some(mut global_listeners) = cx
5994 .global_action_listeners
5995 .remove(&action.as_any().type_id())
5996 {
5997 for listener in &global_listeners {
5998 #[cfg(feature = "profiler")]
5999 self.window_profiler.begin_action_handler(action, cx);
6000 listener(action.as_any(), DispatchPhase::Capture, cx);
6001 #[cfg(feature = "profiler")]
6002 self.window_profiler.end_action_handler();
6003 if !cx.propagate_event {
6004 break;
6005 }
6006 }
6007
6008 global_listeners.extend(
6009 cx.global_action_listeners
6010 .remove(&action.as_any().type_id())
6011 .unwrap_or_default(),
6012 );
6013
6014 cx.global_action_listeners
6015 .insert(action.as_any().type_id(), global_listeners);
6016 }
6017
6018 if !cx.propagate_event {
6019 return;
6020 }
6021
6022 for node_id in &dispatch_path {
6024 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6025 for DispatchActionListener {
6026 action_type,
6027 listener,
6028 } in node.action_listeners.clone()
6029 {
6030 let any_action = action.as_any();
6031 if action_type == any_action.type_id() {
6032 #[cfg(feature = "profiler")]
6033 self.window_profiler.begin_action_handler(action, cx);
6034 listener(any_action, DispatchPhase::Capture, self, cx);
6035 #[cfg(feature = "profiler")]
6036 self.window_profiler.end_action_handler();
6037
6038 if !cx.propagate_event {
6039 return;
6040 }
6041 }
6042 }
6043 }
6044
6045 for node_id in dispatch_path.iter().rev() {
6047 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6048 for DispatchActionListener {
6049 action_type,
6050 listener,
6051 } in node.action_listeners.clone()
6052 {
6053 let any_action = action.as_any();
6054 if action_type == any_action.type_id() {
6055 cx.propagate_event = false; #[cfg(feature = "profiler")]
6057 self.window_profiler.begin_action_handler(action, cx);
6058 listener(any_action, DispatchPhase::Bubble, self, cx);
6059 #[cfg(feature = "profiler")]
6060 self.window_profiler.end_action_handler();
6061
6062 if !cx.propagate_event {
6063 return;
6064 }
6065 }
6066 }
6067 }
6068
6069 if let Some(mut global_listeners) = cx
6071 .global_action_listeners
6072 .remove(&action.as_any().type_id())
6073 {
6074 for listener in global_listeners.iter().rev() {
6075 cx.propagate_event = false; #[cfg(feature = "profiler")]
6078 self.window_profiler.begin_action_handler(action, cx);
6079 listener(action.as_any(), DispatchPhase::Bubble, cx);
6080 #[cfg(feature = "profiler")]
6081 self.window_profiler.end_action_handler();
6082 if !cx.propagate_event {
6083 break;
6084 }
6085 }
6086
6087 global_listeners.extend(
6088 cx.global_action_listeners
6089 .remove(&action.as_any().type_id())
6090 .unwrap_or_default(),
6091 );
6092
6093 cx.global_action_listeners
6094 .insert(action.as_any().type_id(), global_listeners);
6095 }
6096 }
6097
6098 pub fn observe_global<G: Global>(
6101 &mut self,
6102 cx: &mut App,
6103 f: impl Fn(&mut Window, &mut App) + 'static,
6104 ) -> Subscription {
6105 let window_handle = self.handle;
6106 let (subscription, activate) = cx.global_observers.insert(
6107 TypeId::of::<G>(),
6108 Box::new(move |cx| {
6109 window_handle
6110 .update(cx, |_, window, cx| f(window, cx))
6111 .is_ok()
6112 }),
6113 );
6114 cx.defer(move |_| activate());
6115 subscription
6116 }
6117
6118 pub fn activate_window(&self) {
6120 self.platform_window.activate();
6121 }
6122
6123 pub fn request_attention(&self) {
6125 self.platform_window.request_attention();
6126 }
6127
6128 pub fn minimize_window(&self) {
6130 self.platform_window.minimize();
6131 }
6132
6133 pub fn toggle_fullscreen(&self) {
6135 self.platform_window.toggle_fullscreen();
6136 }
6137
6138 pub fn toggle_simple_fullscreen(&self) {
6143 self.platform_window.toggle_simple_fullscreen();
6144 }
6145
6146 pub fn invalidate_character_coordinates(&self) {
6148 self.on_next_frame(|window, cx| {
6149 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
6150 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
6151 window.platform_window.update_ime_position(bounds);
6152 }
6153 window.platform_window.set_input_handler(input_handler);
6154 }
6155 });
6156 }
6157
6158 pub fn prompt<T>(
6162 &mut self,
6163 level: PromptLevel,
6164 message: &str,
6165 detail: Option<&str>,
6166 answers: &[T],
6167 cx: &mut App,
6168 ) -> oneshot::Receiver<usize>
6169 where
6170 T: Clone + Into<PromptButton>,
6171 {
6172 let prompt_builder = cx.prompt_builder.take();
6173 let Some(prompt_builder) = prompt_builder else {
6174 unreachable!("Re-entrant window prompting is not supported by GPUI");
6175 };
6176
6177 let answers = answers
6178 .iter()
6179 .map(|answer| answer.clone().into())
6180 .collect::<Vec<_>>();
6181
6182 let receiver = match &prompt_builder {
6183 PromptBuilder::Default => self
6184 .platform_window
6185 .prompt(level, message, detail, &answers)
6186 .unwrap_or_else(|| {
6187 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6188 }),
6189 PromptBuilder::Custom(_) => {
6190 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6191 }
6192 };
6193
6194 cx.prompt_builder = Some(prompt_builder);
6195
6196 receiver
6197 }
6198
6199 fn build_custom_prompt(
6200 &mut self,
6201 prompt_builder: &PromptBuilder,
6202 level: PromptLevel,
6203 message: &str,
6204 detail: Option<&str>,
6205 answers: &[PromptButton],
6206 cx: &mut App,
6207 ) -> oneshot::Receiver<usize> {
6208 let (sender, receiver) = oneshot::channel();
6209 let handle = PromptHandle::new(sender);
6210 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
6211 self.prompt = Some(handle);
6212 receiver
6213 }
6214
6215 pub fn has_active_prompt(&self) -> bool {
6220 self.prompt.is_some()
6221 }
6222
6223 pub fn context_stack(&self) -> Vec<KeyContext> {
6225 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6226 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6227 dispatch_tree
6228 .dispatch_path(node_id)
6229 .iter()
6230 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
6231 .collect()
6232 }
6233
6234 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
6236 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6237 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
6238 for action_type in cx.global_action_listeners.keys() {
6239 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
6240 let action = cx.actions.build_action_type(action_type).ok();
6241 if let Some(action) = action {
6242 actions.insert(ix, action);
6243 }
6244 }
6245 }
6246 actions
6247 }
6248
6249 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
6252 self.rendered_frame
6253 .dispatch_tree
6254 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
6255 }
6256
6257 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
6260 self.rendered_frame
6261 .dispatch_tree
6262 .highest_precedence_binding_for_action(
6263 action,
6264 &self.rendered_frame.dispatch_tree.context_stack,
6265 )
6266 }
6267
6268 pub fn bindings_for_action_in_context(
6270 &self,
6271 action: &dyn Action,
6272 context: KeyContext,
6273 ) -> Vec<KeyBinding> {
6274 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6275 dispatch_tree.bindings_for_action(action, &[context])
6276 }
6277
6278 pub fn highest_precedence_binding_for_action_in_context(
6281 &self,
6282 action: &dyn Action,
6283 context: KeyContext,
6284 ) -> Option<KeyBinding> {
6285 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6286 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
6287 }
6288
6289 pub fn bindings_for_action_in(
6293 &self,
6294 action: &dyn Action,
6295 focus_handle: &FocusHandle,
6296 ) -> Vec<KeyBinding> {
6297 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6298 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
6299 return vec![];
6300 };
6301 dispatch_tree.bindings_for_action(action, &context_stack)
6302 }
6303
6304 pub fn highest_precedence_binding_for_action_in(
6308 &self,
6309 action: &dyn Action,
6310 focus_handle: &FocusHandle,
6311 ) -> Option<KeyBinding> {
6312 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6313 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
6314 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
6315 }
6316
6317 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
6319 self.rendered_frame
6320 .dispatch_tree
6321 .possible_next_bindings_for_input(input, &self.context_stack())
6322 }
6323
6324 fn context_stack_for_focus_handle(
6325 &self,
6326 focus_handle: &FocusHandle,
6327 ) -> Option<Vec<KeyContext>> {
6328 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6329 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
6330 let context_stack: Vec<_> = dispatch_tree
6331 .dispatch_path(node_id)
6332 .into_iter()
6333 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
6334 .collect();
6335 Some(context_stack)
6336 }
6337
6338 pub fn listener_for<T: 'static, E>(
6340 &self,
6341 view: &Entity<T>,
6342 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
6343 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
6344 let view = view.downgrade();
6345 move |e: &E, window: &mut Window, cx: &mut App| {
6346 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
6347 }
6348 }
6349
6350 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
6352 &self,
6353 entity: &Entity<E>,
6354 f: Callback,
6355 ) -> impl Fn(&mut Window, &mut App) + 'static {
6356 let entity = entity.downgrade();
6357 move |window: &mut Window, cx: &mut App| {
6358 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
6359 }
6360 }
6361
6362 pub fn on_window_should_close(
6365 &self,
6366 cx: &App,
6367 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
6368 ) {
6369 let mut cx = self.to_async(cx);
6370 self.platform_window.on_should_close(Box::new(move || {
6371 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
6372 }))
6373 }
6374
6375 pub fn on_action(
6384 &mut self,
6385 action_type: TypeId,
6386 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
6387 ) {
6388 self.invalidator.debug_assert_paint();
6389
6390 self.next_frame
6391 .dispatch_tree
6392 .on_action(action_type, Rc::new(listener));
6393 }
6394
6395 pub fn on_action_when(
6404 &mut self,
6405 condition: bool,
6406 action_type: TypeId,
6407 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
6408 ) {
6409 self.invalidator.debug_assert_paint();
6410
6411 if condition {
6412 self.next_frame
6413 .dispatch_tree
6414 .on_action(action_type, Rc::new(listener));
6415 }
6416 }
6417
6418 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
6421 self.platform_window.gpu_specs()
6422 }
6423
6424 pub fn gpu_time(&self) -> Option<Duration> {
6429 self.platform_window.gpu_time()
6430 }
6431
6432 pub fn titlebar_double_click(&self) {
6435 self.platform_window
6436 .titlebar_double_click(self.is_resizable, self.is_minimizable);
6437 }
6438
6439 pub fn window_title(&self) -> String {
6442 self.platform_window.get_title()
6443 }
6444
6445 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
6448 self.platform_window.tabbed_windows()
6449 }
6450
6451 pub fn tab_bar_visible(&self) -> bool {
6454 self.platform_window.tab_bar_visible()
6455 }
6456
6457 pub fn merge_all_windows(&self) {
6460 self.platform_window.merge_all_windows()
6461 }
6462
6463 pub fn move_tab_to_new_window(&self) {
6466 self.platform_window.move_tab_to_new_window()
6467 }
6468
6469 pub fn toggle_window_tab_overview(&self) {
6472 self.platform_window.toggle_window_tab_overview()
6473 }
6474
6475 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
6478 self.platform_window
6479 .set_tabbing_identifier(tabbing_identifier)
6480 }
6481
6482 pub fn play_system_bell(&self) {
6485 self.platform_window.play_system_bell()
6486 }
6487
6488 pub fn is_a11y_active(&self) -> bool {
6499 self.a11y.is_active()
6500 }
6501
6502 pub fn debug_a11y_tree_json(&self) -> Option<String> {
6504 self.a11y.debug_tree_json()
6505 }
6506
6507 pub fn on_a11y_action(
6513 &mut self,
6514 node_id: accesskit::NodeId,
6515 action: accesskit::Action,
6516 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
6517 ) {
6518 self.a11y
6519 .action_listeners
6520 .entry(node_id)
6521 .or_default()
6522 .push((action, Box::new(listener)));
6523 }
6524
6525 #[cfg(not(target_family = "wasm"))]
6526 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
6527 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
6530 let extra_data = request.data.as_ref();
6531 let mut matched = false;
6532 for (action, listener) in &mut listeners {
6533 if *action == request.action {
6534 listener(extra_data, self, cx);
6535 matched = true;
6536 }
6537 }
6538 self.a11y
6539 .action_listeners
6540 .insert(request.target_node, listeners);
6541 if matched {
6542 return;
6543 }
6544 }
6545
6546 match request.action {
6548 accesskit::Action::Click => {
6549 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
6550 let center = bounds.center();
6551 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
6552 button: MouseButton::Left,
6553 position: center,
6554 modifiers: Modifiers::default(),
6555 click_count: 1,
6556 first_mouse: false,
6557 });
6558 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
6559 button: MouseButton::Left,
6560 position: center,
6561 modifiers: Modifiers::default(),
6562 click_count: 1,
6563 });
6564 self.dispatch_event(mouse_down, cx);
6565 self.dispatch_event(mouse_up, cx);
6566 }
6567 }
6568 accesskit::Action::Focus => {
6569 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
6570 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
6571 {
6572 self.focus(&handle, cx);
6573 }
6574 }
6575 accesskit::Action::Blur => {
6576 self.blur(cx);
6577 }
6578 _ => {
6579 log::debug!(
6580 "Unhandled a11y action: {:?} on {:?}",
6581 request.action,
6582 request.target_node
6583 );
6584 }
6585 }
6586 }
6587
6588 #[cfg(any(feature = "inspector", debug_assertions))]
6590 pub fn toggle_inspector(&mut self, cx: &mut App) {
6591 self.inspector = match self.inspector {
6592 None => Some(cx.new(|_| Inspector::new())),
6593 Some(_) => None,
6594 };
6595 self.refresh();
6596 }
6597
6598 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
6600 #[cfg(any(feature = "inspector", debug_assertions))]
6601 {
6602 if let Some(inspector) = &self.inspector {
6603 return inspector.read(_cx).is_picking();
6604 }
6605 }
6606 false
6607 }
6608
6609 #[cfg(any(feature = "inspector", debug_assertions))]
6611 pub fn with_inspector_state<T: 'static, R>(
6612 &mut self,
6613 _inspector_id: Option<&crate::InspectorElementId>,
6614 cx: &mut App,
6615 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
6616 ) -> R {
6617 if let Some(inspector_id) = _inspector_id
6618 && let Some(inspector) = &self.inspector
6619 {
6620 let inspector = inspector.clone();
6621 let active_element_id = inspector.read(cx).active_element_id();
6622 if Some(inspector_id) == active_element_id {
6623 return inspector.update(cx, |inspector, _cx| {
6624 inspector.with_active_element_state(self, f)
6625 });
6626 }
6627 }
6628 f(&mut None, self)
6629 }
6630
6631 #[cfg(any(feature = "inspector", debug_assertions))]
6632 pub(crate) fn build_inspector_element_id(
6633 &mut self,
6634 path: crate::InspectorElementPath,
6635 ) -> crate::InspectorElementId {
6636 self.invalidator.debug_assert_paint_or_prepaint();
6637 let path = Rc::new(path);
6638 let next_instance_id = self
6639 .next_frame
6640 .next_inspector_instance_ids
6641 .entry(path.clone())
6642 .or_insert(0);
6643 let instance_id = *next_instance_id;
6644 *next_instance_id += 1;
6645 crate::InspectorElementId { path, instance_id }
6646 }
6647
6648 #[cfg(any(feature = "inspector", debug_assertions))]
6649 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
6650 if let Some(inspector) = self.inspector.take() {
6651 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
6652 inspector_element.prepaint_as_root(
6653 point(self.viewport_size.width - inspector_width, px(0.0)),
6654 size(inspector_width, self.viewport_size.height).into(),
6655 self,
6656 cx,
6657 );
6658 self.inspector = Some(inspector);
6659 Some(inspector_element)
6660 } else {
6661 None
6662 }
6663 }
6664
6665 #[cfg(any(feature = "inspector", debug_assertions))]
6666 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
6667 if let Some(mut inspector_element) = inspector_element {
6668 inspector_element.paint(self, cx);
6669 };
6670 }
6671
6672 #[cfg(any(feature = "inspector", debug_assertions))]
6675 pub fn insert_inspector_hitbox(
6676 &mut self,
6677 hitbox_id: HitboxId,
6678 inspector_id: Option<&crate::InspectorElementId>,
6679 cx: &App,
6680 ) {
6681 self.invalidator.debug_assert_paint_or_prepaint();
6682 if !self.is_inspector_picking(cx) {
6683 return;
6684 }
6685 if let Some(inspector_id) = inspector_id {
6686 self.next_frame
6687 .inspector_hitboxes
6688 .insert(hitbox_id, inspector_id.clone());
6689 }
6690 }
6691
6692 #[cfg(any(feature = "inspector", debug_assertions))]
6693 fn paint_inspector_hitbox(&mut self, cx: &App) {
6694 if let Some(inspector) = self.inspector.as_ref() {
6695 let inspector = inspector.read(cx);
6696 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
6697 && let Some(hitbox) = self
6698 .next_frame
6699 .hitboxes
6700 .iter()
6701 .find(|hitbox| hitbox.id == hitbox_id)
6702 {
6703 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
6704 }
6705 }
6706 }
6707
6708 #[cfg(any(feature = "inspector", debug_assertions))]
6709 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6710 let Some(inspector) = self.inspector.clone() else {
6711 return;
6712 };
6713 if event.downcast_ref::<MouseMoveEvent>().is_some() {
6714 inspector.update(cx, |inspector, _cx| {
6715 if let Some((_, inspector_id)) =
6716 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6717 {
6718 inspector.hover(inspector_id, self);
6719 }
6720 });
6721 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
6722 inspector.update(cx, |inspector, _cx| {
6723 if let Some((_, inspector_id)) =
6724 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6725 {
6726 inspector.select(inspector_id, self);
6727 }
6728 });
6729 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
6730 const SCROLL_LINES: f32 = 3.0;
6732 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
6733 let delta_y = event
6734 .delta
6735 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
6736 .y;
6737 if let Some(inspector) = self.inspector.clone() {
6738 inspector.update(cx, |inspector, _cx| {
6739 if let Some(depth) = inspector.pick_depth.as_mut() {
6740 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
6741 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
6742 if *depth < 0.0 {
6743 *depth = 0.0;
6744 } else if *depth > max_depth {
6745 *depth = max_depth;
6746 }
6747 if let Some((_, inspector_id)) =
6748 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6749 {
6750 inspector.set_active_element_id(inspector_id, self);
6751 }
6752 }
6753 });
6754 }
6755 }
6756 }
6757
6758 #[cfg(any(feature = "inspector", debug_assertions))]
6759 fn hovered_inspector_hitbox(
6760 &self,
6761 inspector: &Inspector,
6762 frame: &Frame,
6763 ) -> Option<(HitboxId, crate::InspectorElementId)> {
6764 if let Some(pick_depth) = inspector.pick_depth {
6765 let depth = (pick_depth as i64).try_into().unwrap_or(0);
6766 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
6767 let skip_count = (depth as usize).min(max_skipped);
6768 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
6769 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
6770 return Some((*hitbox_id, inspector_id.clone()));
6771 }
6772 }
6773 }
6774 None
6775 }
6776
6777 #[cfg(any(test, feature = "test-support"))]
6780 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
6781 self.modifiers = modifiers;
6782 }
6783
6784 #[cfg(any(test, feature = "test-support"))]
6788 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
6789 let event = PlatformInput::MouseMove(MouseMoveEvent {
6790 position,
6791 modifiers: self.modifiers,
6792 pressed_button: None,
6793 });
6794 let _ = self.dispatch_event(event, cx);
6795 }
6796}
6797
6798slotmap::new_key_type! {
6800 pub struct WindowId;
6802}
6803
6804impl WindowId {
6805 pub fn as_u64(&self) -> u64 {
6807 self.0.as_ffi()
6808 }
6809}
6810
6811impl From<u64> for WindowId {
6812 fn from(value: u64) -> Self {
6813 WindowId(slotmap::KeyData::from_ffi(value))
6814 }
6815}
6816
6817#[derive(Deref, DerefMut)]
6820pub struct WindowHandle<V> {
6821 #[deref]
6822 #[deref_mut]
6823 pub(crate) any_handle: AnyWindowHandle,
6824 state_type: PhantomData<fn(V) -> V>,
6825}
6826
6827impl<V> Debug for WindowHandle<V> {
6828 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6829 f.debug_struct("WindowHandle")
6830 .field("any_handle", &self.any_handle.id.as_u64())
6831 .finish()
6832 }
6833}
6834
6835impl<V: 'static + Render> WindowHandle<V> {
6836 pub fn new(id: WindowId) -> Self {
6839 WindowHandle {
6840 any_handle: AnyWindowHandle {
6841 id,
6842 state_type: TypeId::of::<V>(),
6843 root_entity_type_name: std::any::type_name::<V>(),
6844 },
6845 state_type: PhantomData,
6846 }
6847 }
6848
6849 #[cfg(any(test, feature = "test-support"))]
6853 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
6854 where
6855 C: AppContext,
6856 {
6857 cx.update_window(self.any_handle, |root_view, _, _| {
6858 root_view
6859 .downcast::<V>()
6860 .map_err(|_| anyhow!("the type of the window's root view has changed"))
6861 })?
6862 }
6863
6864 pub fn update<C, R>(
6868 &self,
6869 cx: &mut C,
6870 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
6871 ) -> Result<R>
6872 where
6873 C: AppContext,
6874 {
6875 cx.update_window(self.any_handle, |root_view, window, cx| {
6876 let view = root_view
6877 .downcast::<V>()
6878 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6879
6880 Ok(view.update(cx, |view, cx| update(view, window, cx)))
6881 })?
6882 }
6883
6884 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
6888 let x = cx
6889 .windows
6890 .get(self.id)
6891 .and_then(|window| {
6892 window
6893 .as_deref()
6894 .and_then(|window| window.root.clone())
6895 .map(|root_view| root_view.downcast::<V>())
6896 })
6897 .context("window not found")?
6898 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6899
6900 Ok(x.read(cx))
6901 }
6902
6903 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
6907 where
6908 C: AppContext,
6909 {
6910 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
6911 }
6912
6913 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
6917 where
6918 C: AppContext,
6919 {
6920 cx.read_window(self, |root_view, _cx| root_view)
6921 }
6922
6923 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
6928 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
6929 .ok()
6930 }
6931}
6932
6933impl<V> Copy for WindowHandle<V> {}
6934
6935impl<V> Clone for WindowHandle<V> {
6936 fn clone(&self) -> Self {
6937 *self
6938 }
6939}
6940
6941impl<V> PartialEq for WindowHandle<V> {
6942 fn eq(&self, other: &Self) -> bool {
6943 self.any_handle == other.any_handle
6944 }
6945}
6946
6947impl<V> Eq for WindowHandle<V> {}
6948
6949impl<V> Hash for WindowHandle<V> {
6950 fn hash<H: Hasher>(&self, state: &mut H) {
6951 self.any_handle.hash(state);
6952 }
6953}
6954
6955impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
6956 fn from(val: WindowHandle<V>) -> Self {
6957 val.any_handle
6958 }
6959}
6960
6961#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
6963pub struct AnyWindowHandle {
6964 pub(crate) id: WindowId,
6965 state_type: TypeId,
6966 root_entity_type_name: &'static str,
6967}
6968
6969impl AnyWindowHandle {
6970 pub fn window_id(&self) -> WindowId {
6972 self.id
6973 }
6974
6975 pub fn root_entity_type_name(&self) -> &'static str {
6977 self.root_entity_type_name
6978 }
6979
6980 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
6983 if TypeId::of::<T>() == self.state_type {
6984 Some(WindowHandle {
6985 any_handle: *self,
6986 state_type: PhantomData,
6987 })
6988 } else {
6989 None
6990 }
6991 }
6992
6993 pub fn update<C, R>(
6997 self,
6998 cx: &mut C,
6999 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
7000 ) -> Result<R>
7001 where
7002 C: AppContext,
7003 {
7004 cx.update_window(self, update)
7005 }
7006
7007 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
7011 where
7012 C: AppContext,
7013 T: 'static,
7014 {
7015 let view = self
7016 .downcast::<T>()
7017 .context("the type of the window's root view has changed")?;
7018
7019 cx.read_window(&view, read)
7020 }
7021}
7022
7023impl HasWindowHandle for Window {
7024 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
7025 self.platform_window.window_handle()
7026 }
7027}
7028
7029impl HasDisplayHandle for Window {
7030 fn display_handle(
7031 &self,
7032 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
7033 self.platform_window.display_handle()
7034 }
7035}
7036
7037#[derive(Clone, Debug, Eq, PartialEq, Hash)]
7042pub enum ElementId {
7043 View(EntityId),
7045 Integer(u64),
7047 Name(SharedString),
7049 Uuid(Uuid),
7051 FocusHandle(FocusId),
7053 NamedInteger(SharedString, u64),
7055 Path(Arc<std::path::Path>),
7057 CodeLocation(core::panic::Location<'static>),
7059 NamedChild(Arc<ElementId>, SharedString),
7061 OpaqueId([u8; 20]),
7063}
7064
7065impl ElementId {
7066 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
7068 Self::NamedInteger(name.into(), integer as u64)
7069 }
7070}
7071
7072impl Display for ElementId {
7073 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7074 match self {
7075 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
7076 ElementId::Integer(ix) => write!(f, "{}", ix)?,
7077 ElementId::Name(name) => write!(f, "{}", name)?,
7078 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
7079 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
7080 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
7081 ElementId::Path(path) => write!(f, "{}", path.display())?,
7082 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
7083 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
7084 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
7085 }
7086
7087 Ok(())
7088 }
7089}
7090
7091impl TryInto<SharedString> for ElementId {
7092 type Error = anyhow::Error;
7093
7094 fn try_into(self) -> anyhow::Result<SharedString> {
7095 if let ElementId::Name(name) = self {
7096 Ok(name)
7097 } else {
7098 anyhow::bail!("element id is not string")
7099 }
7100 }
7101}
7102
7103impl From<usize> for ElementId {
7104 fn from(id: usize) -> Self {
7105 ElementId::Integer(id as u64)
7106 }
7107}
7108
7109impl From<i32> for ElementId {
7110 fn from(id: i32) -> Self {
7111 Self::Integer(id as u64)
7112 }
7113}
7114
7115impl From<SharedString> for ElementId {
7116 fn from(name: SharedString) -> Self {
7117 ElementId::Name(name)
7118 }
7119}
7120
7121impl From<String> for ElementId {
7122 fn from(name: String) -> Self {
7123 ElementId::Name(name.into())
7124 }
7125}
7126
7127impl From<Arc<str>> for ElementId {
7128 fn from(name: Arc<str>) -> Self {
7129 ElementId::Name(name.into())
7130 }
7131}
7132
7133impl From<Arc<std::path::Path>> for ElementId {
7134 fn from(path: Arc<std::path::Path>) -> Self {
7135 ElementId::Path(path)
7136 }
7137}
7138
7139impl From<&'static str> for ElementId {
7140 fn from(name: &'static str) -> Self {
7141 ElementId::Name(SharedString::new_static(name))
7142 }
7143}
7144
7145impl<'a> From<&'a FocusHandle> for ElementId {
7146 fn from(handle: &'a FocusHandle) -> Self {
7147 ElementId::FocusHandle(handle.id)
7148 }
7149}
7150
7151impl From<(&'static str, EntityId)> for ElementId {
7152 fn from((name, id): (&'static str, EntityId)) -> Self {
7153 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
7154 }
7155}
7156
7157impl From<(&'static str, usize)> for ElementId {
7158 fn from((name, id): (&'static str, usize)) -> Self {
7159 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
7160 }
7161}
7162
7163impl From<(SharedString, usize)> for ElementId {
7164 fn from((name, id): (SharedString, usize)) -> Self {
7165 ElementId::NamedInteger(name, id as u64)
7166 }
7167}
7168
7169impl From<(&'static str, u64)> for ElementId {
7170 fn from((name, id): (&'static str, u64)) -> Self {
7171 ElementId::NamedInteger(SharedString::new_static(name), id)
7172 }
7173}
7174
7175impl From<Uuid> for ElementId {
7176 fn from(value: Uuid) -> Self {
7177 Self::Uuid(value)
7178 }
7179}
7180
7181impl From<(&'static str, u32)> for ElementId {
7182 fn from((name, id): (&'static str, u32)) -> Self {
7183 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
7184 }
7185}
7186
7187impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
7188 fn from((id, name): (ElementId, T)) -> Self {
7189 ElementId::NamedChild(Arc::new(id), name.into())
7190 }
7191}
7192
7193impl From<&'static core::panic::Location<'static>> for ElementId {
7194 fn from(location: &'static core::panic::Location<'static>) -> Self {
7195 ElementId::CodeLocation(*location)
7196 }
7197}
7198
7199impl From<[u8; 20]> for ElementId {
7200 fn from(opaque_id: [u8; 20]) -> Self {
7201 ElementId::OpaqueId(opaque_id)
7202 }
7203}
7204
7205#[derive(Clone)]
7208pub struct PaintQuad {
7209 pub bounds: Bounds<Pixels>,
7211 pub corner_radii: Corners<Pixels>,
7213 pub background: Background,
7215 pub border_widths: Edges<Pixels>,
7217 pub border_color: Hsla,
7219 pub border_style: BorderStyle,
7221}
7222
7223impl PaintQuad {
7224 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
7226 PaintQuad {
7227 corner_radii: corner_radii.into(),
7228 ..self
7229 }
7230 }
7231
7232 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
7234 PaintQuad {
7235 border_widths: border_widths.into(),
7236 ..self
7237 }
7238 }
7239
7240 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
7242 PaintQuad {
7243 border_color: border_color.into(),
7244 ..self
7245 }
7246 }
7247
7248 pub fn background(self, background: impl Into<Background>) -> Self {
7250 PaintQuad {
7251 background: background.into(),
7252 ..self
7253 }
7254 }
7255}
7256
7257pub fn quad(
7259 bounds: Bounds<Pixels>,
7260 corner_radii: impl Into<Corners<Pixels>>,
7261 background: impl Into<Background>,
7262 border_widths: impl Into<Edges<Pixels>>,
7263 border_color: impl Into<Hsla>,
7264 border_style: BorderStyle,
7265) -> PaintQuad {
7266 PaintQuad {
7267 bounds,
7268 corner_radii: corner_radii.into(),
7269 background: background.into(),
7270 border_widths: border_widths.into(),
7271 border_color: border_color.into(),
7272 border_style,
7273 }
7274}
7275
7276pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
7278 PaintQuad {
7279 bounds: bounds.into(),
7280 corner_radii: (0.).into(),
7281 background: background.into(),
7282 border_widths: (0.).into(),
7283 border_color: transparent_black(),
7284 border_style: BorderStyle::default(),
7285 }
7286}
7287
7288pub fn outline(
7290 bounds: impl Into<Bounds<Pixels>>,
7291 border_color: impl Into<Hsla>,
7292 border_style: BorderStyle,
7293) -> PaintQuad {
7294 PaintQuad {
7295 bounds: bounds.into(),
7296 corner_radii: (0.).into(),
7297 background: transparent_black().into(),
7298 border_widths: (1.).into(),
7299 border_color: border_color.into(),
7300 border_style,
7301 }
7302}
7303
7304#[cfg(test)]
7305mod tests {
7306 use std::{
7307 cell::{Cell, RefCell},
7308 path::PathBuf,
7309 rc::Rc,
7310 };
7311
7312 use crate::{
7313 AnyWindowHandle, AppContext as _, Bounds, Context, DragMoveEvent, Empty,
7314 ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle,
7315 InputEvent as _, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,
7316 MouseMoveEvent, ParentElement, Pixels, Point, Render, RequestFrameOptions,
7317 StatefulInteractiveElement as _, Styled, TestAppContext, Window, WindowAppearance,
7318 WindowOptions, canvas, div, point, px, size,
7319 };
7320
7321 struct EmptyView;
7322
7323 impl Render for EmptyView {
7324 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7325 div()
7326 }
7327 }
7328
7329 struct OpensWindowOnPaint {
7330 opened: Rc<Cell<bool>>,
7331 }
7332
7333 impl Render for OpensWindowOnPaint {
7334 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7335 let opened = self.opened.clone();
7336 div()
7337 .size_full()
7338 .child(canvas(
7339 |_, _, _| {},
7340 move |_, _, _window, cx| {
7341 if !opened.replace(true) {
7342 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
7343 .unwrap();
7344 }
7345 },
7346 ))
7347 .child(div().child("after"))
7351 }
7352 }
7353
7354 #[test]
7360 fn test_window_opened_during_draw_defers_arena_clear() {
7361 let mut cx = TestAppContext::single();
7362
7363 let opened = Rc::new(Cell::new(false));
7364 let window = cx.add_window({
7366 let opened = opened.clone();
7367 move |_, _| OpensWindowOnPaint { opened }
7368 });
7369
7370 assert!(opened.get());
7371 assert_eq!(cx.windows().len(), 2);
7372
7373 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
7376 .unwrap();
7377 }
7378
7379 #[gpui::test]
7384 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
7385 let window = cx.add_window(|_, _| EmptyView);
7386 let test_window = cx.test_window(window.into());
7387
7388 assert!(
7392 test_window.frame_wake_count() >= 1,
7393 "opening a window must wake the frame source for the initial frame"
7394 );
7395
7396 test_window.simulate_frame_request(RequestFrameOptions::default());
7398
7399 let baseline = test_window.frame_wake_count();
7402 test_window.simulate_frame_request(RequestFrameOptions::default());
7403 window.update(cx, |_, _, _| {}).unwrap();
7404 assert_eq!(
7405 test_window.frame_wake_count(),
7406 baseline,
7407 "clean frames and non-notifying updates must not wake the frame source"
7408 );
7409
7410 window.update(cx, |_, _, cx| cx.notify()).unwrap();
7412 assert!(
7413 test_window.frame_wake_count() > baseline,
7414 "notifying a view in an idle window must wake the frame source"
7415 );
7416
7417 test_window.simulate_frame_request(RequestFrameOptions::default());
7419 let baseline = test_window.frame_wake_count();
7420 test_window.simulate_frame_request(RequestFrameOptions::default());
7421 assert_eq!(
7422 test_window.frame_wake_count(),
7423 baseline,
7424 "serving demand must return the window to idle"
7425 );
7426
7427 window
7429 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
7430 .unwrap();
7431 assert!(
7432 test_window.frame_wake_count() > baseline,
7433 "scheduling a next-frame callback in an idle window must wake the frame source"
7434 );
7435 }
7436
7437 #[gpui::test]
7442 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
7443 let window = cx.add_window(|_, _| EmptyView);
7444 let test_window = cx.test_window(window.into());
7445 test_window.simulate_frame_request(RequestFrameOptions::default());
7448
7449 let callback_ran = Rc::new(Cell::new(false));
7450 window
7451 .update(cx, {
7452 let callback_ran = callback_ran.clone();
7453 move |_, window, _| {
7454 window.on_next_frame(move |_, _| callback_ran.set(true));
7455 }
7456 })
7457 .unwrap();
7458
7459 let baseline = test_window.frame_wake_count();
7460 test_window.simulate_frame_request(RequestFrameOptions::default());
7461 assert!(
7468 test_window.frame_wake_count() > baseline || callback_ran.get(),
7469 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
7470 );
7471 }
7472
7473 #[gpui::test]
7474 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
7475 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
7476
7477 let window = cx.add_window(|_, _| EmptyView);
7478 window
7479 .update(cx, |_, window, _| {
7480 assert!(matches!(
7481 window.window_handle(),
7482 Err(HandleError::NotSupported)
7483 ));
7484 assert!(matches!(
7485 window.display_handle(),
7486 Err(HandleError::NotSupported)
7487 ));
7488 })
7489 .unwrap();
7490 }
7491
7492 #[gpui::test]
7493 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
7494 let window = cx.add_window(|_, _| EmptyView);
7495 let observed_appearance = Rc::new(Cell::new(None));
7496 let _subscription = window
7497 .update(cx, {
7498 let observed_appearance = observed_appearance.clone();
7499 move |_, window, _| {
7500 window.observe_window_appearance(move |window, _| {
7501 observed_appearance.set(Some(window.appearance()));
7502 })
7503 }
7504 })
7505 .unwrap();
7506 let test_window = cx.test_window(window.into());
7507
7508 cx.update(|_| {
7509 test_window.simulate_appearance_change(WindowAppearance::Dark);
7510 assert_eq!(observed_appearance.get(), None);
7511 });
7512 cx.run_until_parked();
7513
7514 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
7515 }
7516
7517 #[gpui::test]
7518 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
7519 let window = cx.add_window(|_, _| Empty);
7520 let test_window = cx.test_window(window.into());
7521
7522 assert!(test_window.simulate_scheduled_frame());
7523 assert!(test_window.simulate_scheduled_frame());
7524 assert!(!test_window.frame_scheduled());
7525
7526 cx.update_window(window.into(), |_, window, _| {
7527 window.active.set(true);
7528 window.on_next_frame(|_, _| {});
7529 })
7530 .unwrap();
7531 assert!(
7532 test_window.frame_scheduled(),
7533 "queuing work on a parked window must wake the render loop"
7534 );
7535
7536 assert!(test_window.simulate_scheduled_frame());
7537 assert!(
7538 test_window.frame_scheduled(),
7539 "presenting the frame must await one compositor callback"
7540 );
7541 assert!(test_window.simulate_scheduled_frame());
7542 assert!(!test_window.frame_scheduled());
7543 }
7544
7545 #[gpui::test]
7546 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
7547 let window = cx.add_window(|_, _| Empty);
7548 let test_window = cx.test_window(window.into());
7549
7550 assert!(test_window.simulate_scheduled_frame());
7551 assert!(test_window.simulate_scheduled_frame());
7552 assert!(!test_window.frame_scheduled());
7553
7554 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
7555 .unwrap();
7556
7557 assert!(
7558 test_window.frame_scheduled(),
7559 "a rendered scene awaiting presentation must wake the render loop"
7560 );
7561 }
7562
7563 #[gpui::test]
7564 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
7565 let window = cx.add_window(|_, _| Empty);
7566 let test_window = cx.test_window(window.into());
7567
7568 let callback_ran = Rc::new(Cell::new(false));
7569 cx.update_window(window.into(), |_, window, _| {
7570 window.active.set(true);
7573 let callback_ran = callback_ran.clone();
7574 window.on_next_frame(move |window, _| {
7575 window.on_next_frame(move |_, _| callback_ran.set(true));
7576 });
7577 })
7578 .unwrap();
7579
7580 assert!(test_window.simulate_scheduled_frame());
7581 assert!(!callback_ran.get());
7582 assert!(
7583 test_window.frame_scheduled(),
7584 "a callback queued mid-frame must schedule a follow-up before the loop parks"
7585 );
7586
7587 assert!(test_window.simulate_scheduled_frame());
7588 assert!(callback_ran.get());
7589 }
7590
7591 struct RootView {
7592 explicit_size: bool,
7593 child_bounds: Rc<Cell<Bounds<Pixels>>>,
7594 }
7595
7596 impl Render for RootView {
7597 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7598 let child_bounds = self.child_bounds.clone();
7599 let root = div().flex().flex_col().child(
7600 canvas(
7601 move |bounds, _, _| child_bounds.set(bounds),
7602 |_, _, _, _| {},
7603 )
7604 .size_full(),
7605 );
7606 if self.explicit_size {
7607 root.w(px(300.)).h(px(200.))
7608 } else {
7609 root
7610 }
7611 }
7612 }
7613
7614 #[test]
7615 fn auto_sized_window_root_fills_the_window() {
7616 let mut cx = TestAppContext::single();
7617 let child_bounds = Rc::new(Cell::new(Bounds::default()));
7618 let window = cx.add_window({
7619 let child_bounds = child_bounds.clone();
7620 move |_, _| RootView {
7621 explicit_size: false,
7622 child_bounds,
7623 }
7624 });
7625
7626 let viewport_size = cx
7627 .update_window(window.into(), |_, window, cx| {
7628 window.draw(cx).clear(cx);
7629 window.viewport_size()
7630 })
7631 .unwrap();
7632
7633 assert_eq!(child_bounds.get().size, viewport_size);
7634 }
7635
7636 #[test]
7637 fn explicitly_sized_window_root_keeps_its_size() {
7638 let mut cx = TestAppContext::single();
7639 let child_bounds = Rc::new(Cell::new(Bounds::default()));
7640 let window = cx.add_window({
7641 let child_bounds = child_bounds.clone();
7642 move |_, _| RootView {
7643 explicit_size: true,
7644 child_bounds,
7645 }
7646 });
7647
7648 cx.update_window(window.into(), |_, window, cx| {
7649 window.draw(cx).clear(cx);
7650 })
7651 .unwrap();
7652
7653 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
7654 }
7655
7656 struct FileDragView {
7657 path: PathBuf,
7658 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7659 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7660 }
7661
7662 impl Render for FileDragView {
7663 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7664 div()
7665 .id("file-drag")
7666 .size_full()
7667 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
7668 .external_drag_payload(|path: &PathBuf, _, _| {
7669 Some(ExternalDragPayload::Files(FileDragPaths::new([(
7670 path.clone(),
7671 true,
7672 )])))
7673 })
7674 .on_drag_move({
7675 let observed_drag_moves = self.observed_drag_moves.clone();
7676 move |event: &DragMoveEvent<PathBuf>, _, _| {
7677 observed_drag_moves.borrow_mut().push(event.event.position);
7678 }
7679 })
7680 .on_drop({
7681 let observed_drops = self.observed_drops.clone();
7682 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
7683 })
7684 }
7685 }
7686
7687 #[gpui::test]
7688 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
7689 struct Drag {
7690 window: AnyWindowHandle,
7691 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7692 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7693 }
7694
7695 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
7696 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
7697 let observed_drops = Rc::new(RefCell::new(Vec::new()));
7698 let window: AnyWindowHandle = cx
7699 .add_window({
7700 let observed_drag_moves = observed_drag_moves.clone();
7701 let observed_drops = observed_drops.clone();
7702 move |_, _| FileDragView {
7703 path,
7704 observed_drag_moves,
7705 observed_drops,
7706 }
7707 })
7708 .into();
7709 cx.test_window(window)
7710 .set_start_external_drag_result(platform_result);
7711
7712 let update_result = cx.update_window(window, |_, window, cx| {
7713 window.draw(cx).clear(cx);
7714 window.dispatch_event(
7715 MouseDownEvent {
7716 position: point(px(10.), px(10.)),
7717 button: MouseButton::Left,
7718 modifiers: Default::default(),
7719 click_count: 1,
7720 first_mouse: false,
7721 }
7722 .to_platform_input(),
7723 cx,
7724 );
7725 window.dispatch_event(
7726 MouseMoveEvent {
7727 position: point(px(20.), px(20.)),
7728 pressed_button: Some(MouseButton::Left),
7729 modifiers: Default::default(),
7730 }
7731 .to_platform_input(),
7732 cx,
7733 );
7734 assert!(cx.active_drag.is_some());
7735 });
7736 assert!(
7737 update_result.is_ok(),
7738 "failed to start drag: {update_result:?}"
7739 );
7740
7741 assert!(cx.test_window(window).external_drag_files().is_empty());
7742 Drag {
7743 window,
7744 observed_drag_moves,
7745 observed_drops,
7746 }
7747 }
7748
7749 let successful_path = PathBuf::from("/tmp/successful-drag");
7750 let successful = start_drag(cx, successful_path.clone(), true);
7751 let outside_position = point(px(-1.), px(20.));
7752 let update_result = cx.update_window(successful.window, |_, window, cx| {
7753 window.dispatch_event(
7754 MouseMoveEvent {
7755 position: outside_position,
7756 pressed_button: Some(MouseButton::Left),
7757 modifiers: Default::default(),
7758 }
7759 .to_platform_input(),
7760 cx,
7761 );
7762 assert!(cx.active_drag.is_none());
7763 });
7764 assert!(
7765 update_result.is_ok(),
7766 "failed to promote drag: {update_result:?}"
7767 );
7768 assert_eq!(
7769 cx.test_window(successful.window).external_drag_files(),
7770 [(successful_path.clone(), true)]
7771 );
7772 assert_eq!(
7775 successful.observed_drag_moves.borrow().last(),
7776 Some(&outside_position)
7777 );
7778
7779 let destination: AnyWindowHandle = cx.add_window(|_, _| EmptyView).into();
7780 let reentry_position = point(px(30.), px(30.));
7781 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
7782 let update_result = cx.update_window(destination, |_, window, cx| {
7783 window.dispatch_event(
7784 FileDropEvent::Entered {
7785 position: reentry_position,
7786 paths: external_paths(),
7787 }
7788 .to_platform_input(),
7789 cx,
7790 );
7791 assert!(
7792 cx.active_drag
7793 .as_ref()
7794 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7795 );
7796 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7797 assert!(cx.active_drag.is_none());
7798 });
7799 assert!(
7800 update_result.is_ok(),
7801 "failed to handle drag in destination window: {update_result:?}"
7802 );
7803
7804 let update_result = cx.update_window(successful.window, |_, window, cx| {
7805 window.dispatch_event(
7806 FileDropEvent::Entered {
7807 position: reentry_position,
7808 paths: external_paths(),
7809 }
7810 .to_platform_input(),
7811 cx,
7812 );
7813 assert!(
7814 cx.active_drag
7815 .as_ref()
7816 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7817 );
7818 assert_eq!(
7819 successful.observed_drag_moves.borrow().last(),
7820 Some(&reentry_position)
7821 );
7822
7823 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7824 assert!(cx.active_drag.is_none());
7825
7826 window.dispatch_event(
7827 FileDropEvent::Entered {
7828 position: reentry_position,
7829 paths: external_paths(),
7830 }
7831 .to_platform_input(),
7832 cx,
7833 );
7834 assert!(
7835 cx.active_drag
7836 .as_ref()
7837 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7838 );
7839
7840 window.dispatch_event(
7841 FileDropEvent::Submit {
7842 position: reentry_position,
7843 }
7844 .to_platform_input(),
7845 cx,
7846 );
7847 assert_eq!(
7848 successful.observed_drops.borrow().as_slice(),
7849 std::slice::from_ref(&successful_path)
7850 );
7851 assert!(cx.active_drag.is_none());
7852
7853 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7854 assert!(cx.active_drag.is_none());
7855 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
7856 assert!(cx.active_drag.is_none());
7857
7858 window.dispatch_event(
7859 FileDropEvent::Entered {
7860 position: reentry_position,
7861 paths: external_paths(),
7862 }
7863 .to_platform_input(),
7864 cx,
7865 );
7866 assert!(
7867 cx.active_drag
7868 .as_ref()
7869 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7870 );
7871 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7872 });
7873 assert!(
7874 update_result.is_ok(),
7875 "failed to restore drag in source window: {update_result:?}"
7876 );
7877
7878 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
7879 let cancelled = start_drag(cx, cancelled_path.clone(), true);
7880 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
7881 window.dispatch_event(
7882 MouseMoveEvent {
7883 position: outside_position,
7884 pressed_button: Some(MouseButton::Left),
7885 modifiers: Default::default(),
7886 }
7887 .to_platform_input(),
7888 cx,
7889 );
7890 assert!(cx.active_drag.is_none());
7891
7892 window.dispatch_event(
7893 FileDropEvent::Entered {
7894 position: reentry_position,
7895 paths: ExternalPaths([cancelled_path].into_iter().collect()),
7896 }
7897 .to_platform_input(),
7898 cx,
7899 );
7900 assert!(
7901 cx.active_drag
7902 .as_ref()
7903 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7904 );
7905 assert!(cx.stop_active_drag(window));
7906 assert!(cx.active_drag.is_none());
7907 });
7908 assert!(
7909 update_result.is_ok(),
7910 "failed to cancel restored drag: {update_result:?}"
7911 );
7912 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
7913
7914 let removed_path = PathBuf::from("/tmp/removed-window-drag");
7915 let removed = start_drag(cx, removed_path, true);
7916 let removed_window_id = removed.window.window_id();
7917 let update_result = cx.update_window(removed.window, |_, window, cx| {
7918 window.dispatch_event(
7919 MouseMoveEvent {
7920 position: outside_position,
7921 pressed_button: Some(MouseButton::Left),
7922 modifiers: Default::default(),
7923 }
7924 .to_platform_input(),
7925 cx,
7926 );
7927 assert!(cx.active_drag.is_none());
7928 window.remove_window();
7929 });
7930 assert!(
7931 update_result.is_ok(),
7932 "failed to remove drag source window: {update_result:?}"
7933 );
7934 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
7935
7936 let failed_path = PathBuf::from("/tmp/failed-drag");
7937 let failed = start_drag(cx, failed_path.clone(), false);
7938 let update_result = cx.update_window(failed.window, |_, window, cx| {
7939 for x_position in [-1., -2.] {
7940 window.dispatch_event(
7941 MouseMoveEvent {
7942 position: point(px(x_position), px(20.)),
7943 pressed_button: Some(MouseButton::Left),
7944 modifiers: Default::default(),
7945 }
7946 .to_platform_input(),
7947 cx,
7948 );
7949 }
7950 assert!(cx.active_drag.is_some());
7951 });
7952 assert!(
7953 update_result.is_ok(),
7954 "failed to retain drag after platform failure: {update_result:?}"
7955 );
7956 assert_eq!(
7957 cx.test_window(failed.window).external_drag_files(),
7958 [(failed_path, true)]
7959 );
7960 }
7961
7962 struct FocusForwarder {
7963 a: FocusHandle,
7964 b: FocusHandle,
7965 }
7966
7967 impl Render for FocusForwarder {
7968 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7969 div()
7970 .size_full()
7971 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
7972 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
7973 }
7974 }
7975
7976 #[gpui::test]
7980 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
7981 let b_focus_count = Rc::new(Cell::new(0));
7982 let window = cx.add_window({
7983 let b_focus_count = b_focus_count.clone();
7984 move |window, cx| {
7985 let a = cx.focus_handle();
7986 let b = cx.focus_handle();
7987 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
7988 let b = this.b.clone();
7989 window.focus(&b, cx);
7990 })
7991 .detach();
7992 cx.on_focus(&b, window, move |_, _, _| {
7993 b_focus_count.set(b_focus_count.get() + 1);
7994 })
7995 .detach();
7996 FocusForwarder { a, b }
7997 }
7998 });
7999
8000 window
8001 .update(cx, |_, window, _| window.activate_window())
8002 .unwrap();
8003 cx.executor().run_until_parked();
8004
8005 window
8006 .update(cx, |this, window, cx| {
8007 let a = this.a.clone();
8008 window.focus(&a, cx);
8009 })
8010 .unwrap();
8011 cx.executor().run_until_parked();
8012
8013 window
8014 .update(cx, |this, window, _| {
8015 assert!(this.b.is_focused(window));
8016 })
8017 .unwrap();
8018 assert_eq!(b_focus_count.get(), 1);
8019 }
8020}