Skip to main content

gpui/
window.rs

1#[cfg(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(debug_assertions)]
808    pub(crate) next_inspector_instance_ids: FxHashMap<Rc<crate::InspectorElementPath>, usize>,
809    #[cfg(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(debug_assertions)]
856            next_inspector_instance_ids: FxHashMap::default(),
857
858            #[cfg(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(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(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(debug_assertions)]
1635            inspector: None,
1636        })
1637    }
1638
1639    pub(crate) fn new_focus_listener(
1640        &self,
1641        value: AnyWindowFocusListener,
1642    ) -> (Subscription, impl FnOnce() + use<>) {
1643        self.focus_listeners.insert((), value)
1644    }
1645}
1646
1647#[derive(Clone, Debug, Default, PartialEq, Eq)]
1648#[expect(missing_docs)]
1649pub struct DispatchEventResult {
1650    pub propagate: bool,
1651    pub default_prevented: bool,
1652}
1653
1654/// Indicates which region of the window is visible. Content falling outside of this mask will not be
1655/// rendered. Currently, only rectangular content masks are supported, but we give the mask its own type
1656/// to leave room to support more complex shapes in the future.
1657#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
1658#[repr(C)]
1659pub struct ContentMask<P: Clone + Debug + Default + PartialEq> {
1660    /// The bounds
1661    pub bounds: Bounds<P>,
1662}
1663
1664impl ContentMask<Pixels> {
1665    /// Scale the content mask's pixel units by the given scaling factor.
1666    pub fn scale(&self, factor: f32) -> ContentMask<ScaledPixels> {
1667        ContentMask {
1668            bounds: self.bounds.scale(factor),
1669        }
1670    }
1671
1672    /// Intersect the content mask with the given content mask.
1673    pub fn intersect(&self, other: &Self) -> Self {
1674        let bounds = self.bounds.intersect(&other.bounds);
1675        ContentMask { bounds }
1676    }
1677}
1678
1679impl Window {
1680    fn mark_view_dirty(&mut self, view_id: EntityId) {
1681        // Mark ancestor views as dirty. If already in the `dirty_views` set, then all its ancestors
1682        // should already be dirty.
1683        for view_id in self
1684            .rendered_frame
1685            .dispatch_tree
1686            .view_path_reversed(view_id)
1687        {
1688            if !self.dirty_views.insert(view_id) {
1689                break;
1690            }
1691        }
1692    }
1693
1694    /// Registers a callback to be invoked when the window appearance changes.
1695    pub fn observe_window_appearance(
1696        &self,
1697        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1698    ) -> Subscription {
1699        let (subscription, activate) = self.appearance_observers.insert(
1700            (),
1701            Box::new(move |window, cx| {
1702                callback(window, cx);
1703                true
1704            }),
1705        );
1706        activate();
1707        subscription
1708    }
1709
1710    /// Registers a callback to be invoked when the window button layout changes.
1711    pub fn observe_button_layout_changed(
1712        &self,
1713        mut callback: impl FnMut(&mut Window, &mut App) + 'static,
1714    ) -> Subscription {
1715        let (subscription, activate) = self.button_layout_observers.insert(
1716            (),
1717            Box::new(move |window, cx| {
1718                callback(window, cx);
1719                true
1720            }),
1721        );
1722        activate();
1723        subscription
1724    }
1725
1726    /// Replaces the root entity of the window with a new one.
1727    pub fn replace_root<E>(
1728        &mut self,
1729        cx: &mut App,
1730        build_view: impl FnOnce(&mut Window, &mut Context<E>) -> E,
1731    ) -> Entity<E>
1732    where
1733        E: 'static + Render,
1734    {
1735        let view = cx.new(|cx| build_view(self, cx));
1736        self.root = Some(view.clone().into());
1737        self.refresh();
1738        view
1739    }
1740
1741    /// Returns the root entity of the window, if it has one.
1742    pub fn root<E>(&self) -> Option<Option<Entity<E>>>
1743    where
1744        E: 'static + Render,
1745    {
1746        self.root
1747            .as_ref()
1748            .map(|view| view.clone().downcast::<E>().ok())
1749    }
1750
1751    /// Obtain a handle to the window that belongs to this context.
1752    pub fn window_handle(&self) -> AnyWindowHandle {
1753        self.handle
1754    }
1755
1756    /// Mark the window as dirty, scheduling it to be redrawn on the next frame.
1757    pub fn refresh(&mut self) {
1758        if self.invalidator.not_drawing() {
1759            self.refreshing = true;
1760            self.invalidator.set_dirty(true);
1761        }
1762    }
1763
1764    /// Close this window.
1765    pub fn remove_window(&mut self) {
1766        self.removed = true;
1767    }
1768
1769    /// Obtain the currently focused [`FocusHandle`]. If no elements are focused, returns `None`.
1770    pub fn focused(&self, cx: &App) -> Option<FocusHandle> {
1771        self.focus
1772            .and_then(|id| FocusHandle::for_id(id, &cx.focus_handles))
1773    }
1774
1775    /// Move focus to the element associated with the given [`FocusHandle`].
1776    pub fn focus(&mut self, handle: &FocusHandle, cx: &mut App) {
1777        if !self.focus_enabled || self.focus == Some(handle.id) {
1778            return;
1779        }
1780
1781        self.focus = Some(handle.id);
1782        self.clear_pending_keystrokes();
1783
1784        // Avoid re-entrant entity updates by deferring observer notifications to the end of the
1785        // current effect cycle, and only for this window.
1786        let window_handle = self.handle;
1787        cx.defer(move |cx| {
1788            window_handle
1789                .update(cx, |_, window, cx| {
1790                    window.pending_input_changed(cx);
1791                })
1792                .ok();
1793        });
1794
1795        self.refresh();
1796    }
1797
1798    /// Remove focus from all elements within this context's window.
1799    pub fn blur(&mut self) {
1800        if !self.focus_enabled {
1801            return;
1802        }
1803
1804        self.focus = None;
1805        self.refresh();
1806    }
1807
1808    /// Blur the window and don't allow anything in it to be focused again.
1809    pub fn disable_focus(&mut self) {
1810        self.blur();
1811        self.focus_enabled = false;
1812    }
1813
1814    /// Move focus to next tab stop.
1815    pub fn focus_next(&mut self, cx: &mut App) {
1816        if !self.focus_enabled {
1817            return;
1818        }
1819
1820        if let Some(handle) = self.rendered_frame.tab_stops.next(self.focus.as_ref()) {
1821            self.focus(&handle, cx)
1822        }
1823    }
1824
1825    /// Move focus to previous tab stop.
1826    pub fn focus_prev(&mut self, cx: &mut App) {
1827        if !self.focus_enabled {
1828            return;
1829        }
1830
1831        if let Some(handle) = self.rendered_frame.tab_stops.prev(self.focus.as_ref()) {
1832            self.focus(&handle, cx)
1833        }
1834    }
1835
1836    /// Accessor for the text system.
1837    pub fn text_system(&self) -> &Arc<WindowTextSystem> {
1838        &self.text_system
1839    }
1840
1841    /// The current text style. Which is composed of all the style refinements provided to `with_text_style`.
1842    pub fn text_style(&self) -> TextStyle {
1843        let mut style = TextStyle::default();
1844        for refinement in &self.text_style_stack {
1845            style.refine(refinement);
1846        }
1847        style
1848    }
1849
1850    /// Check if the platform window is maximized.
1851    ///
1852    /// On some platforms (namely Windows) this is different than the bounds being the size of the display
1853    pub fn is_maximized(&self) -> bool {
1854        self.platform_window.is_maximized()
1855    }
1856
1857    /// request a certain window decoration (Wayland)
1858    pub fn request_decorations(&self, decorations: WindowDecorations) {
1859        self.platform_window.request_decorations(decorations);
1860    }
1861
1862    /// Start a window resize operation (Wayland)
1863    pub fn start_window_resize(&self, edge: ResizeEdge) {
1864        self.platform_window.start_window_resize(edge);
1865    }
1866
1867    /// Return the `WindowBounds` to indicate that how a window should be opened
1868    /// after it has been closed
1869    pub fn window_bounds(&self) -> WindowBounds {
1870        self.platform_window.window_bounds()
1871    }
1872
1873    /// Return the `WindowBounds` excluding insets (Wayland and X11)
1874    pub fn inner_window_bounds(&self) -> WindowBounds {
1875        self.platform_window.inner_window_bounds()
1876    }
1877
1878    /// Dispatch the given action on the currently focused element.
1879    pub fn dispatch_action(&mut self, action: Box<dyn Action>, cx: &mut App) {
1880        let focus_id = self.focused(cx).map(|handle| handle.id);
1881
1882        let window = self.handle;
1883        cx.defer(move |cx| {
1884            window
1885                .update(cx, |_, window, cx| {
1886                    let node_id = window.focus_node_id_in_rendered_frame(focus_id);
1887                    window.dispatch_action_on_node(node_id, action.as_ref(), cx);
1888                })
1889                .log_err();
1890        })
1891    }
1892
1893    pub(crate) fn dispatch_keystroke_observers(
1894        &mut self,
1895        event: &dyn Any,
1896        action: Option<Box<dyn Action>>,
1897        context_stack: Vec<KeyContext>,
1898        cx: &mut App,
1899    ) {
1900        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1901            return;
1902        };
1903
1904        cx.keystroke_observers.clone().retain(&(), move |callback| {
1905            (callback)(
1906                &KeystrokeEvent {
1907                    keystroke: key_down_event.keystroke.clone(),
1908                    action: action.as_ref().map(|action| action.boxed_clone()),
1909                    context_stack: context_stack.clone(),
1910                },
1911                self,
1912                cx,
1913            )
1914        });
1915    }
1916
1917    pub(crate) fn dispatch_keystroke_interceptors(
1918        &mut self,
1919        event: &dyn Any,
1920        context_stack: Vec<KeyContext>,
1921        cx: &mut App,
1922    ) {
1923        let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() else {
1924            return;
1925        };
1926
1927        cx.keystroke_interceptors
1928            .clone()
1929            .retain(&(), move |callback| {
1930                (callback)(
1931                    &KeystrokeEvent {
1932                        keystroke: key_down_event.keystroke.clone(),
1933                        action: None,
1934                        context_stack: context_stack.clone(),
1935                    },
1936                    self,
1937                    cx,
1938                )
1939            });
1940    }
1941
1942    /// Schedules the given function to be run at the end of the current effect cycle, allowing entities
1943    /// that are currently on the stack to be returned to the app.
1944    pub fn defer(&self, cx: &mut App, f: impl FnOnce(&mut Window, &mut App) + 'static) {
1945        let handle = self.handle;
1946        cx.defer(move |cx| {
1947            handle.update(cx, |_, window, cx| f(window, cx)).ok();
1948        });
1949    }
1950
1951    /// Subscribe to events emitted by a entity.
1952    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1953    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1954    pub fn observe<T: 'static>(
1955        &mut self,
1956        observed: &Entity<T>,
1957        cx: &mut App,
1958        mut on_notify: impl FnMut(Entity<T>, &mut Window, &mut App) + 'static,
1959    ) -> Subscription {
1960        let entity_id = observed.entity_id();
1961        let observed = observed.downgrade();
1962        let window_handle = self.handle;
1963        cx.new_observer(
1964            entity_id,
1965            Box::new(move |cx| {
1966                window_handle
1967                    .update(cx, |_, window, cx| {
1968                        if let Some(handle) = observed.upgrade() {
1969                            on_notify(handle, window, cx);
1970                            true
1971                        } else {
1972                            false
1973                        }
1974                    })
1975                    .unwrap_or(false)
1976            }),
1977        )
1978    }
1979
1980    /// Subscribe to events emitted by a entity.
1981    /// The entity to which you're subscribing must implement the [`EventEmitter`] trait.
1982    /// The callback will be invoked a handle to the emitting entity, the event, and a window context for the current window.
1983    pub fn subscribe<Emitter, Evt>(
1984        &mut self,
1985        entity: &Entity<Emitter>,
1986        cx: &mut App,
1987        mut on_event: impl FnMut(Entity<Emitter>, &Evt, &mut Window, &mut App) + 'static,
1988    ) -> Subscription
1989    where
1990        Emitter: EventEmitter<Evt>,
1991        Evt: 'static,
1992    {
1993        let entity_id = entity.entity_id();
1994        let handle = entity.downgrade();
1995        let window_handle = self.handle;
1996        cx.new_subscription(
1997            entity_id,
1998            (
1999                TypeId::of::<Evt>(),
2000                Box::new(move |event, cx| {
2001                    window_handle
2002                        .update(cx, |_, window, cx| {
2003                            if let Some(entity) = handle.upgrade() {
2004                                let event = event.downcast_ref().expect("invalid event type");
2005                                on_event(entity, event, window, cx);
2006                                true
2007                            } else {
2008                                false
2009                            }
2010                        })
2011                        .unwrap_or(false)
2012                }),
2013            ),
2014        )
2015    }
2016
2017    /// Register a callback to be invoked when the given `Entity` is released.
2018    pub fn observe_release<T>(
2019        &self,
2020        entity: &Entity<T>,
2021        cx: &mut App,
2022        mut on_release: impl FnOnce(&mut T, &mut Window, &mut App) + 'static,
2023    ) -> Subscription
2024    where
2025        T: 'static,
2026    {
2027        let entity_id = entity.entity_id();
2028        let window_handle = self.handle;
2029        let (subscription, activate) = cx.release_listeners.insert(
2030            entity_id,
2031            Box::new(move |entity, cx| {
2032                let entity = entity.downcast_mut().expect("invalid entity type");
2033                let _ = window_handle.update(cx, |_, window, cx| on_release(entity, window, cx));
2034            }),
2035        );
2036        activate();
2037        subscription
2038    }
2039
2040    /// Creates an [`AsyncWindowContext`], which has a static lifetime and can be held across
2041    /// await points in async code.
2042    pub fn to_async(&self, cx: &App) -> AsyncWindowContext {
2043        AsyncWindowContext::new_context(cx.to_async(), self.handle)
2044    }
2045
2046    /// Schedule the given closure to be run directly after the current frame is rendered.
2047    pub fn on_next_frame(&self, callback: impl FnOnce(&mut Window, &mut App) + 'static) {
2048        RefCell::borrow_mut(&self.next_frame_callbacks).push(Box::new(callback));
2049    }
2050
2051    /// Schedule a frame to be drawn on the next animation frame.
2052    ///
2053    /// This is useful for elements that need to animate continuously, such as a video player or an animated GIF.
2054    /// It will cause the window to redraw on the next frame, even if no other changes have occurred.
2055    ///
2056    /// If called from within a view, it will notify that view on the next frame. Otherwise, it will refresh the entire window.
2057    pub fn request_animation_frame(&self) {
2058        let entity = self.current_view();
2059        self.on_next_frame(move |_, cx| cx.notify(entity));
2060    }
2061
2062    /// Spawn the future returned by the given closure on the application thread pool.
2063    /// The closure is provided a handle to the current window and an `AsyncWindowContext` for
2064    /// use within your future.
2065    #[track_caller]
2066    pub fn spawn<AsyncFn, R>(&self, cx: &App, f: AsyncFn) -> Task<R>
2067    where
2068        R: 'static,
2069        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2070    {
2071        let handle = self.handle;
2072        cx.spawn(async move |app| {
2073            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2074            f(&mut async_window_cx).await
2075        })
2076    }
2077
2078    /// Spawn the future returned by the given closure on the application thread
2079    /// pool, with the given priority. The closure is provided a handle to the
2080    /// current window and an `AsyncWindowContext` for use within your future.
2081    #[track_caller]
2082    pub fn spawn_with_priority<AsyncFn, R>(
2083        &self,
2084        priority: Priority,
2085        cx: &App,
2086        f: AsyncFn,
2087    ) -> Task<R>
2088    where
2089        R: 'static,
2090        AsyncFn: AsyncFnOnce(&mut AsyncWindowContext) -> R + 'static,
2091    {
2092        let handle = self.handle;
2093        cx.spawn_with_priority(priority, async move |app| {
2094            let mut async_window_cx = AsyncWindowContext::new_context(app.clone(), handle);
2095            f(&mut async_window_cx).await
2096        })
2097    }
2098
2099    /// Notify the window that its bounds have changed.
2100    ///
2101    /// This updates internal state like `viewport_size` and `scale_factor` from
2102    /// the platform window, then notifies observers. Normally called automatically
2103    /// by the platform's resize callback, but exposed publicly for test infrastructure.
2104    pub fn bounds_changed(&mut self, cx: &mut App) {
2105        self.scale_factor = self.platform_window.scale_factor();
2106        self.viewport_size = self.platform_window.content_size();
2107        self.display_id = self.platform_window.display().map(|display| display.id());
2108
2109        self.refresh();
2110
2111        self.bounds_observers
2112            .clone()
2113            .retain(&(), |callback| callback(self, cx));
2114    }
2115
2116    /// Returns the bounds of the current window in the global coordinate space, which could span across multiple displays.
2117    pub fn bounds(&self) -> Bounds<Pixels> {
2118        self.platform_window.bounds()
2119    }
2120
2121    /// Renders the current frame's scene to a texture and returns the pixel data as an RGBA image.
2122    /// This does not present the frame to screen - useful for visual testing where we want
2123    /// to capture what would be rendered without displaying it or requiring the window to be visible.
2124    #[cfg(any(test, feature = "test-support"))]
2125    pub fn render_to_image(&self) -> anyhow::Result<image::RgbaImage> {
2126        self.platform_window
2127            .render_to_image(&self.rendered_frame.scene)
2128    }
2129
2130    /// Set the content size of the window.
2131    pub fn resize(&mut self, size: Size<Pixels>) {
2132        self.platform_window.resize(size);
2133    }
2134
2135    /// Returns whether or not the window is currently fullscreen
2136    pub fn is_fullscreen(&self) -> bool {
2137        self.platform_window.is_fullscreen()
2138    }
2139
2140    pub(crate) fn appearance_changed(&mut self, cx: &mut App) {
2141        self.appearance = self.platform_window.appearance();
2142
2143        self.appearance_observers
2144            .clone()
2145            .retain(&(), |callback| callback(self, cx));
2146    }
2147
2148    pub(crate) fn button_layout_changed(&mut self, cx: &mut App) {
2149        self.button_layout_observers
2150            .clone()
2151            .retain(&(), |callback| callback(self, cx));
2152    }
2153
2154    /// Returns the appearance of the current window.
2155    pub fn appearance(&self) -> WindowAppearance {
2156        self.appearance
2157    }
2158
2159    /// Returns the size of the drawable area within the window.
2160    pub fn viewport_size(&self) -> Size<Pixels> {
2161        self.viewport_size
2162    }
2163
2164    /// Returns whether this window is focused by the operating system (receiving key events).
2165    pub fn is_window_active(&self) -> bool {
2166        self.active.get()
2167    }
2168
2169    /// Returns whether this window is considered to be the window
2170    /// that currently owns the mouse cursor.
2171    /// On mac, this is equivalent to `is_window_active`.
2172    pub fn is_window_hovered(&self) -> bool {
2173        if cfg!(any(
2174            target_os = "windows",
2175            target_os = "linux",
2176            target_os = "freebsd"
2177        )) {
2178            self.hovered.get()
2179        } else {
2180            self.is_window_active()
2181        }
2182    }
2183
2184    /// Toggle zoom on the window.
2185    pub fn zoom_window(&self) {
2186        self.platform_window.zoom();
2187    }
2188
2189    /// Opens the native title bar context menu, useful when implementing client side decorations (Wayland and X11)
2190    pub fn show_window_menu(&self, position: Point<Pixels>) {
2191        self.platform_window.show_window_menu(position)
2192    }
2193
2194    /// Handle window movement for Linux and macOS.
2195    /// Tells the compositor to take control of window movement (Wayland and X11)
2196    ///
2197    /// Events may not be received during a move operation.
2198    pub fn start_window_move(&self) {
2199        self.platform_window.start_window_move()
2200    }
2201
2202    /// When using client side decorations, set this to the width of the invisible decorations (Wayland and X11)
2203    pub fn set_client_inset(&mut self, inset: Pixels) {
2204        self.client_inset = Some(inset);
2205        self.platform_window.set_client_inset(inset);
2206    }
2207
2208    /// Returns the client_inset value by [`Self::set_client_inset`].
2209    pub fn client_inset(&self) -> Option<Pixels> {
2210        self.client_inset
2211    }
2212
2213    /// Returns whether the title bar window controls need to be rendered by the application (Wayland and X11)
2214    pub fn window_decorations(&self) -> Decorations {
2215        self.platform_window.window_decorations()
2216    }
2217
2218    /// Returns which window controls are currently visible (Wayland)
2219    pub fn window_controls(&self) -> WindowControls {
2220        self.platform_window.window_controls()
2221    }
2222
2223    /// Updates the window's title at the platform level.
2224    pub fn set_window_title(&mut self, title: &str) {
2225        self.platform_window.set_title(title);
2226    }
2227
2228    /// Sets the application identifier.
2229    pub fn set_app_id(&mut self, app_id: &str) {
2230        self.platform_window.set_app_id(app_id);
2231    }
2232
2233    /// Sets the window background appearance.
2234    pub fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {
2235        self.platform_window
2236            .set_background_appearance(background_appearance);
2237    }
2238
2239    /// Mark the window as dirty at the platform level.
2240    pub fn set_window_edited(&mut self, edited: bool) {
2241        self.platform_window.set_edited(edited);
2242    }
2243
2244    /// Set the path of the file this window represents.
2245    /// On macOS, this sets the window's accessibility document property (AXDocument).
2246    pub fn set_document_path(&self, path: Option<&std::path::Path>) {
2247        self.platform_window.set_document_path(path);
2248    }
2249
2250    /// Determine the display on which the window is visible.
2251    pub fn display(&self, cx: &App) -> Option<Rc<dyn PlatformDisplay>> {
2252        cx.platform
2253            .displays()
2254            .into_iter()
2255            .find(|display| Some(display.id()) == self.display_id)
2256    }
2257
2258    /// Show the platform character palette.
2259    pub fn show_character_palette(&self) {
2260        self.platform_window.show_character_palette();
2261    }
2262
2263    /// The scale factor of the display associated with the window. For example, it could
2264    /// return 2.0 for a "retina" display, indicating that each logical pixel should actually
2265    /// be rendered as two pixels on screen.
2266    pub fn scale_factor(&self) -> f32 {
2267        self.scale_factor
2268    }
2269
2270    /// The size of an em for the base font of the application. Adjusting this value allows the
2271    /// UI to scale, just like zooming a web page.
2272    pub fn rem_size(&self) -> Pixels {
2273        self.rem_size_override_stack
2274            .last()
2275            .copied()
2276            .unwrap_or(self.rem_size)
2277    }
2278
2279    /// Sets the size of an em for the base font of the application. Adjusting this value allows the
2280    /// UI to scale, just like zooming a web page.
2281    pub fn set_rem_size(&mut self, rem_size: impl Into<Pixels>) {
2282        self.rem_size = rem_size.into();
2283    }
2284
2285    /// Acquire a globally unique identifier for the given ElementId.
2286    /// Only valid for the duration of the provided closure.
2287    pub fn with_global_id<R>(
2288        &mut self,
2289        element_id: ElementId,
2290        f: impl FnOnce(&GlobalElementId, &mut Self) -> R,
2291    ) -> R {
2292        self.with_id(element_id, |this| {
2293            let global_id = GlobalElementId(Arc::from(&*this.element_id_stack));
2294
2295            f(&global_id, this)
2296        })
2297    }
2298
2299    /// Calls the provided closure with the element ID pushed on the stack.
2300    #[inline]
2301    pub fn with_id<R>(
2302        &mut self,
2303        element_id: impl Into<ElementId>,
2304        f: impl FnOnce(&mut Self) -> R,
2305    ) -> R {
2306        self.element_id_stack.push(element_id.into());
2307        let result = f(self);
2308        self.element_id_stack.pop();
2309        result
2310    }
2311
2312    /// Executes the provided function with the specified rem size.
2313    ///
2314    /// This method must only be called as part of element drawing.
2315    // This function is called in a highly recursive manner in editor
2316    // prepainting, make sure its inlined to reduce the stack burden
2317    #[inline]
2318    pub fn with_rem_size<F, R>(&mut self, rem_size: Option<impl Into<Pixels>>, f: F) -> R
2319    where
2320        F: FnOnce(&mut Self) -> R,
2321    {
2322        self.invalidator.debug_assert_paint_or_prepaint();
2323
2324        if let Some(rem_size) = rem_size {
2325            self.rem_size_override_stack.push(rem_size.into());
2326            let result = f(self);
2327            self.rem_size_override_stack.pop();
2328            result
2329        } else {
2330            f(self)
2331        }
2332    }
2333
2334    /// The line height associated with the current text style.
2335    pub fn line_height(&self) -> Pixels {
2336        self.text_style().line_height_in_pixels(self.rem_size())
2337    }
2338
2339    /// Rounds a logical value to the nearest device pixel.
2340    #[inline]
2341    pub fn pixel_snap(&self, value: Pixels) -> Pixels {
2342        px(round_to_device_pixel(value.0, self.scale_factor()) / self.scale_factor())
2343    }
2344
2345    /// f64 variant of [`Self::pixel_snap`].
2346    #[inline]
2347    pub fn pixel_snap_f64(&self, value: f64) -> f64 {
2348        let scale_factor = f64::from(self.scale_factor());
2349        round_half_toward_zero_f64(value * scale_factor) / scale_factor
2350    }
2351
2352    /// Snaps a bounds' origin and size to the nearest device pixel.
2353    #[inline]
2354    pub fn pixel_snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<Pixels> {
2355        bounds.map(|c| self.pixel_snap(c))
2356    }
2357
2358    /// Snaps a point's coordinates to the nearest device pixel.
2359    #[inline]
2360    pub fn pixel_snap_point(&self, position: Point<Pixels>) -> Point<Pixels> {
2361        position.map(|c| self.pixel_snap(c))
2362    }
2363
2364    #[inline]
2365    fn snap_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2366        let scale_factor = self.scale_factor();
2367        let left = round_to_device_pixel(bounds.left().0, scale_factor);
2368        let top = round_to_device_pixel(bounds.top().0, scale_factor);
2369        let right = round_to_device_pixel(bounds.right().0, scale_factor).max(left);
2370        let bottom = round_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2371        Bounds::from_corners(
2372            point(ScaledPixels(left), ScaledPixels(top)),
2373            point(ScaledPixels(right), ScaledPixels(bottom)),
2374        )
2375    }
2376
2377    /// Rounds half-to-zero but clamps any non-zero input up to 1 dp so thin strokes do not disappear.
2378    #[inline]
2379    fn snap_stroke(&self, value: Pixels) -> ScaledPixels {
2380        ScaledPixels(round_stroke_to_device_pixel(value.0, self.scale_factor()))
2381    }
2382
2383    #[inline]
2384    fn snap_border_widths(&self, edges: Edges<Pixels>) -> Edges<ScaledPixels> {
2385        edges.map(|e| self.snap_stroke(*e))
2386    }
2387
2388    /// Floors the near edge and ceils the far edge, producing a strict superset of the raw region.
2389    #[inline]
2390    fn cover_bounds(&self, bounds: Bounds<Pixels>) -> Bounds<ScaledPixels> {
2391        let scale_factor = self.scale_factor();
2392        let left = floor_to_device_pixel(bounds.left().0, scale_factor);
2393        let top = floor_to_device_pixel(bounds.top().0, scale_factor);
2394        let right = ceil_to_device_pixel(bounds.right().0, scale_factor).max(left);
2395        let bottom = ceil_to_device_pixel(bounds.bottom().0, scale_factor).max(top);
2396        Bounds::from_corners(
2397            point(ScaledPixels(left), ScaledPixels(top)),
2398            point(ScaledPixels(right), ScaledPixels(bottom)),
2399        )
2400    }
2401
2402    #[inline]
2403    fn snapped_content_mask(&self) -> ContentMask<ScaledPixels> {
2404        ContentMask {
2405            bounds: self.cover_bounds(self.content_mask().bounds),
2406        }
2407    }
2408
2409    /// Call to prevent the default action of an event. Currently only used to prevent
2410    /// parent elements from becoming focused on mouse down.
2411    pub fn prevent_default(&mut self) {
2412        self.default_prevented = true;
2413    }
2414
2415    /// Obtain whether default has been prevented for the event currently being dispatched.
2416    pub fn default_prevented(&self) -> bool {
2417        self.default_prevented
2418    }
2419
2420    /// Determine whether the given action is available along the dispatch path to the currently focused element.
2421    pub fn is_action_available(&self, action: &dyn Action, cx: &App) -> bool {
2422        let node_id =
2423            self.focus_node_id_in_rendered_frame(self.focused(cx).map(|handle| handle.id));
2424        self.rendered_frame
2425            .dispatch_tree
2426            .is_action_available(action, node_id)
2427    }
2428
2429    /// Determine whether the given action is available along the dispatch path to the given focus_handle.
2430    pub fn is_action_available_in(&self, action: &dyn Action, focus_handle: &FocusHandle) -> bool {
2431        let node_id = self.focus_node_id_in_rendered_frame(Some(focus_handle.id));
2432        self.rendered_frame
2433            .dispatch_tree
2434            .is_action_available(action, node_id)
2435    }
2436
2437    /// The position of the mouse relative to the window.
2438    pub fn mouse_position(&self) -> Point<Pixels> {
2439        self.mouse_position
2440    }
2441
2442    /// Captures the pointer for the given hitbox. While captured, all mouse move and mouse up
2443    /// events will be routed to listeners that check this hitbox's `is_hovered` status,
2444    /// regardless of actual hit testing. This enables drag operations that continue
2445    /// even when the pointer moves outside the element's bounds.
2446    ///
2447    /// The capture is automatically released on mouse up.
2448    pub fn capture_pointer(&mut self, hitbox_id: HitboxId) {
2449        self.captured_hitbox = Some(hitbox_id);
2450    }
2451
2452    /// Releases any active pointer capture.
2453    pub fn release_pointer(&mut self) {
2454        self.captured_hitbox = None;
2455    }
2456
2457    /// Returns the hitbox that has captured the pointer, if any.
2458    pub fn captured_hitbox(&self) -> Option<HitboxId> {
2459        self.captured_hitbox
2460    }
2461
2462    /// The current state of the keyboard's modifiers
2463    pub fn modifiers(&self) -> Modifiers {
2464        self.modifiers
2465    }
2466
2467    /// Returns true if the last input event was keyboard-based (key press, tab navigation, etc.)
2468    /// This is used for focus-visible styling to show focus indicators only for keyboard navigation.
2469    pub fn last_input_was_keyboard(&self) -> bool {
2470        self.last_input_modality == InputModality::Keyboard
2471    }
2472
2473    /// The current state of the keyboard's capslock
2474    pub fn capslock(&self) -> Capslock {
2475        self.capslock
2476    }
2477
2478    fn complete_frame(&self) {
2479        self.platform_window.completed_frame();
2480    }
2481
2482    /// Produces a new frame and assigns it to `rendered_frame`. To actually show
2483    /// the contents of the new [`Scene`], use [`Self::present`].
2484    #[profiling::function]
2485    pub fn draw(&mut self, cx: &mut App) -> ArenaClearNeeded {
2486        // Set up the per-App arena for element allocation during this draw.
2487        // This ensures that multiple test Apps have isolated arenas.
2488        let _arena_scope = ElementArenaScope::enter(&cx.element_arena);
2489
2490        self.invalidate_entities();
2491        cx.entities.clear_accessed();
2492        debug_assert!(self.rendered_entity_stack.is_empty());
2493        self.invalidator.set_dirty(false);
2494        self.requested_autoscroll = None;
2495
2496        // Restore the previously-used input handler.
2497        if let Some(input_handler) = self.platform_window.take_input_handler() {
2498            self.rendered_frame.input_handlers.push(Some(input_handler));
2499        }
2500        if !cx.mode.skip_drawing() {
2501            self.draw_roots(cx);
2502        }
2503        self.dirty_views.clear();
2504        self.next_frame.window_active = self.active.get();
2505
2506        // Register requested input handler with the platform window.
2507        if let Some(input_handler) = self.next_frame.input_handlers.pop() {
2508            self.platform_window
2509                .set_input_handler(input_handler.unwrap());
2510        }
2511
2512        self.layout_engine.as_mut().unwrap().clear();
2513        self.text_system().finish_frame();
2514        self.next_frame.finish(&mut self.rendered_frame);
2515
2516        self.invalidator.set_phase(DrawPhase::Focus);
2517        let previous_focus_path = self.rendered_frame.focus_path();
2518        let previous_window_active = self.rendered_frame.window_active;
2519        mem::swap(&mut self.rendered_frame, &mut self.next_frame);
2520        self.next_frame.clear();
2521        let current_focus_path = self.rendered_frame.focus_path();
2522        let current_window_active = self.rendered_frame.window_active;
2523
2524        if previous_focus_path != current_focus_path
2525            || previous_window_active != current_window_active
2526        {
2527            if !previous_focus_path.is_empty() && current_focus_path.is_empty() {
2528                self.focus_lost_listeners
2529                    .clone()
2530                    .retain(&(), |listener| listener(self, cx));
2531            }
2532
2533            let event = WindowFocusEvent {
2534                previous_focus_path: if previous_window_active {
2535                    previous_focus_path
2536                } else {
2537                    Default::default()
2538                },
2539                current_focus_path: if current_window_active {
2540                    current_focus_path
2541                } else {
2542                    Default::default()
2543                },
2544            };
2545            self.focus_listeners
2546                .clone()
2547                .retain(&(), |listener| listener(&event, self, cx));
2548        }
2549
2550        debug_assert!(self.rendered_entity_stack.is_empty());
2551        self.record_entities_accessed(cx);
2552        self.reset_cursor_style(cx);
2553        self.refreshing = false;
2554        self.invalidator.set_phase(DrawPhase::None);
2555        self.needs_present.set(true);
2556
2557        ArenaClearNeeded::new(&cx.element_arena)
2558    }
2559
2560    fn record_entities_accessed(&mut self, cx: &mut App) {
2561        let mut entities_ref = cx.entities.accessed_entities.get_mut();
2562        let mut entities = mem::take(entities_ref.deref_mut());
2563        let handle = self.handle;
2564        cx.record_entities_accessed(
2565            handle,
2566            // Try moving window invalidator into the Window
2567            self.invalidator.clone(),
2568            &entities,
2569        );
2570        let mut entities_ref = cx.entities.accessed_entities.get_mut();
2571        mem::swap(&mut entities, entities_ref.deref_mut());
2572    }
2573
2574    fn invalidate_entities(&mut self) {
2575        let mut views = self.invalidator.take_views();
2576        for entity in views.drain() {
2577            self.mark_view_dirty(entity);
2578        }
2579        self.invalidator.replace_views(views);
2580    }
2581
2582    #[profiling::function]
2583    fn present(&mut self) {
2584        self.platform_window.draw(&self.rendered_frame.scene);
2585        #[cfg(feature = "input-latency-histogram")]
2586        self.input_latency_tracker.record_frame_presented();
2587        self.needs_present.set(false);
2588        profiling::finish_frame!();
2589    }
2590
2591    /// Returns a snapshot of the current input-latency histograms.
2592    #[cfg(feature = "input-latency-histogram")]
2593    pub fn input_latency_snapshot(&self) -> InputLatencySnapshot {
2594        self.input_latency_tracker.snapshot()
2595    }
2596
2597    fn draw_roots(&mut self, cx: &mut App) {
2598        self.invalidator.set_phase(DrawPhase::Prepaint);
2599        self.tooltip_bounds.take();
2600
2601        let _inspector_width: Pixels = rems(30.0).to_pixels(self.rem_size());
2602        let root_size = {
2603            #[cfg(debug_assertions)]
2604            {
2605                if self.inspector.is_some() {
2606                    let mut size = self.viewport_size;
2607                    size.width = (size.width - _inspector_width).max(px(0.0));
2608                    size
2609                } else {
2610                    self.viewport_size
2611                }
2612            }
2613            #[cfg(not(debug_assertions))]
2614            {
2615                self.viewport_size
2616            }
2617        };
2618
2619        // Layout all root elements.
2620        let mut root_element = self.root.as_ref().unwrap().clone().into_any();
2621        root_element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2622
2623        #[cfg(debug_assertions)]
2624        let inspector_element = self.prepaint_inspector(_inspector_width, cx);
2625
2626        self.prepaint_deferred_draws(cx);
2627
2628        let mut prompt_element = None;
2629        let mut active_drag_element = None;
2630        let mut tooltip_element = None;
2631        if let Some(prompt) = self.prompt.take() {
2632            let mut element = prompt.view.any_view().into_any();
2633            element.prepaint_as_root(Point::default(), root_size.into(), self, cx);
2634            prompt_element = Some(element);
2635            self.prompt = Some(prompt);
2636        } else if let Some(active_drag) = cx.active_drag.take() {
2637            let mut element = active_drag.view.clone().into_any();
2638            let offset = self.mouse_position() - active_drag.cursor_offset;
2639            element.prepaint_as_root(offset, AvailableSpace::min_size(), self, cx);
2640            active_drag_element = Some(element);
2641            cx.active_drag = Some(active_drag);
2642        } else {
2643            tooltip_element = self.prepaint_tooltip(cx);
2644        }
2645
2646        self.mouse_hit_test = self.next_frame.hit_test(self.mouse_position);
2647
2648        // Now actually paint the elements.
2649        self.invalidator.set_phase(DrawPhase::Paint);
2650        root_element.paint(self, cx);
2651
2652        #[cfg(debug_assertions)]
2653        self.paint_inspector(inspector_element, cx);
2654
2655        self.paint_deferred_draws(cx);
2656
2657        if let Some(mut prompt_element) = prompt_element {
2658            prompt_element.paint(self, cx);
2659        } else if let Some(mut drag_element) = active_drag_element {
2660            drag_element.paint(self, cx);
2661        } else if let Some(mut tooltip_element) = tooltip_element {
2662            tooltip_element.paint(self, cx);
2663        }
2664
2665        #[cfg(debug_assertions)]
2666        self.paint_inspector_hitbox(cx);
2667    }
2668
2669    fn prepaint_tooltip(&mut self, cx: &mut App) -> Option<AnyElement> {
2670        // Use indexing instead of iteration to avoid borrowing self for the duration of the loop.
2671        for tooltip_request_index in (0..self.next_frame.tooltip_requests.len()).rev() {
2672            let Some(Some(tooltip_request)) = self
2673                .next_frame
2674                .tooltip_requests
2675                .get(tooltip_request_index)
2676                .cloned()
2677            else {
2678                log::error!("Unexpectedly absent TooltipRequest");
2679                continue;
2680            };
2681            let mut element = tooltip_request.tooltip.view.clone().into_any();
2682            let mouse_position = tooltip_request.tooltip.mouse_position;
2683            let tooltip_size = element.layout_as_root(AvailableSpace::min_size(), self, cx);
2684
2685            let mut tooltip_bounds =
2686                Bounds::new(mouse_position + point(px(1.), px(1.)), tooltip_size);
2687            let window_bounds = Bounds {
2688                origin: Point::default(),
2689                size: self.viewport_size(),
2690            };
2691
2692            if tooltip_bounds.right() > window_bounds.right() {
2693                let new_x = mouse_position.x - tooltip_bounds.size.width - px(1.);
2694                if new_x >= Pixels::ZERO {
2695                    tooltip_bounds.origin.x = new_x;
2696                } else {
2697                    tooltip_bounds.origin.x = cmp::max(
2698                        Pixels::ZERO,
2699                        tooltip_bounds.origin.x - tooltip_bounds.right() - window_bounds.right(),
2700                    );
2701                }
2702            }
2703
2704            if tooltip_bounds.bottom() > window_bounds.bottom() {
2705                let new_y = mouse_position.y - tooltip_bounds.size.height - px(1.);
2706                if new_y >= Pixels::ZERO {
2707                    tooltip_bounds.origin.y = new_y;
2708                } else {
2709                    tooltip_bounds.origin.y = cmp::max(
2710                        Pixels::ZERO,
2711                        tooltip_bounds.origin.y - tooltip_bounds.bottom() - window_bounds.bottom(),
2712                    );
2713                }
2714            }
2715
2716            // It's possible for an element to have an active tooltip while not being painted (e.g.
2717            // via the `visible_on_hover` method). Since mouse listeners are not active in this
2718            // case, instead update the tooltip's visibility here.
2719            let is_visible =
2720                (tooltip_request.tooltip.check_visible_and_update)(tooltip_bounds, self, cx);
2721            if !is_visible {
2722                continue;
2723            }
2724
2725            self.with_absolute_element_offset(tooltip_bounds.origin, |window| {
2726                element.prepaint(window, cx)
2727            });
2728
2729            self.tooltip_bounds = Some(TooltipBounds {
2730                id: tooltip_request.id,
2731                bounds: tooltip_bounds,
2732            });
2733            return Some(element);
2734        }
2735        None
2736    }
2737
2738    fn prepaint_deferred_draws(&mut self, cx: &mut App) {
2739        assert_eq!(self.element_id_stack.len(), 0);
2740
2741        let mut completed_draws = Vec::new();
2742
2743        // Process deferred draws in multiple rounds to support nesting.
2744        // Each round processes all current deferred draws, which may produce new ones.
2745        let mut depth = 0;
2746        loop {
2747            // Limit maximum nesting depth to prevent infinite loops.
2748            assert!(depth < 10, "Exceeded maximum (10) deferred depth");
2749            depth += 1;
2750            let deferred_count = self.next_frame.deferred_draws.len();
2751            if deferred_count == 0 {
2752                break;
2753            }
2754
2755            // Sort by priority for this round
2756            let traversal_order = self.deferred_draw_traversal_order();
2757            let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2758
2759            for deferred_draw_ix in traversal_order {
2760                let deferred_draw = &mut deferred_draws[deferred_draw_ix];
2761                self.element_id_stack
2762                    .clone_from(&deferred_draw.element_id_stack);
2763                self.text_style_stack
2764                    .clone_from(&deferred_draw.text_style_stack);
2765                self.next_frame
2766                    .dispatch_tree
2767                    .set_active_node(deferred_draw.parent_node);
2768
2769                let prepaint_start = self.prepaint_index();
2770                if let Some(element) = deferred_draw.element.as_mut() {
2771                    self.with_rendered_view(deferred_draw.current_view, |window| {
2772                        window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2773                            window.with_absolute_element_offset(
2774                                deferred_draw.absolute_offset,
2775                                |window| {
2776                                    element.prepaint(window, cx);
2777                                },
2778                            );
2779                        });
2780                    })
2781                } else {
2782                    self.reuse_prepaint(deferred_draw.prepaint_range.clone());
2783                }
2784                let prepaint_end = self.prepaint_index();
2785                deferred_draw.prepaint_range = prepaint_start..prepaint_end;
2786            }
2787
2788            // Save completed draws and continue with newly added ones
2789            completed_draws.append(&mut deferred_draws);
2790
2791            self.element_id_stack.clear();
2792            self.text_style_stack.clear();
2793        }
2794
2795        // Restore all completed draws
2796        self.next_frame.deferred_draws = completed_draws;
2797    }
2798
2799    fn paint_deferred_draws(&mut self, cx: &mut App) {
2800        assert_eq!(self.element_id_stack.len(), 0);
2801
2802        // Paint all deferred draws in priority order.
2803        // Since prepaint has already processed nested deferreds, we just paint them all.
2804        if self.next_frame.deferred_draws.len() == 0 {
2805            return;
2806        }
2807
2808        let traversal_order = self.deferred_draw_traversal_order();
2809        let mut deferred_draws = mem::take(&mut self.next_frame.deferred_draws);
2810        for deferred_draw_ix in traversal_order {
2811            let mut deferred_draw = &mut deferred_draws[deferred_draw_ix];
2812            self.element_id_stack
2813                .clone_from(&deferred_draw.element_id_stack);
2814            self.next_frame
2815                .dispatch_tree
2816                .set_active_node(deferred_draw.parent_node);
2817
2818            let paint_start = self.paint_index();
2819            let content_mask = deferred_draw.content_mask;
2820            if let Some(element) = deferred_draw.element.as_mut() {
2821                self.with_rendered_view(deferred_draw.current_view, |window| {
2822                    window.with_content_mask(content_mask, |window| {
2823                        window.with_rem_size(Some(deferred_draw.rem_size), |window| {
2824                            element.paint(window, cx);
2825                        });
2826                    })
2827                })
2828            } else {
2829                self.reuse_paint(deferred_draw.paint_range.clone());
2830            }
2831            let paint_end = self.paint_index();
2832            deferred_draw.paint_range = paint_start..paint_end;
2833        }
2834        self.next_frame.deferred_draws = deferred_draws;
2835        self.element_id_stack.clear();
2836    }
2837
2838    fn deferred_draw_traversal_order(&mut self) -> SmallVec<[usize; 8]> {
2839        let deferred_count = self.next_frame.deferred_draws.len();
2840        let mut sorted_indices = (0..deferred_count).collect::<SmallVec<[_; 8]>>();
2841        sorted_indices.sort_by_key(|ix| self.next_frame.deferred_draws[*ix].priority);
2842        sorted_indices
2843    }
2844
2845    pub(crate) fn prepaint_index(&self) -> PrepaintStateIndex {
2846        PrepaintStateIndex {
2847            hitboxes_index: self.next_frame.hitboxes.len(),
2848            tooltips_index: self.next_frame.tooltip_requests.len(),
2849            deferred_draws_index: self.next_frame.deferred_draws.len(),
2850            dispatch_tree_index: self.next_frame.dispatch_tree.len(),
2851            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2852            line_layout_index: self.text_system.layout_index(),
2853        }
2854    }
2855
2856    pub(crate) fn reuse_prepaint(&mut self, range: Range<PrepaintStateIndex>) {
2857        self.next_frame.hitboxes.extend(
2858            self.rendered_frame.hitboxes[range.start.hitboxes_index..range.end.hitboxes_index]
2859                .iter()
2860                .cloned(),
2861        );
2862        self.next_frame.tooltip_requests.extend(
2863            self.rendered_frame.tooltip_requests
2864                [range.start.tooltips_index..range.end.tooltips_index]
2865                .iter_mut()
2866                .map(|request| request.take()),
2867        );
2868        self.next_frame.accessed_element_states.extend(
2869            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2870                ..range.end.accessed_element_states_index]
2871                .iter()
2872                .map(|(id, type_id)| (id.clone(), *type_id)),
2873        );
2874        self.text_system
2875            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2876
2877        let reused_subtree = self.next_frame.dispatch_tree.reuse_subtree(
2878            range.start.dispatch_tree_index..range.end.dispatch_tree_index,
2879            &mut self.rendered_frame.dispatch_tree,
2880            self.focus,
2881        );
2882
2883        if reused_subtree.contains_focus() {
2884            self.next_frame.focus = self.focus;
2885        }
2886
2887        self.next_frame.deferred_draws.extend(
2888            self.rendered_frame.deferred_draws
2889                [range.start.deferred_draws_index..range.end.deferred_draws_index]
2890                .iter()
2891                .map(|deferred_draw| DeferredDraw {
2892                    current_view: deferred_draw.current_view,
2893                    parent_node: reused_subtree.refresh_node_id(deferred_draw.parent_node),
2894                    element_id_stack: deferred_draw.element_id_stack.clone(),
2895                    text_style_stack: deferred_draw.text_style_stack.clone(),
2896                    content_mask: deferred_draw.content_mask,
2897                    rem_size: deferred_draw.rem_size,
2898                    priority: deferred_draw.priority,
2899                    element: None,
2900                    absolute_offset: deferred_draw.absolute_offset,
2901                    prepaint_range: deferred_draw.prepaint_range.clone(),
2902                    paint_range: deferred_draw.paint_range.clone(),
2903                }),
2904        );
2905    }
2906
2907    pub(crate) fn paint_index(&self) -> PaintIndex {
2908        PaintIndex {
2909            scene_index: self.next_frame.scene.len(),
2910            mouse_listeners_index: self.next_frame.mouse_listeners.len(),
2911            input_handlers_index: self.next_frame.input_handlers.len(),
2912            cursor_styles_index: self.next_frame.cursor_styles.len(),
2913            accessed_element_states_index: self.next_frame.accessed_element_states.len(),
2914            tab_handle_index: self.next_frame.tab_stops.paint_index(),
2915            line_layout_index: self.text_system.layout_index(),
2916        }
2917    }
2918
2919    pub(crate) fn reuse_paint(&mut self, range: Range<PaintIndex>) {
2920        self.next_frame.cursor_styles.extend(
2921            self.rendered_frame.cursor_styles
2922                [range.start.cursor_styles_index..range.end.cursor_styles_index]
2923                .iter()
2924                .cloned(),
2925        );
2926        self.next_frame.input_handlers.extend(
2927            self.rendered_frame.input_handlers
2928                [range.start.input_handlers_index..range.end.input_handlers_index]
2929                .iter_mut()
2930                .map(|handler| handler.take()),
2931        );
2932        self.next_frame.mouse_listeners.extend(
2933            self.rendered_frame.mouse_listeners
2934                [range.start.mouse_listeners_index..range.end.mouse_listeners_index]
2935                .iter_mut()
2936                .map(|listener| listener.take()),
2937        );
2938        self.next_frame.accessed_element_states.extend(
2939            self.rendered_frame.accessed_element_states[range.start.accessed_element_states_index
2940                ..range.end.accessed_element_states_index]
2941                .iter()
2942                .map(|(id, type_id)| (id.clone(), *type_id)),
2943        );
2944        self.next_frame.tab_stops.replay(
2945            &self.rendered_frame.tab_stops.insertion_history
2946                [range.start.tab_handle_index..range.end.tab_handle_index],
2947        );
2948
2949        self.text_system
2950            .reuse_layouts(range.start.line_layout_index..range.end.line_layout_index);
2951        self.next_frame.scene.replay(
2952            range.start.scene_index..range.end.scene_index,
2953            &self.rendered_frame.scene,
2954        );
2955    }
2956
2957    /// Push a text style onto the stack, and call a function with that style active.
2958    /// Use [`Window::text_style`] to get the current, combined text style. This method
2959    /// should only be called as part of element drawing.
2960    pub fn with_text_style<F, R>(&mut self, style: Option<TextStyleRefinement>, f: F) -> R
2961    where
2962        F: FnOnce(&mut Self) -> R,
2963    {
2964        self.invalidator.debug_assert_paint_or_prepaint();
2965        if let Some(style) = style {
2966            self.text_style_stack.push(style);
2967            let result = f(self);
2968            self.text_style_stack.pop();
2969            result
2970        } else {
2971            f(self)
2972        }
2973    }
2974
2975    /// Updates the cursor style at the platform level. This method should only be called
2976    /// during the paint phase of element drawing.
2977    pub fn set_cursor_style(&mut self, style: CursorStyle, hitbox: &Hitbox) {
2978        self.invalidator.debug_assert_paint();
2979        self.next_frame.cursor_styles.push(CursorStyleRequest {
2980            hitbox_id: Some(hitbox.id),
2981            style,
2982        });
2983    }
2984
2985    /// Updates the cursor style for the entire window at the platform level. A cursor
2986    /// style using this method will have precedence over any cursor style set using
2987    /// `set_cursor_style`. This method should only be called during the paint
2988    /// phase of element drawing.
2989    pub fn set_window_cursor_style(&mut self, style: CursorStyle) {
2990        self.invalidator.debug_assert_paint();
2991        self.next_frame.cursor_styles.push(CursorStyleRequest {
2992            hitbox_id: None,
2993            style,
2994        })
2995    }
2996
2997    /// Sets a tooltip to be rendered for the upcoming frame. This method should only be called
2998    /// during the paint phase of element drawing.
2999    pub fn set_tooltip(&mut self, tooltip: AnyTooltip) -> TooltipId {
3000        self.invalidator.debug_assert_prepaint();
3001        let id = TooltipId(post_inc(&mut self.next_tooltip_id.0));
3002        self.next_frame
3003            .tooltip_requests
3004            .push(Some(TooltipRequest { id, tooltip }));
3005        id
3006    }
3007
3008    /// Invoke the given function with the given content mask after intersecting it
3009    /// with the current mask. This method should only be called during element drawing.
3010    // This function is called in a highly recursive manner in editor
3011    // prepainting, make sure its inlined to reduce the stack burden
3012    #[inline]
3013    pub fn with_content_mask<R>(
3014        &mut self,
3015        mask: Option<ContentMask<Pixels>>,
3016        f: impl FnOnce(&mut Self) -> R,
3017    ) -> R {
3018        self.invalidator.debug_assert_paint_or_prepaint();
3019        if let Some(mask) = mask {
3020            let mask = mask.intersect(&self.content_mask());
3021            self.content_mask_stack.push(mask);
3022            let result = f(self);
3023            self.content_mask_stack.pop();
3024            result
3025        } else {
3026            f(self)
3027        }
3028    }
3029
3030    /// Updates the global element offset relative to the current offset. This is used to implement
3031    /// scrolling. This method should only be called during the prepaint phase of element drawing.
3032    pub fn with_element_offset<R>(
3033        &mut self,
3034        offset: Point<Pixels>,
3035        f: impl FnOnce(&mut Self) -> R,
3036    ) -> R {
3037        self.invalidator.debug_assert_prepaint();
3038
3039        if offset.is_zero() {
3040            return f(self);
3041        };
3042
3043        let abs_offset = self.element_offset() + offset;
3044        self.with_absolute_element_offset(abs_offset, f)
3045    }
3046
3047    /// Updates the global element offset based on the given offset. This is used to implement
3048    /// drag handles and other manual painting of elements. This method should only be called during
3049    /// the prepaint phase of element drawing.
3050    pub fn with_absolute_element_offset<R>(
3051        &mut self,
3052        offset: Point<Pixels>,
3053        f: impl FnOnce(&mut Self) -> R,
3054    ) -> R {
3055        self.invalidator.debug_assert_prepaint();
3056        self.element_offset_stack.push(offset);
3057        let result = f(self);
3058        self.element_offset_stack.pop();
3059        result
3060    }
3061
3062    pub(crate) fn with_element_opacity<R>(
3063        &mut self,
3064        opacity: Option<f32>,
3065        f: impl FnOnce(&mut Self) -> R,
3066    ) -> R {
3067        self.invalidator.debug_assert_paint_or_prepaint();
3068
3069        let Some(opacity) = opacity else {
3070            return f(self);
3071        };
3072
3073        let previous_opacity = self.element_opacity;
3074        self.element_opacity = previous_opacity * opacity;
3075        let result = f(self);
3076        self.element_opacity = previous_opacity;
3077        result
3078    }
3079
3080    /// Perform prepaint on child elements in a "retryable" manner, so that any side effects
3081    /// of prepaints can be discarded before prepainting again. This is used to support autoscroll
3082    /// where we need to prepaint children to detect the autoscroll bounds, then adjust the
3083    /// element offset and prepaint again. See [`crate::List`] for an example. This method should only be
3084    /// called during the prepaint phase of element drawing.
3085    pub fn transact<T, U>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, U>) -> Result<T, U> {
3086        self.invalidator.debug_assert_prepaint();
3087        let index = self.prepaint_index();
3088        let result = f(self);
3089        if result.is_err() {
3090            self.next_frame.hitboxes.truncate(index.hitboxes_index);
3091            self.next_frame
3092                .tooltip_requests
3093                .truncate(index.tooltips_index);
3094            self.next_frame
3095                .deferred_draws
3096                .truncate(index.deferred_draws_index);
3097            self.next_frame
3098                .dispatch_tree
3099                .truncate(index.dispatch_tree_index);
3100            self.next_frame
3101                .accessed_element_states
3102                .truncate(index.accessed_element_states_index);
3103            self.text_system.truncate_layouts(index.line_layout_index);
3104        }
3105        result
3106    }
3107
3108    /// When you call this method during [`Element::prepaint`], containing elements will attempt to
3109    /// scroll to cause the specified bounds to become visible. When they decide to autoscroll, they will call
3110    /// [`Element::prepaint`] again with a new set of bounds. See [`crate::List`] for an example of an element
3111    /// that supports this method being called on the elements it contains. This method should only be
3112    /// called during the prepaint phase of element drawing.
3113    pub fn request_autoscroll(&mut self, bounds: Bounds<Pixels>) {
3114        self.invalidator.debug_assert_prepaint();
3115        self.requested_autoscroll = Some(bounds);
3116    }
3117
3118    /// This method can be called from a containing element such as [`crate::List`] to support the autoscroll behavior
3119    /// described in [`Self::request_autoscroll`].
3120    pub fn take_autoscroll(&mut self) -> Option<Bounds<Pixels>> {
3121        self.invalidator.debug_assert_prepaint();
3122        self.requested_autoscroll.take()
3123    }
3124
3125    /// Asynchronously load an asset, if the asset hasn't finished loading this will return None.
3126    /// Your view will be re-drawn once the asset has finished loading.
3127    ///
3128    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
3129    /// time.
3130    pub fn use_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3131        let (task, is_first) = cx.fetch_asset::<A>(source);
3132        task.clone().now_or_never().or_else(|| {
3133            if is_first {
3134                let entity_id = self.current_view();
3135                self.spawn(cx, {
3136                    let task = task.clone();
3137                    async move |cx| {
3138                        task.await;
3139
3140                        cx.on_next_frame(move |_, cx| {
3141                            cx.notify(entity_id);
3142                        });
3143                    }
3144                })
3145                .detach();
3146            }
3147
3148            None
3149        })
3150    }
3151
3152    /// Asynchronously load an asset, if the asset hasn't finished loading or doesn't exist this will return None.
3153    /// Your view will not be re-drawn once the asset has finished loading.
3154    ///
3155    /// Note that the multiple calls to this method will only result in one `Asset::load` call at a
3156    /// time.
3157    pub fn get_asset<A: Asset>(&mut self, source: &A::Source, cx: &mut App) -> Option<A::Output> {
3158        let (task, _) = cx.fetch_asset::<A>(source);
3159        task.now_or_never()
3160    }
3161    /// Obtain the current element offset. This method should only be called during the
3162    /// prepaint phase of element drawing.
3163    pub fn element_offset(&self) -> Point<Pixels> {
3164        self.invalidator.debug_assert_prepaint();
3165        self.element_offset_stack
3166            .last()
3167            .copied()
3168            .unwrap_or_default()
3169    }
3170
3171    /// Obtain the current element opacity. This method should only be called during the
3172    /// prepaint phase of element drawing.
3173    #[inline]
3174    pub(crate) fn element_opacity(&self) -> f32 {
3175        self.invalidator.debug_assert_paint_or_prepaint();
3176        self.element_opacity
3177    }
3178
3179    /// Obtain the current content mask. This method should only be called during element drawing.
3180    pub fn content_mask(&self) -> ContentMask<Pixels> {
3181        self.invalidator.debug_assert_paint_or_prepaint();
3182        self.content_mask_stack
3183            .last()
3184            .cloned()
3185            .unwrap_or_else(|| ContentMask {
3186                bounds: Bounds {
3187                    origin: Point::default(),
3188                    size: self.viewport_size,
3189                },
3190            })
3191    }
3192
3193    /// Provide elements in the called function with a new namespace in which their identifiers must be unique.
3194    /// This can be used within a custom element to distinguish multiple sets of child elements.
3195    pub fn with_element_namespace<R>(
3196        &mut self,
3197        element_id: impl Into<ElementId>,
3198        f: impl FnOnce(&mut Self) -> R,
3199    ) -> R {
3200        self.element_id_stack.push(element_id.into());
3201        let result = f(self);
3202        self.element_id_stack.pop();
3203        result
3204    }
3205
3206    /// Use a piece of state that exists as long this element is being rendered in consecutive frames.
3207    pub fn use_keyed_state<S: 'static>(
3208        &mut self,
3209        key: impl Into<ElementId>,
3210        cx: &mut App,
3211        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3212    ) -> Entity<S> {
3213        let current_view = self.current_view();
3214        self.with_global_id(key.into(), |global_id, window| {
3215            window.with_element_state(global_id, |state: Option<Entity<S>>, window| {
3216                if let Some(state) = state {
3217                    (state.clone(), state)
3218                } else {
3219                    let new_state = cx.new(|cx| init(window, cx));
3220                    cx.observe(&new_state, move |_, cx| {
3221                        cx.notify(current_view);
3222                    })
3223                    .detach();
3224                    (new_state.clone(), new_state)
3225                }
3226            })
3227        })
3228    }
3229
3230    /// Use a piece of state that exists as long this element is being rendered in consecutive frames, without needing to specify a key
3231    ///
3232    /// NOTE: This method uses the location of the caller to generate an ID for this state.
3233    ///       If this is not sufficient to identify your state (e.g. you're rendering a list item),
3234    ///       you can provide a custom ElementID using the `use_keyed_state` method.
3235    #[track_caller]
3236    pub fn use_state<S: 'static>(
3237        &mut self,
3238        cx: &mut App,
3239        init: impl FnOnce(&mut Self, &mut Context<S>) -> S,
3240    ) -> Entity<S> {
3241        self.use_keyed_state(
3242            ElementId::CodeLocation(*core::panic::Location::caller()),
3243            cx,
3244            init,
3245        )
3246    }
3247
3248    /// Updates or initializes state for an element with the given id that lives across multiple
3249    /// frames. If an element with this ID existed in the rendered frame, its state will be passed
3250    /// to the given closure. The state returned by the closure will be stored so it can be referenced
3251    /// when drawing the next frame. This method should only be called as part of element drawing.
3252    pub fn with_element_state<S, R>(
3253        &mut self,
3254        global_id: &GlobalElementId,
3255        f: impl FnOnce(Option<S>, &mut Self) -> (R, S),
3256    ) -> R
3257    where
3258        S: 'static,
3259    {
3260        self.invalidator.debug_assert_paint_or_prepaint();
3261
3262        let key = (global_id.clone(), TypeId::of::<S>());
3263        self.next_frame.accessed_element_states.push(key.clone());
3264
3265        if let Some(any) = self
3266            .next_frame
3267            .element_states
3268            .remove(&key)
3269            .or_else(|| self.rendered_frame.element_states.remove(&key))
3270        {
3271            let ElementStateBox {
3272                inner,
3273                #[cfg(debug_assertions)]
3274                type_name,
3275            } = any;
3276            // Using the extra inner option to avoid needing to reallocate a new box.
3277            let mut state_box = inner
3278                .downcast::<Option<S>>()
3279                .map_err(|_| {
3280                    #[cfg(debug_assertions)]
3281                    {
3282                        anyhow::anyhow!(
3283                            "invalid element state type for id, requested {:?}, actual: {:?}",
3284                            std::any::type_name::<S>(),
3285                            type_name
3286                        )
3287                    }
3288
3289                    #[cfg(not(debug_assertions))]
3290                    {
3291                        anyhow::anyhow!(
3292                            "invalid element state type for id, requested {:?}",
3293                            std::any::type_name::<S>(),
3294                        )
3295                    }
3296                })
3297                .unwrap();
3298
3299            let state = state_box.take().expect(
3300                "reentrant call to with_element_state for the same state type and element id",
3301            );
3302            let (result, state) = f(Some(state), self);
3303            state_box.replace(state);
3304            self.next_frame.element_states.insert(
3305                key,
3306                ElementStateBox {
3307                    inner: state_box,
3308                    #[cfg(debug_assertions)]
3309                    type_name,
3310                },
3311            );
3312            result
3313        } else {
3314            let (result, state) = f(None, self);
3315            self.next_frame.element_states.insert(
3316                key,
3317                ElementStateBox {
3318                    inner: Box::new(Some(state)),
3319                    #[cfg(debug_assertions)]
3320                    type_name: std::any::type_name::<S>(),
3321                },
3322            );
3323            result
3324        }
3325    }
3326
3327    /// A variant of `with_element_state` that allows the element's id to be optional. This is a convenience
3328    /// method for elements where the element id may or may not be assigned. Prefer using `with_element_state`
3329    /// when the element is guaranteed to have an id.
3330    ///
3331    /// The first option means 'no ID provided'
3332    /// The second option means 'not yet initialized'
3333    pub fn with_optional_element_state<S, R>(
3334        &mut self,
3335        global_id: Option<&GlobalElementId>,
3336        f: impl FnOnce(Option<Option<S>>, &mut Self) -> (R, Option<S>),
3337    ) -> R
3338    where
3339        S: 'static,
3340    {
3341        self.invalidator.debug_assert_paint_or_prepaint();
3342
3343        if let Some(global_id) = global_id {
3344            self.with_element_state(global_id, |state, cx| {
3345                let (result, state) = f(Some(state), cx);
3346                let state =
3347                    state.expect("you must return some state when you pass some element id");
3348                (result, state)
3349            })
3350        } else {
3351            let (result, state) = f(None, self);
3352            debug_assert!(
3353                state.is_none(),
3354                "you must not return an element state when passing None for the global id"
3355            );
3356            result
3357        }
3358    }
3359
3360    /// Executes the given closure within the context of a tab group.
3361    #[inline]
3362    pub fn with_tab_group<R>(&mut self, index: Option<isize>, f: impl FnOnce(&mut Self) -> R) -> R {
3363        if let Some(index) = index {
3364            self.next_frame.tab_stops.begin_group(index);
3365            let result = f(self);
3366            self.next_frame.tab_stops.end_group();
3367            result
3368        } else {
3369            f(self)
3370        }
3371    }
3372
3373    /// Defers the drawing of the given element, scheduling it to be painted on top of the currently-drawn tree
3374    /// at a later time. The `priority` parameter determines the drawing order relative to other deferred elements,
3375    /// with higher values being drawn on top.
3376    ///
3377    /// When `content_mask` is provided, the deferred element will be clipped to that region during
3378    /// both prepaint and paint. When `None`, no additional clipping is applied.
3379    ///
3380    /// This method should only be called as part of the prepaint phase of element drawing.
3381    pub fn defer_draw(
3382        &mut self,
3383        element: AnyElement,
3384        absolute_offset: Point<Pixels>,
3385        priority: usize,
3386        content_mask: Option<ContentMask<Pixels>>,
3387    ) {
3388        self.invalidator.debug_assert_prepaint();
3389        let parent_node = self.next_frame.dispatch_tree.active_node_id().unwrap();
3390        self.next_frame.deferred_draws.push(DeferredDraw {
3391            current_view: self.current_view(),
3392            parent_node,
3393            element_id_stack: self.element_id_stack.clone(),
3394            text_style_stack: self.text_style_stack.clone(),
3395            content_mask,
3396            rem_size: self.rem_size(),
3397            priority,
3398            element: Some(element),
3399            absolute_offset,
3400            prepaint_range: PrepaintStateIndex::default()..PrepaintStateIndex::default(),
3401            paint_range: PaintIndex::default()..PaintIndex::default(),
3402        });
3403    }
3404
3405    /// Creates a new painting layer for the specified bounds. A "layer" is a batch
3406    /// of geometry that are non-overlapping and have the same draw order. This is typically used
3407    /// for performance reasons.
3408    ///
3409    /// This method should only be called as part of the paint phase of element drawing.
3410    pub fn paint_layer<R>(&mut self, bounds: Bounds<Pixels>, f: impl FnOnce(&mut Self) -> R) -> R {
3411        self.invalidator.debug_assert_paint();
3412
3413        let content_mask = self.content_mask();
3414        let clipped_bounds = bounds.intersect(&content_mask.bounds);
3415        if !clipped_bounds.is_empty() {
3416            self.next_frame
3417                .scene
3418                .push_layer(self.cover_bounds(clipped_bounds));
3419        }
3420
3421        let result = f(self);
3422
3423        if !clipped_bounds.is_empty() {
3424            self.next_frame.scene.pop_layer();
3425        }
3426
3427        result
3428    }
3429
3430    /// Paint one or more drop shadows into the scene for the next frame at the current z-index.
3431    ///
3432    /// This method should only be called as part of the paint phase of element drawing.
3433    pub fn paint_shadows(
3434        &mut self,
3435        bounds: Bounds<Pixels>,
3436        corner_radii: Corners<Pixels>,
3437        shadows: &[BoxShadow],
3438    ) {
3439        self.invalidator.debug_assert_paint();
3440
3441        let scale_factor = self.scale_factor();
3442        let content_mask = self.snapped_content_mask();
3443        let opacity = self.element_opacity();
3444        for shadow in shadows {
3445            let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius);
3446            self.next_frame.scene.insert_primitive(Shadow {
3447                order: 0,
3448                blur_radius: shadow.blur_radius.scale(scale_factor),
3449                bounds: self.cover_bounds(shadow_bounds),
3450                content_mask,
3451                corner_radii: corner_radii.scale(scale_factor),
3452                color: shadow.color.opacity(opacity),
3453            });
3454        }
3455    }
3456
3457    /// Paint one or more quads into the scene for the next frame at the current stacking context.
3458    /// Quads are colored rectangular regions with an optional background, border, and corner radius.
3459    /// see [`fill`], [`outline`], and [`quad`] to construct this type.
3460    ///
3461    /// This method should only be called as part of the paint phase of element drawing.
3462    ///
3463    /// Note that the `quad.corner_radii` are allowed to exceed the bounds, creating sharp corners
3464    /// where the circular arcs meet. This will not display well when combined with dashed borders.
3465    /// Use `Corners::clamp_radii_for_quad_size` if the radii should fit within the bounds.
3466    pub fn paint_quad(&mut self, quad: PaintQuad) {
3467        self.invalidator.debug_assert_paint();
3468
3469        let opacity = self.element_opacity();
3470        let snapped_bounds = self.snap_bounds(quad.bounds);
3471        let snapped_border_widths = self.snap_border_widths(quad.border_widths);
3472        self.next_frame.scene.insert_primitive(Quad {
3473            order: 0,
3474            bounds: snapped_bounds,
3475            content_mask: self.snapped_content_mask(),
3476            background: quad.background.opacity(opacity),
3477            border_color: quad.border_color.opacity(opacity),
3478            corner_radii: quad.corner_radii.scale(self.scale_factor()),
3479            border_widths: snapped_border_widths,
3480            border_style: quad.border_style,
3481        });
3482    }
3483
3484    /// Paint the given `Path` into the scene for the next frame at the current z-index.
3485    ///
3486    /// This method should only be called as part of the paint phase of element drawing.
3487    pub fn paint_path(&mut self, mut path: Path<Pixels>, color: impl Into<Background>) {
3488        self.invalidator.debug_assert_paint();
3489
3490        let scale_factor = self.scale_factor();
3491        let content_mask = self.content_mask();
3492        let opacity = self.element_opacity();
3493        path.content_mask = content_mask;
3494        let color: Background = color.into();
3495        path.color = color.opacity(opacity);
3496        self.next_frame
3497            .scene
3498            .insert_primitive(path.scale(scale_factor));
3499    }
3500
3501    /// Paint an underline into the scene for the next frame at the current z-index.
3502    ///
3503    /// This method should only be called as part of the paint phase of element drawing.
3504    pub fn paint_underline(
3505        &mut self,
3506        origin: Point<Pixels>,
3507        width: Pixels,
3508        style: &UnderlineStyle,
3509    ) {
3510        self.invalidator.debug_assert_paint();
3511
3512        let scale_factor = self.scale_factor();
3513        let thickness = self.snap_stroke(style.thickness);
3514        let height = if style.wavy {
3515            ScaledPixels(thickness.0 * 3.)
3516        } else {
3517            thickness
3518        };
3519        let bounds = Bounds {
3520            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3521            size: size(self.snap_stroke(width), height),
3522        };
3523        let element_opacity = self.element_opacity();
3524
3525        self.next_frame.scene.insert_primitive(Underline {
3526            order: 0,
3527            pad: 0,
3528            bounds,
3529            content_mask: self.snapped_content_mask(),
3530            color: style.color.unwrap_or_default().opacity(element_opacity),
3531            thickness,
3532            wavy: if style.wavy { 1 } else { 0 },
3533        });
3534    }
3535
3536    /// Paint a strikethrough into the scene for the next frame at the current z-index.
3537    ///
3538    /// This method should only be called as part of the paint phase of element drawing.
3539    pub fn paint_strikethrough(
3540        &mut self,
3541        origin: Point<Pixels>,
3542        width: Pixels,
3543        style: &StrikethroughStyle,
3544    ) {
3545        self.invalidator.debug_assert_paint();
3546
3547        let scale_factor = self.scale_factor();
3548        let height = style.thickness;
3549        let bounds = Bounds {
3550            origin: origin.map(|c| ScaledPixels(round_to_device_pixel(c.0, scale_factor))),
3551            size: size(self.snap_stroke(width), self.snap_stroke(height)),
3552        };
3553        let opacity = self.element_opacity();
3554
3555        self.next_frame.scene.insert_primitive(Underline {
3556            order: 0,
3557            pad: 0,
3558            bounds,
3559            content_mask: self.snapped_content_mask(),
3560            thickness: self.snap_stroke(style.thickness),
3561            color: style.color.unwrap_or_default().opacity(opacity),
3562            wavy: 0,
3563        });
3564    }
3565
3566    /// Paints a monochrome (non-emoji) glyph into the scene for the next frame at the current z-index.
3567    ///
3568    /// The y component of the origin is the baseline of the glyph.
3569    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3570    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3571    /// This method is only useful if you need to paint a single glyph that has already been shaped.
3572    ///
3573    /// This method should only be called as part of the paint phase of element drawing.
3574    pub fn paint_glyph(
3575        &mut self,
3576        origin: Point<Pixels>,
3577        font_id: FontId,
3578        glyph_id: GlyphId,
3579        font_size: Pixels,
3580        color: Hsla,
3581    ) -> Result<()> {
3582        self.invalidator.debug_assert_paint();
3583
3584        let element_opacity = self.element_opacity();
3585        let scale_factor = self.scale_factor();
3586        let glyph_origin = origin.scale(scale_factor);
3587
3588        let quantized_origin = Point::new(
3589            round_half_toward_zero(glyph_origin.x.0 * SUBPIXEL_VARIANTS_X as f32)
3590                / SUBPIXEL_VARIANTS_X as f32,
3591            round_half_toward_zero(glyph_origin.y.0 * SUBPIXEL_VARIANTS_Y as f32)
3592                / SUBPIXEL_VARIANTS_Y as f32,
3593        );
3594        let subpixel_variant = Point::new(
3595            (quantized_origin.x.fract() * SUBPIXEL_VARIANTS_X as f32) as u8,
3596            (quantized_origin.y.fract() * SUBPIXEL_VARIANTS_Y as f32) as u8,
3597        );
3598        let integer_origin = quantized_origin.map(|c| ScaledPixels(c.trunc()));
3599        let subpixel_rendering = self.should_use_subpixel_rendering(font_id, font_size);
3600        let dilation = self.text_system().glyph_dilation_for_color(color);
3601        let params = RenderGlyphParams {
3602            font_id,
3603            glyph_id,
3604            font_size,
3605            subpixel_variant,
3606            scale_factor,
3607            is_emoji: false,
3608            subpixel_rendering,
3609            dilation,
3610        };
3611
3612        let raster_bounds = self.text_system().raster_bounds(&params)?;
3613        if !raster_bounds.is_zero() {
3614            let tile = self
3615                .sprite_atlas
3616                .get_or_insert_with(&params.clone().into(), &mut || {
3617                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3618                    Ok(Some((size, Cow::Owned(bytes))))
3619                })?
3620                .expect("Callback above only errors or returns Some");
3621            let bounds = Bounds {
3622                origin: integer_origin + raster_bounds.origin.map(Into::into),
3623                size: tile.bounds.size.map(Into::into),
3624            };
3625            let content_mask = self.snapped_content_mask();
3626
3627            if subpixel_rendering {
3628                self.next_frame.scene.insert_primitive(SubpixelSprite {
3629                    order: 0,
3630                    pad: 0,
3631                    bounds,
3632                    content_mask,
3633                    color: color.opacity(element_opacity),
3634                    tile,
3635                    transformation: TransformationMatrix::unit(),
3636                });
3637            } else {
3638                self.next_frame.scene.insert_primitive(MonochromeSprite {
3639                    order: 0,
3640                    pad: 0,
3641                    bounds,
3642                    content_mask,
3643                    color: color.opacity(element_opacity),
3644                    tile,
3645                    transformation: TransformationMatrix::unit(),
3646                });
3647            }
3648        }
3649        Ok(())
3650    }
3651
3652    fn should_use_subpixel_rendering(&self, font_id: FontId, font_size: Pixels) -> bool {
3653        if self.platform_window.background_appearance() != WindowBackgroundAppearance::Opaque {
3654            return false;
3655        }
3656
3657        if !self.platform_window.is_subpixel_rendering_supported() {
3658            return false;
3659        }
3660
3661        let mode = match self.text_rendering_mode.get() {
3662            TextRenderingMode::PlatformDefault => self
3663                .text_system()
3664                .recommended_rendering_mode(font_id, font_size),
3665            mode => mode,
3666        };
3667
3668        mode == TextRenderingMode::Subpixel
3669    }
3670
3671    /// Paints an emoji glyph into the scene for the next frame at the current z-index.
3672    ///
3673    /// The y component of the origin is the baseline of the glyph.
3674    /// You should generally prefer to use the [`ShapedLine::paint`](crate::ShapedLine::paint) or
3675    /// [`WrappedLine::paint`](crate::WrappedLine::paint) methods in the [`TextSystem`](crate::TextSystem).
3676    /// This method is only useful if you need to paint a single emoji that has already been shaped.
3677    ///
3678    /// This method should only be called as part of the paint phase of element drawing.
3679    pub fn paint_emoji(
3680        &mut self,
3681        origin: Point<Pixels>,
3682        font_id: FontId,
3683        glyph_id: GlyphId,
3684        font_size: Pixels,
3685    ) -> Result<()> {
3686        self.invalidator.debug_assert_paint();
3687
3688        let scale_factor = self.scale_factor();
3689        let glyph_origin = origin.scale(scale_factor);
3690        let integer_origin = glyph_origin.map(|c| ScaledPixels(round_half_toward_zero(c.0)));
3691        let params = RenderGlyphParams {
3692            font_id,
3693            glyph_id,
3694            font_size,
3695            subpixel_variant: Default::default(),
3696            scale_factor,
3697            is_emoji: true,
3698            subpixel_rendering: false,
3699            dilation: 0,
3700        };
3701
3702        let raster_bounds = self.text_system().raster_bounds(&params)?;
3703        if !raster_bounds.is_zero() {
3704            let tile = self
3705                .sprite_atlas
3706                .get_or_insert_with(&params.clone().into(), &mut || {
3707                    let (size, bytes) = self.text_system().rasterize_glyph(&params)?;
3708                    Ok(Some((size, Cow::Owned(bytes))))
3709                })?
3710                .expect("Callback above only errors or returns Some");
3711
3712            let bounds = Bounds {
3713                origin: integer_origin + raster_bounds.origin.map(Into::into),
3714                size: tile.bounds.size.map(Into::into),
3715            };
3716            let content_mask = self.snapped_content_mask();
3717            let opacity = self.element_opacity();
3718
3719            self.next_frame.scene.insert_primitive(PolychromeSprite {
3720                order: 0,
3721                pad: 0,
3722                grayscale: false,
3723                bounds,
3724                corner_radii: Default::default(),
3725                content_mask,
3726                tile,
3727                opacity,
3728            });
3729        }
3730        Ok(())
3731    }
3732
3733    /// Paint a monochrome SVG into the scene for the next frame at the current stacking context.
3734    ///
3735    /// This method should only be called as part of the paint phase of element drawing.
3736    pub fn paint_svg(
3737        &mut self,
3738        bounds: Bounds<Pixels>,
3739        path: SharedString,
3740        mut data: Option<&[u8]>,
3741        transformation: TransformationMatrix,
3742        color: Hsla,
3743        cx: &App,
3744    ) -> Result<()> {
3745        self.invalidator.debug_assert_paint();
3746
3747        let element_opacity = self.element_opacity();
3748        let bounds = self.snap_bounds(bounds);
3749
3750        let params = RenderSvgParams {
3751            path,
3752            size: bounds.size.map(|pixels| {
3753                DevicePixels::from((pixels.0 * SMOOTH_SVG_SCALE_FACTOR).ceil() as i32)
3754            }),
3755        };
3756
3757        let Some(tile) =
3758            self.sprite_atlas
3759                .get_or_insert_with(&params.clone().into(), &mut || {
3760                    let Some((size, bytes)) = cx.svg_renderer.render_alpha_mask(&params, data)?
3761                    else {
3762                        return Ok(None);
3763                    };
3764                    Ok(Some((size, Cow::Owned(bytes))))
3765                })?
3766        else {
3767            return Ok(());
3768        };
3769        let content_mask = self.snapped_content_mask();
3770        let svg_bounds = Bounds {
3771            origin: bounds.center()
3772                - Point::new(
3773                    ScaledPixels(tile.bounds.size.width.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3774                    ScaledPixels(tile.bounds.size.height.0 as f32 / SMOOTH_SVG_SCALE_FACTOR / 2.),
3775                ),
3776            size: tile
3777                .bounds
3778                .size
3779                .map(|value| ScaledPixels(value.0 as f32 / SMOOTH_SVG_SCALE_FACTOR)),
3780        };
3781        let final_bounds = svg_bounds
3782            .map_origin(|value| ScaledPixels(round_half_toward_zero(value.0)))
3783            .map_size(|size| size.ceil());
3784
3785        self.next_frame.scene.insert_primitive(MonochromeSprite {
3786            order: 0,
3787            pad: 0,
3788            bounds: final_bounds,
3789            content_mask,
3790            color: color.opacity(element_opacity),
3791            tile,
3792            transformation,
3793        });
3794
3795        Ok(())
3796    }
3797
3798    /// Paint an image into the scene for the next frame at the current z-index.
3799    /// This method will panic if the frame_index is not valid
3800    ///
3801    /// This method should only be called as part of the paint phase of element drawing.
3802    pub fn paint_image(
3803        &mut self,
3804        bounds: Bounds<Pixels>,
3805        corner_radii: Corners<Pixels>,
3806        data: Arc<RenderImage>,
3807        frame_index: usize,
3808        grayscale: bool,
3809    ) -> Result<()> {
3810        self.invalidator.debug_assert_paint();
3811
3812        let bounds = self.snap_bounds(bounds);
3813        let params = RenderImageParams {
3814            image_id: data.id,
3815            frame_index,
3816        };
3817
3818        let tile = self
3819            .sprite_atlas
3820            .get_or_insert_with(&params.into(), &mut || {
3821                Ok(Some((
3822                    data.size(frame_index),
3823                    Cow::Borrowed(
3824                        data.as_bytes(frame_index)
3825                            .expect("It's the caller's job to pass a valid frame index"),
3826                    ),
3827                )))
3828            })?
3829            .expect("Callback above only returns Some");
3830        let content_mask = self.snapped_content_mask();
3831        let corner_radii = corner_radii.scale(self.scale_factor());
3832        let opacity = self.element_opacity();
3833
3834        self.next_frame.scene.insert_primitive(PolychromeSprite {
3835            order: 0,
3836            pad: 0,
3837            grayscale,
3838            bounds,
3839            content_mask,
3840            corner_radii,
3841            tile,
3842            opacity,
3843        });
3844        Ok(())
3845    }
3846
3847    /// Paint a surface into the scene for the next frame at the current z-index.
3848    ///
3849    /// This method should only be called as part of the paint phase of element drawing.
3850    #[cfg(target_os = "macos")]
3851    pub fn paint_surface(&mut self, bounds: Bounds<Pixels>, image_buffer: CVPixelBuffer) {
3852        use crate::PaintSurface;
3853
3854        self.invalidator.debug_assert_paint();
3855
3856        let bounds = self.snap_bounds(bounds);
3857        let content_mask = self.snapped_content_mask();
3858        self.next_frame.scene.insert_primitive(PaintSurface {
3859            order: 0,
3860            bounds,
3861            content_mask,
3862            image_buffer,
3863        });
3864    }
3865
3866    /// Removes an image from the sprite atlas.
3867    pub fn drop_image(&mut self, data: Arc<RenderImage>) -> Result<()> {
3868        for frame_index in 0..data.frame_count() {
3869            let params = RenderImageParams {
3870                image_id: data.id,
3871                frame_index,
3872            };
3873
3874            self.sprite_atlas.remove(&params.clone().into());
3875        }
3876
3877        Ok(())
3878    }
3879
3880    /// Add a node to the layout tree for the current frame. Takes the `Style` of the element for which
3881    /// layout is being requested, along with the layout ids of any children. This method is called during
3882    /// calls to the [`Element::request_layout`] trait method and enables any element to participate in layout.
3883    ///
3884    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3885    #[must_use]
3886    pub fn request_layout(
3887        &mut self,
3888        style: Style,
3889        children: impl IntoIterator<Item = LayoutId>,
3890        cx: &mut App,
3891    ) -> LayoutId {
3892        self.invalidator.debug_assert_prepaint();
3893
3894        cx.layout_id_buffer.clear();
3895        cx.layout_id_buffer.extend(children);
3896        let rem_size = self.rem_size();
3897        let scale_factor = self.scale_factor();
3898
3899        self.layout_engine.as_mut().unwrap().request_layout(
3900            style,
3901            rem_size,
3902            scale_factor,
3903            &cx.layout_id_buffer,
3904        )
3905    }
3906
3907    /// Add a node to the layout tree for the current frame. Instead of taking a `Style` and children,
3908    /// this variant takes a function that is invoked during layout so you can use arbitrary logic to
3909    /// determine the element's size. One place this is used internally is when measuring text.
3910    ///
3911    /// The given closure is invoked at layout time with the known dimensions and available space and
3912    /// returns a `Size`.
3913    ///
3914    /// This method should only be called as part of the request_layout or prepaint phase of element drawing.
3915    pub fn request_measured_layout<F>(&mut self, style: Style, measure: F) -> LayoutId
3916    where
3917        F: Fn(Size<Option<Pixels>>, Size<AvailableSpace>, &mut Window, &mut App) -> Size<Pixels>
3918            + 'static,
3919    {
3920        self.invalidator.debug_assert_prepaint();
3921
3922        let rem_size = self.rem_size();
3923        let scale_factor = self.scale_factor();
3924        self.layout_engine
3925            .as_mut()
3926            .unwrap()
3927            .request_measured_layout(style, rem_size, scale_factor, measure)
3928    }
3929
3930    /// Compute the layout for the given id within the given available space.
3931    /// This method is called for its side effect, typically by the framework prior to painting.
3932    /// After calling it, you can request the bounds of the given layout node id or any descendant.
3933    ///
3934    /// This method should only be called as part of the prepaint phase of element drawing.
3935    pub fn compute_layout(
3936        &mut self,
3937        layout_id: LayoutId,
3938        available_space: Size<AvailableSpace>,
3939        cx: &mut App,
3940    ) {
3941        self.invalidator.debug_assert_prepaint();
3942
3943        let mut layout_engine = self.layout_engine.take().unwrap();
3944        layout_engine.compute_layout(layout_id, available_space, self, cx);
3945        self.layout_engine = Some(layout_engine);
3946    }
3947
3948    /// Obtain the bounds computed for the given LayoutId relative to the window. This method will usually be invoked by
3949    /// GPUI itself automatically in order to pass your element its `Bounds` automatically.
3950    ///
3951    /// This method should only be called as part of element drawing.
3952    pub fn layout_bounds(&mut self, layout_id: LayoutId) -> Bounds<Pixels> {
3953        self.invalidator.debug_assert_prepaint();
3954
3955        let scale_factor = self.scale_factor();
3956        let mut bounds = self
3957            .layout_engine
3958            .as_mut()
3959            .unwrap()
3960            .layout_bounds(layout_id, scale_factor)
3961            .map(Into::into);
3962        let snapped_offset = self.pixel_snap_point(self.element_offset());
3963        bounds.origin += snapped_offset;
3964        bounds
3965    }
3966
3967    /// This method should be called during `prepaint`. You can use
3968    /// the returned [Hitbox] during `paint` or in an event handler
3969    /// to determine whether the inserted hitbox was the topmost.
3970    ///
3971    /// This method should only be called as part of the prepaint phase of element drawing.
3972    pub fn insert_hitbox(&mut self, bounds: Bounds<Pixels>, behavior: HitboxBehavior) -> Hitbox {
3973        self.invalidator.debug_assert_prepaint();
3974
3975        let content_mask = self.content_mask();
3976        let mut id = self.next_hitbox_id;
3977        self.next_hitbox_id = self.next_hitbox_id.next();
3978        let hitbox = Hitbox {
3979            id,
3980            bounds,
3981            content_mask,
3982            behavior,
3983        };
3984        self.next_frame.hitboxes.push(hitbox.clone());
3985        hitbox
3986    }
3987
3988    /// Set a hitbox which will act as a control area of the platform window.
3989    ///
3990    /// This method should only be called as part of the paint phase of element drawing.
3991    pub fn insert_window_control_hitbox(&mut self, area: WindowControlArea, hitbox: Hitbox) {
3992        self.invalidator.debug_assert_paint();
3993        self.next_frame.window_control_hitboxes.push((area, hitbox));
3994    }
3995
3996    /// Sets the key context for the current element. This context will be used to translate
3997    /// keybindings into actions.
3998    ///
3999    /// This method should only be called as part of the paint phase of element drawing.
4000    pub fn set_key_context(&mut self, context: KeyContext) {
4001        self.invalidator.debug_assert_paint();
4002        self.next_frame.dispatch_tree.set_key_context(context);
4003    }
4004
4005    /// Sets the focus handle for the current element. This handle will be used to manage focus state
4006    /// and keyboard event dispatch for the element.
4007    ///
4008    /// This method should only be called as part of the prepaint phase of element drawing.
4009    pub fn set_focus_handle(&mut self, focus_handle: &FocusHandle, _: &App) {
4010        self.invalidator.debug_assert_prepaint();
4011        if focus_handle.is_focused(self) {
4012            self.next_frame.focus = Some(focus_handle.id);
4013        }
4014        self.next_frame.dispatch_tree.set_focus_id(focus_handle.id);
4015    }
4016
4017    /// Sets the view id for the current element, which will be used to manage view caching.
4018    ///
4019    /// This method should only be called as part of element prepaint. We plan on removing this
4020    /// method eventually when we solve some issues that require us to construct editor elements
4021    /// directly instead of always using editors via views.
4022    pub fn set_view_id(&mut self, view_id: EntityId) {
4023        self.invalidator.debug_assert_prepaint();
4024        self.next_frame.dispatch_tree.set_view_id(view_id);
4025    }
4026
4027    /// Get the entity ID for the currently rendering view
4028    pub fn current_view(&self) -> EntityId {
4029        self.invalidator.debug_assert_paint_or_prepaint();
4030        self.rendered_entity_stack.last().copied().unwrap()
4031    }
4032
4033    #[inline]
4034    pub(crate) fn with_rendered_view<R>(
4035        &mut self,
4036        id: EntityId,
4037        f: impl FnOnce(&mut Self) -> R,
4038    ) -> R {
4039        self.rendered_entity_stack.push(id);
4040        let result = f(self);
4041        self.rendered_entity_stack.pop();
4042        result
4043    }
4044
4045    /// Executes the provided function with the specified image cache.
4046    pub fn with_image_cache<F, R>(&mut self, image_cache: Option<AnyImageCache>, f: F) -> R
4047    where
4048        F: FnOnce(&mut Self) -> R,
4049    {
4050        if let Some(image_cache) = image_cache {
4051            self.image_cache_stack.push(image_cache);
4052            let result = f(self);
4053            self.image_cache_stack.pop();
4054            result
4055        } else {
4056            f(self)
4057        }
4058    }
4059
4060    /// Sets an input handler, such as [`ElementInputHandler`][element_input_handler], which interfaces with the
4061    /// platform to receive textual input with proper integration with concerns such
4062    /// as IME interactions. This handler will be active for the upcoming frame until the following frame is
4063    /// rendered.
4064    ///
4065    /// This method should only be called as part of the paint phase of element drawing.
4066    ///
4067    /// [element_input_handler]: crate::ElementInputHandler
4068    pub fn handle_input(
4069        &mut self,
4070        focus_handle: &FocusHandle,
4071        input_handler: impl InputHandler,
4072        cx: &App,
4073    ) {
4074        self.invalidator.debug_assert_paint();
4075
4076        if focus_handle.is_focused(self) {
4077            let cx = self.to_async(cx);
4078            self.next_frame
4079                .input_handlers
4080                .push(Some(PlatformInputHandler::new(cx, Box::new(input_handler))));
4081        }
4082    }
4083
4084    /// Register a mouse event listener on the window for the next frame. The type of event
4085    /// is determined by the first parameter of the given listener. When the next frame is rendered
4086    /// the listener will be cleared.
4087    ///
4088    /// This method should only be called as part of the paint phase of element drawing.
4089    pub fn on_mouse_event<Event: MouseEvent>(
4090        &mut self,
4091        mut listener: impl FnMut(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4092    ) {
4093        self.invalidator.debug_assert_paint();
4094
4095        self.next_frame.mouse_listeners.push(Some(Box::new(
4096            move |event: &dyn Any, phase: DispatchPhase, window: &mut Window, cx: &mut App| {
4097                if let Some(event) = event.downcast_ref() {
4098                    listener(event, phase, window, cx)
4099                }
4100            },
4101        )));
4102    }
4103
4104    /// Register a key event listener on this node for the next frame. The type of event
4105    /// is determined by the first parameter of the given listener. When the next frame is rendered
4106    /// the listener will be cleared.
4107    ///
4108    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
4109    /// a specific need to register a listener yourself.
4110    ///
4111    /// This method should only be called as part of the paint phase of element drawing.
4112    pub fn on_key_event<Event: KeyEvent>(
4113        &mut self,
4114        listener: impl Fn(&Event, DispatchPhase, &mut Window, &mut App) + 'static,
4115    ) {
4116        self.invalidator.debug_assert_paint();
4117
4118        self.next_frame.dispatch_tree.on_key_event(Rc::new(
4119            move |event: &dyn Any, phase, window: &mut Window, cx: &mut App| {
4120                if let Some(event) = event.downcast_ref::<Event>() {
4121                    listener(event, phase, window, cx)
4122                }
4123            },
4124        ));
4125    }
4126
4127    /// Register a modifiers changed event listener on the window for the next frame.
4128    ///
4129    /// This is a fairly low-level method, so prefer using event handlers on elements unless you have
4130    /// a specific need to register a global listener.
4131    ///
4132    /// This method should only be called as part of the paint phase of element drawing.
4133    pub fn on_modifiers_changed(
4134        &mut self,
4135        listener: impl Fn(&ModifiersChangedEvent, &mut Window, &mut App) + 'static,
4136    ) {
4137        self.invalidator.debug_assert_paint();
4138
4139        self.next_frame.dispatch_tree.on_modifiers_changed(Rc::new(
4140            move |event: &ModifiersChangedEvent, window: &mut Window, cx: &mut App| {
4141                listener(event, window, cx)
4142            },
4143        ));
4144    }
4145
4146    /// Register a listener to be called when the given focus handle or one of its descendants receives focus.
4147    /// This does not fire if the given focus handle - or one of its descendants - was previously focused.
4148    /// Returns a subscription and persists until the subscription is dropped.
4149    pub fn on_focus_in(
4150        &mut self,
4151        handle: &FocusHandle,
4152        cx: &mut App,
4153        mut listener: impl FnMut(&mut Window, &mut App) + 'static,
4154    ) -> Subscription {
4155        let focus_id = handle.id;
4156        let (subscription, activate) =
4157            self.new_focus_listener(Box::new(move |event, window, cx| {
4158                if event.is_focus_in(focus_id) {
4159                    listener(window, cx);
4160                }
4161                true
4162            }));
4163        cx.defer(move |_| activate());
4164        subscription
4165    }
4166
4167    /// Register a listener to be called when the given focus handle or one of its descendants loses focus.
4168    /// Returns a subscription and persists until the subscription is dropped.
4169    pub fn on_focus_out(
4170        &mut self,
4171        handle: &FocusHandle,
4172        cx: &mut App,
4173        mut listener: impl FnMut(FocusOutEvent, &mut Window, &mut App) + 'static,
4174    ) -> Subscription {
4175        let focus_id = handle.id;
4176        let (subscription, activate) =
4177            self.new_focus_listener(Box::new(move |event, window, cx| {
4178                if let Some(blurred_id) = event.previous_focus_path.last().copied()
4179                    && event.is_focus_out(focus_id)
4180                {
4181                    let event = FocusOutEvent {
4182                        blurred: WeakFocusHandle {
4183                            id: blurred_id,
4184                            handles: Arc::downgrade(&cx.focus_handles),
4185                        },
4186                    };
4187                    listener(event, window, cx)
4188                }
4189                true
4190            }));
4191        cx.defer(move |_| activate());
4192        subscription
4193    }
4194
4195    fn reset_cursor_style(&self, cx: &mut App) {
4196        // Set the cursor only if we're the active window.
4197        if self.is_window_hovered() {
4198            let style = self
4199                .rendered_frame
4200                .cursor_style(self)
4201                .unwrap_or(CursorStyle::Arrow);
4202            cx.platform.set_cursor_style(style);
4203        }
4204    }
4205
4206    /// Dispatch a given keystroke as though the user had typed it.
4207    /// You can create a keystroke with Keystroke::parse("").
4208    pub fn dispatch_keystroke(&mut self, keystroke: Keystroke, cx: &mut App) -> bool {
4209        let keystroke = keystroke.with_simulated_ime();
4210        let result = self.dispatch_event(
4211            PlatformInput::KeyDown(KeyDownEvent {
4212                keystroke: keystroke.clone(),
4213                is_held: false,
4214                prefer_character_input: false,
4215            }),
4216            cx,
4217        );
4218        if !result.propagate {
4219            return true;
4220        }
4221
4222        if let Some(input) = keystroke.key_char
4223            && let Some(mut input_handler) = self.platform_window.take_input_handler()
4224        {
4225            input_handler.dispatch_input(&input, self, cx);
4226            self.platform_window.set_input_handler(input_handler);
4227            return true;
4228        }
4229
4230        false
4231    }
4232
4233    /// Return a key binding string for an action, to display in the UI. Uses the highest precedence
4234    /// binding for the action (last binding added to the keymap).
4235    pub fn keystroke_text_for(&self, action: &dyn Action) -> String {
4236        self.highest_precedence_binding_for_action(action)
4237            .map(|binding| {
4238                binding
4239                    .keystrokes()
4240                    .iter()
4241                    .map(ToString::to_string)
4242                    .collect::<Vec<_>>()
4243                    .join(" ")
4244            })
4245            .unwrap_or_else(|| action.name().to_string())
4246    }
4247
4248    /// Dispatch a mouse or keyboard event on the window.
4249    #[profiling::function]
4250    pub fn dispatch_event(&mut self, event: PlatformInput, cx: &mut App) -> DispatchEventResult {
4251        #[cfg(feature = "input-latency-histogram")]
4252        let dispatch_time = Instant::now();
4253        let update_count_before = self.invalidator.update_count();
4254        // Track input modality for focus-visible styling and hover suppression.
4255        // Hover is suppressed during keyboard modality so that keyboard navigation
4256        // doesn't show hover highlights on the item under the mouse cursor.
4257        let old_modality = self.last_input_modality;
4258        self.last_input_modality = match &event {
4259            PlatformInput::KeyDown(_) => InputModality::Keyboard,
4260            PlatformInput::MouseMove(_) | PlatformInput::MouseDown(_) => InputModality::Mouse,
4261            _ => self.last_input_modality,
4262        };
4263        if self.last_input_modality != old_modality {
4264            self.refresh();
4265        }
4266
4267        // Handlers may set this to false by calling `stop_propagation`.
4268        cx.propagate_event = true;
4269        // Handlers may set this to true by calling `prevent_default`.
4270        self.default_prevented = false;
4271
4272        let event = match event {
4273            // Track the mouse position with our own state, since accessing the platform
4274            // API for the mouse position can only occur on the main thread.
4275            PlatformInput::MouseMove(mouse_move) => {
4276                self.mouse_position = mouse_move.position;
4277                self.modifiers = mouse_move.modifiers;
4278                PlatformInput::MouseMove(mouse_move)
4279            }
4280            PlatformInput::MouseDown(mouse_down) => {
4281                self.mouse_position = mouse_down.position;
4282                self.modifiers = mouse_down.modifiers;
4283                PlatformInput::MouseDown(mouse_down)
4284            }
4285            PlatformInput::MouseUp(mouse_up) => {
4286                self.mouse_position = mouse_up.position;
4287                self.modifiers = mouse_up.modifiers;
4288                PlatformInput::MouseUp(mouse_up)
4289            }
4290            PlatformInput::MousePressure(mouse_pressure) => {
4291                PlatformInput::MousePressure(mouse_pressure)
4292            }
4293            PlatformInput::MouseExited(mouse_exited) => {
4294                self.modifiers = mouse_exited.modifiers;
4295                PlatformInput::MouseExited(mouse_exited)
4296            }
4297            PlatformInput::ModifiersChanged(modifiers_changed) => {
4298                self.modifiers = modifiers_changed.modifiers;
4299                self.capslock = modifiers_changed.capslock;
4300                PlatformInput::ModifiersChanged(modifiers_changed)
4301            }
4302            PlatformInput::ScrollWheel(scroll_wheel) => {
4303                self.mouse_position = scroll_wheel.position;
4304                self.modifiers = scroll_wheel.modifiers;
4305                PlatformInput::ScrollWheel(scroll_wheel)
4306            }
4307            PlatformInput::Pinch(pinch) => {
4308                self.mouse_position = pinch.position;
4309                self.modifiers = pinch.modifiers;
4310                PlatformInput::Pinch(pinch)
4311            }
4312            // Translate dragging and dropping of external files from the operating system
4313            // to internal drag and drop events.
4314            PlatformInput::FileDrop(file_drop) => match file_drop {
4315                FileDropEvent::Entered { position, paths } => {
4316                    self.mouse_position = position;
4317                    if cx.active_drag.is_none() {
4318                        cx.active_drag = Some(AnyDrag {
4319                            value: Arc::new(paths.clone()),
4320                            view: cx.new(|_| paths).into(),
4321                            cursor_offset: position,
4322                            cursor_style: None,
4323                        });
4324                    }
4325                    PlatformInput::MouseMove(MouseMoveEvent {
4326                        position,
4327                        pressed_button: Some(MouseButton::Left),
4328                        modifiers: Modifiers::default(),
4329                    })
4330                }
4331                FileDropEvent::Pending { position } => {
4332                    self.mouse_position = position;
4333                    PlatformInput::MouseMove(MouseMoveEvent {
4334                        position,
4335                        pressed_button: Some(MouseButton::Left),
4336                        modifiers: Modifiers::default(),
4337                    })
4338                }
4339                FileDropEvent::Submit { position } => {
4340                    cx.activate(true);
4341                    self.mouse_position = position;
4342                    PlatformInput::MouseUp(MouseUpEvent {
4343                        button: MouseButton::Left,
4344                        position,
4345                        modifiers: Modifiers::default(),
4346                        click_count: 1,
4347                    })
4348                }
4349                FileDropEvent::Exited => {
4350                    cx.active_drag.take();
4351                    PlatformInput::FileDrop(FileDropEvent::Exited)
4352                }
4353            },
4354            PlatformInput::KeyDown(_) | PlatformInput::KeyUp(_) => event,
4355        };
4356
4357        if let Some(any_mouse_event) = event.mouse_event() {
4358            self.dispatch_mouse_event(any_mouse_event, cx);
4359        } else if let Some(any_key_event) = event.keyboard_event() {
4360            self.dispatch_key_event(any_key_event, cx);
4361        }
4362
4363        if self.invalidator.update_count() > update_count_before {
4364            self.input_rate_tracker.borrow_mut().record_input();
4365            #[cfg(feature = "input-latency-histogram")]
4366            if self.invalidator.not_drawing() {
4367                self.input_latency_tracker.record_input(dispatch_time);
4368            } else {
4369                self.input_latency_tracker.record_mid_draw_input();
4370            }
4371        }
4372
4373        DispatchEventResult {
4374            propagate: cx.propagate_event,
4375            default_prevented: self.default_prevented,
4376        }
4377    }
4378
4379    fn dispatch_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
4380        let hit_test = self.rendered_frame.hit_test(self.mouse_position());
4381        if hit_test != self.mouse_hit_test {
4382            self.mouse_hit_test = hit_test;
4383            self.reset_cursor_style(cx);
4384        }
4385
4386        #[cfg(debug_assertions)]
4387        if self.is_inspector_picking(cx) {
4388            self.handle_inspector_mouse_event(event, cx);
4389            // When inspector is picking, all other mouse handling is skipped.
4390            return;
4391        }
4392
4393        let mut mouse_listeners = mem::take(&mut self.rendered_frame.mouse_listeners);
4394
4395        // Capture phase, events bubble from back to front. Handlers for this phase are used for
4396        // special purposes, such as detecting events outside of a given Bounds.
4397        for listener in &mut mouse_listeners {
4398            let listener = listener.as_mut().unwrap();
4399            listener(event, DispatchPhase::Capture, self, cx);
4400            if !cx.propagate_event {
4401                break;
4402            }
4403        }
4404
4405        // Bubble phase, where most normal handlers do their work.
4406        if cx.propagate_event {
4407            for listener in mouse_listeners.iter_mut().rev() {
4408                let listener = listener.as_mut().unwrap();
4409                listener(event, DispatchPhase::Bubble, self, cx);
4410                if !cx.propagate_event {
4411                    break;
4412                }
4413            }
4414        }
4415
4416        self.rendered_frame.mouse_listeners = mouse_listeners;
4417
4418        if cx.has_active_drag() {
4419            if event.is::<MouseMoveEvent>() {
4420                // If this was a mouse move event, redraw the window so that the
4421                // active drag can follow the mouse cursor.
4422                self.refresh();
4423            } else if event.is::<MouseUpEvent>() {
4424                // If this was a mouse up event, cancel the active drag and redraw
4425                // the window.
4426                cx.active_drag = None;
4427                self.refresh();
4428            }
4429        }
4430
4431        // Auto-release pointer capture on mouse up
4432        if event.is::<MouseUpEvent>() && self.captured_hitbox.is_some() {
4433            self.captured_hitbox = None;
4434        }
4435    }
4436
4437    fn dispatch_key_event(&mut self, event: &dyn Any, cx: &mut App) {
4438        if self.invalidator.is_dirty() {
4439            self.draw(cx).clear();
4440        }
4441
4442        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4443        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4444
4445        let mut keystroke: Option<Keystroke> = None;
4446
4447        if let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() {
4448            if event.modifiers.number_of_modifiers() == 0
4449                && self.pending_modifier.modifiers.number_of_modifiers() == 1
4450                && !self.pending_modifier.saw_keystroke
4451            {
4452                let key = match self.pending_modifier.modifiers {
4453                    modifiers if modifiers.shift => Some("shift"),
4454                    modifiers if modifiers.control => Some("control"),
4455                    modifiers if modifiers.alt => Some("alt"),
4456                    modifiers if modifiers.platform => Some("platform"),
4457                    modifiers if modifiers.function => Some("function"),
4458                    _ => None,
4459                };
4460                if let Some(key) = key {
4461                    keystroke = Some(Keystroke {
4462                        key: key.to_string(),
4463                        key_char: None,
4464                        modifiers: Modifiers::default(),
4465                    });
4466                }
4467            }
4468
4469            if self.pending_modifier.modifiers.number_of_modifiers() == 0
4470                && event.modifiers.number_of_modifiers() == 1
4471            {
4472                self.pending_modifier.saw_keystroke = false
4473            }
4474            self.pending_modifier.modifiers = event.modifiers
4475        } else if let Some(key_down_event) = event.downcast_ref::<KeyDownEvent>() {
4476            self.pending_modifier.saw_keystroke = true;
4477            keystroke = Some(key_down_event.keystroke.clone());
4478            if key_down_event.keystroke.key_char.is_some()
4479                && matches!(
4480                    cx.cursor_hide_mode,
4481                    CursorHideMode::OnTyping | CursorHideMode::OnTypingAndAction
4482                )
4483            {
4484                cx.platform.hide_cursor_until_mouse_moves();
4485            }
4486        }
4487
4488        let Some(keystroke) = keystroke else {
4489            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4490            return;
4491        };
4492
4493        cx.propagate_event = true;
4494        self.dispatch_keystroke_interceptors(event, self.context_stack(), cx);
4495        if !cx.propagate_event {
4496            self.finish_dispatch_key_event(event, dispatch_path, self.context_stack(), cx);
4497            return;
4498        }
4499
4500        let mut currently_pending = self.pending_input.take().unwrap_or_default();
4501        if currently_pending.focus.is_some() && currently_pending.focus != self.focus {
4502            currently_pending = PendingInput::default();
4503        }
4504
4505        let match_result = self.rendered_frame.dispatch_tree.dispatch_key(
4506            currently_pending.keystrokes,
4507            keystroke,
4508            &dispatch_path,
4509        );
4510
4511        if !match_result.to_replay.is_empty() {
4512            self.replay_pending_input(match_result.to_replay, cx);
4513            cx.propagate_event = true;
4514        }
4515
4516        if !match_result.pending.is_empty() {
4517            currently_pending.timer.take();
4518            currently_pending.keystrokes = match_result.pending;
4519            currently_pending.focus = self.focus;
4520
4521            let text_input_requires_timeout = event
4522                .downcast_ref::<KeyDownEvent>()
4523                .filter(|key_down| key_down.keystroke.key_char.is_some())
4524                .and_then(|_| self.platform_window.take_input_handler())
4525                .map_or(false, |mut input_handler| {
4526                    let accepts = input_handler.accepts_text_input(self, cx);
4527                    self.platform_window.set_input_handler(input_handler);
4528                    accepts
4529                });
4530
4531            currently_pending.needs_timeout |=
4532                match_result.pending_has_binding || text_input_requires_timeout;
4533
4534            if currently_pending.needs_timeout {
4535                currently_pending.timer = Some(self.spawn(cx, async move |cx| {
4536                    cx.background_executor.timer(Duration::from_secs(1)).await;
4537                    cx.update(move |window, cx| {
4538                        let Some(currently_pending) = window
4539                            .pending_input
4540                            .take()
4541                            .filter(|pending| pending.focus == window.focus)
4542                        else {
4543                            return;
4544                        };
4545
4546                        let node_id = window.focus_node_id_in_rendered_frame(window.focus);
4547                        let dispatch_path =
4548                            window.rendered_frame.dispatch_tree.dispatch_path(node_id);
4549
4550                        let to_replay = window
4551                            .rendered_frame
4552                            .dispatch_tree
4553                            .flush_dispatch(currently_pending.keystrokes, &dispatch_path);
4554
4555                        window.pending_input_changed(cx);
4556                        window.replay_pending_input(to_replay, cx)
4557                    })
4558                    .log_err();
4559                }));
4560            } else {
4561                currently_pending.timer = None;
4562            }
4563            self.pending_input = Some(currently_pending);
4564            self.pending_input_changed(cx);
4565            cx.propagate_event = false;
4566            return;
4567        }
4568
4569        let skip_bindings = event
4570            .downcast_ref::<KeyDownEvent>()
4571            .filter(|key_down_event| key_down_event.prefer_character_input)
4572            .map(|_| {
4573                self.platform_window
4574                    .take_input_handler()
4575                    .map_or(false, |mut input_handler| {
4576                        let accepts = input_handler.accepts_text_input(self, cx);
4577                        self.platform_window.set_input_handler(input_handler);
4578                        // If modifiers are not excessive (e.g. AltGr), and the input handler is accepting text input,
4579                        // we prefer the text input over bindings.
4580                        accepts
4581                    })
4582            })
4583            .unwrap_or(false);
4584
4585        if !skip_bindings {
4586            for binding in match_result.bindings {
4587                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4588                if !cx.propagate_event {
4589                    self.dispatch_keystroke_observers(
4590                        event,
4591                        Some(binding.action),
4592                        match_result.context_stack,
4593                        cx,
4594                    );
4595                    self.pending_input_changed(cx);
4596                    return;
4597                }
4598            }
4599        }
4600
4601        self.finish_dispatch_key_event(event, dispatch_path, match_result.context_stack, cx);
4602        self.pending_input_changed(cx);
4603    }
4604
4605    fn finish_dispatch_key_event(
4606        &mut self,
4607        event: &dyn Any,
4608        dispatch_path: SmallVec<[DispatchNodeId; 32]>,
4609        context_stack: Vec<KeyContext>,
4610        cx: &mut App,
4611    ) {
4612        self.dispatch_key_down_up_event(event, &dispatch_path, cx);
4613        if !cx.propagate_event {
4614            return;
4615        }
4616
4617        self.dispatch_modifiers_changed_event(event, &dispatch_path, cx);
4618        if !cx.propagate_event {
4619            return;
4620        }
4621
4622        self.dispatch_keystroke_observers(event, None, context_stack, cx);
4623    }
4624
4625    pub(crate) fn pending_input_changed(&mut self, cx: &mut App) {
4626        self.pending_input_observers
4627            .clone()
4628            .retain(&(), |callback| callback(self, cx));
4629    }
4630
4631    fn dispatch_key_down_up_event(
4632        &mut self,
4633        event: &dyn Any,
4634        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4635        cx: &mut App,
4636    ) {
4637        // Capture phase
4638        for node_id in dispatch_path {
4639            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4640
4641            for key_listener in node.key_listeners.clone() {
4642                key_listener(event, DispatchPhase::Capture, self, cx);
4643                if !cx.propagate_event {
4644                    return;
4645                }
4646            }
4647        }
4648
4649        // Bubble phase
4650        for node_id in dispatch_path.iter().rev() {
4651            // Handle low level key events
4652            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4653            for key_listener in node.key_listeners.clone() {
4654                key_listener(event, DispatchPhase::Bubble, self, cx);
4655                if !cx.propagate_event {
4656                    return;
4657                }
4658            }
4659        }
4660    }
4661
4662    fn dispatch_modifiers_changed_event(
4663        &mut self,
4664        event: &dyn Any,
4665        dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
4666        cx: &mut App,
4667    ) {
4668        let Some(event) = event.downcast_ref::<ModifiersChangedEvent>() else {
4669            return;
4670        };
4671        for node_id in dispatch_path.iter().rev() {
4672            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4673            for listener in node.modifiers_changed_listeners.clone() {
4674                listener(event, self, cx);
4675                if !cx.propagate_event {
4676                    return;
4677                }
4678            }
4679        }
4680    }
4681
4682    /// Determine whether a potential multi-stroke key binding is in progress on this window.
4683    pub fn has_pending_keystrokes(&self) -> bool {
4684        self.pending_input.is_some()
4685    }
4686
4687    pub(crate) fn clear_pending_keystrokes(&mut self) {
4688        self.pending_input.take();
4689    }
4690
4691    /// Returns the currently pending input keystrokes that might result in a multi-stroke key binding.
4692    pub fn pending_input_keystrokes(&self) -> Option<&[Keystroke]> {
4693        self.pending_input
4694            .as_ref()
4695            .map(|pending_input| pending_input.keystrokes.as_slice())
4696    }
4697
4698    fn replay_pending_input(&mut self, replays: SmallVec<[Replay; 1]>, cx: &mut App) {
4699        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4700        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4701
4702        'replay: for replay in replays {
4703            let event = KeyDownEvent {
4704                keystroke: replay.keystroke.clone(),
4705                is_held: false,
4706                prefer_character_input: true,
4707            };
4708
4709            cx.propagate_event = true;
4710            for binding in replay.bindings {
4711                self.dispatch_action_on_node(node_id, binding.action.as_ref(), cx);
4712                if !cx.propagate_event {
4713                    self.dispatch_keystroke_observers(
4714                        &event,
4715                        Some(binding.action),
4716                        Vec::default(),
4717                        cx,
4718                    );
4719                    continue 'replay;
4720                }
4721            }
4722
4723            self.dispatch_key_down_up_event(&event, &dispatch_path, cx);
4724            if !cx.propagate_event {
4725                continue 'replay;
4726            }
4727            if let Some(input) = replay.keystroke.key_char.as_ref().cloned()
4728                && let Some(mut input_handler) = self.platform_window.take_input_handler()
4729            {
4730                input_handler.dispatch_input(&input, self, cx);
4731                self.platform_window.set_input_handler(input_handler)
4732            }
4733        }
4734    }
4735
4736    fn focus_node_id_in_rendered_frame(&self, focus_id: Option<FocusId>) -> DispatchNodeId {
4737        focus_id
4738            .and_then(|focus_id| {
4739                self.rendered_frame
4740                    .dispatch_tree
4741                    .focusable_node_id(focus_id)
4742            })
4743            .unwrap_or_else(|| self.rendered_frame.dispatch_tree.root_node_id())
4744    }
4745
4746    fn dispatch_action_on_node(
4747        &mut self,
4748        node_id: DispatchNodeId,
4749        action: &dyn Action,
4750        cx: &mut App,
4751    ) {
4752        self.dispatch_action_on_node_inner(node_id, action, cx);
4753
4754        if !cx.propagate_event
4755            && cx.cursor_hide_mode == CursorHideMode::OnTypingAndAction
4756            && self.last_input_was_keyboard()
4757        {
4758            cx.platform.hide_cursor_until_mouse_moves();
4759        }
4760    }
4761
4762    fn dispatch_action_on_node_inner(
4763        &mut self,
4764        node_id: DispatchNodeId,
4765        action: &dyn Action,
4766        cx: &mut App,
4767    ) {
4768        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
4769
4770        // Capture phase for global actions.
4771        cx.propagate_event = true;
4772        if let Some(mut global_listeners) = cx
4773            .global_action_listeners
4774            .remove(&action.as_any().type_id())
4775        {
4776            for listener in &global_listeners {
4777                listener(action.as_any(), DispatchPhase::Capture, cx);
4778                if !cx.propagate_event {
4779                    break;
4780                }
4781            }
4782
4783            global_listeners.extend(
4784                cx.global_action_listeners
4785                    .remove(&action.as_any().type_id())
4786                    .unwrap_or_default(),
4787            );
4788
4789            cx.global_action_listeners
4790                .insert(action.as_any().type_id(), global_listeners);
4791        }
4792
4793        if !cx.propagate_event {
4794            return;
4795        }
4796
4797        // Capture phase for window actions.
4798        for node_id in &dispatch_path {
4799            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4800            for DispatchActionListener {
4801                action_type,
4802                listener,
4803            } in node.action_listeners.clone()
4804            {
4805                let any_action = action.as_any();
4806                if action_type == any_action.type_id() {
4807                    listener(any_action, DispatchPhase::Capture, self, cx);
4808
4809                    if !cx.propagate_event {
4810                        return;
4811                    }
4812                }
4813            }
4814        }
4815
4816        // Bubble phase for window actions.
4817        for node_id in dispatch_path.iter().rev() {
4818            let node = self.rendered_frame.dispatch_tree.node(*node_id);
4819            for DispatchActionListener {
4820                action_type,
4821                listener,
4822            } in node.action_listeners.clone()
4823            {
4824                let any_action = action.as_any();
4825                if action_type == any_action.type_id() {
4826                    cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4827                    listener(any_action, DispatchPhase::Bubble, self, cx);
4828
4829                    if !cx.propagate_event {
4830                        return;
4831                    }
4832                }
4833            }
4834        }
4835
4836        // Bubble phase for global actions.
4837        if let Some(mut global_listeners) = cx
4838            .global_action_listeners
4839            .remove(&action.as_any().type_id())
4840        {
4841            for listener in global_listeners.iter().rev() {
4842                cx.propagate_event = false; // Actions stop propagation by default during the bubble phase
4843
4844                listener(action.as_any(), DispatchPhase::Bubble, cx);
4845                if !cx.propagate_event {
4846                    break;
4847                }
4848            }
4849
4850            global_listeners.extend(
4851                cx.global_action_listeners
4852                    .remove(&action.as_any().type_id())
4853                    .unwrap_or_default(),
4854            );
4855
4856            cx.global_action_listeners
4857                .insert(action.as_any().type_id(), global_listeners);
4858        }
4859    }
4860
4861    /// Register the given handler to be invoked whenever the global of the given type
4862    /// is updated.
4863    pub fn observe_global<G: Global>(
4864        &mut self,
4865        cx: &mut App,
4866        f: impl Fn(&mut Window, &mut App) + 'static,
4867    ) -> Subscription {
4868        let window_handle = self.handle;
4869        let (subscription, activate) = cx.global_observers.insert(
4870            TypeId::of::<G>(),
4871            Box::new(move |cx| {
4872                window_handle
4873                    .update(cx, |_, window, cx| f(window, cx))
4874                    .is_ok()
4875            }),
4876        );
4877        cx.defer(move |_| activate());
4878        subscription
4879    }
4880
4881    /// Focus the current window and bring it to the foreground at the platform level.
4882    pub fn activate_window(&self) {
4883        self.platform_window.activate();
4884    }
4885
4886    /// Minimize the current window at the platform level.
4887    pub fn minimize_window(&self) {
4888        self.platform_window.minimize();
4889    }
4890
4891    /// Toggle full screen status on the current window at the platform level.
4892    pub fn toggle_fullscreen(&self) {
4893        self.platform_window.toggle_fullscreen();
4894    }
4895
4896    /// Updates the IME panel position suggestions for languages like japanese, chinese.
4897    pub fn invalidate_character_coordinates(&self) {
4898        self.on_next_frame(|window, cx| {
4899            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
4900                if let Some(bounds) = input_handler.selected_bounds(window, cx) {
4901                    window.platform_window.update_ime_position(bounds);
4902                }
4903                window.platform_window.set_input_handler(input_handler);
4904            }
4905        });
4906    }
4907
4908    /// Present a platform dialog.
4909    /// The provided message will be presented, along with buttons for each answer.
4910    /// When a button is clicked, the returned Receiver will receive the index of the clicked button.
4911    pub fn prompt<T>(
4912        &mut self,
4913        level: PromptLevel,
4914        message: &str,
4915        detail: Option<&str>,
4916        answers: &[T],
4917        cx: &mut App,
4918    ) -> oneshot::Receiver<usize>
4919    where
4920        T: Clone + Into<PromptButton>,
4921    {
4922        let prompt_builder = cx.prompt_builder.take();
4923        let Some(prompt_builder) = prompt_builder else {
4924            unreachable!("Re-entrant window prompting is not supported by GPUI");
4925        };
4926
4927        let answers = answers
4928            .iter()
4929            .map(|answer| answer.clone().into())
4930            .collect::<Vec<_>>();
4931
4932        let receiver = match &prompt_builder {
4933            PromptBuilder::Default => self
4934                .platform_window
4935                .prompt(level, message, detail, &answers)
4936                .unwrap_or_else(|| {
4937                    self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4938                }),
4939            PromptBuilder::Custom(_) => {
4940                self.build_custom_prompt(&prompt_builder, level, message, detail, &answers, cx)
4941            }
4942        };
4943
4944        cx.prompt_builder = Some(prompt_builder);
4945
4946        receiver
4947    }
4948
4949    fn build_custom_prompt(
4950        &mut self,
4951        prompt_builder: &PromptBuilder,
4952        level: PromptLevel,
4953        message: &str,
4954        detail: Option<&str>,
4955        answers: &[PromptButton],
4956        cx: &mut App,
4957    ) -> oneshot::Receiver<usize> {
4958        let (sender, receiver) = oneshot::channel();
4959        let handle = PromptHandle::new(sender);
4960        let handle = (prompt_builder)(level, message, detail, answers, handle, self, cx);
4961        self.prompt = Some(handle);
4962        receiver
4963    }
4964
4965    /// Returns the current context stack.
4966    pub fn context_stack(&self) -> Vec<KeyContext> {
4967        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4968        let dispatch_tree = &self.rendered_frame.dispatch_tree;
4969        dispatch_tree
4970            .dispatch_path(node_id)
4971            .iter()
4972            .filter_map(move |&node_id| dispatch_tree.node(node_id).context.clone())
4973            .collect()
4974    }
4975
4976    /// Returns all available actions for the focused element.
4977    pub fn available_actions(&self, cx: &App) -> Vec<Box<dyn Action>> {
4978        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
4979        let mut actions = self.rendered_frame.dispatch_tree.available_actions(node_id);
4980        for action_type in cx.global_action_listeners.keys() {
4981            if let Err(ix) = actions.binary_search_by_key(action_type, |a| a.as_any().type_id()) {
4982                let action = cx.actions.build_action_type(action_type).ok();
4983                if let Some(action) = action {
4984                    actions.insert(ix, action);
4985                }
4986            }
4987        }
4988        actions
4989    }
4990
4991    /// Returns key bindings that invoke an action on the currently focused element. Bindings are
4992    /// returned in the order they were added. For display, the last binding should take precedence.
4993    pub fn bindings_for_action(&self, action: &dyn Action) -> Vec<KeyBinding> {
4994        self.rendered_frame
4995            .dispatch_tree
4996            .bindings_for_action(action, &self.rendered_frame.dispatch_tree.context_stack)
4997    }
4998
4999    /// Returns the highest precedence key binding that invokes an action on the currently focused
5000    /// element. This is more efficient than getting the last result of `bindings_for_action`.
5001    pub fn highest_precedence_binding_for_action(&self, action: &dyn Action) -> Option<KeyBinding> {
5002        self.rendered_frame
5003            .dispatch_tree
5004            .highest_precedence_binding_for_action(
5005                action,
5006                &self.rendered_frame.dispatch_tree.context_stack,
5007            )
5008    }
5009
5010    /// Returns the key bindings for an action in a context.
5011    pub fn bindings_for_action_in_context(
5012        &self,
5013        action: &dyn Action,
5014        context: KeyContext,
5015    ) -> Vec<KeyBinding> {
5016        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5017        dispatch_tree.bindings_for_action(action, &[context])
5018    }
5019
5020    /// Returns the highest precedence key binding for an action in a context. This is more
5021    /// efficient than getting the last result of `bindings_for_action_in_context`.
5022    pub fn highest_precedence_binding_for_action_in_context(
5023        &self,
5024        action: &dyn Action,
5025        context: KeyContext,
5026    ) -> Option<KeyBinding> {
5027        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5028        dispatch_tree.highest_precedence_binding_for_action(action, &[context])
5029    }
5030
5031    /// Returns any bindings that would invoke an action on the given focus handle if it were
5032    /// focused. Bindings are returned in the order they were added. For display, the last binding
5033    /// should take precedence.
5034    pub fn bindings_for_action_in(
5035        &self,
5036        action: &dyn Action,
5037        focus_handle: &FocusHandle,
5038    ) -> Vec<KeyBinding> {
5039        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5040        let Some(context_stack) = self.context_stack_for_focus_handle(focus_handle) else {
5041            return vec![];
5042        };
5043        dispatch_tree.bindings_for_action(action, &context_stack)
5044    }
5045
5046    /// Returns the highest precedence key binding that would invoke an action on the given focus
5047    /// handle if it were focused. This is more efficient than getting the last result of
5048    /// `bindings_for_action_in`.
5049    pub fn highest_precedence_binding_for_action_in(
5050        &self,
5051        action: &dyn Action,
5052        focus_handle: &FocusHandle,
5053    ) -> Option<KeyBinding> {
5054        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5055        let context_stack = self.context_stack_for_focus_handle(focus_handle)?;
5056        dispatch_tree.highest_precedence_binding_for_action(action, &context_stack)
5057    }
5058
5059    /// Find the bindings that can follow the current input sequence for the current context stack.
5060    pub fn possible_bindings_for_input(&self, input: &[Keystroke]) -> Vec<KeyBinding> {
5061        self.rendered_frame
5062            .dispatch_tree
5063            .possible_next_bindings_for_input(input, &self.context_stack())
5064    }
5065
5066    fn context_stack_for_focus_handle(
5067        &self,
5068        focus_handle: &FocusHandle,
5069    ) -> Option<Vec<KeyContext>> {
5070        let dispatch_tree = &self.rendered_frame.dispatch_tree;
5071        let node_id = dispatch_tree.focusable_node_id(focus_handle.id)?;
5072        let context_stack: Vec<_> = dispatch_tree
5073            .dispatch_path(node_id)
5074            .into_iter()
5075            .filter_map(|node_id| dispatch_tree.node(node_id).context.clone())
5076            .collect();
5077        Some(context_stack)
5078    }
5079
5080    /// Returns a generic event listener that invokes the given listener with the view and context associated with the given view handle.
5081    pub fn listener_for<T: 'static, E>(
5082        &self,
5083        view: &Entity<T>,
5084        f: impl Fn(&mut T, &E, &mut Window, &mut Context<T>) + 'static,
5085    ) -> impl Fn(&E, &mut Window, &mut App) + 'static {
5086        let view = view.downgrade();
5087        move |e: &E, window: &mut Window, cx: &mut App| {
5088            view.update(cx, |view, cx| f(view, e, window, cx)).ok();
5089        }
5090    }
5091
5092    /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
5093    pub fn handler_for<E: 'static, Callback: Fn(&mut E, &mut Window, &mut Context<E>) + 'static>(
5094        &self,
5095        entity: &Entity<E>,
5096        f: Callback,
5097    ) -> impl Fn(&mut Window, &mut App) + 'static {
5098        let entity = entity.downgrade();
5099        move |window: &mut Window, cx: &mut App| {
5100            entity.update(cx, |entity, cx| f(entity, window, cx)).ok();
5101        }
5102    }
5103
5104    /// Register a callback that can interrupt the closing of the current window based the returned boolean.
5105    /// If the callback returns false, the window won't be closed.
5106    pub fn on_window_should_close(
5107        &self,
5108        cx: &App,
5109        f: impl Fn(&mut Window, &mut App) -> bool + 'static,
5110    ) {
5111        let mut cx = self.to_async(cx);
5112        self.platform_window.on_should_close(Box::new(move || {
5113            cx.update(|window, cx| f(window, cx)).unwrap_or(true)
5114        }))
5115    }
5116
5117    /// Register an action listener on this node for the next frame. The type of action
5118    /// is determined by the first parameter of the given listener. When the next frame is rendered
5119    /// the listener will be cleared.
5120    ///
5121    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
5122    /// a specific need to register a listener yourself.
5123    ///
5124    /// This method should only be called as part of the paint phase of element drawing.
5125    pub fn on_action(
5126        &mut self,
5127        action_type: TypeId,
5128        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5129    ) {
5130        self.invalidator.debug_assert_paint();
5131
5132        self.next_frame
5133            .dispatch_tree
5134            .on_action(action_type, Rc::new(listener));
5135    }
5136
5137    /// Register a capturing action listener on this node for the next frame if the condition is true.
5138    /// The type of action is determined by the first parameter of the given listener. When the next
5139    /// frame is rendered the listener will be cleared.
5140    ///
5141    /// This is a fairly low-level method, so prefer using action handlers on elements unless you have
5142    /// a specific need to register a listener yourself.
5143    ///
5144    /// This method should only be called as part of the paint phase of element drawing.
5145    pub fn on_action_when(
5146        &mut self,
5147        condition: bool,
5148        action_type: TypeId,
5149        listener: impl Fn(&dyn Any, DispatchPhase, &mut Window, &mut App) + 'static,
5150    ) {
5151        self.invalidator.debug_assert_paint();
5152
5153        if condition {
5154            self.next_frame
5155                .dispatch_tree
5156                .on_action(action_type, Rc::new(listener));
5157        }
5158    }
5159
5160    /// Read information about the GPU backing this window.
5161    /// Currently returns None on Mac and Windows.
5162    pub fn gpu_specs(&self) -> Option<GpuSpecs> {
5163        self.platform_window.gpu_specs()
5164    }
5165
5166    /// Perform titlebar double-click action.
5167    /// This is macOS specific.
5168    pub fn titlebar_double_click(&self) {
5169        self.platform_window.titlebar_double_click();
5170    }
5171
5172    /// Gets the window's title at the platform level.
5173    /// This is macOS specific.
5174    pub fn window_title(&self) -> String {
5175        self.platform_window.get_title()
5176    }
5177
5178    /// Returns a list of all tabbed windows and their titles.
5179    /// This is macOS specific.
5180    pub fn tabbed_windows(&self) -> Option<Vec<SystemWindowTab>> {
5181        self.platform_window.tabbed_windows()
5182    }
5183
5184    /// Returns the tab bar visibility.
5185    /// This is macOS specific.
5186    pub fn tab_bar_visible(&self) -> bool {
5187        self.platform_window.tab_bar_visible()
5188    }
5189
5190    /// Merges all open windows into a single tabbed window.
5191    /// This is macOS specific.
5192    pub fn merge_all_windows(&self) {
5193        self.platform_window.merge_all_windows()
5194    }
5195
5196    /// Moves the tab to a new containing window.
5197    /// This is macOS specific.
5198    pub fn move_tab_to_new_window(&self) {
5199        self.platform_window.move_tab_to_new_window()
5200    }
5201
5202    /// Shows or hides the window tab overview.
5203    /// This is macOS specific.
5204    pub fn toggle_window_tab_overview(&self) {
5205        self.platform_window.toggle_window_tab_overview()
5206    }
5207
5208    /// Sets the tabbing identifier for the window.
5209    /// This is macOS specific.
5210    pub fn set_tabbing_identifier(&self, tabbing_identifier: Option<String>) {
5211        self.platform_window
5212            .set_tabbing_identifier(tabbing_identifier)
5213    }
5214
5215    /// Request the OS to play an alert sound. On some platforms this is associated
5216    /// with the window, for others it's just a simple global function call.
5217    pub fn play_system_bell(&self) {
5218        self.platform_window.play_system_bell()
5219    }
5220
5221    /// Toggles the inspector mode on this window.
5222    #[cfg(debug_assertions)]
5223    pub fn toggle_inspector(&mut self, cx: &mut App) {
5224        self.inspector = match self.inspector {
5225            None => Some(cx.new(|_| Inspector::new())),
5226            Some(_) => None,
5227        };
5228        self.refresh();
5229    }
5230
5231    /// Returns true if the window is in inspector mode.
5232    pub fn is_inspector_picking(&self, _cx: &App) -> bool {
5233        #[cfg(debug_assertions)]
5234        {
5235            if let Some(inspector) = &self.inspector {
5236                return inspector.read(_cx).is_picking();
5237            }
5238        }
5239        false
5240    }
5241
5242    /// Executes the provided function with mutable access to an inspector state.
5243    #[cfg(debug_assertions)]
5244    pub fn with_inspector_state<T: 'static, R>(
5245        &mut self,
5246        _inspector_id: Option<&crate::InspectorElementId>,
5247        cx: &mut App,
5248        f: impl FnOnce(&mut Option<T>, &mut Self) -> R,
5249    ) -> R {
5250        if let Some(inspector_id) = _inspector_id
5251            && let Some(inspector) = &self.inspector
5252        {
5253            let inspector = inspector.clone();
5254            let active_element_id = inspector.read(cx).active_element_id();
5255            if Some(inspector_id) == active_element_id {
5256                return inspector.update(cx, |inspector, _cx| {
5257                    inspector.with_active_element_state(self, f)
5258                });
5259            }
5260        }
5261        f(&mut None, self)
5262    }
5263
5264    #[cfg(debug_assertions)]
5265    pub(crate) fn build_inspector_element_id(
5266        &mut self,
5267        path: crate::InspectorElementPath,
5268    ) -> crate::InspectorElementId {
5269        self.invalidator.debug_assert_paint_or_prepaint();
5270        let path = Rc::new(path);
5271        let next_instance_id = self
5272            .next_frame
5273            .next_inspector_instance_ids
5274            .entry(path.clone())
5275            .or_insert(0);
5276        let instance_id = *next_instance_id;
5277        *next_instance_id += 1;
5278        crate::InspectorElementId { path, instance_id }
5279    }
5280
5281    #[cfg(debug_assertions)]
5282    fn prepaint_inspector(&mut self, inspector_width: Pixels, cx: &mut App) -> Option<AnyElement> {
5283        if let Some(inspector) = self.inspector.take() {
5284            let mut inspector_element = AnyView::from(inspector.clone()).into_any_element();
5285            inspector_element.prepaint_as_root(
5286                point(self.viewport_size.width - inspector_width, px(0.0)),
5287                size(inspector_width, self.viewport_size.height).into(),
5288                self,
5289                cx,
5290            );
5291            self.inspector = Some(inspector);
5292            Some(inspector_element)
5293        } else {
5294            None
5295        }
5296    }
5297
5298    #[cfg(debug_assertions)]
5299    fn paint_inspector(&mut self, mut inspector_element: Option<AnyElement>, cx: &mut App) {
5300        if let Some(mut inspector_element) = inspector_element {
5301            inspector_element.paint(self, cx);
5302        };
5303    }
5304
5305    /// Registers a hitbox that can be used for inspector picking mode, allowing users to select and
5306    /// inspect UI elements by clicking on them.
5307    #[cfg(debug_assertions)]
5308    pub fn insert_inspector_hitbox(
5309        &mut self,
5310        hitbox_id: HitboxId,
5311        inspector_id: Option<&crate::InspectorElementId>,
5312        cx: &App,
5313    ) {
5314        self.invalidator.debug_assert_paint_or_prepaint();
5315        if !self.is_inspector_picking(cx) {
5316            return;
5317        }
5318        if let Some(inspector_id) = inspector_id {
5319            self.next_frame
5320                .inspector_hitboxes
5321                .insert(hitbox_id, inspector_id.clone());
5322        }
5323    }
5324
5325    #[cfg(debug_assertions)]
5326    fn paint_inspector_hitbox(&mut self, cx: &App) {
5327        if let Some(inspector) = self.inspector.as_ref() {
5328            let inspector = inspector.read(cx);
5329            if let Some((hitbox_id, _)) = self.hovered_inspector_hitbox(inspector, &self.next_frame)
5330                && let Some(hitbox) = self
5331                    .next_frame
5332                    .hitboxes
5333                    .iter()
5334                    .find(|hitbox| hitbox.id == hitbox_id)
5335            {
5336                self.paint_quad(crate::fill(hitbox.bounds, crate::rgba(0x61afef4d)));
5337            }
5338        }
5339    }
5340
5341    #[cfg(debug_assertions)]
5342    fn handle_inspector_mouse_event(&mut self, event: &dyn Any, cx: &mut App) {
5343        let Some(inspector) = self.inspector.clone() else {
5344            return;
5345        };
5346        if event.downcast_ref::<MouseMoveEvent>().is_some() {
5347            inspector.update(cx, |inspector, _cx| {
5348                if let Some((_, inspector_id)) =
5349                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5350                {
5351                    inspector.hover(inspector_id, self);
5352                }
5353            });
5354        } else if event.downcast_ref::<crate::MouseDownEvent>().is_some() {
5355            inspector.update(cx, |inspector, _cx| {
5356                if let Some((_, inspector_id)) =
5357                    self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5358                {
5359                    inspector.select(inspector_id, self);
5360                }
5361            });
5362        } else if let Some(event) = event.downcast_ref::<crate::ScrollWheelEvent>() {
5363            // This should be kept in sync with SCROLL_LINES in x11 platform.
5364            const SCROLL_LINES: f32 = 3.0;
5365            const SCROLL_PIXELS_PER_LAYER: f32 = 36.0;
5366            let delta_y = event
5367                .delta
5368                .pixel_delta(px(SCROLL_PIXELS_PER_LAYER / SCROLL_LINES))
5369                .y;
5370            if let Some(inspector) = self.inspector.clone() {
5371                inspector.update(cx, |inspector, _cx| {
5372                    if let Some(depth) = inspector.pick_depth.as_mut() {
5373                        *depth += f32::from(delta_y) / SCROLL_PIXELS_PER_LAYER;
5374                        let max_depth = self.mouse_hit_test.ids.len() as f32 - 0.5;
5375                        if *depth < 0.0 {
5376                            *depth = 0.0;
5377                        } else if *depth > max_depth {
5378                            *depth = max_depth;
5379                        }
5380                        if let Some((_, inspector_id)) =
5381                            self.hovered_inspector_hitbox(inspector, &self.rendered_frame)
5382                        {
5383                            inspector.set_active_element_id(inspector_id, self);
5384                        }
5385                    }
5386                });
5387            }
5388        }
5389    }
5390
5391    #[cfg(debug_assertions)]
5392    fn hovered_inspector_hitbox(
5393        &self,
5394        inspector: &Inspector,
5395        frame: &Frame,
5396    ) -> Option<(HitboxId, crate::InspectorElementId)> {
5397        if let Some(pick_depth) = inspector.pick_depth {
5398            let depth = (pick_depth as i64).try_into().unwrap_or(0);
5399            let max_skipped = self.mouse_hit_test.ids.len().saturating_sub(1);
5400            let skip_count = (depth as usize).min(max_skipped);
5401            for hitbox_id in self.mouse_hit_test.ids.iter().skip(skip_count) {
5402                if let Some(inspector_id) = frame.inspector_hitboxes.get(hitbox_id) {
5403                    return Some((*hitbox_id, inspector_id.clone()));
5404                }
5405            }
5406        }
5407        None
5408    }
5409
5410    /// For testing: set the current modifier keys state.
5411    /// This does not generate any events.
5412    #[cfg(any(test, feature = "test-support"))]
5413    pub fn set_modifiers(&mut self, modifiers: Modifiers) {
5414        self.modifiers = modifiers;
5415    }
5416
5417    /// For testing: simulate a mouse move event to the given position.
5418    /// This dispatches the event through the normal event handling path,
5419    /// which will trigger hover states and tooltips.
5420    #[cfg(any(test, feature = "test-support"))]
5421    pub fn simulate_mouse_move(&mut self, position: Point<Pixels>, cx: &mut App) {
5422        let event = PlatformInput::MouseMove(MouseMoveEvent {
5423            position,
5424            modifiers: self.modifiers,
5425            pressed_button: None,
5426        });
5427        let _ = self.dispatch_event(event, cx);
5428    }
5429}
5430
5431// #[derive(Clone, Copy, Eq, PartialEq, Hash)]
5432slotmap::new_key_type! {
5433    /// A unique identifier for a window.
5434    pub struct WindowId;
5435}
5436
5437impl WindowId {
5438    /// Converts this window ID to a `u64`.
5439    pub fn as_u64(&self) -> u64 {
5440        self.0.as_ffi()
5441    }
5442}
5443
5444impl From<u64> for WindowId {
5445    fn from(value: u64) -> Self {
5446        WindowId(slotmap::KeyData::from_ffi(value))
5447    }
5448}
5449
5450/// A handle to a window with a specific root view type.
5451/// Note that this does not keep the window alive on its own.
5452#[derive(Deref, DerefMut)]
5453pub struct WindowHandle<V> {
5454    #[deref]
5455    #[deref_mut]
5456    pub(crate) any_handle: AnyWindowHandle,
5457    state_type: PhantomData<fn(V) -> V>,
5458}
5459
5460impl<V> Debug for WindowHandle<V> {
5461    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5462        f.debug_struct("WindowHandle")
5463            .field("any_handle", &self.any_handle.id.as_u64())
5464            .finish()
5465    }
5466}
5467
5468impl<V: 'static + Render> WindowHandle<V> {
5469    /// Creates a new handle from a window ID.
5470    /// This does not check if the root type of the window is `V`.
5471    pub fn new(id: WindowId) -> Self {
5472        WindowHandle {
5473            any_handle: AnyWindowHandle {
5474                id,
5475                state_type: TypeId::of::<V>(),
5476            },
5477            state_type: PhantomData,
5478        }
5479    }
5480
5481    /// Get the root view out of this window.
5482    ///
5483    /// This will fail if the window is closed or if the root view's type does not match `V`.
5484    #[cfg(any(test, feature = "test-support"))]
5485    pub fn root<C>(&self, cx: &mut C) -> Result<Entity<V>>
5486    where
5487        C: AppContext,
5488    {
5489        cx.update_window(self.any_handle, |root_view, _, _| {
5490            root_view
5491                .downcast::<V>()
5492                .map_err(|_| anyhow!("the type of the window's root view has changed"))
5493        })?
5494    }
5495
5496    /// Updates the root view of this window.
5497    ///
5498    /// This will fail if the window has been closed or if the root view's type does not match
5499    pub fn update<C, R>(
5500        &self,
5501        cx: &mut C,
5502        update: impl FnOnce(&mut V, &mut Window, &mut Context<V>) -> R,
5503    ) -> Result<R>
5504    where
5505        C: AppContext,
5506    {
5507        cx.update_window(self.any_handle, |root_view, window, cx| {
5508            let view = root_view
5509                .downcast::<V>()
5510                .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5511
5512            Ok(view.update(cx, |view, cx| update(view, window, cx)))
5513        })?
5514    }
5515
5516    /// Read the root view out of this window.
5517    ///
5518    /// This will fail if the window is closed or if the root view's type does not match `V`.
5519    pub fn read<'a>(&self, cx: &'a App) -> Result<&'a V> {
5520        let x = cx
5521            .windows
5522            .get(self.id)
5523            .and_then(|window| {
5524                window
5525                    .as_deref()
5526                    .and_then(|window| window.root.clone())
5527                    .map(|root_view| root_view.downcast::<V>())
5528            })
5529            .context("window not found")?
5530            .map_err(|_| anyhow!("the type of the window's root view has changed"))?;
5531
5532        Ok(x.read(cx))
5533    }
5534
5535    /// Read the root view out of this window, with a callback
5536    ///
5537    /// This will fail if the window is closed or if the root view's type does not match `V`.
5538    pub fn read_with<C, R>(&self, cx: &C, read_with: impl FnOnce(&V, &App) -> R) -> Result<R>
5539    where
5540        C: AppContext,
5541    {
5542        cx.read_window(self, |root_view, cx| read_with(root_view.read(cx), cx))
5543    }
5544
5545    /// Read the root view pointer off of this window.
5546    ///
5547    /// This will fail if the window is closed or if the root view's type does not match `V`.
5548    pub fn entity<C>(&self, cx: &C) -> Result<Entity<V>>
5549    where
5550        C: AppContext,
5551    {
5552        cx.read_window(self, |root_view, _cx| root_view)
5553    }
5554
5555    /// Check if this window is 'active'.
5556    ///
5557    /// Will return `None` if the window is closed or currently
5558    /// borrowed.
5559    pub fn is_active(&self, cx: &mut App) -> Option<bool> {
5560        cx.update_window(self.any_handle, |_, window, _| window.is_window_active())
5561            .ok()
5562    }
5563}
5564
5565impl<V> Copy for WindowHandle<V> {}
5566
5567impl<V> Clone for WindowHandle<V> {
5568    fn clone(&self) -> Self {
5569        *self
5570    }
5571}
5572
5573impl<V> PartialEq for WindowHandle<V> {
5574    fn eq(&self, other: &Self) -> bool {
5575        self.any_handle == other.any_handle
5576    }
5577}
5578
5579impl<V> Eq for WindowHandle<V> {}
5580
5581impl<V> Hash for WindowHandle<V> {
5582    fn hash<H: Hasher>(&self, state: &mut H) {
5583        self.any_handle.hash(state);
5584    }
5585}
5586
5587impl<V: 'static> From<WindowHandle<V>> for AnyWindowHandle {
5588    fn from(val: WindowHandle<V>) -> Self {
5589        val.any_handle
5590    }
5591}
5592
5593/// A handle to a window with any root view type, which can be downcast to a window with a specific root view type.
5594#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
5595pub struct AnyWindowHandle {
5596    pub(crate) id: WindowId,
5597    state_type: TypeId,
5598}
5599
5600impl AnyWindowHandle {
5601    /// Get the ID of this window.
5602    pub fn window_id(&self) -> WindowId {
5603        self.id
5604    }
5605
5606    /// Attempt to convert this handle to a window handle with a specific root view type.
5607    /// If the types do not match, this will return `None`.
5608    pub fn downcast<T: 'static>(&self) -> Option<WindowHandle<T>> {
5609        if TypeId::of::<T>() == self.state_type {
5610            Some(WindowHandle {
5611                any_handle: *self,
5612                state_type: PhantomData,
5613            })
5614        } else {
5615            None
5616        }
5617    }
5618
5619    /// Updates the state of the root view of this window.
5620    ///
5621    /// This will fail if the window has been closed.
5622    pub fn update<C, R>(
5623        self,
5624        cx: &mut C,
5625        update: impl FnOnce(AnyView, &mut Window, &mut App) -> R,
5626    ) -> Result<R>
5627    where
5628        C: AppContext,
5629    {
5630        cx.update_window(self, update)
5631    }
5632
5633    /// Read the state of the root view of this window.
5634    ///
5635    /// This will fail if the window has been closed.
5636    pub fn read<T, C, R>(self, cx: &C, read: impl FnOnce(Entity<T>, &App) -> R) -> Result<R>
5637    where
5638        C: AppContext,
5639        T: 'static,
5640    {
5641        let view = self
5642            .downcast::<T>()
5643            .context("the type of the window's root view has changed")?;
5644
5645        cx.read_window(&view, read)
5646    }
5647}
5648
5649impl HasWindowHandle for Window {
5650    fn window_handle(&self) -> Result<raw_window_handle::WindowHandle<'_>, HandleError> {
5651        self.platform_window.window_handle()
5652    }
5653}
5654
5655impl HasDisplayHandle for Window {
5656    fn display_handle(
5657        &self,
5658    ) -> std::result::Result<raw_window_handle::DisplayHandle<'_>, HandleError> {
5659        self.platform_window.display_handle()
5660    }
5661}
5662
5663/// An identifier for an [`Element`].
5664///
5665/// Can be constructed with a string, a number, or both, as well
5666/// as other internal representations.
5667#[derive(Clone, Debug, Eq, PartialEq, Hash)]
5668pub enum ElementId {
5669    /// The ID of a View element
5670    View(EntityId),
5671    /// An integer ID.
5672    Integer(u64),
5673    /// A string based ID.
5674    Name(SharedString),
5675    /// A UUID.
5676    Uuid(Uuid),
5677    /// An ID that's equated with a focus handle.
5678    FocusHandle(FocusId),
5679    /// A combination of a name and an integer.
5680    NamedInteger(SharedString, u64),
5681    /// A path.
5682    Path(Arc<std::path::Path>),
5683    /// A code location.
5684    CodeLocation(core::panic::Location<'static>),
5685    /// A labeled child of an element.
5686    NamedChild(Arc<ElementId>, SharedString),
5687    /// A byte array ID (used for text-anchors)
5688    OpaqueId([u8; 20]),
5689}
5690
5691impl ElementId {
5692    /// Constructs an `ElementId::NamedInteger` from a name and `usize`.
5693    pub fn named_usize(name: impl Into<SharedString>, integer: usize) -> ElementId {
5694        Self::NamedInteger(name.into(), integer as u64)
5695    }
5696}
5697
5698impl Display for ElementId {
5699    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5700        match self {
5701            ElementId::View(entity_id) => write!(f, "view-{}", entity_id)?,
5702            ElementId::Integer(ix) => write!(f, "{}", ix)?,
5703            ElementId::Name(name) => write!(f, "{}", name)?,
5704            ElementId::FocusHandle(_) => write!(f, "FocusHandle")?,
5705            ElementId::NamedInteger(s, i) => write!(f, "{}-{}", s, i)?,
5706            ElementId::Uuid(uuid) => write!(f, "{}", uuid)?,
5707            ElementId::Path(path) => write!(f, "{}", path.display())?,
5708            ElementId::CodeLocation(location) => write!(f, "{}", location)?,
5709            ElementId::NamedChild(id, name) => write!(f, "{}-{}", id, name)?,
5710            ElementId::OpaqueId(opaque_id) => write!(f, "{:x?}", opaque_id)?,
5711        }
5712
5713        Ok(())
5714    }
5715}
5716
5717impl TryInto<SharedString> for ElementId {
5718    type Error = anyhow::Error;
5719
5720    fn try_into(self) -> anyhow::Result<SharedString> {
5721        if let ElementId::Name(name) = self {
5722            Ok(name)
5723        } else {
5724            anyhow::bail!("element id is not string")
5725        }
5726    }
5727}
5728
5729impl From<usize> for ElementId {
5730    fn from(id: usize) -> Self {
5731        ElementId::Integer(id as u64)
5732    }
5733}
5734
5735impl From<i32> for ElementId {
5736    fn from(id: i32) -> Self {
5737        Self::Integer(id as u64)
5738    }
5739}
5740
5741impl From<SharedString> for ElementId {
5742    fn from(name: SharedString) -> Self {
5743        ElementId::Name(name)
5744    }
5745}
5746
5747impl From<String> for ElementId {
5748    fn from(name: String) -> Self {
5749        ElementId::Name(name.into())
5750    }
5751}
5752
5753impl From<Arc<str>> for ElementId {
5754    fn from(name: Arc<str>) -> Self {
5755        ElementId::Name(name.into())
5756    }
5757}
5758
5759impl From<Arc<std::path::Path>> for ElementId {
5760    fn from(path: Arc<std::path::Path>) -> Self {
5761        ElementId::Path(path)
5762    }
5763}
5764
5765impl From<&'static str> for ElementId {
5766    fn from(name: &'static str) -> Self {
5767        ElementId::Name(name.into())
5768    }
5769}
5770
5771impl<'a> From<&'a FocusHandle> for ElementId {
5772    fn from(handle: &'a FocusHandle) -> Self {
5773        ElementId::FocusHandle(handle.id)
5774    }
5775}
5776
5777impl From<(&'static str, EntityId)> for ElementId {
5778    fn from((name, id): (&'static str, EntityId)) -> Self {
5779        ElementId::NamedInteger(name.into(), id.as_u64())
5780    }
5781}
5782
5783impl From<(&'static str, usize)> for ElementId {
5784    fn from((name, id): (&'static str, usize)) -> Self {
5785        ElementId::NamedInteger(name.into(), id as u64)
5786    }
5787}
5788
5789impl From<(SharedString, usize)> for ElementId {
5790    fn from((name, id): (SharedString, usize)) -> Self {
5791        ElementId::NamedInteger(name, id as u64)
5792    }
5793}
5794
5795impl From<(&'static str, u64)> for ElementId {
5796    fn from((name, id): (&'static str, u64)) -> Self {
5797        ElementId::NamedInteger(name.into(), id)
5798    }
5799}
5800
5801impl From<Uuid> for ElementId {
5802    fn from(value: Uuid) -> Self {
5803        Self::Uuid(value)
5804    }
5805}
5806
5807impl From<(&'static str, u32)> for ElementId {
5808    fn from((name, id): (&'static str, u32)) -> Self {
5809        ElementId::NamedInteger(name.into(), id.into())
5810    }
5811}
5812
5813impl<T: Into<SharedString>> From<(ElementId, T)> for ElementId {
5814    fn from((id, name): (ElementId, T)) -> Self {
5815        ElementId::NamedChild(Arc::new(id), name.into())
5816    }
5817}
5818
5819impl From<&'static core::panic::Location<'static>> for ElementId {
5820    fn from(location: &'static core::panic::Location<'static>) -> Self {
5821        ElementId::CodeLocation(*location)
5822    }
5823}
5824
5825impl From<[u8; 20]> for ElementId {
5826    fn from(opaque_id: [u8; 20]) -> Self {
5827        ElementId::OpaqueId(opaque_id)
5828    }
5829}
5830
5831/// A rectangle to be rendered in the window at the given position and size.
5832/// Passed as an argument [`Window::paint_quad`].
5833#[derive(Clone)]
5834pub struct PaintQuad {
5835    /// The bounds of the quad within the window.
5836    pub bounds: Bounds<Pixels>,
5837    /// The radii of the quad's corners.
5838    pub corner_radii: Corners<Pixels>,
5839    /// The background color of the quad.
5840    pub background: Background,
5841    /// The widths of the quad's borders.
5842    pub border_widths: Edges<Pixels>,
5843    /// The color of the quad's borders.
5844    pub border_color: Hsla,
5845    /// The style of the quad's borders.
5846    pub border_style: BorderStyle,
5847}
5848
5849impl PaintQuad {
5850    /// Sets the corner radii of the quad.
5851    pub fn corner_radii(self, corner_radii: impl Into<Corners<Pixels>>) -> Self {
5852        PaintQuad {
5853            corner_radii: corner_radii.into(),
5854            ..self
5855        }
5856    }
5857
5858    /// Sets the border widths of the quad.
5859    pub fn border_widths(self, border_widths: impl Into<Edges<Pixels>>) -> Self {
5860        PaintQuad {
5861            border_widths: border_widths.into(),
5862            ..self
5863        }
5864    }
5865
5866    /// Sets the border color of the quad.
5867    pub fn border_color(self, border_color: impl Into<Hsla>) -> Self {
5868        PaintQuad {
5869            border_color: border_color.into(),
5870            ..self
5871        }
5872    }
5873
5874    /// Sets the background color of the quad.
5875    pub fn background(self, background: impl Into<Background>) -> Self {
5876        PaintQuad {
5877            background: background.into(),
5878            ..self
5879        }
5880    }
5881}
5882
5883/// Creates a quad with the given parameters.
5884pub fn quad(
5885    bounds: Bounds<Pixels>,
5886    corner_radii: impl Into<Corners<Pixels>>,
5887    background: impl Into<Background>,
5888    border_widths: impl Into<Edges<Pixels>>,
5889    border_color: impl Into<Hsla>,
5890    border_style: BorderStyle,
5891) -> PaintQuad {
5892    PaintQuad {
5893        bounds,
5894        corner_radii: corner_radii.into(),
5895        background: background.into(),
5896        border_widths: border_widths.into(),
5897        border_color: border_color.into(),
5898        border_style,
5899    }
5900}
5901
5902/// Creates a filled quad with the given bounds and background color.
5903pub fn fill(bounds: impl Into<Bounds<Pixels>>, background: impl Into<Background>) -> PaintQuad {
5904    PaintQuad {
5905        bounds: bounds.into(),
5906        corner_radii: (0.).into(),
5907        background: background.into(),
5908        border_widths: (0.).into(),
5909        border_color: transparent_black(),
5910        border_style: BorderStyle::default(),
5911    }
5912}
5913
5914/// Creates a rectangle outline with the given bounds, border color, and a 1px border width
5915pub fn outline(
5916    bounds: impl Into<Bounds<Pixels>>,
5917    border_color: impl Into<Hsla>,
5918    border_style: BorderStyle,
5919) -> PaintQuad {
5920    PaintQuad {
5921        bounds: bounds.into(),
5922        corner_radii: (0.).into(),
5923        background: transparent_black().into(),
5924        border_widths: (1.).into(),
5925        border_color: border_color.into(),
5926        border_style,
5927    }
5928}