Skip to main content

boltz_gpui/
window.rs

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