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 pub corner_radii: Corners<P>,
1995}
1996
1997impl<P: Clone + Debug + Default + PartialEq> ContentMask<P> {
1998 pub fn new(bounds: Bounds<P>) -> Self {
2000 Self {
2001 bounds,
2002 corner_radii: Corners::default(),
2003 }
2004 }
2005}
2006
2007impl ContentMask<Pixels> {
2008 pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
2010 ContentMask {
2011 bounds: self.bounds.scale(factor),
2012 corner_radii: self.corner_radii.scale(factor),
2013 }
2014 }
2015
2016 pub fn intersect(&self, other: &Self) -> Self {
2024 let bounds = self.bounds.intersect(&other.bounds);
2025 let corner_radii = if bounds == other.bounds {
2026 other.corner_radii.clone()
2027 } else if bounds == self.bounds {
2028 self.corner_radii.clone()
2029 } else {
2030 Corners::default()
2031 };
2032 ContentMask {
2033 bounds,
2034 corner_radii,
2035 }
2036 }
2037}
2038
2039impl Window {
2040 fn mark_view_dirty(&mut self, view_id: EntityId) {
2041 for view_id in self
2044 .rendered_frame
2045 .dispatch_tree
2046 .view_path_reversed(view_id)
2047 {
2048 if !self.dirty_views.insert(view_id) {
2049 break;
2050 }
2051 }
2052 }
2053
2054 pub fn observe_window_appearance(
2056 &self,
2057 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2058 ) -> Subscription {
2059 let (subscription, activate) = self.appearance_observers.insert(
2060 (),
2061 Box::new(move |window, cx| {
2062 callback(window, cx);
2063 true
2064 }),
2065 );
2066 activate();
2067 subscription
2068 }
2069
2070 pub fn observe_button_layout_changed(
2072 &self,
2073 mut callback: impl FnMut(&mut Window, &mut App) + 'static,
2074 ) -> Subscription {
2075 let (subscription, activate) = self.button_layout_observers.insert(
2076 (),
2077 Box::new(move |window, cx| {
2078 callback(window, cx);
2079 true
2080 }),
2081 );
2082 activate();
2083 subscription
2084 }
2085
2086 pub fn replace_root<E>(
2088 &mut self,
2089 cx: &mut App,
2090 build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
2091 ) -> Entity<E>
2092 where
2093 E: 'static + Render,
2094 {
2095 let view = cx.new(|cx| build_view(self, cx));
2096 self.root = Some(view.clone().into());
2097 self.refresh();
2098 view
2099 }
2100
2101 pub fn root<E>(&self) -> Option<Option<Entity<E>>>
2103 where
2104 E: 'static + Render,
2105 {
2106 self.root
2107 .as_ref()
2108 .map(|view| view.clone().downcast::<E>().ok())
2109 }
2110
2111 pub fn window_handle(&self) -> AnyWindowHandle {
2113 self.handle
2114 }
2115
2116 pub fn refresh(&mut self) {
2118 if self.invalidator.not_drawing() {
2119 self.refreshing = true;
2120 self.invalidator.set_dirty(true);
2121 }
2122 }
2123
2124 pub fn remove_window(&mut self) {
2126 self.removed = true;
2127 }
2128
2129 pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
2131 self.focus
2132 .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
2133 }
2134
2135 pub fn focus_lost_restore_target(&self, cx: &App) -> Option<FocusHandle> {
2139 let (_leaf, ancestors) = self.focus_lost_path.split_last()?;
2140 ancestors.iter().rev().find_map(|id| {
2141 self.rendered_frame.dispatch_tree.focusable_node_id(*id)?;
2142 FocusHandle::for_id(*id, &cx.focus_handles)
2143 })
2144 }
2145
2146 pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
2148 if !self.focus_enabled || self.focus == Some(handle.id) {
2149 return;
2150 }
2151
2152 self.focus = Some(handle.id);
2153 self.focus_generation = self.focus_generation.wrapping_add(1);
2154 self.clear_pending_keystrokes(cx);
2155
2156 self.refresh();
2157 }
2158
2159 pub fn blur(&mut self, cx: &mut App) {
2161 self.clear_pending_keystrokes(cx);
2162
2163 if !self.focus_enabled {
2164 return;
2165 }
2166
2167 if self.focus.is_some() {
2168 self.focus_generation = self.focus_generation.wrapping_add(1);
2169 }
2170 self.focus = None;
2171 self.refresh();
2172 }
2173
2174 pub fn disable_focus(&mut self, cx: &mut App) {
2176 self.blur(cx);
2177 self.focus_enabled = false;
2178 }
2179
2180 pub fn focus_next(&mut self, cx: &mut App) {
2182 if !self.focus_enabled {
2183 return;
2184 }
2185
2186 if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
2187 self.focus(&handle, cx)
2188 }
2189 }
2190
2191 pub fn focus_prev(&mut self, cx: &mut App) {
2193 if !self.focus_enabled {
2194 return;
2195 }
2196
2197 if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
2198 self.focus(&handle, cx)
2199 }
2200 }
2201
2202 pub fn text_system(&self) -> &Arc<WindowTextSystem> {
2204 &self.text_system
2205 }
2206
2207 pub fn text_style(&self) -> TextStyle {
2209 let mut style = TextStyle::default();
2210 for refinement in &self.text_style_stack {
2211 style.refine(refinement);
2212 }
2213 style
2214 }
2215
2216 pub fn is_maximized(&self) -> bool {
2220 self.platform_window.is_maximized()
2221 }
2222
2223 pub fn request_decorations(&self, decorations: WindowDecorations) {
2225 self.platform_window.request_decorations(decorations);
2226 }
2227
2228 pub fn set_exclusive_zone(&self, zone: Pixels) {
2234 self.platform_window.set_exclusive_zone(zone);
2235 }
2236
2237 #[cfg(all(target_os = "linux", feature = "wayland"))]
2242 pub fn set_exclusive_edge(&self, edge: crate::layer_shell::Anchor) {
2243 self.platform_window.set_exclusive_edge(edge);
2244 }
2245
2246 pub fn start_window_resize(&self, edge: ResizeEdge) {
2248 if self.is_resizable {
2249 self.platform_window.start_window_resize(edge);
2250 }
2251 }
2252
2253 pub fn set_input_region(&self, region: Option<&[Bounds<Pixels>]>) {
2260 self.platform_window.set_input_region(region);
2261 }
2262
2263 pub fn window_bounds(&self) -> WindowBounds {
2266 self.platform_window.window_bounds()
2267 }
2268
2269 pub fn inner_window_bounds(&self) -> WindowBounds {
2271 self.platform_window.inner_window_bounds()
2272 }
2273
2274 pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
2276 let focus_id = self.focused(cx).map(|handle| handle.id);
2277
2278 let window = self.handle;
2279 cx.defer(move |cx| {
2280 window
2281 .update(cx, |_, window, cx| {
2282 let node_id = window.focus_node_id_in_rendered_frame(focus_id);
2283 window.dispatch_action_on_node(node_id, action.as_ref(), cx);
2284 })
2285 .log_err();
2286 })
2287 }
2288
2289 pub(crate) fn dispatch_keystroke_observers(
2290 &mut self,
2291 event: &dyn Any,
2292 action: Option<Box<dyn Action>>,
2293 context_stack: Vec<KeyContext>,
2294 cx: &mut App,
2295 ) {
2296 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2297 return;
2298 };
2299
2300 cx.keystroke_observers.clone().retain(&(), move |callback| {
2301 (callback)(
2302 &KeystrokeEvent {
2303 keystroke: key_down_event.keystroke.clone(),
2304 action: action.as_ref().map(|action| action.boxed_clone()),
2305 context_stack: context_stack.clone(),
2306 },
2307 self,
2308 cx,
2309 )
2310 });
2311 }
2312
2313 pub(crate) fn dispatch_keystroke_interceptors(
2314 &mut self,
2315 event: &dyn Any,
2316 context_stack: Vec<KeyContext>,
2317 cx: &mut App,
2318 ) {
2319 let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
2320 return;
2321 };
2322
2323 cx.keystroke_interceptors
2324 .clone()
2325 .retain(&(), move |callback| {
2326 (callback)(
2327 &KeystrokeEvent {
2328 keystroke: key_down_event.keystroke.clone(),
2329 action: None,
2330 context_stack: context_stack.clone(),
2331 },
2332 self,
2333 cx,
2334 )
2335 });
2336 }
2337
2338 pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
2341 let handle = self.handle;
2342 cx.defer(move |cx| {
2343 handle.update(cx, |_, window, cx| f(window, cx)).ok();
2344 });
2345 }
2346
2347 pub fn observe<T: 'static>(
2351 &mut self,
2352 observed: &Entity<T>,
2353 cx: &mut App,
2354 mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
2355 ) -> Subscription {
2356 let entity_id = observed.entity_id();
2357 let observed = observed.downgrade();
2358 let window_handle = self.handle;
2359 cx.new_observer(
2360 entity_id,
2361 Box::new(move |cx| {
2362 window_handle
2363 .update(cx, |_, window, cx| {
2364 if let Some(handle) = observed.upgrade() {
2365 on_notify(handle, window, cx);
2366 true
2367 } else {
2368 false
2369 }
2370 })
2371 .unwrap_or(false)
2372 }),
2373 )
2374 }
2375
2376 pub fn subscribe<Emitter, Evt>(
2380 &mut self,
2381 entity: &Entity<Emitter>,
2382 cx: &mut App,
2383 mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
2384 ) -> Subscription
2385 where
2386 Emitter: EventEmitter<Evt>,
2387 Evt: 'static,
2388 {
2389 let entity_id = entity.entity_id();
2390 let handle = entity.downgrade();
2391 let window_handle = self.handle;
2392 cx.new_subscription(
2393 entity_id,
2394 (
2395 TypeId::of::<Evt>(),
2396 Box::new(move |event, cx| {
2397 window_handle
2398 .update(cx, |_, window, cx| {
2399 if let Some(entity) = handle.upgrade() {
2400 let event = event.downcast_ref().expect("invalid event type");
2401 on_event(entity, event, window, cx);
2402 true
2403 } else {
2404 false
2405 }
2406 })
2407 .unwrap_or(false)
2408 }),
2409 ),
2410 )
2411 }
2412
2413 pub fn observe_release<T>(
2415 &self,
2416 entity: &Entity<T>,
2417 cx: &mut App,
2418 mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2419 ) -> Subscription
2420 where
2421 T: 'static,
2422 {
2423 let entity_id = entity.entity_id();
2424 let window_handle = self.handle;
2425 let (subscription, activate) = cx.release_listeners.insert(
2426 entity_id,
2427 Box::new(move |entity, cx| {
2428 let entity = entity.downcast_mut().expect("invalid entity type");
2429 let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2430 }),
2431 );
2432 activate();
2433 subscription
2434 }
2435
2436 pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2439 AsyncWindowContext::new_context(cx.to_async(), self.handle)
2440 }
2441
2442 pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2444 RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2445 self.platform_window.schedule_frame();
2446 self.invalidator.wake_platform();
2449 }
2450
2451 pub fn request_animation_frame(&self) {
2464 let entity = self.current_view();
2465 self.on_next_frame(move |_, cx| cx.notify(entity));
2466 }
2467
2468 #[cfg(any(test, feature = "test-support"))]
2473 pub fn simulate_next_frame(&mut self, cx: &mut App) -> usize {
2474 let callbacks = self.next_frame_callbacks.take();
2475 let count = callbacks.len();
2476 for callback in callbacks {
2477 callback(self, cx);
2478 }
2479 count
2480 }
2481
2482 #[track_caller]
2486 pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2487 where
2488 R: 'static,
2489 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2490 {
2491 let handle = self.handle;
2492 cx.spawn(async move |app| {
2493 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2494 f(&mut async_window_cx).await
2495 })
2496 }
2497
2498 #[track_caller]
2502 pub fn spawn_with_priority<AsyncFn, R>(
2503 &self,
2504 priority: Priority,
2505 cx: &App,
2506 f: AsyncFn,
2507 ) -> Task<R>
2508 where
2509 R: 'static,
2510 AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2511 {
2512 let handle = self.handle;
2513 cx.spawn_with_priority(priority, async move |app| {
2514 let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2515 f(&mut async_window_cx).await
2516 })
2517 }
2518
2519 pub fn bounds_changed(&mut self, cx: &mut App) {
2525 self.scale_factor = self.platform_window.scale_factor();
2526 self.viewport_size = self.platform_window.content_size();
2527 self.display_id = self.platform_window.display().map(|display| display.id());
2528 self.mouse_position = self.platform_window.mouse_position();
2529
2530 self.refresh();
2531
2532 self.bounds_observers
2533 .clone()
2534 .retain(&(), |callback| callback(self, cx));
2535 }
2536
2537 pub fn bounds(&self) -> Bounds<Pixels> {
2539 self.platform_window.bounds()
2540 }
2541
2542 #[cfg(any(test, feature = "test-support"))]
2546 pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
2547 self.platform_window
2548 .render_to_image(&self.rendered_frame.scene)
2549 }
2550
2551 #[cfg(any(test, feature = "test-support"))]
2556 pub fn painted_quads(&self) -> Vec<Quad> {
2557 self.rendered_frame.scene.quads.clone()
2558 }
2559
2560 pub fn resize(&mut self, size: Size<Pixels>) {
2562 self.platform_window.resize(size);
2563 }
2564
2565 pub fn is_fullscreen(&self) -> bool {
2567 self.platform_window.is_fullscreen()
2568 }
2569
2570 pub fn is_simple_fullscreen(&self) -> bool {
2574 self.platform_window.is_simple_fullscreen()
2575 }
2576
2577 pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
2578 self.appearance = self.platform_window.appearance();
2579
2580 self.appearance_observers
2581 .clone()
2582 .retain(&(), |callback| callback(self, cx));
2583 }
2584
2585 pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2586 self.button_layout_observers
2587 .clone()
2588 .retain(&(), |callback| callback(self, cx));
2589 }
2590
2591 pub fn appearance(&self) -> WindowAppearance {
2593 self.appearance
2594 }
2595
2596 pub fn viewport_size(&self) -> Size<Pixels> {
2598 self.viewport_size
2599 }
2600
2601 pub fn is_window_active(&self) -> bool {
2603 self.active.get()
2604 }
2605
2606 pub fn is_window_hovered(&self) -> bool {
2610 if cfg!(any(
2611 target_os = "windows",
2612 target_os = "linux",
2613 target_os = "freebsd"
2614 )) {
2615 self.hovered.get()
2616 } else {
2617 self.is_window_active()
2618 }
2619 }
2620
2621 pub fn zoom_window(&self) {
2623 self.platform_window.zoom();
2624 }
2625
2626 pub fn show_window_menu(&self, position: Point<Pixels>) {
2628 self.platform_window.show_window_menu(position)
2629 }
2630
2631 pub fn start_window_move(&self) {
2636 self.platform_window.start_window_move()
2637 }
2638
2639 pub fn set_client_inset(&mut self, inset: Pixels) {
2641 self.client_inset = Some(inset);
2642 self.platform_window.set_client_inset(inset);
2643 }
2644
2645 pub fn client_inset(&self) -> Option<Pixels> {
2647 self.client_inset
2648 }
2649
2650 pub fn window_decorations(&self) -> Decorations {
2652 self.platform_window.window_decorations()
2653 }
2654
2655 pub fn is_resizable(&self) -> bool {
2657 self.is_resizable
2658 }
2659
2660 pub fn is_minimizable(&self) -> bool {
2662 self.is_minimizable
2663 }
2664
2665 pub fn window_controls(&self) -> WindowControls {
2667 self.platform_window.window_controls()
2668 }
2669
2670 pub fn set_window_title(&mut self, title: &str) {
2672 self.platform_window.set_title(title);
2673 self.a11y.set_window_title(title.to_string());
2674 }
2675
2676 #[cfg(target_os = "macos")]
2678 pub fn set_traffic_light_position(&self, position: Point<Pixels>) {
2679 self.platform_window.set_traffic_light_position(position);
2680 }
2681
2682 pub fn set_app_id(&mut self, app_id: &str) {
2684 self.platform_window.set_app_id(app_id);
2685 }
2686
2687 pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2689 self.platform_window
2690 .set_background_appearance(background_appearance);
2691 }
2692
2693 pub fn set_window_edited(&mut self, edited: bool) {
2695 self.platform_window.set_edited(edited);
2696 }
2697
2698 pub fn set_document_path(&self, path: Option<&std::path::Path>) {
2701 self.platform_window.set_document_path(path);
2702 }
2703
2704 pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2706 cx.platform
2707 .displays()
2708 .into_iter()
2709 .find(|display| Some(display.id()) == self.display_id)
2710 }
2711
2712 pub fn show_character_palette(&self) {
2714 self.platform_window.show_character_palette();
2715 }
2716
2717 pub fn scale_factor(&self) -> f32 {
2721 self.scale_factor
2722 }
2723
2724 #[cfg(any(test, feature = "test-support"))]
2726 pub fn set_scale_factor(&mut self, scale_factor: f32) {
2727 self.scale_factor = scale_factor;
2728 self.refresh();
2729 }
2730
2731 pub fn rem_size(&self) -> Pixels {
2734 self.rem_size_override_stack
2735 .last()
2736 .copied()
2737 .unwrap_or(self.rem_size)
2738 }
2739
2740 pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2743 self.rem_size = rem_size.into();
2744 }
2745
2746 pub fn with_global_id<R>(
2749 &mut self,
2750 element_id: ElementId,
2751 f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2752 ) -> R {
2753 self.with_id(element_id, |this| {
2754 let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2755
2756 f(&global_id, this)
2757 })
2758 }
2759
2760 #[inline]
2762 pub fn with_id<R>(
2763 &mut self,
2764 element_id: impl Into<ElementId>,
2765 f: impl FnOnce(&mut Self) -> R,
2766 ) -> R {
2767 self.element_id_stack.push(element_id.into());
2768 let result = f(self);
2769 self.element_id_stack.pop();
2770 result
2771 }
2772
2773 #[inline]
2779 pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2780 where
2781 F: FnOnce(&mut Self) -> R,
2782 {
2783 self.invalidator.debug_assert_paint_or_prepaint();
2784
2785 if let Some(rem_size) = rem_size {
2786 self.rem_size_override_stack.push(rem_size.into());
2787 let result = f(self);
2788 self.rem_size_override_stack.pop();
2789 result
2790 } else {
2791 f(self)
2792 }
2793 }
2794
2795 pub fn line_height(&self) -> Pixels {
2797 self.text_style().line_height_in_pixels(self.rem_size())
2798 }
2799
2800 #[inline]
2802 pub fn pixel_snap(&self, value: Pixels) -> Pixels {
2803 px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
2804 }
2805
2806 #[inline]
2808 pub fn pixel_snap_f64(&self, value: f64) -> f64 {
2809 let scale_factor = f64::from(self.scale_factor());
2810 round_half_toward_zero_f64(value * scale_factor) / scale_factor
2811 }
2812
2813 #[inline]
2815 pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
2816 bounds.map(|c| self.pixel_snap(c))
2817 }
2818
2819 #[inline]
2821 pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
2822 position.map(|c| self.pixel_snap(c))
2823 }
2824
2825 #[inline]
2826 fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2827 let scale_factor = self.scale_factor();
2828 let left = round_to_device_pixel(bounds.left().0, scale_factor);
2829 let top = round_to_device_pixel(bounds.top().0, scale_factor);
2830 let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
2831 let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2832 Bounds::from_corners(
2833 point(ScaledPixels(left), ScaledPixels(top)),
2834 point(ScaledPixels(right), ScaledPixels(bottom)),
2835 )
2836 }
2837
2838 #[inline]
2840 fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
2841 ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
2842 }
2843
2844 #[inline]
2845 fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
2846 edges.map(|e| self.snap_stroke(*e))
2847 }
2848
2849 #[inline]
2851 fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2852 let scale_factor = self.scale_factor();
2853 let left = floor_to_device_pixel(bounds.left().0, scale_factor);
2854 let top = floor_to_device_pixel(bounds.top().0, scale_factor);
2855 let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
2856 let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2857 Bounds::from_corners(
2858 point(ScaledPixels(left), ScaledPixels(top)),
2859 point(ScaledPixels(right), ScaledPixels(bottom)),
2860 )
2861 }
2862
2863 #[inline]
2864 fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
2865 ContentMask {
2866 bounds: self.cover_bounds(self.content_mask().bounds),
2867 corner_radii: self.content_mask().corner_radii.scale(self.scale_factor()),
2868 }
2869 }
2870
2871 pub fn prevent_default(&mut self) {
2874 self.default_prevented = true;
2875 }
2876
2877 pub fn default_prevented(&self) -> bool {
2879 self.default_prevented
2880 }
2881
2882 pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2884 let node_id =
2885 self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2886 self.rendered_frame
2887 .dispatch_tree
2888 .is_action_available(action, node_id)
2889 }
2890
2891 pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2893 let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2894 self.rendered_frame
2895 .dispatch_tree
2896 .is_action_available(action, node_id)
2897 }
2898
2899 pub fn mouse_position(&self) -> Point<Pixels> {
2901 self.mouse_position
2902 }
2903
2904 pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
2911 self.captured_hitbox = Some(hitbox_id);
2912 }
2913
2914 pub fn release_pointer(&mut self) {
2916 self.captured_hitbox = None;
2917 }
2918
2919 pub fn captured_hitbox(&self) -> Option<HitboxId> {
2921 self.captured_hitbox
2922 }
2923
2924 pub fn modifiers(&self) -> Modifiers {
2926 self.modifiers
2927 }
2928
2929 pub fn last_input_was_keyboard(&self) -> bool {
2932 self.last_input_modality == InputModality::Keyboard
2933 }
2934
2935 pub fn capslock(&self) -> Capslock {
2937 self.capslock
2938 }
2939
2940 #[profiling::function]
2943 pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2944 #[cfg(feature = "profiler")]
2947 let frame_dirty = self.invalidator.take_frame_dirty();
2948 #[cfg(feature = "profiler")]
2949 self.window_profiler.begin_draw();
2950
2951 let arena_scope = ElementArenaScope::enter(&cx.element_arena);
2954
2955 self.invalidate_entities();
2956 cx.entities.clear_accessed();
2957 debug_assert!(self.rendered_entity_stack.is_empty());
2958 self.invalidator.set_dirty(false);
2959 self.requested_autoscroll = None;
2960
2961 if let Some(input_handler) = self.platform_window.take_input_handler() {
2966 if let Some(slot) = self
2967 .rendered_frame
2968 .input_handlers
2969 .iter_mut()
2970 .rev()
2971 .find(|h| h.is_none())
2972 {
2973 *slot = Some(input_handler);
2974 } else {
2975 self.rendered_frame.input_handlers.push(Some(input_handler));
2976 }
2977 }
2978 if !cx.mode.skip_drawing() {
2979 self.draw_roots(cx);
2980 #[cfg(feature = "profiler")]
2981 {
2982 let viewport_size = self.viewport_size;
2983 let scale_factor = self.scale_factor();
2984 self.debug_frame_overlay.paint(
2985 &mut self.next_frame.scene,
2986 viewport_size,
2987 scale_factor,
2988 );
2989 }
2990 }
2991 self.dirty_views.clear();
2992 self.next_frame.window_active = self.active.get();
2993
2994 if let Some(input_handler) = self
3000 .next_frame
3001 .input_handlers
3002 .iter_mut()
3003 .rev()
3004 .find_map(|h| h.take())
3005 {
3006 self.platform_window.set_input_handler(input_handler);
3007 }
3008 self.apply_text_input_configuration(cx);
3009
3010 self.layout_engine.as_mut().unwrap().clear();
3011 self.text_system().finish_frame();
3012 self.next_frame.finish(&mut self.rendered_frame);
3013
3014 self.invalidator.set_phase(DrawPhase::Focus);
3015 let previous_focus_path = self.rendered_frame.focus_path();
3016 let previous_window_active = self.rendered_frame.window_active;
3017 mem::swap(&mut self.rendered_frame, &mut self.next_frame);
3018 self.next_frame.clear();
3019 let current_focus_path = self.rendered_frame.focus_path();
3020 let current_window_active = self.rendered_frame.window_active;
3021 let mut focus_before_listeners = self.focus;
3022
3023 if previous_focus_path != current_focus_path
3024 || previous_window_active != current_window_active
3025 {
3026 if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
3027 self.focus_lost_path = previous_focus_path.clone();
3028 self.focus_lost_listeners
3029 .clone()
3030 .retain(&(), |listener| listener(self, cx));
3031 self.focus_lost_path = SmallVec::new();
3032 focus_before_listeners = self.focus;
3037 }
3038
3039 let event = WindowFocusEvent {
3040 previous_focus_path: if previous_window_active {
3041 previous_focus_path
3042 } else {
3043 Default::default()
3044 },
3045 current_focus_path: if current_window_active {
3046 current_focus_path
3047 } else {
3048 Default::default()
3049 },
3050 };
3051 self.focus_listeners
3052 .clone()
3053 .retain(&(), |listener| listener(&event, self, cx));
3054 }
3055
3056 debug_assert!(self.rendered_entity_stack.is_empty());
3057 self.record_entities_accessed(cx);
3058 self.reset_cursor_style(cx);
3059 self.refreshing = false;
3060 self.invalidator.set_phase(DrawPhase::None);
3061 if self.focus != focus_before_listeners {
3066 self.refresh();
3067 }
3068 self.needs_present.set(true);
3069
3070 #[cfg(feature = "profiler")]
3071 {
3072 let draw_duration = self
3073 .window_profiler
3074 .end_draw(frame_dirty.dirty_at, frame_dirty.invalidations);
3075 self.debug_frame_overlay.record_frame(draw_duration);
3076 }
3077
3078 arena_scope.exit(&cx.element_arena)
3081 }
3082
3083 fn record_entities_accessed(&mut self, cx: &mut App) {
3084 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3085 let mut entities = mem::take(entities_ref.deref_mut());
3086 let handle = self.handle;
3087 cx.record_entities_accessed(
3088 handle,
3089 self.invalidator.clone(),
3091 &entities,
3092 );
3093 let mut entities_ref = cx.entities.accessed_entities.get_mut();
3094 mem::swap(&mut entities, entities_ref.deref_mut());
3095 }
3096
3097 fn invalidate_entities(&mut self) {
3098 let mut views = self.invalidator.take_views();
3099 for entity in views.drain() {
3100 self.mark_view_dirty(entity);
3101 }
3102 self.invalidator.replace_views(views);
3103 }
3104
3105 #[profiling::function]
3106 fn present(&mut self) {
3107 #[cfg(feature = "profiler")]
3108 let _foreground_turn = profiler::journal::foreground_turn();
3109 #[cfg(feature = "profiler")]
3110 let present_start = Instant::now();
3111 self.platform_window.draw(&self.rendered_frame.scene);
3112 #[cfg(feature = "profiler")]
3113 self.window_profiler.record_present(
3114 present_start,
3115 Instant::now(),
3116 self.active.get(),
3117 !self.next_frame_callbacks.borrow().is_empty(),
3118 );
3119 self.needs_present.set(false);
3120 profiling::finish_frame!();
3121 }
3122
3123 #[cfg(any(feature = "bench-support", all(test, feature = "profiler")))]
3129 pub fn present_if_needed(&mut self) {
3130 if self.needs_present.get() {
3131 self.present();
3132 }
3133 }
3134
3135 #[cfg(feature = "profiler")]
3137 pub fn input_latency_snapshot(&self) -> profiler::InputLatencySnapshot {
3138 self.window_profiler.input_latency_snapshot()
3139 }
3140
3141 #[cfg(feature = "profiler")]
3143 pub fn frame_duration_snapshot(&self) -> profiler::FrameDurationSnapshot {
3144 self.window_profiler.frame_duration_snapshot()
3145 }
3146
3147 #[cfg(feature = "profiler")]
3149 pub fn debug_frame_overlay_mode(&self) -> DebugFrameOverlayMode {
3150 self.debug_frame_overlay.mode()
3151 }
3152
3153 #[cfg(feature = "profiler")]
3155 pub fn set_debug_frame_overlay_mode(&mut self, mode: DebugFrameOverlayMode) {
3156 self.debug_frame_overlay.set_mode(mode);
3157 self.refresh();
3158 }
3159
3160 #[cfg(feature = "profiler")]
3163 pub fn cycle_debug_frame_overlay_mode(&mut self) {
3164 self.set_debug_frame_overlay_mode(self.debug_frame_overlay.mode().next());
3165 }
3166
3167 #[cfg(feature = "profiler")]
3170 pub fn reset_debug_frame_overlay_stats(&mut self) {
3171 self.debug_frame_overlay.reset_stats();
3172 self.refresh();
3173 }
3174
3175 fn draw_roots(&mut self, cx: &mut App) {
3176 self.invalidator.set_phase(DrawPhase::Prepaint);
3177 self.tooltip_bounds.take();
3178
3179 self.a11y.sync_active_flag();
3180 if self.a11y.is_active() {
3181 self.a11y.begin_frame();
3182 }
3183
3184 let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
3185 let root_size = {
3186 #[cfg(any(feature = "inspector", debug_assertions))]
3187 {
3188 if self.inspector.is_some() {
3189 let mut size = self.viewport_size;
3190 size.width = (size.width - _inspector_width).max(px(0.0));
3191 size
3192 } else {
3193 self.viewport_size
3194 }
3195 }
3196 #[cfg(not(any(feature = "inspector", debug_assertions)))]
3197 {
3198 self.viewport_size
3199 }
3200 };
3201
3202 let scale_factor = self.scale_factor();
3206 let mut root_element = self.root.as_ref().unwrap().clone().into_any_element();
3207 let root_layout_id = root_element.request_layout(self, cx);
3208 self.layout_engine
3209 .as_mut()
3210 .unwrap()
3211 .stretch_auto_size_to_fill(root_layout_id, root_size, scale_factor);
3212 root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3213
3214 #[cfg(any(feature = "inspector", debug_assertions))]
3215 let inspector_element = self.prepaint_inspector(_inspector_width, cx);
3216
3217 self.prepaint_deferred_draws(cx);
3218
3219 let mut prompt_element = None;
3220 let mut active_drag_element = None;
3221 let mut tooltip_element = None;
3222 if let Some(prompt) = self.prompt.take() {
3223 let mut element = prompt.view.any_view().into_any_element();
3224 let prompt_layout_id = element.request_layout(self, cx);
3225 self.layout_engine
3226 .as_mut()
3227 .unwrap()
3228 .stretch_auto_size_to_fill(prompt_layout_id, root_size, scale_factor);
3229 element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
3230 prompt_element = Some(element);
3231 self.prompt = Some(prompt);
3232 } else if let Some(active_drag) = cx.active_drag.take() {
3233 let mut element = active_drag.view.clone().into_any_element();
3234 let offset = self.mouse_position() - active_drag.cursor_offset;
3235 element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
3236 active_drag_element = Some(element);
3237 cx.active_drag = Some(active_drag);
3238 } else {
3239 tooltip_element = self.prepaint_tooltip(cx);
3240 }
3241
3242 self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
3243
3244 self.invalidator.set_phase(DrawPhase::Paint);
3246 root_element.paint(self, cx);
3247
3248 #[cfg(any(feature = "inspector", debug_assertions))]
3249 self.paint_inspector(inspector_element, cx);
3250
3251 self.paint_deferred_draws(cx);
3252
3253 if let Some(mut prompt_element) = prompt_element {
3254 prompt_element.paint(self, cx);
3255 } else if let Some(mut drag_element) = active_drag_element {
3256 drag_element.paint(self, cx);
3257 } else if let Some(mut tooltip_element) = tooltip_element {
3258 tooltip_element.paint(self, cx);
3259 }
3260
3261 #[cfg(any(feature = "inspector", debug_assertions))]
3262 self.paint_inspector_hitbox(cx);
3263
3264 let a11y_active_start_of_frame = self.a11y.is_active();
3266 self.a11y.sync_active_flag();
3267 let a11y_active_end_of_frame = self.a11y.is_active();
3268
3269 let should_send_a11y_update = a11y_active_start_of_frame && a11y_active_end_of_frame;
3270
3271 if a11y_active_start_of_frame {
3272 let frame_info = crate::window::a11y::debug::FrameDebugInfo {
3275 viewport_size: self.viewport_size,
3276 scale_factor: self.scale_factor,
3277 tab_stop_count: self.next_frame.tab_stops.tab_stop_count(),
3278 };
3279 let tree_update = self.a11y.end_frame(frame_info);
3281
3282 if should_send_a11y_update {
3283 log::debug!(
3284 "Sending a11y tree update: {} nodes",
3285 tree_update.nodes.len()
3286 );
3287 self.platform_window.a11y_tree_update(tree_update);
3288 }
3289 }
3290 }
3291
3292 fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
3293 for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
3295 let Some(Some(tooltip_request)) = self
3296 .next_frame
3297 .tooltip_requests
3298 .get(tooltip_request_index)
3299 .cloned()
3300 else {
3301 log::error!("Unexpectedly absent TooltipRequest");
3302 continue;
3303 };
3304 let mut element = tooltip_request.tooltip.view.clone().into_any_element();
3305 let mouse_position = tooltip_request.tooltip.mouse_position;
3306 let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
3307
3308 let mut tooltip_bounds =
3309 Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
3310 let window_bounds = Bounds {
3311 origin: Point::default(),
3312 size: self.viewport_size(),
3313 };
3314
3315 if tooltip_bounds.right() > window_bounds.right() {
3316 let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
3317 if new_x >= Pixels::ZERO {
3318 tooltip_bounds.origin.x = new_x;
3319 } else {
3320 tooltip_bounds.origin.x = cmp::max(
3321 Pixels::ZERO,
3322 tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
3323 );
3324 }
3325 }
3326
3327 if tooltip_bounds.bottom() > window_bounds.bottom() {
3328 let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
3329 if new_y >= Pixels::ZERO {
3330 tooltip_bounds.origin.y = new_y;
3331 } else {
3332 tooltip_bounds.origin.y = cmp::max(
3333 Pixels::ZERO,
3334 tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
3335 );
3336 }
3337 }
3338
3339 let is_visible =
3343 (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
3344 if !is_visible {
3345 continue;
3346 }
3347
3348 self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
3349 element.prepaint(window, cx)
3350 });
3351
3352 self.tooltip_bounds = Some(TooltipBounds {
3353 id: tooltip_request.id,
3354 bounds: tooltip_bounds,
3355 });
3356 return Some(element);
3357 }
3358 None
3359 }
3360
3361 fn prepaint_deferred_draws(&mut self, cx: &mut App) {
3362 assert_eq!(self.element_id_stack.len(), 0);
3363
3364 let mut round_start = 0;
3375 let mut depth = 0;
3376 loop {
3377 let round_end = self.next_frame.deferred_draws.len();
3378 if round_start == round_end {
3379 break;
3380 }
3381 assert!(depth < 10, "Exceeded maximum (10) deferred depth");
3383 depth += 1;
3384
3385 let mut traversal_order = (round_start..round_end).collect::<SmallVec<[usize; 8]>>();
3387 traversal_order.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3388
3389 for deferred_draw_ix in traversal_order {
3390 let (element, parent_node, current_view, rem_size, absolute_offset, prepaint_range) = {
3391 let deferred_draw = &mut self.next_frame.deferred_draws[deferred_draw_ix];
3392 self.element_id_stack
3393 .clone_from(&deferred_draw.element_id_stack);
3394 self.text_style_stack
3395 .clone_from(&deferred_draw.text_style_stack);
3396 (
3397 deferred_draw.element.take(),
3398 deferred_draw.parent_node,
3399 deferred_draw.current_view,
3400 deferred_draw.rem_size,
3401 deferred_draw.absolute_offset,
3402 deferred_draw.prepaint_range.clone(),
3403 )
3404 };
3405 self.next_frame.dispatch_tree.set_active_node(parent_node);
3406
3407 let prepaint_start = self.prepaint_index();
3408 if let Some(mut element) = element {
3409 self.with_rendered_view(current_view, |window| {
3410 window.with_rem_size(Some(rem_size), |window| {
3411 window.with_absolute_element_offset(absolute_offset, |window| {
3412 element.prepaint(window, cx);
3413 });
3414 });
3415 });
3416 self.next_frame.deferred_draws[deferred_draw_ix].element = Some(element);
3417 } else {
3418 self.reuse_prepaint(prepaint_range);
3419 }
3420 let prepaint_end = self.prepaint_index();
3421 self.next_frame.deferred_draws[deferred_draw_ix].prepaint_range =
3422 prepaint_start..prepaint_end;
3423 }
3424
3425 self.element_id_stack.clear();
3426 self.text_style_stack.clear();
3427 round_start = round_end;
3428 }
3429 }
3430
3431 fn paint_deferred_draws(&mut self, cx: &mut App) {
3432 assert_eq!(self.element_id_stack.len(), 0);
3433
3434 if self.next_frame.deferred_draws.len() == 0 {
3437 return;
3438 }
3439
3440 let traversal_order = self.deferred_draw_traversal_order();
3441 let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
3442 for deferred_draw_ix in traversal_order {
3443 let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
3444 self.element_id_stack
3445 .clone_from(&deferred_draw.element_id_stack);
3446 self.next_frame
3447 .dispatch_tree
3448 .set_active_node(deferred_draw.parent_node);
3449
3450 let paint_start = self.paint_index();
3451 let content_mask = deferred_draw.content_mask;
3452 if let Some(element) = deferred_draw.element.as_mut() {
3453 self.with_rendered_view(deferred_draw.current_view, |window| {
3454 window.with_content_mask(content_mask, |window| {
3455 window.with_rem_size(Some(deferred_draw.rem_size), |window| {
3456 element.paint(window, cx);
3457 });
3458 })
3459 })
3460 } else {
3461 self.reuse_paint(deferred_draw.paint_range.clone());
3462 }
3463 let paint_end = self.paint_index();
3464 deferred_draw.paint_range = paint_start..paint_end;
3465 }
3466 self.next_frame.deferred_draws = deferred_draws;
3467 self.element_id_stack.clear();
3468 }
3469
3470 fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
3471 let deferred_count = self.next_frame.deferred_draws.len();
3472 let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
3473 sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
3474 sorted_indices
3475 }
3476
3477 pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
3478 PrepaintStateIndex {
3479 hitboxes_index: self.next_frame.hitboxes.len(),
3480 tooltips_index: self.next_frame.tooltip_requests.len(),
3481 deferred_draws_index: self.next_frame.deferred_draws.len(),
3482 dispatch_tree_index: self.next_frame.dispatch_tree.len(),
3483 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3484 line_layout_index: self.text_system.layout_index(),
3485 }
3486 }
3487
3488 pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
3489 self.next_frame.hitboxes.extend(
3490 self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
3491 .iter()
3492 .cloned(),
3493 );
3494 self.next_frame.tooltip_requests.extend(
3495 self.rendered_frame.tooltip_requests
3496 [range.start.tooltips_index..range.end.tooltips_index]
3497 .iter_mut()
3498 .map(|request| request.take()),
3499 );
3500 self.next_frame.accessed_element_states.extend(
3501 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3502 ..range.end.accessed_element_states_index]
3503 .iter()
3504 .map(|(id, type_id)| (id.clone(), *type_id)),
3505 );
3506 self.text_system
3507 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3508
3509 let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
3510 range.start.dispatch_tree_index..range.end.dispatch_tree_index,
3511 &mut self.rendered_frame.dispatch_tree,
3512 self.focus,
3513 );
3514
3515 if reused_subtree.contains_focus() {
3516 self.next_frame.focus = self.focus;
3517 }
3518
3519 self.next_frame.deferred_draws.extend(
3520 self.rendered_frame.deferred_draws
3521 [range.start.deferred_draws_index..range.end.deferred_draws_index]
3522 .iter()
3523 .map(|deferred_draw| DeferredDraw {
3524 current_view: deferred_draw.current_view,
3525 parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
3526 element_id_stack: deferred_draw.element_id_stack.clone(),
3527 text_style_stack: deferred_draw.text_style_stack.clone(),
3528 content_mask: deferred_draw.content_mask,
3529 rem_size: deferred_draw.rem_size,
3530 priority: deferred_draw.priority,
3531 element: None,
3532 absolute_offset: deferred_draw.absolute_offset,
3533 prepaint_range: deferred_draw.prepaint_range.clone(),
3534 paint_range: deferred_draw.paint_range.clone(),
3535 }),
3536 );
3537 }
3538
3539 pub(crate) fn paint_index(&self) -> PaintIndex {
3540 PaintIndex {
3541 scene_index: self.next_frame.scene.len(),
3542 mouse_listeners_index: self.next_frame.mouse_listeners.len(),
3543 input_handlers_index: self.next_frame.input_handlers.len(),
3544 cursor_styles_index: self.next_frame.cursor_styles.len(),
3545 accessed_element_states_index: self.next_frame.accessed_element_states.len(),
3546 tab_handle_index: self.next_frame.tab_stops.paint_index(),
3547 line_layout_index: self.text_system.layout_index(),
3548 }
3549 }
3550
3551 pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
3552 self.next_frame.cursor_styles.extend(
3553 self.rendered_frame.cursor_styles
3554 [range.start.cursor_styles_index..range.end.cursor_styles_index]
3555 .iter()
3556 .cloned(),
3557 );
3558 self.next_frame.input_handlers.extend(
3559 self.rendered_frame.input_handlers
3560 [range.start.input_handlers_index..range.end.input_handlers_index]
3561 .iter_mut()
3562 .map(|handler| handler.take()),
3563 );
3564 self.next_frame.mouse_listeners.extend(
3565 self.rendered_frame.mouse_listeners
3566 [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
3567 .iter_mut()
3568 .map(|listener| listener.take()),
3569 );
3570 self.next_frame.accessed_element_states.extend(
3571 self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
3572 ..range.end.accessed_element_states_index]
3573 .iter()
3574 .map(|(id, type_id)| (id.clone(), *type_id)),
3575 );
3576 self.next_frame.tab_stops.replay(
3577 &self.rendered_frame.tab_stops.insertion_history
3578 [range.start.tab_handle_index..range.end.tab_handle_index],
3579 );
3580
3581 self.text_system
3582 .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
3583 self.next_frame.scene.replay(
3584 range.start.scene_index..range.end.scene_index,
3585 &self.rendered_frame.scene,
3586 );
3587 }
3588
3589 pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
3593 where
3594 F: FnOnce(&mut Self) -> R,
3595 {
3596 self.invalidator.debug_assert_paint_or_prepaint();
3597 if let Some(style) = style {
3598 self.text_style_stack.push(style);
3599 let result = f(self);
3600 self.text_style_stack.pop();
3601 result
3602 } else {
3603 f(self)
3604 }
3605 }
3606
3607 pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
3610 self.invalidator.debug_assert_paint();
3611 self.next_frame.cursor_styles.push(CursorStyleRequest {
3612 hitbox_id: Some(hitbox.id),
3613 style,
3614 });
3615 }
3616
3617 pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
3622 self.invalidator.debug_assert_paint();
3623 self.next_frame.cursor_styles.push(CursorStyleRequest {
3624 hitbox_id: None,
3625 style,
3626 })
3627 }
3628
3629 pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
3632 self.invalidator.debug_assert_prepaint();
3633 let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
3634 self.next_frame
3635 .tooltip_requests
3636 .push(Some(TooltipRequest { id, tooltip }));
3637 id
3638 }
3639
3640 #[inline]
3645 pub fn with_content_mask<R>(
3646 &mut self,
3647 mask: Option<ContentMask<Pixels>>,
3648 f: impl FnOnce(&mut Self) -> R,
3649 ) -> R {
3650 self.invalidator.debug_assert_paint_or_prepaint();
3651 if let Some(mask) = mask {
3652 let mask = mask.intersect(&self.content_mask());
3653 self.content_mask_stack.push(mask);
3654 let result = f(self);
3655 self.content_mask_stack.pop();
3656 result
3657 } else {
3658 f(self)
3659 }
3660 }
3661
3662 pub fn with_element_offset<R>(
3665 &mut self,
3666 offset: Point<Pixels>,
3667 f: impl FnOnce(&mut Self) -> R,
3668 ) -> R {
3669 self.invalidator.debug_assert_prepaint();
3670
3671 if offset.is_zero() {
3672 return f(self);
3673 };
3674
3675 let abs_offset = self.element_offset() + offset;
3676 self.with_absolute_element_offset(abs_offset, f)
3677 }
3678
3679 pub fn with_absolute_element_offset<R>(
3683 &mut self,
3684 offset: Point<Pixels>,
3685 f: impl FnOnce(&mut Self) -> R,
3686 ) -> R {
3687 self.invalidator.debug_assert_prepaint();
3688 self.element_offset_stack.push(offset);
3689 let result = f(self);
3690 self.element_offset_stack.pop();
3691 result
3692 }
3693
3694 pub(crate) fn with_element_opacity<R>(
3695 &mut self,
3696 opacity: Option<f32>,
3697 f: impl FnOnce(&mut Self) -> R,
3698 ) -> R {
3699 self.invalidator.debug_assert_paint_or_prepaint();
3700
3701 let Some(opacity) = opacity else {
3702 return f(self);
3703 };
3704
3705 let previous_opacity = self.element_opacity;
3706 self.element_opacity = previous_opacity * opacity;
3707 let result = f(self);
3708 self.element_opacity = previous_opacity;
3709 result
3710 }
3711
3712 pub fn with_edge_fade<R>(
3719 &mut self,
3720 fade: Option<EdgeFade>,
3721 f: impl FnOnce(&mut Self) -> R,
3722 ) -> R {
3723 let Some(fade) = fade else {
3724 return f(self);
3725 };
3726 if !(fade.top || fade.bottom || fade.left || fade.right) {
3727 return f(self);
3728 }
3729 self.invalidator.debug_assert_paint_or_prepaint();
3730 let previous = self.edge_fade.replace(fade);
3731 let result = f(self);
3732 self.edge_fade = previous;
3733 result
3734 }
3735
3736 pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
3742 self.invalidator.debug_assert_prepaint();
3743 let index = self.prepaint_index();
3744 let result = f(self);
3745 if result.is_err() {
3746 self.next_frame.hitboxes.truncate(index.hitboxes_index);
3747 self.next_frame
3748 .tooltip_requests
3749 .truncate(index.tooltips_index);
3750 self.next_frame
3751 .deferred_draws
3752 .truncate(index.deferred_draws_index);
3753 self.next_frame
3754 .dispatch_tree
3755 .truncate(index.dispatch_tree_index);
3756 self.next_frame
3757 .accessed_element_states
3758 .truncate(index.accessed_element_states_index);
3759 self.text_system.truncate_layouts(index.line_layout_index);
3760 }
3761 result
3762 }
3763
3764 pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
3770 self.invalidator.debug_assert_prepaint();
3771 self.requested_autoscroll = Some(bounds);
3772 }
3773
3774 pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
3777 self.invalidator.debug_assert_prepaint();
3778 self.requested_autoscroll.take()
3779 }
3780
3781 pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3787 let (task, is_first) = cx.fetch_asset::<A>(source);
3788 task.clone().now_or_never().or_else(|| {
3789 if is_first {
3790 let entity_id = self.current_view();
3791 self.spawn(cx, {
3792 let task = task.clone();
3793 async move |cx| {
3794 task.await;
3795
3796 cx.on_next_frame(move |_, cx| {
3797 cx.notify(entity_id);
3798 });
3799 }
3800 })
3801 .detach();
3802 }
3803
3804 None
3805 })
3806 }
3807
3808 pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3814 let (task, _) = cx.fetch_asset::<A>(source);
3815 task.now_or_never()
3816 }
3817 pub fn element_offset(&self) -> Point<Pixels> {
3820 self.invalidator.debug_assert_prepaint();
3821 self.element_offset_stack
3822 .last()
3823 .copied()
3824 .unwrap_or_default()
3825 }
3826
3827 #[inline]
3830 pub(crate) fn element_opacity(&self) -> f32 {
3831 self.invalidator.debug_assert_paint_or_prepaint();
3832 self.element_opacity
3833 }
3834
3835 #[inline]
3838 pub(crate) fn element_opacity_at(&self, center: Point<Pixels>) -> f32 {
3839 let opacity = self.element_opacity();
3840 let Some(fade) = &self.edge_fade else {
3841 return opacity;
3842 };
3843 let band = fade.band.0.max(1.0);
3844 let mut ramp: f32 = 1.0;
3845 if fade.top {
3846 ramp = ramp.min(((center.y.0 - fade.bounds.top().0) / band).clamp(0.0, 1.0));
3847 }
3848 if fade.bottom {
3849 ramp = ramp.min(((fade.bounds.bottom().0 - center.y.0) / band).clamp(0.0, 1.0));
3850 }
3851 if fade.left {
3852 ramp = ramp.min(((center.x.0 - fade.bounds.left().0) / band).clamp(0.0, 1.0));
3853 }
3854 if fade.right {
3855 ramp = ramp.min(((fade.bounds.right().0 - center.x.0) / band).clamp(0.0, 1.0));
3856 }
3857 opacity * ramp
3858 }
3859
3860 #[inline]
3867 pub(crate) fn element_opacity_for_bounds(&self, bounds: &Bounds<Pixels>) -> f32 {
3868 let opacity = self.element_opacity();
3869 let Some(fade) = &self.edge_fade else {
3870 return opacity;
3871 };
3872 let band = fade.band.0.max(1.0);
3873 let mut ramp: f32 = 1.0;
3874 if fade.top {
3875 ramp = ramp.min(((bounds.top().0 - fade.bounds.top().0) / band).clamp(0.0, 1.0));
3876 }
3877 if fade.bottom {
3878 ramp = ramp.min(((fade.bounds.bottom().0 - bounds.bottom().0) / band).clamp(0.0, 1.0));
3879 }
3880 if fade.left {
3881 ramp = ramp.min(((bounds.left().0 - fade.bounds.left().0) / band).clamp(0.0, 1.0));
3882 }
3883 if fade.right {
3884 ramp = ramp.min(((fade.bounds.right().0 - bounds.right().0) / band).clamp(0.0, 1.0));
3885 }
3886 opacity * ramp
3887 }
3888
3889 fn quad_fade_gradient(
3898 &self,
3899 bounds: Bounds<Pixels>,
3900 background: &Background,
3901 ) -> Option<Background> {
3902 let fade = self.edge_fade.as_ref()?;
3903 if background.tag != crate::color::BackgroundTag::Solid {
3904 return None;
3905 }
3906 let horizontal = fade.left || fade.right;
3907 let vertical = fade.top || fade.bottom;
3908 if horizontal == vertical {
3909 return None;
3910 }
3911 let band = fade.band.0.max(1.0);
3912 let (lo, hi, edge_lo, edge_hi, fade_lo, fade_hi, angle) = if horizontal {
3913 (
3914 bounds.left().0,
3915 bounds.right().0,
3916 fade.bounds.left().0,
3917 fade.bounds.right().0,
3918 fade.left,
3919 fade.right,
3920 90.0,
3921 )
3922 } else {
3923 (
3924 bounds.top().0,
3925 bounds.bottom().0,
3926 fade.bounds.top().0,
3927 fade.bounds.bottom().0,
3928 fade.top,
3929 fade.bottom,
3930 180.0,
3931 )
3932 };
3933 let extent = (hi - lo).max(1.0);
3934 let in_lo_band = fade_lo && lo < edge_lo + band;
3935 let in_hi_band = fade_hi && hi > edge_hi - band;
3936 let base = self.element_opacity();
3937 let color = background.solid;
3938 let (v0, v1, a0, a1) = match (in_lo_band, in_hi_band) {
3944 (true, true) | (false, false) => return None,
3947 (true, false) => {
3948 let v0 = lo.max(edge_lo);
3949 let v1 = hi.min(edge_lo + band);
3950 let ramp = |v: f32| ((v - edge_lo) / band).clamp(0.0, 1.0);
3951 (v0, v1, ramp(v0), ramp(v1))
3952 }
3953 (false, true) => {
3954 let v0 = lo.max(edge_hi - band);
3955 let v1 = hi.min(edge_hi);
3956 let ramp = |v: f32| ((edge_hi - v) / band).clamp(0.0, 1.0);
3957 (v0, v1, ramp(v0), ramp(v1))
3958 }
3959 };
3960 let p0 = (v0 - lo) / extent;
3961 let p1 = (v1 - lo) / extent;
3962 if (p1 - p0) < 0.001 {
3963 return None;
3964 }
3965 Some(crate::linear_gradient(
3966 angle,
3967 crate::linear_color_stop(color.opacity(a0 * base), p0),
3968 crate::linear_color_stop(color.opacity(a1 * base), p1),
3969 ))
3970 }
3971
3972 pub fn content_mask(&self) -> ContentMask<Pixels> {
3974 self.invalidator.debug_assert_paint_or_prepaint();
3975 self.content_mask_stack.last().cloned().unwrap_or_else(|| {
3976 ContentMask::new(Bounds {
3977 origin: Point::default(),
3978 size: self.viewport_size,
3979 })
3980 })
3981 }
3982
3983 pub fn with_element_namespace<R>(
3986 &mut self,
3987 element_id: impl Into<ElementId>,
3988 f: impl FnOnce(&mut Self) -> R,
3989 ) -> R {
3990 self.element_id_stack.push(element_id.into());
3991 let result = f(self);
3992 self.element_id_stack.pop();
3993 result
3994 }
3995
3996 pub fn use_keyed_state<S: 'static>(
3998 &mut self,
3999 key: impl Into<ElementId>,
4000 cx: &mut App,
4001 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4002 ) -> Entity<S> {
4003 let current_view = self.current_view();
4004 self.with_global_id(key.into(), |global_id, window| {
4005 window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
4006 if let Some(state) = state {
4007 (state.clone(), state)
4008 } else {
4009 let new_state = cx.new(|cx| init(window, cx));
4010 cx.observe(&new_state, move |_, cx| {
4011 cx.notify(current_view);
4012 })
4013 .detach();
4014 (new_state.clone(), new_state)
4015 }
4016 })
4017 })
4018 }
4019
4020 #[track_caller]
4026 pub fn use_state<S: 'static>(
4027 &mut self,
4028 cx: &mut App,
4029 init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
4030 ) -> Entity<S> {
4031 self.use_keyed_state(
4032 ElementId::CodeLocation(*core::panic::Location::caller()),
4033 cx,
4034 init,
4035 )
4036 }
4037
4038 pub fn with_element_state<S, R>(
4043 &mut self,
4044 global_id: &GlobalElementId,
4045 f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
4046 ) -> R
4047 where
4048 S: 'static,
4049 {
4050 self.invalidator.debug_assert_paint_or_prepaint();
4051
4052 let key = (global_id.clone(), TypeId::of::<S>());
4053 self.next_frame.accessed_element_states.push(key.clone());
4054
4055 if let Some(any) = self
4056 .next_frame
4057 .element_states
4058 .remove(&key)
4059 .or_else(|| self.rendered_frame.element_states.remove(&key))
4060 {
4061 let ElementStateBox {
4062 inner,
4063 #[cfg(debug_assertions)]
4064 type_name,
4065 } = any;
4066 let mut state_box = inner
4068 .downcast::<Option<S>>()
4069 .map_err(|_| {
4070 #[cfg(debug_assertions)]
4071 {
4072 anyhow::anyhow!(
4073 "invalid element state type for id, requested {:?}, actual: {:?}",
4074 std::any::type_name::<S>(),
4075 type_name
4076 )
4077 }
4078
4079 #[cfg(not(debug_assertions))]
4080 {
4081 anyhow::anyhow!(
4082 "invalid element state type for id, requested {:?}",
4083 std::any::type_name::<S>(),
4084 )
4085 }
4086 })
4087 .unwrap();
4088
4089 let state = state_box.take().expect(
4090 "reentrant call to with_element_state for the same state type and element id",
4091 );
4092 let (result, state) = f(Some(state), self);
4093 state_box.replace(state);
4094 self.next_frame.element_states.insert(
4095 key,
4096 ElementStateBox {
4097 inner: state_box,
4098 #[cfg(debug_assertions)]
4099 type_name,
4100 },
4101 );
4102 result
4103 } else {
4104 let (result, state) = f(None, self);
4105 self.next_frame.element_states.insert(
4106 key,
4107 ElementStateBox {
4108 inner: Box::new(Some(state)),
4109 #[cfg(debug_assertions)]
4110 type_name: std::any::type_name::<S>(),
4111 },
4112 );
4113 result
4114 }
4115 }
4116
4117 pub fn with_optional_element_state<S, R>(
4124 &mut self,
4125 global_id: Option<&GlobalElementId>,
4126 f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
4127 ) -> R
4128 where
4129 S: 'static,
4130 {
4131 self.invalidator.debug_assert_paint_or_prepaint();
4132
4133 if let Some(global_id) = global_id {
4134 self.with_element_state(global_id, |state, cx| {
4135 let (result, state) = f(Some(state), cx);
4136 let state =
4137 state.expect("you must return some state when you pass some element id");
4138 (result, state)
4139 })
4140 } else {
4141 let (result, state) = f(None, self);
4142 debug_assert!(
4143 state.is_none(),
4144 "you must not return an element state when passing None for the global id"
4145 );
4146 result
4147 }
4148 }
4149
4150 #[inline]
4152 pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
4153 if let Some(index) = index {
4154 self.next_frame.tab_stops.begin_group(index);
4155 let result = f(self);
4156 self.next_frame.tab_stops.end_group();
4157 result
4158 } else {
4159 f(self)
4160 }
4161 }
4162
4163 pub fn defer_draw(
4172 &mut self,
4173 element: AnyElement,
4174 absolute_offset: Point<Pixels>,
4175 priority: usize,
4176 content_mask: Option<ContentMask<Pixels>>,
4177 ) {
4178 self.invalidator.debug_assert_prepaint();
4179 let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
4180 self.next_frame.deferred_draws.push(DeferredDraw {
4181 current_view: self.current_view(),
4182 parent_node,
4183 element_id_stack: self.element_id_stack.clone(),
4184 text_style_stack: self.text_style_stack.clone(),
4185 content_mask,
4186 rem_size: self.rem_size(),
4187 priority,
4188 element: Some(element),
4189 absolute_offset,
4190 prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
4191 paint_range: PaintIndex::default()..PaintIndex::default(),
4192 });
4193 }
4194
4195 pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
4201 self.invalidator.debug_assert_paint();
4202
4203 let content_mask = self.content_mask();
4204 let clipped_bounds = bounds.intersect(&content_mask.bounds);
4205 if !clipped_bounds.is_empty() {
4206 self.next_frame
4207 .scene
4208 .push_layer(self.cover_bounds(clipped_bounds));
4209 }
4210
4211 let result = f(self);
4212
4213 if !clipped_bounds.is_empty() {
4214 self.next_frame.scene.pop_layer();
4215 }
4216
4217 result
4218 }
4219
4220 pub fn paint_drop_shadows(
4226 &mut self,
4227 bounds: Bounds<Pixels>,
4228 corner_radii: Corners<Pixels>,
4229 shadows: &[BoxShadow],
4230 ) {
4231 self.drop_shadows(bounds, corner_radii, shadows, false);
4232 }
4233
4234 pub fn paint_drop_shadows_outside(
4243 &mut self,
4244 bounds: Bounds<Pixels>,
4245 corner_radii: Corners<Pixels>,
4246 shadows: &[BoxShadow],
4247 ) {
4248 self.drop_shadows(bounds, corner_radii, shadows, true);
4249 }
4250
4251 fn drop_shadows(
4252 &mut self,
4253 bounds: Bounds<Pixels>,
4254 corner_radii: Corners<Pixels>,
4255 shadows: &[BoxShadow],
4256 outside: bool,
4257 ) {
4258 self.invalidator.debug_assert_paint();
4259
4260 let scale_factor = self.scale_factor();
4261 let content_mask = self.snapped_content_mask();
4262 let opacity = self.element_opacity_for_bounds(&bounds);
4263 let element_bounds = self.cover_bounds(bounds);
4264 let element_corner_radii = corner_radii.scale(scale_factor);
4265 for shadow in shadows {
4266 if shadow.inset {
4267 continue;
4268 }
4269 let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
4270 self.next_frame.scene.insert_primitive(Shadow {
4271 order: 0,
4272 blur_radius: shadow.blur_radius.scale(scale_factor),
4273 bounds: self.cover_bounds(shadow_bounds),
4274 content_mask,
4275 corner_radii: corner_radii.scale(scale_factor),
4276 color: shadow.color.opacity(opacity),
4277 element_bounds,
4278 element_corner_radii,
4279 inset: if outside { 2 } else { 0 },
4280 pad: 0,
4281 });
4282 }
4283 }
4284
4285 pub fn paint_inset_shadows(
4289 &mut self,
4290 bounds: Bounds<Pixels>,
4291 corner_radii: Corners<Pixels>,
4292 shadows: &[BoxShadow],
4293 ) {
4294 self.invalidator.debug_assert_paint();
4295
4296 let scale_factor = self.scale_factor();
4297 let content_mask = self.snapped_content_mask();
4298 let opacity = self.element_opacity_for_bounds(&bounds);
4299 let element_bounds = self.cover_bounds(bounds);
4300 let element_corner_radii = corner_radii.scale(scale_factor);
4301 for shadow in shadows {
4302 if !shadow.inset {
4303 continue;
4304 }
4305 let hole = (bounds + shadow.offset).dilate(-shadow.spread_radius);
4306 let zero = Pixels::ZERO;
4309 let hole_corner_radii = Corners {
4310 top_left: (corner_radii.top_left - shadow.spread_radius).max(zero),
4311 top_right: (corner_radii.top_right - shadow.spread_radius).max(zero),
4312 bottom_right: (corner_radii.bottom_right - shadow.spread_radius).max(zero),
4313 bottom_left: (corner_radii.bottom_left - shadow.spread_radius).max(zero),
4314 };
4315 self.next_frame.scene.insert_primitive(Shadow {
4316 order: 0,
4317 blur_radius: shadow.blur_radius.scale(scale_factor),
4318 bounds: self.cover_bounds(hole),
4319 content_mask,
4320 corner_radii: hole_corner_radii.scale(scale_factor),
4321 color: shadow.color.opacity(opacity),
4322 element_bounds,
4323 element_corner_radii,
4324 inset: 1,
4325 pad: 0,
4326 });
4327 }
4328 }
4329
4330 pub fn paint_backdrop_blur(
4336 &mut self,
4337 bounds: Bounds<Pixels>,
4338 corner_radii: Corners<Pixels>,
4339 glass: GlassEffect,
4340 ) {
4341 self.invalidator.debug_assert_paint();
4342 let scale_factor = self.scale_factor();
4343 let content_mask = self.content_mask().scale(scale_factor);
4344 let limit = bounds.size.width.min(bounds.size.height) / 2.;
4348 let corner_radii = Corners {
4349 top_left: corner_radii.top_left.min(limit),
4350 top_right: corner_radii.top_right.min(limit),
4351 bottom_right: corner_radii.bottom_right.min(limit),
4352 bottom_left: corner_radii.bottom_left.min(limit),
4353 };
4354 self.next_frame.scene.insert_primitive(Shadow {
4357 order: 0,
4358 blur_radius: ScaledPixels(0.),
4359 bounds: bounds.scale(scale_factor),
4360 corner_radii: corner_radii.scale(scale_factor),
4361 content_mask,
4362 color: crate::transparent_black(),
4363 element_bounds: bounds.scale(scale_factor),
4364 element_corner_radii: corner_radii.scale(scale_factor),
4365 inset: 0,
4366 pad: 0,
4367 });
4368 self.next_frame.scene.insert_backdrop_blur(BackdropBlur {
4369 order: 0,
4370 blur_radius: glass.blur_radius.scale(scale_factor),
4371 bounds: bounds.scale(scale_factor),
4372 content_mask,
4373 corner_radii: corner_radii.scale(scale_factor),
4374 lens: glass.lens.scale(scale_factor),
4375 reach: glass.reach.scale(scale_factor),
4376 magnify: glass.magnify,
4377 dispersion: glass.dispersion,
4378 gain: glass.gain,
4379 saturation: glass.saturation,
4380 tint: glass.tint,
4381 edge: glass.edge,
4382 edge_width: glass.edge_width.scale(scale_factor),
4383 edge_aa: glass.edge_aa.scale(scale_factor),
4384 opacity: self.element_opacity_for_bounds(&bounds),
4387 });
4388 }
4389
4390 fn largest_border_interior(quad: &Quad) -> Bounds<ScaledPixels> {
4391 let radii = &quad.corner_radii;
4392 let widths = &quad.border_widths;
4393 let edge_radii = Edges {
4394 top: radii.top_left.max(radii.top_right),
4395 right: radii.top_right.max(radii.bottom_right),
4396 bottom: radii.bottom_left.max(radii.bottom_right),
4397 left: radii.top_left.max(radii.bottom_left),
4398 };
4399
4400 let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0));
4401 let inset_bounds = |top_left_inset, bottom_right_inset| {
4402 Bounds::from_corners(
4403 quad.bounds.origin + top_left_inset + antialias_inset,
4404 quad.bounds.bottom_right() - bottom_right_inset - antialias_inset,
4405 )
4406 };
4407
4408 let horizontal_band = inset_bounds(
4411 point(widths.left, widths.top.max(edge_radii.top)),
4412 point(widths.right, widths.bottom.max(edge_radii.bottom)),
4413 );
4414 let vertical_band = inset_bounds(
4415 point(widths.left.max(edge_radii.left), widths.top),
4416 point(widths.right.max(edge_radii.right), widths.bottom),
4417 );
4418
4419 let area = |bounds: &Bounds<ScaledPixels>| {
4420 bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.)
4421 };
4422 if area(&horizontal_band) >= area(&vertical_band) {
4423 horizontal_band
4424 } else {
4425 vertical_band
4426 }
4427 }
4428
4429 pub fn paint_quad(&mut self, quad: PaintQuad) {
4439 self.invalidator.debug_assert_paint();
4440
4441 let opacity = self.element_opacity_at(quad.bounds.center());
4442 let background = self
4443 .quad_fade_gradient(quad.bounds, &quad.background)
4444 .unwrap_or_else(|| quad.background.opacity(opacity));
4445 let snapped_bounds = self.snap_bounds(quad.bounds);
4446 let snapped_border_widths = self.snap_border_widths(quad.border_widths);
4447 let quad = Quad {
4448 order: 0,
4449 bounds: snapped_bounds,
4450 content_mask: self.snapped_content_mask(),
4451 background,
4452 border_color: quad.border_color.opacity(opacity),
4453 corner_radii: quad.corner_radii.scale(self.scale_factor()),
4454 border_widths: snapped_border_widths,
4455 border_style: quad.border_style,
4456 };
4457
4458 if !quad.background.is_transparent() {
4459 self.next_frame.scene.insert_primitive(quad);
4460 return;
4461 }
4462
4463 let outer_bounds = quad.bounds;
4466 let inner_bounds = Self::largest_border_interior(&quad);
4467
4468 if inner_bounds.is_empty() {
4469 self.next_frame.scene.insert_primitive(quad);
4470 return;
4471 }
4472
4473 let strips = [
4474 Bounds::from_corners(
4476 outer_bounds.origin,
4477 point(outer_bounds.right(), inner_bounds.top()),
4478 ),
4479 Bounds::from_corners(
4481 point(outer_bounds.left(), inner_bounds.bottom()),
4482 outer_bounds.bottom_right(),
4483 ),
4484 Bounds::from_corners(
4486 point(outer_bounds.left(), inner_bounds.top()),
4487 inner_bounds.bottom_left(),
4488 ),
4489 Bounds::from_corners(
4491 inner_bounds.top_right(),
4492 point(outer_bounds.right(), inner_bounds.bottom()),
4493 ),
4494 ];
4495
4496 for strip in strips {
4497 let content_mask_bounds = quad.content_mask.bounds.intersect(&strip);
4498 if !content_mask_bounds.is_empty() {
4499 self.next_frame.scene.insert_primitive(Quad {
4503 content_mask: ContentMask::new(content_mask_bounds),
4504 ..quad
4505 });
4506 }
4507 }
4508 }
4509
4510 pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
4514 self.invalidator.debug_assert_paint();
4515
4516 let scale_factor = self.scale_factor();
4517 let content_mask = self.content_mask();
4518 let opacity = self.element_opacity_for_bounds(&path.bounds);
4519 path.content_mask = content_mask;
4520 let color: Background = color.into();
4521 path.color = color.opacity(opacity);
4522 self.next_frame
4523 .scene
4524 .insert_primitive(path.scale(scale_factor));
4525 }
4526
4527 pub fn paint_underline(
4531 &mut self,
4532 origin: Point<Pixels>,
4533 width: Pixels,
4534 style: &UnderlineStyle,
4535 ) {
4536 self.invalidator.debug_assert_paint();
4537
4538 let scale_factor = self.scale_factor();
4539 let thickness = self.snap_stroke(style.thickness);
4540 let height = if style.wavy {
4541 ScaledPixels(thickness.0 * 3.)
4542 } else {
4543 thickness
4544 };
4545 let bounds = Bounds {
4546 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4547 size: size(self.snap_stroke(width), height),
4548 };
4549 let element_opacity = self.element_opacity_at(origin);
4550
4551 self.next_frame.scene.insert_primitive(Underline {
4552 order: 0,
4553 pad: 0,
4554 bounds,
4555 content_mask: self.snapped_content_mask(),
4556 color: style.color.unwrap_or_default().opacity(element_opacity),
4557 thickness,
4558 wavy: style.wavy.into(),
4559 });
4560 }
4561
4562 pub fn paint_strikethrough(
4566 &mut self,
4567 origin: Point<Pixels>,
4568 width: Pixels,
4569 style: &StrikethroughStyle,
4570 ) {
4571 self.invalidator.debug_assert_paint();
4572
4573 let scale_factor = self.scale_factor();
4574 let height = style.thickness;
4575 let bounds = Bounds {
4576 origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
4577 size: size(self.snap_stroke(width), self.snap_stroke(height)),
4578 };
4579 let opacity = self.element_opacity_at(origin);
4580
4581 self.next_frame.scene.insert_primitive(Underline {
4582 order: 0,
4583 pad: 0,
4584 bounds,
4585 content_mask: self.snapped_content_mask(),
4586 thickness: self.snap_stroke(style.thickness),
4587 color: style.color.unwrap_or_default().opacity(opacity),
4588 wavy: false.into(),
4589 });
4590 }
4591
4592 pub fn paint_glyph(
4601 &mut self,
4602 origin: Point<Pixels>,
4603 font_id: FontId,
4604 glyph_id: GlyphId,
4605 font_size: Pixels,
4606 color: Hsla,
4607 ) -> Result<()> {
4608 self.invalidator.debug_assert_paint();
4609
4610 let element_opacity = self.element_opacity_for_bounds(&Bounds {
4611 origin,
4612 size: size(font_size * 0.6, font_size),
4613 });
4614 let scale_factor = self.scale_factor();
4615 let glyph_origin = origin.scale(scale_factor);
4616
4617 let quantized_origin = Point::new(
4618 round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
4619 / SUBPIXEL_VARIANTS_X as f32,
4620 round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
4621 / SUBPIXEL_VARIANTS_Y as f32,
4622 );
4623 let subpixel_variant = Point::new(
4624 (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
4625 (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
4626 );
4627 let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
4628 let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
4629 let dilation = self.text_system().glyph_dilation_for_color(color);
4630 let params = RenderGlyphParams {
4631 font_id,
4632 glyph_id,
4633 font_size,
4634 subpixel_variant,
4635 scale_factor,
4636 is_emoji: false,
4637 subpixel_rendering,
4638 dilation,
4639 };
4640
4641 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4642 if !raster_bounds.is_zero() {
4643 let tile = self
4644 .sprite_atlas
4645 .get_or_insert_with(¶ms.clone().into(), &mut || {
4646 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4647 Ok(Some((size, Cow::Owned(bytes))))
4648 })?
4649 .expect("Callback above only errors or returns Some");
4650 let bounds = Bounds {
4651 origin: integer_origin + raster_bounds.origin.map(Into::into),
4652 size: tile.bounds.size.map(Into::into),
4653 };
4654 let content_mask = self.snapped_content_mask();
4655
4656 if subpixel_rendering {
4657 self.next_frame.scene.insert_primitive(SubpixelSprite {
4658 order: 0,
4659 pad: 0,
4660 bounds,
4661 content_mask,
4662 color: color.opacity(element_opacity),
4663 tile,
4664 transformation: TransformationMatrix::unit(),
4665 });
4666 } else {
4667 self.next_frame.scene.insert_primitive(MonochromeSprite {
4668 order: 0,
4669 pad: 0,
4670 bounds,
4671 content_mask,
4672 color: color.opacity(element_opacity),
4673 tile,
4674 transformation: TransformationMatrix::unit(),
4675 });
4676 }
4677 }
4678 Ok(())
4679 }
4680
4681 fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
4682 if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
4683 return false;
4684 }
4685
4686 if !self.platform_window.is_subpixel_rendering_supported() {
4687 return false;
4688 }
4689
4690 let mode = match self.text_rendering_mode.get() {
4691 TextRenderingMode::PlatformDefault => self
4692 .text_system()
4693 .recommended_rendering_mode(font_id, font_size),
4694 mode => mode,
4695 };
4696
4697 mode == TextRenderingMode::Subpixel
4698 }
4699
4700 pub fn paint_emoji(
4709 &mut self,
4710 origin: Point<Pixels>,
4711 font_id: FontId,
4712 glyph_id: GlyphId,
4713 font_size: Pixels,
4714 ) -> Result<()> {
4715 self.invalidator.debug_assert_paint();
4716
4717 let scale_factor = self.scale_factor();
4718 let glyph_origin = origin.scale(scale_factor);
4719 let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
4720 let params = RenderGlyphParams {
4721 font_id,
4722 glyph_id,
4723 font_size,
4724 subpixel_variant: Default::default(),
4725 scale_factor,
4726 is_emoji: true,
4727 subpixel_rendering: false,
4728 dilation: 0,
4729 };
4730
4731 let raster_bounds = self.text_system().raster_bounds(¶ms)?;
4732 if !raster_bounds.is_zero() {
4733 let tile = self
4734 .sprite_atlas
4735 .get_or_insert_with(¶ms.clone().into(), &mut || {
4736 let (size, bytes) = self.text_system().rasterize_glyph(¶ms)?;
4737 Ok(Some((size, Cow::Owned(bytes))))
4738 })?
4739 .expect("Callback above only errors or returns Some");
4740
4741 let bounds = Bounds {
4742 origin: integer_origin + raster_bounds.origin.map(Into::into),
4743 size: tile.bounds.size.map(Into::into),
4744 };
4745 let content_mask = self.snapped_content_mask();
4746 let opacity = self.element_opacity_for_bounds(&Bounds {
4747 origin,
4748 size: size(font_size * 0.6, font_size),
4749 });
4750
4751 self.next_frame.scene.insert_primitive(PolychromeSprite {
4752 order: 0,
4753 pad: 0,
4754 grayscale: false.into(),
4755 bounds,
4756 corner_radii: Default::default(),
4757 content_mask,
4758 tile,
4759 opacity,
4760 });
4761 }
4762 Ok(())
4763 }
4764
4765 pub fn paint_svg(
4769 &mut self,
4770 bounds: Bounds<Pixels>,
4771 path: SharedString,
4772 mut data: Option<&[u8]>,
4773 transformation: TransformationMatrix,
4774 color: Hsla,
4775 cx: &App,
4776 ) -> Result<()> {
4777 self.invalidator.debug_assert_paint();
4778
4779 let element_opacity = self.element_opacity_for_bounds(&bounds);
4780 let bounds = self.snap_bounds(bounds);
4781
4782 let params = RenderSvgParams {
4783 path,
4784 size: bounds.size.map(|pixels| {
4785 DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
4786 }),
4787 };
4788
4789 let Some(tile) =
4790 self.sprite_atlas
4791 .get_or_insert_with(¶ms.clone().into(), &mut || {
4792 let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(¶ms, data)?
4793 else {
4794 return Ok(None);
4795 };
4796 Ok(Some((size, Cow::Owned(bytes))))
4797 })?
4798 else {
4799 return Ok(());
4800 };
4801 let content_mask = self.snapped_content_mask();
4802 let svg_bounds = Bounds {
4803 origin: bounds.center()
4804 - Point::new(
4805 ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4806 ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
4807 ),
4808 size: tile
4809 .bounds
4810 .size
4811 .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
4812 };
4813 let final_bounds = svg_bounds
4814 .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
4815 .map_size(|size| size.ceil());
4816
4817 self.next_frame.scene.insert_primitive(MonochromeSprite {
4818 order: 0,
4819 pad: 0,
4820 bounds: final_bounds,
4821 content_mask,
4822 color: color.opacity(element_opacity),
4823 tile,
4824 transformation,
4825 });
4826
4827 Ok(())
4828 }
4829
4830 pub fn paint_image(
4839 &mut self,
4840 bounds: Bounds<Pixels>,
4841 image_bounds: Bounds<Pixels>,
4842 corner_radii: Corners<Pixels>,
4843 data: Arc<RenderImage>,
4844 frame_index: usize,
4845 grayscale: bool,
4846 ) -> Result<()> {
4847 self.invalidator.debug_assert_paint();
4848
4849 let fade_bounds = bounds;
4850 let visible_bounds = bounds.intersect(&image_bounds);
4851 if visible_bounds.size.width <= Pixels::ZERO || visible_bounds.size.height <= Pixels::ZERO {
4852 return Ok(());
4853 }
4854 if image_bounds.size.width <= Pixels::ZERO || image_bounds.size.height <= Pixels::ZERO {
4855 return Ok(());
4856 }
4857
4858 let params = RenderImageParams {
4859 image_id: data.id,
4860 frame_index,
4861 };
4862
4863 let tile = self
4864 .sprite_atlas
4865 .get_or_insert_with(¶ms.into(), &mut || {
4866 Ok(Some((
4867 data.size(frame_index),
4868 Cow::Borrowed(
4869 data.as_bytes(frame_index)
4870 .expect("It's the caller's job to pass a valid frame index"),
4871 ),
4872 )))
4873 })?
4874 .expect("Callback above only returns Some");
4875
4876 let visible_bounds_snapped = self.snap_bounds(visible_bounds);
4877
4878 let sub_tile = if visible_bounds == image_bounds {
4879 tile
4880 } else {
4881 let x_offset_ratio =
4882 (visible_bounds.origin.x - image_bounds.origin.x) / image_bounds.size.width;
4883 let y_offset_ratio =
4884 (visible_bounds.origin.y - image_bounds.origin.y) / image_bounds.size.height;
4885 let width_ratio = visible_bounds.size.width / image_bounds.size.width;
4886 let height_ratio = visible_bounds.size.height / image_bounds.size.height;
4887
4888 let tile_origin_x = tile.bounds.origin.x.0;
4889 let tile_origin_y = tile.bounds.origin.y.0;
4890 let tile_width = tile.bounds.size.width.0;
4891 let tile_height = tile.bounds.size.height.0;
4892
4893 let sub_origin_x = tile_origin_x + (x_offset_ratio * tile_width as f32).round() as i32;
4894 let sub_origin_y = tile_origin_y + (y_offset_ratio * tile_height as f32).round() as i32;
4895 let sub_width = (width_ratio * tile_width as f32).round() as i32;
4896 let sub_height = (height_ratio * tile_height as f32).round() as i32;
4897
4898 let max_x = tile_origin_x + tile_width;
4899 let max_y = tile_origin_y + tile_height;
4900
4901 let clamped_origin_x = sub_origin_x.clamp(tile_origin_x, max_x);
4902 let clamped_origin_y = sub_origin_y.clamp(tile_origin_y, max_y);
4903 let clamped_width = sub_width.min(max_x - clamped_origin_x).max(0);
4904 let clamped_height = sub_height.min(max_y - clamped_origin_y).max(0);
4905
4906 AtlasTile {
4907 bounds: Bounds {
4908 origin: point(
4909 DevicePixels(clamped_origin_x),
4910 DevicePixels(clamped_origin_y),
4911 ),
4912 size: size(DevicePixels(clamped_width), DevicePixels(clamped_height)),
4913 },
4914 ..tile
4915 }
4916 };
4917
4918 let content_mask = self.snapped_content_mask();
4919 let corner_radii = corner_radii
4920 .clamp_radii_for_quad_size(visible_bounds.size)
4921 .scale(self.scale_factor());
4922 let opacity = self.element_opacity_for_bounds(&fade_bounds);
4923
4924 self.next_frame.scene.insert_primitive(PolychromeSprite {
4925 order: 0,
4926 pad: 0,
4927 grayscale: grayscale.into(),
4928 bounds: visible_bounds_snapped,
4929 content_mask,
4930 corner_radii,
4931 tile: sub_tile,
4932 opacity,
4933 });
4934 Ok(())
4935 }
4936
4937 #[cfg(target_os = "macos")]
4941 pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
4942 use crate::PaintSurface;
4943
4944 self.invalidator.debug_assert_paint();
4945
4946 let bounds = self.snap_bounds(bounds);
4947 let content_mask = self.snapped_content_mask();
4948 self.next_frame.scene.insert_primitive(PaintSurface {
4949 order: 0,
4950 bounds,
4951 content_mask,
4952 image_buffer,
4953 });
4954 }
4955
4956 pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
4958 for frame_index in 0..data.frame_count() {
4959 let params = RenderImageParams {
4960 image_id: data.id,
4961 frame_index,
4962 };
4963
4964 self.sprite_atlas.remove(¶ms.clone().into());
4965 }
4966
4967 Ok(())
4968 }
4969
4970 #[cfg(any(test, feature = "test-support"))]
4972 pub fn has_image_atlas_entry(&self, data: &RenderImage) -> bool {
4973 data.frame_count() > 0
4974 && (0..data.frame_count()).all(|frame_index| {
4975 self.sprite_atlas.contains(
4976 &RenderImageParams {
4977 image_id: data.id,
4978 frame_index,
4979 }
4980 .into(),
4981 )
4982 })
4983 }
4984
4985 #[must_use]
4991 pub fn request_layout(
4992 &mut self,
4993 style: Style,
4994 children: impl IntoIterator<Item = LayoutId>,
4995 cx: &mut App,
4996 ) -> LayoutId {
4997 self.invalidator.debug_assert_prepaint();
4998
4999 cx.layout_id_buffer.clear();
5000 cx.layout_id_buffer.extend(children);
5001 let rem_size = self.rem_size();
5002 let scale_factor = self.scale_factor();
5003
5004 self.layout_engine.as_mut().unwrap().request_layout(
5005 style,
5006 rem_size,
5007 scale_factor,
5008 &cx.layout_id_buffer,
5009 )
5010 }
5011
5012 pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
5021 where
5022 F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
5023 + 'static,
5024 {
5025 self.invalidator.debug_assert_prepaint();
5026
5027 let rem_size = self.rem_size();
5028 let scale_factor = self.scale_factor();
5029 self.layout_engine
5030 .as_mut()
5031 .unwrap()
5032 .request_measured_layout(style, rem_size, scale_factor, measure)
5033 }
5034
5035 pub fn compute_layout(
5041 &mut self,
5042 layout_id: LayoutId,
5043 available_space: Size<AvailableSpace>,
5044 cx: &mut App,
5045 ) {
5046 self.invalidator.debug_assert_prepaint();
5047
5048 let mut layout_engine = self.layout_engine.take().unwrap();
5049 layout_engine.compute_layout(layout_id, available_space, self, cx);
5050 self.layout_engine = Some(layout_engine);
5051 }
5052
5053 pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
5058 self.invalidator.debug_assert_prepaint();
5059
5060 let scale_factor = self.scale_factor();
5061 let mut bounds = self
5062 .layout_engine
5063 .as_mut()
5064 .unwrap()
5065 .layout_bounds(layout_id, scale_factor)
5066 .map(Into::into);
5067 let snapped_offset = self.pixel_snap_point(self.element_offset());
5068 bounds.origin += snapped_offset;
5069 bounds
5070 }
5071
5072 pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
5078 self.invalidator.debug_assert_prepaint();
5079
5080 let content_mask = self.content_mask();
5081 let mut id = self.next_hitbox_id;
5082 self.next_hitbox_id = self.next_hitbox_id.next();
5083 let hitbox = Hitbox {
5084 id,
5085 bounds,
5086 content_mask,
5087 behavior,
5088 };
5089 self.next_frame.hitboxes.push(hitbox.clone());
5090 hitbox
5091 }
5092
5093 pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
5097 self.invalidator.debug_assert_paint();
5098 self.next_frame.window_control_hitboxes.push((area, hitbox));
5099 }
5100
5101 pub fn set_key_context(&mut self, context: KeyContext) {
5106 self.invalidator.debug_assert_paint();
5107 self.next_frame.dispatch_tree.set_key_context(context);
5108 }
5109
5110 pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
5115 self.invalidator.debug_assert_prepaint();
5116 if focus_handle.is_focused(self) {
5117 self.next_frame.focus = Some(focus_handle.id);
5118 }
5119 self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
5120 }
5121
5122 pub fn set_view_id(&mut self, view_id: EntityId) {
5128 self.invalidator.debug_assert_prepaint();
5129 self.next_frame.dispatch_tree.set_view_id(view_id);
5130 }
5131
5132 pub fn current_view(&self) -> EntityId {
5134 self.invalidator.debug_assert_paint_or_prepaint();
5135 self.rendered_entity_stack.last().copied().unwrap()
5136 }
5137
5138 #[inline]
5139 pub(crate) fn with_rendered_view<R>(
5140 &mut self,
5141 id: EntityId,
5142 f: impl FnOnce(&mut Self) -> R,
5143 ) -> R {
5144 self.rendered_entity_stack.push(id);
5145 let result = f(self);
5146 self.rendered_entity_stack.pop();
5147 result
5148 }
5149
5150 pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
5152 where
5153 F: FnOnce(&mut Self) -> R,
5154 {
5155 if let Some(image_cache) = image_cache {
5156 self.image_cache_stack.push(image_cache);
5157 let result = f(self);
5158 self.image_cache_stack.pop();
5159 result
5160 } else {
5161 f(self)
5162 }
5163 }
5164
5165 pub fn handle_input(
5174 &mut self,
5175 focus_handle: &FocusHandle,
5176 input_handler: impl InputHandler,
5177 cx: &App,
5178 ) {
5179 self.invalidator.debug_assert_paint();
5180
5181 if focus_handle.is_focused(self) {
5182 let cx = self.to_async(cx);
5183 self.next_frame
5184 .input_handlers
5185 .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
5186 }
5187 }
5188
5189 fn apply_text_input_configuration(&mut self, cx: &mut App) {
5194 let configuration = match self.platform_window.take_input_handler() {
5195 Some(mut input_handler) => {
5196 let configuration = input_handler.text_input_configuration(self, cx);
5197 self.platform_window.set_input_handler(input_handler);
5198 configuration
5199 }
5200 None => TextInputConfiguration::default(),
5201 };
5202 if self.last_text_input_configuration.as_ref() != Some(&configuration) {
5203 self.platform_window
5204 .set_text_input_configuration(configuration.clone());
5205 self.last_text_input_configuration = Some(configuration);
5206 }
5207 }
5208
5209 pub fn on_mouse_event<Event: MouseEvent>(
5215 &mut self,
5216 mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5217 ) {
5218 self.invalidator.debug_assert_paint();
5219
5220 self.next_frame.mouse_listeners.push(Some(Box::new(
5221 move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
5222 if let Some(event) = event.downcast_ref() {
5223 listener(event, phase, window, cx)
5224 }
5225 },
5226 )));
5227 }
5228
5229 pub fn on_key_event<Event: KeyEvent>(
5238 &mut self,
5239 listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
5240 ) {
5241 self.invalidator.debug_assert_paint();
5242
5243 self.next_frame.dispatch_tree.on_key_event(Rc::new(
5244 move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
5245 if let Some(event) = event.downcast_ref::<Event>() {
5246 listener(event, phase, window, cx)
5247 }
5248 },
5249 ));
5250 }
5251
5252 pub fn on_modifiers_changed(
5259 &mut self,
5260 listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
5261 ) {
5262 self.invalidator.debug_assert_paint();
5263
5264 self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
5265 move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
5266 listener(event, window, cx)
5267 },
5268 ));
5269 }
5270
5271 pub fn on_focus_in(
5275 &mut self,
5276 handle: &FocusHandle,
5277 cx: &mut App,
5278 mut listener: impl FnMut(&mut Window, &mut App) + 'static,
5279 ) -> Subscription {
5280 let focus_id = handle.id;
5281 let (subscription, activate) =
5282 self.new_focus_listener(Box::new(move |event, window, cx| {
5283 if event.is_focus_in(focus_id) {
5284 listener(window, cx);
5285 }
5286 true
5287 }));
5288 cx.defer(move |_| activate());
5289 subscription
5290 }
5291
5292 pub fn on_focus_out(
5295 &mut self,
5296 handle: &FocusHandle,
5297 cx: &mut App,
5298 mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
5299 ) -> Subscription {
5300 let focus_id = handle.id;
5301 let (subscription, activate) =
5302 self.new_focus_listener(Box::new(move |event, window, cx| {
5303 if let Some(blurred_id) = event.previous_focus_path.last().copied()
5304 && event.is_focus_out(focus_id)
5305 {
5306 let event = FocusOutEvent {
5307 blurred: WeakFocusHandle {
5308 id: blurred_id,
5309 handles: Arc::downgrade(&cx.focus_handles),
5310 },
5311 };
5312 listener(event, window, cx)
5313 }
5314 true
5315 }));
5316 cx.defer(move |_| activate());
5317 subscription
5318 }
5319
5320 fn reset_cursor_style(&self, cx: &mut App) {
5321 if self.is_window_hovered() {
5323 let style = self
5324 .rendered_frame
5325 .cursor_style(self)
5326 .unwrap_or(CursorStyle::Arrow);
5327 cx.platform.set_cursor_style(style);
5328 }
5329 }
5330
5331 pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
5334 let keystroke = keystroke.with_simulated_ime();
5335 let result = self.dispatch_event(
5336 PlatformInput::KeyDown(KeyDownEvent {
5337 keystroke: keystroke.clone(),
5338 is_held: false,
5339 prefer_character_input: false,
5340 }),
5341 cx,
5342 );
5343 if !result.propagate {
5344 return true;
5345 }
5346
5347 if let Some(input) = keystroke.key_char
5348 && let Some(mut input_handler) = self.platform_window.take_input_handler()
5349 {
5350 input_handler.dispatch_input(&input, self, cx);
5351 self.platform_window.set_input_handler(input_handler);
5352 return true;
5353 }
5354
5355 false
5356 }
5357
5358 pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
5361 self.highest_precedence_binding_for_action(action)
5362 .map(|binding| {
5363 binding
5364 .keystrokes()
5365 .iter()
5366 .map(ToString::to_string)
5367 .collect::<Vec<_>>()
5368 .join(" ")
5369 })
5370 .unwrap_or_else(|| action.name().to_string())
5371 }
5372
5373 #[profiling::function]
5375 pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
5376 #[cfg(feature = "profiler")]
5377 self.window_profiler.begin_input(event.kind_name());
5378 let update_count_before = self.invalidator.update_count();
5379 let old_modality = self.last_input_modality;
5383 self.last_input_modality = match &event {
5384 PlatformInput::KeyDown(_) => InputModality::Keyboard,
5385 PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
5386 PlatformInput::Touch(_) => InputModality::Touch,
5387 _ => self.last_input_modality,
5388 };
5389 if self.last_input_modality != old_modality {
5390 self.refresh();
5391 }
5392
5393 cx.propagate_event = true;
5395 self.default_prevented = false;
5397
5398 let event = match event {
5399 PlatformInput::MouseMove(mouse_move) => {
5402 self.mouse_position = mouse_move.position;
5403 self.modifiers = mouse_move.modifiers;
5404 PlatformInput::MouseMove(mouse_move)
5405 }
5406 PlatformInput::MouseDown(mouse_down) => {
5407 self.mouse_position = mouse_down.position;
5408 self.modifiers = mouse_down.modifiers;
5409 PlatformInput::MouseDown(mouse_down)
5410 }
5411 PlatformInput::MouseUp(mouse_up) => {
5412 self.mouse_position = mouse_up.position;
5413 self.modifiers = mouse_up.modifiers;
5414 PlatformInput::MouseUp(mouse_up)
5415 }
5416 PlatformInput::MousePressure(mouse_pressure) => {
5417 PlatformInput::MousePressure(mouse_pressure)
5418 }
5419 PlatformInput::MouseExited(mouse_exited) => {
5420 self.modifiers = mouse_exited.modifiers;
5421 PlatformInput::MouseExited(mouse_exited)
5422 }
5423 PlatformInput::ModifiersChanged(modifiers_changed) => {
5424 self.modifiers = modifiers_changed.modifiers;
5425 self.capslock = modifiers_changed.capslock;
5426 PlatformInput::ModifiersChanged(modifiers_changed)
5427 }
5428 PlatformInput::ScrollWheel(scroll_wheel) => {
5429 self.mouse_position = scroll_wheel.position;
5430 self.modifiers = scroll_wheel.modifiers;
5431 PlatformInput::ScrollWheel(scroll_wheel)
5432 }
5433 PlatformInput::Pinch(pinch) => {
5434 self.mouse_position = pinch.position;
5435 self.modifiers = pinch.modifiers;
5436 PlatformInput::Pinch(pinch)
5437 }
5438 PlatformInput::FileDrop(file_drop) => match file_drop {
5441 FileDropEvent::Entered { position, paths } => {
5442 self.mouse_position = position;
5443 let source_window = self.handle.window_id();
5444 if !cx.restore_platform_drag(source_window) && cx.active_drag.is_none() {
5445 cx.active_drag = Some(AnyDrag {
5446 value: Arc::new(paths.clone()),
5447 view: cx.new(|_| paths).into(),
5448 cursor_offset: position,
5449 cursor_style: None,
5450 external_payload_source: None,
5451 });
5452 }
5453 PlatformInput::MouseMove(MouseMoveEvent {
5454 position,
5455 pressed_button: Some(MouseButton::Left),
5456 modifiers: Modifiers::default(),
5457 })
5458 }
5459 FileDropEvent::Pending { position } => {
5460 self.mouse_position = position;
5461 PlatformInput::MouseMove(MouseMoveEvent {
5462 position,
5463 pressed_button: Some(MouseButton::Left),
5464 modifiers: Modifiers::default(),
5465 })
5466 }
5467 FileDropEvent::Submit { position } => {
5468 cx.activate(true);
5469 self.mouse_position = position;
5470 PlatformInput::MouseUp(MouseUpEvent {
5471 button: MouseButton::Left,
5472 position,
5473 modifiers: Modifiers::default(),
5474 click_count: 1,
5475 })
5476 }
5477 FileDropEvent::Exited => {
5478 if !cx.hand_restored_drag_to_platform(self.handle.window_id()) {
5479 cx.active_drag.take();
5480 }
5481 self.refresh();
5482 PlatformInput::FileDrop(FileDropEvent::Exited)
5483 }
5484 FileDropEvent::Ended => {
5485 cx.end_platform_drag(self.handle.window_id());
5486 self.refresh();
5487 PlatformInput::FileDrop(FileDropEvent::Ended)
5488 }
5489 },
5490 PlatformInput::Touch(touch) => PlatformInput::Touch(touch),
5491 PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
5492 };
5493
5494 if let Some(any_mouse_event) = event.mouse_event() {
5495 self.dispatch_mouse_event(any_mouse_event, cx);
5496 } else if let Some(any_key_event) = event.keyboard_event() {
5497 self.dispatch_key_event(any_key_event, cx);
5498 } else if let Some(touch_event) = event.touch_event() {
5499 self.dispatch_touch_event(touch_event, cx);
5500 }
5501
5502 self.promote_external_drag_to_platform(&event, cx);
5505
5506 let caused_invalidation = self.invalidator.update_count() > update_count_before;
5507 if caused_invalidation {
5508 self.input_rate_tracker.borrow_mut().record_input();
5509 }
5510 #[cfg(feature = "profiler")]
5511 self.window_profiler.end_input(caused_invalidation);
5512
5513 DispatchEventResult {
5514 propagate: cx.propagate_event,
5515 default_prevented: self.default_prevented,
5516 }
5517 }
5518
5519 fn promote_external_drag_to_platform(&mut self, event: &PlatformInput, cx: &mut App) {
5520 let PlatformInput::MouseMove(mouse_move) = event else {
5521 return;
5522 };
5523 if mouse_move.pressed_button != Some(MouseButton::Left) {
5524 return;
5525 }
5526 if Bounds::new(Point::default(), self.viewport_size).contains(&mouse_move.position) {
5527 return;
5528 }
5529 if !self.platform_window.can_start_external_drag() {
5530 return;
5531 }
5532 let Some(payload_source) = cx
5533 .active_drag
5534 .as_mut()
5535 .and_then(|drag| drag.external_payload_source.take())
5536 else {
5537 return;
5538 };
5539 let Some(payload) = payload_source(self, cx) else {
5540 return;
5541 };
5542 if self.platform_window.start_external_drag(&payload)
5543 && cx.hand_active_drag_to_platform(self.handle.window_id())
5544 {
5545 self.refresh();
5546 }
5547 }
5548
5549 fn dispatch_touch_event(&mut self, event: &TouchEvent, cx: &mut App) {
5553 let recognized_gestures = self.touch_gestures.handle_event(event);
5554 let mut tapped = false;
5555 for gesture in recognized_gestures {
5556 tapped |= matches!(gesture, RecognizedTouchGesture::Tap { .. });
5557 self.dispatch_recognized_touch_gesture(gesture, cx);
5558 }
5559 if tapped && self.invalidator.is_dirty() {
5565 self.draw(cx).clear(cx);
5566 }
5567 if self.touch_gestures.has_momentum() {
5568 self.schedule_touch_momentum_tick();
5569 }
5570 }
5571
5572 fn dispatch_recognized_touch_gesture(&mut self, gesture: RecognizedTouchGesture, cx: &mut App) {
5573 match gesture {
5574 RecognizedTouchGesture::Scroll(scroll_wheel) => {
5575 self.mouse_position = scroll_wheel.position;
5576 cx.propagate_event = true;
5577 self.dispatch_mouse_event(&scroll_wheel, cx);
5578 }
5579 RecognizedTouchGesture::Tap { down, up } => {
5580 self.mouse_position = up.position;
5581 cx.propagate_event = true;
5582 self.dispatch_mouse_event(&down, cx);
5583 cx.propagate_event = true;
5584 self.dispatch_mouse_event(&up, cx);
5585 }
5586 }
5587 }
5588
5589 fn schedule_touch_momentum_tick(&mut self) {
5590 self.on_next_frame(|window, cx| {
5591 if let Some(gesture) = window.touch_gestures.tick_momentum() {
5592 window.dispatch_recognized_touch_gesture(gesture, cx);
5593 }
5594 if window.touch_gestures.has_momentum() {
5595 window.schedule_touch_momentum_tick();
5596 }
5597 });
5598 }
5599
5600 fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5601 let hit_test = self.rendered_frame.hit_test(self.mouse_position());
5602 if hit_test != self.mouse_hit_test {
5603 self.mouse_hit_test = hit_test;
5604 self.reset_cursor_style(cx);
5605 }
5606
5607 #[cfg(any(feature = "inspector", debug_assertions))]
5608 if self.is_inspector_picking(cx) {
5609 self.handle_inspector_mouse_event(event, cx);
5610 return;
5612 }
5613
5614 let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
5615
5616 for listener in &mut mouse_listeners {
5619 let listener = listener.as_mut().unwrap();
5620 listener(event, DispatchPhase::Capture, self, cx);
5621 if !cx.propagate_event {
5622 break;
5623 }
5624 }
5625
5626 if cx.propagate_event {
5628 for listener in mouse_listeners.iter_mut().rev() {
5629 let listener = listener.as_mut().unwrap();
5630 listener(event, DispatchPhase::Bubble, self, cx);
5631 if !cx.propagate_event {
5632 break;
5633 }
5634 }
5635 }
5636
5637 self.rendered_frame.mouse_listeners = mouse_listeners;
5638
5639 if cx.has_active_drag() {
5640 if event.is::<MouseMoveEvent>() {
5641 self.refresh();
5644 } else if event.is::<MouseUpEvent>() {
5645 cx.active_drag = None;
5648 self.refresh();
5649 }
5650 }
5651
5652 if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
5654 self.captured_hitbox = None;
5655 }
5656 }
5657
5658 fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
5659 if self.invalidator.is_dirty() {
5660 self.draw(cx).clear(cx);
5661 }
5662
5663 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5664 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5665
5666 let mut keystroke: Option<Keystroke> = None;
5667
5668 if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
5669 if event.modifiers.number_of_modifiers() == 0
5670 && self.pending_modifier.modifiers.number_of_modifiers() == 1
5671 && !self.pending_modifier.saw_other_input
5672 {
5673 let key = match self.pending_modifier.modifiers {
5674 modifiers if modifiers.shift => Some("shift"),
5675 modifiers if modifiers.control => Some("control"),
5676 modifiers if modifiers.alt => Some("alt"),
5677 modifiers if modifiers.platform => Some("platform"),
5678 modifiers if modifiers.function => Some("function"),
5679 _ => None,
5680 };
5681 if let Some(key) = key {
5682 keystroke = Some(Keystroke {
5683 key: key.to_string(),
5684 key_char: None,
5685 modifiers: Modifiers::default(),
5686 });
5687 }
5688 }
5689
5690 if self.pending_modifier.modifiers.number_of_modifiers() == 0
5691 && event.modifiers.number_of_modifiers() == 1
5692 {
5693 self.pending_modifier.saw_other_input = false
5694 } else if event.modifiers.number_of_modifiers() > 1 {
5695 self.pending_modifier.saw_other_input = true
5696 }
5697 self.pending_modifier.modifiers = event.modifiers
5698 } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
5699 self.pending_modifier.saw_other_input = true;
5700 keystroke = Some(key_down_event.keystroke.clone());
5701 if key_down_event.keystroke.key_char.is_some()
5702 && matches!(
5703 cx.cursor_hide_mode,
5704 CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
5705 )
5706 {
5707 cx.platform.hide_cursor_until_mouse_moves();
5708 }
5709 }
5710
5711 let Some(keystroke) = keystroke else {
5712 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5713 return;
5714 };
5715
5716 cx.propagate_event = true;
5717 self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
5718 if !cx.propagate_event {
5719 self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
5720 return;
5721 }
5722
5723 let mut currently_pending = self.pending_input.take().unwrap_or_default();
5724 if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
5725 currently_pending = PendingInput::default();
5726 }
5727
5728 let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
5729 currently_pending.keystrokes,
5730 keystroke,
5731 &dispatch_path,
5732 );
5733
5734 if !match_result.to_replay.is_empty() {
5735 self.replay_pending_input(match_result.to_replay, cx);
5736 cx.propagate_event = true;
5737 }
5738
5739 if !match_result.pending.is_empty() {
5740 currently_pending.timer.take();
5741 currently_pending.keystrokes = match_result.pending;
5742 currently_pending.focus = self.focus;
5743
5744 let text_input_requires_timeout = event
5745 .downcast_ref::<KeyDownEvent>()
5746 .filter(|key_down| key_down.keystroke.key_char.is_some())
5747 .and_then(|_| self.platform_window.take_input_handler())
5748 .map_or(false, |mut input_handler| {
5749 let accepts = input_handler.accepts_text_input(self, cx);
5750 self.platform_window.set_input_handler(input_handler);
5751 accepts
5752 });
5753
5754 currently_pending.needs_timeout |=
5755 match_result.pending_has_binding || text_input_requires_timeout;
5756
5757 if currently_pending.needs_timeout {
5758 currently_pending.timer = Some(self.spawn(cx, async move |cx| {
5759 cx.background_executor.timer(Duration::from_secs(1)).await;
5760 cx.update(move |window, cx| {
5761 let Some(currently_pending) = window
5762 .pending_input
5763 .take()
5764 .filter(|pending| pending.focus == window.focus)
5765 else {
5766 return;
5767 };
5768
5769 let node_id = window.focus_node_id_in_rendered_frame(window.focus);
5770 let dispatch_path =
5771 window.rendered_frame.dispatch_tree.dispatch_path(node_id);
5772
5773 let to_replay = window
5774 .rendered_frame
5775 .dispatch_tree
5776 .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
5777
5778 window.pending_input_changed(cx);
5779 window.replay_pending_input(to_replay, cx)
5780 })
5781 .log_err();
5782 }));
5783 } else {
5784 currently_pending.timer = None;
5785 }
5786 self.pending_input = Some(currently_pending);
5787 self.pending_input_changed(cx);
5788 cx.propagate_event = false;
5789 return;
5790 }
5791
5792 let skip_bindings = event
5793 .downcast_ref::<KeyDownEvent>()
5794 .filter(|key_down_event| key_down_event.prefer_character_input)
5795 .map(|_| {
5796 self.platform_window
5797 .take_input_handler()
5798 .map_or(false, |mut input_handler| {
5799 let accepts = input_handler.accepts_text_input(self, cx);
5800 self.platform_window.set_input_handler(input_handler);
5801 accepts
5804 })
5805 })
5806 .unwrap_or(false);
5807
5808 if !skip_bindings {
5809 for binding in match_result.bindings {
5810 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5811 if !cx.propagate_event {
5812 self.dispatch_keystroke_observers(
5813 event,
5814 Some(binding.action),
5815 match_result.context_stack,
5816 cx,
5817 );
5818 self.pending_input_changed(cx);
5819 return;
5820 }
5821 }
5822 }
5823
5824 self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
5825 self.pending_input_changed(cx);
5826 }
5827
5828 fn finish_dispatch_key_event(
5829 &mut self,
5830 event: &dyn Any,
5831 dispatch_path: SmallVec<[DispatchNodeId; 32]>,
5832 context_stack: Vec<KeyContext>,
5833 cx: &mut App,
5834 ) {
5835 self.dispatch_key_down_up_event(event, &dispatch_path, cx);
5836 if !cx.propagate_event {
5837 return;
5838 }
5839
5840 self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
5841 if !cx.propagate_event {
5842 return;
5843 }
5844
5845 self.dispatch_keystroke_observers(event, None, context_stack, cx);
5846 }
5847
5848 pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
5849 self.pending_input_observers
5850 .clone()
5851 .retain(&(), |callback| callback(self, cx));
5852 }
5853
5854 fn defer_pending_input_changed(&self, cx: &mut App) {
5855 let window_handle = self.handle;
5858 cx.defer(move |cx| {
5859 window_handle
5860 .update(cx, |_, window, cx| {
5861 window.pending_input_changed(cx);
5862 })
5863 .ok();
5864 });
5865 }
5866
5867 fn dispatch_key_down_up_event(
5868 &mut self,
5869 event: &dyn Any,
5870 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5871 cx: &mut App,
5872 ) {
5873 for node_id in dispatch_path {
5875 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5876
5877 for key_listener in node.key_listeners.clone() {
5878 key_listener(event, DispatchPhase::Capture, self, cx);
5879 if !cx.propagate_event {
5880 return;
5881 }
5882 }
5883 }
5884
5885 for node_id in dispatch_path.iter().rev() {
5887 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5889 for key_listener in node.key_listeners.clone() {
5890 key_listener(event, DispatchPhase::Bubble, self, cx);
5891 if !cx.propagate_event {
5892 return;
5893 }
5894 }
5895 }
5896 }
5897
5898 fn dispatch_modifiers_changed_event(
5899 &mut self,
5900 event: &dyn Any,
5901 dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
5902 cx: &mut App,
5903 ) {
5904 let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
5905 return;
5906 };
5907 for node_id in dispatch_path.iter().rev() {
5908 let node = self.rendered_frame.dispatch_tree.node(*node_id);
5909 for listener in node.modifiers_changed_listeners.clone() {
5910 listener(event, self, cx);
5911 if !cx.propagate_event {
5912 return;
5913 }
5914 }
5915 }
5916 }
5917
5918 fn active_pending_input(&self) -> Option<&PendingInput> {
5921 self.pending_input
5922 .as_ref()
5923 .filter(|pending_input| pending_input.focus == self.focus)
5924 }
5925
5926 pub fn has_pending_keystrokes(&self) -> bool {
5928 self.active_pending_input().is_some()
5929 }
5930
5931 #[cfg(test)]
5932 pub(crate) fn pending_input_is_none(&self) -> bool {
5933 self.pending_input.is_none()
5934 }
5935
5936 pub(crate) fn clear_pending_keystrokes(&mut self, cx: &mut App) {
5937 if self.pending_input.take().is_some() {
5938 self.defer_pending_input_changed(cx);
5939 }
5940 }
5941
5942 pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
5944 self.active_pending_input()
5945 .map(|pending_input| pending_input.keystrokes.as_slice())
5946 }
5947
5948 fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
5949 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5950 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
5951
5952 'replay: for replay in replays {
5953 let event = KeyDownEvent {
5954 keystroke: replay.keystroke.clone(),
5955 is_held: false,
5956 prefer_character_input: true,
5957 };
5958
5959 cx.propagate_event = true;
5960 for binding in replay.bindings {
5961 self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
5962 if !cx.propagate_event {
5963 self.dispatch_keystroke_observers(
5964 &event,
5965 Some(binding.action),
5966 Vec::default(),
5967 cx,
5968 );
5969 continue 'replay;
5970 }
5971 }
5972
5973 self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
5974 if !cx.propagate_event {
5975 continue 'replay;
5976 }
5977 if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
5978 && let Some(mut input_handler) = self.platform_window.take_input_handler()
5979 {
5980 input_handler.dispatch_input(&input, self, cx);
5981 self.platform_window.set_input_handler(input_handler)
5982 }
5983 }
5984 }
5985
5986 fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
5987 focus_id
5988 .and_then(|focus_id| {
5989 self.rendered_frame
5990 .dispatch_tree
5991 .focusable_node_id(focus_id)
5992 })
5993 .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
5994 }
5995
5996 fn dispatch_action_on_node(
5997 &mut self,
5998 node_id: DispatchNodeId,
5999 action: &dyn Action,
6000 cx: &mut App,
6001 ) {
6002 self.dispatch_action_on_node_inner(node_id, action, cx);
6003
6004 if !cx.propagate_event
6005 && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
6006 && self.last_input_was_keyboard()
6007 {
6008 cx.platform.hide_cursor_until_mouse_moves();
6009 }
6010 }
6011
6012 fn dispatch_action_on_node_inner(
6013 &mut self,
6014 node_id: DispatchNodeId,
6015 action: &dyn Action,
6016 cx: &mut App,
6017 ) {
6018 let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
6019
6020 cx.propagate_event = true;
6022 if let Some(mut global_listeners) = cx
6023 .global_action_listeners
6024 .remove(&action.as_any().type_id())
6025 {
6026 for listener in &global_listeners {
6027 #[cfg(feature = "profiler")]
6028 self.window_profiler.begin_action_handler(action, cx);
6029 listener(action.as_any(), DispatchPhase::Capture, cx);
6030 #[cfg(feature = "profiler")]
6031 self.window_profiler.end_action_handler();
6032 if !cx.propagate_event {
6033 break;
6034 }
6035 }
6036
6037 global_listeners.extend(
6038 cx.global_action_listeners
6039 .remove(&action.as_any().type_id())
6040 .unwrap_or_default(),
6041 );
6042
6043 cx.global_action_listeners
6044 .insert(action.as_any().type_id(), global_listeners);
6045 }
6046
6047 if !cx.propagate_event {
6048 return;
6049 }
6050
6051 for node_id in &dispatch_path {
6053 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6054 for DispatchActionListener {
6055 action_type,
6056 listener,
6057 } in node.action_listeners.clone()
6058 {
6059 let any_action = action.as_any();
6060 if action_type == any_action.type_id() {
6061 #[cfg(feature = "profiler")]
6062 self.window_profiler.begin_action_handler(action, cx);
6063 listener(any_action, DispatchPhase::Capture, self, cx);
6064 #[cfg(feature = "profiler")]
6065 self.window_profiler.end_action_handler();
6066
6067 if !cx.propagate_event {
6068 return;
6069 }
6070 }
6071 }
6072 }
6073
6074 for node_id in dispatch_path.iter().rev() {
6076 let node = self.rendered_frame.dispatch_tree.node(*node_id);
6077 for DispatchActionListener {
6078 action_type,
6079 listener,
6080 } in node.action_listeners.clone()
6081 {
6082 let any_action = action.as_any();
6083 if action_type == any_action.type_id() {
6084 cx.propagate_event = false; #[cfg(feature = "profiler")]
6086 self.window_profiler.begin_action_handler(action, cx);
6087 listener(any_action, DispatchPhase::Bubble, self, cx);
6088 #[cfg(feature = "profiler")]
6089 self.window_profiler.end_action_handler();
6090
6091 if !cx.propagate_event {
6092 return;
6093 }
6094 }
6095 }
6096 }
6097
6098 if let Some(mut global_listeners) = cx
6100 .global_action_listeners
6101 .remove(&action.as_any().type_id())
6102 {
6103 for listener in global_listeners.iter().rev() {
6104 cx.propagate_event = false; #[cfg(feature = "profiler")]
6107 self.window_profiler.begin_action_handler(action, cx);
6108 listener(action.as_any(), DispatchPhase::Bubble, cx);
6109 #[cfg(feature = "profiler")]
6110 self.window_profiler.end_action_handler();
6111 if !cx.propagate_event {
6112 break;
6113 }
6114 }
6115
6116 global_listeners.extend(
6117 cx.global_action_listeners
6118 .remove(&action.as_any().type_id())
6119 .unwrap_or_default(),
6120 );
6121
6122 cx.global_action_listeners
6123 .insert(action.as_any().type_id(), global_listeners);
6124 }
6125 }
6126
6127 pub fn observe_global<G: Global>(
6130 &mut self,
6131 cx: &mut App,
6132 f: impl Fn(&mut Window, &mut App) + 'static,
6133 ) -> Subscription {
6134 let window_handle = self.handle;
6135 let (subscription, activate) = cx.global_observers.insert(
6136 TypeId::of::<G>(),
6137 Box::new(move |cx| {
6138 window_handle
6139 .update(cx, |_, window, cx| f(window, cx))
6140 .is_ok()
6141 }),
6142 );
6143 cx.defer(move |_| activate());
6144 subscription
6145 }
6146
6147 pub fn activate_window(&self) {
6149 self.platform_window.activate();
6150 }
6151
6152 pub fn request_attention(&self) {
6154 self.platform_window.request_attention();
6155 }
6156
6157 pub fn minimize_window(&self) {
6159 self.platform_window.minimize();
6160 }
6161
6162 pub fn toggle_fullscreen(&self) {
6164 self.platform_window.toggle_fullscreen();
6165 }
6166
6167 pub fn toggle_simple_fullscreen(&self) {
6172 self.platform_window.toggle_simple_fullscreen();
6173 }
6174
6175 pub fn invalidate_character_coordinates(&self) {
6177 self.on_next_frame(|window, cx| {
6178 if let Some(mut input_handler) = window.platform_window.take_input_handler() {
6179 if let Some(bounds) = input_handler.selected_bounds(window, cx) {
6180 window.platform_window.update_ime_position(bounds);
6181 }
6182 window.platform_window.set_input_handler(input_handler);
6183 }
6184 });
6185 }
6186
6187 pub fn prompt<T>(
6191 &mut self,
6192 level: PromptLevel,
6193 message: &str,
6194 detail: Option<&str>,
6195 answers: &[T],
6196 cx: &mut App,
6197 ) -> oneshot::Receiver<usize>
6198 where
6199 T: Clone + Into<PromptButton>,
6200 {
6201 let prompt_builder = cx.prompt_builder.take();
6202 let Some(prompt_builder) = prompt_builder else {
6203 unreachable!("Re-entrant window prompting is not supported by GPUI");
6204 };
6205
6206 let answers = answers
6207 .iter()
6208 .map(|answer| answer.clone().into())
6209 .collect::<Vec<_>>();
6210
6211 let receiver = match &prompt_builder {
6212 PromptBuilder::Default => self
6213 .platform_window
6214 .prompt(level, message, detail, &answers)
6215 .unwrap_or_else(|| {
6216 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6217 }),
6218 PromptBuilder::Custom(_) => {
6219 self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
6220 }
6221 };
6222
6223 cx.prompt_builder = Some(prompt_builder);
6224
6225 receiver
6226 }
6227
6228 fn build_custom_prompt(
6229 &mut self,
6230 prompt_builder: &PromptBuilder,
6231 level: PromptLevel,
6232 message: &str,
6233 detail: Option<&str>,
6234 answers: &[PromptButton],
6235 cx: &mut App,
6236 ) -> oneshot::Receiver<usize> {
6237 let (sender, receiver) = oneshot::channel();
6238 let handle = PromptHandle::new(sender);
6239 let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
6240 self.prompt = Some(handle);
6241 receiver
6242 }
6243
6244 pub fn has_active_prompt(&self) -> bool {
6249 self.prompt.is_some()
6250 }
6251
6252 pub fn context_stack(&self) -> Vec<KeyContext> {
6254 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6255 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6256 dispatch_tree
6257 .dispatch_path(node_id)
6258 .iter()
6259 .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
6260 .collect()
6261 }
6262
6263 pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
6265 let node_id = self.focus_node_id_in_rendered_frame(self.focus);
6266 let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
6267 for action_type in cx.global_action_listeners.keys() {
6268 if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
6269 let action = cx.actions.build_action_type(action_type).ok();
6270 if let Some(action) = action {
6271 actions.insert(ix, action);
6272 }
6273 }
6274 }
6275 actions
6276 }
6277
6278 pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
6281 self.rendered_frame
6282 .dispatch_tree
6283 .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
6284 }
6285
6286 pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
6289 self.rendered_frame
6290 .dispatch_tree
6291 .highest_precedence_binding_for_action(
6292 action,
6293 &self.rendered_frame.dispatch_tree.context_stack,
6294 )
6295 }
6296
6297 pub fn bindings_for_action_in_context(
6299 &self,
6300 action: &dyn Action,
6301 context: KeyContext,
6302 ) -> Vec<KeyBinding> {
6303 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6304 dispatch_tree.bindings_for_action(action, &[context])
6305 }
6306
6307 pub fn highest_precedence_binding_for_action_in_context(
6310 &self,
6311 action: &dyn Action,
6312 context: KeyContext,
6313 ) -> Option<KeyBinding> {
6314 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6315 dispatch_tree.highest_precedence_binding_for_action(action, &[context])
6316 }
6317
6318 pub fn bindings_for_action_in(
6322 &self,
6323 action: &dyn Action,
6324 focus_handle: &FocusHandle,
6325 ) -> Vec<KeyBinding> {
6326 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6327 let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
6328 return vec![];
6329 };
6330 dispatch_tree.bindings_for_action(action, &context_stack)
6331 }
6332
6333 pub fn highest_precedence_binding_for_action_in(
6337 &self,
6338 action: &dyn Action,
6339 focus_handle: &FocusHandle,
6340 ) -> Option<KeyBinding> {
6341 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6342 let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
6343 dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
6344 }
6345
6346 pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
6348 self.rendered_frame
6349 .dispatch_tree
6350 .possible_next_bindings_for_input(input, &self.context_stack())
6351 }
6352
6353 fn context_stack_for_focus_handle(
6354 &self,
6355 focus_handle: &FocusHandle,
6356 ) -> Option<Vec<KeyContext>> {
6357 let dispatch_tree = &self.rendered_frame.dispatch_tree;
6358 let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
6359 let context_stack: Vec<_> = dispatch_tree
6360 .dispatch_path(node_id)
6361 .into_iter()
6362 .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
6363 .collect();
6364 Some(context_stack)
6365 }
6366
6367 pub fn listener_for<T: 'static, E>(
6369 &self,
6370 view: &Entity<T>,
6371 f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
6372 ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
6373 let view = view.downgrade();
6374 move |e: &E, window: &mut Window, cx: &mut App| {
6375 view.update(cx, |view, cx| f(view, e, window, cx)).ok();
6376 }
6377 }
6378
6379 pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
6381 &self,
6382 entity: &Entity<E>,
6383 f: Callback,
6384 ) -> impl Fn(&mut Window, &mut App) + 'static {
6385 let entity = entity.downgrade();
6386 move |window: &mut Window, cx: &mut App| {
6387 entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
6388 }
6389 }
6390
6391 pub fn on_window_should_close(
6394 &self,
6395 cx: &App,
6396 f: impl Fn(&mut Window, &mut App) -> bool + 'static,
6397 ) {
6398 let mut cx = self.to_async(cx);
6399 self.platform_window.on_should_close(Box::new(move || {
6400 cx.update(|window, cx| f(window, cx)).unwrap_or(true)
6401 }))
6402 }
6403
6404 pub fn on_action(
6413 &mut self,
6414 action_type: TypeId,
6415 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
6416 ) {
6417 self.invalidator.debug_assert_paint();
6418
6419 self.next_frame
6420 .dispatch_tree
6421 .on_action(action_type, Rc::new(listener));
6422 }
6423
6424 pub fn on_action_when(
6433 &mut self,
6434 condition: bool,
6435 action_type: TypeId,
6436 listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
6437 ) {
6438 self.invalidator.debug_assert_paint();
6439
6440 if condition {
6441 self.next_frame
6442 .dispatch_tree
6443 .on_action(action_type, Rc::new(listener));
6444 }
6445 }
6446
6447 pub fn gpu_specs(&self) -> Option<GpuSpecs> {
6450 self.platform_window.gpu_specs()
6451 }
6452
6453 pub fn gpu_time(&self) -> Option<Duration> {
6458 self.platform_window.gpu_time()
6459 }
6460
6461 pub fn titlebar_double_click(&self) {
6464 self.platform_window
6465 .titlebar_double_click(self.is_resizable, self.is_minimizable);
6466 }
6467
6468 pub fn window_title(&self) -> String {
6471 self.platform_window.get_title()
6472 }
6473
6474 pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
6477 self.platform_window.tabbed_windows()
6478 }
6479
6480 pub fn tab_bar_visible(&self) -> bool {
6483 self.platform_window.tab_bar_visible()
6484 }
6485
6486 pub fn merge_all_windows(&self) {
6489 self.platform_window.merge_all_windows()
6490 }
6491
6492 pub fn move_tab_to_new_window(&self) {
6495 self.platform_window.move_tab_to_new_window()
6496 }
6497
6498 pub fn toggle_window_tab_overview(&self) {
6501 self.platform_window.toggle_window_tab_overview()
6502 }
6503
6504 pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
6507 self.platform_window
6508 .set_tabbing_identifier(tabbing_identifier)
6509 }
6510
6511 pub fn play_system_bell(&self) {
6514 self.platform_window.play_system_bell()
6515 }
6516
6517 pub fn is_a11y_active(&self) -> bool {
6528 self.a11y.is_active()
6529 }
6530
6531 pub fn debug_a11y_tree_json(&self) -> Option<String> {
6533 self.a11y.debug_tree_json()
6534 }
6535
6536 pub fn on_a11y_action(
6542 &mut self,
6543 node_id: accesskit::NodeId,
6544 action: accesskit::Action,
6545 listener: impl FnMut(Option<&accesskit::ActionData>, &mut Window, &mut App) + 'static,
6546 ) {
6547 self.a11y
6548 .action_listeners
6549 .entry(node_id)
6550 .or_default()
6551 .push((action, Box::new(listener)));
6552 }
6553
6554 #[cfg(not(target_family = "wasm"))]
6555 pub(crate) fn handle_a11y_action(&mut self, request: accesskit::ActionRequest, cx: &mut App) {
6556 if let Some(mut listeners) = self.a11y.action_listeners.remove(&request.target_node) {
6559 let extra_data = request.data.as_ref();
6560 let mut matched = false;
6561 for (action, listener) in &mut listeners {
6562 if *action == request.action {
6563 listener(extra_data, self, cx);
6564 matched = true;
6565 }
6566 }
6567 self.a11y
6568 .action_listeners
6569 .insert(request.target_node, listeners);
6570 if matched {
6571 return;
6572 }
6573 }
6574
6575 match request.action {
6577 accesskit::Action::Click => {
6578 if let Some(bounds) = self.a11y.node_bounds.get(&request.target_node).copied() {
6579 let center = bounds.center();
6580 let mouse_down = PlatformInput::MouseDown(crate::MouseDownEvent {
6581 button: MouseButton::Left,
6582 position: center,
6583 modifiers: Modifiers::default(),
6584 click_count: 1,
6585 first_mouse: false,
6586 });
6587 let mouse_up = PlatformInput::MouseUp(MouseUpEvent {
6588 button: MouseButton::Left,
6589 position: center,
6590 modifiers: Modifiers::default(),
6591 click_count: 1,
6592 });
6593 self.dispatch_event(mouse_down, cx);
6594 self.dispatch_event(mouse_up, cx);
6595 }
6596 }
6597 accesskit::Action::Focus => {
6598 if let Some(focus_id) = self.a11y.focus_ids.get(&request.target_node).copied()
6599 && let Some(handle) = FocusHandle::for_id(focus_id, &cx.focus_handles)
6600 {
6601 self.focus(&handle, cx);
6602 }
6603 }
6604 accesskit::Action::Blur => {
6605 self.blur(cx);
6606 }
6607 _ => {
6608 log::debug!(
6609 "Unhandled a11y action: {:?} on {:?}",
6610 request.action,
6611 request.target_node
6612 );
6613 }
6614 }
6615 }
6616
6617 #[cfg(any(feature = "inspector", debug_assertions))]
6619 pub fn toggle_inspector(&mut self, cx: &mut App) {
6620 self.inspector = match self.inspector {
6621 None => Some(cx.new(|_| Inspector::new())),
6622 Some(_) => None,
6623 };
6624 self.refresh();
6625 }
6626
6627 pub fn is_inspector_picking(&self, _cx: &App) -> bool {
6629 #[cfg(any(feature = "inspector", debug_assertions))]
6630 {
6631 if let Some(inspector) = &self.inspector {
6632 return inspector.read(_cx).is_picking();
6633 }
6634 }
6635 false
6636 }
6637
6638 #[cfg(any(feature = "inspector", debug_assertions))]
6640 pub fn with_inspector_state<T: 'static, R>(
6641 &mut self,
6642 _inspector_id: Option<&crate::InspectorElementId>,
6643 cx: &mut App,
6644 f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
6645 ) -> R {
6646 if let Some(inspector_id) = _inspector_id
6647 && let Some(inspector) = &self.inspector
6648 {
6649 let inspector = inspector.clone();
6650 let active_element_id = inspector.read(cx).active_element_id();
6651 if Some(inspector_id) == active_element_id {
6652 return inspector.update(cx, |inspector, _cx| {
6653 inspector.with_active_element_state(self, f)
6654 });
6655 }
6656 }
6657 f(&mut None, self)
6658 }
6659
6660 #[cfg(any(feature = "inspector", debug_assertions))]
6661 pub(crate) fn build_inspector_element_id(
6662 &mut self,
6663 path: crate::InspectorElementPath,
6664 ) -> crate::InspectorElementId {
6665 self.invalidator.debug_assert_paint_or_prepaint();
6666 let path = Rc::new(path);
6667 let next_instance_id = self
6668 .next_frame
6669 .next_inspector_instance_ids
6670 .entry(path.clone())
6671 .or_insert(0);
6672 let instance_id = *next_instance_id;
6673 *next_instance_id += 1;
6674 crate::InspectorElementId { path, instance_id }
6675 }
6676
6677 #[cfg(any(feature = "inspector", debug_assertions))]
6678 fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
6679 if let Some(inspector) = self.inspector.take() {
6680 let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
6681 inspector_element.prepaint_as_root(
6682 point(self.viewport_size.width - inspector_width, px(0.0)),
6683 size(inspector_width, self.viewport_size.height).into(),
6684 self,
6685 cx,
6686 );
6687 self.inspector = Some(inspector);
6688 Some(inspector_element)
6689 } else {
6690 None
6691 }
6692 }
6693
6694 #[cfg(any(feature = "inspector", debug_assertions))]
6695 fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
6696 if let Some(mut inspector_element) = inspector_element {
6697 inspector_element.paint(self, cx);
6698 };
6699 }
6700
6701 #[cfg(any(feature = "inspector", debug_assertions))]
6704 pub fn insert_inspector_hitbox(
6705 &mut self,
6706 hitbox_id: HitboxId,
6707 inspector_id: Option<&crate::InspectorElementId>,
6708 cx: &App,
6709 ) {
6710 self.invalidator.debug_assert_paint_or_prepaint();
6711 if !self.is_inspector_picking(cx) {
6712 return;
6713 }
6714 if let Some(inspector_id) = inspector_id {
6715 self.next_frame
6716 .inspector_hitboxes
6717 .insert(hitbox_id, inspector_id.clone());
6718 }
6719 }
6720
6721 #[cfg(any(feature = "inspector", debug_assertions))]
6722 fn paint_inspector_hitbox(&mut self, cx: &App) {
6723 if let Some(inspector) = self.inspector.as_ref() {
6724 let inspector = inspector.read(cx);
6725 if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
6726 && let Some(hitbox) = self
6727 .next_frame
6728 .hitboxes
6729 .iter()
6730 .find(|hitbox| hitbox.id == hitbox_id)
6731 {
6732 self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
6733 }
6734 }
6735 }
6736
6737 #[cfg(any(feature = "inspector", debug_assertions))]
6738 fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
6739 let Some(inspector) = self.inspector.clone() else {
6740 return;
6741 };
6742 if event.downcast_ref::<MouseMoveEvent>().is_some() {
6743 inspector.update(cx, |inspector, _cx| {
6744 if let Some((_, inspector_id)) =
6745 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6746 {
6747 inspector.hover(inspector_id, self);
6748 }
6749 });
6750 } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
6751 inspector.update(cx, |inspector, _cx| {
6752 if let Some((_, inspector_id)) =
6753 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6754 {
6755 inspector.select(inspector_id, self);
6756 }
6757 });
6758 } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
6759 const SCROLL_LINES: f32 = 3.0;
6761 const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
6762 let delta_y = event
6763 .delta
6764 .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
6765 .y;
6766 if let Some(inspector) = self.inspector.clone() {
6767 inspector.update(cx, |inspector, _cx| {
6768 if let Some(depth) = inspector.pick_depth.as_mut() {
6769 *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
6770 let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
6771 if *depth < 0.0 {
6772 *depth = 0.0;
6773 } else if *depth > max_depth {
6774 *depth = max_depth;
6775 }
6776 if let Some((_, inspector_id)) =
6777 self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
6778 {
6779 inspector.set_active_element_id(inspector_id, self);
6780 }
6781 }
6782 });
6783 }
6784 }
6785 }
6786
6787 #[cfg(any(feature = "inspector", debug_assertions))]
6788 fn hovered_inspector_hitbox(
6789 &self,
6790 inspector: &Inspector,
6791 frame: &Frame,
6792 ) -> Option<(HitboxId, crate::InspectorElementId)> {
6793 if let Some(pick_depth) = inspector.pick_depth {
6794 let depth = (pick_depth as i64).try_into().unwrap_or(0);
6795 let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
6796 let skip_count = (depth as usize).min(max_skipped);
6797 for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
6798 if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
6799 return Some((*hitbox_id, inspector_id.clone()));
6800 }
6801 }
6802 }
6803 None
6804 }
6805
6806 #[cfg(any(test, feature = "test-support"))]
6809 pub fn set_modifiers(&mut self, modifiers: Modifiers) {
6810 self.modifiers = modifiers;
6811 }
6812
6813 #[cfg(any(test, feature = "test-support"))]
6817 pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
6818 let event = PlatformInput::MouseMove(MouseMoveEvent {
6819 position,
6820 modifiers: self.modifiers,
6821 pressed_button: None,
6822 });
6823 let _ = self.dispatch_event(event, cx);
6824 }
6825}
6826
6827slotmap::new_key_type! {
6829 pub struct WindowId;
6831}
6832
6833impl WindowId {
6834 pub fn as_u64(&self) -> u64 {
6836 self.0.as_ffi()
6837 }
6838}
6839
6840impl From<u64> for WindowId {
6841 fn from(value: u64) -> Self {
6842 WindowId(slotmap::KeyData::from_ffi(value))
6843 }
6844}
6845
6846#[derive(Deref, DerefMut)]
6849pub struct WindowHandle<V> {
6850 #[deref]
6851 #[deref_mut]
6852 pub(crate) any_handle: AnyWindowHandle,
6853 state_type: PhantomData<fn(V) -> V>,
6854}
6855
6856impl<V> Debug for WindowHandle<V> {
6857 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6858 f.debug_struct("WindowHandle")
6859 .field("any_handle", &self.any_handle.id.as_u64())
6860 .finish()
6861 }
6862}
6863
6864impl<V: 'static + Render> WindowHandle<V> {
6865 pub fn new(id: WindowId) -> Self {
6868 WindowHandle {
6869 any_handle: AnyWindowHandle {
6870 id,
6871 state_type: TypeId::of::<V>(),
6872 root_entity_type_name: std::any::type_name::<V>(),
6873 },
6874 state_type: PhantomData,
6875 }
6876 }
6877
6878 #[cfg(any(test, feature = "test-support"))]
6882 pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
6883 where
6884 C: AppContext,
6885 {
6886 cx.update_window(self.any_handle, |root_view, _, _| {
6887 root_view
6888 .downcast::<V>()
6889 .map_err(|_| anyhow!("the type of the window's root view has changed"))
6890 })?
6891 }
6892
6893 pub fn update<C, R>(
6897 &self,
6898 cx: &mut C,
6899 update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
6900 ) -> Result<R>
6901 where
6902 C: AppContext,
6903 {
6904 cx.update_window(self.any_handle, |root_view, window, cx| {
6905 let view = root_view
6906 .downcast::<V>()
6907 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6908
6909 Ok(view.update(cx, |view, cx| update(view, window, cx)))
6910 })?
6911 }
6912
6913 pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
6917 let x = cx
6918 .windows
6919 .get(self.id)
6920 .and_then(|window| {
6921 window
6922 .as_deref()
6923 .and_then(|window| window.root.clone())
6924 .map(|root_view| root_view.downcast::<V>())
6925 })
6926 .context("window not found")?
6927 .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
6928
6929 Ok(x.read(cx))
6930 }
6931
6932 pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
6936 where
6937 C: AppContext,
6938 {
6939 cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
6940 }
6941
6942 pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
6946 where
6947 C: AppContext,
6948 {
6949 cx.read_window(self, |root_view, _cx| root_view)
6950 }
6951
6952 pub fn is_active(&self, cx: &mut App) -> Option<bool> {
6957 cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
6958 .ok()
6959 }
6960}
6961
6962impl<V> Copy for WindowHandle<V> {}
6963
6964impl<V> Clone for WindowHandle<V> {
6965 fn clone(&self) -> Self {
6966 *self
6967 }
6968}
6969
6970impl<V> PartialEq for WindowHandle<V> {
6971 fn eq(&self, other: &Self) -> bool {
6972 self.any_handle == other.any_handle
6973 }
6974}
6975
6976impl<V> Eq for WindowHandle<V> {}
6977
6978impl<V> Hash for WindowHandle<V> {
6979 fn hash<H: Hasher>(&self, state: &mut H) {
6980 self.any_handle.hash(state);
6981 }
6982}
6983
6984impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
6985 fn from(val: WindowHandle<V>) -> Self {
6986 val.any_handle
6987 }
6988}
6989
6990#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
6992pub struct AnyWindowHandle {
6993 pub(crate) id: WindowId,
6994 state_type: TypeId,
6995 root_entity_type_name: &'static str,
6996}
6997
6998impl AnyWindowHandle {
6999 pub fn window_id(&self) -> WindowId {
7001 self.id
7002 }
7003
7004 pub fn root_entity_type_name(&self) -> &'static str {
7006 self.root_entity_type_name
7007 }
7008
7009 pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
7012 if TypeId::of::<T>() == self.state_type {
7013 Some(WindowHandle {
7014 any_handle: *self,
7015 state_type: PhantomData,
7016 })
7017 } else {
7018 None
7019 }
7020 }
7021
7022 pub fn update<C, R>(
7026 self,
7027 cx: &mut C,
7028 update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
7029 ) -> Result<R>
7030 where
7031 C: AppContext,
7032 {
7033 cx.update_window(self, update)
7034 }
7035
7036 pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
7040 where
7041 C: AppContext,
7042 T: 'static,
7043 {
7044 let view = self
7045 .downcast::<T>()
7046 .context("the type of the window's root view has changed")?;
7047
7048 cx.read_window(&view, read)
7049 }
7050}
7051
7052impl HasWindowHandle for Window {
7053 fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
7054 self.platform_window.window_handle()
7055 }
7056}
7057
7058impl HasDisplayHandle for Window {
7059 fn display_handle(
7060 &self,
7061 ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
7062 self.platform_window.display_handle()
7063 }
7064}
7065
7066#[derive(Clone, Debug, Eq, PartialEq, Hash)]
7071pub enum ElementId {
7072 View(EntityId),
7074 Integer(u64),
7076 Name(SharedString),
7078 Uuid(Uuid),
7080 FocusHandle(FocusId),
7082 NamedInteger(SharedString, u64),
7084 Path(Arc<std::path::Path>),
7086 CodeLocation(core::panic::Location<'static>),
7088 NamedChild(Arc<ElementId>, SharedString),
7090 OpaqueId([u8; 20]),
7092}
7093
7094impl ElementId {
7095 pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
7097 Self::NamedInteger(name.into(), integer as u64)
7098 }
7099}
7100
7101impl Display for ElementId {
7102 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
7103 match self {
7104 ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
7105 ElementId::Integer(ix) => write!(f, "{}", ix)?,
7106 ElementId::Name(name) => write!(f, "{}", name)?,
7107 ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
7108 ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
7109 ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
7110 ElementId::Path(path) => write!(f, "{}", path.display())?,
7111 ElementId::CodeLocation(location) => write!(f, "{}", location)?,
7112 ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
7113 ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
7114 }
7115
7116 Ok(())
7117 }
7118}
7119
7120impl TryInto<SharedString> for ElementId {
7121 type Error = anyhow::Error;
7122
7123 fn try_into(self) -> anyhow::Result<SharedString> {
7124 if let ElementId::Name(name) = self {
7125 Ok(name)
7126 } else {
7127 anyhow::bail!("element id is not string")
7128 }
7129 }
7130}
7131
7132impl From<usize> for ElementId {
7133 fn from(id: usize) -> Self {
7134 ElementId::Integer(id as u64)
7135 }
7136}
7137
7138impl From<i32> for ElementId {
7139 fn from(id: i32) -> Self {
7140 Self::Integer(id as u64)
7141 }
7142}
7143
7144impl From<SharedString> for ElementId {
7145 fn from(name: SharedString) -> Self {
7146 ElementId::Name(name)
7147 }
7148}
7149
7150impl From<String> for ElementId {
7151 fn from(name: String) -> Self {
7152 ElementId::Name(name.into())
7153 }
7154}
7155
7156impl From<Arc<str>> for ElementId {
7157 fn from(name: Arc<str>) -> Self {
7158 ElementId::Name(name.into())
7159 }
7160}
7161
7162impl From<Arc<std::path::Path>> for ElementId {
7163 fn from(path: Arc<std::path::Path>) -> Self {
7164 ElementId::Path(path)
7165 }
7166}
7167
7168impl From<&'static str> for ElementId {
7169 fn from(name: &'static str) -> Self {
7170 ElementId::Name(SharedString::new_static(name))
7171 }
7172}
7173
7174impl<'a> From<&'a FocusHandle> for ElementId {
7175 fn from(handle: &'a FocusHandle) -> Self {
7176 ElementId::FocusHandle(handle.id)
7177 }
7178}
7179
7180impl From<(&'static str, EntityId)> for ElementId {
7181 fn from((name, id): (&'static str, EntityId)) -> Self {
7182 ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
7183 }
7184}
7185
7186impl From<(&'static str, usize)> for ElementId {
7187 fn from((name, id): (&'static str, usize)) -> Self {
7188 ElementId::NamedInteger(SharedString::new_static(name), id as u64)
7189 }
7190}
7191
7192impl From<(SharedString, usize)> for ElementId {
7193 fn from((name, id): (SharedString, usize)) -> Self {
7194 ElementId::NamedInteger(name, id as u64)
7195 }
7196}
7197
7198impl From<(&'static str, u64)> for ElementId {
7199 fn from((name, id): (&'static str, u64)) -> Self {
7200 ElementId::NamedInteger(SharedString::new_static(name), id)
7201 }
7202}
7203
7204impl From<Uuid> for ElementId {
7205 fn from(value: Uuid) -> Self {
7206 Self::Uuid(value)
7207 }
7208}
7209
7210impl From<(&'static str, u32)> for ElementId {
7211 fn from((name, id): (&'static str, u32)) -> Self {
7212 ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
7213 }
7214}
7215
7216impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
7217 fn from((id, name): (ElementId, T)) -> Self {
7218 ElementId::NamedChild(Arc::new(id), name.into())
7219 }
7220}
7221
7222impl From<&'static core::panic::Location<'static>> for ElementId {
7223 fn from(location: &'static core::panic::Location<'static>) -> Self {
7224 ElementId::CodeLocation(*location)
7225 }
7226}
7227
7228impl From<[u8; 20]> for ElementId {
7229 fn from(opaque_id: [u8; 20]) -> Self {
7230 ElementId::OpaqueId(opaque_id)
7231 }
7232}
7233
7234#[derive(Clone)]
7237pub struct PaintQuad {
7238 pub bounds: Bounds<Pixels>,
7240 pub corner_radii: Corners<Pixels>,
7242 pub background: Background,
7244 pub border_widths: Edges<Pixels>,
7246 pub border_color: Hsla,
7248 pub border_style: BorderStyle,
7250}
7251
7252impl PaintQuad {
7253 pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
7255 PaintQuad {
7256 corner_radii: corner_radii.into(),
7257 ..self
7258 }
7259 }
7260
7261 pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
7263 PaintQuad {
7264 border_widths: border_widths.into(),
7265 ..self
7266 }
7267 }
7268
7269 pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
7271 PaintQuad {
7272 border_color: border_color.into(),
7273 ..self
7274 }
7275 }
7276
7277 pub fn background(self, background: impl Into<Background>) -> Self {
7279 PaintQuad {
7280 background: background.into(),
7281 ..self
7282 }
7283 }
7284}
7285
7286pub fn quad(
7288 bounds: Bounds<Pixels>,
7289 corner_radii: impl Into<Corners<Pixels>>,
7290 background: impl Into<Background>,
7291 border_widths: impl Into<Edges<Pixels>>,
7292 border_color: impl Into<Hsla>,
7293 border_style: BorderStyle,
7294) -> PaintQuad {
7295 PaintQuad {
7296 bounds,
7297 corner_radii: corner_radii.into(),
7298 background: background.into(),
7299 border_widths: border_widths.into(),
7300 border_color: border_color.into(),
7301 border_style,
7302 }
7303}
7304
7305pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
7307 PaintQuad {
7308 bounds: bounds.into(),
7309 corner_radii: (0.).into(),
7310 background: background.into(),
7311 border_widths: (0.).into(),
7312 border_color: transparent_black(),
7313 border_style: BorderStyle::default(),
7314 }
7315}
7316
7317pub fn outline(
7319 bounds: impl Into<Bounds<Pixels>>,
7320 border_color: impl Into<Hsla>,
7321 border_style: BorderStyle,
7322) -> PaintQuad {
7323 PaintQuad {
7324 bounds: bounds.into(),
7325 corner_radii: (0.).into(),
7326 background: transparent_black().into(),
7327 border_widths: (1.).into(),
7328 border_color: border_color.into(),
7329 border_style,
7330 }
7331}
7332
7333#[cfg(test)]
7334mod tests {
7335 use std::{
7336 cell::{Cell, RefCell},
7337 path::PathBuf,
7338 rc::Rc,
7339 };
7340
7341 use crate::{
7342 AnyWindowHandle, AppContext as _, Bounds, Context, DragMoveEvent, Empty,
7343 ExternalDragPayload, ExternalPaths, FileDragPaths, FileDropEvent, FocusHandle,
7344 InputEvent as _, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent,
7345 MouseMoveEvent, ParentElement, Pixels, Point, Render, RequestFrameOptions,
7346 StatefulInteractiveElement as _, Styled, TestAppContext, Window, WindowAppearance,
7347 WindowOptions, canvas, div, point, px, size,
7348 };
7349
7350 struct EmptyView;
7351
7352 impl Render for EmptyView {
7353 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7354 div()
7355 }
7356 }
7357
7358 struct OpensWindowOnPaint {
7359 opened: Rc<Cell<bool>>,
7360 }
7361
7362 impl Render for OpensWindowOnPaint {
7363 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
7364 let opened = self.opened.clone();
7365 div()
7366 .size_full()
7367 .child(canvas(
7368 |_, _, _| {},
7369 move |_, _, _window, cx| {
7370 if !opened.replace(true) {
7371 cx.open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView))
7372 .unwrap();
7373 }
7374 },
7375 ))
7376 .child(div().child("after"))
7380 }
7381 }
7382
7383 #[test]
7389 fn test_window_opened_during_draw_defers_arena_clear() {
7390 let mut cx = TestAppContext::single();
7391
7392 let opened = Rc::new(Cell::new(false));
7393 let window = cx.add_window({
7395 let opened = opened.clone();
7396 move |_, _| OpensWindowOnPaint { opened }
7397 });
7398
7399 assert!(opened.get());
7400 assert_eq!(cx.windows().len(), 2);
7401
7402 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
7405 .unwrap();
7406 }
7407
7408 #[gpui::test]
7413 fn test_frame_waker_fires_on_frame_demand(cx: &mut TestAppContext) {
7414 let window = cx.add_window(|_, _| EmptyView);
7415 let test_window = cx.test_window(window.into());
7416
7417 assert!(
7421 test_window.frame_wake_count() >= 1,
7422 "opening a window must wake the frame source for the initial frame"
7423 );
7424
7425 test_window.simulate_frame_request(RequestFrameOptions::default());
7427
7428 let baseline = test_window.frame_wake_count();
7431 test_window.simulate_frame_request(RequestFrameOptions::default());
7432 window.update(cx, |_, _, _| {}).unwrap();
7433 assert_eq!(
7434 test_window.frame_wake_count(),
7435 baseline,
7436 "clean frames and non-notifying updates must not wake the frame source"
7437 );
7438
7439 window.update(cx, |_, _, cx| cx.notify()).unwrap();
7441 assert!(
7442 test_window.frame_wake_count() > baseline,
7443 "notifying a view in an idle window must wake the frame source"
7444 );
7445
7446 test_window.simulate_frame_request(RequestFrameOptions::default());
7448 let baseline = test_window.frame_wake_count();
7449 test_window.simulate_frame_request(RequestFrameOptions::default());
7450 assert_eq!(
7451 test_window.frame_wake_count(),
7452 baseline,
7453 "serving demand must return the window to idle"
7454 );
7455
7456 window
7458 .update(cx, |_, window, _| window.on_next_frame(|_, _| {}))
7459 .unwrap();
7460 assert!(
7461 test_window.frame_wake_count() > baseline,
7462 "scheduling a next-frame callback in an idle window must wake the frame source"
7463 );
7464 }
7465
7466 #[gpui::test]
7471 fn test_pending_next_frame_callbacks_are_not_stranded(cx: &mut TestAppContext) {
7472 let window = cx.add_window(|_, _| EmptyView);
7473 let test_window = cx.test_window(window.into());
7474 test_window.simulate_frame_request(RequestFrameOptions::default());
7477
7478 let callback_ran = Rc::new(Cell::new(false));
7479 window
7480 .update(cx, {
7481 let callback_ran = callback_ran.clone();
7482 move |_, window, _| {
7483 window.on_next_frame(move |_, _| callback_ran.set(true));
7484 }
7485 })
7486 .unwrap();
7487
7488 let baseline = test_window.frame_wake_count();
7489 test_window.simulate_frame_request(RequestFrameOptions::default());
7490 assert!(
7497 test_window.frame_wake_count() > baseline || callback_ran.get(),
7498 "a frame request with pending next-frame callbacks must either run them or re-arm the frame source"
7499 );
7500 }
7501
7502 #[gpui::test]
7503 fn test_window_reports_no_raw_handle_instead_of_panicking(cx: &mut TestAppContext) {
7504 use raw_window_handle::{HandleError, HasDisplayHandle as _, HasWindowHandle as _};
7505
7506 let window = cx.add_window(|_, _| EmptyView);
7507 window
7508 .update(cx, |_, window, _| {
7509 assert!(matches!(
7510 window.window_handle(),
7511 Err(HandleError::NotSupported)
7512 ));
7513 assert!(matches!(
7514 window.display_handle(),
7515 Err(HandleError::NotSupported)
7516 ));
7517 })
7518 .unwrap();
7519 }
7520
7521 #[gpui::test]
7522 fn test_appearance_change_runs_after_app_update(cx: &mut TestAppContext) {
7523 let window = cx.add_window(|_, _| EmptyView);
7524 let observed_appearance = Rc::new(Cell::new(None));
7525 let _subscription = window
7526 .update(cx, {
7527 let observed_appearance = observed_appearance.clone();
7528 move |_, window, _| {
7529 window.observe_window_appearance(move |window, _| {
7530 observed_appearance.set(Some(window.appearance()));
7531 })
7532 }
7533 })
7534 .unwrap();
7535 let test_window = cx.test_window(window.into());
7536
7537 cx.update(|_| {
7538 test_window.simulate_appearance_change(WindowAppearance::Dark);
7539 assert_eq!(observed_appearance.get(), None);
7540 });
7541 cx.run_until_parked();
7542
7543 assert_eq!(observed_appearance.get(), Some(WindowAppearance::Dark));
7544 }
7545
7546 #[gpui::test]
7547 fn queued_frame_callback_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
7548 let window = cx.add_window(|_, _| Empty);
7549 let test_window = cx.test_window(window.into());
7550
7551 assert!(test_window.simulate_scheduled_frame());
7552 assert!(test_window.simulate_scheduled_frame());
7553 assert!(!test_window.frame_scheduled());
7554
7555 cx.update_window(window.into(), |_, window, _| {
7556 window.active.set(true);
7557 window.on_next_frame(|_, _| {});
7558 })
7559 .unwrap();
7560 assert!(
7561 test_window.frame_scheduled(),
7562 "queuing work on a parked window must wake the render loop"
7563 );
7564
7565 assert!(test_window.simulate_scheduled_frame());
7566 assert!(
7567 test_window.frame_scheduled(),
7568 "presenting the frame must await one compositor callback"
7569 );
7570 assert!(test_window.simulate_scheduled_frame());
7571 assert!(!test_window.frame_scheduled());
7572 }
7573
7574 #[gpui::test]
7575 fn pending_presentation_wakes_a_parked_render_loop(cx: &mut TestAppContext) {
7576 let window = cx.add_window(|_, _| Empty);
7577 let test_window = cx.test_window(window.into());
7578
7579 assert!(test_window.simulate_scheduled_frame());
7580 assert!(test_window.simulate_scheduled_frame());
7581 assert!(!test_window.frame_scheduled());
7582
7583 cx.update_window(window.into(), |_, window, cx| window.draw(cx).clear(cx))
7584 .unwrap();
7585
7586 assert!(
7587 test_window.frame_scheduled(),
7588 "a rendered scene awaiting presentation must wake the render loop"
7589 );
7590 }
7591
7592 #[gpui::test]
7593 fn callback_queued_during_a_frame_requests_a_follow_up(cx: &mut TestAppContext) {
7594 let window = cx.add_window(|_, _| Empty);
7595 let test_window = cx.test_window(window.into());
7596
7597 let callback_ran = Rc::new(Cell::new(false));
7598 cx.update_window(window.into(), |_, window, _| {
7599 window.active.set(true);
7602 let callback_ran = callback_ran.clone();
7603 window.on_next_frame(move |window, _| {
7604 window.on_next_frame(move |_, _| callback_ran.set(true));
7605 });
7606 })
7607 .unwrap();
7608
7609 assert!(test_window.simulate_scheduled_frame());
7610 assert!(!callback_ran.get());
7611 assert!(
7612 test_window.frame_scheduled(),
7613 "a callback queued mid-frame must schedule a follow-up before the loop parks"
7614 );
7615
7616 assert!(test_window.simulate_scheduled_frame());
7617 assert!(callback_ran.get());
7618 }
7619
7620 struct RootView {
7621 explicit_size: bool,
7622 child_bounds: Rc<Cell<Bounds<Pixels>>>,
7623 }
7624
7625 impl Render for RootView {
7626 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7627 let child_bounds = self.child_bounds.clone();
7628 let root = div().flex().flex_col().child(
7629 canvas(
7630 move |bounds, _, _| child_bounds.set(bounds),
7631 |_, _, _, _| {},
7632 )
7633 .size_full(),
7634 );
7635 if self.explicit_size {
7636 root.w(px(300.)).h(px(200.))
7637 } else {
7638 root
7639 }
7640 }
7641 }
7642
7643 #[test]
7644 fn auto_sized_window_root_fills_the_window() {
7645 let mut cx = TestAppContext::single();
7646 let child_bounds = Rc::new(Cell::new(Bounds::default()));
7647 let window = cx.add_window({
7648 let child_bounds = child_bounds.clone();
7649 move |_, _| RootView {
7650 explicit_size: false,
7651 child_bounds,
7652 }
7653 });
7654
7655 let viewport_size = cx
7656 .update_window(window.into(), |_, window, cx| {
7657 window.draw(cx).clear(cx);
7658 window.viewport_size()
7659 })
7660 .unwrap();
7661
7662 assert_eq!(child_bounds.get().size, viewport_size);
7663 }
7664
7665 #[test]
7666 fn explicitly_sized_window_root_keeps_its_size() {
7667 let mut cx = TestAppContext::single();
7668 let child_bounds = Rc::new(Cell::new(Bounds::default()));
7669 let window = cx.add_window({
7670 let child_bounds = child_bounds.clone();
7671 move |_, _| RootView {
7672 explicit_size: true,
7673 child_bounds,
7674 }
7675 });
7676
7677 cx.update_window(window.into(), |_, window, cx| {
7678 window.draw(cx).clear(cx);
7679 })
7680 .unwrap();
7681
7682 assert_eq!(child_bounds.get().size, size(px(300.), px(200.)));
7683 }
7684
7685 struct FileDragView {
7686 path: PathBuf,
7687 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7688 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7689 }
7690
7691 impl Render for FileDragView {
7692 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7693 div()
7694 .id("file-drag")
7695 .size_full()
7696 .on_drag(self.path.clone(), |_, _, _, cx| cx.new(|_| Empty))
7697 .external_drag_payload(|path: &PathBuf, _, _| {
7698 Some(ExternalDragPayload::Files(FileDragPaths::new([(
7699 path.clone(),
7700 true,
7701 )])))
7702 })
7703 .on_drag_move({
7704 let observed_drag_moves = self.observed_drag_moves.clone();
7705 move |event: &DragMoveEvent<PathBuf>, _, _| {
7706 observed_drag_moves.borrow_mut().push(event.event.position);
7707 }
7708 })
7709 .on_drop({
7710 let observed_drops = self.observed_drops.clone();
7711 move |path: &PathBuf, _, _| observed_drops.borrow_mut().push(path.clone())
7712 })
7713 }
7714 }
7715
7716 #[gpui::test]
7717 fn file_drag_is_promoted_once_and_restored_in_source_window(cx: &mut TestAppContext) {
7718 struct Drag {
7719 window: AnyWindowHandle,
7720 observed_drag_moves: Rc<RefCell<Vec<Point<Pixels>>>>,
7721 observed_drops: Rc<RefCell<Vec<PathBuf>>>,
7722 }
7723
7724 fn start_drag(cx: &mut TestAppContext, path: PathBuf, platform_result: bool) -> Drag {
7725 let observed_drag_moves = Rc::new(RefCell::new(Vec::new()));
7726 let observed_drops = Rc::new(RefCell::new(Vec::new()));
7727 let window: AnyWindowHandle = cx
7728 .add_window({
7729 let observed_drag_moves = observed_drag_moves.clone();
7730 let observed_drops = observed_drops.clone();
7731 move |_, _| FileDragView {
7732 path,
7733 observed_drag_moves,
7734 observed_drops,
7735 }
7736 })
7737 .into();
7738 cx.test_window(window)
7739 .set_start_external_drag_result(platform_result);
7740
7741 let update_result = cx.update_window(window, |_, window, cx| {
7742 window.draw(cx).clear(cx);
7743 window.dispatch_event(
7744 MouseDownEvent {
7745 position: point(px(10.), px(10.)),
7746 button: MouseButton::Left,
7747 modifiers: Default::default(),
7748 click_count: 1,
7749 first_mouse: false,
7750 }
7751 .to_platform_input(),
7752 cx,
7753 );
7754 window.dispatch_event(
7755 MouseMoveEvent {
7756 position: point(px(20.), px(20.)),
7757 pressed_button: Some(MouseButton::Left),
7758 modifiers: Default::default(),
7759 }
7760 .to_platform_input(),
7761 cx,
7762 );
7763 assert!(cx.active_drag.is_some());
7764 });
7765 assert!(
7766 update_result.is_ok(),
7767 "failed to start drag: {update_result:?}"
7768 );
7769
7770 assert!(cx.test_window(window).external_drag_files().is_empty());
7771 Drag {
7772 window,
7773 observed_drag_moves,
7774 observed_drops,
7775 }
7776 }
7777
7778 let successful_path = PathBuf::from("/tmp/successful-drag");
7779 let successful = start_drag(cx, successful_path.clone(), true);
7780 let outside_position = point(px(-1.), px(20.));
7781 let update_result = cx.update_window(successful.window, |_, window, cx| {
7782 window.dispatch_event(
7783 MouseMoveEvent {
7784 position: outside_position,
7785 pressed_button: Some(MouseButton::Left),
7786 modifiers: Default::default(),
7787 }
7788 .to_platform_input(),
7789 cx,
7790 );
7791 assert!(cx.active_drag.is_none());
7792 });
7793 assert!(
7794 update_result.is_ok(),
7795 "failed to promote drag: {update_result:?}"
7796 );
7797 assert_eq!(
7798 cx.test_window(successful.window).external_drag_files(),
7799 [(successful_path.clone(), true)]
7800 );
7801 assert_eq!(
7804 successful.observed_drag_moves.borrow().last(),
7805 Some(&outside_position)
7806 );
7807
7808 let destination: AnyWindowHandle = cx.add_window(|_, _| EmptyView).into();
7809 let reentry_position = point(px(30.), px(30.));
7810 let external_paths = || ExternalPaths([successful_path.clone()].into_iter().collect());
7811 let update_result = cx.update_window(destination, |_, window, cx| {
7812 window.dispatch_event(
7813 FileDropEvent::Entered {
7814 position: reentry_position,
7815 paths: external_paths(),
7816 }
7817 .to_platform_input(),
7818 cx,
7819 );
7820 assert!(
7821 cx.active_drag
7822 .as_ref()
7823 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7824 );
7825 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7826 assert!(cx.active_drag.is_none());
7827 });
7828 assert!(
7829 update_result.is_ok(),
7830 "failed to handle drag in destination window: {update_result:?}"
7831 );
7832
7833 let update_result = cx.update_window(successful.window, |_, window, cx| {
7834 window.dispatch_event(
7835 FileDropEvent::Entered {
7836 position: reentry_position,
7837 paths: external_paths(),
7838 }
7839 .to_platform_input(),
7840 cx,
7841 );
7842 assert!(
7843 cx.active_drag
7844 .as_ref()
7845 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7846 );
7847 assert_eq!(
7848 successful.observed_drag_moves.borrow().last(),
7849 Some(&reentry_position)
7850 );
7851
7852 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7853 assert!(cx.active_drag.is_none());
7854
7855 window.dispatch_event(
7856 FileDropEvent::Entered {
7857 position: reentry_position,
7858 paths: external_paths(),
7859 }
7860 .to_platform_input(),
7861 cx,
7862 );
7863 assert!(
7864 cx.active_drag
7865 .as_ref()
7866 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7867 );
7868
7869 window.dispatch_event(
7870 FileDropEvent::Submit {
7871 position: reentry_position,
7872 }
7873 .to_platform_input(),
7874 cx,
7875 );
7876 assert_eq!(
7877 successful.observed_drops.borrow().as_slice(),
7878 std::slice::from_ref(&successful_path)
7879 );
7880 assert!(cx.active_drag.is_none());
7881
7882 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7883 assert!(cx.active_drag.is_none());
7884 window.dispatch_event(FileDropEvent::Ended.to_platform_input(), cx);
7885 assert!(cx.active_drag.is_none());
7886
7887 window.dispatch_event(
7888 FileDropEvent::Entered {
7889 position: reentry_position,
7890 paths: external_paths(),
7891 }
7892 .to_platform_input(),
7893 cx,
7894 );
7895 assert!(
7896 cx.active_drag
7897 .as_ref()
7898 .is_some_and(|drag| drag.value.downcast_ref::<ExternalPaths>().is_some())
7899 );
7900 window.dispatch_event(FileDropEvent::Exited.to_platform_input(), cx);
7901 });
7902 assert!(
7903 update_result.is_ok(),
7904 "failed to restore drag in source window: {update_result:?}"
7905 );
7906
7907 let cancelled_path = PathBuf::from("/tmp/cancelled-drag");
7908 let cancelled = start_drag(cx, cancelled_path.clone(), true);
7909 let update_result = cx.update_window(cancelled.window, |_, window, cx| {
7910 window.dispatch_event(
7911 MouseMoveEvent {
7912 position: outside_position,
7913 pressed_button: Some(MouseButton::Left),
7914 modifiers: Default::default(),
7915 }
7916 .to_platform_input(),
7917 cx,
7918 );
7919 assert!(cx.active_drag.is_none());
7920
7921 window.dispatch_event(
7922 FileDropEvent::Entered {
7923 position: reentry_position,
7924 paths: ExternalPaths([cancelled_path].into_iter().collect()),
7925 }
7926 .to_platform_input(),
7927 cx,
7928 );
7929 assert!(
7930 cx.active_drag
7931 .as_ref()
7932 .is_some_and(|drag| drag.value.downcast_ref::<PathBuf>().is_some())
7933 );
7934 assert!(cx.stop_active_drag(window));
7935 assert!(cx.active_drag.is_none());
7936 });
7937 assert!(
7938 update_result.is_ok(),
7939 "failed to cancel restored drag: {update_result:?}"
7940 );
7941 assert!(!cx.update(|cx| cx.end_platform_drag(cancelled.window.window_id())));
7942
7943 let removed_path = PathBuf::from("/tmp/removed-window-drag");
7944 let removed = start_drag(cx, removed_path, true);
7945 let removed_window_id = removed.window.window_id();
7946 let update_result = cx.update_window(removed.window, |_, window, cx| {
7947 window.dispatch_event(
7948 MouseMoveEvent {
7949 position: outside_position,
7950 pressed_button: Some(MouseButton::Left),
7951 modifiers: Default::default(),
7952 }
7953 .to_platform_input(),
7954 cx,
7955 );
7956 assert!(cx.active_drag.is_none());
7957 window.remove_window();
7958 });
7959 assert!(
7960 update_result.is_ok(),
7961 "failed to remove drag source window: {update_result:?}"
7962 );
7963 assert!(!cx.update(|cx| cx.end_platform_drag(removed_window_id)));
7964
7965 let failed_path = PathBuf::from("/tmp/failed-drag");
7966 let failed = start_drag(cx, failed_path.clone(), false);
7967 let update_result = cx.update_window(failed.window, |_, window, cx| {
7968 for x_position in [-1., -2.] {
7969 window.dispatch_event(
7970 MouseMoveEvent {
7971 position: point(px(x_position), px(20.)),
7972 pressed_button: Some(MouseButton::Left),
7973 modifiers: Default::default(),
7974 }
7975 .to_platform_input(),
7976 cx,
7977 );
7978 }
7979 assert!(cx.active_drag.is_some());
7980 });
7981 assert!(
7982 update_result.is_ok(),
7983 "failed to retain drag after platform failure: {update_result:?}"
7984 );
7985 assert_eq!(
7986 cx.test_window(failed.window).external_drag_files(),
7987 [(failed_path, true)]
7988 );
7989 }
7990
7991 struct FocusForwarder {
7992 a: FocusHandle,
7993 b: FocusHandle,
7994 }
7995
7996 impl Render for FocusForwarder {
7997 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
7998 div()
7999 .size_full()
8000 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.a))
8001 .child(div().w(px(50.)).h(px(50.)).track_focus(&self.b))
8002 }
8003 }
8004
8005 #[gpui::test]
8009 fn test_focus_moved_by_focus_listener_is_dispatched(cx: &mut TestAppContext) {
8010 let b_focus_count = Rc::new(Cell::new(0));
8011 let window = cx.add_window({
8012 let b_focus_count = b_focus_count.clone();
8013 move |window, cx| {
8014 let a = cx.focus_handle();
8015 let b = cx.focus_handle();
8016 cx.on_focus(&a, window, |this: &mut FocusForwarder, window, cx| {
8017 let b = this.b.clone();
8018 window.focus(&b, cx);
8019 })
8020 .detach();
8021 cx.on_focus(&b, window, move |_, _, _| {
8022 b_focus_count.set(b_focus_count.get() + 1);
8023 })
8024 .detach();
8025 FocusForwarder { a, b }
8026 }
8027 });
8028
8029 window
8030 .update(cx, |_, window, _| window.activate_window())
8031 .unwrap();
8032 cx.executor().run_until_parked();
8033
8034 window
8035 .update(cx, |this, window, cx| {
8036 let a = this.a.clone();
8037 window.focus(&a, cx);
8038 })
8039 .unwrap();
8040 cx.executor().run_until_parked();
8041
8042 window
8043 .update(cx, |this, window, _| {
8044 assert!(this.b.is_focused(window));
8045 })
8046 .unwrap();
8047 assert_eq!(b_focus_count.get(), 1);
8048 }
8049}