Skip to main content

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, CursorHideMode, CursorStyle, Decorations, DevicePixels,
7    DispatchActionListener, DispatchNodeId, DispatchTree, DisplayId, Edges, Effect, Entity,
8    EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs,
9    Hsla, InputHandler, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke,
10    KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent, MonochromeSprite,
11    MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, PlatformAtlas,
12    PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, PolychromeSprite,
13    Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage,
14    RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR,
15    SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size,
16    StrikethroughStyle, Style, SubpixelSprite, SubscriberSet, Subscription, SystemWindowTab,
17    SystemWindowTabController, TabStopMap, TaffyLayoutEngine, Task, TextRenderingMode, TextStyle,
18    TextStyleRefinement, ThermalState, TransformationMatrix, Underline, UnderlineStyle,
19    WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControls, WindowDecorations,
20    WindowOptions, WindowParams, WindowTextSystem, point, prelude::*, px, rems, size,
21    transparent_black,
22};
23use anyhow::{Context as _, Result, anyhow};
24use collections::{FxHashMap, FxHashSet};
25#[cfg(target_os = "macos")]
26use core_video::pixel_buffer::CVPixelBuffer;
27use derive_more::{Deref, DerefMut};
28use futures::FutureExt;
29use futures::channel::oneshot;
30use gpui_util::post_inc;
31use gpui_util::{ResultExt, measure};
32#[cfg(feature = "input-latency-histogram")]
33use hdrhistogram::Histogram;
34use itertools::FoldWhile::{Continue, Done};
35use itertools::Itertools;
36use parking_lot::RwLock;
37use raw_window_handle::{HandleError, HasDisplayHandle, HasWindowHandle};
38use refineable::Refineable;
39use scheduler::Instant;
40use slotmap::SlotMap;
41use smallvec::SmallVec;
42use std::{
43    any::{Any, TypeId},
44    borrow::Cow,
45    cell::{Cell, RefCell},
46    cmp,
47    fmt::{Debug, Display},
48    hash::{Hash, Hasher},
49    marker::PhantomData,
50    mem,
51    ops::{DerefMut, Range},
52    rc::Rc,
53    sync::{
54        Arc, Weak,
55        atomic::{AtomicUsize, Ordering::SeqCst},
56    },
57    time::Duration,
58};
59use uuid::Uuid;
60
61mod prompts;
62
63use crate::util::{
64    atomic_incr_if_not_zero, ceil_to_device_pixel, floor_to_device_pixel, round_half_toward_zero,
65    round_half_toward_zero_f64, round_stroke_to_device_pixel, round_to_device_pixel,
66};
67pub use prompts::*;
68
69/// Default window size used when no explicit size is provided.
70pub const DEFAULT_WINDOW_SIZE: Size<Pixels> = size(px(1536.), px(1095.));
71
72/// A 6:5 aspect ratio minimum window size to be used for functional,
73/// additional-to-main-Zed windows, like the settings and rules library windows.
74pub const DEFAULT_ADDITIONAL_WINDOW_SIZE: Size<Pixels> = Size {
75    width: Pixels(900.),
76    height: Pixels(750.),
77};
78
79/// Represents the two different phases when dispatching events.
80#[derive(Default, Copy, Clone, Debug, Eq, PartialEq)]
81pub enum DispatchPhase {
82    /// After the capture phase comes the bubble phase, in which mouse event listeners are
83    /// invoked front to back and keyboard event listeners are invoked from the focused element
84    /// to the root of the element tree. This is the phase you'll most commonly want to use when
85    /// registering event listeners.
86    #[default]
87    Bubble,
88    /// During the initial capture phase, mouse event listeners are invoked back to front, and keyboard
89    /// listeners are invoked from the root of the tree downward toward the focused element. This phase
90    /// is used for special purposes such as clearing the "pressed" state for click events. If
91    /// you stop event propagation during this phase, you need to know what you're doing. Handlers
92    /// outside of the immediate region may rely on detecting non-local events during this phase.
93    Capture,
94}
95
96impl DispatchPhase {
97    /// Returns true if this represents the "bubble" phase.
98    #[inline]
99    pub fn bubble(self) -> bool {
100        self == DispatchPhase::Bubble
101    }
102
103    /// Returns true if this represents the "capture" phase.
104    #[inline]
105    pub fn capture(self) -> bool {
106        self == DispatchPhase::Capture
107    }
108}
109
110struct WindowInvalidatorInner {
111    pub dirty: bool,
112    pub draw_phase: DrawPhase,
113    pub dirty_views: FxHashSet<EntityId>,
114    pub update_count: usize,
115}
116
117#[derive(Clone)]
118pub(crate) struct WindowInvalidator {
119    inner: Rc<RefCell<WindowInvalidatorInner>>,
120}
121
122impl WindowInvalidator {
123    pub fn new() -> Self {
124        WindowInvalidator {
125            inner: Rc::new(RefCell::new(WindowInvalidatorInner {
126                dirty: true,
127                draw_phase: DrawPhase::None,
128                dirty_views: FxHashSet::default(),
129                update_count: 0,
130            })),
131        }
132    }
133
134    pub fn invalidate_view(&self, entity: EntityId, cx: &mut App) -> bool {
135        let mut inner = self.inner.borrow_mut();
136        inner.update_count += 1;
137        inner.dirty_views.insert(entity);
138        if inner.draw_phase == DrawPhase::None {
139            inner.dirty = true;
140            cx.push_effect(Effect::Notify { emitter: entity });
141            true
142        } else {
143            false
144        }
145    }
146
147    pub fn is_dirty(&self) -> bool {
148        self.inner.borrow().dirty
149    }
150
151    pub fn set_dirty(&self, dirty: bool) {
152        let mut inner = self.inner.borrow_mut();
153        inner.dirty = dirty;
154        if dirty {
155            inner.update_count += 1;
156        }
157    }
158
159    pub fn set_phase(&self, phase: DrawPhase) {
160        self.inner.borrow_mut().draw_phase = phase
161    }
162
163    pub fn update_count(&self) -> usize {
164        self.inner.borrow().update_count
165    }
166
167    pub fn take_views(&self) -> FxHashSet<EntityId> {
168        mem::take(&mut self.inner.borrow_mut().dirty_views)
169    }
170
171    pub fn replace_views(&self, views: FxHashSet<EntityId>) {
172        self.inner.borrow_mut().dirty_views = views;
173    }
174
175    pub fn not_drawing(&self) -> bool {
176        self.inner.borrow().draw_phase == DrawPhase::None
177    }
178
179    #[track_caller]
180    pub fn debug_assert_paint(&self) {
181        debug_assert!(
182            matches!(self.inner.borrow().draw_phase, DrawPhase::Paint),
183            "this method can only be called during paint"
184        );
185    }
186
187    #[track_caller]
188    pub fn debug_assert_prepaint(&self) {
189        debug_assert!(
190            matches!(self.inner.borrow().draw_phase, DrawPhase::Prepaint),
191            "this method can only be called during request_layout, or prepaint"
192        );
193    }
194
195    #[track_caller]
196    pub fn debug_assert_paint_or_prepaint(&self) {
197        debug_assert!(
198            matches!(
199                self.inner.borrow().draw_phase,
200                DrawPhase::Paint | DrawPhase::Prepaint
201            ),
202            "this method can only be called during request_layout, prepaint, or paint"
203        );
204    }
205}
206
207type AnyObserver = Box<dyn FnMut(&mut Window, &mut App) -> bool + 'static>;
208
209pub(crate) type AnyWindowFocusListener =
210    Box<dyn FnMut(&WindowFocusEvent, &mut Window, &mut App) -> bool + 'static>;
211
212pub(crate) struct WindowFocusEvent {
213    pub(crate) previous_focus_path: SmallVec<[FocusId; 8]>,
214    pub(crate) current_focus_path: SmallVec<[FocusId; 8]>,
215}
216
217impl WindowFocusEvent {
218    pub fn is_focus_in(&self, focus_id: FocusId) -> bool {
219        !self.previous_focus_path.contains(&focus_id) && self.current_focus_path.contains(&focus_id)
220    }
221
222    pub fn is_focus_out(&self, focus_id: FocusId) -> bool {
223        self.previous_focus_path.contains(&focus_id) && !self.current_focus_path.contains(&focus_id)
224    }
225}
226
227/// This is provided when subscribing for `Context::on_focus_out` events.
228pub struct FocusOutEvent {
229    /// A weak focus handle representing what was blurred.
230    pub blurred: WeakFocusHandle,
231}
232
233slotmap::new_key_type! {
234    /// A globally unique identifier for a focusable element.
235    pub struct FocusId;
236}
237
238thread_local! {
239    /// Fallback arena used when no app-specific arena is active.
240    /// In production, each window draw sets CURRENT_ELEMENT_ARENA to the app's arena.
241    pub(crate) static ELEMENT_ARENA: RefCell<Arena> = RefCell::new(Arena::new(1024 * 1024));
242
243    /// Points to the current App's element arena during draw operations.
244    /// This allows multiple test Apps to have isolated arenas, preventing
245    /// cross-session corruption when the scheduler interleaves their tasks.
246    static CURRENT_ELEMENT_ARENA: Cell<Option<*const RefCell<Arena>>> = const { Cell::new(None) };
247}
248
249/// Allocates an element in the current arena. Uses the app-specific arena if one
250/// is active (during draw), otherwise falls back to the thread-local ELEMENT_ARENA.
251pub(crate) fn with_element_arena<R>(f: impl FnOnce(&mut Arena) -> R) -> R {
252    CURRENT_ELEMENT_ARENA.with(|current| {
253        if let Some(arena_ptr) = current.get() {
254            // SAFETY: The pointer is valid for the duration of the draw operation
255            // that set it, and we're being called during that same draw.
256            let arena_cell = unsafe { &*arena_ptr };
257            f(&mut arena_cell.borrow_mut())
258        } else {
259            ELEMENT_ARENA.with_borrow_mut(f)
260        }
261    })
262}
263
264/// RAII guard that sets CURRENT_ELEMENT_ARENA for the duration of a draw operation.
265/// When dropped, restores the previous arena (supporting nested draws).
266pub(crate) struct ElementArenaScope {
267    previous: Option<*const RefCell<Arena>>,
268}
269
270impl ElementArenaScope {
271    /// Enter a scope where element allocations use the given arena.
272    pub(crate) fn enter(arena: &RefCell<Arena>) -> Self {
273        let previous = CURRENT_ELEMENT_ARENA.with(|current| {
274            let prev = current.get();
275            current.set(Some(arena as *const RefCell<Arena>));
276            prev
277        });
278        Self { previous }
279    }
280}
281
282impl Drop for ElementArenaScope {
283    fn drop(&mut self) {
284        CURRENT_ELEMENT_ARENA.with(|current| {
285            current.set(self.previous);
286        });
287    }
288}
289
290/// Returned when the element arena has been used and so must be cleared before the next draw.
291#[must_use]
292pub struct ArenaClearNeeded {
293    arena: *const RefCell<Arena>,
294}
295
296impl ArenaClearNeeded {
297    /// Create a new ArenaClearNeeded that will clear the given arena.
298    pub(crate) fn new(arena: &RefCell<Arena>) -> Self {
299        Self {
300            arena: arena as *const RefCell<Arena>,
301        }
302    }
303
304    /// Clear the element arena.
305    pub fn clear(self) {
306        // SAFETY: The arena pointer is valid because ArenaClearNeeded is created
307        // at the end of draw() and must be cleared before the next draw.
308        let arena_cell = unsafe { &*self.arena };
309        arena_cell.borrow_mut().clear();
310    }
311}
312
313pub(crate) type FocusMap = RwLock<SlotMap<FocusId, FocusRef>>;
314pub(crate) struct FocusRef {
315    pub(crate) ref_count: AtomicUsize,
316    pub(crate) tab_index: isize,
317    pub(crate) tab_stop: bool,
318}
319
320impl FocusId {
321    /// Obtains whether the element associated with this handle is currently focused.
322    pub fn is_focused(&self, window: &Window) -> bool {
323        window.focus == Some(*self)
324    }
325
326    /// Obtains whether the element associated with this handle contains the focused
327    /// element or is itself focused.
328    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
329        window
330            .focused(cx)
331            .is_some_and(|focused| self.contains(focused.id, window))
332    }
333
334    /// Obtains whether the element associated with this handle is contained within the
335    /// focused element or is itself focused.
336    pub fn within_focused(&self, window: &Window, cx: &App) -> bool {
337        let focused = window.focused(cx);
338        focused.is_some_and(|focused| focused.id.contains(*self, window))
339    }
340
341    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
342    pub(crate) fn contains(&self, other: Self, window: &Window) -> bool {
343        window
344            .rendered_frame
345            .dispatch_tree
346            .focus_contains(*self, other)
347    }
348}
349
350/// A handle which can be used to track and manipulate the focused element in a window.
351pub struct FocusHandle {
352    pub(crate) id: FocusId,
353    handles: Arc<FocusMap>,
354    /// The index of this element in the tab order.
355    pub tab_index: isize,
356    /// Whether this element can be focused by tab navigation.
357    pub tab_stop: bool,
358}
359
360impl std::fmt::Debug for FocusHandle {
361    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
362        f.write_fmt(format_args!("FocusHandle({:?})", self.id))
363    }
364}
365
366impl FocusHandle {
367    pub(crate) fn new(handles: &Arc<FocusMap>) -> Self {
368        let id = handles.write().insert(FocusRef {
369            ref_count: AtomicUsize::new(1),
370            tab_index: 0,
371            tab_stop: false,
372        });
373
374        Self {
375            id,
376            tab_index: 0,
377            tab_stop: false,
378            handles: handles.clone(),
379        }
380    }
381
382    pub(crate) fn for_id(id: FocusId, handles: &Arc<FocusMap>) -> Option<Self> {
383        let lock = handles.read();
384        let focus = lock.get(id)?;
385        if atomic_incr_if_not_zero(&focus.ref_count) == 0 {
386            return None;
387        }
388        Some(Self {
389            id,
390            tab_index: focus.tab_index,
391            tab_stop: focus.tab_stop,
392            handles: handles.clone(),
393        })
394    }
395
396    /// Sets the tab index of the element associated with this handle.
397    pub fn tab_index(mut self, index: isize) -> Self {
398        self.tab_index = index;
399        if let Some(focus) = self.handles.write().get_mut(self.id) {
400            focus.tab_index = index;
401        }
402        self
403    }
404
405    /// Sets whether the element associated with this handle is a tab stop.
406    ///
407    /// When `false`, the element will not be included in the tab order.
408    pub fn tab_stop(mut self, tab_stop: bool) -> Self {
409        self.tab_stop = tab_stop;
410        if let Some(focus) = self.handles.write().get_mut(self.id) {
411            focus.tab_stop = tab_stop;
412        }
413        self
414    }
415
416    /// Converts this focus handle into a weak variant, which does not prevent it from being released.
417    pub fn downgrade(&self) -> WeakFocusHandle {
418        WeakFocusHandle {
419            id: self.id,
420            handles: Arc::downgrade(&self.handles),
421        }
422    }
423
424    /// Moves the focus to the element associated with this handle.
425    pub fn focus(&self, window: &mut Window, cx: &mut App) {
426        window.focus(self, cx)
427    }
428
429    /// Obtains whether the element associated with this handle is currently focused.
430    pub fn is_focused(&self, window: &Window) -> bool {
431        self.id.is_focused(window)
432    }
433
434    /// Obtains whether the element associated with this handle contains the focused
435    /// element or is itself focused.
436    pub fn contains_focused(&self, window: &Window, cx: &App) -> bool {
437        self.id.contains_focused(window, cx)
438    }
439
440    /// Obtains whether the element associated with this handle is contained within the
441    /// focused element or is itself focused.
442    pub fn within_focused(&self, window: &Window, cx: &mut App) -> bool {
443        self.id.within_focused(window, cx)
444    }
445
446    /// Obtains whether this handle contains the given handle in the most recently rendered frame.
447    pub fn contains(&self, other: &Self, window: &Window) -> bool {
448        self.id.contains(other.id, window)
449    }
450
451    /// Dispatch an action on the element that rendered this focus handle
452    pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) {
453        if let Some(node_id) = window
454            .rendered_frame
455            .dispatch_tree
456            .focusable_node_id(self.id)
457        {
458            window.dispatch_action_on_node(node_id, action, cx)
459        }
460    }
461}
462
463impl Clone for FocusHandle {
464    fn clone(&self) -> Self {
465        Self::for_id(self.id, &self.handles).unwrap()
466    }
467}
468
469impl PartialEq for FocusHandle {
470    fn eq(&self, other: &Self) -> bool {
471        self.id == other.id
472    }
473}
474
475impl Eq for FocusHandle {}
476
477impl Drop for FocusHandle {
478    fn drop(&mut self) {
479        self.handles
480            .read()
481            .get(self.id)
482            .unwrap()
483            .ref_count
484            .fetch_sub(1, SeqCst);
485    }
486}
487
488/// A weak reference to a focus handle.
489#[derive(Clone, Debug)]
490pub struct WeakFocusHandle {
491    pub(crate) id: FocusId,
492    pub(crate) handles: Weak<FocusMap>,
493}
494
495impl WeakFocusHandle {
496    /// Attempts to upgrade the [WeakFocusHandle] to a [FocusHandle].
497    pub fn upgrade(&self) -> Option<FocusHandle> {
498        let handles = self.handles.upgrade()?;
499        FocusHandle::for_id(self.id, &handles)
500    }
501}
502
503impl PartialEq for WeakFocusHandle {
504    fn eq(&self, other: &WeakFocusHandle) -> bool {
505        self.id == other.id
506    }
507}
508
509impl Eq for WeakFocusHandle {}
510
511impl PartialEq<FocusHandle> for WeakFocusHandle {
512    fn eq(&self, other: &FocusHandle) -> bool {
513        self.id == other.id
514    }
515}
516
517impl PartialEq<WeakFocusHandle> for FocusHandle {
518    fn eq(&self, other: &WeakFocusHandle) -> bool {
519        self.id == other.id
520    }
521}
522
523/// Focusable allows users of your view to easily
524/// focus it (using window.focus_view(cx, view))
525pub trait Focusable: 'static {
526    /// Returns the focus handle associated with this view.
527    fn focus_handle(&self, cx: &App) -> FocusHandle;
528}
529
530impl<V: Focusable> Focusable for Entity<V> {
531    fn focus_handle(&self, cx: &App) -> FocusHandle {
532        self.read(cx).focus_handle(cx)
533    }
534}
535
536/// ManagedView is a view (like a Modal, Popover, Menu, etc.)
537/// where the lifecycle of the view is handled by another view.
538pub trait ManagedView: Focusable + EventEmitter<DismissEvent> + Render {}
539
540impl<M: Focusable + EventEmitter<DismissEvent> + Render> ManagedView for M {}
541
542/// Emitted by implementers of [`ManagedView`] to indicate the view should be dismissed, such as when a view is presented as a modal.
543pub struct DismissEvent;
544
545type FrameCallback = Box<dyn FnOnce(&mut Window, &mut App)>;
546
547pub(crate) type AnyMouseListener =
548    Box<dyn FnMut(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static>;
549
550#[derive(Clone)]
551pub(crate) struct CursorStyleRequest {
552    pub(crate) hitbox_id: Option<HitboxId>,
553    pub(crate) style: CursorStyle,
554}
555
556#[derive(Default, Eq, PartialEq)]
557pub(crate) struct HitTest {
558    pub(crate) ids: SmallVec<[HitboxId; 8]>,
559    pub(crate) hover_hitbox_count: usize,
560}
561
562/// A type of window control area that corresponds to the platform window.
563#[derive(Clone, Copy, Debug, Eq, PartialEq)]
564pub enum WindowControlArea {
565    /// An area that allows dragging of the platform window.
566    Drag,
567    /// An area that allows closing of the platform window.
568    Close,
569    /// An area that allows maximizing of the platform window.
570    Max,
571    /// An area that allows minimizing of the platform window.
572    Min,
573}
574
575/// An identifier for a [Hitbox] which also includes [HitboxBehavior].
576#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
577pub struct HitboxId(u64);
578
579#[cfg(feature = "test-support")]
580impl HitboxId {
581    /// A placeholder HitboxId exclusively for integration testing API's that
582    /// need a hitbox but where the value of the hitbox does not matter. The
583    /// alternative is to make the Hitbox optional but that complicates the
584    /// implementation.
585    pub const fn placeholder() -> Self {
586        Self(0)
587    }
588}
589
590impl HitboxId {
591    /// Checks if the hitbox with this ID is currently hovered. Returns `false` during keyboard
592    /// input modality so that keyboard navigation suppresses hover highlights. Except when handling
593    /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse
594    /// events or paint hover styles.
595    ///
596    /// See [`Hitbox::is_hovered`] for details.
597    pub fn is_hovered(self, window: &Window) -> bool {
598        // If this hitbox has captured the pointer, it's always considered hovered
599        if window.captured_hitbox == Some(self) {
600            return true;
601        }
602        if window.last_input_was_keyboard() {
603            return false;
604        }
605        self.hit_test(window)
606    }
607
608    /// Checks if the hitbox with this ID is currently hovered, regardless of the last
609    /// input modality used.
610    ///
611    /// See [`HitboxId::is_hovered`] for more details.
612    pub(crate) fn is_hovered_ignoring_last_input(self, window: &Window) -> bool {
613        // If this hitbox has captured the pointer, it's always considered hovered
614        if window.captured_hitbox == Some(self) {
615            return true;
616        }
617        self.hit_test(window)
618    }
619
620    fn hit_test(self, window: &Window) -> bool {
621        let hit_test = &window.mouse_hit_test;
622        for id in hit_test.ids.iter().take(hit_test.hover_hitbox_count) {
623            if self == *id {
624                return true;
625            }
626        }
627        false
628    }
629
630    /// Checks if the hitbox with this ID contains the mouse and should handle scroll events.
631    /// Typically this should only be used when handling `ScrollWheelEvent`, and otherwise
632    /// `is_hovered` should be used. See the documentation of `Hitbox::is_hovered` for details about
633    /// this distinction.
634    pub fn should_handle_scroll(self, window: &Window) -> bool {
635        window.mouse_hit_test.ids.contains(&self)
636    }
637
638    fn next(mut self) -> HitboxId {
639        HitboxId(self.0.wrapping_add(1))
640    }
641}
642
643/// A rectangular region that potentially blocks hitboxes inserted prior.
644/// See [Window::insert_hitbox] for more details.
645#[derive(Clone, Debug, Deref)]
646pub struct Hitbox {
647    /// A unique identifier for the hitbox.
648    pub id: HitboxId,
649    /// The bounds of the hitbox.
650    #[deref]
651    pub bounds: Bounds<Pixels>,
652    /// The content mask when the hitbox was inserted.
653    pub content_mask: ContentMask<Pixels>,
654    /// Flags that specify hitbox behavior.
655    pub behavior: HitboxBehavior,
656}
657
658impl Hitbox {
659    /// Checks if the hitbox is currently hovered. Returns `false` during keyboard input modality
660    /// so that keyboard navigation suppresses hover highlights. Except when handling
661    /// `ScrollWheelEvent`, this is typically what you want when determining whether to handle mouse
662    /// events or paint hover styles.
663    ///
664    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
665    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`) or
666    /// `HitboxBehavior::BlockMouseExceptScroll` (`InteractiveElement::block_mouse_except_scroll`),
667    /// or if the current input modality is keyboard (see [`Window::last_input_was_keyboard`]).
668    ///
669    /// Handling of `ScrollWheelEvent` should typically use `should_handle_scroll` instead.
670    /// Concretely, this is due to use-cases like overlays that cause the elements under to be
671    /// non-interactive while still allowing scrolling. More abstractly, this is because
672    /// `is_hovered` is about element interactions directly under the mouse - mouse moves, clicks,
673    /// hover styling, etc. In contrast, scrolling is about finding the current outer scrollable
674    /// container.
675    pub fn is_hovered(&self, window: &Window) -> bool {
676        self.id.is_hovered(window)
677    }
678
679    /// Checks if the hitbox contains the mouse and should handle scroll events. Typically this
680    /// should only be used when handling `ScrollWheelEvent`, and otherwise `is_hovered` should be
681    /// used. See the documentation of `Hitbox::is_hovered` for details about this distinction.
682    ///
683    /// This can return `false` even when the hitbox contains the mouse, if a hitbox in front of
684    /// this sets `HitboxBehavior::BlockMouse` (`InteractiveElement::occlude`).
685    pub fn should_handle_scroll(&self, window: &Window) -> bool {
686        self.id.should_handle_scroll(window)
687    }
688}
689
690/// How the hitbox affects mouse behavior.
691#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
692pub enum HitboxBehavior {
693    /// Normal hitbox mouse behavior, doesn't affect mouse handling for other hitboxes.
694    #[default]
695    Normal,
696
697    /// All hitboxes behind this hitbox will be ignored and so will have `hitbox.is_hovered() ==
698    /// false` and `hitbox.should_handle_scroll() == false`. Typically for elements this causes
699    /// skipping of all mouse events, hover styles, and tooltips. This flag is set by
700    /// [`InteractiveElement::occlude`].
701    ///
702    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
703    /// bubble-phase handler for every mouse event type:
704    ///
705    /// ```ignore
706    /// window.on_mouse_event(move |_: &EveryMouseEventTypeHere, phase, window, cx| {
707    ///     if phase == DispatchPhase::Capture && hitbox.is_hovered(window) {
708    ///         cx.stop_propagation();
709    ///     }
710    /// })
711    /// ```
712    ///
713    /// This has effects beyond event handling - any use of hitbox checking, such as hover
714    /// styles and tooltips. These other behaviors are the main point of this mechanism. An
715    /// alternative might be to not affect mouse event handling - but this would allow
716    /// inconsistent UI where clicks and moves interact with elements that are not considered to
717    /// be hovered.
718    BlockMouse,
719
720    /// All hitboxes behind this hitbox will have `hitbox.is_hovered() == false`, even when
721    /// `hitbox.should_handle_scroll() == true`. Typically for elements this causes all mouse
722    /// interaction except scroll events to be ignored - see the documentation of
723    /// [`Hitbox::is_hovered`] for details. This flag is set by
724    /// [`InteractiveElement::block_mouse_except_scroll`].
725    ///
726    /// For mouse handlers that check those hitboxes, this behaves the same as registering a
727    /// bubble-phase handler for every mouse event type **except** `ScrollWheelEvent`:
728    ///
729    /// ```ignore
730    /// window.on_mouse_event(move |_: &EveryMouseEventTypeExceptScroll, phase, window, cx| {
731    ///     if phase == DispatchPhase::Bubble && hitbox.should_handle_scroll(window) {
732    ///         cx.stop_propagation();
733    ///     }
734    /// })
735    /// ```
736    ///
737    /// See the documentation of [`Hitbox::is_hovered`] for details of why `ScrollWheelEvent` is
738    /// handled differently than other mouse events. If also blocking these scroll events is
739    /// desired, then a `cx.stop_propagation()` handler like the one above can be used.
740    ///
741    /// This has effects beyond event handling - this affects any use of `is_hovered`, such as
742    /// hover styles and tooltips. These other behaviors are the main point of this mechanism.
743    /// An alternative might be to not affect mouse event handling - but this would allow
744    /// inconsistent UI where clicks and moves interact with elements that are not considered to
745    /// be hovered.
746    BlockMouseExceptScroll,
747}
748
749/// An identifier for a tooltip.
750#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
751pub struct TooltipId(usize);
752
753impl TooltipId {
754    /// Checks if the tooltip is currently hovered.
755    pub fn is_hovered(&self, window: &Window) -> bool {
756        window
757            .tooltip_bounds
758            .as_ref()
759            .is_some_and(|tooltip_bounds| {
760                tooltip_bounds.id == *self
761                    && tooltip_bounds.bounds.contains(&window.mouse_position())
762            })
763    }
764}
765
766pub(crate) struct TooltipBounds {
767    id: TooltipId,
768    bounds: Bounds<Pixels>,
769}
770
771#[derive(Clone)]
772pub(crate) struct TooltipRequest {
773    id: TooltipId,
774    tooltip: AnyTooltip,
775}
776
777pub(crate) struct DeferredDraw {
778    current_view: EntityId,
779    priority: usize,
780    parent_node: DispatchNodeId,
781    element_id_stack: SmallVec<[ElementId; 32]>,
782    text_style_stack: Vec<TextStyleRefinement>,
783    content_mask: Option<ContentMask<Pixels>>,
784    rem_size: Pixels,
785    element: Option<AnyElement>,
786    absolute_offset: Point<Pixels>,
787    prepaint_range: Range<PrepaintStateIndex>,
788    paint_range: Range<PaintIndex>,
789}
790
791pub(crate) struct Frame {
792    pub(crate) focus: Option<FocusId>,
793    pub(crate) window_active: bool,
794    pub(crate) element_states: FxHashMap<(GlobalElementId, TypeId), ElementStateBox>,
795    accessed_element_states: Vec<(GlobalElementId, TypeId)>,
796    pub(crate) mouse_listeners: Vec<Option<AnyMouseListener>>,
797    pub(crate) dispatch_tree: DispatchTree,
798    pub(crate) scene: Scene,
799    pub(crate) hitboxes: Vec<Hitbox>,
800    pub(crate) window_control_hitboxes: Vec<(WindowControlArea, Hitbox)>,
801    pub(crate) deferred_draws: Vec<DeferredDraw>,
802    pub(crate) input_handlers: Vec<Option<PlatformInputHandler>>,
803    pub(crate) tooltip_requests: Vec<Option<TooltipRequest>>,
804    pub(crate) cursor_styles: Vec<CursorStyleRequest>,
805    #[cfg(any(test, feature = "test-support"))]
806    pub(crate) debug_bounds: FxHashMap<String, Bounds<Pixels>>,
807    #[cfg(any(feature = "inspector", debug_assertions))]
808    pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
809    #[cfg(any(feature = "inspector", debug_assertions))]
810    pub(crate) inspector_hitboxes: FxHashMap<HitboxId, crate::InspectorElementId>,
811    pub(crate) tab_stops: TabStopMap,
812}
813
814#[derive(Clone, Default)]
815pub(crate) struct PrepaintStateIndex {
816    hitboxes_index: usize,
817    tooltips_index: usize,
818    deferred_draws_index: usize,
819    dispatch_tree_index: usize,
820    accessed_element_states_index: usize,
821    line_layout_index: LineLayoutIndex,
822}
823
824#[derive(Clone, Default)]
825pub(crate) struct PaintIndex {
826    scene_index: usize,
827    mouse_listeners_index: usize,
828    input_handlers_index: usize,
829    cursor_styles_index: usize,
830    accessed_element_states_index: usize,
831    tab_handle_index: usize,
832    line_layout_index: LineLayoutIndex,
833}
834
835impl Frame {
836    pub(crate) fn new(dispatch_tree: DispatchTree) -> Self {
837        Frame {
838            focus: None,
839            window_active: false,
840            element_states: FxHashMap::default(),
841            accessed_element_states: Vec::new(),
842            mouse_listeners: Vec::new(),
843            dispatch_tree,
844            scene: Scene::default(),
845            hitboxes: Vec::new(),
846            window_control_hitboxes: Vec::new(),
847            deferred_draws: Vec::new(),
848            input_handlers: Vec::new(),
849            tooltip_requests: Vec::new(),
850            cursor_styles: Vec::new(),
851
852            #[cfg(any(test, feature = "test-support"))]
853            debug_bounds: FxHashMap::default(),
854
855            #[cfg(any(feature = "inspector", debug_assertions))]
856            next_inspector_instance_ids: FxHashMap::default(),
857
858            #[cfg(any(feature = "inspector", debug_assertions))]
859            inspector_hitboxes: FxHashMap::default(),
860            tab_stops: TabStopMap::default(),
861        }
862    }
863
864    pub(crate) fn clear(&mut self) {
865        self.element_states.clear();
866        self.accessed_element_states.clear();
867        self.mouse_listeners.clear();
868        self.dispatch_tree.clear();
869        self.scene.clear();
870        self.input_handlers.clear();
871        self.tooltip_requests.clear();
872        self.cursor_styles.clear();
873        self.hitboxes.clear();
874        self.window_control_hitboxes.clear();
875        self.deferred_draws.clear();
876        self.tab_stops.clear();
877        self.focus = None;
878
879        #[cfg(any(test, feature = "test-support"))]
880        {
881            self.debug_bounds.clear();
882        }
883
884        #[cfg(any(feature = "inspector", debug_assertions))]
885        {
886            self.next_inspector_instance_ids.clear();
887            self.inspector_hitboxes.clear();
888        }
889    }
890
891    pub(crate) fn cursor_style(&self, window: &Window) -> Option<CursorStyle> {
892        self.cursor_styles
893            .iter()
894            .rev()
895            .fold_while(None, |style, request| match request.hitbox_id {
896                None => Done(Some(request.style)),
897                Some(hitbox_id) => Continue(style.or_else(|| {
898                    hitbox_id
899                        .is_hovered_ignoring_last_input(window)
900                        .then_some(request.style)
901                })),
902            })
903            .into_inner()
904    }
905
906    pub(crate) fn hit_test(&self, position: Point<Pixels>) -> HitTest {
907        let mut set_hover_hitbox_count = false;
908        let mut hit_test = HitTest::default();
909        for hitbox in self.hitboxes.iter().rev() {
910            let bounds = hitbox.bounds.intersect(&hitbox.content_mask.bounds);
911            if bounds.contains(&position) {
912                hit_test.ids.push(hitbox.id);
913                if !set_hover_hitbox_count
914                    && hitbox.behavior == HitboxBehavior::BlockMouseExceptScroll
915                {
916                    hit_test.hover_hitbox_count = hit_test.ids.len();
917                    set_hover_hitbox_count = true;
918                }
919                if hitbox.behavior == HitboxBehavior::BlockMouse {
920                    break;
921                }
922            }
923        }
924        if !set_hover_hitbox_count {
925            hit_test.hover_hitbox_count = hit_test.ids.len();
926        }
927        hit_test
928    }
929
930    pub(crate) fn focus_path(&self) -> SmallVec<[FocusId; 8]> {
931        self.focus
932            .map(|focus_id| self.dispatch_tree.focus_path(focus_id))
933            .unwrap_or_default()
934    }
935
936    pub(crate) fn finish(&mut self, prev_frame: &mut Self) {
937        for element_state_key in &self.accessed_element_states {
938            if let Some((element_state_key, element_state)) =
939                prev_frame.element_states.remove_entry(element_state_key)
940            {
941                self.element_states.insert(element_state_key, element_state);
942            }
943        }
944
945        self.scene.finish();
946    }
947}
948
949#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
950enum InputModality {
951    Mouse,
952    Keyboard,
953}
954
955/// Holds the state for a specific window.
956pub struct Window {
957    pub(crate) handle: AnyWindowHandle,
958    pub(crate) invalidator: WindowInvalidator,
959    pub(crate) removed: bool,
960    pub(crate) platform_window: Box<dyn PlatformWindow>,
961    display_id: Option<DisplayId>,
962    sprite_atlas: Arc<dyn PlatformAtlas>,
963    text_system: Arc<WindowTextSystem>,
964    text_rendering_mode: Rc<Cell<TextRenderingMode>>,
965    rem_size: Pixels,
966    /// The stack of override values for the window's rem size.
967    ///
968    /// This is used by `with_rem_size` to allow rendering an element tree with
969    /// a given rem size.
970    rem_size_override_stack: SmallVec<[Pixels; 8]>,
971    pub(crate) viewport_size: Size<Pixels>,
972    layout_engine: Option<TaffyLayoutEngine>,
973    pub(crate) root: Option<AnyView>,
974    pub(crate) element_id_stack: SmallVec<[ElementId; 32]>,
975    pub(crate) text_style_stack: Vec<TextStyleRefinement>,
976    pub(crate) rendered_entity_stack: Vec<EntityId>,
977    pub(crate) element_offset_stack: Vec<Point<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                                if request_frame_options.force_render {
1406                                    // Bypass cached view reuse so we don't replay stale
1407                                    // atlas tile references after a GPU device recovery.
1408                                    window.refresh();
1409                                }
1410                                let arena_clear_needed = window.draw(cx);
1411                                window.present();
1412                                arena_clear_needed.clear();
1413                            })
1414                            .log_err();
1415                    })
1416                } else if needs_present {
1417                    handle
1418                        .update(&mut cx, |_, window, _| window.present())
1419                        .log_err();
1420                }
1421
1422                handle
1423                    .update(&mut cx, |_, window, _| {
1424                        window.complete_frame();
1425                    })
1426                    .log_err();
1427            }
1428        }));
1429        platform_window.on_resize(Box::new({
1430            let mut cx = cx.to_async();
1431            move |_, _| {
1432                handle
1433                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1434                    .log_err();
1435            }
1436        }));
1437        platform_window.on_moved(Box::new({
1438            let mut cx = cx.to_async();
1439            move || {
1440                handle
1441                    .update(&mut cx, |_, window, cx| window.bounds_changed(cx))
1442                    .log_err();
1443            }
1444        }));
1445        platform_window.on_appearance_changed(Box::new({
1446            let mut cx = cx.to_async();
1447            move || {
1448                handle
1449                    .update(&mut cx, |_, window, cx| window.appearance_changed(cx))
1450                    .log_err();
1451            }
1452        }));
1453        platform_window.on_button_layout_changed(Box::new({
1454            let mut cx = cx.to_async();
1455            move || {
1456                handle
1457                    .update(&mut cx, |_, window, cx| window.button_layout_changed(cx))
1458                    .log_err();
1459            }
1460        }));
1461        platform_window.on_active_status_change(Box::new({
1462            let mut cx = cx.to_async();
1463            move |active| {
1464                handle
1465                    .update(&mut cx, |_, window, cx| {
1466                        window.active.set(active);
1467                        window.modifiers = window.platform_window.modifiers();
1468                        window.capslock = window.platform_window.capslock();
1469                        window
1470                            .activation_observers
1471                            .clone()
1472                            .retain(&(), |callback| callback(window, cx));
1473
1474                        window.bounds_changed(cx);
1475                        window.refresh();
1476
1477                        SystemWindowTabController::update_last_active(cx, window.handle.id);
1478                    })
1479                    .log_err();
1480            }
1481        }));
1482        platform_window.on_hover_status_change(Box::new({
1483            let mut cx = cx.to_async();
1484            move |active| {
1485                handle
1486                    .update(&mut cx, |_, window, _| {
1487                        window.hovered.set(active);
1488                        window.refresh();
1489                    })
1490                    .log_err();
1491            }
1492        }));
1493        platform_window.on_input({
1494            let mut cx = cx.to_async();
1495            Box::new(move |event| {
1496                handle
1497                    .update(&mut cx, |_, window, cx| window.dispatch_event(event, cx))
1498                    .log_err()
1499                    .unwrap_or(DispatchEventResult::default())
1500            })
1501        });
1502        platform_window.on_hit_test_window_control({
1503            let mut cx = cx.to_async();
1504            Box::new(move || {
1505                handle
1506                    .update(&mut cx, |_, window, _cx| {
1507                        for (area, hitbox) in &window.rendered_frame.window_control_hitboxes {
1508                            if window.mouse_hit_test.ids.contains(&hitbox.id) {
1509                                return Some(*area);
1510                            }
1511                        }
1512                        None
1513                    })
1514                    .log_err()
1515                    .unwrap_or(None)
1516            })
1517        });
1518        platform_window.on_move_tab_to_new_window({
1519            let mut cx = cx.to_async();
1520            Box::new(move || {
1521                handle
1522                    .update(&mut cx, |_, _window, cx| {
1523                        SystemWindowTabController::move_tab_to_new_window(cx, handle.window_id());
1524                    })
1525                    .log_err();
1526            })
1527        });
1528        platform_window.on_merge_all_windows({
1529            let mut cx = cx.to_async();
1530            Box::new(move || {
1531                handle
1532                    .update(&mut cx, |_, _window, cx| {
1533                        SystemWindowTabController::merge_all_windows(cx, handle.window_id());
1534                    })
1535                    .log_err();
1536            })
1537        });
1538        platform_window.on_select_next_tab({
1539            let mut cx = cx.to_async();
1540            Box::new(move || {
1541                handle
1542                    .update(&mut cx, |_, _window, cx| {
1543                        SystemWindowTabController::select_next_tab(cx, handle.window_id());
1544                    })
1545                    .log_err();
1546            })
1547        });
1548        platform_window.on_select_previous_tab({
1549            let mut cx = cx.to_async();
1550            Box::new(move || {
1551                handle
1552                    .update(&mut cx, |_, _window, cx| {
1553                        SystemWindowTabController::select_previous_tab(cx, handle.window_id())
1554                    })
1555                    .log_err();
1556            })
1557        });
1558        platform_window.on_toggle_tab_bar({
1559            let mut cx = cx.to_async();
1560            Box::new(move || {
1561                handle
1562                    .update(&mut cx, |_, window, cx| {
1563                        let tab_bar_visible = window.platform_window.tab_bar_visible();
1564                        SystemWindowTabController::set_visible(cx, tab_bar_visible);
1565                    })
1566                    .log_err();
1567            })
1568        });
1569
1570        if let Some(app_id) = app_id {
1571            platform_window.set_app_id(&app_id);
1572        }
1573
1574        platform_window.map_window().unwrap();
1575
1576        Ok(Window {
1577            handle,
1578            invalidator,
1579            removed: false,
1580            platform_window,
1581            display_id,
1582            sprite_atlas,
1583            text_system,
1584            text_rendering_mode: cx.text_rendering_mode.clone(),
1585            rem_size: px(16.),
1586            rem_size_override_stack: SmallVec::new(),
1587            viewport_size: content_size,
1588            layout_engine: Some(TaffyLayoutEngine::new()),
1589            root: None,
1590            element_id_stack: SmallVec::default(),
1591            text_style_stack: Vec::new(),
1592            rendered_entity_stack: Vec::new(),
1593            element_offset_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        // Place it back into a None slot (left by a previous .take()) so that
2498        // cached paint_range indices in reuse_paint find the handler at the
2499        // expected position.
2500        if let Some(input_handler) = self.platform_window.take_input_handler() {
2501            if let Some(slot) = self
2502                .rendered_frame
2503                .input_handlers
2504                .iter_mut()
2505                .rev()
2506                .find(|h| h.is_none())
2507            {
2508                *slot = Some(input_handler);
2509            } else {
2510                self.rendered_frame.input_handlers.push(Some(input_handler));
2511            }
2512        }
2513        if !cx.mode.skip_drawing() {
2514            self.draw_roots(cx);
2515        }
2516        self.dirty_views.clear();
2517        self.next_frame.window_active = self.active.get();
2518
2519        // Register requested input handler with the platform window.
2520        // Use .take() instead of .pop() to preserve Vec length, so that cached
2521        // paint_range indices remain valid for reuse_paint on the next frame.
2522        // Search backwards to find the last Some entry, since reuse_paint may
2523        // have copied None slots from the previous frame. (Fixes #50456)
2524        if let Some(input_handler) = self
2525            .next_frame
2526            .input_handlers
2527            .iter_mut()
2528            .rev()
2529            .find_map(|h| h.take())
2530        {
2531            self.platform_window.set_input_handler(input_handler);
2532        }
2533
2534        self.layout_engine.as_mut().unwrap().clear();
2535        self.text_system().finish_frame();
2536        self.next_frame.finish(&mut self.rendered_frame);
2537
2538        self.invalidator.set_phase(DrawPhase::Focus);
2539        let previous_focus_path = self.rendered_frame.focus_path();
2540        let previous_window_active = self.rendered_frame.window_active;
2541        mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2542        self.next_frame.clear();
2543        let current_focus_path = self.rendered_frame.focus_path();
2544        let current_window_active = self.rendered_frame.window_active;
2545
2546        if previous_focus_path != current_focus_path
2547            || previous_window_active != current_window_active
2548        {
2549            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2550                self.focus_lost_listeners
2551                    .clone()
2552                    .retain(&(), |listener| listener(self, cx));
2553            }
2554
2555            let event = WindowFocusEvent {
2556                previous_focus_path: if previous_window_active {
2557                    previous_focus_path
2558                } else {
2559                    Default::default()
2560                },
2561                current_focus_path: if current_window_active {
2562                    current_focus_path
2563                } else {
2564                    Default::default()
2565                },
2566            };
2567            self.focus_listeners
2568                .clone()
2569                .retain(&(), |listener| listener(&event, self, cx));
2570        }
2571
2572        debug_assert!(self.rendered_entity_stack.is_empty());
2573        self.record_entities_accessed(cx);
2574        self.reset_cursor_style(cx);
2575        self.refreshing = false;
2576        self.invalidator.set_phase(DrawPhase::None);
2577        self.needs_present.set(true);
2578
2579        ArenaClearNeeded::new(&cx.element_arena)
2580    }
2581
2582    fn record_entities_accessed(&mut self, cx: &mut App) {
2583        let mut entities_ref = cx.entities.accessed_entities.get_mut();
2584        let mut entities = mem::take(entities_ref.deref_mut());
2585        let handle = self.handle;
2586        cx.record_entities_accessed(
2587            handle,
2588            // Try moving window invalidator into the Window
2589            self.invalidator.clone(),
2590            &entities,
2591        );
2592        let mut entities_ref = cx.entities.accessed_entities.get_mut();
2593        mem::swap(&mut entities, entities_ref.deref_mut());
2594    }
2595
2596    fn invalidate_entities(&mut self) {
2597        let mut views = self.invalidator.take_views();
2598        for entity in views.drain() {
2599            self.mark_view_dirty(entity);
2600        }
2601        self.invalidator.replace_views(views);
2602    }
2603
2604    #[profiling::function]
2605    fn present(&mut self) {
2606        self.platform_window.draw(&self.rendered_frame.scene);
2607        #[cfg(feature = "input-latency-histogram")]
2608        self.input_latency_tracker.record_frame_presented();
2609        self.needs_present.set(false);
2610        profiling::finish_frame!();
2611    }
2612
2613    /// Returns a snapshot of the current input-latency histograms.
2614    #[cfg(feature = "input-latency-histogram")]
2615    pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
2616        self.input_latency_tracker.snapshot()
2617    }
2618
2619    fn draw_roots(&mut self, cx: &mut App) {
2620        self.invalidator.set_phase(DrawPhase::Prepaint);
2621        self.tooltip_bounds.take();
2622
2623        let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
2624        let root_size = {
2625            #[cfg(any(feature = "inspector", debug_assertions))]
2626            {
2627                if self.inspector.is_some() {
2628                    let mut size = self.viewport_size;
2629                    size.width = (size.width - _inspector_width).max(px(0.0));
2630                    size
2631                } else {
2632                    self.viewport_size
2633                }
2634            }
2635            #[cfg(not(any(feature = "inspector", debug_assertions)))]
2636            {
2637                self.viewport_size
2638            }
2639        };
2640
2641        // Layout all root elements.
2642        let mut root_element = self.root.as_ref().unwrap().clone().into_any();
2643        root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2644
2645        #[cfg(any(feature = "inspector", debug_assertions))]
2646        let inspector_element = self.prepaint_inspector(_inspector_width, cx);
2647
2648        self.prepaint_deferred_draws(cx);
2649
2650        let mut prompt_element = None;
2651        let mut active_drag_element = None;
2652        let mut tooltip_element = None;
2653        if let Some(prompt) = self.prompt.take() {
2654            let mut element = prompt.view.any_view().into_any();
2655            element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2656            prompt_element = Some(element);
2657            self.prompt = Some(prompt);
2658        } else if let Some(active_drag) = cx.active_drag.take() {
2659            let mut element = active_drag.view.clone().into_any();
2660            let offset = self.mouse_position() - active_drag.cursor_offset;
2661            element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
2662            active_drag_element = Some(element);
2663            cx.active_drag = Some(active_drag);
2664        } else {
2665            tooltip_element = self.prepaint_tooltip(cx);
2666        }
2667
2668        self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
2669
2670        // Now actually paint the elements.
2671        self.invalidator.set_phase(DrawPhase::Paint);
2672        root_element.paint(self, cx);
2673
2674        #[cfg(any(feature = "inspector", debug_assertions))]
2675        self.paint_inspector(inspector_element, cx);
2676
2677        self.paint_deferred_draws(cx);
2678
2679        if let Some(mut prompt_element) = prompt_element {
2680            prompt_element.paint(self, cx);
2681        } else if let Some(mut drag_element) = active_drag_element {
2682            drag_element.paint(self, cx);
2683        } else if let Some(mut tooltip_element) = tooltip_element {
2684            tooltip_element.paint(self, cx);
2685        }
2686
2687        #[cfg(any(feature = "inspector", debug_assertions))]
2688        self.paint_inspector_hitbox(cx);
2689    }
2690
2691    fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
2692        // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
2693        for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
2694            let Some(Some(tooltip_request)) = self
2695                .next_frame
2696                .tooltip_requests
2697                .get(tooltip_request_index)
2698                .cloned()
2699            else {
2700                log::error!("Unexpectedly absent TooltipRequest");
2701                continue;
2702            };
2703            let mut element = tooltip_request.tooltip.view.clone().into_any();
2704            let mouse_position = tooltip_request.tooltip.mouse_position;
2705            let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
2706
2707            let mut tooltip_bounds =
2708                Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
2709            let window_bounds = Bounds {
2710                origin: Point::default(),
2711                size: self.viewport_size(),
2712            };
2713
2714            if tooltip_bounds.right() > window_bounds.right() {
2715                let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
2716                if new_x >= Pixels::ZERO {
2717                    tooltip_bounds.origin.x = new_x;
2718                } else {
2719                    tooltip_bounds.origin.x = cmp::max(
2720                        Pixels::ZERO,
2721                        tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
2722                    );
2723                }
2724            }
2725
2726            if tooltip_bounds.bottom() > window_bounds.bottom() {
2727                let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
2728                if new_y >= Pixels::ZERO {
2729                    tooltip_bounds.origin.y = new_y;
2730                } else {
2731                    tooltip_bounds.origin.y = cmp::max(
2732                        Pixels::ZERO,
2733                        tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
2734                    );
2735                }
2736            }
2737
2738            // It's possible for an element to have an active tooltip while not being painted (e.g.
2739            // via the `visible_on_hover` method). Since mouse listeners are not active in this
2740            // case, instead update the tooltip's visibility here.
2741            let is_visible =
2742                (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
2743            if !is_visible {
2744                continue;
2745            }
2746
2747            self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
2748                element.prepaint(window, cx)
2749            });
2750
2751            self.tooltip_bounds = Some(TooltipBounds {
2752                id: tooltip_request.id,
2753                bounds: tooltip_bounds,
2754            });
2755            return Some(element);
2756        }
2757        None
2758    }
2759
2760    fn prepaint_deferred_draws(&mut self, cx: &mut App) {
2761        assert_eq!(self.element_id_stack.len(), 0);
2762
2763        let mut completed_draws = Vec::new();
2764
2765        // Process deferred draws in multiple rounds to support nesting.
2766        // Each round processes all current deferred draws, which may produce new ones.
2767        let mut depth = 0;
2768        loop {
2769            // Limit maximum nesting depth to prevent infinite loops.
2770            assert!(depth < 10, "Exceeded maximum (10) deferred depth");
2771            depth += 1;
2772            let deferred_count = self.next_frame.deferred_draws.len();
2773            if deferred_count == 0 {
2774                break;
2775            }
2776
2777            // Sort by priority for this round
2778            let traversal_order = self.deferred_draw_traversal_order();
2779            let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2780
2781            for deferred_draw_ix in traversal_order {
2782                let deferred_draw = &mut deferred_draws[deferred_draw_ix];
2783                self.element_id_stack
2784                    .clone_from(&deferred_draw.element_id_stack);
2785                self.text_style_stack
2786                    .clone_from(&deferred_draw.text_style_stack);
2787                self.next_frame
2788                    .dispatch_tree
2789                    .set_active_node(deferred_draw.parent_node);
2790
2791                let prepaint_start = self.prepaint_index();
2792                if let Some(element) = deferred_draw.element.as_mut() {
2793                    self.with_rendered_view(deferred_draw.current_view, |window| {
2794                        window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2795                            window.with_absolute_element_offset(
2796                                deferred_draw.absolute_offset,
2797                                |window| {
2798                                    element.prepaint(window, cx);
2799                                },
2800                            );
2801                        });
2802                    })
2803                } else {
2804                    self.reuse_prepaint(deferred_draw.prepaint_range.clone());
2805                }
2806                let prepaint_end = self.prepaint_index();
2807                deferred_draw.prepaint_range = prepaint_start..prepaint_end;
2808            }
2809
2810            // Save completed draws and continue with newly added ones
2811            completed_draws.append(&mut deferred_draws);
2812
2813            self.element_id_stack.clear();
2814            self.text_style_stack.clear();
2815        }
2816
2817        // Restore all completed draws
2818        self.next_frame.deferred_draws = completed_draws;
2819    }
2820
2821    fn paint_deferred_draws(&mut self, cx: &mut App) {
2822        assert_eq!(self.element_id_stack.len(), 0);
2823
2824        // Paint all deferred draws in priority order.
2825        // Since prepaint has already processed nested deferreds, we just paint them all.
2826        if self.next_frame.deferred_draws.len() == 0 {
2827            return;
2828        }
2829
2830        let traversal_order = self.deferred_draw_traversal_order();
2831        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2832        for deferred_draw_ix in traversal_order {
2833            let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
2834            self.element_id_stack
2835                .clone_from(&deferred_draw.element_id_stack);
2836            self.next_frame
2837                .dispatch_tree
2838                .set_active_node(deferred_draw.parent_node);
2839
2840            let paint_start = self.paint_index();
2841            let content_mask = deferred_draw.content_mask;
2842            if let Some(element) = deferred_draw.element.as_mut() {
2843                self.with_rendered_view(deferred_draw.current_view, |window| {
2844                    window.with_content_mask(content_mask, |window| {
2845                        window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2846                            element.paint(window, cx);
2847                        });
2848                    })
2849                })
2850            } else {
2851                self.reuse_paint(deferred_draw.paint_range.clone());
2852            }
2853            let paint_end = self.paint_index();
2854            deferred_draw.paint_range = paint_start..paint_end;
2855        }
2856        self.next_frame.deferred_draws = deferred_draws;
2857        self.element_id_stack.clear();
2858    }
2859
2860    fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
2861        let deferred_count = self.next_frame.deferred_draws.len();
2862        let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
2863        sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
2864        sorted_indices
2865    }
2866
2867    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
2868        PrepaintStateIndex {
2869            hitboxes_index: self.next_frame.hitboxes.len(),
2870            tooltips_index: self.next_frame.tooltip_requests.len(),
2871            deferred_draws_index: self.next_frame.deferred_draws.len(),
2872            dispatch_tree_index: self.next_frame.dispatch_tree.len(),
2873            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2874            line_layout_index: self.text_system.layout_index(),
2875        }
2876    }
2877
2878    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
2879        self.next_frame.hitboxes.extend(
2880            self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
2881                .iter()
2882                .cloned(),
2883        );
2884        self.next_frame.tooltip_requests.extend(
2885            self.rendered_frame.tooltip_requests
2886                [range.start.tooltips_index..range.end.tooltips_index]
2887                .iter_mut()
2888                .map(|request| request.take()),
2889        );
2890        self.next_frame.accessed_element_states.extend(
2891            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2892                ..range.end.accessed_element_states_index]
2893                .iter()
2894                .map(|(id, type_id)| (id.clone(), *type_id)),
2895        );
2896        self.text_system
2897            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2898
2899        let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
2900            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
2901            &mut self.rendered_frame.dispatch_tree,
2902            self.focus,
2903        );
2904
2905        if reused_subtree.contains_focus() {
2906            self.next_frame.focus = self.focus;
2907        }
2908
2909        self.next_frame.deferred_draws.extend(
2910            self.rendered_frame.deferred_draws
2911                [range.start.deferred_draws_index..range.end.deferred_draws_index]
2912                .iter()
2913                .map(|deferred_draw| DeferredDraw {
2914                    current_view: deferred_draw.current_view,
2915                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
2916                    element_id_stack: deferred_draw.element_id_stack.clone(),
2917                    text_style_stack: deferred_draw.text_style_stack.clone(),
2918                    content_mask: deferred_draw.content_mask,
2919                    rem_size: deferred_draw.rem_size,
2920                    priority: deferred_draw.priority,
2921                    element: None,
2922                    absolute_offset: deferred_draw.absolute_offset,
2923                    prepaint_range: deferred_draw.prepaint_range.clone(),
2924                    paint_range: deferred_draw.paint_range.clone(),
2925                }),
2926        );
2927    }
2928
2929    pub(crate) fn paint_index(&self) -> PaintIndex {
2930        PaintIndex {
2931            scene_index: self.next_frame.scene.len(),
2932            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
2933            input_handlers_index: self.next_frame.input_handlers.len(),
2934            cursor_styles_index: self.next_frame.cursor_styles.len(),
2935            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2936            tab_handle_index: self.next_frame.tab_stops.paint_index(),
2937            line_layout_index: self.text_system.layout_index(),
2938        }
2939    }
2940
2941    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
2942        self.next_frame.cursor_styles.extend(
2943            self.rendered_frame.cursor_styles
2944                [range.start.cursor_styles_index..range.end.cursor_styles_index]
2945                .iter()
2946                .cloned(),
2947        );
2948        self.next_frame.input_handlers.extend(
2949            self.rendered_frame.input_handlers
2950                [range.start.input_handlers_index..range.end.input_handlers_index]
2951                .iter_mut()
2952                .map(|handler| handler.take()),
2953        );
2954        self.next_frame.mouse_listeners.extend(
2955            self.rendered_frame.mouse_listeners
2956                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
2957                .iter_mut()
2958                .map(|listener| listener.take()),
2959        );
2960        self.next_frame.accessed_element_states.extend(
2961            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2962                ..range.end.accessed_element_states_index]
2963                .iter()
2964                .map(|(id, type_id)| (id.clone(), *type_id)),
2965        );
2966        self.next_frame.tab_stops.replay(
2967            &self.rendered_frame.tab_stops.insertion_history
2968                [range.start.tab_handle_index..range.end.tab_handle_index],
2969        );
2970
2971        self.text_system
2972            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2973        self.next_frame.scene.replay(
2974            range.start.scene_index..range.end.scene_index,
2975            &self.rendered_frame.scene,
2976        );
2977    }
2978
2979    /// Push a text style onto the stack, and call a function with that style active.
2980    /// Use [`Window::text_style`] to get the current, combined text style. This method
2981    /// should only be called as part of element drawing.
2982    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
2983    where
2984        F: FnOnce(&mut Self) -> R,
2985    {
2986        self.invalidator.debug_assert_paint_or_prepaint();
2987        if let Some(style) = style {
2988            self.text_style_stack.push(style);
2989            let result = f(self);
2990            self.text_style_stack.pop();
2991            result
2992        } else {
2993            f(self)
2994        }
2995    }
2996
2997    /// Updates the cursor style at the platform level. This method should only be called
2998    /// during the paint phase of element drawing.
2999    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
3000        self.invalidator.debug_assert_paint();
3001        self.next_frame.cursor_styles.push(CursorStyleRequest {
3002            hitbox_id: Some(hitbox.id),
3003            style,
3004        });
3005    }
3006
3007    /// Updates the cursor style for the entire window at the platform level. A cursor
3008    /// style using this method will have precedence over any cursor style set using
3009    /// `set_cursor_style`. This method should only be called during the paint
3010    /// phase of element drawing.
3011    pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
3012        self.invalidator.debug_assert_paint();
3013        self.next_frame.cursor_styles.push(CursorStyleRequest {
3014            hitbox_id: None,
3015            style,
3016        })
3017    }
3018
3019    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
3020    /// during the paint phase of element drawing.
3021    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
3022        self.invalidator.debug_assert_prepaint();
3023        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
3024        self.next_frame
3025            .tooltip_requests
3026            .push(Some(TooltipRequest { id, tooltip }));
3027        id
3028    }
3029
3030    /// Invoke the given function with the given content mask after intersecting it
3031    /// with the current mask. This method should only be called during element drawing.
3032    // This function is called in a highly recursive manner in editor
3033    // prepainting, make sure its inlined to reduce the stack burden
3034    #[inline]
3035    pub fn with_content_mask<R>(
3036        &mut self,
3037        mask: Option<ContentMask<Pixels>>,
3038        f: impl FnOnce(&mut Self) -> R,
3039    ) -> R {
3040        self.invalidator.debug_assert_paint_or_prepaint();
3041        if let Some(mask) = mask {
3042            let mask = mask.intersect(&self.content_mask());
3043            self.content_mask_stack.push(mask);
3044            let result = f(self);
3045            self.content_mask_stack.pop();
3046            result
3047        } else {
3048            f(self)
3049        }
3050    }
3051
3052    /// Updates the global element offset relative to the current offset. This is used to implement
3053    /// scrolling. This method should only be called during the prepaint phase of element drawing.
3054    pub fn with_element_offset<R>(
3055        &mut self,
3056        offset: Point<Pixels>,
3057        f: impl FnOnce(&mut Self) -> R,
3058    ) -> R {
3059        self.invalidator.debug_assert_prepaint();
3060
3061        if offset.is_zero() {
3062            return f(self);
3063        };
3064
3065        let abs_offset = self.element_offset() + offset;
3066        self.with_absolute_element_offset(abs_offset, f)
3067    }
3068
3069    /// Updates the global element offset based on the given offset. This is used to implement
3070    /// drag handles and other manual painting of elements. This method should only be called during
3071    /// the prepaint phase of element drawing.
3072    pub fn with_absolute_element_offset<R>(
3073        &mut self,
3074        offset: Point<Pixels>,
3075        f: impl FnOnce(&mut Self) -> R,
3076    ) -> R {
3077        self.invalidator.debug_assert_prepaint();
3078        self.element_offset_stack.push(offset);
3079        let result = f(self);
3080        self.element_offset_stack.pop();
3081        result
3082    }
3083
3084    pub(crate) fn with_element_opacity<R>(
3085        &mut self,
3086        opacity: Option<f32>,
3087        f: impl FnOnce(&mut Self) -> R,
3088    ) -> R {
3089        self.invalidator.debug_assert_paint_or_prepaint();
3090
3091        let Some(opacity) = opacity else {
3092            return f(self);
3093        };
3094
3095        let previous_opacity = self.element_opacity;
3096        self.element_opacity = previous_opacity * opacity;
3097        let result = f(self);
3098        self.element_opacity = previous_opacity;
3099        result
3100    }
3101
3102    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
3103    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
3104    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
3105    /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
3106    /// called during the prepaint phase of element drawing.
3107    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
3108        self.invalidator.debug_assert_prepaint();
3109        let index = self.prepaint_index();
3110        let result = f(self);
3111        if result.is_err() {
3112            self.next_frame.hitboxes.truncate(index.hitboxes_index);
3113            self.next_frame
3114                .tooltip_requests
3115                .truncate(index.tooltips_index);
3116            self.next_frame
3117                .deferred_draws
3118                .truncate(index.deferred_draws_index);
3119            self.next_frame
3120                .dispatch_tree
3121                .truncate(index.dispatch_tree_index);
3122            self.next_frame
3123                .accessed_element_states
3124                .truncate(index.accessed_element_states_index);
3125            self.text_system.truncate_layouts(index.line_layout_index);
3126        }
3127        result
3128    }
3129
3130    /// When you call this method during [`Element::prepaint`], containing elements will attempt to
3131    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
3132    /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
3133    /// that supports this method being called on the elements it contains. This method should only be
3134    /// called during the prepaint phase of element drawing.
3135    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
3136        self.invalidator.debug_assert_prepaint();
3137        self.requested_autoscroll = Some(bounds);
3138    }
3139
3140    /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
3141    /// described in [`Self::request_autoscroll`].
3142    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
3143        self.invalidator.debug_assert_prepaint();
3144        self.requested_autoscroll.take()
3145    }
3146
3147    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
3148    /// Your view will be re-drawn once the asset has finished loading.
3149    ///
3150    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
3151    /// time.
3152    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3153        let (task, is_first) = cx.fetch_asset::<A>(source);
3154        task.clone().now_or_never().or_else(|| {
3155            if is_first {
3156                let entity_id = self.current_view();
3157                self.spawn(cx, {
3158                    let task = task.clone();
3159                    async move |cx| {
3160                        task.await;
3161
3162                        cx.on_next_frame(move |_, cx| {
3163                            cx.notify(entity_id);
3164                        });
3165                    }
3166                })
3167                .detach();
3168            }
3169
3170            None
3171        })
3172    }
3173
3174    /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
3175    /// Your view will not be re-drawn once the asset has finished loading.
3176    ///
3177    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
3178    /// time.
3179    pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3180        let (task, _) = cx.fetch_asset::<A>(source);
3181        task.now_or_never()
3182    }
3183    /// Obtain the current element offset. This method should only be called during the
3184    /// prepaint phase of element drawing.
3185    pub fn element_offset(&self) -> Point<Pixels> {
3186        self.invalidator.debug_assert_prepaint();
3187        self.element_offset_stack
3188            .last()
3189            .copied()
3190            .unwrap_or_default()
3191    }
3192
3193    /// Obtain the current element opacity. This method should only be called during the
3194    /// prepaint phase of element drawing.
3195    #[inline]
3196    pub(crate) fn element_opacity(&self) -> f32 {
3197        self.invalidator.debug_assert_paint_or_prepaint();
3198        self.element_opacity
3199    }
3200
3201    /// Obtain the current content mask. This method should only be called during element drawing.
3202    pub fn content_mask(&self) -> ContentMask<Pixels> {
3203        self.invalidator.debug_assert_paint_or_prepaint();
3204        self.content_mask_stack
3205            .last()
3206            .cloned()
3207            .unwrap_or_else(|| ContentMask {
3208                bounds: Bounds {
3209                    origin: Point::default(),
3210                    size: self.viewport_size,
3211                },
3212            })
3213    }
3214
3215    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
3216    /// This can be used within a custom element to distinguish multiple sets of child elements.
3217    pub fn with_element_namespace<R>(
3218        &mut self,
3219        element_id: impl Into<ElementId>,
3220        f: impl FnOnce(&mut Self) -> R,
3221    ) -> R {
3222        self.element_id_stack.push(element_id.into());
3223        let result = f(self);
3224        self.element_id_stack.pop();
3225        result
3226    }
3227
3228    /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
3229    pub fn use_keyed_state<S: 'static>(
3230        &mut self,
3231        key: impl Into<ElementId>,
3232        cx: &mut App,
3233        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3234    ) -> Entity<S> {
3235        let current_view = self.current_view();
3236        self.with_global_id(key.into(), |global_id, window| {
3237            window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
3238                if let Some(state) = state {
3239                    (state.clone(), state)
3240                } else {
3241                    let new_state = cx.new(|cx| init(window, cx));
3242                    cx.observe(&new_state, move |_, cx| {
3243                        cx.notify(current_view);
3244                    })
3245                    .detach();
3246                    (new_state.clone(), new_state)
3247                }
3248            })
3249        })
3250    }
3251
3252    /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
3253    ///
3254    /// NOTE: This method uses the location of the caller to generate an ID for this state.
3255    ///       If this is not sufficient to identify your state (e.g. you're rendering a list item),
3256    ///       you can provide a custom ElementID using the `use_keyed_state` method.
3257    #[track_caller]
3258    pub fn use_state<S: 'static>(
3259        &mut self,
3260        cx: &mut App,
3261        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3262    ) -> Entity<S> {
3263        self.use_keyed_state(
3264            ElementId::CodeLocation(*core::panic::Location::caller()),
3265            cx,
3266            init,
3267        )
3268    }
3269
3270    /// Updates or initializes state for an element with the given id that lives across multiple
3271    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
3272    /// to the given closure. The state returned by the closure will be stored so it can be referenced
3273    /// when drawing the next frame. This method should only be called as part of element drawing.
3274    pub fn with_element_state<S, R>(
3275        &mut self,
3276        global_id: &GlobalElementId,
3277        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
3278    ) -> R
3279    where
3280        S: 'static,
3281    {
3282        self.invalidator.debug_assert_paint_or_prepaint();
3283
3284        let key = (global_id.clone(), TypeId::of::<S>());
3285        self.next_frame.accessed_element_states.push(key.clone());
3286
3287        if let Some(any) = self
3288            .next_frame
3289            .element_states
3290            .remove(&key)
3291            .or_else(|| self.rendered_frame.element_states.remove(&key))
3292        {
3293            let ElementStateBox {
3294                inner,
3295                #[cfg(debug_assertions)]
3296                type_name,
3297            } = any;
3298            // Using the extra inner option to avoid needing to reallocate a new box.
3299            let mut state_box = inner
3300                .downcast::<Option<S>>()
3301                .map_err(|_| {
3302                    #[cfg(debug_assertions)]
3303                    {
3304                        anyhow::anyhow!(
3305                            "invalid element state type for id, requested {:?}, actual: {:?}",
3306                            std::any::type_name::<S>(),
3307                            type_name
3308                        )
3309                    }
3310
3311                    #[cfg(not(debug_assertions))]
3312                    {
3313                        anyhow::anyhow!(
3314                            "invalid element state type for id, requested {:?}",
3315                            std::any::type_name::<S>(),
3316                        )
3317                    }
3318                })
3319                .unwrap();
3320
3321            let state = state_box.take().expect(
3322                "reentrant call to with_element_state for the same state type and element id",
3323            );
3324            let (result, state) = f(Some(state), self);
3325            state_box.replace(state);
3326            self.next_frame.element_states.insert(
3327                key,
3328                ElementStateBox {
3329                    inner: state_box,
3330                    #[cfg(debug_assertions)]
3331                    type_name,
3332                },
3333            );
3334            result
3335        } else {
3336            let (result, state) = f(None, self);
3337            self.next_frame.element_states.insert(
3338                key,
3339                ElementStateBox {
3340                    inner: Box::new(Some(state)),
3341                    #[cfg(debug_assertions)]
3342                    type_name: std::any::type_name::<S>(),
3343                },
3344            );
3345            result
3346        }
3347    }
3348
3349    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
3350    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
3351    /// when the element is guaranteed to have an id.
3352    ///
3353    /// The first option means 'no ID provided'
3354    /// The second option means 'not yet initialized'
3355    pub fn with_optional_element_state<S, R>(
3356        &mut self,
3357        global_id: Option<&GlobalElementId>,
3358        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
3359    ) -> R
3360    where
3361        S: 'static,
3362    {
3363        self.invalidator.debug_assert_paint_or_prepaint();
3364
3365        if let Some(global_id) = global_id {
3366            self.with_element_state(global_id, |state, cx| {
3367                let (result, state) = f(Some(state), cx);
3368                let state =
3369                    state.expect("you must return some state when you pass some element id");
3370                (result, state)
3371            })
3372        } else {
3373            let (result, state) = f(None, self);
3374            debug_assert!(
3375                state.is_none(),
3376                "you must not return an element state when passing None for the global id"
3377            );
3378            result
3379        }
3380    }
3381
3382    /// Executes the given closure within the context of a tab group.
3383    #[inline]
3384    pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
3385        if let Some(index) = index {
3386            self.next_frame.tab_stops.begin_group(index);
3387            let result = f(self);
3388            self.next_frame.tab_stops.end_group();
3389            result
3390        } else {
3391            f(self)
3392        }
3393    }
3394
3395    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
3396    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
3397    /// with higher values being drawn on top.
3398    ///
3399    /// When `content_mask` is provided, the deferred element will be clipped to that region during
3400    /// both prepaint and paint. When `None`, no additional clipping is applied.
3401    ///
3402    /// This method should only be called as part of the prepaint phase of element drawing.
3403    pub fn defer_draw(
3404        &mut self,
3405        element: AnyElement,
3406        absolute_offset: Point<Pixels>,
3407        priority: usize,
3408        content_mask: Option<ContentMask<Pixels>>,
3409    ) {
3410        self.invalidator.debug_assert_prepaint();
3411        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3412        self.next_frame.deferred_draws.push(DeferredDraw {
3413            current_view: self.current_view(),
3414            parent_node,
3415            element_id_stack: self.element_id_stack.clone(),
3416            text_style_stack: self.text_style_stack.clone(),
3417            content_mask,
3418            rem_size: self.rem_size(),
3419            priority,
3420            element: Some(element),
3421            absolute_offset,
3422            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3423            paint_range: PaintIndex::default()..PaintIndex::default(),
3424        });
3425    }
3426
3427    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
3428    /// of geometry that are non-overlapping and have the same draw order. This is typically used
3429    /// for performance reasons.
3430    ///
3431    /// This method should only be called as part of the paint phase of element drawing.
3432    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3433        self.invalidator.debug_assert_paint();
3434
3435        let content_mask = self.content_mask();
3436        let clipped_bounds = bounds.intersect(&content_mask.bounds);
3437        if !clipped_bounds.is_empty() {
3438            self.next_frame
3439                .scene
3440                .push_layer(self.cover_bounds(clipped_bounds));
3441        }
3442
3443        let result = f(self);
3444
3445        if !clipped_bounds.is_empty() {
3446            self.next_frame.scene.pop_layer();
3447        }
3448
3449        result
3450    }
3451
3452    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
3453    ///
3454    /// This method should only be called as part of the paint phase of element drawing.
3455    pub fn paint_shadows(
3456        &mut self,
3457        bounds: Bounds<Pixels>,
3458        corner_radii: Corners<Pixels>,
3459        shadows: &[BoxShadow],
3460    ) {
3461        self.invalidator.debug_assert_paint();
3462
3463        let scale_factor = self.scale_factor();
3464        let content_mask = self.snapped_content_mask();
3465        let opacity = self.element_opacity();
3466        for shadow in shadows {
3467            let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3468            self.next_frame.scene.insert_primitive(Shadow {
3469                order: 0,
3470                blur_radius: shadow.blur_radius.scale(scale_factor),
3471                bounds: self.cover_bounds(shadow_bounds),
3472                content_mask,
3473                corner_radii: corner_radii.scale(scale_factor),
3474                color: shadow.color.opacity(opacity),
3475            });
3476        }
3477    }
3478
3479    /// Paint one or more quads into the scene for the next frame at the current stacking context.
3480    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
3481    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
3482    ///
3483    /// This method should only be called as part of the paint phase of element drawing.
3484    ///
3485    /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
3486    /// where the circular arcs meet. This will not display well when combined with dashed borders.
3487    /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
3488    pub fn paint_quad(&mut self, quad: PaintQuad) {
3489        self.invalidator.debug_assert_paint();
3490
3491        let opacity = self.element_opacity();
3492        let snapped_bounds = self.snap_bounds(quad.bounds);
3493        let snapped_border_widths = self.snap_border_widths(quad.border_widths);
3494        self.next_frame.scene.insert_primitive(Quad {
3495            order: 0,
3496            bounds: snapped_bounds,
3497            content_mask: self.snapped_content_mask(),
3498            background: quad.background.opacity(opacity),
3499            border_color: quad.border_color.opacity(opacity),
3500            corner_radii: quad.corner_radii.scale(self.scale_factor()),
3501            border_widths: snapped_border_widths,
3502            border_style: quad.border_style,
3503        });
3504    }
3505
3506    /// Paint the given `Path` into the scene for the next frame at the current z-index.
3507    ///
3508    /// This method should only be called as part of the paint phase of element drawing.
3509    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
3510        self.invalidator.debug_assert_paint();
3511
3512        let scale_factor = self.scale_factor();
3513        let content_mask = self.content_mask();
3514        let opacity = self.element_opacity();
3515        path.content_mask = content_mask;
3516        let color: Background = color.into();
3517        path.color = color.opacity(opacity);
3518        self.next_frame
3519            .scene
3520            .insert_primitive(path.scale(scale_factor));
3521    }
3522
3523    /// Paint an underline into the scene for the next frame at the current z-index.
3524    ///
3525    /// This method should only be called as part of the paint phase of element drawing.
3526    pub fn paint_underline(
3527        &mut self,
3528        origin: Point<Pixels>,
3529        width: Pixels,
3530        style: &UnderlineStyle,
3531    ) {
3532        self.invalidator.debug_assert_paint();
3533
3534        let scale_factor = self.scale_factor();
3535        let thickness = self.snap_stroke(style.thickness);
3536        let height = if style.wavy {
3537            ScaledPixels(thickness.0 * 3.)
3538        } else {
3539            thickness
3540        };
3541        let bounds = Bounds {
3542            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3543            size: size(self.snap_stroke(width), height),
3544        };
3545        let element_opacity = self.element_opacity();
3546
3547        self.next_frame.scene.insert_primitive(Underline {
3548            order: 0,
3549            pad: 0,
3550            bounds,
3551            content_mask: self.snapped_content_mask(),
3552            color: style.color.unwrap_or_default().opacity(element_opacity),
3553            thickness,
3554            wavy: if style.wavy { 1 } else { 0 },
3555        });
3556    }
3557
3558    /// Paint a strikethrough into the scene for the next frame at the current z-index.
3559    ///
3560    /// This method should only be called as part of the paint phase of element drawing.
3561    pub fn paint_strikethrough(
3562        &mut self,
3563        origin: Point<Pixels>,
3564        width: Pixels,
3565        style: &StrikethroughStyle,
3566    ) {
3567        self.invalidator.debug_assert_paint();
3568
3569        let scale_factor = self.scale_factor();
3570        let height = style.thickness;
3571        let bounds = Bounds {
3572            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3573            size: size(self.snap_stroke(width), self.snap_stroke(height)),
3574        };
3575        let opacity = self.element_opacity();
3576
3577        self.next_frame.scene.insert_primitive(Underline {
3578            order: 0,
3579            pad: 0,
3580            bounds,
3581            content_mask: self.snapped_content_mask(),
3582            thickness: self.snap_stroke(style.thickness),
3583            color: style.color.unwrap_or_default().opacity(opacity),
3584            wavy: 0,
3585        });
3586    }
3587
3588    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
3589    ///
3590    /// The y component of the origin is the baseline of the glyph.
3591    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3592    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3593    /// This method is only useful if you need to paint a single glyph that has already been shaped.
3594    ///
3595    /// This method should only be called as part of the paint phase of element drawing.
3596    pub fn paint_glyph(
3597        &mut self,
3598        origin: Point<Pixels>,
3599        font_id: FontId,
3600        glyph_id: GlyphId,
3601        font_size: Pixels,
3602        color: Hsla,
3603    ) -> Result<()> {
3604        self.invalidator.debug_assert_paint();
3605
3606        let element_opacity = self.element_opacity();
3607        let scale_factor = self.scale_factor();
3608        let glyph_origin = origin.scale(scale_factor);
3609
3610        let quantized_origin = Point::new(
3611            round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
3612                / SUBPIXEL_VARIANTS_X as f32,
3613            round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
3614                / SUBPIXEL_VARIANTS_Y as f32,
3615        );
3616        let subpixel_variant = Point::new(
3617            (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
3618            (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
3619        );
3620        let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
3621        let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
3622        let dilation = self.text_system().glyph_dilation_for_color(color);
3623        let params = RenderGlyphParams {
3624            font_id,
3625            glyph_id,
3626            font_size,
3627            subpixel_variant,
3628            scale_factor,
3629            is_emoji: false,
3630            subpixel_rendering,
3631            dilation,
3632        };
3633
3634        let raster_bounds = self.text_system().raster_bounds(&params)?;
3635        if !raster_bounds.is_zero() {
3636            let tile = self
3637                .sprite_atlas
3638                .get_or_insert_with(&params.clone().into(), &mut || {
3639                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3640                    Ok(Some((size, Cow::Owned(bytes))))
3641                })?
3642                .expect("Callback above only errors or returns Some");
3643            let bounds = Bounds {
3644                origin: integer_origin + raster_bounds.origin.map(Into::into),
3645                size: tile.bounds.size.map(Into::into),
3646            };
3647            let content_mask = self.snapped_content_mask();
3648
3649            if subpixel_rendering {
3650                self.next_frame.scene.insert_primitive(SubpixelSprite {
3651                    order: 0,
3652                    pad: 0,
3653                    bounds,
3654                    content_mask,
3655                    color: color.opacity(element_opacity),
3656                    tile,
3657                    transformation: TransformationMatrix::unit(),
3658                });
3659            } else {
3660                self.next_frame.scene.insert_primitive(MonochromeSprite {
3661                    order: 0,
3662                    pad: 0,
3663                    bounds,
3664                    content_mask,
3665                    color: color.opacity(element_opacity),
3666                    tile,
3667                    transformation: TransformationMatrix::unit(),
3668                });
3669            }
3670        }
3671        Ok(())
3672    }
3673
3674    fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
3675        if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
3676            return false;
3677        }
3678
3679        if !self.platform_window.is_subpixel_rendering_supported() {
3680            return false;
3681        }
3682
3683        let mode = match self.text_rendering_mode.get() {
3684            TextRenderingMode::PlatformDefault => self
3685                .text_system()
3686                .recommended_rendering_mode(font_id, font_size),
3687            mode => mode,
3688        };
3689
3690        mode == TextRenderingMode::Subpixel
3691    }
3692
3693    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
3694    ///
3695    /// The y component of the origin is the baseline of the glyph.
3696    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3697    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3698    /// This method is only useful if you need to paint a single emoji that has already been shaped.
3699    ///
3700    /// This method should only be called as part of the paint phase of element drawing.
3701    pub fn paint_emoji(
3702        &mut self,
3703        origin: Point<Pixels>,
3704        font_id: FontId,
3705        glyph_id: GlyphId,
3706        font_size: Pixels,
3707    ) -> Result<()> {
3708        self.invalidator.debug_assert_paint();
3709
3710        let scale_factor = self.scale_factor();
3711        let glyph_origin = origin.scale(scale_factor);
3712        let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
3713        let params = RenderGlyphParams {
3714            font_id,
3715            glyph_id,
3716            font_size,
3717            subpixel_variant: Default::default(),
3718            scale_factor,
3719            is_emoji: true,
3720            subpixel_rendering: false,
3721            dilation: 0,
3722        };
3723
3724        let raster_bounds = self.text_system().raster_bounds(&params)?;
3725        if !raster_bounds.is_zero() {
3726            let tile = self
3727                .sprite_atlas
3728                .get_or_insert_with(&params.clone().into(), &mut || {
3729                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3730                    Ok(Some((size, Cow::Owned(bytes))))
3731                })?
3732                .expect("Callback above only errors or returns Some");
3733
3734            let bounds = Bounds {
3735                origin: integer_origin + raster_bounds.origin.map(Into::into),
3736                size: tile.bounds.size.map(Into::into),
3737            };
3738            let content_mask = self.snapped_content_mask();
3739            let opacity = self.element_opacity();
3740
3741            self.next_frame.scene.insert_primitive(PolychromeSprite {
3742                order: 0,
3743                pad: 0,
3744                grayscale: false,
3745                bounds,
3746                corner_radii: Default::default(),
3747                content_mask,
3748                tile,
3749                opacity,
3750            });
3751        }
3752        Ok(())
3753    }
3754
3755    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
3756    ///
3757    /// This method should only be called as part of the paint phase of element drawing.
3758    pub fn paint_svg(
3759        &mut self,
3760        bounds: Bounds<Pixels>,
3761        path: SharedString,
3762        mut data: Option<&[u8]>,
3763        transformation: TransformationMatrix,
3764        color: Hsla,
3765        cx: &App,
3766    ) -> Result<()> {
3767        self.invalidator.debug_assert_paint();
3768
3769        let element_opacity = self.element_opacity();
3770        let bounds = self.snap_bounds(bounds);
3771
3772        let params = RenderSvgParams {
3773            path,
3774            size: bounds.size.map(|pixels| {
3775                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
3776            }),
3777        };
3778
3779        let Some(tile) =
3780            self.sprite_atlas
3781                .get_or_insert_with(&params.clone().into(), &mut || {
3782                    let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(&params, data)?
3783                    else {
3784                        return Ok(None);
3785                    };
3786                    Ok(Some((size, Cow::Owned(bytes))))
3787                })?
3788        else {
3789            return Ok(());
3790        };
3791        let content_mask = self.snapped_content_mask();
3792        let svg_bounds = Bounds {
3793            origin: bounds.center()
3794                - Point::new(
3795                    ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3796                    ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3797                ),
3798            size: tile
3799                .bounds
3800                .size
3801                .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
3802        };
3803        let final_bounds = svg_bounds
3804            .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
3805            .map_size(|size| size.ceil());
3806
3807        self.next_frame.scene.insert_primitive(MonochromeSprite {
3808            order: 0,
3809            pad: 0,
3810            bounds: final_bounds,
3811            content_mask,
3812            color: color.opacity(element_opacity),
3813            tile,
3814            transformation,
3815        });
3816
3817        Ok(())
3818    }
3819
3820    /// Paint an image into the scene for the next frame at the current z-index.
3821    /// This method will panic if the frame_index is not valid
3822    ///
3823    /// This method should only be called as part of the paint phase of element drawing.
3824    pub fn paint_image(
3825        &mut self,
3826        bounds: Bounds<Pixels>,
3827        corner_radii: Corners<Pixels>,
3828        data: Arc<RenderImage>,
3829        frame_index: usize,
3830        grayscale: bool,
3831    ) -> Result<()> {
3832        self.invalidator.debug_assert_paint();
3833
3834        let bounds = self.snap_bounds(bounds);
3835        let params = RenderImageParams {
3836            image_id: data.id,
3837            frame_index,
3838        };
3839
3840        let tile = self
3841            .sprite_atlas
3842            .get_or_insert_with(&params.into(), &mut || {
3843                Ok(Some((
3844                    data.size(frame_index),
3845                    Cow::Borrowed(
3846                        data.as_bytes(frame_index)
3847                            .expect("It's the caller's job to pass a valid frame index"),
3848                    ),
3849                )))
3850            })?
3851            .expect("Callback above only returns Some");
3852        let content_mask = self.snapped_content_mask();
3853        let corner_radii = corner_radii.scale(self.scale_factor());
3854        let opacity = self.element_opacity();
3855
3856        self.next_frame.scene.insert_primitive(PolychromeSprite {
3857            order: 0,
3858            pad: 0,
3859            grayscale,
3860            bounds,
3861            content_mask,
3862            corner_radii,
3863            tile,
3864            opacity,
3865        });
3866        Ok(())
3867    }
3868
3869    /// Paint a surface into the scene for the next frame at the current z-index.
3870    ///
3871    /// This method should only be called as part of the paint phase of element drawing.
3872    #[cfg(target_os = "macos")]
3873    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
3874        use crate::PaintSurface;
3875
3876        self.invalidator.debug_assert_paint();
3877
3878        let bounds = self.snap_bounds(bounds);
3879        let content_mask = self.snapped_content_mask();
3880        self.next_frame.scene.insert_primitive(PaintSurface {
3881            order: 0,
3882            bounds,
3883            content_mask,
3884            image_buffer,
3885        });
3886    }
3887
3888    /// Removes an image from the sprite atlas.
3889    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
3890        for frame_index in 0..data.frame_count() {
3891            let params = RenderImageParams {
3892                image_id: data.id,
3893                frame_index,
3894            };
3895
3896            self.sprite_atlas.remove(&params.clone().into());
3897        }
3898
3899        Ok(())
3900    }
3901
3902    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
3903    /// layout is being requested, along with the layout ids of any children. This method is called during
3904    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
3905    ///
3906    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3907    #[must_use]
3908    pub fn request_layout(
3909        &mut self,
3910        style: Style,
3911        children: impl IntoIterator<Item = LayoutId>,
3912        cx: &mut App,
3913    ) -> LayoutId {
3914        self.invalidator.debug_assert_prepaint();
3915
3916        cx.layout_id_buffer.clear();
3917        cx.layout_id_buffer.extend(children);
3918        let rem_size = self.rem_size();
3919        let scale_factor = self.scale_factor();
3920
3921        self.layout_engine.as_mut().unwrap().request_layout(
3922            style,
3923            rem_size,
3924            scale_factor,
3925            &cx.layout_id_buffer,
3926        )
3927    }
3928
3929    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
3930    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
3931    /// determine the element's size. One place this is used internally is when measuring text.
3932    ///
3933    /// The given closure is invoked at layout time with the known dimensions and available space and
3934    /// returns a `Size`.
3935    ///
3936    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3937    pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
3938    where
3939        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
3940            + 'static,
3941    {
3942        self.invalidator.debug_assert_prepaint();
3943
3944        let rem_size = self.rem_size();
3945        let scale_factor = self.scale_factor();
3946        self.layout_engine
3947            .as_mut()
3948            .unwrap()
3949            .request_measured_layout(style, rem_size, scale_factor, measure)
3950    }
3951
3952    /// Compute the layout for the given id within the given available space.
3953    /// This method is called for its side effect, typically by the framework prior to painting.
3954    /// After calling it, you can request the bounds of the given layout node id or any descendant.
3955    ///
3956    /// This method should only be called as part of the prepaint phase of element drawing.
3957    pub fn compute_layout(
3958        &mut self,
3959        layout_id: LayoutId,
3960        available_space: Size<AvailableSpace>,
3961        cx: &mut App,
3962    ) {
3963        self.invalidator.debug_assert_prepaint();
3964
3965        let mut layout_engine = self.layout_engine.take().unwrap();
3966        layout_engine.compute_layout(layout_id, available_space, self, cx);
3967        self.layout_engine = Some(layout_engine);
3968    }
3969
3970    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
3971    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
3972    ///
3973    /// This method should only be called as part of element drawing.
3974    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
3975        self.invalidator.debug_assert_prepaint();
3976
3977        let scale_factor = self.scale_factor();
3978        let mut bounds = self
3979            .layout_engine
3980            .as_mut()
3981            .unwrap()
3982            .layout_bounds(layout_id, scale_factor)
3983            .map(Into::into);
3984        let snapped_offset = self.pixel_snap_point(self.element_offset());
3985        bounds.origin += snapped_offset;
3986        bounds
3987    }
3988
3989    /// This method should be called during `prepaint`. You can use
3990    /// the returned [Hitbox] during `paint` or in an event handler
3991    /// to determine whether the inserted hitbox was the topmost.
3992    ///
3993    /// This method should only be called as part of the prepaint phase of element drawing.
3994    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
3995        self.invalidator.debug_assert_prepaint();
3996
3997        let content_mask = self.content_mask();
3998        let mut id = self.next_hitbox_id;
3999        self.next_hitbox_id = self.next_hitbox_id.next();
4000        let hitbox = Hitbox {
4001            id,
4002            bounds,
4003            content_mask,
4004            behavior,
4005        };
4006        self.next_frame.hitboxes.push(hitbox.clone());
4007        hitbox
4008    }
4009
4010    /// Set a hitbox which will act as a control area of the platform window.
4011    ///
4012    /// This method should only be called as part of the paint phase of element drawing.
4013    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
4014        self.invalidator.debug_assert_paint();
4015        self.next_frame.window_control_hitboxes.push((area, hitbox));
4016    }
4017
4018    /// Sets the key context for the current element. This context will be used to translate
4019    /// keybindings into actions.
4020    ///
4021    /// This method should only be called as part of the paint phase of element drawing.
4022    pub fn set_key_context(&mut self, context: KeyContext) {
4023        self.invalidator.debug_assert_paint();
4024        self.next_frame.dispatch_tree.set_key_context(context);
4025    }
4026
4027    /// Sets the focus handle for the current element. This handle will be used to manage focus state
4028    /// and keyboard event dispatch for the element.
4029    ///
4030    /// This method should only be called as part of the prepaint phase of element drawing.
4031    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
4032        self.invalidator.debug_assert_prepaint();
4033        if focus_handle.is_focused(self) {
4034            self.next_frame.focus = Some(focus_handle.id);
4035        }
4036        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
4037    }
4038
4039    /// Sets the view id for the current element, which will be used to manage view caching.
4040    ///
4041    /// This method should only be called as part of element prepaint. We plan on removing this
4042    /// method eventually when we solve some issues that require us to construct editor elements
4043    /// directly instead of always using editors via views.
4044    pub fn set_view_id(&mut self, view_id: EntityId) {
4045        self.invalidator.debug_assert_prepaint();
4046        self.next_frame.dispatch_tree.set_view_id(view_id);
4047    }
4048
4049    /// Get the entity ID for the currently rendering view
4050    pub fn current_view(&self) -> EntityId {
4051        self.invalidator.debug_assert_paint_or_prepaint();
4052        self.rendered_entity_stack.last().copied().unwrap()
4053    }
4054
4055    #[inline]
4056    pub(crate) fn with_rendered_view<R>(
4057        &mut self,
4058        id: EntityId,
4059        f: impl FnOnce(&mut Self) -> R,
4060    ) -> R {
4061        self.rendered_entity_stack.push(id);
4062        let result = f(self);
4063        self.rendered_entity_stack.pop();
4064        result
4065    }
4066
4067    /// Executes the provided function with the specified image cache.
4068    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
4069    where
4070        F: FnOnce(&mut Self) -> R,
4071    {
4072        if let Some(image_cache) = image_cache {
4073            self.image_cache_stack.push(image_cache);
4074            let result = f(self);
4075            self.image_cache_stack.pop();
4076            result
4077        } else {
4078            f(self)
4079        }
4080    }
4081
4082    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
4083    /// platform to receive textual input with proper integration with concerns such
4084    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
4085    /// rendered.
4086    ///
4087    /// This method should only be called as part of the paint phase of element drawing.
4088    ///
4089    /// [element_input_handler]: crate::ElementInputHandler
4090    pub fn handle_input(
4091        &mut self,
4092        focus_handle: &FocusHandle,
4093        input_handler: impl InputHandler,
4094        cx: &App,
4095    ) {
4096        self.invalidator.debug_assert_paint();
4097
4098        if focus_handle.is_focused(self) {
4099            let cx = self.to_async(cx);
4100            self.next_frame
4101                .input_handlers
4102                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
4103        }
4104    }
4105
4106    /// Register a mouse event listener on the window for the next frame. The type of event
4107    /// is determined by the first parameter of the given listener. When the next frame is rendered
4108    /// the listener will be cleared.
4109    ///
4110    /// This method should only be called as part of the paint phase of element drawing.
4111    pub fn on_mouse_event<Event: MouseEvent>(
4112        &mut self,
4113        mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4114    ) {
4115        self.invalidator.debug_assert_paint();
4116
4117        self.next_frame.mouse_listeners.push(Some(Box::new(
4118            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
4119                if let Some(event) = event.downcast_ref() {
4120                    listener(event, phase, window, cx)
4121                }
4122            },
4123        )));
4124    }
4125
4126    /// Register a key event listener on this node for the next frame. The type of event
4127    /// is determined by the first parameter of the given listener. When the next frame is rendered
4128    /// the listener will be cleared.
4129    ///
4130    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
4131    /// a specific need to register a listener yourself.
4132    ///
4133    /// This method should only be called as part of the paint phase of element drawing.
4134    pub fn on_key_event<Event: KeyEvent>(
4135        &mut self,
4136        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4137    ) {
4138        self.invalidator.debug_assert_paint();
4139
4140        self.next_frame.dispatch_tree.on_key_event(Rc::new(
4141            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
4142                if let Some(event) = event.downcast_ref::<Event>() {
4143                    listener(event, phase, window, cx)
4144                }
4145            },
4146        ));
4147    }
4148
4149    /// Register a modifiers changed event listener on the window for the next frame.
4150    ///
4151    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
4152    /// a specific need to register a global listener.
4153    ///
4154    /// This method should only be called as part of the paint phase of element drawing.
4155    pub fn on_modifiers_changed(
4156        &mut self,
4157        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
4158    ) {
4159        self.invalidator.debug_assert_paint();
4160
4161        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
4162            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
4163                listener(event, window, cx)
4164            },
4165        ));
4166    }
4167
4168    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4169    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
4170    /// Returns a subscription and persists until the subscription is dropped.
4171    pub fn on_focus_in(
4172        &mut self,
4173        handle: &FocusHandle,
4174        cx: &mut App,
4175        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
4176    ) -> Subscription {
4177        let focus_id = handle.id;
4178        let (subscription, activate) =
4179            self.new_focus_listener(Box::new(move |event, window, cx| {
4180                if event.is_focus_in(focus_id) {
4181                    listener(window, cx);
4182                }
4183                true
4184            }));
4185        cx.defer(move |_| activate());
4186        subscription
4187    }
4188
4189    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4190    /// Returns a subscription and persists until the subscription is dropped.
4191    pub fn on_focus_out(
4192        &mut self,
4193        handle: &FocusHandle,
4194        cx: &mut App,
4195        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
4196    ) -> Subscription {
4197        let focus_id = handle.id;
4198        let (subscription, activate) =
4199            self.new_focus_listener(Box::new(move |event, window, cx| {
4200                if let Some(blurred_id) = event.previous_focus_path.last().copied()
4201                    && event.is_focus_out(focus_id)
4202                {
4203                    let event = FocusOutEvent {
4204                        blurred: WeakFocusHandle {
4205                            id: blurred_id,
4206                            handles: Arc::downgrade(&cx.focus_handles),
4207                        },
4208                    };
4209                    listener(event, window, cx)
4210                }
4211                true
4212            }));
4213        cx.defer(move |_| activate());
4214        subscription
4215    }
4216
4217    fn reset_cursor_style(&self, cx: &mut App) {
4218        // Set the cursor only if we're the active window.
4219        if self.is_window_hovered() {
4220            let style = self
4221                .rendered_frame
4222                .cursor_style(self)
4223                .unwrap_or(CursorStyle::Arrow);
4224            cx.platform.set_cursor_style(style);
4225        }
4226    }
4227
4228    /// Dispatch a given keystroke as though the user had typed it.
4229    /// You can create a keystroke with Keystroke::parse("").
4230    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
4231        let keystroke = keystroke.with_simulated_ime();
4232        let result = self.dispatch_event(
4233            PlatformInput::KeyDown(KeyDownEvent {
4234                keystroke: keystroke.clone(),
4235                is_held: false,
4236                prefer_character_input: false,
4237            }),
4238            cx,
4239        );
4240        if !result.propagate {
4241            return true;
4242        }
4243
4244        if let Some(input) = keystroke.key_char
4245            && let Some(mut input_handler) = self.platform_window.take_input_handler()
4246        {
4247            input_handler.dispatch_input(&input, self, cx);
4248            self.platform_window.set_input_handler(input_handler);
4249            return true;
4250        }
4251
4252        false
4253    }
4254
4255    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
4256    /// binding for the action (last binding added to the keymap).
4257    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
4258        self.highest_precedence_binding_for_action(action)
4259            .map(|binding| {
4260                binding
4261                    .keystrokes()
4262                    .iter()
4263                    .map(ToString::to_string)
4264                    .collect::<Vec<_>>()
4265                    .join(" ")
4266            })
4267            .unwrap_or_else(|| action.name().to_string())
4268    }
4269
4270    /// Dispatch a mouse or keyboard event on the window.
4271    #[profiling::function]
4272    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
4273        #[cfg(feature = "input-latency-histogram")]
4274        let dispatch_time = Instant::now();
4275        let update_count_before = self.invalidator.update_count();
4276        // Track input modality for focus-visible styling and hover suppression.
4277        // Hover is suppressed during keyboard modality so that keyboard navigation
4278        // doesn't show hover highlights on the item under the mouse cursor.
4279        let old_modality = self.last_input_modality;
4280        self.last_input_modality = match &event {
4281            PlatformInput::KeyDown(_) => InputModality::Keyboard,
4282            PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
4283            _ => self.last_input_modality,
4284        };
4285        if self.last_input_modality != old_modality {
4286            self.refresh();
4287        }
4288
4289        // Handlers may set this to false by calling `stop_propagation`.
4290        cx.propagate_event = true;
4291        // Handlers may set this to true by calling `prevent_default`.
4292        self.default_prevented = false;
4293
4294        let event = match event {
4295            // Track the mouse position with our own state, since accessing the platform
4296            // API for the mouse position can only occur on the main thread.
4297            PlatformInput::MouseMove(mouse_move) => {
4298                self.mouse_position = mouse_move.position;
4299                self.modifiers = mouse_move.modifiers;
4300                PlatformInput::MouseMove(mouse_move)
4301            }
4302            PlatformInput::MouseDown(mouse_down) => {
4303                self.mouse_position = mouse_down.position;
4304                self.modifiers = mouse_down.modifiers;
4305                PlatformInput::MouseDown(mouse_down)
4306            }
4307            PlatformInput::MouseUp(mouse_up) => {
4308                self.mouse_position = mouse_up.position;
4309                self.modifiers = mouse_up.modifiers;
4310                PlatformInput::MouseUp(mouse_up)
4311            }
4312            PlatformInput::MousePressure(mouse_pressure) => {
4313                PlatformInput::MousePressure(mouse_pressure)
4314            }
4315            PlatformInput::MouseExited(mouse_exited) => {
4316                self.modifiers = mouse_exited.modifiers;
4317                PlatformInput::MouseExited(mouse_exited)
4318            }
4319            PlatformInput::ModifiersChanged(modifiers_changed) => {
4320                self.modifiers = modifiers_changed.modifiers;
4321                self.capslock = modifiers_changed.capslock;
4322                PlatformInput::ModifiersChanged(modifiers_changed)
4323            }
4324            PlatformInput::ScrollWheel(scroll_wheel) => {
4325                self.mouse_position = scroll_wheel.position;
4326                self.modifiers = scroll_wheel.modifiers;
4327                PlatformInput::ScrollWheel(scroll_wheel)
4328            }
4329            PlatformInput::Pinch(pinch) => {
4330                self.mouse_position = pinch.position;
4331                self.modifiers = pinch.modifiers;
4332                PlatformInput::Pinch(pinch)
4333            }
4334            // Translate dragging and dropping of external files from the operating system
4335            // to internal drag and drop events.
4336            PlatformInput::FileDrop(file_drop) => match file_drop {
4337                FileDropEvent::Entered { position, paths } => {
4338                    self.mouse_position = position;
4339                    if cx.active_drag.is_none() {
4340                        cx.active_drag = Some(AnyDrag {
4341                            value: Arc::new(paths.clone()),
4342                            view: cx.new(|_| paths).into(),
4343                            cursor_offset: position,
4344                            cursor_style: None,
4345                        });
4346                    }
4347                    PlatformInput::MouseMove(MouseMoveEvent {
4348                        position,
4349                        pressed_button: Some(MouseButton::Left),
4350                        modifiers: Modifiers::default(),
4351                    })
4352                }
4353                FileDropEvent::Pending { position } => {
4354                    self.mouse_position = position;
4355                    PlatformInput::MouseMove(MouseMoveEvent {
4356                        position,
4357                        pressed_button: Some(MouseButton::Left),
4358                        modifiers: Modifiers::default(),
4359                    })
4360                }
4361                FileDropEvent::Submit { position } => {
4362                    cx.activate(true);
4363                    self.mouse_position = position;
4364                    PlatformInput::MouseUp(MouseUpEvent {
4365                        button: MouseButton::Left,
4366                        position,
4367                        modifiers: Modifiers::default(),
4368                        click_count: 1,
4369                    })
4370                }
4371                FileDropEvent::Exited => {
4372                    cx.active_drag.take();
4373                    PlatformInput::FileDrop(FileDropEvent::Exited)
4374                }
4375            },
4376            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
4377        };
4378
4379        if let Some(any_mouse_event) = event.mouse_event() {
4380            self.dispatch_mouse_event(any_mouse_event, cx);
4381        } else if let Some(any_key_event) = event.keyboard_event() {
4382            self.dispatch_key_event(any_key_event, cx);
4383        }
4384
4385        if self.invalidator.update_count() > update_count_before {
4386            self.input_rate_tracker.borrow_mut().record_input();
4387            #[cfg(feature = "input-latency-histogram")]
4388            if self.invalidator.not_drawing() {
4389                self.input_latency_tracker.record_input(dispatch_time);
4390            } else {
4391                self.input_latency_tracker.record_mid_draw_input();
4392            }
4393        }
4394
4395        DispatchEventResult {
4396            propagate: cx.propagate_event,
4397            default_prevented: self.default_prevented,
4398        }
4399    }
4400
4401    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4402        let hit_test = self.rendered_frame.hit_test(self.mouse_position());
4403        if hit_test != self.mouse_hit_test {
4404            self.mouse_hit_test = hit_test;
4405            self.reset_cursor_style(cx);
4406        }
4407
4408        #[cfg(any(feature = "inspector", debug_assertions))]
4409        if self.is_inspector_picking(cx) {
4410            self.handle_inspector_mouse_event(event, cx);
4411            // When inspector is picking, all other mouse handling is skipped.
4412            return;
4413        }
4414
4415        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
4416
4417        // Capture phase, events bubble from back to front. Handlers for this phase are used for
4418        // special purposes, such as detecting events outside of a given Bounds.
4419        for listener in &mut mouse_listeners {
4420            let listener = listener.as_mut().unwrap();
4421            listener(event, DispatchPhase::Capture, self, cx);
4422            if !cx.propagate_event {
4423                break;
4424            }
4425        }
4426
4427        // Bubble phase, where most normal handlers do their work.
4428        if cx.propagate_event {
4429            for listener in mouse_listeners.iter_mut().rev() {
4430                let listener = listener.as_mut().unwrap();
4431                listener(event, DispatchPhase::Bubble, self, cx);
4432                if !cx.propagate_event {
4433                    break;
4434                }
4435            }
4436        }
4437
4438        self.rendered_frame.mouse_listeners = mouse_listeners;
4439
4440        if cx.has_active_drag() {
4441            if event.is::<MouseMoveEvent>() {
4442                // If this was a mouse move event, redraw the window so that the
4443                // active drag can follow the mouse cursor.
4444                self.refresh();
4445            } else if event.is::<MouseUpEvent>() {
4446                // If this was a mouse up event, cancel the active drag and redraw
4447                // the window.
4448                cx.active_drag = None;
4449                self.refresh();
4450            }
4451        }
4452
4453        // Auto-release pointer capture on mouse up
4454        if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
4455            self.captured_hitbox = None;
4456        }
4457    }
4458
4459    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
4460        if self.invalidator.is_dirty() {
4461            self.draw(cx).clear();
4462        }
4463
4464        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4465        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4466
4467        let mut keystroke: Option<Keystroke> = None;
4468
4469        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
4470            if event.modifiers.number_of_modifiers() == 0
4471                && self.pending_modifier.modifiers.number_of_modifiers() == 1
4472                && !self.pending_modifier.saw_keystroke
4473            {
4474                let key = match self.pending_modifier.modifiers {
4475                    modifiers if modifiers.shift => Some("shift"),
4476                    modifiers if modifiers.control => Some("control"),
4477                    modifiers if modifiers.alt => Some("alt"),
4478                    modifiers if modifiers.platform => Some("platform"),
4479                    modifiers if modifiers.function => Some("function"),
4480                    _ => None,
4481                };
4482                if let Some(key) = key {
4483                    keystroke = Some(Keystroke {
4484                        key: key.to_string(),
4485                        key_char: None,
4486                        modifiers: Modifiers::default(),
4487                    });
4488                }
4489            }
4490
4491            if self.pending_modifier.modifiers.number_of_modifiers() == 0
4492                && event.modifiers.number_of_modifiers() == 1
4493            {
4494                self.pending_modifier.saw_keystroke = false
4495            }
4496            self.pending_modifier.modifiers = event.modifiers
4497        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
4498            self.pending_modifier.saw_keystroke = true;
4499            keystroke = Some(key_down_event.keystroke.clone());
4500            if key_down_event.keystroke.key_char.is_some()
4501                && matches!(
4502                    cx.cursor_hide_mode,
4503                    CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
4504                )
4505            {
4506                cx.platform.hide_cursor_until_mouse_moves();
4507            }
4508        }
4509
4510        let Some(keystroke) = keystroke else {
4511            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4512            return;
4513        };
4514
4515        cx.propagate_event = true;
4516        self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
4517        if !cx.propagate_event {
4518            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4519            return;
4520        }
4521
4522        let mut currently_pending = self.pending_input.take().unwrap_or_default();
4523        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
4524            currently_pending = PendingInput::default();
4525        }
4526
4527        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
4528            currently_pending.keystrokes,
4529            keystroke,
4530            &dispatch_path,
4531        );
4532
4533        if !match_result.to_replay.is_empty() {
4534            self.replay_pending_input(match_result.to_replay, cx);
4535            cx.propagate_event = true;
4536        }
4537
4538        if !match_result.pending.is_empty() {
4539            currently_pending.timer.take();
4540            currently_pending.keystrokes = match_result.pending;
4541            currently_pending.focus = self.focus;
4542
4543            let text_input_requires_timeout = event
4544                .downcast_ref::<KeyDownEvent>()
4545                .filter(|key_down| key_down.keystroke.key_char.is_some())
4546                .and_then(|_| self.platform_window.take_input_handler())
4547                .map_or(false, |mut input_handler| {
4548                    let accepts = input_handler.accepts_text_input(self, cx);
4549                    self.platform_window.set_input_handler(input_handler);
4550                    accepts
4551                });
4552
4553            currently_pending.needs_timeout |=
4554                match_result.pending_has_binding || text_input_requires_timeout;
4555
4556            if currently_pending.needs_timeout {
4557                currently_pending.timer = Some(self.spawn(cx, async move |cx| {
4558                    cx.background_executor.timer(Duration::from_secs(1)).await;
4559                    cx.update(move |window, cx| {
4560                        let Some(currently_pending) = window
4561                            .pending_input
4562                            .take()
4563                            .filter(|pending| pending.focus == window.focus)
4564                        else {
4565                            return;
4566                        };
4567
4568                        let node_id = window.focus_node_id_in_rendered_frame(window.focus);
4569                        let dispatch_path =
4570                            window.rendered_frame.dispatch_tree.dispatch_path(node_id);
4571
4572                        let to_replay = window
4573                            .rendered_frame
4574                            .dispatch_tree
4575                            .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
4576
4577                        window.pending_input_changed(cx);
4578                        window.replay_pending_input(to_replay, cx)
4579                    })
4580                    .log_err();
4581                }));
4582            } else {
4583                currently_pending.timer = None;
4584            }
4585            self.pending_input = Some(currently_pending);
4586            self.pending_input_changed(cx);
4587            cx.propagate_event = false;
4588            return;
4589        }
4590
4591        let skip_bindings = event
4592            .downcast_ref::<KeyDownEvent>()
4593            .filter(|key_down_event| key_down_event.prefer_character_input)
4594            .map(|_| {
4595                self.platform_window
4596                    .take_input_handler()
4597                    .map_or(false, |mut input_handler| {
4598                        let accepts = input_handler.accepts_text_input(self, cx);
4599                        self.platform_window.set_input_handler(input_handler);
4600                        // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
4601                        // we prefer the text input over bindings.
4602                        accepts
4603                    })
4604            })
4605            .unwrap_or(false);
4606
4607        if !skip_bindings {
4608            for binding in match_result.bindings {
4609                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4610                if !cx.propagate_event {
4611                    self.dispatch_keystroke_observers(
4612                        event,
4613                        Some(binding.action),
4614                        match_result.context_stack,
4615                        cx,
4616                    );
4617                    self.pending_input_changed(cx);
4618                    return;
4619                }
4620            }
4621        }
4622
4623        self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
4624        self.pending_input_changed(cx);
4625    }
4626
4627    fn finish_dispatch_key_event(
4628        &mut self,
4629        event: &dyn Any,
4630        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
4631        context_stack: Vec<KeyContext>,
4632        cx: &mut App,
4633    ) {
4634        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
4635        if !cx.propagate_event {
4636            return;
4637        }
4638
4639        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
4640        if !cx.propagate_event {
4641            return;
4642        }
4643
4644        self.dispatch_keystroke_observers(event, None, context_stack, cx);
4645    }
4646
4647    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
4648        self.pending_input_observers
4649            .clone()
4650            .retain(&(), |callback| callback(self, cx));
4651    }
4652
4653    fn dispatch_key_down_up_event(
4654        &mut self,
4655        event: &dyn Any,
4656        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4657        cx: &mut App,
4658    ) {
4659        // Capture phase
4660        for node_id in dispatch_path {
4661            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4662
4663            for key_listener in node.key_listeners.clone() {
4664                key_listener(event, DispatchPhase::Capture, self, cx);
4665                if !cx.propagate_event {
4666                    return;
4667                }
4668            }
4669        }
4670
4671        // Bubble phase
4672        for node_id in dispatch_path.iter().rev() {
4673            // Handle low level key events
4674            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4675            for key_listener in node.key_listeners.clone() {
4676                key_listener(event, DispatchPhase::Bubble, self, cx);
4677                if !cx.propagate_event {
4678                    return;
4679                }
4680            }
4681        }
4682    }
4683
4684    fn dispatch_modifiers_changed_event(
4685        &mut self,
4686        event: &dyn Any,
4687        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4688        cx: &mut App,
4689    ) {
4690        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
4691            return;
4692        };
4693        for node_id in dispatch_path.iter().rev() {
4694            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4695            for listener in node.modifiers_changed_listeners.clone() {
4696                listener(event, self, cx);
4697                if !cx.propagate_event {
4698                    return;
4699                }
4700            }
4701        }
4702    }
4703
4704    /// Determine whether a potential multi-stroke key binding is in progress on this window.
4705    pub fn has_pending_keystrokes(&self) -> bool {
4706        self.pending_input.is_some()
4707    }
4708
4709    pub(crate) fn clear_pending_keystrokes(&mut self) {
4710        self.pending_input.take();
4711    }
4712
4713    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
4714    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
4715        self.pending_input
4716            .as_ref()
4717            .map(|pending_input| pending_input.keystrokes.as_slice())
4718    }
4719
4720    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
4721        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4722        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4723
4724        'replay: for replay in replays {
4725            let event = KeyDownEvent {
4726                keystroke: replay.keystroke.clone(),
4727                is_held: false,
4728                prefer_character_input: true,
4729            };
4730
4731            cx.propagate_event = true;
4732            for binding in replay.bindings {
4733                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4734                if !cx.propagate_event {
4735                    self.dispatch_keystroke_observers(
4736                        &event,
4737                        Some(binding.action),
4738                        Vec::default(),
4739                        cx,
4740                    );
4741                    continue 'replay;
4742                }
4743            }
4744
4745            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
4746            if !cx.propagate_event {
4747                continue 'replay;
4748            }
4749            if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
4750                && let Some(mut input_handler) = self.platform_window.take_input_handler()
4751            {
4752                input_handler.dispatch_input(&input, self, cx);
4753                self.platform_window.set_input_handler(input_handler)
4754            }
4755        }
4756    }
4757
4758    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
4759        focus_id
4760            .and_then(|focus_id| {
4761                self.rendered_frame
4762                    .dispatch_tree
4763                    .focusable_node_id(focus_id)
4764            })
4765            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
4766    }
4767
4768    fn dispatch_action_on_node(
4769        &mut self,
4770        node_id: DispatchNodeId,
4771        action: &dyn Action,
4772        cx: &mut App,
4773    ) {
4774        self.dispatch_action_on_node_inner(node_id, action, cx);
4775
4776        if !cx.propagate_event
4777            && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
4778            && self.last_input_was_keyboard()
4779        {
4780            cx.platform.hide_cursor_until_mouse_moves();
4781        }
4782    }
4783
4784    fn dispatch_action_on_node_inner(
4785        &mut self,
4786        node_id: DispatchNodeId,
4787        action: &dyn Action,
4788        cx: &mut App,
4789    ) {
4790        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4791
4792        // Capture phase for global actions.
4793        cx.propagate_event = true;
4794        if let Some(mut global_listeners) = cx
4795            .global_action_listeners
4796            .remove(&action.as_any().type_id())
4797        {
4798            for listener in &global_listeners {
4799                listener(action.as_any(), DispatchPhase::Capture, cx);
4800                if !cx.propagate_event {
4801                    break;
4802                }
4803            }
4804
4805            global_listeners.extend(
4806                cx.global_action_listeners
4807                    .remove(&action.as_any().type_id())
4808                    .unwrap_or_default(),
4809            );
4810
4811            cx.global_action_listeners
4812                .insert(action.as_any().type_id(), global_listeners);
4813        }
4814
4815        if !cx.propagate_event {
4816            return;
4817        }
4818
4819        // Capture phase for window actions.
4820        for node_id in &dispatch_path {
4821            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4822            for DispatchActionListener {
4823                action_type,
4824                listener,
4825            } in node.action_listeners.clone()
4826            {
4827                let any_action = action.as_any();
4828                if action_type == any_action.type_id() {
4829                    listener(any_action, DispatchPhase::Capture, self, cx);
4830
4831                    if !cx.propagate_event {
4832                        return;
4833                    }
4834                }
4835            }
4836        }
4837
4838        // Bubble phase for window actions.
4839        for node_id in dispatch_path.iter().rev() {
4840            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4841            for DispatchActionListener {
4842                action_type,
4843                listener,
4844            } in node.action_listeners.clone()
4845            {
4846                let any_action = action.as_any();
4847                if action_type == any_action.type_id() {
4848                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4849                    listener(any_action, DispatchPhase::Bubble, self, cx);
4850
4851                    if !cx.propagate_event {
4852                        return;
4853                    }
4854                }
4855            }
4856        }
4857
4858        // Bubble phase for global actions.
4859        if let Some(mut global_listeners) = cx
4860            .global_action_listeners
4861            .remove(&action.as_any().type_id())
4862        {
4863            for listener in global_listeners.iter().rev() {
4864                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4865
4866                listener(action.as_any(), DispatchPhase::Bubble, cx);
4867                if !cx.propagate_event {
4868                    break;
4869                }
4870            }
4871
4872            global_listeners.extend(
4873                cx.global_action_listeners
4874                    .remove(&action.as_any().type_id())
4875                    .unwrap_or_default(),
4876            );
4877
4878            cx.global_action_listeners
4879                .insert(action.as_any().type_id(), global_listeners);
4880        }
4881    }
4882
4883    /// Register the given handler to be invoked whenever the global of the given type
4884    /// is updated.
4885    pub fn observe_global<G: Global>(
4886        &mut self,
4887        cx: &mut App,
4888        f: impl Fn(&mut Window, &mut App) + 'static,
4889    ) -> Subscription {
4890        let window_handle = self.handle;
4891        let (subscription, activate) = cx.global_observers.insert(
4892            TypeId::of::<G>(),
4893            Box::new(move |cx| {
4894                window_handle
4895                    .update(cx, |_, window, cx| f(window, cx))
4896                    .is_ok()
4897            }),
4898        );
4899        cx.defer(move |_| activate());
4900        subscription
4901    }
4902
4903    /// Focus the current window and bring it to the foreground at the platform level.
4904    pub fn activate_window(&self) {
4905        self.platform_window.activate();
4906    }
4907
4908    /// Minimize the current window at the platform level.
4909    pub fn minimize_window(&self) {
4910        self.platform_window.minimize();
4911    }
4912
4913    /// Toggle full screen status on the current window at the platform level.
4914    pub fn toggle_fullscreen(&self) {
4915        self.platform_window.toggle_fullscreen();
4916    }
4917
4918    /// Updates the IME panel position suggestions for languages like japanese, chinese.
4919    pub fn invalidate_character_coordinates(&self) {
4920        self.on_next_frame(|window, cx| {
4921            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
4922                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
4923                    window.platform_window.update_ime_position(bounds);
4924                }
4925                window.platform_window.set_input_handler(input_handler);
4926            }
4927        });
4928    }
4929
4930    /// Present a platform dialog.
4931    /// The provided message will be presented, along with buttons for each answer.
4932    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
4933    pub fn prompt<T>(
4934        &mut self,
4935        level: PromptLevel,
4936        message: &str,
4937        detail: Option<&str>,
4938        answers: &[T],
4939        cx: &mut App,
4940    ) -> oneshot::Receiver<usize>
4941    where
4942        T: Clone + Into<PromptButton>,
4943    {
4944        let prompt_builder = cx.prompt_builder.take();
4945        let Some(prompt_builder) = prompt_builder else {
4946            unreachable!("Re-entrant window prompting is not supported by GPUI");
4947        };
4948
4949        let answers = answers
4950            .iter()
4951            .map(|answer| answer.clone().into())
4952            .collect::<Vec<_>>();
4953
4954        let receiver = match &prompt_builder {
4955            PromptBuilder::Default => self
4956                .platform_window
4957                .prompt(level, message, detail, &answers)
4958                .unwrap_or_else(|| {
4959                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4960                }),
4961            PromptBuilder::Custom(_) => {
4962                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4963            }
4964        };
4965
4966        cx.prompt_builder = Some(prompt_builder);
4967
4968        receiver
4969    }
4970
4971    fn build_custom_prompt(
4972        &mut self,
4973        prompt_builder: &PromptBuilder,
4974        level: PromptLevel,
4975        message: &str,
4976        detail: Option<&str>,
4977        answers: &[PromptButton],
4978        cx: &mut App,
4979    ) -> oneshot::Receiver<usize> {
4980        let (sender, receiver) = oneshot::channel();
4981        let handle = PromptHandle::new(sender);
4982        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
4983        self.prompt = Some(handle);
4984        receiver
4985    }
4986
4987    /// Returns the current context stack.
4988    pub fn context_stack(&self) -> Vec<KeyContext> {
4989        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4990        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4991        dispatch_tree
4992            .dispatch_path(node_id)
4993            .iter()
4994            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
4995            .collect()
4996    }
4997
4998    /// Returns all available actions for the focused element.
4999    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
5000        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
5001        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
5002        for action_type in cx.global_action_listeners.keys() {
5003            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
5004                let action = cx.actions.build_action_type(action_type).ok();
5005                if let Some(action) = action {
5006                    actions.insert(ix, action);
5007                }
5008            }
5009        }
5010        actions
5011    }
5012
5013    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
5014    /// returned in the order they were added. For display, the last binding should take precedence.
5015    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
5016        self.rendered_frame
5017            .dispatch_tree
5018            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
5019    }
5020
5021    /// Returns the highest precedence key binding that invokes an action on the currently focused
5022    /// element. This is more efficient than getting the last result of `bindings_for_action`.
5023    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
5024        self.rendered_frame
5025            .dispatch_tree
5026            .highest_precedence_binding_for_action(
5027                action,
5028                &self.rendered_frame.dispatch_tree.context_stack,
5029            )
5030    }
5031
5032    /// Returns the key bindings for an action in a context.
5033    pub fn bindings_for_action_in_context(
5034        &self,
5035        action: &dyn Action,
5036        context: KeyContext,
5037    ) -> Vec<KeyBinding> {
5038        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5039        dispatch_tree.bindings_for_action(action, &[context])
5040    }
5041
5042    /// Returns the highest precedence key binding for an action in a context. This is more
5043    /// efficient than getting the last result of `bindings_for_action_in_context`.
5044    pub fn highest_precedence_binding_for_action_in_context(
5045        &self,
5046        action: &dyn Action,
5047        context: KeyContext,
5048    ) -> Option<KeyBinding> {
5049        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5050        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
5051    }
5052
5053    /// Returns any bindings that would invoke an action on the given focus handle if it were
5054    /// focused. Bindings are returned in the order they were added. For display, the last binding
5055    /// should take precedence.
5056    pub fn bindings_for_action_in(
5057        &self,
5058        action: &dyn Action,
5059        focus_handle: &FocusHandle,
5060    ) -> Vec<KeyBinding> {
5061        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5062        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
5063            return vec![];
5064        };
5065        dispatch_tree.bindings_for_action(action, &context_stack)
5066    }
5067
5068    /// Returns the highest precedence key binding that would invoke an action on the given focus
5069    /// handle if it were focused. This is more efficient than getting the last result of
5070    /// `bindings_for_action_in`.
5071    pub fn highest_precedence_binding_for_action_in(
5072        &self,
5073        action: &dyn Action,
5074        focus_handle: &FocusHandle,
5075    ) -> Option<KeyBinding> {
5076        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5077        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
5078        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
5079    }
5080
5081    /// Find the bindings that can follow the current input sequence for the current context stack.
5082    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
5083        self.rendered_frame
5084            .dispatch_tree
5085            .possible_next_bindings_for_input(input, &self.context_stack())
5086    }
5087
5088    fn context_stack_for_focus_handle(
5089        &self,
5090        focus_handle: &FocusHandle,
5091    ) -> Option<Vec<KeyContext>> {
5092        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5093        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
5094        let context_stack: Vec<_> = dispatch_tree
5095            .dispatch_path(node_id)
5096            .into_iter()
5097            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
5098            .collect();
5099        Some(context_stack)
5100    }
5101
5102    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
5103    pub fn listener_for<T: 'static, E>(
5104        &self,
5105        view: &Entity<T>,
5106        f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
5107    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
5108        let view = view.downgrade();
5109        move |e: &E, window: &mut Window, cx: &mut App| {
5110            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
5111        }
5112    }
5113
5114    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
5115    pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
5116        &self,
5117        entity: &Entity<E>,
5118        f: Callback,
5119    ) -> impl Fn(&mut Window, &mut App) + 'static {
5120        let entity = entity.downgrade();
5121        move |window: &mut Window, cx: &mut App| {
5122            entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
5123        }
5124    }
5125
5126    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
5127    /// If the callback returns false, the window won't be closed.
5128    pub fn on_window_should_close(
5129        &self,
5130        cx: &App,
5131        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
5132    ) {
5133        let mut cx = self.to_async(cx);
5134        self.platform_window.on_should_close(Box::new(move || {
5135            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
5136        }))
5137    }
5138
5139    /// Register an action listener on this node for the next frame. The type of action
5140    /// is determined by the first parameter of the given listener. When the next frame is rendered
5141    /// the listener will be cleared.
5142    ///
5143    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
5144    /// a specific need to register a listener yourself.
5145    ///
5146    /// This method should only be called as part of the paint phase of element drawing.
5147    pub fn on_action(
5148        &mut self,
5149        action_type: TypeId,
5150        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5151    ) {
5152        self.invalidator.debug_assert_paint();
5153
5154        self.next_frame
5155            .dispatch_tree
5156            .on_action(action_type, Rc::new(listener));
5157    }
5158
5159    /// Register a capturing action listener on this node for the next frame if the condition is true.
5160    /// The type of action is determined by the first parameter of the given listener. When the next
5161    /// frame is rendered the listener will be cleared.
5162    ///
5163    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
5164    /// a specific need to register a listener yourself.
5165    ///
5166    /// This method should only be called as part of the paint phase of element drawing.
5167    pub fn on_action_when(
5168        &mut self,
5169        condition: bool,
5170        action_type: TypeId,
5171        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5172    ) {
5173        self.invalidator.debug_assert_paint();
5174
5175        if condition {
5176            self.next_frame
5177                .dispatch_tree
5178                .on_action(action_type, Rc::new(listener));
5179        }
5180    }
5181
5182    /// Read information about the GPU backing this window.
5183    /// Currently returns None on Mac and Windows.
5184    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
5185        self.platform_window.gpu_specs()
5186    }
5187
5188    /// Perform titlebar double-click action.
5189    /// This is macOS specific.
5190    pub fn titlebar_double_click(&self) {
5191        self.platform_window.titlebar_double_click();
5192    }
5193
5194    /// Gets the window's title at the platform level.
5195    /// This is macOS specific.
5196    pub fn window_title(&self) -> String {
5197        self.platform_window.get_title()
5198    }
5199
5200    /// Returns a list of all tabbed windows and their titles.
5201    /// This is macOS specific.
5202    pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
5203        self.platform_window.tabbed_windows()
5204    }
5205
5206    /// Returns the tab bar visibility.
5207    /// This is macOS specific.
5208    pub fn tab_bar_visible(&self) -> bool {
5209        self.platform_window.tab_bar_visible()
5210    }
5211
5212    /// Merges all open windows into a single tabbed window.
5213    /// This is macOS specific.
5214    pub fn merge_all_windows(&self) {
5215        self.platform_window.merge_all_windows()
5216    }
5217
5218    /// Moves the tab to a new containing window.
5219    /// This is macOS specific.
5220    pub fn move_tab_to_new_window(&self) {
5221        self.platform_window.move_tab_to_new_window()
5222    }
5223
5224    /// Shows or hides the window tab overview.
5225    /// This is macOS specific.
5226    pub fn toggle_window_tab_overview(&self) {
5227        self.platform_window.toggle_window_tab_overview()
5228    }
5229
5230    /// Sets the tabbing identifier for the window.
5231    /// This is macOS specific.
5232    pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
5233        self.platform_window
5234            .set_tabbing_identifier(tabbing_identifier)
5235    }
5236
5237    /// Request the OS to play an alert sound. On some platforms this is associated
5238    /// with the window, for others it's just a simple global function call.
5239    pub fn play_system_bell(&self) {
5240        self.platform_window.play_system_bell()
5241    }
5242
5243    /// Toggles the inspector mode on this window.
5244    #[cfg(any(feature = "inspector", debug_assertions))]
5245    pub fn toggle_inspector(&mut self, cx: &mut App) {
5246        self.inspector = match self.inspector {
5247            None => Some(cx.new(|_| Inspector::new())),
5248            Some(_) => None,
5249        };
5250        self.refresh();
5251    }
5252
5253    /// Returns true if the window is in inspector mode.
5254    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
5255        #[cfg(any(feature = "inspector", debug_assertions))]
5256        {
5257            if let Some(inspector) = &self.inspector {
5258                return inspector.read(_cx).is_picking();
5259            }
5260        }
5261        false
5262    }
5263
5264    /// Executes the provided function with mutable access to an inspector state.
5265    #[cfg(any(feature = "inspector", debug_assertions))]
5266    pub fn with_inspector_state<T: 'static, R>(
5267        &mut self,
5268        _inspector_id: Option<&crate::InspectorElementId>,
5269        cx: &mut App,
5270        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
5271    ) -> R {
5272        if let Some(inspector_id) = _inspector_id
5273            && let Some(inspector) = &self.inspector
5274        {
5275            let inspector = inspector.clone();
5276            let active_element_id = inspector.read(cx).active_element_id();
5277            if Some(inspector_id) == active_element_id {
5278                return inspector.update(cx, |inspector, _cx| {
5279                    inspector.with_active_element_state(self, f)
5280                });
5281            }
5282        }
5283        f(&mut None, self)
5284    }
5285
5286    #[cfg(any(feature = "inspector", debug_assertions))]
5287    pub(crate) fn build_inspector_element_id(
5288        &mut self,
5289        path: crate::InspectorElementPath,
5290    ) -> crate::InspectorElementId {
5291        self.invalidator.debug_assert_paint_or_prepaint();
5292        let path = Rc::new(path);
5293        let next_instance_id = self
5294            .next_frame
5295            .next_inspector_instance_ids
5296            .entry(path.clone())
5297            .or_insert(0);
5298        let instance_id = *next_instance_id;
5299        *next_instance_id += 1;
5300        crate::InspectorElementId { path, instance_id }
5301    }
5302
5303    #[cfg(any(feature = "inspector", debug_assertions))]
5304    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
5305        if let Some(inspector) = self.inspector.take() {
5306            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
5307            inspector_element.prepaint_as_root(
5308                point(self.viewport_size.width - inspector_width, px(0.0)),
5309                size(inspector_width, self.viewport_size.height).into(),
5310                self,
5311                cx,
5312            );
5313            self.inspector = Some(inspector);
5314            Some(inspector_element)
5315        } else {
5316            None
5317        }
5318    }
5319
5320    #[cfg(any(feature = "inspector", debug_assertions))]
5321    fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
5322        if let Some(mut inspector_element) = inspector_element {
5323            inspector_element.paint(self, cx);
5324        };
5325    }
5326
5327    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
5328    /// inspect UI elements by clicking on them.
5329    #[cfg(any(feature = "inspector", debug_assertions))]
5330    pub fn insert_inspector_hitbox(
5331        &mut self,
5332        hitbox_id: HitboxId,
5333        inspector_id: Option<&crate::InspectorElementId>,
5334        cx: &App,
5335    ) {
5336        self.invalidator.debug_assert_paint_or_prepaint();
5337        if !self.is_inspector_picking(cx) {
5338            return;
5339        }
5340        if let Some(inspector_id) = inspector_id {
5341            self.next_frame
5342                .inspector_hitboxes
5343                .insert(hitbox_id, inspector_id.clone());
5344        }
5345    }
5346
5347    #[cfg(any(feature = "inspector", debug_assertions))]
5348    fn paint_inspector_hitbox(&mut self, cx: &App) {
5349        if let Some(inspector) = self.inspector.as_ref() {
5350            let inspector = inspector.read(cx);
5351            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
5352                && let Some(hitbox) = self
5353                    .next_frame
5354                    .hitboxes
5355                    .iter()
5356                    .find(|hitbox| hitbox.id == hitbox_id)
5357            {
5358                self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
5359            }
5360        }
5361    }
5362
5363    #[cfg(any(feature = "inspector", debug_assertions))]
5364    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5365        let Some(inspector) = self.inspector.clone() else {
5366            return;
5367        };
5368        if event.downcast_ref::<MouseMoveEvent>().is_some() {
5369            inspector.update(cx, |inspector, _cx| {
5370                if let Some((_, inspector_id)) =
5371                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5372                {
5373                    inspector.hover(inspector_id, self);
5374                }
5375            });
5376        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
5377            inspector.update(cx, |inspector, _cx| {
5378                if let Some((_, inspector_id)) =
5379                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5380                {
5381                    inspector.select(inspector_id, self);
5382                }
5383            });
5384        } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
5385            // This should be kept in sync with SCROLL_LINES in x11 platform.
5386            const SCROLL_LINES: f32 = 3.0;
5387            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
5388            let delta_y = event
5389                .delta
5390                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
5391                .y;
5392            if let Some(inspector) = self.inspector.clone() {
5393                inspector.update(cx, |inspector, _cx| {
5394                    if let Some(depth) = inspector.pick_depth.as_mut() {
5395                        *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
5396                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
5397                        if *depth < 0.0 {
5398                            *depth = 0.0;
5399                        } else if *depth > max_depth {
5400                            *depth = max_depth;
5401                        }
5402                        if let Some((_, inspector_id)) =
5403                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5404                        {
5405                            inspector.set_active_element_id(inspector_id, self);
5406                        }
5407                    }
5408                });
5409            }
5410        }
5411    }
5412
5413    #[cfg(any(feature = "inspector", debug_assertions))]
5414    fn hovered_inspector_hitbox(
5415        &self,
5416        inspector: &Inspector,
5417        frame: &Frame,
5418    ) -> Option<(HitboxId, crate::InspectorElementId)> {
5419        if let Some(pick_depth) = inspector.pick_depth {
5420            let depth = (pick_depth as i64).try_into().unwrap_or(0);
5421            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
5422            let skip_count = (depth as usize).min(max_skipped);
5423            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
5424                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
5425                    return Some((*hitbox_id, inspector_id.clone()));
5426                }
5427            }
5428        }
5429        None
5430    }
5431
5432    /// For testing: set the current modifier keys state.
5433    /// This does not generate any events.
5434    #[cfg(any(test, feature = "test-support"))]
5435    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
5436        self.modifiers = modifiers;
5437    }
5438
5439    /// For testing: simulate a mouse move event to the given position.
5440    /// This dispatches the event through the normal event handling path,
5441    /// which will trigger hover states and tooltips.
5442    #[cfg(any(test, feature = "test-support"))]
5443    pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
5444        let event = PlatformInput::MouseMove(MouseMoveEvent {
5445            position,
5446            modifiers: self.modifiers,
5447            pressed_button: None,
5448        });
5449        let _ = self.dispatch_event(event, cx);
5450    }
5451}
5452
5453// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
5454slotmap::new_key_type! {
5455    /// A unique identifier for a window.
5456    pub struct WindowId;
5457}
5458
5459impl WindowId {
5460    /// Converts this window ID to a `u64`.
5461    pub fn as_u64(&self) -> u64 {
5462        self.0.as_ffi()
5463    }
5464}
5465
5466impl From<u64> for WindowId {
5467    fn from(value: u64) -> Self {
5468        WindowId(slotmap::KeyData::from_ffi(value))
5469    }
5470}
5471
5472/// A handle to a window with a specific root view type.
5473/// Note that this does not keep the window alive on its own.
5474#[derive(Deref, DerefMut)]
5475pub struct WindowHandle<V> {
5476    #[deref]
5477    #[deref_mut]
5478    pub(crate) any_handle: AnyWindowHandle,
5479    state_type: PhantomData<fn(V) -> V>,
5480}
5481
5482impl<V> Debug for WindowHandle<V> {
5483    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5484        f.debug_struct("WindowHandle")
5485            .field("any_handle", &self.any_handle.id.as_u64())
5486            .finish()
5487    }
5488}
5489
5490impl<V: 'static + Render> WindowHandle<V> {
5491    /// Creates a new handle from a window ID.
5492    /// This does not check if the root type of the window is `V`.
5493    pub fn new(id: WindowId) -> Self {
5494        WindowHandle {
5495            any_handle: AnyWindowHandle {
5496                id,
5497                state_type: TypeId::of::<V>(),
5498            },
5499            state_type: PhantomData,
5500        }
5501    }
5502
5503    /// Get the root view out of this window.
5504    ///
5505    /// This will fail if the window is closed or if the root view's type does not match `V`.
5506    #[cfg(any(test, feature = "test-support"))]
5507    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
5508    where
5509        C: AppContext,
5510    {
5511        cx.update_window(self.any_handle, |root_view, _, _| {
5512            root_view
5513                .downcast::<V>()
5514                .map_err(|_| anyhow!("the type of the window's root view has changed"))
5515        })?
5516    }
5517
5518    /// Updates the root view of this window.
5519    ///
5520    /// This will fail if the window has been closed or if the root view's type does not match
5521    pub fn update<C, R>(
5522        &self,
5523        cx: &mut C,
5524        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
5525    ) -> Result<R>
5526    where
5527        C: AppContext,
5528    {
5529        cx.update_window(self.any_handle, |root_view, window, cx| {
5530            let view = root_view
5531                .downcast::<V>()
5532                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5533
5534            Ok(view.update(cx, |view, cx| update(view, window, cx)))
5535        })?
5536    }
5537
5538    /// Read the root view out of this window.
5539    ///
5540    /// This will fail if the window is closed or if the root view's type does not match `V`.
5541    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
5542        let x = cx
5543            .windows
5544            .get(self.id)
5545            .and_then(|window| {
5546                window
5547                    .as_deref()
5548                    .and_then(|window| window.root.clone())
5549                    .map(|root_view| root_view.downcast::<V>())
5550            })
5551            .context("window not found")?
5552            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5553
5554        Ok(x.read(cx))
5555    }
5556
5557    /// Read the root view out of this window, with a callback
5558    ///
5559    /// This will fail if the window is closed or if the root view's type does not match `V`.
5560    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
5561    where
5562        C: AppContext,
5563    {
5564        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
5565    }
5566
5567    /// Read the root view pointer off of this window.
5568    ///
5569    /// This will fail if the window is closed or if the root view's type does not match `V`.
5570    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
5571    where
5572        C: AppContext,
5573    {
5574        cx.read_window(self, |root_view, _cx| root_view)
5575    }
5576
5577    /// Check if this window is 'active'.
5578    ///
5579    /// Will return `None` if the window is closed or currently
5580    /// borrowed.
5581    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
5582        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
5583            .ok()
5584    }
5585}
5586
5587impl<V> Copy for WindowHandle<V> {}
5588
5589impl<V> Clone for WindowHandle<V> {
5590    fn clone(&self) -> Self {
5591        *self
5592    }
5593}
5594
5595impl<V> PartialEq for WindowHandle<V> {
5596    fn eq(&self, other: &Self) -> bool {
5597        self.any_handle == other.any_handle
5598    }
5599}
5600
5601impl<V> Eq for WindowHandle<V> {}
5602
5603impl<V> Hash for WindowHandle<V> {
5604    fn hash<H: Hasher>(&self, state: &mut H) {
5605        self.any_handle.hash(state);
5606    }
5607}
5608
5609impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
5610    fn from(val: WindowHandle<V>) -> Self {
5611        val.any_handle
5612    }
5613}
5614
5615/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
5616#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
5617pub struct AnyWindowHandle {
5618    pub(crate) id: WindowId,
5619    state_type: TypeId,
5620}
5621
5622impl AnyWindowHandle {
5623    /// Get the ID of this window.
5624    pub fn window_id(&self) -> WindowId {
5625        self.id
5626    }
5627
5628    /// Attempt to convert this handle to a window handle with a specific root view type.
5629    /// If the types do not match, this will return `None`.
5630    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
5631        if TypeId::of::<T>() == self.state_type {
5632            Some(WindowHandle {
5633                any_handle: *self,
5634                state_type: PhantomData,
5635            })
5636        } else {
5637            None
5638        }
5639    }
5640
5641    /// Updates the state of the root view of this window.
5642    ///
5643    /// This will fail if the window has been closed.
5644    pub fn update<C, R>(
5645        self,
5646        cx: &mut C,
5647        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
5648    ) -> Result<R>
5649    where
5650        C: AppContext,
5651    {
5652        cx.update_window(self, update)
5653    }
5654
5655    /// Read the state of the root view of this window.
5656    ///
5657    /// This will fail if the window has been closed.
5658    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
5659    where
5660        C: AppContext,
5661        T: 'static,
5662    {
5663        let view = self
5664            .downcast::<T>()
5665            .context("the type of the window's root view has changed")?;
5666
5667        cx.read_window(&view, read)
5668    }
5669}
5670
5671impl HasWindowHandle for Window {
5672    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
5673        self.platform_window.window_handle()
5674    }
5675}
5676
5677impl HasDisplayHandle for Window {
5678    fn display_handle(
5679        &self,
5680    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
5681        self.platform_window.display_handle()
5682    }
5683}
5684
5685/// An identifier for an [`Element`].
5686///
5687/// Can be constructed with a string, a number, or both, as well
5688/// as other internal representations.
5689#[derive(Clone, Debug, Eq, PartialEq, Hash)]
5690pub enum ElementId {
5691    /// The ID of a View element
5692    View(EntityId),
5693    /// An integer ID.
5694    Integer(u64),
5695    /// A string based ID.
5696    Name(SharedString),
5697    /// A UUID.
5698    Uuid(Uuid),
5699    /// An ID that's equated with a focus handle.
5700    FocusHandle(FocusId),
5701    /// A combination of a name and an integer.
5702    NamedInteger(SharedString, u64),
5703    /// A path.
5704    Path(Arc<std::path::Path>),
5705    /// A code location.
5706    CodeLocation(core::panic::Location<'static>),
5707    /// A labeled child of an element.
5708    NamedChild(Arc<ElementId>, SharedString),
5709    /// A byte array ID (used for text-anchors)
5710    OpaqueId([u8; 20]),
5711}
5712
5713impl ElementId {
5714    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
5715    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
5716        Self::NamedInteger(name.into(), integer as u64)
5717    }
5718}
5719
5720impl Display for ElementId {
5721    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5722        match self {
5723            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
5724            ElementId::Integer(ix) => write!(f, "{}", ix)?,
5725            ElementId::Name(name) => write!(f, "{}", name)?,
5726            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
5727            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
5728            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
5729            ElementId::Path(path) => write!(f, "{}", path.display())?,
5730            ElementId::CodeLocation(location) => write!(f, "{}", location)?,
5731            ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
5732            ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
5733        }
5734
5735        Ok(())
5736    }
5737}
5738
5739impl TryInto<SharedString> for ElementId {
5740    type Error = anyhow::Error;
5741
5742    fn try_into(self) -> anyhow::Result<SharedString> {
5743        if let ElementId::Name(name) = self {
5744            Ok(name)
5745        } else {
5746            anyhow::bail!("element id is not string")
5747        }
5748    }
5749}
5750
5751impl From<usize> for ElementId {
5752    fn from(id: usize) -> Self {
5753        ElementId::Integer(id as u64)
5754    }
5755}
5756
5757impl From<i32> for ElementId {
5758    fn from(id: i32) -> Self {
5759        Self::Integer(id as u64)
5760    }
5761}
5762
5763impl From<SharedString> for ElementId {
5764    fn from(name: SharedString) -> Self {
5765        ElementId::Name(name)
5766    }
5767}
5768
5769impl From<String> for ElementId {
5770    fn from(name: String) -> Self {
5771        ElementId::Name(name.into())
5772    }
5773}
5774
5775impl From<Arc<str>> for ElementId {
5776    fn from(name: Arc<str>) -> Self {
5777        ElementId::Name(name.into())
5778    }
5779}
5780
5781impl From<Arc<std::path::Path>> for ElementId {
5782    fn from(path: Arc<std::path::Path>) -> Self {
5783        ElementId::Path(path)
5784    }
5785}
5786
5787impl From<&'static str> for ElementId {
5788    fn from(name: &'static str) -> Self {
5789        ElementId::Name(SharedString::new_static(name))
5790    }
5791}
5792
5793impl<'a> From<&'a FocusHandle> for ElementId {
5794    fn from(handle: &'a FocusHandle) -> Self {
5795        ElementId::FocusHandle(handle.id)
5796    }
5797}
5798
5799impl From<(&'static str, EntityId)> for ElementId {
5800    fn from((name, id): (&'static str, EntityId)) -> Self {
5801        ElementId::NamedInteger(SharedString::new_static(name), id.as_u64())
5802    }
5803}
5804
5805impl From<(&'static str, usize)> for ElementId {
5806    fn from((name, id): (&'static str, usize)) -> Self {
5807        ElementId::NamedInteger(SharedString::new_static(name), id as u64)
5808    }
5809}
5810
5811impl From<(SharedString, usize)> for ElementId {
5812    fn from((name, id): (SharedString, usize)) -> Self {
5813        ElementId::NamedInteger(name, id as u64)
5814    }
5815}
5816
5817impl From<(&'static str, u64)> for ElementId {
5818    fn from((name, id): (&'static str, u64)) -> Self {
5819        ElementId::NamedInteger(SharedString::new_static(name), id)
5820    }
5821}
5822
5823impl From<Uuid> for ElementId {
5824    fn from(value: Uuid) -> Self {
5825        Self::Uuid(value)
5826    }
5827}
5828
5829impl From<(&'static str, u32)> for ElementId {
5830    fn from((name, id): (&'static str, u32)) -> Self {
5831        ElementId::NamedInteger(SharedString::new_static(name), u64::from(id))
5832    }
5833}
5834
5835impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
5836    fn from((id, name): (ElementId, T)) -> Self {
5837        ElementId::NamedChild(Arc::new(id), name.into())
5838    }
5839}
5840
5841impl From<&'static core::panic::Location<'static>> for ElementId {
5842    fn from(location: &'static core::panic::Location<'static>) -> Self {
5843        ElementId::CodeLocation(*location)
5844    }
5845}
5846
5847impl From<[u8; 20]> for ElementId {
5848    fn from(opaque_id: [u8; 20]) -> Self {
5849        ElementId::OpaqueId(opaque_id)
5850    }
5851}
5852
5853/// A rectangle to be rendered in the window at the given position and size.
5854/// Passed as an argument [`Window::paint_quad`].
5855#[derive(Clone)]
5856pub struct PaintQuad {
5857    /// The bounds of the quad within the window.
5858    pub bounds: Bounds<Pixels>,
5859    /// The radii of the quad's corners.
5860    pub corner_radii: Corners<Pixels>,
5861    /// The background color of the quad.
5862    pub background: Background,
5863    /// The widths of the quad's borders.
5864    pub border_widths: Edges<Pixels>,
5865    /// The color of the quad's borders.
5866    pub border_color: Hsla,
5867    /// The style of the quad's borders.
5868    pub border_style: BorderStyle,
5869}
5870
5871impl PaintQuad {
5872    /// Sets the corner radii of the quad.
5873    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
5874        PaintQuad {
5875            corner_radii: corner_radii.into(),
5876            ..self
5877        }
5878    }
5879
5880    /// Sets the border widths of the quad.
5881    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
5882        PaintQuad {
5883            border_widths: border_widths.into(),
5884            ..self
5885        }
5886    }
5887
5888    /// Sets the border color of the quad.
5889    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
5890        PaintQuad {
5891            border_color: border_color.into(),
5892            ..self
5893        }
5894    }
5895
5896    /// Sets the background color of the quad.
5897    pub fn background(self, background: impl Into<Background>) -> Self {
5898        PaintQuad {
5899            background: background.into(),
5900            ..self
5901        }
5902    }
5903}
5904
5905/// Creates a quad with the given parameters.
5906pub fn quad(
5907    bounds: Bounds<Pixels>,
5908    corner_radii: impl Into<Corners<Pixels>>,
5909    background: impl Into<Background>,
5910    border_widths: impl Into<Edges<Pixels>>,
5911    border_color: impl Into<Hsla>,
5912    border_style: BorderStyle,
5913) -> PaintQuad {
5914    PaintQuad {
5915        bounds,
5916        corner_radii: corner_radii.into(),
5917        background: background.into(),
5918        border_widths: border_widths.into(),
5919        border_color: border_color.into(),
5920        border_style,
5921    }
5922}
5923
5924/// Creates a filled quad with the given bounds and background color.
5925pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
5926    PaintQuad {
5927        bounds: bounds.into(),
5928        corner_radii: (0.).into(),
5929        background: background.into(),
5930        border_widths: (0.).into(),
5931        border_color: transparent_black(),
5932        border_style: BorderStyle::default(),
5933    }
5934}
5935
5936/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
5937pub fn outline(
5938    bounds: impl Into<Bounds<Pixels>>,
5939    border_color: impl Into<Hsla>,
5940    border_style: BorderStyle,
5941) -> PaintQuad {
5942    PaintQuad {
5943        bounds: bounds.into(),
5944        corner_radii: (0.).into(),
5945        background: transparent_black().into(),
5946        border_widths: (1.).into(),
5947        border_color: border_color.into(),
5948        border_style,
5949    }
5950}