Skip to main content

boltz_gpui/
window.rs

1#[cfg(any(feature = "inspector", debug_assertions))]
2use crate::Inspector;
3use crate::{
4    Action, AnyDrag, AnyElement, AnyImageCache, AnyTooltip, AnyView, App, AppContext, Arena, Asset,
5    AsyncWindowContext, AvailableSpace, Background, BorderStyle, Bounds, BoxShadow, Capslock,
6    Context, Corners, CursorStyle, Decorations, DevicePixels, DispatchActionListener,
7    DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity, EntityId, EventEmitter,
8    FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs, Hsla, InputHandler, IsZero,
9    KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke, KeystrokeEvent, LayoutId,
10    LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite, MouseButton, MouseEvent,
11    MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas, PlatformDisplay, PlatformInput,
12    PlatformInputHandler, PlatformWindow, Point, PolychromeSprite, Priority, PromptButton,
13    PromptLevel, Quad, Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams,
14    Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y,
15    ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubpixelSprite,
16    SubscriberSet, Subscription, SystemWindowTab, SystemWindowTabController, TabStopMap,
17    TaffyLayoutEngine, Task, TextRenderingMode, TextStyle, TextStyleRefinement, ThermalState,
18    TransformationMatrix, Underline, UnderlineStyle, WindowAppearance, WindowBackgroundAppearance,
19    WindowBounds, WindowControls, WindowDecorations, WindowOptions, WindowParams, WindowTextSystem,
20    point, prelude::*, px, rems, size, transparent_black,
21};
22use anyhow::{Context as _, Result, anyhow};
23use collections::{FxHashMap, FxHashSet};
24#[cfg(target_os = "macos")]
25use core_video::pixel_buffer::CVPixelBuffer;
26use derive_more::{Deref, DerefMut};
27use futures::FutureExt;
28use futures::channel::oneshot;
29use gpui_util::post_inc;
30use gpui_util::{ResultExt, measure};
31#[cfg(feature = "input-latency-histogram")]
32use hdrhistogram::Histogram;
33use itertools::FoldWhile::{Continue, Done};
34use itertools::Itertools;
35use parking_lot::RwLock;
36use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
37use refineable::Refineable;
38use scheduler::Instant;
39use slotmap::SlotMap;
40use smallvec::SmallVec;
41use std::{
42    any::{Any, TypeId},
43    borrow::Cow,
44    cell::{Cell, RefCell},
45    cmp,
46    fmt::{Debug, Display},
47    hash::{Hash, Hasher},
48    marker::PhantomData,
49    mem,
50    ops::{DerefMut, Range},
51    rc::Rc,
52    sync::{
53        Arc, Weak,
54        atomic::{AtomicUsize, Ordering::SeqCst},
55    },
56    time::Duration,
57};
58use uuid::Uuid;
59
60mod prompts;
61
62use crate::util::{
63    atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
64    round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
65};
66pub use prompts::*;
67
68/// Default window size used when no explicit size is provided.
69pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
70
71/// A 6:5 aspect ratio minimum window size to be used for functional,
72/// additional-to-main-app windows, like the settings and rules library windows.
73pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
74    width: Pixels(900.),
75    height: Pixels(750.),
76};
77
78/// Represents the two different phases when dispatching events.
79#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
80pub enum DispatchPhase {
81    /// After the capture phase comes the bubble phase, in which mouse event listeners are
82    /// invoked front to back and keyboard event listeners are invoked from the focused element
83    /// to the root of the element tree. This is the phase you'll most commonly want to use when
84    /// registering event listeners.
85    #[default]
86    Bubble,
87    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
88    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
89    /// is used for special purposes such as clearing the "pressed" state for click events. If
90    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
91    /// outside of the immediate region may rely on detecting non-local events during this phase.
92    Capture,
93}
94
95impl DispatchPhase {
96    /// Returns true if this represents the "bubble" phase.
97    #[inline]
98    pub fn bubble(self) -> bool {
99        self == DispatchPhase::Bubble
100    }
101
102    /// Returns true if this represents the "capture" phase.
103    #[inline]
104    pub fn capture(self) -> bool {
105        self == DispatchPhase::Capture
106    }
107}
108
109struct WindowInvalidatorInner {
110    pub dirty: bool,
111    pub draw_phase: DrawPhase,
112    pub dirty_views: FxHashSet<EntityId>,
113    pub update_count: usize,
114}
115
116#[derive(Clone)]
117pub(crate) struct WindowInvalidator {
118    inner: Rc<RefCell<WindowInvalidatorInner>>,
119}
120
121impl WindowInvalidator {
122    pub fn new() -> Self {
123        WindowInvalidator {
124            inner: Rc::new(RefCell::new(WindowInvalidatorInner {
125                dirty: true,
126                draw_phase: DrawPhase::None,
127                dirty_views: FxHashSet::default(),
128                update_count: 0,
129            })),
130        }
131    }
132
133    pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
134        let mut inner = self.inner.borrow_mut();
135        inner.update_count += 1;
136        inner.dirty_views.insert(entity);
137        if inner.draw_phase == DrawPhase::None {
138            inner.dirty = true;
139            cx.push_effect(Effect::Notify { emitter: entity });
140            true
141        } else {
142            false
143        }
144    }
145
146    pub fn is_dirty(&self) -> bool {
147        self.inner.borrow().dirty
148    }
149
150    pub fn set_dirty(&self, dirty: bool) {
151        let mut inner = self.inner.borrow_mut();
152        inner.dirty = dirty;
153        if dirty {
154            inner.update_count += 1;
155        }
156    }
157
158    pub fn set_phase(&self, phase: DrawPhase) {
159        self.inner.borrow_mut().draw_phase = phase
160    }
161
162    pub fn update_count(&self) -> usize {
163        self.inner.borrow().update_count
164    }
165
166    pub fn take_views(&self) -> FxHashSet<EntityId> {
167        mem::take(&mut self.inner.borrow_mut().dirty_views)
168    }
169
170    pub fn replace_views(&self, views: FxHashSet<EntityId>) {
171        self.inner.borrow_mut().dirty_views = views;
172    }
173
174    pub fn not_drawing(&self) -> bool {
175        self.inner.borrow().draw_phase == DrawPhase::None
176    }
177
178    #[track_caller]
179    pub fn debug_assert_paint(&self) {
180        debug_assert!(
181            matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
182            "this method can only be called during paint"
183        );
184    }
185
186    #[track_caller]
187    pub fn debug_assert_prepaint(&self) {
188        debug_assert!(
189            matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
190            "this method can only be called during request_layout, or prepaint"
191        );
192    }
193
194    #[track_caller]
195    pub fn debug_assert_paint_or_prepaint(&self) {
196        debug_assert!(
197            matches!(
198                self.inner.borrow().draw_phase,
199                DrawPhase::Paint | DrawPhase::Prepaint
200            ),
201            "this method can only be called during request_layout, prepaint, or paint"
202        );
203    }
204}
205
206type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
207
208pub(crate) type AnyWindowFocusListener =
209    Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
210
211pub(crate) struct WindowFocusEvent {
212    pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
213    pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
214}
215
216impl WindowFocusEvent {
217    pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
218        !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
219    }
220
221    pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
222        self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
223    }
224}
225
226/// This is provided when subscribing for `Context::on_focus_out` events.
227pub struct FocusOutEvent {
228    /// A weak focus handle representing what was blurred.
229    pub blurred: WeakFocusHandle,
230}
231
232slotmap::new_key_type! {
233    /// A globally unique identifier for a focusable element.
234    pub struct FocusId;
235}
236
237thread_local! {
238    /// Fallback arena used when no app-specific arena is active.
239    /// In production, each window draw sets CURRENT_ELEMENT_ARENA to the app's arena.
240    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
241
242    /// Points to the current App's element arena during draw operations.
243    /// This allows multiple test Apps to have isolated arenas, preventing
244    /// cross-session corruption when the scheduler interleaves their tasks.
245    static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
246}
247
248/// Allocates an element in the current arena. Uses the app-specific arena if one
249/// is active (during draw), otherwise falls back to the thread-local ELEMENT_ARENA.
250pub(crate) fn with_element_arena<R>(f: impl FnOnce(&mut Arena) -> R) -> R {
251    CURRENT_ELEMENT_ARENA.with(|current| {
252        if let Some(arena_ptr) = current.get() {
253            // SAFETY: The pointer is valid for the duration of the draw operation
254            // that set it, and we're being called during that same draw.
255            let arena_cell = unsafe { &*arena_ptr };
256            f(&mut arena_cell.borrow_mut())
257        } else {
258            ELEMENT_ARENA.with_borrow_mut(f)
259        }
260    })
261}
262
263/// RAII guard that sets CURRENT_ELEMENT_ARENA for the duration of a draw operation.
264/// When dropped, restores the previous arena (supporting nested draws).
265pub(crate) struct ElementArenaScope {
266    previous: Option<*const RefCell<Arena>>,
267}
268
269impl ElementArenaScope {
270    /// Enter a scope where element allocations use the given arena.
271    pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
272        let previous = CURRENT_ELEMENT_ARENA.with(|current| {
273            let prev = current.get();
274            current.set(Some(arena as *const RefCell<Arena>));
275            prev
276        });
277        Self { previous }
278    }
279}
280
281impl Drop for ElementArenaScope {
282    fn drop(&mut self) {
283        CURRENT_ELEMENT_ARENA.with(|current| {
284            current.set(self.previous);
285        });
286    }
287}
288
289/// Returned when the element arena has been used and so must be cleared before the next draw.
290#[must_use]
291pub struct ArenaClearNeeded {
292    arena: *const RefCell<Arena>,
293}
294
295impl ArenaClearNeeded {
296    /// Create a new ArenaClearNeeded that will clear the given arena.
297    pub(crate) fn new(arena: &RefCell<Arena>) -> Self {
298        Self {
299            arena: arena as *const RefCell<Arena>,
300        }
301    }
302
303    /// Clear the element arena.
304    pub fn clear(self) {
305        // SAFETY: The arena pointer is valid because ArenaClearNeeded is created
306        // at the end of draw() and must be cleared before the next draw.
307        let arena_cell = unsafe { &*self.arena };
308        arena_cell.borrow_mut().clear();
309    }
310}
311
312pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;
313pub(crate) struct FocusRef {
314    pub(crate) ref_count: AtomicUsize,
315    pub(crate) tab_index: isize,
316    pub(crate) tab_stop: bool,
317}
318
319impl FocusId {
320    /// Obtains whether the element associated with this handle is currently focused.
321    pub fn is_focused(&self, window: &Window) -> bool {
322        window.focus == Some(*self)
323    }
324
325    /// Obtains whether the element associated with this handle contains the focused
326    /// element or is itself focused.
327    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
328        window
329            .focused(cx)
330            .is_some_and(|focused| self.contains(focused.id, window))
331    }
332
333    /// Obtains whether the element associated with this handle is contained within the
334    /// focused element or is itself focused.
335    pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
336        let focused = window.focused(cx);
337        focused.is_some_and(|focused| focused.id.contains(*self, window))
338    }
339
340    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
341    pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
342        window
343            .rendered_frame
344            .dispatch_tree
345            .focus_contains(*self, other)
346    }
347}
348
349/// A handle which can be used to track and manipulate the focused element in a window.
350pub struct FocusHandle {
351    pub(crate) id: FocusId,
352    handles: Arc<FocusMap>,
353    /// The index of this element in the tab order.
354    pub tab_index: isize,
355    /// Whether this element can be focused by tab navigation.
356    pub tab_stop: bool,
357}
358
359impl std::fmt::Debug for FocusHandle {
360    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
362    }
363}
364
365impl FocusHandle {
366    pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
367        let id = handles.write().insert(FocusRef {
368            ref_count: AtomicUsize::new(1),
369            tab_index: 0,
370            tab_stop: false,
371        });
372
373        Self {
374            id,
375            tab_index: 0,
376            tab_stop: false,
377            handles: handles.clone(),
378        }
379    }
380
381    pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
382        let lock = handles.read();
383        let focus = lock.get(id)?;
384        if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
385            return None;
386        }
387        Some(Self {
388            id,
389            tab_index: focus.tab_index,
390            tab_stop: focus.tab_stop,
391            handles: handles.clone(),
392        })
393    }
394
395    /// Sets the tab index of the element associated with this handle.
396    pub fn tab_index(mut self, index: isize) -> Self {
397        self.tab_index = index;
398        if let Some(focus) = self.handles.write().get_mut(self.id) {
399            focus.tab_index = index;
400        }
401        self
402    }
403
404    /// Sets whether the element associated with this handle is a tab stop.
405    ///
406    /// When `false`, the element will not be included in the tab order.
407    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
408        self.tab_stop = tab_stop;
409        if let Some(focus) = self.handles.write().get_mut(self.id) {
410            focus.tab_stop = tab_stop;
411        }
412        self
413    }
414
415    /// Converts this focus handle into a weak variant, which does not prevent it from being released.
416    pub fn downgrade(&self) -> WeakFocusHandle {
417        WeakFocusHandle {
418            id: self.id,
419            handles: Arc::downgrade(&self.handles),
420        }
421    }
422
423    /// Moves the focus to the element associated with this handle.
424    pub fn focus(&self, window: &mut Window, cx: &mut App) {
425        window.focus(self, cx)
426    }
427
428    /// Obtains whether the element associated with this handle is currently focused.
429    pub fn is_focused(&self, window: &Window) -> bool {
430        self.id.is_focused(window)
431    }
432
433    /// Obtains whether the element associated with this handle contains the focused
434    /// element or is itself focused.
435    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
436        self.id.contains_focused(window, cx)
437    }
438
439    /// Obtains whether the element associated with this handle is contained within the
440    /// focused element or is itself focused.
441    pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
442        self.id.within_focused(window, cx)
443    }
444
445    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
446    pub fn contains(&self, other: &Self, window: &Window) -> bool {
447        self.id.contains(other.id, window)
448    }
449
450    /// Dispatch an action on the element that rendered this focus handle
451    pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
452        if let Some(node_id) = window
453            .rendered_frame
454            .dispatch_tree
455            .focusable_node_id(self.id)
456        {
457            window.dispatch_action_on_node(node_id, action, cx)
458        }
459    }
460}
461
462impl Clone for FocusHandle {
463    fn clone(&self) -> Self {
464        Self::for_id(self.id, &self.handles).unwrap()
465    }
466}
467
468impl PartialEq for FocusHandle {
469    fn eq(&self, other: &Self) -> bool {
470        self.id == other.id
471    }
472}
473
474impl Eq for FocusHandle {}
475
476impl Drop for FocusHandle {
477    fn drop(&mut self) {
478        self.handles
479            .read()
480            .get(self.id)
481            .unwrap()
482            .ref_count
483            .fetch_sub(1, SeqCst);
484    }
485}
486
487/// A weak reference to a focus handle.
488#[derive(Clone, Debug)]
489pub struct WeakFocusHandle {
490    pub(crate) id: FocusId,
491    pub(crate) handles: Weak<FocusMap>,
492}
493
494impl WeakFocusHandle {
495    /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
496    pub fn upgrade(&self) -> Option<FocusHandle> {
497        let handles = self.handles.upgrade()?;
498        FocusHandle::for_id(self.id, &handles)
499    }
500}
501
502impl PartialEq for WeakFocusHandle {
503    fn eq(&self, other: &WeakFocusHandle) -> bool {
504        self.id == other.id
505    }
506}
507
508impl Eq for WeakFocusHandle {}
509
510impl PartialEq<FocusHandle> for WeakFocusHandle {
511    fn eq(&self, other: &FocusHandle) -> bool {
512        self.id == other.id
513    }
514}
515
516impl PartialEq<WeakFocusHandle> for FocusHandle {
517    fn eq(&self, other: &WeakFocusHandle) -> bool {
518        self.id == other.id
519    }
520}
521
522/// Focusable allows users of your view to easily
523/// focus it (using window.focus_view(cx, view))
524pub trait Focusable: 'static {
525    /// Returns the focus handle associated with this view.
526    fn focus_handle(&self, cx: &App) -> FocusHandle;
527}
528
529impl<V: Focusable> Focusable for Entity<V> {
530    fn focus_handle(&self, cx: &App) -> FocusHandle {
531        self.read(cx).focus_handle(cx)
532    }
533}
534
535/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
536/// where the lifecycle of the view is handled by another view.
537pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
538
539impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
540
541/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
542pub struct DismissEvent;
543
544type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
545
546pub(crate) type AnyMouseListener =
547    Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
548
549#[derive(Clone)]
550pub(crate) struct CursorStyleRequest {
551    pub(crate) hitbox_id: Option<HitboxId>,
552    pub(crate) style: CursorStyle,
553}
554
555#[derive(Default, Eq, PartialEq)]
556pub(crate) struct HitTest {
557    pub(crate) ids: SmallVec<[HitboxId; 8]>,
558    pub(crate) hover_hitbox_count: usize,
559}
560
561/// A type of window control area that corresponds to the platform window.
562#[derive(Clone, Copy, Debug, Eq, PartialEq)]
563pub enum WindowControlArea {
564    /// An area that allows dragging of the platform window.
565    Drag,
566    /// An area that allows closing of the platform window.
567    Close,
568    /// An area that allows maximizing of the platform window.
569    Max,
570    /// An area that allows minimizing of the platform window.
571    Min,
572}
573
574/// An identifier for a [Hitbox] which also includes [HitboxBehavior].
575#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
576pub struct HitboxId(u64);
577
578#[cfg(feature = "test-support")]
579impl HitboxId {
580    /// A placeholder HitboxId exclusively for integration testing API's that
581    /// need a hitbox but where the value of the hitbox does not matter. The
582    /// alternative is to make the Hitbox optional but that complicates the
583    /// implementation.
584    pub const fn placeholder() -> Self {
585        Self(0)
586    }
587}
588
589impl HitboxId {
590    /// Checks if the hitbox with this ID is currently hovered. Returns `false` during keyboard
591    /// input modality so that keyboard navigation suppresses hover highlights. Except when handling
592    /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse
593    /// events or paint hover styles.
594    ///
595    /// See [`Hitbox::is_hovered`] for details.
596    pub fn is_hovered(self, window: &Window) -> bool {
597        // If this hitbox has captured the pointer, it's always considered hovered
598        if window.captured_hitbox == Some(self) {
599            return true;
600        }
601        if window.last_input_was_keyboard() {
602            return false;
603        }
604        self.hit_test(window)
605    }
606
607    /// Checks if the hitbox with this ID is currently hovered, regardless of the last
608    /// input modality used.
609    ///
610    /// See [`HitboxId::is_hovered`] for more details.
611    pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
612        // If this hitbox has captured the pointer, it's always considered hovered
613        if window.captured_hitbox == Some(self) {
614            return true;
615        }
616        self.hit_test(window)
617    }
618
619    fn hit_test(self, window: &Window) -> bool {
620        let hit_test = &window.mouse_hit_test;
621        for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
622            if self == *id {
623                return true;
624            }
625        }
626        false
627    }
628
629    /// Checks if the hitbox with this ID contains the mouse and should handle scroll events.
630    /// Typically this should only be used when handling `ScrollWheelEvent`, and otherwise
631    /// `is_hovered` should be used. See the documentation of `Hitbox::is_hovered` for details about
632    /// this distinction.
633    pub fn should_handle_scroll(self, window: &Window) -> bool {
634        window.mouse_hit_test.ids.contains(&self)
635    }
636
637    fn next(mut self) -> HitboxId {
638        HitboxId(self.0.wrapping_add(1))
639    }
640}
641
642/// A rectangular region that potentially blocks hitboxes inserted prior.
643/// See [Window::insert_hitbox] for more details.
644#[derive(Clone, Debug, Deref)]
645pub struct Hitbox {
646    /// A unique identifier for the hitbox.
647    pub id: HitboxId,
648    /// The bounds of the hitbox.
649    #[deref]
650    pub bounds: Bounds<Pixels>,
651    /// The content mask when the hitbox was inserted.
652    pub content_mask: ContentMask<Pixels>,
653    /// Flags that specify hitbox behavior.
654    pub behavior: HitboxBehavior,
655}
656
657impl Hitbox {
658    /// Checks if the hitbox is currently hovered. Returns `false` during keyboard input modality
659    /// so that keyboard navigation suppresses hover highlights. Except when handling
660    /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse
661    /// events or paint hover styles.
662    ///
663    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
664    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`) or
665    /// `HitboxBehavior::BlockMouseExceptScroll` (`InteractiveElement::block_mouse_except_scroll`),
666    /// or if the current input modality is keyboard (see [`Window::last_input_was_keyboard`]).
667    ///
668    /// Handling of `ScrollWheelEvent` should typically use `should_handle_scroll` instead.
669    /// Concretely, this is due to use-cases like overlays that cause the elements under to be
670    /// non-interactive while still allowing scrolling. More abstractly, this is because
671    /// `is_hovered` is about element interactions directly under the mouse - mouse moves, clicks,
672    /// hover styling, etc. In contrast, scrolling is about finding the current outer scrollable
673    /// container.
674    pub fn is_hovered(&self, window: &Window) -> bool {
675        self.id.is_hovered(window)
676    }
677
678    /// Checks if the hitbox contains the mouse and should handle scroll events. Typically this
679    /// should only be used when handling `ScrollWheelEvent`, and otherwise `is_hovered` should be
680    /// used. See the documentation of `Hitbox::is_hovered` for details about this distinction.
681    ///
682    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
683    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`).
684    pub fn should_handle_scroll(&self, window: &Window) -> bool {
685        self.id.should_handle_scroll(window)
686    }
687}
688
689/// How the hitbox affects mouse behavior.
690#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
691pub enum HitboxBehavior {
692    /// Normal hitbox mouse behavior, doesn't affect mouse handling for other hitboxes.
693    #[default]
694    Normal,
695
696    /// All hitboxes behind this hitbox will be ignored and so will have `hitbox.is_hovered() ==
697    /// false` and `hitbox.should_handle_scroll() == false`. Typically for elements this causes
698    /// skipping of all mouse events, hover styles, and tooltips. This flag is set by
699    /// [`InteractiveElement::occlude`].
700    ///
701    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
702    /// bubble-phase handler for every mouse event type:
703    ///
704    /// ```ignore
705    /// window.on_mouse_event(move |_: &EveryMouseEventTypeHere, phase, window, cx| {
706    ///     if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
707    ///         cx.stop_propagation();
708    ///     }
709    /// })
710    /// ```
711    ///
712    /// This has effects beyond event handling - any use of hitbox checking, such as hover
713    /// styles and tooltips. These other behaviors are the main point of this mechanism. An
714    /// alternative might be to not affect mouse event handling - but this would allow
715    /// inconsistent UI where clicks and moves interact with elements that are not considered to
716    /// be hovered.
717    BlockMouse,
718
719    /// All hitboxes behind this hitbox will have `hitbox.is_hovered() == false`, even when
720    /// `hitbox.should_handle_scroll() == true`. Typically for elements this causes all mouse
721    /// interaction except scroll events to be ignored - see the documentation of
722    /// [`Hitbox::is_hovered`] for details. This flag is set by
723    /// [`InteractiveElement::block_mouse_except_scroll`].
724    ///
725    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
726    /// bubble-phase handler for every mouse event type **except** `ScrollWheelEvent`:
727    ///
728    /// ```ignore
729    /// window.on_mouse_event(move |_: &EveryMouseEventTypeExceptScroll, phase, window, cx| {
730    ///     if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
731    ///         cx.stop_propagation();
732    ///     }
733    /// })
734    /// ```
735    ///
736    /// See the documentation of [`Hitbox::is_hovered`] for details of why `ScrollWheelEvent` is
737    /// handled differently than other mouse events. If also blocking these scroll events is
738    /// desired, then a `cx.stop_propagation()` handler like the one above can be used.
739    ///
740    /// This has effects beyond event handling - this affects any use of `is_hovered`, such as
741    /// hover styles and tooltips. These other behaviors are the main point of this mechanism.
742    /// An alternative might be to not affect mouse event handling - but this would allow
743    /// inconsistent UI where clicks and moves interact with elements that are not considered to
744    /// be hovered.
745    BlockMouseExceptScroll,
746}
747
748/// An identifier for a tooltip.
749#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
750pub struct TooltipId(usize);
751
752impl TooltipId {
753    /// Checks if the tooltip is currently hovered.
754    pub fn is_hovered(&self, window: &Window) -> bool {
755        window
756            .tooltip_bounds
757            .as_ref()
758            .is_some_and(|tooltip_bounds| {
759                tooltip_bounds.id == *self
760                    && tooltip_bounds.bounds.contains(&window.mouse_position())
761            })
762    }
763}
764
765pub(crate) struct TooltipBounds {
766    id: TooltipId,
767    bounds: Bounds<Pixels>,
768}
769
770#[derive(Clone)]
771pub(crate) struct TooltipRequest {
772    id: TooltipId,
773    tooltip: AnyTooltip,
774}
775
776pub(crate) struct DeferredDraw {
777    current_view: EntityId,
778    priority: usize,
779    parent_node: DispatchNodeId,
780    element_id_stack: SmallVec<[ElementId; 32]>,
781    text_style_stack: Vec<TextStyleRefinement>,
782    content_mask: Option<ContentMask<Pixels>>,
783    rem_size: Pixels,
784    element: Option<AnyElement>,
785    absolute_offset: Point<Pixels>,
786    prepaint_range: Range<PrepaintStateIndex>,
787    paint_range: Range<PaintIndex>,
788}
789
790pub(crate) struct Frame {
791    pub(crate) focus: Option<FocusId>,
792    pub(crate) window_active: bool,
793    pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
794    accessed_element_states: Vec<(GlobalElementId, TypeId)>,
795    pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
796    pub(crate) dispatch_tree: DispatchTree,
797    pub(crate) scene: Scene,
798    pub(crate) hitboxes: Vec<Hitbox>,
799    pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
800    pub(crate) deferred_draws: Vec<DeferredDraw>,
801    pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
802    pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
803    pub(crate) cursor_styles: Vec<CursorStyleRequest>,
804    #[cfg(any(test, feature = "test-support"))]
805    pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
806    #[cfg(any(feature = "inspector", debug_assertions))]
807    pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
808    #[cfg(any(feature = "inspector", debug_assertions))]
809    pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
810    pub(crate) tab_stops: TabStopMap,
811}
812
813#[derive(Clone, Default)]
814pub(crate) struct PrepaintStateIndex {
815    hitboxes_index: usize,
816    tooltips_index: usize,
817    deferred_draws_index: usize,
818    dispatch_tree_index: usize,
819    accessed_element_states_index: usize,
820    line_layout_index: LineLayoutIndex,
821}
822
823#[derive(Clone, Default)]
824pub(crate) struct PaintIndex {
825    scene_index: usize,
826    mouse_listeners_index: usize,
827    input_handlers_index: usize,
828    cursor_styles_index: usize,
829    accessed_element_states_index: usize,
830    tab_handle_index: usize,
831    line_layout_index: LineLayoutIndex,
832}
833
834impl Frame {
835    pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
836        Frame {
837            focus: None,
838            window_active: false,
839            element_states: FxHashMap::default(),
840            accessed_element_states: Vec::new(),
841            mouse_listeners: Vec::new(),
842            dispatch_tree,
843            scene: Scene::default(),
844            hitboxes: Vec::new(),
845            window_control_hitboxes: Vec::new(),
846            deferred_draws: Vec::new(),
847            input_handlers: Vec::new(),
848            tooltip_requests: Vec::new(),
849            cursor_styles: Vec::new(),
850
851            #[cfg(any(test, feature = "test-support"))]
852            debug_bounds: FxHashMap::default(),
853
854            #[cfg(any(feature = "inspector", debug_assertions))]
855            next_inspector_instance_ids: FxHashMap::default(),
856
857            #[cfg(any(feature = "inspector", debug_assertions))]
858            inspector_hitboxes: FxHashMap::default(),
859            tab_stops: TabStopMap::default(),
860        }
861    }
862
863    pub(crate) fn clear(&mut self) {
864        self.element_states.clear();
865        self.accessed_element_states.clear();
866        self.mouse_listeners.clear();
867        self.dispatch_tree.clear();
868        self.scene.clear();
869        self.input_handlers.clear();
870        self.tooltip_requests.clear();
871        self.cursor_styles.clear();
872        self.hitboxes.clear();
873        self.window_control_hitboxes.clear();
874        self.deferred_draws.clear();
875        self.tab_stops.clear();
876        self.focus = None;
877
878        #[cfg(any(test, feature = "test-support"))]
879        {
880            self.debug_bounds.clear();
881        }
882
883        #[cfg(any(feature = "inspector", debug_assertions))]
884        {
885            self.next_inspector_instance_ids.clear();
886            self.inspector_hitboxes.clear();
887        }
888    }
889
890    pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
891        self.cursor_styles
892            .iter()
893            .rev()
894            .fold_while(None, |style, request| match request.hitbox_id {
895                None => Done(Some(request.style)),
896                Some(hitbox_id) => Continue(style.or_else(|| {
897                    hitbox_id
898                        .is_hovered_ignoring_last_input(window)
899                        .then_some(request.style)
900                })),
901            })
902            .into_inner()
903    }
904
905    pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
906        let mut set_hover_hitbox_count = false;
907        let mut hit_test = HitTest::default();
908        for hitbox in self.hitboxes.iter().rev() {
909            let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
910            if bounds.contains(&position) {
911                hit_test.ids.push(hitbox.id);
912                if !set_hover_hitbox_count
913                    && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
914                {
915                    hit_test.hover_hitbox_count = hit_test.ids.len();
916                    set_hover_hitbox_count = true;
917                }
918                if hitbox.behavior == HitboxBehavior::BlockMouse {
919                    break;
920                }
921            }
922        }
923        if !set_hover_hitbox_count {
924            hit_test.hover_hitbox_count = hit_test.ids.len();
925        }
926        hit_test
927    }
928
929    pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
930        self.focus
931            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
932            .unwrap_or_default()
933    }
934
935    pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
936        for element_state_key in &self.accessed_element_states {
937            if let Some((element_state_key, element_state)) =
938                prev_frame.element_states.remove_entry(element_state_key)
939            {
940                self.element_states.insert(element_state_key, element_state);
941            }
942        }
943
944        self.scene.finish();
945    }
946}
947
948#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
949enum InputModality {
950    Mouse,
951    Keyboard,
952}
953
954/// Holds the state for a specific window.
955pub struct Window {
956    pub(crate) handle: AnyWindowHandle,
957    pub(crate) invalidator: WindowInvalidator,
958    pub(crate) removed: bool,
959    pub(crate) platform_window: Box<dyn PlatformWindow>,
960    display_id: Option<DisplayId>,
961    sprite_atlas: Arc<dyn PlatformAtlas>,
962    text_system: Arc<WindowTextSystem>,
963    text_rendering_mode: Rc<Cell<TextRenderingMode>>,
964    rem_size: Pixels,
965    /// The stack of override values for the window's rem size.
966    ///
967    /// This is used by `with_rem_size` to allow rendering an element tree with
968    /// a given rem size.
969    rem_size_override_stack: SmallVec<[Pixels; 8]>,
970    pub(crate) viewport_size: Size<Pixels>,
971    layout_engine: Option<TaffyLayoutEngine>,
972    pub(crate) root: Option<AnyView>,
973    pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
974    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
975    pub(crate) rendered_entity_stack: Vec<EntityId>,
976    pub(crate) element_offset_stack: Vec<Point<Pixels>>,
977    pub(crate) sticky_viewport_stack: Vec<Bounds<Pixels>>,
978    pub(crate) element_opacity: f32,
979    pub(crate) content_mask_stack: Vec<ContentMask<Pixels>>,
980    pub(crate) requested_autoscroll: Option<Bounds<Pixels>>,
981    pub(crate) image_cache_stack: Vec<AnyImageCache>,
982    pub(crate) rendered_frame: Frame,
983    pub(crate) next_frame: Frame,
984    next_hitbox_id: HitboxId,
985    pub(crate) next_tooltip_id: TooltipId,
986    pub(crate) tooltip_bounds: Option<TooltipBounds>,
987    next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
988    pub(crate) dirty_views: FxHashSet<EntityId>,
989    focus_listeners: SubscriberSet<(), AnyWindowFocusListener>,
990    pub(crate) focus_lost_listeners: SubscriberSet<(), AnyObserver>,
991    default_prevented: bool,
992    mouse_position: Point<Pixels>,
993    mouse_hit_test: HitTest,
994    modifiers: Modifiers,
995    capslock: Capslock,
996    scale_factor: f32,
997    pub(crate) bounds_observers: SubscriberSet<(), AnyObserver>,
998    appearance: WindowAppearance,
999    pub(crate) appearance_observers: SubscriberSet<(), AnyObserver>,
1000    pub(crate) button_layout_observers: SubscriberSet<(), AnyObserver>,
1001    active: Rc<Cell<bool>>,
1002    hovered: Rc<Cell<bool>>,
1003    pub(crate) needs_present: Rc<Cell<bool>>,
1004    /// Tracks recent input event timestamps to determine if input is arriving at a high rate.
1005    /// Used to selectively enable VRR optimization only when input rate exceeds 60fps.
1006    pub(crate) input_rate_tracker: Rc<RefCell<InputRateTracker>>,
1007    #[cfg(feature = "input-latency-histogram")]
1008    input_latency_tracker: InputLatencyTracker,
1009    last_input_modality: InputModality,
1010    pub(crate) refreshing: bool,
1011    pub(crate) activation_observers: SubscriberSet<(), AnyObserver>,
1012    pub(crate) focus: Option<FocusId>,
1013    focus_enabled: bool,
1014    pending_input: Option<PendingInput>,
1015    pending_modifier: ModifierState,
1016    pub(crate) pending_input_observers: SubscriberSet<(), AnyObserver>,
1017    prompt: Option<RenderablePromptHandle>,
1018    pub(crate) client_inset: Option<Pixels>,
1019    /// The hitbox that has captured the pointer, if any.
1020    /// While captured, mouse events route to this hitbox regardless of hit testing.
1021    captured_hitbox: Option<HitboxId>,
1022    #[cfg(any(feature = "inspector", debug_assertions))]
1023    inspector: Option<Entity<Inspector>>,
1024}
1025
1026#[derive(Clone, Debug, Default)]
1027struct ModifierState {
1028    modifiers: Modifiers,
1029    saw_keystroke: bool,
1030}
1031
1032/// Tracks input event timestamps to determine if input is arriving at a high rate.
1033/// Used for selective VRR (Variable Refresh Rate) optimization.
1034#[derive(Clone, Debug)]
1035pub(crate) struct InputRateTracker {
1036    timestamps: Vec<Instant>,
1037    window: Duration,
1038    inputs_per_second: u32,
1039    sustain_until: Instant,
1040    sustain_duration: Duration,
1041}
1042
1043impl Default for InputRateTracker {
1044    fn default() -> Self {
1045        Self {
1046            timestamps: Vec::new(),
1047            window: Duration::from_millis(100),
1048            inputs_per_second: 60,
1049            sustain_until: Instant::now(),
1050            sustain_duration: Duration::from_secs(1),
1051        }
1052    }
1053}
1054
1055impl InputRateTracker {
1056    pub fn record_input(&mut self) {
1057        let now = Instant::now();
1058        self.timestamps.push(now);
1059        self.prune_old_timestamps(now);
1060
1061        let min_events = self.inputs_per_second as u128 * self.window.as_millis() / 1000;
1062        if self.timestamps.len() as u128 >= min_events {
1063            self.sustain_until = now + self.sustain_duration;
1064        }
1065    }
1066
1067    pub fn is_high_rate(&self) -> bool {
1068        Instant::now() < self.sustain_until
1069    }
1070
1071    fn prune_old_timestamps(&mut self, now: Instant) {
1072        self.timestamps
1073            .retain(|&t| now.duration_since(t) <= self.window);
1074    }
1075}
1076
1077/// A point-in-time snapshot of the input-latency histograms for a window,
1078/// suitable for external formatting.
1079#[cfg(feature = "input-latency-histogram")]
1080pub struct InputLatencySnapshot {
1081    /// Histogram of input-to-frame latency samples, in nanoseconds.
1082    pub latency_histogram: Histogram<u64>,
1083    /// Histogram of input events coalesced per rendered frame.
1084    pub events_per_frame_histogram: Histogram<u64>,
1085    /// Count of input events that arrived mid-draw and were excluded from
1086    /// latency recording.
1087    pub mid_draw_events_dropped: u64,
1088}
1089
1090/// Records the time between when the first input event in a frame is dispatched
1091/// and when the resulting frame is presented, capturing worst-case latency when
1092/// multiple events are coalesced into a single frame.
1093#[cfg(feature = "input-latency-histogram")]
1094struct InputLatencyTracker {
1095    /// Timestamp of the first unrendered input event in the current frame;
1096    /// cleared when a frame is presented.
1097    first_input_at: Option<Instant>,
1098    /// Count of input events received since the last frame was presented.
1099    pending_input_count: u64,
1100    /// Histogram of input-to-frame latency samples, in nanoseconds.
1101    latency_histogram: Histogram<u64>,
1102    /// Histogram of input events coalesced per rendered frame.
1103    events_per_frame_histogram: Histogram<u64>,
1104    /// Count of input events that arrived mid-draw and were excluded from
1105    /// latency recording because their effects won't appear until the next frame.
1106    mid_draw_events_dropped: u64,
1107}
1108
1109#[cfg(feature = "input-latency-histogram")]
1110impl InputLatencyTracker {
1111    fn new() -> Result<Self> {
1112        Ok(Self {
1113            first_input_at: None,
1114            pending_input_count: 0,
1115            latency_histogram: Histogram::new(3)
1116                .map_err(|e| anyhow!("Failed to create input latency histogram: {e}"))?,
1117            events_per_frame_histogram: Histogram::new(3)
1118                .map_err(|e| anyhow!("Failed to create events per frame histogram: {e}"))?,
1119            mid_draw_events_dropped: 0,
1120        })
1121    }
1122
1123    /// Record that an input event was dispatched at the given time.
1124    /// Only the first event's timestamp per frame is retained (worst-case latency).
1125    fn record_input(&mut self, dispatch_time: Instant) {
1126        self.first_input_at.get_or_insert(dispatch_time);
1127        self.pending_input_count += 1;
1128    }
1129
1130    /// Record that an input event arrived during a draw phase and was excluded
1131    /// from latency tracking.
1132    fn record_mid_draw_input(&mut self) {
1133        self.mid_draw_events_dropped += 1;
1134    }
1135
1136    /// Record that a frame was presented, flushing pending latency and coalescing samples.
1137    fn record_frame_presented(&mut self) {
1138        if let Some(first_input_at) = self.first_input_at.take() {
1139            let latency_nanos = first_input_at.elapsed().as_nanos() as u64;
1140            self.latency_histogram.record(latency_nanos).ok();
1141        }
1142        if self.pending_input_count > 0 {
1143            self.events_per_frame_histogram
1144                .record(self.pending_input_count)
1145                .ok();
1146            self.pending_input_count = 0;
1147        }
1148    }
1149
1150    fn snapshot(&self) -> InputLatencySnapshot {
1151        InputLatencySnapshot {
1152            latency_histogram: self.latency_histogram.clone(),
1153            events_per_frame_histogram: self.events_per_frame_histogram.clone(),
1154            mid_draw_events_dropped: self.mid_draw_events_dropped,
1155        }
1156    }
1157}
1158
1159#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1160pub(crate) enum DrawPhase {
1161    None,
1162    Prepaint,
1163    Paint,
1164    Focus,
1165}
1166
1167#[derive(Default, Debug)]
1168struct PendingInput {
1169    keystrokes: SmallVec<[Keystroke; 1]>,
1170    focus: Option<FocusId>,
1171    timer: Option<Task<()>>,
1172    needs_timeout: bool,
1173}
1174
1175pub(crate) struct ElementStateBox {
1176    pub(crate) inner: Box<dyn Any>,
1177    #[cfg(debug_assertions)]
1178    pub(crate) type_name: &'static str,
1179}
1180
1181fn default_bounds(display_id: Option<DisplayId>, cx: &mut App) -> WindowBounds {
1182    // TODO, BUG: if you open a window with the currently active window
1183    // on the stack, this will erroneously fallback to `None`
1184    //
1185    // TODO these should be the initial window bounds not considering maximized/fullscreen
1186    let active_window_bounds = cx
1187        .active_window()
1188        .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok());
1189
1190    const CASCADE_OFFSET: f32 = 25.0;
1191
1192    let display = display_id
1193        .map(|id| cx.find_display(id))
1194        .unwrap_or_else(|| cx.primary_display());
1195
1196    let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE);
1197
1198    // Use visible_bounds to exclude taskbar/dock areas
1199    let display_bounds = display
1200        .as_ref()
1201        .map(|d| d.visible_bounds())
1202        .unwrap_or_else(default_placement);
1203
1204    let (
1205        Bounds {
1206            origin: base_origin,
1207            size: base_size,
1208        },
1209        window_bounds_ctor,
1210    ): (_, fn(Bounds<Pixels>) -> WindowBounds) = match active_window_bounds {
1211        Some(bounds) => match bounds {
1212            WindowBounds::Windowed(bounds) => (bounds, WindowBounds::Windowed),
1213            WindowBounds::Maximized(bounds) => (bounds, WindowBounds::Maximized),
1214            WindowBounds::Fullscreen(bounds) => (bounds, WindowBounds::Fullscreen),
1215        },
1216        None => (
1217            display
1218                .as_ref()
1219                .map(|d| d.default_bounds())
1220                .unwrap_or_else(default_placement),
1221            WindowBounds::Windowed,
1222        ),
1223    };
1224
1225    let cascade_offset = point(px(CASCADE_OFFSET), px(CASCADE_OFFSET));
1226    let proposed_origin = base_origin + cascade_offset;
1227    let proposed_bounds = Bounds::new(proposed_origin, base_size);
1228
1229    let display_right = display_bounds.origin.x + display_bounds.size.width;
1230    let display_bottom = display_bounds.origin.y + display_bounds.size.height;
1231    let window_right = proposed_bounds.origin.x + proposed_bounds.size.width;
1232    let window_bottom = proposed_bounds.origin.y + proposed_bounds.size.height;
1233
1234    let fits_horizontally = window_right <= display_right;
1235    let fits_vertically = window_bottom <= display_bottom;
1236
1237    let final_origin = match (fits_horizontally, fits_vertically) {
1238        (true, true) => proposed_origin,
1239        (false, true) => point(display_bounds.origin.x, base_origin.y),
1240        (true, false) => point(base_origin.x, display_bounds.origin.y),
1241        (false, false) => display_bounds.origin,
1242    };
1243    window_bounds_ctor(Bounds::new(final_origin, base_size))
1244}
1245
1246impl Window {
1247    pub(crate) fn new(
1248        handle: AnyWindowHandle,
1249        options: WindowOptions,
1250        cx: &mut App,
1251    ) -> Result<Self> {
1252        let WindowOptions {
1253            window_bounds,
1254            titlebar,
1255            focus,
1256            show,
1257            kind,
1258            is_movable,
1259            is_resizable,
1260            is_minimizable,
1261            display_id,
1262            window_background,
1263            app_id,
1264            window_min_size,
1265            window_decorations,
1266            #[cfg_attr(
1267                not(any(target_os = "linux", target_os = "freebsd")),
1268                allow(unused_variables)
1269            )]
1270            icon,
1271            #[cfg_attr(not(target_os = "macos"), allow(unused_variables))]
1272            tabbing_identifier,
1273        } = options;
1274
1275        let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx));
1276        let mut platform_window = cx.platform.open_window(
1277            handle,
1278            WindowParams {
1279                bounds: window_bounds.get_bounds(),
1280                titlebar,
1281                kind,
1282                is_movable,
1283                is_resizable,
1284                is_minimizable,
1285                focus,
1286                show,
1287                display_id,
1288                window_min_size,
1289                icon,
1290                #[cfg(target_os = "macos")]
1291                tabbing_identifier,
1292            },
1293        )?;
1294
1295        let tab_bar_visible = platform_window.tab_bar_visible();
1296        SystemWindowTabController::init_visible(cx, tab_bar_visible);
1297        if let Some(tabs) = platform_window.tabbed_windows() {
1298            SystemWindowTabController::add_tab(cx, handle.window_id(), tabs);
1299        }
1300
1301        let display_id = platform_window.display().map(|display| display.id());
1302        let sprite_atlas = platform_window.sprite_atlas();
1303        let mouse_position = platform_window.mouse_position();
1304        let modifiers = platform_window.modifiers();
1305        let capslock = platform_window.capslock();
1306        let content_size = platform_window.content_size();
1307        let scale_factor = platform_window.scale_factor();
1308        let appearance = platform_window.appearance();
1309        let text_system = Arc::new(WindowTextSystem::new(cx.text_system().clone()));
1310        let invalidator = WindowInvalidator::new();
1311        let active = Rc::new(Cell::new(platform_window.is_active()));
1312        let hovered = Rc::new(Cell::new(platform_window.is_hovered()));
1313        let needs_present = Rc::new(Cell::new(false));
1314        let next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>> = Default::default();
1315        let input_rate_tracker = Rc::new(RefCell::new(InputRateTracker::default()));
1316        let last_frame_time = Rc::new(Cell::new(None));
1317
1318        platform_window
1319            .request_decorations(window_decorations.unwrap_or(WindowDecorations::Server));
1320        platform_window.set_background_appearance(window_background);
1321
1322        match window_bounds {
1323            WindowBounds::Fullscreen(_) => platform_window.toggle_fullscreen(),
1324            WindowBounds::Maximized(_) => platform_window.zoom(),
1325            WindowBounds::Windowed(_) => {}
1326        }
1327
1328        platform_window.on_close(Box::new({
1329            let window_id = handle.window_id();
1330            let mut cx = cx.to_async();
1331            move || {
1332                let _ = handle.update(&mut cx, |_, window, _| window.remove_window());
1333                let _ = cx.update(|cx| {
1334                    SystemWindowTabController::remove_tab(cx, window_id);
1335                });
1336            }
1337        }));
1338        platform_window.on_request_frame(Box::new({
1339            let mut cx = cx.to_async();
1340            let invalidator = invalidator.clone();
1341            let active = active.clone();
1342            let needs_present = needs_present.clone();
1343            let next_frame_callbacks = next_frame_callbacks.clone();
1344            let input_rate_tracker = input_rate_tracker.clone();
1345            move |request_frame_options| {
1346                let thermal_state = handle
1347                    .update(&mut cx, |_, _, cx| cx.thermal_state())
1348                    .log_err();
1349
1350                // Throttle frame rate based on conditions:
1351                // - Thermal pressure (Serious/Critical): cap to ~60fps
1352                // - Inactive window (not focused): cap to ~30fps to save energy
1353                let min_frame_interval = if !request_frame_options.force_render
1354                    && !request_frame_options.require_presentation
1355                    && next_frame_callbacks.borrow().is_empty()
1356                {
1357                    None
1358                } else if !active.get() {
1359                    Some(Duration::from_micros(33333))
1360                } else if let Some(ThermalState::Critical | ThermalState::Serious) = thermal_state {
1361                    Some(Duration::from_micros(16667))
1362                } else {
1363                    None
1364                };
1365
1366                let now = Instant::now();
1367                if let Some(min_interval) = min_frame_interval {
1368                    if let Some(last_frame) = last_frame_time.get()
1369                        && now.duration_since(last_frame) < min_interval
1370                    {
1371                        // Must still complete the frame on platforms that require it.
1372                        // On Wayland, `surface.frame()` was already called to request the
1373                        // next frame callback, so we must call `surface.commit()` (via
1374                        // `complete_frame`) or the compositor won't send another callback.
1375                        handle
1376                            .update(&mut cx, |_, window, _| window.complete_frame())
1377                            .log_err();
1378                        return;
1379                    }
1380                }
1381                last_frame_time.set(Some(now));
1382
1383                let next_frame_callbacks = next_frame_callbacks.take();
1384                if !next_frame_callbacks.is_empty() {
1385                    handle
1386                        .update(&mut cx, |_, window, cx| {
1387                            for callback in next_frame_callbacks {
1388                                callback(window, cx);
1389                            }
1390                        })
1391                        .log_err();
1392                }
1393
1394                // Keep presenting if input was recently arriving at a high rate (>= 60fps).
1395                // Once high-rate input is detected, we sustain presentation for 1 second
1396                // to prevent display underclocking during active input.
1397                let needs_present = request_frame_options.require_presentation
1398                    || needs_present.get()
1399                    || (active.get() && input_rate_tracker.borrow_mut().is_high_rate());
1400
1401                if invalidator.is_dirty() || request_frame_options.force_render {
1402                    measure("frame duration", || {
1403                        handle
1404                            .update(&mut cx, |_, window, cx| {
1405                                let arena_clear_needed = window.draw(cx);
1406                                window.present();
1407                                arena_clear_needed.clear();
1408                            })
1409                            .log_err();
1410                    })
1411                } else if needs_present {
1412                    handle
1413                        .update(&mut cx, |_, window, _| window.present())
1414                        .log_err();
1415                }
1416
1417                handle
1418                    .update(&mut cx, |_, window, _| {
1419                        window.complete_frame();
1420                    })
1421                    .log_err();
1422            }
1423        }));
1424        platform_window.on_resize(Box::new({
1425            let mut cx = cx.to_async();
1426            move |_, _| {
1427                handle
1428                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1429                    .log_err();
1430            }
1431        }));
1432        platform_window.on_moved(Box::new({
1433            let mut cx = cx.to_async();
1434            move || {
1435                handle
1436                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1437                    .log_err();
1438            }
1439        }));
1440        platform_window.on_appearance_changed(Box::new({
1441            let mut cx = cx.to_async();
1442            move || {
1443                handle
1444                    .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1445                    .log_err();
1446            }
1447        }));
1448        platform_window.on_button_layout_changed(Box::new({
1449            let mut cx = cx.to_async();
1450            move || {
1451                handle
1452                    .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
1453                    .log_err();
1454            }
1455        }));
1456        platform_window.on_active_status_change(Box::new({
1457            let mut cx = cx.to_async();
1458            move |active| {
1459                handle
1460                    .update(&mut cx, |_, window, cx| {
1461                        if !active {
1462                            cx.platform.set_cursor_style(CursorStyle::Arrow);
1463                        }
1464
1465                        window.active.set(active);
1466                        window.modifiers = window.platform_window.modifiers();
1467                        window.capslock = window.platform_window.capslock();
1468                        window
1469                            .activation_observers
1470                            .clone()
1471                            .retain(&(), |callback| callback(window, cx));
1472
1473                        window.bounds_changed(cx);
1474                        window.refresh();
1475
1476                        SystemWindowTabController::update_last_active(cx, window.handle.id);
1477                    })
1478                    .log_err();
1479            }
1480        }));
1481        platform_window.on_hover_status_change(Box::new({
1482            let mut cx = cx.to_async();
1483            move |active| {
1484                handle
1485                    .update(&mut cx, |_, window, _| {
1486                        window.hovered.set(active);
1487                        window.refresh();
1488                    })
1489                    .log_err();
1490            }
1491        }));
1492        platform_window.on_input({
1493            let mut cx = cx.to_async();
1494            Box::new(move |event| {
1495                handle
1496                    .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1497                    .log_err()
1498                    .unwrap_or(DispatchEventResult::default())
1499            })
1500        });
1501        platform_window.on_hit_test_window_control({
1502            let mut cx = cx.to_async();
1503            Box::new(move || {
1504                handle
1505                    .update(&mut cx, |_, window, _cx| {
1506                        for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1507                            if window.mouse_hit_test.ids.contains(&hitbox.id) {
1508                                return Some(*area);
1509                            }
1510                        }
1511                        None
1512                    })
1513                    .log_err()
1514                    .unwrap_or(None)
1515            })
1516        });
1517        platform_window.on_move_tab_to_new_window({
1518            let mut cx = cx.to_async();
1519            Box::new(move || {
1520                handle
1521                    .update(&mut cx, |_, _window, cx| {
1522                        SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1523                    })
1524                    .log_err();
1525            })
1526        });
1527        platform_window.on_merge_all_windows({
1528            let mut cx = cx.to_async();
1529            Box::new(move || {
1530                handle
1531                    .update(&mut cx, |_, _window, cx| {
1532                        SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1533                    })
1534                    .log_err();
1535            })
1536        });
1537        platform_window.on_select_next_tab({
1538            let mut cx = cx.to_async();
1539            Box::new(move || {
1540                handle
1541                    .update(&mut cx, |_, _window, cx| {
1542                        SystemWindowTabController::select_next_tab(cx, handle.window_id());
1543                    })
1544                    .log_err();
1545            })
1546        });
1547        platform_window.on_select_previous_tab({
1548            let mut cx = cx.to_async();
1549            Box::new(move || {
1550                handle
1551                    .update(&mut cx, |_, _window, cx| {
1552                        SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1553                    })
1554                    .log_err();
1555            })
1556        });
1557        platform_window.on_toggle_tab_bar({
1558            let mut cx = cx.to_async();
1559            Box::new(move || {
1560                handle
1561                    .update(&mut cx, |_, window, cx| {
1562                        let tab_bar_visible = window.platform_window.tab_bar_visible();
1563                        SystemWindowTabController::set_visible(cx, tab_bar_visible);
1564                    })
1565                    .log_err();
1566            })
1567        });
1568
1569        if let Some(app_id) = app_id {
1570            platform_window.set_app_id(&app_id);
1571        }
1572
1573        platform_window.map_window().unwrap();
1574
1575        Ok(Window {
1576            handle,
1577            invalidator,
1578            removed: false,
1579            platform_window,
1580            display_id,
1581            sprite_atlas,
1582            text_system,
1583            text_rendering_mode: cx.text_rendering_mode.clone(),
1584            rem_size: px(16.),
1585            rem_size_override_stack: SmallVec::new(),
1586            viewport_size: content_size,
1587            layout_engine: Some(TaffyLayoutEngine::new()),
1588            root: None,
1589            element_id_stack: SmallVec::default(),
1590            text_style_stack: Vec::new(),
1591            rendered_entity_stack: Vec::new(),
1592            element_offset_stack: Vec::new(),
1593            sticky_viewport_stack: Vec::new(),
1594            content_mask_stack: Vec::new(),
1595            element_opacity: 1.0,
1596            requested_autoscroll: None,
1597            rendered_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1598            next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())),
1599            next_frame_callbacks,
1600            next_hitbox_id: HitboxId(0),
1601            next_tooltip_id: TooltipId::default(),
1602            tooltip_bounds: None,
1603            dirty_views: FxHashSet::default(),
1604            focus_listeners: SubscriberSet::new(),
1605            focus_lost_listeners: SubscriberSet::new(),
1606            default_prevented: true,
1607            mouse_position,
1608            mouse_hit_test: HitTest::default(),
1609            modifiers,
1610            capslock,
1611            scale_factor,
1612            bounds_observers: SubscriberSet::new(),
1613            appearance,
1614            appearance_observers: SubscriberSet::new(),
1615            button_layout_observers: SubscriberSet::new(),
1616            active,
1617            hovered,
1618            needs_present,
1619            input_rate_tracker,
1620            #[cfg(feature = "input-latency-histogram")]
1621            input_latency_tracker: InputLatencyTracker::new()?,
1622            last_input_modality: InputModality::Mouse,
1623            refreshing: false,
1624            activation_observers: SubscriberSet::new(),
1625            focus: None,
1626            focus_enabled: true,
1627            pending_input: None,
1628            pending_modifier: ModifierState::default(),
1629            pending_input_observers: SubscriberSet::new(),
1630            prompt: None,
1631            client_inset: None,
1632            image_cache_stack: Vec::new(),
1633            captured_hitbox: None,
1634            #[cfg(any(feature = "inspector", debug_assertions))]
1635            inspector: None,
1636        })
1637    }
1638
1639    pub(crate) fn new_focus_listener(
1640        &self,
1641        value: AnyWindowFocusListener,
1642    ) -> (Subscription, impl FnOnce() + use<>) {
1643        self.focus_listeners.insert((), value)
1644    }
1645}
1646
1647#[derive(Clone, Debug, Default, PartialEq, Eq)]
1648#[expect(missing_docs)]
1649pub struct DispatchEventResult {
1650    pub propagate: bool,
1651    pub default_prevented: bool,
1652}
1653
1654/// Indicates which region of the window is visible. Content falling outside of this mask will not be
1655/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
1656/// to leave room to support more complex shapes in the future.
1657#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1658#[repr(C)]
1659pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1660    /// The bounds
1661    pub bounds: Bounds<P>,
1662}
1663
1664impl ContentMask<Pixels> {
1665    /// Scale the content mask's pixel units by the given scaling factor.
1666    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1667        ContentMask {
1668            bounds: self.bounds.scale(factor),
1669        }
1670    }
1671
1672    /// Intersect the content mask with the given content mask.
1673    pub fn intersect(&self, other: &Self) -> Self {
1674        let bounds = self.bounds.intersect(&other.bounds);
1675        ContentMask { bounds }
1676    }
1677}
1678
1679impl Window {
1680    fn mark_view_dirty(&mut self, view_id: EntityId) {
1681        // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
1682        // should already be dirty.
1683        for view_id in self
1684            .rendered_frame
1685            .dispatch_tree
1686            .view_path_reversed(view_id)
1687        {
1688            if !self.dirty_views.insert(view_id) {
1689                break;
1690            }
1691        }
1692    }
1693
1694    /// Registers a callback to be invoked when the window appearance changes.
1695    pub fn observe_window_appearance(
1696        &self,
1697        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1698    ) -> Subscription {
1699        let (subscription, activate) = self.appearance_observers.insert(
1700            (),
1701            Box::new(move |window, cx| {
1702                callback(window, cx);
1703                true
1704            }),
1705        );
1706        activate();
1707        subscription
1708    }
1709
1710    /// Registers a callback to be invoked when the window button layout changes.
1711    pub fn observe_button_layout_changed(
1712        &self,
1713        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1714    ) -> Subscription {
1715        let (subscription, activate) = self.button_layout_observers.insert(
1716            (),
1717            Box::new(move |window, cx| {
1718                callback(window, cx);
1719                true
1720            }),
1721        );
1722        activate();
1723        subscription
1724    }
1725
1726    /// Replaces the root entity of the window with a new one.
1727    pub fn replace_root<E>(
1728        &mut self,
1729        cx: &mut App,
1730        build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
1731    ) -> Entity<E>
1732    where
1733        E: 'static + Render,
1734    {
1735        let view = cx.new(|cx| build_view(self, cx));
1736        self.root = Some(view.clone().into());
1737        self.refresh();
1738        view
1739    }
1740
1741    /// Returns the root entity of the window, if it has one.
1742    pub fn root<E>(&self) -> Option<Option<Entity<E>>>
1743    where
1744        E: 'static + Render,
1745    {
1746        self.root
1747            .as_ref()
1748            .map(|view| view.clone().downcast::<E>().ok())
1749    }
1750
1751    /// Obtain a handle to the window that belongs to this context.
1752    pub fn window_handle(&self) -> AnyWindowHandle {
1753        self.handle
1754    }
1755
1756    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
1757    pub fn refresh(&mut self) {
1758        if self.invalidator.not_drawing() {
1759            self.refreshing = true;
1760            self.invalidator.set_dirty(true);
1761        }
1762    }
1763
1764    /// Close this window.
1765    pub fn remove_window(&mut self) {
1766        self.removed = true;
1767    }
1768
1769    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
1770    pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
1771        self.focus
1772            .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
1773    }
1774
1775    /// Move focus to the element associated with the given [`FocusHandle`].
1776    pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
1777        if !self.focus_enabled || self.focus == Some(handle.id) {
1778            return;
1779        }
1780
1781        self.focus = Some(handle.id);
1782        self.clear_pending_keystrokes();
1783
1784        // Avoid re-entrant entity updates by deferring observer notifications to the end of the
1785        // current effect cycle, and only for this window.
1786        let window_handle = self.handle;
1787        cx.defer(move |cx| {
1788            window_handle
1789                .update(cx, |_, window, cx| {
1790                    window.pending_input_changed(cx);
1791                })
1792                .ok();
1793        });
1794
1795        self.refresh();
1796    }
1797
1798    /// Remove focus from all elements within this context's window.
1799    pub fn blur(&mut self) {
1800        if !self.focus_enabled {
1801            return;
1802        }
1803
1804        self.focus = None;
1805        self.refresh();
1806    }
1807
1808    /// Blur the window and don't allow anything in it to be focused again.
1809    pub fn disable_focus(&mut self) {
1810        self.blur();
1811        self.focus_enabled = false;
1812    }
1813
1814    /// Move focus to next tab stop.
1815    pub fn focus_next(&mut self, cx: &mut App) {
1816        if !self.focus_enabled {
1817            return;
1818        }
1819
1820        if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
1821            self.focus(&handle, cx)
1822        }
1823    }
1824
1825    /// Move focus to previous tab stop.
1826    pub fn focus_prev(&mut self, cx: &mut App) {
1827        if !self.focus_enabled {
1828            return;
1829        }
1830
1831        if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
1832            self.focus(&handle, cx)
1833        }
1834    }
1835
1836    /// Accessor for the text system.
1837    pub fn text_system(&self) -> &Arc<WindowTextSystem> {
1838        &self.text_system
1839    }
1840
1841    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
1842    pub fn text_style(&self) -> TextStyle {
1843        let mut style = TextStyle::default();
1844        for refinement in &self.text_style_stack {
1845            style.refine(refinement);
1846        }
1847        style
1848    }
1849
1850    /// Check if the platform window is maximized.
1851    ///
1852    /// On some platforms (namely Windows) this is different than the bounds being the size of the display
1853    pub fn is_maximized(&self) -> bool {
1854        self.platform_window.is_maximized()
1855    }
1856
1857    /// request a certain window decoration (Wayland)
1858    pub fn request_decorations(&self, decorations: WindowDecorations) {
1859        self.platform_window.request_decorations(decorations);
1860    }
1861
1862    /// Start a window resize operation (Wayland)
1863    pub fn start_window_resize(&self, edge: ResizeEdge) {
1864        self.platform_window.start_window_resize(edge);
1865    }
1866
1867    /// Return the `WindowBounds` to indicate that how a window should be opened
1868    /// after it has been closed
1869    pub fn window_bounds(&self) -> WindowBounds {
1870        self.platform_window.window_bounds()
1871    }
1872
1873    /// Return the `WindowBounds` excluding insets (Wayland and X11)
1874    pub fn inner_window_bounds(&self) -> WindowBounds {
1875        self.platform_window.inner_window_bounds()
1876    }
1877
1878    /// Dispatch the given action on the currently focused element.
1879    pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
1880        let focus_id = self.focused(cx).map(|handle| handle.id);
1881
1882        let window = self.handle;
1883        cx.defer(move |cx| {
1884            window
1885                .update(cx, |_, window, cx| {
1886                    let node_id = window.focus_node_id_in_rendered_frame(focus_id);
1887                    window.dispatch_action_on_node(node_id, action.as_ref(), cx);
1888                })
1889                .log_err();
1890        })
1891    }
1892
1893    pub(crate) fn dispatch_keystroke_observers(
1894        &mut self,
1895        event: &dyn Any,
1896        action: Option<Box<dyn Action>>,
1897        context_stack: Vec<KeyContext>,
1898        cx: &mut App,
1899    ) {
1900        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1901            return;
1902        };
1903
1904        cx.keystroke_observers.clone().retain(&(), move |callback| {
1905            (callback)(
1906                &KeystrokeEvent {
1907                    keystroke: key_down_event.keystroke.clone(),
1908                    action: action.as_ref().map(|action| action.boxed_clone()),
1909                    context_stack: context_stack.clone(),
1910                },
1911                self,
1912                cx,
1913            )
1914        });
1915    }
1916
1917    pub(crate) fn dispatch_keystroke_interceptors(
1918        &mut self,
1919        event: &dyn Any,
1920        context_stack: Vec<KeyContext>,
1921        cx: &mut App,
1922    ) {
1923        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1924            return;
1925        };
1926
1927        cx.keystroke_interceptors
1928            .clone()
1929            .retain(&(), move |callback| {
1930                (callback)(
1931                    &KeystrokeEvent {
1932                        keystroke: key_down_event.keystroke.clone(),
1933                        action: None,
1934                        context_stack: context_stack.clone(),
1935                    },
1936                    self,
1937                    cx,
1938                )
1939            });
1940    }
1941
1942    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1943    /// that are currently on the stack to be returned to the app.
1944    pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
1945        let handle = self.handle;
1946        cx.defer(move |cx| {
1947            handle.update(cx, |_, window, cx| f(window, cx)).ok();
1948        });
1949    }
1950
1951    /// Subscribe to events emitted by a entity.
1952    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1953    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1954    pub fn observe<T: 'static>(
1955        &mut self,
1956        observed: &Entity<T>,
1957        cx: &mut App,
1958        mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
1959    ) -> Subscription {
1960        let entity_id = observed.entity_id();
1961        let observed = observed.downgrade();
1962        let window_handle = self.handle;
1963        cx.new_observer(
1964            entity_id,
1965            Box::new(move |cx| {
1966                window_handle
1967                    .update(cx, |_, window, cx| {
1968                        if let Some(handle) = observed.upgrade() {
1969                            on_notify(handle, window, cx);
1970                            true
1971                        } else {
1972                            false
1973                        }
1974                    })
1975                    .unwrap_or(false)
1976            }),
1977        )
1978    }
1979
1980    /// Subscribe to events emitted by a entity.
1981    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1982    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1983    pub fn subscribe<Emitter, Evt>(
1984        &mut self,
1985        entity: &Entity<Emitter>,
1986        cx: &mut App,
1987        mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
1988    ) -> Subscription
1989    where
1990        Emitter: EventEmitter<Evt>,
1991        Evt: 'static,
1992    {
1993        let entity_id = entity.entity_id();
1994        let handle = entity.downgrade();
1995        let window_handle = self.handle;
1996        cx.new_subscription(
1997            entity_id,
1998            (
1999                TypeId::of::<Evt>(),
2000                Box::new(move |event, cx| {
2001                    window_handle
2002                        .update(cx, |_, window, cx| {
2003                            if let Some(entity) = handle.upgrade() {
2004                                let event = event.downcast_ref().expect("invalid event type");
2005                                on_event(entity, event, window, cx);
2006                                true
2007                            } else {
2008                                false
2009                            }
2010                        })
2011                        .unwrap_or(false)
2012                }),
2013            ),
2014        )
2015    }
2016
2017    /// Register a callback to be invoked when the given `Entity` is released.
2018    pub fn observe_release<T>(
2019        &self,
2020        entity: &Entity<T>,
2021        cx: &mut App,
2022        mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2023    ) -> Subscription
2024    where
2025        T: 'static,
2026    {
2027        let entity_id = entity.entity_id();
2028        let window_handle = self.handle;
2029        let (subscription, activate) = cx.release_listeners.insert(
2030            entity_id,
2031            Box::new(move |entity, cx| {
2032                let entity = entity.downcast_mut().expect("invalid entity type");
2033                let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2034            }),
2035        );
2036        activate();
2037        subscription
2038    }
2039
2040    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
2041    /// await points in async code.
2042    pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2043        AsyncWindowContext::new_context(cx.to_async(), self.handle)
2044    }
2045
2046    /// Schedule the given closure to be run directly after the current frame is rendered.
2047    pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2048        RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2049    }
2050
2051    /// Schedule a frame to be drawn on the next animation frame.
2052    ///
2053    /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
2054    /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
2055    ///
2056    /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
2057    pub fn request_animation_frame(&self) {
2058        let entity = self.current_view();
2059        self.on_next_frame(move |_, cx| cx.notify(entity));
2060    }
2061
2062    /// Spawn the future returned by the given closure on the application thread pool.
2063    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
2064    /// use within your future.
2065    #[track_caller]
2066    pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2067    where
2068        R: 'static,
2069        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2070    {
2071        let handle = self.handle;
2072        cx.spawn(async move |app| {
2073            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2074            f(&mut async_window_cx).await
2075        })
2076    }
2077
2078    /// Spawn the future returned by the given closure on the application thread
2079    /// pool, with the given priority. The closure is provided a handle to the
2080    /// current window and an `AsyncWindowContext` for use within your future.
2081    #[track_caller]
2082    pub fn spawn_with_priority<AsyncFn, R>(
2083        &self,
2084        priority: Priority,
2085        cx: &App,
2086        f: AsyncFn,
2087    ) -> Task<R>
2088    where
2089        R: 'static,
2090        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2091    {
2092        let handle = self.handle;
2093        cx.spawn_with_priority(priority, async move |app| {
2094            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2095            f(&mut async_window_cx).await
2096        })
2097    }
2098
2099    /// Notify the window that its bounds have changed.
2100    ///
2101    /// This updates internal state like `viewport_size` and `scale_factor` from
2102    /// the platform window, then notifies observers. Normally called automatically
2103    /// by the platform's resize callback, but exposed publicly for test infrastructure.
2104    pub fn bounds_changed(&mut self, cx: &mut App) {
2105        self.scale_factor = self.platform_window.scale_factor();
2106        self.viewport_size = self.platform_window.content_size();
2107        self.display_id = self.platform_window.display().map(|display| display.id());
2108
2109        self.refresh();
2110
2111        self.bounds_observers
2112            .clone()
2113            .retain(&(), |callback| callback(self, cx));
2114    }
2115
2116    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
2117    pub fn bounds(&self) -> Bounds<Pixels> {
2118        self.platform_window.bounds()
2119    }
2120
2121    /// Renders the current frame's scene to a texture and returns the pixel data as an RGBA image.
2122    /// This does not present the frame to screen - useful for visual testing where we want
2123    /// to capture what would be rendered without displaying it or requiring the window to be visible.
2124    #[cfg(any(test, feature = "test-support"))]
2125    pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
2126        self.platform_window
2127            .render_to_image(&self.rendered_frame.scene)
2128    }
2129
2130    /// Set the content size of the window.
2131    pub fn resize(&mut self, size: Size<Pixels>) {
2132        self.platform_window.resize(size);
2133    }
2134
2135    /// Returns whether or not the window is currently fullscreen
2136    pub fn is_fullscreen(&self) -> bool {
2137        self.platform_window.is_fullscreen()
2138    }
2139
2140    pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
2141        self.appearance = self.platform_window.appearance();
2142
2143        self.appearance_observers
2144            .clone()
2145            .retain(&(), |callback| callback(self, cx));
2146    }
2147
2148    pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2149        self.button_layout_observers
2150            .clone()
2151            .retain(&(), |callback| callback(self, cx));
2152    }
2153
2154    /// Returns the appearance of the current window.
2155    pub fn appearance(&self) -> WindowAppearance {
2156        self.appearance
2157    }
2158
2159    /// Returns the size of the drawable area within the window.
2160    pub fn viewport_size(&self) -> Size<Pixels> {
2161        self.viewport_size
2162    }
2163
2164    /// Returns whether this window is focused by the operating system (receiving key events).
2165    pub fn is_window_active(&self) -> bool {
2166        self.active.get()
2167    }
2168
2169    /// Returns whether this window is considered to be the window
2170    /// that currently owns the mouse cursor.
2171    /// On mac, this is equivalent to `is_window_active`.
2172    pub fn is_window_hovered(&self) -> bool {
2173        if cfg!(any(
2174            target_os = "windows",
2175            target_os = "linux",
2176            target_os = "freebsd"
2177        )) {
2178            self.hovered.get()
2179        } else {
2180            self.is_window_active()
2181        }
2182    }
2183
2184    /// Toggle zoom on the window.
2185    pub fn zoom_window(&self) {
2186        self.platform_window.zoom();
2187    }
2188
2189    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
2190    pub fn show_window_menu(&self, position: Point<Pixels>) {
2191        self.platform_window.show_window_menu(position)
2192    }
2193
2194    /// Handle window movement for Linux and macOS.
2195    /// Tells the compositor to take control of window movement (Wayland and X11)
2196    ///
2197    /// Events may not be received during a move operation.
2198    pub fn start_window_move(&self) {
2199        self.platform_window.start_window_move()
2200    }
2201
2202    /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
2203    pub fn set_client_inset(&mut self, inset: Pixels) {
2204        self.client_inset = Some(inset);
2205        self.platform_window.set_client_inset(inset);
2206    }
2207
2208    /// Returns the client_inset value by [`Self::set_client_inset`].
2209    pub fn client_inset(&self) -> Option<Pixels> {
2210        self.client_inset
2211    }
2212
2213    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
2214    pub fn window_decorations(&self) -> Decorations {
2215        self.platform_window.window_decorations()
2216    }
2217
2218    /// Returns which window controls are currently visible (Wayland)
2219    pub fn window_controls(&self) -> WindowControls {
2220        self.platform_window.window_controls()
2221    }
2222
2223    /// Updates the window's title at the platform level.
2224    pub fn set_window_title(&mut self, title: &str) {
2225        self.platform_window.set_title(title);
2226    }
2227
2228    /// Sets the application identifier.
2229    pub fn set_app_id(&mut self, app_id: &str) {
2230        self.platform_window.set_app_id(app_id);
2231    }
2232
2233    /// Sets the window background appearance.
2234    pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2235        self.platform_window
2236            .set_background_appearance(background_appearance);
2237    }
2238
2239    /// Mark the window as dirty at the platform level.
2240    pub fn set_window_edited(&mut self, edited: bool) {
2241        self.platform_window.set_edited(edited);
2242    }
2243
2244    /// Set the path of the file this window represents.
2245    /// On macOS, this sets the window's accessibility document property (AXDocument).
2246    pub fn set_document_path(&self, path: Option<&std::path::Path>) {
2247        self.platform_window.set_document_path(path);
2248    }
2249
2250    /// Determine the display on which the window is visible.
2251    pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2252        cx.platform
2253            .displays()
2254            .into_iter()
2255            .find(|display| Some(display.id()) == self.display_id)
2256    }
2257
2258    /// Show the platform character palette.
2259    pub fn show_character_palette(&self) {
2260        self.platform_window.show_character_palette();
2261    }
2262
2263    /// The scale factor of the display associated with the window. For example, it could
2264    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
2265    /// be rendered as two pixels on screen.
2266    pub fn scale_factor(&self) -> f32 {
2267        self.scale_factor
2268    }
2269
2270    /// The size of an em for the base font of the application. Adjusting this value allows the
2271    /// UI to scale, just like zooming a web page.
2272    pub fn rem_size(&self) -> Pixels {
2273        self.rem_size_override_stack
2274            .last()
2275            .copied()
2276            .unwrap_or(self.rem_size)
2277    }
2278
2279    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
2280    /// UI to scale, just like zooming a web page.
2281    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2282        self.rem_size = rem_size.into();
2283    }
2284
2285    /// Acquire a globally unique identifier for the given ElementId.
2286    /// Only valid for the duration of the provided closure.
2287    pub fn with_global_id<R>(
2288        &mut self,
2289        element_id: ElementId,
2290        f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2291    ) -> R {
2292        self.with_id(element_id, |this| {
2293            let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2294
2295            f(&global_id, this)
2296        })
2297    }
2298
2299    /// Calls the provided closure with the element ID pushed on the stack.
2300    #[inline]
2301    pub fn with_id<R>(
2302        &mut self,
2303        element_id: impl Into<ElementId>,
2304        f: impl FnOnce(&mut Self) -> R,
2305    ) -> R {
2306        self.element_id_stack.push(element_id.into());
2307        let result = f(self);
2308        self.element_id_stack.pop();
2309        result
2310    }
2311
2312    /// Executes the provided function with the specified rem size.
2313    ///
2314    /// This method must only be called as part of element drawing.
2315    // This function is called in a highly recursive manner in editor
2316    // prepainting, make sure its inlined to reduce the stack burden
2317    #[inline]
2318    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2319    where
2320        F: FnOnce(&mut Self) -> R,
2321    {
2322        self.invalidator.debug_assert_paint_or_prepaint();
2323
2324        if let Some(rem_size) = rem_size {
2325            self.rem_size_override_stack.push(rem_size.into());
2326            let result = f(self);
2327            self.rem_size_override_stack.pop();
2328            result
2329        } else {
2330            f(self)
2331        }
2332    }
2333
2334    /// The line height associated with the current text style.
2335    pub fn line_height(&self) -> Pixels {
2336        self.text_style().line_height_in_pixels(self.rem_size())
2337    }
2338
2339    /// Rounds a logical value to the nearest device pixel.
2340    #[inline]
2341    pub fn pixel_snap(&self, value: Pixels) -> Pixels {
2342        px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
2343    }
2344
2345    /// f64 variant of [`Self::pixel_snap`].
2346    #[inline]
2347    pub fn pixel_snap_f64(&self, value: f64) -> f64 {
2348        let scale_factor = f64::from(self.scale_factor());
2349        round_half_toward_zero_f64(value * scale_factor) / scale_factor
2350    }
2351
2352    /// Snaps a bounds' origin and size to the nearest device pixel.
2353    #[inline]
2354    pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
2355        bounds.map(|c| self.pixel_snap(c))
2356    }
2357
2358    /// Snaps a point's coordinates to the nearest device pixel.
2359    #[inline]
2360    pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
2361        position.map(|c| self.pixel_snap(c))
2362    }
2363
2364    #[inline]
2365    fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2366        let scale_factor = self.scale_factor();
2367        let left = round_to_device_pixel(bounds.left().0, scale_factor);
2368        let top = round_to_device_pixel(bounds.top().0, scale_factor);
2369        let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
2370        let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2371        Bounds::from_corners(
2372            point(ScaledPixels(left), ScaledPixels(top)),
2373            point(ScaledPixels(right), ScaledPixels(bottom)),
2374        )
2375    }
2376
2377    /// Rounds half-to-zero but clamps any non-zero input up to 1 dp so thin strokes do not disappear.
2378    #[inline]
2379    fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
2380        ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
2381    }
2382
2383    #[inline]
2384    fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
2385        edges.map(|e| self.snap_stroke(*e))
2386    }
2387
2388    /// Floors the near edge and ceils the far edge, producing a strict superset of the raw region.
2389    #[inline]
2390    fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2391        let scale_factor = self.scale_factor();
2392        let left = floor_to_device_pixel(bounds.left().0, scale_factor);
2393        let top = floor_to_device_pixel(bounds.top().0, scale_factor);
2394        let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
2395        let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2396        Bounds::from_corners(
2397            point(ScaledPixels(left), ScaledPixels(top)),
2398            point(ScaledPixels(right), ScaledPixels(bottom)),
2399        )
2400    }
2401
2402    #[inline]
2403    fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
2404        ContentMask {
2405            bounds: self.cover_bounds(self.content_mask().bounds),
2406        }
2407    }
2408
2409    /// Call to prevent the default action of an event. Currently only used to prevent
2410    /// parent elements from becoming focused on mouse down.
2411    pub fn prevent_default(&mut self) {
2412        self.default_prevented = true;
2413    }
2414
2415    /// Obtain whether default has been prevented for the event currently being dispatched.
2416    pub fn default_prevented(&self) -> bool {
2417        self.default_prevented
2418    }
2419
2420    /// Determine whether the given action is available along the dispatch path to the currently focused element.
2421    pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2422        let node_id =
2423            self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2424        self.rendered_frame
2425            .dispatch_tree
2426            .is_action_available(action, node_id)
2427    }
2428
2429    /// Determine whether the given action is available along the dispatch path to the given focus_handle.
2430    pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2431        let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2432        self.rendered_frame
2433            .dispatch_tree
2434            .is_action_available(action, node_id)
2435    }
2436
2437    /// The position of the mouse relative to the window.
2438    pub fn mouse_position(&self) -> Point<Pixels> {
2439        self.mouse_position
2440    }
2441
2442    /// Captures the pointer for the given hitbox. While captured, all mouse move and mouse up
2443    /// events will be routed to listeners that check this hitbox's `is_hovered` status,
2444    /// regardless of actual hit testing. This enables drag operations that continue
2445    /// even when the pointer moves outside the element's bounds.
2446    ///
2447    /// The capture is automatically released on mouse up.
2448    pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
2449        self.captured_hitbox = Some(hitbox_id);
2450    }
2451
2452    /// Releases any active pointer capture.
2453    pub fn release_pointer(&mut self) {
2454        self.captured_hitbox = None;
2455    }
2456
2457    /// Returns the hitbox that has captured the pointer, if any.
2458    pub fn captured_hitbox(&self) -> Option<HitboxId> {
2459        self.captured_hitbox
2460    }
2461
2462    /// The current state of the keyboard's modifiers
2463    pub fn modifiers(&self) -> Modifiers {
2464        self.modifiers
2465    }
2466
2467    /// Returns true if the last input event was keyboard-based (key press, tab navigation, etc.)
2468    /// This is used for focus-visible styling to show focus indicators only for keyboard navigation.
2469    pub fn last_input_was_keyboard(&self) -> bool {
2470        self.last_input_modality == InputModality::Keyboard
2471    }
2472
2473    /// The current state of the keyboard's capslock
2474    pub fn capslock(&self) -> Capslock {
2475        self.capslock
2476    }
2477
2478    fn complete_frame(&self) {
2479        self.platform_window.completed_frame();
2480    }
2481
2482    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
2483    /// the contents of the new [`Scene`], use [`Self::present`].
2484    #[profiling::function]
2485    pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2486        // Set up the per-App arena for element allocation during this draw.
2487        // This ensures that multiple test Apps have isolated arenas.
2488        let _arena_scope = ElementArenaScope::enter(&cx.element_arena);
2489
2490        self.invalidate_entities();
2491        cx.entities.clear_accessed();
2492        debug_assert!(self.rendered_entity_stack.is_empty());
2493        self.invalidator.set_dirty(false);
2494        self.requested_autoscroll = None;
2495
2496        // Restore the previously-used input handler.
2497        if let Some(input_handler) = self.platform_window.take_input_handler() {
2498            self.rendered_frame.input_handlers.push(Some(input_handler));
2499        }
2500        if !cx.mode.skip_drawing() {
2501            self.draw_roots(cx);
2502        }
2503        self.dirty_views.clear();
2504        self.next_frame.window_active = self.active.get();
2505
2506        // Register requested input handler with the platform window.
2507        if let Some(input_handler) = self.next_frame.input_handlers.pop() {
2508            self.platform_window
2509                .set_input_handler(input_handler.unwrap());
2510        }
2511
2512        self.layout_engine.as_mut().unwrap().clear();
2513        self.text_system().finish_frame();
2514        self.next_frame.finish(&mut self.rendered_frame);
2515
2516        self.invalidator.set_phase(DrawPhase::Focus);
2517        let previous_focus_path = self.rendered_frame.focus_path();
2518        let previous_window_active = self.rendered_frame.window_active;
2519        mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2520        self.next_frame.clear();
2521        let current_focus_path = self.rendered_frame.focus_path();
2522        let current_window_active = self.rendered_frame.window_active;
2523
2524        if previous_focus_path != current_focus_path
2525            || previous_window_active != current_window_active
2526        {
2527            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2528                self.focus_lost_listeners
2529                    .clone()
2530                    .retain(&(), |listener| listener(self, cx));
2531            }
2532
2533            let event = WindowFocusEvent {
2534                previous_focus_path: if previous_window_active {
2535                    previous_focus_path
2536                } else {
2537                    Default::default()
2538                },
2539                current_focus_path: if current_window_active {
2540                    current_focus_path
2541                } else {
2542                    Default::default()
2543                },
2544            };
2545            self.focus_listeners
2546                .clone()
2547                .retain(&(), |listener| listener(&event, self, cx));
2548        }
2549
2550        debug_assert!(self.rendered_entity_stack.is_empty());
2551        self.record_entities_accessed(cx);
2552        self.reset_cursor_style(cx);
2553        self.refreshing = false;
2554        self.invalidator.set_phase(DrawPhase::None);
2555        self.needs_present.set(true);
2556
2557        ArenaClearNeeded::new(&cx.element_arena)
2558    }
2559
2560    fn record_entities_accessed(&mut self, cx: &mut App) {
2561        let mut entities_ref = cx.entities.accessed_entities.get_mut();
2562        let mut entities = mem::take(entities_ref.deref_mut());
2563        let handle = self.handle;
2564        cx.record_entities_accessed(
2565            handle,
2566            // Try moving window invalidator into the Window
2567            self.invalidator.clone(),
2568            &entities,
2569        );
2570        let mut entities_ref = cx.entities.accessed_entities.get_mut();
2571        mem::swap(&mut entities, entities_ref.deref_mut());
2572    }
2573
2574    fn invalidate_entities(&mut self) {
2575        let mut views = self.invalidator.take_views();
2576        for entity in views.drain() {
2577            self.mark_view_dirty(entity);
2578        }
2579        self.invalidator.replace_views(views);
2580    }
2581
2582    #[profiling::function]
2583    fn present(&mut self) {
2584        self.platform_window.draw(&self.rendered_frame.scene);
2585        #[cfg(feature = "input-latency-histogram")]
2586        self.input_latency_tracker.record_frame_presented();
2587        self.needs_present.set(false);
2588        profiling::finish_frame!();
2589    }
2590
2591    /// Returns a snapshot of the current input-latency histograms.
2592    #[cfg(feature = "input-latency-histogram")]
2593    pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
2594        self.input_latency_tracker.snapshot()
2595    }
2596
2597    fn draw_roots(&mut self, cx: &mut App) {
2598        self.invalidator.set_phase(DrawPhase::Prepaint);
2599        self.tooltip_bounds.take();
2600
2601        let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
2602        let root_size = {
2603            #[cfg(any(feature = "inspector", debug_assertions))]
2604            {
2605                if self.inspector.is_some() {
2606                    let mut size = self.viewport_size;
2607                    size.width = (size.width - _inspector_width).max(px(0.0));
2608                    size
2609                } else {
2610                    self.viewport_size
2611                }
2612            }
2613            #[cfg(not(any(feature = "inspector", debug_assertions)))]
2614            {
2615                self.viewport_size
2616            }
2617        };
2618
2619        // Layout all root elements.
2620        let mut root_element = self.root.as_ref().unwrap().clone().into_any();
2621        root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2622
2623        #[cfg(any(feature = "inspector", debug_assertions))]
2624        let inspector_element = self.prepaint_inspector(_inspector_width, cx);
2625
2626        self.prepaint_deferred_draws(cx);
2627
2628        let mut prompt_element = None;
2629        let mut active_drag_element = None;
2630        let mut tooltip_element = None;
2631        if let Some(prompt) = self.prompt.take() {
2632            let mut element = prompt.view.any_view().into_any();
2633            element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2634            prompt_element = Some(element);
2635            self.prompt = Some(prompt);
2636        } else if let Some(active_drag) = cx.active_drag.take() {
2637            let mut element = active_drag.view.clone().into_any();
2638            let offset = self.mouse_position() - active_drag.cursor_offset;
2639            element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
2640            active_drag_element = Some(element);
2641            cx.active_drag = Some(active_drag);
2642        } else {
2643            tooltip_element = self.prepaint_tooltip(cx);
2644        }
2645
2646        self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
2647
2648        // Now actually paint the elements.
2649        self.invalidator.set_phase(DrawPhase::Paint);
2650        root_element.paint(self, cx);
2651
2652        #[cfg(any(feature = "inspector", debug_assertions))]
2653        self.paint_inspector(inspector_element, cx);
2654
2655        self.paint_deferred_draws(cx);
2656
2657        if let Some(mut prompt_element) = prompt_element {
2658            prompt_element.paint(self, cx);
2659        } else if let Some(mut drag_element) = active_drag_element {
2660            drag_element.paint(self, cx);
2661        } else if let Some(mut tooltip_element) = tooltip_element {
2662            tooltip_element.paint(self, cx);
2663        }
2664
2665        #[cfg(any(feature = "inspector", debug_assertions))]
2666        self.paint_inspector_hitbox(cx);
2667    }
2668
2669    fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
2670        // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
2671        for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
2672            let Some(Some(tooltip_request)) = self
2673                .next_frame
2674                .tooltip_requests
2675                .get(tooltip_request_index)
2676                .cloned()
2677            else {
2678                log::error!("Unexpectedly absent TooltipRequest");
2679                continue;
2680            };
2681            let mut element = tooltip_request.tooltip.view.clone().into_any();
2682            let mouse_position = tooltip_request.tooltip.mouse_position;
2683            let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
2684
2685            let mut tooltip_bounds =
2686                Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
2687            let window_bounds = Bounds {
2688                origin: Point::default(),
2689                size: self.viewport_size(),
2690            };
2691
2692            if tooltip_bounds.right() > window_bounds.right() {
2693                let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
2694                if new_x >= Pixels::ZERO {
2695                    tooltip_bounds.origin.x = new_x;
2696                } else {
2697                    tooltip_bounds.origin.x = cmp::max(
2698                        Pixels::ZERO,
2699                        tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
2700                    );
2701                }
2702            }
2703
2704            if tooltip_bounds.bottom() > window_bounds.bottom() {
2705                let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
2706                if new_y >= Pixels::ZERO {
2707                    tooltip_bounds.origin.y = new_y;
2708                } else {
2709                    tooltip_bounds.origin.y = cmp::max(
2710                        Pixels::ZERO,
2711                        tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
2712                    );
2713                }
2714            }
2715
2716            // It's possible for an element to have an active tooltip while not being painted (e.g.
2717            // via the `visible_on_hover` method). Since mouse listeners are not active in this
2718            // case, instead update the tooltip's visibility here.
2719            let is_visible =
2720                (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
2721            if !is_visible {
2722                continue;
2723            }
2724
2725            self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
2726                element.prepaint(window, cx)
2727            });
2728
2729            self.tooltip_bounds = Some(TooltipBounds {
2730                id: tooltip_request.id,
2731                bounds: tooltip_bounds,
2732            });
2733            return Some(element);
2734        }
2735        None
2736    }
2737
2738    fn prepaint_deferred_draws(&mut self, cx: &mut App) {
2739        assert_eq!(self.element_id_stack.len(), 0);
2740
2741        let mut completed_draws = Vec::new();
2742
2743        // Process deferred draws in multiple rounds to support nesting.
2744        // Each round processes all current deferred draws, which may produce new ones.
2745        let mut depth = 0;
2746        loop {
2747            // Limit maximum nesting depth to prevent infinite loops.
2748            assert!(depth < 10, "Exceeded maximum (10) deferred depth");
2749            depth += 1;
2750            let deferred_count = self.next_frame.deferred_draws.len();
2751            if deferred_count == 0 {
2752                break;
2753            }
2754
2755            // Sort by priority for this round
2756            let traversal_order = self.deferred_draw_traversal_order();
2757            let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2758
2759            for deferred_draw_ix in traversal_order {
2760                let deferred_draw = &mut deferred_draws[deferred_draw_ix];
2761                self.element_id_stack
2762                    .clone_from(&deferred_draw.element_id_stack);
2763                self.text_style_stack
2764                    .clone_from(&deferred_draw.text_style_stack);
2765                self.next_frame
2766                    .dispatch_tree
2767                    .set_active_node(deferred_draw.parent_node);
2768
2769                let prepaint_start = self.prepaint_index();
2770                if let Some(element) = deferred_draw.element.as_mut() {
2771                    self.with_rendered_view(deferred_draw.current_view, |window| {
2772                        window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2773                            window.with_absolute_element_offset(
2774                                deferred_draw.absolute_offset,
2775                                |window| {
2776                                    element.prepaint(window, cx);
2777                                },
2778                            );
2779                        });
2780                    })
2781                } else {
2782                    self.reuse_prepaint(deferred_draw.prepaint_range.clone());
2783                }
2784                let prepaint_end = self.prepaint_index();
2785                deferred_draw.prepaint_range = prepaint_start..prepaint_end;
2786            }
2787
2788            // Save completed draws and continue with newly added ones
2789            completed_draws.append(&mut deferred_draws);
2790
2791            self.element_id_stack.clear();
2792            self.text_style_stack.clear();
2793        }
2794
2795        // Restore all completed draws
2796        self.next_frame.deferred_draws = completed_draws;
2797    }
2798
2799    fn paint_deferred_draws(&mut self, cx: &mut App) {
2800        assert_eq!(self.element_id_stack.len(), 0);
2801
2802        // Paint all deferred draws in priority order.
2803        // Since prepaint has already processed nested deferreds, we just paint them all.
2804        if self.next_frame.deferred_draws.len() == 0 {
2805            return;
2806        }
2807
2808        let traversal_order = self.deferred_draw_traversal_order();
2809        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2810        for deferred_draw_ix in traversal_order {
2811            let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
2812            self.element_id_stack
2813                .clone_from(&deferred_draw.element_id_stack);
2814            self.next_frame
2815                .dispatch_tree
2816                .set_active_node(deferred_draw.parent_node);
2817
2818            let paint_start = self.paint_index();
2819            let content_mask = deferred_draw.content_mask;
2820            if let Some(element) = deferred_draw.element.as_mut() {
2821                self.with_rendered_view(deferred_draw.current_view, |window| {
2822                    window.with_content_mask(content_mask, |window| {
2823                        window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2824                            element.paint(window, cx);
2825                        });
2826                    })
2827                })
2828            } else {
2829                self.reuse_paint(deferred_draw.paint_range.clone());
2830            }
2831            let paint_end = self.paint_index();
2832            deferred_draw.paint_range = paint_start..paint_end;
2833        }
2834        self.next_frame.deferred_draws = deferred_draws;
2835        self.element_id_stack.clear();
2836    }
2837
2838    fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
2839        let deferred_count = self.next_frame.deferred_draws.len();
2840        let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
2841        sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
2842        sorted_indices
2843    }
2844
2845    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
2846        PrepaintStateIndex {
2847            hitboxes_index: self.next_frame.hitboxes.len(),
2848            tooltips_index: self.next_frame.tooltip_requests.len(),
2849            deferred_draws_index: self.next_frame.deferred_draws.len(),
2850            dispatch_tree_index: self.next_frame.dispatch_tree.len(),
2851            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2852            line_layout_index: self.text_system.layout_index(),
2853        }
2854    }
2855
2856    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
2857        self.next_frame.hitboxes.extend(
2858            self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
2859                .iter()
2860                .cloned(),
2861        );
2862        self.next_frame.tooltip_requests.extend(
2863            self.rendered_frame.tooltip_requests
2864                [range.start.tooltips_index..range.end.tooltips_index]
2865                .iter_mut()
2866                .map(|request| request.take()),
2867        );
2868        self.next_frame.accessed_element_states.extend(
2869            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2870                ..range.end.accessed_element_states_index]
2871                .iter()
2872                .map(|(id, type_id)| (id.clone(), *type_id)),
2873        );
2874        self.text_system
2875            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2876
2877        let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
2878            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
2879            &mut self.rendered_frame.dispatch_tree,
2880            self.focus,
2881        );
2882
2883        if reused_subtree.contains_focus() {
2884            self.next_frame.focus = self.focus;
2885        }
2886
2887        self.next_frame.deferred_draws.extend(
2888            self.rendered_frame.deferred_draws
2889                [range.start.deferred_draws_index..range.end.deferred_draws_index]
2890                .iter()
2891                .map(|deferred_draw| DeferredDraw {
2892                    current_view: deferred_draw.current_view,
2893                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
2894                    element_id_stack: deferred_draw.element_id_stack.clone(),
2895                    text_style_stack: deferred_draw.text_style_stack.clone(),
2896                    content_mask: deferred_draw.content_mask,
2897                    rem_size: deferred_draw.rem_size,
2898                    priority: deferred_draw.priority,
2899                    element: None,
2900                    absolute_offset: deferred_draw.absolute_offset,
2901                    prepaint_range: deferred_draw.prepaint_range.clone(),
2902                    paint_range: deferred_draw.paint_range.clone(),
2903                }),
2904        );
2905    }
2906
2907    pub(crate) fn paint_index(&self) -> PaintIndex {
2908        PaintIndex {
2909            scene_index: self.next_frame.scene.len(),
2910            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
2911            input_handlers_index: self.next_frame.input_handlers.len(),
2912            cursor_styles_index: self.next_frame.cursor_styles.len(),
2913            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2914            tab_handle_index: self.next_frame.tab_stops.paint_index(),
2915            line_layout_index: self.text_system.layout_index(),
2916        }
2917    }
2918
2919    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
2920        self.next_frame.cursor_styles.extend(
2921            self.rendered_frame.cursor_styles
2922                [range.start.cursor_styles_index..range.end.cursor_styles_index]
2923                .iter()
2924                .cloned(),
2925        );
2926        self.next_frame.input_handlers.extend(
2927            self.rendered_frame.input_handlers
2928                [range.start.input_handlers_index..range.end.input_handlers_index]
2929                .iter_mut()
2930                .map(|handler| handler.take()),
2931        );
2932        self.next_frame.mouse_listeners.extend(
2933            self.rendered_frame.mouse_listeners
2934                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
2935                .iter_mut()
2936                .map(|listener| listener.take()),
2937        );
2938        self.next_frame.accessed_element_states.extend(
2939            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2940                ..range.end.accessed_element_states_index]
2941                .iter()
2942                .map(|(id, type_id)| (id.clone(), *type_id)),
2943        );
2944        self.next_frame.tab_stops.replay(
2945            &self.rendered_frame.tab_stops.insertion_history
2946                [range.start.tab_handle_index..range.end.tab_handle_index],
2947        );
2948
2949        self.text_system
2950            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2951        self.next_frame.scene.replay(
2952            range.start.scene_index..range.end.scene_index,
2953            &self.rendered_frame.scene,
2954        );
2955    }
2956
2957    /// Push a text style onto the stack, and call a function with that style active.
2958    /// Use [`Window::text_style`] to get the current, combined text style. This method
2959    /// should only be called as part of element drawing.
2960    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
2961    where
2962        F: FnOnce(&mut Self) -> R,
2963    {
2964        self.invalidator.debug_assert_paint_or_prepaint();
2965        if let Some(style) = style {
2966            self.text_style_stack.push(style);
2967            let result = f(self);
2968            self.text_style_stack.pop();
2969            result
2970        } else {
2971            f(self)
2972        }
2973    }
2974
2975    /// Updates the cursor style at the platform level. This method should only be called
2976    /// during the paint phase of element drawing.
2977    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
2978        self.invalidator.debug_assert_paint();
2979        self.next_frame.cursor_styles.push(CursorStyleRequest {
2980            hitbox_id: Some(hitbox.id),
2981            style,
2982        });
2983    }
2984
2985    /// Updates the cursor style for the entire window at the platform level. A cursor
2986    /// style using this method will have precedence over any cursor style set using
2987    /// `set_cursor_style`. This method should only be called during the paint
2988    /// phase of element drawing.
2989    pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
2990        self.invalidator.debug_assert_paint();
2991        self.next_frame.cursor_styles.push(CursorStyleRequest {
2992            hitbox_id: None,
2993            style,
2994        })
2995    }
2996
2997    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
2998    /// during the paint phase of element drawing.
2999    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
3000        self.invalidator.debug_assert_prepaint();
3001        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
3002        self.next_frame
3003            .tooltip_requests
3004            .push(Some(TooltipRequest { id, tooltip }));
3005        id
3006    }
3007
3008    /// Invoke the given function with the given content mask after intersecting it
3009    /// with the current mask. This method should only be called during element drawing.
3010    // This function is called in a highly recursive manner in editor
3011    // prepainting, make sure its inlined to reduce the stack burden
3012    #[inline]
3013    pub fn with_content_mask<R>(
3014        &mut self,
3015        mask: Option<ContentMask<Pixels>>,
3016        f: impl FnOnce(&mut Self) -> R,
3017    ) -> R {
3018        self.invalidator.debug_assert_paint_or_prepaint();
3019        if let Some(mask) = mask {
3020            let mask = mask.intersect(&self.content_mask());
3021            self.content_mask_stack.push(mask);
3022            let result = f(self);
3023            self.content_mask_stack.pop();
3024            result
3025        } else {
3026            f(self)
3027        }
3028    }
3029
3030    /// Updates the global element offset relative to the current offset. This is used to implement
3031    /// scrolling. This method should only be called during the prepaint phase of element drawing.
3032    pub fn with_element_offset<R>(
3033        &mut self,
3034        offset: Point<Pixels>,
3035        f: impl FnOnce(&mut Self) -> R,
3036    ) -> R {
3037        self.invalidator.debug_assert_prepaint();
3038
3039        if offset.is_zero() {
3040            return f(self);
3041        };
3042
3043        let abs_offset = self.element_offset() + offset;
3044        self.with_absolute_element_offset(abs_offset, f)
3045    }
3046
3047    /// Updates the global element offset based on the given offset. This is used to implement
3048    /// drag handles and other manual painting of elements. This method should only be called during
3049    /// the prepaint phase of element drawing.
3050    pub fn with_absolute_element_offset<R>(
3051        &mut self,
3052        offset: Point<Pixels>,
3053        f: impl FnOnce(&mut Self) -> R,
3054    ) -> R {
3055        self.invalidator.debug_assert_prepaint();
3056        self.element_offset_stack.push(offset);
3057        let result = f(self);
3058        self.element_offset_stack.pop();
3059        result
3060    }
3061
3062    /// Returns the visible viewport bounds of the nearest scrollable
3063    /// ancestor pushed via [`Self::with_sticky_viewport`], if any. Used to
3064    /// resolve `Position::Sticky` elements' clamped paint position.
3065    pub fn sticky_viewport(&self) -> Option<Bounds<Pixels>> {
3066        self.sticky_viewport_stack.last().copied()
3067    }
3068
3069    /// Marks `viewport` (a scrollable container's own bounds, in window
3070    /// space) as the nearest sticky-positioning reference for the duration
3071    /// of `f`. Call this around prepainting/painting the children of any
3072    /// element with `overflow: scroll`, so descendant `Position::Sticky`
3073    /// elements can clamp against it. This method should only be called
3074    /// during the prepaint or paint phase of element drawing.
3075    pub fn with_sticky_viewport<R>(
3076        &mut self,
3077        viewport: Bounds<Pixels>,
3078        f: impl FnOnce(&mut Self) -> R,
3079    ) -> R {
3080        self.sticky_viewport_stack.push(viewport);
3081        let result = f(self);
3082        self.sticky_viewport_stack.pop();
3083        result
3084    }
3085
3086    pub(crate) fn with_element_opacity<R>(
3087        &mut self,
3088        opacity: Option<f32>,
3089        f: impl FnOnce(&mut Self) -> R,
3090    ) -> R {
3091        self.invalidator.debug_assert_paint_or_prepaint();
3092
3093        let Some(opacity) = opacity else {
3094            return f(self);
3095        };
3096
3097        let previous_opacity = self.element_opacity;
3098        self.element_opacity = previous_opacity * opacity;
3099        let result = f(self);
3100        self.element_opacity = previous_opacity;
3101        result
3102    }
3103
3104    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
3105    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
3106    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
3107    /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
3108    /// called during the prepaint phase of element drawing.
3109    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
3110        self.invalidator.debug_assert_prepaint();
3111        let index = self.prepaint_index();
3112        let result = f(self);
3113        if result.is_err() {
3114            self.next_frame.hitboxes.truncate(index.hitboxes_index);
3115            self.next_frame
3116                .tooltip_requests
3117                .truncate(index.tooltips_index);
3118            self.next_frame
3119                .deferred_draws
3120                .truncate(index.deferred_draws_index);
3121            self.next_frame
3122                .dispatch_tree
3123                .truncate(index.dispatch_tree_index);
3124            self.next_frame
3125                .accessed_element_states
3126                .truncate(index.accessed_element_states_index);
3127            self.text_system.truncate_layouts(index.line_layout_index);
3128        }
3129        result
3130    }
3131
3132    /// When you call this method during [`Element::prepaint`], containing elements will attempt to
3133    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
3134    /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
3135    /// that supports this method being called on the elements it contains. This method should only be
3136    /// called during the prepaint phase of element drawing.
3137    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
3138        self.invalidator.debug_assert_prepaint();
3139        self.requested_autoscroll = Some(bounds);
3140    }
3141
3142    /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
3143    /// described in [`Self::request_autoscroll`].
3144    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
3145        self.invalidator.debug_assert_prepaint();
3146        self.requested_autoscroll.take()
3147    }
3148
3149    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
3150    /// Your view will be re-drawn once the asset has finished loading.
3151    ///
3152    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
3153    /// time.
3154    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3155        let (task, is_first) = cx.fetch_asset::<A>(source);
3156        task.clone().now_or_never().or_else(|| {
3157            if is_first {
3158                let entity_id = self.current_view();
3159                self.spawn(cx, {
3160                    let task = task.clone();
3161                    async move |cx| {
3162                        task.await;
3163
3164                        cx.on_next_frame(move |_, cx| {
3165                            cx.notify(entity_id);
3166                        });
3167                    }
3168                })
3169                .detach();
3170            }
3171
3172            None
3173        })
3174    }
3175
3176    /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
3177    /// Your view will not be re-drawn once the asset has finished loading.
3178    ///
3179    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
3180    /// time.
3181    pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3182        let (task, _) = cx.fetch_asset::<A>(source);
3183        task.now_or_never()
3184    }
3185    /// Obtain the current element offset. This method should only be called during the
3186    /// prepaint phase of element drawing.
3187    pub fn element_offset(&self) -> Point<Pixels> {
3188        self.invalidator.debug_assert_prepaint();
3189        self.element_offset_stack
3190            .last()
3191            .copied()
3192            .unwrap_or_default()
3193    }
3194
3195    /// Obtain the current element opacity. This method should only be called during the
3196    /// prepaint phase of element drawing.
3197    #[inline]
3198    pub(crate) fn element_opacity(&self) -> f32 {
3199        self.invalidator.debug_assert_paint_or_prepaint();
3200        self.element_opacity
3201    }
3202
3203    /// Obtain the current content mask. This method should only be called during element drawing.
3204    pub fn content_mask(&self) -> ContentMask<Pixels> {
3205        self.invalidator.debug_assert_paint_or_prepaint();
3206        self.content_mask_stack
3207            .last()
3208            .cloned()
3209            .unwrap_or_else(|| ContentMask {
3210                bounds: Bounds {
3211                    origin: Point::default(),
3212                    size: self.viewport_size,
3213                },
3214            })
3215    }
3216
3217    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
3218    /// This can be used within a custom element to distinguish multiple sets of child elements.
3219    pub fn with_element_namespace<R>(
3220        &mut self,
3221        element_id: impl Into<ElementId>,
3222        f: impl FnOnce(&mut Self) -> R,
3223    ) -> R {
3224        self.element_id_stack.push(element_id.into());
3225        let result = f(self);
3226        self.element_id_stack.pop();
3227        result
3228    }
3229
3230    /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
3231    pub fn use_keyed_state<S: 'static>(
3232        &mut self,
3233        key: impl Into<ElementId>,
3234        cx: &mut App,
3235        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3236    ) -> Entity<S> {
3237        let current_view = self.current_view();
3238        self.with_global_id(key.into(), |global_id, window| {
3239            window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
3240                if let Some(state) = state {
3241                    (state.clone(), state)
3242                } else {
3243                    let new_state = cx.new(|cx| init(window, cx));
3244                    cx.observe(&new_state, move |_, cx| {
3245                        cx.notify(current_view);
3246                    })
3247                    .detach();
3248                    (new_state.clone(), new_state)
3249                }
3250            })
3251        })
3252    }
3253
3254    /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
3255    ///
3256    /// NOTE: This method uses the location of the caller to generate an ID for this state.
3257    ///       If this is not sufficient to identify your state (e.g. you're rendering a list item),
3258    ///       you can provide a custom ElementID using the `use_keyed_state` method.
3259    #[track_caller]
3260    pub fn use_state<S: 'static>(
3261        &mut self,
3262        cx: &mut App,
3263        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3264    ) -> Entity<S> {
3265        self.use_keyed_state(
3266            ElementId::CodeLocation(*core::panic::Location::caller()),
3267            cx,
3268            init,
3269        )
3270    }
3271
3272    /// Updates or initializes state for an element with the given id that lives across multiple
3273    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
3274    /// to the given closure. The state returned by the closure will be stored so it can be referenced
3275    /// when drawing the next frame. This method should only be called as part of element drawing.
3276    pub fn with_element_state<S, R>(
3277        &mut self,
3278        global_id: &GlobalElementId,
3279        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
3280    ) -> R
3281    where
3282        S: 'static,
3283    {
3284        self.invalidator.debug_assert_paint_or_prepaint();
3285
3286        let key = (global_id.clone(), TypeId::of::<S>());
3287        self.next_frame.accessed_element_states.push(key.clone());
3288
3289        if let Some(any) = self
3290            .next_frame
3291            .element_states
3292            .remove(&key)
3293            .or_else(|| self.rendered_frame.element_states.remove(&key))
3294        {
3295            let ElementStateBox {
3296                inner,
3297                #[cfg(debug_assertions)]
3298                type_name,
3299            } = any;
3300            // Using the extra inner option to avoid needing to reallocate a new box.
3301            let mut state_box = inner
3302                .downcast::<Option<S>>()
3303                .map_err(|_| {
3304                    #[cfg(debug_assertions)]
3305                    {
3306                        anyhow::anyhow!(
3307                            "invalid element state type for id, requested {:?}, actual: {:?}",
3308                            std::any::type_name::<S>(),
3309                            type_name
3310                        )
3311                    }
3312
3313                    #[cfg(not(debug_assertions))]
3314                    {
3315                        anyhow::anyhow!(
3316                            "invalid element state type for id, requested {:?}",
3317                            std::any::type_name::<S>(),
3318                        )
3319                    }
3320                })
3321                .unwrap();
3322
3323            let state = state_box.take().expect(
3324                "reentrant call to with_element_state for the same state type and element id",
3325            );
3326            let (result, state) = f(Some(state), self);
3327            state_box.replace(state);
3328            self.next_frame.element_states.insert(
3329                key,
3330                ElementStateBox {
3331                    inner: state_box,
3332                    #[cfg(debug_assertions)]
3333                    type_name,
3334                },
3335            );
3336            result
3337        } else {
3338            let (result, state) = f(None, self);
3339            self.next_frame.element_states.insert(
3340                key,
3341                ElementStateBox {
3342                    inner: Box::new(Some(state)),
3343                    #[cfg(debug_assertions)]
3344                    type_name: std::any::type_name::<S>(),
3345                },
3346            );
3347            result
3348        }
3349    }
3350
3351    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
3352    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
3353    /// when the element is guaranteed to have an id.
3354    ///
3355    /// The first option means 'no ID provided'
3356    /// The second option means 'not yet initialized'
3357    pub fn with_optional_element_state<S, R>(
3358        &mut self,
3359        global_id: Option<&GlobalElementId>,
3360        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
3361    ) -> R
3362    where
3363        S: 'static,
3364    {
3365        self.invalidator.debug_assert_paint_or_prepaint();
3366
3367        if let Some(global_id) = global_id {
3368            self.with_element_state(global_id, |state, cx| {
3369                let (result, state) = f(Some(state), cx);
3370                let state =
3371                    state.expect("you must return some state when you pass some element id");
3372                (result, state)
3373            })
3374        } else {
3375            let (result, state) = f(None, self);
3376            debug_assert!(
3377                state.is_none(),
3378                "you must not return an element state when passing None for the global id"
3379            );
3380            result
3381        }
3382    }
3383
3384    /// Executes the given closure within the context of a tab group.
3385    #[inline]
3386    pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
3387        if let Some(index) = index {
3388            self.next_frame.tab_stops.begin_group(index);
3389            let result = f(self);
3390            self.next_frame.tab_stops.end_group();
3391            result
3392        } else {
3393            f(self)
3394        }
3395    }
3396
3397    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
3398    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
3399    /// with higher values being drawn on top.
3400    ///
3401    /// When `content_mask` is provided, the deferred element will be clipped to that region during
3402    /// both prepaint and paint. When `None`, no additional clipping is applied.
3403    ///
3404    /// This method should only be called as part of the prepaint phase of element drawing.
3405    pub fn defer_draw(
3406        &mut self,
3407        element: AnyElement,
3408        absolute_offset: Point<Pixels>,
3409        priority: usize,
3410        content_mask: Option<ContentMask<Pixels>>,
3411    ) {
3412        self.invalidator.debug_assert_prepaint();
3413        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3414        self.next_frame.deferred_draws.push(DeferredDraw {
3415            current_view: self.current_view(),
3416            parent_node,
3417            element_id_stack: self.element_id_stack.clone(),
3418            text_style_stack: self.text_style_stack.clone(),
3419            content_mask,
3420            rem_size: self.rem_size(),
3421            priority,
3422            element: Some(element),
3423            absolute_offset,
3424            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3425            paint_range: PaintIndex::default()..PaintIndex::default(),
3426        });
3427    }
3428
3429    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
3430    /// of geometry that are non-overlapping and have the same draw order. This is typically used
3431    /// for performance reasons.
3432    ///
3433    /// This method should only be called as part of the paint phase of element drawing.
3434    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3435        self.invalidator.debug_assert_paint();
3436
3437        let content_mask = self.content_mask();
3438        let clipped_bounds = bounds.intersect(&content_mask.bounds);
3439        if !clipped_bounds.is_empty() {
3440            self.next_frame
3441                .scene
3442                .push_layer(self.cover_bounds(clipped_bounds));
3443        }
3444
3445        let result = f(self);
3446
3447        if !clipped_bounds.is_empty() {
3448            self.next_frame.scene.pop_layer();
3449        }
3450
3451        result
3452    }
3453
3454    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
3455    ///
3456    /// This method should only be called as part of the paint phase of element drawing.
3457    pub fn paint_shadows(
3458        &mut self,
3459        bounds: Bounds<Pixels>,
3460        corner_radii: Corners<Pixels>,
3461        shadows: &[BoxShadow],
3462    ) {
3463        self.invalidator.debug_assert_paint();
3464
3465        let scale_factor = self.scale_factor();
3466        let content_mask = self.snapped_content_mask();
3467        let opacity = self.element_opacity();
3468        for shadow in shadows {
3469            let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3470            self.next_frame.scene.insert_primitive(Shadow {
3471                order: 0,
3472                blur_radius: shadow.blur_radius.scale(scale_factor),
3473                bounds: self.cover_bounds(shadow_bounds),
3474                content_mask,
3475                corner_radii: corner_radii.scale(scale_factor),
3476                color: shadow.color.opacity(opacity),
3477            });
3478        }
3479    }
3480
3481    /// Paint one or more quads into the scene for the next frame at the current stacking context.
3482    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
3483    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
3484    ///
3485    /// This method should only be called as part of the paint phase of element drawing.
3486    ///
3487    /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
3488    /// where the circular arcs meet. This will not display well when combined with dashed borders.
3489    /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
3490    pub fn paint_quad(&mut self, quad: PaintQuad) {
3491        self.invalidator.debug_assert_paint();
3492
3493        let opacity = self.element_opacity();
3494        let snapped_bounds = self.snap_bounds(quad.bounds);
3495        let snapped_border_widths = self.snap_border_widths(quad.border_widths);
3496        self.next_frame.scene.insert_primitive(Quad {
3497            order: 0,
3498            bounds: snapped_bounds,
3499            content_mask: self.snapped_content_mask(),
3500            background: quad.background.opacity(opacity),
3501            border_color: quad.border_color.opacity(opacity),
3502            corner_radii: quad.corner_radii.scale(self.scale_factor()),
3503            border_widths: snapped_border_widths,
3504            border_style: quad.border_style,
3505        });
3506    }
3507
3508    /// Paint the given `Path` into the scene for the next frame at the current z-index.
3509    ///
3510    /// This method should only be called as part of the paint phase of element drawing.
3511    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
3512        self.invalidator.debug_assert_paint();
3513
3514        let scale_factor = self.scale_factor();
3515        let content_mask = self.content_mask();
3516        let opacity = self.element_opacity();
3517        path.content_mask = content_mask;
3518        let color: Background = color.into();
3519        path.color = color.opacity(opacity);
3520        self.next_frame
3521            .scene
3522            .insert_primitive(path.scale(scale_factor));
3523    }
3524
3525    /// Paint an underline into the scene for the next frame at the current z-index.
3526    ///
3527    /// This method should only be called as part of the paint phase of element drawing.
3528    pub fn paint_underline(
3529        &mut self,
3530        origin: Point<Pixels>,
3531        width: Pixels,
3532        style: &UnderlineStyle,
3533    ) {
3534        self.invalidator.debug_assert_paint();
3535
3536        let scale_factor = self.scale_factor();
3537        let thickness = self.snap_stroke(style.thickness);
3538        let height = if style.wavy {
3539            ScaledPixels(thickness.0 * 3.)
3540        } else {
3541            thickness
3542        };
3543        let bounds = Bounds {
3544            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3545            size: size(self.snap_stroke(width), height),
3546        };
3547        let element_opacity = self.element_opacity();
3548
3549        self.next_frame.scene.insert_primitive(Underline {
3550            order: 0,
3551            pad: 0,
3552            bounds,
3553            content_mask: self.snapped_content_mask(),
3554            color: style.color.unwrap_or_default().opacity(element_opacity),
3555            thickness,
3556            wavy: if style.wavy { 1 } else { 0 },
3557        });
3558    }
3559
3560    /// Paint a strikethrough into the scene for the next frame at the current z-index.
3561    ///
3562    /// This method should only be called as part of the paint phase of element drawing.
3563    pub fn paint_strikethrough(
3564        &mut self,
3565        origin: Point<Pixels>,
3566        width: Pixels,
3567        style: &StrikethroughStyle,
3568    ) {
3569        self.invalidator.debug_assert_paint();
3570
3571        let scale_factor = self.scale_factor();
3572        let height = style.thickness;
3573        let bounds = Bounds {
3574            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3575            size: size(self.snap_stroke(width), self.snap_stroke(height)),
3576        };
3577        let opacity = self.element_opacity();
3578
3579        self.next_frame.scene.insert_primitive(Underline {
3580            order: 0,
3581            pad: 0,
3582            bounds,
3583            content_mask: self.snapped_content_mask(),
3584            thickness: self.snap_stroke(style.thickness),
3585            color: style.color.unwrap_or_default().opacity(opacity),
3586            wavy: 0,
3587        });
3588    }
3589
3590    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
3591    ///
3592    /// The y component of the origin is the baseline of the glyph.
3593    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3594    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3595    /// This method is only useful if you need to paint a single glyph that has already been shaped.
3596    ///
3597    /// This method should only be called as part of the paint phase of element drawing.
3598    pub fn paint_glyph(
3599        &mut self,
3600        origin: Point<Pixels>,
3601        font_id: FontId,
3602        glyph_id: GlyphId,
3603        font_size: Pixels,
3604        color: Hsla,
3605    ) -> Result<()> {
3606        self.invalidator.debug_assert_paint();
3607
3608        let element_opacity = self.element_opacity();
3609        let scale_factor = self.scale_factor();
3610        let glyph_origin = origin.scale(scale_factor);
3611
3612        let quantized_origin = Point::new(
3613            round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
3614                / SUBPIXEL_VARIANTS_X as f32,
3615            round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
3616                / SUBPIXEL_VARIANTS_Y as f32,
3617        );
3618        let subpixel_variant = Point::new(
3619            (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
3620            (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
3621        );
3622        let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
3623        let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
3624        let dilation = self.text_system().glyph_dilation_for_color(color);
3625        let params = RenderGlyphParams {
3626            font_id,
3627            glyph_id,
3628            font_size,
3629            subpixel_variant,
3630            scale_factor,
3631            is_emoji: false,
3632            subpixel_rendering,
3633            dilation,
3634        };
3635
3636        let raster_bounds = self.text_system().raster_bounds(&params)?;
3637        if !raster_bounds.is_zero() {
3638            let tile = self
3639                .sprite_atlas
3640                .get_or_insert_with(&params.clone().into(), &mut || {
3641                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3642                    Ok(Some((size, Cow::Owned(bytes))))
3643                })?
3644                .expect("Callback above only errors or returns Some");
3645            let bounds = Bounds {
3646                origin: integer_origin + raster_bounds.origin.map(Into::into),
3647                size: tile.bounds.size.map(Into::into),
3648            };
3649            let content_mask = self.snapped_content_mask();
3650
3651            if subpixel_rendering {
3652                self.next_frame.scene.insert_primitive(SubpixelSprite {
3653                    order: 0,
3654                    pad: 0,
3655                    bounds,
3656                    content_mask,
3657                    color: color.opacity(element_opacity),
3658                    tile,
3659                    transformation: TransformationMatrix::unit(),
3660                });
3661            } else {
3662                self.next_frame.scene.insert_primitive(MonochromeSprite {
3663                    order: 0,
3664                    pad: 0,
3665                    bounds,
3666                    content_mask,
3667                    color: color.opacity(element_opacity),
3668                    tile,
3669                    transformation: TransformationMatrix::unit(),
3670                });
3671            }
3672        }
3673        Ok(())
3674    }
3675
3676    fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
3677        if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
3678            return false;
3679        }
3680
3681        if !self.platform_window.is_subpixel_rendering_supported() {
3682            return false;
3683        }
3684
3685        let mode = match self.text_rendering_mode.get() {
3686            TextRenderingMode::PlatformDefault => self
3687                .text_system()
3688                .recommended_rendering_mode(font_id, font_size),
3689            mode => mode,
3690        };
3691
3692        mode == TextRenderingMode::Subpixel
3693    }
3694
3695    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
3696    ///
3697    /// The y component of the origin is the baseline of the glyph.
3698    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3699    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3700    /// This method is only useful if you need to paint a single emoji that has already been shaped.
3701    ///
3702    /// This method should only be called as part of the paint phase of element drawing.
3703    pub fn paint_emoji(
3704        &mut self,
3705        origin: Point<Pixels>,
3706        font_id: FontId,
3707        glyph_id: GlyphId,
3708        font_size: Pixels,
3709    ) -> Result<()> {
3710        self.invalidator.debug_assert_paint();
3711
3712        let scale_factor = self.scale_factor();
3713        let glyph_origin = origin.scale(scale_factor);
3714        let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
3715        let params = RenderGlyphParams {
3716            font_id,
3717            glyph_id,
3718            font_size,
3719            subpixel_variant: Default::default(),
3720            scale_factor,
3721            is_emoji: true,
3722            subpixel_rendering: false,
3723            dilation: 0,
3724        };
3725
3726        let raster_bounds = self.text_system().raster_bounds(&params)?;
3727        if !raster_bounds.is_zero() {
3728            let tile = self
3729                .sprite_atlas
3730                .get_or_insert_with(&params.clone().into(), &mut || {
3731                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3732                    Ok(Some((size, Cow::Owned(bytes))))
3733                })?
3734                .expect("Callback above only errors or returns Some");
3735
3736            let bounds = Bounds {
3737                origin: integer_origin + raster_bounds.origin.map(Into::into),
3738                size: tile.bounds.size.map(Into::into),
3739            };
3740            let content_mask = self.snapped_content_mask();
3741            let opacity = self.element_opacity();
3742
3743            self.next_frame.scene.insert_primitive(PolychromeSprite {
3744                order: 0,
3745                pad: 0,
3746                grayscale: false,
3747                bounds,
3748                corner_radii: Default::default(),
3749                content_mask,
3750                tile,
3751                opacity,
3752            });
3753        }
3754        Ok(())
3755    }
3756
3757    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
3758    ///
3759    /// This method should only be called as part of the paint phase of element drawing.
3760    pub fn paint_svg(
3761        &mut self,
3762        bounds: Bounds<Pixels>,
3763        path: SharedString,
3764        mut data: Option<&[u8]>,
3765        transformation: TransformationMatrix,
3766        color: Hsla,
3767        cx: &App,
3768    ) -> Result<()> {
3769        self.invalidator.debug_assert_paint();
3770
3771        let element_opacity = self.element_opacity();
3772        let bounds = self.snap_bounds(bounds);
3773
3774        let params = RenderSvgParams {
3775            path,
3776            size: bounds.size.map(|pixels| {
3777                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
3778            }),
3779        };
3780
3781        let Some(tile) =
3782            self.sprite_atlas
3783                .get_or_insert_with(&params.clone().into(), &mut || {
3784                    let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(&params, data)?
3785                    else {
3786                        return Ok(None);
3787                    };
3788                    Ok(Some((size, Cow::Owned(bytes))))
3789                })?
3790        else {
3791            return Ok(());
3792        };
3793        let content_mask = self.snapped_content_mask();
3794        let svg_bounds = Bounds {
3795            origin: bounds.center()
3796                - Point::new(
3797                    ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3798                    ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3799                ),
3800            size: tile
3801                .bounds
3802                .size
3803                .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
3804        };
3805        let final_bounds = svg_bounds
3806            .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
3807            .map_size(|size| size.ceil());
3808
3809        self.next_frame.scene.insert_primitive(MonochromeSprite {
3810            order: 0,
3811            pad: 0,
3812            bounds: final_bounds,
3813            content_mask,
3814            color: color.opacity(element_opacity),
3815            tile,
3816            transformation,
3817        });
3818
3819        Ok(())
3820    }
3821
3822    /// Paint an image into the scene for the next frame at the current z-index.
3823    /// This method will panic if the frame_index is not valid
3824    ///
3825    /// This method should only be called as part of the paint phase of element drawing.
3826    pub fn paint_image(
3827        &mut self,
3828        bounds: Bounds<Pixels>,
3829        corner_radii: Corners<Pixels>,
3830        data: Arc<RenderImage>,
3831        frame_index: usize,
3832        grayscale: bool,
3833    ) -> Result<()> {
3834        self.invalidator.debug_assert_paint();
3835
3836        let bounds = self.snap_bounds(bounds);
3837        let params = RenderImageParams {
3838            image_id: data.id,
3839            frame_index,
3840        };
3841
3842        let tile = self
3843            .sprite_atlas
3844            .get_or_insert_with(&params.into(), &mut || {
3845                Ok(Some((
3846                    data.size(frame_index),
3847                    Cow::Borrowed(
3848                        data.as_bytes(frame_index)
3849                            .expect("It's the caller's job to pass a valid frame index"),
3850                    ),
3851                )))
3852            })?
3853            .expect("Callback above only returns Some");
3854        let content_mask = self.snapped_content_mask();
3855        let corner_radii = corner_radii.scale(self.scale_factor());
3856        let opacity = self.element_opacity();
3857
3858        self.next_frame.scene.insert_primitive(PolychromeSprite {
3859            order: 0,
3860            pad: 0,
3861            grayscale,
3862            bounds,
3863            content_mask,
3864            corner_radii,
3865            tile,
3866            opacity,
3867        });
3868        Ok(())
3869    }
3870
3871    /// Paint a surface into the scene for the next frame at the current z-index.
3872    ///
3873    /// This method should only be called as part of the paint phase of element drawing.
3874    #[cfg(target_os = "macos")]
3875    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
3876        use crate::PaintSurface;
3877
3878        self.invalidator.debug_assert_paint();
3879
3880        let bounds = self.snap_bounds(bounds);
3881        let content_mask = self.snapped_content_mask();
3882        self.next_frame.scene.insert_primitive(PaintSurface {
3883            order: 0,
3884            bounds,
3885            content_mask,
3886            image_buffer,
3887        });
3888    }
3889
3890    /// Removes an image from the sprite atlas.
3891    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
3892        for frame_index in 0..data.frame_count() {
3893            let params = RenderImageParams {
3894                image_id: data.id,
3895                frame_index,
3896            };
3897
3898            self.sprite_atlas.remove(&params.clone().into());
3899        }
3900
3901        Ok(())
3902    }
3903
3904    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
3905    /// layout is being requested, along with the layout ids of any children. This method is called during
3906    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
3907    ///
3908    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3909    #[must_use]
3910    pub fn request_layout(
3911        &mut self,
3912        style: Style,
3913        children: impl IntoIterator<Item = LayoutId>,
3914        cx: &mut App,
3915    ) -> LayoutId {
3916        self.invalidator.debug_assert_prepaint();
3917
3918        cx.layout_id_buffer.clear();
3919        cx.layout_id_buffer.extend(children);
3920        let rem_size = self.rem_size();
3921        let scale_factor = self.scale_factor();
3922
3923        self.layout_engine.as_mut().unwrap().request_layout(
3924            style,
3925            rem_size,
3926            scale_factor,
3927            &cx.layout_id_buffer,
3928        )
3929    }
3930
3931    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
3932    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
3933    /// determine the element's size. One place this is used internally is when measuring text.
3934    ///
3935    /// The given closure is invoked at layout time with the known dimensions and available space and
3936    /// returns a `Size`.
3937    ///
3938    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3939    pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
3940    where
3941        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
3942            + 'static,
3943    {
3944        self.invalidator.debug_assert_prepaint();
3945
3946        let rem_size = self.rem_size();
3947        let scale_factor = self.scale_factor();
3948        self.layout_engine
3949            .as_mut()
3950            .unwrap()
3951            .request_measured_layout(style, rem_size, scale_factor, measure)
3952    }
3953
3954    /// Compute the layout for the given id within the given available space.
3955    /// This method is called for its side effect, typically by the framework prior to painting.
3956    /// After calling it, you can request the bounds of the given layout node id or any descendant.
3957    ///
3958    /// This method should only be called as part of the prepaint phase of element drawing.
3959    pub fn compute_layout(
3960        &mut self,
3961        layout_id: LayoutId,
3962        available_space: Size<AvailableSpace>,
3963        cx: &mut App,
3964    ) {
3965        self.invalidator.debug_assert_prepaint();
3966
3967        let mut layout_engine = self.layout_engine.take().unwrap();
3968        layout_engine.compute_layout(layout_id, available_space, self, cx);
3969        self.layout_engine = Some(layout_engine);
3970    }
3971
3972    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
3973    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
3974    ///
3975    /// This method should only be called as part of element drawing.
3976    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
3977        self.invalidator.debug_assert_prepaint();
3978
3979        let scale_factor = self.scale_factor();
3980        let mut bounds = self
3981            .layout_engine
3982            .as_mut()
3983            .unwrap()
3984            .layout_bounds(layout_id, scale_factor)
3985            .map(Into::into);
3986        let snapped_offset = self.pixel_snap_point(self.element_offset());
3987        bounds.origin += snapped_offset;
3988        bounds
3989    }
3990
3991    /// This method should be called during `prepaint`. You can use
3992    /// the returned [Hitbox] during `paint` or in an event handler
3993    /// to determine whether the inserted hitbox was the topmost.
3994    ///
3995    /// This method should only be called as part of the prepaint phase of element drawing.
3996    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
3997        self.invalidator.debug_assert_prepaint();
3998
3999        let content_mask = self.content_mask();
4000        let mut id = self.next_hitbox_id;
4001        self.next_hitbox_id = self.next_hitbox_id.next();
4002        let hitbox = Hitbox {
4003            id,
4004            bounds,
4005            content_mask,
4006            behavior,
4007        };
4008        self.next_frame.hitboxes.push(hitbox.clone());
4009        hitbox
4010    }
4011
4012    /// Set a hitbox which will act as a control area of the platform window.
4013    ///
4014    /// This method should only be called as part of the paint phase of element drawing.
4015    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
4016        self.invalidator.debug_assert_paint();
4017        self.next_frame.window_control_hitboxes.push((area, hitbox));
4018    }
4019
4020    /// Sets the key context for the current element. This context will be used to translate
4021    /// keybindings into actions.
4022    ///
4023    /// This method should only be called as part of the paint phase of element drawing.
4024    pub fn set_key_context(&mut self, context: KeyContext) {
4025        self.invalidator.debug_assert_paint();
4026        self.next_frame.dispatch_tree.set_key_context(context);
4027    }
4028
4029    /// Sets the focus handle for the current element. This handle will be used to manage focus state
4030    /// and keyboard event dispatch for the element.
4031    ///
4032    /// This method should only be called as part of the prepaint phase of element drawing.
4033    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
4034        self.invalidator.debug_assert_prepaint();
4035        if focus_handle.is_focused(self) {
4036            self.next_frame.focus = Some(focus_handle.id);
4037        }
4038        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
4039    }
4040
4041    /// Sets the view id for the current element, which will be used to manage view caching.
4042    ///
4043    /// This method should only be called as part of element prepaint. We plan on removing this
4044    /// method eventually when we solve some issues that require us to construct editor elements
4045    /// directly instead of always using editors via views.
4046    pub fn set_view_id(&mut self, view_id: EntityId) {
4047        self.invalidator.debug_assert_prepaint();
4048        self.next_frame.dispatch_tree.set_view_id(view_id);
4049    }
4050
4051    /// Get the entity ID for the currently rendering view
4052    pub fn current_view(&self) -> EntityId {
4053        self.invalidator.debug_assert_paint_or_prepaint();
4054        self.rendered_entity_stack.last().copied().unwrap()
4055    }
4056
4057    #[inline]
4058    pub(crate) fn with_rendered_view<R>(
4059        &mut self,
4060        id: EntityId,
4061        f: impl FnOnce(&mut Self) -> R,
4062    ) -> R {
4063        self.rendered_entity_stack.push(id);
4064        let result = f(self);
4065        self.rendered_entity_stack.pop();
4066        result
4067    }
4068
4069    /// Executes the provided function with the specified image cache.
4070    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
4071    where
4072        F: FnOnce(&mut Self) -> R,
4073    {
4074        if let Some(image_cache) = image_cache {
4075            self.image_cache_stack.push(image_cache);
4076            let result = f(self);
4077            self.image_cache_stack.pop();
4078            result
4079        } else {
4080            f(self)
4081        }
4082    }
4083
4084    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
4085    /// platform to receive textual input with proper integration with concerns such
4086    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
4087    /// rendered.
4088    ///
4089    /// This method should only be called as part of the paint phase of element drawing.
4090    ///
4091    /// [element_input_handler]: crate::ElementInputHandler
4092    pub fn handle_input(
4093        &mut self,
4094        focus_handle: &FocusHandle,
4095        input_handler: impl InputHandler,
4096        cx: &App,
4097    ) {
4098        self.invalidator.debug_assert_paint();
4099
4100        if focus_handle.is_focused(self) {
4101            let cx = self.to_async(cx);
4102            self.next_frame
4103                .input_handlers
4104                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
4105        }
4106    }
4107
4108    /// Register a mouse event listener on the window for the next frame. The type of event
4109    /// is determined by the first parameter of the given listener. When the next frame is rendered
4110    /// the listener will be cleared.
4111    ///
4112    /// This method should only be called as part of the paint phase of element drawing.
4113    pub fn on_mouse_event<Event: MouseEvent>(
4114        &mut self,
4115        mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4116    ) {
4117        self.invalidator.debug_assert_paint();
4118
4119        self.next_frame.mouse_listeners.push(Some(Box::new(
4120            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
4121                if let Some(event) = event.downcast_ref() {
4122                    listener(event, phase, window, cx)
4123                }
4124            },
4125        )));
4126    }
4127
4128    /// Register a key event listener on this node for the next frame. The type of event
4129    /// is determined by the first parameter of the given listener. When the next frame is rendered
4130    /// the listener will be cleared.
4131    ///
4132    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
4133    /// a specific need to register a listener yourself.
4134    ///
4135    /// This method should only be called as part of the paint phase of element drawing.
4136    pub fn on_key_event<Event: KeyEvent>(
4137        &mut self,
4138        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4139    ) {
4140        self.invalidator.debug_assert_paint();
4141
4142        self.next_frame.dispatch_tree.on_key_event(Rc::new(
4143            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
4144                if let Some(event) = event.downcast_ref::<Event>() {
4145                    listener(event, phase, window, cx)
4146                }
4147            },
4148        ));
4149    }
4150
4151    /// Register a modifiers changed event listener on the window for the next frame.
4152    ///
4153    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
4154    /// a specific need to register a global listener.
4155    ///
4156    /// This method should only be called as part of the paint phase of element drawing.
4157    pub fn on_modifiers_changed(
4158        &mut self,
4159        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
4160    ) {
4161        self.invalidator.debug_assert_paint();
4162
4163        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
4164            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
4165                listener(event, window, cx)
4166            },
4167        ));
4168    }
4169
4170    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4171    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
4172    /// Returns a subscription and persists until the subscription is dropped.
4173    pub fn on_focus_in(
4174        &mut self,
4175        handle: &FocusHandle,
4176        cx: &mut App,
4177        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
4178    ) -> Subscription {
4179        let focus_id = handle.id;
4180        let (subscription, activate) =
4181            self.new_focus_listener(Box::new(move |event, window, cx| {
4182                if event.is_focus_in(focus_id) {
4183                    listener(window, cx);
4184                }
4185                true
4186            }));
4187        cx.defer(move |_| activate());
4188        subscription
4189    }
4190
4191    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4192    /// Returns a subscription and persists until the subscription is dropped.
4193    pub fn on_focus_out(
4194        &mut self,
4195        handle: &FocusHandle,
4196        cx: &mut App,
4197        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
4198    ) -> Subscription {
4199        let focus_id = handle.id;
4200        let (subscription, activate) =
4201            self.new_focus_listener(Box::new(move |event, window, cx| {
4202                if let Some(blurred_id) = event.previous_focus_path.last().copied()
4203                    && event.is_focus_out(focus_id)
4204                {
4205                    let event = FocusOutEvent {
4206                        blurred: WeakFocusHandle {
4207                            id: blurred_id,
4208                            handles: Arc::downgrade(&cx.focus_handles),
4209                        },
4210                    };
4211                    listener(event, window, cx)
4212                }
4213                true
4214            }));
4215        cx.defer(move |_| activate());
4216        subscription
4217    }
4218
4219    fn reset_cursor_style(&self, cx: &mut App) {
4220        // Set the cursor only if we're the active window.
4221        if self.is_window_hovered() {
4222            let style = self
4223                .rendered_frame
4224                .cursor_style(self)
4225                .unwrap_or(CursorStyle::Arrow);
4226            cx.platform.set_cursor_style(style);
4227        }
4228    }
4229
4230    /// Dispatch a given keystroke as though the user had typed it.
4231    /// You can create a keystroke with Keystroke::parse("").
4232    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
4233        let keystroke = keystroke.with_simulated_ime();
4234        let result = self.dispatch_event(
4235            PlatformInput::KeyDown(KeyDownEvent {
4236                keystroke: keystroke.clone(),
4237                is_held: false,
4238                prefer_character_input: false,
4239            }),
4240            cx,
4241        );
4242        if !result.propagate {
4243            return true;
4244        }
4245
4246        if let Some(input) = keystroke.key_char
4247            && let Some(mut input_handler) = self.platform_window.take_input_handler()
4248        {
4249            input_handler.dispatch_input(&input, self, cx);
4250            self.platform_window.set_input_handler(input_handler);
4251            return true;
4252        }
4253
4254        false
4255    }
4256
4257    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
4258    /// binding for the action (last binding added to the keymap).
4259    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
4260        self.highest_precedence_binding_for_action(action)
4261            .map(|binding| {
4262                binding
4263                    .keystrokes()
4264                    .iter()
4265                    .map(ToString::to_string)
4266                    .collect::<Vec<_>>()
4267                    .join(" ")
4268            })
4269            .unwrap_or_else(|| action.name().to_string())
4270    }
4271
4272    /// Dispatch a mouse or keyboard event on the window.
4273    #[profiling::function]
4274    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
4275        #[cfg(feature = "input-latency-histogram")]
4276        let dispatch_time = Instant::now();
4277        let update_count_before = self.invalidator.update_count();
4278        // Track input modality for focus-visible styling and hover suppression.
4279        // Hover is suppressed during keyboard modality so that keyboard navigation
4280        // doesn't show hover highlights on the item under the mouse cursor.
4281        let old_modality = self.last_input_modality;
4282        self.last_input_modality = match &event {
4283            PlatformInput::KeyDown(_) => InputModality::Keyboard,
4284            PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
4285            _ => self.last_input_modality,
4286        };
4287        if self.last_input_modality != old_modality {
4288            self.refresh();
4289        }
4290
4291        // Handlers may set this to false by calling `stop_propagation`.
4292        cx.propagate_event = true;
4293        // Handlers may set this to true by calling `prevent_default`.
4294        self.default_prevented = false;
4295
4296        let event = match event {
4297            // Track the mouse position with our own state, since accessing the platform
4298            // API for the mouse position can only occur on the main thread.
4299            PlatformInput::MouseMove(mouse_move) => {
4300                self.mouse_position = mouse_move.position;
4301                self.modifiers = mouse_move.modifiers;
4302                PlatformInput::MouseMove(mouse_move)
4303            }
4304            PlatformInput::MouseDown(mouse_down) => {
4305                self.mouse_position = mouse_down.position;
4306                self.modifiers = mouse_down.modifiers;
4307                PlatformInput::MouseDown(mouse_down)
4308            }
4309            PlatformInput::MouseUp(mouse_up) => {
4310                self.mouse_position = mouse_up.position;
4311                self.modifiers = mouse_up.modifiers;
4312                PlatformInput::MouseUp(mouse_up)
4313            }
4314            PlatformInput::MousePressure(mouse_pressure) => {
4315                PlatformInput::MousePressure(mouse_pressure)
4316            }
4317            PlatformInput::MouseExited(mouse_exited) => {
4318                self.modifiers = mouse_exited.modifiers;
4319                PlatformInput::MouseExited(mouse_exited)
4320            }
4321            PlatformInput::ModifiersChanged(modifiers_changed) => {
4322                self.modifiers = modifiers_changed.modifiers;
4323                self.capslock = modifiers_changed.capslock;
4324                PlatformInput::ModifiersChanged(modifiers_changed)
4325            }
4326            PlatformInput::ScrollWheel(scroll_wheel) => {
4327                self.mouse_position = scroll_wheel.position;
4328                self.modifiers = scroll_wheel.modifiers;
4329                PlatformInput::ScrollWheel(scroll_wheel)
4330            }
4331            PlatformInput::Pinch(pinch) => {
4332                self.mouse_position = pinch.position;
4333                self.modifiers = pinch.modifiers;
4334                PlatformInput::Pinch(pinch)
4335            }
4336            // Translate dragging and dropping of external files from the operating system
4337            // to internal drag and drop events.
4338            PlatformInput::FileDrop(file_drop) => match file_drop {
4339                FileDropEvent::Entered { position, paths } => {
4340                    self.mouse_position = position;
4341                    if cx.active_drag.is_none() {
4342                        cx.active_drag = Some(AnyDrag {
4343                            value: Arc::new(paths.clone()),
4344                            view: cx.new(|_| paths).into(),
4345                            cursor_offset: position,
4346                            cursor_style: None,
4347                        });
4348                    }
4349                    PlatformInput::MouseMove(MouseMoveEvent {
4350                        position,
4351                        pressed_button: Some(MouseButton::Left),
4352                        modifiers: Modifiers::default(),
4353                    })
4354                }
4355                FileDropEvent::Pending { position } => {
4356                    self.mouse_position = position;
4357                    PlatformInput::MouseMove(MouseMoveEvent {
4358                        position,
4359                        pressed_button: Some(MouseButton::Left),
4360                        modifiers: Modifiers::default(),
4361                    })
4362                }
4363                FileDropEvent::Submit { position } => {
4364                    cx.activate(true);
4365                    self.mouse_position = position;
4366                    PlatformInput::MouseUp(MouseUpEvent {
4367                        button: MouseButton::Left,
4368                        position,
4369                        modifiers: Modifiers::default(),
4370                        click_count: 1,
4371                    })
4372                }
4373                FileDropEvent::Exited => {
4374                    cx.active_drag.take();
4375                    PlatformInput::FileDrop(FileDropEvent::Exited)
4376                }
4377            },
4378            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
4379        };
4380
4381        if let Some(any_mouse_event) = event.mouse_event() {
4382            self.dispatch_mouse_event(any_mouse_event, cx);
4383        } else if let Some(any_key_event) = event.keyboard_event() {
4384            self.dispatch_key_event(any_key_event, cx);
4385        }
4386
4387        if self.invalidator.update_count() > update_count_before {
4388            self.input_rate_tracker.borrow_mut().record_input();
4389            #[cfg(feature = "input-latency-histogram")]
4390            if self.invalidator.not_drawing() {
4391                self.input_latency_tracker.record_input(dispatch_time);
4392            } else {
4393                self.input_latency_tracker.record_mid_draw_input();
4394            }
4395        }
4396
4397        DispatchEventResult {
4398            propagate: cx.propagate_event,
4399            default_prevented: self.default_prevented,
4400        }
4401    }
4402
4403    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4404        let hit_test = self.rendered_frame.hit_test(self.mouse_position());
4405        if hit_test != self.mouse_hit_test {
4406            self.mouse_hit_test = hit_test;
4407            self.reset_cursor_style(cx);
4408        }
4409
4410        #[cfg(any(feature = "inspector", debug_assertions))]
4411        if self.is_inspector_picking(cx) {
4412            self.handle_inspector_mouse_event(event, cx);
4413            // When inspector is picking, all other mouse handling is skipped.
4414            return;
4415        }
4416
4417        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
4418
4419        // Capture phase, events bubble from back to front. Handlers for this phase are used for
4420        // special purposes, such as detecting events outside of a given Bounds.
4421        for listener in &mut mouse_listeners {
4422            let listener = listener.as_mut().unwrap();
4423            listener(event, DispatchPhase::Capture, self, cx);
4424            if !cx.propagate_event {
4425                break;
4426            }
4427        }
4428
4429        // Bubble phase, where most normal handlers do their work.
4430        if cx.propagate_event {
4431            for listener in mouse_listeners.iter_mut().rev() {
4432                let listener = listener.as_mut().unwrap();
4433                listener(event, DispatchPhase::Bubble, self, cx);
4434                if !cx.propagate_event {
4435                    break;
4436                }
4437            }
4438        }
4439
4440        self.rendered_frame.mouse_listeners = mouse_listeners;
4441
4442        if cx.has_active_drag() {
4443            if event.is::<MouseMoveEvent>() {
4444                // If this was a mouse move event, redraw the window so that the
4445                // active drag can follow the mouse cursor.
4446                self.refresh();
4447            } else if event.is::<MouseUpEvent>() {
4448                // If this was a mouse up event, cancel the active drag and redraw
4449                // the window.
4450                cx.active_drag = None;
4451                self.refresh();
4452            }
4453        }
4454
4455        // Auto-release pointer capture on mouse up
4456        if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
4457            self.captured_hitbox = None;
4458        }
4459    }
4460
4461    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
4462        if self.invalidator.is_dirty() {
4463            self.draw(cx).clear();
4464        }
4465
4466        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4467        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4468
4469        let mut keystroke: Option<Keystroke> = None;
4470
4471        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
4472            if event.modifiers.number_of_modifiers() == 0
4473                && self.pending_modifier.modifiers.number_of_modifiers() == 1
4474                && !self.pending_modifier.saw_keystroke
4475            {
4476                let key = match self.pending_modifier.modifiers {
4477                    modifiers if modifiers.shift => Some("shift"),
4478                    modifiers if modifiers.control => Some("control"),
4479                    modifiers if modifiers.alt => Some("alt"),
4480                    modifiers if modifiers.platform => Some("platform"),
4481                    modifiers if modifiers.function => Some("function"),
4482                    _ => None,
4483                };
4484                if let Some(key) = key {
4485                    keystroke = Some(Keystroke {
4486                        key: key.to_string(),
4487                        key_char: None,
4488                        modifiers: Modifiers::default(),
4489                    });
4490                }
4491            }
4492
4493            if self.pending_modifier.modifiers.number_of_modifiers() == 0
4494                && event.modifiers.number_of_modifiers() == 1
4495            {
4496                self.pending_modifier.saw_keystroke = false
4497            }
4498            self.pending_modifier.modifiers = event.modifiers
4499        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
4500            self.pending_modifier.saw_keystroke = true;
4501            keystroke = Some(key_down_event.keystroke.clone());
4502        }
4503
4504        let Some(keystroke) = keystroke else {
4505            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4506            return;
4507        };
4508
4509        cx.propagate_event = true;
4510        self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
4511        if !cx.propagate_event {
4512            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4513            return;
4514        }
4515
4516        let mut currently_pending = self.pending_input.take().unwrap_or_default();
4517        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
4518            currently_pending = PendingInput::default();
4519        }
4520
4521        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
4522            currently_pending.keystrokes,
4523            keystroke,
4524            &dispatch_path,
4525        );
4526
4527        if !match_result.to_replay.is_empty() {
4528            self.replay_pending_input(match_result.to_replay, cx);
4529            cx.propagate_event = true;
4530        }
4531
4532        if !match_result.pending.is_empty() {
4533            currently_pending.timer.take();
4534            currently_pending.keystrokes = match_result.pending;
4535            currently_pending.focus = self.focus;
4536
4537            let text_input_requires_timeout = event
4538                .downcast_ref::<KeyDownEvent>()
4539                .filter(|key_down| key_down.keystroke.key_char.is_some())
4540                .and_then(|_| self.platform_window.take_input_handler())
4541                .map_or(false, |mut input_handler| {
4542                    let accepts = input_handler.accepts_text_input(self, cx);
4543                    self.platform_window.set_input_handler(input_handler);
4544                    accepts
4545                });
4546
4547            currently_pending.needs_timeout |=
4548                match_result.pending_has_binding || text_input_requires_timeout;
4549
4550            if currently_pending.needs_timeout {
4551                currently_pending.timer = Some(self.spawn(cx, async move |cx| {
4552                    cx.background_executor.timer(Duration::from_secs(1)).await;
4553                    cx.update(move |window, cx| {
4554                        let Some(currently_pending) = window
4555                            .pending_input
4556                            .take()
4557                            .filter(|pending| pending.focus == window.focus)
4558                        else {
4559                            return;
4560                        };
4561
4562                        let node_id = window.focus_node_id_in_rendered_frame(window.focus);
4563                        let dispatch_path =
4564                            window.rendered_frame.dispatch_tree.dispatch_path(node_id);
4565
4566                        let to_replay = window
4567                            .rendered_frame
4568                            .dispatch_tree
4569                            .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
4570
4571                        window.pending_input_changed(cx);
4572                        window.replay_pending_input(to_replay, cx)
4573                    })
4574                    .log_err();
4575                }));
4576            } else {
4577                currently_pending.timer = None;
4578            }
4579            self.pending_input = Some(currently_pending);
4580            self.pending_input_changed(cx);
4581            cx.propagate_event = false;
4582            return;
4583        }
4584
4585        let skip_bindings = event
4586            .downcast_ref::<KeyDownEvent>()
4587            .filter(|key_down_event| key_down_event.prefer_character_input)
4588            .map(|_| {
4589                self.platform_window
4590                    .take_input_handler()
4591                    .map_or(false, |mut input_handler| {
4592                        let accepts = input_handler.accepts_text_input(self, cx);
4593                        self.platform_window.set_input_handler(input_handler);
4594                        // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
4595                        // we prefer the text input over bindings.
4596                        accepts
4597                    })
4598            })
4599            .unwrap_or(false);
4600
4601        if !skip_bindings {
4602            for binding in match_result.bindings {
4603                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4604                if !cx.propagate_event {
4605                    self.dispatch_keystroke_observers(
4606                        event,
4607                        Some(binding.action),
4608                        match_result.context_stack,
4609                        cx,
4610                    );
4611                    self.pending_input_changed(cx);
4612                    return;
4613                }
4614            }
4615        }
4616
4617        self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
4618        self.pending_input_changed(cx);
4619    }
4620
4621    fn finish_dispatch_key_event(
4622        &mut self,
4623        event: &dyn Any,
4624        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
4625        context_stack: Vec<KeyContext>,
4626        cx: &mut App,
4627    ) {
4628        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
4629        if !cx.propagate_event {
4630            return;
4631        }
4632
4633        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
4634        if !cx.propagate_event {
4635            return;
4636        }
4637
4638        self.dispatch_keystroke_observers(event, None, context_stack, cx);
4639    }
4640
4641    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
4642        self.pending_input_observers
4643            .clone()
4644            .retain(&(), |callback| callback(self, cx));
4645    }
4646
4647    fn dispatch_key_down_up_event(
4648        &mut self,
4649        event: &dyn Any,
4650        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4651        cx: &mut App,
4652    ) {
4653        // Capture phase
4654        for node_id in dispatch_path {
4655            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4656
4657            for key_listener in node.key_listeners.clone() {
4658                key_listener(event, DispatchPhase::Capture, self, cx);
4659                if !cx.propagate_event {
4660                    return;
4661                }
4662            }
4663        }
4664
4665        // Bubble phase
4666        for node_id in dispatch_path.iter().rev() {
4667            // Handle low level key events
4668            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4669            for key_listener in node.key_listeners.clone() {
4670                key_listener(event, DispatchPhase::Bubble, self, cx);
4671                if !cx.propagate_event {
4672                    return;
4673                }
4674            }
4675        }
4676    }
4677
4678    fn dispatch_modifiers_changed_event(
4679        &mut self,
4680        event: &dyn Any,
4681        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4682        cx: &mut App,
4683    ) {
4684        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
4685            return;
4686        };
4687        for node_id in dispatch_path.iter().rev() {
4688            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4689            for listener in node.modifiers_changed_listeners.clone() {
4690                listener(event, self, cx);
4691                if !cx.propagate_event {
4692                    return;
4693                }
4694            }
4695        }
4696    }
4697
4698    /// Determine whether a potential multi-stroke key binding is in progress on this window.
4699    pub fn has_pending_keystrokes(&self) -> bool {
4700        self.pending_input.is_some()
4701    }
4702
4703    pub(crate) fn clear_pending_keystrokes(&mut self) {
4704        self.pending_input.take();
4705    }
4706
4707    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
4708    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
4709        self.pending_input
4710            .as_ref()
4711            .map(|pending_input| pending_input.keystrokes.as_slice())
4712    }
4713
4714    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
4715        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4716        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4717
4718        'replay: for replay in replays {
4719            let event = KeyDownEvent {
4720                keystroke: replay.keystroke.clone(),
4721                is_held: false,
4722                prefer_character_input: true,
4723            };
4724
4725            cx.propagate_event = true;
4726            for binding in replay.bindings {
4727                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4728                if !cx.propagate_event {
4729                    self.dispatch_keystroke_observers(
4730                        &event,
4731                        Some(binding.action),
4732                        Vec::default(),
4733                        cx,
4734                    );
4735                    continue 'replay;
4736                }
4737            }
4738
4739            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
4740            if !cx.propagate_event {
4741                continue 'replay;
4742            }
4743            if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
4744                && let Some(mut input_handler) = self.platform_window.take_input_handler()
4745            {
4746                input_handler.dispatch_input(&input, self, cx);
4747                self.platform_window.set_input_handler(input_handler)
4748            }
4749        }
4750    }
4751
4752    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
4753        focus_id
4754            .and_then(|focus_id| {
4755                self.rendered_frame
4756                    .dispatch_tree
4757                    .focusable_node_id(focus_id)
4758            })
4759            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
4760    }
4761
4762    fn dispatch_action_on_node(
4763        &mut self,
4764        node_id: DispatchNodeId,
4765        action: &dyn Action,
4766        cx: &mut App,
4767    ) {
4768        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4769
4770        // Capture phase for global actions.
4771        cx.propagate_event = true;
4772        if let Some(mut global_listeners) = cx
4773            .global_action_listeners
4774            .remove(&action.as_any().type_id())
4775        {
4776            for listener in &global_listeners {
4777                listener(action.as_any(), DispatchPhase::Capture, cx);
4778                if !cx.propagate_event {
4779                    break;
4780                }
4781            }
4782
4783            global_listeners.extend(
4784                cx.global_action_listeners
4785                    .remove(&action.as_any().type_id())
4786                    .unwrap_or_default(),
4787            );
4788
4789            cx.global_action_listeners
4790                .insert(action.as_any().type_id(), global_listeners);
4791        }
4792
4793        if !cx.propagate_event {
4794            return;
4795        }
4796
4797        // Capture phase for window actions.
4798        for node_id in &dispatch_path {
4799            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4800            for DispatchActionListener {
4801                action_type,
4802                listener,
4803            } in node.action_listeners.clone()
4804            {
4805                let any_action = action.as_any();
4806                if action_type == any_action.type_id() {
4807                    listener(any_action, DispatchPhase::Capture, self, cx);
4808
4809                    if !cx.propagate_event {
4810                        return;
4811                    }
4812                }
4813            }
4814        }
4815
4816        // Bubble phase for window actions.
4817        for node_id in dispatch_path.iter().rev() {
4818            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4819            for DispatchActionListener {
4820                action_type,
4821                listener,
4822            } in node.action_listeners.clone()
4823            {
4824                let any_action = action.as_any();
4825                if action_type == any_action.type_id() {
4826                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4827                    listener(any_action, DispatchPhase::Bubble, self, cx);
4828
4829                    if !cx.propagate_event {
4830                        return;
4831                    }
4832                }
4833            }
4834        }
4835
4836        // Bubble phase for global actions.
4837        if let Some(mut global_listeners) = cx
4838            .global_action_listeners
4839            .remove(&action.as_any().type_id())
4840        {
4841            for listener in global_listeners.iter().rev() {
4842                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4843
4844                listener(action.as_any(), DispatchPhase::Bubble, cx);
4845                if !cx.propagate_event {
4846                    break;
4847                }
4848            }
4849
4850            global_listeners.extend(
4851                cx.global_action_listeners
4852                    .remove(&action.as_any().type_id())
4853                    .unwrap_or_default(),
4854            );
4855
4856            cx.global_action_listeners
4857                .insert(action.as_any().type_id(), global_listeners);
4858        }
4859    }
4860
4861    /// Register the given handler to be invoked whenever the global of the given type
4862    /// is updated.
4863    pub fn observe_global<G: Global>(
4864        &mut self,
4865        cx: &mut App,
4866        f: impl Fn(&mut Window, &mut App) + 'static,
4867    ) -> Subscription {
4868        let window_handle = self.handle;
4869        let (subscription, activate) = cx.global_observers.insert(
4870            TypeId::of::<G>(),
4871            Box::new(move |cx| {
4872                window_handle
4873                    .update(cx, |_, window, cx| f(window, cx))
4874                    .is_ok()
4875            }),
4876        );
4877        cx.defer(move |_| activate());
4878        subscription
4879    }
4880
4881    /// Focus the current window and bring it to the foreground at the platform level.
4882    pub fn activate_window(&self) {
4883        self.platform_window.activate();
4884    }
4885
4886    /// Minimize the current window at the platform level.
4887    pub fn minimize_window(&self) {
4888        self.platform_window.minimize();
4889    }
4890
4891    /// Toggle full screen status on the current window at the platform level.
4892    pub fn toggle_fullscreen(&self) {
4893        self.platform_window.toggle_fullscreen();
4894    }
4895
4896    /// Updates the IME panel position suggestions for languages like japanese, chinese.
4897    pub fn invalidate_character_coordinates(&self) {
4898        self.on_next_frame(|window, cx| {
4899            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
4900                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
4901                    window.platform_window.update_ime_position(bounds);
4902                }
4903                window.platform_window.set_input_handler(input_handler);
4904            }
4905        });
4906    }
4907
4908    /// Present a platform dialog.
4909    /// The provided message will be presented, along with buttons for each answer.
4910    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
4911    pub fn prompt<T>(
4912        &mut self,
4913        level: PromptLevel,
4914        message: &str,
4915        detail: Option<&str>,
4916        answers: &[T],
4917        cx: &mut App,
4918    ) -> oneshot::Receiver<usize>
4919    where
4920        T: Clone + Into<PromptButton>,
4921    {
4922        let prompt_builder = cx.prompt_builder.take();
4923        let Some(prompt_builder) = prompt_builder else {
4924            unreachable!("Re-entrant window prompting is not supported by GPUI");
4925        };
4926
4927        let answers = answers
4928            .iter()
4929            .map(|answer| answer.clone().into())
4930            .collect::<Vec<_>>();
4931
4932        let receiver = match &prompt_builder {
4933            PromptBuilder::Default => self
4934                .platform_window
4935                .prompt(level, message, detail, &answers)
4936                .unwrap_or_else(|| {
4937                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4938                }),
4939            PromptBuilder::Custom(_) => {
4940                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4941            }
4942        };
4943
4944        cx.prompt_builder = Some(prompt_builder);
4945
4946        receiver
4947    }
4948
4949    fn build_custom_prompt(
4950        &mut self,
4951        prompt_builder: &PromptBuilder,
4952        level: PromptLevel,
4953        message: &str,
4954        detail: Option<&str>,
4955        answers: &[PromptButton],
4956        cx: &mut App,
4957    ) -> oneshot::Receiver<usize> {
4958        let (sender, receiver) = oneshot::channel();
4959        let handle = PromptHandle::new(sender);
4960        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
4961        self.prompt = Some(handle);
4962        receiver
4963    }
4964
4965    /// Returns the current context stack.
4966    pub fn context_stack(&self) -> Vec<KeyContext> {
4967        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4968        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4969        dispatch_tree
4970            .dispatch_path(node_id)
4971            .iter()
4972            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
4973            .collect()
4974    }
4975
4976    /// Returns all available actions for the focused element.
4977    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
4978        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4979        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
4980        for action_type in cx.global_action_listeners.keys() {
4981            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
4982                let action = cx.actions.build_action_type(action_type).ok();
4983                if let Some(action) = action {
4984                    actions.insert(ix, action);
4985                }
4986            }
4987        }
4988        actions
4989    }
4990
4991    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
4992    /// returned in the order they were added. For display, the last binding should take precedence.
4993    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
4994        self.rendered_frame
4995            .dispatch_tree
4996            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
4997    }
4998
4999    /// Returns the highest precedence key binding that invokes an action on the currently focused
5000    /// element. This is more efficient than getting the last result of `bindings_for_action`.
5001    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
5002        self.rendered_frame
5003            .dispatch_tree
5004            .highest_precedence_binding_for_action(
5005                action,
5006                &self.rendered_frame.dispatch_tree.context_stack,
5007            )
5008    }
5009
5010    /// Returns the key bindings for an action in a context.
5011    pub fn bindings_for_action_in_context(
5012        &self,
5013        action: &dyn Action,
5014        context: KeyContext,
5015    ) -> Vec<KeyBinding> {
5016        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5017        dispatch_tree.bindings_for_action(action, &[context])
5018    }
5019
5020    /// Returns the highest precedence key binding for an action in a context. This is more
5021    /// efficient than getting the last result of `bindings_for_action_in_context`.
5022    pub fn highest_precedence_binding_for_action_in_context(
5023        &self,
5024        action: &dyn Action,
5025        context: KeyContext,
5026    ) -> Option<KeyBinding> {
5027        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5028        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
5029    }
5030
5031    /// Returns any bindings that would invoke an action on the given focus handle if it were
5032    /// focused. Bindings are returned in the order they were added. For display, the last binding
5033    /// should take precedence.
5034    pub fn bindings_for_action_in(
5035        &self,
5036        action: &dyn Action,
5037        focus_handle: &FocusHandle,
5038    ) -> Vec<KeyBinding> {
5039        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5040        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
5041            return vec![];
5042        };
5043        dispatch_tree.bindings_for_action(action, &context_stack)
5044    }
5045
5046    /// Returns the highest precedence key binding that would invoke an action on the given focus
5047    /// handle if it were focused. This is more efficient than getting the last result of
5048    /// `bindings_for_action_in`.
5049    pub fn highest_precedence_binding_for_action_in(
5050        &self,
5051        action: &dyn Action,
5052        focus_handle: &FocusHandle,
5053    ) -> Option<KeyBinding> {
5054        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5055        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
5056        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
5057    }
5058
5059    /// Find the bindings that can follow the current input sequence for the current context stack.
5060    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
5061        self.rendered_frame
5062            .dispatch_tree
5063            .possible_next_bindings_for_input(input, &self.context_stack())
5064    }
5065
5066    fn context_stack_for_focus_handle(
5067        &self,
5068        focus_handle: &FocusHandle,
5069    ) -> Option<Vec<KeyContext>> {
5070        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5071        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
5072        let context_stack: Vec<_> = dispatch_tree
5073            .dispatch_path(node_id)
5074            .into_iter()
5075            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
5076            .collect();
5077        Some(context_stack)
5078    }
5079
5080    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
5081    pub fn listener_for<T: 'static, E>(
5082        &self,
5083        view: &Entity<T>,
5084        f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
5085    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
5086        let view = view.downgrade();
5087        move |e: &E, window: &mut Window, cx: &mut App| {
5088            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
5089        }
5090    }
5091
5092    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
5093    pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
5094        &self,
5095        entity: &Entity<E>,
5096        f: Callback,
5097    ) -> impl Fn(&mut Window, &mut App) + 'static {
5098        let entity = entity.downgrade();
5099        move |window: &mut Window, cx: &mut App| {
5100            entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
5101        }
5102    }
5103
5104    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
5105    /// If the callback returns false, the window won't be closed.
5106    pub fn on_window_should_close(
5107        &self,
5108        cx: &App,
5109        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
5110    ) {
5111        let mut cx = self.to_async(cx);
5112        self.platform_window.on_should_close(Box::new(move || {
5113            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
5114        }))
5115    }
5116
5117    /// Register an action listener on this node for the next frame. The type of action
5118    /// is determined by the first parameter of the given listener. When the next frame is rendered
5119    /// the listener will be cleared.
5120    ///
5121    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
5122    /// a specific need to register a listener yourself.
5123    ///
5124    /// This method should only be called as part of the paint phase of element drawing.
5125    pub fn on_action(
5126        &mut self,
5127        action_type: TypeId,
5128        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5129    ) {
5130        self.invalidator.debug_assert_paint();
5131
5132        self.next_frame
5133            .dispatch_tree
5134            .on_action(action_type, Rc::new(listener));
5135    }
5136
5137    /// Register a capturing action listener on this node for the next frame if the condition is true.
5138    /// The type of action is determined by the first parameter of the given listener. When the next
5139    /// frame is rendered the listener will be cleared.
5140    ///
5141    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
5142    /// a specific need to register a listener yourself.
5143    ///
5144    /// This method should only be called as part of the paint phase of element drawing.
5145    pub fn on_action_when(
5146        &mut self,
5147        condition: bool,
5148        action_type: TypeId,
5149        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5150    ) {
5151        self.invalidator.debug_assert_paint();
5152
5153        if condition {
5154            self.next_frame
5155                .dispatch_tree
5156                .on_action(action_type, Rc::new(listener));
5157        }
5158    }
5159
5160    /// Read information about the GPU backing this window.
5161    /// Currently returns None on Mac and Windows.
5162    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
5163        self.platform_window.gpu_specs()
5164    }
5165
5166    /// Perform titlebar double-click action.
5167    /// This is macOS specific.
5168    pub fn titlebar_double_click(&self) {
5169        self.platform_window.titlebar_double_click();
5170    }
5171
5172    /// Gets the window's title at the platform level.
5173    /// This is macOS specific.
5174    pub fn window_title(&self) -> String {
5175        self.platform_window.get_title()
5176    }
5177
5178    /// Returns a list of all tabbed windows and their titles.
5179    /// This is macOS specific.
5180    pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
5181        self.platform_window.tabbed_windows()
5182    }
5183
5184    /// Returns the tab bar visibility.
5185    /// This is macOS specific.
5186    pub fn tab_bar_visible(&self) -> bool {
5187        self.platform_window.tab_bar_visible()
5188    }
5189
5190    /// Merges all open windows into a single tabbed window.
5191    /// This is macOS specific.
5192    pub fn merge_all_windows(&self) {
5193        self.platform_window.merge_all_windows()
5194    }
5195
5196    /// Moves the tab to a new containing window.
5197    /// This is macOS specific.
5198    pub fn move_tab_to_new_window(&self) {
5199        self.platform_window.move_tab_to_new_window()
5200    }
5201
5202    /// Shows or hides the window tab overview.
5203    /// This is macOS specific.
5204    pub fn toggle_window_tab_overview(&self) {
5205        self.platform_window.toggle_window_tab_overview()
5206    }
5207
5208    /// Sets the tabbing identifier for the window.
5209    /// This is macOS specific.
5210    pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
5211        self.platform_window
5212            .set_tabbing_identifier(tabbing_identifier)
5213    }
5214
5215    /// Request the OS to play an alert sound. On some platforms this is associated
5216    /// with the window, for others it's just a simple global function call.
5217    pub fn play_system_bell(&self) {
5218        self.platform_window.play_system_bell()
5219    }
5220
5221    /// Toggles the inspector mode on this window.
5222    #[cfg(any(feature = "inspector", debug_assertions))]
5223    pub fn toggle_inspector(&mut self, cx: &mut App) {
5224        self.inspector = match self.inspector {
5225            None => Some(cx.new(|_| Inspector::new())),
5226            Some(_) => None,
5227        };
5228        self.refresh();
5229    }
5230
5231    /// Returns true if the window is in inspector mode.
5232    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
5233        #[cfg(any(feature = "inspector", debug_assertions))]
5234        {
5235            if let Some(inspector) = &self.inspector {
5236                return inspector.read(_cx).is_picking();
5237            }
5238        }
5239        false
5240    }
5241
5242    /// Executes the provided function with mutable access to an inspector state.
5243    #[cfg(any(feature = "inspector", debug_assertions))]
5244    pub fn with_inspector_state<T: 'static, R>(
5245        &mut self,
5246        _inspector_id: Option<&crate::InspectorElementId>,
5247        cx: &mut App,
5248        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
5249    ) -> R {
5250        if let Some(inspector_id) = _inspector_id
5251            && let Some(inspector) = &self.inspector
5252        {
5253            let inspector = inspector.clone();
5254            let active_element_id = inspector.read(cx).active_element_id();
5255            if Some(inspector_id) == active_element_id {
5256                return inspector.update(cx, |inspector, _cx| {
5257                    inspector.with_active_element_state(self, f)
5258                });
5259            }
5260        }
5261        f(&mut None, self)
5262    }
5263
5264    #[cfg(any(feature = "inspector", debug_assertions))]
5265    pub(crate) fn build_inspector_element_id(
5266        &mut self,
5267        path: crate::InspectorElementPath,
5268    ) -> crate::InspectorElementId {
5269        self.invalidator.debug_assert_paint_or_prepaint();
5270        let path = Rc::new(path);
5271        let next_instance_id = self
5272            .next_frame
5273            .next_inspector_instance_ids
5274            .entry(path.clone())
5275            .or_insert(0);
5276        let instance_id = *next_instance_id;
5277        *next_instance_id += 1;
5278        crate::InspectorElementId { path, instance_id }
5279    }
5280
5281    #[cfg(any(feature = "inspector", debug_assertions))]
5282    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
5283        if let Some(inspector) = self.inspector.take() {
5284            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
5285            inspector_element.prepaint_as_root(
5286                point(self.viewport_size.width - inspector_width, px(0.0)),
5287                size(inspector_width, self.viewport_size.height).into(),
5288                self,
5289                cx,
5290            );
5291            self.inspector = Some(inspector);
5292            Some(inspector_element)
5293        } else {
5294            None
5295        }
5296    }
5297
5298    #[cfg(any(feature = "inspector", debug_assertions))]
5299    fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
5300        if let Some(mut inspector_element) = inspector_element {
5301            inspector_element.paint(self, cx);
5302        };
5303    }
5304
5305    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
5306    /// inspect UI elements by clicking on them.
5307    #[cfg(any(feature = "inspector", debug_assertions))]
5308    pub fn insert_inspector_hitbox(
5309        &mut self,
5310        hitbox_id: HitboxId,
5311        inspector_id: Option<&crate::InspectorElementId>,
5312        cx: &App,
5313    ) {
5314        self.invalidator.debug_assert_paint_or_prepaint();
5315        if !self.is_inspector_picking(cx) {
5316            return;
5317        }
5318        if let Some(inspector_id) = inspector_id {
5319            self.next_frame
5320                .inspector_hitboxes
5321                .insert(hitbox_id, inspector_id.clone());
5322        }
5323    }
5324
5325    #[cfg(any(feature = "inspector", debug_assertions))]
5326    fn paint_inspector_hitbox(&mut self, cx: &App) {
5327        if let Some(inspector) = self.inspector.as_ref() {
5328            let inspector = inspector.read(cx);
5329            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
5330                && let Some(hitbox) = self
5331                    .next_frame
5332                    .hitboxes
5333                    .iter()
5334                    .find(|hitbox| hitbox.id == hitbox_id)
5335            {
5336                self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
5337            }
5338        }
5339    }
5340
5341    #[cfg(any(feature = "inspector", debug_assertions))]
5342    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5343        let Some(inspector) = self.inspector.clone() else {
5344            return;
5345        };
5346        if event.downcast_ref::<MouseMoveEvent>().is_some() {
5347            inspector.update(cx, |inspector, _cx| {
5348                if let Some((_, inspector_id)) =
5349                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5350                {
5351                    inspector.hover(inspector_id, self);
5352                }
5353            });
5354        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
5355            inspector.update(cx, |inspector, _cx| {
5356                if let Some((_, inspector_id)) =
5357                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5358                {
5359                    inspector.select(inspector_id, self);
5360                }
5361            });
5362        } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
5363            // This should be kept in sync with SCROLL_LINES in x11 platform.
5364            const SCROLL_LINES: f32 = 3.0;
5365            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
5366            let delta_y = event
5367                .delta
5368                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
5369                .y;
5370            if let Some(inspector) = self.inspector.clone() {
5371                inspector.update(cx, |inspector, _cx| {
5372                    if let Some(depth) = inspector.pick_depth.as_mut() {
5373                        *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
5374                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
5375                        if *depth < 0.0 {
5376                            *depth = 0.0;
5377                        } else if *depth > max_depth {
5378                            *depth = max_depth;
5379                        }
5380                        if let Some((_, inspector_id)) =
5381                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5382                        {
5383                            inspector.set_active_element_id(inspector_id, self);
5384                        }
5385                    }
5386                });
5387            }
5388        }
5389    }
5390
5391    #[cfg(any(feature = "inspector", debug_assertions))]
5392    fn hovered_inspector_hitbox(
5393        &self,
5394        inspector: &Inspector,
5395        frame: &Frame,
5396    ) -> Option<(HitboxId, crate::InspectorElementId)> {
5397        if let Some(pick_depth) = inspector.pick_depth {
5398            let depth = (pick_depth as i64).try_into().unwrap_or(0);
5399            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
5400            let skip_count = (depth as usize).min(max_skipped);
5401            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
5402                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
5403                    return Some((*hitbox_id, inspector_id.clone()));
5404                }
5405            }
5406        }
5407        None
5408    }
5409
5410    /// For testing: set the current modifier keys state.
5411    /// This does not generate any events.
5412    #[cfg(any(test, feature = "test-support"))]
5413    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
5414        self.modifiers = modifiers;
5415    }
5416
5417    /// For testing: simulate a mouse move event to the given position.
5418    /// This dispatches the event through the normal event handling path,
5419    /// which will trigger hover states and tooltips.
5420    #[cfg(any(test, feature = "test-support"))]
5421    pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
5422        let event = PlatformInput::MouseMove(MouseMoveEvent {
5423            position,
5424            modifiers: self.modifiers,
5425            pressed_button: None,
5426        });
5427        let _ = self.dispatch_event(event, cx);
5428    }
5429}
5430
5431// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
5432slotmap::new_key_type! {
5433    /// A unique identifier for a window.
5434    pub struct WindowId;
5435}
5436
5437impl WindowId {
5438    /// Converts this window ID to a `u64`.
5439    pub fn as_u64(&self) -> u64 {
5440        self.0.as_ffi()
5441    }
5442}
5443
5444impl From<u64> for WindowId {
5445    fn from(value: u64) -> Self {
5446        WindowId(slotmap::KeyData::from_ffi(value))
5447    }
5448}
5449
5450/// A handle to a window with a specific root view type.
5451/// Note that this does not keep the window alive on its own.
5452#[derive(Deref, DerefMut)]
5453pub struct WindowHandle<V> {
5454    #[deref]
5455    #[deref_mut]
5456    pub(crate) any_handle: AnyWindowHandle,
5457    state_type: PhantomData<fn(V) -> V>,
5458}
5459
5460impl<V> Debug for WindowHandle<V> {
5461    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5462        f.debug_struct("WindowHandle")
5463            .field("any_handle", &self.any_handle.id.as_u64())
5464            .finish()
5465    }
5466}
5467
5468impl<V: 'static + Render> WindowHandle<V> {
5469    /// Creates a new handle from a window ID.
5470    /// This does not check if the root type of the window is `V`.
5471    pub fn new(id: WindowId) -> Self {
5472        WindowHandle {
5473            any_handle: AnyWindowHandle {
5474                id,
5475                state_type: TypeId::of::<V>(),
5476            },
5477            state_type: PhantomData,
5478        }
5479    }
5480
5481    /// Get the root view out of this window.
5482    ///
5483    /// This will fail if the window is closed or if the root view's type does not match `V`.
5484    #[cfg(any(test, feature = "test-support"))]
5485    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
5486    where
5487        C: AppContext,
5488    {
5489        cx.update_window(self.any_handle, |root_view, _, _| {
5490            root_view
5491                .downcast::<V>()
5492                .map_err(|_| anyhow!("the type of the window's root view has changed"))
5493        })?
5494    }
5495
5496    /// Updates the root view of this window.
5497    ///
5498    /// This will fail if the window has been closed or if the root view's type does not match
5499    pub fn update<C, R>(
5500        &self,
5501        cx: &mut C,
5502        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
5503    ) -> Result<R>
5504    where
5505        C: AppContext,
5506    {
5507        cx.update_window(self.any_handle, |root_view, window, cx| {
5508            let view = root_view
5509                .downcast::<V>()
5510                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5511
5512            Ok(view.update(cx, |view, cx| update(view, window, cx)))
5513        })?
5514    }
5515
5516    /// Read the root view out of this window.
5517    ///
5518    /// This will fail if the window is closed or if the root view's type does not match `V`.
5519    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
5520        let x = cx
5521            .windows
5522            .get(self.id)
5523            .and_then(|window| {
5524                window
5525                    .as_deref()
5526                    .and_then(|window| window.root.clone())
5527                    .map(|root_view| root_view.downcast::<V>())
5528            })
5529            .context("window not found")?
5530            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5531
5532        Ok(x.read(cx))
5533    }
5534
5535    /// Read the root view out of this window, with a callback
5536    ///
5537    /// This will fail if the window is closed or if the root view's type does not match `V`.
5538    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
5539    where
5540        C: AppContext,
5541    {
5542        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
5543    }
5544
5545    /// Read the root view pointer off of this window.
5546    ///
5547    /// This will fail if the window is closed or if the root view's type does not match `V`.
5548    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
5549    where
5550        C: AppContext,
5551    {
5552        cx.read_window(self, |root_view, _cx| root_view)
5553    }
5554
5555    /// Check if this window is 'active'.
5556    ///
5557    /// Will return `None` if the window is closed or currently
5558    /// borrowed.
5559    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
5560        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
5561            .ok()
5562    }
5563}
5564
5565impl<V> Copy for WindowHandle<V> {}
5566
5567impl<V> Clone for WindowHandle<V> {
5568    fn clone(&self) -> Self {
5569        *self
5570    }
5571}
5572
5573impl<V> PartialEq for WindowHandle<V> {
5574    fn eq(&self, other: &Self) -> bool {
5575        self.any_handle == other.any_handle
5576    }
5577}
5578
5579impl<V> Eq for WindowHandle<V> {}
5580
5581impl<V> Hash for WindowHandle<V> {
5582    fn hash<H: Hasher>(&self, state: &mut H) {
5583        self.any_handle.hash(state);
5584    }
5585}
5586
5587impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
5588    fn from(val: WindowHandle<V>) -> Self {
5589        val.any_handle
5590    }
5591}
5592
5593/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
5594#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
5595pub struct AnyWindowHandle {
5596    pub(crate) id: WindowId,
5597    state_type: TypeId,
5598}
5599
5600impl AnyWindowHandle {
5601    /// Get the ID of this window.
5602    pub fn window_id(&self) -> WindowId {
5603        self.id
5604    }
5605
5606    /// Attempt to convert this handle to a window handle with a specific root view type.
5607    /// If the types do not match, this will return `None`.
5608    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
5609        if TypeId::of::<T>() == self.state_type {
5610            Some(WindowHandle {
5611                any_handle: *self,
5612                state_type: PhantomData,
5613            })
5614        } else {
5615            None
5616        }
5617    }
5618
5619    /// Updates the state of the root view of this window.
5620    ///
5621    /// This will fail if the window has been closed.
5622    pub fn update<C, R>(
5623        self,
5624        cx: &mut C,
5625        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
5626    ) -> Result<R>
5627    where
5628        C: AppContext,
5629    {
5630        cx.update_window(self, update)
5631    }
5632
5633    /// Read the state of the root view of this window.
5634    ///
5635    /// This will fail if the window has been closed.
5636    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
5637    where
5638        C: AppContext,
5639        T: 'static,
5640    {
5641        let view = self
5642            .downcast::<T>()
5643            .context("the type of the window's root view has changed")?;
5644
5645        cx.read_window(&view, read)
5646    }
5647}
5648
5649impl HasWindowHandle for Window {
5650    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
5651        self.platform_window.window_handle()
5652    }
5653}
5654
5655impl HasDisplayHandle for Window {
5656    fn display_handle(
5657        &self,
5658    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
5659        self.platform_window.display_handle()
5660    }
5661}
5662
5663/// An identifier for an [`Element`].
5664///
5665/// Can be constructed with a string, a number, or both, as well
5666/// as other internal representations.
5667#[derive(Clone, Debug, Eq, PartialEq, Hash)]
5668pub enum ElementId {
5669    /// The ID of a View element
5670    View(EntityId),
5671    /// An integer ID.
5672    Integer(u64),
5673    /// A string based ID.
5674    Name(SharedString),
5675    /// A UUID.
5676    Uuid(Uuid),
5677    /// An ID that's equated with a focus handle.
5678    FocusHandle(FocusId),
5679    /// A combination of a name and an integer.
5680    NamedInteger(SharedString, u64),
5681    /// A path.
5682    Path(Arc<std::path::Path>),
5683    /// A code location.
5684    CodeLocation(core::panic::Location<'static>),
5685    /// A labeled child of an element.
5686    NamedChild(Arc<ElementId>, SharedString),
5687    /// A byte array ID (used for text-anchors)
5688    OpaqueId([u8; 20]),
5689}
5690
5691impl ElementId {
5692    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
5693    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
5694        Self::NamedInteger(name.into(), integer as u64)
5695    }
5696}
5697
5698impl Display for ElementId {
5699    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5700        match self {
5701            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
5702            ElementId::Integer(ix) => write!(f, "{}", ix)?,
5703            ElementId::Name(name) => write!(f, "{}", name)?,
5704            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
5705            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
5706            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
5707            ElementId::Path(path) => write!(f, "{}", path.display())?,
5708            ElementId::CodeLocation(location) => write!(f, "{}", location)?,
5709            ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
5710            ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
5711        }
5712
5713        Ok(())
5714    }
5715}
5716
5717impl TryInto<SharedString> for ElementId {
5718    type Error = anyhow::Error;
5719
5720    fn try_into(self) -> anyhow::Result<SharedString> {
5721        if let ElementId::Name(name) = self {
5722            Ok(name)
5723        } else {
5724            anyhow::bail!("element id is not string")
5725        }
5726    }
5727}
5728
5729impl From<usize> for ElementId {
5730    fn from(id: usize) -> Self {
5731        ElementId::Integer(id as u64)
5732    }
5733}
5734
5735impl From<i32> for ElementId {
5736    fn from(id: i32) -> Self {
5737        Self::Integer(id as u64)
5738    }
5739}
5740
5741impl From<SharedString> for ElementId {
5742    fn from(name: SharedString) -> Self {
5743        ElementId::Name(name)
5744    }
5745}
5746
5747impl From<String> for ElementId {
5748    fn from(name: String) -> Self {
5749        ElementId::Name(name.into())
5750    }
5751}
5752
5753impl From<Arc<str>> for ElementId {
5754    fn from(name: Arc<str>) -> Self {
5755        ElementId::Name(name.into())
5756    }
5757}
5758
5759impl From<Arc<std::path::Path>> for ElementId {
5760    fn from(path: Arc<std::path::Path>) -> Self {
5761        ElementId::Path(path)
5762    }
5763}
5764
5765impl From<&'static str> for ElementId {
5766    fn from(name: &'static str) -> Self {
5767        ElementId::Name(name.into())
5768    }
5769}
5770
5771impl<'a> From<&'a FocusHandle> for ElementId {
5772    fn from(handle: &'a FocusHandle) -> Self {
5773        ElementId::FocusHandle(handle.id)
5774    }
5775}
5776
5777impl From<(&'static str, EntityId)> for ElementId {
5778    fn from((name, id): (&'static str, EntityId)) -> Self {
5779        ElementId::NamedInteger(name.into(), id.as_u64())
5780    }
5781}
5782
5783impl From<(&'static str, usize)> for ElementId {
5784    fn from((name, id): (&'static str, usize)) -> Self {
5785        ElementId::NamedInteger(name.into(), id as u64)
5786    }
5787}
5788
5789impl From<(SharedString, usize)> for ElementId {
5790    fn from((name, id): (SharedString, usize)) -> Self {
5791        ElementId::NamedInteger(name, id as u64)
5792    }
5793}
5794
5795impl From<(&'static str, u64)> for ElementId {
5796    fn from((name, id): (&'static str, u64)) -> Self {
5797        ElementId::NamedInteger(name.into(), id)
5798    }
5799}
5800
5801impl From<Uuid> for ElementId {
5802    fn from(value: Uuid) -> Self {
5803        Self::Uuid(value)
5804    }
5805}
5806
5807impl From<(&'static str, u32)> for ElementId {
5808    fn from((name, id): (&'static str, u32)) -> Self {
5809        ElementId::NamedInteger(name.into(), id.into())
5810    }
5811}
5812
5813impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
5814    fn from((id, name): (ElementId, T)) -> Self {
5815        ElementId::NamedChild(Arc::new(id), name.into())
5816    }
5817}
5818
5819impl From<&'static core::panic::Location<'static>> for ElementId {
5820    fn from(location: &'static core::panic::Location<'static>) -> Self {
5821        ElementId::CodeLocation(*location)
5822    }
5823}
5824
5825impl From<[u8; 20]> for ElementId {
5826    fn from(opaque_id: [u8; 20]) -> Self {
5827        ElementId::OpaqueId(opaque_id)
5828    }
5829}
5830
5831/// A rectangle to be rendered in the window at the given position and size.
5832/// Passed as an argument [`Window::paint_quad`].
5833#[derive(Clone)]
5834pub struct PaintQuad {
5835    /// The bounds of the quad within the window.
5836    pub bounds: Bounds<Pixels>,
5837    /// The radii of the quad's corners.
5838    pub corner_radii: Corners<Pixels>,
5839    /// The background color of the quad.
5840    pub background: Background,
5841    /// The widths of the quad's borders.
5842    pub border_widths: Edges<Pixels>,
5843    /// The color of the quad's borders.
5844    pub border_color: Hsla,
5845    /// The style of the quad's borders.
5846    pub border_style: BorderStyle,
5847}
5848
5849impl PaintQuad {
5850    /// Sets the corner radii of the quad.
5851    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
5852        PaintQuad {
5853            corner_radii: corner_radii.into(),
5854            ..self
5855        }
5856    }
5857
5858    /// Sets the border widths of the quad.
5859    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
5860        PaintQuad {
5861            border_widths: border_widths.into(),
5862            ..self
5863        }
5864    }
5865
5866    /// Sets the border color of the quad.
5867    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
5868        PaintQuad {
5869            border_color: border_color.into(),
5870            ..self
5871        }
5872    }
5873
5874    /// Sets the background color of the quad.
5875    pub fn background(self, background: impl Into<Background>) -> Self {
5876        PaintQuad {
5877            background: background.into(),
5878            ..self
5879        }
5880    }
5881}
5882
5883/// Creates a quad with the given parameters.
5884pub fn quad(
5885    bounds: Bounds<Pixels>,
5886    corner_radii: impl Into<Corners<Pixels>>,
5887    background: impl Into<Background>,
5888    border_widths: impl Into<Edges<Pixels>>,
5889    border_color: impl Into<Hsla>,
5890    border_style: BorderStyle,
5891) -> PaintQuad {
5892    PaintQuad {
5893        bounds,
5894        corner_radii: corner_radii.into(),
5895        background: background.into(),
5896        border_widths: border_widths.into(),
5897        border_color: border_color.into(),
5898        border_style,
5899    }
5900}
5901
5902/// Creates a filled quad with the given bounds and background color.
5903pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
5904    PaintQuad {
5905        bounds: bounds.into(),
5906        corner_radii: (0.).into(),
5907        background: background.into(),
5908        border_widths: (0.).into(),
5909        border_color: transparent_black(),
5910        border_style: BorderStyle::default(),
5911    }
5912}
5913
5914/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
5915pub fn outline(
5916    bounds: impl Into<Bounds<Pixels>>,
5917    border_color: impl Into<Hsla>,
5918    border_style: BorderStyle,
5919) -> PaintQuad {
5920    PaintQuad {
5921        bounds: bounds.into(),
5922        corner_radii: (0.).into(),
5923        background: transparent_black().into(),
5924        border_widths: (1.).into(),
5925        border_color: border_color.into(),
5926        border_style,
5927    }
5928}